diff --git a/changelog.d/preserve-marital-unit-inputs.fixed.md b/changelog.d/preserve-marital-unit-inputs.fixed.md new file mode 100644 index 00000000000..1391a100dfc --- /dev/null +++ b/changelog.d/preserve-marital-unit-inputs.fixed.md @@ -0,0 +1 @@ +Build omitted household marital units from explicit couples, supplied tax roles, a married family or joint and separate filing statuses, and otherwise pair the head and spouse the tax-role fallback infers, instead of putting everyone in one marital unit. diff --git a/docs/usage/microsimulation.md b/docs/usage/microsimulation.md index d31439b825f..558b0d467f8 100644 --- a/docs/usage/microsimulation.md +++ b/docs/usage/microsimulation.md @@ -2,6 +2,109 @@ The `Microsimulation` class is the primary tool for population-level policy analysis in PolicyEngine US. It combines representative survey microdata with PolicyEngine's tax-benefit model to estimate how policies affect the entire US population. +## Marital membership and tax roles + +Dataset `person_marital_unit_id` and `marital_unit_id` columns define marital +membership. Loading the dataset and extending its years preserve those IDs. +Microcosm builds these units from the survey's spouse pointers, and +policyengine-us never rebuilds a dataset's units. + +A household situation's `marital_units` mapping also stands as supplied. An +empty mapping gives each person their own unit. A married couple may share a +marital unit while belonging to separate tax units. + +When an entity-form situation omits `marital_units`, the model pairs at most +one couple in each tax unit and household, from the first of these that +applies, and gives everyone else their own unit: + +1. an unambiguous pair of true `is_tax_unit_head` and `is_tax_unit_spouse` + inputs for overlapping periods, neither input as a dependent or separated; +2. the head and spouse of a `tax_unit_role_input` supplied for every member; +3. the two adults of a family whose `is_married` input is true, when exactly + two of its adults in the tax unit and household are neither input as + dependents nor separated; +4. otherwise, the head and spouse that `is_tax_unit_head` and + `is_tax_unit_spouse` infer from age order: the oldest adult, and the + next-oldest adult who fails the qualifying child age test against them + (under 19, or under 24 if a full-time student, and younger than the head, + or permanently and totally disabled). No couple is formed when the head or + that spouse is separated (another member's separation doesn't matter), when + the two live in different households, when + a family they share has a false `is_married` input, or when either has a + false `is_tax_unit_head` or `is_tax_unit_spouse` input for the role this + step gives them. A tax unit whose `filing_status` input is `JOINT` skips + the age test, because only a married couple files jointly + ([26 USC 6013(a)](https://www.law.cornell.edu/uscode/text/26/6013#a)). + +Only married people file separately +([26 USC 1(d)](https://www.law.cornell.edu/uscode/text/26/1#d)), so when a +household holds exactly two tax units whose `filing_status` input is +`SEPARATE`, their two filers are then paired, unless either is separated, a +family they share has a false `is_married` input, or either is already in a +couple from the steps above. A unit's filer is its one true `is_tax_unit_head` +input, or else its only adult who isn't input as a dependent; a `SEPARATE` unit +with no such filer still counts toward the two, so it blocks the pairing. A +marital unit is a married, co-habiting couple, so separate filers in different +households stay apart. A `filing_status` input that changes between periods +counts as no status. + +The fourth step reads the same inputs and parameters as the role formulas, so +the units it builds agree with the inferred tax roles in the years the inputs +are dated for: a couple sent without marriage information is a couple for SSI +and Medicaid as well as for tax, and +a parent's adult child who meets the age test is neither. When anyone in a +situation supplies a role, student or age input for a year, Core gives everyone +else that variable's default for the year instead of running its formula, and +the fourth step reads the same defaults. The fourth step checks the years the +inputs are dated for, so a payload dated for a year other +than the simulation's default input year pairs the same couple. Under a reform, +it uses the reform's dependent age limits. + +Membership can't change between periods. Inputs that can't settle one static +couple give everyone in that tax unit and household their own unit: two head +or two spouse inputs, a dependent also marked head or spouse in a unit with +both a head and a spouse input, role or `is_married` inputs that change between +periods, or a fourth-step couple that differs between years. With only a spouse +input, on a person also input as a dependent, the fourth step pairs that person +with the oldest other adult, and the role formulas give the same couple. + +Known limitations, which callers avoid by supplying `marital_units`: + +- Like the role fallback, the fourth step pairs an adult who fails the age test + with the head, such as a parent and their adult child or two unrelated adults + in one tax unit. +- A tax unit with two couples pairs only the couple the role formulas pick; + the other two adults get their own units. +- Spouses in two tax units are paired only as the two separate filers of one + household. A family's true `is_married` input doesn't pair them, and neither + do separate returns when the household holds more than two. +- The separate-filer pairing reads no age or relationship, so a parent and an + adult child who each file separately from an absent spouse, beside a third + tax unit, become a couple. +- A `filing_status` input dated for more than one year counts only when it is + the same in every year, so a status that is `JOINT` in the calculation year + and different in another year reads as no status. +- `JOINT` and `SEPARATE` inputs say who is married, but `SINGLE`, + `HEAD_OF_HOUSEHOLD` and `SURVIVING_SPOUSE` inputs don't say who isn't: two + adults in one tax unit with any of them can still be paired by the fourth + step, as on main. +- A lone true `is_tax_unit_spouse` input on the oldest adult makes that person + both head and spouse in the role formulas, as on main; the fourth step pairs + them with the next adult. +- A lone true `is_tax_unit_spouse` input skips the fourth step's separation + check: the fourth step pairs that person with the oldest other adult even + when that adult is separated. +- Marital units follow the years the inputs are dated for, while the role + formulas run again in any year without a role input. So a calculation for + another year can give roles the units don't match. For example, a + grandchild's undated `is_tax_unit_spouse: false` lands in the default input + year (2024), so the grandparents get their own units, while a 2026 + calculation still makes them head and spouse. + +These rules apply to Python household simulations and entity-form YAML tests, +including tests with reforms or inline parameters. Variable-only tests keep +Core's own defaults. + ## Getting started ```python @@ -165,8 +268,9 @@ a dependent. PolicyEngine infers no spouse when the head or selected spouse candidate is separated. It selects the candidate before checking separation, without promoting a younger adult; member order breaks equal-age ties. A separated member doesn't count toward a couple. When a situation omits -marital units, Core puts everyone in one marital unit, so plain age order -applies. A minor living without a parent is left with no head. +marital units, the model builds them by these same rules (see "Marital +membership and tax roles" above), so they give the same roles. A minor living +without a parent is left with no head. This rule has three known limitations. Supply `is_tax_unit_head`, `is_tax_unit_spouse` or `tax_unit_role_input` for these households: diff --git a/policyengine_us/system.py b/policyengine_us/system.py index a004acfe9cb..eaef87ae6a4 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -38,6 +38,7 @@ uprate_parameters, ) from .tools.default_uprating import add_default_uprating +from .tools.marital_units import infer_missing_marital_units from .tools.tob import TobCalculationMixin from .tools.period_branch import delete_input_values from .tools.social_security_inputs import ( @@ -114,6 +115,9 @@ class CountryTaxBenefitSystem(TaxBenefitSystem): ] modelled_policies = COUNTRY_DIR / "programs.yaml" + def preprocess_situation(self, situation, default_period=None): + return infer_missing_marital_units(situation, default_period, self) + def __init__( self, reform: tuple | None = None, diff --git a/policyengine_us/tests/core/test_ar_medical_expense_deduction_properties.py b/policyengine_us/tests/core/test_ar_medical_expense_deduction_properties.py index b9bbcca55b2..7ba2f99c12a 100644 --- a/policyengine_us/tests/core/test_ar_medical_expense_deduction_properties.py +++ b/policyengine_us/tests/core/test_ar_medical_expense_deduction_properties.py @@ -175,9 +175,8 @@ def test_ar_medical_expense_deduction_is_monotone(year): @pytest.mark.parametrize("statuses", list(product(["SINGLE", "SEPARATE"], repeat=2))) @pytest.mark.parametrize("year", [2015, 2017]) def test_ar_medical_expense_floor_in_two_person_simulations(year, statuses): - # With exactly two people and no marital units, the default marital unit - # looks like a couple. Only two separate filers are read as spouses of - # each other (intended: married people filing separately must both file + # With no marital units, only two separate filers in one household are + # paired as a couple (married people filing separately must both file # separately); anyone else keeps the ages on their own return. period = str(year) ages = list(product(HEAD_AGES, HEAD_AGES)) @@ -191,8 +190,7 @@ def test_ar_medical_expense_floor_in_two_person_simulations(year, statuses): for i, (name, status) in enumerate(zip(people, statuses)) }, "households": { - f"h{i}": {"members": [name], "state_code": {period: "AR"}} - for i, name in enumerate(people) + "h": {"members": list(people), "state_code": {period: "AR"}} }, } floor = Simulation(situation=situation).calculate( diff --git a/policyengine_us/tests/core/test_tax_unit_role_inference.py b/policyengine_us/tests/core/test_tax_unit_role_inference.py index eb75efd9b99..847e0ffa013 100644 --- a/policyengine_us/tests/core/test_tax_unit_role_inference.py +++ b/policyengine_us/tests/core/test_tax_unit_role_inference.py @@ -1,11 +1,13 @@ """Invariants for inferring the tax unit head and spouse. ``is_tax_unit_head`` picks the oldest adult and ``is_tax_unit_spouse`` the -next oldest, skipping anyone input as a tax unit dependent unless every adult -in the unit is one. These tests enumerate every tax unit of up to three people -drawn from a small grid of ages and dependent inputs, and compare the model -against reference implementations of that rule and of the rule before -dependent inputs were honoured. +next oldest who fails the qualifying child age test against the head (26 USC +152(c)(3)), skipping anyone input as a tax unit dependent unless every adult +in the unit is one. The situations omit marital units, so +``tools/marital_units.py`` builds them by the same rules. These tests +enumerate every tax unit of up to three people drawn from a small grid of ages +and dependent inputs, and compare the model against reference implementations +of that rule and of the rule before dependent inputs were honoured. """ import itertools @@ -19,6 +21,10 @@ # Covers children, the age-18 adult boundary, and ties between adults. AGES = (10, 18, 40, 70) MAX_UNIT_SIZE = 3 +# A non-student under 19 and younger than the head meets the qualifying child +# age test (26 USC 152(c)(3)(A)(i)), so an 18-year-old is not the spouse of an +# older head. The grid has no students or disabled people. +QUALIFYING_CHILD_AGE_LIMIT = 19 def _all_units(flag_values): @@ -67,7 +73,15 @@ def _reference_roles(members, honour_dependent_input: bool): candidates = non_dependents ranked = sorted(candidates, key=lambda i: (-members[i][0], i)) head = ranked[0] if ranked else None - spouse = ranked[1] if len(ranked) > 1 else None + spouses = [ + i + for i in ranked[1:] + if not ( + members[i][0] < QUALIFYING_CHILD_AGE_LIMIT + and members[i][0] < members[head][0] + ) + ] + spouse = spouses[0] if spouses else None return head, spouse diff --git a/policyengine_us/tests/core/test_tax_unit_role_input_properties.py b/policyengine_us/tests/core/test_tax_unit_role_input_properties.py index 204d6585bca..ef3d652f488 100644 --- a/policyengine_us/tests/core/test_tax_unit_role_input_properties.py +++ b/policyengine_us/tests/core/test_tax_unit_role_input_properties.py @@ -9,10 +9,12 @@ 3. Fallback (marital units omitted): in a unit without supplied roles, the roles equal an independent implementation of age ordering. The oldest adult heads the unit, earliest member on ties, skipping adults input as tax unit - dependents unless every adult is one; the next such adult is the spouse - unless the head or that adult is separated. The generated situations pass - no marital units, so Core puts everyone in one marital unit and the - couple-first head and partner-first spouse rules reduce to age order. + dependents unless every adult is one; the next such adult who fails the + qualifying child age test against the head (26 USC 152(c)(3)) is the + spouse unless the head or that adult is separated. The generated + situations pass no marital units, so the model builds them by these same + rules and the couple-first head and partner-first spouse rules reduce to + age order. 4. Filing status is computed: no supplied status is read, so a unit files jointly exactly when it has a spouse, supplied or inferred. 5. Workaround equivalence (differential): supplying roles through @@ -120,6 +122,12 @@ def _situation(units, pin_explicitly=False): } +# A non-student under 19 and younger than the head meets the qualifying child +# age test (26 USC 152(c)(3)(A)(i)), so they are not the head's spouse. The +# generated units have no students or disabled people. +QUALIFYING_CHILD_AGE_LIMIT = 19 + + def _age_rule(ages, separated, dependent_input=None, head_input=None): """Independent age order for situations without marital-unit inputs.""" adults = [i for i, age in enumerate(ages) if age >= 18] @@ -130,7 +138,16 @@ def _age_rule(ages, separated, dependent_input=None, head_input=None): head = head_input if head is None: head = min(adults, key=lambda i: (-ages[i], i)) if adults else None - candidates = [i for i in adults if i != head] + candidates = [ + i + for i in adults + if i != head + and not ( + head is not None + and ages[i] < QUALIFYING_CHILD_AGE_LIMIT + and ages[i] < ages[head] + ) + ] spouse = min(candidates, key=lambda i: (-ages[i], i)) if candidates else None if spouse is not None and ( (head is not None and separated[head]) or separated[spouse] diff --git a/policyengine_us/tests/core/test_tax_unit_spouse_separation_invariants.py b/policyengine_us/tests/core/test_tax_unit_spouse_separation_invariants.py index 97d35062962..4fb65a06fcd 100644 --- a/policyengine_us/tests/core/test_tax_unit_spouse_separation_invariants.py +++ b/policyengine_us/tests/core/test_tax_unit_spouse_separation_invariants.py @@ -3,9 +3,11 @@ Separation under 26 U.S.C. 7703 concerns the filer's own marriage, so only the head's or the would-be spouse's `is_separated` can leave a tax unit without a spouse. The would-be spouse is the oldest head-or-spouse candidate -other than the head; candidates are adults not input as dependents (every -adult when all are). These situations omit marital units, so head and -spouse selection follows age order. Core breaks equal-age ties by member order. +other than the head who fails the qualifying child age test against them; +candidates are adults not input as dependents (every adult when all are). +These situations omit marital units, so the model builds them by the same +rules and head and spouse selection follows age order. Core breaks equal-age +ties by member order. Hypothesis draws batches of tax units of one to five people, with tied ages, children, separated members and, in turn, no role inputs, input dependent diff --git a/policyengine_us/tests/microsimulation/test_marital_unit_inputs.py b/policyengine_us/tests/microsimulation/test_marital_unit_inputs.py new file mode 100644 index 00000000000..40b18e6c665 --- /dev/null +++ b/policyengine_us/tests/microsimulation/test_marital_unit_inputs.py @@ -0,0 +1,658 @@ +"""Construction/data contracts that the policy YAML runner cannot assert. + +Policy outcomes live in is_tax_unit_spouse.yaml and ssi_claim_is_joint.yaml. +These tests use one six-person dataset and small households to check +identifiers, year extension, caller isolation, clones and source-snapshot +round trips. The pairing tests call the preprocessing helper directly, with +the shared country system for the age-order fallback, without constructing +simulations. +""" + +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest + +from policyengine_us import Microsimulation, Simulation +from policyengine_us.data.dataset_schema import USSingleYearDataset +from policyengine_us.system import system +from policyengine_us.tools.marital_units import infer_missing_marital_units +from policyengine_us.tools.social_security_inputs import ( + export_source_inputs, + reload_source_inputs, +) + + +def _explicit_pair(): + return { + "people": { + "head": {"is_tax_unit_head": {"2024": True}}, + "spouse": {"is_tax_unit_spouse": {"2024": True}}, + "child": {"age": {"2024": 10}}, + }, + "tax_units": {"tax_unit": {"members": ["head", "spouse", "child"]}}, + } + + +def test_household_construction_does_not_mutate_input_and_expands_axes(): + situation = _explicit_pair() + situation["axes"] = [ + [ + { + "name": "employment_income", + "period": "2024", + "min": 0, + "max": 10_000, + "count": 2, + } + ] + ] + before = deepcopy(situation) + sim = Simulation(situation=situation) + assert situation == before + assert sim.marital_unit.members_entity_id.tolist() == [0, 0, 1, 2, 2, 3] + clone = sim.get_branch("copy") + np.testing.assert_array_equal( + clone.marital_unit.members_entity_id, sim.marital_unit.members_entity_id + ) + + +def test_dataset_marital_ids_survive_loading_and_year_extension(): + memberships = np.array([0, 17, 42, 42, 99, 99]) + tax_memberships = np.array([10, 10, 20, 20, 30, 40]) + person = pd.DataFrame( + { + "person_id": [101, 102, 201, 202, 301, 302], + "age": [45, 18, 60, 40, 65, 63], + "person_marital_unit_id": memberships, + "person_tax_unit_id": tax_memberships, + "person_household_id": [1] * 6, + "person_family_id": [1] * 6, + "person_spm_unit_id": [1] * 6, + } + ) + dataset = USSingleYearDataset( + time_period=2024, + person=person, + household=pd.DataFrame({"household_id": [1], "household_weight": [1.0]}), + family=pd.DataFrame({"family_id": [1]}), + spm_unit=pd.DataFrame({"spm_unit_id": [1]}), + tax_unit=pd.DataFrame({"tax_unit_id": [10, 20, 30, 40]}), + marital_unit=pd.DataFrame({"marital_unit_id": [0, 17, 42, 99]}), + ) + original_person = person.copy(deep=True) + sim = Microsimulation(dataset=dataset, dataset_end_year=2025) + np.testing.assert_array_equal( + np.asarray(sim.marital_unit.ids)[sim.marital_unit.members_entity_id], + memberships, + ) + for year in (2024, 2025): + np.testing.assert_array_equal( + sim.calculate("person_marital_unit_id", year), memberships + ) + np.testing.assert_array_equal( + sim.calculate("is_tax_unit_spouse", year), + [False, False, False, True, False, False], + ) + pd.testing.assert_frame_equal(person, original_person) + + +@pytest.mark.parametrize( + "marital_units", + [ + {}, + {"reported": {"members": ["head", "child"]}}, + ], +) +def test_explicit_marital_mapping_is_left_untouched(marital_units): + situation = _explicit_pair() + situation["marital_units"] = marital_units + original = deepcopy(situation) + assert infer_missing_marital_units(situation) == original + assert situation["marital_units"] is marital_units + + +def test_no_pairing_across_households_or_disjoint_role_periods(): + situation = _explicit_pair() + situation["households"] = { + "first": {"members": ["head", "child"]}, + "second": {"members": ["spouse"]}, + } + inferred = infer_missing_marital_units(situation) + assert all(len(unit["members"]) == 1 for unit in inferred["marital_units"].values()) + situation = _explicit_pair() + situation["people"]["spouse"]["is_tax_unit_spouse"] = {"2025": True} + inferred = infer_missing_marital_units(situation) + assert all(len(unit["members"]) == 1 for unit in inferred["marital_units"].values()) + + +@pytest.mark.parametrize( + "extra_inputs", + [ + {"is_tax_unit_spouse": {"2024": True, "2025": False}}, + {"is_tax_unit_head": {"2024": True}}, + {"is_tax_unit_dependent": {"2024": True}}, + ], +) +def test_ambiguous_or_changing_roles_give_everyone_their_own_unit(extra_inputs): + # These computed on main, so the hook pairs no one rather than raising. + situation = _explicit_pair() + situation["people"]["spouse"].update(extra_inputs) + assert _pairs(situation) == [] + + +def test_separated_pair_and_partial_tax_units_stay_singletons(): + separated = _explicit_pair() + separated["people"]["spouse"]["is_separated"] = {"2024": True} + partial = _explicit_pair() + partial["tax_units"]["tax_unit"]["members"] = ["head", "child"] + for situation in (separated, partial): + inferred = infer_missing_marital_units(situation) + assert all( + len(unit["members"]) == 1 for unit in inferred["marital_units"].values() + ) + + +def test_source_snapshot_round_trip_keeps_the_inferred_tax_spouse(): + # The snapshot writes the inferred marital units out as members, and the + # reloaded simulation reads them as supplied; they agree with the tax + # roles, so the second adult stays the tax spouse. + sim = Simulation(situation={"people": {"first": {}, "second": {}}}) + reloaded = reload_source_inputs(export_source_inputs(sim)) + np.testing.assert_array_equal( + reloaded.marital_unit.members_entity_id, sim.marital_unit.members_entity_id + ) + assert sim.calculate("is_tax_unit_spouse", 2024).tolist() == [False, True] + np.testing.assert_array_equal( + reloaded.calculate("is_tax_unit_spouse", 2024), + sim.calculate("is_tax_unit_spouse", 2024), + ) + + +def _married_family(**people): + people = { + "first": {"age": {"2024": 40}}, + "second": {"age": {"2024": 38}}, + "child": {"age": {"2024": 10}}, + **people, + } + return { + "people": people, + "tax_units": {"tax_unit": {"members": list(people)}}, + "families": {"family": {"members": list(people), "is_married": {"2024": True}}}, + } + + +def _pairs(situation): + units = infer_missing_marital_units(situation)["marital_units"].values() + return sorted(sorted(unit["members"]) for unit in units if len(unit["members"]) > 1) + + +def test_a_married_family_pairs_its_two_adults_but_not_its_children(): + assert _pairs(_married_family()) == [["first", "second"]] + + +@pytest.mark.parametrize( + "people", + [ + # A third adult leaves the married couple ambiguous. + {"adult_child": {"age": {"2024": 21}}}, + {"second": {"age": {"2024": 38}, "is_separated": {"2024": True}}}, + {"second": {"age": {"2024": 38}, "is_tax_unit_dependent": {"2024": True}}}, + ], +) +def test_a_married_family_stays_unpaired_when_ambiguous(people): + assert _pairs(_married_family(**people)) == [] + + +def test_a_changing_is_married_input_pairs_no_one(): + situation = _married_family() + situation["families"]["family"]["is_married"] = {"2024": True, "2025": False} + assert _pairs(situation) == [] + + +@pytest.mark.parametrize( + "head, spouse", + [ + ({"2024": np.True_}, {"2024": 1}), + # Overlapping year and month inputs both apply to 2024. + ({"2024": True}, {"2024-01": True}), + ], +) +def test_true_role_inputs_pair_in_any_form_and_overlapping_period(head, spouse): + situation = _explicit_pair() + situation["people"]["head"]["is_tax_unit_head"] = head + situation["people"]["spouse"]["is_tax_unit_spouse"] = spouse + assert _pairs(situation) == [["head", "spouse"]] + + +def test_malformed_input_is_left_to_core_validation(): + bad_period = _explicit_pair() + bad_period["people"]["head"]["is_tax_unit_head"] = {"not a period": True} + listed_twice = _explicit_pair() + listed_twice["tax_units"]["other"] = {"members": ["child"]} + for situation in (bad_period, listed_twice): + assert "marital_units" not in infer_missing_marital_units(situation) + + +def _fallback_pairs(people, **groups): + situation = { + "people": people, + "tax_units": {"tax_unit": {"members": list(people)}}, + **groups, + } + units = infer_missing_marital_units(situation, "2024", system)["marital_units"] + return sorted( + sorted(unit["members"]) for unit in units.values() if len(unit["members"]) > 1 + ) + + +@pytest.mark.parametrize( + "people, pairs", + [ + # The oldest adult and the next-oldest who fails the age test. + ( + {"older": {"age": 45}, "younger": {"age": 20}, "child": {"age": 10}}, + [["older", "younger"]], + ), + # The qualifying child age test keeps an adult child out: under 19, + ({"parent": {"age": 45}, "child": {"age": 18}}, []), + # under 24 and a full-time student, + ( + { + "parent": {"age": 50}, + "child": {"age": 21, "is_full_time_college_student": True}, + }, + [], + ), + # or permanently and totally disabled. + ( + { + "parent": {"age": 70}, + "child": {"age": 40, "is_permanently_and_totally_disabled": True}, + }, + [], + ), + # The role formulas take adults from is_child, which can be an input. + ({"parent": {"age": 45}, "child": {"age": 30, "is_child": True}}, []), + # A separated spouse leaves the unit without one, and no younger adult + # takes their place (26 USC 7703(a)(2)). + ( + { + "first": {"age": 45}, + "second": {"age": 40, "is_separated": True}, + "third": {"age": 30}, + }, + [], + ), + # So does a separated head. + ({"first": {"age": 45, "is_separated": True}, "second": {"age": 43}}, []), + # Another member's separation doesn't stop the couple. + ( + { + "first": {"age": 45}, + "second": {"age": 43}, + "child": {"age": 18, "is_separated": True}, + }, + [["first", "second"]], + ), + # A pairing that changes between years pairs no one. + ({"parent": {"age": 45}, "child": {"age": {"2024": 18, "2025": 19}}}, []), + ], +) +def test_fallback_pairs_the_inferred_tax_head_and_spouse(people, pairs): + assert _fallback_pairs(people) == pairs + + +@pytest.mark.parametrize( + "roles, pairs", + [ + # Supplied roles pair an 18-year-old spouse the age test would not. + ({"first": "HEAD", "second": "SPOUSE"}, [["first", "second"]]), + # And they keep a dependent adult out of a couple. + ({"first": "HEAD", "second": "DEPENDENT"}, []), + ], +) +def test_supplied_tax_roles_decide_the_couple(roles, pairs): + people = { + "first": {"age": 45, "tax_unit_role_input": roles["first"]}, + "second": {"age": 18 if roles["second"] == "SPOUSE" else 30}, + } + people["second"]["tax_unit_role_input"] = roles["second"] + assert _fallback_pairs(people) == pairs + + +def test_fallback_stops_at_a_false_is_married_or_another_household(): + adults = {"first": {"age": 45}, "second": {"age": 40}} + unmarried = {"family": {"members": list(adults), "is_married": False}} + assert _fallback_pairs(adults, families=unmarried) == [] + apart = { + "one": {"members": ["first"]}, + "two": {"members": ["second"]}, + } + assert _fallback_pairs(adults, households=apart) == [] + + +@pytest.mark.parametrize( + "order", + [ + ["grandchild", "husband", "wife"], + ["husband", "grandchild", "wife"], + ], +) +def test_inputs_dated_after_the_default_input_year_keep_the_couple(order): + # Simulation's default input year is 2024; a payload dated 2026 must + # still pair its couple wherever they are listed. + people = { + "grandchild": {"age": {"2026": 10}}, + "husband": {"age": {"2026": 70}}, + "wife": {"age": {"2026": 68}}, + } + sim = Simulation(situation={"people": {name: people[name] for name in order}}) + units = sim.marital_unit.members_entity_id.tolist() + index = {name: position for position, name in enumerate(order)} + assert units[index["husband"]] == units[index["wife"]] + assert units[index["grandchild"]] != units[index["husband"]] + + +def test_two_tax_units_each_pair_their_own_couple(): + people = { + "first_head": {"age": 45}, + "first_spouse": {"age": 43}, + "second_head": {"age": 40}, + "second_spouse": {"age": 38}, + "child": {"age": 5}, + } + situation = { + "people": people, + "tax_units": { + "first": {"members": ["first_head", "first_spouse", "child"]}, + "second": {"members": ["second_head", "second_spouse"]}, + }, + } + units = infer_missing_marital_units(situation, "2024", system)["marital_units"] + pairs = sorted( + sorted(unit["members"]) for unit in units.values() if len(unit["members"]) > 1 + ) + assert pairs == [["first_head", "first_spouse"], ["second_head", "second_spouse"]] + + +def test_two_couples_in_one_tax_unit_pair_only_the_role_couple(): + # A known limitation: the role formulas pick one head and one spouse. + people = { + "older_husband": {"age": 70}, + "older_wife": {"age": 68}, + "younger_husband": {"age": 45}, + "younger_wife": {"age": 43}, + } + assert _fallback_pairs(people) == [["older_husband", "older_wife"]] + + +def test_integer_person_ids_pair(): + people = {1: {"age": 45}, 2: {"age": 43}, 3: {"age": 10}} + assert _fallback_pairs(people) == [["1", "2"]] + + +def test_a_false_spouse_input_leaves_the_roles_without_a_couple(): + people = {"first": {"age": 45}, "second": {"age": 43, "is_tax_unit_spouse": False}} + assert _fallback_pairs(people) == [] + + +@pytest.mark.parametrize( + "filing_status, pairs", + [ + (None, []), + # Only a married couple files jointly (26 USC 6013(a)). + ("JOINT", [["head", "spouse"]]), + # A status that changes between periods counts as no status, so the + # age test applies, even when the last year's status is JOINT. + ({"2024": "SINGLE", "2025": "JOINT"}, []), + ], +) +def test_a_joint_return_pairs_a_spouse_the_age_test_would_not(filing_status, pairs): + people = { + "head": {"age": 22}, + "spouse": {"age": 20, "is_full_time_college_student": True}, + } + tax_units = {"tax_unit": {"members": list(people)}} + if filing_status is not None: + tax_units["tax_unit"]["filing_status"] = filing_status + assert _fallback_pairs(people, tax_units=tax_units) == pairs + + +@pytest.mark.parametrize( + "households, pairs", + [ + # Only married people file separately (26 USC 1(d)). + ({"home": {"members": ["first", "second"]}}, [["first", "second"]]), + # Three separate filers don't say who is married to whom. + ({"home": {"members": ["first", "second", "third"]}}, []), + # A marital unit is a married, co-habiting couple. + ({"one": {"members": ["first"]}, "two": {"members": ["second"]}}, []), + ], +) +def test_the_two_separate_filers_of_a_household_pair(households, pairs): + names = [name for home in households.values() for name in home["members"]] + people = {name: {"age": 45} for name in names} + tax_units = { + name: {"members": [name], "filing_status": "SEPARATE"} for name in names + } + assert _fallback_pairs(people, tax_units=tax_units, households=households) == pairs + + +@pytest.mark.parametrize( + "roles, status", + [ + # Explicit roles settle the couple whatever the status says. + ( + { + "husband": {"is_tax_unit_head": True}, + "wife": {"is_tax_unit_spouse": True}, + }, + {"2025": "JOINT", "2026": "SEPARATE"}, + ), + # Without roles, step 4 pairs them as it would with no status. + ({}, {"2025": "SINGLE", "2026": "HEAD_OF_HOUSEHOLD"}), + ], +) +def test_a_changing_filing_status_counts_as_no_status(roles, status): + people = { + "husband": {"age": 70, **roles.get("husband", {})}, + "wife": {"age": 68, **roles.get("wife", {})}, + } + tax_units = {"tax_unit": {"members": list(people), "filing_status": status}} + assert _fallback_pairs(people, tax_units=tax_units) == [["husband", "wife"]] + + +def _separate_return_pairs(tax_units, people, **groups): + # All in one household. Each tax unit files separately unless it gives + # (members, filing_status). + situation = { + "people": people, + "tax_units": { + name: ( + {"members": unit[0], "filing_status": unit[1]} + if isinstance(unit, tuple) + else {"members": unit, "filing_status": "SEPARATE"} + ) + for name, unit in tax_units.items() + }, + "households": {"home": {"members": list(people)}}, + **groups, + } + units = infer_missing_marital_units(situation, "2024", system)["marital_units"] + return sorted( + sorted(unit["members"]) for unit in units.values() if len(unit["members"]) > 1 + ) + + +@pytest.mark.parametrize( + "tax_units, people, groups, pairs", + [ + # A separate status that changes between periods counts as no status. + ( + { + "one": ["first"], + "two": (["second"], {"2024": "SEPARATE", "2025": "SINGLE"}), + }, + {"first": {"age": 45}, "second": {"age": 45}}, + {}, + [], + ), + # A separated filer pairs no one. + ( + {"one": ["first"], "two": ["second"]}, + {"first": {"age": 45}, "second": {"age": 45, "is_separated": True}}, + {}, + [], + ), + # Nor does a family that says the two aren't married. + ( + {"one": ["first"], "two": ["second"]}, + {"first": {"age": 45}, "second": {"age": 45}}, + { + "families": { + "family": {"members": ["first", "second"], "is_married": False} + } + }, + [], + ), + # A separate return with no clear filer (two adults, neither a head + # input nor a dependent) still counts, so three returns pair no one. + ( + {"one": ["first"], "two": ["second"], "three": ["third", "fourth"]}, + { + "first": {"age": 45}, + "second": {"age": 45}, + "third": {"age": 45}, + "fourth": {"age": 45, "is_tax_unit_spouse": False}, + }, + {}, + [], + ), + # A true is_tax_unit_head input names the filer of a two-adult unit. + ( + {"one": ["first", "roommate"], "two": ["second"]}, + { + "first": {"age": 45, "is_tax_unit_head": True}, + "roommate": {"age": 30, "is_tax_unit_spouse": False}, + "second": {"age": 45}, + }, + {}, + [["first", "second"]], + ), + # An adult input as a dependent isn't the filer. + ( + {"one": ["first", "parent"], "two": ["second"]}, + { + "first": {"age": 45}, + "parent": {"age": 70, "is_tax_unit_dependent": True}, + "second": {"age": 45}, + }, + {}, + [["first", "second"]], + ), + # Nor is a person input as a child, whatever their age. + ( + {"one": ["first", "kid"], "two": ["second"]}, + { + "first": {"age": 45}, + "kid": {"age": 30, "is_child": True}, + "second": {"age": 45}, + }, + {}, + [["first", "second"]], + ), + # A filer already in a couple from the earlier steps stays in it. + ( + {"one": ["first", "partner"], "two": ["second"]}, + { + "first": {"age": 45, "is_tax_unit_head": True}, + "partner": {"age": 43, "is_tax_unit_spouse": True}, + "second": {"age": 45}, + }, + {}, + [["first", "partner"]], + ), + ], +) +def test_the_separate_filer_rules(tax_units, people, groups, pairs): + assert _separate_return_pairs(tax_units, people, **groups) == pairs + + +def test_a_married_family_skips_a_person_input_as_a_child(): + # The role formulas take adults from is_child, so a 21-year-old input as + # a child doesn't make the married family ambiguous. + situation = _married_family( + adult_child={"age": {"2024": 21}, "is_child": {"2024": True}} + ) + assert _pairs(situation) == [["first", "second"]] + + +def test_the_adult_age_matches_is_child(): + from policyengine_us.tools import marital_units + + sim = Simulation( + situation={ + "people": {"minor": {"age": {"2024": 17}}, "adult": {"age": {"2024": 18}}} + } + ) + assert sim.calculate("is_child", 2024).tolist() == [ + age < marital_units._ADULT_AGE for age in (17, 18) + ] + + +@pytest.mark.parametrize("variable", ["is_tax_unit_spouse", "is_tax_unit_head"]) +def test_a_role_input_on_anyone_fills_false_for_the_rest(variable): + # Core fills the role for everyone once a grandchild supplies it, so the + # roles have no couple, and neither do the marital units. + people = { + "husband": {"age": {"2026": 70}}, + "wife": {"age": {"2026": 68}}, + "grandchild": {"age": {"2026": 10}, variable: {"2026": False}}, + } + sim = Simulation(situation={"people": people}) + assert len(set(sim.marital_unit.members_entity_id.tolist())) == 3 + + +def test_a_student_input_on_anyone_fills_false_for_the_rest(): + # Another person's is_full_time_student input gives the college student + # the default false, so the role formulas pair them with their parent. + people = { + "parent": {"age": 45}, + "student": {"age": 22, "is_full_time_college_student": True}, + "child": {"age": 10, "is_full_time_student": False}, + } + assert _fallback_pairs(people) == [["parent", "student"]] + + +def test_a_reform_to_the_age_limit_changes_the_couple(): + from policyengine_core.reforms import Reform + + people = {"parent": {"age": {"2026": 45}}, "child": {"age": {"2026": 25}}} + reform = Reform.from_dict( + {"gov.irs.dependent.ineligible_age.non_student": {"2026-01-01.2100-12-31": 30}}, + country_id="us", + ) + baseline = Simulation(situation={"people": deepcopy(people)}) + reformed = Simulation(situation={"people": deepcopy(people)}, reform=reform) + # A 25-year-old fails the baseline age test (under 19) and passes the + # reformed one (under 30), so only the baseline pairs them. + assert len(set(baseline.marital_unit.members_entity_id.tolist())) == 1 + assert len(set(reformed.marital_unit.members_entity_id.tolist())) == 2 + + +def test_undated_role_inputs_set_units_for_the_default_input_year(): + # A known limitation: the undated inputs land in 2024, where the + # grandchild's false spouse input leaves the roles without a couple, so + # the grandparents get their own units. In 2026, with no role input, the + # role formulas run again and pair them, which the units don't follow. + people = { + "husband": {"age": 70}, + "wife": {"age": 68}, + "grandchild": {"age": 10, "is_tax_unit_spouse": False}, + } + sim = Simulation(situation={"people": people}) + assert len(set(sim.marital_unit.members_entity_id.tolist())) == 3 + assert sim.calculate("is_tax_unit_spouse", 2026).tolist() == [False, True, False] diff --git a/policyengine_us/tests/policy/baseline/gov/hhs/medicaid/eligibility/is_medicaid_long_term_care_home_equity_eligible.yaml b/policyengine_us/tests/policy/baseline/gov/hhs/medicaid/eligibility/is_medicaid_long_term_care_home_equity_eligible.yaml index b6d51d2aee3..b2ef5086513 100644 --- a/policyengine_us/tests/policy/baseline/gov/hhs/medicaid/eligibility/is_medicaid_long_term_care_home_equity_eligible.yaml +++ b/policyengine_us/tests/policy/baseline/gov/hhs/medicaid/eligibility/is_medicaid_long_term_care_home_equity_eligible.yaml @@ -379,5 +379,8 @@ household: members: [agricultural_at_limit, agricultural_above_limit, other_at_cap, other_above_cap] + # Four separate people, each in their own marital unit, so no one has a + # spouse living in the home. + marital_units: {} output: is_medicaid_long_term_care_home_equity_eligible: [true, false, true, false] diff --git a/policyengine_us/tests/policy/baseline/gov/hud/hud_annual_income.yaml b/policyengine_us/tests/policy/baseline/gov/hud/hud_annual_income.yaml index 44411850e63..f10fec5d48e 100644 --- a/policyengine_us/tests/policy/baseline/gov/hud/hud_annual_income.yaml +++ b/policyengine_us/tests/policy/baseline/gov/hud/hud_annual_income.yaml @@ -251,6 +251,9 @@ tax_units: tax_unit: members: [head, spouse] + marital_units: + marital_unit: + members: [head, spouse] spm_units: spm_unit: members: [head, spouse] diff --git a/policyengine_us/tests/policy/baseline/gov/ssa/ssi/ssi_claim_is_joint.yaml b/policyengine_us/tests/policy/baseline/gov/ssa/ssi/ssi_claim_is_joint.yaml index 00448eb3134..449057da4db 100644 --- a/policyengine_us/tests/policy/baseline/gov/ssa/ssi/ssi_claim_is_joint.yaml +++ b/policyengine_us/tests/policy/baseline/gov/ssa/ssi/ssi_claim_is_joint.yaml @@ -287,3 +287,51 @@ state_code: FL output: ssi_claim_is_joint: [false, false] + +- name: With marital units omitted, an aged couple listed after their grandchild makes a joint claim. + period: 2025 + input: + people: + grandchild: + age: 10 + husband: + age: 70 + wife: + age: 68 + tax_units: + tax_unit: + members: [grandchild, husband, wife] + households: + household: + members: [grandchild, husband, wife] + state_code: TX + output: + # The model pairs the couple the tax roles pair as head and spouse, + # wherever they are listed, so each is the other's eligible spouse and + # the claim is joint (20 CFR 416.1801(c)). + ssi_claim_is_joint: [false, true, true] + +- name: With marital units omitted, an aged parent and their disabled adult child are not a joint claim. + period: 2025 + input: + people: + parent: + age: 70 + child: + age: 40 + is_disabled: true + meets_ssi_disability_criteria: true + is_permanently_and_totally_disabled: true + tax_units: + tax_unit: + members: [parent, child] + households: + household: + members: [parent, child] + state_code: TX + output: + # The child meets the qualifying child age test as permanently and + # totally disabled (26 USC 152(c)(3)(B)), so each gets their own marital + # unit. A parent and child aren't husband and wife, so neither is the + # other's eligible spouse (20 CFR 416.1801(c), 416.1806). + ssi_claim_is_joint: [false, false] diff --git a/policyengine_us/tests/policy/baseline/gov/states/mt/tax/income/credits/elderly_homeowner_or_renter/mt_elderly_homeowner_or_renter_credit.yaml b/policyengine_us/tests/policy/baseline/gov/states/mt/tax/income/credits/elderly_homeowner_or_renter/mt_elderly_homeowner_or_renter_credit.yaml index fff1350290b..048e4197635 100644 --- a/policyengine_us/tests/policy/baseline/gov/states/mt/tax/income/credits/elderly_homeowner_or_renter/mt_elderly_homeowner_or_renter_credit.yaml +++ b/policyengine_us/tests/policy/baseline/gov/states/mt/tax/income/credits/elderly_homeowner_or_renter/mt_elderly_homeowner_or_renter_credit.yaml @@ -753,24 +753,27 @@ members: [person1, person2] state_name: MT output: - # Both siblings are 62 or older and file their own returns. Line 18 - # gross household income = 10_000 + 15_000 = 25_000 for each; line 20 = - # 25_000 - 12_600 = 12_400; line 21 = 0.05; line 22 = 620. - # person1: line 25 = 4_800 x 0.15 = 720; line 27 = 720 - 620 = 100. - # person2: line 25 = 7_200 x 0.15 = 1_080; line 27 = 1_080 - 620 = 460. - # Line 29 = 100% (under 35_000). "Only one claimant per household in a - # claim period ... is entitled to relief" (§ 15-30-2341(1)); the + # Both siblings are 62 or older and file their own returns. Siblings + # are not an SSI couple, so person1 receives individual SSI of + # 943 x 12 - (10_000 - 20 x 12) = 1_556, which counts as gross household + # income ("SSI payments"). Line 18 gross household income = 10_000 + + # 1_556 + 15_000 = 26_556 for each; line 20 = 26_556 - 12_600 = 13_956; + # line 21 = 0.05; line 22 = 697.80. + # person1: line 25 = 4_800 x 0.15 = 720; line 27 = 720 - 697.80 = 22.20. + # person2: line 25 = 7_200 x 0.15 = 1_080; line 27 = 1_080 - 697.80 = + # 382.20. Line 29 = 100% (under 35_000). "Only one claimant per household + # in a claim period ... is entitled to relief" (§ 15-30-2341(1)); the # household claims through person2, whose credit is larger. Before the - # limit both were paid, 560 in total. - mt_elderly_homeowner_or_renter_credit_pre_one_claimant: [100, 460] + # limit both were paid, 404.40 in total. + mt_elderly_homeowner_or_renter_credit_pre_one_claimant: [22.20, 382.20] mt_elderly_homeowner_or_renter_credit_selected_claimant: [false, true] - mt_elderly_homeowner_or_renter_credit: [0, 460] - mt_refundable_credits: [0, 460] - taxsim_state_property_tax_credit: [0, 460] + mt_elderly_homeowner_or_renter_credit: [0, 382.20] + mt_refundable_credits: [0, 382.20] + taxsim_state_property_tax_credit: [0, 382.20] # 2024 Form 2, PDF p. 1: federal standard deduction 16,550 plus # old-age subtraction 5,500 exceeds either pension. Tax before # refundable credits is zero, so only person2 receives a refund. - mt_income_tax: [0, -460] + mt_income_tax: [0, -382.20] - name: 2024 Schedule 2EC, one eligible tax unit and one younger household member who files separately period: 2024 @@ -797,9 +800,10 @@ output: # Same household as above, but person2 is under 62 and cannot be a # claimant (§ 15-30-2338(1)(a)), even though their rent is larger. - # Line 22 = 620; person1's line 27 = 720 - 620 = 100. + # person1 receives the same 1_556 of SSI, so line 22 = 697.80; person1's + # line 27 = 720 - 697.80 = 22.20. mt_elderly_homeowner_or_renter_credit_selected_claimant: [true, false] - mt_elderly_homeowner_or_renter_credit: [100, 0] + mt_elderly_homeowner_or_renter_credit: [22.20, 0] - name: 2025 Schedule 2EC, a joint couple who both qualify make one claim period: 2025 @@ -1140,18 +1144,20 @@ state_code: MT output: # Schedule 2EC line 8 counts the federal refundable credits each person - # received, plus actual elderly-credit and rebate receipts. Person amounts: - # 10_000 + 500 + 60 + 20 = 10_580; 15_000 + 300 + 40 + 80 = 15_420. - # Line 18 = 26_000; line 22 = (26_000 - 12_600) * .05 = 670. + # received, plus actual elderly-credit and rebate receipts. person1, not + # part of an SSI couple, also receives SSI of 943 x 12 - (10_000 - + # 20 x 12) = 1_556. Person amounts: 10_000 + 1_556 + 500 + 60 + 20 = + # 12_136; 15_000 + 300 + 40 + 80 = 15_420. + # Line 18 = 27_556; line 22 = (27_556 - 12_600) * .05 = 747.80. # Line 25 rent equivalents = [4_800, 7_200] * .15 = [720, 1_080]. - # Line 27 = [720, 1_080] - 670 = [50, 410], both below the 1_150 cap. - # Line 29 = 100% below 35_000. Only the larger 410 claim is paid; - # without the 1_000 of federal credits/receipts, it would be 460. - mt_elderly_homeowner_or_renter_credit_gross_household_income: [10_580, 15_420] - mt_elderly_homeowner_or_renter_credit_net_household_income: [670, 670] - mt_elderly_homeowner_or_renter_credit_pre_one_claimant: [50, 410] + # Line 27 = [720, 1_080] - 747.80 = [0, 332.20], below the 1_150 cap. + # Line 29 = 100% below 35_000. Only the larger 332.20 claim is paid; + # without the 1_000 of federal credits/receipts, it would be 382.20. + mt_elderly_homeowner_or_renter_credit_gross_household_income: [12_136, 15_420] + mt_elderly_homeowner_or_renter_credit_net_household_income: [747.80, 747.80] + mt_elderly_homeowner_or_renter_credit_pre_one_claimant: [0, 332.20] mt_elderly_homeowner_or_renter_credit_selected_claimant: [false, true] - mt_elderly_homeowner_or_renter_credit: [0, 410] + mt_elderly_homeowner_or_renter_credit: [0, 332.20] - name: 2024 Schedule 2EC, a household member's netted capital loss does not raise the credit period: 2024 diff --git a/policyengine_us/tests/policy/baseline/household/demographic/tax_unit/is_tax_unit_spouse.yaml b/policyengine_us/tests/policy/baseline/household/demographic/tax_unit/is_tax_unit_spouse.yaml index 46cf7a67e48..c79ef978d4f 100644 --- a/policyengine_us/tests/policy/baseline/household/demographic/tax_unit/is_tax_unit_spouse.yaml +++ b/policyengine_us/tests/policy/baseline/household/demographic/tax_unit/is_tax_unit_spouse.yaml @@ -331,6 +331,29 @@ is_tax_unit_dependent: [false, true] filing_status: HEAD_OF_HOUSEHOLD +- name: With marital units omitted, a parent's 18-year-old is a dependent rather than the spouse. + period: 2025 + input: + people: + mother: + age: 45 + employment_income_before_lsr: 20_000 + son: + age: 18 + tax_units: + tax_unit: + members: [mother, son] + households: + household: + members: [mother, son] + state_code: TX + output: + # The model gives each of them their own marital unit, since the son + # meets the qualifying child age test (26 USC 152(c)(3)(A)), so the + # mother files as head of household with her son as a dependent. + is_tax_unit_spouse: [false, false] + filing_status: HEAD_OF_HOUSEHOLD + - name: A separated adult dependent does not remove the filer's spouse. period: 2024 input: diff --git a/policyengine_us/tools/marital_units.py b/policyengine_us/tools/marital_units.py new file mode 100644 index 00000000000..125f41aa7bf --- /dev/null +++ b/policyengine_us/tools/marital_units.py @@ -0,0 +1,643 @@ +"""Construct missing household marital units without replacing supplied data.""" + +import numbers + +import numpy as np +from policyengine_core import periods + +# The age below which is_child treats a person as a child. +_ADULT_AGE = 18 + + +class _LeaveToCore(Exception): + """Malformed input that the situation builder reports more clearly.""" + + +class _Ambiguous(Exception): + """Inputs that can't settle one static couple, so no one is paired.""" + + +# Supplied role inputs that settle a tax unit without a couple. +_NO_PAIR = object() + + +def _is_true(value): + # Core reads real, NumPy and numeric booleans; leave strings and other + # values to its validation. + return isinstance(value, (bool, np.bool_, numbers.Number)) and bool(value) + + +def _true_input_periods(entity, variable, default_period, require_constant=False): + values = entity.get(variable, {}) + if not isinstance(values, dict): + values = {default_period: values} + supplied = {key: value for key, value in values.items() if value is not None} + if require_constant and len({_is_true(value) for value in supplied.values()}) > 1: + # Membership can't change between periods. + raise _Ambiguous + try: + return { + periods.period(key) + for key, value in supplied.items() + if key is not None and _is_true(value) + } + except ValueError as error: + raise _LeaveToCore from error + + +def _periods_overlap(first, second): + return any(a.contains(b) or b.contains(a) for a in first for b in second) + + +def _is_minor(person, default_period): + # The role formulas take adults from is_child, which a caller can supply. + supplied = person.get("is_child") + if supplied is not None: + if not isinstance(supplied, dict): + supplied = {default_period: supplied} + return any(_is_true(value) for value in supplied.values()) + values = person.get("age", {}) + if not isinstance(values, dict): + values = {default_period: values} + return any( + isinstance(value, numbers.Number) + and not isinstance(value, bool) + and value < _ADULT_AGE + for value in values.values() + ) + + +def _membership(situation, plural, people): + groups = situation.get(plural) + if groups is None: + return {name: None for name in people} + # Core assigns unlisted people their own group, including when the + # caller supplies an empty mapping rather than omitting the entity. + result = {name: ("singleton", name) for name in people} + listed = set() + for name, group in groups.items(): + members = group.get("members", []) + if not isinstance(members, list): + members = [members] + for member in members: + if str(member) in listed: + raise _LeaveToCore + listed.add(str(member)) + result[str(member)] = ("supplied", name) + return result + + +def _married_family_pair(members, people, situation, families, default_period): + """The two adults of a married family in this tax unit and household. + + A family's explicit ``is_married`` input says its adults are married. + Pair them when exactly two of its adults, neither an explicit dependent + nor separated, share this tax unit and household; otherwise leave them + as singletons. Ages are read only to set aside children. + """ + supplied_families = situation.get("families") or {} + adults = {} + for name in members: + family = families[name] + if family is None or family[0] != "supplied": + continue + if not _true_input_periods( + supplied_families[family[1]], "is_married", default_period, True + ): + continue + person = people[name] + if ( + _is_minor(person, default_period) + or _true_input_periods(person, "is_tax_unit_dependent", default_period) + or _true_input_periods(person, "is_separated", default_period) + ): + continue + adults.setdefault(family[1], []).append(name) + couples = [names for names in adults.values() if len(names) == 2] + return couples[0] if len(couples) == 1 else None + + +def _explicitly_unmarried(pair, situation, families): + """Whether both adults share a family whose is_married inputs are all false.""" + first, second = (families[name] for name in pair) + if first is None or first != second or first[0] != "supplied": + return False + values = (situation.get("families") or {})[first[1]].get("is_married") + if values is None: + return False + if not isinstance(values, dict): + values = {None: values} + supplied = [value for value in values.values() if value is not None] + return bool(supplied) and not any(_is_true(value) for value in supplied) + + +def infer_missing_marital_units(situation, default_period=None, system=None): + """Pair likely couples when a situation omits marital units. + + Supplied membership, including an empty mapping, is authoritative, and + datasets never reach this hook, so their marital units always stand. + With no supplied membership, each tax unit and household pairs at most + one couple, from the first of these that applies: + + 1. an unambiguous pair of true ``is_tax_unit_head`` and + ``is_tax_unit_spouse`` inputs for overlapping periods; + 2. the head and spouse of a complete ``tax_unit_role_input``; + 3. the two adults of a family whose explicit ``is_married`` input is + true; + 4. otherwise, with the country ``system``, the head and spouse that + ``is_tax_unit_head`` and ``is_tax_unit_spouse`` infer from age order + when everyone has their own marital unit: the oldest adult, and the + next-oldest adult who fails the qualifying child age test against + them, with no couple when the head or that spouse is separated, a + family says the two aren't married, or either has a false input for + the role step 4 gives them. A tax unit whose ``filing_status`` input is JOINT + skips the age test, since only a married couple files jointly (26 USC + 6013(a)). + + Only married people file separately (26 USC 1(d)), so two people who + each file the only separate returns in their household (``filing_status`` + input SEPARATE) are then paired, unless either is separated, a family + says they aren't married, or either is already in a couple. A marital + unit is a married, co-habiting couple, so filers in different households + stay apart. + + Everyone else receives their own unit, without claiming that their + marital status is known. Inputs that can't settle one static couple + (several heads or spouses, a dependent also marked head or spouse beside a + head and spouse pair, or role or is_married inputs that change between + periods) leave everyone in that tax unit and household in their own unit. A + filing_status input that changes between periods counts as no status. + Calculated values are never read: step 4 reads the same inputs and + parameters the role formulas read, including the defaults Core fills in for + everyone once anyone supplies a variable for a year, so the units it builds + agree with the inferred tax roles in the years the inputs are dated for. A + calculation for another year, where the role formulas run again, can give + roles the units don't match. + Core calls this hook on a private copy before building populations; + malformed input is left to its validation. + """ + if situation.get("marital_units") is not None: + return situation + people = situation.get("people", {}) + # Leave malformed entity objects to the builder's standard validation. + if not isinstance(people, dict) or any( + not isinstance(person, dict) for person in people.values() + ): + return situation + for plural in ("tax_units", "households", "families"): + supplied = situation.get(plural) + if supplied is not None and ( + not isinstance(supplied, dict) + or any(not isinstance(group, dict) for group in supplied.values()) + ): + return situation + people = {str(name): person for name, person in people.items()} + try: + units = _infer_units(situation, people, default_period, system) + except _LeaveToCore: + return situation + situation["marital_units"] = units + return situation + + +def _infer_units(situation, people, default_period, system): + tax_units = _membership(situation, "tax_units", people) + households = _membership(situation, "households", people) + families = _membership(situation, "families", people) + groups = {} + tax_unit_members = {} + for name in people: + groups.setdefault((tax_units[name], households[name]), []).append(name) + tax_unit_members.setdefault(tax_units[name], []).append(name) + + filled_years = _situation_input_years(people, default_period) + units = {name: {"members": [name]} for name in people} + for (tax_unit, _), members in groups.items(): + try: + pair = _group_pair( + members, + tax_unit_members[tax_unit], + people, + situation, + families, + default_period, + system, + filled_years, + joint=_filing_status(situation, tax_unit) == "JOINT", + ) + except _Ambiguous: + pair = None + if pair is not None: + _join(units, pair) + for pair in _separate_filer_pairs( + situation, people, tax_units, households, families, default_period + ): + if all(units.get(name, {}).get("members") == [name] for name in pair): + _join(units, pair) + return units + + +def _join(units, pair): + first, second = pair + units[first]["members"].append(second) + del units[second] + + +def _filing_status(situation, tax_unit): + """A supplied tax unit's filing_status input, if one status in every period. + + A status that changes between periods counts as no status. A change from + JOINT to SEPARATE doesn't say a couple split, so it leaves the steps that + don't read the status to settle the couple. + """ + if tax_unit is None or tax_unit[0] != "supplied": + return None + values = situation["tax_units"][tax_unit[1]].get("filing_status") + if not isinstance(values, dict): + values = {None: values} + statuses = {_enum_name(value) for value in values.values() if value is not None} + return statuses.pop() if len(statuses) == 1 else None + + +def _separate_filer_pairs( + situation, people, tax_units, households, families, default_period +): + """The two separate filers of each household that has exactly two. + + Each SEPARATE tax unit's filer is its one true is_tax_unit_head input, or + else its only adult who isn't input as a dependent. A unit with no clear + filer still counts toward its household's separate returns, so it blocks + a pairing there instead of letting two other filers pair. + """ + filers = {} + for tax_unit in {value for value in tax_units.values() if value is not None}: + if _filing_status(situation, tax_unit) != "SEPARATE": + continue + members = [name for name in people if tax_units[name] == tax_unit] + heads = list( + _true_role_inputs(members, people, "is_tax_unit_head", default_period) + ) + adults = [ + name + for name in members + if not _is_minor(people[name], default_period) + and not _true_input_periods( + people[name], "is_tax_unit_dependent", default_period + ) + ] + candidates = heads or adults + filer = candidates[0] if len(candidates) == 1 else None + homes = {households[name] for name in ([filer] if filer else members)} + for household in homes: + filers.setdefault(household, []).append(filer) + pairs = [] + for names in filers.values(): + if len(names) != 2 or None in names: + continue + pair = tuple(sorted(names, key=list(people).index)) + if any( + _true_input_periods(people[name], "is_separated", default_period) + for name in pair + ) or _explicitly_unmarried(pair, situation, families): + continue + pairs.append(pair) + return pairs + + +def _group_pair( + members, + unit_members, + people, + situation, + families, + default_period, + system, + filled_years, + joint=False, +): + """The couple, if any, among the members of one tax unit and household.""" + heads = _true_role_inputs(members, people, "is_tax_unit_head", default_period) + spouses = _true_role_inputs(members, people, "is_tax_unit_spouse", default_period) + if heads and spouses: + pair = _explicit_role_pair(heads, spouses, people, default_period) + return None if pair is _NO_PAIR else pair + pair = _supplied_role_pair(members, people) + if pair is not None: + return None if pair is _NO_PAIR else pair + pair = _married_family_pair(members, people, situation, families, default_period) + if pair is not None or system is None: + return pair + # The role formulas rank the whole tax unit, which can span households. + heads = _true_role_inputs(unit_members, people, "is_tax_unit_head", default_period) + spouses = _true_role_inputs( + unit_members, people, "is_tax_unit_spouse", default_period + ) + if len(heads) > 1 or len(spouses) > 1: + return None + # A one-sided role input that changes between periods can't fix a + # static couple either. + for name in heads: + _true_input_periods(people[name], "is_tax_unit_head", default_period, True) + for name in spouses: + _true_input_periods(people[name], "is_tax_unit_spouse", default_period, True) + pair = _tax_fallback_pair( + unit_members, + people, + default_period, + system, + filled_years, + head=next(iter(heads), None), + spouse=next(iter(spouses), None), + # Only a married couple files jointly (26 USC 6013(a)), so a JOINT + # input pairs the head with the next adult whatever the age test says. + age_test=not joint, + ) + # Only a couple who share this household share a marital unit. + if pair is None or not set(pair) <= set(members): + return None + if _explicitly_unmarried(pair, situation, families): + return None + return pair + + +def _true_role_inputs(members, people, variable, default_period): + return { + name: dates + for name in members + if (dates := _true_input_periods(people[name], variable, default_period)) + } + + +def _explicit_role_pair(heads, spouses, people, default_period): + if len(heads) != 1 or len(spouses) != 1 or heads.keys() == spouses.keys(): + raise _Ambiguous + head = next(iter(heads)) + spouse = next(iter(spouses)) + if not _periods_overlap(heads[head], spouses[spouse]): + return _NO_PAIR + _true_input_periods(people[head], "is_tax_unit_head", default_period, True) + _true_input_periods(people[spouse], "is_tax_unit_spouse", default_period, True) + for name in (head, spouse): + if _true_input_periods(people[name], "is_tax_unit_dependent", default_period): + raise _Ambiguous + if any( + _true_input_periods(people[name], "is_separated", default_period) + for name in (head, spouse) + ): + return _NO_PAIR + return head, spouse + + +def _enum_name(value): + # Enum inputs arrive as names ("HEAD"), values ("Head") or members. + return str(getattr(value, "name", value)).split(".")[-1].upper() + + +def _supplied_role_pair(members, people): + """The head and spouse of a tax unit whose every member has a role. + + is_tax_unit_head and is_tax_unit_spouse use tax_unit_role_input only when + every member of the unit supplies one; a partial or malformed set is an + error there, so it pairs no one here. + """ + roles = {} + for name in members: + values = people[name].get("tax_unit_role_input") + if values is None: + continue + if not isinstance(values, dict): + values = {None: values} + supplied = { + _enum_name(value) + for value in values.values() + if value is not None and _enum_name(value) != "UNSPECIFIED" + } + if len(supplied) > 1: + raise _Ambiguous + if supplied: + roles[name] = supplied.pop() + if not roles: + return None + heads = [name for name, role in roles.items() if role == "HEAD"] + spouses = [name for name, role in roles.items() if role == "SPOUSE"] + if len(roles) < len(members) or len(heads) != 1 or len(spouses) != 1: + return _NO_PAIR + return heads[0], spouses[0] + + +# Inputs the role formulas read for the age-order fallback. +_FALLBACK_INPUTS = ( + "age", + "is_child", + "is_tax_unit_head", + "is_tax_unit_spouse", + "is_tax_unit_dependent", + "is_separated", + "is_full_time_student", + "is_full_time_college_student", + "is_in_k12_school", + "is_permanently_and_totally_disabled", +) + + +def _dated_values(person, variable, default_period): + """A person's supplied values of an input as (start, value), oldest first. + + An undated value with no default period has no start and applies to + every year. + """ + values = person.get(variable) + if values is None: + return [] + if not isinstance(values, dict): + values = {default_period: values} + undated = [] + dated = [] + for key, value in values.items(): + if value is None: + continue + if key is None: + undated.append((None, value)) + continue + try: + start = periods.period(key).start + except ValueError as error: + raise _LeaveToCore from error + dated.append((start, value)) + return undated + sorted(dated, key=lambda item: item[0]) + + +def _fallback_years(members, people, default_period): + """The years the inputs name, or the default period's year if none do. + + An undated input lands in the default period, so it names that year. The + default period alone doesn't: Simulation's default input year can differ + from the year a payload's inputs are dated for. + """ + years = set() + for name in members: + for variable in _FALLBACK_INPUTS: + for start, _ in _dated_values(people[name], variable, default_period): + if start is not None: + years.add(start.year) + if not years and default_period is not None: + try: + years.add(periods.period(default_period).start.year) + except ValueError as error: + raise _LeaveToCore from error + return sorted(years) + + +def _situation_input_years(people, default_period): + """For each fallback input, the years anyone in the situation supplies it.""" + return { + variable: { + start.year + for person in people.values() + for start, _ in _dated_values(person, variable, default_period) + if start is not None + } + for variable in _FALLBACK_INPUTS + } + + +def _value_in_year(person, variable, year, default_period, default, carries): + """The input value the year's calculation reads. + + Core carries an input of a variable without a formula forward to later + years; a variable with a formula computes years without an input. A year + before a person's first input of a variable reads that first input, so a + person dated only in later years keeps their own values, not defaults. + """ + dated = _dated_values(person, variable, default_period) + value = default + found = False + for start, supplied in dated: + if start is None or start.year == year or (carries and start.year < year): + value = supplied + found = True + if not found: + later = [supplied for start, supplied in dated if start.year > year] + if later: + value = later[0] + return value + + +def _tax_fallback_pair( + members, people, default_period, system, filled_years, head, spouse, age_test +): + """The couple is_tax_unit_head and is_tax_unit_spouse infer from age order. + + A pairing that changes between years can't be one static membership, so + the unit pairs no one unless every year's inputs give the same couple. + """ + years = _fallback_years(members, people, default_period) + if not years: + # No year to read the dependent age limits for. + return None + pairs = { + _fallback_pair_in_year( + members, + people, + year, + default_period, + system, + filled_years, + head, + spouse, + age_test, + ) + for year in years + } + return pairs.pop() if len(pairs) == 1 else None + + +def _oldest(names, ages): + # Ties go to the person listed first. + return max(names, key=lambda name: ages[name]) if names else None + + +def _fallback_pair_in_year( + members, people, year, default_period, system, filled_years, head, spouse, age_test +): + def value(name, variable, default=False): + own = _dated_values(people[name], variable, default_period) + if year in filled_years[variable] and not any( + start is None or start.year == year for start, _ in own + ): + # Once anyone in the situation supplies a variable for the year, + # Core fills it for everyone else with its default, and its + # formula doesn't run. + return system.get_variable(variable).default_value + carries = not system.get_variable(variable).formulas + return _value_in_year( + people[name], variable, year, default_period, default, carries + ) + + ages = {} + for name in members: + age = value(name, "age", system.get_variable("age").default_value) + if not isinstance(age, numbers.Number) or isinstance(age, bool): + raise _LeaveToCore + ages[name] = age + + def is_adult(name): + # head_or_spouse_candidates reads is_child, whose formula is this age + # test unless a caller supplies it. + child = value(name, "is_child", None) + if child is None: + return ages[name] >= _ADULT_AGE + return not _is_true(child) + + # head_or_spouse_candidates: adults, skipping input dependents unless + # every adult is one. + adults = [name for name in members if is_adult(name)] + candidates = [ + name for name in adults if not _is_true(value(name, "is_tax_unit_dependent")) + ] or adults + + def input_is_false(name, variable): + supplied = value(name, variable, None) + return supplied is not None and not _is_true(supplied) + + if head is None: + head = _oldest([name for name in candidates if name != spouse], ages) + # A false is_tax_unit_head input leaves the formula's head without + # the role, so the roles have no couple. + if head is None or input_is_false(head, "is_tax_unit_head"): + return None + if spouse is not None: + return head, spouse + # The qualifying child age test (26 USC 152(c)(3)), as is_tax_unit_spouse + # applies it to adults outside the head's marital unit. Under a reform, + # Core passes the reformed system, so these are the reform's age limits. + limits = system.parameters(f"{year}-01-01").gov.irs.dependent.ineligible_age + + def meets_age_test(name): + if not age_test: + return False + student = value(name, "is_full_time_student", None) + if student is None: + # is_full_time_student's formula: college or K-12 enrolment. + student = _is_true(value(name, "is_full_time_college_student")) or ( + _is_true(value(name, "is_in_k12_school")) + ) + limit = limits.student if _is_true(student) else limits.non_student + return (ages[name] < limit and ages[name] < ages[head]) or _is_true( + value(name, "is_permanently_and_totally_disabled") + ) + + spouse = _oldest( + [name for name in candidates if name != head and not meets_age_test(name)], + ages, + ) + # Likewise a false is_tax_unit_spouse input on the formula's spouse. + if spouse is None or input_is_false(spouse, "is_tax_unit_spouse"): + return None + # is_tax_unit_spouse picks its spouse before checking separation, then + # drops that spouse when the head or the spouse is separated, without + # promoting another adult (26 USC 7703(a)(2)). Another member's + # separation doesn't matter. + if any(_is_true(value(name, "is_separated")) for name in (head, spouse)): + return None + return head, spouse diff --git a/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_head.py b/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_head.py index 2cf75ad3d7a..b19b4eae796 100644 --- a/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_head.py +++ b/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_head.py @@ -26,8 +26,9 @@ def formula(person, period, parameters): # dependents (26 USC 152(b)(2)). So when two such adults share a # two-person marital unit within this tax unit, the older of the # couple heads it, even if another adult is older. When a situation - # omits marital units, Core puts everyone in one unit, so this changes - # nothing there: a two-person unit gives the same head. + # omits marital units, tools/marital_units.py pairs the head and + # spouse this fallback picks, so the couple's older member is that + # same head. # A separated member doesn't form such a couple for head selection. # NOTE: the older adult then becomes the couple's dependent whatever # their income. If that adult files instead, claiming a couple who diff --git a/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_spouse.py b/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_spouse.py index 0b771c3de88..0be68c7b4bf 100644 --- a/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_spouse.py +++ b/policyengine_us/variables/household/demographic/tax_unit/is_tax_unit_spouse.py @@ -33,8 +33,9 @@ def formula(person, period, parameters): # the head, or permanently and totally disabled (26 USC 152(c)(3)). # That adult can be the head's dependent, so an adult child isn't # paired with their parent, while an older adult's income stays on - # the return. When a situation omits marital units, Core puts - # everyone in one unit, so the age order applies unchanged. Compare + # the return. When a situation omits marital units, + # tools/marital_units.py builds them by these same rules, so they give + # the same spouse. Compare # memberships, not the ID variable: situations can supply groups # without numeric ID inputs. # NOTE: an adult outside the head's marital unit who fails the age diff --git a/policyengine_us/variables/household/demographic/tax_unit/tax_unit_role_input.py b/policyengine_us/variables/household/demographic/tax_unit/tax_unit_role_input.py index d742e619183..678ff122222 100644 --- a/policyengine_us/variables/household/demographic/tax_unit/tax_unit_role_input.py +++ b/policyengine_us/variables/household/demographic/tax_unit/tax_unit_role_input.py @@ -15,4 +15,4 @@ class tax_unit_role_input(Variable): default_value = TaxUnitRole.UNSPECIFIED definition_period = YEAR label = "Supplied tax unit role" - documentation = "The person's role in their tax unit - head, spouse or dependent - as assigned by the tax-unit constructor that built a dataset, such as the Microcosm US build. When every member of a tax unit has a supplied role, is_tax_unit_head and is_tax_unit_spouse use it, so the constructor's head, its spouse pairing and its dependency claims all hold: a younger reference person can head a couple, an adult student stays a dependent, and a minor living without a parent can head a return. The roles only say who is head, spouse or dependent; filing_status is still computed from the unit's members and the filing rules. UNSPECIFIED (the default) means the role was not supplied, and the role variables fall back to age ordering: the oldest adult is the head, skipping adults input as tax unit dependents unless every adult in the unit is one, except that the older member of a couple sharing a two-person marital unit in the tax unit heads it. The spouse is the head's partner in their marital unit; a head without one takes the next-oldest such adult who doesn't meet the qualifying child age test against the head (under 19, or under 24 if a full-time student, and younger than the head, or permanently and totally disabled). No spouse is inferred when the head or selected spouse candidate is separated. When marital units are omitted, everyone shares one marital unit, so plain age order applies." + documentation = "The person's role in their tax unit - head, spouse or dependent - as assigned by the tax-unit constructor that built a dataset, such as the Microcosm US build. When every member of a tax unit has a supplied role, is_tax_unit_head and is_tax_unit_spouse use it, so the constructor's head, its spouse pairing and its dependency claims all hold: a younger reference person can head a couple, an adult student stays a dependent, and a minor living without a parent can head a return. The roles only say who is head, spouse or dependent; filing_status is still computed from the unit's members and the filing rules. UNSPECIFIED (the default) means the role was not supplied, and the role variables fall back to age ordering: the oldest adult is the head, skipping adults input as tax unit dependents unless every adult in the unit is one, except that the older member of a couple sharing a two-person marital unit in the tax unit heads it. The spouse is the head's partner in their marital unit; a head without one takes the next-oldest such adult who doesn't meet the qualifying child age test against the head (under 19, or under 24 if a full-time student, and younger than the head, or permanently and totally disabled). No spouse is inferred when the head or selected spouse candidate is separated. When a situation omits marital units, the model builds them by these same rules, so they give the same roles."