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: ModelClosureConfig

Economic 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'])

  • fixed (Tuple[str, ...])

  • endogenous (Tuple[str, ...])

  • 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)

  • rmuv (Tuple[str, ...])

  • imuv (Tuple[str, ...])

Example

>>> closure = GTAPClosureConfig(name="gtap_standard")
>>> print(closure.numeraire)
'pnum'
name: str
numeraire: str
numeraire_mode: Literal['fixed_benchmark']
closure_type: Literal['CNS', 'MCP']
capital_mobility: Literal['mobile', 'sluggish']
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
fixed: Tuple[str, ...]
endogenous: Tuple[str, ...]
rmuv: Tuple[str, ...]
imuv: Tuple[str, ...]
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: ModelEquationConfig

Activated equation system for GTAP.

This determines which equations are included in the model.

Variables:
  • name (str) – Equation configuration name

  • include (Tuple[str, ...]) – Tuple of equation IDs to include

  • activation_masks (Literal['gtap_standard', 'all_active']) – How to handle equation activation

Parameters:
  • name (str)

  • include (Tuple[str, ...])

  • activation_masks (Literal['gtap_standard', 'all_active'])

name: str
include: Tuple[str, ...]
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: ModelBoundsConfig

Domain/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:
name: str
positive: Literal['lower_only', 'both_bounds']
fixed_from_closure: bool
free: Tuple[str, ...]
lower_bound: float
upper_bound: float | None
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: ModelContract

Resolved contract for GTAP CGE model.

This combines closure, equation, and bounds configurations into a complete model contract.

Variables:
Parameters:

Example

>>> contract = GTAPContract()
>>> print(contract.closure.name)
'gtap_standard'
name: str
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:

GTAPContract

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:

GTAPClosureConfig

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:

GTAPContract

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: object

Elasticity 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:
esubva: Dict[Tuple[str, str], float]
esubt: Dict[Tuple[str, str], float]
esubd: Dict[Tuple[str, str], float]
esubm: Dict[Tuple[str, str], float]
omegax: Dict[Tuple[str, str], float]
omegaw: Dict[Tuple[str, str], float]
omegas: Dict[Tuple[str, str], float]
sigmas: Dict[Tuple[str, str], float]
etraq: Dict[Tuple[str, str], float]
esubq: Dict[Tuple[str, str], float]
etrae: Dict[str, float]
omegaf: Dict[Tuple[str, str], float]
etaff: Dict[Tuple[str, str, str], float]
esubg: Dict[str, float]
esubi: Dict[str, float]
rorflex: Dict[str, float]
esubc: Dict[Tuple[str, str], float]
incpar: Dict[Tuple[str, str], float]
subpar: Dict[Tuple[str, str], float]
sigmam: Dict[str, float]
sigmap: Dict[Tuple[str, str], float]
sigmand: Dict[Tuple[str, str], float]
sigmav: Dict[Tuple[str, str], float]
load_from_gdx(gdx_path, sets)[source]

Load elasticities from GDX file using GTAP Standard 7 native parameter names.

Parameters:
Return type:

None

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

Parameters:
Return type:

None

calibrate_from_comp_gdx(comp_gdx, sets)[source]

Estimate sigm* elasticities using the COMP GDX time series.

Parameters:
Return type:

None

load_from_har(default_path, sets)[source]

Load elasticities from a GEMPACK default.prm file.

Parameters:
Return type:

None

initialize_nested_elasticities(sets)[source]

Ensure sigmap, sigmand and sigmav cover every (region, activity).

Parameters:

sets (GTAPSets)

Return type:

None

class equilibria.templates.gtap.gtap_parameters.GTAPCalibratedShares(and_param=<factory>, ava_param=<factory>, io_param=<factory>, af_param=<factory>, gx_param=<factory>, pva_bench=<factory>, pnd_bench=<factory>)[source]

Bases: object

GAMS-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:
and_param: Dict[Tuple[str, str], float]
ava_param: Dict[Tuple[str, str], float]
io_param: Dict[Tuple[str, str, str], float]
af_param: Dict[Tuple[str, str, str], float]
gx_param: Dict[Tuple[str, str, str], float]
pva_bench: Dict[Tuple[str, str], float]
pnd_bench: Dict[Tuple[str, str], float]
calibrate_from_benchmark(benchmark, elasticities, sets, taxes=None)[source]

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:
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: object

Benchmark SAM values from GTAP data.

These are the base year values used for calibration.

