Where to draw the line on CreditScore
If you flag every case above a cutoff on CreditScore, how many right and wrong calls does that make?
Loan records with credit score, annual income, debt-to-income, purpose, amount and an outcome (defaulted) flag. Several continuous measures plus a binary target — ideal for scatter/bubble, distribution, and default-rate-by-segment analysis.
Loan Default Predictors: 1400 rows, 7 columns. Download the CSV
| LoanID | CreditScore | AnnualIncome | DebtToIncome | LoanPurpose | Defaulted | Sum of LoanAmount |
|---|---|---|---|---|---|---|
| LN-50000 | 732 | 33233.0 | 0.131 | Home | False | 69787.0 |
| LN-50001 | 682 | 75472.0 | 0.443 | Personal | False | 204801.0 |
| LN-50002 | 614 | 69944.0 | 0.649 | Refi | False | 77570.0 |
| LN-50003 | 705 | 18000.0 | 0.242 | Education | False | 56952.0 |
| LN-50004 | 661 | 69920.0 | 0.37 | Auto | False | 216829.0 |
| LN-50005 | 724 | 39323.0 | 0.414 | Auto | False | 134879.0 |
| LN-50006 | 674 | 32732.0 | 0.442 | Education | False | 96692.0 |
| LN-50007 | 801 | 48263.0 | 0.484 | Auto | False | 141821.0 |
| LN-50008 | 704 | 42262.0 | 0.369 | Refi | False | 147389.0 |
| LN-50009 | 592 | 63715.0 | 0.363 | Personal | False | 40262.0 |

