wiki-plugin-rcnspc 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +24 -2
- package/client/rcnspc.js +1110 -0
- package/factory.json +1 -0
- package/index.js +2 -0
- package/package.json +28 -4
- package/pages/about-rcnspc-plugin +233 -0
package/client/rcnspc.js
ADDED
|
@@ -0,0 +1,1110 @@
|
|
|
1
|
+
// wiki-plugin-rcnspc — an RCN process behavior chart on a Federated Wiki page.
|
|
2
|
+
//
|
|
3
|
+
// The item HOLDS the chart's session, the same thing the tool's "Save session as
|
|
4
|
+
// JSON" writes (format rcn-spc/1): the data (columns and rows), the chart
|
|
5
|
+
// settings, the flags and the change points with their notes. The page draws it.
|
|
6
|
+
// "✎ Edit in the tool" opens the full tool with this session; its "→ Save to
|
|
7
|
+
// wiki item" sends the session back into the item.
|
|
8
|
+
//
|
|
9
|
+
// The arithmetic and the drawing are the SAME file the tool uses,
|
|
10
|
+
// tools/rcn-spc-core.js, pasted below by build.js, and the chart styles are
|
|
11
|
+
// copied out of tools/rcn-spc.html by build.js. Edit those in the rcn repo,
|
|
12
|
+
// then run `node build.js` here. Never edit a pasted block.
|
|
13
|
+
//
|
|
14
|
+
// Marc Pierson with Claude Opus 5.5, December 2026. MIT licence.
|
|
15
|
+
(function () {
|
|
16
|
+
|
|
17
|
+
// BEGIN rcn-spc-core.js — pasted by build.js. Edit the source in the rcn repo, never this block.
|
|
18
|
+
/*
|
|
19
|
+
* rcn-spc-core.js — the arithmetic and the drawing of RCN Process Behavior Charts,
|
|
20
|
+
* with no page around them. One copy, pasted into two places:
|
|
21
|
+
* tools/rcn-spc.html by tools/paste-spc-core.js
|
|
22
|
+
* wiki-plugin-rcnspc/client/rcnspc.js by wiki-plugin-rcnspc/build.js
|
|
23
|
+
* so a chart on a wiki page is drawn by the same lines as the chart in the tool.
|
|
24
|
+
*
|
|
25
|
+
* RCNSPC.view(state) → HTML for the charts, verdicts and tables, where state is
|
|
26
|
+
* an rcn-spc/1 session ({data, settings, flags, changePoints, note}) plus
|
|
27
|
+
* noteTitle (heading over the note) and readOnly (no "click the chart" hints).
|
|
28
|
+
*
|
|
29
|
+
* Edit this file, never a pasted block. After editing: node tools/paste-spc-core.js
|
|
30
|
+
* and (cd wiki-plugin-rcnspc && node build.js).
|
|
31
|
+
*
|
|
32
|
+
* Marc Pierson with Claude Opus 5.5, December 2026. MIT licence.
|
|
33
|
+
*/
|
|
34
|
+
var RCNSPC = (function () {
|
|
35
|
+
"use strict";
|
|
36
|
+
|
|
37
|
+
/* ═══════════════════════════════════════════════════════════════════════
|
|
38
|
+
SPC — the math. Kept in one namespace so it can be checked against
|
|
39
|
+
Hart & Hart line by line. Nothing here touches the DOM.
|
|
40
|
+
═══════════════════════════════════════════════════════════════════════ */
|
|
41
|
+
const SPC = (() => {
|
|
42
|
+
|
|
43
|
+
// Shewhart constants, n = 2..10. d2 and d3 from the distribution of the
|
|
44
|
+
// relative range; c4 the unbiasing constant for the sample SD.
|
|
45
|
+
const D2 = {2:1.128,3:1.693,4:2.059,5:2.326,6:2.534,7:2.704,8:2.847,9:2.970,10:3.078};
|
|
46
|
+
const D3 = {2:0.853,3:0.888,4:0.880,5:0.864,6:0.848,7:0.833,8:0.820,9:0.808,10:0.797};
|
|
47
|
+
const C4 = {2:0.7979,3:0.8862,4:0.9213,5:0.9400,6:0.9515,7:0.9594,8:0.9650,9:0.9693,10:0.9727};
|
|
48
|
+
|
|
49
|
+
// Beyond the tabulated range c4 is well approximated by 4(n-1)/(4n-3).
|
|
50
|
+
const c4 = n => C4[n] !== undefined ? C4[n] : (4*(n-1))/(4*n-3);
|
|
51
|
+
const d2 = n => D2[n] !== undefined ? D2[n] : 3.472 - 0.0000000001; // only used n<=10
|
|
52
|
+
|
|
53
|
+
// XmR scaling constants. 3/d2(2) = 2.660 for average moving range;
|
|
54
|
+
// 3/0.954 = 3.145 for the median moving range (d4 = 0.954 at n = 2).
|
|
55
|
+
const XMR_AVG = 2.660, XMR_AVG_MR = 3.268;
|
|
56
|
+
const XMR_MED = 3.145, XMR_MED_MR = 3.865;
|
|
57
|
+
|
|
58
|
+
const mean = a => a.reduce((s,x)=>s+x,0)/a.length;
|
|
59
|
+
const median = a => { const s=[...a].sort((x,y)=>x-y), m=s.length>>1;
|
|
60
|
+
return s.length%2 ? s[m] : (s[m-1]+s[m])/2; };
|
|
61
|
+
const sd = a => { if(a.length<2) return 0; const m=mean(a);
|
|
62
|
+
return Math.sqrt(a.reduce((s,x)=>s+(x-m)*(x-m),0)/(a.length-1)); };
|
|
63
|
+
|
|
64
|
+
const movingRanges = a => a.slice(1).map((x,i)=>Math.abs(x-a[i]));
|
|
65
|
+
|
|
66
|
+
/* ── XmR / individuals ────────────────────────────────────────────────
|
|
67
|
+
Limits from the AVERAGE (or median) moving range — never from the
|
|
68
|
+
standard deviation of all the values. Using the global SD builds the
|
|
69
|
+
very signal you are trying to detect into the yardstick that is
|
|
70
|
+
supposed to detect it. This is the single most common error in
|
|
71
|
+
spreadsheet "control charts". */
|
|
72
|
+
function xmr(values, opts = {}) {
|
|
73
|
+
const useMedian = !!opts.medianMR;
|
|
74
|
+
const base = opts.baseline && opts.baseline > 1
|
|
75
|
+
? values.slice(0, Math.min(opts.baseline, values.length))
|
|
76
|
+
: values;
|
|
77
|
+
const mrBase = movingRanges(base);
|
|
78
|
+
const center = mean(base);
|
|
79
|
+
const mrBar = mrBase.length ? (useMedian ? median(mrBase) : mean(mrBase)) : 0;
|
|
80
|
+
const kX = useMedian ? XMR_MED : XMR_AVG;
|
|
81
|
+
const kMR = useMedian ? XMR_MED_MR : XMR_AVG_MR;
|
|
82
|
+
const sigma = mrBar / (useMedian ? 0.954 : D2[2]); // one sigma, within-process
|
|
83
|
+
return {
|
|
84
|
+
kind: 'xmr',
|
|
85
|
+
points: values,
|
|
86
|
+
cl: center, ucl: center + kX*mrBar, lcl: center - kX*mrBar,
|
|
87
|
+
sigma,
|
|
88
|
+
mr: { points: movingRanges(values), cl: mrBar, ucl: kMR*mrBar, lcl: 0 },
|
|
89
|
+
basedOn: base.length, mrBar, usedMedian: useMedian
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/* ── p chart ──────────────────────────────────────────────────────────
|
|
94
|
+
Centre line is the POOLED proportion, sum(d)/sum(n) — not the mean of
|
|
95
|
+
the individual proportions. Limits are computed per point because in
|
|
96
|
+
health care the denominator moves every period. */
|
|
97
|
+
function pChart(num, den, opts = {}) {
|
|
98
|
+
const nBase = opts.baseline && opts.baseline > 1 ? Math.min(opts.baseline, num.length) : num.length;
|
|
99
|
+
const sd_ = num.slice(0,nBase).reduce((s,x)=>s+x,0);
|
|
100
|
+
const sn_ = den.slice(0,nBase).reduce((s,x)=>s+x,0);
|
|
101
|
+
const pBar = sn_ > 0 ? sd_/sn_ : 0;
|
|
102
|
+
const pts = num.map((d,i) => den[i] > 0 ? d/den[i] : 0);
|
|
103
|
+
const sig = den.map(n => n > 0 ? Math.sqrt(pBar*(1-pBar)/n) : 0);
|
|
104
|
+
const sz = laneySigmaZ(pts, pBar, sig, nBase);
|
|
105
|
+
const k = opts.laney ? sz : 1;
|
|
106
|
+
return {
|
|
107
|
+
kind: 'p', points: pts, cl: pBar,
|
|
108
|
+
ucl: sig.map(s => Math.min(1, pBar + 3*k*s)),
|
|
109
|
+
lcl: sig.map(s => Math.max(0, pBar - 3*k*s)),
|
|
110
|
+
sigmaAt: sig.map(s => s*k), sigmaZ: sz, laney: !!opts.laney, pBar
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/* ── u chart ──────────────────────────────────────────────────────────
|
|
115
|
+
Same idea for counts over a varying area of opportunity. scale lets a
|
|
116
|
+
co-op read the axis in the units it actually talks in (per 1,000
|
|
117
|
+
member-months), without changing the limit arithmetic. */
|
|
118
|
+
function uChart(count, area, opts = {}) {
|
|
119
|
+
const scale = opts.scale || 1;
|
|
120
|
+
const nBase = opts.baseline && opts.baseline > 1 ? Math.min(opts.baseline, count.length) : count.length;
|
|
121
|
+
const sc_ = count.slice(0,nBase).reduce((s,x)=>s+x,0);
|
|
122
|
+
const sa_ = area.slice(0,nBase).reduce((s,x)=>s+x,0);
|
|
123
|
+
const uBar = sa_ > 0 ? sc_/sa_ : 0;
|
|
124
|
+
const pts = count.map((c,i) => area[i] > 0 ? c/area[i] : 0);
|
|
125
|
+
const sig = area.map(a => a > 0 ? Math.sqrt(uBar/a) : 0);
|
|
126
|
+
const sz = laneySigmaZ(pts, uBar, sig, nBase);
|
|
127
|
+
const k = opts.laney ? sz : 1;
|
|
128
|
+
return {
|
|
129
|
+
kind: 'u', points: pts.map(v=>v*scale), cl: uBar*scale,
|
|
130
|
+
ucl: sig.map(s => (uBar + 3*k*s)*scale),
|
|
131
|
+
lcl: sig.map(s => Math.max(0, uBar - 3*k*s)*scale),
|
|
132
|
+
sigmaAt: sig.map(s => s*k*scale), sigmaZ: sz, laney: !!opts.laney, scale, uBar
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/* ── Laney sigma-z ────────────────────────────────────────────────────
|
|
137
|
+
The overdispersion fix. Standardise every point against its own
|
|
138
|
+
binomial/Poisson sigma, then measure how much the standardised series
|
|
139
|
+
ACTUALLY moves using its average moving range. If the counts really are
|
|
140
|
+
binomial, sigma_z lands near 1 and nothing changes. If there is extra
|
|
141
|
+
between-period variation — which for large denominators there almost
|
|
142
|
+
always is — sigma_z exceeds 1 and the naive chart is throwing false
|
|
143
|
+
alarms on every point. */
|
|
144
|
+
function laneySigmaZ(pts, center, sig, nBase) {
|
|
145
|
+
const z = [];
|
|
146
|
+
for (let i = 0; i < (nBase || pts.length); i++) {
|
|
147
|
+
if (sig[i] > 0) z.push((pts[i] - center)/sig[i]);
|
|
148
|
+
}
|
|
149
|
+
if (z.length < 2) return 1;
|
|
150
|
+
const mr = movingRanges(z);
|
|
151
|
+
if (!mr.length) return 1;
|
|
152
|
+
return mean(mr)/D2[2];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/* ── Run chart ───────────────────────────────────────────────────────
|
|
156
|
+
Median centre line, no limits. Perla / Provost rules: shift of 6+ on
|
|
157
|
+
one side, trend of 5+ stepping the same direction, and too few or too
|
|
158
|
+
many runs for the number of useful observations. */
|
|
159
|
+
function runChart(values) {
|
|
160
|
+
const cl = median(values);
|
|
161
|
+
const signals = [];
|
|
162
|
+
const useful = values.filter(v => v !== cl);
|
|
163
|
+
const side = values.map(v => v > cl ? 1 : v < cl ? -1 : 0);
|
|
164
|
+
|
|
165
|
+
let start = -1, len = 0, cur = 0;
|
|
166
|
+
for (let i = 0; i <= side.length; i++) {
|
|
167
|
+
const s = side[i];
|
|
168
|
+
if (i < side.length && s !== 0 && s === cur) { len++; }
|
|
169
|
+
else {
|
|
170
|
+
if (len >= 6) signals.push({ i: start, span: len,
|
|
171
|
+
rule: 'Shift', text: `${len} consecutive points ${cur>0?'above':'below'} the median` });
|
|
172
|
+
if (i < side.length && s !== 0) { cur = s; start = i; len = 1; }
|
|
173
|
+
else { cur = 0; len = 0; }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let tStart = 0, dir = 0;
|
|
178
|
+
for (let i = 1; i < values.length; i++) {
|
|
179
|
+
const d = Math.sign(values[i] - values[i-1]);
|
|
180
|
+
if (d !== 0 && d === dir) {
|
|
181
|
+
if (i - tStart + 1 >= 5) signals.push({ i: tStart, span: i-tStart+1,
|
|
182
|
+
rule: 'Trend', text: `${i-tStart+1} points ${d>0?'rising':'falling'} in a row` });
|
|
183
|
+
} else { dir = d; tStart = i-1; }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let runs = 0, prev = 0;
|
|
187
|
+
side.forEach(s => { if (s !== 0 && s !== prev) { runs++; prev = s; } else if (s !== 0) prev = s; });
|
|
188
|
+
const nUse = useful.length;
|
|
189
|
+
if (nUse >= 10) {
|
|
190
|
+
const lo = Math.round(nUse/2 - 1.96*Math.sqrt(nUse-1)/2 + 1);
|
|
191
|
+
const hi = Math.round(nUse/2 + 1.96*Math.sqrt(nUse-1)/2 + 1);
|
|
192
|
+
if (runs < lo) signals.push({ i:0, span:values.length, rule:'Too few runs',
|
|
193
|
+
text: `${runs} runs where ${lo}–${hi} would be expected — the series is not behaving randomly` });
|
|
194
|
+
if (runs > hi) signals.push({ i:0, span:values.length, rule:'Too many runs',
|
|
195
|
+
text: `${runs} runs where ${lo}–${hi} would be expected — points are alternating more than chance allows` });
|
|
196
|
+
}
|
|
197
|
+
return { kind:'run', points: values, cl, signals, runs, nUseful: nUse };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/* ── Nelson rules 1–8 ────────────────────────────────────────────────
|
|
201
|
+
Rule 1 always applies. The rest are optional because each added rule
|
|
202
|
+
inflates the false-alarm rate: one rule gives roughly 1 in 370, all
|
|
203
|
+
eight running together give closer to 1 in 90. That is a real cost and
|
|
204
|
+
the tool states it rather than hiding it. */
|
|
205
|
+
function nelson(points, cl, sigmaAt, uclArr, lclArr, opts = {}) {
|
|
206
|
+
const n = points.length, out = [];
|
|
207
|
+
const S = i => Array.isArray(sigmaAt) ? sigmaAt[i] : sigmaAt;
|
|
208
|
+
const U = i => Array.isArray(uclArr) ? uclArr[i] : uclArr;
|
|
209
|
+
const L = i => Array.isArray(lclArr) ? lclArr[i] : lclArr;
|
|
210
|
+
const add = (i, rule, text) => out.push({ i, rule, text });
|
|
211
|
+
|
|
212
|
+
for (let i = 0; i < n; i++) {
|
|
213
|
+
if (points[i] > U(i)) add(i, 1, 'Above the upper limit');
|
|
214
|
+
else if (points[i] < L(i)) add(i, 1, 'Below the lower limit');
|
|
215
|
+
}
|
|
216
|
+
if (!opts.all) return out;
|
|
217
|
+
|
|
218
|
+
const dev = points.map((v,i) => S(i) > 0 ? (v - cl)/S(i) : 0);
|
|
219
|
+
const runOf = (test, len, rule, text) => {
|
|
220
|
+
let c = 0;
|
|
221
|
+
for (let i = 0; i < n; i++) {
|
|
222
|
+
if (test(i)) { c++; if (c >= len) add(i, rule, text); }
|
|
223
|
+
else c = 0;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const sameSideRun = (len, rule, text, pred) => {
|
|
227
|
+
for (const s of [1,-1]) runOf(i => Math.sign(dev[i]) === s && pred(Math.abs(dev[i])), len, rule, text);
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
sameSideRun(9, 2, 'Nine in a row on one side of the centre line', () => true);
|
|
231
|
+
// Rule 3: six steadily increasing or decreasing
|
|
232
|
+
for (const d of [1,-1]) {
|
|
233
|
+
let c = 1;
|
|
234
|
+
for (let i = 1; i < n; i++) {
|
|
235
|
+
if (Math.sign(points[i]-points[i-1]) === d) { c++; if (c >= 6) add(i, 3, 'Six points steadily ' + (d>0?'increasing':'decreasing')); }
|
|
236
|
+
else c = 1;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
// Rule 4: fourteen alternating up and down
|
|
240
|
+
{ let c = 1;
|
|
241
|
+
for (let i = 2; i < n; i++) {
|
|
242
|
+
const a = Math.sign(points[i-1]-points[i-2]), b = Math.sign(points[i]-points[i-1]);
|
|
243
|
+
if (a !== 0 && b !== 0 && a !== b) { c++; if (c >= 14) add(i, 4, 'Fourteen points alternating up and down'); }
|
|
244
|
+
else c = 1;
|
|
245
|
+
} }
|
|
246
|
+
const kOfM = (k, m, pred, rule, text) => {
|
|
247
|
+
for (let i = m-1; i < n; i++) {
|
|
248
|
+
let c = 0;
|
|
249
|
+
for (let j = i-m+1; j <= i; j++) if (pred(j)) c++;
|
|
250
|
+
if (c >= k) add(i, rule, text);
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
for (const s of [1,-1]) {
|
|
254
|
+
kOfM(2, 3, j => Math.sign(dev[j]) === s && Math.abs(dev[j]) > 2, 5, 'Two of three points beyond two sigma on the same side');
|
|
255
|
+
kOfM(4, 5, j => Math.sign(dev[j]) === s && Math.abs(dev[j]) > 1, 6, 'Four of five points beyond one sigma on the same side');
|
|
256
|
+
}
|
|
257
|
+
runOf(i => Math.abs(dev[i]) < 1, 15, 7, 'Fifteen points hugging the centre line — check for stratification');
|
|
258
|
+
runOf(i => Math.abs(dev[i]) > 1, 8, 8, 'Eight points in a row all beyond one sigma — check for a mixture');
|
|
259
|
+
|
|
260
|
+
const seen = new Set();
|
|
261
|
+
return out.filter(s => { const k = s.i+'|'+s.rule; if (seen.has(k)) return false; seen.add(k); return true; });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/* ── Rational subgrouping diagnostic ─────────────────────────────────
|
|
265
|
+
One-way decomposition of variance. This is the heart of the tool.
|
|
266
|
+
|
|
267
|
+
sigma_within — pooled within-subgroup SD. What the chart calls noise.
|
|
268
|
+
sigma_total — SD of every observation ignoring subgroups.
|
|
269
|
+
F, p — is the between-subgroup difference bigger than chance?
|
|
270
|
+
shareBetween — of the total variance, how much lives BETWEEN groups.
|
|
271
|
+
|
|
272
|
+
If shareBetween is large and you subgrouped by that column, you have
|
|
273
|
+
just declared the biggest thing in your data to be noise. */
|
|
274
|
+
function subgroupAnalysis(values, labels) {
|
|
275
|
+
const groups = new Map();
|
|
276
|
+
values.forEach((v,i) => {
|
|
277
|
+
const k = labels[i];
|
|
278
|
+
if (!groups.has(k)) groups.set(k, []);
|
|
279
|
+
groups.get(k).push(v);
|
|
280
|
+
});
|
|
281
|
+
const keys = [...groups.keys()];
|
|
282
|
+
const k = keys.length, N = values.length;
|
|
283
|
+
if (k < 2 || N - k < 1) return null;
|
|
284
|
+
|
|
285
|
+
const grand = mean(values);
|
|
286
|
+
let ssB = 0, ssW = 0;
|
|
287
|
+
const detail = keys.map(key => {
|
|
288
|
+
const g = groups.get(key), m = mean(g);
|
|
289
|
+
ssB += g.length * (m - grand)*(m - grand);
|
|
290
|
+
g.forEach(v => ssW += (v-m)*(v-m));
|
|
291
|
+
return { key, n: g.length, mean: m, sd: sd(g), min: Math.min(...g), max: Math.max(...g) };
|
|
292
|
+
});
|
|
293
|
+
const msB = ssB/(k-1), msW = ssW/(N-k);
|
|
294
|
+
const F = msW > 0 ? msB/msW : Infinity;
|
|
295
|
+
const p = msW > 0 ? 1 - fCDF(F, k-1, N-k) : 0;
|
|
296
|
+
|
|
297
|
+
// Expected value of MSB is sigma_within^2 + n0 * sigma_between^2
|
|
298
|
+
const n0 = (N - detail.reduce((s,d)=>s+d.n*d.n,0)/N)/(k-1);
|
|
299
|
+
const varBetween = Math.max(0, (msB - msW)/n0);
|
|
300
|
+
const varWithin = msW;
|
|
301
|
+
const share = varBetween + varWithin > 0 ? varBetween/(varBetween+varWithin) : 0;
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
k, N, detail: detail.sort((a,b)=>a.mean-b.mean),
|
|
305
|
+
sigmaWithin: Math.sqrt(msW), sigmaTotal: sd(values),
|
|
306
|
+
F, p, shareBetween: share, grand,
|
|
307
|
+
ratio: msW > 0 ? sd(values)/Math.sqrt(msW) : Infinity
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/* ── F distribution, via the regularised incomplete beta ─────────────
|
|
312
|
+
Gil is an engineer; a hand-waved "looks different" would not survive
|
|
313
|
+
contact with him. Continued-fraction evaluation, Lentz's method. */
|
|
314
|
+
function logGamma(x) {
|
|
315
|
+
const c = [76.18009172947146,-86.50532032941677,24.01409824083091,
|
|
316
|
+
-1.231739572450155,0.1208650973866179e-2,-0.5395239384953e-5];
|
|
317
|
+
let y = x, t = x + 5.5;
|
|
318
|
+
t -= (x+0.5)*Math.log(t);
|
|
319
|
+
let s = 1.000000000190015;
|
|
320
|
+
for (let j = 0; j < 6; j++) s += c[j]/++y;
|
|
321
|
+
return -t + Math.log(2.5066282746310005*s/x);
|
|
322
|
+
}
|
|
323
|
+
function betacf(a, b, x) {
|
|
324
|
+
const FPMIN = 1e-300, EPS = 3e-12;
|
|
325
|
+
const qab = a+b, qap = a+1, qam = a-1;
|
|
326
|
+
let c = 1, d = 1 - qab*x/qap;
|
|
327
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
328
|
+
d = 1/d;
|
|
329
|
+
let h = d;
|
|
330
|
+
for (let m = 1; m <= 300; m++) {
|
|
331
|
+
const m2 = 2*m;
|
|
332
|
+
let aa = m*(b-m)*x/((qam+m2)*(a+m2));
|
|
333
|
+
d = 1 + aa*d; if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
334
|
+
c = 1 + aa/c; if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
335
|
+
d = 1/d; h *= d*c;
|
|
336
|
+
aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
|
|
337
|
+
d = 1 + aa*d; if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
338
|
+
c = 1 + aa/c; if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
339
|
+
d = 1/d;
|
|
340
|
+
const del = d*c; h *= del;
|
|
341
|
+
if (Math.abs(del-1) < EPS) break;
|
|
342
|
+
}
|
|
343
|
+
return h;
|
|
344
|
+
}
|
|
345
|
+
function betai(a, b, x) {
|
|
346
|
+
if (x <= 0) return 0;
|
|
347
|
+
if (x >= 1) return 1;
|
|
348
|
+
const bt = Math.exp(logGamma(a+b) - logGamma(a) - logGamma(b) + a*Math.log(x) + b*Math.log(1-x));
|
|
349
|
+
return x < (a+1)/(a+b+2) ? bt*betacf(a,b,x)/a : 1 - bt*betacf(b,a,1-x)/b;
|
|
350
|
+
}
|
|
351
|
+
function fCDF(f, d1, d2) {
|
|
352
|
+
if (!isFinite(f)) return 1;
|
|
353
|
+
if (f <= 0) return 0;
|
|
354
|
+
return betai(d1/2, d2/2, d1*f/(d1*f + d2));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/* ── Change points: phases with their own limits ──────────────────────
|
|
358
|
+
Marking where a process was deliberately changed and recomputing the
|
|
359
|
+
centre line and limits on each side is standard practice — Minitab calls
|
|
360
|
+
them stages, JMP calls them phases.
|
|
361
|
+
|
|
362
|
+
Three things have to happen at a boundary, and skipping any of them
|
|
363
|
+
produces a chart that looks right and is wrong:
|
|
364
|
+
|
|
365
|
+
1. Each phase gets its own centre line and its own limits, computed
|
|
366
|
+
only from its own points.
|
|
367
|
+
2. The run rules restart. A run of nine on one side of the centre line
|
|
368
|
+
means nothing if it straddles a deliberate change — the rules are
|
|
369
|
+
applied inside each phase and never across a boundary.
|
|
370
|
+
3. The moving range that spans the boundary is excluded. It measures
|
|
371
|
+
the change you already know about, and leaving it in inflates the
|
|
372
|
+
limits of whichever phase claims it — exactly the error the change
|
|
373
|
+
point was drawn to avoid.
|
|
374
|
+
|
|
375
|
+
`cps` are 1-based row numbers: the row at which a NEW phase begins. */
|
|
376
|
+
function segments(n, cps) {
|
|
377
|
+
const cuts = [...new Set((cps || [])
|
|
378
|
+
.map(c => Math.round(c) - 1)
|
|
379
|
+
.filter(c => c > 0 && c < n))].sort((a, b) => a - b);
|
|
380
|
+
const bounds = [0, ...cuts, n];
|
|
381
|
+
const out = [];
|
|
382
|
+
for (let i = 0; i < bounds.length - 1; i++) out.push({ s: bounds[i], e: bounds[i + 1] });
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Run `make` on every phase and stitch the per-point limit arrays back together. */
|
|
387
|
+
function phase(n, cps, make) {
|
|
388
|
+
const segs = segments(n, cps);
|
|
389
|
+
const cl = [], ucl = [], lcl = [], sigmaAt = [], parts = [];
|
|
390
|
+
segs.forEach(sg => {
|
|
391
|
+
const r = make(sg);
|
|
392
|
+
const pick = (v, k) => Array.isArray(v) ? v[k] : v;
|
|
393
|
+
for (let i = sg.s; i < sg.e; i++) {
|
|
394
|
+
const k = i - sg.s;
|
|
395
|
+
cl.push(r.cl);
|
|
396
|
+
ucl.push(pick(r.ucl, k));
|
|
397
|
+
lcl.push(pick(r.lcl, k));
|
|
398
|
+
sigmaAt.push(pick(r.sigmaAt !== undefined ? r.sigmaAt : r.sigma, k));
|
|
399
|
+
}
|
|
400
|
+
parts.push({ s: sg.s, e: sg.e, res: r });
|
|
401
|
+
});
|
|
402
|
+
return { segs, cl, ucl, lcl, sigmaAt, parts };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Nelson rules applied inside each phase, never across a boundary. */
|
|
406
|
+
function nelsonPhased(points, cl, sigmaAt, ucl, lcl, segs, opts) {
|
|
407
|
+
const out = [];
|
|
408
|
+
const cut = (a, sg) => Array.isArray(a) ? a.slice(sg.s, sg.e) : a;
|
|
409
|
+
segs.forEach(sg => {
|
|
410
|
+
nelson(points.slice(sg.s, sg.e),
|
|
411
|
+
Array.isArray(cl) ? cl[sg.s] : cl,
|
|
412
|
+
cut(sigmaAt, sg), cut(ucl, sg), cut(lcl, sg), opts)
|
|
413
|
+
.forEach(s => out.push({ ...s, i: s.i + sg.s }));
|
|
414
|
+
});
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Moving ranges, with the boundary-spanning ones excluded from the limits. */
|
|
419
|
+
function mrPhased(values, cps, useMedian) {
|
|
420
|
+
const segs = segments(values.length, cps);
|
|
421
|
+
const all = movingRanges(values); // all.length === values.length - 1
|
|
422
|
+
const skip = new Set(segs.slice(1).map(sg => sg.s - 1)); // mR that straddles a cut
|
|
423
|
+
const cl = [], ucl = [];
|
|
424
|
+
segs.forEach(sg => {
|
|
425
|
+
const own = [];
|
|
426
|
+
for (let i = sg.s; i < sg.e - 1; i++) own.push(all[i]);
|
|
427
|
+
const bar = own.length ? (useMedian ? median(own) : mean(own)) : 0;
|
|
428
|
+
const k = useMedian ? XMR_MED_MR : XMR_AVG_MR;
|
|
429
|
+
for (let i = sg.s; i < sg.e; i++) {
|
|
430
|
+
if (i - 1 >= 0 && i - 1 < all.length) { cl[i - 1] = bar; ucl[i - 1] = k * bar; }
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
for (const i of skip) { cl[i] = cl[i] ?? 0; ucl[i] = ucl[i] ?? 0; }
|
|
434
|
+
return { points: all, cl, ucl, skip };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return { xmr, pChart, uChart, runChart, nelson, subgroupAnalysis,
|
|
438
|
+
segments, phase, nelsonPhased, mrPhased,
|
|
439
|
+
mean, median, sd, movingRanges, d2, c4, D2, D3, C4, fCDF };
|
|
440
|
+
})();
|
|
441
|
+
|
|
442
|
+
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
|
443
|
+
const fmt = (v, d) => {
|
|
444
|
+
if (v === null || v === undefined || !isFinite(v)) return '—';
|
|
445
|
+
if (d !== undefined) return v.toFixed(d);
|
|
446
|
+
const a = Math.abs(v);
|
|
447
|
+
return a >= 1000 ? v.toFixed(0) : a >= 10 ? v.toFixed(2) : a >= 0.01 ? v.toFixed(3) : v.toExponential(2);
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
function parseCSV(text) {
|
|
451
|
+
const rows = [];
|
|
452
|
+
let row = [], field = '', q = false;
|
|
453
|
+
for (let i = 0; i < text.length; i++) {
|
|
454
|
+
const c = text[i];
|
|
455
|
+
if (q) {
|
|
456
|
+
if (c === '"') { if (text[i+1] === '"') { field += '"'; i++; } else q = false; }
|
|
457
|
+
else field += c;
|
|
458
|
+
} else if (c === '"') q = true;
|
|
459
|
+
else if (c === ',') { row.push(field); field = ''; }
|
|
460
|
+
else if (c === '\n') { row.push(field); rows.push(row); row = []; field = ''; }
|
|
461
|
+
else if (c !== '\r') field += c;
|
|
462
|
+
}
|
|
463
|
+
if (field.length || row.length) { row.push(field); rows.push(row); }
|
|
464
|
+
const clean = rows.filter(r => r.some(f => f.trim() !== ''));
|
|
465
|
+
if (!clean.length) return null;
|
|
466
|
+
const cols = clean[0].map(c => c.trim());
|
|
467
|
+
const body = clean.slice(1).map(r => cols.map((_, i) => {
|
|
468
|
+
const raw = (r[i] ?? '').trim();
|
|
469
|
+
const num = raw === '' ? NaN : Number(raw.replace(/[$,%\s]/g, ''));
|
|
470
|
+
return raw !== '' && isFinite(num) ? num : raw;
|
|
471
|
+
}));
|
|
472
|
+
return { cols, rows: body };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function safeUrl(u) {
|
|
476
|
+
const s = (u || '').trim();
|
|
477
|
+
return /^https?:\/\/[^\s<>"]+$/i.test(s) ? s : '';
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/* ═══════════════════════════════════════════════════════════════════════
|
|
481
|
+
Chart drawing — plain SVG, no library. Limits may be a number (constant)
|
|
482
|
+
or an array (stepped, one per point).
|
|
483
|
+
═══════════════════════════════════════════════════════════════════════ */
|
|
484
|
+
|
|
485
|
+
/** Word-wrap change point notes into SVG text lines. The URL is kept whole —
|
|
486
|
+
a broken link is worse than a line that runs slightly long. */
|
|
487
|
+
function wrapCutNotes(cuts, maxW) {
|
|
488
|
+
const cpl = Math.max(28, Math.floor(maxW / 5.3));
|
|
489
|
+
const out = [];
|
|
490
|
+
cuts.forEach(c => {
|
|
491
|
+
const link = safeUrl(c.url);
|
|
492
|
+
const words = [];
|
|
493
|
+
if ((c.note || '').trim()) words.push(...c.note.trim().split(/\s+/));
|
|
494
|
+
if ((c.url || '').trim()) { if (words.length) words.push('·'); words.push(c.url.trim()); }
|
|
495
|
+
let line = '', first = true;
|
|
496
|
+
const flush = () => { out.push({ num: first ? c.n : null, text: line, link }); line = ''; first = false; };
|
|
497
|
+
words.forEach(w => {
|
|
498
|
+
if (line && (line + ' ' + w).length > cpl) flush();
|
|
499
|
+
line = line ? line + ' ' + w : w;
|
|
500
|
+
});
|
|
501
|
+
if (line) flush();
|
|
502
|
+
});
|
|
503
|
+
return out;
|
|
504
|
+
}
|
|
505
|
+
function drawChart(o) {
|
|
506
|
+
const W = Math.max(760, 60 + o.points.length * 26);
|
|
507
|
+
const P = { t: 26, r: 118, b: 46, l: 62 };
|
|
508
|
+
// Annotations are laid out first, because they claim height from the canvas.
|
|
509
|
+
const noteLines = o.showNotes === false ? []
|
|
510
|
+
: wrapCutNotes((o.cuts || []).filter(c => (c.note||'').trim() || (c.url||'').trim()), W - P.l - 24);
|
|
511
|
+
const noteH = noteLines.length ? noteLines.length * 14 + 18 : 0;
|
|
512
|
+
const H = (o.height || 300) + noteH;
|
|
513
|
+
const iw = W - P.l - P.r, ih = H - P.t - P.b - noteH;
|
|
514
|
+
const n = o.points.length;
|
|
515
|
+
const at = (a, i) => Array.isArray(a) ? a[i] : a;
|
|
516
|
+
|
|
517
|
+
let lo = Infinity, hi = -Infinity;
|
|
518
|
+
for (let i = 0; i < n; i++) {
|
|
519
|
+
for (const v of [o.points[i], at(o.ucl, i), at(o.lcl, i), o.cl]) {
|
|
520
|
+
if (v !== null && v !== undefined && isFinite(v)) { lo = Math.min(lo, v); hi = Math.max(hi, v); }
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (!isFinite(lo)) { lo = 0; hi = 1; }
|
|
524
|
+
const pad = (hi - lo) * 0.12 || 1;
|
|
525
|
+
lo -= pad; hi += pad;
|
|
526
|
+
if (o.zeroFloor && lo < 0) lo = 0;
|
|
527
|
+
|
|
528
|
+
const X = i => P.l + (n === 1 ? iw/2 : (i * iw) / (n - 1));
|
|
529
|
+
const Y = v => P.t + ih - ((v - lo) / (hi - lo)) * ih;
|
|
530
|
+
|
|
531
|
+
const sigSet = new Map();
|
|
532
|
+
(o.signals || []).forEach(s => {
|
|
533
|
+
if (s.i >= 0 && s.i < n) {
|
|
534
|
+
if (!sigSet.has(s.i)) sigSet.set(s.i, []);
|
|
535
|
+
sigSet.get(s.i).push(s);
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
const F = 'font-family="system-ui,sans-serif"';
|
|
540
|
+
let g = '';
|
|
541
|
+
|
|
542
|
+
// y grid
|
|
543
|
+
const ticks = 5;
|
|
544
|
+
for (let t = 0; t <= ticks; t++) {
|
|
545
|
+
const v = lo + (hi - lo) * t / ticks, y = Y(v);
|
|
546
|
+
g += `<line x1="${P.l}" y1="${y.toFixed(1)}" x2="${P.l+iw}" y2="${y.toFixed(1)}" stroke="#eef2f6" stroke-width="1"/>`;
|
|
547
|
+
g += `<text x="${P.l-8}" y="${(y+4).toFixed(1)}" ${F} font-size="10" fill="#8299ac" text-anchor="end">${fmt(v)}</text>`;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// limit bands — stepped when the denominator moves
|
|
551
|
+
/* Every phase reports its own centre line and limits. Without this only the
|
|
552
|
+
last phase is labelled, and a reader has to go to the table to find out
|
|
553
|
+
what the line in front of them is worth. Interior labels sit at the right
|
|
554
|
+
end of the phase they belong to, right-aligned against the boundary, with
|
|
555
|
+
a white halo so they stay legible over the series. */
|
|
556
|
+
const phaseSpans = (o.phases && o.phases.length > 1) ? o.phases : [{ s: 0, e: n }];
|
|
557
|
+
|
|
558
|
+
const step = (arr, color, dash, label, dy) => {
|
|
559
|
+
if (arr === null || arr === undefined) return;
|
|
560
|
+
let d = '';
|
|
561
|
+
for (let i = 0; i < n; i++) {
|
|
562
|
+
const v = at(arr, i);
|
|
563
|
+
if (!isFinite(v)) continue;
|
|
564
|
+
const x0 = i === 0 ? P.l : (X(i-1) + X(i))/2;
|
|
565
|
+
const x1 = i === n-1 ? P.l+iw : (X(i) + X(i+1))/2;
|
|
566
|
+
d += `M${x0.toFixed(1)},${Y(v).toFixed(1)}L${x1.toFixed(1)},${Y(v).toFixed(1)}`;
|
|
567
|
+
if (i < n-1) {
|
|
568
|
+
const vn = at(arr, i+1);
|
|
569
|
+
if (isFinite(vn) && vn !== v) d += `L${x1.toFixed(1)},${Y(vn).toFixed(1)}`;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
g += `<path d="${d}" fill="none" stroke="${color}" stroke-width="1.4"${dash?` stroke-dasharray="${dash}"`:''}/>`;
|
|
573
|
+
|
|
574
|
+
phaseSpans.forEach(sg => {
|
|
575
|
+
const v = at(arr, sg.e - 1);
|
|
576
|
+
if (!isFinite(v)) return;
|
|
577
|
+
if (sg.e >= n) { // last phase labels in the right margin
|
|
578
|
+
g += `<text x="${P.l+iw+7}" y="${(Y(v)+4).toFixed(1)}" ${F} font-size="10.5" font-weight="700" fill="${color}">${label} ${fmt(v)}</text>`;
|
|
579
|
+
} else { // interior phases label inside the plot
|
|
580
|
+
const xEnd = (X(sg.e-1) + X(sg.e))/2 - 5;
|
|
581
|
+
g += `<text x="${xEnd.toFixed(1)}" y="${(Y(v)+dy).toFixed(1)}" ${F} font-size="9.5" font-weight="700" fill="${color}" text-anchor="end" paint-order="stroke" stroke="#ffffff" stroke-width="3.2" stroke-linejoin="round">${label} ${fmt(v)}</text>`;
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
step(o.ucl, '#c0392b', '5,4', o.limitLabel || 'UNPL', -4);
|
|
587
|
+
step(o.lcl, '#c0392b', '5,4', o.limitLabel === 'UCL' ? 'LCL' : 'LNPL', 11);
|
|
588
|
+
step(o.cl, '#1e5f8c', null, o.clLabel || 'CL', -4);
|
|
589
|
+
|
|
590
|
+
// baseline window marker
|
|
591
|
+
if (o.baselineAt && o.baselineAt > 0 && o.baselineAt < n) {
|
|
592
|
+
const x = (X(o.baselineAt-1) + X(o.baselineAt))/2;
|
|
593
|
+
g += `<line x1="${x.toFixed(1)}" y1="${P.t}" x2="${x.toFixed(1)}" y2="${P.t+ih}" stroke="#7c8fa1" stroke-width="1.2" stroke-dasharray="2,3"/>`;
|
|
594
|
+
g += `<text x="${(x+4).toFixed(1)}" y="${P.t+11}" ${F} font-size="9.5" fill="#7c8fa1">limits frozen here</text>`;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// change points — a new phase begins at each of these
|
|
598
|
+
(o.cuts || []).forEach(c => {
|
|
599
|
+
if (c.i <= 0 || c.i >= n) return;
|
|
600
|
+
const x = (X(c.i-1) + X(c.i))/2;
|
|
601
|
+
const tip = [c.note, c.url].filter(s => (s||'').trim()).join('\n') || `change ${c.n}`;
|
|
602
|
+
g += `<line x1="${x.toFixed(1)}" y1="${P.t}" x2="${x.toFixed(1)}" y2="${P.t+ih}" stroke="#7a4fa0" stroke-width="1.6" stroke-dasharray="4,3"><title>${esc(tip)}</title></line>`;
|
|
603
|
+
g += `<circle cx="${x.toFixed(1)}" cy="${P.t+7}" r="7.5" fill="#7a4fa0"><title>${esc(tip)}</title></circle>`;
|
|
604
|
+
g += `<text x="${x.toFixed(1)}" y="${P.t+10.5}" ${F} font-size="9" font-weight="700" fill="#fff" text-anchor="middle">${c.n}</text>`;
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
// series
|
|
608
|
+
let line = '';
|
|
609
|
+
for (let i = 0; i < n; i++) line += (i ? 'L' : 'M') + X(i).toFixed(1) + ',' + Y(o.points[i]).toFixed(1);
|
|
610
|
+
g += `<path d="${line}" fill="none" stroke="#41637c" stroke-width="1.6"/>`;
|
|
611
|
+
|
|
612
|
+
for (let i = 0; i < n; i++) {
|
|
613
|
+
const muted = o.muted && o.muted.has(i);
|
|
614
|
+
const sigs = muted ? null : sigSet.get(i);
|
|
615
|
+
const c = sigs ? '#c0392b' : '#41637c';
|
|
616
|
+
const r = sigs ? 5 : 3.2;
|
|
617
|
+
const note = muted ? '\nspans a change point — excluded from the limits' : '';
|
|
618
|
+
g += `<circle cx="${X(i).toFixed(1)}" cy="${Y(o.points[i]).toFixed(1)}" r="${r}" fill="${sigs?'#c0392b':'#fff'}" stroke="${c}" stroke-width="1.8"${muted?' opacity="0.3"':''}><title>${esc(o.labels[i])}: ${fmt(o.points[i])}${sigs?'\n'+sigs.map(s=>'⚠ '+s.text).join('\n'):''}${note}</title></circle>`;
|
|
619
|
+
if (sigs) g += `<text x="${X(i).toFixed(1)}" y="${(Y(o.points[i])-10).toFixed(1)}" ${F} font-size="9" font-weight="700" fill="#c0392b" text-anchor="middle">${sigs.map(s=>s.rule).filter((v,j,a)=>a.indexOf(v)===j).join(',')}</text>`;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// x labels — thinned so they never collide
|
|
623
|
+
const everyN = Math.max(1, Math.ceil(n / Math.floor(iw / 52)));
|
|
624
|
+
for (let i = 0; i < n; i++) {
|
|
625
|
+
if (i % everyN) continue;
|
|
626
|
+
g += `<text x="${X(i).toFixed(1)}" y="${P.t+ih+16}" ${F} font-size="9.5" fill="#7c8fa1" text-anchor="middle" transform="rotate(-32 ${X(i).toFixed(1)} ${P.t+ih+16})">${esc(String(o.labels[i]).slice(0,14))}</text>`;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
g += `<line x1="${P.l}" y1="${P.t+ih}" x2="${P.l+iw}" y2="${P.t+ih}" stroke="#cbd5e1" stroke-width="1"/>`;
|
|
630
|
+
g += `<line x1="${P.l}" y1="${P.t}" x2="${P.l}" y2="${P.t+ih}" stroke="#cbd5e1" stroke-width="1"/>`;
|
|
631
|
+
if (o.yLabel) g += `<text x="14" y="${P.t+ih/2}" ${F} font-size="10.5" font-weight="600" fill="#64748b" text-anchor="middle" transform="rotate(-90 14 ${P.t+ih/2})">${esc(o.yLabel)}</text>`;
|
|
632
|
+
if (o.title) g += `<text x="${P.l}" y="${P.t-10}" ${F} font-size="12" font-weight="700" fill="#0f2f47">${esc(o.title)}</text>`;
|
|
633
|
+
|
|
634
|
+
// Annotation block, inside the SVG so it survives export and print.
|
|
635
|
+
if (noteLines.length) {
|
|
636
|
+
const y0 = H - noteH + 14;
|
|
637
|
+
g += `<line x1="${P.l}" y1="${(y0-11).toFixed(1)}" x2="${W-16}" y2="${(y0-11).toFixed(1)}" stroke="#e6e0ee" stroke-width="1"/>`;
|
|
638
|
+
noteLines.forEach((ln, k) => {
|
|
639
|
+
const y = y0 + k*14;
|
|
640
|
+
if (ln.num !== null) {
|
|
641
|
+
g += `<circle cx="${P.l+7}" cy="${(y-3.5).toFixed(1)}" r="7" fill="#7a4fa0"/>`;
|
|
642
|
+
g += `<text x="${P.l+7}" y="${(y-0.5).toFixed(1)}" ${F} font-size="8.5" font-weight="700" fill="#fff" text-anchor="middle">${ln.num}</text>`;
|
|
643
|
+
}
|
|
644
|
+
const t = `<text x="${P.l+20}" y="${y.toFixed(1)}" ${F} font-size="10.5" fill="${ln.link?'#1e5f8c':'#41637c'}">${esc(ln.text)}</text>`;
|
|
645
|
+
// Printed charts need the URL readable as text; on screen it is also a link.
|
|
646
|
+
g += ln.link ? `<a href="${esc(ln.link)}" xlink:href="${esc(ln.link)}" target="_blank" rel="noopener">${t}</a>` : t;
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// geometry published so a click can be mapped back to a point index
|
|
651
|
+
const clickable = o.clickable ? ` data-click="1" data-l="${P.l}" data-iw="${iw}" data-n="${n}" style="cursor:crosshair"` : '';
|
|
652
|
+
return `<div class="charthost"><svg class="chart" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"${clickable}><rect width="${W}" height="${H}" fill="#fff"/>${g}</svg></div>`;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/* ═══════════════════════════════════════════════════════════════════════
|
|
656
|
+
View — one session in, the whole right-hand side out. Reads nothing
|
|
657
|
+
from the page: the tool hands over its controls' values as state.
|
|
658
|
+
═══════════════════════════════════════════════════════════════════════ */
|
|
659
|
+
let ST = { data: null, s: {}, cps: [], readOnly: false };
|
|
660
|
+
|
|
661
|
+
function col(name) {
|
|
662
|
+
if (!ST.data) return [];
|
|
663
|
+
const i = ST.data.cols.indexOf(name);
|
|
664
|
+
return i < 0 ? [] : ST.data.rows.map(r => r[i]);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function view(state) {
|
|
668
|
+
const s = state.settings || {}, f = state.flags || {};
|
|
669
|
+
ST = { data: state.data, s, cps: state.changePoints || [], readOnly: !!state.readOnly };
|
|
670
|
+
if (!ST.data) return '';
|
|
671
|
+
|
|
672
|
+
const type = s.chartSel || 'xmr';
|
|
673
|
+
const orderC = s.orderSel || '';
|
|
674
|
+
const groupC = s.groupSel || '';
|
|
675
|
+
const split = f.splitChk && groupC;
|
|
676
|
+
const baseN = parseInt(s.baseInput, 10) || 0;
|
|
677
|
+
const opts = { medianMR: !!f.medianMR, laney: !!f.laneyChk,
|
|
678
|
+
baseline: baseN, scale: Number(s.scaleInput) || 1,
|
|
679
|
+
cps: ST.cps.map(c => c.row) };
|
|
680
|
+
const allRules = !!f.nelsonChk;
|
|
681
|
+
|
|
682
|
+
const labels = col(orderC).map(String);
|
|
683
|
+
let html = '';
|
|
684
|
+
|
|
685
|
+
if (state.note) html += `<div class="verdict info"><h4>${esc(state.noteTitle || 'Example dataset')}</h4><p>${esc(state.note)}</p></div>`;
|
|
686
|
+
|
|
687
|
+
// ── Subgrouping panel first: the choice precedes the chart ────────────
|
|
688
|
+
if (groupC) {
|
|
689
|
+
const vals = seriesValues(type, opts);
|
|
690
|
+
const gl = col(groupC).map(String);
|
|
691
|
+
const pairs = vals.map((v,i)=>({v, g: gl[i]})).filter(x => isFinite(x.v));
|
|
692
|
+
const an = SPC.subgroupAnalysis(pairs.map(x=>x.v), pairs.map(x=>x.g));
|
|
693
|
+
html += renderSubgroup(an, groupC, type);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// ── Charts ────────────────────────────────────────────────────────────
|
|
697
|
+
if (split) {
|
|
698
|
+
const gl = col(groupC).map(String);
|
|
699
|
+
const keys = [...new Set(gl)];
|
|
700
|
+
keys.forEach(k => {
|
|
701
|
+
const idx = gl.map((g,i)=>g===k?i:-1).filter(i=>i>=0);
|
|
702
|
+
html += renderOne(type, idx, opts, allRules, `${groupC} = ${k}`, labels);
|
|
703
|
+
});
|
|
704
|
+
} else {
|
|
705
|
+
html += renderOne(type, ST.data.rows.map((_,i)=>i), opts, allRules, null, labels);
|
|
706
|
+
}
|
|
707
|
+
return html;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function cutsFor(segs) {
|
|
711
|
+
return segs.slice(1).map((s, k) => {
|
|
712
|
+
const c = ST.cps.find(c => c.row - 1 === s.s) || {};
|
|
713
|
+
return { i: s.s, n: k + 1, note: c.note || '', url: c.url || '' };
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function seriesValues(type, opts) {
|
|
718
|
+
if (type === 'p') {
|
|
719
|
+
const num = col(ST.s.numSel), den = col(ST.s.denSel);
|
|
720
|
+
return num.map((d,i) => den[i] > 0 ? d/den[i] : NaN);
|
|
721
|
+
}
|
|
722
|
+
if (type === 'u') {
|
|
723
|
+
const num = col(ST.s.numSel), den = col(ST.s.denSel);
|
|
724
|
+
return num.map((c_,i) => den[i] > 0 ? (c_/den[i])*(opts.scale||1) : NaN);
|
|
725
|
+
}
|
|
726
|
+
return col(ST.s.valueSel).map(Number);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function renderOne(type, idx, opts, allRules, titleSuffix, allLabels) {
|
|
730
|
+
const labels = idx.map(i => allLabels[i]);
|
|
731
|
+
const title = titleSuffix ? `${chartName(type)} — ${titleSuffix}` : chartName(type);
|
|
732
|
+
// Change points are positions in the series as loaded. Splitting by subgroup
|
|
733
|
+
// reorders the rows, so a row number no longer means anything — drop them.
|
|
734
|
+
const cps = titleSuffix ? [] : (opts.cps || []);
|
|
735
|
+
const phased = cps.length > 0;
|
|
736
|
+
const base = phased ? 0 : opts.baseline; // a phase computes its own limits
|
|
737
|
+
let chart, extra = '', statList = [], segRows = [];
|
|
738
|
+
|
|
739
|
+
if (type === 'run') {
|
|
740
|
+
const v = idx.map(i => Number(col(ST.s.valueSel)[i])).filter(isFinite);
|
|
741
|
+
const segs = SPC.segments(v.length, cps);
|
|
742
|
+
const cl = [], sigs = [];
|
|
743
|
+
segs.forEach(sg => {
|
|
744
|
+
const r = SPC.runChart(v.slice(sg.s, sg.e));
|
|
745
|
+
for (let i = sg.s; i < sg.e; i++) cl.push(r.cl);
|
|
746
|
+
r.signals.forEach(s => sigs.push({ ...s, i: s.i + sg.s }));
|
|
747
|
+
segRows.push([sg, fmt(r.cl), '—', r.signals.length]);
|
|
748
|
+
});
|
|
749
|
+
chart = drawChart({ points: v, labels, cl, ucl: null, lcl: null, signals: sigs,
|
|
750
|
+
title, clLabel: 'Median', cuts: cutsFor(segs), phases: segs, clickable: !ST.readOnly,
|
|
751
|
+
yLabel: ST.s.valueSel, height: 290 });
|
|
752
|
+
statList = [['Median', fmt(cl[0])], ['Phases', segs.length], ['Points', v.length]];
|
|
753
|
+
extra = signalTable(sigs, labels, 'Run chart rules (Perla)');
|
|
754
|
+
|
|
755
|
+
} else if (type === 'p' || type === 'u') {
|
|
756
|
+
const num = idx.map(i => Number(col(ST.s.numSel)[i]));
|
|
757
|
+
const den = idx.map(i => Number(col(ST.s.denSel)[i]));
|
|
758
|
+
const scale = type === 'u' ? (opts.scale || 1) : 1;
|
|
759
|
+
const pts = num.map((c_, i) => den[i] > 0 ? (c_ / den[i]) * scale : 0);
|
|
760
|
+
const ph = SPC.phase(num.length, cps, sg =>
|
|
761
|
+
(type === 'p' ? SPC.pChart : SPC.uChart)(
|
|
762
|
+
num.slice(sg.s, sg.e), den.slice(sg.s, sg.e), { ...opts, baseline: base }));
|
|
763
|
+
const sigs = SPC.nelsonPhased(pts, ph.cl, ph.sigmaAt, ph.ucl, ph.lcl, ph.segs, { all: allRules });
|
|
764
|
+
const sz = Math.max(...ph.parts.map(p => p.res.sigmaZ).filter(isFinite));
|
|
765
|
+
chart = drawChart({ points: pts, labels, cl: ph.cl, ucl: ph.ucl, lcl: ph.lcl,
|
|
766
|
+
signals: sigs, title, limitLabel: 'UCL', zeroFloor: true, clickable: !ST.readOnly,
|
|
767
|
+
cuts: cutsFor(ph.segs), phases: ph.segs, baselineAt: base, height: 300,
|
|
768
|
+
yLabel: type === 'p' ? 'proportion' : `per ${opts.scale}` });
|
|
769
|
+
ph.parts.forEach(p => segRows.push([{ s: p.s, e: p.e }, fmt(p.res.cl),
|
|
770
|
+
'σz ' + fmt(p.res.sigmaZ, 2),
|
|
771
|
+
sigs.filter(s => s.rule === 1 && s.i >= p.s && s.i < p.e).length]));
|
|
772
|
+
statList = [
|
|
773
|
+
['Centre line', phased ? ph.segs.length + ' phases' : fmt(ph.cl[0])],
|
|
774
|
+
['Sigma z', fmt(sz, 2), sz > 1.2 ? 'overdispersed' : 'binomial holds'],
|
|
775
|
+
['Points signalling', sigs.filter(s=>s.rule===1).length + ' of ' + pts.length],
|
|
776
|
+
['Limits', opts.laney ? 'Laney ' + (type==='p'?'p′':'u′') : 'classical ' + type]
|
|
777
|
+
];
|
|
778
|
+
extra = overdispersionVerdict({ sigmaZ: sz, laney: opts.laney }, type)
|
|
779
|
+
+ signalTable(sigs, labels, 'Signals');
|
|
780
|
+
|
|
781
|
+
} else {
|
|
782
|
+
const v = idx.map(i => Number(col(ST.s.valueSel)[i])).filter(isFinite);
|
|
783
|
+
const ph = SPC.phase(v.length, cps, sg =>
|
|
784
|
+
SPC.xmr(v.slice(sg.s, sg.e), { medianMR: opts.medianMR, baseline: base }));
|
|
785
|
+
const sigs = SPC.nelsonPhased(v, ph.cl, ph.sigmaAt, ph.ucl, ph.lcl, ph.segs, { all: allRules });
|
|
786
|
+
const cuts = cutsFor(ph.segs);
|
|
787
|
+
chart = drawChart({ points: v, labels, cl: ph.cl, ucl: ph.ucl, lcl: ph.lcl,
|
|
788
|
+
signals: sigs, title, cuts, phases: ph.segs, clickable: !ST.readOnly, baselineAt: base,
|
|
789
|
+
height: 300, yLabel: ST.s.valueSel });
|
|
790
|
+
|
|
791
|
+
const mrr = SPC.mrPhased(v, cps, opts.medianMR);
|
|
792
|
+
const mrSigs = mrr.points.map((val, i) =>
|
|
793
|
+
(!mrr.skip.has(i) && val > mrr.ucl[i]) ? { i, rule:1, text:'Moving range above its limit' } : null
|
|
794
|
+
).filter(Boolean);
|
|
795
|
+
chart += drawChart({ points: mrr.points, labels: labels.slice(1), cl: mrr.cl,
|
|
796
|
+
ucl: mrr.ucl, lcl: 0, signals: mrSigs, title: 'Moving range', zeroFloor: true,
|
|
797
|
+
height: 200, limitLabel: 'URL', yLabel: 'mR', muted: mrr.skip,
|
|
798
|
+
showNotes: false, cuts: cuts.map(c => ({ ...c, i: c.i - 1 })),
|
|
799
|
+
phases: ph.segs.map(sg => ({ s: sg.s, e: sg.e - 1 })).filter(sg => sg.e > sg.s) });
|
|
800
|
+
|
|
801
|
+
ph.parts.forEach(p => segRows.push([{ s: p.s, e: p.e }, fmt(p.res.cl),
|
|
802
|
+
fmt(p.res.lcl) + ' to ' + fmt(p.res.ucl),
|
|
803
|
+
sigs.filter(s => s.rule === 1 && s.i >= p.s && s.i < p.e).length]));
|
|
804
|
+
statList = [
|
|
805
|
+
['Centre line', phased ? ph.segs.length + ' phases' : fmt(ph.cl[0])],
|
|
806
|
+
['Sigma (within)', fmt(ph.sigmaAt[0]), opts.medianMR ? 'from median mR' : 'mR̄ / 1.128'],
|
|
807
|
+
['Limits', phased ? 'per phase' : fmt(ph.lcl[0]) + ' to ' + fmt(ph.ucl[0])],
|
|
808
|
+
['Points signalling', sigs.filter(s=>s.rule===1).length + ' of ' + v.length]
|
|
809
|
+
];
|
|
810
|
+
extra = signalTable(sigs.concat(mrSigs.map(s=>({...s, text:'mR: '+s.text}))), labels, 'Signals');
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
const hint = titleSuffix && (opts.cps || []).length
|
|
814
|
+
? `<div class="verdict warn"><h4>Change points are off while subgroups are split</h4><p>They are row positions in the series as loaded, and splitting reorders the rows. Untick <strong>Chart each subgroup separately</strong> to use them.</p></div>`
|
|
815
|
+
: '';
|
|
816
|
+
|
|
817
|
+
return `<div class="card"><h2>${esc(title)}</h2>` +
|
|
818
|
+
`<div class="sub">${esc(chartBlurb(type))}${ST.readOnly ? '' : phased ? ' · Click the chart to add or remove a change point.' : ' · Click the chart to mark where the process changed.'}</div>` +
|
|
819
|
+
hint + chart +
|
|
820
|
+
`<div class="stats">${statList.map(s=>`<div class="stat"><div class="k">${esc(s[0])}</div><div class="v">${esc(String(s[1]))}</div>${s[2]?`<div class="n">${esc(s[2])}</div>`:''}</div>`).join('')}</div>` +
|
|
821
|
+
(phased ? phaseTable(segRows, labels, type) : '') + extra + '</div>';
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Per-phase readout — the whole point of marking a change. */
|
|
825
|
+
function phaseTable(rows, labels, type) {
|
|
826
|
+
const head = type === 'run' ? 'Median' : 'Centre line';
|
|
827
|
+
const third = type === 'run' ? '' : (type === 'p' || type === 'u' ? 'Dispersion' : 'Limits');
|
|
828
|
+
const body = rows.map((r, k) => {
|
|
829
|
+
const [sg, cl, mid, sig] = r;
|
|
830
|
+
const c = ST.cps.find(c => c.row - 1 === sg.s);
|
|
831
|
+
const link = c && safeUrl(c.url);
|
|
832
|
+
const why = k === 0 ? '<span style="color:#94a3b8">baseline</span>'
|
|
833
|
+
: (c && (c.note || '').trim() ? esc(c.note) : '<span style="color:#c0392b">— not yet described —</span>')
|
|
834
|
+
+ (link ? ` <a href="${esc(link)}" target="_blank" rel="noopener">link</a>` : '');
|
|
835
|
+
return `<tr><td class="pt">Phase ${k+1}</td><td>${esc(labels[sg.s] ?? '#'+(sg.s+1))} – ${esc(labels[sg.e-1] ?? '#'+sg.e)}</td><td>${sg.e - sg.s}</td><td>${esc(cl)}</td><td>${esc(String(mid))}</td><td>${sig}</td><td>${why}</td></tr>`;
|
|
836
|
+
}).join('');
|
|
837
|
+
return `<table class="sig" style="margin-top:14px"><thead><tr><th>Phase</th><th>From – to</th><th>n</th><th>${esc(head)}</th><th>${esc(third)}</th><th>Outside</th><th>What changed</th></tr></thead><tbody>${body}</tbody></table>`;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function chartName(t) {
|
|
841
|
+
return { xmr:'XmR chart', p:'p chart', u:'u chart', run:'Run chart' }[t];
|
|
842
|
+
}
|
|
843
|
+
function chartBlurb(t) {
|
|
844
|
+
return {
|
|
845
|
+
xmr: 'Individual values with limits from the average moving range — never from the standard deviation of all the values.',
|
|
846
|
+
p: 'Proportion with limits recomputed at every point, because the denominator moves.',
|
|
847
|
+
u: 'Count over a varying area of opportunity. Limits widen where the denominator is small; that is correct.',
|
|
848
|
+
run: 'Median centre line, no limits. Fewer assumptions, less power.'
|
|
849
|
+
}[t];
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function overdispersionVerdict(res, type) {
|
|
853
|
+
const sz = res.sigmaZ;
|
|
854
|
+
if (!isFinite(sz)) return '';
|
|
855
|
+
if (sz > 1.2 && !res.laney) {
|
|
856
|
+
return `<div class="verdict bad"><h4>These limits are almost certainly too tight</h4>
|
|
857
|
+
<p>Sigma z is <code>${fmt(sz,2)}</code>. The points move about <strong>${fmt(sz,1)}×</strong> more than the ${type==='p'?'binomial':'Poisson'} model says they can. With denominators this large, the classical ${type} chart will flag nearly every period as special cause when nothing unusual has happened.</p>
|
|
858
|
+
<p>This is <em>overdispersion</em>, and it is the normal condition for health care rates with big populations. Turn on the <strong>Laney ${type==='p'?'p′':'u′'}</strong> correction in the Limits panel.</p></div>`;
|
|
859
|
+
}
|
|
860
|
+
if (sz > 1.2 && res.laney) {
|
|
861
|
+
return `<div class="verdict ok"><h4>Laney correction applied</h4>
|
|
862
|
+
<p>Sigma z of <code>${fmt(sz,2)}</code> means there was real between-period variation beyond the ${type==='p'?'binomial':'Poisson'} model. The limits above are widened by that factor, so what remains outside them is worth investigating.</p></div>`;
|
|
863
|
+
}
|
|
864
|
+
if (sz < 0.75) {
|
|
865
|
+
return `<div class="verdict warn"><h4>Points are moving less than chance allows</h4>
|
|
866
|
+
<p>Sigma z is <code>${fmt(sz,2)}</code>. Under-dispersion usually means the denominator is wrong, the data has been smoothed or averaged before it reached you, or the numbers are being adjusted before reporting.</p></div>`;
|
|
867
|
+
}
|
|
868
|
+
return '';
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function signalTable(sigs, labels, heading) {
|
|
872
|
+
if (!sigs.length) return `<div style="margin-top:14px"><div class="k" style="font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#64748b">${esc(heading)}</div><div class="none">No signals. This process is behaving predictably — which is a finding, not a failure.</div></div>`;
|
|
873
|
+
const rows = sigs.slice().sort((a,b)=>a.i-b.i).map(s =>
|
|
874
|
+
`<tr class="hi"><td class="pt">${esc(labels[s.i] ?? ('#'+(s.i+1)))}</td><td>${esc(String(s.rule))}</td><td>${esc(s.text)}</td></tr>`).join('');
|
|
875
|
+
return `<table class="sig"><thead><tr><th>${esc(heading==='Run chart rules (Perla)'?'Starting at':'Point')}</th><th>Rule</th><th>What it means</th></tr></thead><tbody>${rows}</tbody></table>`;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/* The subgrouping panel — the reason this tool exists. */
|
|
879
|
+
function renderSubgroup(an, colName, type) {
|
|
880
|
+
if (!an) return `<div class="verdict warn"><h4>Not enough to compare</h4><p>Subgrouping by <code>${esc(colName)}</code> needs at least two groups with more than one observation between them.</p></div>`;
|
|
881
|
+
|
|
882
|
+
const pct = Math.round(an.shareBetween * 100);
|
|
883
|
+
const sig = an.p < 0.05;
|
|
884
|
+
const cls = pct >= 40 ? 'bad' : pct >= 15 ? 'warn' : 'ok';
|
|
885
|
+
|
|
886
|
+
let verdict;
|
|
887
|
+
if (pct >= 40 && sig) {
|
|
888
|
+
verdict = `<h4>${pct}% of all the variation is <em>between</em> ${esc(colName)}s — not within them</h4>
|
|
889
|
+
<p>These are not one process. They are ${an.k} processes that happen to share a spreadsheet. Pooling them into a single chart makes the limits wide enough to hide everything real, and comparing the pooled average to a target tells you nothing about any actual ${esc(colName)}.</p>
|
|
890
|
+
<p>Tick <strong>Chart each subgroup separately</strong> in the Subgrouping panel. If instead you subgroup <em>by</em> ${esc(colName)} and chart the pooled series, you have just declared the largest effect in your data to be noise.</p>`;
|
|
891
|
+
} else if (pct >= 15) {
|
|
892
|
+
verdict = `<h4>${pct}% of the variation is between ${esc(colName)}s</h4>
|
|
893
|
+
<p>Enough to matter, not enough to be the whole story. Chart both ways and see which reading survives. A difference this size will show up in a league table as a ranking every quarter, and the ranking will reshuffle on noise.</p>`;
|
|
894
|
+
} else {
|
|
895
|
+
verdict = `<h4>${esc(colName)} explains almost none of the variation (${pct}%)</h4>
|
|
896
|
+
<p>Whatever is moving this measure, it is not which ${esc(colName)} the observation came from. Pooling them is legitimate, and a single chart is the honest picture.</p>
|
|
897
|
+
<p>Note what this rules out: any intervention aimed at differences between ${esc(colName)}s is aimed at ${pct}% of the problem.</p>`;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const bar = `<div class="varbar">
|
|
901
|
+
<div class="between" style="width:${Math.max(pct,3)}%">${pct >= 12 ? 'between ' + pct + '%' : ''}</div>
|
|
902
|
+
<div class="within" style="width:${Math.max(100-pct,3)}%">${100-pct >= 12 ? 'within ' + (100-pct) + '%' : ''}</div>
|
|
903
|
+
</div>
|
|
904
|
+
<div class="legend2"><span><i style="background:#d4622f"></i>between ${esc(colName)}s</span><span><i style="background:#7fa8c4"></i>within a ${esc(colName)}</span></div>`;
|
|
905
|
+
|
|
906
|
+
const rows = an.detail.map(d =>
|
|
907
|
+
`<tr><td class="pt">${esc(d.key)}</td><td>${d.n}</td><td>${fmt(d.mean)}</td><td>${fmt(d.sd)}</td><td>${fmt(d.min)} – ${fmt(d.max)}</td></tr>`).join('');
|
|
908
|
+
|
|
909
|
+
return `<div class="card"><h2>Subgrouping by ${esc(colName)}</h2>
|
|
910
|
+
<div class="sub">Choosing a subgroup is a claim about cause, not a display option. Here is what that claim costs.</div>
|
|
911
|
+
<div class="verdict ${cls}">${verdict}</div>
|
|
912
|
+
${bar}
|
|
913
|
+
<div class="stats">
|
|
914
|
+
<div class="stat"><div class="k">Sigma within</div><div class="v">${fmt(an.sigmaWithin)}</div><div class="n">pooled, what the chart calls noise</div></div>
|
|
915
|
+
<div class="stat"><div class="k">Sigma overall</div><div class="v">${fmt(an.sigmaTotal)}</div><div class="n">ignoring ${esc(colName)}</div></div>
|
|
916
|
+
<div class="stat"><div class="k">Ratio</div><div class="v">${fmt(an.ratio,2)}×</div><div class="n">overall ÷ within</div></div>
|
|
917
|
+
<div class="stat"><div class="k">F(${an.k-1}, ${an.N-an.k})</div><div class="v">${fmt(an.F,2)}</div><div class="n">p ${an.p < 0.0001 ? '< 0.0001' : '= ' + fmt(an.p,4)}</div></div>
|
|
918
|
+
</div>
|
|
919
|
+
<table class="sig" style="margin-top:14px"><thead><tr><th>${esc(colName)}</th><th>n</th><th>Mean</th><th>SD</th><th>Range</th></tr></thead><tbody>${rows}</tbody></table>
|
|
920
|
+
</div>`;
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
return { SPC, esc, fmt, parseCSV, safeUrl, wrapCutNotes, drawChart, view, chartName, chartBlurb };
|
|
924
|
+
})();
|
|
925
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = RCNSPC;
|
|
926
|
+
// END rcn-spc-core.js
|
|
927
|
+
|
|
928
|
+
// BEGIN chart css — pasted by build.js. Edit the source in the rcn repo, never this block.
|
|
929
|
+
const CSS = ".rcnspc .card{background:#fff;border:1px solid #d9e2ea;border-radius:10px;padding:18px 20px;margin-bottom:18px}\n.rcnspc .card>h2{font-size:15px;font-weight:700;color:#0f2f47;margin-bottom:3px}\n.rcnspc .card>.sub{font-size:12px;color:#64748b;margin-bottom:14px}\n.rcnspc .verdict{border-radius:9px;padding:14px 16px;margin-bottom:14px;border:1px solid}\n.rcnspc .verdict h4{font-size:13px;font-weight:700;margin-bottom:5px}\n.rcnspc .verdict p{font-size:12.5px;line-height:1.6;margin-bottom:6px}\n.rcnspc .verdict p:last-child{margin-bottom:0}\n.rcnspc .verdict.warn{background:#fff8e6;border-color:#f0d48a;color:#6b4e08}\n.rcnspc .verdict.warn h4{color:#8a6300}\n.rcnspc .verdict.bad{background:#fdf0ee;border-color:#f0bdb3;color:#7d2d1c}\n.rcnspc .verdict.bad h4{color:#a83217}\n.rcnspc .verdict.ok{background:#eef7f0;border-color:#b8dcc2;color:#28563a}\n.rcnspc .verdict.ok h4{color:#2f6b45}\n.rcnspc .verdict.info{background:#eef4fa;border-color:#bcd4e8;color:#274a67}\n.rcnspc .verdict.info h4{color:#1e5f8c}\n.rcnspc .verdict code{background:rgba(0,0,0, .rcnspc .06);padding:1px 5px;border-radius:4px;font-family:ui-monospace,Menlo, .rcnspc monospace;font-size:11.5px}\n.rcnspc .stats{display:grid;grid-template-columns:repeat(auto-fill, .rcnspc minmax(150px,1fr));gap:10px;margin-top:12px}\n.rcnspc .stat{background:#f6f9fb;border:1px solid #e2eaf1;border-radius:8px;padding:9px 11px}\n.rcnspc .stat .k{font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#7089a0;margin-bottom:3px}\n.rcnspc .stat .v{font-size:17px;font-weight:700;color:#0f2f47;font-variant-numeric:tabular-nums}\n.rcnspc .stat .n{font-size:10.5px;color:#7c8fa1;margin-top:1px}\n.rcnspc table.sig{width:100%;border-collapse:collapse;font-size:12.5px;margin-top:6px}\n.rcnspc table.sig th{text-align:left;padding:6px 9px;font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#64748b;background:#f6f9fb;border-bottom:2px solid #e2eaf1}\n.rcnspc table.sig td{padding:6px 9px;border-bottom:1px solid #f0f4f8;vertical-align:top;color:#334155}\n.rcnspc table.sig td.pt{font-weight:700;color:#0f2f47;white-space:nowrap;font-variant-numeric:tabular-nums}\n.rcnspc table.sig tr.hi td{background:#fdf5f3}\n.rcnspc .none{font-size:12.5px;color:#64748b;font-style:italic;padding:8px 0}\n.rcnspc .varbar{height:22px;border-radius:5px;overflow:hidden;display:flex;margin:10px 0 6px;border:1px solid #d9e2ea}\n.rcnspc .varbar .between{background:#d4622f}\n.rcnspc .varbar .within{background:#7fa8c4}\n.rcnspc .varbar div{display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:#fff;white-space:nowrap}\n.rcnspc .legend2{display:flex;gap:14px;font-size:11px;color:#64748b}\n.rcnspc .legend2 i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:4px;vertical-align:-1px}\n.rcnspc svg.chart{display:block;width:100%;height:auto;font-family:system-ui, .rcnspc sans-serif}\n.rcnspc svg.chart a text{text-decoration:underline}\n.rcnspc .charthost{overflow-x:auto}";
|
|
930
|
+
// END chart css
|
|
931
|
+
|
|
932
|
+
// ── words (Marc edits these) ──
|
|
933
|
+
const W = {
|
|
934
|
+
title: 'RCN Process Behavior Chart',
|
|
935
|
+
empty: 'Drop a CSV file (first row = column names, one row per observation) or a saved session (.spc.json) here.',
|
|
936
|
+
emptyHow: 'Or open the tool, make the chart there, and press → Save to wiki item.',
|
|
937
|
+
open: 'Open the tool ↗',
|
|
938
|
+
edit: '✎ Edit in the tool',
|
|
939
|
+
editTip: 'Open this chart in the full tool: change the data, the chart, the change points; then → Save to wiki item',
|
|
940
|
+
tables: 'Signals and phases, in tables',
|
|
941
|
+
savedBack: 'Saved from the tool.',
|
|
942
|
+
notOwner: 'Only the owner of this wiki can drop a file here.',
|
|
943
|
+
notCsv: 'Could not read that file: ',
|
|
944
|
+
blocked: 'The browser blocked the popup. Allow popups for this site and press the button again.'
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// Local wikis (localhost and *.localhost farm sites) get the working copy off the
|
|
948
|
+
// local static server; everything else the copy on NDC Assets.
|
|
949
|
+
const LOCAL = /(^|\.)localhost$/.test(window.location.hostname)
|
|
950
|
+
const TOOL_URL = LOCAL
|
|
951
|
+
? 'http://localhost:8765/tools/rcn-spc.html'
|
|
952
|
+
: 'https://ndcgroup.relocalizecreativity.net/assets/NDC/rcn-spc.html'
|
|
953
|
+
|
|
954
|
+
const esc = RCNSPC.esc
|
|
955
|
+
const CHARTS = { xmr: 'XmR chart', p: 'p chart', u: 'u chart', run: 'Run chart' }
|
|
956
|
+
|
|
957
|
+
// ── the words a search finds: caption, what is charted, what changed ──
|
|
958
|
+
function describe (item) {
|
|
959
|
+
const s = item.session
|
|
960
|
+
const caption = String(item.text || '').split('\n')[0].trim() || (s && s.note) || W.title
|
|
961
|
+
if (!s || !s.data) return caption
|
|
962
|
+
const st = s.settings || {}, t = st.chartSel || 'xmr'
|
|
963
|
+
const what = (t === 'p' || t === 'u') ? `${st.numSel} over ${st.denSel}` : st.valueSel
|
|
964
|
+
const lines = [caption, `${CHARTS[t] || t} of ${what}${st.orderSel ? ' by ' + st.orderSel : ''}${st.groupSel ? ', subgrouped by ' + st.groupSel : ''}: ${s.data.rows.length} rows.`]
|
|
965
|
+
const cps = (s.changePoints || []).filter(c => c && c.row)
|
|
966
|
+
if (cps.length) lines.push('What changed: ' + cps.map(c => `row ${c.row}${(c.note || '').trim() ? ' — ' + c.note.trim() : ''}`).join('; ') + '.')
|
|
967
|
+
return lines.join('\n')
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function injectCss () {
|
|
971
|
+
if (document.getElementById('rcnspc-css')) return
|
|
972
|
+
const el = document.createElement('style')
|
|
973
|
+
el.id = 'rcnspc-css'
|
|
974
|
+
el.textContent = CSS + `
|
|
975
|
+
.rcnspc .card{padding:10px 10px;margin-bottom:10px}
|
|
976
|
+
.rcnspc .stats{grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:6px}
|
|
977
|
+
.rcnspc details{margin-top:8px;font-size:12px}
|
|
978
|
+
.rcnspc details>summary{cursor:pointer;color:#475569}`
|
|
979
|
+
document.head.appendChild(el)
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// ── drawing ──
|
|
983
|
+
function emit ($item, item) {
|
|
984
|
+
injectCss()
|
|
985
|
+
$item.empty()
|
|
986
|
+
if (!item.session || !item.session.data) {
|
|
987
|
+
$item.append(`
|
|
988
|
+
<div class="rcnspc-empty" style="background:#eee;padding:15px;text-align:center;border:2px dashed transparent">
|
|
989
|
+
<p style="font-weight:bold;margin:0 0 6px">${W.title}</p>
|
|
990
|
+
<p style="color:#666;font-size:.85em;margin:0 0 4px">${W.empty}</p>
|
|
991
|
+
<p style="color:#666;font-size:.85em;margin:0 0 12px">${W.emptyHow}</p>
|
|
992
|
+
<button class="rcnspc-open" style="cursor:pointer">${W.open}</button>
|
|
993
|
+
<div class="rcnspc-msg" style="font-size:12px;color:#92400e;padding-top:6px"></div>
|
|
994
|
+
</div>`)
|
|
995
|
+
return
|
|
996
|
+
}
|
|
997
|
+
const caption = String(item.text || '').split('\n')[0].trim()
|
|
998
|
+
let body = ''
|
|
999
|
+
try { body = RCNSPC.view({ ...item.session, readOnly: true }) } catch (e) { body = `<p style="color:#a83217">${esc(e.message)}</p>` }
|
|
1000
|
+
$item.append(`
|
|
1001
|
+
<div class="rcnspc" style="background:#f5f5f5;padding:8px">
|
|
1002
|
+
${caption ? `<div style="font-weight:600;font-size:14px;margin:0 0 6px">${esc(caption)}</div>` : ''}
|
|
1003
|
+
<div class="rcnspc-body">${body}</div>
|
|
1004
|
+
<div style="padding:6px 0 0;display:flex;gap:6px;justify-content:center">
|
|
1005
|
+
<button class="rcnspc-edit" style="cursor:pointer" title="${esc(W.editTip)}">${W.edit}</button>
|
|
1006
|
+
</div>
|
|
1007
|
+
<div class="rcnspc-msg" style="font-size:12px;color:#92400e;padding-top:4px"></div>
|
|
1008
|
+
</div>`)
|
|
1009
|
+
// Tables fold away on a narrow page; the chart, the numbers and the verdicts stay.
|
|
1010
|
+
$item.find('.rcnspc-body .card').each(function () {
|
|
1011
|
+
const tables = $(this).children('table.sig, div').filter(function () { return this.tagName === 'TABLE' || $(this).children('table.sig, .none').length })
|
|
1012
|
+
if (!tables.length) return
|
|
1013
|
+
const $d = $(`<details><summary>${W.tables}</summary></details>`)
|
|
1014
|
+
tables.first().before($d)
|
|
1015
|
+
$d.append(tables)
|
|
1016
|
+
})
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// ── the tool, and saving ──
|
|
1020
|
+
let popup = null, pendingItem = null, pending$item = null
|
|
1021
|
+
|
|
1022
|
+
function openTool ($item, item) {
|
|
1023
|
+
pendingItem = item; pending$item = $item
|
|
1024
|
+
popup = window.open(item.tool || TOOL_URL, 'rcnspc', 'popup,height=900,width=1400')
|
|
1025
|
+
if (popup) try { popup.focus() } catch (e) {}
|
|
1026
|
+
else $item.find('.rcnspc-msg').text(W.blocked)
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
function save ($item, item) {
|
|
1030
|
+
item.text = describe(item)
|
|
1031
|
+
wiki.pageHandler.put($item.parents('.page:first'), { type: 'edit', id: item.id, item })
|
|
1032
|
+
emit($item, item); bind($item, item)
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function canEdit ($item) {
|
|
1036
|
+
if (!window.isOwner) return false
|
|
1037
|
+
const $p = $item.parents('.page:first')
|
|
1038
|
+
return !$p.hasClass('remote') && !$p.hasClass('ghost')
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// A dropped file becomes a session: a saved session as it is, a CSV as data
|
|
1042
|
+
// with the first column as the order and the first number column charted.
|
|
1043
|
+
function sessionFrom (text, name) {
|
|
1044
|
+
if (/\.json$/i.test(name) || /^\s*\{/.test(text)) {
|
|
1045
|
+
const s = JSON.parse(text)
|
|
1046
|
+
if (!s.data || !Array.isArray(s.data.cols)) throw new Error('not an RCN SPC session')
|
|
1047
|
+
return { format: 'rcn-spc/1', data: s.data, note: s.note || null, settings: s.settings || {}, flags: s.flags || {}, changePoints: s.changePoints || [] }
|
|
1048
|
+
}
|
|
1049
|
+
const d = RCNSPC.parseCSV(text)
|
|
1050
|
+
if (!d || !d.rows.length) throw new Error('first row should be column names, then one row per observation')
|
|
1051
|
+
const nums = d.cols.filter((_, i) => d.rows.some(r => typeof r[i] === 'number'))
|
|
1052
|
+
if (!nums.length) throw new Error('no column of numbers to chart')
|
|
1053
|
+
return { format: 'rcn-spc/1', data: d, note: null, changePoints: [],
|
|
1054
|
+
settings: { chartSel: 'xmr', orderSel: d.cols[0], valueSel: nums[nums.length > 1 && nums[0] === d.cols[0] ? 1 : 0], numSel: nums[nums.length - 1], denSel: nums[0], groupSel: '', scaleInput: '1000', baseInput: '' },
|
|
1055
|
+
flags: { splitChk: false, medianMR: false, laneyChk: false, nelsonChk: true } }
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function bind ($item, item) {
|
|
1059
|
+
$item.off('.rcnspc')
|
|
1060
|
+
$item.on('click.rcnspc', '.rcnspc-open, .rcnspc-edit', e => { e.stopPropagation(); openTool($item, item) })
|
|
1061
|
+
$item.on('dblclick.rcnspc', e => {
|
|
1062
|
+
if ($(e.target).closest('.rcnspc-body, details').length) return
|
|
1063
|
+
wiki.textEditor($item, item)
|
|
1064
|
+
})
|
|
1065
|
+
$item.on('dragover.rcnspc', e => { e.preventDefault(); e.stopPropagation(); $item.find('.rcnspc-empty').css('border-color', '#2f6f5e') })
|
|
1066
|
+
$item.on('dragleave.rcnspc', () => $item.find('.rcnspc-empty').css('border-color', 'transparent'))
|
|
1067
|
+
$item.on('drop.rcnspc', e => {
|
|
1068
|
+
const dt = e.originalEvent && e.originalEvent.dataTransfer, f = dt && dt.files && dt.files[0]
|
|
1069
|
+
if (!f) return
|
|
1070
|
+
e.preventDefault(); e.stopPropagation()
|
|
1071
|
+
if (!canEdit($item)) { $item.find('.rcnspc-msg').text(W.notOwner); return }
|
|
1072
|
+
const rd = new FileReader()
|
|
1073
|
+
rd.onload = () => {
|
|
1074
|
+
try {
|
|
1075
|
+
item.session = sessionFrom(String(rd.result), f.name)
|
|
1076
|
+
if (!String(item.text || '').trim()) item.text = f.name.replace(/\.(spc\.json|json|csv|txt)$/i, '')
|
|
1077
|
+
save($item, item)
|
|
1078
|
+
} catch (err) { $item.find('.rcnspc-msg').text(W.notCsv + err.message) }
|
|
1079
|
+
}
|
|
1080
|
+
rd.readAsText(f)
|
|
1081
|
+
})
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
// ── the tool talks back ──
|
|
1085
|
+
// Only the popup this page opened is listened to.
|
|
1086
|
+
function listener (event) {
|
|
1087
|
+
const d = event.data
|
|
1088
|
+
if (!d || d.toolType !== 'rcn-spc' || !popup || event.source !== popup) return
|
|
1089
|
+
if (d.action === 'ready' && pendingItem) {
|
|
1090
|
+
const $page = pending$item ? pending$item.parents('.page:first') : null
|
|
1091
|
+
const pageTitle = $page ? (($page.data('data') || {}).title || $page.find('h1').first().text().trim() || undefined) : undefined
|
|
1092
|
+
popup.postMessage({ toolType: 'rcn-spc', action: 'loadSession', session: pendingItem.session || null, pageTitle }, '*')
|
|
1093
|
+
} else if (d.action === 'saveSession' && pendingItem && pending$item) {
|
|
1094
|
+
const s = d.session
|
|
1095
|
+
if (!s || !s.data || !Array.isArray(s.data.cols)) return
|
|
1096
|
+
const item = pendingItem, $item = pending$item
|
|
1097
|
+
item.session = { format: 'rcn-spc/1', data: s.data, note: s.note || null, settings: s.settings || {}, flags: s.flags || {}, changePoints: s.changePoints || [] }
|
|
1098
|
+
save($item, item)
|
|
1099
|
+
$item.find('.rcnspc-msg').text(W.savedBack)
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
if (typeof window !== 'undefined') {
|
|
1104
|
+
window.plugins.rcnspc = { emit, bind }
|
|
1105
|
+
if (!window.rcnspcListener) {
|
|
1106
|
+
window.rcnspcListener = listener
|
|
1107
|
+
window.addEventListener('message', listener)
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
})()
|