Parameters:
vom: Dict[Tuple[str, str], float]
vom_i: Dict[Tuple[str, str], float]
makb: Dict[Tuple[str, str, str], float]
maks: Dict[Tuple[str, str, str], float]
vfm: Dict[Tuple[str, str, str], float]
vfb: Dict[Tuple[str, str], float]
evfb: Dict[Tuple[str, str, str], float]
evos: Dict[Tuple[str, str, str], float]
fbep: Dict[Tuple[str, str, str], float]
ftrv: Dict[Tuple[str, str, str], float]
vmfp: Dict[Tuple[str, str, str], float]
vmfb: Dict[Tuple[str, str, str], float]
vdfm: Dict[Tuple[str, str, str], float]
vifm: Dict[Tuple[str, str, str], float]
vdfp: Dict[Tuple[str, str, str], float]
vdfb: Dict[Tuple[str, str, str], float]
vmpp: Dict[Tuple[str, str, str], float]
vmpb: Dict[Tuple[str, str, str], float]
vdpp: Dict[Tuple[str, str, str], float]
vdpb: Dict[Tuple[str, str, str], float]
vdgp: Dict[Tuple[str, str], float]
vdgb: Dict[Tuple[str, str], float]
vmgp: Dict[Tuple[str, str], float]
vmgb: Dict[Tuple[str, str], float]
vdip: Dict[Tuple[str, str], float]
vdib: Dict[Tuple[str, str], float]
vmip: Dict[Tuple[str, str], float]
vmib: Dict[Tuple[str, str], float]
vpm: Dict[Tuple[str, str], float]
vgm: Dict[Tuple[str, str], float]
vim: Dict[Tuple[str, str], float]
vxmd: Dict[Tuple[str, str, str], float]
vswd: Dict[Tuple[str, str, str], float]
vtwr: Dict[Tuple[str, str, str, str], float]
vxsb: Dict[Tuple[str, str, str], float]
vfob: Dict[Tuple[str, str, str], float]
vcif: Dict[Tuple[str, str, str], float]
vmsb: Dict[Tuple[str, str, str], float]
vst: Dict[Tuple[str, str], float]
viws: Dict[Tuple[str, str, str], float]
vims: Dict[Tuple[str, str, str], float]
save: Dict[str, float]
vdep: Dict[str, float]
vkb: Dict[str, float]
pop: Dict[str, float]
yp: Dict[str, float]
yg: Dict[str, float]
get_private_demand(region, commodity)[source]
Parameters:
  • region (str)

  • commodity (str)

Return type:

tuple[float, float, float]

get_government_demand(region, commodity)[source]
Parameters:
  • region (str)

  • commodity (str)

Return type:

tuple[float, float, float]

get_investment_demand(region, commodity)[source]
Parameters:
  • region (str)

  • commodity (str)

Return type:

tuple[float, float, float]

load_from_gdx(gdx_path, sets)[source]

Load benchmark values from GDX file using GTAP Standard 7 native parameter names.

Parameters:
Return type:

None

load_from_har(basedata_path, sets)[source]

Load benchmark values from a GEMPACK basedata.har file.

Parameters:
Return type:

None

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.

Parameters:
Return type:

tuple[float, float, float, float, float]

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: object

Tax rates for GTAP model.

All tax rates are expressed as fractions (e.g., 0.05 = 5% tax).

Parameters:
rto: Dict[Tuple[str, str], float]
rtf: Dict[Tuple[str, str, str], float]
rtfd: Dict[Tuple[str, str, str], float]
rtfi: Dict[Tuple[str, str, str], float]
rtpd: Dict[Tuple[str, str, str], float]
rtpi: Dict[Tuple[str, str, str], float]
rtgd: Dict[Tuple[str, str], float]
rtgi: Dict[Tuple[str, str], float]
rtxs: Dict[Tuple[str, str, str], float]
rtms: Dict[Tuple[str, str, str], float]
imptx: Dict[Tuple[str, str, str], float]
kappaf: Dict[Tuple[str, str], float]
kappaf_activity: Dict[Tuple[str, str, str], float]
dintx0: Dict[Tuple[str, str, str], float]
mintx0: Dict[Tuple[str, str, str], float]
load_from_gdx(gdx_path, sets)[source]

Load tax rates from GDX file.

Parameters:
Return type:

None

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:
Return type:

None

derive_trade_route_wedges(benchmark, sets)[source]

Derive trade route wedges (stub).

Parameters:
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:
Return type:

None

derive_from_benchmark(benchmark, sets)[source]

Derive ad-valorem tax rates from benchmark SAM flows (GAMS-style).

Parameters:
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: object

Snapshot of normalized shares derived from the benchmark.

