Predicting the other fields from the ones you set

If you fix some of these fields to values you choose, what range do the others fall in?

Daily wearable-device activity for a cohort of users: step counts, calories burned, average heart rate and sleep hours, with weekday and per-user grain. A rich mix of a date, a category (user), and several measures — good for time-series, per-category comparison, and tabular scorecards.

Fitness Tracker — Daily Steps, Sleep & Heart Rate: 5430 rows, 7 columns. Download the CSV

The first 10 rows
DateUserIDWeekdaySum of StepsSum of CaloriesBurnedAvgHeartRateSleepHours
2025-01-01U001Wed10071428687.7
2025-01-02U001Thu4474197808.1
2025-01-03U001Fri11527556806.9
2025-01-04U001Sat15062693856.4
2025-01-05U001Sun10226536966.9
2025-01-06U001Mon10164516806.5
2025-01-07U001Tue9765552828.6
2025-01-08U001Wed7720406966.1
2025-01-09U001Thu5680245889.4
2025-01-10U001Fri6647356786.6
A what-if predictor on the "Fitness Tracker — Daily Steps, Sleep & Heart Rate" dataset: one model fitted to how its fields move together.
A what-if predictor on the "Fitness Tracker — Daily Steps, Sleep & Heart Rate" dataset: one model fitted to how its fields move together.

How to read it

Each field shows the range seen in the data and the model's predicted range. Type a value into any field, or pick a category, and every other field's predicted range moves; the confidence buttons widen or narrow the ranges, and a weak prediction is drawn hollow rather than hidden.

The chart's code (69 KB of JavaScript, D3)

It carries its own copies of these helpers: llmText, llmFrameTween, llmRangeBrush, llmSlider, llmNumberEntry, llmSegmented, llmPredictor, llmResponseCurves, llmTerritories, llmCutoff, llmContrast, llmSurvival, llmModelFormat, llmSubgroups, llmSegments, llmGlyphs, llmBreadcrumb, llmKeyframes, llmScrubber, llmValueColumn, llmValueRamp, llmFitLabel, llmThinLabels, llmFitAxisTicks, llmSymlog, llmClipOutliers, llmGeoZoom, llmGeoPointNotes, llmMapLabels, llmGeoMarks, llmPlaceUnit, llmWorldFit, llmRegionFit, llmFlowKey, llmFlowArcs, llmFrameFill, llmTooltip, llmSwarm, llmKde, llmOrbit3d, llmBoundedScale, llmBivariate, llmLegendLayout, llmPager, llmTableFrame, llmGrid, llmUtcDays, llmPeriodGrid, llmTileGrid, llmMermaid, llmDecomp, llmTopN, llmFlipDeck, llmFilterScope, llmDisplayName, llmThemeColors, llmWordCloud.

