policyengine-household-wizard 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,124 @@
1
+ import { createPerson } from '../draft';
2
+ import type { USHouseholdDraft, USMaritalStatus, USPersonDraft } from '../types';
3
+ import catalog from './catalog.json';
4
+
5
+ export interface DrawUsSampleHouseholdOptions {
6
+ /** Omit to draw across states. State codes use two uppercase letters. */
7
+ stateCode?: string;
8
+ /** Skip copies of the previous profile in its state when another profile is available. */
9
+ excludeId?: string;
10
+ /** Returns a number from zero inclusive to one exclusive. */
11
+ random?: () => number;
12
+ }
13
+
14
+ export interface UsSampleHousehold {
15
+ /** A catalog slot local to this release, suitable for excludeId. */
16
+ id: string;
17
+ stateCode: string;
18
+ draft: USHouseholdDraft;
19
+ provenance: {
20
+ dataset: string;
21
+ buildId: string;
22
+ year: number;
23
+ url: string;
24
+ sha256: string;
25
+ policyengineVersion: string;
26
+ policyengineUsVersion: string;
27
+ sourceHouseholds: number;
28
+ eligibleHouseholds: number;
29
+ totalWeight: number;
30
+ eligibleWeight: number;
31
+ drawsPerState: number;
32
+ seed: number;
33
+ };
34
+ }
35
+
36
+ interface SampleProfile {
37
+ maritalStatus: USMaritalStatus;
38
+ people: Pick<
39
+ USPersonDraft,
40
+ 'kind' | 'age' | 'isFullTimeStudent' | 'isDisabled' | 'employmentIncome' |
41
+ 'selfEmploymentIncome' | 'socialSecurityIncome' | 'privatePensionIncome'
42
+ >[];
43
+ }
44
+
45
+ interface StateSamples {
46
+ populationWeight: number;
47
+ households: SampleProfile[];
48
+ }
49
+
50
+ function profileKey(stateCode: string, profile: SampleProfile): string {
51
+ // The same person fields can arrive in a different key order. The order of
52
+ // the people themselves matters: the head and spouse occupy distinct rows.
53
+ const members = profile.people.map((person) =>
54
+ Object.entries(person).sort(([left], [right]) => left.localeCompare(right)),
55
+ );
56
+ return JSON.stringify([stateCode, profile.maritalStatus, members]);
57
+ }
58
+
59
+ // The generator has already drawn household slots in proportion to source
60
+ // weights within each state. Divide the state's eligible-household weight
61
+ // evenly among its slots so national draws also respect state population.
62
+ const states = catalog.states as Record<string, StateSamples>;
63
+ const slots = Object.entries(states).flatMap(([stateCode, state]) =>
64
+ state.households.map((household, index) => ({
65
+ id: `${stateCode}-${index}`,
66
+ stateCode,
67
+ weight: state.populationWeight / state.households.length,
68
+ profile: household,
69
+ profileKey: profileKey(stateCode, household),
70
+ })),
71
+ );
72
+
73
+ /**
74
+ * Draw an editable household from the calibrated populace_us_2024 dataset in its source year.
75
+ * ZIP, county and other facts outside the projection stay unset.
76
+ */
77
+ export function drawUsSampleHousehold({
78
+ stateCode,
79
+ excludeId,
80
+ random = Math.random,
81
+ }: DrawUsSampleHouseholdOptions = {}): UsSampleHousehold {
82
+ const matching = stateCode === undefined ? slots : slots.filter((slot) => slot.stateCode === stateCode);
83
+ if (!matching.length) {
84
+ throw new RangeError(`No sample households for state "${stateCode}".`);
85
+ }
86
+ const previous = excludeId === undefined ? undefined : matching.find((slot) => slot.id === excludeId);
87
+ const alternatives = previous
88
+ ? matching.filter((slot) => slot.profileKey !== previous.profileKey)
89
+ : matching;
90
+ const pool = alternatives.length > 0 ? alternatives : matching;
91
+
92
+ const unit = random();
93
+ if (!Number.isFinite(unit) || unit < 0 || unit >= 1) {
94
+ throw new RangeError('The random draw must be at least zero and less than one.');
95
+ }
96
+ let remaining = unit * pool.reduce((sum, slot) => sum + slot.weight, 0);
97
+ const selected = pool.find((slot) => {
98
+ remaining -= slot.weight;
99
+ return remaining < 0;
100
+ }) ?? pool[pool.length - 1]; // rounding at the upper end of the last slot
101
+ return sampleFromSlot(selected);
102
+ }
103
+
104
+ /** Reopen a sample from this catalog release, or return undefined for an unknown ID. */
105
+ export function getUsSampleHousehold(id: string): UsSampleHousehold | undefined {
106
+ const selected = slots.find((slot) => slot.id === id);
107
+ return selected && sampleFromSlot(selected);
108
+ }
109
+
110
+ function sampleFromSlot(selected: (typeof slots)[number]): UsSampleHousehold {
111
+ const people: USPersonDraft[] = [];
112
+ for (const person of selected.profile.people) {
113
+ people.push(createPerson(person.kind, people, person));
114
+ }
115
+ return {
116
+ id: selected.id,
117
+ stateCode: selected.stateCode,
118
+ provenance: { ...catalog.provenance },
119
+ draft: {
120
+ year: catalog.provenance.year, state: selected.stateCode, county: null, zip: null,
121
+ maritalStatus: selected.profile.maritalStatus, people,
122
+ },
123
+ };
124
+ }
@@ -1,4 +1,5 @@
1
1
  import { createBlankDraft } from './draft';