Parameters:
value_added_share: Dict[Tuple[str, str], float]
intermediate_share: Dict[Tuple[str, str], float]
output_share: Dict[Tuple[str, str, str], float]
commodity_share: Dict[Tuple[str, str, str], float]
factor_supply_share: Dict[Tuple[str, str, str], float]
factor_value_share: Dict[Tuple[str, str, str], float]
armington_domestic: Dict[Tuple[str, str, str], float]
armington_import: Dict[Tuple[str, str, str], float]
armington_national: Dict[Tuple[str, str, str], float]
import_source_share: Dict[Tuple[str, str, str], float]
export_destination_share: Dict[Tuple[str, str, str], float]
domestic_supply_share: Dict[Tuple[str, str], float]
export_supply_share: Dict[Tuple[str, str], float]
update_from_shares(share_params)[source]
Parameters:

share_params (GTAPShareParameters)

Return type:

None

class equilibria.templates.gtap.gtap_parameters.GTAPShareParameters(p_gx=<factory>, p_ax=<factory>, p_va=<factory>, p_nd=<factory>, p_io=<factory>, p_alphad=<factory>, p_alpham=<factory>, p_alphan=<factory>, p_amw=<factory>, p_gw=<factory>, p_gd=<factory>, p_ge=<factory>, p_gf=<factory>, p_af=<factory>, p_axg=<factory>, p_axi=<factory>)[source]

Bases: object

Share parameters from calibration.

These are derived from the benchmark SAM and elasticities.

Parameters:
normalized: GTAPNormalizedParameters
p_gx: Dict[Tuple[str, str, str], float]
p_ax: Dict[Tuple[str, str, str], float]
p_va: Dict[Tuple[str, str], float]
p_nd: Dict[Tuple[str, str], float]
p_io: Dict[Tuple[str, str, str], float]
p_alphad: Dict[Tuple[str, str, str], float]
p_alpham: Dict[Tuple[str, str, str], float]
p_alphan: Dict[Tuple[str, str, str], float]
p_amw: Dict[Tuple[str, str, str], float]
p_gw: Dict[Tuple[str, str, str], float]
p_gd: Dict[Tuple[str, str], float]
p_ge: Dict[Tuple[str, str], float]
p_gf: Dict[Tuple[str, str, str], float]
p_af: Dict[Tuple[str, str, str], float]
p_axg: Dict[str, float]
p_axi: Dict[str, float]
calibrate(benchmark, elasticities, sets, taxes=None)[source]

Calibrate all share parameters from benchmark data.

Parameters:
Return type:

None

apply_equilibrium_snapshot(snapshot, sets)[source]

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: object

Variables that act as multipliers/technology shifters.

Parameters:
axp: Dict[Tuple[str, str], float]
lambdand: Dict[Tuple[str, str], float]
lambdava: Dict[Tuple[str, str], float]
lambdaio: Dict[Tuple[str, str, str], float]
lambdaf: Dict[Tuple[str, str, str], float]
load_from_gdx(gdx_path)[source]

Load technology shifters from the GDX.

Parameters:

gdx_path (Path)

Return type:

None

class equilibria.templates.gtap.gtap_parameters.GAMSCalibrationDump(source_gdx, derived_params=<factory>, benchmark_levels=<factory>)[source]

Bases: object

Container 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:
source_gdx: Path
derived_params: Dict[str, Dict[Tuple[str, ...], float]]
benchmark_levels: Dict[str, Dict[Tuple[str, ...], float]]
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')
classmethod from_gdx(path, *, derived_symbols=None, level_symbols=None)[source]
Parameters:
Return type:

GAMSCalibrationDump

get_derived(name)[source]
Parameters:

name (str)

Return type:

Dict[Tuple[str, …], float]

get_levels(name)[source]
Parameters:

name (str)

Return type:

Dict[Tuple[str, …], float]

class equilibria.templates.gtap.gtap_parameters.GTAPParameters(sets=<factory>, elasticities=<factory>, benchmark=<factory>, taxes=<factory>, shares=<factory>, calibrated=<factory>, shifts=<factory>)[source]

Bases: object

Complete 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
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

apply_equilibrium_snapshot(snapshot)[source]

Override share parameters using an equilibrium CSV snapshot.

Parameters:

snapshot (GTAPEquilibriumSnapshot)

Return type:

None

validate()[source]

Validate all parameters.

Return type:

Tuple[bool, List[str]]

get_info()[source]

Get summary information.

Return type:

Dict[str, Any]

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: object

GTAP 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}")
r: List[str]
i: List[str]
a: List[str]
f: List[str]
mf: List[str]
sf: List[str]
m: List[str]
marg: List[str]
h: List[str] | None = None
s: List[str] | None = None
i_to_a: Dict[str, str]
a_to_i: Dict[str, str]
output_pairs: List[Tuple[str, str]]
activity_commodities: Dict[str, List[str]]
commodity_activities: Dict[str, List[str]]
aggregation_name: str = ''
base_year: int = 2014
source_gdx: Path | None = None
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:
Return type:

