Skip to content

Result Analysers

Comparing experiment configurations

The standard summary has one row per stored generation configuration with aggregate metrics. Compare or join rows by generation_id. Two rows can share the same model name, dataset and other display labels. For example, the same model run at temperatures 0 and 1 has two generation IDs. The ID identifies a configuration and can recur across runs of that configuration.

dataset_version and experiment_name give human-readable context. To inspect a row's temperature in an existing project, use the ID from the table:

import json

for record in project.records.evaluation:
    if record.generation_id == selected_id:
        settings = json.loads(record.model_record.generation_args_json)
        print(record.evaluator_name, settings.get("temperature"))

Evaluators that score the same generation appear side by side. A unique metric keeps its usual score/metric column name. When several recorded aggregates share that name, their column labels include the evaluator name and an identifier derived from their settings. A missing combination has a null cell. A repeated value for the same generation and aggregate raises an error even when both scores are equal. The analyser also checks for incompatible metric implementations before building the table.

Older projects use the identity fields present in their records. If two runs were already saved under the same record, the summary cannot recover the missing distinction. Rerun the summary from the saved evaluation logs to update a previously exported table.

Modules:

Name Description
meta_result_analyser
metric_correlation_analyser
tabular_analyser

Classes:

Name Description
CorrelationResults

Correlation matrices and counts, with the same metric order in each table.

MetaResultAnalyser

Describe within-sample rank agreement across a declared complete tier set.

MetricCorrelationAnalyser

Correlate scores on the same generated observations.

TabularResultAnalyser

An analyser summarising evaluation results in a tabular format.

CorrelationResults dataclass

Correlation matrices and counts, with the same metric order in each table.

Attributes:

Name Type Description
correlation_matrix T

Pairwise coefficients in the requested output format.

figure Figure | None

Correlation plot, or None when no plot was produced.

paired_counts T | None

Number of finite, identity-matched observations used for each coefficient. Populated by MetricCorrelationAnalyser.

excluded_counts T | None

Number of identity-matched pairs excluded because either score is non-finite. Unmatched observations are not included in either count. Populated by MetricCorrelationAnalyser.

Source code in evalsense/workflow/analysers/metric_correlation_analyser.py
@dataclass
class CorrelationResults[T: pl.DataFrame | pd.DataFrame | npt.NDArray[np.float64]]:
    """Correlation matrices and counts, with the same metric order in each table.

    Attributes:
        correlation_matrix (T): Pairwise coefficients in the requested output format.
        figure (Figure | None): Correlation plot, or None when no plot was produced.
        paired_counts (T | None): Number of finite, identity-matched observations
            used for each coefficient. Populated by MetricCorrelationAnalyser.
        excluded_counts (T | None): Number of identity-matched pairs excluded
            because either score is non-finite. Unmatched observations are not
            included in either count. Populated by MetricCorrelationAnalyser.
    """

    correlation_matrix: T
    figure: Figure | None = None
    paired_counts: T | None = None
    excluded_counts: T | None = None

MetaResultAnalyser

Bases: ResultAnalyser[T]

Describe within-sample rank agreement across a declared complete tier set.

For three or more planned tiers, each sample contributes one Spearman correlation. A deliberately two-tier design instead reports pairwise ordering: pairwise_accuracy is concordant / (concordant + discordant), and avg_correlation is 2 * pairwise_accuracy - 1. analysis_kind identifies the design. Equal-score pairs are undefined correlations, excluded and counted in n_constant; pairwise accuracy is conditional on non-tied, usable pairs. A missing tier never changes the declared design or selects pairwise analysis.

The reported mean gives included samples equal weight. Results are kept separate by dataset, task, generating model, evaluator configuration and scorer; only the tier generator is grouped out. group_id is a stable digest of that grouped record; full configurations remain in the project. Aliases change presentation only.

Counts cover the union of sample IDs in available evaluation logs, including failed logs, or an explicit expected_sample_ids manifest. Samples absent from every log cannot be counted without that manifest. Missing logs are reported separately. Scores from unsuccessful records/logs are not used. Exclusion reasons are mutually exclusive, checked in this order: incomplete tiers, missing/failed scores, invalid/non-finite values, missing validation, constant scores, undefined correlation. No score is imputed or set to zero.

For three or more tiers, confidence limits use a percentile bootstrap of included sample-level correlations, never of individual tiers. Those intervals are unavailable for fewer than two included samples or degenerate distributions. Two-tier designs use Wilson binomial limits for the ordering accuracy, mapped to the mean-correlation scale as 2 * limit - 1. They are defined even for one non-tied pair or unanimous pairs; no usable pairs gives no estimate or interval. ci_low and ci_high are always on the avg_correlation scale.

Both interval methods assume independent sample IDs and are conditional on retained samples and the tier design. They do not correct selection bias, establish clinical validity, or quantify uncertainty in generated severity. Small samples and few tiers provide limited evidence; a perfect mean alone is not evidence of a reliable evaluator.

Generated tier IDs specify intended severity, not independently verified severity. By default results carry validation_policy='not_checked' and a warning. tier_validation_field requires caller-supplied True flags on all tiers of a sample, after independent review of the actual generated outputs. These flags are attestations, not validation performed by this analyser.

Duplicate sample/tier observations and multiple epochs within a cohort raise ValueError. Repeated measurements need a separate, explicit aggregation policy.

Methods:

Name Description
__call__

Summarise complete, finite tier comparisons with explicit evidence counts.

__init__

Initialise the analyser.

