Skip to content

API Reference

Simulation

Core simulation engine.

Workflow

  1. Read the TOML configuration.
  2. For each generative model x n_voters x n_candidates x iteration: a. Check if the generated profile already exists on disk : load it. b. If not, generate it via the generator registry and persist it.
  3. Apply every rule to each profile and collect winners.
  4. Persist the simulation results to sim_result/.

The directory layout follows::

<output_base>/
  gen/<MODEL>_v<NV>_c<NC>/
    iter_0001.parquet
    …
  sim_result/<MODEL>_v<NV>_c<NC>/
    iter_0001.parquet
    …

generate_data(config_path, show_progress=True)

Generate (or retrieve cached) profiles for every combination defined in the config.

Returns:

Type Description
list[str]

List of file paths of generated/cached parquet files.

Source code in src/vote_simulation/simulation/simulation.py
def generate_data(config_path: str, show_progress: bool = True) -> list[str]:
    """Generate (or retrieve cached) profiles for every combination defined in the config.

    Returns:
        List of file paths of generated/cached parquet files.
    """
    config = load_simulation_config(config_path)
    _validate_generation_config(config)

    paths: list[str] = []
    total = len(config.generative_models) * len(config.voters or []) * len(config.candidates or []) * config.iterations
    with tqdm(total=total, desc="Generating profiles", disable=not show_progress) as pbar:
        for model in config.generative_models:
            extra = config.generator_params.get(model, {})
            for n_v in config.voters or []:
                for n_c in config.candidates or []:
                    for it in range(config.iterations):
                        di = obtain_data_instance(
                            model=model,
                            n_v=n_v,
                            n_c=n_c,
                            iteration=it,
                            seed=config.seed,
                            base_path=config.output_base_path,
                            extra_params=extra,
                        )
                        paths.append(di.file_path)
                        pbar.update(1)
    print(f"Generated / loaded {len(paths)} profiles.")
    return paths

obtain_data_instance(model, n_v, n_c, *, iteration=0, seed=161, base_path='data', extra_params=None, reload=False)

Load a cached profile or generate + persist it.

If the parquet file already exists AND reload is False, the profile is loaded from disk; otherwise it is (re-)generated with the given seed and saved for future reuse.

Parameters:

Name Type Description Default
model str

Generative model code (e.g. "UNI", "IC").

required
n_v int

Number of voters.

required
n_c int

Number of candidates.

required
iteration int

Iteration index.

0
seed int

Random seed for generation (combined with iteration for uniqueness).

161
base_path str

Root folder for generated data (see config.output_base_path).

'data'
extra_params dict[str, object] | None

Optional dict of extra parameters to pass to the generator (per-model).

None
reload bool

When True, ignore any existing cached file and regenerate from the seed. Use this whenever the seed changes to ensure the new seed is actually applied.

False
Source code in src/vote_simulation/simulation/simulation.py
def obtain_data_instance(
    model: str,
    n_v: int,
    n_c: int,
    *,
    iteration: int = 0,
    seed: int = 161,
    base_path: str = "data",
    extra_params: dict[str, object] | None = None,
    reload: bool = False,
) -> DataInstance:
    """Load a cached profile or generate + persist it.

    If the parquet file already exists AND *reload* is False, the profile
    is loaded from disk; otherwise it is (re-)generated with the given seed
    and saved for future reuse.

    Args:
        model: Generative model code (e.g. "UNI", "IC").
        n_v: Number of voters.
        n_c: Number of candidates.
        iteration: Iteration index.
        seed: Random seed for generation (combined with iteration for uniqueness).
        base_path: Root folder for generated data (see config.output_base_path).
        extra_params: Optional dict of extra parameters to pass to the generator (per-model).
        reload: When True, ignore any existing cached file and regenerate from
            the seed.  Use this whenever the seed changes to ensure the new
            seed is actually applied.
    """
    gen_path = _gen_dir(base_path, model, n_v, n_c) / _iter_filename(iteration)

    # Single stat() call instead of is_file() + stat() (2 syscalls → 1).
    if not reload:
        try:
            if gen_path.stat().st_size > 0:
                return DataInstance(str(gen_path))
        except FileNotFoundError:
            pass

    # Generate
    di = DataInstance.from_generator(
        model_code=model,
        n_v=n_v,
        n_c=n_c,
        seed=seed,
        iteration=iteration,
        **(extra_params or {}),
    )
    di.save_parquet(str(gen_path))
    di.file_path = str(gen_path)
    return di

run_rules_on_instance(data_instance, rule_codes, config=None, *, compute_metrics=True)

Apply every rule and collect winners into a SimulationStepResult.

Parameters:

Name Type Description Default
data_instance DataInstance

The profile data to run the rules on.

required
rule_codes list[str]

List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]).

required
config ResultConfig | None

Optional :class:ResultConfig attached to the step.

None
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Set to False to skip metric computation and reduce runtime when quality metrics are not needed.

True
Source code in src/vote_simulation/simulation/simulation.py
def run_rules_on_instance(
    data_instance: DataInstance,
    rule_codes: list[str],
    config: ResultConfig | None = None,
    *,
    compute_metrics: bool = True,
) -> SimulationStepResult:
    """
    Apply every rule and collect winners into a ``SimulationStepResult``.

    Args:
        data_instance: The profile data to run the rules on.
        rule_codes: List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]).
        config: Optional :class:`ResultConfig` attached to the step.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Set to ``False`` to skip metric computation and
            reduce runtime when quality metrics are not needed.
    """
    profile = data_instance.profile
    # base_preferences_ut = np.asarray(profile.preferences_ut, dtype=np.float64)
    # base_preferences_rk = np.argsort(-base_preferences_ut, axis=1, kind="stable")
    # labels = list(getattr(profile, "labels_candidates", [str(i) for i in range(base_preferences_ut.shape[1])]))

    step = SimulationStepResult(
        data_source=data_instance.file_path,
        config=config or ResultConfig(),
    )

    for code in rule_codes:
        normalized = code.strip().upper()
        try:
            builder = get_rule_builder(normalized)
            # Recreate a fresh profile per rule to avoid state leakage between wrappers.
            # rule_profile = Profile(
            #    preferences_ut=base_preferences_ut.copy(),
            #    labels_candidates=labels,
            # )
            rule: RuleResult = builder(profile, None)
            winners = rule.cowinners_
            if compute_metrics:
                try:
                    metrics = rule.compute_metrics()
                    step.add_method_result_with_metrics(normalized, winners, metrics)
                except Exception:
                    # Rule wrappers outside SvvampRuleWrapper don't carry metrics — degrade gracefully.
                    step.add_method_result(normalized, winners)
            else:
                step.add_method_result(normalized, winners)
        except Exception as e:  # noqa: BLE001
            print(f"Error applying rule '{normalized}': {e}")
            step.add_method_result(normalized, [f"ERROR: {e}"])
    return step

sim(file_path, rule_code)

Execute a single rule on a single file.

Source code in src/vote_simulation/simulation/simulation.py
def sim(file_path: str, rule_code: str) -> None:
    """Execute a single rule on a single file."""
    data_instance = DataInstance(file_path)
    profile = data_instance.profile
    rule_code = rule_code.strip().upper()

    try:
        rule_builder = get_rule_builder(rule_code)
        rule: RuleResult = rule_builder(profile, None)
        if not hasattr(rule, "w_") and not hasattr(rule, "winner_indices_") and not hasattr(rule, "winner_"):
            raise TypeError(f"Unexpected rule type for '{rule_code}': {type(rule)!r}")
        print(f"{rule_code.upper()} winner: {rule.cowinners_}")
    except Exception as e:
        print(f"Error building rule '{rule_code}': {e}")

simulation_from_config(config_path, show_progress=True, *, reload=False, compute_metrics=True)

Full pipeline: generate profiles, apply rules, save results.

For every (model, n_voters, n_candidates, iteration) combination: 1. Obtain (generate or load) the profile. 2. Run all requested rules. 3. Save the result in sim_result/<MODEL>_v<NV>_c<NC>/iter_XXXX.parquet.

Parameters:

Name Type Description Default
config_path str

Path to the TOML configuration file (see docs for the template).

required
show_progress bool

Whether to display a progress bar.

True
reload bool

When True, ignore any cached result files and recompute every iteration from scratch. When False (default), iterations whose result file already exists are skipped.

False
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Defaults to True.

True
Source code in src/vote_simulation/simulation/simulation.py
def simulation_from_config(
    config_path: str,
    show_progress: bool = True,
    *,
    reload: bool = False,
    compute_metrics: bool = True,
) -> None:
    """Full pipeline: generate profiles, apply rules, save results.

    For every ``(model, n_voters, n_candidates, iteration)`` combination:
    1. Obtain (generate or load) the profile.
    2. Run all requested rules.
    3. Save the result in ``sim_result/<MODEL>_v<NV>_c<NC>/iter_XXXX.parquet``.

    Args:
        config_path: Path to the TOML configuration file (see docs for the template).
        show_progress: Whether to display a progress bar.
        reload: When ``True``, ignore any cached result files and recompute
            every iteration from scratch.  When ``False`` (default), iterations
            whose result file already exists are skipped.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Defaults to ``True``.
    """
    config = load_simulation_config(config_path)
    _validate_generation_config(config)

    # Pre-fetch rule builders once before any loop.
    # config.rule_codes are already normalised by load_simulation_config, so no
    # .strip().upper() needed here.  Avoids len(rules) × total_iterations
    # redundant dict lookups + string operations in the hot path.
    # Unknown codes are warned once and skipped (graceful degradation).
    builders: list[tuple[str, Any]] = []
    for code in config.rule_codes:
        try:
            builders.append((code, get_rule_builder(code)))
        except ValueError:
            print(f"Warning: unknown rule code '{code}' — skipped.")

    total = len(config.generative_models) * len(config.voters or []) * len(config.candidates or []) * config.iterations
    print(f"Running full simulation: {total} profile(s) × {len(builders)} rule(s)")

    with tqdm(total=total, desc="Simulating", disable=not show_progress) as pbar:
        for model in config.generative_models:
            extra = config.generator_params.get(model, {})
            for n_v in config.voters or []:
                for n_c in config.candidates or []:
                    # Create output directory ONCE per (model, n_v, n_c) combo,
                    # not 1 000 times inside the iteration loop.
                    sim_dir = _sim_dir(config.output_base_path, model, n_v, n_c)
                    sim_dir.mkdir(parents=True, exist_ok=True)

                    step_cfg = ResultConfig.single(
                        gen_model=model,
                        n_voters=n_v,
                        n_candidates=n_c,
                        rules_codes=config.rule_codes,
                    )
                    for it in range(config.iterations):
                        result_path = sim_dir / _iter_filename(it)

                        # Single stat() call instead of is_file() + stat() (2 syscalls → 1).
                        if not reload:
                            try:
                                if result_path.stat().st_size > 0:
                                    pbar.update(1)
                                    continue
                            except FileNotFoundError:
                                pass

                        # 1) Obtain (generate or load) profile
                        di = obtain_data_instance(
                            model=model,
                            n_v=n_v,
                            n_c=n_c,
                            iteration=it,
                            seed=config.seed,
                            base_path=config.output_base_path,
                            extra_params=extra,
                            reload=reload,
                        )

                        # 2) Apply rules using pre-fetched builders (inline hot path)
                        profile = di.profile
                        step = SimulationStepResult(
                            data_source=di.file_path,
                            config=step_cfg,
                        )
                        for code, builder in builders:
                            try:
                                rule = builder(profile, None)
                                winners = rule.cowinners_
                                if compute_metrics:
                                    try:
                                        metrics = rule.compute_metrics()
                                        step.add_method_result_with_metrics(code, winners, metrics)
                                    except Exception:
                                        step.add_method_result(code, winners)
                                else:
                                    step.add_method_result(code, winners)
                            except Exception as e:  # noqa: BLE001
                                print(f"Error applying rule '{code}': {e}")
                                step.add_method_result(code, [f"ERROR: {e}"])

                        # 3) Save result
                        step.save_to_file(str(result_path))

                        pbar.update(1)

    print("Full simulation completed.")

simulation_instance(gen_code, n_v, n_c, rule_codes, n_iteration=1000, seed=161, base_path='data', reload=False, show_progress=True, *, extra_params=None, compute_metrics=True)

Run the workflow on a single (model, voters, candidates) instance.

Each step receives a :class:ResultConfig so that the series automatically aggregates the simulation context.

Cache logic: 1. Checks for a cached result at <base_path>/results/<base_label>.parquet (where base_label excludes rules). 2. If found with matching step count and same base parameters: - If rules are identical: returns cached series (no recomputation). - If rules differ: loads cached series and applies new rules incrementally. 3. If not found or stale: recomputes from scratch.

Parameters:

Name Type Description Default
gen_code str

Generative model code (list can be found in doc).

required
n_v int

Number of voters.

required
n_c int

Number of candidates.

required
rule_codes list[str]

List of rule codes to apply.

required
n_iteration int

Number of iterations. Defaults to 1000.

1000
seed int

Seed for reproducibility. Defaults to 161.

161
base_path str

Root folder for generated data. Defaults to "data".

'data'
reload bool

Force re-computation (ignore cache). Defaults to False.

False
show_progress bool

Whether to display progress bars. Defaults to True.

True
extra_params dict[str, object] | None

Optional dict of extra generator parameters (e.g. {"vmf_concentration": 100.0}). Passed to :func:obtain_data_instance on cache miss. Defaults to None.

None
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Defaults to True. Set to False to skip metric computation when only winner distances are needed.

True

Returns: SimulationSeriesResult with attached :attr:config including all rules.

Source code in src/vote_simulation/simulation/simulation.py
def simulation_instance(
    gen_code: str,
    n_v: int,
    n_c: int,
    rule_codes: list[str],
    n_iteration: int = 1000,
    seed: int = 161,
    base_path: str = "data",
    reload: bool = False,
    show_progress: bool = True,
    *,
    extra_params: dict[str, object] | None = None,
    compute_metrics: bool = True,
) -> SimulationSeriesResult:
    """Run the workflow on a single (model, voters, candidates) instance.

    Each step receives a :class:`ResultConfig` so that the series
    automatically aggregates the simulation context.

    Cache logic:
    1. Checks for a cached result at ``<base_path>/results/<base_label>.parquet``
       (where base_label excludes rules).
    2. If found with matching step count and same base parameters:
       - If rules are identical: returns cached series (no recomputation).
       - If rules differ: loads cached series and applies new rules incrementally.
    3. If not found or stale: recomputes from scratch.

    Args:
        gen_code: Generative model code (list can be found in doc).
        n_v: Number of voters.
        n_c: Number of candidates.
        rule_codes: List of rule codes to apply.
        n_iteration: Number of iterations. Defaults to 1000.
        seed: Seed for reproducibility. Defaults to 161.
        base_path: Root folder for generated data. Defaults to ``"data"``.
        reload: Force re-computation (ignore cache). Defaults to False.
        show_progress: Whether to display progress bars. Defaults to True.
        extra_params: Optional dict of extra generator parameters (e.g.
            ``{"vmf_concentration": 100.0}``). Passed to
            :func:`obtain_data_instance` on cache miss. Defaults to ``None``.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Defaults to ``True``.  Set to ``False`` to skip
            metric computation when only winner distances are needed.
    Returns:
        SimulationSeriesResult with attached :attr:`config` including all rules.
    """
    # Build the base config (cache key, excludes rules)
    gen_code = gen_code.strip().upper()
    base_config = ResultConfig.single(
        gen_model=gen_code,
        n_voters=n_v,
        n_candidates=n_c,
        n_iterations=n_iteration,
    )

    # Pre-build rule builders once before any loop (mirrors simulation_from_config).
    # Unknown codes are warned once and skipped; avoids per-iteration exceptions,
    # error-message formatting (sorted string of 68+ codes), and queue.put() calls.
    valid_builders: list[tuple[str, Any]] = []
    for code in [r.strip().upper() for r in rule_codes]:
        try:
            valid_builders.append((code, get_rule_builder(code)))
        except ValueError:
            print(f"Warning: unknown rule code '{code}' — skipped.")
    valid_rule_codes = [code for code, _ in valid_builders]

    # full_config uses only valid rules so the cache key is accurate.
    full_config = ResultConfig.single(
        gen_model=gen_code,
        n_voters=n_v,
        n_candidates=n_c,
        n_iterations=n_iteration,
        rules_codes=valid_rule_codes,
    )

    # --- Cache check with metadata validation + partial-load support ---
    cache_path = Path(base_path) / "results" / f"{base_config.label}.parquet"
    meta_path = _series_cache_meta_path(cache_path)
    requested_meta = _build_series_cache_meta(
        seed=seed,
        extra_params=extra_params,
        compute_metrics=compute_metrics,
    )
    cache_meta_matches = False

    if not reload and cache_path.is_file():
        cached = SimulationSeriesResult()
        cached.load_from_file(str(cache_path))
        cached_meta = _read_series_cache_meta(meta_path)
        cache_meta_matches = cached_meta == requested_meta

        cached_rules = set(cached.config.rules_codes)
        requested_rules = set(valid_rule_codes)

        if cache_meta_matches and cached_rules == requested_rules:
            return cached
        elif cache_meta_matches and cached_rules < requested_rules:
            new_rules = sorted(requested_rules - cached_rules)
            cached.add_rules_to_steps(new_rules)
            cached.config = ResultConfig.single(
                gen_model=gen_code,
                n_voters=n_v,
                n_candidates=n_c,
                n_iterations=n_iteration,
                rules_codes=valid_rule_codes,
            )
            cache_path.parent.mkdir(parents=True, exist_ok=True)
            cached.save_to_file(str(cache_path))
            _write_series_cache_meta(meta_path, requested_meta)
            return cached

    # If metadata changed (seed / extra_params / compute_metrics), force a data
    # refresh to overwrite stale generated profiles and series cache consistently.
    data_reload = reload
    if not reload and cache_path.is_file() and not cache_meta_matches:
        data_reload = True

    series = SimulationSeriesResult()
    with tqdm(total=n_iteration, desc="Simulating", disable=not show_progress) as pbar:
        for it in range(n_iteration):
            di = obtain_data_instance(
                model=gen_code,
                n_v=n_v,
                n_c=n_c,
                iteration=it,
                seed=seed,
                base_path=base_path,
                extra_params=extra_params or {},
                reload=data_reload,
            )
            # Inline hot loop using pre-built builders (mirrors simulation_from_config).
            # Avoids per-iteration get_rule_builder() calls and exception overhead.
            profile = di.profile
            step = SimulationStepResult(data_source=di.file_path, config=base_config)
            for code, builder in valid_builders:
                try:
                    rule: RuleResult = builder(profile, None)
                    winners = rule.cowinners_
                    if compute_metrics:
                        try:
                            metrics = rule.compute_metrics()
                            step.add_method_result_with_metrics(code, winners, metrics)
                        except Exception:
                            step.add_method_result(code, winners)
                    else:
                        step.add_method_result(code, winners)
                except Exception as e:  # noqa: BLE001
                    print(f"Error applying rule '{code}': {e}")
                    step.add_method_result(code, [f"ERROR: {e}"])
            series.add_step(step)
            pbar.update(1)

    # Set the full config on the series (including rules)
    series.config = full_config

    # --- Persist for future cache hits ---
    cache_path.parent.mkdir(parents=True, exist_ok=True)
    series.save_to_file(str(cache_path))
    _write_series_cache_meta(meta_path, requested_meta)
    return series

simulation_series_from_config(config_path, reload=False, *, compute_metrics=True)

Run simulation instances for every combination in the config.

Iterates over each (model, n_voters, n_candidates) triplet defined in the TOML configuration, delegates to :func:simulation_instance, and collects all resulting series into a :class:SimulationTotalResult.

Séquentiel — le travail est CPU-bound Python (svvamp) ; le GIL empêche toute parallélisation réelle via ThreadPoolExecutor. En mode UI (Streamlit), le tqdm externe est intercepté par _PatchedTqdm pour mettre à jour la barre de progression sans toucher à la hot loop.

Parameters:

Name Type Description Default
config_path str

Path to the TOML configuration file.

required
reload bool

Force re-computation (ignore cache). Defaults to False.

False
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Defaults to True.

True

Returns:

Name Type Description
A SimulationTotalResult

class:SimulationTotalResult containing one series per

SimulationTotalResult

(model, voters, candidates) combination.

Source code in src/vote_simulation/simulation/simulation.py
def simulation_series_from_config(
    config_path: str,
    reload: bool = False,
    *,
    compute_metrics: bool = True,
) -> SimulationTotalResult:
    """Run simulation instances for every combination in the config.

    Iterates over each ``(model, n_voters, n_candidates)`` triplet defined
    in the TOML configuration, delegates to :func:`simulation_instance`,
    and collects all resulting series into a :class:`SimulationTotalResult`.

    Séquentiel — le travail est CPU-bound Python (svvamp) ; le GIL empêche
    toute parallélisation réelle via ThreadPoolExecutor.
    En mode UI (Streamlit), le tqdm externe est intercepté par ``_PatchedTqdm``
    pour mettre à jour la barre de progression sans toucher à la hot loop.

    Args:
        config_path: Path to the TOML configuration file.
        reload: Force re-computation (ignore cache). Defaults to False.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Defaults to ``True``.

    Returns:
        A :class:`SimulationTotalResult` containing one series per
        ``(model, voters, candidates)`` combination.
    """
    config = load_simulation_config(config_path)
    _validate_generation_config(config)

    total_result = SimulationTotalResult()
    combos = [
        (model, config.generator_params.get(model, {}), n_v, n_c)
        for model in config.generative_models
        for n_v in (config.voters or [])
        for n_c in (config.candidates or [])
    ]
    n_combos = len(combos)

    with tqdm(total=n_combos, desc="Running simulation series") as pbar:
        for model, extra, n_v, n_c in combos:
            total_result.add_series(
                simulation_instance(
                    gen_code=model,
                    n_v=n_v,
                    n_c=n_c,
                    rule_codes=config.rule_codes,
                    n_iteration=config.iterations,
                    seed=config.seed,
                    base_path=config.output_base_path,
                    reload=reload,
                    show_progress=False,
                    extra_params=extra,
                    compute_metrics=compute_metrics,
                )
            )
            pbar.update(1)

    print(f"Completed {total_result.series_count} simulation series.")
    return total_result

simulation_series_from_config_2(config_path, reload=False, *, compute_metrics=True)

Run simulation instances for every combination in the config.

Iterates over each (model, n_voters, n_candidates) triplet defined in the TOML configuration, delegates to :func:simulation_instance, and collects all resulting series into a :class:SimulationTotalResult.

Parameters:

Name Type Description Default
config_path str

Path to the TOML configuration file.

required
reload bool

Force re-computation (ignore cache). Defaults to False.

False
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Defaults to True.

True

Returns:

Name Type Description
A SimulationTotalResult

class:SimulationTotalResult containing one series per

SimulationTotalResult

(model, voters, candidates) combination.

Source code in src/vote_simulation/simulation/simulation.py
def simulation_series_from_config_2(
    config_path: str,
    reload: bool = False,
    *,
    compute_metrics: bool = True,
) -> SimulationTotalResult:
    """Run simulation instances for every combination in the config.

    Iterates over each ``(model, n_voters, n_candidates)`` triplet defined
    in the TOML configuration, delegates to :func:`simulation_instance`,
    and collects all resulting series into a :class:`SimulationTotalResult`.

    Args:
        config_path: Path to the TOML configuration file.
        reload: Force re-computation (ignore cache). Defaults to False.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Defaults to ``True``.

    Returns:
        A :class:`SimulationTotalResult` containing one series per
        ``(model, voters, candidates)`` combination.
    """
    config = load_simulation_config(config_path)
    _validate_generation_config(config)

    total_result = SimulationTotalResult()
    n_combos = len(config.generative_models) * len(config.voters or []) * len(config.candidates or [])
    with tqdm(total=n_combos, desc="Running simulation series") as pbar:
        for model in config.generative_models:
            for n_v in config.voters or []:
                for n_c in config.candidates or []:
                    series = simulation_instance(
                        gen_code=model,
                        n_v=n_v,
                        n_c=n_c,
                        rule_codes=config.rule_codes,
                        n_iteration=config.iterations,
                        seed=config.seed,
                        base_path=config.output_base_path,
                        reload=reload,
                        show_progress=False,  # inner progress is handled by simulation_instance
                        extra_params=config.generator_params.get(model, {}),
                        compute_metrics=compute_metrics,
                    )
                    total_result.add_series(series)
                    pbar.update(1)

    print(f"Completed {total_result.series_count} simulation series.")
    return total_result

simulation_step(profile, rule_codes, config=None, *, compute_metrics=True)

Run a single profile through all rules and return a :class:SimulationStepResult.

Parameters:

Name Type Description Default
profile Profile

The profile data to run the rules on.

required
candidates

List of candidate names.

required
rule_codes list[str]

List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]).

required
config ResultConfig | None

Optional :class:ResultConfig attached to the step.

None
compute_metrics bool

Whether to compute :class:~vote_simulation.models.rules.WinnerMetrics for each rule. Defaults to True.

True
Source code in src/vote_simulation/simulation/simulation.py
def simulation_step(
    profile: Profile,
    rule_codes: list[str],
    config: ResultConfig | None = None,
    *,
    compute_metrics: bool = True,
) -> SimulationStepResult:
    """Run a single profile through all rules and return a :class:`SimulationStepResult`.

    Args:
        profile: The profile data to run the rules on.
        candidates: List of candidate names.
        rule_codes: List of rule codes to apply (e.g. ["RV", "MJ", "AP_T"]).
        config: Optional :class:`ResultConfig` attached to the step.
        compute_metrics: Whether to compute :class:`~vote_simulation.models.rules.WinnerMetrics`
            for each rule.  Defaults to ``True``.
    """
    step_config = config or ResultConfig()

    data = DataInstance.from_profile(profile)

    step_result = run_rules_on_instance(data, rule_codes, config=step_config, compute_metrics=compute_metrics)

    return step_result

Configuration

Configuration loading for vote simulations.

SimulationConfig dataclass

Validated simulation configuration.

Source code in src/vote_simulation/simulation/configuration.py
@dataclass(slots=True)
class SimulationConfig:
    """Validated simulation configuration."""

    rule_codes: list[str]
    candidates: list[int] | None = None
    voters: list[int] | None = None
    iterations: int = 1
    seed: int = 0
    generative_models: list[str] = field(default_factory=list)  # e.g. ["UNI", "IC"]
    output_base_path: str = "data"  # root folder for gen/ and sim_result/
    input_folder_path: str | None = None  # folder with pre-existing vote files for batch mode
    generator_params: dict[str, dict[str, object]] = field(default_factory=dict)  # per-model extra params

load_simulation_config(config_path=DEFAULT_CONFIG_PATH)

Load and validate a simulation config file.

Source code in src/vote_simulation/simulation/configuration.py
def load_simulation_config(config_path: str | Path = DEFAULT_CONFIG_PATH) -> SimulationConfig:
    """Load and validate a simulation config file."""
    path = Path(config_path)

    # Check path
    if not path.is_file():
        raise ValueError(f"Configuration file not found: {path}")

    with path.open("rb") as handle:
        payload = tomllib.load(handle)

    simulation = payload.get("simulation")
    # simulation section must exist and be a dict
    if not isinstance(simulation, dict):
        raise ValueError("Invalid configuration: missing [simulation] section")

    # Check validity of rules codes
    rule_codes = simulation.get("rule_codes")
    if not isinstance(rule_codes, list) or not rule_codes:
        raise ValueError("Invalid configuration: simulation.rule_codes must be a non-empty list")

    normalized_rule_codes = [str(code).strip().upper() for code in rule_codes if str(code).strip()]
    if not normalized_rule_codes:
        raise ValueError("Invalid configuration: simulation.rule_codes cannot be empty")

    # Check validity of candidates, voters, iterations
    candidates = simulation.get("candidates")
    if candidates is not None:
        if not isinstance(candidates, list) or not candidates:
            raise ValueError("Invalid configuration: simulation.candidates must be a non-empty list")
        if not all(isinstance(c, int) and c > 0 for c in candidates):
            raise ValueError("Invalid configuration: all simulation.candidates must be positive integers")

    voters = simulation.get("voters")
    if voters is not None:
        if not isinstance(voters, list) or not voters:
            raise ValueError("Invalid configuration: simulation.voters must be a non-empty list")
        if not all(isinstance(v, int) and v > 0 for v in voters):
            raise ValueError("Invalid configuration: all simulation.voters must be positive integers")

    iterations = simulation.get("iterations", 1)
    if not isinstance(iterations, int) or iterations <= 0:
        raise ValueError("Invalid configuration: simulation.iterations must be a positive integer")

    # Check validity of seed
    seed = simulation.get("seed", 0)
    if not isinstance(seed, int) or seed < 0:
        raise ValueError("Invalid configuration: simulation.seed must be a non-negative integer")

    # --- Generative models ---
    raw_gen_models = simulation.get("generative_models")
    generative_models: list[str] = []
    if raw_gen_models is not None:
        if not isinstance(raw_gen_models, list):
            raise ValueError("Invalid configuration: simulation.generative_models must be a list")
        generative_models = [str(m).strip().upper() for m in raw_gen_models if str(m).strip()]

    # --- Output base path ---
    # Relative paths are resolved from the current working directory (the project root),
    # consistent with how the UI and write_temp_toml resolve them.
    output_base_path = simulation.get("output_base_path", "data")
    if not isinstance(output_base_path, str) or not output_base_path.strip():
        output_base_path = "data"
    if not Path(output_base_path).is_absolute():
        output_base_path = str(Path(output_base_path).resolve())

    # --- Per-model generator params (optional TOML sub-tables) ---
    generator_params: dict[str, dict[str, object]] = {}
    gen_params_section = payload.get("generator_params")
    if isinstance(gen_params_section, dict):
        for model_key, params in gen_params_section.items():
            if isinstance(params, dict):
                generator_params[model_key.strip().upper()] = dict(params)

    # --- Input folder path (optional, for batch mode) ---
    raw_input_folder = simulation.get("input_folder_path")
    input_folder_path: str | None = None
    if raw_input_folder is not None:
        input_folder_path = str(raw_input_folder).strip() or None
        if input_folder_path and not Path(input_folder_path).is_absolute():
            input_folder_path = str(Path(input_folder_path).resolve())

    return SimulationConfig(
        rule_codes=normalized_rule_codes,
        candidates=candidates,
        voters=voters,
        iterations=iterations,
        seed=seed,
        generative_models=generative_models,
        output_base_path=output_base_path,
        input_folder_path=input_folder_path,
        generator_params=generator_params,
    )