None

property is_diagonal: bool

Whether activities and commodities share the same labels.

property has_multi_output_activities: bool

Whether any activity supplies more than one commodity.

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.

property structure: str

High-level output structure tag.

property n_regions: int

Number of regions.

property n_commodities: int

Number of commodities.

property n_activities: int

Number of activities/sectors.

property n_factors: int

Number of factors.

property n_mobile_factors: int

Number of mobile factors.

property n_specific_factors: int

Number of sector-specific factors.

get_region_index(region)[source]

Get index of a region.

Parameters:

region (str)

Return type:

int

get_commodity_index(commodity)[source]

Get index of a commodity.

Parameters:

commodity (str)

Return type:

int

get_activity_index(activity)[source]

Get index of an activity.

Parameters:

activity (str)

Return type:

int

get_factor_index(factor)[source]

Get index of a factor.

Parameters:

factor (str)

Return type:

int

is_mobile_factor(factor)[source]

Check if a factor is mobile.

Parameters:

factor (str)

Return type:

bool

is_specific_factor(factor)[source]

Check if a factor is sector-specific.

Parameters:

factor (str)

Return type:

bool

validate()[source]

Validate sets consistency.

Returns:

Tuple of (is_valid, error_messages)

Return type:

Tuple[bool, List[str]]

get_info()[source]

Get summary information about sets.

Return type:

Dict

load_from_har(sets_path, default_path=None)[source]

Load set definitions from a GEMPACK sets.har file.

Parameters:
  • sets_path (Path) – Path to sets.har (contains REG, COMM, ACTS, ENDW, MARG arrays).

  • default_path (Path | None) – Optional path to default.prm. If provided, EFLG header is used to classify factors into mobile/sluggish (matches GAMS getData.gms).

Return type:

None

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: Enum

Solver 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: object

Result 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
termination_condition: str | None = None
objective_value: float | None = None
solve_time: float = 0.0
iterations: int = 0
residual: float = inf
walras_value: float = inf
variables: Dict[str, Any]
success: bool = False
message: str = ''
class equilibria.templates.gtap.gtap_solver.GTAPSolver(model, closure=None, solver_name='ipopt', solver_options=None, params=None)[source]

Bases: object

Solver 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.

Parameters:

hint (Any)

Return type:

int

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:

int

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:

int

solve(warm_start=True, tee=False, keepfiles=False, report_timing=False)[source]

Solve the GTAP model.

Parameters:
  • warm_start (bool) – Use warm start if available

  • tee (bool) – Display solver output

  • keepfiles (bool) – Keep temporary files

  • report_timing (bool) – Report timing information

Returns:

SolverResult with solution status and values

Return type:

SolverResult

apply_shock(shock)[source]

Apply a shock to the model.

Parameters:

shock (Dict[str, Any]) – Dictionary describing the shock Format: {“variable”: name, “index”: (r, i, …), “value”: new_value} or list of such dictionaries

Return type:

None

get_summary()[source]

Get summary of model and solution.

Returns:

Dictionary with model summary

Return type:

Dict[str, Any]

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) -> dict

Returns {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.

Parameters:

period (str)

Return type:

int

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.

Parameters:

active_period (str)

Return type:

int

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):

  1. freeze_inactive_periods(m, period) — pin all non-active-period vars

  2. seed active period from prior-period solved values (warm start)

  3. apply period-specific setup (altertax elasticities, imptx shock, pnum)

  4. call _run_path_capi_nonlinear_full(m, …) ON m ITSELF (not a temp model)

  5. 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 GAMS tm.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 params instead of deep-copying.

  • predicate (Callable[[tuple], bool] | None) – Optional (key) -> bool used 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 raise TypeError.

Return type:

GTAPParameters

Returns the (possibly new) GTAPParameters. Raises ValueError for unknown target or mode.

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 GAMS tm.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 for taxes.imptx.

Parameters:
Return type:

GTAPParameters

equilibria.templates.gtap.shocks.list_shock_targets()[source]

Return every target name registered for apply_shock.

Return type:

list[str]

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: object

Per-region Huff welfare decomposition (USD millions, baseline prices).

Parameters:
A: Dict[str, float]
T: float = 0.0
IS: float = 0.0
ENDW: float = 0.0
TECH: float = 0.0
EV: float = 0.0
EV_priv: float = 0.0
EV_gov: float = 0.0
EV_save: float = 0.0
property A_total: float
property total: float
property residual: float
as_dict()[source]
Return type:

Dict[str, float]

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:

Dict[str, WelfareComponents]

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:

Dict[str, WelfareComponents]

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.