Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/uprate-self-growth.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
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.
15 changes: 4 additions & 11 deletions docs/contributing/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`](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

Expand Down
10 changes: 10 additions & 0 deletions docs/usage/parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,16 @@ 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 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. 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

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:
Expand Down
216 changes: 159 additions & 57 deletions policyengine_core/parameters/operations/uprate_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,9 @@ 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.
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`.
Expand All @@ -342,12 +345,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 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"
)
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(
Expand All @@ -356,10 +368,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 = [
Expand All @@ -380,20 +392,22 @@ 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 -
# this should be the first application date (month, day)
# 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
Expand All @@ -404,6 +418,8 @@ def uprate_parameter(
uprating_first_date,
uprating_last_date,
meta,
self_growth=self_growth,
number=number,
)

# Append uprated data to parameter values list
Expand Down Expand Up @@ -986,24 +1002,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
Expand All @@ -1015,32 +1038,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)

Expand Down Expand Up @@ -1106,26 +1132,102 @@ 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 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)
start_instant = instant(
meta.get(
"from",
last_instant.offset(-1, meta.get("interval", "year")),
)
end_instant = instant(meta.get("to", last_instant))
start_instant = (
instant(meta["from"]) if "from" in meta else last_instant.offset(-1, interval)
)

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"
)

start = parameter(start_instant)
end_instant = instant(meta.get("to", last_instant))
if start == 0:
raise ValueError(
f"Failed to self-uprate {parameter.name}: starting value at {start_instant} is zero"
)
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)
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
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"
)

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(
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
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)
22 changes: 16 additions & 6 deletions tests/core/parameters/operations/test_base_uprating_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -804,6 +802,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",
[
Expand Down
Loading