policyengine-core 0.1.0__tar.gz
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.
- PolicyEngine-Core-0.1.0/PKG-INFO +10 -0
- PolicyEngine-Core-0.1.0/PolicyEngine_Core.egg-info/PKG-INFO +10 -0
- PolicyEngine-Core-0.1.0/PolicyEngine_Core.egg-info/SOURCES.txt +11 -0
- PolicyEngine-Core-0.1.0/PolicyEngine_Core.egg-info/dependency_links.txt +1 -0
- PolicyEngine-Core-0.1.0/PolicyEngine_Core.egg-info/requires.txt +6 -0
- PolicyEngine-Core-0.1.0/PolicyEngine_Core.egg-info/top_level.txt +1 -0
- PolicyEngine-Core-0.1.0/README.md +3 -0
- PolicyEngine-Core-0.1.0/policyengine_core/__init__.py +0 -0
- PolicyEngine-Core-0.1.0/policyengine_core/reforms/__init__.py +1 -0
- PolicyEngine-Core-0.1.0/policyengine_core/reforms/utils.py +68 -0
- PolicyEngine-Core-0.1.0/policyengine_core/server.py +194 -0
- PolicyEngine-Core-0.1.0/setup.cfg +4 -0
- PolicyEngine-Core-0.1.0/setup.py +19 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 1.0
|
|
2
|
+
Name: PolicyEngine-Core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: UNKNOWN
|
|
5
|
+
Home-page: https://github.com/policyengine/policyengine-core
|
|
6
|
+
Author: PolicyEngine
|
|
7
|
+
Author-email: UNKNOWN
|
|
8
|
+
License: http://www.fsf.org/licensing/licenses/agpl-3.0.html
|
|
9
|
+
Description: UNKNOWN
|
|
10
|
+
Platform: UNKNOWN
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 1.0
|
|
2
|
+
Name: PolicyEngine-Core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: UNKNOWN
|
|
5
|
+
Home-page: https://github.com/policyengine/policyengine-core
|
|
6
|
+
Author: PolicyEngine
|
|
7
|
+
Author-email: UNKNOWN
|
|
8
|
+
License: http://www.fsf.org/licensing/licenses/agpl-3.0.html
|
|
9
|
+
Description: UNKNOWN
|
|
10
|
+
Platform: UNKNOWN
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
setup.py
|
|
3
|
+
PolicyEngine_Core.egg-info/PKG-INFO
|
|
4
|
+
PolicyEngine_Core.egg-info/SOURCES.txt
|
|
5
|
+
PolicyEngine_Core.egg-info/dependency_links.txt
|
|
6
|
+
PolicyEngine_Core.egg-info/requires.txt
|
|
7
|
+
PolicyEngine_Core.egg-info/top_level.txt
|
|
8
|
+
policyengine_core/__init__.py
|
|
9
|
+
policyengine_core/server.py
|
|
10
|
+
policyengine_core/reforms/__init__.py
|
|
11
|
+
policyengine_core/reforms/utils.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
policyengine_core
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# policyengine-core
|
|
2
|
+
|
|
3
|
+
This repository contains the core infrastructure for PolicyEngine sites in order to reduce code duplication. Namely, `policyengine_core`, a Python package which contains the server-side implementations, and `policyengine-client`, a React library containing high-level components to build the client-side interface.
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from policyengine_core.reforms.utils import structural, parametric
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utility functions for writing reforms.
|
|
3
|
+
"""
|
|
4
|
+
from typing import Type
|
|
5
|
+
from openfisca_core.reforms.reform import Reform
|
|
6
|
+
from openfisca_core.tracers.tracing_parameter_node_at_instant import (
|
|
7
|
+
ParameterNode,
|
|
8
|
+
)
|
|
9
|
+
from openfisca_core.variables import Variable
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def structural(variable: Type[Variable]) -> Reform:
|
|
13
|
+
"""Generates a structural reform.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
variable (Type[Variable]): The class definition of a variable to replace.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
Reform: The reform object.
|
|
20
|
+
"""
|
|
21
|
+
return type(
|
|
22
|
+
variable.__name__,
|
|
23
|
+
(Reform,),
|
|
24
|
+
dict(apply=lambda self: self.update_variable(variable)),
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parametric(
|
|
29
|
+
parameter: str, value: float, period: str = "year:2015:10"
|
|
30
|
+
) -> Reform:
|
|
31
|
+
"""Generates a parametric reform.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
parameter (str): The name of the parameter, e.g. tax.income_tax.rate.
|
|
35
|
+
value (float): The value to set as the parameter value.
|
|
36
|
+
period (str): The time period to set it for. Defaults to a ten-year period from 2015 to 2025.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
Reform: The reform object.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def modifier_fn(parameters: ParameterNode):
|
|
43
|
+
node = parameters
|
|
44
|
+
for name in parameter.split("."):
|
|
45
|
+
try:
|
|
46
|
+
if "[" not in name:
|
|
47
|
+
node = node.children[name]
|
|
48
|
+
else:
|
|
49
|
+
try:
|
|
50
|
+
name, index = name.split("[")
|
|
51
|
+
index = int(index[:-1])
|
|
52
|
+
node = node.children[name].brackets[index]
|
|
53
|
+
except:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
"Invalid bracket syntax (should be e.g. tax.brackets[3].rate"
|
|
56
|
+
)
|
|
57
|
+
except:
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"Could not find the parameter (failed at {name})."
|
|
60
|
+
)
|
|
61
|
+
node.update(period=period, value=value)
|
|
62
|
+
return parameters
|
|
63
|
+
|
|
64
|
+
return type(
|
|
65
|
+
parameter,
|
|
66
|
+
(Reform,),
|
|
67
|
+
dict(apply=lambda self: self.modify_parameters(modifier_fn)),
|
|
68
|
+
)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The PolicyEngine server logic (Flask-based).
|
|
3
|
+
"""
|
|
4
|
+
from flask import Flask, request, make_response, send_from_directory
|
|
5
|
+
from flask_cors import CORS
|
|
6
|
+
import logging
|
|
7
|
+
from time import time
|
|
8
|
+
|
|
9
|
+
class PolicyEngine:
|
|
10
|
+
static_folder: str
|
|
11
|
+
version: str
|
|
12
|
+
use_cache: bool
|
|
13
|
+
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.app = Flask(type(self).__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
VERSION = "0.1.5"
|
|
20
|
+
USE_CACHE = True
|
|
21
|
+
logging.getLogger("werkzeug").disabled = True
|
|
22
|
+
|
|
23
|
+
client = storage.Client()
|
|
24
|
+
bucket = client.get_bucket("uk-policy-engine.appspot.com")
|
|
25
|
+
|
|
26
|
+
baseline = Microsimulation(use_current_parameters())
|
|
27
|
+
baseline_microsim = baseline
|
|
28
|
+
|
|
29
|
+
app = Flask(__name__, static_url_path="")
|
|
30
|
+
logging.getLogger("werkzeug").disabled = True
|
|
31
|
+
CORS(app)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def static_site():
|
|
35
|
+
return send_from_directory("static", "index.html")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
STATIC_SITE_ROUTES = (
|
|
39
|
+
"/",
|
|
40
|
+
"/faq",
|
|
41
|
+
"/situation",
|
|
42
|
+
"/population-results",
|
|
43
|
+
"/situation-results",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
for route in STATIC_SITE_ROUTES:
|
|
47
|
+
static_site = app.route(route)(static_site)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@app.route("/api/ubi")
|
|
51
|
+
def ubi():
|
|
52
|
+
start_time = time()
|
|
53
|
+
app.logger.info("UBI size request received")
|
|
54
|
+
params = {**request.args, **(request.json or {})}
|
|
55
|
+
request_id = "ubi-" + dict_to_string(params) + "-" + VERSION
|
|
56
|
+
blob = bucket.blob(request_id + ".json")
|
|
57
|
+
if blob.exists() and USE_CACHE:
|
|
58
|
+
app.logger.info("Returning cached response")
|
|
59
|
+
result = json.loads(blob.download_as_string())
|
|
60
|
+
return result
|
|
61
|
+
reform, _ = create_reform(params, return_names=True)
|
|
62
|
+
reformed = Microsimulation(reform)
|
|
63
|
+
revenue = (
|
|
64
|
+
baseline.calc("net_income").sum() - reformed.calc("net_income").sum()
|
|
65
|
+
)
|
|
66
|
+
UBI_amount = max(0, revenue / baseline.calc("people").sum())
|
|
67
|
+
result = {"UBI": float(UBI_amount)}
|
|
68
|
+
if USE_CACHE:
|
|
69
|
+
blob.upload_from_string(json.dumps(result))
|
|
70
|
+
gc.collect()
|
|
71
|
+
duration = time() - start_time
|
|
72
|
+
app.logger.info(f"UBI size calculation completed ({round(duration, 2)}s)")
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@app.route("/api/population-reform")
|
|
77
|
+
def population_reform():
|
|
78
|
+
start_time = time()
|
|
79
|
+
app.logger.info("Population reform request received")
|
|
80
|
+
params = {**request.args, **(request.json or {})}
|
|
81
|
+
request_id = "population-" + dict_to_string(params) + "-" + VERSION
|
|
82
|
+
blob = bucket.blob(request_id + ".json")
|
|
83
|
+
if blob.exists() and USE_CACHE:
|
|
84
|
+
app.logger.info("Returning cached response")
|
|
85
|
+
result = json.loads(blob.download_as_string())
|
|
86
|
+
return result
|
|
87
|
+
reform, components = create_reform(params, return_names=True)
|
|
88
|
+
reformed = Microsimulation(reform)
|
|
89
|
+
result = dict(
|
|
90
|
+
**headline_metrics(baseline, reformed),
|
|
91
|
+
decile_chart=decile_chart(baseline, reformed),
|
|
92
|
+
age_chart=age_chart(baseline, reformed),
|
|
93
|
+
poverty_chart=poverty_chart(baseline, reformed),
|
|
94
|
+
waterfall_chart=population_waterfall_chart(
|
|
95
|
+
reform, components, baseline, reformed
|
|
96
|
+
),
|
|
97
|
+
intra_decile_chart=intra_decile_chart(baseline, reformed),
|
|
98
|
+
)
|
|
99
|
+
del reformed
|
|
100
|
+
del reform
|
|
101
|
+
if USE_CACHE:
|
|
102
|
+
blob.upload_from_string(json.dumps(result))
|
|
103
|
+
gc.collect()
|
|
104
|
+
duration = time() - start_time
|
|
105
|
+
app.logger.info(f"Population reform completed ({round(duration, 2)}s)")
|
|
106
|
+
return result
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def dict_to_string(d):
|
|
110
|
+
return "_".join(["_".join((x, y)) for x, y in d.items()])
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@app.route("/api/situation-reform", methods=["GET", "POST"])
|
|
114
|
+
def situation_reform():
|
|
115
|
+
start_time = time()
|
|
116
|
+
app.logger.info("Situation reform request received")
|
|
117
|
+
params = {**request.args, **(request.json or {})}
|
|
118
|
+
request_id = "situation-" + dict_to_string(params) + "-" + VERSION
|
|
119
|
+
blob = bucket.blob(request_id + ".json")
|
|
120
|
+
if blob.exists() and USE_CACHE:
|
|
121
|
+
app.logger.info("Returning cached response")
|
|
122
|
+
result = json.loads(blob.download_as_string())
|
|
123
|
+
return result
|
|
124
|
+
app.logger.info("Creating situation")
|
|
125
|
+
situation = create_situation(params)
|
|
126
|
+
app.logger.info("Creating reform")
|
|
127
|
+
reform, subreform_labels = create_reform(params, return_names=True)
|
|
128
|
+
baseline_config = use_current_parameters(), add_LVT()
|
|
129
|
+
reform_config = use_current_parameters(), reform
|
|
130
|
+
app.logger.info("Creating baseline individualsim")
|
|
131
|
+
baseline = situation(IndividualSim(baseline_config, year=2021))
|
|
132
|
+
app.logger.info("Creating reform individualsim")
|
|
133
|
+
reformed = situation(IndividualSim(reform_config, year=2021))
|
|
134
|
+
app.logger.info("Headline figures")
|
|
135
|
+
headlines = headline_figures(baseline, reformed)
|
|
136
|
+
app.logger.info("waterfall")
|
|
137
|
+
waterfall = household_waterfall_chart(
|
|
138
|
+
reform, subreform_labels, situation, baseline, reformed
|
|
139
|
+
)
|
|
140
|
+
app.logger.info("Varying baseline")
|
|
141
|
+
baseline.vary("employment_income", step=10)
|
|
142
|
+
app.logger.info("Varying reform")
|
|
143
|
+
reformed.vary("employment_income", step=10)
|
|
144
|
+
app.logger.info("Budget")
|
|
145
|
+
budget = budget_chart(baseline, reformed)
|
|
146
|
+
app.logger.info("mtr chart")
|
|
147
|
+
mtr = mtr_chart(baseline, reformed)
|
|
148
|
+
del situation
|
|
149
|
+
del reform
|
|
150
|
+
del baseline
|
|
151
|
+
del reformed
|
|
152
|
+
result = dict(
|
|
153
|
+
**headlines,
|
|
154
|
+
waterfall_chart=waterfall,
|
|
155
|
+
budget_chart=budget,
|
|
156
|
+
mtr_chart=mtr,
|
|
157
|
+
)
|
|
158
|
+
if USE_CACHE:
|
|
159
|
+
blob.upload_from_string(json.dumps(result))
|
|
160
|
+
gc.collect()
|
|
161
|
+
duration = time() - start_time
|
|
162
|
+
app.logger.info(f"Situation reform completed ({round(duration, 2)}s)")
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@app.after_request
|
|
167
|
+
def after_request_func(response):
|
|
168
|
+
origin = request.headers.get("Origin")
|
|
169
|
+
if request.method == "OPTIONS":
|
|
170
|
+
response = make_response()
|
|
171
|
+
response.headers.add("Access-Control-Allow-Credentials", "true")
|
|
172
|
+
response.headers.add("Access-Control-Allow-Headers", "Content-Type")
|
|
173
|
+
response.headers.add("Access-Control-Allow-Headers", "x-csrf-token")
|
|
174
|
+
response.headers.add(
|
|
175
|
+
"Access-Control-Allow-Methods",
|
|
176
|
+
"GET, POST, OPTIONS, PUT, PATCH, DELETE",
|
|
177
|
+
)
|
|
178
|
+
if origin:
|
|
179
|
+
response.headers.add("Access-Control-Allow-Origin", origin)
|
|
180
|
+
else:
|
|
181
|
+
response.headers.add("Access-Control-Allow-Credentials", "true")
|
|
182
|
+
if origin:
|
|
183
|
+
response.headers.add("Access-Control-Allow-Origin", origin)
|
|
184
|
+
response.headers[
|
|
185
|
+
"Cache-Control"
|
|
186
|
+
] = "no-cache, no-store, must-revalidate, public, max-age=0"
|
|
187
|
+
response.headers["Pragma"] = "no-cache"
|
|
188
|
+
response.headers["Expires"] = "0"
|
|
189
|
+
|
|
190
|
+
return response
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
app.run()
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from setuptools import setup, find_packages
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
setup(
|
|
5
|
+
name="PolicyEngine-Core",
|
|
6
|
+
version="0.1.0",
|
|
7
|
+
author="PolicyEngine",
|
|
8
|
+
license="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
|
|
9
|
+
url="https://github.com/policyengine/policyengine-core",
|
|
10
|
+
install_requires=[
|
|
11
|
+
"plotly",
|
|
12
|
+
"flask",
|
|
13
|
+
"flask_cors",
|
|
14
|
+
"kaleido",
|
|
15
|
+
"google-cloud-storage>=1.42.0",
|
|
16
|
+
"gunicorn",
|
|
17
|
+
],
|
|
18
|
+
packages=find_packages(),
|
|
19
|
+
)
|