policyengine-core 0.1.0__tar.gz → 0.1.2__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 (19) hide show
  1. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PKG-INFO +1 -1
  2. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PolicyEngine_Core.egg-info/PKG-INFO +1 -1
  3. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PolicyEngine_Core.egg-info/SOURCES.txt +5 -0
  4. PolicyEngine-Core-0.1.2/policyengine_core/__init__.py +1 -0
  5. PolicyEngine-Core-0.1.2/policyengine_core/api/__init__.py +2 -0
  6. PolicyEngine-Core-0.1.2/policyengine_core/api/cloud_run.py +3 -0
  7. PolicyEngine-Core-0.1.2/policyengine_core/api/general.py +4 -0
  8. PolicyEngine-Core-0.1.2/policyengine_core/api/hypothetical.py +266 -0
  9. PolicyEngine-Core-0.1.2/policyengine_core/api/microsimulation.py +367 -0
  10. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/setup.py +1 -1
  11. PolicyEngine-Core-0.1.0/policyengine_core/__init__.py +0 -0
  12. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PolicyEngine_Core.egg-info/dependency_links.txt +0 -0
  13. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PolicyEngine_Core.egg-info/requires.txt +0 -0
  14. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/PolicyEngine_Core.egg-info/top_level.txt +0 -0
  15. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/README.md +0 -0
  16. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/policyengine_core/reforms/__init__.py +0 -0
  17. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/policyengine_core/reforms/utils.py +0 -0
  18. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/policyengine_core/server.py +1 -1
  19. {PolicyEngine-Core-0.1.0 → PolicyEngine-Core-0.1.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: PolicyEngine-Core
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: UNKNOWN
5
5
  Home-page: https://github.com/policyengine/policyengine-core
6
6
  Author: PolicyEngine
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: PolicyEngine-Core
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: UNKNOWN
5
5
  Home-page: https://github.com/policyengine/policyengine-core
6
6
  Author: PolicyEngine
@@ -7,5 +7,10 @@ PolicyEngine_Core.egg-info/requires.txt
7
7
  PolicyEngine_Core.egg-info/top_level.txt
8
8
  policyengine_core/__init__.py
9
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
10
15
  policyengine_core/reforms/__init__.py
11
16
  policyengine_core/reforms/utils.py
@@ -0,0 +1 @@
1
+ from policyengine_core.api import Microsimulation, IndividualSim
@@ -0,0 +1,2 @@
1
+ from policyengine_core.api.microsimulation import Microsimulation
2
+ from policyengine_core.api.hypothetical import IndividualSim
@@ -0,0 +1,3 @@
1
+ """
2
+ Python interfaces to run reforms on the PolicyEngine API.
3
+ """
@@ -0,0 +1,4 @@
1
+ from typing import Tuple, Union
2
+ from openfisca_core.model_api import *
3
+
4
+ ReformType = Union[Reform, Tuple[Reform]]
@@ -0,0 +1,266 @@
1
+ """
2
+ IndividualSim and any other interfaces to intialising and running simulations on hypothetical situations.
3
+ """
4
+ from openfisca_core.entities.entity import Entity
5
+ from policyengine_core.api.general import ReformType
6
+ import numpy as np
7
+ from openfisca_core.simulation_builder import SimulationBuilder
8
+ from openfisca_core.taxbenefitsystems.tax_benefit_system import (
9
+ TaxBenefitSystem,
10
+ )
11
+ from openfisca_core.periods import period
12
+
13
+
14
+ class IndividualSim:
15
+ tax_benefit_system: TaxBenefitSystem
16
+
17
+ def __init__(self, reform: ReformType = (), year: int = 2021) -> None:
18
+ """Initialises a hypothetical simulation.
19
+
20
+ Args:
21
+ reform (ReformType, optional): The reform to apply. Defaults to ().
22
+ year (int, optional): The default year input. Defaults to 2020.
23
+ """
24
+ self.year = year
25
+ self.reforms = reform
26
+ self.system = self.tax_benefit_system()
27
+ self.sim_builder = SimulationBuilder()
28
+ self.entity_names = {var.key: var for var in self.system.entities}
29
+ self.apply_reform(self.reforms)
30
+ self.situation_data = {entity: {} for entity in self.entity_names}
31
+ self.varying = False
32
+ self.num_points = None
33
+
34
+ # Add add_entity functions
35
+
36
+ for entity in self.entity_names:
37
+ setattr(
38
+ self,
39
+ f"add_{entity}",
40
+ lambda *args, **kwargs: self.add_data(
41
+ *args, **kwargs, entity=entity
42
+ ),
43
+ )
44
+
45
+ def build(self):
46
+ self.sim = self.sim_builder.build_from_entities(
47
+ self.system, self.situation_data
48
+ )
49
+
50
+ def apply_reform(self, reform: ReformType) -> None:
51
+ """Recursively applies a reform to the tax-benefit system.
52
+
53
+ Args:
54
+ reform (ReformType): The reform to apply to the tax-benefit system.
55
+ """
56
+ for reform in self.reform:
57
+ if isinstance(reform, tuple):
58
+ self.apply_reform(reform)
59
+ else:
60
+ self.system = reform(self.system)
61
+
62
+ def add_data(
63
+ self,
64
+ entity: str = "person",
65
+ name: str = None,
66
+ input_period: str = None,
67
+ auto_period: str = True,
68
+ **kwargs: dict,
69
+ ) -> None:
70
+ """Add an entity to the situation data.
71
+
72
+ Args:
73
+ entity (str, optional): The entity name. Defaults to "person".
74
+ name (str, optional): The name of the entity instance. Defaults to None.
75
+ input_period (str, optional): The input period for the values. Defaults to None.
76
+ auto_period (str, optional): Whether to automatically repeat inputs onto subperiods. Defaults to True.
77
+ kwargs (dict): A dictionary of (variable, value).
78
+ """
79
+ input_period = input_period or self.year
80
+ entity_plural = self.entities[entity].plural
81
+ if name is None:
82
+ name = (
83
+ entity + "_" + str(len(self.situation_data[entity_plural]) + 1)
84
+ )
85
+ if auto_period:
86
+ data = {}
87
+ for var, value in kwargs.items():
88
+ try:
89
+ def_period = self.system.get_variable(
90
+ var
91
+ ).definition_period
92
+ if def_period in ["eternity", "year"]:
93
+ input_periods = [input_period]
94
+ else:
95
+ input_periods = period(input_period).get_subperiods(
96
+ def_period
97
+ )
98
+ data[var] = {
99
+ str(subperiod): value for subperiod in input_periods
100
+ }
101
+ except:
102
+ data[var] = value
103
+ self.situation_data[entity_plural][name] = data
104
+
105
+ def get_entity(self, name: str) -> Entity:
106
+ """Gets the entity type of the entity with a given name.
107
+
108
+ Args:
109
+ name (str): The name of the entity.
110
+
111
+ Returns:
112
+ Entity: The type of the entity.
113
+ """
114
+ entity_type = [
115
+ entity
116
+ for entity in self.entities.values()
117
+ if name in self.situation_data[entity.plural]
118
+ ][0]
119
+ return entity_type
120
+
121
+ def get_group(self, entity: str, name: str) -> str:
122
+ """Gets the name of the containing entity for a named entity and group type.
123
+
124
+ Args:
125
+ entity (str): The group type, e.g. "household".
126
+ name (str): The name of the entity, e.g. "person1".
127
+
128
+ Returns:
129
+ str: The containing entity, e.g. "household1".
130
+ """
131
+ containing_entity = [
132
+ group
133
+ for group in self.situation_data[entity.plural]
134
+ if name in self.situation_data[entity.plural][group]["adults"]
135
+ or name in self.situation_data[entity.plural][group]["children"]
136
+ ][0]
137
+ return containing_entity
138
+
139
+ def calc(
140
+ self,
141
+ var: str,
142
+ period: int = None,
143
+ target: str = None,
144
+ index: int = None,
145
+ ) -> np.array:
146
+ """Calculates the value of a variable, executing any required formulas.
147
+
148
+ Args:
149
+ var (str): The variable to calculate.
150
+ period (int, optional): The time period to calculate for. Defaults to None.
151
+ target (str, optional): The target entity if not all entities are required. Defaults to None.
152
+ index (int, optional): The numerical index of the target entity. Defaults to None.
153
+
154
+ Returns:
155
+ np.array: The resulting values.
156
+ """
157
+ if not hasattr(self, "sim"):
158
+ self.build()
159
+ period = period or self.year
160
+ entity = self.system.variables[var].entity
161
+ if target is not None:
162
+ target_entity = self.get_entity(target)
163
+ if target_entity.key != entity.key:
164
+ target = self.get_group(entity, target)
165
+ try:
166
+ result = self.sim.calculate(var, period)
167
+ except:
168
+ try:
169
+ result = self.sim.calculate_add(var, period)
170
+ except:
171
+ result = self.sim.calculate_divide(var, period)
172
+ if self.varying:
173
+ result = result.reshape(
174
+ (self.num_points, len(self.situation_data[entity.plural]))
175
+ ).transpose()
176
+ members = list(self.situation_data[entity.plural])
177
+ if index is not None:
178
+ index = min(len(members) - 1, index)
179
+ if target is not None:
180
+ index = members.index(target)
181
+ if target is not None or index is not None:
182
+ return result[index]
183
+ return result
184
+
185
+ def deriv(
186
+ self,
187
+ var: str,
188
+ wrt: str = "employment_income",
189
+ period: int = None,
190
+ var_target: str = None,
191
+ wrt_target: str = None,
192
+ ):
193
+ """Calculates the derivative of one variable with respect to another.
194
+
195
+ Args:
196
+ var (str): The target variable.
197
+ wrt (str, optional): The varying variable. Defaults to "employment_income".
198
+ period (int, optional): The time period to calculate over. Defaults to None.
199
+ var_target (str, optional): The target name. Defaults to None.
200
+ wrt_target (str, optional): The source name. Defaults to None.
201
+
202
+ Returns:
203
+ np.array: The derivatives as the source variable varies.
204
+ """
205
+ period = period or self.year
206
+ y = self.calc(var, period=period, target=var_target)
207
+ x = self.calc(wrt, period=period, target=wrt_target)
208
+ try:
209
+ y = y.squeeze()
210
+ except:
211
+ pass
212
+ try:
213
+ x = x.squeeze()
214
+ except:
215
+ pass
216
+ x = x.astype(np.float32)
217
+ y = y.astype(np.float32)
218
+ assert (
219
+ len(y) > 1 and len(x) > 1
220
+ ), "Simulation must vary on an axis to calculate derivatives."
221
+ deriv = (y[1:] - y[:-1]) / (x[1:] - x[:-1])
222
+ deriv = np.append(deriv, deriv[-1])
223
+ return deriv
224
+
225
+ def reset_vary(self) -> None:
226
+ """Removes an axis from the simulation."""
227
+ del self.situation_data["axes"]
228
+ self.varying = False
229
+ self.num_points = None
230
+
231
+ def vary(
232
+ self,
233
+ var: str,
234
+ min: float = 0,
235
+ max: float = 200000,
236
+ step: float = 100,
237
+ index: int = 0,
238
+ period: int = None,
239
+ ) -> None:
240
+ """Adds an axis to the situation, varying one variable.
241
+
242
+ Args:
243
+ var (str): The variable to change.
244
+ min (float, optional): The minimum value. Defaults to 0.
245
+ max (float, optional): The maximum value. Defaults to 200000.
246
+ step (float, optional): The step size. Defaults to 100.
247
+ index (int, optional): The specific entity index to target. Defaults to 0.
248
+ period (int, optional): The time period. Defaults to None.
249
+ """
250
+ period = period or self.year
251
+ if "axes" not in self.situation_data:
252
+ self.situation_data["axes"] = [[]]
253
+ count = int((max - min) / step)
254
+ self.situation_data["axes"][0] += [
255
+ {
256
+ "count": count,
257
+ "name": var,
258
+ "min": min,
259
+ "max": max,
260
+ "period": period,
261
+ "index": index,
262
+ }
263
+ ]
264
+ self.build()
265
+ self.varying = True
266
+ self.num_points = count
@@ -0,0 +1,367 @@
1
+ """
2
+ Microsimulation interfaces and utility functions.
3
+ """
4
+ from typing import List, Tuple
5
+ from openfisca_core.entities.entity import Entity
6
+ from policyengine_core.api.general import ReformType
7
+ from microdf.generic import MicroDataFrame
8
+ import numpy as np
9
+ from openfisca_core.entities import GroupEntity
10
+ from openfisca_core.model_api import *
11
+ from openfisca_core.simulation_builder import SimulationBuilder
12
+ from microdf import MicroSeries
13
+ import tables
14
+ from openfisca_core.taxbenefitsystems import TaxBenefitSystem
15
+
16
+
17
+ class Microsimulation:
18
+ tax_benefit_system: TaxBenefitSystem
19
+ default_dataset: type
20
+ entities: Tuple[Entity]
21
+ default_role: str = "member"
22
+
23
+ def __init__(
24
+ self, reform: ReformType = (), dataset: type = None, year: int = 2020
25
+ ):
26
+ """Initialises a microsimulation.
27
+
28
+ Args:
29
+ reform (ReformType): The reform to apply. Can be a tuple of OpenFisca Reforms.
30
+ dataset (type, optional): The dataset to use.
31
+ year (int, optional): The year of the dataset to load. Defaults to 2020.
32
+ """
33
+ tables.file._open_files.close_all()
34
+ self.reform = reform
35
+ if dataset is None:
36
+ self.dataset = self.default_dataset
37
+ else:
38
+ self.dataset = dataset
39
+ if year is None:
40
+ self.year = max(dataset.years)
41
+ else:
42
+ self.year = year
43
+ self.default_year = year
44
+ self.bonus_sims = {}
45
+ self.person_entities = tuple(
46
+ filter(
47
+ lambda entity: not isinstance(entity, GroupEntity),
48
+ self.entities,
49
+ )
50
+ )
51
+ self.person_entity_names = tuple(
52
+ map(lambda entity: entity.key, self.person_entities)
53
+ )
54
+ self.group_entities = tuple(
55
+ filter(
56
+ lambda entity: isinstance(entity, GroupEntity),
57
+ self.entities,
58
+ )
59
+ )
60
+ self.group_entity_names = tuple(
61
+ map(lambda entity: entity.key, self.group_entities)
62
+ )
63
+ self.load_dataset(self.dataset, self.year)
64
+
65
+ def apply_reform(self, reform: ReformType) -> None:
66
+ """Recursively applies a reform to the tax-benefit system.
67
+
68
+ Args:
69
+ reform (ReformType): The reform to apply to the tax-benefit system.
70
+ """
71
+ for reform in self.reform:
72
+ if isinstance(reform, tuple):
73
+ self.apply_reform(reform)
74
+ else:
75
+ self.system = reform(self.system)
76
+
77
+ def load_dataset(self, dataset: type, year: int) -> None:
78
+ """Loads the dataset with the specified year.
79
+
80
+ Args:
81
+ dataset (type): The dataset to use.
82
+ year (int): The year of the data to load.
83
+ """
84
+ self.system = self.tax_benefit_system()
85
+ self.apply_reform(self.reform)
86
+ builder = SimulationBuilder()
87
+ builder.create_entities(self.system)
88
+
89
+ data = dataset.load(year)
90
+
91
+ for person_entity in self.person_entity_names:
92
+ builder.declare_person_entity(
93
+ person_entity, np.array(data[f"{person_entity}_id"])
94
+ )
95
+
96
+ for group_entity in self.group_entity_names:
97
+ primary_keys = np.array(data[f"{group_entity}_id"])
98
+ group = builder.declare_entity(group_entity, primary_keys)
99
+ foreign_keys = np.array(data[f"person_{group_entity}_id"])
100
+ if f"person_{group_entity}_role" in data.keys():
101
+ roles = np.array(data[f"person_{group_entity}_role"])
102
+ else:
103
+ roles = np.array([self.default_role] * len(foreign_keys))
104
+ builder.join_with_persons(group, foreign_keys, roles)
105
+
106
+ self.simulation = builder.build(self.system)
107
+ self.set_input = self.simulation.set_input
108
+
109
+ for variable in data.keys():
110
+ if variable in self.system.variables:
111
+ self.set_input(
112
+ variable,
113
+ year,
114
+ np.array(data[variable]),
115
+ )
116
+ data.close()
117
+
118
+ def map_to(
119
+ self, arr: np.array, entity: str, target_entity: str, how: str = None
120
+ ):
121
+ """Maps values from one entity to another.
122
+
123
+ Args:
124
+ arr (np.array): The values in their original position.
125
+ entity (str): The source entity.
126
+ target_entity (str): The target entity.
127
+ how (str, optional): A function to use when mapping. Defaults to None.
128
+
129
+ Raises:
130
+ ValueError: If an invalid (dis)aggregation function is passed.
131
+
132
+ Returns:
133
+ np.array: The mapped values.
134
+ """
135
+ entity_pop = self.simulation.populations[entity]
136
+ target_pop = self.simulation.populations[target_entity]
137
+ if entity == "person" and target_entity in self.group_entity_names:
138
+ if how and how not in (
139
+ "sum",
140
+ "any",
141
+ "min",
142
+ "max",
143
+ "all",
144
+ "value_from_first_person",
145
+ ):
146
+ raise ValueError("Not a valid function.")
147
+ return target_pop.__getattribute__(how or "sum")(arr)
148
+ elif entity in self.group_entity_names and target_entity == "person":
149
+ if not how:
150
+ return entity_pop.project(arr)
151
+ if how == "mean":
152
+ return entity_pop.project(arr / entity_pop.nb_persons())
153
+ elif entity == target_entity:
154
+ return arr
155
+ else:
156
+ return self.map_to(
157
+ self.map_to(arr, entity, "person", how="mean"),
158
+ "person",
159
+ target_entity,
160
+ how="sum",
161
+ )
162
+
163
+ def calc(
164
+ self,
165
+ variable: str,
166
+ map_to: str = None,
167
+ how: str = None,
168
+ period: int = None,
169
+ weighted: bool = True,
170
+ ):
171
+ """Calculates the values of a variable, executing any formulas required.
172
+
173
+ Args:
174
+ variable (str): The name of the variable.
175
+ map_to (str, optional): The entity to map to. Defaults to None (the original entity).
176
+ how (str, optional): The (dis)aggregation function to use when mapping. Defaults to None.
177
+ period (int, optional): The time period to calculate for. Defaults to 2020.
178
+ weighted (bool, optional): Whether to return weighted results. Defaults to True.
179
+
180
+ Returns:
181
+ Union[np.array, MicroSeries]: A weighted or unweighted array.
182
+ """
183
+ if period is None:
184
+ period = self.default_year
185
+ var_metadata = self.simulation.tax_benefit_system.variables[variable]
186
+ entity = var_metadata.entity.key
187
+ arr = self.simulation.calculate(variable, period)
188
+ if var_metadata.value_type == Enum:
189
+ arr = arr.decode_to_str()
190
+ if map_to:
191
+ arr = self.map_to(arr, entity, map_to, how=how)
192
+ entity = map_to
193
+ if weighted:
194
+ series = MicroSeries(
195
+ arr,
196
+ weights=self.calc(
197
+ f"{entity}_weight", period=period, weighted=False
198
+ ),
199
+ )
200
+ return series
201
+ else:
202
+ return arr
203
+
204
+ def df(
205
+ self,
206
+ variables: List[str],
207
+ map_to: str = None,
208
+ how: str = None,
209
+ period: int = None,
210
+ ) -> MicroDataFrame:
211
+ """Constructs a DataFrame of multiple variables.
212
+
213
+ Args:
214
+ variables (List[str]): The variables to include in the DataFrame.
215
+ period (int, optional): The time period to calculate for. Defaults to None.
216
+
217
+ Returns:
218
+ MicroDataFrame: The weighted DataFrame.
219
+ """
220
+ if period is None:
221
+ period = self.default_year
222
+ df_dict = {}
223
+ var_metadata = self.simulation.tax_benefit_system.variables[
224
+ variables[0]
225
+ ]
226
+ entity = var_metadata.entity.key or map_to
227
+ weights = self.calc(f"{entity}_weight", period=period, weighted=False)
228
+ for var in variables:
229
+ df_dict[var] = self.calc(
230
+ var, period=period, map_to=entity, how=how
231
+ )
232
+ return MicroDataFrame(df_dict, weights=weights)
233
+
234
+ def deriv(
235
+ self,
236
+ target: str,
237
+ wrt: str,
238
+ delta: float = 100,
239
+ percent: bool = False,
240
+ group_limit: int = 5,
241
+ ) -> MicroSeries:
242
+ """Calculates the derivative of one variable with respect to another.
243
+
244
+ Args:
245
+ target (str): The target variable.
246
+ wrt (str): The source variable.
247
+ delta (float, optional): The amount to increase the source by. Defaults to 100.
248
+ percent (bool, optional): Whether the delta is relative to the original value or absolute. Defaults to False.
249
+ group_limit (int, optional): The maximum number of people in a group to calculate derivatives for. Defaults to 5.
250
+
251
+ Raises:
252
+ ValueError: If source variable is upstream of the target variable.
253
+
254
+ Returns:
255
+ MicroSeries: The weighted derivatives.
256
+ """
257
+ system = self.simulation.tax_benefit_system
258
+ target_entity = system.variables[target].entity.key
259
+ wrt_entity = system.variables[wrt].entity.key
260
+ if target_entity == wrt_entity:
261
+ # calculating a derivative with both source and target in the same entity
262
+ config = (wrt, delta, percent, "same-entity")
263
+ if config not in self.bonus_sims:
264
+ self.bonus_sims[config] = type(self)(
265
+ self.bonus_sims,
266
+ dataset=self.dataset,
267
+ year=self.year,
268
+ )
269
+ original_values = (
270
+ self.bonus_sims[config].calc(wrt, period=self.year).values
271
+ )
272
+ if not percent:
273
+ self.bonus_sims[config].simulation.set_input(
274
+ wrt, self.year, original_values + delta
275
+ )
276
+ else:
277
+ self.bonus_sims[config].simulation.set_input(
278
+ wrt, self.year, original_values * (1 + delta)
279
+ )
280
+
281
+ bonus_sim = self.bonus_sims[config]
282
+ bonus_increase = bonus_sim.calc(wrt).astype(float) - self.calc(
283
+ wrt
284
+ ).astype(float)
285
+ target_increase = bonus_sim.calc(target).astype(float) - self.calc(
286
+ target
287
+ ).astype(float)
288
+
289
+ gradient = target_increase / bonus_increase
290
+
291
+ return gradient
292
+ elif (
293
+ target_entity in self.group_entity_names
294
+ and wrt_entity in self.person_entity_names
295
+ ):
296
+ # calculate the derivative for a group variable wrt a source variable, independent of other members in the group
297
+ index_in_group = (
298
+ self.calc("person_id")
299
+ .groupby(self.calc(f"{target_entity}_id", map_to="person"))
300
+ .cumcount()
301
+ )
302
+ max_group_size = min(max(index_in_group) + 1, group_limit)
303
+
304
+ derivative = np.empty((len(index_in_group))) * np.nan
305
+
306
+ for i in range(max_group_size):
307
+ config = (wrt, delta, percent, "group-entity", i)
308
+ if config not in self.bonus_sims:
309
+ self.bonus_sims[config] = type(self)(
310
+ self.reform,
311
+ dataset=self.dataset,
312
+ year=self.year,
313
+ )
314
+ original_values = (
315
+ self.bonus_sims[config]
316
+ .calc(wrt, period=self.year)
317
+ .values
318
+ )
319
+
320
+ if not percent:
321
+ self.bonus_sims[config].simulation.set_input(
322
+ wrt,
323
+ self.year,
324
+ original_values + delta * (index_in_group == i),
325
+ )
326
+ else:
327
+ self.bonus_sims[config].simulation.set_input(
328
+ wrt,
329
+ self.year,
330
+ original_values
331
+ * (1 + delta * (index_in_group == i)),
332
+ )
333
+
334
+ bonus_sim = self.bonus_sims[config]
335
+ bonus_increase = bonus_sim.calc(wrt).astype(float) - self.calc(
336
+ wrt
337
+ ).astype(float)
338
+ target_increase = bonus_sim.calc(
339
+ target, map_to="person"
340
+ ).astype(float) - self.calc(target, map_to="person").astype(
341
+ float
342
+ )
343
+ result = target_increase / bonus_increase
344
+ derivative[bonus_increase > 0] = result[bonus_increase > 0]
345
+
346
+ return MicroSeries(
347
+ derivative,
348
+ weights=self.calc("person_weight", weighted=False),
349
+ index=self.calc("person_id", weighted=False),
350
+ )
351
+ else:
352
+ raise ValueError(
353
+ "Unable to compute derivative - target variable must be from a group of or the same as the source variable."
354
+ )
355
+
356
+ def deriv_df(
357
+ self, *targets, wrt="employment_income", delta=100, percent=False
358
+ ) -> MicroDataFrame:
359
+ wrt_entity = self.simulation.tax_benefit_system.variables[
360
+ wrt
361
+ ].entity.key
362
+ df = MicroDataFrame(weights=self.entity_weights[wrt_entity])
363
+ for target in targets:
364
+ df[target] = self.deriv(
365
+ target, wrt=wrt, delta=delta, percent=percent
366
+ )
367
+ return df
@@ -3,7 +3,7 @@ from pathlib import Path
3
3
 
4
4
  setup(
5
5
  name="PolicyEngine-Core",
6
- version="0.1.0",
6
+ version="0.1.2",
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",
File without changes
@@ -6,6 +6,7 @@ from flask_cors import CORS
6
6
  import logging
7
7
  from time import time
8
8
 
9
+
9
10
  class PolicyEngine:
10
11
  static_folder: str
11
12
  version: str
@@ -15,7 +16,6 @@ class PolicyEngine:
15
16
  self.app = Flask(type(self).__name__)
16
17
 
17
18
 
18
-
19
19
  VERSION = "0.1.5"
20
20
  USE_CACHE = True
21
21
  logging.getLogger("werkzeug").disabled = True