File size: 29,540 Bytes
5693bf5
 
 
 
 
 
 
 
 
 
3da93de
 
 
1e946ed
25388f9
3da93de
5693bf5
3da93de
 
5693bf5
 
 
 
 
3da93de
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
 
5693bf5
 
 
 
 
 
3da93de
 
 
 
 
 
 
 
 
 
 
 
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
 
5693bf5
 
3da93de
 
 
 
 
5693bf5
 
 
 
3da93de
 
5693bf5
 
3da93de
1e946ed
 
 
 
5693bf5
 
 
3da93de
5693bf5
 
 
 
 
 
 
 
3da93de
5693bf5
3da93de
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
5693bf5
3da93de
 
5693bf5
3da93de
 
5693bf5
3da93de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5693bf5
 
 
 
 
 
 
 
 
 
3da93de
 
5693bf5
 
 
3da93de
 
 
5693bf5
3da93de
 
 
 
 
 
 
5693bf5
 
 
3da93de
5693bf5
 
 
 
3da93de
5693bf5
 
 
 
 
3da93de
 
 
 
5693bf5
 
 
 
 
3da93de
 
 
 
 
 
 
 
5693bf5
 
3da93de
 
 
 
 
 
5693bf5
 
3da93de
 
 
 
5693bf5
3da93de
 
5693bf5
3da93de
5693bf5
3da93de
 
 
 
 
 
 
 
 
 
5693bf5
 
 
3da93de
 
 
 
 
 
 
 
5693bf5
3da93de
5693bf5
 
 
 
 
3da93de
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
 
5693bf5
 
3da93de
 
5693bf5
 
 
 
3da93de
5693bf5
3da93de
 
 
5693bf5
 
 
 
3da93de
 
 
 
 
 
 
5693bf5
 
 
 
3da93de
 
 
 
 
 
 
 
 
 
 
5693bf5
 
 
 
 
 
3da93de
5693bf5
3da93de
5693bf5
 
 
3da93de
 
 
5693bf5
 
 
 
 
 
 
 
3da93de
 
5693bf5
 
 
3da93de
 
 
5693bf5
 
 
 
 
 
 
 
 
 
 
3da93de
 
 
5693bf5
 
 
 
 
3da93de
5693bf5
3da93de
5693bf5
3da93de
5693bf5
 
 
 
 
 
 
 
 
 
 
 
 
3da93de
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
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
import data from './benchmark.json';
import challenge from './challenge.json';
import { scoreSubmission } from './challenge';
import { age65Composition, aggregate, type Frame, type LinearModel, type ResponseQuestion } from './runtime';
import { fieldwork, type PreparationInput } from './preparation';
import './style.css';

const model = data.linear as LinearModel;
const frame = data.population as Frame;
const questions: ResponseQuestion[] = data.questions;
const datasetUrl = 'https://huggingface.co/datasets/Giuliocc/windtunnel-ces-cross-wave/tree/aaad117e1fdc8ff76eedf283dc1fe931dfce756c';
const crossWaveModelUrl = 'https://huggingface.co/Giuliocc/windtunnel-response-cross-wave/tree/3078a5e449a3001f53b79c675f6f0f93012ad790';
const pollingAppUrl = 'https://windtunnel.tacitus.me/poll';
const disclosureAppUrl = 'https://windtunnel.tacitus.me/research/new?starter=disclosure';
const transferEvidenceUrl = 'https://huggingface.co/datasets/Giuliocc/windtunnel-response-data/tree/49d71ee3e38e8dfd3924021b13eb2ce7c98af5d6/external/htops-transfer-v1';
const answerAudience = 'All held-out CES answerers';
type Mode = 'observed' | 'prediction' | 'composition' | 'failure' | 'policy' | 'ad' | 'challenge';
type EvidenceMode = Exclude<Mode, 'policy' | 'ad' | 'challenge'>;
type Series = { name: string; shares: number[]; className: 'observed' | 'predicted' | 'reference' };
const examples: { id: Mode; label: string }[] = [
  { id: 'observed', label: 'Human evidence' },
  { id: 'prediction', label: 'Known-item estimate' },
  { id: 'composition', label: 'Composition scenario' },
  { id: 'failure', label: 'Model failure' },
  { id: 'policy', label: 'New question' },
  { id: 'ad', label: 'Commercial creative' },
  { id: 'challenge', label: 'Test your model' },
];

