From 77f3121b9c009a30a4abb12b9c474cdc6b6adc6f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 02:47:01 +0000 Subject: [PATCH 1/6] Fix self uprating growth and projection counts Co-Authored-By: GPT-6.2 Sol --- changelog.d/uprate-self-growth.fixed.md | 1 + docs/usage/parameters.md | 2 + .../operations/uprate_parameters.py | 52 +++++-- .../parameters/operations/test_uprating.py | 137 ++++++++++++++++++ 4 files changed, 176 insertions(+), 16 deletions(-) create mode 100644 changelog.d/uprate-self-growth.fixed.md diff --git a/changelog.d/uprate-self-growth.fixed.md b/changelog.d/uprate-self-growth.fixed.md new file mode 100644 index 000000000..dc3f85d57 --- /dev/null +++ b/changelog.d/uprate-self-growth.fixed.md @@ -0,0 +1 @@ +Self uprating compounds growth per interval and adds the requested number of future values. diff --git a/docs/usage/parameters.md b/docs/usage/parameters.md index 19a3a258b..864e36aff 100644 --- a/docs/usage/parameters.md +++ b/docs/usage/parameters.md @@ -90,6 +90,8 @@ metadata: `rounding` rounds the uprated amount, as a floating-point number, to a multiple of `interval`; `nearest` takes an exact half to the even multiple. A bare float, such as `rounding: 0.01`, rounds to the nearest multiple. Chained mode also takes `start_instant`, to project from an instant other than the last explicit value; `at_defined_interval`, to uprate on a fixed cadence; and `parameter: self`, to extend the parameter's own growth. +Self uprating compounds the growth from `from` to `to` at a constant rate per `interval` (`year` by default, or `month` or `day`). The dates default to one interval before the last explicit value and the date of that value, respectively. The growth span must be positive and cover whole intervals. `number` sets how many future values to add after the last explicit value and defaults to ten. + ### Base mode Some statutes index a fixed base amount and round the increase rather than the increased amount. 26 U.S.C. 63(c)(7)(B)(ii), for example, increases the $23,625 head-of-household standard deduction by the cost-of-living adjustment since 2024 and rounds that increase down to a multiple of $50. A `base` block opts a parameter into this rule: diff --git a/policyengine_core/parameters/operations/uprate_parameters.py b/policyengine_core/parameters/operations/uprate_parameters.py index 0a1b10b7f..c9015dd61 100644 --- a/policyengine_core/parameters/operations/uprate_parameters.py +++ b/policyengine_core/parameters/operations/uprate_parameters.py @@ -1107,25 +1107,45 @@ def construct_cadence_options(cadence_settings: dict, parameter: Parameter) -> d def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: + interval = meta.get("interval", "year") last_instant = instant(parameter.values_list[0].instant_str) - start_instant = instant( - meta.get( - "from", - last_instant.offset(-1, meta.get("interval", "year")), - ) - ) - start = parameter(start_instant) end_instant = instant(meta.get("to", last_instant)) - end = parameter(end_instant) - increase = end / start - if "from" in meta: - # This won't work for non-year periods, which are more complicated - increase / (end_instant.year - start_instant.year) + start_instant = ( + instant(meta["from"]) if "from" in meta else last_instant.offset(-1, interval) + ) + + # The default start is one interval back, including month-end clipping. + periods = 1 + if "from" in meta or end_instant != last_instant: + if end_instant <= start_instant: + raise ValueError( + f"Failed to self-uprate {parameter.name}: to must be after from" + ) + if interval == "day": + periods = (end_instant.date - start_instant.date).days + else: + periods = end_instant.year - start_instant.year + if interval == "month": + periods = 12 * periods + end_instant.month - start_instant.month + if start_instant.offset(periods, interval) != end_instant: + raise ValueError( + f"Failed to self-uprate {parameter.name}: from {start_instant} " + f"to {end_instant} must span whole {interval} intervals" + ) + + increase = parameter(end_instant) / parameter(start_instant) + if periods > 1: + if increase < 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: negative growth factor " + f"over {periods} {interval} intervals" + ) + increase **= 1 / periods + data = {} value = parameter.values_list[0].value - for i in range(meta.get("number", 10)): - data[str(last_instant.offset(i, meta.get("interval", "year")))] = ( - value * increase - ) + # The chained calculation needs an anchor at the last explicit instant. + for i in range(meta.get("number", 10) + 1): value *= increase + data[str(last_instant.offset(i, interval))] = value return Parameter("self", data=data) diff --git a/tests/core/parameters/operations/test_uprating.py b/tests/core/parameters/operations/test_uprating.py index 74aee22ef..90e2c9db7 100644 --- a/tests/core/parameters/operations/test_uprating.py +++ b/tests/core/parameters/operations/test_uprating.py @@ -431,6 +431,143 @@ def test_parameter_uprating_with_self(): assert uprated.to_be_uprated("2018-01-01") == 8 +@pytest.mark.parametrize( + "interval, start, end, next_instant, end_value, projected", + [ + pytest.param( + "year", "2020-01-01", "2022-01-01", "2023-01-01", 4, 8, id="two-years" + ), + pytest.param( + "year", "2020-01-01", "2022-01-01", "2023-01-01", 9, 27, id="ninefold" + ), + pytest.param( + "month", "2020-11-01", "2021-01-01", "2021-02-01", 9, 27, id="two-months" + ), + pytest.param( + "day", "2020-02-28", "2020-03-01", "2020-03-02", 9, 27, id="two-days" + ), + ], +) +def test_self_uprating_compounds_growth_per_interval( + interval, start, end, next_instant, end_value, projected +): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {start: 1, end: end_value}, + "metadata": { + "uprating": { + "parameter": "self", + "interval": interval, + "from": start, + "to": end, + }, + }, + }, + } + ) + + assert uprate_parameters(root).amount(next_instant) == projected + + +@pytest.mark.parametrize( + "interval, start, end, options, expected", + [ + pytest.param( + "year", + "1999-01-01", + "2000-01-01", + {"number": 1}, + {"2001-01-01": 4}, + id="one-year", + ), + pytest.param( + "month", + "2021-02-28", + "2021-03-31", + {"number": 1}, + {"2021-04-30": 4}, + id="one-month", + ), + pytest.param( + "day", + "2020-12-31", + "2021-01-01", + {"number": 1}, + {"2021-01-02": 4}, + id="one-day", + ), + pytest.param("year", "1999-01-01", "2000-01-01", {"number": 0}, {}, id="zero"), + pytest.param( + "year", + "1999-01-01", + "2000-01-01", + {}, + {f"{2000 + i}-01-01": 2 ** (i + 1) for i in range(1, 11)}, + id="default-ten", + ), + ], +) +def test_self_uprating_counts_future_values(interval, start, end, options, expected): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {start: 1, end: 2}, + "metadata": { + "uprating": {"parameter": "self", "interval": interval, **options}, + }, + }, + } + ) + + amount = uprate_parameters(root).amount + assert {entry.instant_str: entry.value for entry in amount.values_list} == { + start: 1, + end: 2, + **expected, + } + + +@pytest.mark.parametrize( + "interval, start, end, end_value, error", + [ + ("year", "2020-01-01", "2022-02-01", 4, "whole year intervals"), + ("month", "2020-11-01", "2021-01-02", 4, "whole month intervals"), + ("day", "2020-01-01", "2020-01-01", 4, "to must be after from"), + ("day", "2020-01-03", "2020-01-01", 4, "to must be after from"), + ("year", "2020-01-01", "2022-01-01", -4, "negative growth factor"), + ], + ids=["partial-year", "partial-month", "same-date", "reversed", "negative-factor"], +) +def test_self_uprating_rejects_invalid_growth_spans( + interval, start, end, end_value, error +): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {start: 1, end: end_value}, + "metadata": { + "uprating": { + "parameter": "self", + "interval": interval, + "from": start, + "to": end, + }, + }, + }, + } + ) + + with pytest.raises(ValueError, match=error): + uprate_parameters(root) + + def test_parameter_uprating_with_cadence(): from policyengine_core.parameters import ParameterNode From dd15697d761cc718d60e0c09f57012be1e2358fe Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 02:47:01 +0000 Subject: [PATCH 2/6] Compound self growth and count future values in the chained reference Co-Authored-By: GPT-6.2 Sol --- tests/fixtures/chained_uprating_reference.py | 55 ++++++++++++++------ 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/tests/fixtures/chained_uprating_reference.py b/tests/fixtures/chained_uprating_reference.py index cac4db4bf..cdd4b19e0 100644 --- a/tests/fixtures/chained_uprating_reference.py +++ b/tests/fixtures/chained_uprating_reference.py @@ -11,6 +11,9 @@ every chained-mode parameter exactly what ``reference_uprate_parameters`` gives it, and pins a few chained outputs as literals. A change that means to alter chained mode should update this copy with the reason. +Self uprating compounds growth per interval to preserve the observed rate +and counts only future values toward ``number`` so each requested projection +is added. """ # ruff: noqa @@ -678,27 +681,47 @@ def construct_cadence_options(cadence_settings: dict, parameter: Parameter) -> d def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: + interval = meta.get("interval", "year") last_instant = instant(parameter.values_list[0].instant_str) - start_instant = instant( - meta.get( - "from", - last_instant.offset(-1, meta.get("interval", "year")), - ) - ) - start = parameter(start_instant) end_instant = instant(meta.get("to", last_instant)) - end = parameter(end_instant) - increase = end / start - if "from" in meta: - # This won't work for non-year periods, which are more complicated - increase / (end_instant.year - start_instant.year) + start_instant = ( + instant(meta["from"]) if "from" in meta else last_instant.offset(-1, interval) + ) + + # The default start is one interval back, including month-end clipping. + periods = 1 + if "from" in meta or end_instant != last_instant: + if end_instant <= start_instant: + raise ValueError( + f"Failed to self-uprate {parameter.name}: to must be after from" + ) + if interval == "day": + periods = (end_instant.date - start_instant.date).days + else: + periods = end_instant.year - start_instant.year + if interval == "month": + periods = 12 * periods + end_instant.month - start_instant.month + if start_instant.offset(periods, interval) != end_instant: + raise ValueError( + f"Failed to self-uprate {parameter.name}: from {start_instant} " + f"to {end_instant} must span whole {interval} intervals" + ) + + increase = parameter(end_instant) / parameter(start_instant) + if periods > 1: + if increase < 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: negative growth factor " + f"over {periods} {interval} intervals" + ) + increase **= 1 / periods + data = {} value = parameter.values_list[0].value - for i in range(meta.get("number", 10)): - data[str(last_instant.offset(i, meta.get("interval", "year")))] = ( - value * increase - ) + # The chained calculation needs an anchor at the last explicit instant. + for i in range(meta.get("number", 10) + 1): value *= increase + data[str(last_instant.offset(i, interval))] = value return Parameter("self", data=data) From f9986cf20c308bcccb775465b1d0dc0abd23e01d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 17:22:09 +0000 Subject: [PATCH 3/6] Apply self-uprating growth directly to projections Accept calendar clipping from either endpoint, diagnose a zero starting value, and count future cadence dates. Co-Authored-By: GPT-6.2 Sol --- changelog.d/uprate-self-growth.fixed.md | 2 +- docs/contributing/intro.md | 15 +- docs/usage/parameters.md | 4 +- .../operations/uprate_parameters.py | 194 ++++++++++++------ .../operations/test_base_uprating_property.py | 12 ++ .../parameters/operations/test_uprating.py | 133 ++++++++++++ 6 files changed, 281 insertions(+), 79 deletions(-) diff --git a/changelog.d/uprate-self-growth.fixed.md b/changelog.d/uprate-self-growth.fixed.md index dc3f85d57..3442c8ec7 100644 --- a/changelog.d/uprate-self-growth.fixed.md +++ b/changelog.d/uprate-self-growth.fixed.md @@ -1 +1 @@ -Self uprating compounds growth per interval and adds the requested number of future values. +Self uprating compounds growth per whole calendar interval, handles zero and large projections, and adds the requested number of future values on regular and cadence schedules. diff --git a/docs/contributing/intro.md b/docs/contributing/intro.md index 700a0f735..c88d281d3 100644 --- a/docs/contributing/intro.md +++ b/docs/contributing/intro.md @@ -9,17 +9,10 @@ If you file an issue or a pull request, one of the maintainers (primarily [@nikh ## Changelog Entries -Before you send out a pull request, make sure to add a description of your changes to [changelog_entry.yaml](../../changelog_entry.yaml). -For example, -```yaml -- bump: patch - changes: - fixed: - - Fixed a bug causing Windows tests to fail. -``` -You can find more examples in [changelog.yaml](../../changelog.yaml). Note that you do not need to add the date field. -That field is automatically populated by `make changelog`. Also, note that **you should not run `make changelog` -yourself**, as [our GitHub workflows](../../.github/workflows) will do this for you as part of the build process. +Before opening a pull request, add a one-sentence Markdown fragment to +[`changelog.d/`](./changelog.d/), such as `fix-windows-tests.fixed.md`. +Use a type listed in the [changelog fragment guide](./docs/engineering/skills/github-prs.md#changelog-fragment). +The release workflow builds the changelog from these fragments after merge. ## Pull requests diff --git a/docs/usage/parameters.md b/docs/usage/parameters.md index 864e36aff..0d49b52c3 100644 --- a/docs/usage/parameters.md +++ b/docs/usage/parameters.md @@ -90,7 +90,9 @@ metadata: `rounding` rounds the uprated amount, as a floating-point number, to a multiple of `interval`; `nearest` takes an exact half to the even multiple. A bare float, such as `rounding: 0.01`, rounds to the nearest multiple. Chained mode also takes `start_instant`, to project from an instant other than the last explicit value; `at_defined_interval`, to uprate on a fixed cadence; and `parameter: self`, to extend the parameter's own growth. -Self uprating compounds the growth from `from` to `to` at a constant rate per `interval` (`year` by default, or `month` or `day`). The dates default to one interval before the last explicit value and the date of that value, respectively. The growth span must be positive and cover whole intervals. `number` sets how many future values to add after the last explicit value and defaults to ten. +Self uprating compounds the growth from `from` to `to` at a constant rate per `interval` (`year` by default, or `month` or `day`). The dates default to one interval before the last explicit value and the date of that value, respectively. The span must be positive and cover whole intervals. A calendar offset from either endpoint may clip to the last valid day of the target month. For example, February 28 to March 31 can be one month, and February 28 to February 29 of the following year can be one year. + +The value at `from` must be nonzero. Growth to zero is valid. `number` sets how many future values to add after the last explicit value, including when `at_defined_interval` sets the projection dates. It defaults to ten and accepts zero. ### Base mode diff --git a/policyengine_core/parameters/operations/uprate_parameters.py b/policyengine_core/parameters/operations/uprate_parameters.py index c9015dd61..ed8ec3ac1 100644 --- a/policyengine_core/parameters/operations/uprate_parameters.py +++ b/policyengine_core/parameters/operations/uprate_parameters.py @@ -322,6 +322,8 @@ def uprate_parameter( Chained mode, the default, grows the parameter's last explicit value by the index's change since that value's instant and rounds the uprated amount. + Self uprating applies the parameter's own per-interval growth to the last + explicit value and adds ``number`` future values, including on a cadence. Base mode, chosen by an ``uprating.base`` block, computes each projected value from a fixed base amount and rounds the increase over it; see :func:`uprate_parameter_from_base`. @@ -342,12 +344,21 @@ def uprate_parameter( uprate_parameter_from_base(parameter, root, meta, parameter_paths) return - # If param is "self", construct the uprating table + cadence_meta = meta.get("at_defined_interval") + self_growth = None + number = None if meta["parameter"] == "self": - uprating_parameter = construct_uprater_self( - parameter, - meta, - ) + self_growth = get_self_uprating_growth(parameter, meta) + number = meta.get("number", 10) + if not isinstance(number, int) or number < 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: number must be a non-negative integer" + ) + if not cadence_meta: + uprate_parameter_from_self(parameter, meta, self_growth, number) + return + uprating_parameter = None + uprating_name = "self" # Otherwise, pull uprating table from YAML else: uprating_parameter = get_uprating_parameter( @@ -356,10 +367,10 @@ def uprate_parameter( meta["parameter"], parameter_paths, ) + uprating_name = uprating_parameter.name # If uprating with a set candence, ensure that all # required values are present - cadence_meta = meta.get("at_defined_interval") cadence_options = {} if cadence_meta: cadence_options_test = [ @@ -380,11 +391,11 @@ def uprate_parameter( # Ensure that end comes after start and enactment comes after end if cadence_options["end"] <= cadence_options["start"]: raise ValueError( - f"Failed to uprate {parameter.name} using {uprating_parameter.name}: end must come after start" + f"Failed to uprate {parameter.name} using {uprating_name}: end must come after start" ) if cadence_options["enactment"] <= cadence_options["end"]: raise ValueError( - f"Failed to uprate {parameter.name} using {uprating_parameter.name}: enactment must come after end" + f"Failed to uprate {parameter.name} using {uprating_name}: enactment must come after end" ) # Determine the first date from which to start uprating - @@ -392,8 +403,10 @@ def uprate_parameter( # following the last defined param value (not including the # final value) uprating_first_date: datetime = find_cadence_first(parameter, cadence_options) - uprating_last_date: datetime = find_cadence_last( - uprating_parameter, cadence_options + uprating_last_date = ( + find_cadence_last(uprating_parameter, cadence_options) + if uprating_parameter is not None + else None ) # Uprate data @@ -404,6 +417,8 @@ def uprate_parameter( uprating_first_date, uprating_last_date, meta, + self_growth=self_growth, + number=number, ) # Append uprated data to parameter values list @@ -986,24 +1001,31 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime: def uprate_by_cadence( parameter: Parameter, - uprating_parameter: Parameter, + uprating_parameter: Optional[Parameter], cadence_options: dict, first_date: datetime, - last_date: datetime, + last_date: Optional[datetime], meta: dict, + *, + self_growth: Optional[float] = None, + number: Optional[int] = None, ) -> list[ParameterAtInstant]: - # Determine the frequency module to utilize within rrule - interval = "" - rrule_interval = "" - if cadence_options.get("interval"): - interval = cadence_options["interval"] - rrule_interval = getattr(rrule, ((interval + "LY").upper())) + interval = cadence_options.get("interval", "year") + if self_growth is not None and interval == "day": + rrule_interval = rrule.DAILY else: - interval = "year" - rrule_interval = rrule.YEARLY + rrule_interval = getattr(rrule, (interval + "LY").upper()) - # Generate a list of iterations iterations = rrule.rrule(freq=rrule_interval, dtstart=first_date, until=last_date) + if self_growth is not None: + anchor = instant(parameter.values_list[0].instant_str) + iterations = iterations.xafter( + datetime.combine(anchor.date, dt.time()), count=number + ) + reference_value = parameter(anchor) + growth_interval = meta.get("interval", "year") + else: + reference_value = parameter.get_at_instant(instant(first_date.date())) # Determine the offset between the first enactment # date and the first start and end date @@ -1015,32 +1037,35 @@ def uprate_by_cadence( cadence_options["enactment"], cadence_options["end"] ) - # Set a starting reference value to calculate against - reference_value = parameter.get_at_instant(instant(first_date.date())) - # For each entry (corresponding to an enactment date) in the iteration list... for enactment_date in iterations: # Calculate the start and end calculation dates start_calc_date: datetime = enactment_date - enactment_start_offset end_calc_date: datetime = enactment_date - enactment_end_offset - # Find uprater value at cadence start - start_val = uprating_parameter.get_at_instant(instant(start_calc_date.date())) - - # Find uprater value at cadence end - end_val = uprating_parameter.get_at_instant(instant(end_calc_date.date())) - - # Ensure that earliest date exists within uprater - if not start_val: - raise ValueError( - f"Failed to uprate {parameter.name} using {uprating_parameter.name}: uprater missing values at date {start_calc_date.date()}" + if self_growth is not None: + start = instant(start_calc_date.date()) + end = instant(end_calc_date.date()) + if start < anchor: + raise ValueError( + f"Failed to uprate {parameter.name} using self: uprater missing values at date {start}" + ) + start_step = self_uprating_step(anchor, start, growth_interval) + end_step = self_uprating_step(anchor, end, growth_interval) + uprated_value = reference_value + for _ in range(end_step - start_step): + uprated_value *= self_growth + else: + assert uprating_parameter is not None + start_val = uprating_parameter.get_at_instant( + instant(start_calc_date.date()) ) - - # Find difference of these values - difference = end_val / start_val - - # Uprate value - uprated_value = difference * reference_value + end_val = uprating_parameter.get_at_instant(instant(end_calc_date.date())) + if not start_val: + raise ValueError( + f"Failed to uprate {parameter.name} using {uprating_parameter.name}: uprater missing values at date {start_calc_date.date()}" + ) + uprated_value = (end_val / start_val) * reference_value if "rounding" in meta: uprated_value = round_uprated_value(meta, uprated_value) @@ -1106,7 +1131,26 @@ def construct_cadence_options(cadence_settings: dict, parameter: Parameter) -> d return cadence_options -def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: +def calendar_interval_count(start: Instant, end: Instant, interval: str) -> int: + """Count calendar years, months, or days between the dates' fields.""" + if interval == "day": + return (end.date - start.date).days + years = end.year - start.year + if interval == "month": + return 12 * years + end.month - start.month + return years + + +def self_uprating_step(anchor: Instant, date: Instant, interval: str) -> int: + """Find the last growth step reached by a date on the anchor's schedule.""" + steps = calendar_interval_count(anchor, date, interval) + if interval != "day" and anchor.offset(steps, interval) > date: + steps -= 1 + return steps + + +def get_self_uprating_growth(parameter: Parameter, meta: dict) -> float: + """Measure growth across whole intervals, allowing calendar clipping.""" interval = meta.get("interval", "year") last_instant = instant(parameter.values_list[0].instant_str) end_instant = instant(meta.get("to", last_instant)) @@ -1114,26 +1158,27 @@ def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: instant(meta["from"]) if "from" in meta else last_instant.offset(-1, interval) ) - # The default start is one interval back, including month-end clipping. - periods = 1 - if "from" in meta or end_instant != last_instant: - if end_instant <= start_instant: - raise ValueError( - f"Failed to self-uprate {parameter.name}: to must be after from" - ) - if interval == "day": - periods = (end_instant.date - start_instant.date).days - else: - periods = end_instant.year - start_instant.year - if interval == "month": - periods = 12 * periods + end_instant.month - start_instant.month - if start_instant.offset(periods, interval) != end_instant: - raise ValueError( - f"Failed to self-uprate {parameter.name}: from {start_instant} " - f"to {end_instant} must span whole {interval} intervals" - ) + if end_instant <= start_instant: + raise ValueError( + f"Failed to self-uprate {parameter.name}: to must be after from" + ) + periods = calendar_interval_count(start_instant, end_instant, interval) + if ( + interval != "day" + and start_instant.offset(periods, interval) != end_instant + and end_instant.offset(-periods, interval) != start_instant + ): + raise ValueError( + f"Failed to self-uprate {parameter.name}: from {start_instant} " + f"to {end_instant} must span whole {interval} intervals" + ) - increase = parameter(end_instant) / parameter(start_instant) + start = parameter(start_instant) + if start == 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: starting value at {start_instant} is zero" + ) + increase = parameter(end_instant) / start if periods > 1: if increase < 0: raise ValueError( @@ -1142,10 +1187,27 @@ def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: ) increase **= 1 / periods - data = {} - value = parameter.values_list[0].value - # The chained calculation needs an anchor at the last explicit instant. - for i in range(meta.get("number", 10) + 1): + return increase + + +def uprate_parameter_from_self( + parameter: Parameter, meta: dict, increase: float, number: int +) -> None: + """Project the amount directly and keep rounding out of the growth steps.""" + interval = meta.get("interval", "year") + last = parameter.values_list[0] + anchor = instant(last.instant_str) + start = instant(meta.get("start_instant", anchor)) + if start < anchor: + raise ValueError( + f"Failed to uprate using self at {start} for {parameter.name} because the uprating parameter is not defined at {start}." + ) + start_step = self_uprating_step(anchor, start, interval) + value = last.value + projections = [] + for step in range(start_step + 1, start_step + number + 1): value *= increase - data[str(last_instant.offset(i, interval))] = value - return Parameter("self", data=data) + rounded = round_uprated_value(meta, value) if "rounding" in meta else value + date = anchor.offset(step, interval) + projections.append(ParameterAtInstant(parameter.name, str(date), data=rounded)) + parameter.values_list[:0] = reversed(projections) diff --git a/tests/core/parameters/operations/test_base_uprating_property.py b/tests/core/parameters/operations/test_base_uprating_property.py index cc9bfbcec..b41f0a51e 100644 --- a/tests/core/parameters/operations/test_base_uprating_property.py +++ b/tests/core/parameters/operations/test_base_uprating_property.py @@ -804,6 +804,18 @@ def test_chained_mode_matches_the_implementation_before_base_mode(case): ) +def test_chained_reference_projects_zero_ending_value(): + data = { + "amount": { + "values": {"2020-01-01": 2, "2021-01-01": 0}, + "metadata": {"uprating": {"parameter": "self", "number": 1}}, + } + } + amount = reference_uprate_parameters(ParameterNode(data=data)).amount + assert amount.values_list[0].instant_str == "2022-01-01" + assert amount.values_list[0].value == 0 + + @pytest.mark.parametrize( "case, expected", [ diff --git a/tests/core/parameters/operations/test_uprating.py b/tests/core/parameters/operations/test_uprating.py index 90e2c9db7..235de2a24 100644 --- a/tests/core/parameters/operations/test_uprating.py +++ b/tests/core/parameters/operations/test_uprating.py @@ -568,6 +568,139 @@ def test_self_uprating_rejects_invalid_growth_spans( uprate_parameters(root) +MONTHLY_SELF_CADENCE = { + "interval": "month", + "start": "2022-01-01", + "end": "2022-02-01", + "enactment": "2022-03-01", + "effective": "2022-03-01", +} + + +@pytest.mark.parametrize( + "values, options, expected", + [ + pytest.param( + {"2021-02-28": 1, "2021-03-31": 2}, + {"interval": "month", "from": "2021-02-28", "number": 1}, + {"2021-04-30": 4}, + id="explicit-month-end", + ), + pytest.param( + {"2019-02-28": 1, "2020-02-29": 2}, + {"from": "2019-02-28", "number": 1}, + {"2021-02-28": 4}, + id="explicit-leap-day", + ), + pytest.param( + {"2020-01-01": 2, "2021-01-01": 0}, + {"number": 1}, + {"2022-01-01": 0}, + id="zero-ending-value", + ), + pytest.param( + {"2020-01-01": -1, "2022-01-01": -4, "2024-01-01": -5}, + {"from": "2020-01-01", "to": "2022-01-01", "number": 2}, + {"2025-01-01": -10, "2026-01-01": -20}, + id="historical-end-with-negative-values", + ), + pytest.param( + {"2020-01-01": 16, "2022-01-01": 4}, + { + "from": "2020-01-01", + "number": 2, + "rounding": {"type": "downwards", "interval": 2}, + }, + {"2023-01-01": 2, "2024-01-01": 0}, + id="decline-with-rounding", + ), + pytest.param( + {"2021-01-01": 1, "2022-01-01": 2}, + {"number": 1, "at_defined_interval": MONTHLY_SELF_CADENCE}, + {"2022-03-01": 2}, + id="cadence-count", + ), + pytest.param( + {"2021-01-01": 1, "2022-01-01": 2}, + {"number": 0, "at_defined_interval": MONTHLY_SELF_CADENCE}, + {}, + id="zero-cadence-count", + ), + pytest.param( + {"2021-12-31": 1, "2022-01-01": 2}, + { + "interval": "day", + "number": 2, + "at_defined_interval": { + "interval": "day", + "start": "2022-01-01", + "end": "2022-01-02", + "enactment": "2022-01-03", + "effective": "2022-01-03", + }, + }, + {"2022-01-03": 4, "2022-01-04": 8}, + id="daily-cadence", + ), + pytest.param( + {"2021-01-01": 2, "2022-01-01": 0}, + { + "number": 2, + "at_defined_interval": { + "interval": "year", + "start": "2022-01-01", + "end": "2023-01-01", + "enactment": "2023-02-01", + "effective": "2023-02-01", + }, + }, + {"2023-02-01": 0, "2024-02-01": 0}, + id="zero-ending-value-with-cadence", + ), + pytest.param( + {"2020-01-01": 1e-100, "2021-01-01": 1e100}, + {"number": 1}, + {"2022-01-01": pytest.approx(1e300)}, + id="large-scale-change", + ), + ], +) +def test_self_uprating_projection_values(values, options, expected): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": values, + "metadata": {"uprating": {"parameter": "self", **options}}, + }, + } + ) + + result = uprate_parameters(root).amount + actual = {entry.instant_str: entry.value for entry in result.values_list} + assert len(result.values_list) == len(values) + len(expected) + assert actual == {**values, **expected} + + +def test_self_uprating_rejects_zero_starting_value(): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2020-01-01": 0, "2021-01-01": 2}, + "metadata": {"uprating": {"parameter": "self", "number": 1}}, + }, + } + ) + + with pytest.raises( + ValueError, match="amount: starting value at 2020-01-01 is zero" + ): + uprate_parameters(root) + + def test_parameter_uprating_with_cadence(): from policyengine_core.parameters import ParameterNode From 390904404b26c5e7bb7f0ede71a0e8c51186740a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 17:22:09 +0000 Subject: [PATCH 4/6] Give annual self-uprating parity tests an independent reference Compound annual amounts in the reference so valid zero-ending inputs produce a zero projection instead of sharing a synthetic-index division error. Co-Authored-By: GPT-6.2 Sol --- tests/fixtures/chained_uprating_reference.py | 109 ++++++------------- 1 file changed, 36 insertions(+), 73 deletions(-) diff --git a/tests/fixtures/chained_uprating_reference.py b/tests/fixtures/chained_uprating_reference.py index cdd4b19e0..4e755c30a 100644 --- a/tests/fixtures/chained_uprating_reference.py +++ b/tests/fixtures/chained_uprating_reference.py @@ -1,23 +1,16 @@ -"""Chained-mode uprating as it was before base mode, for differential tests. - -Between this docstring and the alias at the end, this file is -``policyengine_core/parameters/operations/uprate_parameters.py`` at -PolicyEngine/policyengine-core@7c84d941b, the last commit before base mode, -copied verbatim (``git show 7c84d941b:``). It imports nothing from the -live uprating module, so a change to a live helper, such as chained mode's -rounding, shows up as a difference rather than reaching both sides. - -``test_base_uprating_property.py`` checks that ``uprate_parameters`` gives -every chained-mode parameter exactly what ``reference_uprate_parameters`` -gives it, and pins a few chained outputs as literals. A change that means to -alter chained mode should update this copy with the reason. -Self uprating compounds growth per interval to preserve the observed rate -and counts only future values toward ``number`` so each requested projection -is added. +"""Reference chained uprating for differential tests. + +External-index uprating comes from PolicyEngine/policyengine-core@7c84d941b, +the last commit before base mode. The annual self-uprating cases use the last +value and the prior year's value to compound each projection. The reference +imports no production uprating functions. """ # ruff: noqa +from itertools import accumulate, repeat +from operator import mul + from numpy import ceil, floor # rrule is purposely imported this way to allow for programmatic @@ -289,20 +282,15 @@ def uprate_parameter( # Pull the uprating definition dict meta = normalize_uprating_metadata(parameter.metadata["uprating"]) - # If param is "self", construct the uprating table if meta["parameter"] == "self": - uprating_parameter = construct_uprater_self( - parameter, - meta, - ) - # Otherwise, pull uprating table from YAML - else: - uprating_parameter = get_uprating_parameter( - root, - parameter, - meta["parameter"], - parameter_paths, - ) + project_annual_self(parameter, meta) + return + uprating_parameter = get_uprating_parameter( + root, + parameter, + meta["parameter"], + parameter_paths, + ) # If uprating with a set candence, ensure that all # required values are present @@ -680,50 +668,25 @@ def construct_cadence_options(cadence_settings: dict, parameter: Parameter) -> d return cadence_options -def construct_uprater_self(parameter: Parameter, meta: dict) -> Parameter: - interval = meta.get("interval", "year") - last_instant = instant(parameter.values_list[0].instant_str) - end_instant = instant(meta.get("to", last_instant)) - start_instant = ( - instant(meta["from"]) if "from" in meta else last_instant.offset(-1, interval) - ) - - # The default start is one interval back, including month-end clipping. - periods = 1 - if "from" in meta or end_instant != last_instant: - if end_instant <= start_instant: - raise ValueError( - f"Failed to self-uprate {parameter.name}: to must be after from" - ) - if interval == "day": - periods = (end_instant.date - start_instant.date).days - else: - periods = end_instant.year - start_instant.year - if interval == "month": - periods = 12 * periods + end_instant.month - start_instant.month - if start_instant.offset(periods, interval) != end_instant: - raise ValueError( - f"Failed to self-uprate {parameter.name}: from {start_instant} " - f"to {end_instant} must span whole {interval} intervals" - ) - - increase = parameter(end_instant) / parameter(start_instant) - if periods > 1: - if increase < 0: - raise ValueError( - f"Failed to self-uprate {parameter.name}: negative growth factor " - f"over {periods} {interval} intervals" - ) - increase **= 1 / periods - - data = {} - value = parameter.values_list[0].value - # The chained calculation needs an anchor at the last explicit instant. - for i in range(meta.get("number", 10) + 1): - value *= increase - data[str(last_instant.offset(i, interval))] = value - return Parameter("self", data=data) +def project_annual_self(parameter: Parameter, meta: dict) -> None: + if meta.keys() - {"parameter", "number"}: + raise AssertionError("The self-uprating reference covers default annual growth") + latest = instant(parameter.values_list[0].instant_str) + prior = latest.offset(-1, "year") + start = parameter(prior) + if start == 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: starting value at {prior} is zero" + ) + current = parameter(latest) + factor = current / start + projected = accumulate(repeat(factor, meta.get("number", 10)), mul, initial=current) + next(projected) + for offset, value in enumerate(projected, 1): + date = str(latest.offset(offset, "year")) + parameter.values_list.insert( + 0, ParameterAtInstant(parameter.name, date, data=value) + ) -#: The frozen ``uprate_parameters``, under the name the tests import. reference_uprate_parameters = uprate_parameters From 5e11e100ee3b7ee75de18672e876e4119254db39 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 17:22:09 +0000 Subject: [PATCH 5/6] Clarify changelog links and chained reference scope Co-Authored-By: GPT-6.2 Sol --- docs/contributing/intro.md | 4 ++-- .../operations/test_base_uprating_property.py | 10 ++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/docs/contributing/intro.md b/docs/contributing/intro.md index c88d281d3..4fddf5172 100644 --- a/docs/contributing/intro.md +++ b/docs/contributing/intro.md @@ -10,8 +10,8 @@ If you file an issue or a pull request, one of the maintainers (primarily [@nikh ## Changelog Entries Before opening a pull request, add a one-sentence Markdown fragment to -[`changelog.d/`](./changelog.d/), such as `fix-windows-tests.fixed.md`. -Use a type listed in the [changelog fragment guide](./docs/engineering/skills/github-prs.md#changelog-fragment). +[`changelog.d/`](https://github.com/PolicyEngine/policyengine-core/tree/master/changelog.d), such as `fix-windows-tests.fixed.md`. +Use a type listed in the [changelog fragment guide](https://github.com/PolicyEngine/policyengine-core/blob/master/docs/engineering/skills/github-prs.md#changelog-fragment). The release workflow builds the changelog from these fragments after merge. ## Pull requests diff --git a/tests/core/parameters/operations/test_base_uprating_property.py b/tests/core/parameters/operations/test_base_uprating_property.py index b41f0a51e..c86f73925 100644 --- a/tests/core/parameters/operations/test_base_uprating_property.py +++ b/tests/core/parameters/operations/test_base_uprating_property.py @@ -24,12 +24,10 @@ only after the last of them, at the index's periods. 6. The values base mode adds depend on the explicit values only through the base amount and the last explicit instant. -7. Every chained-mode parameter gets exactly the values, or the error, that - the implementation before base mode gives it - (``tests/fixtures/chained_uprating_reference.py``, a frozen copy of the - module at 7c84d941b), including at rounding boundaries, where a change to - the arithmetic before rounding shows. Three such boundaries are also - pinned as literals. +7. Chained-mode values and errors match the reference in + ``tests/fixtures/chained_uprating_reference.py``. It uses the original + chained logic for external indexes and compounds default annual self + growth separately. Rounding boundaries also have literal expectations. 8. ``base.floor: true`` changes nothing where the index is at or above its base-period level, to the last bit, and gives exactly the base where the index is below it, so a positive base never projects below itself. From 387585cef92ec4cb9fac74b7cef3407c24c410cc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 06:20:08 +0000 Subject: [PATCH 6/6] Handle extreme and signed self-uprating growth Co-Authored-By: GPT-6.2 Sol --- changelog.d/uprate-self-growth.fixed.md | 2 +- docs/usage/parameters.md | 8 +- .../operations/uprate_parameters.py | 42 +++++++--- .../parameters/operations/test_uprating.py | 83 +++++++++++++++++++ 4 files changed, 122 insertions(+), 13 deletions(-) diff --git a/changelog.d/uprate-self-growth.fixed.md b/changelog.d/uprate-self-growth.fixed.md index 3442c8ec7..6c5a60637 100644 --- a/changelog.d/uprate-self-growth.fixed.md +++ b/changelog.d/uprate-self-growth.fixed.md @@ -1 +1 @@ -Self uprating compounds growth per whole calendar interval, handles zero and large projections, and adds the requested number of future values on regular and cadence schedules. +Self uprating compounds growth per whole calendar interval, handles growth to zero, extreme ratios and sign changes over odd spans, and adds the requested number of future values on regular and cadence schedules. diff --git a/docs/usage/parameters.md b/docs/usage/parameters.md index 0d49b52c3..efffa9ff4 100644 --- a/docs/usage/parameters.md +++ b/docs/usage/parameters.md @@ -92,7 +92,13 @@ metadata: Self uprating compounds the growth from `from` to `to` at a constant rate per `interval` (`year` by default, or `month` or `day`). The dates default to one interval before the last explicit value and the date of that value, respectively. The span must be positive and cover whole intervals. A calendar offset from either endpoint may clip to the last valid day of the target month. For example, February 28 to March 31 can be one month, and February 28 to February 29 of the following year can be one year. -The value at `from` must be nonzero. Growth to zero is valid. `number` sets how many future values to add after the last explicit value, including when `at_defined_interval` sets the projection dates. It defaults to ten and accepts zero. +The value at `from` must be nonzero. Growth to zero is valid. When the values at `from` and `to` have opposite signs, the span must have an odd number of intervals for the growth multiplier to be real. Each growth step then uses a negative multiplier. + +`number` sets how many future values to add after the last explicit value, including when `at_defined_interval` sets the projection dates. It must be a non-negative integer and defaults to ten. + +With `at_defined_interval`, each self-uprating measurement window must start on or after the last explicit date. For example, if January 2022 is the last explicit date, the February 2022 enactment cannot use a January 2021 to January 2022 window, even if both January values exist. + +Self uprating calculates and applies growth in floating point. A projection can land just below or above a mathematical rounding boundary. For example, growth from 1 to 1,000 over three annual intervals gives a multiplier just below 10. With `downwards` rounding to a multiple of 1, the next value is 9,999. ### Base mode diff --git a/policyengine_core/parameters/operations/uprate_parameters.py b/policyengine_core/parameters/operations/uprate_parameters.py index ed8ec3ac1..d7a978895 100644 --- a/policyengine_core/parameters/operations/uprate_parameters.py +++ b/policyengine_core/parameters/operations/uprate_parameters.py @@ -324,6 +324,7 @@ def uprate_parameter( index's change since that value's instant and rounds the uprated amount. Self uprating applies the parameter's own per-interval growth to the last explicit value and adds ``number`` future values, including on a cadence. + Self-uprating cadence windows must start on or after the last explicit date. Base mode, chosen by an ``uprating.base`` block, computes each projected value from a fixed base amount and rounds the increase over it; see :func:`uprate_parameter_from_base`. @@ -350,7 +351,7 @@ def uprate_parameter( if meta["parameter"] == "self": self_growth = get_self_uprating_growth(parameter, meta) number = meta.get("number", 10) - if not isinstance(number, int) or number < 0: + if isinstance(number, bool) or not isinstance(number, int) or number < 0: raise ValueError( f"Failed to self-uprate {parameter.name}: number must be a non-negative integer" ) @@ -1150,7 +1151,10 @@ def self_uprating_step(anchor: Instant, date: Instant, interval: str) -> int: def get_self_uprating_growth(parameter: Parameter, meta: dict) -> float: - """Measure growth across whole intervals, allowing calendar clipping.""" + """Measure floating-point growth across whole intervals with calendar clipping. + + Opposite signs require an odd interval count for a real growth factor. + """ interval = meta.get("interval", "year") last_instant = instant(parameter.values_list[0].instant_str) end_instant = instant(meta.get("to", last_instant)) @@ -1178,16 +1182,32 @@ def get_self_uprating_growth(parameter: Parameter, meta: dict) -> float: raise ValueError( f"Failed to self-uprate {parameter.name}: starting value at {start_instant} is zero" ) - increase = parameter(end_instant) / start - if periods > 1: - if increase < 0: - raise ValueError( - f"Failed to self-uprate {parameter.name}: negative growth factor " - f"over {periods} {interval} intervals" - ) - increase **= 1 / periods + end = parameter(end_instant) + if periods == 1 or end == 0: + return end / start + + negative = (start < 0) != (end < 0) + if negative and periods % 2 == 0: + raise ValueError( + f"Failed to self-uprate {parameter.name}: negative growth factor " + f"over {periods} {interval} intervals" + ) - return increase + start_magnitude = abs(start) + end_magnitude = abs(end) + root = 1 / periods + # Take roots first if the ratio could overflow or lose precision below the + # smallest normal float. + if ( + start_magnitude <= sys.float_info.max + and end_magnitude <= start_magnitude * sys.float_info.min + ) or ( + start_magnitude < 1 and end_magnitude >= start_magnitude * sys.float_info.max + ): + growth = end_magnitude**root / start_magnitude**root + else: + growth = (end_magnitude / start_magnitude) ** root + return -growth if negative else growth def uprate_parameter_from_self( diff --git a/tests/core/parameters/operations/test_uprating.py b/tests/core/parameters/operations/test_uprating.py index 235de2a24..7ad5fd95c 100644 --- a/tests/core/parameters/operations/test_uprating.py +++ b/tests/core/parameters/operations/test_uprating.py @@ -532,6 +532,23 @@ def test_self_uprating_counts_future_values(interval, start, end, options, expec } +@pytest.mark.parametrize("number", [True, False]) +def test_self_uprating_rejects_boolean_counts(number): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2020-01-01": 1, "2021-01-01": 2}, + "metadata": {"uprating": {"parameter": "self", "number": number}}, + }, + } + ) + + with pytest.raises(ValueError, match="number must be a non-negative integer"): + uprate_parameters(root) + + @pytest.mark.parametrize( "interval, start, end, end_value, error", [ @@ -663,6 +680,46 @@ def test_self_uprating_rejects_invalid_growth_spans( {"2022-01-01": pytest.approx(1e300)}, id="large-scale-change", ), + pytest.param( + {"2020-01-01": 1e-200, "2030-01-01": 1e200}, + {"from": "2020-01-01", "number": 1}, + {"2031-01-01": pytest.approx(1e240, rel=1e-12, abs=0)}, + id="overflow-before-root", + ), + pytest.param( + {"2020-01-01": 1e200, "2030-01-01": 1e-200}, + {"from": "2020-01-01", "number": 1}, + {"2031-01-01": pytest.approx(1e-240, rel=1e-12, abs=0)}, + id="underflow-before-root", + ), + pytest.param( + {"2020-01-01": 1, "2023-01-01": -8}, + {"from": "2020-01-01", "number": 1}, + {"2024-01-01": 16}, + id="odd-span-sign-change", + ), + pytest.param( + {"2020-01-01": 1, "2021-01-01": -2}, + {"number": 2}, + {"2022-01-01": 4, "2023-01-01": -8}, + id="single-interval-sign-change", + ), + pytest.param( + {"2020-01-01": 1, "2023-01-01": 1000}, + { + "from": "2020-01-01", + "number": 1, + "rounding": {"type": "downwards", "interval": 1}, + }, + {"2024-01-01": 9999}, + id="downward-rounding-at-float-boundary", + ), + pytest.param( + {"2020-01-01": 1, "2021-01-01": 2}, + {"start_instant": "2023-06-01", "number": 2}, + {"2024-01-01": 4, "2025-01-01": 8}, + id="later-start", + ), ], ) def test_self_uprating_projection_values(values, options, expected): @@ -683,6 +740,32 @@ def test_self_uprating_projection_values(values, options, expected): assert actual == {**values, **expected} +def test_self_uprating_rejects_cadence_window_before_last_value(): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2020-01-01": 1, "2021-01-01": 2, "2022-01-01": 4}, + "metadata": { + "uprating": { + "parameter": "self", + "number": 1, + "at_defined_interval": { + "start": "2021-01-01", + "end": "2022-01-01", + "enactment": "2022-02-01", + }, + }, + }, + }, + } + ) + + with pytest.raises(ValueError, match="uprater missing values at date 2021-01-01"): + uprate_parameters(root) + + def test_self_uprating_rejects_zero_starting_value(): from policyengine_core.parameters import ParameterNode, uprate_parameters