// bic:keyboard-marks
// English whatever the chart's language. A helper now asks for each one here and declares `// @requires llmText`:
d3.llmText = function (key, english, vars, count) {
var fill = function (s, vv) {
vv = vv || vars;
return String(s).replace(/\{([a-z][a-z0-9_]*)\}/g, function (m, k) {
return vv && Object.prototype.hasOwnProperty.call(vv, k) ? String(vv[k]) : m;
});
};
var en = fill(english);
var host = d3.llmText.host;
if (typeof host === 'function') {
try { var h = host(key, english, vars, count); if (typeof h === 'string' && h !== en && h !== english) return h; } catch (e) {}
}
var cat = d3.llmText._cat, lang = d3.llmText._lang;
if (cat && lang && Object.prototype.hasOwnProperty.call(cat, key)) {
var v = cat[key];
if (v && typeof v === 'object') {
var form = 'other';
try { form = new Intl.PluralRules(lang).select(typeof count === 'number' ? count : 0); } catch (e) {}
v = v[form] != null ? v[form] : v.other != null ? v.other : v.many;
}
var tv = vars;
if (vars && typeof vars.grain === 'string' && Object.prototype.hasOwnProperty.call(cat, 'd3.grain.' + vars.grain)
&& typeof cat['d3.grain.' + vars.grain] === 'string' && cat['d3.grain.' + vars.grain]) {
tv = {};
for (var vk in vars) if (Object.prototype.hasOwnProperty.call(vars, vk)) tv[vk] = vars[vk];
tv.grain = cat['d3.grain.' + vars.grain];
}
if (typeof v === 'string' && v) {
var t = fill(v, tv), left = String(t).match(/\{[a-z][a-z0-9_]*\}/g) || [];
if (left.every(function (x) { return en.indexOf(x) >= 0; })) return t;
}
}
return en;
};
d3.llmText._lang = null;
d3.llmText._cat = null;
d3.llmText.use = function (lang, catalog) {
d3.llmText._lang = lang || null; d3.llmText._cat = catalog || null;
d3.llmText.dates(lang);
};
d3.llmText.dates = function (lang) {
try {
var o = d3.llmText._d3orig;
if (!o) {
o = d3.llmText._d3orig = { timeFormat: d3.timeFormat, utcFormat: d3.utcFormat, timeParse: d3.timeParse,
utcParse: d3.utcParse, scaleTime: d3.scaleTime, scaleUtc: d3.scaleUtc };
}
var restore = function () { for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k) && o[k]) d3[k] = o[k]; };
var base = String(lang || '').toLowerCase().split(/[-_]/)[0];
if (!base || base === 'en' || typeof d3.timeFormatLocale !== 'function' || typeof Intl === 'undefined') { restore(); return; }
var mk = function (opts) { var x = { timeZone: 'UTC' }; for (var k in opts) x[k] = opts[k]; return new Intl.DateTimeFormat(lang, x); };
var months = [], shortMonths = [], days = [], shortDays = [], m, w;
var fM = mk({ month: 'long' }), fMs = mk({ month: 'short' }), fD = mk({ weekday: 'long' }), fDs = mk({ weekday: 'short' });
for (m = 0; m < 12; m++) { var dm = new Date(Date.UTC(2021, m, 15)); months.push(fM.format(dm)); shortMonths.push(fMs.format(dm)); }
for (w = 0; w < 7; w++) { var dw = new Date(Date.UTC(2021, 0, 3 + w)); days.push(fD.format(dw)); shortDays.push(fDs.format(dw)); }   // 3 Jan 2021 is a Sunday
if (months[0] === 'January' && days[0] === 'Sunday') { restore(); return; }   // no names for the language here: keep d3's
var L = d3.timeFormatLocale({ dateTime: '%x %X', date: '%Y-%m-%d', time: '%H:%M:%S', periods: ['AM', 'PM'],
days: days, shortDays: shortDays, months: months, shortMonths: shortMonths });
d3.timeFormat = L.format; d3.utcFormat = L.utcFormat; d3.timeParse = L.parse; d3.utcParse = L.utcParse;
var multi = function (utc) {
var F = utc ? L.utcFormat : L.format, P = utc ? 'utc' : 'time';
var iv = function (n) { return d3[P + n]; };
var fL = F('.%L'), fS = F(':%S'), fMi = F('%H:%M'), fH = F('%H:00'), fDy = F('%a %d'), fW = F('%b %d'), fMo = F('%B'), fY = F('%Y');
var wk = utc ? d3.utcSunday : d3.timeSunday;
return function (date) {
return (iv('Second')(date) < date ? fL : iv('Minute')(date) < date ? fS : iv('Hour')(date) < date ? fMi
: iv('Day')(date) < date ? fH : iv('Month')(date) < date ? (wk(date) < date ? fDy : fW)
: iv('Year')(date) < date ? fMo : fY)(date);
};
};
var wrap = function (make, utc) {
if (typeof make !== 'function') return make;
var dress = function (sc) {
var cp = sc.copy;
sc.tickFormat = function (count, spec) { return spec == null ? multi(utc) : (utc ? L.utcFormat : L.format)(spec); };
if (typeof cp === 'function') sc.copy = function () { return dress(cp.apply(sc, arguments)); };
return sc;
};
return function () { return dress(make.apply(this, arguments)); };
};
d3.scaleTime = wrap(o.scaleTime, false); d3.scaleUtc = wrap(o.scaleUtc, true);
} catch (e) {}
};
d3.llmNumberEntry = function (svg, cfg) {
var TYPE_FLOOR = 10, XHTML = 'http://www.w3.org/1999/xhtml';
cfg = cfg || {};
var options = cfg.options || {}, container = cfg.container;
var key = cfg.key || 'value';
var onChange = typeof cfg.onChange === 'function' ? cfg.onChange : function () {};
var allowEmpty = cfg.allowEmpty !== false;
var levels = Array.isArray(cfg.levels) && cfg.levels.length ? cfg.levels.map(String) : null;
var lo = cfg.min != null && isFinite(+cfg.min) ? +cfg.min : -Infinity;
var hi = cfg.max != null && isFinite(+cfg.max) ? +cfg.max : Infinity;
var noop = { value: function () { return null; }, set: function () {}, reset: function () {},
outOfRange: function () { return false; }, bounds: function () { return { left: 0, right: 0 }; }, node: null,
destroy: function () {} };
if (!svg || typeof svg.append !== 'function') return noop;
var fg = options.themeFg || '#252423', bg = options.themeBg || '#ffffff';
var neg = options.themeNegative || '#c4314b';
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var x = cfg.x != null ? +cfg.x : 0, y = cfg.y != null ? +cfg.y : 0;
var w = cfg.width != null ? Math.max(fsz * 3, +cfg.width) : fsz * 7;
var h = Math.round(fsz * 1.8);

var culture = options.cultureCode || undefined, decimal = '.', group = ',';
try {
var parts = new Intl.NumberFormat(culture).formatToParts(12345.6);
parts.forEach(function (p) { if (p.type === 'decimal') decimal = p.value; if (p.type === 'group') group = p.value; });
} catch (e) { /* the defaults are the invariant culture's */ }
var fmtNum;
try {
var nf = new Intl.NumberFormat(culture, { maximumFractionDigits: 6 });
var pf = new Intl.NumberFormat(culture, { style: 'percent', maximumFractionDigits: 4 });
fmtNum = function (v) { return cfg.percent ? pf.format(v) : nf.format(v); };
} catch (e) { fmtNum = function (v) { return cfg.percent ? (v * 100) + '%' : String(v); }; }
var fmt = typeof cfg.format === 'function' ? cfg.format : fmtNum;

function levelOf(s) {
var t = String(s == null ? '' : s).trim().toLowerCase();
for (var i = 0; i < levels.length; i++) if (levels[i].toLowerCase() === t) return levels[i];
return undefined;
}
function parseTyped(s) {
var t = String(s == null ? '' : s).trim();
if (t === '') return allowEmpty ? null : undefined;
if (levels) return levelOf(t);
t = t.replace(/[$\u20AC\u00A3\u00A5]/g, '').trim();   // the box's own format printed a currency sign ('$62,542'): it reads back as the number
var pct = false, mult = 1;
if (/%$/.test(t)) { pct = true; t = t.slice(0, -1).trim(); }
var suf = /([kKmMbB])$/.exec(t);
if (suf) { mult = { k: 1e3, m: 1e6, b: 1e9 }[suf[1].toLowerCase()]; t = t.slice(0, -1).trim(); }
t = t.replace(/[\s  ']/g, '');
if (group && group !== decimal) t = t.split(group).join('');
if (decimal !== '.') t = t.split(decimal).join('.');
if (!/^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(t)) return undefined;
var v = +t * mult;
if (!isFinite(v)) return undefined;
if (pct || cfg.percent) v = v / 100;   // '3.2%' is 0.032 anywhere; '3.2' is 0.032 in a percent box
return v;
}
function coerce(v) {
if (v === null || v === '') return allowEmpty ? null : undefined;
if (v === undefined || typeof v === 'boolean' || typeof v === 'object') return undefined;
if (levels) return levelOf(v);
var n = typeof v === 'number' ? v : NaN;
if (!isFinite(n) || n < lo || n > hi) return undefined;
return n;
}
function show(v) { return v === null || v === undefined ? '' : (levels ? String(v) : String(fmt(v))); }

var bag = {};
if (container) {
if (!container.__lchKnobs || typeof container.__lchKnobs !== 'object') container.__lchKnobs = {};
bag = container.__lchKnobs;
}
var ui = options.uiState && typeof options.uiState === 'object' ? options.uiState : {};
var hasRestore = ui.knobs && typeof ui.knobs === 'object' && Object.prototype.hasOwnProperty.call(ui.knobs, key);
var cur = hasRestore ? coerce(ui.knobs[key]) : undefined;
var dflt = coerce(cfg['default'] === undefined ? null : cfg['default']);
if (cur === undefined) cur = dflt === undefined ? null : dflt;

var g = svg.append('g').attr('class', 'llm-entry lch-control');
var labelRight = cfg.labelRight != null ? +cfg.labelRight : x - fsz * 0.6, labelW = 0;
if (cfg.label) {
var ln = g.append('text').attr('class', 'llm-entry-label').attr('x', labelRight).attr('y', y + fsz * 0.35)
.attr('text-anchor', 'end').attr('font-size', Math.max(TYPE_FLOOR, fsz * 0.9)).attr('fill', fg)
.text(String(cfg.label));
labelW = String(cfg.label).length * Math.max(TYPE_FLOOR, fsz * 0.9) * 0.6;
try { var m = ln.node().getComputedTextLength(); if (m > 0) labelW = m; } catch (e) { /* estimate */ }
}
var fo = g.append('foreignObject').attr('class', 'lch-control').attr('x', x).attr('y', y - h / 2)
.attr('width', w).attr('height', h);
var doc = fo.node().ownerDocument;
var div = doc.createElementNS(XHTML, 'div');
div.setAttribute('class', 'lch-control');
div.setAttribute('style', 'margin:0;padding:0;width:100%;height:100%;box-sizing:border-box;line-height:0;');
var input = doc.createElementNS(XHTML, 'input');
input.setAttribute('type', 'text');
input.setAttribute('inputmode', levels ? 'text' : 'decimal');
input.setAttribute('class', 'lch-control lch-entry');
input.setAttribute('autocomplete', 'off');
input.setAttribute('spellcheck', 'false');
if (cfg.label) input.setAttribute('aria-label', String(cfg.label));
var baseStyle = 'display:block;box-sizing:border-box;width:100%;height:100%;margin:0;padding:0 ' + Math.round(fsz * 0.4) + 'px;' +
'font-family:inherit;font-size:' + fsz + 'px;text-align:right;' +
'color:var(--lch-hc-foreground,' + fg + ');background:var(--lch-hc-background,' + bg + ');' +
'border:1px solid var(--lch-hc-foreground,' + fg + ');border-radius:3px;outline:none;';
function mark(bad) {
input.setAttribute('style', baseStyle + (bad ? 'box-shadow:0 0 0 2px ' + neg + ';' : ''));
input.setAttribute('aria-invalid', bad ? 'true' : 'false');
}
mark(false);
input.value = show(cur);
div.appendChild(input);
fo.node().appendChild(div);

function persist(phase) {
bag[key] = cur;
onChange(cur, phase);
if (typeof options.setUiState !== 'function') return;
var live = container && container.__lchUiLiveOpts === options && container.__lchUiLiveSeed === options.uiState
? container.__lchUiLive : null;
var base = live || ui, next = {}, k;
for (k in base) if (Object.prototype.hasOwnProperty.call(base, k)) next[k] = base[k];
next.knobs = {};
for (k in bag) if (Object.prototype.hasOwnProperty.call(bag, k)) next.knobs[k] = bag[k];
if (container) { container.__lchUiLive = next; container.__lchUiLiveOpts = options; container.__lchUiLiveSeed = options.uiState; }
try { options.setUiState(next); } catch (e) { /* persistence is advisory, never fatal */ }
}
function report() {
if (typeof options.onControlChange !== 'function') return;
try { options.onControlChange({ control: 'entry', key: key, value: cur }); }
catch (e) { /* telemetry is advisory, never fatal */ }
}
var committedText = input.value;
function commit() {
var v = parseTyped(input.value);
if (v === undefined) { mark(true); return false; }
mark(false);
var changed = v !== cur;
cur = v;
input.value = show(cur);
committedText = input.value;
if (changed) { persist('change'); report(); }
return true;
}
function stop(ev) { if (ev && typeof ev.stopPropagation === 'function') ev.stopPropagation(); }
input.addEventListener('keydown', function (ev) {
stop(ev);
if (ev.key === 'Enter') { if (typeof ev.preventDefault === 'function') ev.preventDefault(); commit(); }
else if (ev.key === 'Escape') {
if (typeof ev.preventDefault === 'function') ev.preventDefault();
input.value = committedText; mark(false);
if (typeof input.blur === 'function') input.blur();
}
});
input.addEventListener('keyup', stop);
input.addEventListener('keypress', stop);
input.addEventListener('change', function (ev) { stop(ev); commit(); });
['click', 'dblclick', 'mousedown', 'pointerdown', 'pointerup', 'mouseup', 'contextmenu', 'wheel']
.forEach(function (t) { div.addEventListener(t, stop); });

bag[key] = cur;
onChange(cur, 'init');
return {
node: input,
value: function () { return cur; },
set: function (v, fire) {
var c = typeof v === 'string' ? parseTyped(v) : coerce(v);
if (c === undefined) return;
cur = c; input.value = show(cur); committedText = input.value; mark(false);
if (fire === false) { bag[key] = cur; onChange(cur, 'change'); } else persist('change');
},
reset: function (fire) {
cur = dflt === undefined ? null : dflt; input.value = show(cur); committedText = input.value; mark(false);
if (fire === false) { bag[key] = cur; onChange(cur, 'reset'); } else persist('reset');
},
outOfRange: function () { return typeof cur === 'number' && (cur < lo || cur > hi); },
bounds: function () { return { left: cfg.label ? labelRight - labelW : x, right: x + w }; },
destroy: function () { g.remove(); }
};
};
d3.llmSegmented = function (svg, cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px
cfg = cfg || {};
var options = cfg.options || {}, container = cfg.container;
var key = typeof cfg.key === 'string' && cfg.key ? cfg.key : 'segment';
var onChange = typeof cfg.onChange === 'function' ? cfg.onChange : function () {};
var offered = Array.isArray(cfg.choices) ? cfg.choices : [];
var choices = offered.map(d3.llmSegmented.choice).filter(function (c) {
return c && typeof c.value === 'string' && c.value !== '';
});
var noop = { value: function () { return null; }, set: function () {}, g: null,
bounds: function () { return { left: 0, right: 0, width: 0, height: 0 }; } };
if (!svg || choices.length < 2) {
if (svg && offered.length >= 2 && typeof svg.attr === 'function') {
var inert = svg.attr('data-llm-inert-control');
svg.attr('data-llm-inert-control', (inert ? inert + ',' : '') + key);
}
return noop;
}
var fg = options.themeFg || '#252423', accent = options.themeAccent || fg;
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var geo = d3.llmSegmented.measure({ choices: choices, fontSize: fsz, label: cfg.label });
var x = cfg.x != null ? +cfg.x : 0, y = cfg.y != null ? +cfg.y : 0;

function isChoice(v) {
if (typeof v !== 'string') return false;
for (var i = 0; i < choices.length; i++) if (choices[i].value === v) return true;
return false;
}
var fallback = isChoice(cfg['default']) ? cfg['default'] : choices[0].value;

var bag = {};
if (container) {
if (!container.__lchSegments || typeof container.__lchSegments !== 'object') container.__lchSegments = {};
bag = container.__lchSegments;
}
var ui = options.uiState && typeof options.uiState === 'object' ? options.uiState : {};
var restoredBag = ui.segments && typeof ui.segments === 'object' ? ui.segments : null;
var restored = restoredBag && Object.prototype.hasOwnProperty.call(restoredBag, key) ? restoredBag[key] : undefined;
var cur = isChoice(restored) ? restored : fallback;
var shown = bag && Object.prototype.hasOwnProperty.call(bag, key) ? bag[key] : undefined;
var codeChange = isChoice(restored) && shown !== undefined && restored !== shown;

var g = svg.append('g').attr('class', 'llm-segmented').attr('data-segment-key', key);
var maxW = +cfg.maxWidth > 0 ? +cfg.maxWidth : (+options.width > 0 ? +options.width - x - 4 : Infinity);
var lay = d3.llmSegmented.layout(geo, maxW);
var left = x;
if (cfg.label) {
g.append('text').attr('class', 'llm-segmented-label')
.attr('x', left).attr('y', y + fsz * 0.35).attr('font-size', Math.max(TYPE_FLOOR, fsz * 0.9))
.attr('fill', fg).attr('fill-opacity', 0.75).text(String(cfg.label));
left += geo.labelW;
}
var buttons = [];
choices.forEach(function (c, i) {
var w = geo.buttonW[i], rowY = y + lay.row[i] * (geo.height + 2);
left = x + lay.left[i];
var b = g.append('g').attr('class', 'llm-segmented-button lch-control').attr('data-segment-value', c.value)
.attr('cursor', 'pointer').attr('role', 'button')
.attr('aria-label', (cfg.label ? String(cfg.label) + ': ' : '') + String(c.label == null ? c.value : c.label));
b.append('rect').attr('class', 'llm-segmented-hit')
.attr('x', left).attr('y', rowY - geo.height / 2).attr('width', w).attr('height', geo.height)
.attr('rx', i === 0 || i === choices.length - 1 ? 3 : 0)
.attr('stroke', fg).attr('stroke-opacity', 0.35);
b.append('text').attr('class', 'llm-segmented-text')
.attr('x', left + w / 2).attr('y', rowY + fsz * 0.35).attr('text-anchor', 'middle')
.attr('font-size', fsz).text(String(c.label == null ? c.value : c.label));
b.on('click', function (event) {
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
setCur(c.value, 'click');
});
buttons.push({ value: c.value, g: b });
left += w;
});

function paint() {
buttons.forEach(function (bt) {
var on = bt.value === cur;
bt.g.attr('aria-pressed', on ? 'true' : 'false');
bt.g.select('rect').attr('fill', on ? accent : 'transparent').attr('fill-opacity', on ? 0.18 : 0);
bt.g.select('text').attr('fill', fg).attr('font-weight', on ? 'bold' : 'normal');
});
}
function persist() {
bag[key] = cur;
if (typeof options.setUiState !== 'function') return;
var live = container && container.__lchUiLiveOpts === options && container.__lchUiLiveSeed === options.uiState
? container.__lchUiLive : null;
var base = live || ui;
var next = {}, k;
for (k in base) if (Object.prototype.hasOwnProperty.call(base, k)) next[k] = base[k];
next.segments = {};
for (k in bag) if (Object.prototype.hasOwnProperty.call(bag, k)) next.segments[k] = bag[k];
if (container) { container.__lchUiLive = next; container.__lchUiLiveOpts = options; container.__lchUiLiveSeed = options.uiState; }
try { options.setUiState(next); } catch (e) { /* persistence is advisory, never fatal */ }
}
function report() {
if (!options || typeof options.onControlChange !== 'function') return;
try { options.onControlChange({ control: 'segmented', key: key, value: cur }); }
catch (e) { /* telemetry is advisory, never fatal */ }
}
function setCur(v, phase) {
if (!isChoice(v)) return;
if (v === cur && phase !== 'init') return;         // re-clicking the active button does nothing
cur = v;
paint();
if (phase === 'click') { persist(); report(); }
onChange(cur, phase);
}

paint();
bag[key] = cur;
if (codeChange) persist();
onChange(cur, 'init');
return {
value: function () { return cur; },
g: g,
set: function (v, fire) { setCur(v, fire === false ? 'init' : 'click'); },
bounds: function () { return { left: x, right: x + lay.width, width: lay.width, height: lay.height }; }
};
};
d3.llmSegmented.measure = function (cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px - the row draws no smaller, so it reserves no smaller
cfg = cfg || {};
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize : 11);
var choices = (Array.isArray(cfg.choices) ? cfg.choices : []).map(d3.llmSegmented.choice);
var pad = fsz * 0.9;
var buttonW = choices.map(function (c) {
var t = String(c && (c.label == null ? c.value : c.label));
return Math.max(20, Math.round(t.length * fsz * 0.6 + pad * 2));
});
var labelW = cfg.label ? Math.round(String(cfg.label).length * Math.max(TYPE_FLOOR, fsz * 0.9) * 0.6 + fsz * 0.6) : 0;
var width = labelW + buttonW.reduce(function (a, b) { return a + b; }, 0);
var geo = { width: width, height: Math.max(20, Math.round(fsz * 1.9)), buttonW: buttonW, labelW: labelW };
if (!(+cfg.maxWidth > 0)) return geo;
var lay = d3.llmSegmented.layout(geo, +cfg.maxWidth);
return { width: lay.width, height: lay.height, buttonW: buttonW, labelW: labelW, rows: lay.rows };
};
d3.llmSegmented.layout = function (geo, maxW) {
var start = geo.labelW, left = start, row = 0, lefts = [], rows = [], right = start;
for (var i = 0; i < geo.buttonW.length; i++) {
var w = geo.buttonW[i];
if (left + w > maxW && left > start) { row++; left = start; }
lefts.push(left); rows.push(row); left += w; if (left > right) right = left;
}
var n = row + 1;
return { left: lefts, row: rows, width: right, height: n * geo.height + (n - 1) * 2, rows: n };
};
d3.llmSegmented.choice = function (c) { return typeof c === 'string' ? { value: c, label: c } : c; };
// @requires llmText
d3.llmPredictor = function (data, cfg) {
cfg = cfg || {};
var columns = (data && data.columns) || [];
var allRows = (data && data.rows) || [];
var colIdx = {};
for (var ci = 0; ci < columns.length; ci++) {
var cn = columns[ci] && (columns[ci].name !== undefined ? columns[ci].name : columns[ci]);
if (cn !== undefined && cn !== null) colIdx[String(cn)] = ci;
}
function cell(row, name) {
if (row === null || row === undefined) return undefined;
if (Array.isArray(row)) return colIdx[name] === undefined ? undefined : row[colIdx[name]];
return row[name];
}
function num(v) {
if (v === null || v === undefined || v === '' || typeof v === 'boolean') return NaN;
var x = typeof v === 'number' ? v : +String(v).trim();
return isFinite(x) ? x : NaN;
}
var measures = (cfg.measures || []).map(String);
var ordinals = cfg.ordinals || {};
var ordNames = Object.keys(ordinals);
var nominalCol = cfg.nominal ? String(cfg.nominal.column || cfg.nominal) : null;
var maxLevels = (cfg.nominal && cfg.nominal.maxLevels) || 6;
var minPerLevel = (cfg.nominal && cfg.nominal.minPerLevel) || 5;
var weakBelow = cfg.weakBelow === undefined ? 0.25 : cfg.weakBelow;
var collinearAt = cfg.collinearAt === undefined ? 0.97 : cfg.collinearAt;

function rankOf(name, v) {
var levels = ordinals[name] || [];
if (typeof v === 'number' && isFinite(v)) return v;
var s = String(v === null || v === undefined ? '' : v).trim().toLowerCase();
if (s === '') return NaN;
for (var i = 0; i < levels.length; i++) if (String(levels[i]).toLowerCase() === s) return i + 1;
var asNum = num(v);
return isFinite(asNum) ? asNum : NaN;
}
function levelKey(v) { return v === null || v === undefined ? '' : String(v).trim(); }

function lgamma(x) {
var g = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
if (x < 0.5) return Math.log(Math.PI / Math.abs(Math.sin(Math.PI * x))) - lgamma(1 - x);
x -= 1;
var a = g[0], t = x + 7.5;
for (var i = 1; i < 9; i++) a += g[i] / (x + i);
return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);
}
function betacf(a, b, x) {
var TINY = 1e-300, qab = a + b, qap = a + 1, qam = a - 1, c = 1, d = 1 - qab * x / qap;
if (Math.abs(d) < TINY) d = TINY;
d = 1 / d;
var h = d;
for (var m = 1; m <= 300; m++) {
var m2 = 2 * m, aa = m * (b - m) * x / ((qam + m2) * (a + m2));
d = 1 + aa * d; if (Math.abs(d) < TINY) d = TINY;
c = 1 + aa / c; if (Math.abs(c) < TINY) c = TINY;
d = 1 / d; h *= d * c;
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
d = 1 + aa * d; if (Math.abs(d) < TINY) d = TINY;
c = 1 + aa / c; if (Math.abs(c) < TINY) c = TINY;
d = 1 / d;
var del = d * c;
h *= del;
if (Math.abs(del - 1) < 1e-16) break;
}
return h;
}
function ibeta(x, a, b) {
if (x <= 0) return 0;
if (x >= 1) return 1;
var bt = Math.exp(lgamma(a + b) - lgamma(a) - lgamma(b) + a * Math.log(x) + b * Math.log(1 - x));
return x < (a + 1) / (a + b + 2) ? bt * betacf(a, b, x) / a : 1 - bt * betacf(b, a, 1 - x) / b;
}
function tcdf(t, df) {
var tail = 0.5 * ibeta(df / (df + t * t), df / 2, 0.5);
return t >= 0 ? 1 - tail : tail;
}
function tquantile(p, df) {
var lo = 0, hi = 1;
while (tcdf(hi, df) < p && hi < 1e7) hi *= 2;
for (var i = 0; i < 200; i++) {
var mid = (lo + hi) / 2;
if (tcdf(mid, df) < p) lo = mid; else hi = mid;
if (hi - lo < 1e-13 * Math.max(1, hi)) break;
}
return (lo + hi) / 2;
}

function solver(S) {
var k = S.length, d = new Array(k), L = [], i, j, r;
for (i = 0; i < k; i++) d[i] = Math.sqrt(Math.max(S[i][i], 0)) || 1;
for (var ridge = 0; ridge <= 1e-3; ridge = ridge ? ridge * 1000 : 1e-9) {
L = []; var ok = true;
for (i = 0; i < k && ok; i++) {
L.push(new Array(k).fill(0));
for (j = 0; j <= i; j++) {
var s = S[i][j] / (d[i] * d[j]) + (i === j ? ridge : 0);
for (r = 0; r < j; r++) s -= L[i][r] * L[j][r];
if (i === j) { if (s <= 0) { ok = false; break; } L[i][i] = Math.sqrt(s); }
else L[i][j] = s / L[j][j];
}
}
if (ok) return { ridge: ridge, solve: function (y) {
var z = new Array(k), x = new Array(k), q, t;
for (q = 0; q < k; q++) { t = y[q] / d[q]; for (r = 0; r < q; r++) t -= L[q][r] * z[r]; z[q] = t / L[q][q]; }
for (q = k - 1; q >= 0; q--) { t = z[q]; for (r = q + 1; r < k; r++) t -= L[r][q] * x[r]; x[q] = t / L[q][q]; }
for (q = 0; q < k; q++) x[q] /= d[q];
return x;
} };
}
return null;
}

var holder = cfg.container && typeof cfg.container === 'object' ? cfg.container : null;
var modelKey = JSON.stringify([measures, ordinals, nominalCol]);
var last = holder && holder.__lchPredictorLast && holder.__lchPredictorLast.key === modelKey ? holder.__lchPredictorLast.fit : null;

function fit(rowsInView) {
var rows = rowsInView ? (Array.isArray(rowsInView) ? rowsInView : rowsInView.rows || []) : allRows;
var notes = [], excluded = [], tracks = [];
var nominal = null;
if (nominalCol) {
var counts = {}, order = [];
rows.forEach(function (row) {
var key = levelKey(cell(row, nominalCol));
if (key === '') return;
if (!counts[key]) { counts[key] = 0; order.push(key); }
counts[key]++;
});
order.sort(function (a, b) { return counts[b] - counts[a] || (a < b ? -1 : a > b ? 1 : 0); });
var kept = [], pooled = [];
order.forEach(function (lv) { if (counts[lv] >= minPerLevel) kept.push(lv); else pooled.push(lv); });
var map = {};
kept.forEach(function (lv) { map[lv] = lv; });
if (pooled.length) {
pooled.forEach(function (lv) { map[lv] = 'other'; });
kept.push('other');
notes.push(d3.llmText('d3.predictor.pooled_other', 'fewer than {count} rows each, pooled into other: {levels}', { count: minPerLevel, levels: pooled.join(', ') }, minPerLevel));
}
if (kept.length > maxLevels) {
excluded.push({ name: nominalCol, reason: 'levels', levels: kept.length });
} else if (kept.length < 2) {
excluded.push({ name: nominalCol, reason: 'constant' });
} else {
nominal = { name: nominalCol, levels: kept, map: map, dummies: kept.slice(1) };
}
}
var cand = measures.map(function (m) { return { name: m, kind: 'measure' }; })
.concat(ordNames.map(function (o) { return { name: o, kind: 'ordinal', levels: ordinals[o].slice() }; }));
function valueOf(v, row) { return v.kind === 'ordinal' ? rankOf(v.name, cell(row, v.name)) : num(cell(row, v.name)); }
var used = [], blanks = 0;
rows.forEach(function (row) {
var vals = cand.map(function (v) { return valueOf(v, row); });
var lv = nominal ? nominal.map[levelKey(cell(row, nominal.name))] : null;
if (vals.some(function (x) { return !isFinite(x); }) || (nominal && !lv)) { blanks++; return; }
used.push({ vals: vals, level: lv });
});
if (blanks) notes.push(blanks === 1 ? d3.llmText('d3.allocator.blank_rows', '{count} row with a blank left out', { count: blanks }, blanks) : d3.llmText('d3.allocator.blank_rows', '{count} rows with a blank left out', { count: blanks }, blanks));
var n = used.length;
var dummyCount = nominal ? nominal.dummies.length : 0;
var floor = cfg.minRows || Math.max(30, 10 * (cand.length - 1 + dummyCount));
if (n < floor && last) {
var keep = {};
for (var key in last) if (Object.prototype.hasOwnProperty.call(last, key)) keep[key] = last[key];
keep.stale = true; keep.nInView = n; keep.nominalFrequencies = null;
return keep;
}
function column(idx) { return used.map(function (u) { return u.vals[idx]; }); }
function mean(a) { var s = 0; for (var i = 0; i < a.length; i++) s += a[i]; return a.length ? s / a.length : NaN; }
function cov(a, b, ma, mb) { var s = 0; for (var i = 0; i < a.length; i++) s += (a[i] - ma) * (b[i] - mb); return a.length > 1 ? s / (a.length - 1) : NaN; }
var live = [];
cand.forEach(function (v, idx) {
var col = column(idx), mv = mean(col), vv = cov(col, col, mv, mv);
if (!(vv > 0)) { excluded.push({ name: v.name, reason: 'constant' }); return; }
live.push({ v: v, idx: idx, col: col, mean: mv, variance: vv });
});
var model = [];
live.forEach(function (a) {
for (var j = 0; j < model.length; j++) {
var b = model[j];
if (a.v.kind !== 'measure' || b.v.kind !== 'measure') continue;
var c = cov(a.col, b.col, a.mean, b.mean);
if (Math.abs(c / Math.sqrt(a.variance * b.variance)) >= collinearAt) {
var slope = c / b.variance;
var resid = 0;
for (var i = 0; i < n; i++) { var e = a.col[i] - (a.mean + slope * (b.col[i] - b.mean)); resid += e * e; }
tracks.push({ name: a.v.name, partner: b.v.name, a: a.mean - slope * b.mean, b: slope,
s2: n > 2 ? resid / (n - 2) : 0, partnerMean: b.mean, partnerSxx: b.variance * (n - 1),
min: a.col.reduce(function (m, x) { return x < m ? x : m; }, Infinity), max: a.col.reduce(function (m, x) { return x > m ? x : m; }, -Infinity), mean: a.mean });
return;
}
}
model.push(a);
});
var vars = model.map(function (a) {
var mn = Infinity, mx = -Infinity;
a.col.forEach(function (x) { if (x < mn) mn = x; if (x > mx) mx = x; });
return { name: a.v.name, kind: a.v.kind, levels: a.v.levels, values: a.col, mean: a.mean, min: mn, max: mx };
});
if (nominal) nominal.dummies.forEach(function (lv) {
var col = used.map(function (u) { return u.level === lv ? 1 : 0; });
vars.push({ name: nominal.name + '=' + lv, kind: 'dummy', level: lv, values: col, mean: mean(col), min: 0, max: 1 });
});
var k = vars.length, S = [];
for (var p = 0; p < k; p++) {
S.push(new Array(k));
for (var q = 0; q <= p; q++) S[p][q] = cov(vars[p].values, vars[q].values, vars[p].mean, vars[q].mean);
}
for (p = 0; p < k; p++) for (q = p + 1; q < k; q++) S[p][q] = S[q][p];
var freq = null;
if (nominal) {
freq = nominal.levels.map(function (lv) {
var c = used.filter(function (u) { return u.level === lv; }).length;
return { level: lv, count: c, share: n ? c / n : 0 };
});
}
var result = { model: 'linear', n: n, nInView: n, floor: floor, belowFloor: n < floor, stale: false,
vars: vars.map(function (v) { return { name: v.name, kind: v.kind, mean: v.mean, min: v.min, max: v.max, levels: v.levels }; }),
excluded: excluded, tracks: tracks, notes: notes, nominal: nominal ? { name: nominal.name, levels: nominal.levels } : null,
nominalFrequencies: freq, _vars: vars, _S: S, _nominal: nominal };
if (n >= floor) { last = result; if (holder) holder.__lchPredictorLast = { key: modelKey, fit: result }; }
return result;
}

var current = null;

function predict(pins, confidence) {
var f = current || (current = fit());
if (!f || f.n < 3) return { confidence: confidence, rows: [], notes: [d3.llmText('d3.predictor.too_few_rows', 'too few rows to fit')] };
var c = +confidence;
if (!(c > 0 && c < 1)) c = 0.9;
var vars = f._vars, S = f._S, nominal = f._nominal, n = f.n;
var byName = {};
vars.forEach(function (v, i) { byName[v.name] = i; });
var trackOf = {};
f.tracks.forEach(function (t) { trackOf[t.name] = t; });
pins = pins || {};
var pinned = {}, notes = [], pinnedTracks = {};
var nominalLevel = null;
Object.keys(pins).forEach(function (name) {
var raw = pins[name];
if (raw === null || raw === undefined || String(raw).trim() === '') return;
if (nominal && name === nominal.name) {
var key = levelKey(raw);
if (key.toLowerCase() === 'any') return;
var hit = null;
nominal.levels.forEach(function (lv) { if (lv.toLowerCase() === key.toLowerCase()) hit = lv; });
if (!hit && nominal.map[key]) hit = nominal.map[key];
if (hit) nominalLevel = hit; else notes.push(d3.llmText('d3.predictor.no_level', '{name}: no level named {level}', { name: name, level: key }));
return;
}
if (trackOf[name]) {
var t = trackOf[name], v = num(raw);
if (!isFinite(v)) { notes.push(d3.llmText('d3.predictor.not_a_number', '{name}: not a number', { name: name })); return; }
pinnedTracks[name] = v;
if (byName[t.partner] !== undefined && pins[t.partner] === undefined) pinned[byName[t.partner]] = (v - t.a) / t.b;
return;
}
var i = byName[name];
if (i === undefined || vars[i].kind === 'dummy') return;
var val = vars[i].kind === 'ordinal' ? rankOf(name, raw) : num(raw);
if (!isFinite(val)) { notes.push(d3.llmText('d3.predictor.could_not_read', '{name}: could not read {value}', { name: name, value: raw })); return; }
pinned[i] = val;
});
var P = [], x0 = [];
Object.keys(pinned).map(Number).sort(function (a, b) { return a - b; }).forEach(function (i) { P.push(i); x0.push(pinned[i]); });
if (nominalLevel) vars.forEach(function (v, i) { if (v.kind === 'dummy') { P.push(i); x0.push(v.level === nominalLevel ? 1 : 0); } });
var F = [];
vars.forEach(function (v, i) { if (v.kind !== 'dummy' && pinned[i] === undefined) F.push(i); });
var dfree = n - P.length - 1;
if (dfree < 1) return { confidence: c, n: n, df: dfree, rows: [], notes: notes.concat([d3.llmText('d3.predictor.too_many_pins', 'more pins than the rows can carry')]) };
var tq = tquantile((1 + c) / 2, dfree);
var dev = x0.map(function (x, j) { return x - vars[P[j]].mean; });
var w = [], h = 0, sol = null;
if (P.length) {
var SPP = P.map(function (a) { return P.map(function (b) { return S[a][b]; }); });
sol = solver(SPP);
if (!sol) return { confidence: c, n: n, df: dfree, rows: [], notes: notes.concat([d3.llmText('d3.predictor.not_solved', 'the pinned measures could not be solved together')]) };
if (sol.ridge > 0) notes.push(d3.llmText('d3.predictor.near_collinear', 'the pinned measures nearly determine each other'));
w = sol.solve(dev);
for (var j = 0; j < P.length; j++) h += dev[j] * w[j];
h /= (n - 1);
}
var bandOf = {};
F.forEach(function (fi) {
var centre = vars[fi].mean, condVar = S[fi][fi];
if (P.length) {
var sFP = P.map(function (a) { return S[fi][a]; });
var b = sol.solve(sFP);
for (var j = 0; j < P.length; j++) { centre += sFP[j] * w[j]; condVar -= sFP[j] * b[j]; }
}
var s2 = Math.max(0, condVar) * (n - 1) / dfree;
var half = tq * Math.sqrt(s2 * (1 + 1 / n + h));
var explained = S[fi][fi] > 0 ? Math.min(1, Math.max(0, 1 - Math.max(0, condVar) / S[fi][fi])) : 0;
bandOf[fi] = { centre: centre, lo: centre - half, hi: centre + half, explained: explained };
});
function labelAt(levels, r) { var i = Math.round(Math.min(levels.length, Math.max(1, r))) - 1; return levels[i]; }
var rows = [];
measures.concat(ordNames).forEach(function (name) {
var gone = f.excluded.filter(function (e) { return e.name === name; })[0];
if (gone) { rows.push({ name: name, kind: ordinals[name] ? 'ordinal' : 'measure', excluded: gone.reason }); return; }
if (trackOf[name]) {
var t = trackOf[name], pi = byName[t.partner], row = { name: name, kind: 'measure', tracks: t.partner, min: t.min, max: t.max, mean: t.mean };
if (pinnedTracks[name] !== undefined) { row.pinned = true; row.value = pinnedTracks[name]; rows.push(row); return; }
var xp = pinned[pi] !== undefined ? pinned[pi] : (bandOf[pi] ? bandOf[pi].centre : vars[pi].mean);
row.pinned = false; row.centre = t.a + t.b * xp;
if (pinned[pi] !== undefined) {
var hp = (xp - t.partnerMean) * (xp - t.partnerMean) / t.partnerSxx;
var half = tquantile((1 + c) / 2, Math.max(1, n - 2)) * Math.sqrt(t.s2 * (1 + 1 / n + hp));
row.lo = row.centre - half; row.hi = row.centre + half; row.explained = 1;
} else {
var e1 = t.a + t.b * bandOf[pi].lo, e2 = t.a + t.b * bandOf[pi].hi;
row.lo = Math.min(e1, e2); row.hi = Math.max(e1, e2); row.explained = bandOf[pi].explained;
}
row.weak = P.length > 0 && row.explained < weakBelow;
rows.push(row);
return;
}
var i = byName[name], v = vars[i], out = { name: name, kind: v.kind, min: v.min, max: v.max, mean: v.mean };
if (pinned[i] !== undefined && pinnedTracks[name] === undefined && pins[name] !== undefined) {
out.pinned = true; out.value = pinned[i]; out.outside = pinned[i] < v.min || pinned[i] > v.max;
if (v.kind === 'ordinal') out.level = labelAt(v.levels, pinned[i]);
} else {
var bnd = bandOf[i];
if (!bnd) { out.pinned = true; out.value = pinned[i]; out.via = 'tracks'; rows.push(out); return; }
out.pinned = false; out.centre = bnd.centre; out.lo = bnd.lo; out.hi = bnd.hi; out.explained = bnd.explained;
out.weak = P.length > 0 && bnd.explained < weakBelow;
if (v.kind === 'ordinal') out.labels = { lo: labelAt(v.levels, bnd.lo), hi: labelAt(v.levels, bnd.hi), centre: labelAt(v.levels, bnd.centre) };
}
rows.push(out);
});
if (nominal) rows.push(nominalLevel
? { name: nominal.name, kind: 'nominal', pinned: true, level: nominalLevel, levels: nominal.levels }
: { name: nominal.name, kind: 'nominal', pinned: false, levels: nominal.levels, frequencies: f.nominalFrequencies || [] });
var nonNeg = {};
(cfg.nonNegative || []).forEach(function (nm) { nonNeg[String(nm)] = true; });
var clipped = [];
rows.forEach(function (r) {
if (r.pinned || r.kind !== 'measure' || !nonNeg[r.name] || !(r.lo < 0)) return;
r.lo = 0; if (r.centre < 0) r.centre = 0; if (r.hi < 0) r.hi = 0;
r.clipped = true; clipped.push(r.name);
});
if (clipped.length) notes.push(clipped.length === 1
? d3.llmText('d3.predictor.clipped', '{names}: predicted range clipped at 0 - it is never negative', { names: clipped.join(', ') }, clipped.length)
: d3.llmText('d3.predictor.clipped', '{names}: predicted ranges clipped at 0 - they are never negative', { names: clipped.join(', ') }, clipped.length));
return { confidence: c, n: n, df: dfree, leverage: h, t: tq, stale: !!f.stale, nInView: f.nInView, rows: rows,
notes: f.notes.concat(notes) };
}

return {
fit: function (rowsInView) { current = fit(rowsInView); return current; },
predict: predict,
tQuantile: tquantile
};
};
d3.llmFitLabel = function (sel, widthAccessor, opts) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: a string is fitted at no smaller size than a chart may draw it
if (widthAccessor != null && typeof widthAccessor === 'object' && !Array.isArray(widthAccessor)) {
var wobj = widthAccessor, wopts = {};
for (var wk in wobj) if (Object.prototype.hasOwnProperty.call(wobj, wk) && wk !== 'width' && wk !== 'room') wopts[wk] = wobj[wk];
if (opts != null && typeof opts === 'object') {
for (var wk2 in opts) if (Object.prototype.hasOwnProperty.call(opts, wk2)) wopts[wk2] = opts[wk2];
} else if (typeof opts === 'number' && opts > 0 && wopts.fontSize == null) {
wopts.fontSize = Math.max(TYPE_FLOOR, opts);
}
widthAccessor = wobj.width != null ? wobj.width : wobj.room;
opts = wopts;
}
if (typeof sel === 'string' || typeof sel === 'number') {
var so = (opts != null && typeof opts === 'object') ? opts
: ((arguments[3] != null && typeof arguments[3] === 'object') ? arguments[3] : {});
var sfs = Math.max(TYPE_FLOOR, (typeof opts === 'number' && opts > 0) ? opts : (+so.fontSize > 0 ? +so.fontSize : TYPE_FLOOR));
var sopts = {};
for (var sk in so) if (Object.prototype.hasOwnProperty.call(so, sk)) sopts[sk] = so[sk];
sopts.text = String(sel);
sopts.shrinkTo = null;
var holder = null, sn = null;
try {
if (typeof document !== 'undefined' && document && document.body && document.createElementNS) {
holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
holder.setAttribute('width', '0'); holder.setAttribute('height', '0');
holder.style.position = 'absolute'; holder.style.left = '-10000px'; holder.style.visibility = 'hidden';
sn = document.createElementNS('http://www.w3.org/2000/svg', 'text');
holder.appendChild(sn);
document.body.appendChild(holder);
}
} catch (e) { holder = null; sn = null; }
if (!sn) {
sn = { textContent: '', style: {}, fs: sfs,
getAttribute: function (a) { return a === 'font-size' ? String(sn.fs) : null; },
setAttribute: function (a, v) { if (a === 'font-size') sn.fs = +v; } };
}
var fitted;
try {
sn.setAttribute('font-size', String(sfs));
if (so.fontFamily) sn.setAttribute('font-family', String(so.fontFamily));
if (so.fontWeight) sn.setAttribute('font-weight', String(so.fontWeight));
d3.llmFitLabel({ each: function (fn) { fn.call(sn, null, 0); return this; } }, widthAccessor, sopts);
fitted = sn.textContent == null ? '' : String(sn.textContent);
} catch (e) { fitted = String(sel); }
try { if (holder && holder.parentNode) holder.parentNode.removeChild(holder); } catch (e) { /* detached */ }
return fitted;
}
opts = opts || {};
var pad = opts.pad == null ? 4 : opts.pad;
var minWidth = opts.minWidth == null ? 14 : opts.minWidth;
var ell = opts.ellipsis == null ? '\u2026' : opts.ellipsis;
var fallbackFs = opts.fontSize == null ? 10 : opts.fontSize;
var shrinkTo = opts.shrinkTo == null ? null : +opts.shrinkTo;
var overflow = opts.overflow === 'drop' ? 'drop' : 'truncate';
var NEAR_MISS_PX = 1, SHORT_KEEP = 3;   // 1 px, flat: a census of 142 saved generations found 8% of a wide room overprinting long labels
function nearMiss(w, room) { return overflow !== 'drop' && w <= room + NEAR_MISS_PX; }
function keepShort(s, w, room) { return overflow !== 'drop' && s.length <= SHORT_KEEP && w <= room * 1.5; }
var sibs = Array.isArray(opts.distinctFrom) ? opts.distinctFrom : null;