Source code in evalsense/workflow/analysers/meta_result_analyser.py
class MetaResultAnalyser[T: pl.DataFrame | pd.DataFrame](ResultAnalyser[T]):
    """Describe within-sample rank agreement across a declared complete tier set.

    For three or more planned tiers, each sample contributes one Spearman
    correlation. A deliberately two-tier design instead reports pairwise ordering:
    ``pairwise_accuracy`` is concordant / (concordant + discordant), and
    ``avg_correlation`` is 2 * pairwise_accuracy - 1. ``analysis_kind`` identifies
    the design. Equal-score pairs are undefined correlations, excluded and counted
    in ``n_constant``; pairwise accuracy is conditional on non-tied, usable pairs.
    A missing tier never changes the declared design or selects pairwise analysis.

    The reported mean gives included samples equal weight. Results are kept
    separate by dataset, task, generating model, evaluator configuration and scorer;
    only the tier generator is grouped out. ``group_id`` is a stable digest of
    that grouped record; full configurations remain in the project. Aliases
    change presentation only.

    Counts cover the union of sample IDs in available evaluation logs, including
    failed logs, or an explicit ``expected_sample_ids`` manifest. Samples absent
    from every log cannot be counted without that manifest. Missing logs are
    reported separately. Scores from unsuccessful records/logs are not used.
    Exclusion reasons are mutually exclusive, checked in this order: incomplete
    tiers, missing/failed scores, invalid/non-finite values, missing validation,
    constant scores, undefined correlation. No score is imputed or set to zero.

    For three or more tiers, confidence limits use a percentile bootstrap of
    included sample-level correlations, never of individual tiers. Those intervals
    are unavailable for fewer than two included samples or degenerate distributions.
    Two-tier designs use Wilson binomial limits for the ordering accuracy, mapped
    to the mean-correlation scale as 2 * limit - 1. They are defined even for one
    non-tied pair or unanimous pairs; no usable pairs gives no estimate or interval.
    ``ci_low`` and ``ci_high`` are always on the ``avg_correlation`` scale.

    Both interval methods assume independent sample IDs and are conditional on
    retained samples and the tier design. They do not correct selection bias,
    establish clinical validity, or quantify uncertainty in generated severity.
    Small samples and few tiers provide limited evidence; a perfect mean alone
    is not evidence of a reliable evaluator.

    Generated tier IDs specify intended severity, not independently verified
    severity. By default results carry ``validation_policy='not_checked'`` and a
    warning. ``tier_validation_field`` requires caller-supplied True flags on all
    tiers of a sample, after independent review of the actual generated outputs.
    These flags are attestations, not validation performed by this analyser.

    Duplicate sample/tier observations and multiple epochs within a cohort raise
    ValueError. Repeated measurements need a separate, explicit aggregation policy.
    """

    def __init__(
        self,
        name: str = "MetaResultAnalyser",
        output_format: Literal["polars", "pandas"] = "polars",
    ):
        """Initialise the analyser.

        Args:
            name (str): Name of the analyser.
            output_format (Literal["polars", "pandas"]): Result table format.

        Raises:
            ValueError: If the output format is unsupported.
        """
        super().__init__(name=name)
        if output_format not in OUTPUT_FORMATTERS:
            raise ValueError(
                f"Invalid output format: {output_format}. Use polars or pandas."
            )
        self.output_format = output_format

    @override
    def __call__(
        self,
        project: Project,
        meta_tier_field: str = "perturbation_type_tier",
        lower_tier_is_better: bool = False,
        metric_labels: dict[str, str] | None = None,
        *,
        expected_tiers: Sequence[int],
        expected_sample_ids: Sequence[str | int] | None = None,
        tier_validation_field: str | None = None,
        confidence_level: float = 0.95,
        n_resamples: int = 2000,
        seed: int = 0,
        **kwargs: dict,
    ) -> T:
        """Summarise complete, finite tier comparisons with explicit evidence counts.

        Args:
            project (Project): Project containing the evaluation logs.
            meta_tier_field (str): Metadata field containing integer tier IDs.
            lower_tier_is_better (bool): True when lower tiers mean better outputs.
                All analysed metrics must be oriented so higher scores are better.
            metric_labels (dict[str, str] | None): Display aliases for original
                scalar scorer or inner metric names. Does not combine identities.
            expected_tiers (Sequence[int]): Complete planned tier set, with at least
                two distinct integers. Two tiers select pairwise-ordering analysis;
                three or more select mean Spearman correlation. Never inferred
                from surviving results.
            expected_sample_ids (Sequence[str | int] | None): Optional full sample
                manifest, applied to each cohort. IDs must be unique and cover all
                observations. Without it, counts describe observed IDs only.
            tier_validation_field (str | None): Optional metadata field containing
                the boolean True after external review of each generated output's
                assigned tier. Missing/false flags exclude the whole sample.
            confidence_level (float): Two-sided confidence level in (0, 1).
            n_resamples (int): Bootstrap resamples for three or more tiers, at least
                1000. Defaults to 2000. Unused for two-tier designs.
            seed (int): Non-negative bootstrap seed. Defaults to 0. Unused for
                two-tier designs.
            **kwargs (dict): Unused arguments accepted for ResultAnalyser compatibility.

        Returns:
            T: One row per cohort/scorer/metric, with the mean correlation, interval,
                interval status, included/excluded counts, exclusion reasons and
                analysis settings. Two-tier rows include concordant/discordant
                counts and accuracy; bootstrap-only settings are null. Unestimable
                values are null. Cohorts without any recorded metrics have a null
                metric row. Empty projects return
                a typed empty table. Neither logs nor project records are modified.

        Raises:
            ValueError: For invalid settings, invalid/unexpected tiers, IDs outside
                the manifest, duplicate sample/tier observations or mixed epochs.
        """
        tiers = _tier_set(expected_tiers)
        pairwise = len(tiers) == 2
        if not meta_tier_field or not isinstance(meta_tier_field, str):
            raise ValueError("meta_tier_field must be a non-empty string.")
        if type(lower_tier_is_better) is not bool:
            raise ValueError("lower_tier_is_better must be a boolean.")
        if type(confidence_level) not in (int, float) or not 0 < confidence_level < 1:
            raise ValueError("confidence_level must be between zero and one.")
        if type(n_resamples) is not int or n_resamples < 1000:
            raise ValueError("n_resamples must be an integer of at least 1000.")
        if type(seed) is not int or not 0 <= seed <= 2**63 - 1:
            raise ValueError("seed must be a non-negative 64-bit integer.")
        if tier_validation_field is not None and (
            not isinstance(tier_validation_field, str)
            or not tier_validation_field.strip()
        ):
            raise ValueError("tier_validation_field must be a non-empty string.")
        population = None
        if expected_sample_ids is not None:
            if isinstance(expected_sample_ids, (str, bytes)):
                raise ValueError(
                    "expected_sample_ids must be a sequence of sample IDs."
                )
            population = {_sample_key(value) for value in expected_sample_ids}
            if len(population) != len(expected_sample_ids):
                raise ValueError("expected_sample_ids must not contain duplicates.")
        if tier_validation_field is None:
            warnings.warn(
                "Meta-evaluation tier severity has not been independently checked. "
                "Interpret these correlations as agreement with intended tiers, "
                "not validated evaluator accuracy.",
                UserWarning,
                stacklevel=2,
            )

        cohorts: dict[MetaTierGroupedRecord, _Cohort] = {}
        logs = project.get_logs(type="evaluation")
        check_metric_implementations(
            {record: log for record, log in logs.items() if log.status == "success"}
        )
        for record, result in project.records.evaluation.items():
            group = record.get_meta_grouped_record("")
            cohort = cohorts.setdefault(group, _Cohort())
            log = logs.get(record)
            if result.status != "success" or (
                log is not None and log.status != "success"
            ):
                cohort.failed_logs += 1
            if log is None or not log.samples:
                cohort.unavailable_logs += 1
                continue
            for sample in log.samples:
                tier = sample.metadata.get(meta_tier_field)
                if type(tier) is not int or tier not in tiers:
                    raise ValueError(
                        f"Metadata field {meta_tier_field!r} must contain an expected "
                        "integer tier ID; check the experiment design and log metadata."
                    )
                if cohort.epoch is not None and cohort.epoch != sample.epoch:
                    raise ValueError(
                        "Multiple epochs require an explicit aggregation policy. "
                        "Analyse one epoch at a time."
                    )
                cohort.epoch = sample.epoch
                key = _sample_key(sample.id)
                if population is not None and key not in population:
                    raise ValueError(
                        "Observed sample ID is absent from expected_sample_ids."
                    )
                observations = cohort.samples.setdefault(key, {})
                if tier in observations:
                    raise ValueError(
                        "Duplicate sample/tier observation; results cannot be overwritten."
                    )
                values: dict[MetricKey, Any] = {}
                for scorer_name, score in (sample.scores or {}).items():
                    if isinstance(score.value, dict):
                        values.update(
                            {
                                (scorer_name, inner): value
                                for inner, value in score.value.items()
                            }
                        )
                    else:
                        values[(scorer_name, None)] = score.value
                cohort.metrics.update(values)
                observations[tier] = _Observation(
                    values,
                    result.status == log.status == "success" and sample.error is None,
                    tier_validation_field is not None
                    and sample.metadata.get(tier_validation_field) is True,
                )

        rows = []
        for group, cohort in sorted(
            cohorts.items(), key=lambda item: item[0].model_dump_json()
        ):
            group_json = json.dumps(group.model_dump(mode="json"), sort_keys=True)
            sample_ids = sorted(
                population if population is not None else cohort.samples
            )
            metrics = sorted(cohort.metrics, key=lambda key: (key[0], key[1] or ""))
            for metric in metrics or [None]:
                counts: Counter[str] = Counter()
                correlations = []
                for sample_id in sample_ids:
                    observed = cohort.samples.get(sample_id, {})
                    if set(observed) != set(tiers):
                        counts["incomplete_tiers"] += 1
                        continue
                    if metric is None or any(
                        not observed[t].usable or metric not in observed[t].scores
                        for t in tiers
                    ):
                        counts["missing_scores"] += 1
                        continue
                    tier_values = [observed[t].scores[metric] for t in tiers]
                    if any(
                        type(v) not in (int, float) or not math.isfinite(v)
                        for v in tier_values
                    ):
                        counts["invalid_scores"] += 1
                        continue
                    if tier_validation_field is not None and not all(
                        observed[t].validated for t in tiers
                    ):
                        counts["unvalidated"] += 1
                        continue
                    if len(set(tier_values)) == 1:
                        counts["constant"] += 1
                        continue
                    multiplier = -1 if lower_tier_is_better else 1
                    if pairwise:
                        # Compare directly to avoid overflow when subtracting scores.
                        correlation = (
                            float(multiplier)
                            if tier_values[1] > tier_values[0]
                            else -float(multiplier)
                        )
                    else:
                        correlation = float(
                            cast(
                                float,
                                spearmanr([multiplier * t for t in tiers], tier_values)[
                                    0
                                ],
                            )
                        )
                    if not math.isfinite(correlation):
                        counts["undefined"] += 1
                        continue
                    correlations.append(correlation)
                concordant = (
                    sum(value > 0 for value in correlations) if pairwise else None
                )
                if pairwise:
                    assert concordant is not None
                    low, high, interval_status = _pairwise_interval(
                        concordant, len(correlations), confidence_level
                    )
                else:
                    low, high, interval_status = _interval(
                        correlations, confidence_level, n_resamples, seed
                    )
                raw_name = (
                    (metric[1] if metric[1] is not None else metric[0])
                    if metric
                    else None
                )
                rows.append(
                    {
                        "group_id": hashlib.sha256(group_json.encode()).hexdigest(),
                        "dataset": group.dataset_record.name,
                        "model": group.model_record.name,
                        "task": group.task_name,
                        "evaluator": group.evaluator_name,
                        "scorer": metric[0] if metric else None,
                        "metric_name": (metric_labels or {}).get(raw_name, raw_name)
                        if raw_name is not None
                        else None,
                        "analysis_kind": "pairwise_ordering"
                        if pairwise
                        else "mean_spearman",
                        "pairwise_accuracy": concordant / len(correlations)
                        if concordant is not None and correlations
                        else None,
                        "n_concordant": concordant,
                        "n_discordant": len(correlations) - concordant
                        if concordant is not None
                        else None,
                        "avg_correlation": math.fsum(correlations) / len(correlations)
                        if correlations
                        else None,
                        "ci_low": low,
                        "ci_high": high,
                        "ci_status": interval_status,
                        "n_samples": len(sample_ids),
                        "n_included": len(correlations),
                        "n_excluded": len(sample_ids) - len(correlations),
                        **{
                            f"n_{reason}": counts[reason]
                            for reason in (
                                "incomplete_tiers",
                                "missing_scores",
                                "invalid_scores",
                                "unvalidated",
                                "constant",
                                "undefined",
                            )
                        },
                        "failed_logs": cohort.failed_logs,
                        "unavailable_logs": cohort.unavailable_logs,
                        "sample_population": "declared"
                        if population is not None
                        else "observed",
                        "expected_tiers": json.dumps(tiers),
                        "lower_tier_is_better": lower_tier_is_better,
                        "validation_policy": "require_caller_attestation"
                        if tier_validation_field
                        else "not_checked",
                        "tier_validation_field": tier_validation_field,
                        "confidence_level": float(confidence_level),
                        "n_resamples": None if pairwise else n_resamples,
                        "seed": None if pairwise else seed,
                    }
                )
        return cast(
            T, OUTPUT_FORMATTERS[self.output_format](pl.DataFrame(rows, schema=_SCHEMA))
        )

