policyengine-core 0.1.2__tar.gz → 0.1.4__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.
Files changed (34) hide show
  1. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/PKG-INFO +5 -4
  2. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/PolicyEngine_Core.egg-info/PKG-INFO +5 -4
  3. PolicyEngine-Core-0.1.4/PolicyEngine_Core.egg-info/SOURCES.txt +29 -0
  4. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/PolicyEngine_Core.egg-info/requires.txt +6 -0
  5. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/__init__.py +1 -0
  6. PolicyEngine-Core-0.1.4/policyengine_core/charts/__init__.py +0 -0
  7. PolicyEngine-Core-0.1.4/policyengine_core/charts/hypothetical/__init__.py +0 -0
  8. PolicyEngine-Core-0.1.4/policyengine_core/charts/hypothetical/varying.py +3 -0
  9. PolicyEngine-Core-0.1.4/policyengine_core/charts/hypothetical/waterfall.py +0 -0
  10. PolicyEngine-Core-0.1.4/policyengine_core/charts/population/__init__.py +0 -0
  11. PolicyEngine-Core-0.1.4/policyengine_core/charts/population/distributional.py +3 -0
  12. PolicyEngine-Core-0.1.4/policyengine_core/charts/population/poverty.py +3 -0
  13. PolicyEngine-Core-0.1.4/policyengine_core/charts/population/waterfall.py +3 -0
  14. PolicyEngine-Core-0.1.4/policyengine_core/metrics/__init__.py +0 -0
  15. PolicyEngine-Core-0.1.4/policyengine_core/metrics/hypothetical.py +3 -0
  16. PolicyEngine-Core-0.1.4/policyengine_core/metrics/population.py +53 -0
  17. PolicyEngine-Core-0.1.4/policyengine_core/server.py +105 -0
  18. PolicyEngine-Core-0.1.4/policyengine_core/utils/__init__.py +0 -0
  19. PolicyEngine-Core-0.1.4/policyengine_core/utils/formatting.py +3 -0
  20. PolicyEngine-Core-0.1.4/policyengine_core/utils/general.py +42 -0
  21. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/setup.py +7 -1
  22. PolicyEngine-Core-0.1.2/PolicyEngine_Core.egg-info/SOURCES.txt +0 -16
  23. PolicyEngine-Core-0.1.2/README.md +0 -3
  24. PolicyEngine-Core-0.1.2/policyengine_core/server.py +0 -194
  25. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/PolicyEngine_Core.egg-info/dependency_links.txt +0 -0
  26. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/PolicyEngine_Core.egg-info/top_level.txt +0 -0
  27. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/api/__init__.py +0 -0
  28. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/api/cloud_run.py +0 -0
  29. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/api/general.py +0 -0
  30. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/api/hypothetical.py +0 -0
  31. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/api/microsimulation.py +0 -0
  32. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/reforms/__init__.py +0 -0
  33. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/policyengine_core/reforms/utils.py +0 -0
  34. {PolicyEngine-Core-0.1.2 → PolicyEngine-Core-0.1.4}/setup.cfg +0 -0
@@ -1,10 +1,11 @@
1
- Metadata-Version: 1.0
1
+ Metadata-Version: 2.1
2
2
  Name: PolicyEngine-Core
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: UNKNOWN
5
5
  Home-page: https://github.com/policyengine/policyengine-core
6
6
  Author: PolicyEngine
7
- Author-email: UNKNOWN
8
7
  License: http://www.fsf.org/licensing/licenses/agpl-3.0.html
9
- Description: UNKNOWN
10
8
  Platform: UNKNOWN
9
+
10
+ UNKNOWN
11
+
@@ -1,10 +1,11 @@
1
- Metadata-Version: 1.0
1
+ Metadata-Version: 2.1
2
2
  Name: PolicyEngine-Core
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: UNKNOWN
5
5
  Home-page: https://github.com/policyengine/policyengine-core
6
6
  Author: PolicyEngine
7
- Author-email: UNKNOWN
8
7
  License: http://www.fsf.org/licensing/licenses/agpl-3.0.html