if (!sel || typeof sel.each !== 'function') return sel;

var DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\uFF10-\uFF19]/;
var JOIN = /[.,'\u00A0\u202F\u2019\u066B\u066C]/;
var GLUED = /[A-Za-z%\u2030]/;
var LEAD = /[+\-\u2212$\u20AC\u00A3\u00A5\u20B9]/;
function numberSafeCut(s, lo) {
if (!(lo > 0) || lo >= s.length) return lo;
var a = s.charAt(lo - 1), b = s.charAt(lo);
var splits = DIGIT.test(a)
? (DIGIT.test(b) || GLUED.test(b) || (JOIN.test(b) && DIGIT.test(s.charAt(lo + 1))))
: (lo >= 2 && JOIN.test(a) && DIGIT.test(s.charAt(lo - 2)) && DIGIT.test(b));
if (!splits) return lo;
var i = lo;
while (i > 0 && (DIGIT.test(s.charAt(i - 1))
|| (i >= 2 && JOIN.test(s.charAt(i - 1)) && DIGIT.test(s.charAt(i - 2))))) i--;
while (i > 0 && LEAD.test(s.charAt(i - 1))) i--;
while (i > 0 && /\s/.test(s.charAt(i - 1))) i--;
return i;
}

function fontSizeOf(node) {
try {
var a = parseFloat(node.getAttribute && node.getAttribute('font-size'));
if (a > 0) return a;
var s = node.style && node.style.fontSize ? parseFloat(node.style.fontSize) : NaN;
if (s > 0) return s;
} catch (e) { /* fall through */ }
return fallbackFs;
}

function setFontSize(node, fs) {
try { if (node.setAttribute) node.setAttribute('font-size', String(fs)); } catch (e) { /* detached */ }
}

function measure(node, txt) {
try {
if (typeof node.getComputedTextLength === 'function') {
var w = node.getComputedTextLength();
if (w > 0) return w;
}
} catch (e) { /* fall through */ }
return String(txt).length * fontSizeOf(node) * 0.6;
}

function ownerSvg(node) {
try {
if (node.ownerSVGElement) return node.ownerSVGElement;
for (var p = node.parentNode; p; p = p.parentNode) {
if (p.nodeName && String(p.nodeName).toLowerCase() === 'svg') return p;
}
} catch (e) { /* detached */ }
return null;
}
function shownText(node) {
var kids = node && node.childNodes;
if (!kids || !kids.length) return node.textContent == null ? '' : String(node.textContent);
var s = '';
for (var c = 0; c < kids.length; c++) {
var k = kids[c];
if (k.nodeType === 3) s += k.nodeValue;
else if (k.nodeType === 1 && String(k.nodeName).toLowerCase() !== 'title') s += shownText(k);
}
return s;
}
function setShown(node, s) {
var kids = node.childNodes, keep = [];
if (kids && kids.length) {
for (var c = 0; c < kids.length; c++) {
if (kids[c].nodeType === 1 && String(kids[c].nodeName).toLowerCase() === 'title') keep.push(kids[c]);
}
}
node.textContent = s;
for (var q = 0; q < keep.length; q++) node.appendChild(keep[q]);
}
function hiddenIn(node, svg) {
try {
for (var p = node, hop = 0; p && hop < 64; p = p.parentNode, hop++) {
if (p.getAttribute && (p.getAttribute('display') === 'none' || p.getAttribute('visibility') === 'hidden')) return true;
if (p.style && (p.style.display === 'none' || p.style.visibility === 'hidden')) return true;
if (p === svg) break;
}
} catch (e) { /* read as shown */ }
return false;
}
function fittedFrom(node) {
return node.__llmFitFrom != null ? node.__llmFitFrom : node.__llmFullLabel;
}
function live(svg, en) {
if (shownText(en.node) !== en.visible) return false;
if (fittedFrom(en.node) != null && String(fittedFrom(en.node)) !== en.full) return false;
try { if (typeof svg.contains === 'function' && !svg.contains(en.node)) return false; } catch (e) { /* keep */ }
return true;
}
function endsWithText(s, t) { return s.length >= t.length && s.slice(s.length - t.length) === t; }
function ending(en, others) {
var f = en.full, n = en.node, E = en.ell;
if (en.drop) return '';
var fits = function (s) { setShown(n, s); return measure(n, s) <= en.room; };
var t = -1;
for (var s = f.length - 1; s >= 1 && t < 0; s--) {
var tl = f.slice(s), alone = true;
for (var o = 0; o < others.length && alone; o++) if (endsWithText(others[o], tl)) alone = false;
if (alone) t = s;
}
if (t < 1) return '';
if (DIGIT.test(f.charAt(t)) && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) {
while (t > 0 && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) t--;
}
if (t < 1) return '';
var ws = t;
while (ws > 0 && !/\s/.test(f.charAt(ws - 1))) ws--;
if (ws > 0 && ws < t && fits(E + f.slice(ws))) t = ws;
else if (!fits(E + f.slice(t))) return '';
var tail = f.slice(t), lo = 0, hi = t - 1;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
if (fits(f.slice(0, mid) + E + tail)) lo = mid; else hi = mid - 1;
}
var head = f.slice(0, numberSafeCut(f, lo)).replace(/\s+$/, '');
if (head.length < 2) head = '';
return head + E + tail;
}
function distinguish(group) {
var g, h, s, en, others;
for (g = 0; g < group.length; g++) {
en = group[g];
others = [];
for (h = 0; h < group.length; h++) if (group[h].full !== en.full) others.push(group[h].full);
try { s = ending(en, others); } catch (e) { s = ''; }
setShown(en.node, s);
en.visible = shownText(en.node);
}
for (g = 0; g < group.length; g++) {
for (h = g + 1; h < group.length; h++) {
var a = group[g], b = group[h];
if (a.visible && a.visible === b.visible && a.full !== b.full) {
setShown(a.node, ''); a.visible = '';
setShown(b.node, ''); b.visible = '';
}
}
}
}
function clashes(reg, svg, en) {
var group = [en], differ = false;
if (hiddenIn(en.node, svg)) return group;
for (var k = reg.length - 1; k >= 0; k--) {
var o = reg[k];
if (o === en || o.visible !== en.visible) continue;
if (!live(svg, o)) { reg.splice(k, 1); continue; }
if (hiddenIn(o.node, svg)) continue;
group.push(o);
if (o.full !== en.full) differ = true;
}
return differ ? group : [en];
}
function settle(node, room) {
var svg = ownerSvg(node);
if (!svg) return;
var reg = svg.__llmFitRegistry;
if (!Array.isArray(reg)) { reg = []; svg.__llmFitRegistry = reg; }
var k;
for (k = reg.length - 1; k >= 0; k--) if (reg[k].node === node) reg.splice(k, 1);
if (reg.length >= (reg.sweepAt || 256)) {
for (k = reg.length - 1; k >= 0; k--) if (!live(svg, reg[k])) reg.splice(k, 1);
reg.sweepAt = Math.max(256, reg.length * 2);
}
var vis = shownText(node);
if (!(room > 0) || !vis) return;
var me = { node: node, full: fittedFrom(node) == null ? vis : String(fittedFrom(node)),
visible: vis, room: room, ell: ell, drop: overflow === 'drop' };
reg.push(me);
var queue = [me];
for (var round = 0; queue.length && round < 32; round++) {
var en = queue.shift();
if (!en.visible) continue;
var group = clashes(reg, svg, en);
if (group.length < 2) continue;
distinguish(group);
for (var g = 0; g < group.length; g++) if (group[g].visible) queue.push(group[g]);
}
}