__call__

__call__(
    project: Project,
    meta_tier_field: str = "perturbation_type_tier",
    lower_tier_is_better: bool = False,
    metric_labels: dict[str, str] | None = None,
    *,
    expected_tiers: Sequence[int],
    expected_sample_ids: Sequence[str | int] | None = None,
    tier_validation_field: str | None = None,
    confidence_level: float = 0.95,
    n_resamples: int = 2000,
    seed: int = 0,
    **kwargs: dict,
) -> T

Summarise complete, finite tier comparisons with explicit evidence counts.

Parameters:

Name Type Description Default
project Project

Project containing the evaluation logs.

required
meta_tier_field str

Metadata field containing integer tier IDs.

'perturbation_type_tier'
lower_tier_is_better bool

True when lower tiers mean better outputs. All analysed metrics must be oriented so higher scores are better.

False
metric_labels dict[str, str] | None

Display aliases for original scalar scorer or inner metric names. Does not combine identities.

None
expected_tiers Sequence[int]

Complete planned tier set, with at least two distinct integers. Two tiers select pairwise-ordering analysis; three or more select mean Spearman correlation. Never inferred from surviving results.

required
expected_sample_ids Sequence[str | int] | None

Optional full sample manifest, applied to each cohort. IDs must be unique and cover all observations. Without it, counts describe observed IDs only.

None
tier_validation_field str | None

Optional metadata field containing the boolean True after external review of each generated output's assigned tier. Missing/false flags exclude the whole sample.

None
confidence_level float

Two-sided confidence level in (0, 1).

0.95
n_resamples int

Bootstrap resamples for three or more tiers, at least 1000. Defaults to 2000. Unused for two-tier designs.

2000
seed int

Non-negative bootstrap seed. Defaults to 0. Unused for two-tier designs.

0
**kwargs dict

Unused arguments accepted for ResultAnalyser compatibility.

{}

Returns:

Name Type Description
T T

One row per cohort/scorer/metric, with the mean correlation, interval, interval status, included/excluded counts, exclusion reasons and analysis settings. Two-tier rows include concordant/discordant counts and accuracy; bootstrap-only settings are null. Unestimable values are null. Cohorts without any recorded metrics have a null metric row. Empty projects return a typed empty table. Neither logs nor project records are modified.

Raises:

Type Description
ValueError

For invalid settings, invalid/unexpected tiers, IDs outside the manifest, duplicate sample/tier observations or mixed epochs.