Rule registry

Rule index for mapping short codes to svvamp rule factories.

RuleResult

Bases: Protocol

Protocol for rule results that have been post-processed to include co-winners.

Source code in src/vote_simulation/models/rules/registry.py
class RuleResult(Protocol):
    """Protocol for rule results that have been post-processed to include co-winners."""

    cowinners_: list[str]

    def compute_metrics(self) -> Any: ...

get_all_rules_codes()

Return a list of all registered rule codes.

Source code in src/vote_simulation/models/rules/registry.py
def get_all_rules_codes() -> list[str]:
    """Return a list of all registered rule codes."""
    return sorted(_RULE_BUILDERS.keys())

get_rule_builder(code)

Return rule builder from code

Parameters:

Name Type Description Default
code str

rule encoding (detailed index in documentation)

required

Raises:

Type Description
ValueError

if wrong code

Returns:

Name Type Description
RuleBuilder RuleBuilder

rule applied

Source code in src/vote_simulation/models/rules/registry.py
def get_rule_builder(code: str) -> RuleBuilder:
    """Return rule builder from code

    Args:
        code (str): rule encoding (detailed index in documentation)

    Raises:
        ValueError: if wrong code

    Returns:
        RuleBuilder: rule applied
    """
    normalized_code = code.strip().upper()
    try:
        return _RULE_BUILDERS[normalized_code]
    except KeyError as error:
        available = ", ".join(sorted(_RULE_BUILDERS))
        raise ValueError(f"Unknown rule code: '{code}'. Available codes: {available}") from error

make_rule_builder(rule_factory)

Create a public RuleBuilder from a Profile -> rule result factory.

This helper is intended for external users who want to register custom rules while reusing the registry's profile conversion and co-winner post-processing.

Parameters:

Name Type Description Default
rule_factory Callable[[Profile], Any]

Callable that takes a svvamp.Profile and returns a rule result.

required

Returns:

Type Description
RuleBuilder

A RuleBuilder that can be registered in the registry.

Source code in src/vote_simulation/models/rules/registry.py
def make_rule_builder(rule_factory: Callable[[Profile], Any]) -> RuleBuilder:
    """Create a public `RuleBuilder` from a `Profile -> rule result` factory.

    This helper is intended for external users who want to register custom rules
    while reusing the registry's profile conversion and co-winner post-processing.

    Args:
        rule_factory: Callable that takes a `svvamp.Profile` and returns a rule result.

    Returns:
        A `RuleBuilder` that can be registered in the registry.
    """
    return _build_with_rule(rule_factory)

register_rule(code, builder)

Register a rule builder under a short code.

Source code in src/vote_simulation/models/rules/registry.py
def register_rule(code: str, builder: RuleBuilder) -> None:
    """Register a rule builder under a short code."""
    normalized_code = code.strip().upper()
    _RULE_BUILDERS[normalized_code] = builder

Generator registry

Generator registry mapping short codes to svvamp GeneratorProfile factories.

Usage examples:

> from vote_simulation.models.data_generation.generator_registry import get_generator_builder
> builder = get_generator_builder("UNI")
> profile = builder(n_v=100, n_c=5, seed=42)

GeneratorBuilder = Callable[..., Profile] module-attribute

Signature: (n_v, n_c, seed=0, **extra) -> svvamp.Profile

get_generator_builder(code)

Return the generator builder for the given code.

Raises:

Type Description
ValueError

If code is not registered.

Source code in src/vote_simulation/models/data_generation/generator_registry.py
def get_generator_builder(code: str) -> GeneratorBuilder:
    """Return the generator builder for the given code.

    Raises:
        ValueError: If code is not registered.
    """
    normalized = code.strip().upper()
    try:
        return _GENERATOR_BUILDERS[normalized]
    except KeyError as exc:
        available = ", ".join(sorted(_GENERATOR_BUILDERS))
        raise ValueError(f"Unknown generator code: '{code}'. Available: {available}") from exc

list_generator_codes()

Return sorted list of all registered generator codes.

Source code in src/vote_simulation/models/data_generation/generator_registry.py
def list_generator_codes() -> list[str]:
    """Return sorted list of all registered generator codes."""
    return sorted(_GENERATOR_BUILDERS)

make_generator_builder(generator_factory, **default_kwargs)

Create a public GeneratorBuilder from a generator factory.

This helper is intended for external users who want to register custom generators while reusing the registry's seeding and relabeling logic.

Parameters:

Name Type Description Default
generator_factory Callable[..., Any]

Callable (n_v, n_c, **kw) -> svvamp generator that, when called, returns an svvamp generator object.

required
**default_kwargs object

Default keyword arguments forwarded to the factory.

{}

Returns:

Type Description
GeneratorBuilder

A GeneratorBuilder that can be registered in the registry.

Example::

from svvamp import GeneratorProfileEuclideanBox
builder = make_generator_builder(
    GeneratorProfileEuclideanBox,
    box_dimensions=[1.0, 1.0, 1.0],
)
register_generator("MY_EUCLID_3D", builder)
Source code in src/vote_simulation/models/data_generation/generator_registry.py
def make_generator_builder(
    generator_factory: Callable[..., Any],
    **default_kwargs: object,
) -> GeneratorBuilder:
    """Create a public `GeneratorBuilder` from a generator factory.

    This helper is intended for external users who want to register custom
    generators while reusing the registry's seeding and relabeling logic.

    Args:
        generator_factory: Callable ``(n_v, n_c, **kw) -> svvamp generator``
            that, when called, returns an svvamp generator object.
        **default_kwargs: Default keyword arguments forwarded to the factory.

    Returns:
        A `GeneratorBuilder` that can be registered in the registry.

    Example::

        from svvamp import GeneratorProfileEuclideanBox
        builder = make_generator_builder(
            GeneratorProfileEuclideanBox,
            box_dimensions=[1.0, 1.0, 1.0],
        )
        register_generator("MY_EUCLID_3D", builder)
    """

    def _builder(
        n_v: int,
        n_c: int,
        *,
        seed: int = 0,
        iteration: int = 0,
        **kw: object,
    ) -> Profile:
        _seed(seed, iteration)
        merged = {**default_kwargs, **kw}
        gen = generator_factory(n_v=n_v, n_c=n_c, **merged)
        return _relabel(gen(), n_c)

    return _builder

register_generator(code, builder)

Register a generator builder under a short code.

Parameters:

Name Type Description Default
code str

Short code - case-insensitive, will be normalized.

required
builder GeneratorBuilder

Callable (n_v, n_c, seed=0, **extra) -> Profile.

required
Source code in src/vote_simulation/models/data_generation/generator_registry.py
def register_generator(code: str, builder: GeneratorBuilder) -> None:
    """Register a generator builder under a short code.

    Args:
        code: Short code - case-insensitive, will be normalized.
        builder: Callable ``(n_v, n_c, seed=0, **extra) -> Profile``.
    """
    _GENERATOR_BUILDERS[code.strip().upper()] = builder

Data instance

Load or generate election profiles and persist them.

DataInstance

Encapsulates an election profile (utility matrix + candidate labels).

