|
| 1 | +""" |
| 2 | +Dynamic Weight Modification in PolicyEngine Microsimulation |
| 3 | +
|
| 4 | +When changing household_weight, ALL derived weight variables must be invalidated |
| 5 | +""" |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +from policyengine_us import Microsimulation |
| 9 | + |
| 10 | +sim = Microsimulation(dataset="hf://policyengine/policyengine-us-data/enhanced_cps_2024.h5") |
| 11 | +period = 2024 |
| 12 | +n_households = len(sim.calculate("household_id", period)) |
| 13 | + |
| 14 | +# Calculate total income tax with original weights |
| 15 | +income_tax = sim.calculate("income_tax", period) |
| 16 | +sim.calculate("income_tax", period) |
| 17 | +income_tax.sum() / 1E9 |
| 18 | + |
| 19 | + |
| 20 | +# Change weights and nothing happens! |
| 21 | +new_weights = 10 * np.ones(n_households) |
| 22 | +sim.set_input("household_weight", period, new_weights) |
| 23 | + |
| 24 | +sim.calculate("income_tax", period) # weights not changed |
| 25 | +income_tax = sim.calculate("income_tax", period) |
| 26 | +income_tax.sum() / 1E9 # sum not changed |
| 27 | + |
| 28 | +# Invalidate all weight-related caches so they recalculate |
| 29 | +for entity_weight in ['household_weight', 'tax_unit_weight', 'person_weight', |
| 30 | + 'spm_unit_weight', 'marital_unit_weight']: |
| 31 | + sim.delete_arrays(entity_weight, period) |
| 32 | + |
| 33 | +# Recalculate with new weights |
| 34 | +sim.calculate("income_tax", period) # Now they're zeros |
| 35 | +sim.calculate("income_tax", period, map_to="household") # Now they're zeros |
| 36 | +sim.calculate("income_tax", period).sum() / 1E9 # zero, because tax_unit weights are zero |
| 37 | +sim.calculate("income_tax", period, map_to="household").sum() / 1E9 # not zero, because household weights are zero |
| 38 | + |
| 39 | +income_tax = sim.calculate("income_tax", period).sum() |
| 40 | +income_tax.sum() / 1E9 |
0 commit comments