Source code in evalsense/workflow/analysers/meta_result_analyser.py
@override
def __call__(
    self,
    project: Project,
    meta_tier_field: str = "perturbation_type_tier",
    lower_tier_is_better: bool = False,
    metric_labels: dict[str, str] | None = None,
    *,
    expected_tiers: Sequence[int],
    expected_sample_ids: Sequence[str | int] | None = None,
    tier_validation_field: str | None = None,
    confidence_level: float = 0.95,
    n_resamples: int = 2000,
    seed: int = 0,
    **kwargs: dict,
) -> T:
    """Summarise complete, finite tier comparisons with explicit evidence counts.

    Args:
        project (Project): Project containing the evaluation logs.
        meta_tier_field (str): Metadata field containing integer tier IDs.
        lower_tier_is_better (bool): True when lower tiers mean better outputs.
            All analysed metrics must be oriented so higher scores are better.
        metric_labels (dict[str, str] | None): Display aliases for original
            scalar scorer or inner metric names. Does not combine identities.
        expected_tiers (Sequence[int]): Complete planned tier set, with at least
            two distinct integers. Two tiers select pairwise-ordering analysis;
            three or more select mean Spearman correlation. Never inferred
            from surviving results.
        expected_sample_ids (Sequence[str | int] | None): Optional full sample
            manifest, applied to each cohort. IDs must be unique and cover all
            observations. Without it, counts describe observed IDs only.
        tier_validation_field (str | None): Optional metadata field containing
            the boolean True after external review of each generated output's
            assigned tier. Missing/false flags exclude the whole sample.
        confidence_level (float): Two-sided confidence level in (0, 1).
        n_resamples (int): Bootstrap resamples for three or more tiers, at least
            1000. Defaults to 2000. Unused for two-tier designs.
        seed (int): Non-negative bootstrap seed. Defaults to 0. Unused for
            two-tier designs.
        **kwargs (dict): Unused arguments accepted for ResultAnalyser compatibility.

    Returns:
        T: One row per cohort/scorer/metric, with the mean correlation, interval,
            interval status, included/excluded counts, exclusion reasons and
            analysis settings. Two-tier rows include concordant/discordant
            counts and accuracy; bootstrap-only settings are null. Unestimable
            values are null. Cohorts without any recorded metrics have a null
            metric row. Empty projects return
            a typed empty table. Neither logs nor project records are modified.

    Raises:
        ValueError: For invalid settings, invalid/unexpected tiers, IDs outside
            the manifest, duplicate sample/tier observations or mixed epochs.
    """
    tiers = _tier_set(expected_tiers)
    pairwise = len(tiers) == 2
    if not meta_tier_field or not isinstance(meta_tier_field, str):
        raise ValueError("meta_tier_field must be a non-empty string.")
    if type(lower_tier_is_better) is not bool:
        raise ValueError("lower_tier_is_better must be a boolean.")
    if type(confidence_level) not in (int, float) or not 0 < confidence_level < 1:
        raise ValueError("confidence_level must be between zero and one.")
    if type(n_resamples) is not int or n_resamples < 1000:
        raise ValueError("n_resamples must be an integer of at least 1000.")
    if type(seed) is not int or not 0 <= seed <= 2**63 - 1:
        raise ValueError("seed must be a non-negative 64-bit integer.")
    if tier_validation_field is not None and (
        not isinstance(tier_validation_field, str)
        or not tier_validation_field.strip()
    ):
        raise ValueError("tier_validation_field must be a non-empty string.")
    population = None
    if expected_sample_ids is not None:
        if isinstance(expected_sample_ids, (str, bytes)):
            raise ValueError(
                "expected_sample_ids must be a sequence of sample IDs."
            )
        population = {_sample_key(value) for value in expected_sample_ids}
        if len(population) != len(expected_sample_ids):
            raise ValueError("expected_sample_ids must not contain duplicates.")
    if tier_validation_field is None:
        warnings.warn(
            "Meta-evaluation tier severity has not been independently checked. "
            "Interpret these correlations as agreement with intended tiers, "
            "not validated evaluator accuracy.",
            UserWarning,
            stacklevel=2,
        )

    cohorts: dict[MetaTierGroupedRecord, _Cohort] = {}
    logs = project.get_logs(type="evaluation")
    check_metric_implementations(
        {record: log for record, log in logs.items() if log.status == "success"}
    )
    for record, result in project.records.evaluation.items():
        group = record.get_meta_grouped_record("")
        cohort = cohorts.setdefault(group, _Cohort())
        log = logs.get(record)
        if result.status != "success" or (
            log is not None and log.status != "success"
        ):
            cohort.failed_logs += 1
        if log is None or not log.samples:
            cohort.unavailable_logs += 1
            continue
        for sample in log.samples:
            tier = sample.metadata.get(meta_tier_field)
            if type(tier) is not int or tier not in tiers:
                raise ValueError(
                    f"Metadata field {meta_tier_field!r} must contain an expected "
                    "integer tier ID; check the experiment design and log metadata."
                )
            if cohort.epoch is not None and cohort.epoch != sample.epoch:
                raise ValueError(
                    "Multiple epochs require an explicit aggregation policy. "
                    "Analyse one epoch at a time."
                )
            cohort.epoch = sample.epoch
            key = _sample_key(sample.id)
            if population is not None and key not in population:
                raise ValueError(
                    "Observed sample ID is absent from expected_sample_ids."
                )
            observations = cohort.samples.setdefault(key, {})
            if tier in observations:
                raise ValueError(
                    "Duplicate sample/tier observation; results cannot be overwritten."
                )
            values: dict[MetricKey, Any] = {}
            for scorer_name, score in (sample.scores or {}).items():
                if isinstance(score.value, dict):
                    values.update(
                        {
                            (scorer_name, inner): value
                            for inner, value in score.value.items()
                        }
                    )
                else:
                    values[(scorer_name, None)] = score.value
            cohort.metrics.update(values)
            observations[tier] = _Observation(
                values,
                result.status == log.status == "success" and sample.error is None,
                tier_validation_field is not None
                and sample.metadata.get(tier_validation_field) is True,
            )

    rows = []
    for group, cohort in sorted(
        cohorts.items(), key=lambda item: item[0].model_dump_json()
    ):
        group_json = json.dumps(group.model_dump(mode="json"), sort_keys=True)
        sample_ids = sorted(
            population if population is not None else cohort.samples
        )
        metrics = sorted(cohort.metrics, key=lambda key: (key[0], key[1] or ""))
        for metric in metrics or [None]:
            counts: Counter[str] = Counter()
            correlations = []
            for sample_id in sample_ids:
                observed = cohort.samples.get(sample_id, {})
                if set(observed) != set(tiers):
                    counts["incomplete_tiers"] += 1
                    continue
                if metric is None or any(
                    not observed[t].usable or metric not in observed[t].scores
                    for t in tiers
                ):
                    counts["missing_scores"] += 1
                    continue
                tier_values = [observed[t].scores[metric] for t in tiers]
                if any(
                    type(v) not in (int, float) or not math.isfinite(v)
                    for v in tier_values
                ):
                    counts["invalid_scores"] += 1
                    continue
                if tier_validation_field is not None and not all(
                    observed[t].validated for t in tiers
                ):
                    counts["unvalidated"] += 1
                    continue
                if len(set(tier_values)) == 1:
                    counts["constant"] += 1
                    continue
                multiplier = -1 if lower_tier_is_better else 1
                if pairwise:
                    # Compare directly to avoid overflow when subtracting scores.
                    correlation = (
                        float(multiplier)
                        if tier_values[1] > tier_values[0]
                        else -float(multiplier)
                    )
                else:
                    correlation = float(
                        cast(
                            float,
                            spearmanr([multiplier * t for t in tiers], tier_values)[
                                0
                            ],
                        )
                    )
                if not math.isfinite(correlation):
                    counts["undefined"] += 1
                    continue
                correlations.append(correlation)
            concordant = (
                sum(value > 0 for value in correlations) if pairwise else None
            )
            if pairwise:
                assert concordant is not None
                low, high, interval_status = _pairwise_interval(
                    concordant, len(correlations), confidence_level
                )
            else:
                low, high, interval_status = _interval(
                    correlations, confidence_level, n_resamples, seed
                )
            raw_name = (
                (metric[1] if metric[1] is not None else metric[0])
                if metric
                else None
            )
            rows.append(
                {
                    "group_id": hashlib.sha256(group_json.encode()).hexdigest(),
                    "dataset": group.dataset_record.name,
                    "model": group.model_record.name,
                    "task": group.task_name,
                    "evaluator": group.evaluator_name,
                    "scorer": metric[0] if metric else None,
                    "metric_name": (metric_labels or {}).get(raw_name, raw_name)
                    if raw_name is not None
                    else None,
                    "analysis_kind": "pairwise_ordering"
                    if pairwise
                    else "mean_spearman",
                    "pairwise_accuracy": concordant / len(correlations)
                    if concordant is not None and correlations
                    else None,
                    "n_concordant": concordant,
                    "n_discordant": len(correlations) - concordant
                    if concordant is not None
                    else None,
                    "avg_correlation": math.fsum(correlations) / len(correlations)
                    if correlations
                    else None,
                    "ci_low": low,
                    "ci_high": high,
                    "ci_status": interval_status,
                    "n_samples": len(sample_ids),
                    "n_included": len(correlations),
                    "n_excluded": len(sample_ids) - len(correlations),
                    **{
                        f"n_{reason}": counts[reason]
                        for reason in (
                            "incomplete_tiers",
                            "missing_scores",
                            "invalid_scores",
                            "unvalidated",
                            "constant",
                            "undefined",
                        )
                    },
                    "failed_logs": cohort.failed_logs,
                    "unavailable_logs": cohort.unavailable_logs,
                    "sample_population": "declared"
                    if population is not None
                    else "observed",
                    "expected_tiers": json.dumps(tiers),
                    "lower_tier_is_better": lower_tier_is_better,
                    "validation_policy": "require_caller_attestation"
                    if tier_validation_field
                    else "not_checked",
                    "tier_validation_field": tier_validation_field,
                    "confidence_level": float(confidence_level),
                    "n_resamples": None if pairwise else n_resamples,
                    "seed": None if pairwise else seed,
                }
            )
    return cast(
        T, OUTPUT_FORMATTERS[self.output_format](pl.DataFrame(rows, schema=_SCHEMA))
    )