9
- Description: UNKNOWN
10
8
  Platform: UNKNOWN
9
+
10
+ UNKNOWN
11
+
@@ -0,0 +1,29 @@
1
+ setup.py
2
+ PolicyEngine_Core.egg-info/PKG-INFO
3
+ PolicyEngine_Core.egg-info/SOURCES.txt
4
+ PolicyEngine_Core.egg-info/dependency_links.txt
5
+ PolicyEngine_Core.egg-info/requires.txt
6
+ PolicyEngine_Core.egg-info/top_level.txt
7
+ policyengine_core/__init__.py
8
+ policyengine_core/server.py
9
+ policyengine_core/api/__init__.py
10
+ policyengine_core/api/cloud_run.py
11
+ policyengine_core/api/general.py
12
+ policyengine_core/api/hypothetical.py
13
+ policyengine_core/api/microsimulation.py
14
+ policyengine_core/charts/__init__.py
15
+ policyengine_core/charts/hypothetical/__init__.py
16
+ policyengine_core/charts/hypothetical/varying.py
17
+ policyengine_core/charts/hypothetical/waterfall.py
18
+ policyengine_core/charts/population/__init__.py
19
+ policyengine_core/charts/population/distributional.py
20
+ policyengine_core/charts/population/poverty.py
21
+ policyengine_core/charts/population/waterfall.py
22
+ policyengine_core/metrics/__init__.py
23
+ policyengine_core/metrics/hypothetical.py
24
+ policyengine_core/metrics/population.py
25
+ policyengine_core/reforms/__init__.py
26
+ policyengine_core/reforms/utils.py
27
+ policyengine_core/utils/__init__.py
28
+ policyengine_core/utils/formatting.py
29
+ policyengine_core/utils/general.py
@@ -4,3 +4,9 @@ flask_cors
4
4
  kaleido
5
5
  google-cloud-storage>=1.42.0
6
6
  gunicorn
7
+ OpenFisca-Core
8
+ microdf_python
9
+ numpy
10
+ pandas
11
+ tables
12
+ wheel
@@ -1 +1,2 @@
1
1
  from policyengine_core.api import Microsimulation, IndividualSim