function element<K extends keyof HTMLElementTagNameMap>(tag: K, copy?: string, className?: string) {
  const node = document.createElement(tag);
  if (copy !== undefined) node.textContent = copy;
  if (className) node.className = className;
  return node;
}

function link(label: string, url: string) {
  const node = element('a', label);
  node.href = url;
  return node;
}

function download(filename: string, blob: Blob) {
  const object = URL.createObjectURL(blob);
  const file = link('', object);
  file.download = filename;
  file.click();
  setTimeout(() => URL.revokeObjectURL(object), 1000);
}

function save(filename: string, value: unknown) {
  download(filename, new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' }));
}

function step(heading: string, number: number) {
  const title = element('h2', heading, 'step-heading');
  const mark = element('span', String(number), 'step-number');
  mark.setAttribute('aria-hidden', 'true');
  title.prepend(mark);
  return title;
}

function button(label: string, handler: () => void) {
  const action = element('button', label);
  action.type = 'button';
  action.addEventListener('click', handler);
  return action;
}

const app = document.querySelector<HTMLDivElement>('#app')!;
const header = element('header');
const brand = element('a', 'Wind Tunnel', 'brand');
brand.href = './';
const logo = element('span', undefined, 'kite');
logo.setAttribute('aria-hidden', 'true');
brand.prepend(logo);
header.append(brand, element('span', 'RESPONSE LAB', 'edition'));
const main = element('main');
main.id = 'main';
const hero = element('section', undefined, 'hero');
hero.append(element('h1', 'Wind Tunnel polling lab'),
  element('p', 'Pick a real survey question, choose a demographic audience, and explore how answers are distributed. Bring a new question to draft a study.', 'dek'));
const choices = element('nav', undefined, 'examples');
choices.setAttribute('aria-label', 'Worked examples');
const primary = element('div', undefined, 'primary-options');
const advanced = element('details', undefined, 'advanced');
const additional = element('div', undefined, 'extra-options');
advanced.append(element('summary', 'Advanced settings and benchmarks'), additional);
choices.append(primary, advanced);
const grid = element('div', undefined, 'workbench');
const controls = element('section', undefined, 'panel controls');
const output = element('section', undefined, 'panel output');
grid.append(controls, output);
const announcement = element('p', undefined, 'sr-only');
announcement.setAttribute('role', 'status');
const footer = element('footer');
footer.append(element('p', 'Source data and methods'), link('CES 2024 Common Content V9', data.source.canonical_url),
  link('ACS 2024 one-year PUMS', 'https://www.census.gov/programs-surveys/acs/microdata/access.2024.html'),
  link('CES cross-wave dataset', datasetUrl), link('CES cross-wave research model', crossWaveModelUrl),
  link('External Census HTOPS transfer check', transferEvidenceUrl),
  element('p', 'The experimental encoder scored slightly worse than uniform on four external HTOPS questions. Use actual customer responses to assess billing comprehension.', 'muted'),
  link('Prepare a human billing-disclosure comparison', disclosureAppUrl));
for (const artifact of (data as typeof data & { artifacts?: { label: string; url: string }[] }).artifacts ?? []) {
  footer.append(link(artifact.label, artifact.url));
}
main.append(hero, choices, grid, announcement, footer);
const skip = link('Skip to research lab', '#main');
skip.className = 'skip';
app.append(skip, header, main);

function percent(value: number) {
  return `${(100 * value).toFixed(1)}%`;
}

function chart(question: ResponseQuestion, series: Series[]) {
  const figure = element('figure');
  figure.append(element('figcaption', 'Share of recorded answers', 'chart-caption'));
  for (const [index, option] of question.options.entries()) {
    const group = element('div', undefined, 'option');
    group.append(element('h3', option.label));
    for (const row of series) {
      const value = element('div', undefined, 'bar-row');
      const rail = element('span', undefined, 'rail');
      rail.setAttribute('aria-hidden', 'true');
      const bar = element('span', undefined, `bar ${row.className}`);
      bar.style.width = percent(row.shares[index]);
      rail.append(bar);
      value.append(element('span', row.name), rail, element('strong', percent(row.shares[index])));
      group.append(value);
    }
    figure.append(group);
  }
  return figure;
}

function exportChart(filename: string, question: ResponseQuestion, title: string, audience: string, description: string, series: Series[]) {
  const canvas = document.createElement('canvas');
  const drawing = canvas.getContext('2d');
  if (!drawing) return;
  const context = drawing;
  const width = 1120;
  const gutter = 56;
  const maxText = width - gutter * 2;
  function wrap(copy: string, font: string) {
    context.font = font;
    const lines: string[] = [];
    let line = '';
    for (const word of copy.split(/\s+/)) {
      const next = line ? `${line} ${word}` : word;
      if (line && context.measureText(next).width > maxText) {
        lines.push(line);
        line = word;
      } else line = next;
    }
    if (line) lines.push(line);
    return lines;
  }
  const instrument = [question.preceding_context, question.question_text, question.stimulus_text]
    .filter(Boolean).flatMap(copy => wrap(copy, '25px system-ui'));
  const detail = wrap(description, '22px system-ui');
  const groupHeight = 52 + series.length * 38;
  canvas.width = width;
  canvas.height = 274 + (instrument.length + detail.length) * 34 + question.options.length * groupHeight;
  context.fillStyle = '#fff';
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.textBaseline = 'top';
  let y = gutter;
  function line(copy: string, font: string, fill = '#172f31', x = gutter) {
    context.fillStyle = fill;
    context.font = font;
    context.fillText(copy, x, y);
  }
  line('WIND TUNNEL 路 CES 2024 V9', '700 20px system-ui', '#155d57');
  y += 42;
  line(title, 'bold 42px Georgia');
  y += 66;
  for (const copy of instrument) {
    line(copy, '25px system-ui');
    y += 34;
  }
  line(audience, '700 24px system-ui');
  y += 46;
  const colors = { observed: '#27766d', predicted: '#486b9a', reference: '#9a631e' };
  for (const [index, option] of question.options.entries()) {
    line(option.label, '700 24px system-ui');
    y += 38;
    for (const value of series) {
      line(value.name, '20px system-ui');
      context.fillStyle = '#e7ece8';
      context.fillRect(gutter + 228, y + 5, 660, 16);
      context.fillStyle = colors[value.className];
      context.fillRect(gutter + 228, y + 5, 660 * value.shares[index], 16);
      context.textAlign = 'right';
      line(percent(value.shares[index]), '700 22px system-ui', '#172f31', width - gutter);
      context.textAlign = 'left';
      y += 38;
    }
    y += 14;
  }
  for (const copy of detail) {
    line(copy, '22px system-ui', '#4b6160');
    y += 34;
  }
  y += 12;
  line(`Historical survey evidence 路 ${question.question_id} 路 doi.org/10.7910/DVN/X11EP6`, '20px system-ui', '#4b6160');
  canvas.toBlob(blob => { if (blob) download(filename, blob); }, 'image/png');
}

let mode: Mode = 'prediction';

function renderChallenge() {
  const input = element('input');
  input.type = 'file';
  input.id = 'submission';
  input.accept = '.json,application/json';
  const label = element('label', 'Prediction JSON');
  label.htmlFor = input.id;
  const template = {
    challenge_revision: challenge.revision,
    predictions: challenge.rows.map(row => ({ row_id: row.row_id, probabilities: null })),
  };
  const example = {
    ...template,
    predictions: challenge.rows.map(row => ({ row_id: row.row_id, probabilities: row.baseline })),
  };
  controls.replaceChildren(element('h2', 'Test your model'),
    element('p', 'Score predictions locally against published CES holdout distributions. Enter probabilities in the published option order. Use null to abstain.'),
    button('Download template', () => save('windtunnel-submission.json', template)),
    button('Download challenge data', () => save('windtunnel-challenge.json', challenge)), label, input);
  const render = (submission: unknown) => {
    if (mode !== 'challenge') return;
    const report = scoreSubmission(challenge, submission);
    const metrics = report.metrics;
    output.replaceChildren(element('h2', 'Benchmark scorecard'),
      element('p', `${report.scored_rows} of ${report.expected_rows} rows scored 路 ${percent(report.coverage)} coverage`),
      element('p', 'This retrospective benchmark publishes its labels for reproducibility.'),
      ...(!metrics ? [] : [
        element('p', `Your within-cell total variation: ${percent(metrics.submission.total_variation)}`),
        element('p', `Fitted baseline on the same rows: ${percent(metrics.reference.total_variation)}`),
        element('p', `Expected half Brier: ${metrics.submission.half_multiclass_brier?.toFixed(4)} 路 fitted baseline ${metrics.reference.half_multiclass_brier?.toFixed(4)}`),
      ]),
      button('Download scorecard', () => save('windtunnel-scorecard.json', report)));
  };
  controls.append(button('Run fitted baseline example', () => render(example)));
  input.addEventListener('change', () => {
    const file = input.files?.[0];
    if (!file) return;
    void (async () => {
      try {
        if (file.size > 200_000) throw new Error('Choose a JSON file smaller than 200 KB.');
        render(JSON.parse(await file.text()));
      } catch (error) {
        if (mode === 'challenge') output.replaceChildren(element('h2', 'Prediction file could not be scored'),
          element('p', error instanceof Error ? error.message : 'Check the submission template.', 'failure'));
      }
    })();
  });
  output.replaceChildren(element('h2', 'Benchmark scorecard'),
    element('p', `${challenge.rows.length} survey-question 脳 population-cell rows are available. Upload predictions or run the fitted baseline example.`));
}

function setMode(next: Mode) {
  mode = next;
  for (const item of choices.querySelectorAll('button')) item.setAttribute('aria-pressed', String(item.dataset.mode === next));
  if (next === 'policy' || next === 'ad') {
    preparation(next);
    return;
  }
  if (next === 'challenge') {
    renderChallenge();
    return;
  }
  const select = element('select');
  select.id = 'question';
  for (const question of questions) {
    const option = element('option', question.stimulus_text || question.question_text);
    option.value = question.question_id;
    select.append(option);
  }
  select.value = data.examples[next];
  const label = element('label', 'Published survey question');
  label.htmlFor = select.id;
  const selected = element('p', undefined, 'selected-question');
  const exact = element('details', undefined, 'instrument');
  const population = element('div', undefined, 'population');
  controls.replaceChildren(step('Question', 1), label, select, selected, exact,
    step('Demographic audience', 2), population);
  const view = next;
  const audience = element('select');
  audience.id = 'audience';
  const audienceLabel = element('label', 'Age and education');
  audienceLabel.htmlFor = audience.id;
  const full = element('option', answerAudience);
  full.value = '';
  audience.append(full);
  for (const age of new Set(frame.cells.map(cell => cell.age))) {
    const group = element('optgroup');
    group.label = age === '65+' ? 'Age 65+' : `Ages ${age}`;
    for (const cell of frame.cells.filter(cell => cell.age === age)) {
      const option = element('option', `${cell.age} 路 ${cell.education}`);
      option.value = cell.cell_id;
      group.append(option);
    }
    audience.append(group);
  }
  const sliderLabel = element('label');
  sliderLabel.htmlFor = 'composition';
  const slider = element('input');
  slider.type = 'range';
  slider.id = 'composition';
  slider.min = '0';
  slider.max = '30';
  slider.value = '15';
  function render() {
    const question = questions.find(q => q.question_id === select.value)!;
    selected.textContent = question.stimulus_text || question.question_text;
    exact.replaceChildren(element('summary', 'Exact wording and answer choices'));
    if (question.preceding_context) exact.append(element('p', question.preceding_context, 'muted'));
    exact.append(element('p', question.question_text, 'stem'));
    if (question.stimulus_text) exact.append(element('blockquote', question.stimulus_text));
    const options = element('ul', undefined, 'instrument-options');
    for (const option of question.options) options.append(element('li', option.label));
    exact.append(options);
    sliderLabel.textContent = `Increase the weight of age 65+ cells by ${slider.value}%`;
    result(question, view, Number(slider.value), audience.value);
  }
  if (view === 'prediction') {
    population.append(audienceLabel, audience, element('p', 'U.S. citizen adults in the 2024 CES. Select one age-and-education group to see its model estimate and evidence coverage.', 'muted'));
  } else {
    population.append(element('p', view === 'composition' ? frame.universe : 'CES citizen adult answerers 路 50 states and DC'),
      element('p', view === 'composition' ? '2024 one-year ACS PUMS 路 experimental sensitivity scenario' : 'October 1鈥揘ovember 4, 2024 路 weighted held-out records', 'muted'));
  }
  if (view === 'composition') population.append(sliderLabel, slider);
  select.addEventListener('change', render);
  audience.addEventListener('change', render);
  slider.addEventListener('input', render);
  render();
}

function result(question: ResponseQuestion, view: EvidenceMode, adjustment: number, cellId: string) {
  const key = question.question_id as keyof typeof data.rows;
  const row = data.rows[key];
  const observed = row.observed.probabilities;
  const candidate = model.items[key].champion;
  const replayCells = Object.keys(model.cell_features).map((cell_id, i) => ({ cell_id, population_mass: row.test_answerer_mix[i] }));
  const cell = frame.cells.find(item => item.cell_id === cellId);
  const replay = cell
    ? aggregate(model, question, [{ cell_id: cell.cell_id, population_mass: 1 }], candidate)
    : aggregate(model, question, replayCells, view === 'failure' ? 'linear' : candidate, false);
  const composition = view === 'composition' ? aggregate(model, question,
    age65Composition(frame, adjustment)) : null;
  const referenceComposition = composition ? aggregate(model, question, frame.cells) : null;
  const titles = { observed: 'Observed human evidence', prediction: 'Experimental model estimate',
    composition: 'Experimental composition sensitivity', failure: 'Where the model fails' };
  const groups = row.subgroups as Record<string, { n: number; tv: number }>;
  const group = cell ? groups[cell.cell_id] : undefined;
  const evidence = cell ? challenge.rows.find(item =>
    item.question_id === key && item.cell_id === cell.cell_id && item.instrument_hash === question.instrument_hash
    && item.option_ids.length === question.options.length
    && item.option_ids.every((id, index) => id === question.options[index].id)) : undefined;
  const support = cell ? model.items[key].training_support[cell.cell_id] : undefined;
  const bars: (Omit<Series, 'shares'> & { shares?: number[] | null })[] = view === 'composition'
    ? [{ name: 'Reference mix', shares: referenceComposition?.probabilities, className: 'observed' },
       { name: 'Adjusted mix', shares: composition?.probabilities, className: 'predicted' }]
    : cell ? [
      { name: 'Observed', shares: evidence?.observed, className: 'observed' },
      candidate === 'marginal'
        ? { name: 'Training baseline', shares: replay.probabilities, className: 'reference' }
        : { name: 'Model estimate', shares: replay.probabilities, className: 'predicted' },
    ]
    : [{ name: 'Observed', shares: observed, className: 'observed' },
       ...(view === 'observed' ? [] : [
         ...(candidate === 'marginal' && view === 'prediction'
           ? [{ name: 'Training baseline', shares: replay.probabilities, className: 'reference' as const }]
           : [{ name: 'Model estimate', shares: replay.probabilities, className: 'predicted' as const },
             { name: 'Training baseline', shares: row.candidates.marginal.prediction, className: 'reference' as const }]),
       ])];
  const audience = cell ? `Age ${cell.age} 路 ${cell.education}` : composition ? 'ACS adult citizen composition scenario' : answerAudience;
  const description = composition
    ? `Training support covers ${percent(composition?.coverage_fraction ?? 0)} of scenario weight. Cell-level response estimates stay fixed. The calculation assumes CES answerers represent responses within each bin.`
    : cell ? `${support?.answered.toLocaleString() ?? '0'} training answerers 路 ${evidence ? `${evidence.human_answered.toLocaleString()} held-out answerers` : 'held-out count withheld'} 路 CES 2024 V9`
    : `${row.observed.human_n_answered.toLocaleString()} held-out human answerers 路 commonweight 路 CES 2024 V9`;
  const scope = composition
    ? 'Historical composition sensitivity. The model holds responses within each demographic group fixed.'
    : view === 'observed' ? 'Weighted responses from a matched opt-in survey panel, fielded October鈥揘ovember 2024.'
    : cell ? candidate === 'marginal'
      ? 'This item uses the training baseline, which gives the same estimate for each supported group.'
      : 'Historical estimates for this demographic group. Current public opinion requires fresh fieldwork.'
    : 'Reconstruction of a historical survey using the held-out answerer mix. Current public opinion requires fresh fieldwork.';
  output.replaceChildren(step('Result', 3), element('h3', titles[view], 'result-title'),
    element('p', audience, 'audience-tag'), element('p', description, 'sample'));
  announcement.textContent = `${titles[view]} updated for ${audience}. ${description}.`;
  if (view === 'failure') output.append(element('p',
    `Across this item's cells, the fitted model missed ${percent(row.candidates.linear.within_cell_total_variation)} of probability mass on average. The aggregate gap was ${percent(row.candidates.linear.total_variation)}.`, 'failure'));
  const availableBars = bars.flatMap(value => value.shares ? [{ ...value, shares: value.shares }] : []);
  if (composition && !composition.probabilities) output.append(element('p', 'Adjusted estimate withheld because one or more cells lack training support.', 'failure'));
  if (cell && !replay.probabilities) output.append(element('p', 'Estimate withheld. This demographic group has insufficient training support for this question.', 'failure'));
  if (cell && !evidence) output.append(element('p', 'Held-out human shares are withheld for this demographic group.', 'scope-note'));
  const estimate = replay.probabilities;
  if (evidence && estimate) {
    const tv = evidence.observed.reduce((total, share, index) => total + Math.abs(share - estimate[index]), 0) / 2;
    output.append(element('p', `${percent(tv)} held-out distribution error (total variation)`, 'sample'));
  }
  if (availableBars.length) output.append(chart(question, availableBars));
  output.append(element('p', scope, 'scope-note'));
  const details = element('details');
  details.append(element('summary', 'Population coverage and subgroup errors'));
  const table = element('table');
  const tableHead = element('thead');
  const top = element('tr');
  for (const title of ['Population cell', 'PUMS share', 'Test answerers', 'Fitted model TV']) {
    const heading = element('th', title); heading.scope = 'col'; top.append(heading);
  }
  tableHead.append(top);
  const body = element('tbody');
  for (const cell of frame.cells) {
    const entry = element('tr');
    const statistics = groups[cell.cell_id];
    const cellLabel = element('th', `${cell.age} 路 ${cell.education}`);
    cellLabel.scope = 'row';
    entry.append(cellLabel, element('td', percent(cell.population_mass / frame.population_mass)),
      element('td', statistics ? statistics.n.toLocaleString() : 'Withheld'),
      element('td', statistics ? percent(statistics.tv) : 'Withheld'));
    body.append(entry);
  }
  table.append(tableHead, body);
  details.append(table);
  if (row.subgroup_suppression) details.append(element('p', row.subgroup_suppression, 'muted'));
  const method = element('details');
  const modelSource = element('p');
  modelSource.append(link('Published model used in this lab', 'https://huggingface.co/Giuliocc/windtunnel-response-baseline/tree/07f15115e2876e8a37de739c0574fb104b99995b'));
  method.append(element('summary', 'Method and limitations'), element('p', question.response_estimand),
    element('p', data.source.design), element('p', 'The held-out mix uses observed answerer weights. ACS composition scenarios are assumption-sensitive and are evaluated separately from held-out reconstruction.'),
    link('Published CES 2024 response dataset', 'https://huggingface.co/datasets/Giuliocc/windtunnel-response-data/tree/c9f07d8ffef1a26564d7b2c30f75914534dc265a'),
    modelSource,
    element('p', `Protocol ${model.evaluation_protocol_id} 路 Model SHA-256 ${data.model_artifact_sha256}`, 'digest'));
  const exportResult = () => save(`${key}-${view}.json`, {
    schema_version: 'windtunnel-response-lab-result-v1', run_id: crypto.randomUUID(),
    created_at: new Date().toISOString(), task_id: composition ? 'composition_sensitivity' : model.validation_track,
    status: !(composition ?? replay).probabilities ? 'insufficient_support' : view === 'observed' ? 'available' : 'experimental',
    result_kind: view === 'observed' ? 'observed_human' : 'model_estimate',
    instrument: question, evidence_source: data.source, human_evidence_ids: cell
      ? (evidence ? [evidence.row_id] : [])
      : [`${data.source.id}/${key}/test`],
    method_id: model.method_id, method_version: model.method_version, evaluation_protocol_id: model.evaluation_protocol_id,
    model_revision: data.local_model_revision, model_artifact_sha256: data.model_artifact_sha256,
    population_frame_id: composition ? frame.frame_id : 'ces-2024-v9-test-answerers',
    population_frame_revision: composition ? frame.revision : data.source.version,
    audience_cell_id: cell?.cell_id ?? null,
    audience_label: audience,
    observed_human: cell ? (evidence ? {
      probabilities: evidence.observed, human_n_answered: evidence.human_answered, weight_sum: evidence.weight,
    } : null) : row.observed,
    challenge_revision: evidence ? challenge.revision : null,
    coverage: composition ?? (cell ? replay : null), subgroup_errors: cell ? (group ? { [cell.cell_id]: group } : {}) : groups,
    option_probabilities: view === 'observed' ? null : composition ? composition.probabilities : replay.probabilities,
    series: availableBars, scenario_65_plus_weight_increase_percent: composition ? adjustment : null,
    limitations: composition ? frame.limitations : [data.source.design, question.response_estimand],
  });
  const actions = element('div', undefined, 'result-actions');
  const chartNotes = [
    description.endsWith('.') ? description : `${description}.`, scope,
    cell && !evidence ? 'Held-out human shares were withheld for this group.' : '',
    cell && !replay.probabilities ? 'The model estimate was withheld because training support was insufficient.' : '',
    composition && !composition.probabilities ? 'The adjusted estimate was withheld because training support was insufficient.' : '',
  ].filter(Boolean).join(' ');
  if (availableBars.length) actions.append(button('Save chart PNG', () => exportChart(
    `${key}-${cell?.cell_id ?? view}.png`, question, titles[view], audience, chartNotes, availableBars)));
  actions.append(button('Download result JSON', exportResult));
  output.append(actions, details, method);
}

function preparation(kind: 'policy' | 'ad') {
  const initial = data.examples[kind] as PreparationInput;
  const form = element('form');
  const fields = [
    ['stimulus', kind === 'policy' ? 'Your question or proposal' : 'Exact ad text'],
    ['population', 'Who should be included'],
    ['action', kind === 'policy' ? 'Action and implementing actor' : 'Offer and call to action'],
    ['conditions', 'Costs, conditions and timing'],
    ['outcome', 'Outcome to measure'],
  ] as const;
  const settings = element('details', undefined, 'fieldwork-settings');
  settings.append(element('summary', 'Fieldwork details'));
  form.append(step('Question', 1));
  for (const [key, title] of fields) {
    const label = element('label', title);
    label.htmlFor = key;
    const input = element(key === 'stimulus' ? 'textarea' : 'input');
    input.name = input.id = key;
    input.value = initial[key];
    input.maxLength = key === 'stimulus' ? 12000 : 1000;
    input.required = key !== 'conditions';
    if (key === 'population') form.append(step('Demographic audience', 2));
    (key === 'population' || key === 'stimulus' ? form : settings).append(label, input);
  }
  const submit = element('button', 'Prepare fieldwork');
  submit.type = 'submit';
  form.append(settings, submit);
  settings.addEventListener('invalid', () => { settings.open = true; }, true);
  controls.replaceChildren(form);
  function show(input: PreparationInput) {
    const pack = fieldwork(input);
    const list = element('ol');
    for (const q of pack.questionnaire) {
      const item = element('li', q.question);
      if (q.options.length) item.append(element('p', q.options.join(' 路 '), 'muted'));
      list.append(item);
    }
    const checks = element('ul');
    for (const note of pack.wording_review) checks.append(element('li', note));
    const context = element('details');
    const next = element('p', undefined, 'app-link');
    next.append(link('Open polling in Wind Tunnel', pollingAppUrl),
      element('span', 'Sign in to set up your question and review the quote before you run it.', 'muted'));
    const related = questions.filter(q => kind === 'policy' && q.question_family_id === 'tax_and_domestic_policy_battery');
    context.append(element('summary', 'Evidence scope and study design'), element('p', pack.measurement_plan.recruitment),
      element('p', pack.measurement_plan.assignment), element('p', pack.measurement_plan.analysis));
    if (related.length) context.append(element('p', 'Related policy measurement from CES 2024, using different instruments:'),
      ...related.map(q => element('blockquote', q.stimulus_text)));
    output.replaceChildren(step('Result', 3), element('h3', 'Research preparation', 'result-title'),
      element('p', pack.abstention_reasons[0], 'failure'), element('h3', 'Draft questionnaire'), list,
      element('h3', 'Review before fielding'), checks, context, next,
      button('Download fieldwork pack', () => save(`${kind}-fieldwork-pack.json`, pack)));
    announcement.textContent = 'Fieldwork draft updated. No response estimate is available for this question.';
  }
  form.addEventListener('submit', event => {
    event.preventDefault();
    const values = new FormData(form);
    show({ kind, stimulus: String(values.get('stimulus')), action: String(values.get('action')),
      population: String(values.get('population')), conditions: String(values.get('conditions')), outcome: String(values.get('outcome')) });
  });
  show(initial);
}

for (const example of examples) {
  const control = button(example.label, () => setMode(example.id));
  control.dataset.mode = example.id;
  (example.id === 'prediction' || example.id === 'policy' ? primary : additional).append(control);
}
setMode(mode);