-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3651 lines (3161 loc) · 166 KB
/
Copy pathscript.js
File metadata and controls
3651 lines (3161 loc) · 166 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* script.js — U.S. Migration Explorer
*
* Phase 3 — Core D3 Infrastructure
*
* Milestone 3.1: Data Loading & Preprocessing
* - Loads all 12 enriched CSV files (state + county, inflow + outflow, 3 years)
* - Parses numeric columns (n1, n2, AGI) to numbers
* - Builds stateFlows / countyFlows lookup maps
* - Precomputes per-region totals from IRS aggregate rows (y1/y2 FIPS = "96")
*
* Milestone 3.2: Derived Metric Computation
* - METRIC_META: registry of all 22+ metrics (label, unit, direction, format)
* - computeMetric(metricKey, records): pure function → number | null
* - getMapValue(regionKey, year, metricKey, level, primaryRegion): dispatcher
* - formatMetricValue(value, metricKey): display formatter
* - computeNationalTotals(): sums stateTotals across all states (share denominator)
*
* Milestone 3.3: Application State & Event Wiring [→ appState + render()]
*/
'use strict';
const workerUrl = new URL("./libs/sql.js-httpvfs/sqlite.worker.js", import.meta.url);
const wasmUrl = new URL("./libs/sql.js-httpvfs/sql-wasm.wasm", import.meta.url);
let sqlDb = null; // Global reference to the VFS database
/* ════════════════════════════════════════════════════════════════════════════
SECTION 1 — CONSTANTS & MANIFEST
═══════════════════════════════════════════════════════════════════════════ */
/**
* Available year-range tags.
* The slider positions 0/1/2 map to these keys in the flow maps.
*/
const YEARS = [
'0607', '0708', '0809', '0910', '1011', '1112', '1213', '1314', '1415',
'1516', '1617', '1718', '1819', '1920', '2021', '2122', '2223'
];
/** Human-readable labels for each year tag. */
const YEAR_LABELS = {
'0607': '2006–2007', '0708': '2007–2008', '0809': '2008–2009', '0910': '2009–2010', '1011': '2010–2011', '1112': '2011–2012', '1213': '2012–2013',
'1314': '2013–2014', '1415': '2014–2015', '1516': '2015–2016', '1617': '2016–2017', '1718': '2017–2018',
'1819': '2018–2019', '1920': '2019–2020', '2021': '2020–2021', '2122': '2021–2022', '2223': '2022–2023'
};
/** IRS aggregate FIPS — total U.S.+Foreign migration. */
const FIPS_TOTAL = '96'; // US + Foreign total
const FIPS_TOTAL_US = '97'; // US only
const FIPS_TOTAL_FOREIGN = '98'; // Foreign only
/**
* State-level FIPS codes that represent IRS aggregate rows, not real geographies.
* Rows with these FIPS codes are excluded from map rendering but included in
* the flow map so that metric computations can access them.
*/
const SPECIAL_STATE_FIPS = new Set(['57', '58', '59', '96', '97', '98']);
/**
* County-level codes used by the IRS for aggregate rows.
* When combined with a real state FIPS, these are aggregate, not real counties.
* When combined with a special state FIPS (96/97/98/57) they are also aggregate.
*/
const SPECIAL_COUNTY_FIPS = new Set(['000']);
/**
* File manifest.
* Each entry describes one enriched CSV and its logical key triple.
* State files are loaded eagerly on startup (small, ~200 KB each).
* County files are loaded lazily the first time the user switches to county
* view (large, ~7–8 MB each × 6 files ≈ 45 MB total).
*/
const DATA_FILES = [];
for (const year of YEARS) {
// ── State files ─────────────────────────────────────────────────────────
DATA_FILES.push({
level: 'state', year: year, direction: 'inflow',
path: `data/enriched/state_inflow/stateinflow${year}_enriched.csv`
});
DATA_FILES.push({
level: 'state', year: year, direction: 'outflow',
path: `data/enriched/state_outflow/stateoutflow${year}_enriched.csv`
});
// ── County files ────────────────────────────────────────────────────────
DATA_FILES.push({
level: 'county', year: year, direction: 'inflow',
path: `data/enriched/county_inflow/countyinflow${year}_enriched.csv`
});
DATA_FILES.push({
level: 'county', year: year, direction: 'outflow',
path: `data/enriched/county_outflow/countyoutflow${year}_enriched.csv`
});
}
/* ════════════════════════════════════════════════════════════════════════════
SECTION 2 — IN-MEMORY DATA STORES
═══════════════════════════════════════════════════════════════════════════ */
/**
* stateFlows[year][direction][y1_fips][y2_fips] → { n1, n2, AGI }
*
* Stores EVERY row from the state-level enriched files, including IRS
* aggregate rows (y1/y2 FIPS ∈ SPECIAL_STATE_FIPS). Keyed by the raw
* 2-digit zero-padded FIPS strings from the enriched files.
*
* Inflow files: y2 = destination state, y1 = origin (or aggregate code)
* Outflow files: y1 = origin state, y2 = destination (or aggregate code)
*/
const stateFlows = {};
/**
* countyFlows[year][direction][y1Key][y2Key] → { n1, n2, AGI }
*
* Key format: `${statefips}_${countyfips}` (e.g. "01_073" for Jefferson Co., AL).
* Includes aggregate rows so metric computations can look up IRS totals.
*
* Inflow files: y2Key = destination county, y1Key = origin (or aggregate)
* Outflow files: y1Key = origin county, y2Key = destination (or aggregate)
*/
const countyFlows = {};
/**
* stateTotals[year][statefips] → { inflow: {n1,n2,AGI}, outflow: {n1,n2,AGI} }
*
* Extracted from IRS aggregate rows:
* Inflow total = inflow row where y1_statefips = "96" (US+Foreign total)
* Outflow total = outflow row where y2_statefips = "96"
* Only populated for real state FIPS (01–56, 72).
*/
const stateTotals = {};
/**
* countyTotals[year][key] → { inflow: {n1,n2,AGI}, outflow: {n1,n2,AGI} }
*
* Extracted from IRS aggregate rows:
* Inflow total = row where y1_statefips="96" AND y1_countyfips="000"
* Outflow total = row where y2_statefips="96" AND y2_countyfips="000"
*/
const countyTotals = {};
/**
* stateMeta[statefips] → { postal, name }
* Built incrementally as state files are processed.
*/
const stateMeta = {};
/**
* countyMeta[key] → { statefips, countyfips, countyName, stateName, statePostal }
* key = `${statefips}_${countyfips}`
* Built incrementally as county files are processed.
*/
const countyMeta = {};
/**
* nationalTotals[year] → { inflow: {n1,n2,AGI}, outflow: {n1,n2,AGI} }
*
* Sum of all real-state stateTotals for a given year.
* Used as the denominator for share metrics in the default (no-selection) map view
* so that each state's value = "fraction of national migration flow".
* Populated by computeNationalTotals() after all state files are loaded.
*/
const nationalTotals = {};
let countyDataLoaded = false;
let countyDataLoading = null; // Promise, set while loading metadata
const countyDataLoadedForYear = {}; // Tracks which years have flow data loaded
/* ════════════════════════════════════════════════════════════════════════════
SECTION 3 — UTILITY FUNCTIONS
═══════════════════════════════════════════════════════════════════════════ */
/** Parse a CSV string to a number; returns 0 for blank/NaN values. */
function parseNum(s) {
const n = +s;
return Number.isFinite(n) ? n : 0;
}
/**
* Return true if the given 2-digit state FIPS is a real U.S. geography
* (not an IRS aggregate code like 96/97/98/57/58/59).
*/
function isRealStateFips(fips) {
return !SPECIAL_STATE_FIPS.has(fips);
}
/**
* Return true if a (stateFips, countyFips) pair represents a real county,
* i.e. neither the state FIPS nor the county FIPS is an IRS aggregate code.
*/
function isRealCounty(sf, cf) {
return isRealStateFips(sf) && !SPECIAL_COUNTY_FIPS.has(cf) && !cf.startsWith('AGG');
}
/**
* Return the flow record { n1, n2, AGI } for a state-level origin→destination
* pair from the appropriate flow map, or null if not found.
*
* @param {string} year - e.g. "2122"
* @param {string} direction - "inflow" | "outflow"
* @param {string} y1 - 2-digit origin state FIPS
* @param {string} y2 - 2-digit destination state FIPS
*/
function getStateFlow(year, direction, y1, y2) {
return stateFlows[year]?.[direction]?.[y1]?.[y2] ?? null;
}
/**
* Return the flow record for a county-level origin→destination pair, or null.
* Keys are `${statefips}_${countyfips}`.
*/
function getCountyFlow(year, direction, y1Key, y2Key) {
return countyFlows[year]?.[direction]?.[y1Key]?.[y2Key] ?? null;
}
/**
* Return the precomputed total { inflow: {...}, outflow: {...} } for a state
* across all years, or just one direction. Returns null if not found.
*/
function getStateTotals(year, statefips) {
return stateTotals[year]?.[statefips] ?? null;
}
/** Return the precomputed county totals for a given year and key. */
function getCountyTotals(year, key) {
return countyTotals[year]?.[key] ?? null;
}
/* ════════════════════════════════════════════════════════════════════════════
SECTION 4 — PER-FILE PROCESSORS
═══════════════════════════════════════════════════════════════════════════ */
/**
* Process one batch of rows from a state enriched CSV.
* Populates stateFlows, stateTotals, and stateMeta.
*/
function processStateRows(rows, year, direction) {
if (!stateFlows[year]) stateFlows[year] = {};
if (!stateFlows[year][direction]) stateFlows[year][direction] = {};
if (!stateTotals[year]) stateTotals[year] = {};
const dirMap = stateFlows[year][direction];
for (const row of rows) {
const y1 = row.y1_statefips;
const y2 = row.y2_statefips;
const rec = { n1: parseNum(row.n1), n2: parseNum(row.n2), AGI: parseNum(row.AGI) };
if (!dirMap[y1]) dirMap[y1] = {};
dirMap[y1][y2] = rec;
if (isRealStateFips(y2)) stateMeta[y2] = { postal: row.y2_state, name: row.y2_state_name };
if (isRealStateFips(y1)) stateMeta[y1] = { postal: row.y1_state, name: row.y1_state_name };
// Support fallback naming in case scripts output differently
const y1Name = row.y1_state_name || row.y1_statename || row.y1_name || '';
const y2Name = row.y2_state_name || row.y2_statename || row.y2_name || '';
const isNonMigrant = y1Name.includes('Non-migrants') || y2Name.includes('Non-migrants');
const isSameState1 = y1Name.includes('Total Migration-Same State');
const isSameState2 = y2Name.includes('Total Migration-Same State');
if (direction === 'inflow') {
let refFips = null;
let isTotal = false;
// Agnostic check: Find which side is the real state and which has the aggregate string
if (isRealStateFips(y2) && y1Name.includes('Total Migration-US and Foreign')) {
refFips = y2;
isTotal = true;
} else if (isRealStateFips(y1) && y2Name.includes('Total Migration-US and Foreign')) {
refFips = y1;
isTotal = true;
} else if (isRealStateFips(y2) && (isNonMigrant || isSameState1)) {
refFips = y2;
} else if (isRealStateFips(y1) && (isNonMigrant || isSameState2)) {
refFips = y1;
}
if (refFips) {
if (!stateTotals[year][refFips]) stateTotals[year][refFips] = {};
// base_inflow: Includes everything (Non-migrants, Same State, Total Migration) for share denominators
if (!stateTotals[year][refFips].base_inflow) stateTotals[year][refFips].base_inflow = { n1: 0, n2: 0, AGI: 0 };
stateTotals[year][refFips].base_inflow.n1 += rec.n1;
stateTotals[year][refFips].base_inflow.n2 += rec.n2;
stateTotals[year][refFips].base_inflow.AGI += rec.AGI;
// inflow: Purely migration from US/Foreign
if (isTotal) {
if (!stateTotals[year][refFips].inflow) stateTotals[year][refFips].inflow = { n1: 0, n2: 0, AGI: 0 };
stateTotals[year][refFips].inflow.n1 += rec.n1;
stateTotals[year][refFips].inflow.n2 += rec.n2;
stateTotals[year][refFips].inflow.AGI += rec.AGI;
}
}
}
if (direction === 'outflow') {
let refFips = null;
let isTotal = false;
if (isRealStateFips(y1) && y2Name.includes('Total Migration-US and Foreign')) {
refFips = y1;
isTotal = true;
} else if (isRealStateFips(y2) && y1Name.includes('Total Migration-US and Foreign')) {
refFips = y2;
isTotal = true;
} else if (isRealStateFips(y1) && (isNonMigrant || isSameState2)) {
refFips = y1;
} else if (isRealStateFips(y2) && (isNonMigrant || isSameState1)) {
refFips = y2;
}
if (refFips) {
if (!stateTotals[year][refFips]) stateTotals[year][refFips] = {};
if (!stateTotals[year][refFips].base_outflow) stateTotals[year][refFips].base_outflow = { n1: 0, n2: 0, AGI: 0 };
stateTotals[year][refFips].base_outflow.n1 += rec.n1;
stateTotals[year][refFips].base_outflow.n2 += rec.n2;
stateTotals[year][refFips].base_outflow.AGI += rec.AGI;
if (isTotal) {
if (!stateTotals[year][refFips].outflow) stateTotals[year][refFips].outflow = { n1: 0, n2: 0, AGI: 0 };
stateTotals[year][refFips].outflow.n1 += rec.n1;
stateTotals[year][refFips].outflow.n2 += rec.n2;
stateTotals[year][refFips].outflow.AGI += rec.AGI;
}
}
}
}
}
/**
* Process one batch of rows from a county enriched CSV.
* Populates countyFlows, countyTotals, and countyMeta.
*/
function processCountyRows(rows, year, direction) {
if (!countyFlows[year]) countyFlows[year] = {};
if (!countyFlows[year][direction]) countyFlows[year][direction] = {};
if (!countyTotals[year]) countyTotals[year] = {};
const dirMap = countyFlows[year][direction];
for (const row of rows) {
const y1sf = row.y1_statefips, y1cf = row.y1_countyfips;
const y2sf = row.y2_statefips, y2cf = row.y2_countyfips;
const y1Key = `${y1sf}_${y1cf}`, y2Key = `${y2sf}_${y2cf}`;
const rec = { n1: parseNum(row.n1), n2: parseNum(row.n2), AGI: parseNum(row.AGI) };
if (!dirMap[y1Key]) dirMap[y1Key] = {};
dirMap[y1Key][y2Key] = rec;
if (isRealCounty(y2sf, y2cf)) countyMeta[y2Key] = { statefips: y2sf, countyfips: y2cf, countyName: row.y2_county_name, stateName: row.y2_state_name, statePostal: row.y2_state };
if (isRealCounty(y1sf, y1cf)) countyMeta[y1Key] = { statefips: y1sf, countyfips: y1cf, countyName: row.y1_county_name, stateName: row.y1_state_name, statePostal: row.y1_state };
// Robust FIPS-based checks instead of fragile string matching
const isNonMigrant = (y1sf === y2sf && y1cf === y2cf);
if (direction === 'inflow') {
let refKey = null;
let isTotal = false;
if (isRealCounty(y2sf, y2cf) && y1sf === '96') {
refKey = y2Key;
isTotal = true;
} else if (isRealCounty(y1sf, y1cf) && y2sf === '96') {
refKey = y1Key;
isTotal = true;
} else if (isRealCounty(y1sf, y1cf) && isNonMigrant) {
refKey = y1Key;
} else if (isRealCounty(y2sf, y2cf) && isNonMigrant) {
refKey = y2Key;
}
if (refKey) {
if (!countyTotals[year][refKey]) countyTotals[year][refKey] = {};
if (!countyTotals[year][refKey].base_inflow) countyTotals[year][refKey].base_inflow = { n1: 0, n2: 0, AGI: 0 };
countyTotals[year][refKey].base_inflow.n1 += rec.n1;
countyTotals[year][refKey].base_inflow.n2 += rec.n2;
countyTotals[year][refKey].base_inflow.AGI += rec.AGI;
if (isTotal) {
if (!countyTotals[year][refKey].inflow) countyTotals[year][refKey].inflow = { n1: 0, n2: 0, AGI: 0 };
countyTotals[year][refKey].inflow.n1 += rec.n1;
countyTotals[year][refKey].inflow.n2 += rec.n2;
countyTotals[year][refKey].inflow.AGI += rec.AGI;
}
}
}
if (direction === 'outflow') {
let refKey = null;
let isTotal = false;
if (isRealCounty(y1sf, y1cf) && y2sf === '96') {
refKey = y1Key;
isTotal = true;
} else if (isRealCounty(y2sf, y2cf) && y1sf === '96') {
refKey = y2Key;
isTotal = true;
} else if (isRealCounty(y1sf, y1cf) && isNonMigrant) {
refKey = y1Key;
} else if (isRealCounty(y2sf, y2cf) && isNonMigrant) {
refKey = y2Key;
}
if (refKey) {
if (!countyTotals[year][refKey]) countyTotals[year][refKey] = {};
if (!countyTotals[year][refKey].base_outflow) countyTotals[year][refKey].base_outflow = { n1: 0, n2: 0, AGI: 0 };
countyTotals[year][refKey].base_outflow.n1 += rec.n1;
countyTotals[year][refKey].base_outflow.n2 += rec.n2;
countyTotals[year][refKey].base_outflow.AGI += rec.AGI;
if (isTotal) {
if (!countyTotals[year][refKey].outflow) countyTotals[year][refKey].outflow = { n1: 0, n2: 0, AGI: 0 };
countyTotals[year][refKey].outflow.n1 += rec.n1;
countyTotals[year][refKey].outflow.n2 += rec.n2;
countyTotals[year][refKey].outflow.AGI += rec.AGI;
}
}
}
}
}
/* ════════════════════════════════════════════════════════════════════════════
SECTION 5 — FILE LOADING
═══════════════════════════════════════════════════════════════════════════ */
/**
* Load all state-level CSV files (eagerly, at startup).
* Now using sql.js-httpvfs to query the chunked remote database.
*/
async function loadStateData() {
console.log('[Data] Initializing sql.js-httpvfs database …');
const worker = await createDbWorker(
[{
from: "inline",
config: {
serverMode: "chunked",
requestChunkSize: 4096,
databaseLengthBytes: 537571328,
serverChunkSize: 41943040,
urlPrefix: new URL("data/db_chunks/database.sqlite.", window.location.href).toString(),
suffixLength: 3
}
}],
workerUrl.toString(),
wasmUrl.toString()
);
sqlDb = worker.db;
console.log('[Data] Loading all state data from VFS …');
const rows = await sqlDb.query("SELECT * FROM state_flows");
// Group by year and direction so processStateRows can parse them natively
const grouped = {};
for (const row of rows) {
const y = row.year;
const d = row.direction;
if (!grouped[y]) grouped[y] = {};
if (!grouped[y][d]) grouped[y][d] = [];
grouped[y][d].push(row);
}
for (const y in grouped) {
for (const d in grouped[y]) {
processStateRows(grouped[y][d], y, d);
}
}
console.log(`[Data] State data ready — ${rows.length.toLocaleString()} total rows`);
}
/**
* Load county-level metadata (lazily, on first use of county view).
* Instead of downloading 440MB of county flow data, we just query the DISTINCT
* counties for one year to populate the combobox metadata.
*/
function loadCountyData() {
if (countyDataLoaded) return Promise.resolve();
if (countyDataLoading) return countyDataLoading;
console.log('[Data] Loading county metadata from VFS …');
countyDataLoading = sqlDb.query("SELECT DISTINCT y1_statefips, y1_countyfips, y1_state, y1_state_name, y1_county_name FROM county_flows WHERE year='2122' AND direction='outflow'").then(rows => {
for (const row of rows) {
const key = `${row.y1_statefips}_${row.y1_countyfips}`;
if (isRealCounty(row.y1_statefips, row.y1_countyfips)) {
countyMeta[key] = {
countyName: row.y1_county_name,
statePostal: row.y1_state,
stateName: row.y1_state_name
};
}
}
countyDataLoaded = true;
console.log(`[Data] County metadata ready — ${rows.length.toLocaleString()} counties`);
});
return countyDataLoading;
}
/**
* Lazy load all flow data for a specific year and process it into the county stores.
* This fetches ~30MB from the SQLite chunks.
*/
async function ensureCountyYearData(yearTag) {
if (appState.level !== 'county') return;
if (countyDataLoadedForYear[yearTag]) return;
setLoadingState(true, `Loading county data for ${YEAR_LABELS[yearTag]}…`);
try {
const rows = await sqlDb.query(`SELECT * FROM county_flows WHERE year='${yearTag}'`);
const inflows = rows.filter(r => r.direction === 'inflow');
const outflows = rows.filter(r => r.direction === 'outflow');
processCountyRows(inflows, yearTag, 'inflow');
processCountyRows(outflows, yearTag, 'outflow');
countyDataLoadedForYear[yearTag] = true;
} catch (err) {
console.error('[Data] Failed to load county year:', err);
} finally {
setLoadingState(false);
}
}
const countyDataLoadedForKey = {};
/**
* Lazy load all cross-year flow data for a specific county.
* This fetches ~15MB from the SQLite chunks.
*/
async function ensureCountyRegionData(key) {
if (appState.level !== 'county') return;
if (!key || countyDataLoadedForKey[key]) return;
const [sf, cf] = key.split('_');
setLoadingState(true, `Loading data for county...`);
try {
const rows = await sqlDb.query(`SELECT * FROM county_flows WHERE (y1_statefips='${sf}' AND y1_countyfips='${cf}') OR (y2_statefips='${sf}' AND y2_countyfips='${cf}')`);
const grouped = {};
for (const row of rows) {
const y = row.year;
const d = row.direction;
if (!grouped[y]) grouped[y] = {};
if (!grouped[y][d]) grouped[y][d] = [];
grouped[y][d].push(row);
}
for (const y in grouped) {
for (const d in grouped[y]) {
processCountyRows(grouped[y][d], y, d);
}
}
countyDataLoadedForKey[key] = true;
} catch (err) {
console.error('[Data] Failed to load region cross-year:', err);
} finally {
setLoadingState(false);
}
}
/**
* Compute and cache national (all-state) inflow/outflow totals for each year.
* Call this once after all state data is loaded.
* Result is stored in nationalTotals[year].
*/
function computeNationalTotals() {
for (const year of YEARS) {
const inf = { n1: 0, n2: 0, AGI: 0 };
const out = { n1: 0, n2: 0, AGI: 0 };
for (const fips of Object.keys(stateTotals[year] ?? {})) {
const t = stateTotals[year][fips];
if (t.inflow) { inf.n1 += t.inflow.n1; inf.n2 += t.inflow.n2; inf.AGI += t.inflow.AGI; }
if (t.outflow) { out.n1 += t.outflow.n1; out.n2 += t.outflow.n2; out.AGI += t.outflow.AGI; }
}
nationalTotals[year] = { inflow: inf, outflow: out };
}
console.debug('[Data] National totals computed for', YEARS.length, 'years.');
}
/* ════════════════════════════════════════════════════════════════════════════
SECTION 6 — DERIVED METRIC COMPUTATION (Milestone 3.2 & 9.2)
═══════════════════════════════════════════════════════════════════════════ */
/**
* Metadata registry for all metrics.
*
* Fields:
* label — human-readable name (matches index.html <option> text)
* direction — which flow direction(s) the metric reads:
* 'inflow' → only uses inflow record
* 'outflow' → only uses outflow record
* 'both' → uses both (net metrics) or neither (avg AGI)
* format — how to display the value:
* 'integer' → round to whole number, add comma separator
* 'currency' → round to whole number, thousands of $, add comma
* 'percent' → multiply by 100, show as X.X %
* 'decimal' → display with 2 decimal places
*
* AGI values in the raw data are in thousands of dollars.
* Avg AGI metrics therefore produce values in thousands of $/person.
*/
const METRIC_META = {
// ── Population ──────────────────────────────────────────────────────────
pop_inflow: { label: 'Population inflow', direction: 'inflow', format: 'integer' },
pop_outflow: { label: 'Population outflow', direction: 'outflow', format: 'integer' },
pop_net_inflow: { label: 'Net population inflow', direction: 'both', format: 'integer' },
pop_net_outflow: { label: 'Net population outflow', direction: 'both', format: 'integer' },
pop_inflow_share: { label: 'Population inflow as share of population', direction: 'inflow', format: 'percent' },
pop_outflow_share: { label: 'Population outflow as share of population', direction: 'outflow', format: 'percent' },
pop_net_inflow_share: { label: 'Net population inflow as share of population', direction: 'both', format: 'percent' },
pop_net_outflow_share: { label: 'Net population outflow as share of population', direction: 'both', format: 'percent' },
pop_inflow_total_share: { label: 'Share of total population inflow', direction: 'inflow', format: 'percent' },
pop_outflow_total_share: { label: 'Share of total population outflow', direction: 'outflow', format: 'percent' },
// ── Households ──────────────────────────────────────────────────────────
hh_inflow: { label: 'Household inflow', direction: 'inflow', format: 'integer' },
hh_outflow: { label: 'Household outflow', direction: 'outflow', format: 'integer' },
hh_net_inflow: { label: 'Net household inflow', direction: 'both', format: 'integer' },
hh_net_outflow: { label: 'Net household outflow', direction: 'both', format: 'integer' },
hh_inflow_share: { label: 'Household inflow as share of households', direction: 'inflow', format: 'percent' },
hh_outflow_share: { label: 'Household outflow as share of households', direction: 'outflow', format: 'percent' },
hh_net_inflow_share: { label: 'Net household inflow as share of households', direction: 'both', format: 'percent' },
hh_net_outflow_share: { label: 'Net household outflow as share of households', direction: 'both', format: 'percent' },
hh_inflow_total_share: { label: 'Share of total household inflow', direction: 'inflow', format: 'percent' },
hh_outflow_total_share: { label: 'Share of total household outflow', direction: 'outflow', format: 'percent' },
// ── AGI ─────────────────────────────────────────────────────────────────
agi_inflow: { label: 'AGI inflow', direction: 'inflow', format: 'currency' },
agi_outflow: { label: 'AGI outflow', direction: 'outflow', format: 'currency' },
agi_net_inflow: { label: 'Net AGI inflow', direction: 'both', format: 'currency' },
agi_net_outflow: { label: 'Net AGI outflow', direction: 'both', format: 'currency' },
agi_inflow_share: { label: 'AGI inflow as share of AGI', direction: 'inflow', format: 'percent' },
agi_outflow_share: { label: 'AGI outflow as share of AGI', direction: 'outflow', format: 'percent' },
agi_net_inflow_share: { label: 'Net AGI inflow as share of AGI', direction: 'both', format: 'percent' },
agi_net_outflow_share: { label: 'Net AGI outflow as share of AGI', direction: 'both', format: 'percent' },
agi_inflow_total_share: { label: 'Share of total AGI inflow', direction: 'inflow', format: 'percent' },
agi_outflow_total_share: { label: 'Share of total AGI outflow', direction: 'outflow', format: 'percent' },
// ── Inbound / Outbound Rates ─────────────────────────────────────────────
pop_inbound_rate: { label: 'Population inbound rate', direction: 'both', format: 'percent' },
pop_outbound_rate: { label: 'Population outbound rate', direction: 'both', format: 'percent' },
hh_inbound_rate: { label: 'Household inbound rate', direction: 'both', format: 'percent' },
hh_outbound_rate: { label: 'Household outbound rate', direction: 'both', format: 'percent' },
agi_inbound_rate: { label: 'AGI inbound rate', direction: 'both', format: 'percent' },
agi_outbound_rate: { label: 'AGI outbound rate', direction: 'both', format: 'percent' },
// ── Average AGI ─────────────────────────────────────────────────────────
avg_agi_in_individual: { label: 'Avg AGI of individual moving in', direction: 'inflow', format: 'currency' },
avg_agi_in_household: { label: 'Avg AGI of household moving in', direction: 'inflow', format: 'currency' },
avg_agi_out_individual: { label: 'Avg AGI of individual moving out', direction: 'outflow', format: 'currency' },
avg_agi_out_household: { label: 'Avg AGI of household moving out', direction: 'outflow', format: 'currency' },
// ── Ratio of Average AGIs ────────────────────────────────────────────────
agi_ratio_in_out_individual: { label: 'Avg AGI ratio, in- to out-mover individual', direction: 'both', format: 'decimal' },
agi_ratio_in_out_household: { label: 'Avg AGI ratio, in- to out-mover household', direction: 'both', format: 'decimal' },
agi_ratio_out_in_individual: { label: 'Avg AGI ratio, out- to in-mover individual', direction: 'both', format: 'decimal' },
agi_ratio_out_in_household: { label: 'Avg AGI ratio, out- to in-mover household', direction: 'both', format: 'decimal' },
};
/* ── Two-dropdown metric selection ──────────────────────────────────────────
* Instead of one large dropdown, the UI uses a Category selector (Population /
* Households / AGI) paired with a Statistic selector whose options depend on
* the chosen category. AGI has extra stats (avg AGI metrics) that the other
* categories lack.
*
* STAT_OPTIONS lists the common statistics available in ALL categories.
* AGI_EXTRA_STATS lists additional statistics available only when AGI is selected.
*/
const STAT_OPTIONS = [
{ suffix: 'inflow', label: 'Inflow', pairLabel: 'Inflow (B → A)', desc: 'The number of people, households, or dollars (AGI) moving into a region during a given tax year.' },
{ suffix: 'outflow', label: 'Outflow', pairLabel: 'Outflow (A → B)', desc: 'The number of people, households, or dollars (AGI) moving out of a region during a given tax year.' },
{ suffix: 'net_inflow', label: 'Net inflow', pairLabel: 'Net inflow (B → A)', desc: 'The difference between inflow and outflow. Net inflow = inflow − outflow (positive means the region gained).' },
{ suffix: 'net_outflow', label: 'Net outflow', pairLabel: 'Net outflow (A → B)', desc: 'The difference between inflow and outflow. Net outflow = outflow − inflow (positive means the region lost).' },
{ suffix: 'inflow_share', label: 'Inflow rate', pairLabel: 'Inflow rate (B → A)', desc: "A region's inflow expressed as a percentage of the region's total population, number of households, or AGI." },
{ suffix: 'outflow_share', label: 'Outflow rate', pairLabel: 'Outflow rate (A → B)', desc: "A region's outflow expressed as a percentage of the region's total population, number of households, or AGI." },
{ suffix: 'net_inflow_share', label: 'Net inflow rate', pairLabel: 'Net inflow rate (B → A)', desc: "A region's net inflow expressed as a percentage of the region's total population, number of households, or AGI." },
{ suffix: 'net_outflow_share', label: 'Net outflow rate', pairLabel: 'Net outflow rate (A → B)', desc: "A region's net outflow expressed as a percentage of the region's total population, number of households, or AGI." },
{ suffix: 'inflow_total_share', label: 'Inflow share', pairLabel: 'Inflow share (B → A)', desc: "When unselected, the region's share of the total national inflow of people, households, or dollars (AGI). When selected, the region's share of the primary region's total inflow." },
{ suffix: 'outflow_total_share', label: 'Outflow share', pairLabel: 'Outflow share (A → B)', desc: "When unselected, the region's share of the total national outflow of people, households, or dollars (AGI). When selected, the region's share of the primary region's total outflow." },
{ suffix: 'inbound_rate', label: 'Inbound rate', pairLabel: 'Inbound rate', desc: 'The proportion of total migration volume that is inbound. Calculated as inflow ÷ (inflow + outflow). A rate above 50% indicates the region attracts more migrants than it loses.' },
{ suffix: 'outbound_rate', label: 'Outbound rate', pairLabel: 'Outbound rate', desc: 'The proportion of total migration volume that is outbound. Calculated as outflow ÷ (inflow + outflow). Equal to 1 − inbound rate.' },
];
/* ── Split dropdown options (Base stats) ─────────────────────────────────── */
const STAT_BASE_OPTIONS = [
{ base: 'total', label: 'Total', pairLabel: 'Total', desc: 'The total number of people, households, or dollars (AGI) moving.' },
{ base: 'net', label: 'Net', pairLabel: 'Net', desc: 'The difference between inflow and outflow.' },
{ base: 'rate', label: 'Rate (relative to population)', pairLabel: 'Rate', desc: "The migration expressed as a percentage of the region's total population, households, or AGI." },
{ base: 'net_rate', label: 'Net rate (relative to population)', pairLabel: 'Net rate', desc: "The net migration expressed as a percentage of the region's total population, households, or AGI." },
{ base: 'share', label: 'Share of total migration', pairLabel: 'Share', desc: "The region's share of the total national or primary region's migration flow." },
{ base: 'volume_share', label: 'Share of combined in/out volume', pairLabel: 'Volume share', desc: 'The proportion of total migration volume (inflow + outflow) that is in this direction.' }
];
const AGI_EXTRA_BASE_STATS = [
{ base: 'avg_individual', label: 'Average AGI per individual', pairLabel: 'Average AGI per individual', desc: 'The average AGI of each individual moving.' },
{ base: 'avg_household', label: 'Average AGI per household', pairLabel: 'Average AGI per household', desc: 'The average AGI of each household moving.' },
{ base: 'ratio_individual', label: 'Ratio of avg AGI per individual', pairLabel: 'Ratio of avg AGI per individual', desc: 'The ratio of average AGI between in-movers and out-movers.' },
{ base: 'ratio_household', label: 'Ratio of avg AGI per household', pairLabel: 'Ratio of avg AGI per household', desc: 'The ratio of average AGI between in-movers and out-movers.' }
];
const AGI_EXTRA_STATS = [
{ suffix: 'avg_agi_in_individual', label: 'Avg AGI of individual moving in', pairLabel: 'Avg AGI of individual moving in (B → A)', desc: 'The average Adjusted Gross Income (AGI) of each individual moving into a region.' },
{ suffix: 'avg_agi_in_household', label: 'Avg AGI of household moving in', pairLabel: 'Avg AGI of household moving in (B → A)', desc: 'The average Adjusted Gross Income (AGI) of each household moving into a region.' },
{ suffix: 'avg_agi_out_individual', label: 'Avg AGI of individual moving out', pairLabel: 'Avg AGI of individual moving out (A → B)', desc: 'The average Adjusted Gross Income (AGI) of each individual moving out of a region.' },
{ suffix: 'avg_agi_out_household', label: 'Avg AGI of household moving out', pairLabel: 'Avg AGI of household moving out (A → B)', desc: 'The average Adjusted Gross Income (AGI) of each household moving out of a region.' },
{ suffix: 'agi_ratio_in_out_individual', label: 'Avg AGI ratio, in- to out-mover individual', pairLabel: 'Avg AGI ratio, in- to out-mover individual', desc: 'The ratio of the average AGI per individual moving in to the average AGI per individual moving out. A ratio above 1.0 means in-movers have higher average incomes than out-movers.' },
{ suffix: 'agi_ratio_in_out_household', label: 'Avg AGI ratio, in- to out-mover household', pairLabel: 'Avg AGI ratio, in- to out-mover household', desc: 'The ratio of the average AGI per household moving in to the average AGI per household moving out. A ratio above 1.0 means in-movers have higher average incomes than out-movers.' },
{ suffix: 'agi_ratio_out_in_individual', label: 'Avg AGI ratio, out- to in-mover individual', pairLabel: 'Avg AGI ratio, out- to in-mover individual', desc: 'The ratio of the average AGI per individual moving out to the average AGI per individual moving in. A ratio above 1.0 means out-movers have higher average incomes than in-movers.' },
{ suffix: 'agi_ratio_out_in_household', label: 'Avg AGI ratio, out- to in-mover household', pairLabel: 'Avg AGI ratio, out- to in-mover household', desc: 'The ratio of the average AGI per household moving out to the average AGI per household moving in. A ratio above 1.0 means out-movers have higher average incomes than in-movers.' },
];
function getMetricDescription(metricKey) {
const suffix = extractStatSuffix(metricKey);
const category = extractMetricCategory(metricKey);
const allStats = [...STAT_OPTIONS, ...AGI_EXTRA_STATS];
const stat = allStats.find(s => s.suffix === suffix);
let desc = stat && stat.desc ? stat.desc : '';
if (category === 'pop') {
desc = desc.replace('people, households, or dollars (AGI)', 'people');
desc = desc.replace("population, number of households, or AGI", "population");
} else if (category === 'hh') {
desc = desc.replace('people, households, or dollars (AGI)', 'households');
desc = desc.replace("population, number of households, or AGI", "number of households");
} else if (category === 'agi') {
desc = desc.replace('people, households, or dollars (AGI)', 'dollars (AGI)');
desc = desc.replace("population, number of households, or AGI", "AGI");
}
return desc;
}
function updateStatisticDescription(elementId, metricKey) {
const el = document.getElementById(elementId);
if (el) {
el.textContent = getMetricDescription(metricKey);
}
}
/**
* Build the full METRIC_META key from category, direction, and baseStat.
*/
function buildMetricKey(category, direction, baseStat) {
const isOut = (direction === 'out');
// AGI Extras
if (baseStat === 'avg_individual') return isOut ? 'avg_agi_out_individual' : 'avg_agi_in_individual';
if (baseStat === 'avg_household') return isOut ? 'avg_agi_out_household' : 'avg_agi_in_household';
if (baseStat === 'ratio_individual') return isOut ? 'agi_ratio_out_in_individual' : 'agi_ratio_in_out_individual';
if (baseStat === 'ratio_household') return isOut ? 'agi_ratio_out_in_household' : 'agi_ratio_in_out_household';
// Standard Stats
let suffix = '';
if (baseStat === 'total') suffix = isOut ? 'outflow' : 'inflow';
if (baseStat === 'net') suffix = isOut ? 'net_outflow' : 'net_inflow';
if (baseStat === 'rate') suffix = isOut ? 'outflow_share' : 'inflow_share';
if (baseStat === 'net_rate') suffix = isOut ? 'net_outflow_share' : 'net_inflow_share';
if (baseStat === 'share') suffix = isOut ? 'outflow_total_share' : 'inflow_total_share';
if (baseStat === 'volume_share') suffix = isOut ? 'outbound_rate' : 'inbound_rate';
return `${category}_${suffix}`;
}
/**
* Extract category, direction, and baseStat from a full metric key.
*/
function parseMetricKey(metricKey) {
let category = 'pop';
if (metricKey.startsWith('agi_') || metricKey.startsWith('avg_agi_') || metricKey.startsWith('agi_ratio_')) category = 'agi';
else if (metricKey.startsWith('hh_')) category = 'hh';
let suffix = metricKey;
for (const p of ['pop_', 'hh_', 'agi_']) {
if (metricKey.startsWith(p)) {
suffix = metricKey.slice(p.length);
break;
}
}
let direction = 'in';
if (metricKey.includes('outbound_rate') || metricKey.includes('outflow') || metricKey.includes('avg_agi_out') || metricKey.includes('agi_ratio_out_in')) {
direction = 'out';
}
let baseStat = 'total';
if (metricKey.includes('net_inflow_share') || metricKey.includes('net_outflow_share')) baseStat = 'net_rate';
else if (metricKey.includes('inflow_share') || metricKey.includes('outflow_share')) baseStat = 'rate';
else if (metricKey.includes('total_share')) baseStat = 'share';
else if (metricKey.includes('inbound_rate') || metricKey.includes('outbound_rate')) baseStat = 'volume_share';
else if (metricKey.includes('net_inflow') || metricKey.includes('net_outflow')) baseStat = 'net';
else if (metricKey.includes('inflow') || metricKey.includes('outflow')) baseStat = 'total';
else if (metricKey.includes('avg_agi_in_individual') || metricKey.includes('avg_agi_out_individual')) baseStat = 'avg_individual';
else if (metricKey.includes('avg_agi_in_household') || metricKey.includes('avg_agi_out_household')) baseStat = 'avg_household';
else if (metricKey.includes('agi_ratio_in_out_individual') || metricKey.includes('agi_ratio_out_in_individual')) baseStat = 'ratio_individual';
else if (metricKey.includes('agi_ratio_in_out_household') || metricKey.includes('agi_ratio_out_in_household')) baseStat = 'ratio_household';
return { category, direction, baseStat };
}
/**
* Extract the stat suffix from a full metric key.
* Returns the suffix that, combined with a category, reproduces the key.
*/
function extractStatSuffix(metricKey) {
if (metricKey.startsWith('avg_agi_') || metricKey.startsWith('agi_ratio_')) return metricKey;
for (const p of ['pop_', 'hh_', 'agi_']) {
if (metricKey.startsWith(p)) return metricKey.slice(p.length);
}
return metricKey;
}
/**
* Extract the category prefix from a full metric key.
*/
function extractMetricCategory(metricKey) {
if (metricKey.startsWith('avg_agi_') || metricKey.startsWith('agi_ratio_')) return 'agi';
if (metricKey.startsWith('pop_')) return 'pop';
if (metricKey.startsWith('hh_')) return 'hh';
if (metricKey.startsWith('agi_')) return 'agi';
return 'pop';
}
/**
* Populate a stat <select> with base options appropriate for the given category.
* Tries to preserve the currently-selected baseStat when the category changes.
* Returns the selected baseStat.
*/
function populateStatSelect(selectEl, category, isPairMode = false, preferredBaseStat = null) {
if (!selectEl) return '';
const currentBaseStat = preferredBaseStat ?? selectEl.value;
selectEl.innerHTML = '';
// Common stats
for (const stat of STAT_BASE_OPTIONS) {
const opt = document.createElement('option');
opt.value = stat.base;
opt.textContent = isPairMode ? stat.pairLabel : stat.label;
selectEl.appendChild(opt);
}
// AGI-only extras
if (category === 'agi') {
for (const stat of AGI_EXTRA_BASE_STATS) {
const opt = document.createElement('option');
opt.value = stat.base;
opt.textContent = isPairMode ? stat.pairLabel : stat.label;
selectEl.appendChild(opt);
}
}
// Try to preserve selection
const hasTarget = Array.from(selectEl.options).some(o => o.value === currentBaseStat);
selectEl.value = hasTarget ? currentBaseStat : selectEl.options[0]?.value || '';
return selectEl.value;
}
/**
* computeMetric(metricKey, records) → number | null
*
* Pure function. Given the relevant flow records for a region (or a pair of
* regions), returns the numeric value for the selected metric, or null if the
* required data is missing / the denominator is zero.
*
* @param {string} metricKey
* @param {Object} records
* @param {FlowRecord|null} records.inflow
* The inflow record to use. In the default map view this is the region's
* total inflow (FIPS-96 row). When a primary region P is selected, this is
* the flow from region R into P: stateFlows[year]['inflow'][R][P].
* @param {FlowRecord|null} records.outflow
* The outflow record. In the default map view this is the region's total
* outflow. When a primary P is selected, this is the flow from P to R:
* stateFlows[year]['outflow'][P][R].
* @param {FlowRecord|null} records.totalInflow
* Denominator for inflow share metrics.
* Default view: nationalTotals[year].inflow (so share = state's fraction
* of all national migration → meaningful choropleth comparison).
* Primary-selected view: stateTotals[year][P].inflow (so share = fraction
* of P's total inflow that came from R).
* @param {FlowRecord|null} records.totalOutflow
* Denominator for outflow share metrics (same logic as totalInflow).
*
* FlowRecord = { n1: number, n2: number, AGI: number }
* n1 = households
* n2 = individuals
* AGI = adjusted gross income (thousands of dollars)
*/
function computeMetric(metricKey, { inflow, outflow, baseOutflow, totalInflow, totalOutflow }, isRelative = false, level = appState.level) {
// ── Milestone 5.2: Check for missing data in county level ──
if (level === 'county') {
const meta = METRIC_META[metricKey];
if (meta) {
if (meta.direction === 'inflow' && !inflow) return null;
if (meta.direction === 'outflow' && !outflow) return null;
if (meta.direction === 'both' && (!inflow || !outflow)) return null;
}
}
const i = inflow ?? { n1: 0, n2: 0, AGI: 0 };
const o = outflow ?? { n1: 0, n2: 0, AGI: 0 };
const bo = baseOutflow ?? { n1: 0, n2: 0, AGI: 0 };
const ti = totalInflow ?? i;
const to = totalOutflow ?? o;
// Explicit net calculations replacing the former isRelative flip
const netInflowN2 = i.n2 - o.n2;
const netOutflowN2 = o.n2 - i.n2;
const netInflowN1 = i.n1 - o.n1;
const netOutflowN1 = o.n1 - i.n1;
const netInflowAGI = i.AGI - o.AGI;
const netOutflowAGI = o.AGI - i.AGI;
switch (metricKey) {
// ── Population ──────────────────────────────────────────────────────────
case 'pop_inflow': return i.n2;
case 'pop_outflow': return o.n2;
case 'pop_net_inflow': return netInflowN2;
case 'pop_net_outflow': return netOutflowN2;
case 'pop_inflow_share': return bo.n2 > 0 ? i.n2 / bo.n2 : null;
case 'pop_outflow_share': return bo.n2 > 0 ? o.n2 / bo.n2 : null;
case 'pop_net_inflow_share': return bo.n2 > 0 ? netInflowN2 / bo.n2 : null;
case 'pop_net_outflow_share': return bo.n2 > 0 ? netOutflowN2 / bo.n2 : null;
case 'pop_inflow_total_share': return ti.n2 > 0 ? i.n2 / ti.n2 : null;
case 'pop_outflow_total_share': return to.n2 > 0 ? o.n2 / to.n2 : null;
// ── Households ──────────────────────────────────────────────────────────
case 'hh_inflow': return i.n1;
case 'hh_outflow': return o.n1;
case 'hh_net_inflow': return netInflowN1;
case 'hh_net_outflow': return netOutflowN1;
case 'hh_inflow_share': return bo.n1 > 0 ? i.n1 / bo.n1 : null;
case 'hh_outflow_share': return bo.n1 > 0 ? o.n1 / bo.n1 : null;
case 'hh_net_inflow_share': return bo.n1 > 0 ? netInflowN1 / bo.n1 : null;
case 'hh_net_outflow_share': return bo.n1 > 0 ? netOutflowN1 / bo.n1 : null;
case 'hh_inflow_total_share': return ti.n1 > 0 ? i.n1 / ti.n1 : null;
case 'hh_outflow_total_share': return to.n1 > 0 ? o.n1 / to.n1 : null;
// ── AGI ─────────────────────────────────────────────────────────────────
case 'agi_inflow': return i.AGI;
case 'agi_outflow': return o.AGI;
case 'agi_net_inflow': return netInflowAGI;
case 'agi_net_outflow': return netOutflowAGI;
case 'agi_inflow_share': return bo.AGI > 0 ? i.AGI / bo.AGI : null;
case 'agi_outflow_share': return bo.AGI > 0 ? o.AGI / bo.AGI : null;
case 'agi_net_inflow_share': return bo.AGI > 0 ? netInflowAGI / bo.AGI : null;
case 'agi_net_outflow_share': return bo.AGI > 0 ? netOutflowAGI / bo.AGI : null;
case 'agi_inflow_total_share': return ti.AGI > 0 ? i.AGI / ti.AGI : null;
case 'agi_outflow_total_share': return to.AGI > 0 ? o.AGI / to.AGI : null;
// ── Inbound / Outbound Rates ─────────────────────────────────────────────
case 'pop_inbound_rate': { const sum = i.n2 + o.n2; return sum > 0 ? i.n2 / sum : null; }
case 'pop_outbound_rate': { const sum = i.n2 + o.n2; return sum > 0 ? o.n2 / sum : null; }
case 'hh_inbound_rate': { const sum = i.n1 + o.n1; return sum > 0 ? i.n1 / sum : null; }
case 'hh_outbound_rate': { const sum = i.n1 + o.n1; return sum > 0 ? o.n1 / sum : null; }
case 'agi_inbound_rate': { const sum = i.AGI + o.AGI; return sum > 0 ? i.AGI / sum : null; }
case 'agi_outbound_rate': { const sum = i.AGI + o.AGI; return sum > 0 ? o.AGI / sum : null; }
// ── Average AGI ─────────────────────────────────────────────────────────
case 'avg_agi_in_individual': return i.n2 > 0 ? i.AGI / i.n2 : null;
case 'avg_agi_in_household': return i.n1 > 0 ? i.AGI / i.n1 : null;
case 'avg_agi_out_individual': return o.n2 > 0 ? o.AGI / o.n2 : null;
case 'avg_agi_out_household': return o.n1 > 0 ? o.AGI / o.n1 : null;
// ── Ratio of Average AGIs ───────────────────────────────────────────────
case 'agi_ratio_in_out_individual': {
const avgIn = i.n2 > 0 ? i.AGI / i.n2 : 0;
const avgOut = o.n2 > 0 ? o.AGI / o.n2 : 0;
return avgOut > 0 ? avgIn / avgOut : null;
}
case 'agi_ratio_in_out_household': {
const avgIn = i.n1 > 0 ? i.AGI / i.n1 : 0;
const avgOut = o.n1 > 0 ? o.AGI / o.n1 : 0;
return avgOut > 0 ? avgIn / avgOut : null;
}
case 'agi_ratio_out_in_individual': {
const avgIn = i.n2 > 0 ? i.AGI / i.n2 : 0;
const avgOut = o.n2 > 0 ? o.AGI / o.n2 : 0;
return avgIn > 0 ? avgOut / avgIn : null;
}
case 'agi_ratio_out_in_household': {
const avgIn = i.n1 > 0 ? i.AGI / i.n1 : 0;
const avgOut = o.n1 > 0 ? o.AGI / o.n1 : 0;
return avgIn > 0 ? avgOut / avgIn : null;
}
default:
console.warn(`computeMetric: unknown metric key "${metricKey}"`);
return null;
}
}