cgemod 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cgemod/__init__.py +35 -0
- cgemod/__main__.py +45 -0
- cgemod/_util.py +151 -0
- cgemod/app.py +121 -0
- cgemod/appcore.py +54 -0
- cgemod/config.py +185 -0
- cgemod/data/cgemod_ext_reference.csv +35 -0
- cgemod/data/cgemod_nigeria_reference.csv +149 -0
- cgemod/data/cgemod_paneldata.csv +361 -0
- cgemod/data/cgemod_sam3.csv +19 -0
- cgemod/data/cgemod_sam_ext.csv +23 -0
- cgemod/data/cgemod_survey.csv +3001 -0
- cgemod/data/cgemod_tier2_reference.csv +28 -0
- cgemod/data/cgemod_tsdata.csv +61 -0
- cgemod/dynamic.py +269 -0
- cgemod/estimate.py +553 -0
- cgemod/latexdoc.py +288 -0
- cgemod/model.py +1545 -0
- cgemod/nexus.py +111 -0
- cgemod/poverty.py +194 -0
- cgemod/sam.py +770 -0
- cgemod/scenario.py +244 -0
- cgemod/ssa.py +159 -0
- cgemod/structure.py +499 -0
- cgemod/validate.py +258 -0
- cgemod-1.2.0.dist-info/METADATA +304 -0
- cgemod-1.2.0.dist-info/RECORD +31 -0
- cgemod-1.2.0.dist-info/WHEEL +5 -0
- cgemod-1.2.0.dist-info/entry_points.txt +2 -0
- cgemod-1.2.0.dist-info/licenses/LICENSE +21 -0
- cgemod-1.2.0.dist-info/top_level.txt +1 -0
cgemod/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""cgemod: computable general equilibrium modelling in Python.
|
|
2
|
+
|
|
3
|
+
The Python counterpart of the Stata package of the same name: SAM import, aggregation, audit and
|
|
4
|
+
balancing; calibration and simulation of a standard open-economy CGE model (IFPRI standard model
|
|
5
|
+
family); scenario management; model validation; systematic sensitivity analysis; poverty
|
|
6
|
+
microsimulation; and dashboards. It reproduces the Stata results, and adds user-defined
|
|
7
|
+
functional forms, variables and equations.
|
|
8
|
+
"""
|
|
9
|
+
from .sam import SAM, read_sam, read_gams, from_long, samgen
|
|
10
|
+
from .model import Model, Results, SolverError
|
|
11
|
+
from .structure import Nest, nest, default_tree, LabeledArray
|
|
12
|
+
from .validate import validate, check
|
|
13
|
+
from .ssa import ssa
|
|
14
|
+
from .scenario import Scenarios
|
|
15
|
+
from .dynamic import dynamic
|
|
16
|
+
from .poverty import poverty
|
|
17
|
+
from .estimate import estimate_elasticity, ElasticityResult
|
|
18
|
+
from .nexus import nexus_mapping, nexus_read
|
|
19
|
+
|
|
20
|
+
import os as _os
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def data_path(name: str = "") -> str:
|
|
24
|
+
"""Path of a file shipped with the package (example SAMs, survey and Stata reference results)."""
|
|
25
|
+
return _os.path.join(_os.path.dirname(__file__), "data", name)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
from .config import run_yaml, run_config # noqa: E402
|
|
29
|
+
|
|
30
|
+
__version__ = "1.2.0"
|
|
31
|
+
|
|
32
|
+
__all__ = ["SAM", "read_sam", "read_gams", "from_long", "samgen", "Model", "Results", "SolverError",
|
|
33
|
+
"validate", "check", "ssa", "Scenarios", "dynamic", "poverty", "data_path", "Nest", "nest",
|
|
34
|
+
"default_tree", "LabeledArray", "estimate_elasticity", "ElasticityResult",
|
|
35
|
+
"nexus_mapping", "nexus_read", "run_yaml", "run_config", "__version__"]
|
cgemod/__main__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Command line: ``cgemod run analysis.yaml``, ``cgemod app``, ``cgemod version``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main(argv=None) -> int:
|
|
11
|
+
ap = argparse.ArgumentParser(prog="cgemod", description="Computable general equilibrium modelling")
|
|
12
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
13
|
+
r = sub.add_parser("run", help="run the analysis described in a YAML file")
|
|
14
|
+
r.add_argument("file")
|
|
15
|
+
r.add_argument("--quiet", action="store_true")
|
|
16
|
+
a = sub.add_parser("app", help="start the interactive policy app (needs streamlit)")
|
|
17
|
+
a.add_argument("--sam", help="SAM file to open at start", default=None)
|
|
18
|
+
a.add_argument("--labelcol", type=int, default=1)
|
|
19
|
+
sub.add_parser("version", help="show the version")
|
|
20
|
+
args = ap.parse_args(argv)
|
|
21
|
+
if args.cmd == "run":
|
|
22
|
+
from .config import run_yaml
|
|
23
|
+
run_yaml(args.file, verbose=not args.quiet)
|
|
24
|
+
return 0
|
|
25
|
+
if args.cmd == "app":
|
|
26
|
+
try:
|
|
27
|
+
import streamlit # noqa: F401
|
|
28
|
+
except ImportError:
|
|
29
|
+
print("the app needs streamlit: pip install \"cgemod[app]\"", file=sys.stderr)
|
|
30
|
+
return 1
|
|
31
|
+
app = os.path.join(os.path.dirname(__file__), "app.py")
|
|
32
|
+
cmd = [sys.executable, "-m", "streamlit", "run", app, "--"]
|
|
33
|
+
if args.sam:
|
|
34
|
+
cmd += ["--sam", os.path.abspath(args.sam), "--labelcol", str(args.labelcol)]
|
|
35
|
+
return subprocess.call(cmd)
|
|
36
|
+
if args.cmd == "version":
|
|
37
|
+
from . import __version__
|
|
38
|
+
print(f"cgemod {__version__}")
|
|
39
|
+
return 0
|
|
40
|
+
ap.print_help()
|
|
41
|
+
return 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if __name__ == "__main__":
|
|
45
|
+
sys.exit(main())
|
cgemod/_util.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Small helpers shared by the cgemod modules."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Iterable, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def strtoname(s: str) -> str:
|
|
11
|
+
"""Make a valid Stata-style name, as Stata's strtoname() does.
|
|
12
|
+
|
|
13
|
+
Invalid characters become underscores, a leading digit gets an underscore in front,
|
|
14
|
+
and names are cut to 32 characters. Using the same rule as the Stata package keeps
|
|
15
|
+
account names identical in both implementations.
|
|
16
|
+
"""
|
|
17
|
+
s = str(s)
|
|
18
|
+
out = re.sub(r"[^A-Za-z0-9_]", "_", s)
|
|
19
|
+
if out == "":
|
|
20
|
+
out = "_"
|
|
21
|
+
if out[0].isdigit():
|
|
22
|
+
out = "_" + out
|
|
23
|
+
return out[:32]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find(name: str, n1: Sequence[str], n2: Sequence[str] = ()) -> int:
|
|
27
|
+
"""Index of ``name`` in n1 (or in n2 if n2 has the same length); -1 if not found."""
|
|
28
|
+
hits = [i for i, v in enumerate(n1) if v == name]
|
|
29
|
+
if len(hits) == 1:
|
|
30
|
+
return hits[0]
|
|
31
|
+
if len(n2) == len(n1):
|
|
32
|
+
hits = [i for i, v in enumerate(n2) if v == name]
|
|
33
|
+
if len(hits) == 1:
|
|
34
|
+
return hits[0]
|
|
35
|
+
return -1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def pvec(spec, n1: Sequence[str], n2: Sequence[str] = (), default: float = 0.0, what: str = "") -> np.ndarray:
|
|
39
|
+
"""Parameter vector by name.
|
|
40
|
+
|
|
41
|
+
``spec`` is None, a number, a dict {name: value}, a pandas Series, a sequence of numbers of
|
|
42
|
+
the right length, or a string such as ``"1.5 C_AGR=0.9"`` (a bare number sets all entries,
|
|
43
|
+
named entries override).
|
|
44
|
+
"""
|
|
45
|
+
n = len(n1)
|
|
46
|
+
v = np.full(n, float(default))
|
|
47
|
+
if spec is None or (isinstance(spec, str) and spec.strip() == ""):
|
|
48
|
+
return v
|
|
49
|
+
if isinstance(spec, (int, float, np.floating, np.integer)):
|
|
50
|
+
return np.full(n, float(spec))
|
|
51
|
+
if hasattr(spec, "to_dict") and not isinstance(spec, dict):
|
|
52
|
+
spec = spec.to_dict()
|
|
53
|
+
if isinstance(spec, Mapping):
|
|
54
|
+
for k, val in spec.items():
|
|
55
|
+
j = find(str(k), n1, n2)
|
|
56
|
+
if j < 0:
|
|
57
|
+
raise ValueError(f"{what}: {k} is not a valid name here")
|
|
58
|
+
v[j] = float(val)
|
|
59
|
+
return v
|
|
60
|
+
if isinstance(spec, str):
|
|
61
|
+
for tok in spec.split():
|
|
62
|
+
if "=" not in tok:
|
|
63
|
+
try:
|
|
64
|
+
v[:] = float(tok)
|
|
65
|
+
except ValueError as exc:
|
|
66
|
+
raise ValueError(f"{what}: cannot read {tok}") from exc
|
|
67
|
+
else:
|
|
68
|
+
nm, val = tok.split("=", 1)
|
|
69
|
+
j = find(nm, n1, n2)
|
|
70
|
+
if j < 0:
|
|
71
|
+
raise ValueError(f"{what}: cannot read {tok}")
|
|
72
|
+
v[j] = float(val)
|
|
73
|
+
return v
|
|
74
|
+
arr = np.asarray(spec, dtype=float).ravel()
|
|
75
|
+
if arr.size != n:
|
|
76
|
+
raise ValueError(f"{what}: expected {n} values, got {arr.size}")
|
|
77
|
+
return arr.copy()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def apply_op(x0: np.ndarray, spec, n1: Sequence[str], n2: Sequence[str] = (), what: str = "") -> np.ndarray:
|
|
81
|
+
"""Apply a shock specification to a parameter vector.
|
|
82
|
+
|
|
83
|
+
String tokens are ``NAME=v`` (set), ``NAME*v`` (multiply), ``NAME+v`` (add); an empty name
|
|
84
|
+
or ``_all`` applies to every element, e.g. ``"*0"`` or ``"C_IND=0.05 C_AGR*0.5"``.
|
|
85
|
+
A dict {name: value} sets values. A number sets every element.
|
|
86
|
+
"""
|
|
87
|
+
x = np.array(x0, dtype=float, copy=True)
|
|
88
|
+
if spec is None:
|
|
89
|
+
return x
|
|
90
|
+
if isinstance(spec, (int, float, np.floating, np.integer)):
|
|
91
|
+
x[:] = float(spec)
|
|
92
|
+
return x
|
|
93
|
+
if isinstance(spec, Mapping):
|
|
94
|
+
for k, val in spec.items():
|
|
95
|
+
j = find(str(k), n1, n2)
|
|
96
|
+
if j < 0:
|
|
97
|
+
raise ValueError(f"{what}: {k} is not a valid account name here")
|
|
98
|
+
x[j] = float(val)
|
|
99
|
+
return x
|
|
100
|
+
for tok in str(spec).split():
|
|
101
|
+
pos = [p for p in (tok.find("="), tok.find("*"), tok.find("+")) if p >= 0]
|
|
102
|
+
if not pos:
|
|
103
|
+
raise ValueError(f"{what}: token {tok} needs an operator (=, * or +), e.g. '*0.5' or 'NAME=0.1'")
|
|
104
|
+
p = min(pos)
|
|
105
|
+
op, nm = tok[p], tok[:p]
|
|
106
|
+
try:
|
|
107
|
+
val = float(tok[p + 1:])
|
|
108
|
+
except ValueError as exc:
|
|
109
|
+
raise ValueError(f"{what}: cannot read the value in {tok}") from exc
|
|
110
|
+
if nm in ("", "_all"):
|
|
111
|
+
idx: Iterable[int] = range(len(x))
|
|
112
|
+
else:
|
|
113
|
+
j = find(nm, n1, n2)
|
|
114
|
+
if j < 0:
|
|
115
|
+
raise ValueError(f"{what}: {nm} is not a valid account name here")
|
|
116
|
+
idx = [j]
|
|
117
|
+
for q in idx:
|
|
118
|
+
if op == "=":
|
|
119
|
+
x[q] = val
|
|
120
|
+
elif op == "*":
|
|
121
|
+
x[q] = x[q] * val
|
|
122
|
+
else:
|
|
123
|
+
x[q] = x[q] + val
|
|
124
|
+
return x
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def pch(a: float, b: float) -> float:
|
|
128
|
+
"""Percentage change; NaN when the base is zero."""
|
|
129
|
+
if abs(a) < 1e-12:
|
|
130
|
+
return float("nan")
|
|
131
|
+
return 100.0 * (b / a - 1.0)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def cesp(th: np.ndarray, rel: np.ndarray, sig: float) -> float:
|
|
135
|
+
"""CES unit-cost (price) index with benchmark shares ``th``."""
|
|
136
|
+
if abs(sig - 1.0) < 1e-8:
|
|
137
|
+
return float(np.exp(np.sum(th * np.log(rel))))
|
|
138
|
+
return float(np.sum(th * rel ** (1.0 - sig)) ** (1.0 / (1.0 - sig)))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def cesq(dl: np.ndarray, q: np.ndarray, sig: float) -> float:
|
|
142
|
+
"""CES quantity aggregate (index) with benchmark shares ``dl``."""
|
|
143
|
+
if abs(sig - 1.0) < 1e-8:
|
|
144
|
+
return float(np.exp(np.sum(dl * np.log(q))))
|
|
145
|
+
rr = (sig - 1.0) / sig
|
|
146
|
+
return float(np.sum(dl * q ** rr) ** (1.0 / rr))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def fischer_burmeister(a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
|
150
|
+
"""Smoothed complementarity: zero iff a >= 0, b >= 0 and a*b = 0."""
|
|
151
|
+
return a + b - np.sqrt(a ** 2 + b ** 2)
|
cgemod/app.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Interactive policy app (Streamlit). Start it with ``cgemod app`` or ``cgemod app --sam file.tab``."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
import streamlit as st
|
|
10
|
+
|
|
11
|
+
import cgemod as cg
|
|
12
|
+
from cgemod.appcore import build_shocks, run, to_excel_bytes
|
|
13
|
+
|
|
14
|
+
st.set_page_config(page_title="cgemod policy simulator", layout="wide")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _args():
|
|
18
|
+
ap = argparse.ArgumentParser()
|
|
19
|
+
ap.add_argument("--sam", default=None)
|
|
20
|
+
ap.add_argument("--labelcol", type=int, default=1)
|
|
21
|
+
a, _ = ap.parse_known_args(sys.argv[1:])
|
|
22
|
+
return a
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@st.cache_resource(show_spinner="Calibrating the model ...")
|
|
26
|
+
def load(path: str, labelcol: int, nexus: str, exchange: str, gsav: str, fiscal: str, siclosure: str,
|
|
27
|
+
demand: str):
|
|
28
|
+
if nexus != "none":
|
|
29
|
+
sam = cg.nexus_read(path, sectors=nexus, households="rural-urban", verbose=False)
|
|
30
|
+
else:
|
|
31
|
+
sam = cg.read_sam(path, labelcol=labelcol, verbose=False)
|
|
32
|
+
opts = dict(exchange=exchange, siclosure=siclosure, demand=demand)
|
|
33
|
+
if gsav == "fixed":
|
|
34
|
+
opts.update(gsav="fixed", fiscal=fiscal)
|
|
35
|
+
return cg.Model(sam, verbose=False, **opts)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
args = _args()
|
|
39
|
+
st.title("cgemod policy simulator")
|
|
40
|
+
st.caption("Computable general equilibrium model calibrated to a social accounting matrix. "
|
|
41
|
+
"Results are percentage changes from the benchmark unless stated.")
|
|
42
|
+
|
|
43
|
+
with st.sidebar:
|
|
44
|
+
st.header("Data")
|
|
45
|
+
up = st.file_uploader("SAM file (Excel, CSV or IFPRI .tab)", type=["xlsx", "xls", "csv", "tab", "txt", "inc"])
|
|
46
|
+
labelcol = st.number_input("Column with account codes", 1, 5, args.labelcol)
|
|
47
|
+
nexus = st.selectbox("IFPRI Nexus aggregation", ["none", "8", "3", "agrifood"],
|
|
48
|
+
help="Aggregate an IFPRI Nexus SAM with a built-in template")
|
|
49
|
+
if up is not None:
|
|
50
|
+
tmp = os.path.join(tempfile.gettempdir(), "cgemod_" + up.name)
|
|
51
|
+
with open(tmp, "wb") as fh:
|
|
52
|
+
fh.write(up.getvalue())
|
|
53
|
+
path = tmp
|
|
54
|
+
elif args.sam:
|
|
55
|
+
path = args.sam
|
|
56
|
+
else:
|
|
57
|
+
path = cg.data_path("cgemod_sam_ext.csv")
|
|
58
|
+
st.info("Using the example SAM shipped with cgemod.")
|
|
59
|
+
st.header("Closures")
|
|
60
|
+
exchange = st.radio("Exchange rate", ["flexible", "fixed"], horizontal=True)
|
|
61
|
+
gsav = st.radio("Government savings", ["flexible", "fixed"], horizontal=True)
|
|
62
|
+
fiscal = st.selectbox("Instrument when savings are fixed", ["dirtax", "transfers", "salestax", "spending"])
|
|
63
|
+
siclosure = st.radio("Savings-investment", ["savings", "investment"], horizontal=True)
|
|
64
|
+
demand = st.selectbox("Household demand", ["les", "ces", "aids"])
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
model = load(path, int(labelcol), nexus, exchange, gsav, fiscal, siclosure, demand)
|
|
68
|
+
except Exception as exc: # noqa: BLE001
|
|
69
|
+
st.error(f"The model could not be calibrated: {exc}")
|
|
70
|
+
st.stop()
|
|
71
|
+
|
|
72
|
+
p = model.p
|
|
73
|
+
st.subheader("Policy shocks")
|
|
74
|
+
c1, c2, c3 = st.columns(3)
|
|
75
|
+
with c1:
|
|
76
|
+
tariff = st.slider("Import tariffs (% of current rates)", 0, 200, 100, 5)
|
|
77
|
+
stax = st.slider("Sales tax rates (change, points)", -5.0, 5.0, 0.0, 0.5)
|
|
78
|
+
gov = st.slider("Government consumption (% change)", -30, 30, 0, 1)
|
|
79
|
+
with c2:
|
|
80
|
+
exp_c = st.selectbox("Export price of", ["(none)"] + [c for c, e in zip(p["com"], p["hasE"]) if e])
|
|
81
|
+
exp_pct = st.slider("World export price (% change)", -60, 60, 0, 5)
|
|
82
|
+
imp_c = st.selectbox("Import price of", ["(none)"] + [c for c, m in zip(p["com"], p["hasM"]) if m])
|
|
83
|
+
imp_pct = st.slider("World import price (% change)", -60, 100, 0, 5)
|
|
84
|
+
with c3:
|
|
85
|
+
tfp_a = st.selectbox("Productivity of", ["(all)"] + list(p["act"]))
|
|
86
|
+
tfp_pct = st.slider("Productivity (% change)", -20, 20, 0, 1)
|
|
87
|
+
fsav = st.slider("Foreign savings (% change)", -50, 50, 0, 5, disabled=exchange == "fixed")
|
|
88
|
+
|
|
89
|
+
shocks = build_shocks(tariff, stax, None if exp_c == "(none)" else exp_c, exp_pct,
|
|
90
|
+
None if imp_c == "(none)" else imp_c, imp_pct, tfp_a, tfp_pct, gov,
|
|
91
|
+
fsav if exchange == "flexible" else 0)
|
|
92
|
+
st.code(f"model.simulate({', '.join(f'{k}={v!r}' for k, v in shocks.items())})", language="python")
|
|
93
|
+
try:
|
|
94
|
+
out = run(model, shocks)
|
|
95
|
+
except Exception as exc: # noqa: BLE001
|
|
96
|
+
st.error(f"The model did not solve for this shock: {exc}")
|
|
97
|
+
st.stop()
|
|
98
|
+
|
|
99
|
+
mac = out["macro"]
|
|
100
|
+
m1, m2, m3, m4 = st.columns(4)
|
|
101
|
+
m1.metric("Real GDP", f"{mac.loc['RGDP', 'change']:.2f}%")
|
|
102
|
+
m2.metric("Household consumption", f"{mac.loc['RCONS', 'change']:.2f}%")
|
|
103
|
+
m3.metric("Exchange rate", f"{mac.loc['EXR', 'change']:.2f}%")
|
|
104
|
+
m4.metric("Real investment", f"{mac.loc['RINV', 'change']:.2f}%")
|
|
105
|
+
|
|
106
|
+
t1, t2, t3, t4 = st.tabs(["Macro", "Households", "Sectors", "Factors and prices"])
|
|
107
|
+
with t1:
|
|
108
|
+
st.bar_chart(mac.loc[mac["unit"] == "%", "change"].rename(index=dict(zip(mac.index, mac["label"]))))
|
|
109
|
+
st.dataframe(mac, use_container_width=True)
|
|
110
|
+
with t2:
|
|
111
|
+
st.bar_chart(out["households"]["EVPCT"])
|
|
112
|
+
st.dataframe(out["households"].rename(columns={"EH": "consumption %", "EV": "EV (level)", "EVPCT": "EV % of spending"}),
|
|
113
|
+
use_container_width=True)
|
|
114
|
+
with t3:
|
|
115
|
+
st.bar_chart(out["activities"]["X"])
|
|
116
|
+
st.dataframe(out["activities"], use_container_width=True)
|
|
117
|
+
with t4:
|
|
118
|
+
st.dataframe(out["factors"], use_container_width=True)
|
|
119
|
+
st.dataframe(out["prices"], use_container_width=True)
|
|
120
|
+
|
|
121
|
+
st.download_button("Download results (Excel)", to_excel_bytes(out), file_name="cgemod_results.xlsx")
|
cgemod/appcore.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Logic of the interactive policy app, kept separate from the user interface so that it can be
|
|
2
|
+
tested without Streamlit."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from .model import Model, Results
|
|
11
|
+
|
|
12
|
+
MACRO_SHOWN = ["RGDP", "RABS", "RCONS", "RINV", "REXP", "RIMP", "EXR", "RER", "GSAV"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_shocks(tariff_pct: float = 100.0, salestax_pts: float = 0.0, export_price: Optional[str] = None,
|
|
16
|
+
export_pct: float = 0.0, import_price: Optional[str] = None, import_pct: float = 0.0,
|
|
17
|
+
tfp_activity: Optional[str] = None, tfp_pct: float = 0.0, gov_pct: float = 0.0,
|
|
18
|
+
fsav_pct: float = 0.0) -> Dict[str, Any]:
|
|
19
|
+
"""Shocks from the app's controls (percentages of current values or changes in points)."""
|
|
20
|
+
sh: Dict[str, Any] = {}
|
|
21
|
+
if abs(tariff_pct - 100.0) > 1e-12:
|
|
22
|
+
sh["tm"] = f"*{tariff_pct / 100:.10g}"
|
|
23
|
+
if abs(salestax_pts) > 1e-12:
|
|
24
|
+
sh["tq"] = f"+{salestax_pts / 100:.10g}" if salestax_pts > 0 else f"+-{abs(salestax_pts) / 100:.10g}"
|
|
25
|
+
if export_price and abs(export_pct) > 1e-12:
|
|
26
|
+
sh["pwe"] = f"{export_price}*{1 + export_pct / 100:.10g}"
|
|
27
|
+
if import_price and abs(import_pct) > 1e-12:
|
|
28
|
+
sh["pwm"] = f"{import_price}*{1 + import_pct / 100:.10g}"
|
|
29
|
+
if tfp_activity and abs(tfp_pct) > 1e-12:
|
|
30
|
+
sh["tfp"] = (f"{tfp_activity}*{1 + tfp_pct / 100:.10g}" if tfp_activity != "(all)"
|
|
31
|
+
else f"*{1 + tfp_pct / 100:.10g}")
|
|
32
|
+
if abs(gov_pct) > 1e-12:
|
|
33
|
+
sh["gadj"] = 1 + gov_pct / 100
|
|
34
|
+
if abs(fsav_pct) > 1e-12:
|
|
35
|
+
sh["fsav"] = f"*{1 + fsav_pct / 100:.10g}"
|
|
36
|
+
return sh
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def run(model: Model, shocks: Dict[str, Any]) -> Dict[str, pd.DataFrame]:
|
|
40
|
+
r: Results = model.simulate(**shocks)
|
|
41
|
+
mac = r.macro.loc[MACRO_SHOWN, ["label", "change"]].copy()
|
|
42
|
+
mac["unit"] = ["%"] * 8 + ["level change"]
|
|
43
|
+
return {"macro": mac, "activities": r.activities[["X", "VA", "PA"]], "commodities": r.commodities,
|
|
44
|
+
"prices": r.prices, "factors": r.factors[["EMP", "WF", "YF"]],
|
|
45
|
+
"households": r.households[["EH", "EV", "EVPCT"]], "results": r}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def to_excel_bytes(tables: Dict[str, pd.DataFrame]) -> bytes:
|
|
49
|
+
buf = io.BytesIO()
|
|
50
|
+
with pd.ExcelWriter(buf) as xw:
|
|
51
|
+
for k, v in tables.items():
|
|
52
|
+
if isinstance(v, pd.DataFrame):
|
|
53
|
+
v.to_excel(xw, sheet_name=k[:30])
|
|
54
|
+
return buf.getvalue()
|
cgemod/config.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Run a complete analysis from a YAML file, without writing Python.
|
|
2
|
+
|
|
3
|
+
python -m cgemod run analysis.yaml
|
|
4
|
+
|
|
5
|
+
Example file::
|
|
6
|
+
|
|
7
|
+
sam:
|
|
8
|
+
file: 002_IFPRI_SAM_NGA_2018_SAM.tab
|
|
9
|
+
labelcol: 2
|
|
10
|
+
nexus: {sectors: "8", households: rural-urban} # or mapping: map.csv
|
|
11
|
+
model:
|
|
12
|
+
sigmaq: "2 cagri=1.5"
|
|
13
|
+
exchange: flexible
|
|
14
|
+
demand: aids
|
|
15
|
+
ownprice: -0.7
|
|
16
|
+
production: # optional production tree
|
|
17
|
+
nest: top
|
|
18
|
+
sigma: 0
|
|
19
|
+
children:
|
|
20
|
+
- {nest: KLE, sigma: 0.5, children: [{nest: KE, sigma: 0.3, children: [fcap, celec]}, "*factors"]}
|
|
21
|
+
- "*inputs"
|
|
22
|
+
parameters: {target: 1.0}
|
|
23
|
+
variables: {sub: 0}
|
|
24
|
+
hooks: ["ta['aagri'] = ta['aagri'] - v.sub"]
|
|
25
|
+
equations: {agri_target: "o.X['aagri'] / p.X0['aagri'] - p.target"}
|
|
26
|
+
minimum_wage: {flab_n: 1.0}
|
|
27
|
+
checks: [check, validate]
|
|
28
|
+
scenarios:
|
|
29
|
+
tariffs: {tm: "*0", description: All tariffs removed}
|
|
30
|
+
tariffs_fix: {tm: "*0", closure: {exchange: fixed}}
|
|
31
|
+
agri_push: {params: {target: 1.05}}
|
|
32
|
+
poverty: {data: survey.csv, group: group, welfare: pcexp, weight: weight, line: 167.8}
|
|
33
|
+
output: {html: dashboard.html, excel: results.xlsx, latex: model.tex}
|
|
34
|
+
|
|
35
|
+
Relative file names are read relative to the YAML file.
|
|
36
|
+
"""
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import os
|
|
40
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
41
|
+
|
|
42
|
+
import pandas as pd
|
|
43
|
+
|
|
44
|
+
from .model import SHOCK_KEYS, Model
|
|
45
|
+
from .structure import Nest, nest
|
|
46
|
+
|
|
47
|
+
_SCEN_KEYS = {"closure", "params", "description", "steps"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_tree(spec: Any) -> Any:
|
|
51
|
+
"""A production tree from a nested dict: {nest: name, sigma: s, children: [...]}."""
|
|
52
|
+
if isinstance(spec, str):
|
|
53
|
+
return spec
|
|
54
|
+
if isinstance(spec, Mapping):
|
|
55
|
+
if "nest" in spec:
|
|
56
|
+
ch = [build_tree(c) for c in spec.get("children", [])]
|
|
57
|
+
return nest(spec["nest"], spec.get("sigma", 0), *ch)
|
|
58
|
+
return {k: build_tree(v) for k, v in spec.items()}
|
|
59
|
+
raise ValueError(f"cannot read the production tree {spec!r}")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _path(base: str, f: str) -> str:
|
|
63
|
+
"""A file relative to the YAML file; names of files shipped with cgemod (such as
|
|
64
|
+
cgemod_sam_ext.csv) are found in the package data if not present there."""
|
|
65
|
+
if os.path.isabs(f):
|
|
66
|
+
return f
|
|
67
|
+
p = os.path.join(base, f)
|
|
68
|
+
if not os.path.exists(p):
|
|
69
|
+
shipped = os.path.join(os.path.dirname(__file__), "data", f)
|
|
70
|
+
if os.path.exists(shipped):
|
|
71
|
+
return shipped
|
|
72
|
+
return p
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_model(cfg: Mapping[str, Any], base: str = ".", verbose: bool = True) -> Model:
|
|
76
|
+
from .nexus import nexus_read
|
|
77
|
+
from .sam import read_sam
|
|
78
|
+
s = cfg.get("sam")
|
|
79
|
+
if not s or "file" not in s:
|
|
80
|
+
raise ValueError("the configuration needs sam: {file: ...}")
|
|
81
|
+
f = _path(base, s["file"])
|
|
82
|
+
if s.get("nexus") is not None:
|
|
83
|
+
nx = s["nexus"] or {}
|
|
84
|
+
sam = nexus_read(f, sectors=nx.get("sectors", "8"), households=nx.get("households"),
|
|
85
|
+
labour=nx.get("labour"), extra=nx.get("extra"), verbose=verbose)
|
|
86
|
+
else:
|
|
87
|
+
mapping = s.get("mapping")
|
|
88
|
+
if isinstance(mapping, str):
|
|
89
|
+
mapping = _path(base, mapping)
|
|
90
|
+
sam = read_sam(f, sheet=s.get("sheet"), labelcol=int(s.get("labelcol", 1)), merge=s.get("merge"),
|
|
91
|
+
mapping=mapping, verbose=verbose)
|
|
92
|
+
if s.get("balance"):
|
|
93
|
+
b = s["balance"] if isinstance(s["balance"], Mapping) else {"method": str(s["balance"])}
|
|
94
|
+
sam = sam.balance(show=verbose, **b)
|
|
95
|
+
if cfg.get("roles"):
|
|
96
|
+
sam.set_roles(**cfg["roles"])
|
|
97
|
+
opts = dict(cfg.get("model") or {})
|
|
98
|
+
if "production" in opts and not isinstance(opts["production"], str):
|
|
99
|
+
opts["production"] = build_tree(opts["production"])
|
|
100
|
+
m = Model(sam, verbose=verbose, solve=False, **opts)
|
|
101
|
+
for k, v in (cfg.get("parameters") or {}).items():
|
|
102
|
+
m.add_parameter(k, v)
|
|
103
|
+
vars_ = cfg.get("variables") or {}
|
|
104
|
+
if isinstance(vars_, list):
|
|
105
|
+
vars_ = {v: 0.0 for v in vars_}
|
|
106
|
+
for k, v in vars_.items():
|
|
107
|
+
m.add_variable(k, float(v))
|
|
108
|
+
for h in cfg.get("hooks") or []:
|
|
109
|
+
m.add_hook(h)
|
|
110
|
+
for k, v in (cfg.get("equations") or {}).items():
|
|
111
|
+
m.add_equation(k, v)
|
|
112
|
+
for k, v in (cfg.get("replace") or {}).items():
|
|
113
|
+
m.replace_equation(k, v)
|
|
114
|
+
for k in cfg.get("drop") or []:
|
|
115
|
+
m.drop_equation(k)
|
|
116
|
+
for c in cfg.get("complementarity") or []:
|
|
117
|
+
m.add_complementarity(c["name"], c["variable"], c["slack"])
|
|
118
|
+
for k, v in (cfg.get("minimum_wage") or {}).items():
|
|
119
|
+
m.minimum_wage(k, float(v))
|
|
120
|
+
for k, v in (cfg.get("price_floor") or {}).items():
|
|
121
|
+
m.price_floor(k, float(v))
|
|
122
|
+
for k, v in (cfg.get("capacity_limit") or {}).items():
|
|
123
|
+
m.capacity_limit(k, float(v))
|
|
124
|
+
m.solve_benchmark()
|
|
125
|
+
return m
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def run_config(cfg: Mapping[str, Any], base: str = ".", verbose: bool = True) -> Dict[str, Any]:
|
|
129
|
+
from .scenario import Scenarios
|
|
130
|
+
from .ssa import ssa as _ssa
|
|
131
|
+
from .validate import check, validate
|
|
132
|
+
m = load_model(cfg, base, verbose)
|
|
133
|
+
out: Dict[str, Any] = {"model": m}
|
|
134
|
+
for c in cfg.get("checks") or []:
|
|
135
|
+
if c == "check":
|
|
136
|
+
out["check"] = check(m, show=verbose)
|
|
137
|
+
elif c == "validate":
|
|
138
|
+
out["validate"] = validate(m, show=verbose)
|
|
139
|
+
else:
|
|
140
|
+
raise ValueError("checks may contain check and validate")
|
|
141
|
+
sc = Scenarios(m)
|
|
142
|
+
for name, spec in (cfg.get("scenarios") or {}).items():
|
|
143
|
+
spec = dict(spec or {})
|
|
144
|
+
shocks = {k: v for k, v in spec.items() if k not in _SCEN_KEYS}
|
|
145
|
+
bad = [k for k in shocks if k not in SHOCK_KEYS]
|
|
146
|
+
if bad:
|
|
147
|
+
raise ValueError(f"scenario {name}: unknown keys {bad}; shocks are {SHOCK_KEYS}")
|
|
148
|
+
sc.define(name, closure=spec.get("closure"), description=spec.get("description", ""),
|
|
149
|
+
params=spec.get("params"), **shocks)
|
|
150
|
+
pov = None
|
|
151
|
+
if cfg.get("poverty"):
|
|
152
|
+
pv = dict(cfg["poverty"])
|
|
153
|
+
pv["data"] = pd.read_csv(_path(base, pv["data"])) if str(pv["data"]).endswith(".csv") else \
|
|
154
|
+
pd.read_stata(_path(base, pv["data"]))
|
|
155
|
+
pov = pv
|
|
156
|
+
if sc.items:
|
|
157
|
+
sc.run(poverty=pov, show=verbose)
|
|
158
|
+
out["scenarios"] = sc
|
|
159
|
+
out["table"] = sc.table(show=verbose)
|
|
160
|
+
if cfg.get("ssa"):
|
|
161
|
+
sa = dict(cfg["ssa"])
|
|
162
|
+
scen = sa.pop("scenario")
|
|
163
|
+
spec = sc.items[scen]
|
|
164
|
+
shocks = {k: v for k, v in spec.shocks.items() if not k.startswith("_")}
|
|
165
|
+
el = sa.pop("elasticities", "sigmava sigmaq omega")
|
|
166
|
+
rg = float(sa.pop("range", 0.5))
|
|
167
|
+
out["ssa"] = _ssa(m, elasticities=el, range_=rg, show=verbose, **sa, **shocks)
|
|
168
|
+
o = cfg.get("output") or {}
|
|
169
|
+
if o.get("html") and sc.items:
|
|
170
|
+
sc.to_html(_path(base, o["html"]), title=o.get("title", "cgemod scenario dashboard"))
|
|
171
|
+
if o.get("excel") and sc.items:
|
|
172
|
+
sc.to_excel(_path(base, o["excel"]))
|
|
173
|
+
if o.get("csv") and sc.items:
|
|
174
|
+
sc.to_csv(_path(base, o["csv"]))
|
|
175
|
+
if o.get("latex"):
|
|
176
|
+
m.to_latex(_path(base, o["latex"]), title=o.get("title", "Model documentation"))
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def run_yaml(path: str, verbose: bool = True) -> Dict[str, Any]:
|
|
181
|
+
"""Run the analysis described in a YAML file (see the module documentation for the format)."""
|
|
182
|
+
import yaml
|
|
183
|
+
with open(path, encoding="utf-8") as fh:
|
|
184
|
+
cfg = yaml.safe_load(fh)
|
|
185
|
+
return run_config(cfg, base=os.path.dirname(os.path.abspath(path)), verbose=verbose)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
variable,default,fixer,inv,unemp
|
|
2
|
+
RGDP,-7.409252699e-05,-1.665968991e-05,-0.001063690493,4.509119108
|
|
3
|
+
EXR,6.974015875,0,6.850222516,7.430998471
|
|
4
|
+
CPI,-8.841816168e-11,-3.330669074e-14,-4.908295992e-11,-2.176037128e-12
|
|
5
|
+
RIMP,7.920638485,28.73876652,8.38680534,12.55338557
|
|
6
|
+
REXP,9.167256536,-5.66724835,9.506832853,14.80208682
|
|
7
|
+
X_A_AGR,0.2292439185,-5.127465642,-0.5260106005,5.538358859
|
|
8
|
+
PA_A_AGR,2.980703411,3.456627407,2.680507921,2.624546422
|
|
9
|
+
X_A_IND,-1.326077073,-0.09938285997,-0.1854277659,2.892202097
|
|
10
|
+
PA_A_IND,1.465751771,1.283964189,1.338662829,2.072105075
|
|
11
|
+
X_A_SER,0.726755082,4.663371734,0.5988406661,4.723854362
|
|
12
|
+
PA_A_SER,2.804163757,2.883153263,3.207622562,2.646676662
|
|
13
|
+
QX_C_AGR,0.1461513328,-5.587532134,-0.6721543846,5.564663598
|
|
14
|
+
QM_C_AGR,31.17138541,54.0616892,29.34959128,34.83938916
|
|
15
|
+
QQ_C_AGR,1.6961089,2.716695153,0.6781346693,6.328233031
|
|
16
|
+
PQ_C_AGR,-0.1816024563,0.9883710516,-0.4679392311,-0.6318429859
|
|
17
|
+
QX_C_IND,-1.326077073,-0.09938285997,-0.1854277659,2.892202097
|
|
18
|
+
QM_C_IND,10.45149996,38.72023165,11.60155046,16.23664739
|
|
19
|
+
QQ_C_IND,-0.4241633584,11.94724341,0.6714767966,4.299776035
|
|
20
|
+
PQ_C_IND,-3.07097149,-3.934693845,-3.191125476,-2.452742624
|
|
21
|
+
QX_C_SER,0.5405804571,4.230162879,0.5278168846,4.55779425
|
|
22
|
+
QM_C_SER,-7.955885885,11.27888603,-6.965862659,-5.540655043
|
|
23
|
+
QQ_C_SER,-0.5880020796,5.090508655,-0.4615696798,3.206420318
|
|
24
|
+
PQ_C_SER,2.933540229,2.90219474,3.300210024,2.777658533
|
|
25
|
+
QM_C_OIL,0.2382556338,3.041259267,0.0104302813,4.379689083
|
|
26
|
+
QQ_C_OIL,0.2382556338,3.041259267,0.0104302813,4.379689083
|
|
27
|
+
PQ_C_OIL,-1.508395551,-7.411474147,-1.58470275,-1.133834708
|
|
28
|
+
WF_LAB,4.582897506,4.998817246,4.521237442,0
|
|
29
|
+
EMP_LAB,-3.568256801e-11,-9.992007222e-14,-2.274069821e-10,8.297264691
|
|
30
|
+
WF_CAP,4.294102816,5.136568722,4.464878813,10.30976253
|
|
31
|
+
EMP_CAP,2.979838598e-11,2.220446049e-13,8.812062191e-10,3.549360805e-09
|
|
32
|
+
EV_HH_RUR,4.628243418,4.253073139,2.988548531,8.70729221
|
|
33
|
+
YH_HH_RUR,4.313757382,4.253729085,4.122525663,7.962191544
|
|
34
|
+
EV_HH_URB,5.251139291,6.006706421,-1.640237063,10.77663108
|
|
35
|
+
YH_HH_URB,4.347757999,4.717899098,3.605700689,8.821531649
|