-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsimulation.py
1654 lines (1432 loc) · 64.2 KB
/
simulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tempfile
from typing import TYPE_CHECKING, Any, Dict, List, Type, Union
import numpy as np
import pandas as pd
from numpy.typing import ArrayLike
import logging
from pathlib import Path
from policyengine_core import commons, periods
from policyengine_core.data.dataset import Dataset
from policyengine_core.entities.entity import Entity
from policyengine_core.enums import Enum, EnumArray
from policyengine_core.errors import CycleError, SpiralError
from policyengine_core.holders.holder import Holder
from policyengine_core.periods import Period
from policyengine_core.periods.config import ETERNITY, MONTH, YEAR
from policyengine_core.periods.helpers import period
from policyengine_core.tracers import (
FullTracer,
SimpleTracer,
TracingParameterNodeAtInstant,
)
import random
from policyengine_core.tools.hugging_face import *
import json
if TYPE_CHECKING:
from policyengine_core.taxbenefitsystems import TaxBenefitSystem
from policyengine_core.experimental import MemoryConfig
from policyengine_core.populations import Population, GroupPopulation
from policyengine_core.tracers import SimpleTracer
from policyengine_core.variables import Variable, QuantityType
from policyengine_core.reforms.reform import Reform
from policyengine_core.parameters import get_parameter
from policyengine_core.simulations.simulation_macro_cache import (
SimulationMacroCache,
)
class Simulation:
"""
Represents a simulation, and handles the calculation logic
"""
default_tax_benefit_system: Type["TaxBenefitSystem"] = None
"""The default tax-benefit system class to use if none is provided."""
default_tax_benefit_system_instance: "TaxBenefitSystem" = None
"""The default tax-benefit system instance to use if none is provided. This requires that the tax-benefit system is initialised when importing a country package. This will slow down the import, but may speed up individual simulations."""
default_dataset: Dataset = None
"""The default dataset class to use if none is provided."""
default_role: str = "member"
"""The default role to assign people to groups if none is provided."""
default_input_period: str = None
"""The default period to use when inputting variables."""
default_calculation_period: str = None
"""The default period to calculate for if none is provided."""
datasets: List[Dataset] = []
"""The list of datasets available for this simulation."""
baseline: "Simulation" = None
"""The baseline simulation, if this simulation is a reform."""
is_over_dataset: bool = False
"""Whether this simulation is built over a dataset."""
macro_cache_read: bool = False
"""Whether to read from the macro cache."""
macro_cache_write: bool = False
"""Whether to write to the macro cache."""
start_instant: str = None
"""The earliest data input instant of the simulation."""
def __init__(
self,
tax_benefit_system: "TaxBenefitSystem" = None,
populations: Dict[str, Population] = None,
situation: dict = None,
dataset: Union[str, Type[Dataset]] = None,
reform: Reform = None,
trace: bool = False,
):
if tax_benefit_system is None:
if (
self.default_tax_benefit_system_instance is not None
and reform is None
):
tax_benefit_system = self.default_tax_benefit_system_instance
else:
tax_benefit_system = self.default_tax_benefit_system(
reform=reform
)
self.tax_benefit_system = tax_benefit_system
self.reform = reform
self.tax_benefit_system = tax_benefit_system
self.branch_name = "default"
self.dataset = dataset
if dataset is None:
if self.default_dataset is not None:
dataset = self.default_dataset
self.is_over_dataset = dataset is not None
self.invalidated_caches = set()
self.debug: bool = False
self.trace: bool = trace
self.tracer: SimpleTracer = (
SimpleTracer() if not trace else FullTracer()
)
self.opt_out_cache: bool = False
# controls the spirals detection; check for performance impact if > 1
self.max_spiral_loops: int = 10
self.memory_config: MemoryConfig = None
self._data_storage_dir: str = None
self.branches: Dict[str, Simulation] = {}
self.has_axes = False
np.random.seed(0)
if situation is not None:
if dataset is not None:
raise ValueError(
"You provided both a situation and a dataset. Only one input method is allowed."
)
self.build_from_populations(
self.tax_benefit_system.instantiate_entities()
)
from policyengine_core.simulations.simulation_builder import (
SimulationBuilder,
) # Import here to avoid circular dependency
builder = SimulationBuilder()
builder.default_period = self.default_input_period
builder.build_from_dict(self.tax_benefit_system, situation, self)
self.has_axes = builder.has_axes
if populations is not None:
self.build_from_populations(populations)
if dataset is not None:
if isinstance(dataset, str):
if "hf://" in dataset:
owner, repo, filename = dataset.split("/")[-3:]
if "@" in filename:
version = filename.split("@")[-1]
filename = filename.split("@")[0]
else:
version = None
dataset = download_huggingface_dataset(
repo=f"{owner}/{repo}",
repo_filename=filename,
version=version,
)
datasets_by_name = {
dataset.name: dataset for dataset in self.datasets
}
if dataset in datasets_by_name:
dataset = datasets_by_name.get(dataset)
elif Path(dataset).exists():
dataset = Dataset.from_file(
dataset, self.default_input_period
)
if isinstance(dataset, type):
self.dataset: Dataset = dataset(require=True)
elif isinstance(dataset, pd.DataFrame):
self.dataset = Dataset.from_dataframe(
dataset, self.default_input_period
)
else:
self.dataset = dataset
self.build_from_dataset()
self.tax_benefit_system.simulation = self
if self.reform is not None:
self.tax_benefit_system.apply_reform_set(self.reform)
# Backwards compatibility methods
self.calc = self.calculate
self.df = self.calculate_dataframe
self.input_variables = [
variable.name
for variable in self.tax_benefit_system.variables.values()
if len(self.get_holder(variable.name).get_known_periods()) > 0
]
self.situation_input = situation
if self.situation_input is not None:
original_input = json.loads(json.dumps(self.situation_input))
if original_input.get("axes") is not None:
original_input["axes"] = {}
# Hash the situation input to a random number, so situations with axes behave the
# same ways as the same situations without axes.
hashed_input = hash(json.dumps(original_input)) % 1000000
np.random.seed(hashed_input)
if reform is not None:
self.baseline = self.get_branch("baseline")
self.baseline.trace = self.trace
self.baseline.tracer = self.tracer
self.baseline.tax_benefit_system = (
self.default_tax_benefit_system_instance
)
else:
self.baseline = None
self.parent_branch = None
def apply_reform(self, reform: Union[tuple, Reform]):
if isinstance(reform, tuple):
for subreform in reform:
self.apply_reform(subreform)
else:
if isinstance(reform, dict):
reform = Reform.from_dict(reform)
reform.apply(self.tax_benefit_system)
def build_from_populations(
self, populations: Dict[str, Population]
) -> None:
"""This method of initialisation requires the populations to be pre-initialised.
Args:
populations (Dict[str, Population]): A dictionary of populations, indexed by entity key.
"""
self.populations = populations
self.link_to_entities_instances()
self.create_shortcuts()
self.populations = populations
self.persons: Population = self.populations[
self.tax_benefit_system.person_entity.key
]
self.link_to_entities_instances()
self.create_shortcuts()
def build_from_dataset(self) -> None:
"""Build a simulation from a dataset."""
self.build_from_populations(
self.tax_benefit_system.instantiate_entities()
)
from policyengine_core.simulations.simulation_builder import (
SimulationBuilder,
) # Import here to avoid circular dependency
builder = SimulationBuilder()
builder.populations = self.populations
try:
data = self.dataset.load()
except FileNotFoundError as e:
raise FileNotFoundError(
f"The dataset file {self.dataset.name} could not be found. "
+ "Make sure you have downloaded or built it using the `policyengine-core data` command."
) from e
if self.dataset.data_format == Dataset.FLAT_FILE:
data_copy = {col: data[col].values for col in data.copy().columns}
data = {col: data[col].values for col in data.columns}
person_entity = self.tax_benefit_system.person_entity
entity_id_field = f"{person_entity.key}_id"
def get_eternity_array(name):
if self.dataset.data_format == Dataset.FLAT_FILE:
# Look for any column with variablename__timeperiod
for col in data:
if col.split("__")[0] == name:
return data[col]
elif self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS:
return data[name][list(data[name].keys())[0]]
return data[name]
if self.dataset.data_format != Dataset.FLAT_FILE:
assert (
entity_id_field in data
), f"Missing {entity_id_field} column in the dataset. Each person entity must have an ID array defined for ETERNITY."
elif entity_id_field not in data:
data[entity_id_field] = np.arange(
len(get_eternity_array("person_id"))
)
entity_ids = get_eternity_array(entity_id_field)
builder.declare_person_entity(person_entity.key, entity_ids)
for group_entity in self.tax_benefit_system.group_entities:
entity_id_field = f"{group_entity.key}_id"
if self.dataset.data_format != Dataset.FLAT_FILE:
assert (
entity_id_field in data
), f"Missing {entity_id_field} column in the dataset. Each group entity must have an ID array defined for ETERNITY."
entity_ids = get_eternity_array(entity_id_field)
elif entity_id_field not in data:
entity_id_field_values = get_eternity_array(
f"person_{group_entity.key}_id"
)
if entity_id_field_values is not None:
entity_ids = np.arange(
len(np.unique(entity_id_field_values))
)
else:
entity_ids = np.arange(len(data[list(data.keys())[0]]))
builder.declare_entity(group_entity.key, entity_ids)
person_membership_id_field = (
f"{person_entity.key}_{group_entity.key}_id"
)
if self.dataset.data_format != Dataset.FLAT_FILE:
assert (
person_membership_id_field in data
), f"Missing {person_membership_id_field} column in the dataset. Each group entity must have a person membership array defined for ETERNITY."
elif person_membership_id_field not in data:
data[person_membership_id_field] = np.arange(len(data))
person_membership_ids = get_eternity_array(
person_membership_id_field
)
person_role_field = f"{person_entity.key}_{group_entity.key}_role"
if person_role_field in data:
person_roles = get_eternity_array(person_role_field)
elif "role" in data:
person_roles = get_eternity_array("role")
elif self.default_role is not None:
person_roles = np.full(len(entity_ids), self.default_role)
else:
raise ValueError(
f"Missing {person_role_field} column in the dataset. Each group entity must have a person role array defined for ETERNITY."
)
builder.join_with_persons(
self.populations[group_entity.key],
person_membership_ids,
person_roles,
)
self.build_from_populations(builder.populations)
if self.dataset.data_format == Dataset.FLAT_FILE:
# Ensure we're back to all person-level data.
data = data_copy
if self.dataset.data_format != Dataset.FLAT_FILE:
for variable in data:
if variable in self.tax_benefit_system.variables:
if self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS:
for time_period in data[variable]:
self.set_input(
variable,
time_period,
data[variable][time_period],
)
else:
self.set_input(
variable, self.dataset.time_period, data[variable]
)
else:
# Silently skip.
pass
else:
for variable in data:
if "__" in variable:
variable_name, time_period = variable.split("__")
else:
variable_name = variable
time_period = (
self.dataset.time_period or self.default_input_period
)
if variable_name not in self.tax_benefit_system.variables:
continue
variable_meta = self.tax_benefit_system.get_variable(
variable_name
)
entity = variable_meta.entity
population = self.get_population(entity.plural)
# All data should be person level
if len(data[variable]) != len(population.ids):
population: GroupPopulation
entity_level_data = population.value_from_first_person(
data[variable]
)
else:
entity_level_data = data[variable]
self.set_input(variable_name, time_period, entity_level_data)
self.default_calculation_period = (
self.dataset.time_period or self.default_calculation_period
)
self.tax_benefit_system.data_modified = False
@property
def trace(self) -> bool:
return self._trace
@trace.setter
def trace(self, trace: SimpleTracer) -> None:
self._trace = trace
if trace:
self.tracer = FullTracer()
else:
self.tracer = SimpleTracer()
def link_to_entities_instances(self) -> None:
for _key, entity_instance in self.populations.items():
entity_instance.simulation = self
def create_shortcuts(self) -> None:
for _key, population in self.populations.items():
# create shortcut simulation.person and simulation.household (for instance)
setattr(self, population.entity.key, population)
@property
def data_storage_dir(self) -> str:
"""
Temporary folder used to store intermediate calculation data in case the memory is saturated
"""
if self._data_storage_dir is None:
self._data_storage_dir = tempfile.mkdtemp(prefix="openfisca_")
message = [
(
"Intermediate results will be stored on disk in {} in case of memory overflow."
).format(self._data_storage_dir),
"You should remove this directory once you're done with your simulation.",
]
return self._data_storage_dir
# ----- Calculation methods ----- #
def calculate(
self,
variable_name: str,
period: Period = None,
map_to: str = None,
decode_enums: bool = False,
) -> ArrayLike:
"""Calculate ``variable_name`` for ``period``.
Args:
variable_name (str): The name of the variable to calculate.
period (Period): The period to calculate the variable for.
map_to (str): The name of the variable to map the result to. If None, the result is returned as is.
decode_enums (bool): If True, the result is decoded from an array of integers to an array of strings.
Returns:
ArrayLike: The calculated variable.
"""
if period is not None and not isinstance(period, Period):
period = periods.period(period)
elif period is None and self.default_calculation_period is not None:
period = periods.period(self.default_calculation_period)
self.tracer.record_calculation_start(
variable_name, period, self.branch_name
)
np.random.seed(hash(variable_name + str(period)) % 1000000)
try:
result = self._calculate(variable_name, period)
if isinstance(result, EnumArray) and decode_enums:
result = result.decode_to_str()
self.tracer.record_calculation_result(result)
if map_to is not None:
source_entity = self.tax_benefit_system.get_variable(
variable_name
).entity.key
result = self.map_result(result, source_entity, map_to)
return result
finally:
self.tracer.record_calculation_end()
self.purge_cache_of_invalid_values()
def map_result(
self,
values: ArrayLike,
source_entity: str,
target_entity: str,
how: str = None,
):
"""Maps values from one entity to another.
Args:
arr (np.array): The values in their original position.
source_entity (str): The source entity key.
target_entity (str): The target entity key.
how (str, optional): A function to use when mapping. Defaults to None.
Raises:
ValueError: If an invalid (dis)aggregation function is passed.
Returns:
np.array: The mapped values.
"""
entity_pop = self.populations[source_entity]
target_pop = self.populations[target_entity]
if (
source_entity == "person"
and target_entity in self.tax_benefit_system.group_entity_keys
):
if how and how not in (
"sum",
"any",
"min",
"max",
"all",
"value_from_first_person",
):
raise ValueError("Not a valid function.")
return target_pop.__getattribute__(how or "sum")(values)
elif (
source_entity in self.tax_benefit_system.group_entity_keys
and target_entity == "person"
):
if not how:
return entity_pop.project(values)
if how == "mean":
return entity_pop.project(values / entity_pop.nb_persons())
elif source_entity == target_entity:
return values
else:
return self.map_result(
self.map_result(
values,
source_entity,
self.tax_benefit_system.person_entity.key,
how="mean",
),
"person",
target_entity,
how="sum",
)
def calculate_dataframe(
self,
variable_names: List[str],
period: Period = None,
map_to: str = None,
) -> pd.DataFrame:
"""Calculate ``variable_names`` for ``period``.
Args:
variable_names (List[str]): A list of variable names to calculate.
period (Period): The period to calculate for.
Returns:
pd.DataFrame: A dataframe containing the calculated variables.
"""
if period is not None and not isinstance(period, Period):
period = periods.period(period)
elif period is None and self.default_calculation_period is not None:
period = periods.period(self.default_calculation_period)
# Check each variable exists
for variable_name in variable_names:
if variable_name not in self.tax_benefit_system.variables:
raise ValueError(f"Variable {variable_name} does not exist.")
df = pd.DataFrame()
entities = [
self.tax_benefit_system.get_variable(variable_name).entity.key
for variable_name in variable_names
]
# Check that all variables are from the same entity. If not, map values to the entity of the first variable.
entity = map_to or entities[0]
if not all(entity == e for e in entities):
map_to = entity
for variable_name in variable_names:
df[variable_name] = self.calculate(variable_name, period, map_to)
return df
def _calculate(
self, variable_name: str, period: Period = None
) -> ArrayLike:
"""
Calculate the variable ``variable_name`` for the period ``period``, using the variable formula if it exists.
Args:
variable_name (str): The name of the variable to calculate.
period (Period): The period to calculate the variable for.
Returns:
ArrayLike: The calculated variable.
"""
if variable_name not in self.tax_benefit_system.variables:
raise ValueError(f"Variable {variable_name} does not exist.")
population = self.get_variable_population(variable_name)
holder = population.get_holder(variable_name)
variable = self.tax_benefit_system.get_variable(
variable_name, check_existence=True
)
# Check if we've neutralized via parameters.
try:
if (
variable.is_neutralized
or self.tax_benefit_system.parameters(period).gov.abolitions[
variable.name
]
):
return holder.default_array()
except Exception as e:
pass
# First look for a value already cached
cached_array = holder.get_array(period, self.branch_name)
if cached_array is not None:
return cached_array
smc = SimulationMacroCache(self.tax_benefit_system)
# Check if cache can be used, if available, check if path exists
is_cache_available = self.check_macro_cache(variable_name, str(period))
if is_cache_available:
smc.set_cache_path(
self.dataset.file_path.parent,
self.dataset.name,
variable_name,
str(period),
self.branch_name,
)
cache_path = smc.get_cache_path()
if cache_path.exists():
if (
not self.macro_cache_read
or self.tax_benefit_system.data_modified
):
value = None
else:
value = smc.get_cache_value(cache_path)
if value is not None:
return value
if variable.requires_computation_after is not None:
variables_in_stack = [
node.get("name") for node in self.tracer.stack
]
variable_in_stack = (
variable.requires_computation_after in variables_in_stack
)
required_is_known_periods = self.get_holder(
variable.requires_computation_after
).get_known_periods()
if (not variable_in_stack) and (
not len(required_is_known_periods) > 0
):
raise ValueError(
f"Variable {variable_name} requires {variable.requires_computation_after} to be requested first. That variable is known in: {required_is_known_periods}. The full stack is: {variables_in_stack}. {variable_in_stack, len(required_is_known_periods) > 0}"
)
alternate_period_handling = False
if variable.definition_period == MONTH and period.unit == YEAR:
if variable.quantity_type == QuantityType.STOCK:
contained_months = period.get_subperiods(MONTH)
values = self._calculate(variable_name, contained_months[-1])
else:
values = self.calculate_add(variable_name, period)
alternate_period_handling = True
elif variable.definition_period == YEAR and period.unit == MONTH:
alternate_period_handling = True
if variable.quantity_type == QuantityType.STOCK:
values = self._calculate(variable_name, period.this_year)
else:
values = self.calculate_divide(variable_name, period)
if alternate_period_handling:
if is_cache_available:
smc.set_cache_value(cache_path, values)
return values
self._check_period_consistency(period, variable)
if variable.defined_for is not None:
mask = (
self.calculate(
variable.defined_for, period, map_to=variable.entity.key
)
> 0
)
if np.all(~mask):
array = holder.default_array()
array = self._cast_formula_result(array, variable)
holder.put_in_cache(array, period, self.branch_name)
return array
array = None
# First, try to run a formula
try:
self._check_for_cycle(variable.name, period)
array = self._run_formula(variable, population, period)
# If no result, use the default value and cache it
if array is None:
# Check if the variable has a previously defined value
known_periods = holder.get_known_periods()
start_instants = [
str(known_period.start)
for known_period in known_periods
if known_period.unit == variable.definition_period
and known_period.start < period.start
]
if variable.uprating is not None and len(start_instants) > 0:
latest_known_period = known_periods[
np.argmax(start_instants)
]
try:
uprating_parameter = get_parameter(
self.tax_benefit_system.parameters,
variable.uprating,
)
except:
raise ValueError(
f"Could not find uprating parameter {variable.uprating} when trying to uprate {variable_name}."
)
value_in_last_period = uprating_parameter(
latest_known_period.start
)
value_in_this_period = uprating_parameter(period.start)
if value_in_last_period == 0:
uprating_factor = 1
else:
uprating_factor = (
value_in_this_period / value_in_last_period
)
array = (
holder.get_array(latest_known_period, self.branch_name)
* uprating_factor
)
elif (
self.tax_benefit_system.auto_carry_over_input_variables
and variable.calculate_output is None
and len(known_periods) > 0
):
# Variables with a calculate-output property specify
last_known_period = sorted(known_periods)[-1]
if last_known_period.start > period.start:
return holder.default_array()
array = holder.get_array(last_known_period)
else:
array = holder.default_array()
if variable.defined_for is not None:
array = np.where(mask, array, variable.default_value)
if variable.value_type == Enum:
array = np.array(
[
item.index if isinstance(item, Enum) else item
for item in array
]
)
array = EnumArray(array, variable.possible_values)
array = self._cast_formula_result(array, variable)
holder.put_in_cache(array, period, self.branch_name)
except SpiralError:
array = holder.default_array()
except RecursionError as e:
if isinstance(self.tracer, FullTracer):
self.tracer.print_computation_log()
stack = self.tracer.stack
stack_formatted = "\n".join(
[
f" - {node.get('name')} {node.get('period')}, {node.get('branch_name')}"
for node in stack
]
)
raise Exception(
f"RecursionError while calculating {variable_name} for period {period}. The full computation stack is:\n{stack_formatted}"
)
if is_cache_available:
smc.set_cache_value(cache_path, array)
return array
def purge_cache_of_invalid_values(self) -> None:
# We wait for the end of calculate(), signalled by an empty stack, before purging the cache
if self.tracer.stack:
return
for _name, _period in self.invalidated_caches:
holder = self.get_holder(_name)
holder.delete_arrays(_period)
self.invalidated_caches = set()
def calculate_add(
self,
variable_name: str,
period: Period = None,
decode_enums: bool = False,
) -> ArrayLike:
variable = self.tax_benefit_system.get_variable(
variable_name, check_existence=True
)
if period is not None and not isinstance(period, Period):
period = periods.period(period)
# Check that the requested period matches definition_period
if periods.unit_weight(
variable.definition_period
) > periods.unit_weight(period.unit):
raise ValueError(
"Unable to compute variable '{0}' for period {1}: '{0}' can only be computed for {2}-long periods. You can use the DIVIDE option to get an estimate of {0} by dividing the yearly value by 12, or change the requested period to 'period.this_year'.".format(
variable.name, period, variable.definition_period
)
)
if variable.definition_period not in [
periods.DAY,
periods.MONTH,
periods.YEAR,
]:
raise ValueError(
"Unable to sum constant variable '{}' over period {}: only variables defined daily, monthly, or yearly can be summed over time.".format(
variable.name, period
)
)
result = sum(
self.calculate(variable_name, sub_period)
for sub_period in period.get_subperiods(variable.definition_period)
)
holder = self.get_holder(variable.name)
holder.put_in_cache(result, period, self.branch_name)
return result
def calculate_divide(
self,
variable_name: str,
period: Period = None,
decode_enums: bool = False,
) -> ArrayLike:
variable = self.tax_benefit_system.get_variable(
variable_name, check_existence=True
)
if period is not None and not isinstance(period, Period):
period = periods.period(period)
# Check that the requested period matches definition_period
if variable.definition_period != periods.YEAR:
raise ValueError(
"Unable to divide the value of '{}' over time on period {}: only variables defined yearly can be divided over time.".format(
variable_name, period
)
)
if period.size != 1:
raise ValueError(
"DIVIDE option can only be used for a one-year or a one-month requested period"
)
if period.unit == periods.MONTH:
computation_period = period.this_year
result = (
self.calculate(variable_name, period=computation_period) / 12.0
)
holder = self.get_holder(variable.name)
holder.put_in_cache(result, period, self.branch_name)
return result
elif period.unit == periods.YEAR:
return self.calculate(variable_name, period)
raise ValueError(
"Unable to divide the value of '{}' to match period {}.".format(
variable_name, period
)
)
def calculate_output(
self, variable_name: str, period: Period = None
) -> ArrayLike:
"""
Calculate the value of a variable using the ``calculate_output`` attribute of the variable.
"""
variable = self.tax_benefit_system.get_variable(
variable_name, check_existence=True
)
if variable.calculate_output is None:
return self.calculate(variable_name, period)
return variable.calculate_output(self, variable_name, period)
def _run_formula(
self, variable: str, population: Population, period: Period
) -> ArrayLike:
"""
Find the ``variable`` formula for the given ``period`` if it exists, and apply it to ``population``.
"""
formula = variable.get_formula(period)
if formula is None:
values = None
if variable.adds is not None and len(variable.adds) > 0:
if isinstance(variable.adds, str):
try:
adds_parameter = get_parameter(
self.tax_benefit_system.parameters,
variable.adds,
)
except:
raise ValueError(
f"In the variable '{variable.name}', the 'adds' attribute is a string '{variable.adds}' that does not match any parameter."
)
adds_list = adds_parameter(period.start)
else:
adds_list = variable.adds
values = 0
for added_variable in adds_list:
if added_variable in self.tax_benefit_system.variables:
values = values + self.calculate(
added_variable, period, map_to=variable.entity.key
)
else:
try:
parameter = get_parameter(
self.tax_benefit_system.parameters,
added_variable,
)
values = values + parameter(period.start)
except:
raise ValueError(
f"In the variable '{variable.name}', the 'adds' attribute is a list that contains a string '{added_variable}' that does not match any variable or parameter."
)
if variable.subtracts is not None and len(variable.subtracts) > 0:
if isinstance(variable.subtracts, str):
try:
subtracts_parameter = get_parameter(
self.tax_benefit_system.parameters,
variable.subtracts,
)
except:
raise ValueError(
f"In the variable '{variable.name}', the 'subtracts' attribute is a string '{variable.subtracts}' that does not match any parameter."
)
subtracts_list = subtracts_parameter(period.start)
else:
subtracts_list = variable.subtracts
if values is None:
values = 0
for subtracted_variable in subtracts_list:
if (
subtracted_variable
in self.tax_benefit_system.variables
):
values = values - self.calculate(
subtracted_variable,
period,
map_to=variable.entity.key,
)
else:
try:
parameter = get_parameter(
self.tax_benefit_system.parameters,
subtracted_variable,
)
values = values + parameter(period.start)
except:
raise ValueError(
f"In the variable '{variable.name}', the 'subtracts' attribute is a list that contains a string '{subtracted_variable}' that does not match any variable or parameter."
)
return values
if self.trace and not isinstance(
self.tax_benefit_system.parameters, TracingParameterNodeAtInstant
):
# Soft-recast
self.tax_benefit_system.parameters.branch_name = self.branch_name
self.tax_benefit_system.parameters.trace = True
self.tax_benefit_system.parameters.tracer = self.tracer
parameters_at = self.tax_benefit_system.parameters
if formula.__code__.co_argcount == 2:
array = formula(population, period)
else:
array = formula(population, period, parameters_at)
return array