Sum of Orders between ToStep and Team
Which pairs exchange the most Sum of Orders?
Twenty-two hand-offs between the twelve steps of an order fulfilment process, from order received to delivered, each with the team that owns the step it starts from and the number of orders that took that path. Backorders, cancellations, rework and returns loop back or leave the main line, so it is a real process rather than a straight chain. A from-step, a to-step and a team make a flowchart with a swimlane per team.
Order Fulfilment Process Flow: 22 rows, 4 columns. Download the CSV
| FromStep | ToStep | Team | Sum of Orders |
|---|---|---|---|
| Order received | Stock check | Receiving | 8150 |
| Order received | Backorder | Receiving | 280 |
| Order received | Cancelled | Receiving | 170 |
| Stock check | Pick | Receiving | 8080 |
| Stock check | Backorder | Receiving | 690 |
| Stock check | Cancelled | Receiving | 80 |
| Backorder | Stock check | Receiving | 700 |
| Backorder | Pick | Receiving | 260 |
| Backorder | Cancelled | Receiving | 130 |
| Pick | Pack | Warehouse | 8180 |

How to read it
Each arc on the circle is a node, and a chord's width at each end is the amount between that pair. The widest runs between Stock check and Receiving.
The chart's code (65 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
d3.llmValueColumn = function (columns, rows, opts) {
opts = opts || {};
var cols = Array.isArray(columns) ? columns : [];
var data = Array.isArray(rows) ? rows : [];
var isHost = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
return n.indexOf('__') === 0;
};
var taken = {};
(Array.isArray(opts.exclude) ? opts.exclude : []).forEach(function (i) {
if (i != null && i >= 0) taken[i] = 1;
});
var coordinates = [];
if (opts.excludeCoordinates) {
var coordWords = d3.llmValueColumn.nameWords;
var allLongitudes = function (ci) {
var seenL = 0;
for (var rr = 0; rr < data.length; rr++) {
var lv = data[rr] ? data[rr][ci] : null;
if (lv === null || lv === undefined || lv === '') continue;
lv = +lv; seenL++;
if (!isFinite(lv) || lv < -180 || lv > 180) return false;
}
return seenL > 0;
};
cols.forEach(function (c, ci) {
if (!c || isHost(c)) return;
var declared = String(c.semanticType || c.dataCategory || '').toLowerCase();
var w = coordWords(c.name);
if (declared === 'latitude' || declared === 'longitude'
|| w.some(function (t) { return /^(lat|latitude|lon|lng|longitude)$/.test(t); })
|| (w.indexOf('long') >= 0 && allLongitudes(ci))) {
taken[ci] = 1;
coordinates.push(String(c.name));
}
});
}
var NUMERIC_TYPES = { integer: 1, decimal: 1, double: 1, float: 1, single: 1,
number: 1, int64: 1, int32: 1, currency: 1, money: 1 };
var isNumericCol = function (c, i) {
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (dt) return NUMERIC_TYPES[dt] === 1;
var seen = 0, num = 0;
for (var r = 0; r < data.length && seen < 50; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
if (typeof v !== 'boolean' && isFinite(+v)) num++;
}
return seen > 0 && num === seen;
};
var isRegionCode = function (c) {
var k = (c && c.geoKind != null) ? String(c.geoKind).toLowerCase() : '';
if (!k) return false;
return k.indexOf('zip') === 0 || k.indexOf('us-zip') === 0 || k.indexOf('us-state') === 0 ||
k.indexOf('us-county') === 0 || k.indexOf('us-fips') === 0 || k.indexOf('fips') === 0 ||
k.indexOf('country-') === 0 || k.indexOf('iso-') === 0;
};
var ID_TOKENS = { id: 1, ids: 1, identifier: 1, code: 1, codes: 1, zip: 1, zipcode: 1,
postal: 1, postcode: 1, fips: 1, guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1,
isbn: 1, key: 1, num: 1, number: 1, no: 1, ref: 1, serial: 1, barcode: 1,
account: 1, acct: 1, vin: 1, imei: 1, ssn: 1 };
var nameLooksLikeId = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
if (!n) return false;
var parts = n.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^A-Za-z0-9]+/);
for (var p = 0; p < parts.length; p++) {
if (parts[p] && ID_TOKENS[parts[p].toLowerCase()] === 1) return true;
}
return false;
};
var looksLikeKeyData = function (c, i) {
var seen = 0, ints = 0, vals = {}, distinct = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
var num = +v;
if (isFinite(num) && Math.floor(num) === num) ints++;
var kk = String(v);
if (vals[kk] !== 1) { vals[kk] = 1; distinct++; }
}
return seen >= 8 && ints === seen && (distinct / seen) >= 0.9;
};
var isIdentifierCol = function (c, i) {
if (!c) return false;
if (isRegionCode(c)) return true;
return nameLooksLikeId(c) && looksLikeKeyData(c, i);
};
var STRONG_ID_HEADS = { id: 1, ids: 1, identifier: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1,
guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1, isbn: 1, serial: 1, barcode: 1, vin: 1, imei: 1, ssn: 1 };
var WEAK_ID_TAILS = { code: 1, codes: 1, number: 1, num: 1, no: 1, nbr: 1, ref: 1 };
var allIntegers = function (i) {
var seen = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
}
return seen > 0;
};
var COUNT_WORDS = { count: 1, countd: 1, distinct: 1, recuento: 1, contagem: 1, anzahl: 1, aantal: 1, conteggio: 1,
antal: 1, antall: 1, lukumaara: 1, 'lukum\u00e4\u00e4r\u00e4': 1, pocet: 1, 'po\u010det': 1, liczba: 1 };
var NUMBER_OF = { number: 1, num: 1, no: 1, nombre: 1 };
var OF_WORDS = { of: 1, de: 1, du: 1, des: 1 };
var countsSomething = function (c, w) {
if (/^\s*#/.test(String(c.name))) return true;
for (var k = 0; k < w.length; k++) {
if (COUNT_WORDS[w[k]] === 1) return true;
if (NUMBER_OF[w[k]] === 1 && OF_WORDS[w[k + 1]] === 1) return true;
}
return false;
};
var CODE_WORDS = { zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1, code: 1, iso: 1, geoid: 1 };
var isFlaggedIdentifier = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name);
if (isRegionCode(c)) for (var cw = 0; cw < w.length; cw++) if (CODE_WORDS[w[cw]] === 1) return true;
if (!w.length || countsSomething(c, w)) return false;
var head = w[w.length - 1];
if (WEAK_ID_TAILS[head] === 1 && w.length > 1 && STRONG_ID_HEADS[w[w.length - 2]] === 1) head = w[w.length - 2];
if (!(STRONG_ID_HEADS[head] === 1 || w[0] === 'id')) return false;
return allIntegers(i);
};
var DATE_KEY_WORDS = { key: 1, date: 1, period: 1, month: 1, yyyymm: 1, yyyymmdd: 1, ym: 1, ymd: 1 };
var isDateKey = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name), named = false;
for (var k = 0; k < w.length; k++) if (DATE_KEY_WORDS[w[k]] === 1) { named = true; break; }
if (!named) return false;
var seen = 0, ymd = 0, ym = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
if (n >= 19000101 && n <= 21001231) {
var mo = Math.floor(n / 100) % 100, dd = n % 100;
if (mo >= 1 && mo <= 12 && dd >= 1 && dd <= 31) ymd++;
} else if (n >= 190001 && n <= 210012) {
var m2 = n % 100;
if (m2 >= 1 && m2 <= 12) ym++;
}
}
return seen > 0 && (ymd === seen || ym === seen);
};
var isTextMeasure = function (c) {
if (!c || !c.isMeasure) return false;
var dt = (c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (!dt || NUMERIC_TYPES[dt] === 1 || dt === 'datetime' || dt === 'date' || dt === 'boolean') return false;
if (c.stdDev != null || c.sum != null || c.avgValue != null) return false;
return String(c.valueNature || '').toLowerCase() !== 'continuous';
};
var valueIndex = -1, resolvedBy = 'count';
var skipped = [];
var skippedText = []; // measures passed over because they hold text (isTextMeasure)
if (opts.prefer != null) {
var want = opts.prefer;
for (var q = 0; q < cols.length; q++) {
if (!cols[q]) continue;
if (q === want || (typeof want === 'string' && String(cols[q].name) === want)) {
if (!taken[q] && !isHost(cols[q])) { valueIndex = q; resolvedBy = 'preferred'; }
break;
}
}
}
var refused = {};
var notAQuantity = function (c, ci) {
if (refused[ci] !== undefined) return refused[ci];
return (refused[ci] = isTextMeasure(c) ? 'text' : ((isFlaggedIdentifier(c, ci) || isDateKey(c, ci)) ? 'key' : ''));
};
var IDENT_LAST = { id: 1, ids: 1, uuid: 1, guid: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postalcode: 1, ssn: 1,
code: 1, codes: 1, sku: 1, isbn: 1, msisdn: 1, imei: 1 };
var ORDINAL_WORDS = { hour: 1, hr: 1, day: 1, dow: 1, dom: 1, weekday: 1, week: 1, wk: 1, woy: 1, month: 1, mth: 1,
quarter: 1, qtr: 1, year: 1, yr: 1, semester: 1, trimester: 1, decade: 1, period: 1, fiscal: 1,
fy: 1, rank: 1, level: 1, lvl: 1, tier: 1, grade: 1, band: 1, decile: 1, percentile: 1,
quartile: 1, quintile: 1, score: 1, rating: 1, stars: 1, step: 1, stage: 1, phase: 1, round: 1,
wave: 1, episode: 1, chapter: 1, age: 1, cohort: 1, generation: 1, seniority: 1, position: 1,
sequence: 1, seq: 1, priority: 1 };
var looksContinuous = function (c, i) {
var w = d3.llmValueColumn.nameWords(c.name);
if (w.length && IDENT_LAST[w[w.length - 1]] === 1) return false;
if (d3.llmValueColumn.localizedIdentifierWord(c.name)) return false;
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
var hasFraction = false, seenV = {}, distinct = 0, nonblank = 0, mn = Infinity, mx = -Infinity;
for (var r = 0; r < data.length; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n)) continue;
nonblank++;
var key = String(v);
if (seenV[key] !== 1) { seenV[key] = 1; distinct++; }
if (n < mn) mn = n;
if (n > mx) mx = n;
if (Math.floor(n) !== n) hasFraction = true;
}
if (nonblank === 0) return false;
var fractional = hasFraction || dt === 'decimal' || dt === 'double' || dt === 'float' || dt === 'single'
|| dt === 'currency' || dt === 'money';
var span = mx - mn + 1, density = span > 0 ? distinct / span : 1;
if (density >= 0.9) {
for (var k = 0; k < w.length; k++) if (ORDINAL_WORDS[w[k]] === 1 && distinct <= 120) return false;
if (mn >= 1900 && mx <= 2100) return false;
if (mn >= 0 && mx <= 20) return false;
}
return distinct > 12 && (fractional || distinct >= 100 || distinct / nonblank >= 0.30);
};
var measures = [];
for (var mi = 0; mi < cols.length; mi++) {
if (taken[mi] || !cols[mi] || !cols[mi].isMeasure || isHost(cols[mi])) continue;
if (!notAQuantity(cols[mi], mi)) measures.push(mi);
}
var measuresInferred = false;
var anyFlagged = false, anyProfiled = false;
for (var fi = 0; fi < cols.length; fi++) {
var fc = cols[fi];
if (!fc || isHost(fc)) continue;
if (fc.isMeasure) anyFlagged = true;
if (fc.valueNature != null || fc.distinctCount != null) anyProfiled = true;
}
if (!anyFlagged && !anyProfiled) {
for (var ni = 0; ni < cols.length; ni++) {
if (taken[ni] || !cols[ni] || isHost(cols[ni])) continue;
if (!isNumericCol(cols[ni], ni)) continue;
if (isIdentifierCol(cols[ni], ni) || isDateKey(cols[ni], ni)) continue;
if (!looksContinuous(cols[ni], ni)) continue;
measures.push(ni);
}
measuresInferred = measures.length > 0;
}
if (valueIndex < 0) {
for (var i = 0; i < cols.length; i++) {
if (taken[i]) continue;
if (!cols[i] || !cols[i].isMeasure || isHost(cols[i])) continue;
var why = notAQuantity(cols[i], i);
if (why === 'text') { skippedText.push(String(cols[i].name)); continue; }
if (why === 'key') { skipped.push(String(cols[i].name)); continue; }
valueIndex = i; resolvedBy = 'measure'; break;
}
}
if (valueIndex < 0) {
for (var j = 0; j < cols.length; j++) {
if (taken[j] || !cols[j] || isHost(cols[j])) continue;
if (!isNumericCol(cols[j], j)) continue;
if (refused[j] === 'key') continue; // a flagged key rule 1 already refused and named
if (isIdentifierCol(cols[j], j) || isDateKey(cols[j], j)) {
skipped.push(String(cols[j].name));
continue;
}
valueIndex = j; resolvedBy = 'numeric'; break;
}
}
var labelIndex = -1;
for (var k = 0; k < cols.length; k++) {
if (taken[k] || !cols[k] || isHost(cols[k]) || k === valueIndex) continue;
labelIndex = k; break;
}
var isCount = valueIndex < 0;
var nameOf = function (idx) {
var c = cols[idx];
return (c && c.name != null) ? String(c.name) : '';
};
return {
valueIndex: valueIndex,
valueName: isCount ? (opts.countLabel || 'Rows') : nameOf(valueIndex),
labelIndex: labelIndex,
labelName: labelIndex >= 0 ? nameOf(labelIndex) : '',
isCount: isCount,
resolvedBy: resolvedBy,
skipped: skipped,
skippedText: skippedText,
coordinates: coordinates,
measures: measures,
measuresInferred: measuresInferred,
valueOf: function (row) {
if (isCount) return 1;
if (!row) return null;
var v = row[valueIndex];
if (v == null || v === '' || typeof v === 'boolean') return null;
var n = +v;
return isFinite(n) ? n : null;
}
};
};
d3.llmValueColumn.nameWords = function (name, opts) {
var s = String(name == null ? '' : name);
try { s = s.normalize('NFC'); } catch (e) { /* an unpaired surrogate: read it as it stands */ }
s = s.replace(/([\p{Ll}\p{Nd}])(?=\p{Lu})/gu, '$1 ').toLowerCase();
return s.split(opts && opts.digits ? /[^\p{L}\p{M}\p{N}]+/u : /[^\p{L}\p{M}]+/u)
.filter(function (w) { return w.length > 0; });
};
d3.llmValueColumn.localizedIdentifierWord = (function () {
var WORDS = {
de: ['nr', 'nummer', 'kennung', 'kennziffer', 'plz', 'postleitzahl'],
nl: ['nr', 'nummer'],
sv: ['nr', 'nummer'],
da: ['nr', 'nummer'],
nb: ['nr', 'nummer'],
fi: ['tunnus', 'koodi', 'nro'],
hu: ['azonos\u00edt\u00f3', 'k\u00f3d'],
tr: ['kod', 'kodu', 'numaras\u0131', 'numarasi'],
zh: ['\u7f16\u53f7', '\u4ee3\u7801', '\u7f16\u7801', '\u53f7\u7801', '\u90ae\u7f16'],
ja: ['\u756a\u53f7', '\u30b3\u30fc\u30c9'],
ko: ['\ubc88\ud638', '\ucf54\ub4dc'],
hi: ['\u0915\u094b\u0921', '\u0915\u094d\u0930\u092e\u093e\u0902\u0915'],
fr: ['num\u00e9ro'],
es: ['c\u00f3digo'],
pt: ['c\u00f3digo', 'cep'],
it: ['codice'],
pl: ['kod', 'numer'],
cs: ['k\u00f3d', '\u010d\u00edslo'],
sk: ['k\u00f3d', '\u010d\u00edslo'],
hr: ['\u0161ifra', 'oznaka'],
ru: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
uk: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
el: ['\u03ba\u03c9\u03b4\u03b9\u03ba\u03cc\u03c2'],
ar: ['\u0631\u0645\u0632', '\u0643\u0648\u062f', '\u0631\u0642\u0645'],
he: ['\u05e7\u05d5\u05d3'],
id: ['kode', 'nomor'],
vi: ['m\u00e3'],
th: ['\u0e23\u0e2b\u0e31\u0e2a']
};
var HEAD_INITIAL = ['fr', 'es', 'pt', 'it', 'pl', 'cs', 'sk', 'hr', 'ru', 'uk', 'el', 'ar', 'he', 'id', 'vi', 'th'];
var COMPOUNDS = ['nl', 'de', 'sv', 'da', 'nb', 'fi', 'hu'];
var NO_BREAKS = ['zh', 'ja', 'th'];
var UNFOLDED = ['num\u00e9ro'];
var GLUED = { ar: ['\u0627\u0644', '\u0648\u0627\u0644', '\u0628\u0627\u0644', '\u0641\u0627\u0644', '\u0643\u0627\u0644', '\u0644\u0644', '\u0648', '\u0641', '\u0628', '\u0643', '\u0644'], he: ['\u05d4', '\u05d5', '\u05d1', '\u05dc', '\u05de', '\u05e9', '\u05db', '\u05d5\u05d4', '\u05e9\u05d4', '\u05de\u05d4', '\u05d5\u05d1', '\u05d5\u05dc', '\u05d5\u05de', '\u05d1\u05d4', '\u05dc\u05d4'] };
var DEFAULT_PREFIXES = ['somme de', 'suma de', 'soma de', 'summe von', 'som van', 'somma di', 'summa av', 'sum av', 'sum af', 'soucet z', 'suma z', 'totaal van', 'total de', 'toplam', 'osszeg', 'nombre de', 'recuento de', 'contagem de', 'anzahl von', 'aantal van', 'conteggio di', 'antal av', 'lukumaara', 'pocet z', 'sum pa', '\u0441\u0443\u043c\u043c\u0430', '\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e', '\u0441\u0443\u043c\u0430', '\u043a\u0456\u043b\u044c\u043a\u0456\u0441\u0442\u044c', '\u03b1\u03b8\u03c1\u03bf\u03b9\u03c3\u03bc\u03b1', '\u03c0\u03bb\u03b7\u03b8\u03bf\u03c2'];
var DEFAULT_SUFFIXES = ['osszege', 'sucet', '\u7684\u603b\u548c', '\u7684\u8ba1\u6570', '\u306e\u5408\u8a08', '\uc758 \ud569\uacc4'];
var has = function (list, x) { return list.indexOf(x) >= 0; };
var cpLen = function (s) { return Array.from(s).length; };
var STROKE = { '\u0142': 'l', '\u0141': 'L', '\u0131': 'i', '\u00f8': 'o', '\u00d8': 'O', '\u0111': 'd', '\u0110': 'D', '\u00f0': 'd', '\u00d0': 'D' };
var DIGIT_ZEROS = [0x0660, 0x06F0, 0x0966, 0x0E50, 0xFF10];
var foldName = function (s) {
var out = '';
Array.from(s).forEach(function (ch) {
if (STROKE[ch]) { out += STROKE[ch]; return; }
var cp = ch.codePointAt(0);
for (var z = 0; z < DIGIT_ZEROS.length; z++) if (cp >= DIGIT_ZEROS[z] && cp <= DIGIT_ZEROS[z] + 9) { out += String.fromCharCode(0x30 + cp - DIGIT_ZEROS[z]); return; }
if ((cp >= 0xFF21 && cp <= 0xFF3A) || (cp >= 0xFF41 && cp <= 0xFF5A)) { out += String.fromCharCode(cp - 0xFEE0); return; }
var d = ch.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
out += d.length === 1 ? d : ch;
});
return out;
};
var readWords = function (name) {
return String(name == null ? '' : name).normalize('NFC')
.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu, '$1 $2').replace(/[_\-.\/]+/g, ' ')
.replace(/[^\p{L}\p{M}\p{N}\x00-\x7F]/gu, ' ').toLowerCase().split(/\s+/)
.filter(function (w) { return w.length > 0; });
};
var readName = function (name) {
var s = String(name == null ? '' : name).normalize('NFC');
var words = readWords(s), folded = readWords(foldName(s));
return { words: words, folded: folded.length === words.length ? folded : words.map(foldName) };
};
var lowerNfc = function (s) { return s.normalize('NFC').toLowerCase(); };
var alt = function (phrases) {
return phrases.slice().sort(function (a, b) { return b.length - a.length; })
.map(function (t) { return t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+'); }).join('|');
};
var hasCjk = function (t) {
return Array.from(t).some(function (ch) { var c = ch.codePointAt(0); return (c >= 0x2e80 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af); });
};
var PREFIX_RE = new RegExp('^\\s*(?:(?:sum|count|count\\s+distinct|distinct\\s+count)\\s+of\\s+|(?:' + alt(DEFAULT_PREFIXES) + ')\\s+)', 'i');
var SUFFIX_RE = (function () {
var latin = DEFAULT_SUFFIXES.filter(function (l) { return !hasCjk(l); }), cjk = DEFAULT_SUFFIXES.filter(hasCjk), parts = [];
if (latin.length) parts.push('(?:\\s+|\\s*[\u2013\u2014-]\\s*)(' + alt(latin) + ')');
if (cjk.length) parts.push('\\s*(' + alt(cjk) + ')');
return new RegExp('(?:' + parts.join('|') + ')\\s*$', 'i');
})();
var stripAgg = function (name) {
var s = String(name == null ? '' : name), folded = foldName(s);
var m = PREFIX_RE.exec(folded);
if (m) return s.slice(m[0].length).trim();
var sm = SUFFIX_RE.exec(folded);
if (sm && folded.slice(0, sm.index).trim() !== '') return s.slice(0, sm.index).trim();
return s.trim();
};
var endsWithStem = function (word, token, minStem) {
return !!word && !!token && word.length > token.length && word.endsWith(token) && cpLen(word.slice(0, word.length - token.length)) >= minStem;
};
var gluedStems = function (word, lang) {
var out = [], list = GLUED[lang];
if (!word || !list) return out;
list.slice().sort(function (a, b) { return b.length - a.length; }).forEach(function (p) {
if (word.length > p.length && word.startsWith(p)) { var st = word.slice(p.length); if (cpLen(st) >= 2 && out.indexOf(st) < 0) out.push(st); }
});
return out;
};
var readsAs = function (word, token, lang, first) {
if (!word) return false;
if (word === token) return true;
if (has(NO_BREAKS, lang)) {
if (cpLen(token) < 2) return false;
return (first ? word.startsWith(token) : word.endsWith(token)) && word.length > token.length;
}
if (first) return gluedStems(word, lang).indexOf(token) >= 0;
if (lang === 'ko') return /\p{Script=Hangul}/u.test(token) && endsWithStem(word, token, 2);
if (has(COMPOUNDS, lang)) return endsWithStem(word, token, 3);
return false;
};
return function (name) {
var n = String(name == null ? '' : name).trim();
if (!n) return false;
var whole = readName(n), stripped = readName(stripAgg(n));
for (var lang in WORDS) {
var first = has(HEAD_INITIAL, lang), reading = first ? stripped : whole;
for (var t = 0; t < WORDS[lang].length; t++) {
var token = WORDS[lang][t];
var plain = has(UNFOLDED, token) || lang === 'vi';
var words = plain ? reading.words : reading.folded;
if (words.length === 0) continue;
var tok = plain ? lowerNfc(token) : readName(token).folded.join(' ');
if (readsAs(first ? words[0] : words[words.length - 1], tok, lang, first)) return true;
}
}
return false;
};
})();
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 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
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) : '';
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : '';
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.llmTooltip = function (container, opts) {
opts = opts || {};
var gap = opts.gap == null ? 12 : opts.gap; // distance from the cursor
var edge = opts.edge == null ? 4 : opts.edge; // minimum distance from the container edge
var routed = false; // true while the HOST is showing our content
var lastContent = ''; // what to re-send if the host is driving
var lastEv = null; // where the cursor last was, for a re-fit
var host = (container && typeof container.node === 'function') ? container.node() : container;
var noop = { show: function () { return this; }, move: function () { return this; }, hide: function () { return this; },
html: function () { return this; }, text: function () { return this; }, node: null };
if (!host || !host.appendChild) return noop;
var mount = host;
if (mount.tagName && String(mount.tagName).toLowerCase() === 'svg' && mount.parentNode) {
mount = mount.parentNode;
}
if (!mount || !mount.appendChild) return noop;
try {
var pos = (typeof getComputedStyle === 'function') ? getComputedStyle(mount).position : '';
if (!pos || pos === 'static') mount.style.position = 'relative';
} catch (e) { /* jsdom / exec-gate: no layout engine, positioning is inert anyway */ }
var tip = mount.__llmTip;
if (!tip || tip.parentNode !== mount) {
tip = document.createElement('div');
tip.className = 'llm-tooltip';
tip.style.position = 'absolute';
tip.style.left = '0px';
tip.style.top = '0px';
tip.style.pointerEvents = 'none';
tip.style.visibility = 'hidden';
tip.style.zIndex = '20';
tip.style.boxSizing = 'border-box';
tip.style.whiteSpace = opts.wrap ? 'normal' : 'nowrap';
tip.style.background = 'rgba(255,255,255,0.97)';
tip.style.border = '1px solid rgba(0,0,0,0.28)';
tip.style.borderRadius = '4px';
tip.style.padding = '6px 9px';
tip.style.boxShadow = '0 2px 6px rgba(0,0,0,0.22)';
tip.style.color = '#222';
tip.style.fontSize = '12px';
mount.appendChild(tip);
mount.__llmTip = tip;
}
function hostTip() {
try {
var n = mount, guard = 0;
while (n && guard++ < 8) {
if (n.__lchHostTip && typeof n.__lchHostTip.show === 'function') return n.__lchHostTip;
n = n.parentNode;
}
} catch (e) { /* detached node / cross-document parent */ }
return null;
}
function metrics() {
var w = 0, h = 0, cw = 0, ch = 0;
try {
var r = mount.getBoundingClientRect();
cw = r.width; ch = r.height;
} catch (e) { /* fall through to the client* fallbacks */ }
if (!cw) cw = mount.clientWidth || 0;
if (!ch) ch = mount.clientHeight || 0;
w = tip.offsetWidth || 0;
h = tip.offsetHeight || 0;
return { w: w, h: h, cw: cw, ch: ch };
}
function local(ev) {
var x = 0, y = 0;
try {
var r = mount.getBoundingClientRect();
if (ev && ev.clientX != null) { x = ev.clientX - r.left; y = ev.clientY - r.top; }
} catch (e) {
if (ev && ev.clientX != null) { x = ev.clientX; y = ev.clientY; }
}
return { x: x, y: y };
}
function place(ev) {
var m = metrics();
if (!m.cw || !m.ch) return; // no layout to clamp against (exec gate)
var p = local(ev);
var left = p.x + gap;
if (left + m.w > m.cw - edge) left = p.x - gap - m.w;
if (left < edge) left = edge;
if (left + m.w > m.cw - edge) left = Math.max(edge, m.cw - m.w - edge);
var top = p.y + gap;
if (top + m.h > m.ch - edge) top = p.y - gap - m.h;
if (top < edge) top = edge;
if (top + m.h > m.ch - edge) top = Math.max(edge, m.ch - m.h - edge);
tip.style.left = Math.round(left) + 'px';
tip.style.top = Math.round(top) + 'px';
}
function looksLikeEvent(x) {
return !!x && typeof x === 'object' && !Array.isArray(x)
&& (typeof x.clientX === 'number' || typeof x.type === 'string' || ('target' in x));
}
function setContent(content, asText) {
if (Array.isArray(content)) content = content.map(function (x) { return x == null ? '' : String(x); }).join(asText ? ' ' : '<br/>');
lastContent = content == null ? '' : String(content);
if (!asText && typeof content === 'string' && content.indexOf('<') >= 0) tip.innerHTML = lastContent;
else tip.textContent = lastContent;
}
function setAndRefit(self, content, asText) {
setContent(content, asText);
if (routed) {
var hbSet = hostTip();
if (hbSet && hbSet.show(lastContent, lastEv) === true) return self;
routed = false; // the host let go: the tooltip is still on screen, so draw ours
return self.show(null, lastEv);
}
if (tip.style.visibility === 'visible') return self.show(null, lastEv);
return self;
}
return {
node: tip,
html: function (content) { return arguments.length ? setAndRefit(this, content, false) : lastContent; },
text: function (content) { return arguments.length ? setAndRefit(this, content, true) : (tip.textContent || ''); },
show: function (content, ev) {
if (looksLikeEvent(content) && !looksLikeEvent(ev)) { var swapped = content; content = ev; ev = swapped; }
if (ev) lastEv = ev;
if (content != null) setContent(content, false);
tip.style.maxWidth = 'none';
tip.style.visibility = 'visible'; // measurable BEFORE placing
var m = metrics();
if (m.ch && m.h + (2 * edge) > m.ch) {
var hbShow = hostTip();
if (hbShow && hbShow.show(lastContent, ev) === true) {
routed = true;
tip.style.visibility = 'hidden';
return this;
}
}
routed = false;
if (m.cw) tip.style.maxWidth = Math.max(80, m.cw - (2 * edge)) + 'px';
place(ev);
return this;
},
move: function (ev) {
if (ev) lastEv = ev;
if (routed) { var hbMove = hostTip(); if (hbMove) hbMove.move(ev); return this; }
if (tip.style.visibility === 'visible') place(ev);
return this;
},
hide: function () {
if (routed) { var hbHide = hostTip(); if (hbHide) hbHide.hide(); routed = false; }
tip.style.visibility = 'hidden';
return this;
}
};
};
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();
};
d3.llmThemeColors = function (options) {
options = options || {};
var pick = function (v, d) { return (typeof v === 'string' && v && v !== 'transparent') ? v : d; };
var bg = pick(options.backgroundColor, pick(options.themeBg, '#ffffff'));
var fg = pick(options.themeFg, '#252423');
var hc = !!options.isHighContrast;
var pal = (options.palette && options.palette.length) ? options.palette.slice() : ['#4C78A8', '#F58518', '#54A24B', '#E45756', '#72B7B2', '#B279A2', '#FF9DA6', '#9D755D'];
var rgb = function (c) { var x = null; try { x = d3.rgb(c); } catch (e) { x = null; } return x && isFinite(x.r) ? x : d3.rgb(128, 128, 128); };
var lum = function (c) {
var r = rgb(c);
var f = function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r.r) + 0.7152 * f(r.g) + 0.0722 * f(r.b);
};
var contrast = function (a, b) { var x = lum(a) + 0.05, y = lum(b) + 0.05; return x > y ? x / y : y / x; };
var legible = function (col, floor) {
floor = floor || 3;
var c = d3.lab(rgb(col));
var step = lum(bg) > 0.5 ? -3 : 3; // a light background darkens the hue, a dark one lightens it
for (var i = 0; i < 34 && contrast(c.formatHex(), bg) < floor; i++) c.l = Math.max(0, Math.min(100, c.l + step));
return c.formatHex();
};
var good = hc ? pick(options.themeAccent, fg) : legible('#2e7d32');
var bad = hc ? fg : legible('#c62828');
var slot = function (value, n) {
var h = 2166136261, text = String(value);
for (var i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h % n;
};
var deltaE2000 = function (x, y) {
var rad = Math.PI / 180, L1 = x.l, a1 = x.a, b1 = x.b, L2 = y.l, a2 = y.a, b2 = y.b;
var C1 = Math.sqrt(a1 * a1 + b1 * b1), C2 = Math.sqrt(a2 * a2 + b2 * b2), Cm = (C1 + C2) / 2;
var G = 0.5 * (1 - Math.sqrt(Math.pow(Cm, 7) / (Math.pow(Cm, 7) + Math.pow(25, 7))));
var a1p = (1 + G) * a1, a2p = (1 + G) * a2;
var C1p = Math.sqrt(a1p * a1p + b1 * b1), C2p = Math.sqrt(a2p * a2p + b2 * b2);
var hp = function (bb, ap) { if (bb === 0 && ap === 0) return 0; var hh = Math.atan2(bb, ap) / rad; return hh < 0 ? hh + 360 : hh; };
var h1p = hp(b1, a1p), h2p = hp(b2, a2p);
var dLp = L2 - L1, dCp = C2p - C1p, dhp = 0;
if (C1p * C2p !== 0) { dhp = h2p - h1p; if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360; }
var dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhp * rad / 2);
var Lm = (L1 + L2) / 2, Cmp = (C1p + C2p) / 2, hm = h1p + h2p;
if (C1p * C2p !== 0) { if (Math.abs(h1p - h2p) > 180) hm += (hm < 360 ? 360 : -360); hm /= 2; }
var T = 1 - 0.17 * Math.cos((hm - 30) * rad) + 0.24 * Math.cos(2 * hm * rad) + 0.32 * Math.cos((3 * hm + 6) * rad) - 0.2 * Math.cos((4 * hm - 63) * rad);
var dTh = 30 * Math.exp(-Math.pow((hm - 275) / 25, 2));
var Rc = 2 * Math.sqrt(Math.pow(Cmp, 7) / (Math.pow(Cmp, 7) + Math.pow(25, 7)));
var Sl = 1 + 0.015 * Math.pow(Lm - 50, 2) / Math.sqrt(20 + Math.pow(Lm - 50, 2)), Sc = 1 + 0.045 * Cmp, Sh = 1 + 0.015 * Cmp * T;
var Rt = -Math.sin(2 * dTh * rad) * Rc;
var tl = dLp / Sl, tc = dCp / Sc, th = dHp / Sh;
return Math.sqrt(tl * tl + tc * tc + th * th + Rt * tc * th);
};
var order = null, pool = null, near = null;
var growOrder = function (count) {
if (!order) {
order = pal.map(function (c) { return rgb(c).formatHex(); });
var taken = order.map(function (c) { return d3.lab(c); });
var seenHex = {};
order.forEach(function (c) { seenHex[c] = 1; });
pool = [];
pal.forEach(function (c) {
var h = d3.hcl(rgb(c));
if (!isFinite(h.h)) h.h = 0;
var chroma = Math.max(isFinite(h.c) ? h.c : 0, 35);
[h.l, 38, 52, 66].forEach(function (L) {
for (var k = 1; k < 18; k++) {
var cc = d3.hcl((h.h + k * 20) % 360, chroma, L);
while (!cc.displayable() && cc.c > 20) cc.c -= 5;
if (!cc.displayable()) continue;
var hl = d3.hsl(cc).l;
if (!(hl > 0.15 && hl < 0.85)) continue;
var hx = cc.formatHex();
if (seenHex[hx]) continue;
seenHex[hx] = 1;
pool.push({ hex: hx, lab: d3.lab(hx) });
}
});
});
near = pool.map(function (q) {
var m = Infinity;
for (var t = 0; t < taken.length; t++) m = Math.min(m, deltaE2000(q.lab, taken[t]));
return m;
});
}
while (order.length < count && pool.length) {
var best = 0;
for (var q = 1; q < pool.length; q++) if (near[q] > near[best]) best = q;
var picked = pool.splice(best, 1)[0];
near.splice(best, 1);
order.push(picked.hex);
for (var r2 = 0; r2 < pool.length; r2++) near[r2] = Math.min(near[r2], deltaE2000(pool[r2].lab, picked.lab));
}
for (var round = 1; order.length < count && round < 40; round++) {
for (var e = 0; e < pal.length && order.length < count; e++) {
var hc = d3.hsl(pal[e]);
if (!isFinite(hc.h)) hc.h = 0;
var step = Math.ceil(round / 2) * 0.12 * (round % 2 ? 1 : -1);
hc.l = Math.max(0.12, Math.min(0.88, hc.l + step));
hc.h = (hc.h + round * 7) % 360;
var cx = hc.formatHex();
if (order.indexOf(cx) < 0) order.push(cx);
}
}
};
var extended = function (count) {
if (pal.length >= count) return pal.slice();
growOrder(count);
return pal.slice().concat(order.slice(pal.length, count));
};
var memory = function () {
var m = d3.__lchCategorySlots;
if (!m || !Array.isArray(m.groups)) { m = { groups: [] }; try { d3.__lchCategorySlots = m; } catch (e) { /* a frozen d3: no memory */ } }
return m;
};
var categories = function (values) {
var seen = {}, list = [];
(values || []).forEach(function (v) { var k = v === null || v === undefined ? '' : String(v); if (!seen[k]) { seen[k] = 1; list.push(k); } });
list.sort();
var mem = memory(), group = null, best = 0;
mem.groups.forEach(function (g) {
var shared = 0;
list.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(g.slots, k)) shared++; });
if (shared > best) { best = shared; group = g; }
});
if (!group) {
group = { slots: {}, used: {}, size: 0 };
mem.groups.push(group);
if (mem.groups.length > 32) mem.groups.shift();
}
var fresh = list.filter(function (k) { return !Object.prototype.hasOwnProperty.call(group.slots, k); });
var total = group.size + fresh.length;
var cols = extended(Math.max(list.length, total));
var n = cols.length;
fresh.forEach(function (k) {
if (group.size >= 2000) return; // a category this long is not a palette's job: past it, a value is placed but not remembered
var i = 0;
while (group.used[i] && i < n) i++;
group.used[i] = 1;
group.slots[k] = i;
group.size++;
});
var map = {};
list.forEach(function (k) {
var i = Object.prototype.hasOwnProperty.call(group.slots, k) ? group.slots[k] : slot(k, n);
if (i >= cols.length) cols = extended(i + 1);
map[k] = cols[i % cols.length];
});
return function (v) {
var k = v === null || v === undefined ? '' : String(v);
return map[k] || cols[slot(k, n)];
};
};
return { bg: bg, fg: fg, good: good, bad: bad, categories: categories, legible: function (c) { return legible(c); }, contrast: contrast, palette: pal };
};
function render(container, data, options) {
const TYPE_FLOOR = 10;
const W = options.width, H = options.height;
const FS = Math.max(TYPE_FLOOR, Math.min(13, Math.min(W, H) / 45));
const CAP_FS = Math.max(TYPE_FLOOR, FS * 0.9);
const fg = options.themeFg || '#252423';
const bg = options.themeBg || '#ffffff';
const loc = options.cultureCode || 'en-US';
const nf = new Intl.NumberFormat(loc, { maximumFractionDigits: 1, notation: 'compact' });
const nfFull = new Intl.NumberFormat(loc, { maximumFractionDigits: 2 });
const pct = new Intl.NumberFormat(loc, { style: 'percent', maximumFractionDigits: 0 });
const collator = new Intl.Collator(loc, { numeric: true });
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
function stop(reason) {
container.replaceChildren();
const t = d3.select(container).append('svg').attr('width', W).attr('height', H)
.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle')
.attr('font-size', FS).attr('fill', fg);
d3.llmFitLabel(t, W - 12, { pad: 0,
text: reason || (typeof options.noDataText === 'string' && options.noDataText) || 'No data to display' });
}
const { columns, rows } = data;
const QUANT = d3.llmValueColumn(columns, rows, {}).measures;
const ciRow = columns.findIndex(c => c.name === '__rowIdx__');
const cats = [];
let ciVal = -1;
columns.forEach((c, i) => {
if (c.name === '__rowIdx__' || c.name.indexOf('__geo') === 0) return;
if (c.isMeasure) { if (ciVal < 0 && QUANT.indexOf(i) >= 0) ciVal = i; } else cats.push(i);
});
if (cats.length < 2) {
throw new Error('INVALID:Chord diagram needs two category fields - the two ends of each link, such as from and to - bind a second category, or use a bar chart for one.');
}
const FROM_WORDS = ['from', 'source', 'src', 'origin', 'initial', 'start', 'begin', 'before', 'prior', 'previous', 'prev', 'old', 'original', 'sender', 'departure', 'pickup'];
const TO_WORDS = ['to', 'target', 'tgt', 'dest', 'destination', 'current', 'end', 'final', 'after', 'next', 'new', 'latest', 'receiver', 'recipient', 'arrival', 'dropoff'];
const endOf = name => {
const words = String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/);
const f = words.some(w => FROM_WORDS.indexOf(w) >= 0), t = words.some(w => TO_WORDS.indexOf(w) >= 0);
return f === t ? 0 : (f ? -1 : 1);
};
let ciA = cats[0], ciB = cats[1];
if (endOf(d3.llmDisplayName(columns[ciA].name)) > endOf(d3.llmDisplayName(columns[ciB].name))) { const s = ciA; ciA = ciB; ciB = s; }
const nameA = d3.llmDisplayName(columns[ciA].name), nameB = d3.llmDisplayName(columns[ciB].name);
const labelOf = v => (v === null || v === undefined || v === '') ? '(blank)' : String(v);
const rowId = (r, i) => ciRow >= 0 ? r[ciRow] : i;
const raw = new Map(), totA = new Map(), totB = new Map();
const seen = new Map();
let negative = false;
rows.forEach((r, i) => {
const a0 = labelOf(r[ciA]), b0 = labelOf(r[ciB]);
if (!seen.has(a0)) seen.set(a0, seen.size);
if (!seen.has(b0)) seen.set(b0, seen.size);
const rawV = ciVal >= 0 ? r[ciVal] : 1;
if (rawV === null || rawV === undefined || rawV === '') return;
const v = +rawV;
if (!isFinite(v)) return;
if (v < 0) { negative = true; return; }
const key = JSON.stringify([a0, b0]);
let p = raw.get(key);
if (!p) { p = { a: a0, b: b0, v: 0, ids: [] }; raw.set(key, p); }
p.v += v;
p.ids.push(rowId(r, i));
totA.set(a0, (totA.get(a0) || 0) + v);
totB.set(b0, (totB.get(b0) || 0) + v);
});
if (negative) {
stop('Chord diagram cannot draw a negative flow - a ribbon is a width. Filter out the negative rows, or use a bar chart that can show values below zero.');
return;
}
let common = 0;
totA.forEach((v, nm) => { if (totB.has(nm)) common++; });
const DIRECTED = common >= 2 && common >= 0.5 * Math.min(totA.size, totB.size);
const byName = (x, y) => collator.compare(x, y) || (x < y ? -1 : (x > y ? 1 : 0));
const others = new Set();
function fold(tot, cap) {
const names = Array.from(tot.keys()), to = new Map(names.map(nm => [nm, nm]));
if (names.length > cap) {
const keep = new Set(names.slice().sort((x, y) => (tot.get(y) - tot.get(x)) || byName(x, y)).slice(0, cap - 1));
const other = 'Other (' + (names.length - cap + 1) + ')';
others.add(other);
names.forEach(nm => { if (!keep.has(nm)) to.set(nm, other); });
}
return to;
}
let mapA, mapB;
if (DIRECTED) {
const both = new Map(totA);
totB.forEach((v, nm) => both.set(nm, (both.get(nm) || 0) + v));
mapA = mapB = fold(both, 30);
} else {
mapA = fold(totA, 15);
mapB = fold(totB, 15);
}
// Process order = first appearance in the rows; 'Other' last.
const seenAt = x => seen.has(x) ? seen.get(x) : 1e9;
const order = (x, y) => (others.has(x) - others.has(y)) || (seenAt(x) - seenAt(y)) || byName(x, y);
const namesOf = m => Array.from(new Set(m.values())).sort(order);
const groups = DIRECTED
? namesOf(mapA).map(nm => ({ name: nm, side: 0 }))
: namesOf(mapA).map(nm => ({ name: nm, side: 0 })).concat(namesOf(mapB).map(nm => ({ name: nm, side: 1 })));
const n = groups.length;
const keyOf = (side, nm) => (DIRECTED ? '' : side + ':') + nm;
const gIndex = new Map(groups.map((g, i) => [keyOf(g.side, g.name), i]));
const M = groups.map(() => new Array(n).fill(0));
const cell = groups.map(() => groups.map(() => []));
const stay = new Array(n).fill(0), stayIds = groups.map(() => []);
let grand = 0;
raw.forEach(p => {
const i = gIndex.get(keyOf(0, mapA.get(p.a))), j = gIndex.get(keyOf(1, mapB.get(p.b)));
grand += p.v;
const ids = i === j ? stayIds[i] : cell[i][j];
p.ids.forEach(id => ids.push(id));
if (i === j) stay[i] += p.v;
else { M[i][j] += p.v; if (!DIRECTED) M[j][i] += p.v; }
});
if (!(grand > 0)) {
stop(rows.length ? 'Chord diagram has nothing to size: every flow in this view is zero.' : '');
return;
}
container.replaceChildren();
const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
const padAngle = Math.min(0.04, Math.PI * 0.3 / n);
const layout = (DIRECTED ? d3.chordDirected() : d3.chord()).padAngle(padAngle).sortSubgroups(d3.descending);
const chords = layout(M);
const span = Math.max(0, 2 * Math.PI - padAngle * n);
const moveSum = d3.sum(chords.groups, g => g.value);
const k = moveSum > 0 ? span / moveSum : 0;
const K = span / (moveSum + d3.sum(stay));
const gv = chords.groups.map((g, i) => g.value + stay[i]);
const arcs = [];
let at = 0, d3At = 0;
groups.forEach((g, i) => {
const mv = chords.groups[i].value;
arcs.push({ i: i, a0: at, split: at + mv * K, a1: at + gv[i] * K, old0: d3At });
at += gv[i] * K + padAngle;
d3At += mv * k + padAngle;
});
const ratio = k > 0 ? K / k : 0;
const remap = e => ({ index: e.index, value: e.value,
startAngle: arcs[e.index].a0 + (e.startAngle - arcs[e.index].old0) * ratio,
endAngle: arcs[e.index].a0 + (e.endAngle - arcs[e.index].old0) * ratio });
const links = chords.map(c => ({ source: remap(c.source), target: remap(c.target) }));
const mid = arcs.map(a => (a.a0 + a.a1) / 2);
const PAD = Math.max(4, FS * 0.4), GAP = FS * 0.6, LH = FS * 1.2;
const capH = CAP_FS * 1.6;
const probe = svg.append('text').attr('font-size', FS).style('visibility', 'hidden');
function textW(s) {
probe.text(s);
let w = 0;
try { w = probe.node().getComputedTextLength(); } catch (e) { w = 0; }
return w > 0 ? w : String(s).length * FS * 0.6;
}
const forms = groups.map((g, i) => {
const f = [g.name + ' ' + nf.format(gv[i]), g.name];
if (stay[i] > 0) f.unshift(g.name + ' ' + nf.format(gv[i]) + ' (' + nf.format(stay[i]) + ' unchanged)');
return f.map(s => ({ s: s, w: textW(s) }));
});
function corners(mode, a, w) {
const ux = Math.sin(a), uy = -Math.cos(a);
if (mode === 'radial') {
const vx = -uy, vy = ux, out = [];
[GAP, GAP + w].forEach(t => [-LH / 2, LH / 2].forEach(s => out.push({ dx: ux, dy: uy, ox: t * ux + s * vx, oy: t * uy + s * vy })));
return out;
}
if (Math.abs(ux) < 0.2) {
const dy = uy < 0 ? -1 : 1;
return [[-w / 2, GAP], [w / 2, GAP], [-w / 2, GAP + LH], [w / 2, GAP + LH]]
.map(c => ({ dx: ux, dy: dy, ox: GAP * ux + c[0], oy: dy * c[1] }));
}
const x0 = ux > 0 ? 0 : -w, x1 = ux > 0 ? w : 0;
return [[x0, -LH / 2], [x1, -LH / 2], [x0, LH / 2], [x1, LH / 2]]
.map(c => ({ dx: ux, dy: uy, ox: GAP * ux + c[0], oy: GAP * uy + c[1] }));
}
function limitR(cn, cx, cy, top, bottom) {
let r = Infinity;
const axis = (c, d, o, lo, hi) => {
if (d > 1e-9) r = Math.min(r, (hi - c - o) / d);
else if (d < -1e-9) r = Math.min(r, (lo - c - o) / d);
else if (c + o < lo || c + o > hi) r = -Infinity;
};
axis(cx, cn.dx, cn.ox, PAD, W - PAD);
axis(cy, cn.dy, cn.oy, top, bottom);
return r;
}
function boxOf(mode, L, R, cx, cy) {
const cs = corners(mode, mid[L.i], forms[L.i][L.f].w).map(cn => [cx + R * cn.dx + cn.ox, cy + R * cn.dy + cn.oy]);
return { a: mid[L.i], x0: d3.min(cs, c => c[0]), x1: d3.max(cs, c => c[0]), y0: d3.min(cs, c => c[1]), y1: d3.max(cs, c => c[1]) };
}
function clash(mode, p, q, R) {
if (mode === 'radial') {
const da = Math.abs(p.a - q.a), gap = Math.min(da, 2 * Math.PI - da) * (R + GAP);
return gap < LH;
}
return p.x0 < q.x1 - 1 && q.x0 < p.x1 - 1 && p.y0 < q.y1 - 1 && q.y0 < p.y1 - 1;
}
function place(mode, top, bottom) {
const cx = W / 2, cy = (top + bottom) / 2;
const cap = Math.max(FS, Math.min(cx - PAD, cy - top));
const floorR = Math.min(cap, Math.max(FS * 3, cap * 0.45)), goodR = Math.max(floorR, cap * 0.7);
const lab = groups.map((g, i) => ({ i: i, f: 0, lim: 0, box: null }));
const limitOf = L => L.f >= forms[L.i].length ? Infinity
: d3.min(corners(mode, mid[L.i], forms[L.i][L.f].w), cn => limitR(cn, cx, cy, top, bottom));
let R = cap;
for (let guard = 0; guard <= 4 * n; guard++) {
let worst = null;
lab.forEach(L => { L.lim = limitOf(L); if (!worst || L.lim < worst.lim) worst = L; });
R = Math.min(cap, worst.lim);
const nameOnly = forms[worst.i].length - 1;
if (R >= goodR || worst.f > nameOnly) break;
if (worst.f === nameOnly && R >= floorR) break;
worst.f++;
}
R = Math.max(R, Math.min(cap, floorR));
const kept = [];
lab.filter(L => L.f < forms[L.i].length)
.sort((p, q) => (gv[q.i] - gv[p.i]) || (p.i - q.i))
.forEach(L => {
for (; L.f < forms[L.i].length; L.f++) {
if (limitOf(L) < R - 0.5) continue;
const box = boxOf(mode, L, R, cx, cy);
if (!kept.some(o => clash(mode, box, o.box, R))) { L.box = box; kept.push(L); break; }
if (mode === 'radial') { L.f = forms[L.i].length; break; }
}
});
const whole = d3.sum(kept, L => forms[L.i].length - L.f);
return { mode: mode, R: R, cx: cx, cy: cy, bottom: bottom, lab: lab,
dropped: lab.filter(L => !L.box).map(L => L.i),
score: kept.length * 1e7 + Math.round(R) * 1e3 + whole };
}
const SW = FS * 0.8, ROW_H = FS * 1.5;
function legendLayout(list, maxH) {
const room = W - 2 * PAD, nameRoom = room - SW - FS * 0.4;
const rowsMax = Math.max(1, Math.floor(maxH / ROW_H));
const items = [];
let xx = 0, row = 0;
for (const i of list) {
const tw = Math.min(textW(groups[i].name), nameRoom), iw = SW + FS * 0.4 + tw;
if (xx > 0 && xx + iw > room) { xx = 0; row++; }
if (row >= rowsMax) break;
items.push({ i: i, x: PAD + xx, row: row, tw: tw, iw: iw });
xx += iw + FS;
}
return { items: items, more: list.length - items.length, rows: items.length ? items[items.length - 1].row + 1 : 0 };
}
let legH = 0, lay = null;
for (let pass = 0; pass < 3; pass++) {
const bottom = H - PAD - capH - legH;
const flat = place('flat', PAD, bottom), radial = place('radial', PAD, bottom);
lay = radial.score > flat.score ? radial : flat;
const need = lay.dropped.length ? legendLayout(lay.dropped, H * 0.25).rows * ROW_H + FS * 0.3 : 0;
if (need <= legH) break;
legH = need;
}
const R = lay.R, cx = lay.cx, cy = lay.cy;
const ringW = Math.max(FS * 0.6, Math.min(FS * 1.4, R * 0.08));
const innerR = Math.max(R * 0.5, R - ringW);
const T = d3.llmThemeColors(options);
const neutral = d3.interpolateRgb(bg, fg)(0.45);
const groupColour = T.categories(groups.filter(g => DIRECTED || g.side === 0).map(g => g.name));
const colour = i => (DIRECTED || groups[i].side === 0) ? T.legible(groupColour(groups[i].name)) : neutral;
const tip = options.allowTooltips === false ? null : d3.llmTooltip(container);
const hover = (sel, html) => sel
.on('mouseover', function (e, d) { if (tip) tip.show(html(d), e); })
.on('mousemove', function (e) { if (tip) tip.move(e); })
.on('mouseout', function () { if (tip) tip.hide(); });
const nameOf = i => esc(groups[i].name);
const share = v => nfFull.format(v) + ' (' + pct.format(v / grand) + ')';
const allRows = i => {
const ids = stayIds[i].slice();
for (let j = 0; j < n; j++) {
cell[i][j].forEach(id => ids.push(id));
if (j !== i) cell[j][i].forEach(id => ids.push(id));
}
return ids;
};
const moveRows = i => {
const ids = [];
for (let j = 0; j < n; j++) {
cell[i][j].forEach(id => ids.push(id));
if (j !== i) cell[j][i].forEach(id => ids.push(id));
}
return ids.join(',');
};
const ring = svg.append('g').attr('transform', 'translate(' + cx + ',' + cy + ')');
const ribbon = (DIRECTED ? d3.ribbonArrow().headRadius(Math.max(FS * 0.6, Math.min(FS * 4, innerR * 0.2))) : d3.ribbon())
.radius(innerR - 1).padAngle(1 / innerR);
ring.append('g').attr('class', 'lch-ribbons').selectAll('path').data(links).join('path')
.attr('class', 'd3-mark')
.attr('data-row-idx', d => {
const s = d.source.index, t = d.target.index;
return (DIRECTED ? cell[s][t] : cell[Math.min(s, t)][Math.max(s, t)]).join(',');
})
.attr('d', ribbon)
.attr('fill', d => colour(d.source.index)).attr('fill-opacity', 0.72)
.attr('stroke', bg).attr('stroke-width', 0.5)
.style('cursor', 'pointer')
.call(hover, d => {
const s = d.source.index, t = d.target.index;
if (!DIRECTED) {
return esc(nameA) + ': <b>' + nameOf(s) + '</b><br>' + esc(nameB) + ': <b>' + nameOf(t) + '</b><br>' + share(d.source.value);
}
return '<b>' + nameOf(s) + ' → ' + nameOf(t) + '</b><br>' + share(d.source.value)
+ (M[t][s] > 0 ? '<br>' + nameOf(t) + ' → ' + nameOf(s) + ': ' + nfFull.format(M[t][s]) : '');
});
const arcGen = d3.arc().innerRadius(innerR).outerRadius(R);
ring.append('g').attr('class', 'lch-arcs').selectAll('path').data(arcs.filter(a => a.split > a.a0 + 1e-9)).join('path')
.attr('class', 'd3-mark')
.attr('data-row-idx', a => moveRows(a.i))
.attr('d', a => arcGen({ startAngle: a.a0, endAngle: a.split }))
.attr('fill', a => colour(a.i)).attr('stroke', bg).attr('stroke-width', 0.5)
.style('cursor', 'pointer')
.call(hover, a => {
const i = a.i;
if (!DIRECTED) return esc(groups[i].side === 0 ? nameA : nameB) + ': <b>' + nameOf(i) + '</b><br>' + share(gv[i]);
const out = d3.sum(M[i]), inn = d3.sum(M, r => r[i]);
return '<b>' + nameOf(i) + '</b><br>moved out ' + nfFull.format(out) + '<br>moved in ' + nfFull.format(inn)
+ (stay[i] > 0 ? '<br>unchanged ' + nfFull.format(stay[i]) : '');
});
ring.append('g').attr('class', 'lch-unchanged').selectAll('path').data(arcs.filter(a => stay[a.i] > 0)).join('path')
.attr('class', 'd3-mark')
.attr('data-row-idx', a => stayIds[a.i].join(','))
.attr('d', a => arcGen({ startAngle: a.split, endAngle: a.a1 }))
.attr('fill', a => colour(a.i)).attr('fill-opacity', 0.3)
.attr('stroke', a => colour(a.i)).attr('stroke-width', 1)
.style('cursor', 'pointer')
.call(hover, a => '<b>' + nameOf(a.i) + '</b><br>unchanged ' + share(stay[a.i])
+ (others.has(groups[a.i].name) ? '<br>or moved within it' : ''));
probe.remove();
function reach(px, py, ux, uy) {
let t = Infinity;
if (ux > 1e-9) t = Math.min(t, (W - PAD - px) / ux); else if (ux < -1e-9) t = Math.min(t, (PAD - px) / ux);
if (uy > 1e-9) t = Math.min(t, (lay.bottom - py) / uy); else if (uy < -1e-9) t = Math.min(t, (PAD - py) / uy);
return t;
}
const late = [];
const labels = svg.append('g').attr('class', 'lch-ring-labels');
lay.lab.filter(L => L.box).forEach(L => {
const a = mid[L.i], ux = Math.sin(a), uy = -Math.cos(a), rr = R + GAP;
const t = labels.append('text').attr('font-size', FS).attr('fill', fg).attr('dy', '0.35em')
.attr('class', 'd3-mark').attr('data-row-idx', allRows(L.i).join(','))
.style('cursor', 'pointer').style('pointer-events', 'all');
let room;
if (lay.mode === 'radial') {
const left = a > Math.PI, px = cx + rr * ux, py = cy + rr * uy;
t.attr('text-anchor', left ? 'end' : 'start')
.attr('transform', 'translate(' + cx + ',' + cy + ') rotate(' + (a * 180 / Math.PI - 90) + ') translate(' + rr + ',0)' + (left ? ' rotate(180)' : ''));
room = Math.min(reach(px - uy * LH / 2, py + ux * LH / 2, ux, uy), reach(px + uy * LH / 2, py - ux * LH / 2, ux, uy));
} else if (Math.abs(ux) < 0.2) {
const x = cx + GAP * ux + R * ux, dy = uy < 0 ? -1 : 1;
t.attr('text-anchor', 'middle').attr('x', x).attr('y', cy + dy * (rr + LH / 2));
room = 2 * Math.min(x - PAD, W - PAD - x);
} else {
const x = cx + rr * ux;
t.attr('text-anchor', ux > 0 ? 'start' : 'end').attr('x', x).attr('y', cy + rr * uy);
room = ux > 0 ? W - PAD - x : x - PAD;
}
for (let f = L.f; f < forms[L.i].length; f++) {
d3.llmFitLabel(t, room + 0.5, { pad: 0, text: forms[L.i][f].s, overflow: 'drop' });
if (t.text()) break;
}
if (!t.text()) late.push(L.i);
});
const lg = legendLayout(lay.dropped.concat(late), Math.max(0, legH - FS * 0.3));
const legend = svg.append('g').attr('class', 'lch-legend');
lg.items.forEach(it => {
const y = lay.bottom + FS * 0.3 + it.row * ROW_H, nm = groups[it.i].name;
const e = legend.append('g');
e.append('rect').attr('class', 'd3-legend-mark').attr('data-row-idx', allRows(it.i).join(','))
.attr('x', it.x).attr('y', y).attr('width', it.iw).attr('height', ROW_H)
.attr('fill', bg).attr('fill-opacity', 0).style('pointer-events', 'all').style('cursor', 'pointer');
e.append('rect').attr('x', it.x).attr('y', y + (ROW_H - SW) / 2).attr('width', SW).attr('height', SW).attr('fill', colour(it.i))
.style('pointer-events', 'none');
const tx = e.append('text').attr('x', it.x + SW + FS * 0.4).attr('y', y + ROW_H / 2).attr('dy', '0.35em')
.attr('font-size', FS).attr('fill', fg).style('pointer-events', 'none');
d3.llmFitLabel(tx, it.tw + 1, { pad: 0, text: nm });
if (tx.text() !== nm) e.append('title').text(nm);
});
if (lg.more > 0 && lg.items.length) {
const last = lg.items[lg.items.length - 1], x = last.x + last.iw + FS;
const more = legend.append('text').attr('x', x).attr('y', lay.bottom + FS * 0.3 + last.row * ROW_H + ROW_H / 2)
.attr('dy', '0.35em').attr('font-size', FS).attr('fill', fg);
d3.llmFitLabel(more, W - PAD - x, { pad: 0, text: '+' + lg.more + ' more on the ring', overflow: 'drop' });
}
const unit = ciVal < 0 ? 'row count'
: (/^(sum|total|count)([^a-z0-9_]|$)/i.test(d3.llmDisplayName(columns[ciVal].name)) ? d3.llmDisplayName(columns[ciVal].name) : d3.llmDisplayName(columns[ciVal].name) + ', summed');
const stayTotal = d3.sum(stay);
const unchanged = 'pale arcs are unchanged, ' + nfFull.format(stayTotal) + ' of ' + nfFull.format(grand);
const capForms = DIRECTED
? ['Arrows point from ' + nameA + ' to ' + nameB + ' - ' + unit + (stayTotal > 0 ? '; ' + unchanged : ''),
'From ' + nameA + ' to ' + nameB + (stayTotal > 0 ? '; ' + unchanged : ''),
stayTotal > 0 ? 'Pale ' + unchanged.slice(5) : 'From ' + nameA + ' to ' + nameB,
'From ' + nameA + ' to ' + nameB]
: ['Ribbons join ' + nameA + ' (colored arcs) and ' + nameB + ' (gray arcs) - ' + unit,
nameA + ' (colored) and ' + nameB + ' (gray)',
unit];
const cap = svg.append('text').attr('x', W / 2).attr('y', H - PAD - capH * 0.3).attr('text-anchor', 'middle')
.attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.8);
for (const form of capForms) {
d3.llmFitLabel(cap, W - 2 * PAD, { pad: 0, text: form, overflow: 'drop' });
if (cap.text()) break;
}
if (cap.text() !== capForms[0]) cap.append('title').text(capForms[0]);
}
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.