neuron-explorer
Qwen3.5‑4B 전용 조향형 뉴런 탐색기, 모든 MLP 뉴런을 밀어 결과를 보관·탐색
사회 회계 행렬 기반 CGE 모델을 위한 일반 라이브러리: 균형·보정·폐쇄·CET·기관·외국자본·재귀 동태와 다중 자본 스톡을 지원합니다
A general library for CGE models built on a social accounting matrix: balancing, calibration, closures, CET, institutions and foreign capital, recursive dynamics with several capital stocks, and welfa
개발 도구Python · HTMLGitHub @GustavoHM온라인운영자 미확인
써 보셨어요? 한 번만 눌러 주세요. 로그인은 필요 없어요.
개인 계정의 공개 저장소 소유자는 GitHub로 로그인해 운영자를 확인하고 소개를 직접 관리할 수 있습니다. 관리자 승인은 필요하지 않습니다.
로그인한 뒤 확인 파일을 만들어 이 저장소의 기본 브랜치에 30분 안에 커밋해 주세요. 다른 브랜치나 포크의 파일은 인정하지 않습니다. 파일을 올린 뒤 아래에서 확인하면 관리자 승인 없이 관리할 수 있습니다. 자격을 유지하려면 파일을 남겨 두세요.
로그인이 필요하면 로그인 화면으로 이동합니다. 로그인 후 이곳으로 돌아와 원하는 확인 버튼을 다시 눌러 주세요.
프로젝트 폴더에서 /nomorevibe verify를 실행하면 소유권을 확인하고 소개를 직접 관리할 수 있습니다.
1분 만에 확인하기General toolkit for SAM-based computable general equilibrium models in Python
저장소 README에서 가져옴
README 전체를 불러오는 중입니다.
README 전문 보기 ↗A general toolkit for SAM-based computable general equilibrium models in Python. You supply a social accounting matrix. The package calibrates a standard nested CGE from it, solves each period, runs a recursive-dynamic path and measures welfare. The accounting checks that make any of it believable are built in rather than left to the user.
A model is assembled from three separable objects, and keeping them separable is the point:
| Object | Says |
|---|---|
SAM | what the base year was |
ModelSpec | what is assumed about substitution and functional form |
Closure | which balances are imposed and who adjusts |
Results can turn on the last two, so both travel with the results instead of living in a branch inside a solver.
pip install cgelab # from PyPI
pip install "cgelab[parquet]" # adds pyarrow for .parquet SAMs
pip install "cgelab[dsge]" # adds dsgelab, for forward-looking investment
pip install "cgelab[ibge]" # adds xlrd, for the IBGE's supply and use tables
pip install "cgelab[plot]" # adds matplotlib, for optional robustness figures
pip install "cgelab @ git+https://github.com/GustavoHM/cgelab" # the current main branch
For development:
git clone https://github.com/GustavoHM/cgelab && cd cgelab
pip install -e ".[test]" && pytest
Requires Python 3.11+, numpy, scipy and pandas. Try it with no data at all:
cgelab # runs the bundled toy economy and prints the diagnostics
cgelab my_sam.csv --sigma-armington 2.0 --sigma-va 0.5 # the same on your own SAM
The bundled toy economy has every SAM entry written out, so the base year is known on paper and this runs as it is:
import cgelab as cge
from cgelab.examples import toy
sam, econ = toy.build()
print(cge.report(econ)) # base-year reproduction, Walras, homogeneity
base = cge.solve_period(econ)
shock = cge.solve_period(econ, scenario=cge.Scenario(
name="tax +50%", product_tax=econ.ptax * 1.5))
print(shock.summary())
A counterfactual over a horizon, and its welfare incidence:
growth = cge.Growth(labour=0.005, tfp=0.010, depreciation=0.05, discount=0.05)
years = range(2021, 2046)
W = cge.consumer_wedge(econ, {"c_ind": 0.03})
ref = cge.run_path(econ, years=years, growth=growth)
alt = cge.run_path(econ, years=years, growth=growth,
scenario=lambda y, t: cge.Scenario(consumer_wedge=W,
wedge_revenue_to="capital")
if y >= 2026 else cge.Scenario())
ev = cge.equivalent_variation(ref, alt)
print(cge.ev_by_group(ev, {"hh_1": "rich", "hh_2": "poor"}))
With your own data, the first lines change (a .parquet SAM needs the parquet extra):
sam = cge.SAM.read("my_sam.parquet") # or SAM.from_long(df) / SAM.from_square(df)
sam.check_balance() # a hard gate, not a warning
econ = cge.calibrate(sam, cge.ModelSpec(sigma_armington=2.0, sigma_va=0.5))
X = MSH @ Q.Closure).The numeraire factor's market is deliberately not solved. It is left to Walras' law, so its residual is an independent check on the accounting rather than an identity the solver was told to satisfy. It is recorded on every period.
| Capability | Entry point |
|---|---|
| SAM container, balance gate, sign-preserving RAS; GEMPACK/GTAP header array files | SAM, read_har, write_har |
| Calibration: coefficients, nests, taxes (tariff and output tax inside prices), margins, LES subsistence, institutional flows, a list of cells the model does not read | calibrate |
| Within-period equilibrium; investment, government (including deficit and revenue targets), foreign and labour closures | solve_period, Closure |
| Trade: Armington, CET, export demand and import supply curves (large country) | ModelSpec |
| Energy: a value-added-energy or capital-energy nest with interfuel substitution, emissions accounts, a carbon price, physical units | ModelSpec.energy, add_emissions, add_physical_units |
| Factor mobility (CET or logit, pools of origin); labour segments, dual markets and Harris–Todaro | ModelSpec.factor_mobility, ModelSpec.labour_segments, LabourMarket |
| Counterfactuals: taxes, wedges, endowments, ownership, productivity, own-account levels, world prices, FDI, the investment basket | Scenario |
| Recursive dynamics: several capital stocks, capital by sector, putty-clay vintages, investment allocation, foreign-owned capital, a per-year economy | run_path, Growth, ModelSpec.vintages |
| Baselines calibrated to real GDP and limited historical closures with technology and relative-preference shifters | calibrate_baseline, calibrate_historical, Baseline, Historical |
| Microsimulation: survey households reconciled with the SAM; Gini, FGT, generalised entropy, Atkinson and their decompositions; reweighting; a behavioural model (BRR) | microsimulate, inequality, poverty, Behaviour |
| Building a SAM from supply and use tables, with the provenance of every block; splitting households and labour by surveys; readers for the IBGE's tables, PNAD Contínua and POF | sut_to_sam, split_households, split_factor, , , |
docs/guide.md: the user guide, from SAM to welfaredocs/api.md: API referencedocs/whitepaper.md: the mathematics of calibration, the period equilibrium, recursive dynamics and welfare (in Portuguese)docs/design-notes.md: the accounting decisions and the errors they preventdocs/from-scripts.md: porting an existing CGE pipelinedocs/comparison.md: how this package compares with what exists, and where it does not winCHANGELOG.md, ROADMAP.md, CONTRIBUTING.mdEvery number the package produces is checked against something it did not compute itself:
stdcge and lrgcge against a line-by-line JuMP transcription of the GAMS
programs, in all 49 displayed variables, to 2.4e-12.to_jump writes the same equilibrium as a JuMP model
in which nothing is nested. validation/roundtrip_jump.py runs 50 cases; the
nested solver and Ipopt agree to 1.2e-11.pytest # the suite, without external tools
cd validation && julia --project=. -e 'using Pkg; Pkg.instantiate()' && cd ..
python validation/roundtrip_jump.py # the JuMP replica
python validation/replicate_hosoe.py # stdcge and lrgcge
cgelab covers a single-country CGE at applied scale. It does not have the
maturity of GAMS or GEMPACK, and docs/comparison.md says
where it stands. Things to know before relying on it:
sigma_va = 0 in every activity) can leave
the model without a solution under full employment of every factor.solve_period refuses that combination; near an Armington
elasticity of one it is badly conditioned.pip install "cgelab[dsge]"). run_path itself has no forward-looking agent.pip install -e) can break silently on
Python 3.14 on macOS; install from the wheel if import cgelab fails.dsgelab, by the same author, solves dynamic stochastic
general equilibrium (DSGE) models. The module cgelab.bridge uses it for the intertemporal part
of a model, a Ramsey CGE in which investment follows an Euler equation
(pip install "cgelab[dsge]").
If the package contributed to a published result, cite it as any other methodological input,
with the version, because a number that reproduces only under one version cannot be reproduced
without knowing which. CITATION.cff
holds the same metadata in the format GitHub reads.
Moreira, G. H. (2026). cgelab: A general toolkit for SAM-based computable general equilibrium models in Python (Version 0.7.0) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.23644708
@software{cgelab_2026,
author = {Moreira, Gustavo Hoffmann},
title = {{cgelab}: a general toolkit for SAM-based computable general equilibrium models in Python},
year = {2026},
version = {0.7.0},
license = {MIT},
doi = {10.5281/zenodo.23644708},
url = {https://github.com/GustavoHM/cgelab},
note = {Python package}
}
Each release is archived on Zenodo with a DOI of its own; the DOI above is that of version 0.7.0 (0.5.0 is 10.5281/zenodo.23458852). The concept DOI 10.5281/zenodo.23458851 resolves to the latest release.
read_trupnadcpof| Forward-looking investment (a Ramsey CGE solved by dsgelab) | cgelab.bridge |
| Accounts: GDP from both sides, Laspeyres, Paasche and Fisher indices, terms of trade, the government account | national_accounts, price_indices, government_account |
| Decompositions: subtotals by shock, Huff-Hertel welfare decomposition | subtotals, welfare_decomposition |
| SAM multipliers, linkages, structural path analysis | accounting_multipliers, linkages, structural_paths |
| Systematic sensitivity and one-call robustness reports: quadrature, Monte Carlo, Sobol, SAM draws, closure grids, money and optional figures | sensitivity, spec_sweep, sobol, sam_draws, sam_sweep, closure_sweep, in_money, robustness_report |
| Minimum-distance matching of model outcomes to external coefficients, with covariance weighting and bounded elasticities | match_targets, MatchResult |
| Treated-minus-control contrasts of solved regional outcomes, with custom measures and control weights | treated_vs_control |
| Regional investment driven by saving or held fixed in real terms, with a per-capita forced-saving levy | Closure(investment="fixed_real"), Scenario.investment_level |
| Optional government and investment accounts mapped by region, with factor income and household saving included | ModelSpec.regional_government, ModelSpec.regional_investment |
| Factor migration between regional pools, with CET/logit proximity matrices and origin income preserved | ModelSpec.factor_migration, calibrate(factor_pools=) |
Capital stock per region in run_path, and a tidy simulated region-by-year panel with optional ex-post noise | run_path, simulated_panel |
| Welfare: EV, CV and composition-immune group aggregation | cgelab.welfare |
| Base-year reproduction, homogeneity, Walras | cgelab.diagnostics |
| The same equilibrium as a JuMP model, for independent validation | to_jump |