GTAP template¶
Public surface of equilibria.templates.gtap. The equation monolith
(gtap_model_equations, ~6k lines) is deliberately not auto-documented —
its extraction into equilibria.blocks is roadmap phase F3.
GTAP Contract Models (Standard GTAP 7)
This module defines canonical contract models for GTAP following Standard GTAP 7 implementation. Reference: /Users/marmol/proyectos2/cge_babel/standard_gtap_7/comp.gms
Closures determine which variables are fixed (exogenous) and which are endogenous. GTAP Standard 7 supports multiple closure types: - Standard GTAP closure (default) - Trade policy closure - Single region closure - Full model closure
- class equilibria.templates.gtap.gtap_contract.GTAPClosureConfig(*, name='gtap_standard', numeraire='pnum', numeraire_mode='fixed_benchmark', capital_mobility='mobile', fixed=<factory>, endogenous=<factory>, label=None, closure_type='CNS', savf_flag='capFix', if_sub=True, calibration_source='python', calibration_dump=None, apply_flag_fixing=True, close_mcp_gap=False, fix_taxes=True, fix_technology=True, fix_endowments=True, fix_world_prices=False, rmuv=<factory>, imuv=<factory>)[source]¶
Bases:
ModelClosureConfigEconomic closure choices for GTAP model.
This defines which variables remain fixed (exogenous) and which are determined endogenously by the model.
- Variables:
name (str) – Closure configuration name
numeraire (str) – Price variable used as numeraire (default: “pnum”)
numeraire_mode (Literal['fixed_benchmark']) – How to handle numeraire (“fixed_benchmark”)
closure_type (Literal['CNS', 'MCP']) – Type of closure (“CNS” or “MCP”)
capital_mobility (Literal['mobile', 'sluggish']) – Factor mobility assumption (“mobile” or “sluggish”)
fix_taxes (bool) – Whether to fix tax rates at benchmark values
fix_technology (bool) – Whether to fix technology parameters
fix_endowments (bool) – Whether to fix factor endowments
fix_world_prices (bool) – Whether to fix world prices (single region mode)
fixed (Tuple[str, ...]) – Tuple of variable names to fix
endogenous (Tuple[str, ...]) – Tuple of variable names that are endogenous
- Parameters:
name (str)
numeraire (str)
numeraire_mode (Literal['fixed_benchmark'])
capital_mobility (Literal['mobile', 'sluggish'])
label (str | None)
closure_type (Literal['CNS', 'MCP'])
savf_flag (Literal['capFix', 'capSFix', 'capShrFix', 'capFlex'])
if_sub (bool)
calibration_source (str)
calibration_dump (str | None)
apply_flag_fixing (bool)
close_mcp_gap (bool)
fix_taxes (bool)
fix_technology (bool)
fix_endowments (bool)
fix_world_prices (bool)
Example
>>> closure = GTAPClosureConfig(name="gtap_standard") >>> print(closure.numeraire) 'pnum'
- numeraire_mode: Literal['fixed_benchmark']¶
- closure_type: Literal['CNS', 'MCP']¶
- capital_mobility: Literal['mobile', 'sluggish']¶
- savf_flag: Literal['capFix', 'capSFix', 'capShrFix', 'capFlex']¶
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.templates.gtap.gtap_contract.GTAPEquationConfig(*, name='full_gtap', include=<factory>, activation_masks='gtap_standard')[source]¶
Bases:
ModelEquationConfigActivated equation system for GTAP.
This determines which equations are included in the model.
- Variables:
- Parameters:
- activation_masks: Literal['gtap_standard', 'all_active']¶
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.templates.gtap.gtap_contract.GTAPBoundsConfig(*, name='economic', positive='lower_only', fixed_from_closure=True, free=<factory>, lower_bound=1e-06, upper_bound=None)[source]¶
Bases:
ModelBoundsConfigDomain/bounds policy for GTAP variables.
This defines bounds for model variables to ensure economic meaningfulness and numerical stability.
- Variables:
name (str) – Bounds configuration name
positive (Literal['lower_only', 'both_bounds']) – How to handle positive variables
fixed_from_closure (bool) – Whether to apply bounds from closure
free (Tuple[str, ...]) – Variables that should be unrestricted
lower_bound (float) – Default lower bound for positive variables
upper_bound (Optional[float]) – Default upper bound (if any)
- Parameters:
- positive: Literal['lower_only', 'both_bounds']¶
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class equilibria.templates.gtap.gtap_contract.GTAPContract(*, name='gtap_standard7_9x10', closure=<factory>, equations=<factory>, bounds=<factory>)[source]¶
Bases:
ModelContractResolved contract for GTAP CGE model.
This combines closure, equation, and bounds configurations into a complete model contract.
- Variables:
name (str) – Contract name
closure (GTAPClosureConfig) – Closure configuration
equations (GTAPEquationConfig) – Equation configuration
bounds (GTAPBoundsConfig) – Bounds configuration
- Parameters:
name (str)
closure (GTAPClosureConfig)
equations (GTAPEquationConfig)
bounds (GTAPBoundsConfig)
Example
>>> contract = GTAPContract() >>> print(contract.closure.name) 'gtap_standard'
- closure: GTAPClosureConfig¶
- equations: GTAPEquationConfig¶
- bounds: GTAPBoundsConfig¶
- model_config = {'extra': 'forbid', 'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- equilibria.templates.gtap.gtap_contract.default_gtap_contract()[source]¶
Return the canonical GTAP contract.
- Returns:
GTAPContract with standard GTAP closure
- Return type:
- equilibria.templates.gtap.gtap_contract.build_gtap_closure_config(value=None)[source]¶
Resolve a GTAP closure configuration.
- Parameters:
value (str | Mapping[str, Any] | GTAPClosureConfig | None) – Can be: - None: Use default closure - str: Closure name (e.g., “gtap_standard”) - Mapping: Dict with closure overrides - GTAPClosureConfig: Use as-is
- Returns:
Resolved GTAPClosureConfig
- Return type:
- equilibria.templates.gtap.gtap_contract.build_gtap_contract(value=None)[source]¶
Resolve a GTAP contract.
- Parameters:
value (str | Mapping[str, Any] | GTAPContract | None) – Can be: - None: Use default contract - str: Contract name (currently only “gtap_standard7_9x10”) - Mapping: Dict with contract overrides - GTAPContract: Use as-is
- Returns:
Resolved GTAPContract
- Return type:
GTAP Parameters (Standard GTAP 7)
This module defines all GTAP model parameters following the GTAP Standard 7 implementation. Reference: /Users/marmol/proyectos2/cge_babel/standard_gtap_7/model.gms
Parameters include: - Elasticities (substitution, transformation) - Benchmark SAM values - Tax rates - Share parameters (from calibration) - Technical change parameters
- class equilibria.templates.gtap.gtap_parameters.GTAPElasticities(esubva=<factory>, esubt=<factory>, esubd=<factory>, esubm=<factory>, omegax=<factory>, omegaw=<factory>, omegas=<factory>, sigmas=<factory>, etraq=<factory>, esubq=<factory>, etrae=<factory>, omegaf=<factory>, etaff=<factory>, esubg=<factory>, esubi=<factory>, rorflex=<factory>, esubc=<factory>, incpar=<factory>, subpar=<factory>, sigmam=<factory>, sigmap=<factory>, sigmand=<factory>, sigmav=<factory>)[source]¶
Bases:
objectElasticity parameters for GTAP model.
Key elasticities: - esubva: CES elasticity between value-added and intermediate demand - esubt: CES elasticity between primary factors and intermediates (top production nest) - esubd: CES elasticity between domestic and imported goods (top Armington) - esubm: CES elasticity across import sources (bottom Armington) - etrae: CET elasticity for factor mobility across sectors - omegax: CET elasticity between domestic sales and exports - omegaw: CET elasticity across export destinations
- Parameters:
- load_from_gdx(gdx_path, sets)[source]¶
Load elasticities from GDX file using GTAP Standard 7 native parameter names.
- override_omegas_sigmas_from_gdx(gdx_path, sets)[source]¶
Override only make-aggregation elasticities from a calibration GDX.
This is used to mirror GAMS COMP-calibrated values for: - omegas(r,a): activity transformation elasticity - sigmas(r,i): commodity aggregation elasticity
- calibrate_from_comp_gdx(comp_gdx, sets)[source]¶
Estimate sigm* elasticities using the COMP GDX time series.
Bases:
objectGAMS-style calibrated share parameters.
These parameters are calibrated from benchmark SAM data to ensure the benchmark is an exact solution of the CES/CET equations.
Following GAMS cal.gms lines 724-730: - and: ND bundle share parameter (calibrated with sigmap) - ava: VA bundle share parameter (calibrated with sigmap) - io: Input-output coefficients wrt ND (calibrated with sigmand) - af: Factor shares wrt VA (calibrated with sigmav) - gx: CET share parameter for commodity supply (calibrated with omegas)
- Parameters:
Calibrate all share parameters from benchmark data.
This follows GAMS cal.gms calibration logic (lines 724-730). All prices are assumed = 1.0 in benchmark (GAMS convention).
- Parameters:
benchmark (GTAPBenchmarkValues)
elasticities (GTAPElasticities)
sets (GTAPSets)
taxes (GTAPTaxRates | None)
- Return type:
None
- class equilibria.templates.gtap.gtap_parameters.GTAPBenchmarkValues(vom=<factory>, vom_i=<factory>, makb=<factory>, maks=<factory>, vfm=<factory>, vfb=<factory>, evfb=<factory>, evos=<factory>, fbep=<factory>, ftrv=<factory>, vmfp=<factory>, vmfb=<factory>, vdfm=<factory>, vifm=<factory>, vdfp=<factory>, vdfb=<factory>, vmpp=<factory>, vmpb=<factory>, vdpp=<factory>, vdpb=<factory>, vdgp=<factory>, vdgb=<factory>, vmgp=<factory>, vmgb=<factory>, vdip=<factory>, vdib=<factory>, vmip=<factory>, vmib=<factory>, vpm=<factory>, vgm=<factory>, vim=<factory>, vxmd=<factory>, vswd=<factory>, vtwr=<factory>, vxsb=<factory>, vfob=<factory>, vcif=<factory>, vmsb=<factory>, vst=<factory>, viws=<factory>, vims=<factory>, save=<factory>, vdep=<factory>, vkb=<factory>, pop=<factory>, yp=<factory>, yg=<factory>)[source]¶
Bases:
objectBenchmark SAM values from GTAP data.
These are the base year values used for calibration.
- Parameters:
- load_from_gdx(gdx_path, sets)[source]¶
Load benchmark values from GDX file using GTAP Standard 7 native parameter names.
- get_trade_totals(sets, region, commodity)[source]¶
Return benchmark trade totals for standard aggregates.
The simplified Python CET block only represents a top-level split between domestic sales and aggregate exports. To keep that block benchmark-feasible, we anchor domestic sales to absorbed domestic use and aggregate exports to the observed bilateral export flows. The top-level supply quantity then follows from that same split so the CET nest starts from an internally consistent benchmark.
- class equilibria.templates.gtap.gtap_parameters.GTAPTaxRates(rto=<factory>, rtf=<factory>, rtfd=<factory>, rtfi=<factory>, rtpd=<factory>, rtpi=<factory>, rtgd=<factory>, rtgi=<factory>, rtxs=<factory>, rtms=<factory>, imptx=<factory>, kappaf=<factory>, kappaf_activity=<factory>, dintx0=<factory>, mintx0=<factory>)[source]¶
Bases:
objectTax rates for GTAP model.
All tax rates are expressed as fractions (e.g., 0.05 = 5% tax).
- Parameters:
- derive_agent_consumption_taxes(benchmark, sets)[source]¶
Derive agent-level consumption tax rates (GAMS dintx0, mintx0).
- These taxes are calculated from benchmark data as:
dintx = (purchaser_price - basic_price) / basic_price = (vdfp - vdfb) / vdfb mintx = (purchaser_price - basic_price) / basic_price = (vmfp - vmfb) / vmfb
- For activities (firms):
dintx(r,i,a) = (vdfp - vdfb) / (pd * xd) where pd=1, xd=vdfb mintx(r,i,a) = (vmfp - vmfb) / (pmt * xm) where pmt=1, xm=vmfb
- For final demand agents (gov, priv, inv):
Similar logic using vdgp/vdgb, vdpp/vdpb, vdip/vdib
- Parameters:
benchmark (GTAPBenchmarkValues)
sets (GTAPSets)
- Return type:
None
- derive_trade_route_wedges(benchmark, sets)[source]¶
Derive trade route wedges (stub).
- Parameters:
benchmark (GTAPBenchmarkValues)
sets (GTAPSets)
- Return type:
None
- load_from_har(baserate_path, sets, benchmark)[source]¶
Load tax rates from a GEMPACK baserate.har file and derive benchmark rates.
- Parameters:
baserate_path (Path)
sets (GTAPSets)
benchmark (GTAPBenchmarkValues)
- Return type:
None
- derive_from_benchmark(benchmark, sets)[source]¶
Derive ad-valorem tax rates from benchmark SAM flows (GAMS-style).
- Parameters:
benchmark (GTAPBenchmarkValues)
sets (GTAPSets)
- Return type:
None
- class equilibria.templates.gtap.gtap_parameters.GTAPNormalizedParameters(value_added_share=<factory>, intermediate_share=<factory>, output_share=<factory>, commodity_share=<factory>, factor_supply_share=<factory>, factor_value_share=<factory>, armington_domestic=<factory>, armington_import=<factory>, armington_national=<factory>, import_source_share=<factory>, export_destination_share=<factory>, domestic_supply_share=<factory>, export_supply_share=<factory>)[source]¶
Bases:
objectSnapshot of normalized shares derived from the benchmark.
- Parameters:
share_params (GTAPShareParameters)
- Return type:
None
Bases:
objectShare parameters from calibration.
These are derived from the benchmark SAM and elasticities.
- Parameters:
Calibrate all share parameters from benchmark data.
- Parameters:
benchmark (GTAPBenchmarkValues)
elasticities (GTAPElasticities)
sets (GTAPSets)
taxes (GTAPTaxRates | None)
- Return type:
None
Update share parameters using an equilibrium CSV snapshot.
- Parameters:
snapshot (GTAPEquilibriumSnapshot)
sets (GTAPSets)
- Return type:
None
- class equilibria.templates.gtap.gtap_parameters.GTAPShiftParameters(axp=<factory>, lambdand=<factory>, lambdava=<factory>, lambdaio=<factory>, lambdaf=<factory>)[source]¶
Bases:
objectVariables that act as multipliers/technology shifters.
- Parameters:
- class equilibria.templates.gtap.gtap_parameters.GAMSCalibrationDump(source_gdx, derived_params=<factory>, benchmark_levels=<factory>)[source]¶
Bases:
objectContainer for calibration/benchmark symbols exported from a GAMS dump GDX.
The dump is used as a parity reference and optional override source. Symbol keys are normalized to lowercase and any trailing time dimension (base, t0, check, shock) is collapsed to a single benchmark slice.
- Parameters:
- DEFAULT_DERIVED_SYMBOLS: ClassVar[Tuple[str, ...]] = ('and', 'ava', 'io', 'af', 'gx', 'gf', 'gw', 'ge', 'gd', 'amw', 'alphaa', 'alphad', 'alpham', 'alphan', 'tmarg', 'chipm', 'chipd', 'kappaf', 'omegaf', 'etaff', 'esubt', 'esubc', 'esubm', 'esubva', 'sigmas', 'omegaw', 'axp', 'aft', 'aa', 'lambdam', 'lambdamg', 'mtax', 'etax')¶
- DEFAULT_LEVEL_SYMBOLS: ClassVar[Tuple[str, ...]] = ('xf', 'xft', 'xc', 'xa', 'xaa', 'xda', 'xma', 'xm', 'xd', 'xmt', 'xw', 'xe', 'xet', 'xp', 'va', 'nd', 'pf', 'pfa', 'pfy', 'pft', 'pa', 'pd', 'pm', 'pe', 'pet', 'px', 'pva', 'pnd', 'ps', 'pmcif', 'pefob', 'pwmg', 'ptmg', 'yi', 'yc', 'yg', 'kstock', 'arent', 'ytax', 'etax', 'mtax', 'dintx', 'mintx')¶
- class equilibria.templates.gtap.gtap_parameters.GTAPParameters(sets=<factory>, elasticities=<factory>, benchmark=<factory>, taxes=<factory>, shares=<factory>, calibrated=<factory>, shifts=<factory>)[source]¶
Bases:
objectComplete GTAP parameters container.
This combines all parameter types for the GTAP model.
- Parameters:
sets (GTAPSets)
elasticities (GTAPElasticities)
benchmark (GTAPBenchmarkValues)
taxes (GTAPTaxRates)
shares (GTAPShareParameters)
calibrated (GTAPCalibratedShares)
shifts (GTAPShiftParameters)
- elasticities: GTAPElasticities¶
- benchmark: GTAPBenchmarkValues¶
- taxes: GTAPTaxRates¶
- calibrated: GTAPCalibratedShares¶
- shifts: GTAPShiftParameters¶
- load_from_gdx(gdx_path, elasticity_gdx=None, elasticity_override_gdx=None)[source]¶
Load all parameters from GDX file(s).
- Parameters:
gdx_path (Path) – Path to GTAP GDX file with benchmark data (e.g., basedata-9x10.gdx)
elasticity_gdx (Path | None) – Optional separate GDX file with elasticities (e.g., default-9x10.gdx)
elasticity_override_gdx (Path | None) – Optional GDX used to override only omegas/sigmas after loading the base elasticity set (typically COMP.gdx).
- Return type:
None
- load_from_har(basedata_path, sets_path, default_path, baserate_path=None)[source]¶
Load all parameters from GEMPACK HAR/PRM files.
- Parameters:
basedata_path (Path) – Path to basedata.har (benchmark monetary flows).
sets_path (Path) – Path to sets.har (REG, COMM, ACTS, ENDW, MARG).
default_path (Path) – Path to default.prm (elasticities).
baserate_path (Path | None) – Optional baserate.har with explicit tax rate headers (RTMS, RTFD, RTFM, RTIN, RTXS). Required by the GTAPv7/GEMPACK pipeline (e.g. NUS333). Standard 7 GAMS aggregations (e.g. 9x10) ship only the 3 core HAR files and derive every tax rate from basedata wedges (imptx = (VMSB-VCIF)/VCIF, etc.); pass
None(or omit) in that case.
- Return type:
None
GTAP Sets and Declarations (Standard GTAP 7)
This module defines all GTAP model sets following the GTAP Standard 7 implementation. Reference: /Users/marmol/proyectos2/cge_babel/standard_gtap_7/model.gms
Key Sets: - r: Regions - i: Commodities/goods - a: Activities/sectors (alias of i in standard GTAP) - f: Factors of production - mf: Mobile factors (subset of f) - sf: Sector-specific factors (subset of f) - m: Alias of i used by the GTAP trade-margin mode block - marg: Active margin commodities from data (subset of i)
- class equilibria.templates.gtap.gtap_sets.GTAPSets(r=<factory>, i=<factory>, a=<factory>, f=<factory>, mf=<factory>, sf=<factory>, m=<factory>, marg=<factory>, h=None, s=None, i_to_a=<factory>, a_to_i=<factory>, output_pairs=<factory>, activity_commodities=<factory>, commodity_activities=<factory>, aggregation_name='', base_year=2014, source_gdx=None)[source]¶
Bases:
objectGTAP model sets following GTAP Standard 7 structure.
- Variables:
r (List[str]) – Regions in the model (e.g., [“EUR”, “USA”, “CHN”, “BRA”, “IND”])
i (List[str]) – Commodities/goods (e.g., [“agr”, “food”, “mfg”, “srv”, “ene”])
a (List[str]) – Activities/sectors (typically alias of i, but allows multi-product)
f (List[str]) – Factors of production (e.g., [“lnd”, “skl”, “unsk”, “cap”, “nrs”])
mf (List[str]) – Mobile factors (subset of f that can move across sectors)
sf (List[str]) – Sector-specific factors (subset of f that are fixed to sectors)
m (List[str]) – Alias of i for trade/transport modes in model.gms (alias(m,i))
marg (List[str]) – Active margin commodities from data (subset from MARG set)
h (List[str] | None) – Households (for myGTAP extension, optional)
- Parameters:
Example
>>> sets = GTAPSets() >>> sets.load_from_gdx(Path("asa7x5.gdx")) >>> print(f"Regions: {sets.r}") >>> print(f"Commodities: {sets.i}")
- load_from_gdx(gdx_path)[source]¶
Load sets from GTAP GDX file.
- Parameters:
gdx_path (Path) – Path to GDX file (e.g., asa7x5.gdx)
- Raises:
FileNotFoundError – If GDX file doesn’t exist
ValueError – If required sets are not found
- Return type:
None
- property has_multi_source_commodities: bool¶
Whether any commodity is supplied by more than one activity.
- property is_bijective_output_structure: bool¶
Whether activities and commodities can be matched one-to-one.
GTAP Solver (Standard GTAP 7)
This module implements the solver for GTAP CGE models. Supports multiple solvers: - IPOPT: Interior Point OPTimizer (default, for NLP/CNS) - PATH: Mixed Complementarity Problem solver (for MCP) - PATH-CAPI: Compatibility alias that routes through PATH backend in GTAPSolver
Reference: /Users/marmol/proyectos2/cge_babel/standard_gtap_7/comp.gms
- class equilibria.templates.gtap.gtap_solver.SolverStatus(*values)[source]¶
Bases:
EnumSolver status enumeration.
- CONVERGED = 'converged'¶
- ITERATION_LIMIT = 'iteration_limit'¶
- TIME_LIMIT = 'time_limit'¶
- INFEASIBLE = 'infeasible'¶
- UNBOUNDED = 'unbounded'¶
- NUMERICAL_ISSUES = 'numerical_issues'¶
- ERROR = 'error'¶
- UNKNOWN = 'unknown'¶
- class equilibria.templates.gtap.gtap_solver.SolverResult(status, termination_condition=None, objective_value=None, solve_time=0.0, iterations=0, residual=inf, walras_value=inf, variables=<factory>, success=False, message='')[source]¶
Bases:
objectResult from solver execution.
- Variables:
status (equilibria.templates.gtap.gtap_solver.SolverStatus) – Solver status
termination_condition (str | None) – Pyomo termination condition
objective_value (float | None) – Final objective value (if applicable)
solve_time (float) – Time taken to solve (seconds)
iterations (int) – Number of iterations
residual (float) – Final residual norm
walras_value (float) – Value of Walras check (should be ~0)
variables (Dict[str, Any]) – Dictionary of final variable values
success (bool) – Whether solve was successful
message (str) – Status message
- Parameters:
- status: SolverStatus¶
- class equilibria.templates.gtap.gtap_solver.GTAPSolver(model, closure=None, solver_name='ipopt', solver_options=None, params=None)[source]¶
Bases:
objectSolver for GTAP CGE models.
This class handles the solution of GTAP models using various solvers including IPOPT (default) and PATH.
- Variables:
model – Pyomo ConcreteModel
closure – Closure configuration
solver_name – Name of solver to use
solver_options – Solver-specific options
- Parameters:
model (ConcreteModel)
closure (Optional[GTAPClosureConfig])
solver_name (str)
solver_options (Optional[Dict[str, Any]])
params (Optional['GTAPParameters'])
Example
>>> solver = GTAPSolver(model, closure, solver_name="ipopt") >>> result = solver.solve() >>> if result.success: ... print(f"Converged in {result.iterations} iterations")
- apply_solution_hint(hint)[source]¶
Warm-start variables from a snapshot-like object.
The hint is typically a GTAPVariableSnapshot from the parity pipeline. Missing variables or indices are ignored.
- apply_closure(closure=None)[source]¶
Apply closure rules to fix exogenous variables.
- Parameters:
closure (GTAPClosureConfig | None) – Closure configuration (uses self.closure if None)
- Return type:
None
- apply_conditional_fixing()[source]¶
Apply conditional fixing based on SAM data (like GAMS).
This fixes variables where no underlying flow exists in the data: - Trade variables (xw, pe, pm, pmcif, pefob, etc.) when VXSB=0 - Factor variables (xf, pf) when VFM/EVFB=0 - Output variables (x) when VOA/VOM=0
This mirrors GAMS behavior where variables are fixed at zero/numeraire when the corresponding data flow is zero.
- Returns:
Number of variables fixed
- Return type:
- apply_aggressive_fixing_for_mcp()[source]¶
Apply aggressive fixing to make MCP square.
This fixes additional variables that GAMS fixes but the standard conditional fixing doesn’t cover. Used specifically for PATH-CAPI nonlinear mode.
- Returns:
Number of additional variables fixed
- Return type:
- solve(warm_start=True, tee=False, keepfiles=False, report_timing=False)[source]¶
Solve the GTAP model.
- Parameters:
- Returns:
SolverResult with solution status and values
- Return type:
GTAP multi-period driver: replicates GAMS loop(tsim) + iterloop.gms.
Solves base → check → shock sequentially on the FULL multi-period model m. Each period is solved by PATH via freeze_inactive_periods: all vars outside the active period are fixed at their current values, making the full m effectively single-period-for-PATH while the inactive-period equations remain as satisfied rows referencing fixed vars (exactly the GAMS holdfixed=1 structure).
After each period solves, the solved values remain fixed for subsequent periods, replicating GAMS iterloop.gms:149-178 var.fx(tsim-1) = var.l(tsim-1).
Public API¶
solve_multiperiod(m, params, closure, *, ref_gdx=None) -> dictReturns {period: {“code”: int, “residual”: float}} for each period.
- freeze_period(m, period)
Fixes all Var families at the given period so they serve as holdfixed parameters for subsequent periods.
- freeze_inactive_periods(m, active_period)
Freezes all var cells NOT belonging to active_period, leaving only active_period cells free (subject to PATH solve).
- equilibria.templates.gtap.gtap_multiperiod_driver.freeze_period(m, period)[source]¶
Fix every VarData at index (…, period) at its current value.
Replicates GAMS iterloop.gms:149-178 holdfixed block for the given period. Returns the count of VarData entries that were fixed.
- equilibria.templates.gtap.gtap_multiperiod_driver.freeze_inactive_periods(m, active_period)[source]¶
Fix all VarData cells NOT belonging to active_period and deactivate their constraints.
This makes the full multi-period model m look like a single-period system to PATH:
active_period vars are free; inactive-period vars are fixed.
active_period constraints are active (Jacobian rows for PATH).
inactive-period constraints are deactivated (no rows → square system).
The Fisher cross-period equations (eq_rgdpmp, eq_pgdpmp, eq_pabs, eq_pfact, eq_pwfact) are ALWAYS deactivated for inactive periods since those rows reference fixed base-period vars and would be trivially satisfied (not useful as PATH rows); the active period’s Fisher rows remain active.
Returns count of VarData entries frozen.
- equilibria.templates.gtap.gtap_multiperiod_driver.solve_multiperiod(m, params, closure, *, ref_gdx=None, skip_base_solve=False, mute_welfare=True, seed_from_prior=False, holdfix_cd=True, mode='altertax')[source]¶
Replicate GAMS loop(tsim): solve base → check → shock on the FULL model m.
PATH options: unless the caller already set PATH_CAPI_OPTIONS, each MODE defaults to the options its OWN reference bundles were solved with: altertax → the tight inline path.opt of the regenerated NEOS bundles (crash_method none, nms_searchtype line, convergence_tolerance 1e-10); gtap (pure) → PATH defaults (the pure bundles carry no path.opt). This is a solver-discipline mirror, not a tuning knob. Historical note: the June “crash phase jumps basins” episode (pure 15x10 ifsub0, default options walked into the xw=0/pe=57.7 autarky corner, 89.8%) was a corner FABRICATED by the then lb=0 boxes on xw/xet — with those domains freed (GAMS declares quantities free) the corner no longer exists and defaults land the ref root on every pure dataset, while the tight set walks 15x10 ifsub0 into an alternative Land-block root (90.91%).
Strategy (freeze_inactive_periods per period): For each period in (base, check, shock):
freeze_inactive_periods(m, period) — pin all non-active-period vars
seed active period from prior-period solved values (warm start)
apply period-specific setup (altertax elasticities, imptx shock, pnum)
call _run_path_capi_nonlinear_full(m, …) ON m ITSELF (not a temp model)
After solve, the active period vars stay fixed (freeze_inactive_periods for the next period will also freeze them — idempotent)
The multi-period model m must already have:
build_vars, build_equations_intra (all 3 periods), build_equations_fisher
Fisher rows (eq_rgdpmp, eq_pgdpmp, eq_pabs, eq_pfact, eq_pwfact) are live Jacobian rows in m; the PATH solve of each period sees them as constraints referencing the FIXED base-period vars (constants in Jacobian for check/shock).
- Parameters:
m (Pyomo ConcreteModel built by GTAPMultiPeriodModel)
params (GTAPParameters (used for altertax elasticities / imptx shock))
closure (GTAPClosureConfig or None)
ref_gdx (path to GAMS reference GDX (optional, not yet used))
skip_base_solve (bool)
mute_welfare (bool)
seed_from_prior (bool)
holdfix_cd (bool)
mode (str)
- Returns:
dict mapping “base” | “check” | “shock” → {“code”
- Return type:
int, “residual”: float}
High-level shock helpers for GTAP parameter containers.
apply_shock is the generic parent: it can shock any registered
container on a GTAPParameters instance — taxes, technical change,
endowments, elasticities — using a uniform target / mode /
filters API.
apply_tariff_shock is a thin tariff-specific wrapper kept for backward compatibility and ergonomics; new tax types only need to be added to the _REGISTRY below.
- equilibria.templates.gtap.shocks.apply_shock(params, target, value, *, mode='pct', inplace=False, predicate=None, **filters)[source]¶
Apply a generic shock to any registered parameter container.
- Parameters:
params (GTAPParameters) – Calibrated GTAPParameters to shock.
target (str) – Registered container name, e.g.
"taxes.imptx","taxes.rtf","calibrated.aoall". See list_shock_targets() for the full list.value (float) – Shock magnitude. Interpretation depends on
mode.mode (Literal['pct', 'power', 'set', 'add', 'mul', 'tm_pct']) –
One of:
"pct"— scale rate:new = old * (1 + value)"power"— scale power:new = (1 + old) * (1 + value) - 1(canonical for tariff/tax shocks à la GAMStm.fx = tm.l*1.1)"set"— replace:new = value"add"— add:new = old + value"mul"— multiply:new = old * value"tm_pct"— alias of"power"(legacy)
inplace (bool) – Mutate
paramsinstead of deep-copying.predicate (Callable[[tuple], bool] | None) – Optional
(key) -> boolused as a final filter after the named dim filters resolve.**filters (Iterable[str] | None) – Per-dimension restrictions. Valid filter names depend on the target’s registered dim names — e.g.
commodities=for any target with a commodity axis,sources=for trade tax targets,regions=/factors=/sectors=for others. Unknown filter names raiseTypeError.
- Return type:
Returns the (possibly new) GTAPParameters. Raises
ValueErrorfor unknowntargetormode.
- equilibria.templates.gtap.shocks.apply_tariff_shock(params, value, *, mode='tm_pct', commodities=None, sources=None, destinations=None, inplace=False)[source]¶
Tariff-specific wrapper around apply_shock for
taxes.imptx.Equivalent to:
apply_shock(params, "taxes.imptx", value, mode=mode, commodities=..., sources=..., destinations=..., inplace=inplace)
The default
mode="tm_pct"matches GAMStm.fx = tm.l * (1 + value)(power scaling). The diagonal (r, i, r) is skipped automatically and the legacy alias params.taxes.rtms is kept in sync — both behaviours are encoded in the registry entry fortaxes.imptx.
- equilibria.templates.gtap.shocks.list_shock_targets()[source]¶
Return every target name registered for apply_shock.
GTAP Welfare Decomposition — RunGTAP/GTAPVIEW Huff (1996) style.
- Post-processing decomposition of EV into additive contributions:
EV_r ≈ A_r + T_r + IS_r + ENDW_r + TECH_r + residual
Structure matches RunGTAP WELVIEW.har: - 11 allocative sub-buckets (one per distortion source) - T and IS deflated by pnum (numeraire ≡ pmuv proxy) - EV in USD millions via vpm_base · (uh_shock - uh_base) - Expected residual ~1-3% from levels vs linearized formulation (NOT a bug).
For exact RunGTAP equivalence use the homotopy variant compute_welfare_decomposition_homotopy(…) which sums Huff contributions over N intermediate steps (Gragg-style), driving residual to < 0.01%.
- class equilibria.templates.gtap.welfare_decomp.WelfareComponents(A=<factory>, T=0.0, IS=0.0, ENDW=0.0, TECH=0.0, EV=0.0, EV_priv=0.0, EV_gov=0.0, EV_save=0.0)[source]¶
Bases:
objectPer-region Huff welfare decomposition (USD millions, baseline prices).
- Parameters:
- equilibria.templates.gtap.welfare_decomp.compute_welfare_decomposition(base_params, shock_params, base_levels, shock_levels)[source]¶
Single-step Huff decomposition. Expected residual 1-3% for 10% shocks.
- Parameters:
- Return type:
- equilibria.templates.gtap.welfare_decomp.compute_welfare_decomposition_homotopy(step_params, step_levels)[source]¶
Sum Huff contributions across N+1 homotopy snapshots.
- Parameters:
- Return type:
The Huff functional is path-independent in the linearized GEMPACK model; summing local first-order contributions over N small steps recovers the exact decomposition with error O(1/N²). N=4 is sufficient for <0.01% residual on a 10% tariff shock.