__init__

__init__(
    name: str = "MetaResultAnalyser",
    output_format: Literal["polars", "pandas"] = "polars",
)

Initialise the analyser.

Parameters:

Name Type Description Default
name str

Name of the analyser.

'MetaResultAnalyser'
output_format Literal['polars', 'pandas']

Result table format.

'polars'

Raises:

Type Description
ValueError

If the output format is unsupported.

Source code in evalsense/workflow/analysers/meta_result_analyser.py
def __init__(
    self,
    name: str = "MetaResultAnalyser",
    output_format: Literal["polars", "pandas"] = "polars",
):
    """Initialise the analyser.

    Args:
        name (str): Name of the analyser.
        output_format (Literal["polars", "pandas"]): Result table format.

    Raises:
        ValueError: If the output format is unsupported.
    """
    super().__init__(name=name)
    if output_format not in OUTPUT_FORMATTERS:
        raise ValueError(
            f"Invalid output format: {output_format}. Use polars or pandas."
        )
    self.output_format = output_format

MetricCorrelationAnalyser

Bases: ResultAnalyser[T]

Correlate scores on the same generated observations.

Pairing uses the full generation record, source Inspect eval_id, sample ID (including its type), and epoch. Older logs without eval_id require both run_id and task_id. Copies of the same generation can be compared across evaluators; independent generation attempts are not paired by sample ID alone.

Evaluator, scorer and inner-metric identities remain separate from display labels. Names are qualified when needed; ambiguous labels raise ValueError rather than merge distinct metrics. Retained evaluator configurations can share display names even when their identities differ.

Non-finite scores are excluded pairwise and counted. Fewer than two finite pairs or a constant vector produces NaN, including on the diagonal. Pairwise exclusion does not establish unbiased missingness; these are descriptive correlations without confidence estimates.

All tables use the same metric order and requested output format. The first column, Metric, contains row labels, including in NumPy output. Empty selections return empty tables and no figure. See CorrelationResults for the definitions of paired_counts and excluded_counts.

Methods:

Name Description
__call__

Calculate pairwise correlations after joining observation identities.

__init__

Initialise the metric correlation analyser.