2
+ import { toAmount } from './amount';
2
3
  import type { USHouseholdDraft, USPersonDraft } from './types';
3
4
 
4
5
  /**
@@ -10,6 +11,7 @@ import type { USHouseholdDraft, USPersonDraft } from './types';
10
11
  * &p=adult:35:e50000,adult:33:e20000,dep:6`
11
12
  *
12
13
  * Fields are pipe-separated within each person; people are comma-separated.
14
+ * `childcare=3000` carries annual household childcare costs, including 0.
13
15
  * Only the keys below are written: other person fields, such as tips,
14
16
  * investment income and expenses, are dropped from links for now.
15
17
  * Income/flag keys are single letters to keep the URL short:
@@ -103,6 +105,8 @@ export function serializeDraft(draft: USHouseholdDraft): string {
103
105
  if (draft.zip) params.set('zip', draft.zip);
104
106
  if (draft.maritalStatus) params.set('marital', draft.maritalStatus);
105
107
  params.set('year', String(draft.year));
108
+ const childcare = toAmount(draft.childcareExpenses);
109
+ if (childcare !== undefined) params.set('childcare', String(childcare));
106
110
  if (draft.people.length > 0) {
107
111
  params.set('p', draft.people.map(serializePerson).join(','));
108
112
  }
@@ -112,6 +116,8 @@ export function serializeDraft(draft: USHouseholdDraft): string {
112
116
  export function deserializeDraft(query: string | URLSearchParams): USHouseholdDraft {
113
117
  const params = typeof query === 'string' ? new URLSearchParams(query) : query;
114
118
  const draft = createBlankDraft();
119
+ const childcare = toAmount(params.get('childcare'));
120
+ if (childcare !== undefined) draft.childcareExpenses = childcare;
115
121
 
116
122
  const state = params.get('state');
117
123
  if (state) draft.state = state;
@@ -202,6 +202,14 @@ export interface USHouseholdDraft {
202
202
  * differentiates them. Order is significant for UI labels ("Adult 1", etc.).
203
203
  */
204
204
  people: USPersonDraft[];
205
+ /**
206
+ * Annual household childcare costs before childcare subsidies, in dollars.
207
+ * The V1 adapter sends this total once as the SPM-unit input
208
+ * `spm_unit_pre_subsidy_childcare_expenses`; the model allocates costs among
209
+ * children and subtracts subsidies. Do not repeat the total for each child.
210
+ * Leave unset when the app does not ask about childcare costs.
211
+ */
212
+ childcareExpenses?: number;
205
213
  /** Year the household is being modeled for. */
206
214
  year: number;
207
215
  /** App-controlled household-level fields ignored by the shared adapters. */
@@ -47,6 +47,21 @@ export function validate(
47
47
  const { requireCounty = false, requireAges = true } = options;
48
48
  const issues: ValidationIssue[] = [];
49
49
 
50
+ const childcare = toAmount(draft.childcareExpenses);
51
+ if (draft.childcareExpenses != null && childcare === undefined) {
52
+ issues.push({
53
+ code: 'childcareExpenses.invalid',
54
+ path: 'childcareExpenses',
55
+ message: 'Childcare expenses must be a finite amount.',
56
+ });
57
+ } else if (childcare !== undefined && childcare < 0) {
58
+ issues.push({
59
+ code: 'childcareExpenses.negative',
60
+ path: 'childcareExpenses',
61
+ message: 'Childcare expenses cannot be negative.',
62
+ });
63
+ }
64
+
50
65
  if (!draft.state) {
51
66
  issues.push({
52
67
  code: 'state.required',