2
+ from policyengine_core.server import PolicyEngine
@@ -0,0 +1,3 @@
1
+ """
2
+ Functions to generate budget and MTR charts as earnings vary.
3
+ """
@@ -0,0 +1,3 @@
1
+ """
2
+ Distributional charts (e.g. inter-decile and intra-decile) for reforms.
3
+ """
@@ -0,0 +1,3 @@
1
+ """
2
+ Charts showing changes to poverty and inequality.
3
+ """
@@ -0,0 +1,3 @@
1
+ """
2
+ Waterfall charts, breaking down sequential impacts.
3
+ """
@@ -0,0 +1,3 @@
1
+ """
2
+ Functions extracting numerical outputs from simulations results on hypothetical situations.
3
+ """
@@ -0,0 +1,53 @@
1
+ """
2
+ Functions generating aggregates and other numerical outputs from microsimulation results.
3
+ """
4
+ from policyengine_core.api.microsimulation import Microsimulation
5
+
6
+
7
+ def gbp(x: float) -> str:
8
+ return f"£{round(x / 1e+9, 1)}bn"
9
+
10
+
11
+ def pct_change(x: float, y: float) -> float:
12
+ return (y - x) / x
13
+
14
+
15
+ def poverty_rate(sim: Microsimulation, population_var: str) -> float:
16
+ return sim.calc("in_poverty_bhc", map_to="person", period=2021)[
17
+ sim.calc(population_var) > 0
18
+ ].mean()
19
+
20
+
21
+ def headline_metrics(
22
+ baseline: Microsimulation, reformed: Microsimulation
23
+ ) -> dict:
24
+ """Compute headline society-wide metrics.
25
+
26
+ :param baseline: Baseline simulation.
27
+ :type baseline: Microsimulation
28
+ :param reformed: Reform simulation.
29
+ :type reformed: Microsimulation
30
+ :return: Dictionary with net_cost, poverty_change, winner_share,
31
+ loser_share, and gini_change.
32
+ :rtype: dict
33
+ """
34
+ new_income = reformed.calc("equiv_household_net_income", map_to="person")
35
+ old_income = baseline.calc("equiv_household_net_income", map_to="person")
36
+ gain = new_income - old_income
37
+ net_cost = (
38
+ reformed.calc("net_income").sum() - baseline.calc("net_income").sum()
39
+ )
40
+ poverty_change = pct_change(
41
+ baseline.calc("in_poverty_bhc", map_to="person").mean(),
42
+ reformed.calc("in_poverty_bhc", map_to="person").mean(),
43
+ )
44
+ winner_share = (gain > 0).mean()
45
+ loser_share = (gain < 0).mean()
46
+ gini_change = pct_change(old_income.gini(), new_income.gini())
47
+ return dict(
48
+ net_cost=gbp(net_cost),
49
+ poverty_change=float(poverty_change),
50
+ winner_share=float(winner_share),
51
+ loser_share=float(loser_share),
52
+ gini_change=float(gini_change),
53
+ )
@@ -0,0 +1,105 @@
1
+ """
2
+ The PolicyEngine server logic (Flask-based).
3
+ """
4
+ from typing import Callable, Tuple
5
+ from flask import Flask, request, make_response, send_from_directory
6
+ from flask_cors import CORS
7
+ import logging
8
+ from time import time
9
+
10
+ from policyengine_core.utils.general import (
11
+ dict_to_string,
12
+ get_cached_result,
13
+ after_request_func,
14
+ )
15
+
16
+
17
+ class PolicyEngine:
18
+ static_folder: str = "static"
19
+ version: str
20
+ cache_bucket_name: str = None
21
+ Microsimulation: type
22
+ IndividualSim: type
23
+ default_reform: type
24
+ default_dataset: type
25
+ client_endpoints: Tuple[str] = (
26
+ "/",
27
+ "/population-impact",
28
+ "/household",
29
+ "/household-impact",
30
+ "/faq",
31
+ )
32
+ api_endpoints: Tuple[str] = ("population_reform", "household_reform")
33
+
34
+ def __init__(self):
35
+ # Set up Flask server and caching
36
+ self.app = Flask(
37
+ type(self).__name__,
38
+ static_url_path="",
39
+ static_folder=self.static_folder,
40
+ )
41
+ self.app.logger.info("Initialising server.")
42
+ CORS(self.app)
43
+ if self.cache_bucket_name is not None:
44
+ from google.cloud import storage
45
+
46
+ self.cache = storage.Client().get_bucket(self.cache_bucket_name)
47
+ else:
48
+ self.cache = None
49
+
50
+ # Forward client endpoints to React and API endpoints to Flask
51
+
52
+ def static_site():
53
+ return send_from_directory(self.static_folder, "index.html")
54
+
55
+ for route in self.client_endpoints:
56
+ static_site = self.app.route(route)(static_site)
57
+
58
+ def timed_endpoint(fn):
59
+ def new_fn(*args, **kwargs):
60
+ start_time = time()
61
+ result = fn(*args, **kwargs)
62
+ duration = time() - start_time
63
+ self.app.logger.info(
64
+ f"{fn.__name__} completed in {round(duration, 1)}s."
65
+ )
66
+ return result
67
+
68
+ return new_fn
69
+
70
+ def pass_params_and_cache(fn):
71
+ def new_fn(*args, **kwargs):
72
+ params = {**request.args, **(request.json or {})}
73
+ if self.cache is not None:
74
+ cached_result = get_cached_result(
75
+ params, fn.__name__, self.version, self.cache
76
+ )
77
+ return cached_result
78
+ else:
79
+ return fn(*args, params=params, **kwargs)
80
+
81
+ return new_fn
82
+
83
+ self.api_decorators = (
84
+ timed_endpoint,
85
+ pass_params_and_cache,
86
+ )
87
+
88
+ for route in self.api_endpoints:
89
+ for decorator in (
90
+ *self.api_decorators,
91
+ self.app.route(f"/api/{route.replace('_', '-')}"),
92
+ ):
93
+ new_fn = decorator(getattr(self, route))
94
+ new_fn.__name__ = route
95
+ setattr(self, route, new_fn)
96
+
97
+ self.after_request_func = self.app.after_request(after_request_func)
98
+
99
+ # Initialise baseline simulation
100
+
101
+ self.baseline = self.Microsimulation(
102
+ self.default_reform, dataset=self.default_dataset
103
+ )
104
+
105
+ self.app.logger.info("Initialisation complete.")
@@ -0,0 +1,3 @@
1
+ """
2
+ Utility functions for formatting charts.
3
+ """
@@ -0,0 +1,42 @@
1
+ import json
2
+ from time import time
3
+ from flask import request, make_response
4
+
5
+
6
+ def dict_to_string(d: dict) -> str:
7
+ return "_".join(["_".join((x, y)) for x, y in d.items()])
8
+
9
+
10
+ def get_cached_result(
11
+ params: dict, endpoint: str, version: str, bucket
12
+ ) -> dict:
13
+ request_id = f"{endpoint}-{dict_to_string(params)}-{version}"
14
+ blob = bucket.blob(request_id + ".json")
15
+ if blob.exists():
16
+ return json.loads(blob.download_as_string())
17
+
18
+
19
+ def after_request_func(response):
20
+ origin = request.headers.get("Origin")
21
+ if request.method == "OPTIONS":
22
+ response = make_response()
23
+ response.headers.add("Access-Control-Allow-Credentials", "true")
24
+ response.headers.add("Access-Control-Allow-Headers", "Content-Type")
25
+ response.headers.add("Access-Control-Allow-Headers", "x-csrf-token")
26
+ response.headers.add(
27
+ "Access-Control-Allow-Methods",
28
+ "GET, POST, OPTIONS, PUT, PATCH, DELETE",
29
+ )
30
+ if origin:
31
+ response.headers.add("Access-Control-Allow-Origin", origin)
32
+ else:
33
+ response.headers.add("Access-Control-Allow-Credentials", "true")
34
+ if origin:
35
+ response.headers.add("Access-Control-Allow-Origin", origin)
36
+ response.headers[
37
+ "Cache-Control"
38
+ ] = "no-cache, no-store, must-revalidate, public, max-age=0"
39
+ response.headers["Pragma"] = "no-cache"
40
+ response.headers["Expires"] = "0"
41
+
42
+ return response
@@ -3,7 +3,7 @@ from pathlib import Path
3
3
 