Source code in evalsense/workflow/analysers/metric_correlation_analyser.py
class MetricCorrelationAnalyser[T: CorrelationResults](ResultAnalyser[T]):
    """Correlate scores on the same generated observations.

    Pairing uses the full generation record, source Inspect ``eval_id``, sample ID
    (including its type), and epoch. Older logs without ``eval_id`` require both
    ``run_id`` and ``task_id``. Copies of the same generation can be compared across
    evaluators; independent generation attempts are not paired by sample ID alone.

    Evaluator, scorer and inner-metric identities remain separate from display
    labels. Names are qualified when needed; ambiguous labels raise ValueError
    rather than merge distinct metrics. Retained evaluator configurations can
    share display names even when their identities differ.

    Non-finite scores are excluded pairwise and counted. Fewer than two finite
    pairs or a constant vector produces NaN, including on the diagonal. Pairwise
    exclusion does not establish unbiased missingness; these are descriptive
    correlations without confidence estimates.

    All tables use the same metric order and requested output format. The first
    column, ``Metric``, contains row labels, including in NumPy output. Empty
    selections return empty tables and no figure. See CorrelationResults for the
    definitions of ``paired_counts`` and ``excluded_counts``.
    """

    def __init__(
        self,
        name: str = "MetricCorrelationAnalyser",
        output_format: Literal["polars", "pandas", "numpy"] = "polars",
    ):
        """Initialise the metric correlation analyser.

        Args:
            name (str): Analyser name. Defaults to "MetricCorrelationAnalyser".
            output_format (Literal["polars", "pandas", "numpy"]): Format of all
                result tables. Defaults to "polars".

        Raises:
            ValueError: If output_format is unsupported.
        """
        super().__init__(name=name)
        if output_format not in OUTPUT_FORMATTERS:
            raise ValueError(
                f"Invalid output format: {output_format}. "
                f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
            )
        self.output_format = output_format

    @override
    def __call__(
        self,
        project: Project,
        corr_method: Literal["spearman", "pearson"] = "spearman",
        return_plot: bool = True,
        figsize: tuple[int, int] = (12, 10),
        metric_labels: dict[str, str] | None = None,
        method_filter_fun: Callable[[str], bool] = lambda _: True,
        **kwargs: dict,
    ) -> T:
        """Calculate pairwise correlations after joining observation identities.

        Args:
            project (Project): Project containing the successful evaluation logs
                to analyse.
            corr_method (Literal["spearman", "pearson"]): Correlation method.
                Defaults to "spearman".
            return_plot (bool): Whether to include a correlation plot when metrics
                are selected. Defaults to True.
            figsize (tuple[int, int]): Plot dimensions. Defaults to (12, 10).
            metric_labels (dict[str, str] | None): Map original scalar scorer names
                or inner metric names to display aliases in all tables and the
                plot. Aliases do not change observation identity. Defaults to None.
            method_filter_fun (Callable[[str], bool]): Include a numeric metric
                when this function returns True for its original scalar scorer
                name or inner metric name, before aliasing. Defaults to including
                all numeric metrics.
            **kwargs (dict): Additional analyser-interface arguments. Unused.

        Returns:
            T: CorrelationResults containing correlation_matrix, paired_counts and
                excluded_counts in the requested output format, and an optional
                figure. Empty selections produce empty tables and no figure.

        Raises:
            ValueError: If corr_method is unsupported, source identity is missing,
                a metric/observation key is duplicated (even with equal scores),
                or display labels are ambiguous or use the reserved name "Metric".
        """
        if corr_method not in ("spearman", "pearson"):
            raise ValueError("corr_method must be 'spearman' or 'pearson'.")
        observations: dict[MetricKey, dict[ObservationKey, float]] = defaultdict(dict)
        evaluator_names: dict[MetricKey, str] = {}
        eval_logs = project.get_logs(type="evaluation", status="success")
        check_metric_implementations(eval_logs)
        for record, log in eval_logs.items():
            if not log.samples:
                continue
            generation = record.generation_record
            # Evaluation logs are copies of a generation log, so eval_id identifies
            # their common source. Paths and scoring timestamps do not.
            source_id = _source_identity(log)
            generation_fields = generation.model_dump()
            evaluator_identity = json.dumps(
                {
                    key: value
                    for key, value in record.model_dump(mode="json").items()
                    if key not in generation_fields
                },
                sort_keys=True,
            )
            for sample in log.samples:
                if not sample.scores:
                    continue
                observation = (
                    generation,
                    source_id,
                    type(sample.id),
                    sample.id,
                    sample.epoch,
                )
                for scorer_name, score in sample.scores.items():
                    components = (
                        score.value.items()
                        if isinstance(score.value, dict)
                        else [(None, score.value)]
                    )
                    for inner_name, value in components:
                        name = inner_name if inner_name is not None else scorer_name
                        if type(value) not in (int, float) or not method_filter_fun(
                            name
                        ):
                            continue
                        key = (evaluator_identity, scorer_name, inner_name)
                        if observation in observations[key]:
                            raise ValueError(
                                f"Duplicate observation for {record.evaluator_name!r}, "
                                f"scorer {scorer_name!r}, metric {name!r}, "
                                f"sample {sample.id!r}, epoch {sample.epoch}, "
                                f"source eval {source_id!r}."
                            )
                        observations[key][observation] = float(cast(float | int, value))
                        evaluator_names[key] = record.evaluator_name

        keys = sorted(observations, key=lambda key: (key[0], key[1], key[2] or ""))
        names = _metric_names(keys, evaluator_names, metric_labels or {})
        size = len(keys)
        correlations = [[math.nan] * size for _ in keys]
        paired = [[0] * size for _ in keys]
        excluded = [[0] * size for _ in keys]
        for i, left in enumerate(keys):
            for j in range(i, size):
                right = keys[j]
                # Join before filtering values; never align by vector position.
                common = observations[left].keys() & observations[right].keys()
                pairs = sorted(
                    (observations[left][obs], observations[right][obs])
                    for obs in common
                    if math.isfinite(observations[left][obs])
                    and math.isfinite(observations[right][obs])
                )
                paired[i][j] = paired[j][i] = len(pairs)
                excluded[i][j] = excluded[j][i] = len(common) - len(pairs)
                if len(pairs) < 2:
                    continue
                x, y = zip(*pairs)
                if len(set(x)) < 2 or len(set(y)) < 2:
                    continue
                value = (
                    pl.DataFrame(
                        {
                            "left": pl.Series(x, dtype=pl.Float64),
                            "right": pl.Series(y, dtype=pl.Float64),
                        }
                    )
                    .select(
                        pl.corr(
                            "left", "right", method=corr_method, propagate_nans=True
                        )
                    )
                    .item()
                )
                correlations[i][j] = correlations[j][i] = (
                    float(value) if value is not None else math.nan
                )

        corr_matrix = _matrix(correlations, names, pl.Float64())
        count_matrix = _matrix(paired, names, pl.Int64())
        excluded_matrix = _matrix(excluded, names, pl.Int64())
        fig = None
        if return_plot and names:
            corr_matrix_pd = corr_matrix.to_pandas().set_index("Metric")
            fig, ax = plt.subplots(figsize=figsize)
            mask = np.triu(np.ones_like(corr_matrix_pd, dtype=bool), k=1)
            sns.heatmap(
                corr_matrix_pd,
                mask=mask | corr_matrix_pd.isna(),
                cmap=sns.diverging_palette(220, 10, as_cmap=True),
                vmax=1.0,
                vmin=-1.0,
                center=0,
                square=True,
                linewidths=0.5,
                cbar_kws={"shrink": 0.5},
                annot=True,
                fmt=".2f",
                ax=ax,
            )
            ax.set_title(
                "Spearman Rank Correlation Between Evaluation Metrics"
                if corr_method == "spearman"
                else "Pearson Correlation Between Evaluation Metrics"
            )
            fig.tight_layout()

        formatter = OUTPUT_FORMATTERS[self.output_format]
        return cast(
            T,
            CorrelationResults(
                correlation_matrix=formatter(corr_matrix),
                figure=fig,
                paired_counts=formatter(count_matrix),
                excluded_counts=formatter(excluded_matrix),
            ),
        )

__call__

__call__(
    project: Project,
    corr_method: Literal[
        "spearman", "pearson"
    ] = "spearman",
    return_plot: bool = True,
    figsize: tuple[int, int] = (12, 10),
    metric_labels: dict[str, str] | None = None,
    method_filter_fun: Callable[[str], bool] = lambda _: (
        True
    ),
    **kwargs: dict,
) -> T

Calculate pairwise correlations after joining observation identities.

Parameters:

Name Type Description Default
project Project

Project containing the successful evaluation logs to analyse.

required
corr_method Literal['spearman', 'pearson']

Correlation method. Defaults to "spearman".

'spearman'
return_plot bool

Whether to include a correlation plot when metrics are selected. Defaults to True.

True
figsize tuple[int, int]

Plot dimensions. Defaults to (12, 10).

(12, 10)
metric_labels dict[str, str] | None

Map original scalar scorer names or inner metric names to display aliases in all tables and the plot. Aliases do not change observation identity. Defaults to None.

None
method_filter_fun Callable[[str], bool]

Include a numeric metric when this function returns True for its original scalar scorer name or inner metric name, before aliasing. Defaults to including all numeric metrics.

lambda _: True
**kwargs dict

Additional analyser-interface arguments. Unused.

{}

Returns:

Name Type Description
T T

CorrelationResults containing correlation_matrix, paired_counts and excluded_counts in the requested output format, and an optional figure. Empty selections produce empty tables and no figure.

Raises:

Type Description
ValueError

If corr_method is unsupported, source identity is missing, a metric/observation key is duplicated (even with equal scores), or display labels are ambiguous or use the reserved name "Metric".

