From 2f91192421b8965ac79075cd4f08e7411977fb6b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 12:05:59 +0000 Subject: [PATCH 1/2] Fix leap-day cadence and fractional cadence rounding Co-Authored-By: GPT-6.2 Sol --- changelog.d/uprate-cadence-rounding.fixed.md | 1 + .../operations/uprate_parameters.py | 52 +++++---- .../parameters/operations/test_uprating.py | 107 ++++++++++++++++++ 3 files changed, 141 insertions(+), 19 deletions(-) create mode 100644 changelog.d/uprate-cadence-rounding.fixed.md diff --git a/changelog.d/uprate-cadence-rounding.fixed.md b/changelog.d/uprate-cadence-rounding.fixed.md new file mode 100644 index 000000000..35f531582 --- /dev/null +++ b/changelog.d/uprate-cadence-rounding.fixed.md @@ -0,0 +1 @@ +Fix leap-day cadence and fractional cadence rounding, and show valid rounding formats when an interval is written as a bare integer. diff --git a/policyengine_core/parameters/operations/uprate_parameters.py b/policyengine_core/parameters/operations/uprate_parameters.py index 0a1b10b7f..ca87c2991 100644 --- a/policyengine_core/parameters/operations/uprate_parameters.py +++ b/policyengine_core/parameters/operations/uprate_parameters.py @@ -4,7 +4,7 @@ import sys from fractions import Fraction -from numpy import ceil, floor +from numpy import ceil, float64, floor # rrule is purposely imported this way to allow for programmatic # calling of rrule.YEARLY, rrule.MONTHLY, and rrule.DAILY @@ -834,8 +834,29 @@ def round_uprated_value(meta: dict, uprated_value: float) -> float: upwards=ceil, downwards=floor, )[rounding_config["type"]] - uprated_value = rounding_fn(uprated_value / interval) * interval - return uprated_value + else: + # Keep the exception text for callers that inspect it. + error = UnboundLocalError( + "cannot access local variable 'rounding_fn' where it is not associated with a value" + ) + error.add_note("Write the rounding interval as a float or a mapping.") + raise error + + if ( + meta.get("at_defined_interval") + and isinstance(interval, float) + and interval != 0 + and math.isfinite(interval) + and math.isfinite(uprated_value) + ): + step = exact_decimal(interval) + intervals = exact_decimal(uprated_value) / step + round_intervals = {ceil: math.ceil, floor: math.floor}.get(rounding_fn, round) + whole_intervals = round_intervals(intervals) + result_type = type(interval) if rounding_fn is round else float64 + return result_type(whole_intervals * step) + + return rounding_fn(uprated_value / interval) * interval def find_cadence_first(parameter: Parameter, cadence_options: dict) -> datetime: @@ -934,22 +955,18 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime: # Pull of the first (newest) value and parse into datetime object last_param: datetime = parse(uprater_values[0].instant_str) - # Create an offset to allow us to search for one year, from one year - # minus 1 day before the last uprater param, to the last uprater param; - # this must be 1 year, minus 1 day, because rrule is inclusive of its - # start date. This must also be done as 1 year, then 1 day, because - # leap years are not handled differently when specifying a day-based offset, - # resulting in 25% of offsets being one day short if calculated - # using days only; further, this must be done with relativedelta and not - # datetime's timedelta, which doesn't handle year-based offsets - start_date: datetime = last_param - relativedelta(years=1) + relativedelta(days=1) - # Conditionally determine settings to utilize # Set the month only if the interval is "year" month_option = cadence_options["end"].month if interval == "year" else None # Set the day if interval is "year" or "month", just not "day" day_option = cadence_options["end"].day if interval != "day" else None + if (month_option, day_option) == (2, 29): + # Leap days can be eight years apart at a century boundary. + start_date = datetime(max(1, last_param.year - 8), 1, 1) + else: + start_date = last_param - relativedelta(years=1) + relativedelta(days=1) + rrule_obj = rrule.rrule( freq=rrule.YEARLY, dtstart=start_date, @@ -958,18 +975,15 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime: bymonthday=day_option, ) - # rrule can't look backward, so we generated an entire array of options - # for a year; for monthly and daily intervals, we'll need the last item - # in this array - last_end: datetime = rrule_obj[-1] + last_end = rrule_obj.before(last_param, inc=True) # Ensure that data exists for the "start" parameter for this "end," # otherwise raise error end_start_diff: relativedelta = relativedelta( cadence_options["end"], cadence_options["start"] ) - last_start = last_end - end_start_diff - if (uprater(instant(last_start.date()))) is None: + last_start = last_end - end_start_diff if last_end is not None else None + if last_start is None or uprater(instant(last_start.date())) is None: raise ValueError( f"Error while uprating using {uprater.name}: no valid start, end pair found; did " + "you forget to add earlier values, or is there a long gap between start and end year?" diff --git a/tests/core/parameters/operations/test_uprating.py b/tests/core/parameters/operations/test_uprating.py index 74aee22ef..fdd62feb1 100644 --- a/tests/core/parameters/operations/test_uprating.py +++ b/tests/core/parameters/operations/test_uprating.py @@ -1020,3 +1020,110 @@ def test_parameter_uprating_cadence_minimal_data(): uprated = uprate_parameters(root) assert round(uprated.to_be_uprated("2023-04-01"), 3) == 1.101 + + +@pytest.mark.parametrize( + "year, later_observation", + [("2004", None), ("2004", "2005-03-01"), ("2096", "2104-02-28")], +) +def test_cadence_uses_latest_leap_day(year, later_observation): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + index = {f"{year}-01-01": 100, f"{year}-02-29": 102} + if later_observation: + index[later_observation] = 103 + root = ParameterNode( + data={ + "amount": { + "values": {f"{year}-02-29": 1}, + "metadata": { + "uprating": { + "parameter": "index", + "at_defined_interval": { + "start": f"{year}-01-01", + "end": f"{year}-02-29", + "enactment": f"{year}-03-01", + }, + }, + }, + }, + "index": {"values": index}, + } + ) + + amount = uprate_parameters(root).amount + + assert [(entry.instant_str, entry.value) for entry in amount.values_list] == [ + (f"{year}-03-01", 1.02), + (f"{year}-02-29", 1), + ] + + +@pytest.mark.parametrize( + "amount, rounding_type, expected", + [ + pytest.param(0.29, "downwards", 0.29, id="aligned-downwards"), + pytest.param(0.7, "downwards", 0.7, id="downwards-bound"), + pytest.param(0.030000000000000002, "upwards", 0.04, id="upwards-bound"), + pytest.param(0.695, "nearest", 0.7, id="nearest-product"), + pytest.param(0.125, "nearest", 0.12, id="half-to-even"), + ], +) +def test_flat_index_cadence_rounds_to_exact_cents(amount, rounding_type, expected): + from numpy import float64 + + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2026-07-01": amount}, + "metadata": { + "uprating": { + "parameter": "index", + "rounding": {"interval": 0.01, "type": rounding_type}, + "at_defined_interval": { + "start": "2026-05-01", + "end": "2027-05-01", + "enactment": "2027-07-01", + }, + }, + }, + }, + "index": {"values": {"2026-05-01": 100, "2027-05-01": 100}}, + } + ) + + projected = uprate_parameters(root).amount("2027-07-01") + assert projected == expected + assert type(projected) is (float if rounding_type == "nearest" else float64) + + +@pytest.mark.parametrize( + "rounding", + [ + pytest.param(50, id="bare-int"), + pytest.param(50.0, id="bare-float"), + pytest.param({"interval": 50, "type": "nearest"}, id="mapped-int"), + ], +) +def test_chained_rounding_interval_forms(rounding): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2026-01-01": 50}, + "metadata": { + "uprating": {"parameter": "index", "rounding": rounding}, + }, + }, + "index": {"values": {"2026-01-01": 2, "2027-01-01": 5}}, + } + ) + + if isinstance(rounding, int): + with pytest.raises(UnboundLocalError, match="rounding.*float or a mapping"): + uprate_parameters(root) + else: + assert uprate_parameters(root).amount("2027-01-01") == 100 From 25a14b8490ca809bda08b7dd7210717aaa0fde5c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 04:25:45 +0000 Subject: [PATCH 2/2] Fix cadence index rounding and month-end lookups Co-Authored-By: GPT-6.2 Sol --- changelog.d/uprate-cadence-rounding.fixed.md | 2 +- .../operations/uprate_parameters.py | 78 +++++++++++-------- .../parameters/operations/test_uprating.py | 78 +++++++++++++++++++ 3 files changed, 123 insertions(+), 35 deletions(-) diff --git a/changelog.d/uprate-cadence-rounding.fixed.md b/changelog.d/uprate-cadence-rounding.fixed.md index 35f531582..0deee793f 100644 --- a/changelog.d/uprate-cadence-rounding.fixed.md +++ b/changelog.d/uprate-cadence-rounding.fixed.md @@ -1 +1 @@ -Fix leap-day cadence and fractional cadence rounding, and show valid rounding formats when an interval is written as a bare integer. +Find the latest leap day for annual uprating and use the configured month-end dates. Use exact decimal arithmetic to apply index growth and round cadence amounts to fractional intervals. Show valid rounding formats when an interval is written as a bare integer. diff --git a/policyengine_core/parameters/operations/uprate_parameters.py b/policyengine_core/parameters/operations/uprate_parameters.py index ca87c2991..ab3a76eac 100644 --- a/policyengine_core/parameters/operations/uprate_parameters.py +++ b/policyengine_core/parameters/operations/uprate_parameters.py @@ -822,7 +822,12 @@ def project_from_base( return float(base + whole_intervals * step) -def round_uprated_value(meta: dict, uprated_value: float) -> float: +def round_uprated_value( + meta: dict, + amount: float, + *, + index_values: Optional[tuple[float, float]] = None, +) -> float: rounding_config = meta["rounding"] if isinstance(rounding_config, float): interval = rounding_config @@ -842,21 +847,29 @@ def round_uprated_value(meta: dict, uprated_value: float) -> float: error.add_note("Write the rounding interval as a float or a mapping.") raise error - if ( - meta.get("at_defined_interval") - and isinstance(interval, float) - and interval != 0 - and math.isfinite(interval) - and math.isfinite(uprated_value) - ): - step = exact_decimal(interval) - intervals = exact_decimal(uprated_value) / step - round_intervals = {ceil: math.ceil, floor: math.floor}.get(rounding_fn, round) - whole_intervals = round_intervals(intervals) - result_type = type(interval) if rounding_fn is round else float64 - return result_type(whole_intervals * step) + if index_values is not None: + index_start, index_end = index_values + if ( + isinstance(interval, float) + and interval != 0 + and math.isfinite(interval) + and all( + isinstance(value, numbers.Integral) or math.isfinite(value) + for value in (amount, index_start, index_end) + ) + ): + step = exact_decimal(interval) + ratio = exact_decimal(index_end) / exact_decimal(index_start) + intervals = exact_decimal(amount) * ratio / step + round_intervals = {ceil: math.ceil, floor: math.floor}.get( + rounding_fn, round + ) + whole_intervals = round_intervals(intervals) + result_type = type(interval) if rounding_fn is round else float64 + return result_type(whole_intervals * step) + amount = (index_end / index_start) * amount - return rounding_fn(uprated_value / interval) * interval + return rounding_fn(amount / interval) * interval def find_cadence_first(parameter: Parameter, cadence_options: dict) -> datetime: @@ -977,12 +990,10 @@ def find_cadence_last(uprater: Parameter, cadence_options: dict) -> datetime: last_end = rrule_obj.before(last_param, inc=True) - # Ensure that data exists for the "start" parameter for this "end," - # otherwise raise error - end_start_diff: relativedelta = relativedelta( - cadence_options["end"], cadence_options["start"] - ) - last_start = last_end - end_start_diff if last_end is not None else None + # Check the index at the corresponding start. A forward offset can clip + # the day at month-end, so compute the offset in the lookup direction. + end_to_start = relativedelta(cadence_options["start"], cadence_options["end"]) + last_start = last_end + end_to_start if last_end is not None else None if last_start is None or uprater(instant(last_start.date())) is None: raise ValueError( f"Error while uprating using {uprater.name}: no valid start, end pair found; did " @@ -1019,14 +1030,13 @@ def uprate_by_cadence( # Generate a list of iterations iterations = rrule.rrule(freq=rrule_interval, dtstart=first_date, until=last_date) - # Determine the offset between the first enactment - # date and the first start and end date + # Use offsets from enactment to the index dates to account for month ends. uprated_data: list[ParameterAtInstant] = [] - enactment_start_offset: relativedelta = relativedelta( - cadence_options["enactment"], cadence_options["start"] + enactment_to_start = relativedelta( + cadence_options["start"], cadence_options["enactment"] ) - enactment_end_offset: relativedelta = relativedelta( - cadence_options["enactment"], cadence_options["end"] + enactment_to_end = relativedelta( + cadence_options["end"], cadence_options["enactment"] ) # Set a starting reference value to calculate against @@ -1035,8 +1045,8 @@ def uprate_by_cadence( # 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 + start_calc_date: datetime = enactment_date + enactment_to_start + end_calc_date: datetime = enactment_date + enactment_to_end # Find uprater value at cadence start start_val = uprating_parameter.get_at_instant(instant(start_calc_date.date())) @@ -1050,13 +1060,13 @@ def uprate_by_cadence( f"Failed to uprate {parameter.name} using {uprating_parameter.name}: uprater missing values at date {start_calc_date.date()}" ) - # Find difference of these values - difference = end_val / start_val - # Uprate value - uprated_value = difference * reference_value if "rounding" in meta: - uprated_value = round_uprated_value(meta, uprated_value) + uprated_value = round_uprated_value( + meta, reference_value, index_values=(start_val, end_val) + ) + else: + uprated_value = (end_val / start_val) * reference_value # Add uprated value to data list uprated_data.append( diff --git a/tests/core/parameters/operations/test_uprating.py b/tests/core/parameters/operations/test_uprating.py index fdd62feb1..04387b297 100644 --- a/tests/core/parameters/operations/test_uprating.py +++ b/tests/core/parameters/operations/test_uprating.py @@ -1059,6 +1059,47 @@ def test_cadence_uses_latest_leap_day(year, later_observation): ] +@pytest.mark.parametrize( + "start, enactment, earlier_index", + [ + pytest.param( + "2004-01-31", "2004-03-01", {"2004-01-31": 100}, id="january-31-start" + ), + pytest.param( + "2004-01-01", + "2004-03-31", + {"2004-01-01": 100, "2004-02-27": 101}, + id="march-31-enactment", + ), + ], +) +def test_leap_day_cadence_uses_month_end_dates(start, enactment, earlier_index): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2004-02-29": 1}, + "metadata": { + "uprating": { + "parameter": "index", + "at_defined_interval": { + "start": start, + "end": "2004-02-29", + "enactment": enactment, + }, + }, + }, + }, + "index": { + "values": {**earlier_index, "2004-02-29": 102, "2005-03-01": 103} + }, + } + ) + + assert uprate_parameters(root).amount(enactment) == 1.02 + + @pytest.mark.parametrize( "amount, rounding_type, expected", [ @@ -1099,6 +1140,43 @@ def test_flat_index_cadence_rounds_to_exact_cents(amount, rounding_type, expecte assert type(projected) is (float if rounding_type == "nearest" else float64) +@pytest.mark.parametrize( + "amount, index_end, rounding_type, expected", + [ + pytest.param(0.07, 300, "upwards", 0.21, id="upwards-exact-cent"), + pytest.param(0.07, 150, "nearest", 0.10, id="nearest-half-to-even"), + pytest.param(-0.07, 300, "downwards", -0.21, id="downwards-negative-cent"), + pytest.param(0.29, 300, "downwards", 0.87, id="downwards-exact-cent"), + ], +) +def test_cadence_rounds_exact_index_projection( + amount, index_end, rounding_type, expected +): + from policyengine_core.parameters import ParameterNode, uprate_parameters + + root = ParameterNode( + data={ + "amount": { + "values": {"2026-07-01": amount}, + "metadata": { + "uprating": { + "parameter": "index", + "rounding": {"interval": 0.01, "type": rounding_type}, + "at_defined_interval": { + "start": "2026-05-01", + "end": "2027-05-01", + "enactment": "2027-07-01", + }, + }, + }, + }, + "index": {"values": {"2026-05-01": 100, "2027-05-01": index_end}}, + } + ) + + assert uprate_parameters(root).amount("2027-07-01") == expected + + @pytest.mark.parametrize( "rounding", [