Skip to content

compute_anchor_aligned_encoding_matrix

Compute an oriented cross-encoding matrix for symmetric pairwise GRADIENDs.

This helper is intended for symmetric suites where many binary GRADIENDs cover overlapping feature-class pairs. Rows index an anchor feature class, and signs are aligned so a class is comparable whether it appeared as the left or right class in an individual binary pair.

Parameters:

Name Type Description Default
pair_by_id Dict[str, Tuple[str, str]]

Mapping from trainer/model id to its ordered binary class pair (left_class, right_class).

required
encoder_summary Dict[str, Any]

Mapping from trainer/model id to an evaluation result dict containing an encoder_df DataFrame and optionally a correlation value.

required
feature_classes Sequence[str]

Row order and default column order. Must contain at least two classes.

required
aggregate str

Aggregation applied to aligned contributions. Supported values are "mean", "min", "max", "std", "count", and "raw_count".

'mean'
alignment str

Column alignment mode. Supported aliases resolve to "factual", "counterfactual", or "transition".

'factual'
column_ids Optional[Sequence[str]]

Optional explicit column order/filter. If omitted, factual/counterfactual alignment uses feature_classes and transition alignment uses observed transition ids.

None

Returns:

Type Description
Dict[str, Any]

A payload with measure, model_ids, column_ids, rows,

Dict[str, Any]

columns, matrix, aggregate, alignment, aligned_rows,

Dict[str, Any]

n_matrix, raw_n_matrix, and pair_by_trainer.

Raises:

Type Description
ValueError

If too few feature classes are passed, alignment is unsupported, or aggregate is unsupported.

Source code in gradiend/comparison/anchor_aligned.py
def compute_anchor_aligned_encoding_matrix(
    *,
    pair_by_id: Dict[str, Tuple[str, str]],
    encoder_summary: Dict[str, Any],
    feature_classes: Sequence[str],
    aggregate: str = "mean",
    alignment: str = "factual",
    column_ids: Optional[Sequence[str]] = None,
    source_by_id: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
    """Compute an oriented cross-encoding matrix for symmetric pairwise GRADIENDs.

    This helper is intended for symmetric suites where many binary GRADIENDs
    cover overlapping feature-class pairs. Rows index an anchor feature class,
    and signs are aligned so a class is comparable whether it appeared as the
    left or right class in an individual binary pair.

    Args:
        pair_by_id: Mapping from trainer/model id to its ordered binary class
            pair ``(left_class, right_class)``.
        encoder_summary: Mapping from trainer/model id to an evaluation result
            dict containing an ``encoder_df`` DataFrame and optionally a
            ``correlation`` value.
        feature_classes: Row order and default column order. Must contain at
            least two classes.
        aggregate: Aggregation applied to aligned contributions. Supported
            values are ``"mean"``, ``"min"``, ``"max"``, ``"std"``,
            ``"count"``, and ``"raw_count"``.
        alignment: Column alignment mode. Supported aliases resolve to
            ``"factual"``, ``"counterfactual"``, or ``"transition"``.
        column_ids: Optional explicit column order/filter. If omitted,
            factual/counterfactual alignment uses ``feature_classes`` and
            transition alignment uses observed transition ids.

    Returns:
        A payload with ``measure``, ``model_ids``, ``column_ids``, ``rows``,
        ``columns``, ``matrix``, ``aggregate``, ``alignment``, ``aligned_rows``,
        ``n_matrix``, ``raw_n_matrix``, and ``pair_by_trainer``.

    Raises:
        ValueError: If too few feature classes are passed, ``alignment`` is
            unsupported, or ``aggregate`` is unsupported.
    """
    alignment = _normalise_alignment(alignment)
    classes = [str(value) for value in feature_classes]
    if len(classes) < 2:
        raise ValueError("feature_classes must contain at least 2 classes")
    columns = [str(value) for value in column_ids] if column_ids is not None else None
    aligned_df = build_anchor_aligned_encoding_rows(
        pair_by_id=pair_by_id,
        encoder_summary=encoder_summary,
        feature_classes=classes,
        alignment=alignment,
        column_ids=columns,
        source_by_id=source_by_id,
    )
    if columns is None:
        if alignment == "transition" and not aligned_df.empty:
            columns = sorted(aligned_df["eval_class"].dropna().astype(str).unique().tolist())
        else:
            columns = list(classes)
    matrix_df = aggregate_anchor_aligned_encoding_rows(
        aligned_df,
        classes,
        column_ids=columns,
        aggregate=aggregate,
    )
    matrix = matrix_df.astype(float).values.tolist()
    counts_df = aggregate_anchor_aligned_encoding_rows(aligned_df, classes, column_ids=columns, aggregate="count")
    raw_counts_df = aggregate_anchor_aligned_encoding_rows(aligned_df, classes, column_ids=columns, aggregate="raw_count")
    return {
        "measure": f"anchor_aligned_encoding_{alignment}_{aggregate}",
        "model_ids": classes,
        "column_ids": columns,
        "matrix": matrix,
        "rows": classes,
        "columns": columns,
        "aggregate": aggregate,
        "alignment": alignment,
        "aligned_rows": aligned_df,
        "n_matrix": counts_df.fillna(0).astype(int).values.tolist(),
        "raw_n_matrix": raw_counts_df.fillna(0).astype(int).values.tolist(),
        "pair_by_trainer": {str(k): [str(v) for v in pair] for k, pair in pair_by_id.items()},
    }