euromod.statistics

Below are listed the main public classes of the euromod.statistics module.

Classes

Statistics

Calculates statistics from EUROMOD simulation output.

StatisticsResult

Container for statistics calculation results, ready for Python consumption.

StatisticsTable

A single statistics table with Python-native data access.

class euromod.statistics.Statistics(template_path: str, variable: str = None)
Calculates statistics from EUROMOD simulation output.
Parameters:
  • template_path (str) – Path to the template XML file.

  • variable (str, optional) – Variable name for Variable-type templates.

Raises:

Overview

Methods

calculate(baseline, reforms, pages, tables)

Calculate statistics from simulation output.

calculate_custom(baseline, aggregate_stats, distributional_stats)

Calculate custom statistics.

list_pages()

Return the list of page names in the template.

list_structure()

Return the template structure as {page_name: [table_names]}.

list_tables(page)

Return table names in the template, or only those of page if given.

Methods

calculate(baseline, reforms=None, pages=None, tables=None)

Calculate statistics from simulation output.

Parameters:
  • baseline (Simulation or pandas.DataFrame or polars.DataFrame) – Baseline simulation output. A DataFrame must contain the variables required by the template (including idperson, idhh, dwt and dag). Note: passing a DataFrame skips the keep_clr_data zero-copy fast path, so the data is converted to CLR arrays on each call.

  • reforms (list of Simulation or pandas.DataFrame or polars.DataFrame, optional) – Reform outputs for comparison templates. Entries may be Simulations or DataFrames and may be mixed with the baseline type.

  • pages (list[str], optional) – If given, only these template pages are calculated (partial execution); the rest are skipped, which can be much faster. Use list_pages() to discover names. Global prerequisite actions always run, but a kept page that depends on a skipped one may fail.

  • tables (list[str], optional) – If given, only these tables are calculated. Can be combined with pages. Use list_tables() to discover names.

Returns:

Calculation results with multiple access patterns.

Return type:

StatisticsResult

Raises:
  • ValueError – If required variables are missing from the simulation output, or if template type requires reforms but none are provided.

  • RuntimeError – If the EM_TemplateCalculator reports errors during preparation or calculation.

calculate_custom(baseline, aggregate_stats=None, distributional_stats=None)

Calculate custom statistics.

Accepts aggregate and distributional statistic definitions as Python dicts, maps them to C# ExternalStatisticAggregate and ExternalStatisticDistributional objects, builds a programmatic template, and runs the calculation using the baseline Simulation data.

If this Statistics instance was initialized with a template, the custom statistics are combined with the template-driven calculations in a single pass. Otherwise, a minimal template is constructed for the custom statistics alone.

Parameters:
  • baseline (Simulation or pandas.DataFrame or polars.DataFrame) – Simulation output, or a DataFrame containing the income-list variables (and idperson, idhh, dwt, dag) referenced by the requested statistics.

  • aggregate_stats (list[dict], optional) –

    Aggregate statistic definitions. Each dict should have:
    • name (str): statistic name

    • income_list (str): income list variable name

    • description (str, optional): description

    • source (str, optional): data source

    • year (str, optional): year for year values

    • amount (str, optional): amount value for the year

    • beneficiaries (str, optional): beneficiaries count for the year

  • distributional_stats (list[dict], optional) –

    Distributional statistic definitions. Each dict should have:
    • name (str): statistic name

    • income_list (str): income list variable name

    • description (str, optional): description

    • measures (list[str], optional): distributional measures to calculate. Supported: “gini”, “s80s20”, “poverty_rate”, “median”, “mean”, “atkinson”, “mean_log_deviation”, “population_count”

Returns:

Calculation results with multiple access patterns.

Return type:

StatisticsResult

Raises:
  • ValueError – If no custom statistics definitions are provided, or if definitions are invalid (missing required fields).

  • RuntimeError – If the EM_TemplateCalculator reports errors during preparation or calculation.

list_pages() list

Return the list of page names in the template.

list_structure() dict

Return the template structure as {page_name: [table_names]}.

Useful for discovering which pages/tables exist before requesting a subset via the pages/tables parameters of calculate().

list_tables(page: str = None) list

Return table names in the template, or only those of page if given.

class euromod.statistics.StatisticsResult(display_results=None, use_polars=False, errors=None, warnings=None)
Container for statistics calculation results, ready for Python consumption.
Parameters:
  • display_results (DisplayResults (CLR object), optional) – The C# DisplayResults object from EM_TemplateCalculator.

  • use_polars (bool, optional) – If True, DataFrames produced by this result will use polars (default: False).

  • errors (list[str], optional) – Error messages from the ErrorCollector.

  • warnings (list[str], optional) – Warning messages (non-fatal) from the ErrorCollector.

Overview

Methods

to_dataframes()

Convert each table in results to a DataFrame, keyed by table name.

to_dict()

Full results as a nested dict matching the SP_ExecutableCaller JSON structure.

to_excel(path)

Export results to Excel file via EM_Statistics ExportHandling.

to_json(path)

Export results to JSON file in SP_ExecutableCaller-compatible format.

Methods

to_dataframes() dict

Convert each table in results to a DataFrame, keyed by table name.

Returns:

Dictionary mapping table name to its DataFrame representation. Uses the same DataFrame library (pandas or polars) as the input Simulation.

Return type:

dict[str, pandas.DataFrame | polars.DataFrame]

to_dict() dict

Full results as a nested dict matching the SP_ExecutableCaller JSON structure.

The returned dictionary has the following shape:

{
    "info": {"title": str, "subtitle": str, "button": str, "description": str},
    "pages": [
        {
            "name": str, "title": str, "subtitle": str, "description": str,
            "tables": [
                {
                    "name": str, "title": str, "subtitle": str,
                    "columns": [{"name": str, "title": str}],
                    "rows": [{"name": str, "title": str}],
                    "cells": [[{"displayValue": str, "value": float, "isStringValue": bool}]]
                }
            ]
        }
    ],
    "prepared": bool,
    "calculated": bool
}
Returns:

Nested dictionary matching the SP_ExecutableCaller JSON schema.

Return type:

dict

to_excel(path: str) None

Export results to Excel file via EM_Statistics ExportHandling.

Uses the C# ExportHandling.ExportSinglePackage method to generate an Excel workbook from the DisplayResults object, then writes the resulting MemoryStream to the specified file path.

Parameters:

path (str) – File path where the Excel (.xlsx) output will be written.

Raises:
  • ValueError – If no DisplayResults are available (calculation did not complete).

  • RuntimeError – If the C# ExportHandling reports an error during export.

  • OSError – If the file cannot be written to the specified path.

to_json(path: str) None

Export results to JSON file in SP_ExecutableCaller-compatible format.

Serializes the results using to_dict() and writes to the specified file. Applies sentinel value substitution for special float values: - NaN → 99999998 - +Infinity → 99999999 - -Infinity → -99999999

Parameters:

path (str) – File path where the JSON output will be written.

Raises:

OSError – If the file cannot be written to the specified path.

class euromod.statistics.StatisticsTable
A single statistics table with Python-native data access.