Skip to content

role_grouper

Assign extracted SNOMED CT attributes to role groups.

The grouping combines:

  • LLM-proposed groups (role_groups in the selection output) for the clusters listed in hierarchy.mrcm.grouping.llm_grouped_clusters;
  • interprets_interpretation pairs (each pair is one group);
  • deterministic rules for everything else: self-grouped attributes get one group per value; for a cluster, one group when every attribute has a single value, one group per value when one attribute has several values (single values are repeated in every group), and a positional fallback when several attributes have several values (ambiguous — flagged).

Output format (result["role_groups"])::

[{"group": 1, "members": [{"attribute": "finding_site", "concept_id": ..., "concept_name": ...,
                           "concept_code": ...}, ...]}, ...]

group 0 holds attributes the MRCM marks as ungrouped for the term's domain.

attribute_keys(attributes)

Attribute keys with at least one value (interprets_interpretation expanded).

Source code in src/ariadne/hierarchy/role_grouper.py
81
82
83
84
85
86
87
88
89
90
91
def attribute_keys(attributes: dict | None) -> list[str]:
    """Attribute keys with at least one value (``interprets_interpretation`` expanded)."""
    keys: list[str] = []
    for key, value in (attributes or {}).items():
        if key == INTERPRETS_PAIR_KEY:
            for pair in value or []:
                if isinstance(pair, dict):
                    keys += [k for k in ("interprets", "interpretation") if _as_concepts(pair.get(k))]
        elif _as_concepts(value):
            keys.append(key)
    return list(dict.fromkeys(keys))

flatten_role_groups(llm_role_groups)

Collapse LLM role_groups ([{attribute_key: concept | [concepts]}]) to flat attributes.

Source code in src/ariadne/hierarchy/role_grouper.py
 94
 95
 96
 97
 98
 99
100
101
def flatten_role_groups(llm_role_groups: list[dict] | None) -> dict[str, list[Concept]]:
    """Collapse LLM ``role_groups`` (``[{attribute_key: concept | [concepts]}]``) to flat attributes."""
    flat: dict[str, list[Concept]] = {}
    for group in llm_role_groups or []:
        if isinstance(group, dict):
            for key, value in group.items():
                _add_values(flat, key, _as_concepts(value))
    return flat

group_attributes(attributes, settings, llm_role_groups=None, rules=None, domain=None)

Assign the selected attributes of one term to role groups.

Parameters:

Name Type Description Default
attributes dict | None

result["attributes"] ({key: concept | [concepts] | None}, with optional interprets_interpretation pairs).

required
settings MrcmSettings

hierarchy.mrcm settings (grouping rules).

required
llm_role_groups list[dict] | None

Normalized LLM role groups [{attribute_key: concept | [concepts]}].

None
rules Any

Optional :class:~ariadne.hierarchy.mrcm.MrcmRules; when given with domain, attributes the MRCM marks as ungrouped are placed in group 0.

None
domain str | None

MRCM domain name of the term.

None

Returns:

Type Description
GroupingResult

GroupingResult(role_groups, method).

