Repository navigation
Conversation
Tests that fail before the change: Population.current_law reads a variable declared with current_law_read, an undeclared read raises, each declared call is reported to the tracer, a reform simulation builds no current-law copy while it is constructed, the copy is built from the inputs held when it is first needed and made read-only by the first declared call, and assigning baseline replaces the copy. Two existing tests read the baseline branch before anything built it; they now build it through simulation.baseline, or drop it only if it exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Core requires a label on every variable, and income tax is calculated in float32, so the tests compare it with the expected amounts to one part in a million. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A variable that must be calculated after another raises in the current-law copy when the copy has not requested that other variable, as it did when construction built the copy, even if the reform simulation requested it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Formulas read current law through declared calls, each reported to the
simulation's tracer (record_current_law_call; the full tracer keeps them on
TraceNode.current_law_calls):
- Population.current_law(variable, period) reads a variable declaring
current_law_read = True, and raises UndeclaredCurrentLawReadError for any
other; without a reform it returns the simulation's own value.
- Simulation.compares_with_current_law and Simulation.current_law_system,
which never build a copy.
- Simulation.current_law_simulation(), the simulation that calculates
current-law values.
A reform simulation no longer branches its current-law copy while it is
constructed. The overridable _build_current_law_simulation() builds it the
first time it is needed: a branch named baseline under the default system
instance, keeping the inputs held then and dropping calculated values. The
first declared call that reaches it makes it read-only. Branches read their
parent's copy, and clone() and subsample() keep a copy only if one was built.
Simulation.baseline is now a deprecated property: reading it returns the copy,
left writable, and is reported to the tracer; assigning a simulation makes it
the copy, kept as given, and assigning None stops the comparison.
get_branch("baseline") still returns the copy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the fixes: current_law is projected through entity
projections like a population call; current_law without a period raises
before building the copy and names the calling code; a derivative does not
depend on whether the copy was built before it; removing the registered copy
lets get_branch("baseline") make a new branch; a simulation saved with
baseline in its instance dictionary keeps it; an AttributeError while building
the copy is not read as "no baseline".
Tests for behaviour that already holds: options pass through current_law; a
copy built inside a calculation ignores that calculation's reform values; a
clone of a simulation with a read-only copy gets its own copy; a branch of a
branch reads the first simulation's copy; a deep copy keeps its own copy; the
declaration check reads an assigned simulation's system. One edited test now
builds the baseline by reading it, and two test modules no longer say
construction builds the branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- current_law is projectable, so person.household.current_law(...) returns
one value per person, as person.household(...) does.
- current_law checks the period before building the copy, so a missing
period builds nothing and the error names the calling code.
- derivative builds the current-law copy before cloning, so its result does
not depend on whether an earlier call built the copy: the changed clone
compares with the current law of the simulation's own inputs, as before.
- get_branch("baseline") returns a built copy missing from branches only on a
read-only simulation; elsewhere, code that removed the registered copy gets
a new branch, as before.
- subsample builds a copy core built again with _build_current_law_simulation,
so an override applies and the copy starts with nothing requested; other
baseline branches are rebuilt as before.
- The builder also clears pending cache invalidations.
- A simulation that kept baseline in its instance dictionary (saved by an
earlier core) keeps it as its current-law copy.
- An AttributeError while building the copy through the baseline property is
raised as a RuntimeError, so getattr(simulation, "baseline", None) does not
read it as "no baseline".
- Docstrings no longer say construction builds the copy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the fixes: a read-only simulation registers the
current-law copy it builds, so a clone of it keeps its copy registered and
get_branch("baseline") and subsample see it; a saved simulation's own
baseline branch, kept in its instance dictionary by an earlier core, is
copied by clone rather than shared; assigning baseline on a read-only
simulation raises.
Tests for behaviour that already holds: subsample builds a read-only copy
again as a writable one, and does so with an overridden builder; a copy built
in a calculation that runs again after an input change reads the new input.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A read-only simulation registers the current-law copy it builds, so a
clone of it keeps its copy registered and get_branch("baseline") and
subsample see it. get_branch("baseline") now returns the record's copy
only while it is not built.
- clone() and get_branch() turn a baseline kept in the instance dictionary by
an earlier core into a record before deciding, so a clone copies a saved
simulation's own baseline branch rather than sharing it.
- Assigning baseline on a read-only simulation raises
ReadOnlySimulationError, as assigning tax_benefit_system does.
- The builder and subsample set up the baseline branch with one helper,
_make_current_law_branch, and subsample gives the simulation a new record
in both of its paths.
- Docstrings: the builder is also called by subsample; get_branch's
"baseline" case applies to a reform simulation, not its branches; a
current_law result from a read-only copy is non-writable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the fixes: a clone announced as a branch outside get_branch (as policyengine-uk's subsample makes one, to share arrays) builds its own current-law copy from its own inputs and does not keep its source alive through the current-law record; assigning baseline on a simulation saved by an earlier core drops the saved attribute, so its clones do not carry it. Test for behaviour that already holds: a traced clone of a simulation whose copy is built traces the clone's copy in the clone. The clone test module's docstring now says when a test's clone builds a copy of its own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The template's module-level system names the last simulation built from it, which keeps that simulation alive whatever the clone holds, so the test now checks that the clone's current-law record refers to the clone and not to its source. It fails before the fix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A clone announced as a branch outside get_branch (policyengine-uk's subsample announces one to share arrays) gets a current-law record of its own that does not refer to its source, so it no longer keeps the source alive, and builds its own copy from its own inputs. get_branch gives the branch its parent's record once the clone is made. - Assigning baseline drops a baseline kept in the instance dictionary by an earlier core, so clones and pickles no longer carry it. - Docstrings: current_law_system names the default system of the simulation the copy is built from; current_law_simulation states that the copy is registered, also on a read-only simulation; current_law states the exception for an assigned simulation; TraceNode.current_law_calls says the values read are children only when the calculating simulation shares the tracer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests that fail before the change: export, save, load and supply give the current-law copy's values for every registered variable and value type; ID arrays that differ are refused naming the entity; Enum values are supplied by member name; supplied values are calculated values, never inputs or uprating bases; a run with every read supplied builds no copy; a subsample drops the values and logs it; the file is one versioned HDF5 file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed values Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
export_current_law_values calculates every variable that declares current_law_read = True on a simulation without a reform (the calculation year, its months for monthly variables, eternity for eternal ones) and returns a CurrentLawValues with each entity's ID array and the source run id. save and load write one HDF5 file whose JSON manifest names the format and its version; load refuses another format or a newer version and ignores groups it does not list. Numbers, booleans, dates, strings and Enum values are kept, Enum values as positions with their member names. A simulation takes them with current_law_values= or supply_current_law_values, which checks each entity's ID array element by element and maps Enum values to the current-law system's Enum classes by member name, raising CurrentLawValuesMismatchError naming the entity or variable. Declared reads and supplied_current_law_value return supplied values, not writable, without building the current-law copy; a copy core builds starts from them as calculated values, never inputs. Clones and branches keep them; subsample drops them and logs a warning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Clones made before the copy is built read current law of their own inputs; a declared read of a variable holding an input reads the input; a rebuilt population drops supplied values and logs it; Enum positions outside the saved members and arrays of the wrong length are refused naming the variable; byte-string IDs are accepted after save and load; a copy built through the baseline alias hands out writable values; supplying to a branch is refused; a failed subsample keeps the values. Two tests cover behaviour that already holds: an assigned baseline is not filled, and ADD reads go to the copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A clone made before the current-law copy is built no longer keeps supplied values, so it calculates current law from its own inputs, as a clone does without them; get_branch gives branches the simulation's values. Declared reads and supplied_current_law_value skip a supplied value where the simulation holds an input for that variable and period. build_from_populations drops supplied values with the same logged warning as subsample, and a read whose array no longer fits the population drops them too; subsample drops them only once its own checks have passed. Supplying refuses Enum positions outside the saved member names, arrays whose length differs from their entity's IDs, and a branch. Byte-string IDs compare as text. A copy is filled with writable copies of the arrays. save writes through a temporary file of its own. Docs describe which inputs the values reflect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The saved file gets the mode a new file gets, and a population replaced without build_from_populations drops the supplied values before a copy is filled from them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
save gives the file the mode a newly created file gets, not the owner-only mode of its temporary file. Filling a copy checks each supplied array's length against the copy's population first, and drops the values with the logged warning when the population changed some way that did not drop them. The refusal on a branch names clones of branches too; docs describe deep copies and the input exception. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An input set after a supplied read does not change later reads, as it does not without supplied values; saving never changes the process umask. The input exception's test now sets the input before the values are supplied. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
save creates its temporary file with os.open and mode 0o666, so the process umask gives it a new file's mode, instead of changing the umask and the file's mode. Whether a supplied value is skipped for an input the simulation holds is decided once, when the values are supplied, so an input set later cannot make one run give two current-law values for the same variable and period. Docs and the changelog fragment name the error class, the logged drops, export's default period and the eternity key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #678
What this adds
A simulation run without a reform can save the current-law values a reform simulation over the same population would otherwise calculate again, and a reform simulation can use them instead of building its current-law copy. New module
policyengine_core.simulations.current_law_values.export_current_law_values(simulation, period=None, source_run_id=None)calculates every variable that declarescurrent_law_read = True: a yearly variable for the calculation year (by defaultdefault_calculation_period), a monthly variable for each of its twelve months, an eternal variable once (a variable defined for days is left out, with a warning). It returns aCurrentLawValues: arrays keyed by variable andPeriodKey(unit, first day, size; notstr(period)), each entity's ID array, andsource_run_id. Every value type core stores is kept: numbers, booleans, dates, strings, and Enum values as positions with their member names. Arrays are copied and not writable. It refuses a simulation that compares with current law.values.save(path)writes one HDF5 file:entity_ids/<entity>andarrays/<n>datasets, and a JSON manifest in the root attributemanifest(format name, format version 1, core version,source_run_id,calculated_values, and each dataset's variable, period, dtype and Enum member names). It writes a temporary file of its own besidepathand moves it into place.CurrentLawValues.load(path)refuses another format or a newer version and ignores groups the manifest does not list, so a later format (a seeds file) can extend this one.Simulation(..., current_law_values=values)calls the new publicsimulation.supply_current_law_values(values)once its population is built. A caller that builds the population after construction (.py's US model), or a simulation that does not run core's constructor (policyengine-uk), calls it once the population is in place.CurrentLawValuesMismatchError(aValueError) naming the entity or the variable, and leaves the simulation as it was. Every other check on where the values came from belongs to the caller.Population.current_law(...)without options returns a supplied value, not writable, without building the copy. ADD and DIVIDE reads and periods not supplied go to the copy.simulation.supplied_current_law_value(variable, period)returns the supplied array orNone, never builds the copy, and is reported to the tracer as a declared call.put_in_cache(..., derived=True)as calculated values, so its branches do too. They are never inputs: not ininput_variablesor the input record, and never an uprating or carry-over base. A simulation assigned tobaselineis kept as given and not filled.get_branchread the supplied values, as they read the simulation's copy.subsample(just before it rebuilds the population) andbuild_from_populationsdrop them and log a warning on the loggerpolicyengine_core.simulations.current_law_values. So does a read, or a copy being built, after the population changed some other way.The values describe current law for the inputs the simulation held when they were supplied. Inputs set afterwards on the simulation, or on its copy through the deprecated
baselinealias, are not reflected in them. Dropping the values whenever an input changes would discard them in policyengine-us, whose constructor moves inputs after core's__init__supplies them, and decision D1 leaves those checks to the caller.Docs:
docs/python_api/simulations.md("Stored current-law values") anddocs/python_api/errors.md. Changelog:changelog.d/current-law-values.added.md.Builds on #675
This branch starts from #675's head
13aad572(declared-current-law-reads, still open), which adds the declared current-law calls and the copy built on demand. Until #675 merges, this PR's diff againstmasterincludes #675's commits. This PR's own commits are those after13aad572.Population.current_law's declaration check moved intoSimulation._declared_current_law_variable, shared withsupplied_current_law_value; its message is unchanged.Known limits for country packages
current_law_values=reaches it. Its constructor readsbaseline(migrate_social_security_inputs), which builds and fills a copy, then_rebuild_baseline_branchassigns its own branch, which core keeps unfilled. So only declared reads without options use the values, until project 14's task 2.5 · 1 turns that rebuild into a_build_current_law_simulationoverride. No policyengine-us variable declarescurrent_law_readyet.baselineon every simulation, so every UK simulation compares with current law andexport_current_law_valuesrefuses it until task 2.7 · 1 changes that.situation={}and its population afterwards, so it supplies values withsupply_current_law_values(task 3.3 · 1).Checks
tests/core/test_current_law_values.py, 41 tests. Each test commit precedes the change or fix it tests, and each test was run by node ID:0f4feafc, count corrected in24da6442): all 23 failed on the assertion that the new module exists. 2 more (8ccf920e, pickling the values and deep-copying a simulation) also fail there on that commit. Against the first, uncommitted version of the change they failed on a caughtTypeError, becauseMappingProxyTypedoes not pickle. All 25 pass on the change commit87f832dc.62f78c71): 10 failed on assertions before the fixes inb559d18c. The other 3 cover behaviour that already held: branches and clones made with the copy, an assignedbaselineleft unfilled, and ADD reads going to the copy.d1b537b9): both failed before the fixes ind3a80380.69202604): both failed before the fixes in702bd199. One round-1 test now sets its input before the values are supplied.13aad572; after: this branch). Core's country template with test variables of every value type, a reform income tax rate of 0.42 against 0.15 from 2022, and two people in one household. Compared: 85 values, each registered variable's reform value and itscurrent_lawread for every exported period, plusincome_tax. They are identical before and after without supplied values, and identical again with values exported from a current-law run and supplied.ruff format --check .andruff checkon the changed files are clean.Review rounds
Three rounds of adversarial review before this PR opened:
subsamplekept the values.baselinehanded out non-writable values.Left (code quality, no bug found):
loadraisesKeyErrororTypeError, notValueError, for unexpected content under the same format version.derivative().Merge order
This PR waits for these earlier tasks in the same set to merge; nothing here uses the first two, and none needs a release first:
Simulation.temporary_branch).No release of another package is needed before this merges.
🤖 Generated with Claude Code