4
4
  setup(
5
5
  name="PolicyEngine-Core",
6
- version="0.1.2",
6
+ version="0.1.4",
7
7
  author="PolicyEngine",
8
8
  license="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
9
9
  url="https://github.com/policyengine/policyengine-core",
@@ -14,6 +14,12 @@ setup(
14
14
  "kaleido",
15
15
  "google-cloud-storage>=1.42.0",
16
16
  "gunicorn",
17
+ "OpenFisca-Core",
18
+ "microdf_python",
19
+ "numpy",
20
+ "pandas",
21
+ "tables",
22
+ "wheel",
17
23
  ],
18
24
  packages=find_packages(),
19
25
  )
@@ -1,16 +0,0 @@
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/api/__init__.py
11
- policyengine_core/api/cloud_run.py
12
- policyengine_core/api/general.py
13
- policyengine_core/api/hypothetical.py
14
- policyengine_core/api/microsimulation.py
15
- policyengine_core/reforms/__init__.py
16
- policyengine_core/reforms/utils.py
@@ -1,3 +0,0 @@
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.
@@ -1,194 +0,0 @@
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
-
10
- class PolicyEngine:
11
- static_folder: str
12
- version: str
13
- use_cache: bool
14
-
15
- def __init__(self):
16
- self.app = Flask(type(self).__name__)
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()