How to read it
Drag the cutoff and the two-by-two table of right and wrong calls, the point on the curve and the two score distributions move together. Type what a false alarm and a miss each cost, and the tuner marks the cheapest cutoff.
The chart's code (94 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) {}
};
// @requires llmText
d3.llmSlider = function (svg, cfg) {
var TYPE_FLOOR = 10; // the minimum readable type, px
cfg = cfg || {};
var options = cfg.options || {}, container = cfg.container;
var key = cfg.key || 'value';
var onChange = typeof cfg.onChange === 'function' ? cfg.onChange : function () {};
var snaps = cfg.snapValues, dom = cfg.domain;
var isSnap = Array.isArray(snaps) && snaps.length > 1;
var noop = { value: function () { return null; }, set: function () {}, reset: function () {}, g: null,
bounds: function () { return { left: 0, right: 0 }; } };
var numericOk = dom && dom.length === 2 && isFinite(+dom[0]) && isFinite(+dom[1]) && +dom[1] > +dom[0];
var handleOnly = cfg.handleOnly === true && !isSnap && typeof cfg.position === 'function';
if (!svg || (!isSnap && !numericOk) || (cfg.handleOnly === true && !handleOnly)) {
return cfg.handleOnly === true ? { value: noop.value, set: noop.set, reset: noop.reset, g: null, bounds: noop.bounds,
domain: function () { return this; }, refresh: function () { return this; } } : noop;
}
var isDate = isSnap && snaps[0] instanceof Date;
var fg = options.themeFg || '#252423', accent = options.themeAccent || fg;
var x = cfg.x != null ? cfg.x : 0, y = cfg.y != null ? cfg.y : 0, w = cfg.width != null ? cfg.width : 120;
var step = isSnap ? 1 : (+cfg.step > 0 ? +cfg.step : (dom[1] - dom[0]) / 100);
var continuous = handleOnly && !(+cfg.step > 0); // a handle-only dot with no step keeps the value it is given
var fmt = typeof cfg.format === 'function' ? cfg.format
: function (v) { return isDate ? new Date(+v).toISOString().slice(0, 10) : String(v); };
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var fszSub = Math.max(TYPE_FLOOR, fsz * 0.9); // label and readout: one size for the drawing and the measure
var tw = d3.llmSlider.textWidth;
var withSteppers = cfg.steppers !== false;
var gap = fsz * 0.6, box = Math.max(20, Math.round(fsz * 1.5));
var minusLeft = x - gap - box; // [-] box spans [minusLeft, x - gap]
var labelRight = withSteppers ? minusLeft - fsz * 0.5 : x - fsz * 0.8;
var plusLeft = x + w + gap; // [+] box spans [plusLeft, plusLeft + box]
var readoutLeft = withSteppers ? plusLeft + box + fsz * 0.5 : x + w + fsz * 0.8;
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 restored = ui.knobs && typeof ui.knobs === 'object' ? ui.knobs[key] : undefined;
function coerce(v) { // UNTRUSTED input -> a valid internal value, or null
if (v === null || v === undefined || v === '' || typeof v === 'boolean') return null;
if (isSnap) {
var n = isDate ? +new Date(v) : +v;
if (!isFinite(n)) return null;
var best = -1, bd = Infinity;
for (var i = 0; i < snaps.length; i++) {
var d = Math.abs(+snaps[i] - n);
if (d < bd) { bd = d; best = i; }
}
return best; // snap knobs hold an INDEX internally
}
var f = +v;
if (!isFinite(f) || f < dom[0] || f > dom[1]) return null;
return continuous ? f : Math.round((f - dom[0]) / step) * step + dom[0];
}
var cur = coerce(restored);
if (cur === null) cur = coerce(cfg.value);
if (cur === null) cur = coerce(cfg['default']);
if (cur === null) cur = isSnap ? 0 : dom[0];
var scale = isSnap ? d3.scaleLinear().domain([0, snaps.length - 1]).range([x, x + w])
: d3.scaleLinear().domain(dom).range([x, x + w]);
function stop(ev) { if (ev && typeof ev.stopPropagation === 'function') ev.stopPropagation(); }
function place(v) { // handle-only: where the caller's position() puts the value
var p = cfg.position(v);
return p && isFinite(+p[0]) && isFinite(+p[1]) ? [+p[0], +p[1]] : [0, 0];
}
function invertPlace(px) { // handle-only: the value whose handle sits at pixel px
if (typeof cfg.invert === 'function') { var iv = +cfg.invert(px); if (isFinite(iv)) return iv; }
var lo = dom[0], hi = dom[1], pLo = place(lo)[0], pHi = place(hi)[0];
if (pLo === pHi) return cur;
var rising = pHi > pLo;
if (rising ? px <= pLo : px >= pLo) return lo;
if (rising ? px >= pHi : px <= pHi) return hi;
for (var i = 0; i < 60; i++) {
var mid = (lo + hi) / 2;
if ((place(mid)[0] < px) === rising) lo = mid; else hi = mid;
}
return (lo + hi) / 2;
}
var g = svg.append('g').attr('class', 'llm-slider lch-control').attr('data-knob', key).on('click', stop);
var labelText = '', labelW = 0;
if (cfg.label && !handleOnly) {
labelText = String(cfg.label);
var labelNode = g.append('text').attr('class', 'llm-slider-label')
.attr('x', labelRight).attr('y', y + fsz * 0.35).attr('text-anchor', 'end')
.attr('font-size', fszSub).attr('fill', fg).text(labelText);
labelW = measure(labelNode, labelText, fszSub);
if (+cfg.labelRoom > 0 && labelW > +cfg.labelRoom) {
var keep = labelText;
while (keep.length > 1 && measure(labelNode.text(keep + '\u2026'), keep + '\u2026', fszSub) > +cfg.labelRoom) keep = keep.slice(0, -1);
labelText = keep.length > 1 ? keep + '\u2026' : '';
labelNode.text(labelText);
labelW = labelText ? measure(labelNode, labelText, fszSub) : 0;
}
}
if (!handleOnly) g.append('line').attr('class', 'llm-slider-track')
.attr('x1', x).attr('x2', x + w).attr('y1', y).attr('y2', y)
.attr('stroke', fg).attr('stroke-width', 2).attr('opacity', 0.35);
var handle = g.append('g').attr('class', 'llm-slider-handle').attr('cursor', 'ew-resize');
handle.append('circle').attr('r', fsz * 0.55).attr('cy', handleOnly ? 0 : y).attr('fill', accent)
.attr('stroke', fg).attr('stroke-width', 1);
handle.append('rect').attr('x', -12).attr('y', (handleOnly ? 0 : y) - 12).attr('width', 24).attr('height', 24)
.attr('fill', 'transparent').attr('pointer-events', 'all');
handle.attr('role', 'slider').attr('tabindex', 0).attr('aria-label', String(cfg.label || key)).attr('aria-orientation', 'horizontal');
handle.on('keydown', function (event) {
var k = event && event.key, big = isSnap ? Math.max(1, Math.round(snaps.length / 10)) : 10;
var by = k === 'ArrowRight' || k === 'ArrowUp' ? 1 : k === 'ArrowLeft' || k === 'ArrowDown' ? -1
: k === 'PageUp' ? big : k === 'PageDown' ? -big : 0;
if (by) nudge(by);
else if (k === 'Home') setCur(isSnap ? 0 : dom[0], 'end');
else if (k === 'End') setCur(isSnap ? snaps.length - 1 : dom[1], 'end');
else return;
if (event && typeof event.preventDefault === 'function') event.preventDefault();
stop(event);
});
var readout = handleOnly ? null : g.append('text').attr('class', 'llm-slider-readout')
.attr('x', readoutLeft).attr('y', y + fsz * 0.35)
.attr('font-size', fszSub).attr('fill', fg);
var readoutText = '';
function measure(sel, txt, fs) {
try {
var node = typeof sel.node === 'function' ? sel.node() : null;
if (node && typeof node.getComputedTextLength === 'function') {
var mw = node.getComputedTextLength();
if (mw > 0) return mw;
}
} catch (e) { /* fall through to the estimate */ }
return tw(txt, fs);
}
function valueOf() { return isSnap ? snaps[cur] : cur; }
function stored() { return isSnap ? (isDate ? new Date(+snaps[cur]).toISOString() : snaps[cur]) : cur; }
function paint() {
handle.attr('aria-valuemin', isSnap ? 0 : dom[0]).attr('aria-valuemax', isSnap ? snaps.length - 1 : dom[1])
.attr('aria-valuenow', cur).attr('aria-valuetext', String(fmt(valueOf())));
if (handleOnly) { var at = place(cur); handle.attr('transform', 'translate(' + at[0] + ',' + at[1] + ')'); return; }
handle.attr('transform', 'translate(' + scale(cur) + ',0)');
readoutText = String(fmt(valueOf()));
readout.text(readoutText);
}
function reportControl() {
if (typeof options.onControlChange !== 'function') return;
try { options.onControlChange({ control: 'slider', key: key, value: String(stored()) }); }
catch (e) { /* a host that refuses the report must never take the chart down with it */ }
}
function persist(phase) {
bag[key] = stored();
onChange(valueOf(), phase);
if (phase === 'end' || phase === 'reset') reportControl();
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.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 setCur(c, phase) {
var v = isSnap ? Math.max(0, Math.min(snaps.length - 1, Math.round(c)))
: Math.max(dom[0], Math.min(dom[1], c));
if (v === cur && phase !== 'init') return;
cur = v;
paint();
if (phase === 'drag') onChange(valueOf(), 'drag'); else persist(phase);
}
function nudge(dir) { setCur(isSnap ? cur + dir : cur + dir * step, 'end'); }
function mkStepper(parent, dir, left) {
var s = parent.append('g').attr('class', 'llm-slider-step lch-control').attr('cursor', 'pointer')
.attr('aria-label', dir < 0 ? d3.llmText('d3.slider.decrease', 'Decrease {label}', { label: String(cfg.label || key) }) : d3.llmText('d3.slider.increase', 'Increase {label}', { label: String(cfg.label || key) }))
.on('click', function () { nudge(dir); });
s.append('rect').attr('x', left).attr('y', y - box / 2).attr('width', box).attr('height', box)
.attr('rx', 3).attr('fill', 'transparent').attr('stroke', fg).attr('opacity', 0.6);
s.append('text').attr('x', left + box / 2).attr('y', y + fsz * 0.35).attr('text-anchor', 'middle')
.attr('font-size', fsz).attr('fill', fg).text(dir < 0 ? '-' : '+');
return s;
}
if (withSteppers && !handleOnly) {
var stepG = g.append('g').attr('class', 'llm-slider-steppers');
mkStepper(stepG, -1, minusLeft);
mkStepper(stepG, +1, plusLeft);
}
handle.call(d3.drag()
.on('drag', function (event) {
var v = handleOnly ? invertPlace(event.x) : scale.invert(event.x);
setCur(isSnap || continuous ? v : Math.round((v - dom[0]) / step) * step + dom[0], 'drag');
})
.on('end', function () { persist('end'); }));
paint();
if (!handleOnly) bag[key] = stored(); // a handle-only dot writes the bag only when the reader lets go
onChange(valueOf(), 'init');
var api = {
value: valueOf,
g: g,
set: function (v, fire) { var c = coerce(v); if (c === null) return; setCur(c, fire === false ? 'drag' : 'end'); },
reset: function (fire) { var c = coerce(cfg['default']); if (c === null) return; setCur(c, fire === false ? 'drag' : 'reset'); },
bounds: function () {
if (handleOnly) { var hp = place(cur); return { left: hp[0], right: hp[0] }; }
var left = labelText ? labelRight - labelW : (withSteppers ? minusLeft : x);
var right = readoutLeft + measure(readout, readoutText, fszSub);
return { left: left, right: right };
}
};
if (handleOnly) {
api.domain = function (d) {
if (d && d.length === 2 && isFinite(+d[0]) && isFinite(+d[1]) && +d[1] >= +d[0]) {
dom = [+d[0], +d[1]];
cur = Math.max(dom[0], Math.min(dom[1], cur));
paint();
}
return api;
};
api.refresh = function () { paint(); return api; };
}
return api;
};
d3.llmSlider.textWidth = function (txt, fontSize) {
var s = String(txt == null ? '' : txt), f = +fontSize > 0 ? +fontSize : 10;
var wide = s.match(/[\u1100-\u11ff\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/g), n = wide ? wide.length : 0;
return ((s.length - n) * 0.6 + n) * f;
};
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.llmCutoff = 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;
}
var scoreName = cfg.score === undefined || cfg.score === null ? '' : String(cfg.score);
var outcomeName = cfg.outcome === undefined || cfg.outcome === null ? '' : String(cfg.outcome);
var weightName = cfg.weight ? String(cfg.weight) : '';
var rowIdxName = cfg.rowIdx === false ? '' : (cfg.rowIdx ? String(cfg.rowIdx) : '__rowIdx__');
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];
}
var NUM = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/;
var GROUPED = /^[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
var LEAD = /^\s*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)/;
function strictNum(v) {
if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'object') return NaN;
if (typeof v === 'number') return isFinite(v) ? v : NaN;
var s = String(v).trim();
if (s === '') return NaN;
if (NUM.test(s)) return +s;
if (GROUPED.test(s)) return +s.replace(/,/g, '');
return NaN;
}
function scoreOf(v) {
var x = strictNum(v);
if (isFinite(x)) return x;
if (typeof v !== 'string') return NaN;
var m = LEAD.exec(v);
return m ? +m[1] : NaN;
}
function outKey(v) {
if (v === null || v === undefined) return null;
var s = String(v).trim();
return s === '' ? null : s;
}
var YES = ['true', 'yes', 'y', 't', '1'], NO = ['false', 'no', 'n', 'f', '0'];
var NEGATION = ['no', 'not', 'non', 'never', 'retained'];
var FILLER = ['is', 'has', 'was', 'did', 'will', 'flag', 'flagged', 'indicator', 'ind', 'status', 'label', 'outcome', 'target',
'class', 'result', 'the', 'of', 'a', 'an'];
var EVENT = /^(?:churn\w*|default\w*|fraud\w*|cancel\w*|lapse\w*|attrit\w*|delinquen\w*|readmit\w*|fail\w*|reject\w*|lost|bad)$/;
function plain(s) {
s = String(s === null || s === undefined ? '' : s);
if (typeof s.normalize === 'function') s = s.normalize('NFD').replace(/[̀-ͯ]/g, '');
return s;
}
function wordsOf(s) {
return plain(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(function (w) { return w !== ''; });
}
function stem(w) {
if (w.length > 4 && /ied$/.test(w)) w = w.slice(0, -3) + 'y';
else if (w.length > 5 && /ing$/.test(w)) w = w.slice(0, -3);
else if (w.length > 3 && /ed$/.test(w)) w = w.slice(0, -2);
else if (w.length > 3 && /s$/.test(w) && !/ss$/.test(w)) w = w.slice(0, -1);
if (w.length > 3 && /e$/.test(w)) w = w.slice(0, -1);
return w;
}
function boolToken(label) {
var s = plain(label).trim().toLowerCase();
if (NUM.test(s)) { var n = +s; if (n === 1) s = '1'; else if (n === 0) s = '0'; }
return YES.indexOf(s) >= 0 ? 'yes' : (NO.indexOf(s) >= 0 ? 'no' : '');
}
var colStems = (function () {
var ws = wordsOf(outcomeName), keep = ws.filter(function (w) { return FILLER.indexOf(w) < 0; });
return (keep.length ? keep : ws).map(stem).filter(function (w) { return w.length >= 3; });
})();
function evidence(label, test) {
var ws = wordsOf(label), word = '', negated = false, i;
for (i = 0; i < ws.length; i++) if (NEGATION.indexOf(ws[i]) >= 0) negated = true;
for (i = 0; i < ws.length; i++) {
if (test(ws[i])) { word = ws[i]; continue; }
var g = /^(?:non|not|never|no)(.{3,})$/.exec(ws[i]);
if (g && test(g[1])) { word = g[1]; negated = true; }
}
return { word: word, negated: negated };
}
function stemTest(w) { return colStems.indexOf(stem(w)) >= 0; }
function eventTest(w) { return EVENT.test(w); }
function byKey(a, b) { var x = a.key.toLowerCase(), y = b.key.toLowerCase(); return x < y ? -1 : (x > y ? 1 : (a.key < b.key ? -1 : (a.key > b.key ? 1 : 0))); }
function decide(values) {
var i, yes = [], no = [], hits;
for (i = 0; i < values.length; i++) { var t = boolToken(values[i].key); if (t === 'yes') yes.push(i); else if (t === 'no') no.push(i); }
if (values.length === 2 && yes.length === 1 && no.length === 1) {
return { pos: yes[0], rule: 'boolean', no: 1, word: values[yes[0]].key.toLowerCase(), text: d3.llmText('d3.cutoff.rule_boolean', 'reads as yes') };
}
if (values.length === 1 && yes.length === 1) return { pos: 0, rule: 'boolean', no: 1, word: values[0].key.toLowerCase(), text: d3.llmText('d3.cutoff.rule_boolean', 'reads as yes') };
var rules = [['name', 2, stemTest, function (w) { return d3.llmText('d3.cutoff.rule_name', 'named for the column ({word})', { word: w }); }],
['event', 3, eventTest, function (w) { return d3.llmText('d3.cutoff.rule_event', 'an event word ({word})', { word: w }); }]];
for (var r = 0; r < rules.length; r++) {
if (r === 0 && !colStems.length) continue;
hits = [];
for (i = 0; i < values.length; i++) {
var ev = evidence(values[i].key, rules[r][2]);
if (ev.word && !ev.negated) hits.push({ i: i, word: ev.word });
}
if (hits.length === 1) return { pos: hits[0].i, rule: rules[r][0], no: rules[r][1], word: hits[0].word, text: rules[r][3](hits[0].word) };
}
if (values.length === 2) {
var a = values[0], b = values[1];
if (a.w === b.w) return { pos: 0, rule: 'minority', no: 4, word: '', text: d3.llmText('d3.cutoff.rule_minority_tie', 'one of two equally common values, the first alphabetically - switch it with the toggle') };
return { pos: a.w < b.w ? 0 : 1, rule: 'minority', no: 4, word: '', text: d3.llmText('d3.cutoff.rule_minority', 'the less common value - switch it with the toggle') };
}
return { pos: -1, rule: 'none', no: 0, word: '', text: '' };
}
function hintRule(h) {
if (h === undefined || h === null || h === '') return 0;
if (typeof h === 'object') return +h.rule || 0;
var m = /(\d)/.exec(String(h));
return m ? +m[1] : 0;
}
function shell(reason) {
var none = function () { return null; };
return { ok: false, reason: reason, degenerate: null, weighted: !!weightName, nRows: 0, skipped: { score: 0, outcome: 0, weight: 0 },
n: 0, nPos: 0, nNeg: 0, prevalence: null, outcomes: [], positive: null, negative: null, positiveRule: 'none', positiveRuleNo: 0,
positiveWord: '', positiveRuleText: '', positiveFallback: false, ruledPositive: null, hintAgrees: null,
direction: 'high', directionSource: 'default', flipped: false, aucHigh: null, auc: null, band: null, withinBand: true,
averagePrecision: null, distinct: 0, ties: 0, tieBlocks: 0, min: null, max: null, cuts: [], cutNobody: null, cutEverybody: null,
roc: [], pr: [], at: none, cost: none, cheapest: none, youden: null, bins: function () { return []; }, binAt: none,
flaggedRowIdxs: function () { return []; } };
}
if (!scoreName || colIdx[scoreName] === undefined) return shell(d3.llmText('d3.cutoff.no_score_column', 'the score column {column} is not in the data', { column: scoreName }));
if (!outcomeName || colIdx[outcomeName] === undefined) return shell(d3.llmText('d3.cutoff.no_outcome_column', 'the outcome column {column} is not in the data', { column: outcomeName }));
if (weightName && colIdx[weightName] === undefined) return shell(d3.llmText('d3.cutoff.no_count_column', 'the count column {column} is not in the data', { column: weightName }));
var useRowIdx = rowIdxName !== '' && colIdx[rowIdxName] !== undefined;
var skipped = { score: 0, outcome: 0, weight: 0 };
var cs = [], totals = {}, keys = [];
for (var ri = 0; ri < allRows.length; ri++) {
var row = allRows[ri];
var s = scoreOf(cell(row, scoreName));
if (!isFinite(s)) { skipped.score++; continue; }
var key = outKey(cell(row, outcomeName));
if (key === null) { skipped.outcome++; continue; }
var w = 1;
if (weightName) { w = strictNum(cell(row, weightName)); if (!(w > 0)) { skipped.weight++; continue; } }
var id = ri;
if (useRowIdx) { var iv = strictNum(cell(row, rowIdxName)); if (isFinite(iv)) id = iv; }
if (!Object.prototype.hasOwnProperty.call(totals, key)) { totals[key] = { key: key, w: 0 }; keys.push(key); }
totals[key].w += w;
cs.push({ s: s, k: key, w: w, id: id, i: ri, y: 0 });
}
if (!cs.length) { var empty = shell(d3.llmText('d3.cutoff.no_usable_rows', 'no row has both a numeric score and an outcome')); empty.skipped = skipped; empty.nRows = 0; return empty; }
if (keys.length > 2) { var many = shell(d3.llmText('d3.cutoff.too_many_outcomes', 'the outcome {column} has {count} values - a cutoff needs exactly two', { column: outcomeName, count: String(keys.length) }, keys.length)); many.skipped = skipped; many.nRows = cs.length; return many; }
var values = keys.map(function (k) { return totals[k]; }).sort(byKey);
var ruled = decide(values);
var chosenKey = cfg.positive === undefined || cfg.positive === null ? null : outKey(cfg.positive);
var chosen = -1;
if (chosenKey !== null) for (var vi = 0; vi < values.length; vi++) if (values[vi].key.toLowerCase() === chosenKey.toLowerCase()) chosen = vi;
var pick = chosen >= 0 ? { pos: chosen, rule: 'chosen', no: 0, word: '', text: d3.llmText('d3.cutoff.rule_chosen', 'your choice') } : ruled;
var posKey = pick.pos >= 0 ? values[pick.pos].key : null;
var negKey = null;
for (vi = 0; vi < values.length; vi++) if (values[vi].key !== posKey) negKey = values[vi].key;
var hr = hintRule(cfg.positiveHint);
var P = 0, N = 0, i, j;
for (i = 0; i < cs.length; i++) { cs[i].y = cs[i].k === posKey ? 1 : 0; if (cs[i].y) P += cs[i].w; else N += cs[i].w; }
cs.sort(function (a, b) { return a.s !== b.s ? (a.s < b.s ? -1 : 1) : (a.id !== b.id ? (a.id < b.id ? -1 : 1) : a.i - b.i); });
var nc = cs.length;
var casP = [0], casN = [0];
for (i = 0; i < nc; i++) { casP.push(casP[i] + (cs[i].y ? cs[i].w : 0)); casN.push(casN[i] + (cs[i].y ? 0 : cs[i].w)); }
var bs = [], bst = [], ben = [], cp = [0], cnn = [0], ties = 0, tieBlocks = 0;
for (i = 0; i < nc; i = j) {
j = i;
while (j < nc && cs[j].s === cs[i].s) j++;
bs.push(cs[i].s); bst.push(i); ben.push(j);
cp.push(cp[cp.length - 1] + casP[j] - casP[i]); cnn.push(cnn[cnn.length - 1] + casN[j] - casN[i]);
if (j - i > 1) { ties += j - i; tieBlocks++; }
}
var K = bs.length, lo = bs[0], hi = bs[K - 1], span = hi - lo, nTot = P + N;
var aucHigh = null, band = null;
if (P > 0 && N > 0) {
var acc = 0;
for (var bk = 0; bk < K; bk++) acc += (cp[bk + 1] - cp[bk]) * (cnn[bk] + 0.5 * (cnn[bk + 1] - cnn[bk]));
aucHigh = acc / (P * N);
band = 1.96 * Math.sqrt((P + N + 1) / (12 * P * N));
}
var asked = String(cfg.direction === undefined || cfg.direction === null ? 'auto' : cfg.direction).toLowerCase();
var direction = 'high', directionSource = 'default';
if (asked === 'high' || asked === 'low') { direction = asked; directionSource = 'given'; }
else if (aucHigh !== null) {
if (aucHigh < 0.5 - band) { direction = 'low'; directionSource = 'data'; }
else if (aucHigh > 0.5 + band) directionSource = 'data';
}
var low = direction === 'low';
var auc = aucHigh === null ? null : (low ? 1 - aucHigh : aucHigh);
function firstAtOrAbove(t) { var a = 0, b = K; while (a < b) { var m = (a + b) >> 1; if (bs[m] >= t) b = m; else a = m + 1; } return a; }
function countAtOrBelow(t) { var a = 0, b = K; while (a < b) { var m = (a + b) >> 1; if (bs[m] <= t) a = m + 1; else b = m; } return a; }
function flaggedBlocks(t) { return low ? countAtOrBelow(t) : K - firstAtOrAbove(t); }
function shape(t, tp, fp) {
var fn = P - tp, tn = N - fp, fl = tp + fp;
return { t: t, tp: tp, fp: fp, fn: fn, tn: tn, flagged: fl, notFlagged: fn + tn, n: nTot,
flaggedShare: nTot > 0 ? fl / nTot : null,
catchRate: P > 0 ? tp / P : null, missRate: P > 0 ? fn / P : null,
falseAlarmRate: N > 0 ? fp / N : null, specificity: N > 0 ? tn / N : null,
tpr: P > 0 ? tp / P : null, fpr: N > 0 ? fp / N : null, recall: P > 0 ? tp / P : null,
precision: fl > 0 ? tp / fl : null, accuracy: nTot > 0 ? (tp + tn) / nTot : null };
}
function countsFor(nb) { // nb = how many tie blocks are flagged, from the flagged end
return low ? [cp[nb], cnn[nb]] : [P - cp[K - nb], N - cnn[K - nb]];
}
function at(t) {
t = +t;
if (t !== t) return null;
var c = countsFor(flaggedBlocks(t));
return shape(t, c[0], c[1]);
}
var eps = K > 1 ? span / (K - 1) : 1;
var cutNobody = low ? lo - eps : hi + eps;
var cuts = [];
if (low) cuts.push(cutNobody);
for (i = 0; i < K; i++) cuts.push(bs[i]);
if (!low) cuts.push(cutNobody);
var cutEverybody = low ? hi : lo;
var ptT = [], ptTP = [], ptFP = [];
for (var nb = 0; nb <= K; nb++) {
var cc = countsFor(nb);
ptT.push(nb === 0 ? cutNobody : (low ? bs[nb - 1] : bs[K - nb]));
ptTP.push(cc[0]); ptFP.push(cc[1]);
}
function point(k) { return shape(ptT[k], ptTP[k], ptFP[k]); }
var rocMemo = null, prMemo = null;
function rocPoints() {
if (rocMemo === null) {
rocMemo = [];
for (var k = 0; k <= K; k++) { var p = point(k); rocMemo.push({ t: p.t, fpr: p.falseAlarmRate, tpr: p.catchRate, tp: p.tp, fp: p.fp, fn: p.fn, tn: p.tn }); }
}
return rocMemo;
}
function prPoints() {
if (prMemo === null) {
prMemo = [];
for (var k = 0; k <= K; k++) { var p = point(k); prMemo.push({ t: p.t, recall: p.catchRate, precision: k === 0 ? 1 : p.precision, tp: p.tp, fp: p.fp, fn: p.fn, tn: p.tn }); }
}
return prMemo;
}
var averagePrecision = null;
if (P > 0) {
averagePrecision = 0;
for (i = 1; i <= K; i++) averagePrecision += (ptTP[i] / P - ptTP[i - 1] / P) * (ptTP[i] / (ptTP[i] + ptFP[i]));
}
function costNum(c) { return typeof c === 'number' && isFinite(c) && c >= 0 ? c : (typeof c === 'string' && c.trim() !== '' && isFinite(+c) && +c >= 0 ? +c : null); }
function costOf(p, cFP, cMiss) { return p.fp * cFP + p.fn * cMiss; }
function cost(t, cFP, cMiss) {
var a = costNum(cFP), b = costNum(cMiss), p = at(t);
return a === null || b === null || p === null ? null : costOf(p, a, b);
}
function costAt(k, cFP, cMiss) { return ptFP[k] * cFP + (P - ptTP[k]) * cMiss; }
function cheapest(cFP, cMiss) {
var a = costNum(cFP), b = costNum(cMiss);
if (a === null || b === null) return null;
var best = 0, bestCost = costAt(0, a, b), c;
for (var k = 1; k <= K; k++) {
c = costAt(k, a, b);
if (c < bestCost - 1e-9 * Math.max(1, Math.abs(bestCost))) { best = k; bestCost = c; }
}
var out = point(best);
out.cost = bestCost;
out.nobodyCost = costAt(0, a, b);
out.everybodyCost = costAt(K, a, b);
out.baseline = out.everybodyCost < out.nobodyCost ? 'everybody' : 'nobody';
out.baselineCost = Math.min(out.nobodyCost, out.everybodyCost);
out.ratio = a > 0 ? b / a : null;
out.ratio2 = out.ratio === null ? null : +out.ratio.toPrecision(2);
return out;
}
var youden = null;
if (P > 0 && N > 0) {
var yb = 0, yj = ptTP[0] / P - ptFP[0] / N;
for (i = 1; i <= K; i++) {
var jv = ptTP[i] / P - ptFP[i] / N;
if (jv > yj + 1e-12) { yb = i; yj = jv; }
}
youden = point(yb);
youden.j = yj;
}
function bins(nWanted) {
var n = Math.floor(+nWanted);
if (!(n >= 1)) n = 30;
n = Math.min(n, K, 400);
var th = [], out = [], b = 0, k, i;
for (k = 0; k <= n; k++) th.push(k === n ? hi : lo + span * k / n);
for (k = 0; k < n; k++) out.push({ x0: th[k], x1: th[k + 1], pos: 0, neg: 0, posRowIdxs: [], negRowIdxs: [], i0: 0, i1: 0 });
for (i = 0; i < nc; i++) {
while (b < n - 1 && cs[i].s >= th[b + 1]) b++;
var o = out[b];
o.i1++;
if (cs[i].y) { o.pos += cs[i].w; o.posRowIdxs.push(cs[i].id); } else { o.neg += cs[i].w; o.negRowIdxs.push(cs[i].id); }
}
var at0 = 0, mp = 0, mn = 0;
for (k = 0; k < n; k++) {
out[k].i0 = at0; out[k].i1 += at0; at0 = out[k].i1;
out[k].posRowIdxs.sort(function (x, y) { return x - y; }); out[k].negRowIdxs.sort(function (x, y) { return x - y; });
if (out[k].pos > mp) mp = out[k].pos;
if (out[k].neg > mn) mn = out[k].neg;
}
out.thresholds = th; out.maxPos = mp; out.maxNeg = mn;
return out;
}
function flaggedSpan(t) {
if (low) { var nb = countAtOrBelow(t); return [0, nb ? ben[nb - 1] : 0]; }
var f = firstAtOrAbove(t);
return [f < K ? bst[f] : nc, nc];
}
function binAt(bin, t) {
var sp = flaggedSpan(+t), from = Math.max(bin.i0, sp[0]), to = Math.min(bin.i1, sp[1]);
var fp = to > from ? casP[to] - casP[from] : 0, fn = to > from ? casN[to] - casN[from] : 0;
var all = bin.pos + bin.neg, got = fp + fn;
return { pos: bin.pos, neg: bin.neg, posFlagged: fp, negFlagged: fn, state: got <= 0 ? 'none' : (got >= all ? 'all' : 'part') };
}
function flaggedRowIdxs(t, cellName) {
var sp = flaggedSpan(+t), out = [];
for (var k = 0; k < nc; k++) {
var fl = k >= sp[0] && k < sp[1], y = cs[k].y === 1, keep;
if (cellName === 'tp') keep = fl && y;
else if (cellName === 'fp') keep = fl && !y;
else if (cellName === 'fn') keep = !fl && y;
else if (cellName === 'tn') keep = !fl && !y;
else if (cellName === 'flagged') keep = fl;
else if (cellName === 'notFlagged') keep = !fl;
else keep = true;
if (keep) out.push(cs[k].id);
}
return out.sort(function (x, y) { return x - y; });
}
var result = { ok: true, reason: '', degenerate: P <= 0 ? 'noPositives' : (N <= 0 ? 'noNegatives' : null), weighted: !!weightName,
nRows: nc, skipped: skipped, n: nTot, nPos: P, nNeg: N, prevalence: nTot > 0 ? P / nTot : null,
outcomes: values.map(function (v) { return v.key; }), positive: posKey, negative: negKey,
positiveRule: pick.rule, positiveRuleNo: pick.no, positiveWord: pick.word, positiveRuleText: pick.text,
positiveFallback: chosenKey !== null && chosen < 0, ruledPositive: ruled.pos >= 0 ? values[ruled.pos].key : null,
hintAgrees: hr ? hr === ruled.no : null,
direction: direction, directionSource: directionSource, flipped: low && directionSource === 'data',
aucHigh: aucHigh, auc: auc, band: band, withinBand: auc === null ? true : Math.abs(auc - 0.5) <= band,
averagePrecision: averagePrecision, distinct: K, ties: ties, tieBlocks: tieBlocks, min: lo, max: hi,
cuts: cuts, cutNobody: cutNobody, cutEverybody: cutEverybody,
at: at, cost: cost, cheapest: cheapest, youden: youden, bins: bins, binAt: binAt, flaggedRowIdxs: flaggedRowIdxs };
Object.defineProperty(result, 'roc', { get: rocPoints, enumerable: true });
Object.defineProperty(result, 'pr', { get: prPoints, enumerable: true });
return result;
};
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;
};
d3.llmDisplayName = function (name) {
var s = name === null || name === undefined ? '' : String(name);
if (!s || /\s/.test(s)) return s.trim();
var t = s.replace(/[_]+/g, ' ');
if (/^[a-z0-9]+(?:-+[a-z0-9]+)+$/.test(t)) t = t.replace(/-+/g, ' ');
t = t.trim();
if (t !== s) return t.charAt(0).toUpperCase() + t.slice(1);
var parts = [];
var re = /[a-z][A-Z][a-z]+|[A-Z][a-z][A-Z](?![a-z])|[A-Z]+[0-9]+|[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|[0-9]+[A-Z](?![a-z0-9])|[0-9]+|[^A-Za-z0-9]+/g;
var m;
while ((m = re.exec(s)) !== null) {
if (m[0] === '') { re.lastIndex++; continue; }
parts.push(m[0]);
}
if (parts.length < 2 || parts.join('') !== s) return s;
var out = '';
for (var i = 0; i < parts.length; i++) {
var punct = /^[^A-Za-z0-9]+$/.test(parts[i]), prevPunct = i > 0 && /^[^A-Za-z0-9]+$/.test(parts[i - 1]);
out += i === 0 || punct || prevPunct ? parts[i] : ' ' + parts[i];
}
return out.trim();
};
function render(container, data, options) {
const TYPE_FLOOR = 10;
container.replaceChildren();
var SCORE = 'CreditScore';
var OUTCOME = 'Defaulted';
var POSITIVE_HINT = '2:defaulted';
var DIRECTION_HINT = 'low';
var WEIGHT = '';
var CASE_BY = 'LoanID';
var OTHER_SCORES = ['DebtToIncome', 'AnnualIncome', 'Sum of LoanAmount'];
var ROW_CAP = 5000;
var CUTOFF_FROM = '';
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), BIG_FS = Math.max(TYPE_FLOOR, FS * 1.5);
var fg = options.themeFg || 'currentColor';
var accent = options.themeAccent || ((options.palette && options.palette.length) ? options.palette[0] : fg);
var warm = (options.palette && options.palette.length > 1) ? options.palette[1] : '#c4314b';
var loc = options.cultureCode || 'en-US';
var svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
var cols = data.columns || [], rows = data.rows || [];
var idx0 = function (n) { return data.columns.findIndex(function (c) { return c.name === n; }); };
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);
var t = svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle').attr('font-size', FS).attr('fill', fg).text(msg);
d3.llmFitLabel(t, W - 16, { pad: 0, text: msg });
}
function fitForms(el, room, forms) {
for (var fi = 0; fi < forms.length; fi++) {
el.text(forms[fi]);
d3.llmFitLabel(el, room, { pad: 0, text: forms[fi], overflow: 'drop' });
if (el.text()) return;
}
}
if (idx0(SCORE) < 0) throw new Error('INVALID:column "' + SCORE + '" not found');
if (idx0(OUTCOME) < 0) throw new Error('INVALID:column "' + OUTCOME + '" not found');
if (!rows.length) { emptyFrame(options.noDataText || 'No data to display'); return; }
var positive = null;
var C = null;
function compute() {
C = d3.llmCutoff(data, { score: SCORE, outcome: OUTCOME, positiveHint: POSITIVE_HINT, direction: 'auto',
rowIdx: '__rowIdx__', weight: WEIGHT, positive: positive });
}
compute();
if (!C.ok) {
emptyFrame(d3.llmText('d3.cutofflane.empty', 'Cutoff tuner: {reason}', { reason: C.reason }));
return;
}
var nf0 = new Intl.NumberFormat(loc, { maximumFractionDigits: 0 });
var nf1 = new Intl.NumberFormat(loc, { maximumFractionDigits: 1 });
var pf1 = new Intl.NumberFormat(loc, { style: 'percent', maximumFractionDigits: 1 });
var pf0 = new Intl.NumberFormat(loc, { style: 'percent', maximumFractionDigits: 0 });
var cf = new Intl.NumberFormat(loc, { maximumFractionDigits: 2 });
var f2 = new Intl.NumberFormat(loc, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
var span = C.max - C.min, dec = span >= 100 ? 0 : span >= 10 ? 1 : span >= 1 ? 2 : span >= 0.1 ? 3 : 4;
var sf = new Intl.NumberFormat(loc, { minimumFractionDigits: 0, maximumFractionDigits: dec });
function cnt(v) { return v === null || v === undefined || !isFinite(v) ? '-' : (Math.abs(v - Math.round(v)) < 1e-9 ? nf0.format(v) : nf1.format(v)); }
function pct(v) { return v === null || v === undefined || !isFinite(v) ? '-' : pf1.format(v); }
function score(v) { return v === null || v === undefined || !isFinite(v) ? '-' : sf.format(v); }
function money(v) { return v === null || v === undefined || !isFinite(v) ? '-' : cf.format(v); }
function tickPct(v) { return pf0.format(v); }
function tickScore(v) { return sf.format(v); }
var CUTS = C.cuts.slice();
var cut = C.youden ? C.youden.t : C.cuts[Math.floor(C.cuts.length / 2)];
function posName() { return C.positive === null ? d3.llmText('d3.cutofflane.class_flagged', 'flagged') : C.positive; }
function negName() { return C.negative === null ? d3.llmText('d3.cutofflane.class_other', 'other') : C.negative; }
function whoCut(v) { return v === C.cutNobody ? d3.llmText('d3.cutofflane.cut_nobody', 'nobody') : score(v); }
function whoCutLong(v) { return v === C.cutNobody ? d3.llmText('d3.cutofflane.cut_flagging_nobody', 'flagging nobody') : score(v); }
var tw = function (s, fs) { var f = Math.max(TYPE_FLOOR, +fs > 0 ? +fs : 10), t = String(s == null ? '' : s), pr = svg.append('text').attr('font-size', f).attr('visibility', 'hidden').text(t), w = 0; try { w = pr.node().getComputedTextLength(); } catch (eT) { w = 0; } pr.remove(); return w > 0 ? w : t.length * f * 0.6; };
var PAD = FS * 0.8, ROW = FS * 2.5, GAP = FS * 1.4;
var strip = svg.append('g').attr('class', 'lch-knobs');
var boxes = {}, sliderApi = null, posSeg = null, curveSeg = null, curveKind = 'roc';
var ready = false;
var RESET_TXT = d3.llmText('d3.cutofflane.reset', 'reset');
var resetW = Math.max(20, FS * 3.2, tw(RESET_TXT, SUB_FS) + FS * 0.2), resetH = Math.max(20, FS * 2.0), resetLeft = W - PAD - resetW, resetY = PAD + FS * 1.3;
var flowX = PAD, flowRow = 0;
function flowAt(w) {
var rowEnd = flowRow === 0 ? resetLeft - GAP : W - PAD;
if (flowX + w > rowEnd && (flowX > PAD || flowRow === 0)) { flowRow++; flowX = PAD; }
var at = { x: flowX, y: PAD + FS * 1.3 + flowRow * ROW };
flowX += w + GAP;
return at;
}
var sliderLabelW = tw(d3.llmText('d3.cutofflane.cutoff', 'cutoff'), SUB_FS), box = Math.max(20, Math.round(FS * 1.5)), sgap = FS * 0.6;
var sliderX = PAD + sliderLabelW + FS * 0.5 + box + sgap, sliderW = Math.max(FS * 8, Math.min(FS * 28, W * 0.3));
var sliderRest = sliderX - PAD + sgap + box + FS * 0.5 + tw('everybody', SUB_FS) + FS;
sliderW = Math.max(FS * 5, Math.min(sliderW, resetLeft - GAP - PAD - sliderRest));
var sliderBlockW = sliderRest + sliderW;
var cutoffAt = flowAt(sliderBlockW);
sliderApi = d3.llmSlider(svg, { container: container, options: options, key: 'cutoff', snapValues: CUTS,
'default': cut, value: cut, x: cutoffAt.x + (sliderX - PAD), y: cutoffAt.y, width: sliderW, fontSize: FS, label: d3.llmText('d3.cutofflane.cutoff', 'cutoff'),
labelRoom: sliderLabelW + FS, format: whoCut,
onChange: function (v, phase) { cut = v; if (ready) update(v, phase); } });
cut = sliderApi.value() === null ? cut : sliderApi.value();
if (C.outcomes.length === 2) {
var segCfg = { choices: C.outcomes.map(function (o) { return { value: o, label: o }; }), fontSize: FS, label: d3.llmText('d3.cutofflane.flag_for', 'flag for') };
var segW = d3.llmSegmented.measure(segCfg).width;
var posAt = flowAt(segW);
posSeg = d3.llmSegmented(svg, { container: container, options: options, key: 'positive', choices: segCfg.choices,
'default': C.positive, x: posAt.x, y: posAt.y, fontSize: FS, label: d3.llmText('d3.cutofflane.flag_for', 'flag for'),
onChange: function (v, phase) {
if (v === C.positive) return;
positive = v;
if (ready) { compute(); paintAll(); }
} });
if (positive !== null && positive !== C.positive) { compute(); }
}
var costDefs = [{ key: 'costFalseAlarm', label: d3.llmText('d3.cutofflane.false_alarm_costs', 'false alarm costs') }, { key: 'costMiss', label: d3.llmText('d3.cutofflane.miss_costs', 'a miss costs') }];
var boxW = Math.max(FS * 5.5, Math.min(FS * 8, W * 0.1));
costDefs.forEach(function (cd) {
var lw = tw(cd.label, SUB_FS) + FS * 0.6;
var at = flowAt(lw + boxW);
strip.append('text').attr('class', 'lch-cost-label').attr('x', at.x).attr('y', at.y + FS * 0.35).attr('font-size', SUB_FS).attr('fill', fg).text(cd.label);
boxes[cd.key] = d3.llmNumberEntry(svg, { container: container, options: options, key: cd.key, min: 0, 'default': null,
x: at.x + lw, y: at.y, width: boxW, fontSize: FS,
onChange: function (v, phase) { if (ready) paintCost(); } });
});
var reset = svg.append('g').attr('class', 'lch-reset lch-control').attr('cursor', 'pointer')
.attr('aria-label', RESET_TXT)
.on('click', function () {
if (sliderApi) sliderApi.reset();
Object.keys(boxes).forEach(function (k) { boxes[k].reset(false); });
if (curveSeg) curveSeg.set('roc');
if (posSeg && C.ruledPositive) posSeg.set(C.ruledPositive);
paintCost();
});
reset.append('rect').attr('x', resetLeft).attr('y', resetY - 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', resetY + FS * 0.35).attr('text-anchor', 'middle')
.attr('font-size', SUB_FS).attr('fill', fg).text(RESET_TXT);
var stripBottom = PAD + FS * 1.3 + flowRow * ROW + Math.max(ROW * 0.6, resetH / 2 + FS * 0.8);
var sentenceY = stripBottom + FS * 0.2;
var sentence = svg.append('g').attr('class', 'lch-sentence');
var sLine1 = sentence.append('text').attr('class', 'lch-sentence-line').attr('x', PAD).attr('y', sentenceY).attr('font-size', SUB_FS).attr('fill', fg);
var sLine2 = sentence.append('text').attr('class', 'lch-sentence-line').attr('x', PAD).attr('y', sentenceY + FS * 1.35).attr('font-size', SUB_FS).attr('fill', fg);
var sentenceH = FS * 2.6;
var readouts = svg.append('g').attr('class', 'lch-readouts');
var read1 = readouts.append('text').attr('class', 'lch-read-flag').attr('x', PAD).attr('y', sentenceY + sentenceH + FS * 0.2).attr('font-size', SUB_FS).attr('fill', fg);
var read2 = readouts.append('text').attr('class', 'lch-read-cost').attr('x', PAD).attr('y', sentenceY + sentenceH + FS * 1.55).attr('font-size', SUB_FS).attr('fill', fg);
var capText = svg.append('text').attr('class', 'lch-caption').attr('x', PAD).attr('y', H - PAD * 0.6).attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75);
var panelTop = sentenceY + sentenceH + FS * 2.4, panelBottom = H - PAD - CAP_FS * 1.6;
var panelsH = Math.max(FS * 12, panelBottom - panelTop);
var rowAH = panelsH * 0.56, rowBH = panelsH - rowAH - GAP * 0.6;
var cellsX = PAD, cellsW = Math.max(FS * 20, Math.min(W * 0.42, FS * 34));
var curveX = cellsX + cellsW + GAP, curveW = Math.max(FS * 12, W - PAD - curveX);
var rowBY = panelTop + rowAH + GAP * 0.6;
var gCells = svg.append('g').attr('class', 'lch-cells');
var gCurve = svg.append('g').attr('class', 'lch-curve');
var gDist = svg.append('g').attr('class', 'lch-dist');
var curveChoices = [{ value: 'roc', label: d3.llmText('d3.cutofflane.curve_roc', 'ROC') }, { value: 'pr', label: d3.llmText('d3.cutofflane.curve_pr', 'Precision-recall') }];
curveSeg = d3.llmSegmented(svg, { container: container, options: options, key: 'curve', choices: curveChoices, 'default': 'roc',
x: curveX, y: panelTop + FS * 0.9, fontSize: FS,
onChange: function (v, phase) { curveKind = v; if (ready) { paintCurve(); update(cut, 'end'); } } });
curveKind = curveSeg.value() || 'roc';
var curveTop = panelTop + FS * 2.2;
var cellEls = {}, dotEl = null, ringEl = null, binEls = [], cutLineEl = null, curveGeom = null, distGeom = null, aucEl = null;
function costs() {
var a = boxes.costFalseAlarm ? boxes.costFalseAlarm.value() : null, b = boxes.costMiss ? boxes.costMiss.value() : null;
var ok = function (v) { return typeof v === 'number' && isFinite(v) && v >= 0; };
return ok(a) && ok(b) ? { a: a, b: b } : null;
}
function sentenceLines() {
var low = C.direction === 'low', S = d3.llmDisplayName(SCORE), O = d3.llmDisplayName(OUTCOME);
var way = C.directionSource === 'data'
? (low ? d3.llmText('d3.cutofflane.way_low', ': lower {score} means more likely {outcome} = {positive} (read from the data)', { score: S, outcome: O, positive: posName() })
: d3.llmText('d3.cutofflane.way_high', ': higher {score} means more likely {outcome} = {positive} (read from the data)', { score: S, outcome: O, positive: posName() }))
: (C.directionSource === 'given' ? '' : d3.llmText('d3.cutofflane.way_unknown', ': the data does not say which way {score} points, assuming higher', { score: S }));
var hinted = DIRECTION_HINT === 'low' || DIRECTION_HINT === 'high';
var again = hinted && DIRECTION_HINT !== C.direction ? d3.llmText('d3.cutofflane.read_from_view', ' - read from the rows in view') : '';
var flagFor = d3.llmText('d3.cutofflane.flagging_for', 'flagging for {outcome} = {positive} ({rule})', { outcome: O, positive: posName(), rule: C.positiveRuleText });
var other = OTHER_SCORES.length ? d3.llmText('d3.cutofflane.also_bound', '; also bound: {names} - drop the one you did not mean', { names: OTHER_SCORES.map(d3.llmDisplayName).join(', ') }) : '';
var a = (low ? d3.llmText('d3.cutofflane.flagged_below', 'flagged at or below the cutoff') : d3.llmText('d3.cutofflane.flagged_above', 'flagged at or above the cutoff')) + way + again, b = flagFor + other;
return tw(a + '; ' + b, SUB_FS) <= W - 2 * PAD ? [a + '; ' + b, ''] : [a, b];
}
function paintCells() {
gCells.selectAll('*').remove();
cellEls = {};
var labelW = Math.min(cellsW * 0.28, FS * 7), headH = FS * 2.0, capH = FS * 1.6;
var cw = (cellsW - labelW) / 2, ch = Math.max(FS * 3.4, (rowAH - headH - capH) / 2);
var x0 = cellsX + labelW, y0 = panelTop + headH;
var heads = [d3.llmText('d3.cutofflane.actual', 'actual {name}', { name: posName() }), d3.llmText('d3.cutofflane.actual', 'actual {name}', { name: negName() })];
heads.forEach(function (h, i) {
var t = gCells.append('text').attr('class', 'lch-cell-head').attr('x', x0 + cw * (i + 0.5)).attr('y', panelTop + FS * 1.1)
.attr('text-anchor', 'middle').attr('font-size', SUB_FS).attr('fill', fg).text(h);
d3.llmFitLabel(t, cw - 4, { pad: 0, text: h });
});
[d3.llmText('d3.cutofflane.row_flagged', 'flagged'), d3.llmText('d3.cutofflane.row_not_flagged', 'not flagged')].forEach(function (h, i) {
var t = gCells.append('text').attr('class', 'lch-cell-side').attr('x', x0 - 4).attr('y', y0 + ch * (i + 0.5) + FS * 0.35)
.attr('text-anchor', 'end').attr('font-size', SUB_FS).attr('fill', fg).text(h);
d3.llmFitLabel(t, labelW - 4, { pad: 0, text: h });
});
var defs = [
{ k: 'tp', r: 0, c: 0, tag: 'TP', word: d3.llmText('d3.cutofflane.caught', 'caught'), right: true }, { k: 'fp', r: 0, c: 1, tag: 'FP', word: d3.llmText('d3.cutofflane.false_alarms', 'false alarms'), right: false },
{ k: 'fn', r: 1, c: 0, tag: 'FN', word: d3.llmText('d3.cutofflane.missed', 'missed'), right: false }, { k: 'tn', r: 1, c: 1, tag: 'TN', word: d3.llmText('d3.cutofflane.left_alone', 'left alone'), right: true },
];
defs.forEach(function (d) {
var g = gCells.append('g').attr('class', 'lch-cell lch-cell-' + d.k);
var rect = g.append('rect').attr('class', 'lch-cell-rect lch-control').attr('x', x0 + cw * d.c + 1).attr('y', y0 + ch * d.r + 1)
.attr('width', cw - 2).attr('height', ch - 2).attr('rx', 3).attr('fill', d.right ? accent : warm).attr('stroke', d.right ? accent : warm);
var cx = x0 + cw * (d.c + 0.5), cy = y0 + ch * (d.r + 0.5);
var big = g.append('text').attr('class', 'lch-cell-count').attr('x', cx).attr('y', cy - FS * 0.1).attr('text-anchor', 'middle')
.attr('font-size', BIG_FS).attr('font-weight', 600).attr('fill', fg).attr('pointer-events', 'none');
var small = g.append('text').attr('class', 'lch-cell-rate').attr('x', cx).attr('y', cy + FS * 1.15).attr('text-anchor', 'middle')
.attr('font-size', CAP_FS).attr('fill', fg).attr('pointer-events', 'none');
g.append('text').attr('class', 'lch-cell-tag').attr('x', x0 + cw * d.c + 5).attr('y', y0 + ch * d.r + CAP_FS + 2)
.attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.6).attr('pointer-events', 'none').text(d.tag);
var title = rect.append('title');
cellEls[d.k] = { rect: rect, big: big, small: small, title: title, d: d, g: g };
});
gCells.append('text').attr('class', 'lch-cell-accuracy').attr('x', cellsX).attr('y', y0 + ch * 2 + FS * 1.1)
.attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75);
}
function paintCurve() {
gCurve.selectAll('*').remove();
dotEl = null; ringEl = null; aucEl = null;
var m = { l: FS * 4.4, r: FS * 0.8, t: FS * 0.4, b: FS * 3.1 };
var px = curveX + m.l, py = curveTop + m.t, pw = Math.max(FS * 6, curveW - m.l - m.r), ph = Math.max(FS * 5, rowAH - (curveTop - panelTop) - m.t - m.b);
curveGeom = { px: px, py: py, pw: pw, ph: ph };
var x = d3.scaleLinear().domain([0, 1]).range([px, px + pw]), y = d3.scaleLinear().domain([0, 1]).range([py + ph, py]);
curveGeom.x = x; curveGeom.y = y;
gCurve.append('rect').attr('x', px).attr('y', py).attr('width', pw).attr('height', ph).attr('fill', 'none').attr('stroke', fg).attr('stroke-opacity', 0.3);
var ax = d3.axisBottom(x).ticks(4).tickSize(3).tickFormat(tickPct), ay = d3.axisLeft(y).ticks(4).tickSize(3).tickFormat(tickPct);
gCurve.append('g').attr('class', 'lch-axis').attr('transform', 'translate(0,' + (py + ph) + ')').call(ax).selectAll('text').attr('font-size', CAP_FS).attr('fill', fg);
gCurve.append('g').attr('class', 'lch-axis').attr('transform', 'translate(' + px + ',0)').call(ay).selectAll('text').attr('font-size', CAP_FS).attr('fill', fg);
gCurve.selectAll('.lch-axis path, .lch-axis line').attr('stroke', fg).attr('stroke-opacity', 0.4);
var showRoc = curveKind === 'roc';
gCurve.append('text').attr('class', 'lch-curve-xlabel').attr('x', px + pw / 2).attr('y', py + ph + FS * 2.6).attr('text-anchor', 'middle')
.attr('font-size', CAP_FS).attr('fill', fg).text(showRoc ? d3.llmText('d3.cutofflane.axis_false_alarm_rate', 'false alarm rate') : d3.llmText('d3.cutofflane.axis_recall', 'catch rate (recall)'));
gCurve.append('text').attr('class', 'lch-curve-ylabel').attr('transform', 'translate(' + (curveX + FS * 0.5) + ',' + (py + ph / 2) + ') rotate(-90)')
.attr('text-anchor', 'middle').attr('font-size', CAP_FS).attr('fill', fg).text(showRoc ? d3.llmText('d3.cutofflane.axis_catch_rate', 'catch rate') : d3.llmText('d3.cutofflane.axis_precision', 'precision'));
if (C.degenerate) {
var none = C.degenerate === 'noPositives' ? d3.llmText('d3.cutofflane.none_positive', 'no {outcome} = {positive} in the rows in view', { outcome: OUTCOME, positive: posName() }) : d3.llmText('d3.cutofflane.none_negative', 'no {negative} in the rows in view', { negative: negName() });
var nt = gCurve.append('text').attr('class', 'lch-curve-none').attr('x', px + pw / 2).attr('y', py + ph / 2).attr('text-anchor', 'middle')
.attr('font-size', SUB_FS).attr('fill', fg).text(none);
d3.llmFitLabel(nt, pw - 8, { pad: 0, text: none });
return;
}
if (showRoc) gCurve.append('line').attr('class', 'lch-chance').attr('x1', x(0)).attr('y1', y(0)).attr('x2', x(1)).attr('y2', y(1))
.attr('stroke', fg).attr('stroke-opacity', 0.35).attr('stroke-dasharray', '4 3');
else gCurve.append('line').attr('class', 'lch-chance').attr('x1', x(0)).attr('x2', x(1)).attr('y1', y(C.prevalence)).attr('y2', y(C.prevalence))
.attr('stroke', fg).attr('stroke-opacity', 0.35).attr('stroke-dasharray', '4 3');
var pts = (showRoc ? C.roc : C.pr).map(function (p) { return showRoc ? [x(p.fpr), y(p.tpr)] : [x(p.recall), y(p.precision === null ? 1 : p.precision)]; });
gCurve.append('path').attr('class', 'lch-curve-line').attr('d', d3.line()(pts)).attr('fill', 'none').attr('stroke', accent).attr('stroke-width', 2);
ringEl = gCurve.append('circle').attr('class', 'lch-ring').attr('r', Math.max(4, FS * 0.55)).attr('fill', 'none').attr('stroke', fg).attr('stroke-width', 1.5).attr('display', 'none');
dotEl = gCurve.append('circle').attr('class', 'lch-dot').attr('r', Math.max(3, FS * 0.4)).attr('fill', accent).attr('stroke', fg).attr('stroke-width', 1);
aucEl = gCurve.append('text').attr('class', 'lch-auc').attr('x', px + pw - 4).attr('y', py + ph - FS * 0.8).attr('text-anchor', 'end')
.attr('font-size', CAP_FS).attr('fill', fg);
var aucVal = C.auc === null ? '-' : f2.format(C.auc), apVal = C.averagePrecision === null ? '-' : f2.format(C.averagePrecision);
fitForms(aucEl, pw - 8, showRoc
? [d3.llmText('d3.cutofflane.auc_on_class', 'AUC {auc} on {n} {positive}', { auc: aucVal, n: cnt(C.nPos), positive: posName() }), d3.llmText('d3.cutofflane.auc_on', 'AUC {auc} on {n}', { auc: aucVal, n: cnt(C.nPos) }), d3.llmText('d3.cutofflane.auc', 'AUC {auc}', { auc: aucVal })]
: [d3.llmText('d3.cutofflane.ap_on_class', 'average precision {ap} on {n} {positive}', { ap: apVal, n: cnt(C.nPos), positive: posName() }), d3.llmText('d3.cutofflane.ap_on', 'precision {ap} on {n}', { ap: apVal, n: cnt(C.nPos) }), d3.llmText('d3.cutofflane.ap', 'precision {ap}', { ap: apVal })]);
}
function paintDist() {
gDist.selectAll('*').remove();
binEls = []; cutLineEl = null;
var m = { l: FS * 7, r: FS * 0.8, t: FS * 0.2, b: FS * 1.9 };
var px = PAD + m.l, py = rowBY + m.t, pw = Math.max(FS * 8, W - PAD - px - m.r), ph = Math.max(FS * 5, rowBH - m.t - m.b);
var n = Math.min(30, C.distinct), bins = C.bins(n);
var x = d3.scaleLinear().domain([C.min, C.max > C.min ? C.max : C.min + 1]).range([px, px + pw]);
var half = ph / 2, mid = py + half;
var yNeg = d3.scaleLinear().domain([0, Math.max(1, bins.maxNeg)]).range([0, half - 2]);
var yPos = d3.scaleLinear().domain([0, Math.max(1, bins.maxPos)]).range([0, half - 2]);
distGeom = { x: x, px: px, pw: pw, py: py, ph: ph };
gDist.append('line').attr('class', 'lch-dist-axis').attr('x1', px).attr('x2', px + pw).attr('y1', mid).attr('y2', mid).attr('stroke', fg).attr('stroke-opacity', 0.5);
gDist.append('g').attr('class', 'lch-axis').attr('transform', 'translate(0,' + (py + ph) + ')').call(d3.axisBottom(x).ticks(6).tickSize(3).tickFormat(tickScore))
.selectAll('text').attr('font-size', CAP_FS).attr('fill', fg);
gDist.selectAll('.lch-axis path, .lch-axis line').attr('stroke', fg).attr('stroke-opacity', 0.4);
var labW = m.l - FS * 0.6;
function sideLabel(cls, y, name, big) {
var a = gDist.append('text').attr('class', 'lch-dist-label-' + cls).attr('x', PAD).attr('y', y).attr('font-size', CAP_FS).attr('fill', fg).text(name);
d3.llmFitLabel(a, labW, { pad: 0, text: name });
var b = gDist.append('text').attr('class', 'lch-dist-scale-' + cls).attr('x', PAD).attr('y', y + FS * 1.25).attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.7);
fitForms(b, labW, [d3.llmText('d3.cutofflane.up_to', 'up to {n}', { n: cnt(big) }), cnt(big)]);
}
sideLabel('neg', py + FS * 0.9, negName(), bins.maxNeg);
sideLabel('pos', py + ph - FS * 2.3, posName(), bins.maxPos);
bins.forEach(function (b) {
var bx = x(b.x0) + 0.5, bw = Math.max(1, x(b.x1) - x(b.x0) - 1);
[{ k: 'neg', count: b.neg, ids: b.negRowIdxs, label: negName() }, { k: 'pos', count: b.pos, ids: b.posRowIdxs, label: posName() }].forEach(function (s) {
if (!(s.count > 0)) return;
var hgt = s.k === 'neg' ? yNeg(s.count) : yPos(s.count);
var rect = gDist.append('rect').attr('class', 'lch-bin lch-bin-' + s.k).attr('x', bx).attr('width', bw)
.attr('y', s.k === 'neg' ? mid - hgt : mid).attr('height', Math.max(1, hgt)).attr('stroke', s.k === 'neg' ? fg : warm)
.attr('fill', s.k === 'neg' ? fg : warm);
var rowsHere = s.ids.length;
if (rowsHere > ROW_CAP) {
rect.attr('class', 'lch-bin lch-bin-' + s.k + ' lch-control').attr('cursor', 'not-allowed');
rect.append('title').text(d3.llmText('d3.cutofflane.bin_too_many', '{n} {label} between {from} and {to}: {rows} rows are too many to select at once (limit {limit})', { n: cnt(s.count), label: s.label, from: score(b.x0), to: score(b.x1), rows: nf0.format(rowsHere), limit: nf0.format(ROW_CAP) }));
} else {
rect.attr('class', 'lch-bin lch-bin-' + s.k + ' d3-mark').attr('data-row-idx', s.ids.join(',')).attr('cursor', 'pointer');
rect.append('title').text(d3.llmText('d3.cutofflane.bin', '{n} {label} between {from} and {to}', { n: cnt(s.count), label: s.label, from: score(b.x0), to: score(b.x1) }));
}
binEls.push({ rect: rect, bin: b });
});
});
cutLineEl = gDist.append('line').attr('class', 'lch-cut-line').attr('y1', py).attr('y2', py + ph).attr('stroke', fg).attr('stroke-width', 1.5).attr('pointer-events', 'none');
}
function paintCost() {
var k = costs(), A = C.at(cut);
if (!k || !A) {
if (ringEl) ringEl.attr('display', 'none');
fitForms(read2, W - 2 * PAD, [d3.llmText('d3.cutofflane.type_costs', 'type what a false alarm costs and what a miss costs to find the cheapest cutoff'), d3.llmText('d3.cutofflane.type_costs_short', 'type both costs to find the cheapest cutoff')]);
return;
}
var here = A.fp * k.a + A.fn * k.b, ch = C.cheapest(k.a, k.b);
if (!ch) { read2.text(d3.llmText('d3.cutofflane.cost_nonneg', 'a cost is zero or more')); if (ringEl) ringEl.attr('display', 'none'); return; }
var less = here - ch.cost;
var ratio = ch.ratio2 === null ? '' : (ch.ratio2 === 1 ? d3.llmText('d3.cutofflane.ratio', ' | a miss costs one false alarm', { ratio: cf.format(1) }, 1) : d3.llmText('d3.cutofflane.ratio', ' | a miss costs {ratio} false alarms', { ratio: cf.format(ch.ratio2) }, ch.ratio2));
var head = d3.llmText('d3.cutofflane.total_cost', 'total cost {cost} at {cut}', { cost: money(here), cut: whoCutLong(cut) });
var best = less > 1e-9 ? d3.llmText('d3.cutofflane.cheapest_less', 'cheapest {cut}: {cost} ({less} less)', { cut: whoCutLong(ch.t), cost: money(ch.cost), less: money(less) }) : d3.llmText('d3.cutofflane.cheapest_here', 'cheapest {cut}: {cost} (this is the cheapest)', { cut: whoCutLong(ch.t), cost: money(ch.cost) });
var base = d3.llmText('d3.cutofflane.baselines', 'flag nobody {nobody}, flag everybody {everybody}', { nobody: money(ch.nobodyCost), everybody: money(ch.everybodyCost) });
fitForms(read2, W - 2 * PAD, [head + ' | ' + best + ' | ' + base + ratio, head + ' | ' + best + ' | ' + base, head + ' | ' + best, best]);
if (ringEl && curveGeom) {
var rx = curveKind === 'roc' ? ch.falseAlarmRate : ch.catchRate, ry = curveKind === 'roc' ? ch.catchRate : (ch.precision === null ? 1 : ch.precision);
ringEl.attr('cx', curveGeom.x(rx)).attr('cy', curveGeom.y(ry)).attr('display', null);
}
}
function update(t, phase) {
var A = C.at(t);
if (!A) return;
var info = {
tp: { n: A.tp, rate: A.catchRate, of: d3.llmText('d3.cutofflane.caught', 'caught') }, fp: { n: A.fp, rate: A.falseAlarmRate, of: d3.llmText('d3.cutofflane.false_alarms', 'false alarms') },
fn: { n: A.fn, rate: A.missRate, of: d3.llmText('d3.cutofflane.missed', 'missed') }, tn: { n: A.tn, rate: A.specificity, of: d3.llmText('d3.cutofflane.left_alone', 'left alone') },
};
Object.keys(cellEls).forEach(function (k) {
var e = cellEls[k], v = info[k];
e.big.text(cnt(v.n));
fitForms(e.small, +e.rect.attr('width') - 6, v.rate === null ? [''] : [d3.llmText('d3.cutofflane.cell_rate', '{rate} {what}', { rate: pct(v.rate), what: v.of }), pct(v.rate)]);
e.rect.attr('fill-opacity', v.rate === null ? 0.08 : 0.12 + 0.5 * v.rate).attr('stroke-opacity', 0.6);
if (phase !== 'drag') {
var ids = C.flaggedRowIdxs(t, k);
if (ids.length > ROW_CAP) {
e.rect.attr('class', 'lch-cell-rect lch-control').attr('cursor', 'not-allowed').attr('data-row-idx', null);
e.title.text(d3.llmText('d3.cutofflane.cell_too_many', '{n} {what}: {rows} rows are too many to select at once (limit {limit})', { n: cnt(v.n), what: e.d.word, rows: nf0.format(ids.length), limit: nf0.format(ROW_CAP) }));
} else if (ids.length) {
e.rect.attr('class', 'lch-cell-rect d3-mark').attr('cursor', 'pointer').attr('data-row-idx', ids.join(','));
e.title.text(d3.llmText('d3.cutofflane.cell_select', '{n} {what} - click to select them', { n: cnt(v.n), what: e.d.word }));
} else {
e.rect.attr('class', 'lch-cell-rect lch-control').attr('cursor', 'default').attr('data-row-idx', null);
e.title.text(d3.llmText('d3.cutofflane.cell_none', 'no cases {what}', { what: e.d.word }));
}
}
});
var acc = gCells.select('.lch-cell-accuracy');
var nobodyAcc = C.n > 0 ? (C.nNeg / C.n) : null;
fitForms(acc, cellsW, A.accuracy === null ? [''] : [d3.llmText('d3.cutofflane.accuracy', 'accuracy {acc}, against {base} for flagging nobody', { acc: pct(A.accuracy), base: pct(nobodyAcc) }), d3.llmText('d3.cutofflane.accuracy_short', 'accuracy {acc} vs {base} flagging nobody', { acc: pct(A.accuracy), base: pct(nobodyAcc) })]);
if (dotEl && curveGeom) {
var dx = curveKind === 'roc' ? A.falseAlarmRate : A.catchRate, dy = curveKind === 'roc' ? A.catchRate : (A.precision === null ? 1 : A.precision);
if (dx !== null && dy !== null) dotEl.attr('cx', curveGeom.x(dx)).attr('cy', curveGeom.y(dy));
}
if (cutLineEl && distGeom) {
var cx = distGeom.x(Math.max(C.min, Math.min(C.max, t)));
cutLineEl.attr('x1', cx).attr('x2', cx);
}
binEls.forEach(function (be) {
var st = C.binAt(be.bin, t).state;
be.rect.attr('fill-opacity', st === 'all' ? 0.85 : st === 'part' ? 0.45 : 0.0).attr('stroke-opacity', 0.7);
});
var flagged = d3.llmText('d3.cutofflane.readout', 'flagged {flagged} of {n} ({share}) caught {tp} of {npos} {positive} ({catch}) false alarms {fp} ({far} of {negative})', { flagged: cnt(A.flagged), n: cnt(A.n), share: pct(A.flaggedShare), tp: cnt(A.tp), npos: cnt(C.nPos), positive: posName(), catch: pct(A.catchRate), fp: cnt(A.fp), far: pct(A.falseAlarmRate), negative: negName() });
fitForms(read1, W - 2 * PAD, [flagged,
d3.llmText('d3.cutofflane.readout_mid', 'flagged {flagged} ({share}) caught {tp} ({catch}) false alarms {fp} ({far})', { flagged: cnt(A.flagged), share: pct(A.flaggedShare), tp: cnt(A.tp), catch: pct(A.catchRate), fp: cnt(A.fp), far: pct(A.falseAlarmRate) }),
d3.llmText('d3.cutofflane.readout_short', 'flagged {flagged}, caught {tp}, false alarms {fp}', { flagged: cnt(A.flagged), tp: cnt(A.tp), fp: cnt(A.fp) })]);
paintCost();
}
function paintAll() {
var s = sentenceLines();
sLine1.text(s[0]); sLine2.text(s[1]);
d3.llmFitLabel(sLine1, W - 2 * PAD, { pad: 0, text: s[0] });
d3.llmFitLabel(sLine2, W - 2 * PAD, { pad: 0, text: s[1] });
var notes = [];
if (C.weighted && C.distinct <= 40) notes.push(d3.llmText('d3.cutofflane.note_buckets', '{n} score buckets: each step moves a whole bucket', { n: String(C.distinct) }));
else if (C.distinct <= 20) notes.push(d3.llmText('d3.cutofflane.note_distinct', '{n} distinct scores: each step moves every case at that score', { n: String(C.distinct) }));
if (C.nPos > 0 && C.nPos < 30 && !C.weighted) notes.push(d3.llmText('d3.cutofflane.note_few', 'built on {n} {positive}: each step on the curve is one case', { n: cnt(C.nPos), positive: posName() }));
if (C.band !== null && C.withinBand) notes.push(d3.llmText('d3.cutofflane.note_noise', 'this score is within the noise: AUC {auc}, and chance alone reaches {chance}', { auc: C.auc === null ? '-' : f2.format(C.auc), chance: f2.format(0.5 + C.band) }));
if (C.prevalence !== null && C.prevalence < 0.1 && curveKind === 'roc') notes.push(d3.llmText('d3.cutofflane.note_rare', 'with {share} {positive}, precision-recall shows the false alarms more plainly', { share: pct(C.prevalence), positive: posName() }));
if (C.skipped && (C.skipped.score || C.skipped.outcome || C.skipped.weight)) notes.push(d3.llmText('d3.cutofflane.note_skipped', '{n} rows left out (no score, outcome or count)', { n: String(C.skipped.score + C.skipped.outcome + C.skipped.weight) }));
var capForms = [];
for (var ni = notes.length; ni >= 1; ni--) capForms.push(notes.slice(0, ni).join('; '));
fitForms(capText, W - 2 * PAD, capForms.length ? capForms : ['']);
paintCells(); paintCurve(); paintDist();
update(cut, 'end');
}
ready = true;
paintAll();
}
Keep going
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.