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; } export interface LinearModel { method_id: string; method_version: string; validation_track: string; evaluation_protocol_id: string; frozen_split_sha256: string; cell_features: Record; items: Record; } 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(); 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), })); }