Core¶
Model assembly, datasets, calibration and solver support.
Main Model class for equilibria CGE framework.
The Model class is the central component that assembles blocks, manages sets, parameters, variables, and equations, and provides interfaces for calibration and solving.
- class equilibria.model.ModelStatistics(*, variables=0, equations=0, degrees_of_freedom=0, blocks=0, sparsity=0.0)[source]¶
Bases:
BaseModelStatistics for a CGE model.
Provides counts of variables, equations, degrees of freedom, and other model metrics.
- Variables:
- Parameters:
- model_config = {'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.model.Model(*, name, description='', set_manager=<factory>, parameter_manager=<factory>, variable_manager=<factory>, equation_manager=<factory>, blocks=<factory>)[source]¶
Bases:
BaseModelCGE Model class.
The Model class assembles equation blocks, manages all model components (sets, parameters, variables, equations), and provides interfaces for calibration and solving.
- Variables:
name (str) – Model identifier
description (str) – Model description
set_manager (SetManager) – Manager for all sets
parameter_manager (ParameterManager) – Manager for all parameters
variable_manager (VariableManager) – Manager for all variables
equation_manager (EquationManager) – Manager for all equations
- Parameters:
Example
>>> model = Model(name="MyCGE") >>> model.add_sets([ ... Set(name="J", elements=["agr", "mfg", "svc"]), ... ]) >>> model.add_block(CESValueAdded(sigma=0.8)) >>> print(model.statistics)
- set_manager: SetManager¶
- parameter_manager: ParameterManager¶
- variable_manager: VariableManager¶
- equation_manager: EquationManager¶
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- add_set(set_obj)[source]¶
Add a set to the model.
- Parameters:
set_obj (Set) – Set to add
- Return type:
None
- add_sets(sets)[source]¶
Add multiple sets to the model.
- Parameters:
sets (list[Set]) – List of sets to add
- Return type:
None
- add_parameter(param)[source]¶
Add a parameter to the model.
- Parameters:
param (Parameter) – Parameter to add
- Return type:
None
- add_variable(var)[source]¶
Add a variable to the model.
- Parameters:
var (Variable) – Variable to add
- Return type:
None
- add_equation(eq)[source]¶
Add an equation to the model.
- Parameters:
eq (Equation) – Equation to add
- Return type:
None
- add_block(block)[source]¶
Add a block to the model.
This validates that required sets exist, then calls the block’s setup method to add parameters, variables, and equations.
- Parameters:
block (Block) – Block to add
- Raises:
ValueError – If required sets are missing
- Return type:
None
- get_parameter(name)[source]¶
Get a parameter by name.
- Parameters:
name (str) – Parameter name
- Returns:
Parameter object
- Return type:
Parameter
- get_variable(name)[source]¶
Get a variable by name.
- Parameters:
name (str) – Variable name
- Returns:
Variable object
- Return type:
Variable
- get_equation(name)[source]¶
Get an equation by name.
- Parameters:
name (str) – Equation name
- Returns:
Equation object
- Return type:
Equation
- property statistics: ModelStatistics¶
Calculate model statistics.
- Returns:
ModelStatistics with counts and metrics
Bundled reference datasets shipped with equilibria.
load_bundled(category, name) returns a ready-to-use object built from the canonical source files for one of the small datasets that travel with the package (useful for tutorials, tests, and example notebooks). Callers that need a custom aggregation should still go through the underlying loaders directly.
- Source-of-truth conventions per category:
"gtap"— native GEMPACK HAR/PRM files. That is what the officialconvert.cmdflow builds GDX from upstream."pep"— Excel workbooks (SAM-V2_0.xlsx, VAL_PAR.xlsx). That is the form in which the PEP-1-1 reference data is published.
- equilibria.datasets.dataset_path(category, name)[source]¶
Return the directory holding a bundled dataset’s raw files.
- equilibria.datasets.load_bundled(category, name='default')[source]¶
Load a bundled dataset and return a ready-to-use object.
For
category="gtap"this always reads native HAR/PRM files (basedata.har, sets.har, default.prm, plus optional baserate.har for GTAPv7-style aggregations like NUS333) and returns a calibrated GTAPParameters.For
category="pep"this always reads the canonical Excel workbooks (SAM-V2_0.xlsx and VAL_PAR.xlsx), converts the SAM on-the-fly to the 4D GDX layout the PEP calibrator consumes, and returns a PEPModelCalibrator ready to call .calibrate(). The intermediate GDX is written to a tmp directory under ~/.cache/equilibria/pep/ so subsequent calls reuse it.
Calibration base classes for equilibria CGE framework.
This module provides the foundation for calibrating CGE models from SAM data, including elasticity estimation and parameter computation.
- class equilibria.calibration.base.CalibrationResult(*, success=True, parameters=<factory>, statistics=<factory>, messages=<factory>, warnings=<factory>)[source]¶
Bases:
BaseModelResults from a calibration operation.
Stores calibrated parameters, statistics, and diagnostic information from the calibration process.
- Variables:
- Parameters:
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.calibration.base.Calibrator(*, name, description='')[source]¶
Bases:
ABC,BaseModelAbstract base class for model calibrators.
Calibrators compute model parameters from SAM data and user-provided elasticities.
- Variables:
- Parameters:
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- abstractmethod calibrate(model, sam, elasticities=None)[source]¶
Calibrate model parameters from SAM data.
- Parameters:
- Returns:
CalibrationResult with calibrated parameters
- Return type:
- validate_sam(sam, tolerance=1e-06)[source]¶
Validate that SAM is balanced.
- Parameters:
sam (SAM) – SAM to validate
tolerance (float) – Balance tolerance
- Returns:
True if valid
- Raises:
ValueError – If SAM is not balanced
- Return type:
- class equilibria.calibration.base.ModelCalibrator[source]¶
Bases:
objectOrchestrates calibration of multiple model components.
Manages multiple calibrators and coordinates the full model calibration process.
- Variables:
calibrators – List of calibrators to apply
- add_calibrator(calibrator)[source]¶
Add a calibrator.
- Parameters:
calibrator (Calibrator) – Calibrator to add
- Return type:
None
CES (Constant Elasticity of Substitution) calibration.
Calibrates CES production function parameters from SAM data.
- class equilibria.calibration.ces.CESCalibrator(*, name='CES', description='CES production function calibration', default_sigma=0.8)[source]¶
Bases:
CalibratorCalibrator for CES production functions.
Computes CES share parameters and efficiency parameters from SAM data and user-provided elasticities.
The CES function is: VA[j] = B[j] * (sum_i beta[i,j] * FD[i,j]^(-rho[j]))^(-1/rho[j])
Where: - rho[j] = (sigma[j] - 1) / sigma[j] - beta[i,j] = (WF[i] * FD[i,j]) / PVA[j] / VA[j] - B[j] = VA[j] / (sum_i beta[i,j] * FD[i,j]^(-rho[j]))^(-1/rho[j])
- Variables:
default_sigma (float) – Default elasticity if not provided
- Parameters:
- calibrate(model, sam, elasticities=None)[source]¶
Calibrate CES parameters from SAM.
- Parameters:
- Returns:
CalibrationResult with beta_VA, B_VA, sigma_VA
- Return type:
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Leontief calibration for intermediate inputs.
Calibrates input-output coefficients from SAM data.
- class equilibria.calibration.leontief.LeontiefCalibrator(*, name='Leontief', description='Leontief intermediate input calibration', min_coefficient=1e-10)[source]¶
Bases:
CalibratorCalibrator for Leontief intermediate inputs.
Computes input-output coefficients from SAM data.
The Leontief function is: XST[i,j] = a_io[i,j] * Z[j]
Where: - XST[i,j] = intermediate demand for commodity i by sector j - Z[j] = total output of sector j - a_io[i,j] = input-output coefficient
The coefficient is computed as: a_io[i,j] = XST[i,j] / Z[j]
- Variables:
min_coefficient (float) – Minimum threshold for IO coefficients
- Parameters:
- calibrate(model, sam, elasticities=None)[source]¶
Calibrate Leontief IO coefficients from SAM.
- Parameters:
- Returns:
CalibrationResult with a_io coefficients
- Return type:
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Canonical post-transform safeguards for solver variables.
- equilibria.solver.guards.rebuild_tax_detail_from_rates(vars, sets, params, *, include_tip=True)[source]¶
Rebuild detailed tax-payment variables from ad-valorem policy rates.
This is the canonical reconstruction used after array->variables conversion and in initialization routines that need deterministic tax detail.
Canonical array<->variable transforms for the PEP solver.
- equilibria.solver.transforms.pep_array_to_variables(x, sets, *, min_price=1e-06)[source]¶
Convert flat solver vector to PEPModelVariables.
Ordering is intentionally aligned with historical IPOPT packing order.
- equilibria.solver.transforms.pep_variables_to_array(vars, sets)[source]¶
Convert PEPModelVariables to flat solver vector.
Generic contract/runtime primitives shared across model templates.
- equilibria.contracts.base.normalize_string_tuple(value)[source]¶
Normalize string-like inputs into an ordered unique tuple.
- equilibria.contracts.base.deep_merge_model_dicts(base, updates)[source]¶
Recursively merge nested dictionaries used to build contract/config models.
- class equilibria.contracts.base.ModelClosureConfig(*, name='default', numeraire='e', numeraire_mode='fixed_benchmark', capital_mobility='mobile', fixed=<factory>, endogenous=<factory>, label=None)[source]¶
Bases:
BaseModelGeneric closure definition shared across model contracts.
- Parameters:
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.contracts.base.ModelEquationConfig(*, name='full_model', include=<factory>, activation_masks='default')[source]¶
Bases:
BaseModelGeneric equation activation policy.
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.contracts.base.ModelBoundsConfig(*, name='economic', positive='lower_only', fixed_from_closure=True, free=<factory>)[source]¶
Bases:
BaseModelGeneric bounds/domain policy.
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.contracts.base.ModelContract(*, name, closure, equations, bounds)[source]¶
Bases:
BaseModelGeneric model contract: closure + equations + bounds.
- Parameters:
name (str)
closure (ModelClosureConfig)
equations (ModelEquationConfig)
bounds (ModelBoundsConfig)
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- closure: ModelClosureConfig¶
- equations: ModelEquationConfig¶
- bounds: ModelBoundsConfig¶
- class equilibria.contracts.base.ModelReferenceConfig(*, enabled=False, source='none', model_type=None, solver=None, slice=None, levels_tol=1e-08, params_tol=1e-08)[source]¶
Bases:
BaseModelOptional parity/reference settings kept outside the economic contract.
- Parameters:
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.contracts.base.ModelRuntimeConfig(*, name='default', problem_type='nlp', solver='ipopt', tolerance=1e-08, max_iterations=300, require_solver_success=True, accept_square_feasible=True, reference=<factory>)[source]¶
Bases:
BaseModelGeneric runtime configuration for executing a model contract.
- Parameters:
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- reference: ModelReferenceConfig¶
- class equilibria.contracts.base.ModelClosureValidationReport(*, is_valid, system_shape, active_equation_count, free_endogenous_variable_count, fixed_by_closure_count, fixed_by_bounds_only_count, equation_variable_gap, numeraire=None, numeraire_is_fixed=None, duplicate_equations=<factory>, duplicate_free_variables=<factory>, unsupported_fixed_symbols=<factory>, unsupported_endogenous_symbols=<factory>, messages=<factory>)[source]¶
Bases:
BaseModelGeneric structural validation report for closure/system shape.
- Parameters:
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- system_shape: Literal['square', 'overdetermined', 'underdetermined']¶
- equilibria.contracts.base.validate_closure_structure(*, active_equations, free_endogenous_variables, fixed_by_closure=None, fixed_by_bounds_only=None, numeraire=None, unsupported_fixed_symbols=None, unsupported_endogenous_symbols=None)[source]¶
Validate the structural shape implied by the current closure.
- Parameters:
- Return type: