tol = ({
QualBright: ['#4477AA', '#EE6677', '#228833', '#CCBB44', '#66CCEE','#AA3377'],
QualHighContrast: ['#004488', '#DDAA33', '#BB5566'],
QualVibrant: ['#EE7733', '#0077BB', '#33BBEE', '#EE3377', '#CC3311', '#009988'],
QualMuted: ['#CC6677', '#332288', '#DDCC77', '#117733', '#88CCEE','#882255', '#44AA99', '#999933', '#AA4499'],
QualLight: ['#77AADD', '#EE8866', '#EEDD88', '#FFAABB', '#99DDFF', '#44BB99', '#BBCC33', '#AAAA00'],
Sunset: ['#364B9A', '#4A7BB7', '#6EA6CD', '#98CAE1', '#C2E4EF', '#EAECCC', '#FEDA8B', '#FDB366', '#F67E4B', '#DD3D2D', '#A50026'],
BuRd: ['#2166AC', '#4393C3', '#92C5DE', '#D1E5F0', '#F7F7F7', '#FDDBC7', '#F4A582', '#D6604D', '#B2182B'],
PRGn: ['#762A83', '#9970AB', '#C2A5CF', '#E7D4E8', '#F7F7F7', '#D9F0D3', '#ACD39E', '#5AAE61', '#1B7837'],
YlOrBr: ['#FFFFE5', '#FFF7BC', '#FEE391', '#FEC44F', '#FB9A29',
'#EC7014', '#CC4C02', '#993404', '#662506'],
Iridescent: ['#FEFBE9', '#FCF7D5', '#F5F3C1', '#EAF0B5', '#DDECBF',
'#D0E7CA', '#C2E3D2', '#B5DDD8', '#A8D8DC', '#9BD2E1',
'#8DCBE4', '#81C4E7', '#7BBCE7', '#7EB2E4', '#88A5DD',
'#9398D2', '#9B8AC4', '#9D7DB2', '#9A709E', '#906388',
'#805770', '#684957', '#46353A'],
RainbowPuRd: ['#6F4C9B', '#6059A9', '#5568B8', '#4E79C5', '#4D8AC6',
'#4E96BC', '#549EB3', '#59A5A9', '#60AB9E', '#69B190',
'#77B77D', '#8CBC68', '#A6BE54', '#BEBC48', '#D1B541',
'#DDAA3C', '#E49C39', '#E78C35', '#E67932', '#E4632D',
'#DF4828', '#DA2222'],
RainbowPuBr: ['#6F4C9B', '#6059A9', '#5568B8', '#4E79C5', '#4D8AC6',
'#4E96BC', '#549EB3', '#59A5A9', '#60AB9E', '#69B190',
'#77B77D', '#8CBC68', '#A6BE54', '#BEBC48', '#D1B541',
'#DDAA3C', '#E49C39', '#E78C35', '#E67932', '#E4632D',
'#DF4828', '#DA2222', '#B8221E', '#95211B', '#721E17',
'#521A13'],
RainbowWhRd: ['#E8ECFB', '#DDD8EF', '#D1C1E1', '#C3A8D1', '#B58FC2',
'#A778B4', '#9B62A7', '#8C4E99', '#6F4C9B', '#6059A9',
'#5568B8', '#4E79C5', '#4D8AC6', '#4E96BC', '#549EB3',
'#59A5A9', '#60AB9E', '#69B190', '#77B77D', '#8CBC68',
'#A6BE54', '#BEBC48', '#D1B541', '#DDAA3C', '#E49C39',
'#E78C35', '#E67932', '#E4632D', '#DF4828', '#DA2222'],
RainbowDiscrete: ['#E8ECFB', '#D9CCE3', '#D1BBD7', '#CAACCB', '#BA8DB4',
'#AE76A3', '#AA6F9E', '#994F88', '#882E72', '#1965B0',
'#437DBF', '#5289C7', '#6195CF', '#7BAFDE', '#4EB265',
'#90C987', '#CAE0AB', '#F7F056', '#F7CB45', '#F6C141',
'#F4A736', '#F1932D', '#EE8026', '#E8601C', '#E65518',
'#DC050C', '#A5170E', '#72190E', '#42150A']
})function interval(range = [], options = {}) {
const [min = 0, max = 1] = range;
const {
step = .001,
label = null,
value = [min, max],
format = ([start, end]) => `${start} … ${end}`,
color,
width,
theme,
__ns__ = randomScope(),
} = options;
const css = `
#${__ns__} {
//font: 13px/1.2 var(--sans-serif);
display: flex;
align-items: baseline;
flex-wrap: wrap;
max-width: 100%;
width: auto;
flex-direction: column;
}
@media only screen and (min-width: 30em) {
#${__ns__} {
flex-wrap: nowrap;
width: 360px;
}
}
#${__ns__} .label {
//width: 120px;
//padding: 5px 0 4px 0;
//padding: 5px 0 0 0;
//margin-right: 6.5px;
flex-shrink: 0;
}
#${__ns__} .form {
display: flex;
width: 100%;
}
#${__ns__} .range {
flex-shrink: 1;
width: 100%;
}
#${__ns__} .range-slider {
width: 100%;
margin-bottom: .3em;
margin-top: .3em;
}
`;
const $range = rangeInput({min, max, value: [value[0], value[1]], step, color, width, theme});
const $output = html`<output>`;
const $view = html`<div id=${__ns__}>
${label == null ? '' : html`<div class="label">${label}`}
<div class=form>
<div class=range>
${$range}<div class=range-output>${$output}</div>
</div>
</div>
${html`<style>${css}`}
`;
const update = () => {
const content = format([$range.value[0], $range.value[1]]);
if(typeof content === 'string') $output.value = content;
else {
while($output.lastChild) $output.lastChild.remove();
$output.appendChild(content);
}
};
$range.oninput = update;
// the slider only fires input on release, so follow its drags for the readout
$range.addEventListener('dragging', update);
update();
return Object.defineProperty($view, 'value', {
get: () => $range.value,
set: ([a, b]) => {
$range.value = [a, b];
update();
},
});
}
// date version of interval. the underlying input only handles numbers, so work
// in epoch milliseconds internally and report the value as dates. step is in
// days, and the range is widened to whole UTC days so values land on dates.
function dateInterval(range = [], options = {}) {
const day = 864e5;
const fmtDate = d3.utcFormat("%Y-%m-%d");
const [min, max] = [d3.utcDay.floor(range[0]), d3.utcDay.ceil(range[1])];
const {
step = 1,
value = [min, max],
format = ([start, end]) => `${fmtDate(start)} … ${fmtDate(end)}`,
...rest
} = options;
const $interval = interval([+min, +max], {
...rest,
step: step * day,
// widen outward, else the slider snaps to the nearest day and clips the ends
value: [+d3.utcDay.floor(value[0]), +d3.utcDay.ceil(value[1])],
format: ([start, end]) => format([new Date(start), new Date(end)]),
});
// input events bubble up from the slider, so the wrapper works as a viewof
const $view = html`<div>${$interval}`;
return Object.defineProperty($view, 'value', {
get: () => $interval.value.map(ms => new Date(ms)),
set: ([a, b]) => {
$interval.value = [+a, +b];
},
});
}
function rangeInput(options = {}) {
const {
min = 0,
max = 100,
step = 'any',
value: defaultValue = [min, max],
color,
width,
theme = theme_Flat,
} = options;
const controls = {};
const scope = randomScope();
const clamp = (a, b, v) => v < a ? a : v > b ? b : v;
// Will be used to sanitize values while avoiding floating point issues.
const input = html`<input type=range ${{min, max, step}}>`;
const dom = html`<div class=${`${scope} range-slider`} style=${{
color,
width: cssLength(width),
}}>
${controls.track = html`<div class="range-track">
${controls.zone = html`<div class="range-track-zone">
${controls.range = html`<div class="range-select" tabindex=0>
${controls.min = html`<div class="thumb thumb-min" tabindex=0>`}
${controls.max = html`<div class="thumb thumb-max" tabindex=0>`}
`}
`}
`}
${html`<style>${theme.replace(/:scope\b/g, '.'+scope)}`}
</div>`;
let value = [], changed = false, dragging = false;
Object.defineProperty(dom, 'value', {
get: () => [...value],
set: ([a, b]) => {
value = sanitize(a, b);
updateRange();
},
});
const sanitize = (a, b) => {
a = isNaN(a) ? min : ((input.value = a), input.valueAsNumber);
b = isNaN(b) ? max : ((input.value = b), input.valueAsNumber);
return [Math.min(a, b), Math.max(a, b)];
}
const updateRange = () => {
const ratio = v => (v - min) / (max - min);
dom.style.setProperty('--range-min', `${ratio(value[0]) * 100}%`);
dom.style.setProperty('--range-max', `${ratio(value[1]) * 100}%`);
};
const dispatch = name => {
dom.dispatchEvent(new Event(name, {bubbles: true}));
};
const setValue = (vmin, vmax) => {
const [pmin, pmax] = value;
value = sanitize(vmin, vmax);
updateRange();
// Only dispatch if values have changed.
if(pmin === value[0] && pmax === value[1]) return;
// mid-drag this only moves the readout; 'input' (which downstream cells
// recompute on) fires once on release rather than on every step crossed
dispatch(dragging ? 'dragging' : 'input');
changed = true;
};
setValue(...defaultValue);
// Mousemove handlers.
const handlers = new Map([
[controls.min, (dt, ov) => {
const v = clamp(min, ov[1], ov[0] + dt * (max - min));
setValue(v, ov[1]);
}],
[controls.max, (dt, ov) => {
const v = clamp(ov[0], max, ov[1] + dt * (max - min));
setValue(ov[0], v);
}],
[controls.range, (dt, ov) => {
const d = ov[1] - ov[0];
const v = clamp(min, max - d, ov[0] + dt * (max - min));
setValue(v, v + d);
}],
]);
// Returns client offset object.
const pointer = e => e.touches ? e.touches[0] : e;
// Note: Chrome defaults "passive" for touch events to true.
const on = (e, fn) => e.split(' ').map(e => document.addEventListener(e, fn, {passive: false}));
const off = (e, fn) => e.split(' ').map(e => document.removeEventListener(e, fn, {passive: false}));
let initialX, initialV, target;
function handleDrag(e) {
// Gracefully handle exit and reentry of the viewport.
if(!e.buttons && !e.touches) {
handleDragStop();
return;
}
dragging = true;
const w = controls.zone.getBoundingClientRect().width;
e.preventDefault();
handlers.get(target)((pointer(e).clientX - initialX) / w, initialV);
}
function handleDragStop(e) {
off('mousemove touchmove', handleDrag);
off('mouseup touchend', handleDragStop);
if(changed) {
dispatch('input');
dispatch('change');
}
}
invalidation.then(handleDragStop);
dom.ontouchstart = dom.onmousedown = e => {
dragging = false;
changed = false;
if(!handlers.has(e.target)) return;
on('mousemove touchmove', handleDrag);
on('mouseup touchend', handleDragStop);
e.preventDefault();
e.stopPropagation();
target = e.target;
initialX = pointer(e).clientX;
initialV = value.slice();
};
controls.track.onclick = e => {
if(dragging) return;
changed = false;
const r = controls.zone.getBoundingClientRect();
const t = clamp(0, 1, (pointer(e).clientX - r.left) / r.width);
const v = min + t * (max - min);
const [vmin, vmax] = value, d = vmax - vmin;
if(v < vmin) setValue(v, v + d);
else if(v > vmax) setValue(v - d, v);
if(changed) dispatch('change');
};
return dom;
}
function randomScope(prefix = 'scope-') {
return prefix + (performance.now() + Math.random()).toString(32).replace('.', '-');
}
cssLength = v => v == null ? null : typeof v === 'number' ? `${v}px` : `${v}`
html = htl.html
theme_Flat = `
/* Options */
:scope {
color: #3b99fc;
width: 240px;
}
:scope {
position: relative;
display: inline-block;
--thumb-size: 15px;
--thumb-radius: calc(var(--thumb-size) / 2);
//padding: var(--thumb-radius) 0;
margin: 2px;
vertical-align: middle;
}
:scope .range-track {
box-sizing: border-box;
position: relative;
height: 7px;
background-color: hsl(0, 0%, 80%);
overflow: visible;
border-radius: 4px;
padding: 0 var(--thumb-radius);
}
:scope .range-track-zone {
box-sizing: border-box;
position: relative;
}
:scope .range-select {
box-sizing: border-box;
position: relative;
left: var(--range-min);
width: calc(var(--range-max) - var(--range-min));
cursor: ew-resize;
background: currentColor;
height: 7px;
border: inherit;
}
/* Expands the hotspot area. */
:scope .range-select:before {
content: "";
position: absolute;
width: 100%;
height: var(--thumb-size);
left: 0;
top: calc(2px - var(--thumb-radius));
}
:scope .range-select:focus,
:scope .thumb:focus {
outline: none;
}
:scope .thumb {
box-sizing: border-box;
position: absolute;
width: var(--thumb-size);
height: var(--thumb-size);
background: #fcfcfc;
top: -4px;
border-radius: 100%;
border: 1px solid hsl(0,0%,55%);
cursor: default;
margin: 0;
}
:scope .thumb:active {
box-shadow: inset 0 var(--thumb-size) #0002;
}
:scope .thumb-min {
left: calc(-1px - var(--thumb-radius));
}
:scope .thumb-max {
right: calc(-1px - var(--thumb-radius));
}
`ns = Inputs.text().classList[0]
// custom css to override some ojs defaults for inputs
html`<style>
.${ns} {
--label-width: 80px;
}
form.${ns} {
flex-wrap: wrap;
}
/* label above options -- add stacked-input to an input elsewhere to get this */
.plot-inputs form.${ns},
form.${ns}.stacked-input {
flex-direction: column;
}
/* inputs' forms center their items, which in a column centers the options */
form.${ns}.stacked-input {
align-items: flex-start;
}
.${ns} div label {
background-color: #f4f4f4;
padding: 0.25rem 0.5rem;
border-radius: 0.5rem;
margin-right: 0.25rem;
margin-bottom: 0.25rem;
width: auto;
}
.${ns} div label:hover,
.${ns} div label:active,
.${ns} div label:focus {
background-color: #fbe4b4;
}
.${ns} input[type="checkbox"] {
accent-color: black;
margin-bottom: 0;
}
.${ns} div input[type="number"] {
background-color: #f4f4f4;
padding: 0.25rem 0.5rem;
border-radius: 0.5rem;
flex-shrink: 3;
border: none;
}
/* wide enough for 3-4 digit values, which the shrink above would cut off */
.${ns} div input[type="number"] {
flex-shrink: 0;
width: 4.5em;
}
/* single ended sliders, styled to match the double ended ones in _interval:
the track is filled up to the thumb centre, given by --fill (0 to 1), which
has to be set from js since browsers other than firefox have no fill element */
.${ns} input[type="range"] {
-webkit-appearance: none;
appearance: none;
height: 7px;
border-radius: 4px;
--fill-px: calc(7.5px + var(--fill, 0) * (100% - 15px));
background: linear-gradient(to right, #f7ca69 var(--fill-px), hsl(0, 0%, 80%) var(--fill-px));
}
.${ns} input[type="range"]::-moz-range-track {
background: transparent;
}
.${ns} input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 15px;
height: 15px;
border-radius: 100%;
background: #fcfcfc;
border: 1px solid hsl(0, 0%, 55%);
}
.${ns} input[type="range"]::-moz-range-thumb {
box-sizing: border-box;
width: 15px;
height: 15px;
border-radius: 100%;
background: #fcfcfc;
border: 1px solid hsl(0, 0%, 55%);
}
.${ns} select {
background-color: #f4f4f4;
border: none;
border-radius: 0.5rem;
padding: 0.25rem 0.5rem;
//width: auto;
}
.${ns} .hist {
width: 100%;
display: flex;
flex-direction: column;
row-gap: 0em;
}
</style>`// keeps an input's value in a URL parameter, so that links to the page can
// share its state. on creation the input is set from the parameter (if valid),
// and the parameter is updated whenever the input changes, with it left out
// when the input is at its default value
//
// choices: Map of option labels to values for radio/select/checkbox inputs,
// which are stored by label (their values can be null or data), comma separated
// for checkboxes; otherwise the value is stored as a number, or as comma
// separated numbers for intervals
url_bound = (key, input, { choices } = {}) => {
const is_number = s => s !== "" && Number.isFinite(+s)
const label_of = v => [...choices].find(([label, value]) => value === v)?.[0]
// checkbox values are arrays, but so can be the values of other inputs
const multiple = choices && input.querySelector("input[type=checkbox]") !== null
const encode = multiple
? v => v.map(label_of).join(",")
: choices
? label_of
: v => String(v)
const decode = multiple
? s => { const v = s === "" ? [] : s.split(","); return v.every(l => choices.has(l)) ? { value: v.map(l => choices.get(l)) } : null }
: choices
? s => choices.has(s) ? { value: choices.get(s) } : null
: Array.isArray(input.value)
? s => { const v = s.split(","); return v.length === 2 && v.every(is_number) ? { value: v.map(Number) } : null }
: s => is_number(s) ? { value: +s } : null
const default_param = encode(input.value)
const param = new URLSearchParams(location.search).get(key)
const decoded = param === null ? null : decode(param)
if (decoded !== null) {
input.value = decoded.value
// the value setter alone is silent, so let the input's own listeners (e.g.
// slider fill) know
input.dispatchEvent(new Event("input", { bubbles: true }))
}
input.addEventListener("input", () => {
const url = new URL(location.href)
const p = encode(input.value)
if (p === undefined || p === default_param) url.searchParams.delete(key)
else url.searchParams.set(key, p)
history.replaceState(history.state, "", url)
})
return input
}Plot = import("https://esm.sh/@observablehq/plot@0.6.17")
task_info = ({
"hf": "Hearts & Flowers",
"sds": "Same & Different",
"mg": "Memory",
"math": "Math",
"matrix": "Pattern Matching",
"mrot": "Shape Rotation",
"trog": "Sentence Understanding",
"vocab": "Vocabulary",
"tom": "Stories",
"pa": "Language Sounds",
"sre": "Sentence Reading",
"swr": "Word Reading",
})
// time_started is always utc, but arrives in two formats: "2024-05-07 09:06:25"
// via ojs_define from the r loader, and iso ("2024-05-07T13:05:41.810Z") from the
// redivis js client used by the data source switcher
parse_time = (t) => {
if (t == null) return null
if (t instanceof Date) return t
return d3.utcParse("%Y-%m-%d %H:%M:%S")(t) || d3.isoParse(t)
}
// scores and which dataset and version they're from, starting with those
// loaded at render (replaced by the data source switcher)
mutable source = ({ rows: transpose(data), ...data_source })
scores = source.rows
// scored runs
runs = scores
.filter(d => d.score != null)
.map(d => ({ ...d, date: parse_time(d.time_started) }))
// sd of all scores from each scoring model (of each task), regardless of the
// inputs, to put age slopes in sds per year (as in the tasks paper)
score_sds = d3.rollup(runs, g => d3.deviation(g, d => d.score),
d => d.task_id, d => d.task_code, d => d.scoring_model)
// consecutive pairs of each child's runs on a task, with the gap between them
// in months, and which of the child's runs they are (e.g. "1-2"). tasks are
// grouped by both task_id and task_code since they disagree for a few runs
pairs = d3.flatGroup(runs, d => d.dataset, d => d.user_id, d => d.task_id, d => d.task_code)
.flatMap(([dataset, user_id, task_id, task_code, g]) =>
d3.pairs(d3.sort(g, d => d.date)).map(([a, b], i) => ({
dataset, task_id, task_code,
score_1: a.score, score_2: b.score, age_1: a.age,
gap: (b.date - a.date) / (864e5 * 365.25 / 12),
runs: `${i + 1}-${i + 2}`
})))
// pearson correlation of two arrays
cor = (x, y) => {
const mx = d3.mean(x), my = d3.mean(y)
const sxy = d3.sum(x, (xi, i) => (xi - mx) * (y[i] - my))
return sxy / Math.sqrt(d3.sum(x, xi => (xi - mx) ** 2) * d3.sum(y, yi => (yi - my) ** 2))
}
// 95% confidence interval of a correlation r over n observations, via fisher's z
cor_ci = (r, n) => {
if (!(n > 3)) return [NaN, NaN]
const z = Math.atanh(r), h = 1.96 / Math.sqrt(n - 3)
return [Math.tanh(z - h), Math.tanh(z + h)]
}
// empirical reliability = var(score) / (var(score) + mean(se^2)), from arrays
// of scores and squared ses
rxx = (s, e2) => { const v = d3.variance(s); return v / (v + d3.mean(e2)) }
// 95% percentile bootstrap interval of empirical reliability, resampling runs
// (written out with typed arrays since it runs for every group on every change)
rxx_ci = (s, e2, rand, B = 500) => {
const n = s.length
if (n < 2 || e2.some(isNaN)) return [NaN, NaN]
const out = new Float64Array(B)
for (let b = 0; b < B; b++) {
let sum = 0, sum2 = 0, sum_e2 = 0
for (let i = 0; i < n; i++) {
const j = Math.floor(rand() * n)
sum += s[j]; sum2 += s[j] ** 2; sum_e2 += e2[j]
}
const v = (sum2 - sum ** 2 / n) / (n - 1)
out[b] = v / (v + sum_e2 / n)
}
return [d3.quantile(out, 0.025), d3.quantile(out, 0.975)]
}
// least squares slope of y on x and its standard error
ols_slope = (x, y) => {
const n = x.length, mx = d3.mean(x), my = d3.mean(y)
const sxx = d3.sum(x, xi => (xi - mx) ** 2)
const b = d3.sum(x, (xi, i) => (xi - mx) * (y[i] - my)) / sxx
const ss_res = d3.sum(x, (xi, i) => (y[i] - my - b * (xi - mx)) ** 2)
return { b, se: Math.sqrt(ss_res / (n - 2) / sxx) }
}
// reliability, age correlation, and age slope, with 95% intervals, for each
// dataset x task x scoring model. the bootstrap's random numbers are seeded, so that the same
// inputs always give the same intervals
score_stats = (rs) => {
const rand = d3.randomLcg(42)
return d3.flatRollup(rs, g => {
const s = Float64Array.from(g, d => d.score)
const e2 = Float64Array.from(g, d => d.score_se == null ? NaN : d.score_se ** 2)
const r_age = cor(g.map(d => d.score), g.map(d => d.age))
const [rxx_lo, rxx_hi] = rxx_ci(s, e2, rand)
const [age_lo, age_hi] = cor_ci(r_age, g.length)
// slope of scores in sds of their scoring model's scores, with normal interval
const { task_id, task_code, scoring_model } = g[0]
const sd = score_sds.get(task_id).get(task_code).get(scoring_model)
const { b, se } = ols_slope(g.map(d => d.age), g.map(d => d.score / sd))
return {
n_scores: g.length,
empirical_rxx: rxx(s, e2), rxx_lo, rxx_hi,
cor_score_age: r_age, age_lo, age_hi,
slope_age: b, slope_se: se, slope_lo: b - 1.96 * se, slope_hi: b + 1.96 * se,
age_sd: d3.deviation(g, d => d.age)
}
}, d => d.dataset, d => d.task_id, d => d.task_code, d => d.scoring_model)
.map(([dataset, task_id, task_code, scoring_model, s]) => ({ dataset, task_id, task_code, scoring_model, ...s, Task: task_info[task_code] }))
}
// test-retest correlation, with 95% interval, for each dataset x task
retest_stats = (ps) => d3.flatRollup(ps, g => {
const trt = cor(g.map(d => d.score_1), g.map(d => d.score_2))
const [trt_lo, trt_hi] = cor_ci(trt, g.length)
return { n_pairs: g.length, trt, trt_lo, trt_hi, gap_median: d3.median(g, d => d.gap) }
}, d => d.dataset, d => d.task_id, d => d.task_code)
.map(([dataset, task_id, task_code, s]) => ({ dataset, task_id, task_code, ...s, Task: task_info[task_code] }))
// weighted average of a statistic over the datasets shown for each task -- for
// correlations, averaged as fisher's z (with weights n - 3, this is a fixed
// effect meta-analysis)
pooled = (rows, x, weight, { fisher = false } = {}) => d3.flatRollup(
rows.filter(d => Number.isFinite(d[x]) && weight(d) > 0),
g => {
const w = g.map(weight)
const v = g.map(d => fisher ? Math.atanh(d[x]) : d[x])
const m = d3.sum(v, (vi, i) => vi * w[i]) / d3.sum(w)
return fisher ? Math.tanh(m) : m
}, d => d.Task)
.map(([Task, value]) => ({ Task, value }))
// order of tasks for every plot's y axis and colors -- by highest reliability
// over all runs (so that it doesn't change with the inputs), with tasks that
// have none last
task_order = d3.groupSort(score_stats(runs),
g => -(d3.max(g, d => d.empirical_rxx) ?? -Infinity),
d => d.Task)stats_opts = ({
className: "stats-plot", // figure gets class stats-plot-figure (see layout.scss)
style: { fontFamily: "var(--sans-serif)", fontSize: 12, overflow: "visible" },
width: 0.4 * width,
marginLeft: 130,
marginTop: 5,
marginBottom: 40,
insetLeft: 10,
y: { grid: true, label: null, tickSize: 0, tickPadding: 2, domain: task_order },
x: { line: true },
r: { label: "N", range: [1, 5] },
color: { scheme: "Turbo", domain: task_order, reverse: true }
})
// tooltip formats and extra channels
fmt = d3.format(".2f")
tip_opts = ({ format: { x: ".2f", stroke: false } })
ci_channel = (lo, hi) => ({ label: "95% CI", value: d => `[${fmt(d[lo])}, ${fmt(d[hi])}]` })
// short label for a scoring model, e.g. "multigroup_dataset_all_items_rasch_f1_scalar"
// -> "multigroup Rasch", "by_language_es-CO_rasch_f1" -> "es-CO Rasch" (and
// anything that doesn't match that pattern as is)
model_label = (m) => {
if (m == null) return "not IRT"
const match = m.match(/^(?:(multigroup)|by_language_([^_]+))_.*?(rasch|2pl)_/)
if (!match) return m
const [, multigroup, language, itemtype] = match
return `${multigroup ?? language} ${itemtype === "rasch" ? "Rasch" : "2PL"}`
}
score_channels = ({
"Dataset": "dataset",
"Scoring model": { value: d => model_label(d.scoring_model), label: "Scoring model" },
"Age SD (years)": { value: d => fmt(d.age_sd), label: "Age SD (years)" }
})
// marks for a statistic shared by the plots: a 95% interval line and a dot for
// each dataset, and a tick for the average across datasets of each task
stat_marks = (rows, { x, lo, hi, n, weight, channels, fisher }) => [
Plot.ruleY(rows, { y: "Task", x1: lo, x2: hi, stroke: "Task", strokeOpacity: 0.35 }),
Plot.dot(rows, {
x, y: "Task", stroke: "Task", r: n, tip: tip_opts,
channels: { ...channels, "95% CI": ci_channel(lo, hi) }
}),
Plot.tickX(pooled(rows, x, weight, { fisher }), { x: "value", y: "Task", stroke: "black", strokeWidth: 2 })
]
// put an input's label on its own line above its options (see _style)
stacked = (input) => {
input.classList.add("stacked-input")
return input
}
// slider for the minimum value of a sample size variable
min_n_input = (label) => {
const form = Inputs.range([0, 300], { label: label, step: 1, value: 30 })
// set how far to fill the slider track (see _style)
const range = form.querySelector("input[type=range]")
const fill = () => range.style.setProperty("--fill", (range.valueAsNumber - range.min) / (range.max - range.min))
form.addEventListener("input", fill)
fill()
return form
}
// formatting function for how two ended slider displays selected range
interval_number = ([start, end]) => `[${Plot.formatNumber("en-US")(start)}; ${Plot.formatNumber("en-US")(end)}]`
// two ended slider for a range of a numeric variable
range_input = (label, range, step, value = range) => interval(range, {
label: label, step: step, value: value, format: interval_number, color: "#f7ca69", width: "95%"
})in_range = (x, [min, max]) => x != null && x >= min && x <= max
// stats for runs in the age range, optionally only each child's earliest one of
// those on a task. computed apart from the min n filter, so that dragging its
// slider doesn't rerun the bootstrap
stats_age = {
const rs = runs.filter(d => in_range(d.age, age_range))
const rs_set = run_set === "all" ? rs
: d3.flatRollup(rs, g => d3.least(g, d => d.date), d => d.user_id, d => d.task_id, d => d.task_code)
.map(([user_id, task_id, task_code, r]) => r)
return score_stats(rs_set)
}
stats_n_scores = stats_age.filter(d => d.n_scores >= min_n_scores)
// pairs of the selected runs, with the age at the first run in the age range
// and the gap in the gap range
retest_n_pairs = retest_stats(pairs.filter(d =>
pair_runs.includes(d.runs) && in_range(d.age_1, retest_age_range) && in_range(d.gap, gap_range)))
.filter(d => d.n_pairs >= retest_min_n)viewof min_n_scores = url_bound("min_n", min_n_input("Min N scores"))
viewof age_range = url_bound("age", range_input("Age (years)", [2, 16], 0.5))
run_opts = new Map([["All", "all"], ["First per child", "first"]])
viewof run_set = url_bound("set", Inputs.radio(run_opts, { label: "Assessment set", value: "all" }), { choices: run_opts })
age_stat_opts = new Map([["Correlation", "cor"], ["Slope", "slope"]])
viewof age_stat = url_bound("age_stat", Inputs.radio(age_stat_opts, { label: "Age statistic", value: "cor" }), { choices: age_stat_opts })
// reliability
Plot.plot({
...stats_opts,
title: "Score reliability",
x: { label: "Empirical reliability", line: true, domain: [0, 1] },
marks: [
...stat_marks(stats_n_scores, {
x: "empirical_rxx", lo: "rxx_lo", hi: "rxx_hi", n: "n_scores", weight: d => d.n_scores,
channels: score_channels
}),
// say why tasks shown have no reliability, rather than leave an empty row
Plot.text(
d3.groups(stats_n_scores, d => d.Task)
.filter(([, g]) => g.every(d => !Number.isFinite(d.empirical_rxx)))
.map(([Task]) => ({ Task })),
{ x: 0, y: "Task", text: () => "not IRT-scored", textAnchor: "start", fill: "gray", fontStyle: "italic" }
)
]
})
// age correlation or slope
age_stat === "cor"
? Plot.plot({
...stats_opts,
title: "Score–age correlation",
x: { label: "Age correlation", line: true },
marks: stat_marks(stats_n_scores, {
x: "cor_score_age", lo: "age_lo", hi: "age_hi", n: "n_scores", weight: d => d.n_scores - 3,
fisher: true, channels: score_channels
})
})
: Plot.plot({
...stats_opts,
title: "Score–age slope",
x: { label: "Age slope (SDs per year)", line: true },
marks: stat_marks(stats_n_scores, {
x: "slope_age", lo: "slope_lo", hi: "slope_hi", n: "n_scores", weight: d => d.slope_se ** -2,
channels: score_channels
})
})
NoteAbout these statistics
Each dot is one dataset, sized proportional to its number of scores, with a line for its 95% confidence interval. The black tick is the average across the datasets shown. Scores without an age are left out, and the first per child option uses only each child’s earliest assessment on a task within the age range.
Empirical reliability is var(θ) / (var(θ) + mean(SE2)) over the ability scores θ and their standard errors. Its confidence interval is from a bootstrap of scores (500 resamples); the average weights datasets by number of scores. Sentence Reading scores have no standard errors, so no reliability.
Age correlation is the Pearson correlation of scores with age. Its confidence interval is from Fisher’s z, and the average is of Fisher’s z, weighted by N − 3.
Note that reliability and age correlation both depend on how spread out ages are in a dataset: a narrower age range gives lower values.
Age slope is the least squares slope of scores on age, with scores divided by the SD of all scores from their scoring model. So the units are score SDs per year, and it doesn’t depend on a dataset’s age range. It’s comparable across datasets that share a scoring model, but less so across tasks or scoring models, since each one’s SD depends on the ages and datasets it has scores for. Its confidence interval is ±1.96 standard errors, and the average is weighted by inverse variance.
viewof retest_min_n = url_bound("retest_min_n", min_n_input("Min N pairs"))
pair_opts = new Map([["1→2", "1-2"], ["2→3", "2-3"]])
viewof pair_runs = url_bound("pairs", stacked(Inputs.checkbox(pair_opts, { label: "Assessment pair", value: [...pair_opts.values()] })), { choices: pair_opts })
viewof gap_range = url_bound("gap", range_input("Retest gap (months)", [0, 30], 1, [2, 12]))
viewof retest_age_range = url_bound("retest_age", range_input("Age at first assessment (years)", [2, 16], 0.5))
// test-retest correlation
Plot.plot({
...stats_opts,
title: "Test–retest correlation",
x: { label: "Test-retest correlation", line: true, domain: [0, 1] },
marks: stat_marks(retest_n_pairs, {
x: "trt", lo: "trt_lo", hi: "trt_hi", n: "n_pairs", weight: d => d.n_pairs - 3, fisher: true,
channels: { "Dataset": "dataset", "Median gap (months)": { value: d => d.gap_median.toFixed(1), label: "Median gap (months)" } }
})
})
NoteAbout these statistics
Each dot is one dataset, sized by its number of pairs, with a line for its 95% interval (from Fisher’s z). The black tick is the average across the datasets shown, of Fisher’s z weighted by N − 3.
A pair is two consecutive assessments of the same child on the same task, ordered by start time: 1→2 is their first and second assessments, 2→3 their second and third. The retest gap is the time between the two assessments’ starts, and the age is the child’s age at the first assessment.
Test-retest correlation is the Pearson correlation of the two assessments’ scores. Over longer gaps it reflects children’s development (stability of their rank order) as well as the reliability of measurement.
Change data source…
To change data sources, you need a Redivis account. Click on “Populate data sources” to log in and list data sources you have access to.
// replaces current scores with scores from selected datasource and version
viewof switch_datasource_button = Inputs.button("Switch data source", {
disabled: !version,
reduce: async () => {
mutable load_status = `Loading ${datasource.name} ${version.tag}...`
try {
mutable source = await getScores(version)
mutable load_status = ""
} catch (e) {
mutable load_status = `Couldn't load ${datasource.name} ${version.tag}: ${e.message}`
}
}
})redivis = import("https://cdn.jsdelivr.net/npm/redivis@0.4.2/+esm")
// get scores table for a given version of a dataset, along with which dataset
// and version they're from
async function getScores(version) {
console.log('getting scores')
const dataset = await version.dataset().get()
const rows = await dataset
.table('scores')
.toRowsArray({
variables: ['dataset', 'task_id', 'task_code', 'user_id', 'score', 'score_se', 'score_type',
'scoring_model', 'age', 'time_started'],
temporal: false
})
console.log('got scores')
return { rows, name: dataset.properties.name, version: version.tag, url: dataset.properties.url }
}
// get references to all LEVANTE datasets (with "properties" populated). signs in
// first, since listing datasets works anonymously, but then gives only their
// public access level
async function getDatasets() {
await redivis.authorize()
const ds = await redivis
.organization('LEVANTE')
.listDatasets()
return await Promise.all(ds.map(d => d.get()))
}
// get versions of a dataset: its next (unreleased) version if it has one that the
// user can see, then its released versions, latest first. the next version isn't
// listed, and getting it as a version needs edit scope, so it's looked up as the
// dataset at that version (which fails if there isn't one)
async function getVersions(dataset) {
const vs = (await dataset.listVersions())
.filter(v => v.properties.isReleased && !v.properties.isDeleted)
.reverse()
const next = await dataset.version("next")
const has_next = await next.dataset().get().then(() => true, () => false)
return has_next ? [next, ...vs] : vs
}
// filter datasets by authed user's access + get "processed" datasets
allowedDatasets = (ds) => {
const accessLevels = ["data", "edit"]
const defaultDataset = "levante-data-pilots"
const datasets = ds.filter(d => accessLevels.includes(d.properties.accessLevel))
.filter(d => d.properties.tableCount > 0)
.filter(d => !d.name.match("-raw|-metadata-|-example|test-"))
return d3.sort(datasets, d => d.name !== defaultDataset, d => d.name)
}