function fitOne(node, d, i) {
var full, alts = [];
if (opts.text != null) {
try {
full = typeof opts.text === 'function' ? opts.text.call(node, d, i) : opts.text;
} catch (e) { full = ''; }
if (Array.isArray(full)) { alts = full.slice(1); full = full[0]; }
full = full == null ? '' : String(full);
node.__llmFullLabel = full;
node.textContent = full;              // authoritative: an EMPTY label must CLEAR the node,
if (!full) return;                    // never leave the previous frame's text standing
} else {
full = node.__llmFullLabel;
if (full == null) {
full = node.textContent == null ? '' : String(node.textContent);
node.__llmFullLabel = full;
}
if (!full) return;
}
node.__llmFitFrom = null;
var fo = opts.forms;
if (typeof fo === 'function') { try { fo = fo.call(node, d, i); } catch (e) { fo = null; } }
if (fo != null) alts = alts.concat(Array.isArray(fo) ? fo : [fo]);
var cands = [full];
for (var ci = 0; ci < alts.length; ci++) {
var alt = alts[ci] == null ? '' : String(alts[ci]);
if (alt && cands.indexOf(alt) < 0) cands.push(alt);
}

var room;
try {
room = typeof widthAccessor === 'function'
? widthAccessor.call(node, d, i)
: widthAccessor;
} catch (e) { room = 0; }
room = (room == null ? 0 : +room) - pad * 2;

if (!(room > 0) || room < minWidth) { node.textContent = ''; return room; }

if (shrinkTo != null) {
if (node.__llmFullFontSize == null) node.__llmFullFontSize = fontSizeOf(node);
setFontSize(node, node.__llmFullFontSize);
}
node.textContent = full;
var w = measure(node, full);
if (w <= room) return room;                                // fits whole - done
if (nearMiss(w, room)) return room;                        // a near miss is drawn whole

var c;
for (c = 1; c < cands.length; c++) {
node.textContent = cands[c];
if (measure(node, cands[c]) <= room) { node.__llmFitFrom = cands[c]; return room; }
}

if (shrinkTo != null && shrinkTo > 0) {
for (c = 0; c < cands.length; c++) {
setFontSize(node, node.__llmFullFontSize);
node.textContent = cands[c];
var cur = fontSizeOf(node), wc = measure(node, cands[c]);
if (!(cur > shrinkTo)) break;
var fs = Math.max(shrinkTo, Math.floor((cur * room / wc) * 2) / 2);
for (; fs >= shrinkTo; fs -= 0.5) {
setFontSize(node, fs);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
setFontSize(node, shrinkTo);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
}
if (cands.length > 1) { full = cands[cands.length - 1]; node.__llmFitFrom = full; }
node.textContent = full;
if (overflow === 'drop') { node.textContent = ''; return room; }

var lo = 0, hi = full.length;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
node.textContent = full.slice(0, mid) + ell;
if (measure(node, node.textContent) <= room) lo = mid; else hi = mid - 1;
}
lo = numberSafeCut(full, lo);
if (sibs) {
var shared = 0;
for (var si = 0; si < sibs.length; si++) {
var o = sibs[si] == null ? '' : String(sibs[si]);
if (o === full) continue;
var k = 0;
while (k < o.length && k < full.length && o.charAt(k) === full.charAt(k)) k++;
if (k > shared) shared = k;
}
if (shared > 0 && lo <= shared) {
var a = 1, b = full.length;
while (a < b) {
var m = (a + b) >> 1;
node.textContent = ell + full.slice(m);
if (measure(node, node.textContent) <= room) b = m; else a = m + 1;
}
var inNum = function (i) {
return i > 0 && i < full.length && DIGIT.test(full.charAt(i))
&& (DIGIT.test(full.charAt(i - 1)) || (i >= 2 && JOIN.test(full.charAt(i - 1)) && DIGIT.test(full.charAt(i - 2))));
};
if (inNum(a)) {
var t0 = a;
while (t0 > 0 && (DIGIT.test(full.charAt(t0 - 1)) || (t0 >= 2 && JOIN.test(full.charAt(t0 - 1)) && DIGIT.test(full.charAt(t0 - 2))))) t0--;
node.textContent = ell + full.slice(t0);
a = measure(node, node.textContent) <= room ? t0 : full.length;
}
node.textContent = a < full.length ? ell + full.slice(a) : (keepShort(full, w, room) ? full : '');
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : (keepShort(full, w, room) ? full : '');
return room;
}

sel.each(function (d, i) {
var room = fitOne(this, d, i);
try { settle(this, room); } catch (e) { /* a failed sibling check leaves the fit as it stands */ }
});

return sel;
};

function render(container, data, options) {
  const TYPE_FLOOR = 10;
  container.replaceChildren();

  var ORDINALS = {"Weekday":["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]};
  var NOMINAL = '';
  var MIN_ROWS = 30;
  var ROW_IS = "Date x UserID x AvgHeartRate";
  var NONNEG = ["Sum of Steps","Sum of CaloriesBurned","SleepHours"];

  var W = options.width, H = options.height;
  var FS = Math.max(TYPE_FLOOR, Math.min(14, Math.min(W, H) / 55));
  var SUB_FS = Math.max(TYPE_FLOOR, FS * 0.9), CAP_FS = Math.max(TYPE_FLOOR, FS * 0.8);
  var fg = options.themeFg || 'currentColor';
  var accent = options.themeAccent || ((options.palette && options.palette.length) ? options.palette[0] : fg);
  var loc = options.cultureCode || 'en-US';
  var svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  var NEEDS = 'What-if predictor needs 3 to 10 numeric measures over enough rows to fit them.';

  function emptyFrame(msg) {
    svg.append('rect').attr('x', 0.5).attr('y', 0.5).attr('width', W - 1).attr('height', H - 1)
      .attr('fill', 'none').attr('stroke', fg).attr('stroke-opacity', 0.25);
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle')
      .attr('font-size', FS).attr('fill', fg).text(msg);
  }

  var cols = data.columns || [], rows = data.rows || [];
  var idx = function (n) { return data.columns.findIndex(function (c) { return c.name === n; }); };
  var measures = [], overflow = [], identity = '';
  cols.forEach(function (c) {
    if (c.name === '__rowIdx__' || c.name.indexOf('__geo') === 0) return;
    if (ORDINALS[c.name] || c.name === NOMINAL) return;
    if (c.isMeasure) { if (measures.length < 10) measures.push(c.name); else overflow.push(c.name); return; }
    if (!identity) identity = c.name;
  });
  var ordinals = {};
  Object.keys(ORDINALS).forEach(function (n) { if (idx(n) >= 0 && ORDINALS[n].length > 1) ordinals[n] = ORDINALS[n]; });
  var nominal = NOMINAL && idx(NOMINAL) >= 0 ? NOMINAL : '';
  if (measures.length + Object.keys(ordinals).length < 3) throw new Error('INVALID:' + NEEDS);
  if (!rows.length) { emptyFrame(options.noDataText || d3.llmText('d3.whatiflane.no_data', 'No data')); return; }

  svg.append('g').attr('class', 'lch-row-stubs').attr('display', 'none').attr('aria-hidden', 'true')
    .selectAll('desc').data(rows).join('desc').attr('data-row-idx', function (d, i) { return i; });

  var pred = d3.llmPredictor(data, { measures: measures, ordinals: ordinals, nominal: nominal || null,
    minRows: MIN_ROWS, nonNegative: NONNEG, container: container });
  var fit = pred.fit(rows);
  if (fit.n < 3 || fit.vars.filter(function (v) { return v.kind !== 'dummy'; }).length < 2) { emptyFrame(d3.llmText('d3.whatiflane.needs', NEEDS)); return; }

  function isPct(name) { var c = cols[idx(name)] || {}; return /%/.test(String(c.format || c.formatString || '')); }
  var pctF = new Intl.NumberFormat(loc, { style: 'percent', maximumSignificantDigits: 3 });
  var bigF = new Intl.NumberFormat(loc, { notation: 'compact', maximumSignificantDigits: 3 });
  var smallF = new Intl.NumberFormat(loc, { maximumSignificantDigits: 3 });
  function fmt(name, v) {
    if (v === null || v === undefined || !isFinite(v)) return '';
    if (isPct(name)) return pctF.format(v);
    return Math.abs(v) >= 10000 ? bigF.format(v) : smallF.format(v);
  }
  var shareF = new Intl.NumberFormat(loc, { style: 'percent', maximumFractionDigits: 0 });

  var names = measures.concat(Object.keys(ordinals)).concat(nominal ? [nominal] : []);
  var tw = function (s, fs) { return String(s == null ? '' : s).length * (+fs > 0 ? +fs : 10) * 0.6; };
  var PAD = FS * 0.8;
  var STRIP_Y = FS * 1.4;
  var ROWS_Y = STRIP_Y + FS * 2.2;

  var captionLines = function (sentences, room, maxLines, fs) {
    var lines = [], ends = [];
    sentences.forEach(function (s) {
      var cur = '';
      String(s).split(' ').forEach(function (w) {
        var cand = cur ? cur + ' ' + w : w;
        if (!cur || d3.llmFitLabel(cand, room, { fontSize: Math.max(TYPE_FLOOR, fs) }) === cand) cur = cand;
        else { lines.push(cur); ends.push(false); cur = w; }
      });
      if (cur) { lines.push(cur); ends.push(true); }
    });
    maxLines = Math.max(1, Math.floor(maxLines) || 1);
    if (lines.length <= maxLines) return lines;
    var rest = lines.slice(maxLines - 1).map(function (l, i) { return l + (ends[maxLines - 1 + i] && maxLines + i < lines.length ? ';' : ''); });
    return lines.slice(0, maxLines - 1).concat([rest.join(' ')]);
  };
  var CAP_LINE = FS * 1.3;
  var noteNoDirection = d3.llmText('d3.whatiflane.note_no_direction', 'estimated from how these measures move together; it claims no direction');
  var noteOrdinals = Object.keys(ordinals).map(function (n) { return d3.llmText('d3.whatiflane.note_ordinal', '{name} treated as equally spaced: {levels}', { name: n, levels: ordinals[n].join(', ') }); });
  var noteLevels = (fit.excluded || []).filter(function (e) { return e.reason === 'levels'; }).map(function (e) { return d3.llmText('d3.whatiflane.note_levels', '{name} has {count} values - slice it on the page instead', { name: e.name, count: String(e.levels) }); });
  var noteOverflow = overflow.length ? [overflow.length === 1 ? d3.llmText('d3.whatiflane.overflow', '{count} more measure not in the model: {names}', { count: String(overflow.length), names: overflow.join(', ') }, overflow.length) : d3.llmText('d3.whatiflane.overflow', '{count} more measures not in the model: {names}', { count: String(overflow.length), names: overflow.join(', ') }, overflow.length)] : [];
  var keyLinesFor = function (pct) {
    var legend = d3.llmText('d3.whatiflane.legend', 'thin line = observed range of the rows in view · thick bar = predicted range at {pct} · | = center · hollow bar = weak', { pct: pct });
    var room = W - 2 * PAD, kfs = Math.max(TYPE_FLOOR, CAP_FS), lines = [], cur = '';
    legend.split(' · ').forEach(function (e) {
      var cand = cur ? cur + ' · ' + e : e;
      if (!cur || d3.llmFitLabel(cand, room, { fontSize: kfs }) === cand) cur = cand;
      else { lines.push(cur); cur = e; }
    });
    if (cur) lines.push(cur);
    return lines;
  };
  var KEY_N = Math.max(keyLinesFor('80%').length, keyLinesFor('90%').length, keyLinesFor('95%').length);
  var noteRoom = Math.max(1, Math.min(captionLines((fit.notes || []).concat(noteLevels, noteOverflow, [noteNoDirection], noteOrdinals), W - 2 * PAD, 99, CAP_FS).length + 1,
    Math.floor((H - ROWS_Y - names.length * FS * 1.9 - FS * 1.9 - (KEY_N - 1) * CAP_LINE) / CAP_LINE)));
  var CAP_H = FS * 1.9 + (noteRoom + KEY_N - 1) * CAP_LINE;
  var rowH = Math.max(FS * 1.9, (H - ROWS_Y - CAP_H) / names.length);
  var nameW = Math.min(W * 0.22, d3.max(names, function (n) { return tw(n, SUB_FS); }) + FS * 0.4);
  var boxX = PAD + nameW + FS * 0.6, boxW = Math.max(FS * 5.5, Math.min(FS * 8, W * 0.14));
  var readW = Math.min(W * 0.34, FS * 22);
  var trackX = boxX + boxW + FS * 1.2;
  var trackW = Math.max(FS * 6, W - trackX - readW - PAD - FS);
  var readX = trackX + trackW + FS;

  var strip = svg.append('g').attr('class', 'lch-knobs');
  var body = svg.append('g').attr('class', 'lch-measures');
  var CAP_Y = Math.min(H - FS * 0.6 - (noteRoom + KEY_N - 1) * CAP_LINE, ROWS_Y + rowH * names.length + FS * 1.3);
  var capKey = svg.append('g').attr('class', 'lch-legend');
  var capNotes = svg.append('g').attr('class', 'lch-caption-notes');

  var confidence = 0.9;
  var conf = d3.llmSegmented(svg, { container: container, options: options, key: 'confidence',
    choices: [{ value: '80', label: '80%' }, { value: '90', label: '90%' }, { value: '95', label: '95%' }],
    'default': '90', x: PAD, y: STRIP_Y, fontSize: FS, label: d3.llmText('d3.whatiflane.confidence', 'confidence'),
    onChange: function (v, phase) { confidence = (+v || 90) / 100; if (phase !== 'init') repaint(); } });
  var CORNER_W = Math.min(96, W * 0.25);
  var RESET_TXT = d3.llmText('d3.whatiflane.reset', 'reset');
  function pillTextW(t) { var pr = svg.append('text').attr('font-size', SUB_FS).attr('visibility', 'hidden').text(t), w = 0; try { w = pr.node().getComputedTextLength(); } catch (eW) { w = 0; } pr.remove(); return w > 0 ? w : String(t).length * SUB_FS * 0.6; }
  var resetW = Math.max(20, FS * 3.2, pillTextW(RESET_TXT) + FS * 0.2), resetH = Math.max(20, FS * 2.0), resetLeft = conf.bounds().right + FS;
  var modelNote = strip.append('text').attr('class', 'lch-model').attr('y', STRIP_Y + FS * 0.35)
    .attr('x', resetLeft + resetW + FS * 1.2).attr('font-size', SUB_FS).attr('fill', fg);
  var boxes = {}, nomSeg = null, pins = {};
  var reset = svg.append('g').attr('class', 'lch-reset lch-control').attr('aria-label', RESET_TXT).attr('cursor', 'pointer')
    .on('click', function (ev) {
      if (ev && ev.stopPropagation) ev.stopPropagation();
      Object.keys(boxes).forEach(function (n) { boxes[n].reset(false); });
      if (nomSeg) nomSeg.set('any');
      conf.set('90');
      readPins(); repaint();
    });
  reset.append('rect').attr('x', resetLeft).attr('y', STRIP_Y - resetH / 2).attr('width', resetW).attr('height', resetH)
    .attr('rx', 3).attr('fill', 'transparent').attr('stroke', fg).attr('opacity', 0.6);
  reset.append('text').attr('x', resetLeft + resetW / 2).attr('y', STRIP_Y + FS * 0.35).attr('text-anchor', 'middle')
    .attr('font-size', SUB_FS).attr('fill', fg).text(RESET_TXT);

  var rowG = {};
  names.forEach(function (name, i) {
    var cy = ROWS_Y + rowH * (i + 0.5);
    var g = body.append('g').attr('class', 'lch-measure');
    g.append('text').attr('class', 'lch-measure-name').attr('x', PAD).attr('y', cy + FS * 0.35)
      .attr('font-size', SUB_FS).attr('fill', fg).text(name).append('title').text(name);
    if (name === nominal) {
      var levels = (fit.nominal ? fit.nominal.levels : []).map(String);
      nomSeg = d3.llmSegmented(svg, { container: container, options: options, key: 'pin:' + name,
        choices: levels.map(function (l) { return { value: l, label: l }; }).concat([{ value: 'any', label: d3.llmText('d3.whatiflane.any', 'any') }]),
        'default': 'any', x: boxX, y: cy, fontSize: FS,
        onChange: function (v, phase) { if (phase !== 'init') { readPins(); repaint(); } } });
    } else {
      var lv = ordinals[name] || null;
      boxes[name] = d3.llmNumberEntry(svg, { container: container, options: options, key: 'pin:' + name,
        levels: lv, percent: isPct(name), x: boxX, y: cy, width: boxW, fontSize: FS,
        onChange: function (v, phase) { if (phase !== 'init') { readPins(); repaint(); } } });
    }
    rowG[name] = { g: g, dyn: g.append('g').attr('class', 'lch-measure-live'), cy: cy };
  });

  function readPins() {
    pins = {};
    Object.keys(boxes).forEach(function (n) { var v = boxes[n].value(); if (v !== null && v !== undefined) pins[n] = v; });
    if (nomSeg && nomSeg.value() && nomSeg.value() !== 'any') pins[nominal] = nomSeg.value();
  }

  function repaint() {
    var out = pred.predict(pins, confidence);
    var anyPin = Object.keys(pins).length > 0;
    var mFit = d3.llmText('d3.whatiflane.model', 'linear model fit on {n} rows', { n: String(out.n) });
    var mOne = (ROW_IS || identity) ? d3.llmText('d3.whatiflane.one_row', ' (one row = {what})', { what: (ROW_IS || identity) }) : '';
    var mView = out.stale ? d3.llmText('d3.whatiflane.in_view', '; {n} in view', { n: String(out.nInView) }) : '';
    var mHint = anyPin ? '' : d3.llmText('d3.whatiflane.pin_hint', ' - type a value to pin a measure');
    var modelFull = mFit + mOne + mView + mHint, modelRoom = W - CORNER_W - FS - (+modelNote.attr('x'));
    [modelFull, mFit + mOne + mView, mFit + mView, mFit].some(function (f) {
      modelNote.text(f); d3.llmFitLabel(modelNote, modelRoom, { pad: 0, text: f, overflow: 'drop' }); return modelNote.text() === f;
    });
    if (modelNote.text() && modelNote.text() !== modelFull) modelNote.append('title').text(modelFull);
    var modelDropped = modelNote.text() ? '' : mFit + mOne + mView;
    out.rows.forEach(function (r) {
      var slot = rowG[r.name]; if (!slot) return;
      var dyn = slot.dyn, cy = slot.cy;
      dyn.selectAll('*').remove();
      var readout = dyn.append('text').attr('class', 'lch-readout').attr('x', readX).attr('y', cy + FS * 0.35)
        .attr('font-size', SUB_FS).attr('fill', fg);
      if (r.kind === 'nominal') {
        var fr = r.frequencies || [], segR = nomSeg ? nomSeg.bounds().right : trackX;
        if (r.pinned) {
          var pinX = Math.max(readX, segR + FS);
          var pinText = d3.llmText('d3.whatiflane.pinned_level', 'pinned {level}', { level: r.level });
          readout.attr('x', pinX);
          [pinText, String(r.level)].some(function (f) { readout.text(f); d3.llmFitLabel(readout, W - pinX - PAD, { pad: 0, text: f }); return readout.text() === f; });
          if (readout.text() !== pinText) readout.append('title').text(pinText);
          return;
        }
        var fx = Math.max(trackX, segR + FS), fw = Math.max(FS * 3, readX - FS - fx), bw = fw / Math.max(1, fr.length);
        var nomX = Math.max(readX, fx + fw + FS);
        readout.attr('x', nomX);
        fr.forEach(function (f, k) {
          var hgt = Math.max(1, f.share * rowH * 0.7);
          dyn.append('rect').attr('class', 'lch-freq').attr('x', fx + k * bw + 1).attr('width', Math.max(1, bw - 2))
            .attr('y', cy + rowH * 0.35 - hgt).attr('height', hgt).attr('fill', fg).attr('fill-opacity', 0.35)
            .append('title').text(d3.llmText('d3.whatiflane.freq', '{level}: {share} of rows', { level: f.level, share: shareF.format(f.share) }));
        });
        var freeText = d3.llmText('d3.whatiflane.free', 'free - {levels}', { levels: fr.map(function (f) { return f.level + ' ' + shareF.format(f.share); }).join(', ') });
        var freeNames = d3.llmText('d3.whatiflane.free', 'free - {levels}', { levels: fr.map(function (f) { return f.level; }).join(', ') });
        [freeText, freeNames].some(function (f) {
          readout.text(f); d3.llmFitLabel(readout, W - nomX - PAD, { pad: 0, text: f, overflow: 'drop' }); return readout.text() === f;
        });
        if (readout.text() && readout.text() !== freeText) readout.append('title').text(freeText);
        return;
      }
      if (r.excluded) { readout.text(r.excluded === 'constant' ? d3.llmText('d3.whatiflane.excluded_constant', 'constant - left out of the model') : d3.llmText('d3.whatiflane.excluded', 'left out of the model')); return; }
      var v = fit.vars.filter(function (q) { return q.name === r.name; })[0] || { min: r.min, max: r.max, mean: r.mean };
      var lo = isFinite(v.min) ? v.min : Infinity, hi = isFinite(v.max) ? v.max : -Infinity;
      var ord = ordinals[r.name];
      var past = '';
      if (ord) {
        lo = 1; hi = ord.length;
        if (!r.pinned && isFinite(r.centre)) past = r.centre > hi + 0.5 ? d3.llmText('d3.whatiflane.past_last', ' - past the last level') : (r.centre < 0.5 ? d3.llmText('d3.whatiflane.before_first', ' - before the first level') : '');
      } else {
        [r.value, r.lo, r.hi].forEach(function (q) { if (typeof q === 'number' && isFinite(q)) { lo = Math.min(lo, q); hi = Math.max(hi, q); } });
      }
      if (!isFinite(lo) || !isFinite(hi)) { readout.text(d3.llmText('d3.whatiflane.no_range', 'no range to draw')); return; }
      if (!(hi > lo)) { hi = lo + 1; }
      var x = d3.scaleLinear().domain([lo, hi]).range([trackX, trackX + trackW]);
      if (isFinite(v.min) && isFinite(v.max)) {
        dyn.append('line').attr('class', 'lch-observed').attr('x1', x(v.min)).attr('x2', x(v.max)).attr('y1', cy).attr('y2', cy)
          .attr('stroke', fg).attr('stroke-opacity', 0.45).attr('stroke-width', 1);
        dyn.append('line').attr('class', 'lch-mean').attr('x1', x(v.mean)).attr('x2', x(v.mean))
          .attr('y1', cy - FS * 0.3).attr('y2', cy + FS * 0.3).attr('stroke', fg).attr('stroke-opacity', 0.45);
      }
      if (r.pinned) {
        dyn.append('circle').attr('class', 'lch-pin').attr('cx', x(r.value)).attr('cy', cy).attr('r', Math.max(3, FS * 0.4))
          .attr('fill', accent).attr('stroke', fg).attr('stroke-width', 1);
        readout.text(r.via === 'tracks' ? d3.llmText('d3.whatiflane.set_via_tracks', 'set through the measure it tracks')
          : (r.outside ? d3.llmText('d3.whatiflane.pinned_outside', 'pinned - outside the observed range') : d3.llmText('d3.whatiflane.pinned', 'pinned')));
        return;
      }
      var bh = Math.max(4, FS * 0.7);
      var bLo = ord ? Math.max(lo, Math.min(hi, r.lo)) : r.lo, bHi = ord ? Math.max(lo, Math.min(hi, r.hi)) : r.hi;
      var bC = ord ? Math.max(lo, Math.min(hi, r.centre)) : r.centre;
      dyn.append('rect').attr('class', 'lch-band').attr('x', x(bLo)).attr('width', Math.max(2, x(bHi) - x(bLo)))
        .attr('y', cy - bh / 2).attr('height', bh).attr('rx', 2)
        .attr('fill', r.weak ? 'none' : accent).attr('fill-opacity', r.weak ? null : 0.55)
        .attr('stroke', accent).attr('stroke-width', 1.2);
      dyn.append('line').attr('class', 'lch-centre').attr('x1', x(bC)).attr('x2', x(bC))
        .attr('y1', cy - bh * 0.8).attr('y2', cy + bh * 0.8).attr('stroke', fg).attr('stroke-width', 1.5);
      var range = ord && r.labels ? (r.labels.lo === r.labels.hi ? d3.llmText('d3.whatiflane.range_one', '{value}  center {center}', { value: r.labels.lo, center: r.labels.centre }) : d3.llmText('d3.whatiflane.range', '{lo} .. {hi}  center {center}', { lo: r.labels.lo, hi: r.labels.hi, center: r.labels.centre }))
        : d3.llmText('d3.whatiflane.range', '{lo} .. {hi}  center {center}', { lo: fmt(r.name, r.lo), hi: fmt(r.name, r.hi), center: fmt(r.name, r.centre) });
      var txt = range + past + (anyPin ? d3.llmText('d3.whatiflane.explained', '  explained {share}', { share: shareF.format(r.explained || 0) }) : '') + (r.weak ? d3.llmText('d3.whatiflane.weak', '  weak') : '')
        + (r.tracks ? d3.llmText('d3.whatiflane.tracks', '  (tracks {name}; predicted from it)', { name: r.tracks }) : '');
      readout.text(txt);
      var forms = [txt, range + (anyPin ? d3.llmText('d3.whatiflane.explained', '  explained {share}', { share: shareF.format(r.explained || 0) }) : '') + (r.weak ? d3.llmText('d3.whatiflane.weak', '  weak') : ''), range];
      for (var fi = 0; fi < forms.length; fi++) {
        d3.llmFitLabel(readout, W - readX - PAD, { pad: 0, text: forms[fi], overflow: 'drop' });
        if (readout.text()) break;
      }
      if (readout.text() !== txt) readout.append('title').text(txt);
    });

    var pct = Math.round(confidence * 100) + '%';
    var notes = (out.notes || []).concat(noteLevels, noteOverflow, [noteNoDirection], noteOrdinals,
      pins[nominal] ? [d3.llmText('d3.whatiflane.note_nominal', 'the same relationships assumed in every {name}', { name: nominal })] : []);
    var noteText = notes.join('; ') + (modelDropped ? '; ' + modelDropped : '');
    capNotes.selectAll('text').remove();
    var noteLines = captionLines(notes, W - 2 * PAD, noteRoom, CAP_FS);
    noteLines.forEach(function (line, k) {
      var t = capNotes.append('text').attr('class', 'lch-caption').attr('x', PAD).attr('y', CAP_Y + CAP_LINE * k)
        .attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75);
      d3.llmFitLabel(t, W - 2 * PAD, { pad: 0, text: line });
      if (t.text() !== line || (modelDropped && k === noteLines.length - 1)) t.append('title').text(noteText);
    });
    capKey.selectAll('text').remove();
    keyLinesFor(pct).forEach(function (line, k) {
      capKey.append('text').attr('class', 'lch-legend-note').attr('x', PAD).attr('y', CAP_Y + CAP_LINE * (noteLines.length + k))
        .attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75).text(line);
    });
  }

  readPins();
  repaint();
}

This chart was made by RegiaBI from the data above. Get it for Power BI or see pricing.

New articles in your inbox

Drop your email and we'll tell you when we publish something new. No spam — unsubscribe anytime.

This application may no longer respond until reloaded. Reload 🗙