File size: 4,769 Bytes
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export interface ResponseQuestion {
  question_id: string;
  question_family_id: string;
  question_text: string;
  stimulus_text: string;
  preceding_context: string;
  options: { id: string; label: string }[];
  language: string;
  instrument_hash: string;
  response_estimand: string;
  field_dates: string[];
  eligibility: string;
}

export interface ItemModel {
  instrument_hash: string;
  option_ids: string[];
  marginal: number[];
  coefficients: number[][];
  intercepts: number[];
  champion: 'linear' | 'marginal';
  training_support: Record<string, { answered: number; effective_n_weight_only: number; supported: boolean }>;
}

export interface LinearModel {
  method_id: string;
  method_version: string;
  validation_track: string;
  evaluation_protocol_id: string;
  frozen_split_sha256: string;
  cell_features: Record<string, number[]>;
  items: Record<string, ItemModel>;
}

export interface FrameCell {
  cell_id: string;
  age: string;
  education: string;
  population_mass: number;
  pums_unweighted_n: number;
}

export interface Frame {
  frame_id: string;
  revision: string;
  universe: string;
  population_mass: number;
  cells: FrameCell[];
  limitations: string[];
}

export function predictCell(model: LinearModel, question: ResponseQuestion, cell: string, candidate?: ItemModel['champion']) {
  const item = model.items[question.question_id];
  const features = model.cell_features[cell];
  if (!item || question.instrument_hash !== item.instrument_hash || !features
    || question.options.length !== item.option_ids.length
    || question.options.some((option, index) => option.id !== item.option_ids[index])) {
    throw new Error('Instrument or population cell is outside this model’s capability.');
  }
  if ((candidate ?? item.champion) === 'marginal') return item.marginal;
  const logits = item.coefficients.map((coefficients, option) =>
    coefficients.reduce((score, coefficient, index) => score + coefficient * features[index], item.intercepts[option]));
  const max = Math.max(...logits);
  const weights = logits.map(logit => Math.exp(logit - max));
  const total = weights.reduce((sum, weight) => sum + weight, 0);
  return weights.map(weight => weight / total);
}

export function sameInstrument(expected: ResponseQuestion, submitted: ResponseQuestion) {
  return expected.instrument_hash === submitted.instrument_hash && expected.question_id === submitted.question_id
    && expected.question_text === submitted.question_text && expected.stimulus_text === submitted.stimulus_text
    && expected.preceding_context === submitted.preceding_context && expected.language === submitted.language
    && expected.options.length === submitted.options.length
    && expected.options.every((option, index) => option.id === submitted.options[index].id && option.label === submitted.options[index].label);
}

export function aggregate(
  model: LinearModel,
  question: ResponseQuestion,
  cells: { cell_id: string; population_mass: number }[],
  candidate?: ItemModel['champion'],
  requireSupport = true,
) {
  const item = model.items[question.question_id];
  const ids = new Set<string>();
  let eligible = 0;
  let covered = 0;
  const unsupported: string[] = [];
  const sum = question.options.map(() => 0);
  for (const cell of cells) {
    const mass = cell.population_mass;
    if (!Number.isFinite(mass) || mass < 0 || ids.has(cell.cell_id) || !Object.hasOwn(model.cell_features, cell.cell_id)) {
      throw new Error('The composition must contain distinct recognized cells with finite nonnegative mass.');
    }
    ids.add(cell.cell_id);
    if (!mass) continue;
    eligible += mass;
    if (requireSupport && !item?.training_support[cell.cell_id]?.supported) {
      unsupported.push(cell.cell_id);
      continue;
    }
    predictCell(model, question, cell.cell_id, candidate).forEach((p, index) => { sum[index] += mass * p; });
    covered += mass;
  }
  if (!Number.isFinite(eligible) || eligible <= 0) throw new Error('The composition has no eligible mass.');
  return {
    probabilities: unsupported.length ? null : sum.map(value => value / covered),
    eligible_population_mass: eligible,
    covered_population_mass: covered,
    coverage_fraction: covered / eligible,
    unsupported_cells: unsupported,
  };
}

/** Adjust the relative mass of age 65+ cells before final normalization. */
export function age65Composition(frame: Frame, increasePercent: number) {
  if (!Number.isFinite(increasePercent) || increasePercent < 0 || increasePercent > 30) {
    throw new Error('The age 65+ scenario weight increase must be between 0% and 30%.');
  }
  return frame.cells.map(cell => ({
    ...cell,
    population_mass: cell.population_mass * (cell.age === '65+' ? 1 + increasePercent / 100 : 1),
  }));
}