Advanced PyCGE API#
PyCGE is the retained lower-level engine for advanced inspection, debugging,
validation, and engine-level work. v0.8 re-homes the implementation under the
private module cge_core._pycge while keeping the intentional public import:
from cge_core import PyCGE
- class cge_core._pycge.PyCGE(model_def)#
Bases:
objectPyomo-based CGE calibration and counterfactual workflow.
Orchestrates the sequence (cf. OG-Core’s
run_SSpipeline):model_data -> model_instance -> model_drop_redundant -> model_calibrate -> model_sim -> model_modify_sim -> model_solve -> model_compare / model_postprocess
- Parameters:
model_def (object) – model-definition object exposing
model()that returns a Pyomo AbstractModel (e.g.StdModelDef).
- base#
the baseline instance; after
model_calibrateit reproduces the SAM benchmark.- Type:
ConcreteModel or None
- sim#
the counterfactual instance, cloned from the calibrated baseline by
model_sim.- Type:
ConcreteModel or None
- dict_base, dict_sim
reversible-modification history for
model_modify_base/model_modify_simundo support.- Type:
dict
- static degrees_of_freedom(instance)#
Return free variables minus active equality constraints.
- Return type:
int
- model_calibrate(solver=None, mgr='')#
Solve the BASE instance (the calibration check).
Because every behavioural parameter is recovered from the SAM, the solved baseline must reproduce the SAM benchmark exactly at unit prices; this solve verifies it (cf. OG-Core solving the baseline steady state before a reform).
- Parameters:
solver (str, optional) – local solver name; auto-detects ipopt/cyipopt if omitted.
mgr (str, optional) – Pyomo solver-manager name for remote solving (e.g.
'neos'); requiressolver.
- Returns:
- solver results. If the model is
already calibrated, the cached results are returned.
- Return type:
results (SolverResults)
- Raises:
WorkflowError – if the BASE instance does not exist.
SolveError – if the solver does not reach an acceptable optimum. The failed results are attached to the exception; solved-state flags are left unset.
- model_compare(verbose=None)#
Compare SIM against BASE variable by variable.
Differences are reported as
sim - baseand percentage change as(sim - base)/base * 100throughout, including the objective (utility), so a welfare gain is positive.- Parameters:
verbose (str, optional) –
Noneto just return the DataFrame;'print'to also print it; any other string is treated as a directory path in whichcompared.csvis written.- Returns:
- one row per variable element with
columns
component,index_1..index_N,base_value,sim_value,difference,pct_change. The objective comparison is attached asframe.attrs['objective']with keysbase,sim, anddifference.
- Return type:
frame (pandas.DataFrame)
- Raises:
WorkflowError – if the BASE or SIM instance does not exist.
- model_data(data_dir='')#
Load
set-*.csvandparam-*.csvfiles into a DataPortal.A file named
param-sam-.csv(the social accounting matrix) is structurally validated first: square, unique labels, finite numeric cells, and row/column totals balanced to tolerance. An unbalanced SAM cannot be reproduced by any equilibrium, so it is rejected before Pyomo ever sees it.- Parameters:
data_dir (str or PathLike) – directory containing the CSVs, e.g. from
cge_core.example_data()or built bycge_core.sam.build_dataset().- Returns:
the loaded data.
- Return type:
data (pyomo DataPortal)
- Raises:
DataValidationError – if
data_diris missing/invalid or the SAM fails validation.
- model_drop_redundant(name, index=None, base=True)#
Deactivate exactly one redundant equality constraint.
By Walras’ law, once the numeraire is fixed the system carries one redundant market-clearing equation; IPOPT rejects the resulting over-determined system (“too few degrees of freedom”). Dropping any single market-clearing equation restores a square system, and the dropped market still clears at the solution (asserted in the test suite). See docs/MODEL.md, “Closure and degrees of freedom”.
The operation is transactional: the selected equation is reactivated unless deactivation leaves the model with exactly zero degrees of freedom.
- Parameters:
name (str) – constraint name, e.g.
'eqpf'.index – index of the constraint instance to drop (required for indexed constraints), e.g.
'LAB'.base (bool) – operate on the BASE (True) or SIM (False) instance.
- Returns:
True; the system is now square.
- Return type:
success (bool)
- Raises:
WorkflowError – if the target instance does not exist, the equation is already inactive, or deactivation would not leave exactly zero degrees of freedom (rolled back).
ComponentError – if
nameis unknown, is not an equality Constraint, orindexis missing/invalid.
- model_instance(NAME, INDEX)#
Create the BASE concrete instance and fix the numeraire.
A CGE determines only relative prices, so exactly one price must be fixed as numeraire (Hosoe:
pf.fx("LAB") = 1). This method builds the concrete instance from the loaded data and fixes variableNAME[INDEX]at its initialized value (1 for prices).- Parameters:
NAME (str) – name of the variable to fix, e.g.
'pf'.INDEX – index of that variable, e.g.
'LAB'.
- Returns:
the new BASE instance.
- Return type:
instance (ConcreteModel)
- Raises:
WorkflowError – if the model or data are not loaded.
ComponentError – if
NAMEis not a variable orINDEXis not one of its indexes. The half-created instance is discarded, soself.basestays unchanged.DataValidationError – if model-specific calibration cannot be constructed from the supplied benchmark flows.
- model_load_instance(pathname, base=True)#
Load a trusted dill file created by
model_postprocess().Dill can execute code while loading. Never open an untrusted file. Legacy v0.2.1 files containing only a raw Pyomo instance are accepted.
- Parameters:
pathname (str or PathLike) – path to the dill file.
base (bool) – restore into the BASE (True) or SIM (False) slot.
- Returns:
the loaded instance.
- Return type:
instance (ConcreteModel)
- Raises:
FileNotFoundError – if
pathnamedoes not exist.
- model_modify_base(NAME, INDEX, VALUE, fix=True, undo=False)#
Apply (or undo) a modification on the BASE instance.
Benchmark calibration inputs (
sam,FF, and*0parameters) are refused here, because the calibrated share/scale parameters derived from them would silently go stale; change the input CSVs and rebuild instead. Signature as inmodel_modify_sim().- Returns:
True if the modification was applied.
- Return type:
success (bool)
- Raises:
WorkflowError, ComponentError, ValueError – as in
model_modify_sim(); additionally ComponentError when targeting protected calibration data.
- model_modify_sim(NAME, INDEX, VALUE, fix=True, undo=False)#
Apply (or undo) a reform shock on the SIM instance.
This is CGE-Core’s reform interface (cf. OG-Core reform dicts): e.g.
model_modify_sim('taum', 'BRD', 0)abolishes the tariff on BRD. Original values and fixed-status are recorded so the shock can be reversed withundo=True. Benchmark-onlysam/*0components are rejected because changing them after calibration is a silent no-op; factor endowments (FF) remain valid SIM shocks.- Parameters:
NAME (str) – variable or mutable parameter to change.
INDEX – index of the component (None/’’ for scalars).
VALUE – finite numeric scalar; for variables, checked against bounds.
fix (bool) – if a variable, fix it at VALUE (an exogenous shock) rather than leaving it free.
undo (bool) – restore the stored original value instead.
- Returns:
True if the modification was applied.
- Return type:
success (bool)
- Raises:
WorkflowError – if the SIM instance does not exist yet.
ComponentError – for unknown components/indexes, immutable parameters, or undo with no stored original.
ValueError – if VALUE is nonnumeric/nonfinite or violates a variable’s bounds.
- model_postprocess(object_name='', verbose='', base=True)#
Display or export an instance, results, params, or variables.
- Parameters:
object_name (str) – one of
'compare'(dispatches tomodel_compare()withverbose),'instance','results','params'(returns a dict of parameter values),'vars'(CSV export),'obj'(CSV export), or'dill_instance'(persistence).verbose (str) –
'print'or a destination directory, depending onobject_name.base (bool) – operate on the BASE (True) or SIM (False) instance.
- Returns:
the comparison DataFrame, a params dict, a written path, or None for display modes.
- Return type:
Varies by
object_name- Raises:
WorkflowError – if the required instance/results are missing.
ValueError – for an unknown
object_nameor a missing required destination.
- model_sim()#
Clone the calibrated BASE into a SIM (counterfactual) instance.
The clone is a deep copy, so shocks applied to SIM can never leak into the calibrated baseline. The OG-Core analogue is constructing the reform
Specificationsfrom the baseline beforerun_SS.- Returns:
the new SIM instance.
- Return type:
sim (ConcreteModel)
- Raises:
WorkflowError – if the BASE instance is missing or not yet calibrated.
- model_solve(solver=None, mgr='')#
Solve the SIM (counterfactual) instance.
Signature and error behaviour as in
model_calibrate().- Returns:
- solver results. If the sim is
already solved, the cached results are returned.
- Return type:
results (SolverResults)
- Raises:
WorkflowError – if the model is not calibrated or the SIM instance does not exist.
SolveError – if the solver does not reach an acceptable optimum.
Exceptions#
- class cge_core._pycge.CGEError#
Bases:
RuntimeErrorBase exception for CGE-Core workflow errors.
- class cge_core._pycge.WorkflowError#
Bases:
CGEErrorRaised when workflow methods are called out of order.
The message always names the method to call first (e.g. “Call
model_calibratefirst”), preserving the guidance that earlier versions printed.
- class cge_core._pycge.ComponentError#
Bases:
CGEErrorRaised when a named model component cannot be used as requested.
Covers unknown component names, invalid indexes, immutable parameters, protected calibration inputs, and undo requests with no stored original value.