Source code in evalsense/workflow/analysers/metric_correlation_analyser.py
@override
def __call__(
    self,
    project: Project,
    corr_method: Literal["spearman", "pearson"] = "spearman",
    return_plot: bool = True,
    figsize: tuple[int, int] = (12, 10),
    metric_labels: dict[str, str] | None = None,
    method_filter_fun: Callable[[str], bool] = lambda _: True,
    **kwargs: dict,
) -> T:
    """Calculate pairwise correlations after joining observation identities.

    Args:
        project (Project): Project containing the successful evaluation logs
            to analyse.
        corr_method (Literal["spearman", "pearson"]): Correlation method.
            Defaults to "spearman".
        return_plot (bool): Whether to include a correlation plot when metrics
            are selected. Defaults to True.
        figsize (tuple[int, int]): Plot dimensions. Defaults to (12, 10).
        metric_labels (dict[str, str] | None): Map original scalar scorer names
            or inner metric names to display aliases in all tables and the
            plot. Aliases do not change observation identity. Defaults to None.
        method_filter_fun (Callable[[str], bool]): Include a numeric metric
            when this function returns True for its original scalar scorer
            name or inner metric name, before aliasing. Defaults to including
            all numeric metrics.
        **kwargs (dict): Additional analyser-interface arguments. Unused.

    Returns:
        T: CorrelationResults containing correlation_matrix, paired_counts and
            excluded_counts in the requested output format, and an optional
            figure. Empty selections produce empty tables and no figure.

    Raises:
        ValueError: If corr_method is unsupported, source identity is missing,
            a metric/observation key is duplicated (even with equal scores),
            or display labels are ambiguous or use the reserved name "Metric".
    """
    if corr_method not in ("spearman", "pearson"):
        raise ValueError("corr_method must be 'spearman' or 'pearson'.")
    observations: dict[MetricKey, dict[ObservationKey, float]] = defaultdict(dict)
    evaluator_names: dict[MetricKey, str] = {}
    eval_logs = project.get_logs(type="evaluation", status="success")
    check_metric_implementations(eval_logs)
    for record, log in eval_logs.items():
        if not log.samples:
            continue
        generation = record.generation_record
        # Evaluation logs are copies of a generation log, so eval_id identifies
        # their common source. Paths and scoring timestamps do not.
        source_id = _source_identity(log)
        generation_fields = generation.model_dump()
        evaluator_identity = json.dumps(
            {
                key: value
                for key, value in record.model_dump(mode="json").items()
                if key not in generation_fields
            },
            sort_keys=True,
        )
        for sample in log.samples:
            if not sample.scores:
                continue
            observation = (
                generation,
                source_id,
                type(sample.id),
                sample.id,
                sample.epoch,
            )
            for scorer_name, score in sample.scores.items():
                components = (
                    score.value.items()
                    if isinstance(score.value, dict)
                    else [(None, score.value)]
                )
                for inner_name, value in components:
                    name = inner_name if inner_name is not None else scorer_name
                    if type(value) not in (int, float) or not method_filter_fun(
                        name
                    ):
                        continue
                    key = (evaluator_identity, scorer_name, inner_name)
                    if observation in observations[key]:
                        raise ValueError(
                            f"Duplicate observation for {record.evaluator_name!r}, "
                            f"scorer {scorer_name!r}, metric {name!r}, "
                            f"sample {sample.id!r}, epoch {sample.epoch}, "
                            f"source eval {source_id!r}."
                        )
                    observations[key][observation] = float(cast(float | int, value))
                    evaluator_names[key] = record.evaluator_name

    keys = sorted(observations, key=lambda key: (key[0], key[1], key[2] or ""))
    names = _metric_names(keys, evaluator_names, metric_labels or {})
    size = len(keys)
    correlations = [[math.nan] * size for _ in keys]
    paired = [[0] * size for _ in keys]
    excluded = [[0] * size for _ in keys]
    for i, left in enumerate(keys):
        for j in range(i, size):
            right = keys[j]
            # Join before filtering values; never align by vector position.
            common = observations[left].keys() & observations[right].keys()
            pairs = sorted(
                (observations[left][obs], observations[right][obs])
                for obs in common
                if math.isfinite(observations[left][obs])
                and math.isfinite(observations[right][obs])
            )
            paired[i][j] = paired[j][i] = len(pairs)
            excluded[i][j] = excluded[j][i] = len(common) - len(pairs)
            if len(pairs) < 2:
                continue
            x, y = zip(*pairs)
            if len(set(x)) < 2 or len(set(y)) < 2:
                continue
            value = (
                pl.DataFrame(
                    {
                        "left": pl.Series(x, dtype=pl.Float64),
                        "right": pl.Series(y, dtype=pl.Float64),
                    }
                )
                .select(
                    pl.corr(
                        "left", "right", method=corr_method, propagate_nans=True
                    )
                )
                .item()
            )
            correlations[i][j] = correlations[j][i] = (
                float(value) if value is not None else math.nan
            )

    corr_matrix = _matrix(correlations, names, pl.Float64())
    count_matrix = _matrix(paired, names, pl.Int64())
    excluded_matrix = _matrix(excluded, names, pl.Int64())
    fig = None
    if return_plot and names:
        corr_matrix_pd = corr_matrix.to_pandas().set_index("Metric")
        fig, ax = plt.subplots(figsize=figsize)
        mask = np.triu(np.ones_like(corr_matrix_pd, dtype=bool), k=1)
        sns.heatmap(
            corr_matrix_pd,
            mask=mask | corr_matrix_pd.isna(),
            cmap=sns.diverging_palette(220, 10, as_cmap=True),
            vmax=1.0,
            vmin=-1.0,
            center=0,
            square=True,
            linewidths=0.5,
            cbar_kws={"shrink": 0.5},
            annot=True,
            fmt=".2f",
            ax=ax,
        )
        ax.set_title(
            "Spearman Rank Correlation Between Evaluation Metrics"
            if corr_method == "spearman"
            else "Pearson Correlation Between Evaluation Metrics"
        )
        fig.tight_layout()

    formatter = OUTPUT_FORMATTERS[self.output_format]
    return cast(
        T,
        CorrelationResults(
            correlation_matrix=formatter(corr_matrix),
            figure=fig,
            paired_counts=formatter(count_matrix),
            excluded_counts=formatter(excluded_matrix),
        ),
    )

__init__

__init__(
    name: str = "MetricCorrelationAnalyser",
    output_format: Literal[
        "polars", "pandas", "numpy"
    ] = "polars",
)

Initialise the metric correlation analyser.

Parameters:

Name Type Description Default
name str

Analyser name. Defaults to "MetricCorrelationAnalyser".

'MetricCorrelationAnalyser'
output_format Literal['polars', 'pandas', 'numpy']

Format of all result tables. Defaults to "polars".

'polars'

Raises:

Type Description
ValueError

If output_format is unsupported.

Source code in evalsense/workflow/analysers/metric_correlation_analyser.py
def __init__(
    self,
    name: str = "MetricCorrelationAnalyser",
    output_format: Literal["polars", "pandas", "numpy"] = "polars",
):
    """Initialise the metric correlation analyser.

    Args:
        name (str): Analyser name. Defaults to "MetricCorrelationAnalyser".
        output_format (Literal["polars", "pandas", "numpy"]): Format of all
            result tables. Defaults to "polars".

    Raises:
        ValueError: If output_format is unsupported.
    """
    super().__init__(name=name)
    if output_format not in OUTPUT_FORMATTERS:
        raise ValueError(
            f"Invalid output format: {output_format}. "
            f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
        )
    self.output_format = output_format

TabularResultAnalyser

Bases: ResultAnalyser[T]

An analyser summarising evaluation results in a tabular format.

This class is generic in T to provide better type hints when returning different output types. It is the responsibility of the client code to ensure that the specified output_format is compatible with the type T. For example, a correct use of this class could look as follows:

analyser = TabularResultAnalyser[pl.DataFrame](
    output_format="polars",
)

Methods:

Name Description
__call__

Summarise successful evaluation logs by stored generation configuration.

__init__

Initializes the tabular result analyser.