`DataInstance`` can be created in three ways:

From an existing file (CSV or Parquet)::

   di = DataInstance("path/to/data.csv")

From a generator (wraps svvamp GeneratorProfile*)::

   di = DataInstance.from_generator(
       model_code="UNI", n_v=101, n_c=5, seed=42, iteration=0
   )

From a raw Profile::

   di = DataInstance.from_profile(profile)
Source code in src/vote_simulation/models/data_generation/data_instance.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class DataInstance:
    """Encapsulates an election profile (utility matrix + candidate labels).

    `DataInstance`` can be created in three ways:

     **From an existing file** (CSV or Parquet)::

           di = DataInstance("path/to/data.csv")

     **From a generator** (wraps svvamp ``GeneratorProfile*``)::

           di = DataInstance.from_generator(
               model_code="UNI", n_v=101, n_c=5, seed=42, iteration=0
           )

     **From a raw Profile**::

           di = DataInstance.from_profile(profile)
    """

    def __init__(self, file_path: str):
        try:
            self.candidates, raw = self.get_data(file_path)
            self.data, self._orig_min, self._orig_max = self._normalize(raw)
            self.profile = self.build_profile(self.candidates, self.data)
            self.file_path = file_path
            self.model = None
            self.model_code: str = ""
        except Exception as e:
            raise ValueError(f"Error initializing DataInstance: {e}") from e

    # -------------------------------------------------- normalization helpers

    @staticmethod
    def _normalize(data: np.ndarray) -> tuple[np.ndarray, float, float]:
        """Min-max normalize a utility matrix to [0, 1].

        The transformation is a global affine map that preserves every
        relative difference in the original data, making it fully
        reversible via :meth:`denormalize`.

        Args:
            data: 2-D array of shape ``(n_voters, n_candidates)``.

        Returns:
            A tuple ``(normalized, orig_min, orig_max)``.
        """
        dmin: float = float(data.min())
        dmax: float = float(data.max())
        spread = dmax - dmin
        if spread > 0.0:
            normalized = (data - dmin) * (1.0 / spread)  # one division
        else:
            # all utilities identical → perfect indifference
            normalized = np.full_like(data, 0.5)
        return normalized, dmin, dmax

    def denormalize(self) -> np.ndarray:
        """Restore the original (pre-normalization) utility values.

        Returns:
            2-D array with the same shape as ``self.data`` containing
            the utilities on their original scale.
        """
        spread = self._orig_max - self._orig_min
        if spread > 0.0:
            return self.data * spread + self._orig_min
        return np.full_like(self.data, self._orig_min)

    # --------------------------------------------------------- class methods

    @classmethod
    def from_generator(
        cls,
        model_code: str,
        n_v: int,
        n_c: int,
        *,
        seed: int = 0,
        iteration: int = 0,
        **extra_params: object,
    ) -> DataInstance:
        """Generate an election profile using a registered generator.

        Args:
            model_code: Registered generator short code (e.g. ``"UNI"``).
            n_v: Number of voters.
            n_c: Number of candidates.
            seed: Base random seed for reproducibility.
            iteration: Iteration index (added to *seed*).
            **extra_params: Model-specific keyword arguments forwarded to
                the generator builder.

        Returns:
            A new ``DataInstance`` whose profile was generated in-memory.
        """
        from vote_simulation.models.data_generation.from_r_registry import register_r_generators
        from vote_simulation.models.data_generation.generator_registry import (
            get_generator_builder,
        )

        register_r_generators()
        builder = get_generator_builder(model_code)
        profile: Profile = builder(n_v, n_c, seed=seed, iteration=iteration, **extra_params)

        instance = object.__new__(cls)
        instance.candidates = np.asarray(profile.labels_candidates, dtype=str)
        raw = np.asarray(profile.preferences_ut, dtype=np.float64)
        instance.data, instance._orig_min, instance._orig_max = cls._normalize(raw)
        instance.profile = Profile(
            preferences_ut=instance.data,
            labels_candidates=profile.labels_candidates,
        )
        instance.file_path = ""  # not loaded from disk
        instance.model_code = model_code
        return instance

    @classmethod
    def from_profile(cls, profile: Profile, file_path: str = "") -> DataInstance:
        """Wrap an existing ``svvamp.Profile`` into a ``DataInstance``.

        Args:
            profile: An existing ``svvamp.Profile`` object.
            file_path: Optional file path associated with the profile.

        Returns:
            A new ``DataInstance`` wrapping the provided profile.
        """
        instance = object.__new__(cls)
        instance.candidates = np.asarray(profile.labels_candidates, dtype=str)
        raw = np.asarray(profile.preferences_ut, dtype=np.float64)
        instance.data, instance._orig_min, instance._orig_max = cls._normalize(raw)
        instance.profile = Profile(
            preferences_ut=instance.data,
            labels_candidates=profile.labels_candidates,
        )
        instance.file_path = file_path
        instance.model_code = ""
        return instance

    def get_csv(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
        """Load candidate labels and utility matrix from a CSV file.

        Args:
            file_path: Path to the CSV file.

        Returns:
            A tuple containing:
                - candidates: 1-D array of candidate names.
                - data: 2-D array of shape (n_voters, n_candidates) with utility values.
        """
        try:
            candidates_list: list[str] = []
            rows: list[list[float]] = []

            with open(file_path, encoding="utf-8", newline="") as fh:
                csv_reader = reader(fh)
                next(csv_reader, None)

                for row in csv_reader:
                    if len(row) < 2:
                        raise ValueError("CSV file must contain at least one data column.")
                    candidates_list.append(row[0].strip('"'))
                    rows.append([float(value) for value in row[1:]])

            if not rows:
                raise ValueError("CSV file must contain at least one row.")

            candidates = np.asarray(candidates_list, dtype=str)
            data = np.asarray(rows, dtype=np.float64).T  # rows = voters, columns = candidates

        except Exception as e:
            raise ValueError(f"Error reading the file : {e}") from e

        return candidates, data

    def get_parquet(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
        """Load candidate labels and utility matrix from a Parquet file.

        The Parquet file is expected to have one column per candidate
        (column name = candidate label) and one row per voter.

        Args:
            file_path: Path to the Parquet file.

        Returns:
            A tuple containing:
                - candidates: 1-D array of candidate names.
                - data: 2-D array of shape (n_voters, n_candidates) with utility values.
        """
        try:
            df = pd.read_parquet(file_path)
            if df.empty:
                raise ValueError("Parquet file is empty.")
            candidates = np.asarray(df.columns.tolist(), dtype=str)
            data = df.to_numpy(dtype=np.float64)  # (n_voters, n_candidates)
        except Exception as e:
            raise ValueError(f"Error reading parquet file: {e}") from e
        return candidates, data

    def get_data(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
        """Load data from a CSV or Parquet file.

        Args:
            file_path: Path to the data file.

        Returns:
            candidates: 1-D array of candidate names.
            data: 2-D array of shape ``(n_voters, n_candidates)``.
        """
        if not os.path.isfile(file_path):
            raise ValueError("Invalid file path. Please provide a valid file path.")

        if file_path.endswith(".csv"):
            return self.get_csv(file_path)

        if file_path.endswith(".parquet"):
            return self.get_parquet(file_path)

        raise ValueError("Unable to load data from provided file path.")

    # profile builder

    def build_profile(self, candidates: np.ndarray, data: np.ndarray) -> Profile:
        """Build a ``svvamp.Profile`` from candidate labels and utility matrix."""
        return Profile(preferences_ut=data, labels_candidates=candidates.tolist())

    def save_parquet(self, file_path: str) -> str:
        """Persist the utility matrix to a Parquet file.

        Creates parent directories if needed. The file contains one column
        per candidate and one row per voter.

        Args:
            file_path: Destination path (should end in ``.parquet``).

        Returns:
            The resolved absolute path of the written file.
        """
        path = Path(file_path)
        path.parent.mkdir(parents=True, exist_ok=True)
        df = pd.DataFrame(self.data, columns=self.candidates.tolist())
        df.to_parquet(str(path), index=False)
        return str(path.resolve())

    def save_csv(self, file_path: str) -> str:
        """Persist the utility matrix to a CSV file (same layout as input).

        Args:
            file_path: Destination path (should end in ``.csv``).

        Returns:
            The resolved absolute path of the written file.
        """
        path = Path(file_path)
        path.parent.mkdir(parents=True, exist_ok=True)
        df = pd.DataFrame(self.data, columns=self.candidates.tolist())
        df.to_csv(str(path), index=False)
        return str(path.resolve())

    @property
    def n_voters(self) -> int:
        """Number of voters in this instance."""
        return int(self.data.shape[0])

    @property
    def n_candidates(self) -> int:
        """Number of candidates in this instance."""
        return int(self.data.shape[1])

    @staticmethod
    def _cluster_order(matrix: np.ndarray, axis: int, method: str = "average", metric: str = "euclidean") -> np.ndarray:
        """Return the reordered indices of rows or columns via hierarchical clustering.

        Args:
            matrix: 2-D array ``(n_voters, n_candidates)``.
            axis: 0 = cluster rows (voters), 1 = cluster columns (candidates).
            method: Linkage method passed to ``scipy.cluster.hierarchy.linkage``.
            metric: Distance metric passed to ``scipy.cluster.hierarchy.linkage``.

        Returns:
            1-D array of reordered indices.
        """
        n_items = matrix.shape[axis]
        if n_items <= 1 or not _HAS_SCIPY:
            return np.arange(n_items)

        # For column clustering, transpose so rows = candidates
        data = matrix.T if axis == 1 else matrix
        lnk = linkage(data, method=method, metric=metric)
        return leaves_list(lnk)

    def plot_heatmap(
        self,
        *,
        cluster_columns: bool = False,
        cluster_rows: bool = True,
        method: str = "average",
        metric: str = "euclidean",
        cmap: str = "viridis",
        title: str | None = None,
        save_path: str | None = None,
        show: bool = True,
    ) -> dict:
        """Visualize the utility matrix as a heatmap with optional hierarchical clustering.

        Values are already in [0, 1]. Columns (candidates) are reordered by
        hierarchical clustering by default so that similar preference profiles
        appear next to each other.

        Args:
            cluster_columns: Reorder candidates by hierarchical clustering (default True).
            cluster_rows: Reorder voters by hierarchical clustering (default False).
            method: Linkage method (``"average"``, ``"ward"``, ``"complete"``, …).
            metric: Distance metric (``"euclidean"``, ``"cosine"``, …).
            cmap: Matplotlib colormap name.
            title: Figure title. Defaults to model code if available.
            save_path: If provided, save the figure to this path.
            show: Whether to call ``plt.show()``.

        Returns:
            Dict with keys ``ordered_matrix``, ``row_order``, ``col_order``.

        Raises:
            ImportError: If matplotlib is not installed.
        """
        if not _HAS_MPL:
            raise ImportError("matplotlib is required for plot_heatmap(). Install it with: pip install matplotlib")

        if not _HAS_SCIPY and (cluster_columns or cluster_rows):
            print("[Warning] scipy not found. Clustering disabled. Install with: pip install scipy")

        matrix = self.data  # already in [0, 1]

        row_order: np.ndarray = (
            self._cluster_order(matrix, axis=0, method=method, metric=metric)
            if cluster_rows
            else np.arange(matrix.shape[0])
        )
        col_order: np.ndarray = (
            self._cluster_order(matrix, axis=1, method=method, metric=metric)
            if cluster_columns
            else np.arange(matrix.shape[1])
        )

        ordered = matrix[row_order][:, col_order]
        ordered_candidates = self.candidates[col_order]

        # --- figure sizing
        fig_w = max(8, ordered.shape[1] * 0.5)
        fig_h = max(5, ordered.shape[0] * 0.08)

        fig, ax = plt.subplots(figsize=(fig_w, fig_h))

        im = ax.imshow(
            ordered,
            aspect="auto",
            interpolation="nearest",
            cmap=cmap,
            vmin=0.0,
            vmax=1.0,
        )

        # --- axes labels
        if title is None:
            title = f"Profiles heatmap — {self.model_code}" if self.model_code else "Profiles heatmap"

        xlabel = "Candidates"
        if cluster_columns and _HAS_SCIPY:
            xlabel += " (clustered)"
        ylabel = "Voters"
        if cluster_rows and _HAS_SCIPY:
            ylabel += " (clustered)"

        ax.set_title(title, fontsize=14, fontweight="bold")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

        # candidate labels on x-axis (readable even with many candidates)
        ax.set_xticks(np.arange(len(ordered_candidates)))
        ax.set_xticklabels(ordered_candidates, rotation=45, ha="right", fontsize=8)

        # hide individual voter ticks when there are many
        if ordered.shape[0] <= 30:
            ax.set_yticks(np.arange(ordered.shape[0]))
            ax.set_yticklabels(row_order, fontsize=7)
        else:
            ax.set_yticks([])

        plt.colorbar(im, ax=ax, label="Normalized utility [0, 1]")
        plt.tight_layout()

        if save_path:
            fig.savefig(save_path, dpi=200, bbox_inches="tight")
            print(f"Figure saved to: {save_path}")

        if show:
            plt.show()

        return {
            "ordered_matrix": ordered,
            "row_order": row_order,
            "col_order": col_order,
        }

n_candidates property

Number of candidates in this instance.

n_voters property

Number of voters in this instance.

build_profile(candidates, data)

Build a svvamp.Profile from candidate labels and utility matrix.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def build_profile(self, candidates: np.ndarray, data: np.ndarray) -> Profile:
    """Build a ``svvamp.Profile`` from candidate labels and utility matrix."""
    return Profile(preferences_ut=data, labels_candidates=candidates.tolist())

denormalize()

Restore the original (pre-normalization) utility values.

Returns:

Type Description
ndarray

2-D array with the same shape as self.data containing

ndarray

the utilities on their original scale.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def denormalize(self) -> np.ndarray:
    """Restore the original (pre-normalization) utility values.

    Returns:
        2-D array with the same shape as ``self.data`` containing
        the utilities on their original scale.
    """
    spread = self._orig_max - self._orig_min
    if spread > 0.0:
        return self.data * spread + self._orig_min
    return np.full_like(self.data, self._orig_min)

from_generator(model_code, n_v, n_c, *, seed=0, iteration=0, **extra_params) classmethod

Generate an election profile using a registered generator.

Parameters:

Name Type Description Default
model_code str

Registered generator short code (e.g. "UNI").

required
n_v int

Number of voters.

required
n_c int

Number of candidates.

required
seed int

Base random seed for reproducibility.

0
iteration int

Iteration index (added to seed).

0
**extra_params object

Model-specific keyword arguments forwarded to the generator builder.

{}

Returns:

Type Description
DataInstance

A new DataInstance whose profile was generated in-memory.

Source code in src/vote_simulation/models/data_generation/data_instance.py
@classmethod
def from_generator(
    cls,
    model_code: str,
    n_v: int,
    n_c: int,
    *,
    seed: int = 0,
    iteration: int = 0,
    **extra_params: object,
) -> DataInstance:
    """Generate an election profile using a registered generator.

    Args:
        model_code: Registered generator short code (e.g. ``"UNI"``).
        n_v: Number of voters.
        n_c: Number of candidates.
        seed: Base random seed for reproducibility.
        iteration: Iteration index (added to *seed*).
        **extra_params: Model-specific keyword arguments forwarded to
            the generator builder.

    Returns:
        A new ``DataInstance`` whose profile was generated in-memory.
    """
    from vote_simulation.models.data_generation.from_r_registry import register_r_generators
    from vote_simulation.models.data_generation.generator_registry import (
        get_generator_builder,
    )

    register_r_generators()
    builder = get_generator_builder(model_code)
    profile: Profile = builder(n_v, n_c, seed=seed, iteration=iteration, **extra_params)

    instance = object.__new__(cls)
    instance.candidates = np.asarray(profile.labels_candidates, dtype=str)
    raw = np.asarray(profile.preferences_ut, dtype=np.float64)
    instance.data, instance._orig_min, instance._orig_max = cls._normalize(raw)
    instance.profile = Profile(
        preferences_ut=instance.data,
        labels_candidates=profile.labels_candidates,
    )
    instance.file_path = ""  # not loaded from disk
    instance.model_code = model_code
    return instance

from_profile(profile, file_path='') classmethod

Wrap an existing svvamp.Profile into a DataInstance.

Parameters:

Name Type Description Default
profile Profile

An existing svvamp.Profile object.

required
file_path str

Optional file path associated with the profile.

''

Returns:

Type Description
DataInstance

A new DataInstance wrapping the provided profile.

Source code in src/vote_simulation/models/data_generation/data_instance.py
@classmethod
def from_profile(cls, profile: Profile, file_path: str = "") -> DataInstance:
    """Wrap an existing ``svvamp.Profile`` into a ``DataInstance``.

    Args:
        profile: An existing ``svvamp.Profile`` object.
        file_path: Optional file path associated with the profile.

    Returns:
        A new ``DataInstance`` wrapping the provided profile.
    """
    instance = object.__new__(cls)
    instance.candidates = np.asarray(profile.labels_candidates, dtype=str)
    raw = np.asarray(profile.preferences_ut, dtype=np.float64)
    instance.data, instance._orig_min, instance._orig_max = cls._normalize(raw)
    instance.profile = Profile(
        preferences_ut=instance.data,
        labels_candidates=profile.labels_candidates,
    )
    instance.file_path = file_path
    instance.model_code = ""
    return instance

get_csv(file_path)

Load candidate labels and utility matrix from a CSV file.

Parameters:

Name Type Description Default
file_path str

Path to the CSV file.

required

Returns:

Type Description
tuple[ndarray, ndarray]

A tuple containing: - candidates: 1-D array of candidate names. - data: 2-D array of shape (n_voters, n_candidates) with utility values.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def get_csv(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
    """Load candidate labels and utility matrix from a CSV file.

    Args:
        file_path: Path to the CSV file.

    Returns:
        A tuple containing:
            - candidates: 1-D array of candidate names.
            - data: 2-D array of shape (n_voters, n_candidates) with utility values.
    """
    try:
        candidates_list: list[str] = []
        rows: list[list[float]] = []

        with open(file_path, encoding="utf-8", newline="") as fh:
            csv_reader = reader(fh)
            next(csv_reader, None)

            for row in csv_reader:
                if len(row) < 2:
                    raise ValueError("CSV file must contain at least one data column.")
                candidates_list.append(row[0].strip('"'))
                rows.append([float(value) for value in row[1:]])

        if not rows:
            raise ValueError("CSV file must contain at least one row.")

        candidates = np.asarray(candidates_list, dtype=str)
        data = np.asarray(rows, dtype=np.float64).T  # rows = voters, columns = candidates

    except Exception as e:
        raise ValueError(f"Error reading the file : {e}") from e

    return candidates, data

get_data(file_path)

Load data from a CSV or Parquet file.

Parameters:

Name Type Description Default
file_path str

Path to the data file.

required

Returns:

Name Type Description
candidates ndarray

1-D array of candidate names.

data ndarray

2-D array of shape (n_voters, n_candidates).

Source code in src/vote_simulation/models/data_generation/data_instance.py
def get_data(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
    """Load data from a CSV or Parquet file.

    Args:
        file_path: Path to the data file.

    Returns:
        candidates: 1-D array of candidate names.
        data: 2-D array of shape ``(n_voters, n_candidates)``.
    """
    if not os.path.isfile(file_path):
        raise ValueError("Invalid file path. Please provide a valid file path.")

    if file_path.endswith(".csv"):
        return self.get_csv(file_path)

    if file_path.endswith(".parquet"):
        return self.get_parquet(file_path)

    raise ValueError("Unable to load data from provided file path.")

get_parquet(file_path)

Load candidate labels and utility matrix from a Parquet file.

The Parquet file is expected to have one column per candidate (column name = candidate label) and one row per voter.

Parameters:

Name Type Description Default
file_path str

Path to the Parquet file.

required

Returns:

Type Description
tuple[ndarray, ndarray]

A tuple containing: - candidates: 1-D array of candidate names. - data: 2-D array of shape (n_voters, n_candidates) with utility values.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def get_parquet(self, file_path: str) -> tuple[np.ndarray, np.ndarray]:
    """Load candidate labels and utility matrix from a Parquet file.

    The Parquet file is expected to have one column per candidate
    (column name = candidate label) and one row per voter.

    Args:
        file_path: Path to the Parquet file.

    Returns:
        A tuple containing:
            - candidates: 1-D array of candidate names.
            - data: 2-D array of shape (n_voters, n_candidates) with utility values.
    """
    try:
        df = pd.read_parquet(file_path)
        if df.empty:
            raise ValueError("Parquet file is empty.")
        candidates = np.asarray(df.columns.tolist(), dtype=str)
        data = df.to_numpy(dtype=np.float64)  # (n_voters, n_candidates)
    except Exception as e:
        raise ValueError(f"Error reading parquet file: {e}") from e
    return candidates, data

plot_heatmap(*, cluster_columns=False, cluster_rows=True, method='average', metric='euclidean', cmap='viridis', title=None, save_path=None, show=True)

Visualize the utility matrix as a heatmap with optional hierarchical clustering.

Values are already in [0, 1]. Columns (candidates) are reordered by hierarchical clustering by default so that similar preference profiles appear next to each other.

Parameters:

Name Type Description Default
cluster_columns bool

Reorder candidates by hierarchical clustering (default True).

False
cluster_rows bool

Reorder voters by hierarchical clustering (default False).

True
method str

Linkage method ("average", "ward", "complete", …).

'average'
metric str

Distance metric ("euclidean", "cosine", …).

'euclidean'
cmap str

Matplotlib colormap name.

'viridis'
title str | None

Figure title. Defaults to model code if available.

None
save_path str | None

If provided, save the figure to this path.

None
show bool

Whether to call plt.show().

True

Returns:

Type Description
dict

Dict with keys ordered_matrix, row_order, col_order.

Raises:

Type Description
ImportError

If matplotlib is not installed.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def plot_heatmap(
    self,
    *,
    cluster_columns: bool = False,
    cluster_rows: bool = True,
    method: str = "average",
    metric: str = "euclidean",
    cmap: str = "viridis",
    title: str | None = None,
    save_path: str | None = None,
    show: bool = True,
) -> dict:
    """Visualize the utility matrix as a heatmap with optional hierarchical clustering.

    Values are already in [0, 1]. Columns (candidates) are reordered by
    hierarchical clustering by default so that similar preference profiles
    appear next to each other.

    Args:
        cluster_columns: Reorder candidates by hierarchical clustering (default True).
        cluster_rows: Reorder voters by hierarchical clustering (default False).
        method: Linkage method (``"average"``, ``"ward"``, ``"complete"``, …).
        metric: Distance metric (``"euclidean"``, ``"cosine"``, …).
        cmap: Matplotlib colormap name.
        title: Figure title. Defaults to model code if available.
        save_path: If provided, save the figure to this path.
        show: Whether to call ``plt.show()``.

    Returns:
        Dict with keys ``ordered_matrix``, ``row_order``, ``col_order``.

    Raises:
        ImportError: If matplotlib is not installed.
    """
    if not _HAS_MPL:
        raise ImportError("matplotlib is required for plot_heatmap(). Install it with: pip install matplotlib")

    if not _HAS_SCIPY and (cluster_columns or cluster_rows):
        print("[Warning] scipy not found. Clustering disabled. Install with: pip install scipy")

    matrix = self.data  # already in [0, 1]

    row_order: np.ndarray = (
        self._cluster_order(matrix, axis=0, method=method, metric=metric)
        if cluster_rows
        else np.arange(matrix.shape[0])
    )
    col_order: np.ndarray = (
        self._cluster_order(matrix, axis=1, method=method, metric=metric)
        if cluster_columns
        else np.arange(matrix.shape[1])
    )

    ordered = matrix[row_order][:, col_order]
    ordered_candidates = self.candidates[col_order]

    # --- figure sizing
    fig_w = max(8, ordered.shape[1] * 0.5)
    fig_h = max(5, ordered.shape[0] * 0.08)

    fig, ax = plt.subplots(figsize=(fig_w, fig_h))

    im = ax.imshow(
        ordered,
        aspect="auto",
        interpolation="nearest",
        cmap=cmap,
        vmin=0.0,
        vmax=1.0,
    )

    # --- axes labels
    if title is None:
        title = f"Profiles heatmap — {self.model_code}" if self.model_code else "Profiles heatmap"

    xlabel = "Candidates"
    if cluster_columns and _HAS_SCIPY:
        xlabel += " (clustered)"
    ylabel = "Voters"
    if cluster_rows and _HAS_SCIPY:
        ylabel += " (clustered)"

    ax.set_title(title, fontsize=14, fontweight="bold")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    # candidate labels on x-axis (readable even with many candidates)
    ax.set_xticks(np.arange(len(ordered_candidates)))
    ax.set_xticklabels(ordered_candidates, rotation=45, ha="right", fontsize=8)

    # hide individual voter ticks when there are many
    if ordered.shape[0] <= 30:
        ax.set_yticks(np.arange(ordered.shape[0]))
        ax.set_yticklabels(row_order, fontsize=7)
    else:
        ax.set_yticks([])

    plt.colorbar(im, ax=ax, label="Normalized utility [0, 1]")
    plt.tight_layout()

    if save_path:
        fig.savefig(save_path, dpi=200, bbox_inches="tight")
        print(f"Figure saved to: {save_path}")

    if show:
        plt.show()

    return {
        "ordered_matrix": ordered,
        "row_order": row_order,
        "col_order": col_order,
    }

save_csv(file_path)

Persist the utility matrix to a CSV file (same layout as input).

Parameters:

Name Type Description Default
file_path str

Destination path (should end in .csv).

required

Returns:

Type Description
str

The resolved absolute path of the written file.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def save_csv(self, file_path: str) -> str:
    """Persist the utility matrix to a CSV file (same layout as input).

    Args:
        file_path: Destination path (should end in ``.csv``).

    Returns:
        The resolved absolute path of the written file.
    """
    path = Path(file_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    df = pd.DataFrame(self.data, columns=self.candidates.tolist())
    df.to_csv(str(path), index=False)
    return str(path.resolve())

save_parquet(file_path)

Persist the utility matrix to a Parquet file.

Creates parent directories if needed. The file contains one column per candidate and one row per voter.

Parameters:

Name Type Description Default
file_path str

Destination path (should end in .parquet).

required

Returns:

Type Description
str

The resolved absolute path of the written file.

Source code in src/vote_simulation/models/data_generation/data_instance.py
def save_parquet(self, file_path: str) -> str:
    """Persist the utility matrix to a Parquet file.

    Creates parent directories if needed. The file contains one column
    per candidate and one row per voter.

    Args:
        file_path: Destination path (should end in ``.parquet``).

    Returns:
        The resolved absolute path of the written file.
    """
    path = Path(file_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    df = pd.DataFrame(self.data, columns=self.candidates.tolist())
    df.to_parquet(str(path), index=False)
    return str(path.resolve())

Results

SimulationStepResult dataclass

Result of a simulation step.

The comparison matrix is stored as a symmetric float32 2D array so that any distance metric (binary, Jaccard, etc.) can be used.

Source code in src/vote_simulation/models/results/step_result.py
@dataclass(slots=True)
class SimulationStepResult:
    """Result of a simulation step.

    The comparison matrix is stored as a symmetric ``float32`` 2D array so that
    any distance metric (binary, Jaccard, etc.) can be used.
    """

    data_source: str
    winners_by_rule: dict[str, list[str]] = field(default_factory=dict)
    distance_metric: Distance = field(default_factory=JaccardDistance)
    config: ResultConfig = field(default_factory=ResultConfig)
    _rule_order: list[str] = field(default_factory=list, init=False, repr=False)
    _rule_index: dict[str, int] = field(default_factory=dict, init=False, repr=False)
    _winner_sets_by_rule: dict[str, frozenset[str]] = field(default_factory=dict, init=False, repr=False)
    _distance_matrix: np.ndarray = field(
        default_factory=lambda: np.zeros((0, 0), dtype=np.float32),
        init=False,
        repr=False,
    )
    _metrics_by_rule: dict[str, WinnerMetrics] = field(default_factory=dict, init=False, repr=False)

    def __post_init__(self) -> None:
        """Normalize any pre-populated data and build the matrix once."""

        initial_items = list(self.winners_by_rule.items())
        self.winners_by_rule = {}
        self._rule_order = []
        self._rule_index = {}
        self._winner_sets_by_rule = {}
        self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
        self._metrics_by_rule = {}

        for rule_code, winners in initial_items:
            self.add_method_result(rule_code, winners)

    @property
    def rule_codes(self) -> list[str]:
        """Ordered rule codes matching the matrix axes."""

        return list(self._rule_order)

    @property
    def dist_matrix(self) -> np.ndarray:
        """Read-only 2D matrix of pairwise distances between rules."""

        matrix = self._distance_matrix.view()
        matrix.flags.writeable = False
        return matrix

    @property
    def distance_matrix_frame(self) -> pd.DataFrame:
        """Distance matrix as a labeled DataFrame for display and analysis."""

        idx = pd.Index(self._rule_order)
        return pd.DataFrame(self._distance_matrix, index=idx, columns=idx, copy=False)

    def add_method_result(self, rule_code: str, winners: list[str]) -> None:
        """Add or update winners for one voting method in this step.

        Args:
            rule_code: str - Code of the voting method (e.g., "STV", "IRV", "Borda")
            winners: list[str] - List of winner labels for the given method. Can be multiple in case of ties.
        """

        normalized_code = rule_code.strip().upper()
        normalized_winners = list(dict.fromkeys(winners))
        winner_set = frozenset(normalized_winners)

        self.winners_by_rule[normalized_code] = normalized_winners
        self._winner_sets_by_rule[normalized_code] = winner_set

        if normalized_code in self._rule_index:
            self._refresh_rule_distances(normalized_code)
            return

        self._append_rule(normalized_code)

    def add_method_result_with_metrics(
        self,
        rule_code: str,
        winners: list[str],
        metrics: WinnerMetrics,
    ) -> None:
        """Add winners *and* pre-computed :class:`WinnerMetrics` for one rule.

        This is the enriched variant of :meth:`add_method_result` used by the
        simulation engine so that winner-quality metrics can be aggregated
        across iterations with no extra recomputation.

        Args:
            rule_code: Voting rule code (e.g. ``"COPE"``).
            winners: List of co-winner labels.
            metrics: Pre-computed :class:`WinnerMetrics` for this step.
        """
        self.add_method_result(rule_code, winners)
        normalized_code = rule_code.strip().upper()
        self._metrics_by_rule[normalized_code] = metrics

    @property
    def metrics_by_rule(self) -> dict[str, WinnerMetrics]:
        """Mapping from rule code to its :class:`WinnerMetrics` for this step.

        Only rules registered via :meth:`add_method_result_with_metrics` will
        appear here.  Rules loaded from disk (without metrics) return an empty
        dict for their key.
        """
        return dict(self._metrics_by_rule)

    @property
    def metrics_frame(self) -> pd.DataFrame:
        """Metrics for all rules in this step as a tidy DataFrame.

        Returns a DataFrame indexed by ``rule`` with one column per metric
        field (see :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`).
        Rules without metrics are omitted.
        """
        if not self._metrics_by_rule:
            return pd.DataFrame(columns=pd.Index(np.asarray(list(METRIC_FIELDS), dtype=object)))
        rows = [{"rule": code, **m.to_dict()} for code, m in self._metrics_by_rule.items()]
        return pd.DataFrame(rows).set_index("rule")

    # ------------------------------------------------------------------
    # Distance metrics
    # ------------------------------------------------------------------

    @property
    def mean_distance(self) -> float:
        """Mean of all off-diagonal pairwise distances (O(1) numpy ops)."""
        n = len(self._rule_order)
        if n < 2:
            return 0.0
        total = float(np.sum(self._distance_matrix))  # diag is 0 so no need to subtract
        return total / (n * (n - 1))

    @property
    def most_distant_rules(self) -> tuple[str, str, float]:
        """Pair of rules with the maximum distance.

        Returns:
            ``(rule_a, rule_b, distance)`` or ``("", "", 0.0)`` if fewer
            than two rules are present.
        """
        n = len(self._rule_order)
        if n < 2:
            return ("", "", 0.0)
        idx = int(np.argmax(self._distance_matrix))
        i, j = divmod(idx, n)
        return (self._rule_order[i], self._rule_order[j], float(self._distance_matrix[i, j]))

    # Persistence

    def save_to_file(self, file_path: str) -> None:
        """Save the step result to a parquet file.

        Configuration metadata is stored via pyarrow schema metadata.
        Winner-quality metrics are stored as additional columns so that they
        survive the disk round-trip and can be accumulated by
        :class:`SimulationSeriesResult` after loading.

        Args:
            file_path: Path to the output parquet file.
        """
        import pyarrow as pa
        import pyarrow.parquet as pq

        rows = []
        nan_metrics = {f: float("nan") for f in METRIC_FIELDS}
        for rule, winners in self.winners_by_rule.items():
            metrics = self._metrics_by_rule.get(rule)
            metric_vals = metrics.to_dict() if metrics is not None else nan_metrics
            for winner in winners:
                rows.append({"Rule": rule, "Winner": winner, **metric_vals})
        df = pd.DataFrame(rows, columns=pd.Index(["Rule", "Winner"] + list(METRIC_FIELDS)))
        table = pa.Table.from_pandas(df, preserve_index=False)

        # Inject config into schema metadata (prefixed to avoid collisions).
        existing_meta = table.schema.metadata or {}
        config_meta = {f"vote_sim:{k}".encode(): v.encode() for k, v in self.config.to_dict().items()}
        table = table.replace_schema_metadata({**existing_meta, **config_meta})

        os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
        pq.write_table(table, file_path)

    def load_from_file(self, file_path: str) -> None:
        """Load the step result from a parquet file.

        Reads configuration metadata from the parquet schema when available.
        Winner-quality metrics are restored from metric columns when present
        (files written before this feature are loaded without metrics).

        Args:
            file_path: Path to the parquet file containing the step result.
        """
        import pyarrow.parquet as pq

        table = pq.read_table(file_path)
        meta = table.schema.metadata or {}
        config_dict = {
            k.decode().removeprefix("vote_sim:"): v.decode()
            for k, v in meta.items()
            if k.decode().startswith("vote_sim:")
        }
        self.config = ResultConfig.from_dict(config_dict) if config_dict else ResultConfig()

        df = table.to_pandas()
        loaded_winners = df.groupby("Rule")["Winner"].apply(list).to_dict()

        self.winners_by_rule = {}
        self._rule_order = []
        self._rule_index = {}
        self._winner_sets_by_rule = {}
        self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
        self._metrics_by_rule = {}

        # Restore per-rule metrics when the parquet file contains metric columns
        # (backward-compatible: old files without those columns are silently skipped).
        if all(c in df.columns for c in METRIC_FIELDS):
            first_rows = df.groupby("Rule", sort=False).first()
            for rule_code, row in first_rows.iterrows():
                if pd.isna(row.get("social_acceptability")):
                    continue
                try:
                    self._metrics_by_rule[str(rule_code)] = WinnerMetrics(
                        social_acceptability=float(row["social_acceptability"]),
                        utility_mean=float(row["utility_mean"]),
                        utility_median=float(row["utility_median"]),
                        utility_var=float(row["utility_var"]),
                        rank_mean=float(row["rank_mean"]),
                        rank_median=float(row["rank_median"]),
                        rank_var=float(row["rank_var"]),
                        freq_first=float(row["freq_first"]),
                        freq_last=float(row["freq_last"]),
                        has_tie=bool(row["has_tie"]),
                        n_cowinners=int(row["n_cowinners"]),
                    )
                except (TypeError, ValueError, KeyError):
                    pass

        for rule_code, winners in loaded_winners.items():
            self.add_method_result(str(rule_code), winners)

    @staticmethod
    def delete_file(file_path: str) -> bool:
        """Delete a saved step result file.

        Returns:
            ``True`` if the file existed and was deleted, ``False`` otherwise.
        """
        try:
            os.remove(file_path)
            return True
        except FileNotFoundError:
            return False

    def format_distance_matrix(self) -> str:
        """Return a printable matrix with row and column labels."""

        if self._distance_matrix.size == 0:
            return "<empty matrix>"

        return self.distance_matrix_frame.to_string()

    def __str__(self) -> str:
        """String representation with a readable matrix block."""

        winners_str = (
            "\n".join(f"- {rule}: {', '.join(winners)}" for rule, winners in self.winners_by_rule.items()) or "- <none>"
        )

        header = f"Data Source: {self.data_source}"
        if self.config:
            header += f"\nConfig: {self.config.description}"

        n = len(self._rule_order)
        metrics = ""
        if n >= 2:
            r1, r2, d = self.most_distant_rules
            metrics = f"\nMean distance: {self.mean_distance:.4f}\nMost distant: {r1} <-> {r2} ({d:.4f})"

        mat_str = f"\nDistance Matrix:\n{indent(self.format_distance_matrix(), '  ')}" if self._rule_order else ""
        return f"{header}\nWinners by rule:\n{indent(winners_str, '  ')}{metrics}{mat_str}\n"

    def compute_distance_matrix(self) -> np.ndarray:
        """Rebuild the full distance matrix from winners and return it."""

        ordered_items = [(rule_code, self.winners_by_rule[rule_code]) for rule_code in self._rule_order]
        self.winners_by_rule = {}
        self._rule_order = []
        self._rule_index = {}
        self._winner_sets_by_rule = {}
        self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
        self._metrics_by_rule = {}

        for rule_code, winners in ordered_items:
            self.add_method_result(rule_code, winners)

        return self.dist_matrix

    def plot_distance_matrix(
        self,
        ax: Any | None = None,
        save_path: str | None = None,
        *,
        annotate: bool = True,
        show: bool = True,
    ) -> Any:
        """Plot the distance matrix as a heatmap.

        When *save_path* is given the plot is written to disk.  If *save_path*
        is a **directory**, the filename is derived automatically from the
        attached :attr:`config`.
        """

        if not self._rule_order:
            raise ValueError("Cannot plot an empty distance matrix.")

        subtitle = self.config.description if self.config else ""
        title = "Rule distance matrix"
        if subtitle:
            title += f"\n{subtitle}"
        else:
            title += f"\n{self.data_source}"

        resolved_save: str | None = None
        if save_path is not None:
            resolved_save = self._resolve_save_path(save_path, "step_distance_matrix.png")

        return _plot_heatmap(
            self._distance_matrix,
            self._rule_order,
            title=title,
            ax=ax,
            vmin=0,
            vmax=1,
            annotate=annotate,
            annotation_fmt=".2f",
            colorbar_label="Distance",
            show=show,
            save_path=resolved_save,
        )

    # Path helpers

    def _resolve_save_path(self, path: str, default_filename: str) -> str:
        """If *path* is a directory, append a config-based filename."""
        if os.path.isdir(path) or path.endswith(os.sep):
            subdir = self.config.label if self.config else "unknown"
            out = os.path.join(path, subdir, default_filename)
        else:
            out = path
        os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
        return out

    def _append_rule(self, rule_code: str) -> None:
        """Append a new rule and update only the new row/column."""

        previous_size = len(self._rule_order)
        new_size = previous_size + 1
        new_matrix = np.zeros((new_size, new_size), dtype=np.float32)

        if previous_size:
            new_matrix[:previous_size, :previous_size] = self._distance_matrix

        self._rule_order.append(rule_code)
        self._rule_index[rule_code] = previous_size
        self._distance_matrix = new_matrix
        self._refresh_rule_distances(rule_code)

    def _refresh_rule_distances(self, rule_code: str) -> None:
        """Refresh only one rule row/column in the symmetric matrix."""

        row_index = self._rule_index[rule_code]
        self._distance_matrix[row_index, row_index] = 0.0
        winner_set = self._winner_sets_by_rule[rule_code]
        metric = self.distance_metric

        for other_rule, other_index in self._rule_index.items():
            if other_rule == rule_code:
                continue

            distance = metric.compute(winner_set, self._winner_sets_by_rule[other_rule])
            self._distance_matrix[row_index, other_index] = distance
            self._distance_matrix[other_index, row_index] = distance

dist_matrix property

Read-only 2D matrix of pairwise distances between rules.

distance_matrix_frame property

Distance matrix as a labeled DataFrame for display and analysis.

mean_distance property

Mean of all off-diagonal pairwise distances (O(1) numpy ops).

metrics_by_rule property

Mapping from rule code to its :class:WinnerMetrics for this step.

Only rules registered via :meth:add_method_result_with_metrics will appear here. Rules loaded from disk (without metrics) return an empty dict for their key.

metrics_frame property

Metrics for all rules in this step as a tidy DataFrame.

Returns a DataFrame indexed by rule with one column per metric field (see :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS). Rules without metrics are omitted.

most_distant_rules property

Pair of rules with the maximum distance.

Returns:

Type Description
str

(rule_a, rule_b, distance) or ("", "", 0.0) if fewer

str

than two rules are present.

rule_codes property

Ordered rule codes matching the matrix axes.

__post_init__()

Normalize any pre-populated data and build the matrix once.

Source code in src/vote_simulation/models/results/step_result.py
def __post_init__(self) -> None:
    """Normalize any pre-populated data and build the matrix once."""

    initial_items = list(self.winners_by_rule.items())
    self.winners_by_rule = {}
    self._rule_order = []
    self._rule_index = {}
    self._winner_sets_by_rule = {}
    self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
    self._metrics_by_rule = {}

    for rule_code, winners in initial_items:
        self.add_method_result(rule_code, winners)

__str__()

String representation with a readable matrix block.

Source code in src/vote_simulation/models/results/step_result.py
def __str__(self) -> str:
    """String representation with a readable matrix block."""

    winners_str = (
        "\n".join(f"- {rule}: {', '.join(winners)}" for rule, winners in self.winners_by_rule.items()) or "- <none>"
    )

    header = f"Data Source: {self.data_source}"
    if self.config:
        header += f"\nConfig: {self.config.description}"

    n = len(self._rule_order)
    metrics = ""
    if n >= 2:
        r1, r2, d = self.most_distant_rules
        metrics = f"\nMean distance: {self.mean_distance:.4f}\nMost distant: {r1} <-> {r2} ({d:.4f})"

    mat_str = f"\nDistance Matrix:\n{indent(self.format_distance_matrix(), '  ')}" if self._rule_order else ""
    return f"{header}\nWinners by rule:\n{indent(winners_str, '  ')}{metrics}{mat_str}\n"

add_method_result(rule_code, winners)

Add or update winners for one voting method in this step.

Parameters:

Name Type Description Default
rule_code str

str - Code of the voting method (e.g., "STV", "IRV", "Borda")

required
winners list[str]

list[str] - List of winner labels for the given method. Can be multiple in case of ties.

required
Source code in src/vote_simulation/models/results/step_result.py
def add_method_result(self, rule_code: str, winners: list[str]) -> None:
    """Add or update winners for one voting method in this step.

    Args:
        rule_code: str - Code of the voting method (e.g., "STV", "IRV", "Borda")
        winners: list[str] - List of winner labels for the given method. Can be multiple in case of ties.
    """

    normalized_code = rule_code.strip().upper()
    normalized_winners = list(dict.fromkeys(winners))
    winner_set = frozenset(normalized_winners)

    self.winners_by_rule[normalized_code] = normalized_winners
    self._winner_sets_by_rule[normalized_code] = winner_set

    if normalized_code in self._rule_index:
        self._refresh_rule_distances(normalized_code)
        return

    self._append_rule(normalized_code)

add_method_result_with_metrics(rule_code, winners, metrics)

Add winners and pre-computed :class:WinnerMetrics for one rule.

This is the enriched variant of :meth:add_method_result used by the simulation engine so that winner-quality metrics can be aggregated across iterations with no extra recomputation.

Parameters:

Name Type Description Default
rule_code str

Voting rule code (e.g. "COPE").

required
winners list[str]

List of co-winner labels.

required
metrics WinnerMetrics

Pre-computed :class:WinnerMetrics for this step.

required
Source code in src/vote_simulation/models/results/step_result.py
def add_method_result_with_metrics(
    self,
    rule_code: str,
    winners: list[str],
    metrics: WinnerMetrics,
) -> None:
    """Add winners *and* pre-computed :class:`WinnerMetrics` for one rule.

    This is the enriched variant of :meth:`add_method_result` used by the
    simulation engine so that winner-quality metrics can be aggregated
    across iterations with no extra recomputation.

    Args:
        rule_code: Voting rule code (e.g. ``"COPE"``).
        winners: List of co-winner labels.
        metrics: Pre-computed :class:`WinnerMetrics` for this step.
    """
    self.add_method_result(rule_code, winners)
    normalized_code = rule_code.strip().upper()
    self._metrics_by_rule[normalized_code] = metrics

compute_distance_matrix()

Rebuild the full distance matrix from winners and return it.

Source code in src/vote_simulation/models/results/step_result.py
def compute_distance_matrix(self) -> np.ndarray:
    """Rebuild the full distance matrix from winners and return it."""

    ordered_items = [(rule_code, self.winners_by_rule[rule_code]) for rule_code in self._rule_order]
    self.winners_by_rule = {}
    self._rule_order = []
    self._rule_index = {}
    self._winner_sets_by_rule = {}
    self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
    self._metrics_by_rule = {}

    for rule_code, winners in ordered_items:
        self.add_method_result(rule_code, winners)

    return self.dist_matrix

delete_file(file_path) staticmethod

Delete a saved step result file.

Returns:

Type Description
bool

True if the file existed and was deleted, False otherwise.

Source code in src/vote_simulation/models/results/step_result.py
@staticmethod
def delete_file(file_path: str) -> bool:
    """Delete a saved step result file.

    Returns:
        ``True`` if the file existed and was deleted, ``False`` otherwise.
    """
    try:
        os.remove(file_path)
        return True
    except FileNotFoundError:
        return False

format_distance_matrix()

Return a printable matrix with row and column labels.

Source code in src/vote_simulation/models/results/step_result.py
def format_distance_matrix(self) -> str:
    """Return a printable matrix with row and column labels."""

    if self._distance_matrix.size == 0:
        return "<empty matrix>"

    return self.distance_matrix_frame.to_string()

load_from_file(file_path)

Load the step result from a parquet file.

Reads configuration metadata from the parquet schema when available. Winner-quality metrics are restored from metric columns when present (files written before this feature are loaded without metrics).

Parameters:

Name Type Description Default
file_path str

Path to the parquet file containing the step result.

required
Source code in src/vote_simulation/models/results/step_result.py
def load_from_file(self, file_path: str) -> None:
    """Load the step result from a parquet file.

    Reads configuration metadata from the parquet schema when available.
    Winner-quality metrics are restored from metric columns when present
    (files written before this feature are loaded without metrics).

    Args:
        file_path: Path to the parquet file containing the step result.
    """
    import pyarrow.parquet as pq

    table = pq.read_table(file_path)
    meta = table.schema.metadata or {}
    config_dict = {
        k.decode().removeprefix("vote_sim:"): v.decode()
        for k, v in meta.items()
        if k.decode().startswith("vote_sim:")
    }
    self.config = ResultConfig.from_dict(config_dict) if config_dict else ResultConfig()

    df = table.to_pandas()
    loaded_winners = df.groupby("Rule")["Winner"].apply(list).to_dict()

    self.winners_by_rule = {}
    self._rule_order = []
    self._rule_index = {}
    self._winner_sets_by_rule = {}
    self._distance_matrix = np.zeros((0, 0), dtype=np.float32)
    self._metrics_by_rule = {}

    # Restore per-rule metrics when the parquet file contains metric columns
    # (backward-compatible: old files without those columns are silently skipped).
    if all(c in df.columns for c in METRIC_FIELDS):
        first_rows = df.groupby("Rule", sort=False).first()
        for rule_code, row in first_rows.iterrows():
            if pd.isna(row.get("social_acceptability")):
                continue
            try:
                self._metrics_by_rule[str(rule_code)] = WinnerMetrics(
                    social_acceptability=float(row["social_acceptability"]),
                    utility_mean=float(row["utility_mean"]),
                    utility_median=float(row["utility_median"]),
                    utility_var=float(row["utility_var"]),
                    rank_mean=float(row["rank_mean"]),
                    rank_median=float(row["rank_median"]),
                    rank_var=float(row["rank_var"]),
                    freq_first=float(row["freq_first"]),
                    freq_last=float(row["freq_last"]),
                    has_tie=bool(row["has_tie"]),
                    n_cowinners=int(row["n_cowinners"]),
                )
            except (TypeError, ValueError, KeyError):
                pass

    for rule_code, winners in loaded_winners.items():
        self.add_method_result(str(rule_code), winners)

plot_distance_matrix(ax=None, save_path=None, *, annotate=True, show=True)

Plot the distance matrix as a heatmap.

When save_path is given the plot is written to disk. If save_path is a directory, the filename is derived automatically from the attached :attr:config.

Source code in src/vote_simulation/models/results/step_result.py
def plot_distance_matrix(
    self,
    ax: Any | None = None,
    save_path: str | None = None,
    *,
    annotate: bool = True,
    show: bool = True,
) -> Any:
    """Plot the distance matrix as a heatmap.

    When *save_path* is given the plot is written to disk.  If *save_path*
    is a **directory**, the filename is derived automatically from the
    attached :attr:`config`.
    """

    if not self._rule_order:
        raise ValueError("Cannot plot an empty distance matrix.")

    subtitle = self.config.description if self.config else ""
    title = "Rule distance matrix"
    if subtitle:
        title += f"\n{subtitle}"
    else:
        title += f"\n{self.data_source}"

    resolved_save: str | None = None
    if save_path is not None:
        resolved_save = self._resolve_save_path(save_path, "step_distance_matrix.png")

    return _plot_heatmap(
        self._distance_matrix,
        self._rule_order,
        title=title,
        ax=ax,
        vmin=0,
        vmax=1,
        annotate=annotate,
        annotation_fmt=".2f",
        colorbar_label="Distance",
        show=show,
        save_path=resolved_save,
    )

save_to_file(file_path)

Save the step result to a parquet file.

Configuration metadata is stored via pyarrow schema metadata. Winner-quality metrics are stored as additional columns so that they survive the disk round-trip and can be accumulated by :class:SimulationSeriesResult after loading.

Parameters:

Name Type Description Default
file_path str

Path to the output parquet file.

required
Source code in src/vote_simulation/models/results/step_result.py
def save_to_file(self, file_path: str) -> None:
    """Save the step result to a parquet file.

    Configuration metadata is stored via pyarrow schema metadata.
    Winner-quality metrics are stored as additional columns so that they
    survive the disk round-trip and can be accumulated by
    :class:`SimulationSeriesResult` after loading.

    Args:
        file_path: Path to the output parquet file.
    """
    import pyarrow as pa
    import pyarrow.parquet as pq

    rows = []
    nan_metrics = {f: float("nan") for f in METRIC_FIELDS}
    for rule, winners in self.winners_by_rule.items():
        metrics = self._metrics_by_rule.get(rule)
        metric_vals = metrics.to_dict() if metrics is not None else nan_metrics
        for winner in winners:
            rows.append({"Rule": rule, "Winner": winner, **metric_vals})
    df = pd.DataFrame(rows, columns=pd.Index(["Rule", "Winner"] + list(METRIC_FIELDS)))
    table = pa.Table.from_pandas(df, preserve_index=False)

    # Inject config into schema metadata (prefixed to avoid collisions).
    existing_meta = table.schema.metadata or {}
    config_meta = {f"vote_sim:{k}".encode(): v.encode() for k, v in self.config.to_dict().items()}
    table = table.replace_schema_metadata({**existing_meta, **config_meta})

    os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
    pq.write_table(table, file_path)

Data models for simulation outputs across multiple iterations.

SimulationSeriesResult dataclass

Aggregation of simulation steps.

Maintains a running float64 sum of per-step distance matrices so that the mean can be computed with a single division at any time, regardless of how many iterations have been added.

The aggregated :attr:config is automatically updated on each :meth:add_step call and reflects the union of all per-step configs.

Source code in src/vote_simulation/models/results/series_result.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
@dataclass(slots=True)
class SimulationSeriesResult:
    """Aggregation of simulation steps.

    Maintains a running ``float64`` sum of per-step distance matrices so
    that the mean can be computed with a single division at any time, regardless
    of how many iterations have been added.

    The aggregated :attr:`config` is automatically updated on each
    :meth:`add_step` call and reflects the union of all per-step configs.
    """

    steps: list[SimulationStepResult] = field(default_factory=list)
    # Accumulator fields
    _rule_order: list[str] = field(default_factory=list, init=False, repr=False)
    _rule_index: dict[str, int] = field(default_factory=dict, init=False, repr=False)
    _matrix_sum: np.ndarray = field(
        default_factory=lambda: np.zeros((0, 0), dtype=np.float64),
        init=False,
        repr=False,
    )
    _iteration_count: int = field(default=0, init=False, repr=False)
    _config: ResultConfig = field(default_factory=ResultConfig, init=False, repr=False)
    # Per-rule metric accumulators (sum and sum-of-squares for online mean/std)
    _metrics_sum: dict[str, np.ndarray] = field(default_factory=dict, init=False, repr=False)
    _metrics_sum_sq: dict[str, np.ndarray] = field(default_factory=dict, init=False, repr=False)
    _metrics_count: dict[str, int] = field(default_factory=dict, init=False, repr=False)

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def add_step(self, step_result: SimulationStepResult) -> None:
        """Add one step result to the series and accumulate its distance matrix."""

        self.steps.append(step_result)
        self._accumulate_step(step_result)
        if step_result.config:
            self._config = self._config.merge(step_result.config)

    def add_rules_to_steps(self, new_rule_codes: list[str]) -> None:
        """Apply additional rules to all existing steps and update the series.

        Does not re-run existing rules, only computes distances for new rules.
        Rebuilds the accumulated distance matrix with all rules (old + new).

        Args:
            new_rule_codes: List of additional rule codes to apply to each step.

        Raises:
            ImportError: If ``vote_simulation.models.rules`` is not available.
        """
        if not new_rule_codes:
            return

        from vote_simulation.models.data_generation.data_instance import DataInstance
        from vote_simulation.models.rules import get_rule_builder

        # Apply new rules to each step
        for step in self.steps:
            if not step.data_source:
                print("Warning: Step without data_source, skipping rule application")
                continue

            try:
                di = DataInstance(step.data_source)
                profile = di.profile

                for code in new_rule_codes:
                    normalized = code.strip().upper()
                    if normalized in step.winners_by_rule:
                        continue  # Skip if rule already exists

                    try:
                        builder = get_rule_builder(normalized)
                        rule = builder(profile, None)
                        winners = rule.cowinners_
                        try:
                            metrics = rule.compute_metrics()
                            step.add_method_result_with_metrics(normalized, winners, metrics)
                        except Exception:
                            step.add_method_result(normalized, winners)
                    except Exception as e:
                        print(f"Error applying rule '{normalized}' to step: {e}")
                        step.add_method_result(normalized, [f"ERROR: {e}"])
            except Exception as e:
                print(f"Error loading data source '{step.data_source}': {e}")

        # Rebuild the aggregated distance matrix and metric accumulators
        self._rule_order = []
        self._rule_index = {}
        self._matrix_sum = np.zeros((0, 0), dtype=np.float64)
        self._iteration_count = 0
        self._metrics_sum = {}
        self._metrics_sum_sq = {}
        self._metrics_count = {}

        for step in self.steps:
            self._accumulate_step(step)

        # Update config to include new rules
        if new_rule_codes:
            new_rules = frozenset(c.strip().upper() for c in new_rule_codes)
            self._config = ResultConfig(
                gen_models=self._config.gen_models,
                n_voters=self._config.n_voters,
                n_candidates=self._config.n_candidates,
                rules_codes=self._config.rules_codes | new_rules,
                n_iterations=self._config.n_iterations,
            )

    def filter_rules(self, rule_codes: list[str]) -> SimulationSeriesResult:
        """Return a new series restricted to the specified rule codes.

        Only the accumulator state is copied — ``steps`` are not included in
        the returned object.  All plot and export methods work identically on
        the filtered result.

        Args:
            rule_codes: Rule codes to keep.  Unknown codes are silently
                ignored.  Codes are normalised (stripped, upper-cased) before
                matching.

        Returns:
            A new :class:`SimulationSeriesResult` with only the selected
            rules.  Returns an empty instance if none of the requested rules
            are present.
        """
        if not rule_codes:
            return SimulationSeriesResult()
        normalized = {r.strip().upper() for r in rule_codes}
        selected = [r for r in self._rule_order if r in normalized]
        if not selected:
            return SimulationSeriesResult()

        new = SimulationSeriesResult()
        new._rule_order = list(selected)
        new._rule_index = {r: i for i, r in enumerate(selected)}
        new._iteration_count = self._iteration_count
        new._config = self._config

        # Extract the sub-matrix for selected rules
        idx = np.array([self._rule_index[r] for r in selected], dtype=np.intp)
        new._matrix_sum = self._matrix_sum[np.ix_(idx, idx)].copy()

        # Filter per-rule metric accumulators
        new._metrics_sum = {r: v.copy() for r, v in self._metrics_sum.items() if r in normalized}
        new._metrics_sum_sq = {r: v.copy() for r, v in self._metrics_sum_sq.items() if r in normalized}
        new._metrics_count = {r: v for r, v in self._metrics_count.items() if r in normalized}

        return new

    @property
    def config(self) -> ResultConfig:
        """Aggregated configuration across all added steps."""
        return self._config

    @config.setter
    def config(self, value: ResultConfig) -> None:
        self._config = value

    @property
    def step_count(self) -> int:
        """Number of recorded steps (equals the iteration count)."""
        return self._iteration_count

    @property
    def rule_codes(self) -> list[str]:
        """Ordered rule codes currently available in the aggregated result."""
        return list(self._rule_order)

    @property
    def mean_distance_matrix(self) -> np.ndarray:
        """Mean pairwise distance matrix over all accumulated steps.

        Returns a ``float32`` array of shape ``(n_rules, n_rules)``.
        Values are in ``[0, 100]``: 0 means every step agreed, 100 means they never did.
        """
        if self._iteration_count == 0:
            return np.zeros((0, 0), dtype=np.float32)
        return (100.0 * self._matrix_sum / self._iteration_count).astype(np.float32)

    @property
    def mean_distance_matrix_frame(self) -> pd.DataFrame:
        """Mean distance matrix as a labeled DataFrame."""
        matrix = self.mean_distance_matrix
        idx = pd.Index(self._rule_order)
        return pd.DataFrame(matrix, index=idx, columns=idx)

    @property
    def metrics_summary_frame(self) -> pd.DataFrame:
        """Per-rule winner-metric statistics aggregated across all iterations.

        Returns a :class:`~pandas.DataFrame` indexed by ``rule`` with two
        columns per metric field — one for the mean and one for the standard
        deviation across all accumulated steps:

        ``<field>_mean``, ``<field>_std``  for each field in
        :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`.

        Rules for which no metrics were recorded (e.g. loaded from a parquet
        file without metrics) are omitted from the frame.

        An empty DataFrame is returned when no metrics have been accumulated.
        """
        if not self._metrics_sum:
            col_names = [f"{f}_{s}" for f in METRIC_FIELDS for s in ("mean", "std")]
            return pd.DataFrame(columns=pd.Index(np.asarray(col_names, dtype=object)))

        rows = []
        for rule in self._rule_order:
            if rule not in self._metrics_sum:
                continue
            count = self._metrics_count[rule]
            mean_arr = self._metrics_sum[rule] / count
            mean_sq_arr = self._metrics_sum_sq[rule] / count
            # population std — safe against floating precision below zero
            std_arr = np.sqrt(np.maximum(0.0, mean_sq_arr - mean_arr**2))
            row: dict[str, object] = {"rule": rule}
            for i, field_name in enumerate(METRIC_FIELDS):
                row[f"{field_name}_mean"] = float(mean_arr[i])
                row[f"{field_name}_std"] = float(std_arr[i])
            rows.append(row)

        if not rows:
            col_names = [f"{f}_{s}" for f in METRIC_FIELDS for s in ("mean", "std")]
            return pd.DataFrame(columns=pd.Index(np.asarray(col_names, dtype=object)))
        return pd.DataFrame(rows).set_index("rule")

    # ------------------------------------------------------------------
    # Distance metrics
    # ------------------------------------------------------------------

    @property
    def mean_distance(self) -> float:
        """Scalar mean of all off-diagonal cells in the mean distance matrix.

        Value in ``[0, 100]``.
        """
        n = len(self._rule_order)
        if n < 2 or self._iteration_count == 0:
            return 0.0
        mean_mat = self.mean_distance_matrix
        total = float(np.sum(mean_mat))  # diag is 0
        return total / (n * (n - 1))

    @property
    def most_distant_rules(self) -> tuple[str, str, float]:
        """Pair of rules with the maximum mean distance.

        Returns:
            ``(rule_a, rule_b, distance)`` or ``("", "", 0.0)`` when fewer
            than two rules are present.
        """
        n = len(self._rule_order)
        if n < 2 or self._iteration_count == 0:
            return ("", "", 0.0)
        mean_mat = self.mean_distance_matrix
        idx = int(np.argmax(mean_mat))
        i, j = divmod(idx, n)
        return (self._rule_order[i], self._rule_order[j], float(mean_mat[i, j]))

    # ------------------------------------------------------------------
    # Plotting
    # ------------------------------------------------------------------

    def _build_title(self, prefix: str) -> str:
        """Build a plot title from *prefix*, config description and iteration count."""
        desc = self._config.description if self._config else ""
        iters = f"{self._iteration_count} iterations"
        if desc:
            return f"{prefix}\n{desc} \u00b7 {iters}"
        return f"{prefix}\n({iters})"

    def _resolve_save_path(self, base_path: str, default_filename: str) -> str:
        """Derive a full save path, inserting a config‑based sub-directory."""
        if os.path.isdir(base_path) or base_path.endswith(os.sep):
            subdir = self._config.label if self._config else "unknown"
            out = os.path.join(base_path, subdir, default_filename)
        else:
            out = base_path
        os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
        return out

    def plot_mean_distance_matrix(
        self,
        ax: Any | None = None,
        folder_save_path: str | None = None,
        *,
        annotate: bool = True,
        show: bool = True,
    ) -> Any:
        """Plot the mean distance matrix as a heatmap.

        Cell values show the percentage of iterations where two rules disagreed.
        When multi‑config (several models / voter counts / candidate counts),
        the title mentions all of them.
        """
        if self._iteration_count == 0:
            raise ValueError("Cannot plot: no steps have been added yet.")

        save_path: str | None = None
        if folder_save_path is not None:
            save_path = self._resolve_save_path(
                folder_save_path,
                f"{self._iteration_count}_mean_distance_matrix.png",
            )

        result = _plot_heatmap(
            self.mean_distance_matrix,
            self._rule_order,
            self._build_title("Mean rule distance matrix"),
            ax,
            annotate=annotate,
            annotation_fmt=".1f",
            colorbar_label="Mean distance (%)",
            show=show,
            save_path=save_path,
        )

        # Auto-save series parquet alongside the plot
        if save_path is not None:
            parquet_path = os.path.join(
                os.path.dirname(save_path),
                f"{self._iteration_count}_series.parquet",
            )
            self.save_to_file(parquet_path)

        return result

    def export_mean_distance_matrix_csv(self, folder_save_path: str) -> str:
        """Export the mean distance matrix as CSV.

        Uses the same folder semantics as :meth:`plot_mean_distance_matrix`:
        if *folder_save_path* is a directory (or ends with a path separator),
        the file is written under a config-based sub-directory.

        Args:
            folder_save_path: Destination file path or folder path.

        Returns:
            The resolved CSV file path.
        """
        if self._iteration_count == 0:
            raise ValueError("Cannot export: no steps have been added yet.")

        save_path = self._resolve_save_path(
            folder_save_path,
            f"{self._iteration_count}_mean_distance_matrix.csv",
        )
        self.mean_distance_matrix_frame.to_csv(save_path, index=True)
        return save_path

    def export_metrics_summary_csv(
        self,
        folder_save_path: str,
        *,
        stat: str = "mean",
        metrics: list[str] | None = None,
    ) -> str:
        """Export per-rule winner metrics as CSV.

        Args:
            folder_save_path: Destination file path or folder path.
            stat: Statistic to export, ``"mean"`` or ``"std"``.
            metrics: Optional subset of metric field names.

        Returns:
            The resolved CSV file path.
        """
        if stat not in {"mean", "std"}:
            raise ValueError(f"Invalid stat '{stat}'. Expected 'mean' or 'std'.")

        frame = self.metrics_summary_frame
        if frame.empty:
            raise ValueError("No winner-metric data found. Check that metrics were computed during simulation.")

        fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)
        invalid = [m for m in fields if m not in METRIC_FIELDS]
        if invalid:
            raise ValueError(f"Unknown metric fields: {invalid}")

        cols = [f"{field}_{stat}" for field in fields if f"{field}_{stat}" in frame.columns]
        if not cols:
            raise ValueError("No valid metric columns available for export.")

        save_path = self._resolve_save_path(
            folder_save_path,
            f"{self._iteration_count}_metrics_{stat}.csv",
        )
        frame.loc[:, cols].to_csv(save_path, index=True)
        return save_path

    def map_rules_2d(self) -> MdsProjection:
        """Project rules into 2D using Multi-Dimensional Scaling (MDS).

        Uses the mean distance matrix as a precomputed dissimilarity matrix
        so that pairwise distances in the 2D plane approximate the original
        rule-to-rule distances.

        Returns:
            :class:`MdsProjection` with 2D coordinates and normalized stress.

        Raises:
            ValueError: If no steps have been added yet.
        """
        if self._iteration_count == 0:
            raise ValueError("Cannot project: no steps have been added yet.")
        return _mds_project(self.mean_distance_matrix.astype(np.float64), n_components=2)

    def map_rules_3d(self) -> MdsProjection:
        """Project rules into 3D using Multi-Dimensional Scaling (MDS).

        Uses the mean distance matrix as a precomputed dissimilarity matrix
        so that pairwise distances in the 3D space approximate the original
        rule-to-rule distances.

        Returns:
            :class:`MdsProjection` with 3D coordinates and normalized stress.

        Raises:
            ValueError: If no steps have been added yet.
        """
        if self._iteration_count == 0:
            raise ValueError("Cannot project: no steps have been added yet.")
        return _mds_project(self.mean_distance_matrix.astype(np.float64), n_components=3)

    def plot_rules_3d(
        self,
        ax: Any | None = None,
        *,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Plot rules as labeled points in a 3D MDS projection.

        Distances between points approximate mean pairwise rule distances.
        The normalized MDS stress is shown on the plot.

        Args:
            ax: Optional matplotlib Axes to draw on. A new figure is created
                when *None*.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional path (file or directory) to save the plot.

        Returns:
            The matplotlib Axes used for plotting.
        """
        projection = self.map_rules_3d()
        title = self._build_title("Rule proximity map (3D)")
        title += f"\nMDS stress: {projection.stress:.4f}"

        resolved: str | None = None
        if save_path is not None:
            resolved = self._resolve_save_path(save_path, f"{self._iteration_count}_rules_3d.png")

        ax = _plot_rules_3d_scatter(projection.coords, self._rule_order, title, ax, show=show, save_path=resolved)

        if resolved is not None:
            self.save_to_file(os.path.join(os.path.dirname(resolved), f"{self._iteration_count}_series.parquet"))

        return ax

    def plot_rules_2d(
        self,
        ax: Any | None = None,
        *,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Plot rules as labeled points in a 2D MDS projection.

        Distances between points approximate mean pairwise rule distances.

        Args:
            ax: Optional matplotlib Axes to draw on. A new figure is created
                when *None*.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional path (file or directory) to save the plot.

        Returns:
            The matplotlib Axes used for plotting.
        """
        projection = self.map_rules_2d()
        title = self._build_title("Rule proximity map")

        resolved: str | None = None
        if save_path is not None:
            resolved = self._resolve_save_path(save_path, f"{self._iteration_count}_rules_2d.png")

        ax = _plot_rules_2d_scatter(projection.coords, self._rule_order, title, ax, show=show, save_path=resolved)

        if resolved is not None:
            self.save_to_file(os.path.join(os.path.dirname(resolved), f"{self._iteration_count}_series.parquet"))

        return ax

    # ------------------------------------------------------------------
    # Persistence
    # ------------------------------------------------------------------

    def save_to_file(self, file_path: str) -> None:
        """Save the series result to a parquet file.

        Per-step config is stored in columns ``GenModel``, ``NVoters``,
        ``NCandidates`` so that each row is self-describing.  The aggregated
        series config is stored in schema metadata.

        Args:
            file_path: Path to the output parquet file.
        """
        import pyarrow as pa
        import pyarrow.parquet as pq

        rows: list[dict[str, str | int]] = []
        for step in self.steps:
            # Flatten per-step config to single values (or empty string / 0)
            gm = ",".join(sorted(step.config.gen_models)) if step.config.gen_models else ""
            nv = ",".join(str(v) for v in sorted(step.config.n_voters)) if step.config.n_voters else ""
            nc = ",".join(str(c) for c in sorted(step.config.n_candidates)) if step.config.n_candidates else ""
            for rule, winners in step.winners_by_rule.items():
                for winner in winners:
                    rows.append(
                        {
                            "DataSource": step.data_source,
                            "GenModel": gm,
                            "NVoters": nv,
                            "NCandidates": nc,
                            "Rule": rule,
                            "Winner": winner,
                        }
                    )

        df = pd.DataFrame(rows)
        table = pa.Table.from_pandas(df, preserve_index=False)

        # Store aggregated config in schema metadata
        existing_meta = table.schema.metadata or {}
        config_meta = {f"vote_sim:{k}".encode(): v.encode() for k, v in self._config.to_dict().items()}

        # Persist metric accumulators so they survive a round-trip through disk.
        # Serialised as JSON under the key "vote_sim:metrics".
        import json as _json

        if self._metrics_sum:
            metrics_payload = {
                "sum": {rule: arr.tolist() for rule, arr in self._metrics_sum.items()},
                "sum_sq": {rule: arr.tolist() for rule, arr in self._metrics_sum_sq.items()},
                "count": {rule: int(c) for rule, c in self._metrics_count.items()},
            }
            metrics_meta = {b"vote_sim:metrics": _json.dumps(metrics_payload).encode()}
        else:
            metrics_meta = {}

        table = table.replace_schema_metadata({**existing_meta, **config_meta, **metrics_meta})

        os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
        pq.write_table(table, file_path)

    def load_from_file(self, file_path: str) -> None:
        """Load the series result from a parquet file and rebuild the accumulator.

        Reads per-step config from row columns and aggregated config from
        schema metadata.  Backwards-compatible with files lacking config columns.

        Args:
            file_path: Path to the parquet file containing the series result.
        """
        import pyarrow.parquet as pq

        table = pq.read_table(file_path)

        # --- Aggregated config from metadata ---
        meta = table.schema.metadata or {}
        config_dict = {
            k.decode().removeprefix("vote_sim:"): v.decode()
            for k, v in meta.items()
            if k.decode().startswith("vote_sim:") and k != b"vote_sim:metrics"
        }

        df = table.to_pandas()

        self.steps = []
        self._rule_order = []
        self._rule_index = {}
        self._matrix_sum = np.zeros((0, 0), dtype=np.float64)
        self._iteration_count = 0
        self._config = ResultConfig()
        self._metrics_sum = {}
        self._metrics_sum_sq = {}
        self._metrics_count = {}

        has_config_cols = {"GenModel", "NVoters", "NCandidates"}.issubset(df.columns)

        for data_source, group in df.groupby("DataSource", sort=False):
            step_config = ResultConfig()
            if has_config_cols:
                row0 = group.iloc[0]
                gm = str(row0["GenModel"]) if row0["GenModel"] else ""
                nv_str = str(row0["NVoters"]) if row0["NVoters"] else ""
                nc_str = str(row0["NCandidates"]) if row0["NCandidates"] else ""
                step_config = ResultConfig(
                    gen_models=frozenset(m for m in gm.split(",") if m),
                    n_voters=frozenset(int(v) for v in nv_str.split(",") if v),
                    n_candidates=frozenset(int(c) for c in nc_str.split(",") if c),
                )

            step_result = SimulationStepResult(
                data_source=str(data_source),
                config=step_config,
            )
            for rule, winners in group.groupby("Rule", sort=False)["Winner"]:
                step_result.add_method_result(str(rule), winners.tolist())
            self.add_step(step_result)

        # If schema metadata had config, prefer it (more complete for aggregates)
        if config_dict:
            self._config = ResultConfig.from_dict(config_dict)

        # Restore metric accumulators if they were persisted in the metadata.
        # This is backward-compatible: files without "vote_sim:metrics" will
        # simply have empty metric accumulators (metrics not available).
        import json as _json

        metrics_raw = meta.get(b"vote_sim:metrics")
        if metrics_raw:
            try:
                payload = _json.loads(metrics_raw.decode())
                self._metrics_sum = {
                    rule: np.array(arr, dtype=np.float64) for rule, arr in payload.get("sum", {}).items()
                }
                self._metrics_sum_sq = {
                    rule: np.array(arr, dtype=np.float64) for rule, arr in payload.get("sum_sq", {}).items()
                }
                self._metrics_count = {rule: int(c) for rule, c in payload.get("count", {}).items()}
            except Exception:
                # Corrupted metadata — silently ignore; metrics will be unavailable.
                pass

    @staticmethod
    def delete_file(file_path: str) -> bool:
        """Delete a saved series result file.

        Returns:
            ``True`` if the file existed and was deleted, ``False`` otherwise.
        """
        try:
            os.remove(file_path)
            return True
        except FileNotFoundError:
            return False

    # ------------------------------------------------------------------
    # Private helpers
    # ------------------------------------------------------------------

    def _accumulate_step(self, step: SimulationStepResult) -> None:
        """Add one step's distance matrix and winner metrics to the running sums."""

        step_rules = step._rule_order
        if not step_rules:
            return

        if not self._rule_order:
            # First step: establish canonical rule order for the whole series
            self._rule_order = list(step_rules)
            self._rule_index = dict(step._rule_index)
            n = len(step_rules)
            self._matrix_sum = np.zeros((n, n), dtype=np.float64)
        else:
            # Expand the matrix if this step introduces rules not seen before.
            new_rules = [r for r in step_rules if r not in self._rule_index]
            if new_rules:
                old_n = len(self._rule_order)
                for r in new_rules:
                    self._rule_index[r] = len(self._rule_order)
                    self._rule_order.append(r)
                new_n = len(self._rule_order)
                expanded = np.zeros((new_n, new_n), dtype=np.float64)
                expanded[:old_n, :old_n] = self._matrix_sum
                self._matrix_sum = expanded

        # Build permutation mapping step column index → series column index.
        # This handles the (rare) case where a step's rules are in a different order,
        # or when a step introduces rules not present in earlier steps.
        perm = np.array([self._rule_index[r] for r in step_rules], dtype=np.intp)
        self._matrix_sum[np.ix_(perm, perm)] += step._distance_matrix
        self._iteration_count += 1

        # Accumulate winner metrics (only for rules that carry metrics)
        n_fields = len(METRIC_FIELDS)
        for rule_code, wm in step._metrics_by_rule.items():
            arr = metrics_to_array(wm)
            if rule_code not in self._metrics_sum:
                self._metrics_sum[rule_code] = np.zeros(n_fields, dtype=np.float64)
                self._metrics_sum_sq[rule_code] = np.zeros(n_fields, dtype=np.float64)
                self._metrics_count[rule_code] = 0
            self._metrics_sum[rule_code] += arr
            self._metrics_sum_sq[rule_code] += arr * arr
            self._metrics_count[rule_code] += 1

config property writable

Aggregated configuration across all added steps.

mean_distance property

Scalar mean of all off-diagonal cells in the mean distance matrix.

Value in [0, 100].

mean_distance_matrix property

Mean pairwise distance matrix over all accumulated steps.

Returns a float32 array of shape (n_rules, n_rules). Values are in [0, 100]: 0 means every step agreed, 100 means they never did.

mean_distance_matrix_frame property

Mean distance matrix as a labeled DataFrame.

metrics_summary_frame property

Per-rule winner-metric statistics aggregated across all iterations.

Returns a :class:~pandas.DataFrame indexed by rule with two columns per metric field — one for the mean and one for the standard deviation across all accumulated steps:

<field>_mean, <field>_std for each field in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS.

Rules for which no metrics were recorded (e.g. loaded from a parquet file without metrics) are omitted from the frame.

An empty DataFrame is returned when no metrics have been accumulated.

most_distant_rules property

Pair of rules with the maximum mean distance.

Returns:

Type Description
str

(rule_a, rule_b, distance) or ("", "", 0.0) when fewer

str

than two rules are present.

rule_codes property

Ordered rule codes currently available in the aggregated result.

step_count property

Number of recorded steps (equals the iteration count).

add_rules_to_steps(new_rule_codes)

Apply additional rules to all existing steps and update the series.

Does not re-run existing rules, only computes distances for new rules. Rebuilds the accumulated distance matrix with all rules (old + new).

Parameters:

Name Type Description Default
new_rule_codes list[str]

List of additional rule codes to apply to each step.

required

Raises:

Type Description
ImportError

If vote_simulation.models.rules is not available.

Source code in src/vote_simulation/models/results/series_result.py
def add_rules_to_steps(self, new_rule_codes: list[str]) -> None:
    """Apply additional rules to all existing steps and update the series.

    Does not re-run existing rules, only computes distances for new rules.
    Rebuilds the accumulated distance matrix with all rules (old + new).

    Args:
        new_rule_codes: List of additional rule codes to apply to each step.

    Raises:
        ImportError: If ``vote_simulation.models.rules`` is not available.
    """
    if not new_rule_codes:
        return

    from vote_simulation.models.data_generation.data_instance import DataInstance
    from vote_simulation.models.rules import get_rule_builder

    # Apply new rules to each step
    for step in self.steps:
        if not step.data_source:
            print("Warning: Step without data_source, skipping rule application")
            continue

        try:
            di = DataInstance(step.data_source)
            profile = di.profile

            for code in new_rule_codes:
                normalized = code.strip().upper()
                if normalized in step.winners_by_rule:
                    continue  # Skip if rule already exists

                try:
                    builder = get_rule_builder(normalized)
                    rule = builder(profile, None)
                    winners = rule.cowinners_
                    try:
                        metrics = rule.compute_metrics()
                        step.add_method_result_with_metrics(normalized, winners, metrics)
                    except Exception:
                        step.add_method_result(normalized, winners)
                except Exception as e:
                    print(f"Error applying rule '{normalized}' to step: {e}")
                    step.add_method_result(normalized, [f"ERROR: {e}"])
        except Exception as e:
            print(f"Error loading data source '{step.data_source}': {e}")

    # Rebuild the aggregated distance matrix and metric accumulators
    self._rule_order = []
    self._rule_index = {}
    self._matrix_sum = np.zeros((0, 0), dtype=np.float64)
    self._iteration_count = 0
    self._metrics_sum = {}
    self._metrics_sum_sq = {}
    self._metrics_count = {}

    for step in self.steps:
        self._accumulate_step(step)

    # Update config to include new rules
    if new_rule_codes:
        new_rules = frozenset(c.strip().upper() for c in new_rule_codes)
        self._config = ResultConfig(
            gen_models=self._config.gen_models,
            n_voters=self._config.n_voters,
            n_candidates=self._config.n_candidates,
            rules_codes=self._config.rules_codes | new_rules,
            n_iterations=self._config.n_iterations,
        )

add_step(step_result)

Add one step result to the series and accumulate its distance matrix.

Source code in src/vote_simulation/models/results/series_result.py
def add_step(self, step_result: SimulationStepResult) -> None:
    """Add one step result to the series and accumulate its distance matrix."""

    self.steps.append(step_result)
    self._accumulate_step(step_result)
    if step_result.config:
        self._config = self._config.merge(step_result.config)

delete_file(file_path) staticmethod

Delete a saved series result file.

Returns:

Type Description
bool

True if the file existed and was deleted, False otherwise.

Source code in src/vote_simulation/models/results/series_result.py
@staticmethod
def delete_file(file_path: str) -> bool:
    """Delete a saved series result file.

    Returns:
        ``True`` if the file existed and was deleted, ``False`` otherwise.
    """
    try:
        os.remove(file_path)
        return True
    except FileNotFoundError:
        return False

export_mean_distance_matrix_csv(folder_save_path)

Export the mean distance matrix as CSV.

Uses the same folder semantics as :meth:plot_mean_distance_matrix: if folder_save_path is a directory (or ends with a path separator), the file is written under a config-based sub-directory.

Parameters:

Name Type Description Default
folder_save_path str

Destination file path or folder path.

required

Returns:

Type Description
str

The resolved CSV file path.

Source code in src/vote_simulation/models/results/series_result.py
def export_mean_distance_matrix_csv(self, folder_save_path: str) -> str:
    """Export the mean distance matrix as CSV.

    Uses the same folder semantics as :meth:`plot_mean_distance_matrix`:
    if *folder_save_path* is a directory (or ends with a path separator),
    the file is written under a config-based sub-directory.

    Args:
        folder_save_path: Destination file path or folder path.

    Returns:
        The resolved CSV file path.
    """
    if self._iteration_count == 0:
        raise ValueError("Cannot export: no steps have been added yet.")

    save_path = self._resolve_save_path(
        folder_save_path,
        f"{self._iteration_count}_mean_distance_matrix.csv",
    )
    self.mean_distance_matrix_frame.to_csv(save_path, index=True)
    return save_path

export_metrics_summary_csv(folder_save_path, *, stat='mean', metrics=None)

Export per-rule winner metrics as CSV.

Parameters:

Name Type Description Default
folder_save_path str

Destination file path or folder path.

required
stat str

Statistic to export, "mean" or "std".

'mean'
metrics list[str] | None

Optional subset of metric field names.

None

Returns:

Type Description
str

The resolved CSV file path.

Source code in src/vote_simulation/models/results/series_result.py
def export_metrics_summary_csv(
    self,
    folder_save_path: str,
    *,
    stat: str = "mean",
    metrics: list[str] | None = None,
) -> str:
    """Export per-rule winner metrics as CSV.

    Args:
        folder_save_path: Destination file path or folder path.
        stat: Statistic to export, ``"mean"`` or ``"std"``.
        metrics: Optional subset of metric field names.

    Returns:
        The resolved CSV file path.
    """
    if stat not in {"mean", "std"}:
        raise ValueError(f"Invalid stat '{stat}'. Expected 'mean' or 'std'.")

    frame = self.metrics_summary_frame
    if frame.empty:
        raise ValueError("No winner-metric data found. Check that metrics were computed during simulation.")

    fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)
    invalid = [m for m in fields if m not in METRIC_FIELDS]
    if invalid:
        raise ValueError(f"Unknown metric fields: {invalid}")

    cols = [f"{field}_{stat}" for field in fields if f"{field}_{stat}" in frame.columns]
    if not cols:
        raise ValueError("No valid metric columns available for export.")

    save_path = self._resolve_save_path(
        folder_save_path,
        f"{self._iteration_count}_metrics_{stat}.csv",
    )
    frame.loc[:, cols].to_csv(save_path, index=True)
    return save_path

filter_rules(rule_codes)

Return a new series restricted to the specified rule codes.

Only the accumulator state is copied — steps are not included in the returned object. All plot and export methods work identically on the filtered result.

Parameters:

Name Type Description Default
rule_codes list[str]

Rule codes to keep. Unknown codes are silently ignored. Codes are normalised (stripped, upper-cased) before matching.

required

Returns:

Type Description
SimulationSeriesResult

A new :class:SimulationSeriesResult with only the selected

SimulationSeriesResult

rules. Returns an empty instance if none of the requested rules

SimulationSeriesResult

are present.

Source code in src/vote_simulation/models/results/series_result.py
def filter_rules(self, rule_codes: list[str]) -> SimulationSeriesResult:
    """Return a new series restricted to the specified rule codes.

    Only the accumulator state is copied — ``steps`` are not included in
    the returned object.  All plot and export methods work identically on
    the filtered result.

    Args:
        rule_codes: Rule codes to keep.  Unknown codes are silently
            ignored.  Codes are normalised (stripped, upper-cased) before
            matching.

    Returns:
        A new :class:`SimulationSeriesResult` with only the selected
        rules.  Returns an empty instance if none of the requested rules
        are present.
    """
    if not rule_codes:
        return SimulationSeriesResult()
    normalized = {r.strip().upper() for r in rule_codes}
    selected = [r for r in self._rule_order if r in normalized]
    if not selected:
        return SimulationSeriesResult()

    new = SimulationSeriesResult()
    new._rule_order = list(selected)
    new._rule_index = {r: i for i, r in enumerate(selected)}
    new._iteration_count = self._iteration_count
    new._config = self._config

    # Extract the sub-matrix for selected rules
    idx = np.array([self._rule_index[r] for r in selected], dtype=np.intp)
    new._matrix_sum = self._matrix_sum[np.ix_(idx, idx)].copy()

    # Filter per-rule metric accumulators
    new._metrics_sum = {r: v.copy() for r, v in self._metrics_sum.items() if r in normalized}
    new._metrics_sum_sq = {r: v.copy() for r, v in self._metrics_sum_sq.items() if r in normalized}
    new._metrics_count = {r: v for r, v in self._metrics_count.items() if r in normalized}

    return new

load_from_file(file_path)

Load the series result from a parquet file and rebuild the accumulator.

Reads per-step config from row columns and aggregated config from schema metadata. Backwards-compatible with files lacking config columns.

Parameters:

Name Type Description Default
file_path str

Path to the parquet file containing the series result.

required
Source code in src/vote_simulation/models/results/series_result.py
def load_from_file(self, file_path: str) -> None:
    """Load the series result from a parquet file and rebuild the accumulator.

    Reads per-step config from row columns and aggregated config from
    schema metadata.  Backwards-compatible with files lacking config columns.

    Args:
        file_path: Path to the parquet file containing the series result.
    """
    import pyarrow.parquet as pq

    table = pq.read_table(file_path)

    # --- Aggregated config from metadata ---
    meta = table.schema.metadata or {}
    config_dict = {
        k.decode().removeprefix("vote_sim:"): v.decode()
        for k, v in meta.items()
        if k.decode().startswith("vote_sim:") and k != b"vote_sim:metrics"
    }

    df = table.to_pandas()

    self.steps = []
    self._rule_order = []
    self._rule_index = {}
    self._matrix_sum = np.zeros((0, 0), dtype=np.float64)
    self._iteration_count = 0
    self._config = ResultConfig()
    self._metrics_sum = {}
    self._metrics_sum_sq = {}
    self._metrics_count = {}

    has_config_cols = {"GenModel", "NVoters", "NCandidates"}.issubset(df.columns)

    for data_source, group in df.groupby("DataSource", sort=False):
        step_config = ResultConfig()
        if has_config_cols:
            row0 = group.iloc[0]
            gm = str(row0["GenModel"]) if row0["GenModel"] else ""
            nv_str = str(row0["NVoters"]) if row0["NVoters"] else ""
            nc_str = str(row0["NCandidates"]) if row0["NCandidates"] else ""
            step_config = ResultConfig(
                gen_models=frozenset(m for m in gm.split(",") if m),
                n_voters=frozenset(int(v) for v in nv_str.split(",") if v),
                n_candidates=frozenset(int(c) for c in nc_str.split(",") if c),
            )

        step_result = SimulationStepResult(
            data_source=str(data_source),
            config=step_config,
        )
        for rule, winners in group.groupby("Rule", sort=False)["Winner"]:
            step_result.add_method_result(str(rule), winners.tolist())
        self.add_step(step_result)

    # If schema metadata had config, prefer it (more complete for aggregates)
    if config_dict:
        self._config = ResultConfig.from_dict(config_dict)

    # Restore metric accumulators if they were persisted in the metadata.
    # This is backward-compatible: files without "vote_sim:metrics" will
    # simply have empty metric accumulators (metrics not available).
    import json as _json

    metrics_raw = meta.get(b"vote_sim:metrics")
    if metrics_raw:
        try:
            payload = _json.loads(metrics_raw.decode())
            self._metrics_sum = {
                rule: np.array(arr, dtype=np.float64) for rule, arr in payload.get("sum", {}).items()
            }
            self._metrics_sum_sq = {
                rule: np.array(arr, dtype=np.float64) for rule, arr in payload.get("sum_sq", {}).items()
            }
            self._metrics_count = {rule: int(c) for rule, c in payload.get("count", {}).items()}
        except Exception:
            # Corrupted metadata — silently ignore; metrics will be unavailable.
            pass

map_rules_2d()

Project rules into 2D using Multi-Dimensional Scaling (MDS).

Uses the mean distance matrix as a precomputed dissimilarity matrix so that pairwise distances in the 2D plane approximate the original rule-to-rule distances.

Returns:

Type Description
MdsProjection

class:MdsProjection with 2D coordinates and normalized stress.

Raises:

Type Description
ValueError

If no steps have been added yet.

Source code in src/vote_simulation/models/results/series_result.py
def map_rules_2d(self) -> MdsProjection:
    """Project rules into 2D using Multi-Dimensional Scaling (MDS).

    Uses the mean distance matrix as a precomputed dissimilarity matrix
    so that pairwise distances in the 2D plane approximate the original
    rule-to-rule distances.

    Returns:
        :class:`MdsProjection` with 2D coordinates and normalized stress.

    Raises:
        ValueError: If no steps have been added yet.
    """
    if self._iteration_count == 0:
        raise ValueError("Cannot project: no steps have been added yet.")
    return _mds_project(self.mean_distance_matrix.astype(np.float64), n_components=2)

map_rules_3d()

Project rules into 3D using Multi-Dimensional Scaling (MDS).

Uses the mean distance matrix as a precomputed dissimilarity matrix so that pairwise distances in the 3D space approximate the original rule-to-rule distances.

Returns:

Type Description
MdsProjection

class:MdsProjection with 3D coordinates and normalized stress.

Raises:

Type Description
ValueError

If no steps have been added yet.

Source code in src/vote_simulation/models/results/series_result.py
def map_rules_3d(self) -> MdsProjection:
    """Project rules into 3D using Multi-Dimensional Scaling (MDS).

    Uses the mean distance matrix as a precomputed dissimilarity matrix
    so that pairwise distances in the 3D space approximate the original
    rule-to-rule distances.

    Returns:
        :class:`MdsProjection` with 3D coordinates and normalized stress.

    Raises:
        ValueError: If no steps have been added yet.
    """
    if self._iteration_count == 0:
        raise ValueError("Cannot project: no steps have been added yet.")
    return _mds_project(self.mean_distance_matrix.astype(np.float64), n_components=3)

plot_mean_distance_matrix(ax=None, folder_save_path=None, *, annotate=True, show=True)

Plot the mean distance matrix as a heatmap.

Cell values show the percentage of iterations where two rules disagreed. When multi‑config (several models / voter counts / candidate counts), the title mentions all of them.

Source code in src/vote_simulation/models/results/series_result.py
def plot_mean_distance_matrix(
    self,
    ax: Any | None = None,
    folder_save_path: str | None = None,
    *,
    annotate: bool = True,
    show: bool = True,
) -> Any:
    """Plot the mean distance matrix as a heatmap.

    Cell values show the percentage of iterations where two rules disagreed.
    When multi‑config (several models / voter counts / candidate counts),
    the title mentions all of them.
    """
    if self._iteration_count == 0:
        raise ValueError("Cannot plot: no steps have been added yet.")

    save_path: str | None = None
    if folder_save_path is not None:
        save_path = self._resolve_save_path(
            folder_save_path,
            f"{self._iteration_count}_mean_distance_matrix.png",
        )

    result = _plot_heatmap(
        self.mean_distance_matrix,
        self._rule_order,
        self._build_title("Mean rule distance matrix"),
        ax,
        annotate=annotate,
        annotation_fmt=".1f",
        colorbar_label="Mean distance (%)",
        show=show,
        save_path=save_path,
    )

    # Auto-save series parquet alongside the plot
    if save_path is not None:
        parquet_path = os.path.join(
            os.path.dirname(save_path),
            f"{self._iteration_count}_series.parquet",
        )
        self.save_to_file(parquet_path)

    return result

plot_rules_2d(ax=None, *, show=True, save_path=None)

Plot rules as labeled points in a 2D MDS projection.

Distances between points approximate mean pairwise rule distances.

Parameters:

Name Type Description Default
ax Any | None

Optional matplotlib Axes to draw on. A new figure is created when None.

None
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional path (file or directory) to save the plot.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/series_result.py
def plot_rules_2d(
    self,
    ax: Any | None = None,
    *,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Plot rules as labeled points in a 2D MDS projection.

    Distances between points approximate mean pairwise rule distances.

    Args:
        ax: Optional matplotlib Axes to draw on. A new figure is created
            when *None*.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional path (file or directory) to save the plot.

    Returns:
        The matplotlib Axes used for plotting.
    """
    projection = self.map_rules_2d()
    title = self._build_title("Rule proximity map")

    resolved: str | None = None
    if save_path is not None:
        resolved = self._resolve_save_path(save_path, f"{self._iteration_count}_rules_2d.png")

    ax = _plot_rules_2d_scatter(projection.coords, self._rule_order, title, ax, show=show, save_path=resolved)

    if resolved is not None:
        self.save_to_file(os.path.join(os.path.dirname(resolved), f"{self._iteration_count}_series.parquet"))

    return ax

plot_rules_3d(ax=None, *, show=True, save_path=None)

Plot rules as labeled points in a 3D MDS projection.

Distances between points approximate mean pairwise rule distances. The normalized MDS stress is shown on the plot.

Parameters:

Name Type Description Default
ax Any | None

Optional matplotlib Axes to draw on. A new figure is created when None.

None
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional path (file or directory) to save the plot.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/series_result.py
def plot_rules_3d(
    self,
    ax: Any | None = None,
    *,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Plot rules as labeled points in a 3D MDS projection.

    Distances between points approximate mean pairwise rule distances.
    The normalized MDS stress is shown on the plot.

    Args:
        ax: Optional matplotlib Axes to draw on. A new figure is created
            when *None*.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional path (file or directory) to save the plot.

    Returns:
        The matplotlib Axes used for plotting.
    """
    projection = self.map_rules_3d()
    title = self._build_title("Rule proximity map (3D)")
    title += f"\nMDS stress: {projection.stress:.4f}"

    resolved: str | None = None
    if save_path is not None:
        resolved = self._resolve_save_path(save_path, f"{self._iteration_count}_rules_3d.png")

    ax = _plot_rules_3d_scatter(projection.coords, self._rule_order, title, ax, show=show, save_path=resolved)

    if resolved is not None:
        self.save_to_file(os.path.join(os.path.dirname(resolved), f"{self._iteration_count}_series.parquet"))

    return ax

save_to_file(file_path)

Save the series result to a parquet file.

Per-step config is stored in columns GenModel, NVoters, NCandidates so that each row is self-describing. The aggregated series config is stored in schema metadata.

Parameters:

Name Type Description Default
file_path str

Path to the output parquet file.

required
Source code in src/vote_simulation/models/results/series_result.py
def save_to_file(self, file_path: str) -> None:
    """Save the series result to a parquet file.

    Per-step config is stored in columns ``GenModel``, ``NVoters``,
    ``NCandidates`` so that each row is self-describing.  The aggregated
    series config is stored in schema metadata.

    Args:
        file_path: Path to the output parquet file.
    """
    import pyarrow as pa
    import pyarrow.parquet as pq

    rows: list[dict[str, str | int]] = []
    for step in self.steps:
        # Flatten per-step config to single values (or empty string / 0)
        gm = ",".join(sorted(step.config.gen_models)) if step.config.gen_models else ""
        nv = ",".join(str(v) for v in sorted(step.config.n_voters)) if step.config.n_voters else ""
        nc = ",".join(str(c) for c in sorted(step.config.n_candidates)) if step.config.n_candidates else ""
        for rule, winners in step.winners_by_rule.items():
            for winner in winners:
                rows.append(
                    {
                        "DataSource": step.data_source,
                        "GenModel": gm,
                        "NVoters": nv,
                        "NCandidates": nc,
                        "Rule": rule,
                        "Winner": winner,
                    }
                )

    df = pd.DataFrame(rows)
    table = pa.Table.from_pandas(df, preserve_index=False)

    # Store aggregated config in schema metadata
    existing_meta = table.schema.metadata or {}
    config_meta = {f"vote_sim:{k}".encode(): v.encode() for k, v in self._config.to_dict().items()}

    # Persist metric accumulators so they survive a round-trip through disk.
    # Serialised as JSON under the key "vote_sim:metrics".
    import json as _json

    if self._metrics_sum:
        metrics_payload = {
            "sum": {rule: arr.tolist() for rule, arr in self._metrics_sum.items()},
            "sum_sq": {rule: arr.tolist() for rule, arr in self._metrics_sum_sq.items()},
            "count": {rule: int(c) for rule, c in self._metrics_count.items()},
        }
        metrics_meta = {b"vote_sim:metrics": _json.dumps(metrics_payload).encode()}
    else:
        metrics_meta = {}

    table = table.replace_schema_metadata({**existing_meta, **config_meta, **metrics_meta})

    os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
    pq.write_table(table, file_path)

Total result model for vote_simulation.

Aggregates multiple :class:SimulationSeriesResult instances across a parameter space defined by generative model, number of voters, and number of candidates.

Each series is uniquely keyed by (gen_model, n_voters, n_candidates). Provides filtering, scalar-metric pivots, and comparison plots.

Typical workflow::

total = SimulationTotalResult()
for model in ["UNI", "IC"]:
    for n_v in [101, 1001]:
        for n_c in [3, 14]:
            series = simulation_instance(model, n_v, n_c, rules)
            total.add_series(series)

# Fix model, compare across voters x candidates
uni = total.filter(gen_model="UNI")
uni.plot_metric_heatmap(row_param="n_voters", col_param="n_candidates")

# Side-by-side rule distance heatmaps varying candidates
total.filter(gen_model="UNI", n_voters=1001) \
     .plot_comparison_grid("n_candidates")

SeriesKey

Bases: NamedTuple

Identifies one series in the (model, voters, candidates) space.

Source code in src/vote_simulation/models/results/total_result.py
class SeriesKey(NamedTuple):
    """Identifies one series in the ``(model, voters, candidates)`` space."""

    gen_model: str
    n_voters: int
    n_candidates: int

SimulationTotalResult dataclass

Collection of series results spanning a parameter space.

Each series is uniquely keyed by (gen_model, n_voters, n_candidates). Provides filtering, scalar-metric pivots, and comparison plots.

Source code in src/vote_simulation/models/results/total_result.py
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 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
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
@dataclass(slots=True)
class SimulationTotalResult:
    """Collection of series results spanning a parameter space.

    Each series is uniquely keyed by ``(gen_model, n_voters, n_candidates)``.
    Provides filtering, scalar-metric pivots, and comparison plots.
    """

    _entries: dict[SeriesKey, SimulationSeriesResult] = field(
        default_factory=dict,
        init=False,
        repr=False,
    )

    # ------------------------------------------------------------------
    # Mutation
    # ------------------------------------------------------------------

    def add_series(self, series: SimulationSeriesResult) -> None:
        """Register a series result.

        Raises:
            ValueError: If a series with the same key is already present.
        """
        key = _extract_key(series)
        if key in self._entries:
            raise ValueError(f"Duplicate series key {key!r}. Use replace_series() to overwrite.")
        self._entries[key] = series

    def replace_series(self, series: SimulationSeriesResult) -> None:
        """Add or overwrite a series at its config key."""
        key = _extract_key(series)
        self._entries[key] = series

    # ------------------------------------------------------------------
    # Accessors
    # ------------------------------------------------------------------

    @property
    def series_count(self) -> int:
        """Number of stored series."""
        return len(self._entries)

    @property
    def keys(self) -> list[SeriesKey]:
        """Sorted list of all series keys."""
        return sorted(self._entries)

    @property
    def gen_models(self) -> list[str]:
        """Sorted distinct generative-model codes."""
        return sorted({k.gen_model for k in self._entries})

    @property
    def voter_counts(self) -> list[int]:
        """Sorted distinct voter counts."""
        return sorted({k.n_voters for k in self._entries})

    @property
    def candidate_counts(self) -> list[int]:
        """Sorted distinct candidate counts."""
        return sorted({k.n_candidates for k in self._entries})

    @property
    def rule_codes(self) -> list[str]:
        """Distinct rule codes available across stored series.

        The order is deterministic and follows the first occurrence when
        iterating over series in sorted key order.
        """
        ordered_codes: list[str] = []
        seen: set[str] = set()
        for key in sorted(self._entries):
            for code in self._entries[key].rule_codes:
                if code not in seen:
                    seen.add(code)
                    ordered_codes.append(code)
        return ordered_codes

    @property
    def rules(self) -> list[str]:
        """Backward-compatible alias for the distinct rule codes in the result."""
        return self.rule_codes

    def get_series(self, gen_model: str, n_voters: int, n_candidates: int) -> SimulationSeriesResult:
        """Retrieve a single series by its parameter triple.

        Raises:
            KeyError: If no matching series exists.
        """
        key = SeriesKey(gen_model, n_voters, n_candidates)
        try:
            return self._entries[key]
        except KeyError:
            raise KeyError(f"No series for {key!r}") from None

    def __len__(self) -> int:
        return len(self._entries)

    def __contains__(self, key: object) -> bool:
        return key in self._entries

    def __iter__(self):  # noqa: ANN204
        """Iterate over ``(key, series)`` pairs in sorted key order."""
        yield from sorted(self._entries.items())

    def __repr__(self) -> str:
        return (
            f"SimulationTotalResult("
            f"series={self.series_count}, "
            f"models={self.gen_models}, "
            f"voters={self.voter_counts}, "
            f"candidates={self.candidate_counts})"
        )

    # ------------------------------------------------------------------
    # Filtering
    # ------------------------------------------------------------------

    def filter(
        self,
        *,
        gen_model: str | None = None,
        n_voters: int | None = None,
        n_candidates: int | None = None,
    ) -> SimulationTotalResult:
        """Return a new instance containing only the matching series.

        Series objects are shared (shallow copy), not deep-copied.
        """
        result = SimulationTotalResult()
        for key, series in self._entries.items():
            if gen_model is not None and key.gen_model != gen_model:
                continue
            if n_voters is not None and key.n_voters != n_voters:
                continue
            if n_candidates is not None and key.n_candidates != n_candidates:
                continue
            result._entries[key] = series
        return result

    def filter_rules(self, rule_codes: list[str]) -> SimulationTotalResult:
        """Return a new instance where every series is restricted to *rule_codes*.

        Applies
        :meth:`~vote_simulation.models.results.series_result.SimulationSeriesResult.filter_rules`
        to each stored series.  Entries whose filtered version contains no
        rules are dropped.  Series keys are preserved.

        Args:
            rule_codes: Rule codes to keep across all series.  Unknown or
                absent codes are silently ignored per series.

        Returns:
            A new :class:`SimulationTotalResult` with filtered series.
        """
        result = SimulationTotalResult()
        for key, series in self._entries.items():
            filtered = series.filter_rules(rule_codes)
            if filtered.step_count > 0:
                result._entries[key] = filtered
        return result

    # ------------------------------------------------------------------
    # Metrics
    # ------------------------------------------------------------------

    def summary_frame(self) -> pd.DataFrame:
        """One-row-per-series DataFrame with key fields and scalar metrics.

        Columns: ``gen_model``, ``n_voters``, ``n_candidates``,
        ``step_count``, ``n_iterations``, ``mean_distance``,
        ``most_distant_rule_a``, ``most_distant_rule_b``,
        ``most_distant_distance``.
        """
        rows: list[dict[str, Any]] = []
        for key in sorted(self._entries):
            series = self._entries[key]
            r_a, r_b, dist = series.most_distant_rules
            rows.append(
                {
                    "gen_model": key.gen_model,
                    "n_voters": key.n_voters,
                    "n_candidates": key.n_candidates,
                    "step_count": series.step_count,
                    "n_iterations": series.config.n_iterations,
                    "mean_distance": series.mean_distance,
                    "most_distant_rule_a": r_a,
                    "most_distant_rule_b": r_b,
                    "most_distant_distance": dist,
                }
            )
        return pd.DataFrame(rows)

    def metrics_comparison_frame(
        self,
        metric_field: str,
        rule_code: str,
        stat: str = "mean",
    ) -> pd.DataFrame:
        """Cross-parameter table of one winner metric for one rule.

        Builds a long-form :class:`~pandas.DataFrame` with one row per
        ``(gen_model, n_voters, n_candidates)`` entry, containing the
        requested aggregated statistic for ``rule_code``.

        Parameters
        ----------
        metric_field:
            One of the fields in
            :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
            (e.g. ``"social_acceptability"``, ``"rank_mean"``).
        rule_code:
            The normalised rule code to extract (e.g. ``"COPE"``).
        stat:
            Which statistic column to read from
            :attr:`~vote_simulation.models.results.series_result.SimulationSeriesResult.metrics_summary_frame`:
            ``"mean"`` (default) or ``"std"``.

        Returns
        -------
        pd.DataFrame
            Columns: ``gen_model``, ``n_voters``, ``n_candidates``,
            ``<metric_field>_<stat>``.  Series without the requested rule's
            metrics are omitted.
        """
        col = f"{metric_field}_{stat}"
        rule_up = rule_code.strip().upper()
        rows: list[dict[str, Any]] = []
        for key in sorted(self._entries):
            series = self._entries[key]
            frame = series.metrics_summary_frame
            if frame.empty or rule_up not in frame.index or col not in frame.columns:
                continue
            rows.append(
                {
                    "gen_model": key.gen_model,
                    "n_voters": key.n_voters,
                    "n_candidates": key.n_candidates,
                    col: float(frame.loc[rule_up, col]),
                }
            )
        return pd.DataFrame(rows)

    def metrics_pivot(
        self,
        metric_field: str,
        rule_code: str,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        stat: str = "mean",
    ) -> tuple[pd.DataFrame, str]:
        """Pivot :meth:`metrics_comparison_frame` into a 2D matrix.

        Analogous to :meth:`metric_matrix` but for winner metrics instead of
        rule-distance metrics.

        Parameters
        ----------
        metric_field:
            Metric field name (see :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`).
        rule_code:
            The rule to inspect.
        row_param / col_param:
            Which of the three key parameters (``gen_model``, ``n_voters``,
            ``n_candidates``) to use as row/column axes.
        stat:
            ``"mean"`` or ``"std"``.

        Returns
        -------
        (pivot_df, fixed_description)
            The pivot DataFrame and a description of the fixed third parameter.
        """
        self._validate_axis_params(row_param, col_param)
        col = f"{metric_field}_{stat}"
        df = self.metrics_comparison_frame(metric_field, rule_code, stat=stat)
        if df.empty:
            return pd.DataFrame(), ""
        third = next(iter(_PARAM_NAMES - {row_param, col_param}))
        third_vals = {str(v) for v in df[third].unique()}
        fixed_desc = f"{third}={', '.join(sorted(third_vals))}" if third_vals else ""
        pivot = df.pivot_table(index=row_param, columns=col_param, values=col, aggfunc="mean")
        return pivot, fixed_desc

    def metric_matrix(
        self,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        metric: str = "mean_distance",
    ) -> tuple[pd.DataFrame, str]:
        """Pivot a scalar metric into a 2D matrix.

        Args:
            row_param: Key field for the row axis.
            col_param: Key field for the column axis.
            metric: Column name from :meth:`summary_frame`
                (e.g. ``"mean_distance"``, ``"most_distant_distance"``).

        Returns:
            ``(pivot_df, fixed_description)`` — the pivot DataFrame and a
            human-readable description of the fixed (third) parameter.
            If the third parameter has multiple distinct values, they are
            averaged and the description reflects this.
        """
        self._validate_axis_params(row_param, col_param)

        third = next(iter(_PARAM_NAMES - {row_param, col_param}))
        third_vals = {getattr(k, third) for k in self._entries}

        if len(third_vals) > 1:
            fixed_desc = f"{third}=avg({', '.join(str(v) for v in sorted(third_vals))})"
        else:
            fixed_desc = f"{third}={next(iter(third_vals))}" if third_vals else ""

        df = self.summary_frame()
        pivot = df.pivot_table(
            index=row_param,
            columns=col_param,
            values=metric,
            aggfunc="mean",
        )
        return pivot, fixed_desc

    def rule_pair_frame(self, rule_a: str, rule_b: str) -> pd.DataFrame:
        """Mean distance between two rules in every series.

        Returns a DataFrame with columns ``gen_model``, ``n_voters``,
        ``n_candidates``, ``distance``.
        """
        a, b = rule_a.strip().upper(), rule_b.strip().upper()
        rows: list[dict[str, Any]] = []
        for key in sorted(self._entries):
            series = self._entries[key]
            mat = series.mean_distance_matrix_frame
            if a in mat.index and b in mat.columns:
                dist = float(mat.loc[a, b])
            else:
                dist = float("nan")
            rows.append(
                {
                    "gen_model": key.gen_model,
                    "n_voters": key.n_voters,
                    "n_candidates": key.n_candidates,
                    "distance": dist,
                }
            )
        return pd.DataFrame(rows)

    def mean_distance_matrix_frame(self) -> pd.DataFrame:
        """Mean rule-distance matrix averaged across all series as a DataFrame."""
        if not self._entries:
            raise ValueError("No series in this result.")

        # Collect all rule labels (union, preserving first-seen order)
        all_rules: list[str] = []
        rule_index: dict[str, int] = {}
        for series in self._entries.values():
            for rule_code in series._rule_order:
                if rule_code not in rule_index:
                    rule_index[rule_code] = len(all_rules)
                    all_rules.append(rule_code)

        n = len(all_rules)
        acc = np.zeros((n, n), dtype=np.float64)
        counts = np.zeros((n, n), dtype=np.int64)

        for series in self._entries.values():
            mat = series.mean_distance_matrix
            if mat.size == 0:
                continue
            perm = np.array([rule_index[r] for r in series._rule_order], dtype=np.intp)
            ix = np.ix_(perm, perm)
            acc[ix] += mat.astype(np.float64)
            counts[ix] += 1

        with np.errstate(invalid="ignore"):
            avg_matrix = np.where(counts > 0, acc / counts, np.nan)

        idx = pd.Index(all_rules)
        return pd.DataFrame(avg_matrix.astype(np.float32), index=idx, columns=idx)

    def metrics_rules_matrix_frame(
        self,
        *,
        stat: str = "mean",
        metrics: list[str] | None = None,
    ) -> pd.DataFrame:
        """Winner-metric matrix with rules as rows and metric stats as columns."""
        if stat not in {"mean", "std"}:
            raise ValueError(f"Invalid stat '{stat}'. Expected 'mean' or 'std'.")

        fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)
        invalid = [m for m in fields if m not in METRIC_FIELDS]
        if invalid:
            raise ValueError(f"Unknown metric fields: {invalid}")

        all_rules: list[str] = []
        for series in self._entries.values():
            frame = series.metrics_summary_frame
            if not frame.empty:
                for rule_code in frame.index:
                    if rule_code not in all_rules:
                        all_rules.append(rule_code)

        if not all_rules:
            raise ValueError("No winner-metric data found. Check that metrics were computed during simulation.")

        n_m = len(fields)
        n_r = len(all_rules)
        sums = np.zeros((n_m, n_r), dtype=np.float64)
        counts = np.zeros((n_m, n_r), dtype=np.int64)

        for series in self._entries.values():
            frame = series.metrics_summary_frame
            if frame.empty:
                continue
            for ri, rule_code in enumerate(all_rules):
                if rule_code not in frame.index:
                    continue
                for mi, field_name in enumerate(fields):
                    col = f"{field_name}_{stat}"
                    if col not in frame.columns:
                        continue
                    val = float(frame.loc[rule_code, col])
                    if np.isnan(val):
                        continue
                    sums[mi, ri] += val
                    counts[mi, ri] += 1

        with np.errstate(invalid="ignore"):
            raw = np.where(counts > 0, sums / counts, np.nan)

        valid_mask = ~np.all(np.isnan(raw), axis=1)
        fields = [f for f, v in zip(fields, valid_mask, strict=False) if v]
        raw = raw[valid_mask]
        if len(fields) == 0:
            raise ValueError("No valid metric data to export.")

        columns = [f"{field}_{stat}" for field in fields]
        return pd.DataFrame(
            raw.T,
            index=pd.Index(np.asarray(all_rules, dtype=object), name="rule"),
            columns=pd.Index(np.asarray(columns, dtype=object)),
        )

    def export_mean_distance_matrix_csv(self, save_path: str) -> str:
        """Export :meth:`mean_distance_matrix_frame` to CSV."""
        frame = self.mean_distance_matrix_frame()
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        frame.to_csv(save_path, index=True)
        return save_path

    def export_metrics_rules_matrix_csv(
        self,
        save_path: str,
        *,
        stat: str = "mean",
        metrics: list[str] | None = None,
    ) -> str:
        """Export :meth:`metrics_rules_matrix_frame` to CSV."""
        frame = self.metrics_rules_matrix_frame(stat=stat, metrics=metrics)
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        frame.to_csv(save_path, index=True)
        return save_path

    # ------------------------------------------------------------------
    # Plotting
    # ------------------------------------------------------------------

    def plot_mean_distance_matrix(
        self,
        ax: Any | None = None,
        *,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Heatmap of the mean rule-distance matrix averaged across all series.

        Each cell ``(i, j)`` shows the average percentage of iterations where
        rules *i* and *j* disagreed, averaged over every series currently in
        the object.  Use :meth:`filter` to restrict the scope first.

        Args:
            ax: Optional matplotlib Axes. A new figure is created when *None*.
            annotate: Whether to print cell values on the heatmap.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the figure.

        Returns:
            The matplotlib Axes used for plotting.
        """
        if not self._entries:
            raise ValueError("No series in this result — nothing to plot.")

        matrix_frame = self.mean_distance_matrix_frame()
        all_rules = list(matrix_frame.index)
        avg_matrix = matrix_frame.to_numpy(dtype=np.float64)

        # Build title
        n_series = self.series_count

        def _avg_label(name: str, values: list[int], *, max_items: int = 7) -> str:
            shown = ",".join(str(v) for v in values[:max_items])
            suffix = ",..." if len(values) > max_items else ""
            return f"{name}=avg({shown}{suffix})"

        parts: list[str] = []
        if len(self.gen_models) == 1:
            parts.append(self.gen_models[0])
        if len(self.voter_counts) == 1:
            parts.append(f"n_votants={self.voter_counts[0]}")
        elif self.voter_counts:
            parts.append(_avg_label("n_votants", self.voter_counts))
        if len(self.candidate_counts) == 1:
            parts.append(f"n_candidates={self.candidate_counts[0]}")
        elif self.candidate_counts:
            parts.append(_avg_label("n_candidates", self.candidate_counts))
        desc = " · ".join(parts) if parts else f"{n_series} series averaged"
        title = f"Mean rule distance matrix\n{desc}"

        return _plot_heatmap(
            avg_matrix.astype(np.float32),
            all_rules,
            title,
            ax,
            annotate=annotate,
            annotation_fmt=".1f",
            colorbar_label="Mean distance (%)",
            show=show,
            save_path=save_path,
        )

    def plot_metric_heatmap(
        self,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        metric: str = "mean_distance",
        ax: Any | None = None,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Heatmap of a scalar metric pivoted across two parameters.

        The remaining (third) parameter must have a single distinct value
        — use :meth:`filter` first if needed.
        """
        import matplotlib.pyplot as plt

        pivot, fixed_desc = self.metric_matrix(row_param, col_param, metric=metric)
        matrix = pivot.to_numpy(dtype=np.float64)
        row_labels = [str(v) for v in pivot.index]
        col_labels = [str(v) for v in pivot.columns]

        vmin = float(np.nanmin(matrix))
        vmax = float(np.nanmax(matrix))
        margin = (vmax - vmin) * 0.1 or 1.0
        vmin = max(0.0, vmin - margin)
        vmax = vmax + margin

        fig_w = max(6.0, 1.2 * len(col_labels) + 2)
        fig_h = max(4.0, 1.0 * len(row_labels) + 2)
        if ax is None:
            _, ax = plt.subplots(
                figsize=(fig_w, fig_h),
                constrained_layout=True,
            )

        image = ax.imshow(
            matrix,
            cmap="YlOrRd",
            vmin=vmin,
            vmax=vmax,
            interpolation="nearest",
            aspect="auto",
        )
        ax.set_xticks(range(len(col_labels)), labels=col_labels)
        ax.set_yticks(range(len(row_labels)), labels=row_labels)
        ax.set_xlabel(col_param)
        ax.set_ylabel(row_param)

        title = metric.replace("_", " ").title()
        if fixed_desc:
            title += f"\n({fixed_desc})"
        ax.set_title(title, fontsize=11)

        if annotate:
            fs = max(6, min(12, int(160 / max(matrix.size, 1))))
            for i in range(matrix.shape[0]):
                for j in range(matrix.shape[1]):
                    val = matrix[i, j]
                    if not np.isnan(val):
                        ax.text(
                            j,
                            i,
                            f"{val:.1f}",
                            ha="center",
                            va="center",
                            fontsize=fs,
                            color="black",
                        )

        cbar = ax.figure.colorbar(
            image,
            ax=ax,
            fraction=0.046,
            pad=0.04,
            shrink=0.9,
        )
        cbar.set_label(metric.replace("_", " ").title())

        if save_path is not None:
            _save_figure(ax.figure, save_path)
        if show:
            plt.show()
        else:
            plt.close(cast(Any, ax.figure))

        return ax

    def plot_rule_pair_heatmap(
        self,
        rule_a: str,
        rule_b: str,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        ax: Any | None = None,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Heatmap of one rule-pair distance across two parameters."""
        import matplotlib.pyplot as plt

        self._validate_axis_params(row_param, col_param)

        df = self.rule_pair_frame(rule_a, rule_b)
        third = next(iter(_PARAM_NAMES - {row_param, col_param}))
        third_vals = df[third].unique()

        pivot = df.pivot_table(
            index=row_param,
            columns=col_param,
            values="distance",
            aggfunc="mean",
        )
        matrix = pivot.to_numpy(dtype=np.float64)
        row_labels = [str(v) for v in pivot.index]
        col_labels = [str(v) for v in pivot.columns]

        fig_w = max(6.0, 1.2 * len(col_labels) + 2)
        fig_h = max(4.0, 1.0 * len(row_labels) + 2)
        if ax is None:
            _, ax = plt.subplots(
                figsize=(fig_w, fig_h),
                constrained_layout=True,
            )

        image = ax.imshow(
            matrix,
            cmap="Reds",
            vmin=0,
            vmax=100,
            interpolation="nearest",
            aspect="auto",
        )
        ax.set_xticks(range(len(col_labels)), labels=col_labels)
        ax.set_yticks(range(len(row_labels)), labels=row_labels)
        ax.set_xlabel(col_param)
        ax.set_ylabel(row_param)

        a_up, b_up = rule_a.strip().upper(), rule_b.strip().upper()
        title = f"Distance: {a_up} \u2194 {b_up}"
        if len(third_vals) == 1:
            title += f"\n({third}={third_vals[0]})"
        elif len(third_vals) > 1:
            title += f"\n({third}=avg({', '.join(str(v) for v in sorted(third_vals))}))"
        ax.set_title(title, fontsize=11)

        if annotate:
            fs = max(8, min(12, int(160 / max(matrix.size, 1))))
            for i in range(matrix.shape[0]):
                for j in range(matrix.shape[1]):
                    val = matrix[i, j]
                    if not np.isnan(val):
                        ax.text(
                            j,
                            i,
                            f"{val:.1f}",
                            ha="center",
                            va="center",
                            fontsize=fs,
                            color="black",
                        )

        cbar = ax.figure.colorbar(
            image,
            ax=ax,
            fraction=0.046,
            pad=0.04,
            shrink=0.9,
        )
        cbar.set_label("Mean distance (%)")

        if save_path is not None:
            _save_figure(ax.figure, save_path)
        if show:
            plt.show()
        else:
            plt.close(cast(Any, ax.figure))

        return ax

    def plot_metrics_rules_matrix(
        self,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        stat: str = "mean",
        metrics: list[str] | None = None,
        annotate: bool = True,
        fmt: str = ".3f",
        cell_fontsize: int | None = None,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Heatmap with rules as columns and metrics as rows.

        Each cell shows the aggregated statistic (*stat*) for a given
        ``(metric, rule)`` pair, averaged over all series currently in the
        object (use :meth:`filter` to restrict the scope first).

        The color scale is **normalised per row** (per metric) so that the
        gradient is uniform within each row and rules can be directly compared
        regardless of the absolute scale of each metric.

        Args:
            row_param: Used only to derive a description of fixed parameters
                in the title.  Filtering is the recommended way to narrow down
                the data.
            col_param: Same as *row_param*.
            stat: ``"mean"`` (default) or ``"std"``.
            metrics: Explicit list of metric fields (rows).  When *None* all
                fields in :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
                are included.
            annotate: Whether to print raw values inside each cell.
            fmt: Format string used for annotations (e.g. ``\".3f\"``).
            cell_fontsize: Font size for cell annotations.  When *None*
                (default) the size is chosen automatically based on the number
                of rules (smaller when there are many rules).  Pass an
                explicit integer (e.g. ``8``) to override.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the figure.

        Returns:
            The matplotlib Axes used for plotting.
        """
        import matplotlib.pyplot as plt
        from matplotlib.cm import ScalarMappable
        from matplotlib.colors import Normalize

        matrix_frame = self.metrics_rules_matrix_frame(stat=stat, metrics=metrics)
        all_rules = list(matrix_frame.index)
        field_cols = list(matrix_frame.columns)
        fields = [col.removesuffix(f"_{stat}") for col in field_cols]
        raw = matrix_frame.to_numpy(dtype=np.float64).T
        n_r = len(all_rules)

        # Row-normalise: each row scaled to [0, 1]
        row_min = np.nanmin(raw, axis=1, keepdims=True)
        row_max = np.nanmax(raw, axis=1, keepdims=True)
        row_range = row_max - row_min
        row_range[row_range == 0] = 1.0  # avoid division by zero for constant rows
        normed = (raw - row_min) / row_range

        fig_w = max(10.0, 0.7 * len(fields) + 3.0)
        fig_h = max(6.0, 1.6 * n_r + 2)
        fig, ax = plt.subplots(figsize=(fig_w, fig_h), constrained_layout=True)

        ax.imshow(normed.T, cmap="YlGnBu", vmin=0, vmax=1, interpolation="nearest", aspect="auto")

        tick_fs = max(10, min(13, int(200 / max(len(fields), 1))))
        ax.set_xticks(
            range(len(fields)), labels=[f.replace("_", " ") for f in fields], rotation=45, ha="right", fontsize=tick_fs
        )
        ax.set_yticks(range(n_r), labels=all_rules, fontsize=11)
        ax.set_xlabel("Metric", fontsize=12)
        ax.set_ylabel("Rule", fontsize=12)

        # Build title from fixed params info
        n_series = self.series_count
        fixed_parts = []
        if len(self.gen_models) == 1:
            fixed_parts.append(f"model={self.gen_models[0]}")
        if len(self.voter_counts) == 1:
            fixed_parts.append(f"n_voters={self.voter_counts[0]}")
        if len(self.candidate_counts) == 1:
            fixed_parts.append(f"n_candidates={self.candidate_counts[0]}")
        desc = " · ".join(fixed_parts) if fixed_parts else f"{n_series} series averaged"
        ax.set_title(
            f"Winner metrics ({stat}) per rule\n{desc}",
            fontsize=13,
        )

        if annotate:
            fs = cell_fontsize if cell_fontsize is not None else max(12, min(12, int(120 / max(len(fields), 1))))
            for mi in range(len(fields)):
                for ri in range(n_r):
                    val = raw[mi, ri]
                    if not np.isnan(val):
                        cell_norm = normed[mi, ri]
                        txt_color = "white" if cell_norm > 0.65 else "black"
                        ax.text(mi, ri, format(val, fmt), ha="center", va="center", fontsize=fs, color=txt_color)

        cbar = fig.colorbar(
            ScalarMappable(norm=Normalize(0, 1), cmap="YlGnBu"),
            ax=ax,
            location="bottom",
            fraction=0.05,
            pad=0.05,
            shrink=0.6,
            aspect=40,
        )
        cbar.set_label("Normalised value (per metric)", fontsize=12)
        cbar.set_ticks([0, 0.5, 1])
        cbar.set_ticklabels(["min", "mid", "max"], fontsize=12)
        cbar.ax.tick_params(labelsize=12)

        if save_path is not None:
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
            fig.savefig(save_path)
        if show:
            plt.show()
        else:
            plt.close(fig)
        return ax

    def plot_winner_metric_heatmap(
        self,
        metric_field: str,
        rule_code: str,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        stat: str = "mean",
        ax: Any | None = None,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Heatmap of one winner metric for one rule, pivoted across two parameters.

        Analogous to :meth:`plot_metric_heatmap` but for
        :class:`~vote_simulation.models.rules.WinnerMetrics` fields instead of
        rule-distance metrics.

        Args:
            metric_field: One of the fields in
                :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
                (e.g. ``"social_acceptability"``, ``"rank_mean"``).
            rule_code: Normalised rule code to inspect (e.g. ``"COPE"``).
            row_param: Row axis — ``"gen_model"``, ``"n_voters"``, or
                ``"n_candidates"``.
            col_param: Column axis (same choices).
            stat: ``"mean"`` (default) or ``"std"``.
            ax: Optional matplotlib Axes.  A new figure is created when *None*.
            annotate: Whether to print cell values on the heatmap.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the figure.

        Returns:
            The matplotlib Axes used for plotting.
        """
        import matplotlib.pyplot as plt

        pivot, fixed_desc = self.metrics_pivot(
            metric_field,
            rule_code,
            row_param=row_param,
            col_param=col_param,
            stat=stat,
        )
        if pivot.empty:
            raise ValueError(
                f"No data for metric '{metric_field}' / rule '{rule_code}'. "
                "Check that metrics were computed during simulation."
            )

        # Remettre row_param/col_param dans l'ordre naturel (pas de transposition)
        matrix = pivot.to_numpy(dtype=np.float64)
        row_labels = [str(v) for v in pivot.index]
        col_labels = [str(v) for v in pivot.columns]

        vmin = float(np.nanmin(matrix))
        vmax = float(np.nanmax(matrix))
        margin = (vmax - vmin) * 0.1 or 0.01
        vmin = max(0.0, vmin - margin)
        vmax = (
            min(1.0, vmax + margin)
            if metric_field
            not in {
                "rank_mean",
                "rank_median",
                "rank_var",
                "utility_mean",
                "utility_median",
                "utility_var",
                "n_cowinners",
            }
            else vmax + margin
        )

        fig_w = max(6.0, 1.2 * len(col_labels) + 2)
        fig_h = max(4.0, 1.0 * len(row_labels) + 2)
        if ax is None:
            _, ax = plt.subplots(figsize=(fig_w, fig_h), constrained_layout=True)

        image = ax.imshow(
            matrix,
            cmap="YlGnBu",
            vmin=vmin,
            vmax=vmax,
            interpolation="nearest",
            aspect="auto",
        )
        ax.set_xticks(range(len(col_labels)), labels=col_labels)
        ax.set_yticks(range(len(row_labels)), labels=row_labels)
        ax.set_xlabel(col_param)
        ax.set_ylabel(row_param)

        rule_up = rule_code.strip().upper()
        title = f"{metric_field.replace('_', ' ').title()} ({stat}) — {rule_up}"
        if fixed_desc:
            title += f"\n({fixed_desc})"
        ax.set_title(title, fontsize=11)

        if annotate:
            fs = max(6, min(12, int(160 / max(matrix.size, 1))))
            for i in range(matrix.shape[0]):
                for j in range(matrix.shape[1]):
                    val = matrix[i, j]
                    if not np.isnan(val):
                        ax.text(j, i, f"{val:.3f}", ha="center", va="center", fontsize=fs, color="black")

        cbar = ax.figure.colorbar(image, ax=ax, fraction=0.046, pad=0.04, shrink=0.9)
        cbar.set_label(f"{metric_field.replace('_', ' ').title()} ({stat})")

        if save_path is not None:
            _save_figure(ax.figure, save_path)
        if show:
            plt.show()
        else:
            plt.close(cast(Any, ax.figure))
        return ax

    def plot_winner_metrics_grid(
        self,
        rule_code: str,
        row_param: str = "n_voters",
        col_param: str = "n_candidates",
        *,
        stat: str = "mean",
        metrics: list[str] | None = None,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Grid of heatmaps — one panel per winner metric — for a single rule.

        Iterates over every field in
        :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS` (or
        the subset given by *metrics*) and draws each as a heatmap panel,
        using the same axes as :meth:`plot_winner_metric_heatmap`.

        Args:
            rule_code: Normalised rule code to inspect (e.g. ``"COPE"``).
            row_param: Row axis — ``"gen_model"``, ``"n_voters"``, or
                ``"n_candidates"``.
            col_param: Column axis (same choices).
            stat: ``"mean"`` (default) or ``"std"``.
            metrics: Explicit list of metric fields to plot.  When *None* all
                fields in :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
                are included.
            annotate: Whether to print cell values on each panel.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the whole figure.

        Returns:
            The 2-D NumPy array of matplotlib Axes.
        """
        import math

        import matplotlib.pyplot as plt

        fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)

        # Drop metrics with no data
        available = [f for f in fields if not self.metrics_comparison_frame(f, rule_code, stat=stat).empty]
        if not available:
            raise ValueError(
                f"No winner-metric data found for rule '{rule_code}'. "
                "Check that metrics were computed during simulation."
            )

        n = len(available)
        ncols = min(4, n)
        nrows = math.ceil(n / ncols)

        fig, axes = plt.subplots(
            nrows,
            ncols,
            figsize=(5 * ncols, 4 * nrows),
            constrained_layout=True,
        )
        # Normalise axes to a flat list
        axes_flat: list[Any] = np.array(axes).flatten().tolist()

        rule_up = rule_code.strip().upper()
        fig.suptitle(
            f"Winner metrics ({stat}) — {rule_up}",
            fontsize=13,
            fontweight="bold",
        )

        for ax_i, f_name in zip(axes_flat, available, strict=False):
            try:
                self.plot_winner_metric_heatmap(
                    f_name,
                    rule_code,
                    row_param=row_param,
                    col_param=col_param,
                    stat=stat,
                    ax=ax_i,
                    annotate=annotate,
                    show=False,
                )
            except ValueError:
                ax_i.set_visible(False)

        # Hide unused axes
        for ax_i in axes_flat[len(available) :]:
            ax_i.set_visible(False)

        if save_path is not None:
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
            fig.savefig(save_path)
        if show:
            plt.show()
        else:
            plt.close(fig)
        return axes

    def map_rules_2d(self) -> MdsProjection:
        """Project rules into 2D using Multi-Dimensional Scaling (MDS).

        Uses the global mean distance matrix (averaged over all series) as a
        precomputed dissimilarity matrix.

        Returns:
            :class:`MdsProjection` with 2D coordinates and normalized stress.

        Raises:
            ValueError: If no series have been added yet.
        """
        if not self._entries:
            raise ValueError("No series in this result.")
        matrix = self.mean_distance_matrix_frame().to_numpy(dtype=np.float64)
        return _mds_project(matrix, n_components=2)

    def map_rules_3d(self) -> MdsProjection:
        """Project rules into 3D using Multi-Dimensional Scaling (MDS).

        Uses the global mean distance matrix (averaged over all series) as a
        precomputed dissimilarity matrix.

        Returns:
            :class:`MdsProjection` with 3D coordinates and normalized stress.

        Raises:
            ValueError: If no series have been added yet.
        """
        if not self._entries:
            raise ValueError("No series in this result.")
        matrix = self.mean_distance_matrix_frame().to_numpy(dtype=np.float64)
        return _mds_project(matrix, n_components=3)

    def plot_rules_2d(
        self,
        ax: Any | None = None,
        *,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Plot rules as labeled points in a 2D MDS projection.

        Distances between points approximate the global mean pairwise rule
        distances, averaged over all series in this result.  Use
        :meth:`filter` to restrict the scope first.

        Args:
            ax: Optional matplotlib Axes. A new figure is created when *None*.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the figure.

        Returns:
            The matplotlib Axes used for plotting.
        """
        if not self._entries:
            raise ValueError("No series in this result — nothing to plot.")
        projection = self.map_rules_2d()
        labels = list(self.mean_distance_matrix_frame().index)
        desc = self._build_plot_desc()
        title = f"Rule proximity map\n{desc}"
        if save_path is not None:
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        return _plot_rules_2d_scatter(projection.coords, labels, title, ax, show=show, save_path=save_path)

    def plot_rules_3d(
        self,
        ax: Any | None = None,
        *,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Plot rules as labeled points in a 3D MDS projection.

        Distances between points approximate the global mean pairwise rule
        distances, averaged over all series in this result.  Use
        :meth:`filter` to restrict the scope first.

        Args:
            ax: Optional matplotlib 3D Axes. A new figure is created when *None*.
            show: Whether to call ``plt.show()`` at the end.
            save_path: Optional file path to save the figure.

        Returns:
            The matplotlib Axes used for plotting.
        """
        if not self._entries:
            raise ValueError("No series in this result — nothing to plot.")
        projection = self.map_rules_3d()
        labels = list(self.mean_distance_matrix_frame().index)
        desc = self._build_plot_desc()
        title = f"Rule proximity map (3D)\n{desc}\nMDS stress: {projection.stress:.4f}"
        if save_path is not None:
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        return _plot_rules_3d_scatter(projection.coords, labels, title, ax, show=show, save_path=save_path)

    def plot_comparison_grid(
        self,
        vary_param: str = "n_candidates",
        *,
        annotate: bool = True,
        show: bool = True,
        save_path: str | None = None,
    ) -> Any:
        """Side-by-side rule-distance heatmaps, one per value of *vary_param*.

        The other two parameters must each have a single distinct value
        — use :meth:`filter` first.

        Example::

            total.filter(gen_model="UNI", n_voters=1001) \\
                 .plot_comparison_grid("n_candidates")
        """
        import matplotlib.pyplot as plt

        if vary_param not in _PARAM_NAMES:
            raise ValueError(f"Invalid param '{vary_param}'. Choose from {sorted(_PARAM_NAMES)}")

        fixed_params = _PARAM_NAMES - {vary_param}

        vary_values = sorted({getattr(k, vary_param) for k in self._entries})
        n = len(vary_values)
        if n == 0:
            raise ValueError("No series to plot.")

        fig, axes = plt.subplots(
            1,
            n,
            figsize=(6 * n + 1, 6),
            constrained_layout=True,
        )
        if n == 1:
            axes = [axes]

        for ax_i, val in zip(axes, vary_values, strict=True):
            matching = [s for k, s in self._entries.items() if getattr(k, vary_param) == val]
            if not matching:
                continue
            # Average distance matrices when multiple series match
            avg_matrix = np.mean(
                np.stack([s.mean_distance_matrix for s in matching]),
                axis=0,
            )
            labels = matching[0]._rule_order
            subtitle = f"{vary_param}={val}"
            if len(matching) > 1:
                subtitle += f" (avg. {len(matching)})"
            _plot_heatmap(
                avg_matrix,
                labels,
                subtitle,
                ax=ax_i,
                annotate=annotate,
                annotation_fmt=".1f",
                colorbar_label="Mean distance (%)",
                show=False,
            )

        # Build description of fixed parameters
        fixed_parts: list[str] = []
        for p in sorted(fixed_params):
            vals = sorted({getattr(k, p) for k in self._entries}, key=str)
            if len(vals) == 1:
                fixed_parts.append(f"{p}={vals[0]}")
            else:
                fixed_parts.append(f"{p}: averaged")
        fixed_desc = " \u00b7 ".join(fixed_parts)

        fig.suptitle(
            f"Rule distance comparison\n{fixed_desc}",
            fontsize=13,
        )

        if save_path is not None:
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
            fig.savefig(save_path)
        if show:
            plt.show()
        else:
            plt.close(fig)

        return axes

    # ------------------------------------------------------------------
    # Persistence
    # ------------------------------------------------------------------

    def save_to_dir(self, dir_path: str) -> None:
        """Persist every series as ``<label>.parquet`` inside *dir_path*."""
        os.makedirs(dir_path, exist_ok=True)
        for _key, series in self._entries.items():
            filename = f"{series.config.label}.parquet"
            series.save_to_file(os.path.join(dir_path, filename))

    @classmethod
    def load_from_dir(cls, dir_path: str) -> SimulationTotalResult:
        """Reconstruct a :class:`SimulationTotalResult` from a folder of parquet files.

        Each ``.parquet`` file is loaded as a :class:`SimulationSeriesResult`
        and registered via :meth:`add_series`.
        """
        import glob as _glob

        total = cls()
        paths = sorted(_glob.glob(os.path.join(dir_path, "*.parquet")))
        if not paths:
            raise ValueError(f"No .parquet files found in {dir_path!r}")
        for path in paths:
            series = SimulationSeriesResult()
            series.load_from_file(path)
            total.add_series(series)
        return total

    @staticmethod
    def delete_dir(dir_path: str) -> bool:
        """Remove a saved total-result directory.

        Returns ``True`` if the directory existed and was deleted.
        """
        import shutil

        try:
            shutil.rmtree(dir_path)
            return True
        except FileNotFoundError:
            return False

    # Private helpers

    def _build_plot_desc(self) -> str:
        """Build a human-readable description of current parameter values for plot titles."""

        def _avg_label(name: str, values: list[int], *, max_items: int = 7) -> str:
            shown = ",".join(str(v) for v in values[:max_items])
            suffix = ",..." if len(values) > max_items else ""
            return f"{name}=avg({shown}{suffix})"

        parts: list[str] = []
        if len(self.gen_models) == 1:
            parts.append(self.gen_models[0])
        if len(self.voter_counts) == 1:
            parts.append(f"n_votants={self.voter_counts[0]}")
        elif self.voter_counts:
            parts.append(_avg_label("n_votants", self.voter_counts))
        if len(self.candidate_counts) == 1:
            parts.append(f"n_candidates={self.candidate_counts[0]}")
        elif self.candidate_counts:
            parts.append(_avg_label("n_candidates", self.candidate_counts))
        return " \u00b7 ".join(parts) if parts else f"{self.series_count} series averaged"

    @staticmethod
    def _validate_axis_params(row_param: str, col_param: str) -> None:
        """Ensure *row_param* and *col_param* are valid and distinct."""
        if row_param not in _PARAM_NAMES:
            raise ValueError(f"Invalid row_param '{row_param}'. Choose from {sorted(_PARAM_NAMES)}")
        if col_param not in _PARAM_NAMES:
            raise ValueError(f"Invalid col_param '{col_param}'. Choose from {sorted(_PARAM_NAMES)}")
        if row_param == col_param:
            raise ValueError("row_param and col_param must be different.")

candidate_counts property

Sorted distinct candidate counts.

gen_models property

Sorted distinct generative-model codes.

keys property

Sorted list of all series keys.

rule_codes property

Distinct rule codes available across stored series.

The order is deterministic and follows the first occurrence when iterating over series in sorted key order.

rules property

Backward-compatible alias for the distinct rule codes in the result.

series_count property

Number of stored series.

voter_counts property

Sorted distinct voter counts.

__iter__()

Iterate over (key, series) pairs in sorted key order.

Source code in src/vote_simulation/models/results/total_result.py
def __iter__(self):  # noqa: ANN204
    """Iterate over ``(key, series)`` pairs in sorted key order."""
    yield from sorted(self._entries.items())

add_series(series)

Register a series result.

Raises:

Type Description
ValueError

If a series with the same key is already present.

Source code in src/vote_simulation/models/results/total_result.py
def add_series(self, series: SimulationSeriesResult) -> None:
    """Register a series result.

    Raises:
        ValueError: If a series with the same key is already present.
    """
    key = _extract_key(series)
    if key in self._entries:
        raise ValueError(f"Duplicate series key {key!r}. Use replace_series() to overwrite.")
    self._entries[key] = series

delete_dir(dir_path) staticmethod

Remove a saved total-result directory.

Returns True if the directory existed and was deleted.

Source code in src/vote_simulation/models/results/total_result.py
@staticmethod
def delete_dir(dir_path: str) -> bool:
    """Remove a saved total-result directory.

    Returns ``True`` if the directory existed and was deleted.
    """
    import shutil

    try:
        shutil.rmtree(dir_path)
        return True
    except FileNotFoundError:
        return False

export_mean_distance_matrix_csv(save_path)

Export :meth:mean_distance_matrix_frame to CSV.

Source code in src/vote_simulation/models/results/total_result.py
def export_mean_distance_matrix_csv(self, save_path: str) -> str:
    """Export :meth:`mean_distance_matrix_frame` to CSV."""
    frame = self.mean_distance_matrix_frame()
    os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
    frame.to_csv(save_path, index=True)
    return save_path

export_metrics_rules_matrix_csv(save_path, *, stat='mean', metrics=None)

Export :meth:metrics_rules_matrix_frame to CSV.

Source code in src/vote_simulation/models/results/total_result.py
def export_metrics_rules_matrix_csv(
    self,
    save_path: str,
    *,
    stat: str = "mean",
    metrics: list[str] | None = None,
) -> str:
    """Export :meth:`metrics_rules_matrix_frame` to CSV."""
    frame = self.metrics_rules_matrix_frame(stat=stat, metrics=metrics)
    os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
    frame.to_csv(save_path, index=True)
    return save_path

filter(*, gen_model=None, n_voters=None, n_candidates=None)

Return a new instance containing only the matching series.

Series objects are shared (shallow copy), not deep-copied.

Source code in src/vote_simulation/models/results/total_result.py
def filter(
    self,
    *,
    gen_model: str | None = None,
    n_voters: int | None = None,
    n_candidates: int | None = None,
) -> SimulationTotalResult:
    """Return a new instance containing only the matching series.

    Series objects are shared (shallow copy), not deep-copied.
    """
    result = SimulationTotalResult()
    for key, series in self._entries.items():
        if gen_model is not None and key.gen_model != gen_model:
            continue
        if n_voters is not None and key.n_voters != n_voters:
            continue
        if n_candidates is not None and key.n_candidates != n_candidates:
            continue
        result._entries[key] = series
    return result

filter_rules(rule_codes)

Return a new instance where every series is restricted to rule_codes.

Applies :meth:~vote_simulation.models.results.series_result.SimulationSeriesResult.filter_rules to each stored series. Entries whose filtered version contains no rules are dropped. Series keys are preserved.

Parameters:

Name Type Description Default
rule_codes list[str]

Rule codes to keep across all series. Unknown or absent codes are silently ignored per series.

required

Returns:

Type Description
SimulationTotalResult

A new :class:SimulationTotalResult with filtered series.

Source code in src/vote_simulation/models/results/total_result.py
def filter_rules(self, rule_codes: list[str]) -> SimulationTotalResult:
    """Return a new instance where every series is restricted to *rule_codes*.

    Applies
    :meth:`~vote_simulation.models.results.series_result.SimulationSeriesResult.filter_rules`
    to each stored series.  Entries whose filtered version contains no
    rules are dropped.  Series keys are preserved.

    Args:
        rule_codes: Rule codes to keep across all series.  Unknown or
            absent codes are silently ignored per series.

    Returns:
        A new :class:`SimulationTotalResult` with filtered series.
    """
    result = SimulationTotalResult()
    for key, series in self._entries.items():
        filtered = series.filter_rules(rule_codes)
        if filtered.step_count > 0:
            result._entries[key] = filtered
    return result

get_series(gen_model, n_voters, n_candidates)

Retrieve a single series by its parameter triple.

Raises:

Type Description
KeyError

If no matching series exists.

Source code in src/vote_simulation/models/results/total_result.py
def get_series(self, gen_model: str, n_voters: int, n_candidates: int) -> SimulationSeriesResult:
    """Retrieve a single series by its parameter triple.

    Raises:
        KeyError: If no matching series exists.
    """
    key = SeriesKey(gen_model, n_voters, n_candidates)
    try:
        return self._entries[key]
    except KeyError:
        raise KeyError(f"No series for {key!r}") from None

load_from_dir(dir_path) classmethod

Reconstruct a :class:SimulationTotalResult from a folder of parquet files.

Each .parquet file is loaded as a :class:SimulationSeriesResult and registered via :meth:add_series.

Source code in src/vote_simulation/models/results/total_result.py
@classmethod
def load_from_dir(cls, dir_path: str) -> SimulationTotalResult:
    """Reconstruct a :class:`SimulationTotalResult` from a folder of parquet files.

    Each ``.parquet`` file is loaded as a :class:`SimulationSeriesResult`
    and registered via :meth:`add_series`.
    """
    import glob as _glob

    total = cls()
    paths = sorted(_glob.glob(os.path.join(dir_path, "*.parquet")))
    if not paths:
        raise ValueError(f"No .parquet files found in {dir_path!r}")
    for path in paths:
        series = SimulationSeriesResult()
        series.load_from_file(path)
        total.add_series(series)
    return total

map_rules_2d()

Project rules into 2D using Multi-Dimensional Scaling (MDS).

Uses the global mean distance matrix (averaged over all series) as a precomputed dissimilarity matrix.

Returns:

Type Description
MdsProjection

class:MdsProjection with 2D coordinates and normalized stress.

Raises:

Type Description
ValueError

If no series have been added yet.

Source code in src/vote_simulation/models/results/total_result.py
def map_rules_2d(self) -> MdsProjection:
    """Project rules into 2D using Multi-Dimensional Scaling (MDS).

    Uses the global mean distance matrix (averaged over all series) as a
    precomputed dissimilarity matrix.

    Returns:
        :class:`MdsProjection` with 2D coordinates and normalized stress.

    Raises:
        ValueError: If no series have been added yet.
    """
    if not self._entries:
        raise ValueError("No series in this result.")
    matrix = self.mean_distance_matrix_frame().to_numpy(dtype=np.float64)
    return _mds_project(matrix, n_components=2)

map_rules_3d()

Project rules into 3D using Multi-Dimensional Scaling (MDS).

Uses the global mean distance matrix (averaged over all series) as a precomputed dissimilarity matrix.

Returns:

Type Description
MdsProjection

class:MdsProjection with 3D coordinates and normalized stress.

Raises:

Type Description
ValueError

If no series have been added yet.

Source code in src/vote_simulation/models/results/total_result.py
def map_rules_3d(self) -> MdsProjection:
    """Project rules into 3D using Multi-Dimensional Scaling (MDS).

    Uses the global mean distance matrix (averaged over all series) as a
    precomputed dissimilarity matrix.

    Returns:
        :class:`MdsProjection` with 3D coordinates and normalized stress.

    Raises:
        ValueError: If no series have been added yet.
    """
    if not self._entries:
        raise ValueError("No series in this result.")
    matrix = self.mean_distance_matrix_frame().to_numpy(dtype=np.float64)
    return _mds_project(matrix, n_components=3)

mean_distance_matrix_frame()

Mean rule-distance matrix averaged across all series as a DataFrame.

Source code in src/vote_simulation/models/results/total_result.py
def mean_distance_matrix_frame(self) -> pd.DataFrame:
    """Mean rule-distance matrix averaged across all series as a DataFrame."""
    if not self._entries:
        raise ValueError("No series in this result.")

    # Collect all rule labels (union, preserving first-seen order)
    all_rules: list[str] = []
    rule_index: dict[str, int] = {}
    for series in self._entries.values():
        for rule_code in series._rule_order:
            if rule_code not in rule_index:
                rule_index[rule_code] = len(all_rules)
                all_rules.append(rule_code)

    n = len(all_rules)
    acc = np.zeros((n, n), dtype=np.float64)
    counts = np.zeros((n, n), dtype=np.int64)

    for series in self._entries.values():
        mat = series.mean_distance_matrix
        if mat.size == 0:
            continue
        perm = np.array([rule_index[r] for r in series._rule_order], dtype=np.intp)
        ix = np.ix_(perm, perm)
        acc[ix] += mat.astype(np.float64)
        counts[ix] += 1

    with np.errstate(invalid="ignore"):
        avg_matrix = np.where(counts > 0, acc / counts, np.nan)

    idx = pd.Index(all_rules)
    return pd.DataFrame(avg_matrix.astype(np.float32), index=idx, columns=idx)

metric_matrix(row_param='n_voters', col_param='n_candidates', *, metric='mean_distance')

Pivot a scalar metric into a 2D matrix.

Parameters:

Name Type Description Default
row_param str

Key field for the row axis.

'n_voters'
col_param str

Key field for the column axis.

'n_candidates'
metric str

Column name from :meth:summary_frame (e.g. "mean_distance", "most_distant_distance").

'mean_distance'

Returns:

Type Description
DataFrame

(pivot_df, fixed_description) — the pivot DataFrame and a

str

human-readable description of the fixed (third) parameter.

tuple[DataFrame, str]

If the third parameter has multiple distinct values, they are

tuple[DataFrame, str]

averaged and the description reflects this.

Source code in src/vote_simulation/models/results/total_result.py
def metric_matrix(
    self,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    metric: str = "mean_distance",
) -> tuple[pd.DataFrame, str]:
    """Pivot a scalar metric into a 2D matrix.

    Args:
        row_param: Key field for the row axis.
        col_param: Key field for the column axis.
        metric: Column name from :meth:`summary_frame`
            (e.g. ``"mean_distance"``, ``"most_distant_distance"``).

    Returns:
        ``(pivot_df, fixed_description)`` — the pivot DataFrame and a
        human-readable description of the fixed (third) parameter.
        If the third parameter has multiple distinct values, they are
        averaged and the description reflects this.
    """
    self._validate_axis_params(row_param, col_param)

    third = next(iter(_PARAM_NAMES - {row_param, col_param}))
    third_vals = {getattr(k, third) for k in self._entries}

    if len(third_vals) > 1:
        fixed_desc = f"{third}=avg({', '.join(str(v) for v in sorted(third_vals))})"
    else:
        fixed_desc = f"{third}={next(iter(third_vals))}" if third_vals else ""

    df = self.summary_frame()
    pivot = df.pivot_table(
        index=row_param,
        columns=col_param,
        values=metric,
        aggfunc="mean",
    )
    return pivot, fixed_desc

metrics_comparison_frame(metric_field, rule_code, stat='mean')

Cross-parameter table of one winner metric for one rule.

Builds a long-form :class:~pandas.DataFrame with one row per (gen_model, n_voters, n_candidates) entry, containing the requested aggregated statistic for rule_code.

Parameters

metric_field: One of the fields in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS (e.g. "social_acceptability", "rank_mean"). rule_code: The normalised rule code to extract (e.g. "COPE"). stat: Which statistic column to read from :attr:~vote_simulation.models.results.series_result.SimulationSeriesResult.metrics_summary_frame: "mean" (default) or "std".

Returns

pd.DataFrame Columns: gen_model, n_voters, n_candidates, <metric_field>_<stat>. Series without the requested rule's metrics are omitted.

Source code in src/vote_simulation/models/results/total_result.py
def metrics_comparison_frame(
    self,
    metric_field: str,
    rule_code: str,
    stat: str = "mean",
) -> pd.DataFrame:
    """Cross-parameter table of one winner metric for one rule.

    Builds a long-form :class:`~pandas.DataFrame` with one row per
    ``(gen_model, n_voters, n_candidates)`` entry, containing the
    requested aggregated statistic for ``rule_code``.

    Parameters
    ----------
    metric_field:
        One of the fields in
        :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
        (e.g. ``"social_acceptability"``, ``"rank_mean"``).
    rule_code:
        The normalised rule code to extract (e.g. ``"COPE"``).
    stat:
        Which statistic column to read from
        :attr:`~vote_simulation.models.results.series_result.SimulationSeriesResult.metrics_summary_frame`:
        ``"mean"`` (default) or ``"std"``.

    Returns
    -------
    pd.DataFrame
        Columns: ``gen_model``, ``n_voters``, ``n_candidates``,
        ``<metric_field>_<stat>``.  Series without the requested rule's
        metrics are omitted.
    """
    col = f"{metric_field}_{stat}"
    rule_up = rule_code.strip().upper()
    rows: list[dict[str, Any]] = []
    for key in sorted(self._entries):
        series = self._entries[key]
        frame = series.metrics_summary_frame
        if frame.empty or rule_up not in frame.index or col not in frame.columns:
            continue
        rows.append(
            {
                "gen_model": key.gen_model,
                "n_voters": key.n_voters,
                "n_candidates": key.n_candidates,
                col: float(frame.loc[rule_up, col]),
            }
        )
    return pd.DataFrame(rows)

metrics_pivot(metric_field, rule_code, row_param='n_voters', col_param='n_candidates', stat='mean')

Pivot :meth:metrics_comparison_frame into a 2D matrix.

Analogous to :meth:metric_matrix but for winner metrics instead of rule-distance metrics.

Parameters

metric_field: Metric field name (see :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS). rule_code: The rule to inspect. row_param / col_param: Which of the three key parameters (gen_model, n_voters, n_candidates) to use as row/column axes. stat: "mean" or "std".

Returns

(pivot_df, fixed_description) The pivot DataFrame and a description of the fixed third parameter.

Source code in src/vote_simulation/models/results/total_result.py
def metrics_pivot(
    self,
    metric_field: str,
    rule_code: str,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    stat: str = "mean",
) -> tuple[pd.DataFrame, str]:
    """Pivot :meth:`metrics_comparison_frame` into a 2D matrix.

    Analogous to :meth:`metric_matrix` but for winner metrics instead of
    rule-distance metrics.

    Parameters
    ----------
    metric_field:
        Metric field name (see :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`).
    rule_code:
        The rule to inspect.
    row_param / col_param:
        Which of the three key parameters (``gen_model``, ``n_voters``,
        ``n_candidates``) to use as row/column axes.
    stat:
        ``"mean"`` or ``"std"``.

    Returns
    -------
    (pivot_df, fixed_description)
        The pivot DataFrame and a description of the fixed third parameter.
    """
    self._validate_axis_params(row_param, col_param)
    col = f"{metric_field}_{stat}"
    df = self.metrics_comparison_frame(metric_field, rule_code, stat=stat)
    if df.empty:
        return pd.DataFrame(), ""
    third = next(iter(_PARAM_NAMES - {row_param, col_param}))
    third_vals = {str(v) for v in df[third].unique()}
    fixed_desc = f"{third}={', '.join(sorted(third_vals))}" if third_vals else ""
    pivot = df.pivot_table(index=row_param, columns=col_param, values=col, aggfunc="mean")
    return pivot, fixed_desc

metrics_rules_matrix_frame(*, stat='mean', metrics=None)

Winner-metric matrix with rules as rows and metric stats as columns.

Source code in src/vote_simulation/models/results/total_result.py
def metrics_rules_matrix_frame(
    self,
    *,
    stat: str = "mean",
    metrics: list[str] | None = None,
) -> pd.DataFrame:
    """Winner-metric matrix with rules as rows and metric stats as columns."""
    if stat not in {"mean", "std"}:
        raise ValueError(f"Invalid stat '{stat}'. Expected 'mean' or 'std'.")

    fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)
    invalid = [m for m in fields if m not in METRIC_FIELDS]
    if invalid:
        raise ValueError(f"Unknown metric fields: {invalid}")

    all_rules: list[str] = []
    for series in self._entries.values():
        frame = series.metrics_summary_frame
        if not frame.empty:
            for rule_code in frame.index:
                if rule_code not in all_rules:
                    all_rules.append(rule_code)

    if not all_rules:
        raise ValueError("No winner-metric data found. Check that metrics were computed during simulation.")

    n_m = len(fields)
    n_r = len(all_rules)
    sums = np.zeros((n_m, n_r), dtype=np.float64)
    counts = np.zeros((n_m, n_r), dtype=np.int64)

    for series in self._entries.values():
        frame = series.metrics_summary_frame
        if frame.empty:
            continue
        for ri, rule_code in enumerate(all_rules):
            if rule_code not in frame.index:
                continue
            for mi, field_name in enumerate(fields):
                col = f"{field_name}_{stat}"
                if col not in frame.columns:
                    continue
                val = float(frame.loc[rule_code, col])
                if np.isnan(val):
                    continue
                sums[mi, ri] += val
                counts[mi, ri] += 1

    with np.errstate(invalid="ignore"):
        raw = np.where(counts > 0, sums / counts, np.nan)

    valid_mask = ~np.all(np.isnan(raw), axis=1)
    fields = [f for f, v in zip(fields, valid_mask, strict=False) if v]
    raw = raw[valid_mask]
    if len(fields) == 0:
        raise ValueError("No valid metric data to export.")

    columns = [f"{field}_{stat}" for field in fields]
    return pd.DataFrame(
        raw.T,
        index=pd.Index(np.asarray(all_rules, dtype=object), name="rule"),
        columns=pd.Index(np.asarray(columns, dtype=object)),
    )

plot_comparison_grid(vary_param='n_candidates', *, annotate=True, show=True, save_path=None)

Side-by-side rule-distance heatmaps, one per value of vary_param.

The other two parameters must each have a single distinct value — use :meth:filter first.

Example::

total.filter(gen_model="UNI", n_voters=1001) \
     .plot_comparison_grid("n_candidates")
Source code in src/vote_simulation/models/results/total_result.py
def plot_comparison_grid(
    self,
    vary_param: str = "n_candidates",
    *,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Side-by-side rule-distance heatmaps, one per value of *vary_param*.

    The other two parameters must each have a single distinct value
    — use :meth:`filter` first.

    Example::

        total.filter(gen_model="UNI", n_voters=1001) \\
             .plot_comparison_grid("n_candidates")
    """
    import matplotlib.pyplot as plt

    if vary_param not in _PARAM_NAMES:
        raise ValueError(f"Invalid param '{vary_param}'. Choose from {sorted(_PARAM_NAMES)}")

    fixed_params = _PARAM_NAMES - {vary_param}

    vary_values = sorted({getattr(k, vary_param) for k in self._entries})
    n = len(vary_values)
    if n == 0:
        raise ValueError("No series to plot.")

    fig, axes = plt.subplots(
        1,
        n,
        figsize=(6 * n + 1, 6),
        constrained_layout=True,
    )
    if n == 1:
        axes = [axes]

    for ax_i, val in zip(axes, vary_values, strict=True):
        matching = [s for k, s in self._entries.items() if getattr(k, vary_param) == val]
        if not matching:
            continue
        # Average distance matrices when multiple series match
        avg_matrix = np.mean(
            np.stack([s.mean_distance_matrix for s in matching]),
            axis=0,
        )
        labels = matching[0]._rule_order
        subtitle = f"{vary_param}={val}"
        if len(matching) > 1:
            subtitle += f" (avg. {len(matching)})"
        _plot_heatmap(
            avg_matrix,
            labels,
            subtitle,
            ax=ax_i,
            annotate=annotate,
            annotation_fmt=".1f",
            colorbar_label="Mean distance (%)",
            show=False,
        )

    # Build description of fixed parameters
    fixed_parts: list[str] = []
    for p in sorted(fixed_params):
        vals = sorted({getattr(k, p) for k in self._entries}, key=str)
        if len(vals) == 1:
            fixed_parts.append(f"{p}={vals[0]}")
        else:
            fixed_parts.append(f"{p}: averaged")
    fixed_desc = " \u00b7 ".join(fixed_parts)

    fig.suptitle(
        f"Rule distance comparison\n{fixed_desc}",
        fontsize=13,
    )

    if save_path is not None:
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        fig.savefig(save_path)
    if show:
        plt.show()
    else:
        plt.close(fig)

    return axes

plot_mean_distance_matrix(ax=None, *, annotate=True, show=True, save_path=None)

Heatmap of the mean rule-distance matrix averaged across all series.

Each cell (i, j) shows the average percentage of iterations where rules i and j disagreed, averaged over every series currently in the object. Use :meth:filter to restrict the scope first.

Parameters:

Name Type Description Default
ax Any | None

Optional matplotlib Axes. A new figure is created when None.

None
annotate bool

Whether to print cell values on the heatmap.

True
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the figure.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/total_result.py
def plot_mean_distance_matrix(
    self,
    ax: Any | None = None,
    *,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Heatmap of the mean rule-distance matrix averaged across all series.

    Each cell ``(i, j)`` shows the average percentage of iterations where
    rules *i* and *j* disagreed, averaged over every series currently in
    the object.  Use :meth:`filter` to restrict the scope first.

    Args:
        ax: Optional matplotlib Axes. A new figure is created when *None*.
        annotate: Whether to print cell values on the heatmap.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the figure.

    Returns:
        The matplotlib Axes used for plotting.
    """
    if not self._entries:
        raise ValueError("No series in this result — nothing to plot.")

    matrix_frame = self.mean_distance_matrix_frame()
    all_rules = list(matrix_frame.index)
    avg_matrix = matrix_frame.to_numpy(dtype=np.float64)

    # Build title
    n_series = self.series_count

    def _avg_label(name: str, values: list[int], *, max_items: int = 7) -> str:
        shown = ",".join(str(v) for v in values[:max_items])
        suffix = ",..." if len(values) > max_items else ""
        return f"{name}=avg({shown}{suffix})"

    parts: list[str] = []
    if len(self.gen_models) == 1:
        parts.append(self.gen_models[0])
    if len(self.voter_counts) == 1:
        parts.append(f"n_votants={self.voter_counts[0]}")
    elif self.voter_counts:
        parts.append(_avg_label("n_votants", self.voter_counts))
    if len(self.candidate_counts) == 1:
        parts.append(f"n_candidates={self.candidate_counts[0]}")
    elif self.candidate_counts:
        parts.append(_avg_label("n_candidates", self.candidate_counts))
    desc = " · ".join(parts) if parts else f"{n_series} series averaged"
    title = f"Mean rule distance matrix\n{desc}"

    return _plot_heatmap(
        avg_matrix.astype(np.float32),
        all_rules,
        title,
        ax,
        annotate=annotate,
        annotation_fmt=".1f",
        colorbar_label="Mean distance (%)",
        show=show,
        save_path=save_path,
    )

plot_metric_heatmap(row_param='n_voters', col_param='n_candidates', *, metric='mean_distance', ax=None, annotate=True, show=True, save_path=None)

Heatmap of a scalar metric pivoted across two parameters.

The remaining (third) parameter must have a single distinct value — use :meth:filter first if needed.

Source code in src/vote_simulation/models/results/total_result.py
def plot_metric_heatmap(
    self,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    metric: str = "mean_distance",
    ax: Any | None = None,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Heatmap of a scalar metric pivoted across two parameters.

    The remaining (third) parameter must have a single distinct value
    — use :meth:`filter` first if needed.
    """
    import matplotlib.pyplot as plt

    pivot, fixed_desc = self.metric_matrix(row_param, col_param, metric=metric)
    matrix = pivot.to_numpy(dtype=np.float64)
    row_labels = [str(v) for v in pivot.index]
    col_labels = [str(v) for v in pivot.columns]

    vmin = float(np.nanmin(matrix))
    vmax = float(np.nanmax(matrix))
    margin = (vmax - vmin) * 0.1 or 1.0
    vmin = max(0.0, vmin - margin)
    vmax = vmax + margin

    fig_w = max(6.0, 1.2 * len(col_labels) + 2)
    fig_h = max(4.0, 1.0 * len(row_labels) + 2)
    if ax is None:
        _, ax = plt.subplots(
            figsize=(fig_w, fig_h),
            constrained_layout=True,
        )

    image = ax.imshow(
        matrix,
        cmap="YlOrRd",
        vmin=vmin,
        vmax=vmax,
        interpolation="nearest",
        aspect="auto",
    )
    ax.set_xticks(range(len(col_labels)), labels=col_labels)
    ax.set_yticks(range(len(row_labels)), labels=row_labels)
    ax.set_xlabel(col_param)
    ax.set_ylabel(row_param)

    title = metric.replace("_", " ").title()
    if fixed_desc:
        title += f"\n({fixed_desc})"
    ax.set_title(title, fontsize=11)

    if annotate:
        fs = max(6, min(12, int(160 / max(matrix.size, 1))))
        for i in range(matrix.shape[0]):
            for j in range(matrix.shape[1]):
                val = matrix[i, j]
                if not np.isnan(val):
                    ax.text(
                        j,
                        i,
                        f"{val:.1f}",
                        ha="center",
                        va="center",
                        fontsize=fs,
                        color="black",
                    )

    cbar = ax.figure.colorbar(
        image,
        ax=ax,
        fraction=0.046,
        pad=0.04,
        shrink=0.9,
    )
    cbar.set_label(metric.replace("_", " ").title())

    if save_path is not None:
        _save_figure(ax.figure, save_path)
    if show:
        plt.show()
    else:
        plt.close(cast(Any, ax.figure))

    return ax

plot_metrics_rules_matrix(row_param='n_voters', col_param='n_candidates', *, stat='mean', metrics=None, annotate=True, fmt='.3f', cell_fontsize=None, show=True, save_path=None)

Heatmap with rules as columns and metrics as rows.

Each cell shows the aggregated statistic (stat) for a given (metric, rule) pair, averaged over all series currently in the object (use :meth:filter to restrict the scope first).

The color scale is normalised per row (per metric) so that the gradient is uniform within each row and rules can be directly compared regardless of the absolute scale of each metric.

Parameters:

Name Type Description Default
row_param str

Used only to derive a description of fixed parameters in the title. Filtering is the recommended way to narrow down the data.

'n_voters'
col_param str

Same as row_param.

'n_candidates'
stat str

"mean" (default) or "std".

'mean'
metrics list[str] | None

Explicit list of metric fields (rows). When None all fields in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS are included.

None
annotate bool

Whether to print raw values inside each cell.

True
fmt str

Format string used for annotations (e.g. ".3f").

'.3f'
cell_fontsize int | None

Font size for cell annotations. When None (default) the size is chosen automatically based on the number of rules (smaller when there are many rules). Pass an explicit integer (e.g. 8) to override.

None
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the figure.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/total_result.py
def plot_metrics_rules_matrix(
    self,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    stat: str = "mean",
    metrics: list[str] | None = None,
    annotate: bool = True,
    fmt: str = ".3f",
    cell_fontsize: int | None = None,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Heatmap with rules as columns and metrics as rows.

    Each cell shows the aggregated statistic (*stat*) for a given
    ``(metric, rule)`` pair, averaged over all series currently in the
    object (use :meth:`filter` to restrict the scope first).

    The color scale is **normalised per row** (per metric) so that the
    gradient is uniform within each row and rules can be directly compared
    regardless of the absolute scale of each metric.

    Args:
        row_param: Used only to derive a description of fixed parameters
            in the title.  Filtering is the recommended way to narrow down
            the data.
        col_param: Same as *row_param*.
        stat: ``"mean"`` (default) or ``"std"``.
        metrics: Explicit list of metric fields (rows).  When *None* all
            fields in :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
            are included.
        annotate: Whether to print raw values inside each cell.
        fmt: Format string used for annotations (e.g. ``\".3f\"``).
        cell_fontsize: Font size for cell annotations.  When *None*
            (default) the size is chosen automatically based on the number
            of rules (smaller when there are many rules).  Pass an
            explicit integer (e.g. ``8``) to override.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the figure.

    Returns:
        The matplotlib Axes used for plotting.
    """
    import matplotlib.pyplot as plt
    from matplotlib.cm import ScalarMappable
    from matplotlib.colors import Normalize

    matrix_frame = self.metrics_rules_matrix_frame(stat=stat, metrics=metrics)
    all_rules = list(matrix_frame.index)
    field_cols = list(matrix_frame.columns)
    fields = [col.removesuffix(f"_{stat}") for col in field_cols]
    raw = matrix_frame.to_numpy(dtype=np.float64).T
    n_r = len(all_rules)

    # Row-normalise: each row scaled to [0, 1]
    row_min = np.nanmin(raw, axis=1, keepdims=True)
    row_max = np.nanmax(raw, axis=1, keepdims=True)
    row_range = row_max - row_min
    row_range[row_range == 0] = 1.0  # avoid division by zero for constant rows
    normed = (raw - row_min) / row_range

    fig_w = max(10.0, 0.7 * len(fields) + 3.0)
    fig_h = max(6.0, 1.6 * n_r + 2)
    fig, ax = plt.subplots(figsize=(fig_w, fig_h), constrained_layout=True)

    ax.imshow(normed.T, cmap="YlGnBu", vmin=0, vmax=1, interpolation="nearest", aspect="auto")

    tick_fs = max(10, min(13, int(200 / max(len(fields), 1))))
    ax.set_xticks(
        range(len(fields)), labels=[f.replace("_", " ") for f in fields], rotation=45, ha="right", fontsize=tick_fs
    )
    ax.set_yticks(range(n_r), labels=all_rules, fontsize=11)
    ax.set_xlabel("Metric", fontsize=12)
    ax.set_ylabel("Rule", fontsize=12)

    # Build title from fixed params info
    n_series = self.series_count
    fixed_parts = []
    if len(self.gen_models) == 1:
        fixed_parts.append(f"model={self.gen_models[0]}")
    if len(self.voter_counts) == 1:
        fixed_parts.append(f"n_voters={self.voter_counts[0]}")
    if len(self.candidate_counts) == 1:
        fixed_parts.append(f"n_candidates={self.candidate_counts[0]}")
    desc = " · ".join(fixed_parts) if fixed_parts else f"{n_series} series averaged"
    ax.set_title(
        f"Winner metrics ({stat}) per rule\n{desc}",
        fontsize=13,
    )

    if annotate:
        fs = cell_fontsize if cell_fontsize is not None else max(12, min(12, int(120 / max(len(fields), 1))))
        for mi in range(len(fields)):
            for ri in range(n_r):
                val = raw[mi, ri]
                if not np.isnan(val):
                    cell_norm = normed[mi, ri]
                    txt_color = "white" if cell_norm > 0.65 else "black"
                    ax.text(mi, ri, format(val, fmt), ha="center", va="center", fontsize=fs, color=txt_color)

    cbar = fig.colorbar(
        ScalarMappable(norm=Normalize(0, 1), cmap="YlGnBu"),
        ax=ax,
        location="bottom",
        fraction=0.05,
        pad=0.05,
        shrink=0.6,
        aspect=40,
    )
    cbar.set_label("Normalised value (per metric)", fontsize=12)
    cbar.set_ticks([0, 0.5, 1])
    cbar.set_ticklabels(["min", "mid", "max"], fontsize=12)
    cbar.ax.tick_params(labelsize=12)

    if save_path is not None:
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        fig.savefig(save_path)
    if show:
        plt.show()
    else:
        plt.close(fig)
    return ax

plot_rule_pair_heatmap(rule_a, rule_b, row_param='n_voters', col_param='n_candidates', *, ax=None, annotate=True, show=True, save_path=None)

Heatmap of one rule-pair distance across two parameters.

Source code in src/vote_simulation/models/results/total_result.py
def plot_rule_pair_heatmap(
    self,
    rule_a: str,
    rule_b: str,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    ax: Any | None = None,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Heatmap of one rule-pair distance across two parameters."""
    import matplotlib.pyplot as plt

    self._validate_axis_params(row_param, col_param)

    df = self.rule_pair_frame(rule_a, rule_b)
    third = next(iter(_PARAM_NAMES - {row_param, col_param}))
    third_vals = df[third].unique()

    pivot = df.pivot_table(
        index=row_param,
        columns=col_param,
        values="distance",
        aggfunc="mean",
    )
    matrix = pivot.to_numpy(dtype=np.float64)
    row_labels = [str(v) for v in pivot.index]
    col_labels = [str(v) for v in pivot.columns]

    fig_w = max(6.0, 1.2 * len(col_labels) + 2)
    fig_h = max(4.0, 1.0 * len(row_labels) + 2)
    if ax is None:
        _, ax = plt.subplots(
            figsize=(fig_w, fig_h),
            constrained_layout=True,
        )

    image = ax.imshow(
        matrix,
        cmap="Reds",
        vmin=0,
        vmax=100,
        interpolation="nearest",
        aspect="auto",
    )
    ax.set_xticks(range(len(col_labels)), labels=col_labels)
    ax.set_yticks(range(len(row_labels)), labels=row_labels)
    ax.set_xlabel(col_param)
    ax.set_ylabel(row_param)

    a_up, b_up = rule_a.strip().upper(), rule_b.strip().upper()
    title = f"Distance: {a_up} \u2194 {b_up}"
    if len(third_vals) == 1:
        title += f"\n({third}={third_vals[0]})"
    elif len(third_vals) > 1:
        title += f"\n({third}=avg({', '.join(str(v) for v in sorted(third_vals))}))"
    ax.set_title(title, fontsize=11)

    if annotate:
        fs = max(8, min(12, int(160 / max(matrix.size, 1))))
        for i in range(matrix.shape[0]):
            for j in range(matrix.shape[1]):
                val = matrix[i, j]
                if not np.isnan(val):
                    ax.text(
                        j,
                        i,
                        f"{val:.1f}",
                        ha="center",
                        va="center",
                        fontsize=fs,
                        color="black",
                    )

    cbar = ax.figure.colorbar(
        image,
        ax=ax,
        fraction=0.046,
        pad=0.04,
        shrink=0.9,
    )
    cbar.set_label("Mean distance (%)")

    if save_path is not None:
        _save_figure(ax.figure, save_path)
    if show:
        plt.show()
    else:
        plt.close(cast(Any, ax.figure))

    return ax

plot_rules_2d(ax=None, *, show=True, save_path=None)

Plot rules as labeled points in a 2D MDS projection.

Distances between points approximate the global mean pairwise rule distances, averaged over all series in this result. Use :meth:filter to restrict the scope first.

Parameters:

Name Type Description Default
ax Any | None

Optional matplotlib Axes. A new figure is created when None.

None
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the figure.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/total_result.py
def plot_rules_2d(
    self,
    ax: Any | None = None,
    *,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Plot rules as labeled points in a 2D MDS projection.

    Distances between points approximate the global mean pairwise rule
    distances, averaged over all series in this result.  Use
    :meth:`filter` to restrict the scope first.

    Args:
        ax: Optional matplotlib Axes. A new figure is created when *None*.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the figure.

    Returns:
        The matplotlib Axes used for plotting.
    """
    if not self._entries:
        raise ValueError("No series in this result — nothing to plot.")
    projection = self.map_rules_2d()
    labels = list(self.mean_distance_matrix_frame().index)
    desc = self._build_plot_desc()
    title = f"Rule proximity map\n{desc}"
    if save_path is not None:
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
    return _plot_rules_2d_scatter(projection.coords, labels, title, ax, show=show, save_path=save_path)

plot_rules_3d(ax=None, *, show=True, save_path=None)

Plot rules as labeled points in a 3D MDS projection.

Distances between points approximate the global mean pairwise rule distances, averaged over all series in this result. Use :meth:filter to restrict the scope first.

Parameters:

Name Type Description Default
ax Any | None

Optional matplotlib 3D Axes. A new figure is created when None.

None
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the figure.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/total_result.py
def plot_rules_3d(
    self,
    ax: Any | None = None,
    *,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Plot rules as labeled points in a 3D MDS projection.

    Distances between points approximate the global mean pairwise rule
    distances, averaged over all series in this result.  Use
    :meth:`filter` to restrict the scope first.

    Args:
        ax: Optional matplotlib 3D Axes. A new figure is created when *None*.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the figure.

    Returns:
        The matplotlib Axes used for plotting.
    """
    if not self._entries:
        raise ValueError("No series in this result — nothing to plot.")
    projection = self.map_rules_3d()
    labels = list(self.mean_distance_matrix_frame().index)
    desc = self._build_plot_desc()
    title = f"Rule proximity map (3D)\n{desc}\nMDS stress: {projection.stress:.4f}"
    if save_path is not None:
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
    return _plot_rules_3d_scatter(projection.coords, labels, title, ax, show=show, save_path=save_path)

plot_winner_metric_heatmap(metric_field, rule_code, row_param='n_voters', col_param='n_candidates', *, stat='mean', ax=None, annotate=True, show=True, save_path=None)

Heatmap of one winner metric for one rule, pivoted across two parameters.

Analogous to :meth:plot_metric_heatmap but for :class:~vote_simulation.models.rules.WinnerMetrics fields instead of rule-distance metrics.

Parameters:

Name Type Description Default
metric_field str

One of the fields in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS (e.g. "social_acceptability", "rank_mean").

required
rule_code str

Normalised rule code to inspect (e.g. "COPE").

required
row_param str

Row axis — "gen_model", "n_voters", or "n_candidates".

'n_voters'
col_param str

Column axis (same choices).

'n_candidates'
stat str

"mean" (default) or "std".

'mean'
ax Any | None

Optional matplotlib Axes. A new figure is created when None.

None
annotate bool

Whether to print cell values on the heatmap.

True
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the figure.

None

Returns:

Type Description
Any

The matplotlib Axes used for plotting.

Source code in src/vote_simulation/models/results/total_result.py
def plot_winner_metric_heatmap(
    self,
    metric_field: str,
    rule_code: str,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    stat: str = "mean",
    ax: Any | None = None,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Heatmap of one winner metric for one rule, pivoted across two parameters.

    Analogous to :meth:`plot_metric_heatmap` but for
    :class:`~vote_simulation.models.rules.WinnerMetrics` fields instead of
    rule-distance metrics.

    Args:
        metric_field: One of the fields in
            :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
            (e.g. ``"social_acceptability"``, ``"rank_mean"``).
        rule_code: Normalised rule code to inspect (e.g. ``"COPE"``).
        row_param: Row axis — ``"gen_model"``, ``"n_voters"``, or
            ``"n_candidates"``.
        col_param: Column axis (same choices).
        stat: ``"mean"`` (default) or ``"std"``.
        ax: Optional matplotlib Axes.  A new figure is created when *None*.
        annotate: Whether to print cell values on the heatmap.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the figure.

    Returns:
        The matplotlib Axes used for plotting.
    """
    import matplotlib.pyplot as plt

    pivot, fixed_desc = self.metrics_pivot(
        metric_field,
        rule_code,
        row_param=row_param,
        col_param=col_param,
        stat=stat,
    )
    if pivot.empty:
        raise ValueError(
            f"No data for metric '{metric_field}' / rule '{rule_code}'. "
            "Check that metrics were computed during simulation."
        )

    # Remettre row_param/col_param dans l'ordre naturel (pas de transposition)
    matrix = pivot.to_numpy(dtype=np.float64)
    row_labels = [str(v) for v in pivot.index]
    col_labels = [str(v) for v in pivot.columns]

    vmin = float(np.nanmin(matrix))
    vmax = float(np.nanmax(matrix))
    margin = (vmax - vmin) * 0.1 or 0.01
    vmin = max(0.0, vmin - margin)
    vmax = (
        min(1.0, vmax + margin)
        if metric_field
        not in {
            "rank_mean",
            "rank_median",
            "rank_var",
            "utility_mean",
            "utility_median",
            "utility_var",
            "n_cowinners",
        }
        else vmax + margin
    )

    fig_w = max(6.0, 1.2 * len(col_labels) + 2)
    fig_h = max(4.0, 1.0 * len(row_labels) + 2)
    if ax is None:
        _, ax = plt.subplots(figsize=(fig_w, fig_h), constrained_layout=True)

    image = ax.imshow(
        matrix,
        cmap="YlGnBu",
        vmin=vmin,
        vmax=vmax,
        interpolation="nearest",
        aspect="auto",
    )
    ax.set_xticks(range(len(col_labels)), labels=col_labels)
    ax.set_yticks(range(len(row_labels)), labels=row_labels)
    ax.set_xlabel(col_param)
    ax.set_ylabel(row_param)

    rule_up = rule_code.strip().upper()
    title = f"{metric_field.replace('_', ' ').title()} ({stat}) — {rule_up}"
    if fixed_desc:
        title += f"\n({fixed_desc})"
    ax.set_title(title, fontsize=11)

    if annotate:
        fs = max(6, min(12, int(160 / max(matrix.size, 1))))
        for i in range(matrix.shape[0]):
            for j in range(matrix.shape[1]):
                val = matrix[i, j]
                if not np.isnan(val):
                    ax.text(j, i, f"{val:.3f}", ha="center", va="center", fontsize=fs, color="black")

    cbar = ax.figure.colorbar(image, ax=ax, fraction=0.046, pad=0.04, shrink=0.9)
    cbar.set_label(f"{metric_field.replace('_', ' ').title()} ({stat})")

    if save_path is not None:
        _save_figure(ax.figure, save_path)
    if show:
        plt.show()
    else:
        plt.close(cast(Any, ax.figure))
    return ax

plot_winner_metrics_grid(rule_code, row_param='n_voters', col_param='n_candidates', *, stat='mean', metrics=None, annotate=True, show=True, save_path=None)

Grid of heatmaps — one panel per winner metric — for a single rule.

Iterates over every field in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS (or the subset given by metrics) and draws each as a heatmap panel, using the same axes as :meth:plot_winner_metric_heatmap.

Parameters:

Name Type Description Default
rule_code str

Normalised rule code to inspect (e.g. "COPE").

required
row_param str

Row axis — "gen_model", "n_voters", or "n_candidates".

'n_voters'
col_param str

Column axis (same choices).

'n_candidates'
stat str

"mean" (default) or "std".

'mean'
metrics list[str] | None

Explicit list of metric fields to plot. When None all fields in :data:~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS are included.

None
annotate bool

Whether to print cell values on each panel.

True
show bool

Whether to call plt.show() at the end.

True
save_path str | None

Optional file path to save the whole figure.

None

Returns:

Type Description
Any

The 2-D NumPy array of matplotlib Axes.

Source code in src/vote_simulation/models/results/total_result.py
def plot_winner_metrics_grid(
    self,
    rule_code: str,
    row_param: str = "n_voters",
    col_param: str = "n_candidates",
    *,
    stat: str = "mean",
    metrics: list[str] | None = None,
    annotate: bool = True,
    show: bool = True,
    save_path: str | None = None,
) -> Any:
    """Grid of heatmaps — one panel per winner metric — for a single rule.

    Iterates over every field in
    :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS` (or
    the subset given by *metrics*) and draws each as a heatmap panel,
    using the same axes as :meth:`plot_winner_metric_heatmap`.

    Args:
        rule_code: Normalised rule code to inspect (e.g. ``"COPE"``).
        row_param: Row axis — ``"gen_model"``, ``"n_voters"``, or
            ``"n_candidates"``.
        col_param: Column axis (same choices).
        stat: ``"mean"`` (default) or ``"std"``.
        metrics: Explicit list of metric fields to plot.  When *None* all
            fields in :data:`~vote_simulation.models.rules.winner_metrics.METRIC_FIELDS`
            are included.
        annotate: Whether to print cell values on each panel.
        show: Whether to call ``plt.show()`` at the end.
        save_path: Optional file path to save the whole figure.

    Returns:
        The 2-D NumPy array of matplotlib Axes.
    """
    import math

    import matplotlib.pyplot as plt

    fields = list(metrics) if metrics is not None else list(METRIC_FIELDS)

    # Drop metrics with no data
    available = [f for f in fields if not self.metrics_comparison_frame(f, rule_code, stat=stat).empty]
    if not available:
        raise ValueError(
            f"No winner-metric data found for rule '{rule_code}'. "
            "Check that metrics were computed during simulation."
        )

    n = len(available)
    ncols = min(4, n)
    nrows = math.ceil(n / ncols)

    fig, axes = plt.subplots(
        nrows,
        ncols,
        figsize=(5 * ncols, 4 * nrows),
        constrained_layout=True,
    )
    # Normalise axes to a flat list
    axes_flat: list[Any] = np.array(axes).flatten().tolist()

    rule_up = rule_code.strip().upper()
    fig.suptitle(
        f"Winner metrics ({stat}) — {rule_up}",
        fontsize=13,
        fontweight="bold",
    )

    for ax_i, f_name in zip(axes_flat, available, strict=False):
        try:
            self.plot_winner_metric_heatmap(
                f_name,
                rule_code,
                row_param=row_param,
                col_param=col_param,
                stat=stat,
                ax=ax_i,
                annotate=annotate,
                show=False,
            )
        except ValueError:
            ax_i.set_visible(False)

    # Hide unused axes
    for ax_i in axes_flat[len(available) :]:
        ax_i.set_visible(False)

    if save_path is not None:
        os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
        fig.savefig(save_path)
    if show:
        plt.show()
    else:
        plt.close(fig)
    return axes

replace_series(series)

Add or overwrite a series at its config key.

Source code in src/vote_simulation/models/results/total_result.py
def replace_series(self, series: SimulationSeriesResult) -> None:
    """Add or overwrite a series at its config key."""
    key = _extract_key(series)
    self._entries[key] = series

rule_pair_frame(rule_a, rule_b)

Mean distance between two rules in every series.

Returns a DataFrame with columns gen_model, n_voters, n_candidates, distance.

Source code in src/vote_simulation/models/results/total_result.py
def rule_pair_frame(self, rule_a: str, rule_b: str) -> pd.DataFrame:
    """Mean distance between two rules in every series.

    Returns a DataFrame with columns ``gen_model``, ``n_voters``,
    ``n_candidates``, ``distance``.
    """
    a, b = rule_a.strip().upper(), rule_b.strip().upper()
    rows: list[dict[str, Any]] = []
    for key in sorted(self._entries):
        series = self._entries[key]
        mat = series.mean_distance_matrix_frame
        if a in mat.index and b in mat.columns:
            dist = float(mat.loc[a, b])
        else:
            dist = float("nan")
        rows.append(
            {
                "gen_model": key.gen_model,
                "n_voters": key.n_voters,
                "n_candidates": key.n_candidates,
                "distance": dist,
            }
        )
    return pd.DataFrame(rows)

save_to_dir(dir_path)

Persist every series as <label>.parquet inside dir_path.

Source code in src/vote_simulation/models/results/total_result.py
def save_to_dir(self, dir_path: str) -> None:
    """Persist every series as ``<label>.parquet`` inside *dir_path*."""
    os.makedirs(dir_path, exist_ok=True)
    for _key, series in self._entries.items():
        filename = f"{series.config.label}.parquet"
        series.save_to_file(os.path.join(dir_path, filename))

summary_frame()

One-row-per-series DataFrame with key fields and scalar metrics.

Columns: gen_model, n_voters, n_candidates, step_count, n_iterations, mean_distance, most_distant_rule_a, most_distant_rule_b, most_distant_distance.

Source code in src/vote_simulation/models/results/total_result.py
def summary_frame(self) -> pd.DataFrame:
    """One-row-per-series DataFrame with key fields and scalar metrics.

    Columns: ``gen_model``, ``n_voters``, ``n_candidates``,
    ``step_count``, ``n_iterations``, ``mean_distance``,
    ``most_distant_rule_a``, ``most_distant_rule_b``,
    ``most_distant_distance``.
    """
    rows: list[dict[str, Any]] = []
    for key in sorted(self._entries):
        series = self._entries[key]
        r_a, r_b, dist = series.most_distant_rules
        rows.append(
            {
                "gen_model": key.gen_model,
                "n_voters": key.n_voters,
                "n_candidates": key.n_candidates,
                "step_count": series.step_count,
                "n_iterations": series.config.n_iterations,
                "mean_distance": series.mean_distance,
                "most_distant_rule_a": r_a,
                "most_distant_rule_b": r_b,
                "most_distant_distance": dist,
            }
        )
    return pd.DataFrame(rows)

Defines the :class:ResultConfig dataclass for describing simulation contexts.

This class encapsulates the parameters that define a simulation run as such :

  • the generation models used,
  • the number of voters and candidates,
  • the rules applied,
  • and the number of iterations.

The class provides for adding rules to existing configs, merging configs, and generating labels for results based on their parameters.

ResultConfig dataclass

Describes the simulation context attached to a result.

Supports single-valued and multi-valued configurations to express metadata.

All collection fields use :class:frozenset for immutability and light membership checks.

Source code in src/vote_simulation/models/results/result_config.py
@dataclass(frozen=True, slots=True)
class ResultConfig:
    """Describes the simulation context attached to a result.

    Supports single-valued **and** multi-valued configurations to
    express metadata.

    All collection fields use :class:`frozenset` for immutability and
    light membership checks.
    """

    gen_models: frozenset[str] = field(default_factory=frozenset)
    n_voters: frozenset[int] = field(default_factory=frozenset)
    n_candidates: frozenset[int] = field(default_factory=frozenset)
    rules_codes: frozenset[str] = field(default_factory=frozenset)
    n_iterations: int = 0

    # Factories

    @staticmethod
    def single(
        gen_model: str = "",
        n_voters: int = 0,
        n_candidates: int = 0,
        n_iterations: int = 0,
        rules_codes: list[str] | None = None,
    ) -> ResultConfig:
        """Create a config for a single (model, voters, candidates) combo."""
        return ResultConfig(
            gen_models=frozenset({gen_model}) if gen_model else frozenset(),
            n_voters=frozenset({n_voters}) if n_voters else frozenset(),
            n_candidates=frozenset({n_candidates}) if n_candidates else frozenset(),
            rules_codes=frozenset(rules_codes) if rules_codes else frozenset(),
            n_iterations=n_iterations,
        )

    # Merge / combine

    def merge(self, other: ResultConfig) -> ResultConfig:
        """Return the union of two configs (idempotent & commutative)."""
        return ResultConfig(
            gen_models=self.gen_models | other.gen_models,
            n_voters=self.n_voters | other.n_voters,
            n_candidates=self.n_candidates | other.n_candidates,
            rules_codes=self.rules_codes | other.rules_codes,
            n_iterations=max(self.n_iterations, other.n_iterations),
        )

    def base_config(self) -> ResultConfig:
        """Return a copy with rules_codes cleared (for cache keys based on data params only)."""
        return ResultConfig(
            gen_models=self.gen_models,
            n_voters=self.n_voters,
            n_candidates=self.n_candidates,
            rules_codes=frozenset(),
            n_iterations=self.n_iterations,
        )

    def matches_base(self, other: ResultConfig) -> bool:
        """Check if two configs have identical base parameters (ignoring rules_codes)."""
        return (
            self.gen_models == other.gen_models
            and self.n_voters == other.n_voters
            and self.n_candidates == other.n_candidates
            and self.n_iterations == other.n_iterations
        )

    # Labels

    @property
    def label(self) -> str:
        """Base label suitable for directory / file names (excludes rules).

        Used for cache keys and data organization directories.
        Format depends on how many values are set::

            "UNI_v101_c3"          (single model, voters, candidates)
            "IC_UNI_v11_101_c3_14" (multiple values)

        When n_iterations is set, appends ``_i{n_iterations}``.
        """
        models = "_".join(sorted(self.gen_models)) or "UNKNOWN"
        voters = "_".join(str(v) for v in sorted(self.n_voters)) or "0"
        candidates = "_".join(str(c) for c in sorted(self.n_candidates)) or "0"
        base = f"{models}_v{voters}_c{candidates}"
        if self.n_iterations:
            base += f"_i{self.n_iterations}"
        return base

    @property
    def label_with_rules(self) -> str:
        """Full label including rules codes (for complete identification).

        Format: ``{base_label}_r{rules_joined}``
        """
        base = self.label
        if self.rules_codes:
            rules = "_".join(sorted(self.rules_codes))
            return f"{base}_r{rules}"
        return base

    @property
    def description(self) -> str:
        """Human-readable description for plot titles.

        Automatically switches between singular and plural phrasing depending
        on how many distinct values are present.
        """
        parts: list[str] = []
        if self.gen_models:
            if len(self.gen_models) == 1:
                parts.append(next(iter(self.gen_models)))
            else:
                parts.append(f"Models: {', '.join(sorted(self.gen_models))}")
        if self.n_voters:
            if len(self.n_voters) == 1:
                parts.append(f"{next(iter(self.n_voters))} voters")
            else:
                parts.append(f"Voters: {', '.join(str(v) for v in sorted(self.n_voters))}")
        if self.n_candidates:
            if len(self.n_candidates) == 1:
                parts.append(f"{next(iter(self.n_candidates))} cand.")
            else:
                parts.append(f"Candidates: {', '.join(str(c) for c in sorted(self.n_candidates))}")
        return " · ".join(parts) if parts else ""

    # -- Serialization ----------------------------------------------------

    def to_dict(self) -> dict[str, str]:
        """Serialize to a ``{key: csv_string}`` mapping."""
        return {
            "gen_models": ",".join(sorted(self.gen_models)),
            "n_voters": ",".join(str(v) for v in sorted(self.n_voters)),
            "n_candidates": ",".join(str(c) for c in sorted(self.n_candidates)),
            "n_iterations": str(self.n_iterations),
            "rules_codes": ",".join(sorted(self.rules_codes)),
        }

    @staticmethod
    def from_dict(data: dict[str, str]) -> ResultConfig:
        """Deserialize from a ``{key: csv_string}`` mapping."""
        gen_models = frozenset(m for m in data.get("gen_models", "").split(",") if m)
        n_voters = frozenset(int(v) for v in data.get("n_voters", "").split(",") if v)
        n_candidates = frozenset(int(c) for c in data.get("n_candidates", "").split(",") if c)
        n_iterations = int(data["n_iterations"]) if data.get("n_iterations") else 0
        rules_codes = frozenset(c for c in data.get("rules_codes", "").split(",") if c)
        return ResultConfig(
            gen_models=gen_models,
            n_voters=n_voters,
            n_candidates=n_candidates,
            n_iterations=n_iterations,
            rules_codes=rules_codes,
        )

    def __bool__(self) -> bool:
        return bool(self.gen_models or self.n_voters or self.n_candidates or self.n_iterations or self.rules_codes)

description property

Human-readable description for plot titles.

Automatically switches between singular and plural phrasing depending on how many distinct values are present.

label property

Base label suitable for directory / file names (excludes rules).

Used for cache keys and data organization directories. Format depends on how many values are set::

"UNI_v101_c3"          (single model, voters, candidates)
"IC_UNI_v11_101_c3_14" (multiple values)

When n_iterations is set, appends _i{n_iterations}.

label_with_rules property

Full label including rules codes (for complete identification).

Format: {base_label}_r{rules_joined}

base_config()

Return a copy with rules_codes cleared (for cache keys based on data params only).

Source code in src/vote_simulation/models/results/result_config.py
def base_config(self) -> ResultConfig:
    """Return a copy with rules_codes cleared (for cache keys based on data params only)."""
    return ResultConfig(
        gen_models=self.gen_models,
        n_voters=self.n_voters,
        n_candidates=self.n_candidates,
        rules_codes=frozenset(),
        n_iterations=self.n_iterations,
    )

from_dict(data) staticmethod

Deserialize from a {key: csv_string} mapping.

Source code in src/vote_simulation/models/results/result_config.py
@staticmethod
def from_dict(data: dict[str, str]) -> ResultConfig:
    """Deserialize from a ``{key: csv_string}`` mapping."""
    gen_models = frozenset(m for m in data.get("gen_models", "").split(",") if m)
    n_voters = frozenset(int(v) for v in data.get("n_voters", "").split(",") if v)
    n_candidates = frozenset(int(c) for c in data.get("n_candidates", "").split(",") if c)
    n_iterations = int(data["n_iterations"]) if data.get("n_iterations") else 0
    rules_codes = frozenset(c for c in data.get("rules_codes", "").split(",") if c)
    return ResultConfig(
        gen_models=gen_models,
        n_voters=n_voters,
        n_candidates=n_candidates,
        n_iterations=n_iterations,
        rules_codes=rules_codes,
    )

matches_base(other)

Check if two configs have identical base parameters (ignoring rules_codes).

Source code in src/vote_simulation/models/results/result_config.py
def matches_base(self, other: ResultConfig) -> bool:
    """Check if two configs have identical base parameters (ignoring rules_codes)."""
    return (
        self.gen_models == other.gen_models
        and self.n_voters == other.n_voters
        and self.n_candidates == other.n_candidates
        and self.n_iterations == other.n_iterations
    )

merge(other)

Return the union of two configs (idempotent & commutative).

Source code in src/vote_simulation/models/results/result_config.py
def merge(self, other: ResultConfig) -> ResultConfig:
    """Return the union of two configs (idempotent & commutative)."""
    return ResultConfig(
        gen_models=self.gen_models | other.gen_models,
        n_voters=self.n_voters | other.n_voters,
        n_candidates=self.n_candidates | other.n_candidates,
        rules_codes=self.rules_codes | other.rules_codes,
        n_iterations=max(self.n_iterations, other.n_iterations),
    )

single(gen_model='', n_voters=0, n_candidates=0, n_iterations=0, rules_codes=None) staticmethod

Create a config for a single (model, voters, candidates) combo.

Source code in src/vote_simulation/models/results/result_config.py
@staticmethod
def single(
    gen_model: str = "",
    n_voters: int = 0,
    n_candidates: int = 0,
    n_iterations: int = 0,
    rules_codes: list[str] | None = None,
) -> ResultConfig:
    """Create a config for a single (model, voters, candidates) combo."""
    return ResultConfig(
        gen_models=frozenset({gen_model}) if gen_model else frozenset(),
        n_voters=frozenset({n_voters}) if n_voters else frozenset(),
        n_candidates=frozenset({n_candidates}) if n_candidates else frozenset(),
        rules_codes=frozenset(rules_codes) if rules_codes else frozenset(),
        n_iterations=n_iterations,
    )

to_dict()

Serialize to a {key: csv_string} mapping.

Source code in src/vote_simulation/models/results/result_config.py
def to_dict(self) -> dict[str, str]:
    """Serialize to a ``{key: csv_string}`` mapping."""
    return {
        "gen_models": ",".join(sorted(self.gen_models)),
        "n_voters": ",".join(str(v) for v in sorted(self.n_voters)),
        "n_candidates": ",".join(str(c) for c in sorted(self.n_candidates)),
        "n_iterations": str(self.n_iterations),
        "rules_codes": ",".join(sorted(self.rules_codes)),
    }