Source code in src/ariadne/hierarchy/role_grouper.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def group_attributes(
    attributes: dict | None,
    settings: MrcmSettings,
    llm_role_groups: list[dict] | None = None,
    rules: Any = None,
    domain: str | None = None,
) -> GroupingResult:
    """Assign the selected attributes of one term to role groups.

    Args:
        attributes: ``result["attributes"]`` (``{key: concept | [concepts] | None}``, with
            optional ``interprets_interpretation`` pairs).
        settings: ``hierarchy.mrcm`` settings (grouping rules).
        llm_role_groups: Normalized LLM role groups ``[{attribute_key: concept | [concepts]}]``.
        rules: Optional :class:`~ariadne.hierarchy.mrcm.MrcmRules`; when given with ``domain``,
            attributes the MRCM marks as ungrouped are placed in group 0.
        domain: MRCM domain name of the term.

    Returns:
        ``GroupingResult(role_groups, method)``.
    """
    grouping = settings.grouping
    values: dict[str, list[Concept]] = {}
    pairs: list[tuple[Concept, Concept]] = []
    for key, value in (attributes or {}).items():
        if key == INTERPRETS_PAIR_KEY:
            for pair in value or []:
                if not isinstance(pair, dict):
                    continue
                interprets, interpretation = _as_concepts(pair.get("interprets")), _as_concepts(pair.get("interpretation"))
                if interprets and interpretation:
                    pairs.append((interprets[0], interpretation[0]))
                else:
                    _add_values(values, "interprets", interprets)
                    _add_values(values, "interpretation", interpretation)
        else:
            _add_values(values, key, _as_concepts(value))
    for key, concepts in flatten_role_groups(llm_role_groups).items():
        _add_values(values, key, concepts)

    methods: set[str] = set()
    ungrouped: list[Member] = []
    if rules is not None and domain:
        domain_rules = rules.rules_for_domain(domain)
        for key in list(values):
            rule = domain_rules.get(key)
            if rule is not None and not rule.grouped:
                ungrouped += [_member(key, c) for c in values.pop(key)]

    groups: list[list[Member]] = []
    pair_cluster = grouping.cluster_of("interprets")
    for name, keys in grouping.clusters.items():
        cluster_groups: list[list[Member]] = []
        if name == pair_cluster:
            cluster_groups += [[_member("interprets", a), _member("interpretation", b)] for a, b in pairs]
        if name in grouping.llm_grouped_clusters and llm_role_groups:
            llm_groups, llm_method = _llm_cluster(keys, values, llm_role_groups)
            if llm_groups:
                methods.add(llm_method)
                cluster_groups += llm_groups
        remaining = {k: values.pop(k) for k in keys if k in values and k not in grouping.self_grouped}
        if remaining:
            extra, method = _deterministic_cluster(remaining)
            methods.add(method)
            cluster_groups += extra
        groups += cluster_groups
    if pair_cluster is None:
        groups += [[_member("interprets", a), _member("interpretation", b)] for a, b in pairs]

    # Self-grouped attributes, then anything not covered by the grouping rules: one group per value.
    for key in [k for k in grouping.self_grouped if k in values] + [k for k in values if k not in grouping.self_grouped]:
        groups += [[_member(key, c)] for c in values[key]]
    if groups:
        methods.add(METHOD_DETERMINISTIC)

    unique: list[list[Member]] = []
    seen: set[frozenset] = set()
    for group in groups:
        signature = frozenset((m["attribute"], str(m["concept_id"])) for m in group)
        if signature not in seen:
            seen.add(signature)
            unique.append(group)

    role_groups = [{"group": 0, "members": ungrouped}] if ungrouped else []
    role_groups += [{"group": i, "members": members} for i, members in enumerate(unique, start=1)]

    if not role_groups:
        method = METHOD_NONE
    elif METHOD_POSITIONAL in methods:
        method = METHOD_POSITIONAL
    elif METHOD_LLM in methods:
        method = METHOD_LLM
    else:
        method = METHOD_DETERMINISTIC
    return GroupingResult(role_groups, method)

group_result(result, settings, rules=None)

Set role_groups, grouping_method and, when rules is given, mrcm_domain on a pipeline result (in place).

Source code in src/ariadne/hierarchy/role_grouper.py
254
255
256
257
258
259
260
261
262
263
def group_result(result: dict, settings: MrcmSettings, rules: Any = None) -> None:
    """Set ``role_groups``, ``grouping_method`` and, when ``rules`` is given, ``mrcm_domain`` on a
    pipeline result (in place)."""
    attributes = result.get("attributes") or {}
    domain = rules.select_domain(attribute_keys(attributes)) if rules is not None else None
    if domain:
        result["mrcm_domain"] = domain
    grouping = group_attributes(attributes, settings, result.get("llm_role_groups"), rules, domain)
    result["role_groups"] = grouping.role_groups
    result["grouping_method"] = grouping.method

regroup_result(result, settings, rules=None)

Return a copy of a pipeline result with role groups (re)computed by :func:group_result.

Results with an error key are returned unchanged.

Source code in src/ariadne/hierarchy/role_grouper.py
266
267
268
269
270
271
272
273
274
275
def regroup_result(result: dict, settings: MrcmSettings, rules: Any = None) -> dict:
    """Return a copy of a pipeline result with role groups (re)computed by :func:`group_result`.

    Results with an ``error`` key are returned unchanged.
    """
    if not isinstance(result, dict) or result.get("error"):
        return result
    updated = copy.deepcopy(result)
    group_result(updated, settings, rules)
    return updated

regroup_results(results, settings, rules=None)

Apply :func:regroup_result to cached pipeline results (no LLM calls).

Source code in src/ariadne/hierarchy/role_grouper.py
278
279
280
def regroup_results(results: list[dict], settings: MrcmSettings, rules: Any = None) -> list[dict]:
    """Apply :func:`regroup_result` to cached pipeline results (no LLM calls)."""
    return [regroup_result(r, settings, rules) for r in results]