Source code in evalsense/workflow/analysers/tabular_analyser.py
class TabularResultAnalyser[T: pl.DataFrame | pd.DataFrame](ResultAnalyser[T]):
    """An analyser summarising evaluation results in a tabular format.

    This class is generic in T to provide better type hints when returning
    different output types. It is the responsibility of the client code to
    ensure that the specified `output_format` is compatible with the type T.
    For example, a correct use of this class could look as follows:

        analyser = TabularResultAnalyser[pl.DataFrame](
            output_format="polars",
        )
    """

    def __init__(
        self,
        name: str = "TabularResultAnalyser",
        output_format: Literal["polars", "pandas"] = "polars",
    ):
        """Initializes the tabular result analyser.

        Args:
            name (str): The name of the tabular result analyser.
            output_format (Literal["polars", "pandas", "dataset"]): The output format of the
                result. Can be "polars" or "pandas". Defaults to "polars".
        """
        super().__init__(name=name)
        if output_format not in OUTPUT_FORMATTERS:
            raise ValueError(
                f"Invalid output format: {output_format}. "
                f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
            )
        self.output_format = output_format

    @override
    def __call__(self, project: Project, **kwargs: dict) -> T:
        """Summarise successful evaluation logs by stored generation configuration.

        Args:
            project (Project): The project holding the evaluation data to analyse.
            **kwargs (dict): Additional arguments for the analysis.

        Returns:
            T: One row per generation ID with available aggregate metrics. Metrics
                for different evaluators share a row when their generation matches.
                A project without aggregates returns just the identity columns.

        Raises:
            ValueError: If an aggregate is duplicated for a generation, if metric
                labels remain ambiguous, or if metric implementations conflict.
        """
        eval_logs = project.get_logs(type="evaluation", status="success")
        check_metric_implementations(eval_logs)

        rows: dict[str, dict[str, str | int | float | None]] = {}
        columns: dict[str, tuple[str, str]] = {}
        for eval_record, log in eval_logs.items():
            if not log.results or not any(
                score.metrics for score in log.results.scores
            ):
                continue

            generation_id = eval_record.generation_id
            row = rows.setdefault(
                generation_id,
                {
                    "dataset": eval_record.dataset_record.name,
                    "splits": ", ".join(eval_record.dataset_record.splits),
                    "task": eval_record.task_name,
                    "generator": eval_record.generator_name,
                    "model": eval_record.model_record.name,
                    "generation_id": generation_id,
                    "dataset_version": eval_record.dataset_record.version,
                    "experiment_name": eval_record.experiment_name,
                },
            )
            for score in log.results.scores:
                for metric_name, metric in score.metrics.items():
                    key = _metric_id(eval_record, score, metric_name, metric)
                    label = f"{score.name}/{metric_name}"
                    if key in row:
                        raise ValueError(
                            f"Duplicate summary metric {label!r} for generation {generation_id}."
                        )
                    columns[key] = (label, eval_record.evaluator_name)
                    row[key] = metric.value

        index = [
            "dataset",
            "splits",
            "task",
            "generator",
            "model",
            "generation_id",
            "dataset_version",
            "experiment_name",
        ]
        df = pl.DataFrame(
            list(rows.values()),
            schema={**dict.fromkeys(index, pl.String), **dict.fromkeys(columns)},
            infer_schema_length=None,
        ).rename(_metric_labels(columns))
        if self.output_format in OUTPUT_FORMATTERS:
            return cast(T, OUTPUT_FORMATTERS[self.output_format](df))
        raise ValueError(
            f"Invalid output format: {self.output_format}. "
            f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
        )

__call__

__call__(project: Project, **kwargs: dict) -> T

Summarise successful evaluation logs by stored generation configuration.

Parameters:

Name Type Description Default
project Project

The project holding the evaluation data to analyse.

required
**kwargs dict

Additional arguments for the analysis.

{}

Returns:

Name Type Description
T T

One row per generation ID with available aggregate metrics. Metrics for different evaluators share a row when their generation matches. A project without aggregates returns just the identity columns.

Raises:

Type Description
ValueError

If an aggregate is duplicated for a generation, if metric labels remain ambiguous, or if metric implementations conflict.

Source code in evalsense/workflow/analysers/tabular_analyser.py
@override
def __call__(self, project: Project, **kwargs: dict) -> T:
    """Summarise successful evaluation logs by stored generation configuration.

    Args:
        project (Project): The project holding the evaluation data to analyse.
        **kwargs (dict): Additional arguments for the analysis.

    Returns:
        T: One row per generation ID with available aggregate metrics. Metrics
            for different evaluators share a row when their generation matches.
            A project without aggregates returns just the identity columns.

    Raises:
        ValueError: If an aggregate is duplicated for a generation, if metric
            labels remain ambiguous, or if metric implementations conflict.
    """
    eval_logs = project.get_logs(type="evaluation", status="success")
    check_metric_implementations(eval_logs)

    rows: dict[str, dict[str, str | int | float | None]] = {}
    columns: dict[str, tuple[str, str]] = {}
    for eval_record, log in eval_logs.items():
        if not log.results or not any(
            score.metrics for score in log.results.scores
        ):
            continue

        generation_id = eval_record.generation_id
        row = rows.setdefault(
            generation_id,
            {
                "dataset": eval_record.dataset_record.name,
                "splits": ", ".join(eval_record.dataset_record.splits),
                "task": eval_record.task_name,
                "generator": eval_record.generator_name,
                "model": eval_record.model_record.name,
                "generation_id": generation_id,
                "dataset_version": eval_record.dataset_record.version,
                "experiment_name": eval_record.experiment_name,
            },
        )
        for score in log.results.scores:
            for metric_name, metric in score.metrics.items():
                key = _metric_id(eval_record, score, metric_name, metric)
                label = f"{score.name}/{metric_name}"
                if key in row:
                    raise ValueError(
                        f"Duplicate summary metric {label!r} for generation {generation_id}."
                    )
                columns[key] = (label, eval_record.evaluator_name)
                row[key] = metric.value

    index = [
        "dataset",
        "splits",
        "task",
        "generator",
        "model",
        "generation_id",
        "dataset_version",
        "experiment_name",
    ]
    df = pl.DataFrame(
        list(rows.values()),
        schema={**dict.fromkeys(index, pl.String), **dict.fromkeys(columns)},
        infer_schema_length=None,
    ).rename(_metric_labels(columns))
    if self.output_format in OUTPUT_FORMATTERS:
        return cast(T, OUTPUT_FORMATTERS[self.output_format](df))
    raise ValueError(
        f"Invalid output format: {self.output_format}. "
        f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
    )

__init__

__init__(
    name: str = "TabularResultAnalyser",
    output_format: Literal["polars", "pandas"] = "polars",
)

Initializes the tabular result analyser.

Parameters:

Name Type Description Default
name str

The name of the tabular result analyser.

'TabularResultAnalyser'
output_format Literal['polars', 'pandas', 'dataset']

The output format of the result. Can be "polars" or "pandas". Defaults to "polars".

'polars'
Source code in evalsense/workflow/analysers/tabular_analyser.py
def __init__(
    self,
    name: str = "TabularResultAnalyser",
    output_format: Literal["polars", "pandas"] = "polars",
):
    """Initializes the tabular result analyser.

    Args:
        name (str): The name of the tabular result analyser.
        output_format (Literal["polars", "pandas", "dataset"]): The output format of the
            result. Can be "polars" or "pandas". Defaults to "polars".
    """
    super().__init__(name=name)
    if output_format not in OUTPUT_FORMATTERS:
        raise ValueError(
            f"Invalid output format: {output_format}. "
            f"Must be one of: {', '.join(OUTPUT_FORMATTERS.keys())}."
        )
    self.output_format = output_format