Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
1335 lines (1238 loc) · 56.1 KB
/
Copy pathindex.html
File metadata and controls
1335 lines (1238 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flow Simulation — Rework Backwash</title>
<style>
* { box-sizing: border-box; }
body {
margin: 0; padding: 0;
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background: #f4f6f8; color: #1f2a37;
}
header { padding: 14px 22px 6px; }
header h1 { margin: 0; font-size: 1.4em; }
header .sub { color: #5d6b7a; margin-top: 2px; font-size: 0.95em; }
#panel {
display: flex; flex-wrap: wrap; gap: 10px 14px; align-items: end;
margin: 10px 16px; padding: 12px 14px;
background: #fff; border: 1px solid #e3e8ee; border-radius: 8px;
}
#panel label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: #5d6b7a; font-weight: 500; }
#panel input, #panel select {
padding: 6px 8px; border: 1px solid #cfd6de; border-radius: 5px;
background: #fff; font-size: 13px; min-width: 110px;
}
#panel input:focus, #panel select:focus { outline: 2px solid #6aa3f0; outline-offset: -1px; border-color: #6aa3f0; }
#panel input:disabled { background: #eef1f4; color: #9aa4af; border-color: #dde3ea; }
#panel .spacer { flex: 1; }
#panel .buttons { display: flex; gap: 6px; }
#panel button {
padding: 7px 14px; border-radius: 5px; border: 1px solid #4a90e2; background: #4a90e2; color: #fff;
font-weight: 500; cursor: pointer; font-size: 13px;
}
#panel button.secondary { background: #fff; color: #4a90e2; }
#panel button:hover { filter: brightness(1.05); }
#statusBar {
margin: 0 16px 10px; padding: 8px 14px; border-radius: 6px;
display: flex; flex-wrap: wrap; gap: 6px 18px; align-items: center; font-size: 13px;
}
/* Fixed-height bar: the message changes length with every state change and
wraps on narrow windows — without reserved space the bar's height jumps
and the whole page below it wiggles. (Thanks Tim.) The text row always
reserves exactly two lines and can never grow past two; the pills always
sit on their own row. Constant height at any width. */
#statusTop { flex: 1 1 100%; display: flex; gap: 10px; align-items: flex-start; }
#statePill {
flex: 0 0 auto; margin-top: 1px;
padding: 2px 10px; border-radius: 10px;
font-weight: 700; font-size: 11px; letter-spacing: 0.05em; text-transform: uppercase;
color: #fff; background: #6b7683;
}
#statusText {
flex: 1 1 auto;
min-height: 2.9em;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
#statusBar .pill { white-space: nowrap; font-variant-numeric: tabular-nums; }
/* The full-width state timeline: one colored tick per day, under the banner. */
#stateStrip {
display: block; width: calc(100% - 32px); height: 14px;
margin: 0 16px 10px; border-radius: 3px; background: #e7ebef;
}
.status-normal { background: #e3f7ec; border: 1px solid #9dd9b7; color: #1c5b34; }
.status-balking { background: #fff3d9; border: 1px solid #e8c275; color: #7a5a14; }
.status-collapse { background: #fbe1dd; border: 1px solid #e89687; color: #7a2c1b; }
#statusBar .pill { background: rgba(0,0,0,0.06); padding: 2px 8px; border-radius: 10px; font-weight: 600; }
#main { display: grid; grid-template-columns: 1fr 320px; gap: 12px; margin: 0 16px 12px; }
@media (max-width: 1100px) { #main { grid-template-columns: 1fr; } }
.card { background: #fff; border: 1px solid #e3e8ee; border-radius: 8px; }
#canvasWrap { padding: 6px; }
#simCanvas { display: block; width: 100%; height: auto; }
#side { display: flex; flex-direction: column; gap: 12px; }
.metric-card { padding: 12px 14px; }
.metric-card h3 {
margin: 0 0 8px; font-size: 12px; letter-spacing: 0.05em; text-transform: uppercase;
color: #5d6b7a; border-bottom: 1px solid #eef1f5; padding-bottom: 6px;
}
.metric-card .row { display: flex; justify-content: space-between; padding: 3px 0; font-size: 13px; }
.metric-card .row b { font-variant-numeric: tabular-nums; color: #1f2a37; }
.metric-card .row.muted { color: #7c8794; }
#chartCard { padding: 8px; }
#chartCard canvas { display: block; width: 100%; height: 180px; }
#chartCard .legend { display: flex; gap: 14px; justify-content: center; font-size: 12px; color: #5d6b7a; margin-top: 4px; }
.swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; vertical-align: middle; margin-right: 4px; }
details { margin: 0 16px 24px; padding: 10px 14px; background: #fff; border: 1px solid #e3e8ee; border-radius: 8px; }
details summary { cursor: pointer; font-weight: 600; color: #1f2a37; }
details p, details ul { color: #4a5662; margin: 8px 0; }
details ul { padding-left: 22px; }
</style>
</head>
<body>
<header>
<h1>The Defect Circulatron 3000 — the rework backwash effect</h1>
<div class="sub">One process box. Arrivals head straight for Production; they only divert to the Product Backlog when Production balks at capacity — and defects loop back to the pull switch. Watch what 33% rework does to throughput — not 33% slower, but a cliff.</div>
</header>
<div id="panel">
<label>Arrival mode
<select id="arrivalMode">
<option value="poisson" selected>Poisson</option>
<option value="deterministic">Deterministic</option>
</select>
</label>
<label>Arrival rate (/day)
<input id="arrivalRate" type="number" min="0" step="0.1" value="9">
</label>
<label>Process rate (/day)
<input id="processRate" type="number" min="1" step="1" value="10">
</label>
<label>Defect rate (0–1)
<input id="defectRate" type="number" min="0" max="1" step="0.01" value="0.10">
</label>
<label>Rework policy
<select id="reworkPolicy">
<option value="proportional" selected>Proportional (mix ratio)</option>
<option value="1perN">1 rework per N new</option>
<option value="priority">Defect-first (rework cuts the line)</option>
</select>
</label>
<label><span id="mixLabel">Mix (0–1)</span>
<input id="mixParam" type="number" min="0" step="0.05" value="0.10">
</label>
<label>Speed (ms/day)
<input id="dayMs" type="number" min="60" step="20" value="2000">
</label>
<div class="spacer"></div>
<div class="buttons">
<button id="startBtn">Start</button>
<button id="pauseBtn" class="secondary">Pause</button>
<button id="resetBtn" class="secondary">Reset</button>
</div>
</div>
<div id="statusBar" class="status-normal">
<div id="statusTop">
<span id="statePill">Idle</span>
<span id="statusText">Idle — press Start</span>
</div>
<span class="pill">Day <span id="dayPill">0</span></span>
<span class="pill">Effective arrival <span id="arrPill">—</span></span>
<span class="pill">Effective intake <span id="intakePill">—</span></span>
<span class="pill">Utilization <span id="utilPill">0%</span></span>
<span class="pill">Rework load <span id="reworkPill">0%</span></span>
</div>
<canvas id="stateStrip" width="1280" height="14" title="One tick per day: green stable, amber critical, red supercritical — watch the flicker frequency"></canvas>
<div id="main">
<div class="card" id="canvasWrap">
<canvas id="simCanvas" width="1280" height="640"></canvas>
</div>
<div id="side">
<div class="card metric-card">
<h3>Throughput</h3>
<div class="row"><span>Day</span><b id="mDay">0</b></div>
<div class="row"><span>Shipped (total)</span><b id="mShipped">0</b></div>
<div class="row"><span>Shipped / day (rolling)</span><b id="mTput">—</b></div>
<div class="row muted"><span>Sustainable rate †</span><b id="mCeiling">—</b></div>
<div class="row muted"><span>Drag vs sustainable</span><b id="mLost">—</b></div>
</div>
<div class="card metric-card">
<h3>Lead time</h3>
<div class="row"><span>Avg lead time (days)</span><b id="mLead">—</b></div>
<div class="row"><span>85th %ile lead time</span><b id="mLeadP85">—</b></div>
<div class="row"><span>Worst</span><b id="mLeadMax">—</b></div>
</div>
<div class="card metric-card">
<h3>Queues & WIP</h3>
<div class="row"><span>Product backlog</span><b id="mBacklog">0</b></div>
<div class="row"><span>Defect queue</span><b id="mDefects">0</b></div>
<div class="row"><span>In process</span><b id="mInProc">0</b></div>
<div class="row"><span>Total WIP</span><b id="mWip">0</b></div>
</div>
<div class="card metric-card">
<h3>Defects</h3>
<div class="row"><span>Created (cumulative)</span><b id="mDefCreated">0</b></div>
<div class="row"><span>Rework cycles (cumulative)</span><b id="mReworkDone">0</b></div>
<div class="row muted"><span>Avg rework / shipped item</span><b id="mReworkPer">0.00</b></div>
</div>
<div class="card" id="chartCard">
<canvas id="chartCanvas" width="640" height="360"></canvas>
<div class="legend">
<span><span class="swatch" style="background:#2f7d39"></span>Cumulative shipped</span>
<span><span class="swatch" style="background:#aaa"></span>Counterfactual ceiling</span>
<span><span class="swatch" style="background:#e89320"></span>Product Backlog depth</span>
</div>
</div>
</div>
</div>
<details open>
<summary>What this is showing — and why "33% rework" doesn't mean "33% slower"</summary>
<p>This is a single-station queueing model with feedback. Items arrive at rate <b>λ</b>, the team works at rate <b>μ</b>, and a fraction <b>d</b> of completed items come back to be reworked.</p>
<p>Arrivals head straight for Production. The balk turnout only sends an item up to the Product Backlog when Production is at capacity — or when the backlog already holds someone (strict FIFO, no line-jumping). The team pulls waiting work into Process at the <b>switch</b>, where two lines merge: items pulled down from the backlog, and defects climbing back up from the Defect Queue for another full pass. The rework policy sets the switch. Because every defect must be served again, rework doesn't add arrivals — it multiplies <em>passes</em>: the team's total service demand is <b>λ / (1 − d)</b> passes per day (new items plus the repeat passes defects buy). Utilization is <b>ρ = demand / μ</b>. As ρ approaches 1, queues grow without bound — the bottleneck collapses.</p>
<ul>
<li>λ=9, μ=10, d=0 → ρ = 0.90 (comfortable)</li>
<li>λ=9, μ=10, d=0.10 → ρ = 1.00 (on the edge)</li>
<li>λ=9, μ=10, d=0.33 → ρ = 1.34 (system can't keep up — queues grow forever)</li>
</ul>
<p><b>Arrival mode:</b> Poisson (the default) makes the daily count random with mean λ: some days 6, some days 13 — like real demand. At high utilization those bursts queue up even with zero defects: variance × utilization = queues, its own lesson. Switch to deterministic for exactly λ items every day — the cleanest way to isolate what rework alone does.</p>
<p>† <b>Sustainable rate</b> = <code>min(λ, μ·(1−d))</code> — the most the team can ship per day in steady state. If λ is low enough that arrivals are the bottleneck, this equals λ. If rework is eating capacity, it's lower. The <b>drag</b> stat compares actual rolling throughput to this number.</p>
<p><b>Symbols inside the dots</b> (1…9, 0, A…Z, a…z) are item IDs — lets you track an individual unit of work through the system. A white ring around a dot means it has been reworked at least once.</p>
</details>
<script>
"use strict";
// ===================================================================
// LAYOUT
// ===================================================================
const W = 1280, H = 640;
// All horizontal flow is on y=380. Arrivals ride the mainline straight at
// Production. The turnout up to the Product Backlog (x=340) only throws when
// Production balks at capacity (or someone is already waiting — no
// line-jumping). The PBL pull comes down at x=430 and defect rework climbs
// up at x=430, merging at the SWITCH that feeds Process.
const layout = {
arrivalStart: { x: 30, y: 380 },
pblTurn: { x: 340, y: 380 }, // the balk turnout: arrivals divert up to the PBL here ONLY when Production is full
switchNode: { x: 430, y: 380 }, // THE SWITCH: PBL pull (from above) + rework (from below) merge here
processIn: { x: 600, y: 380 },
processOut: { x: 960, y: 380 },
defectOut: { x: 960, y: 430 }, // defects leave Production by their OWN lower door — no shared outlet with the ship track
shipTurn: { x:1180, y: 380 },
shipTop: { x:1180, y: 130 },
defectTurn1: { x:1080, y: 430 },
defectTurn2: { x:1080, y: 520 },
defectBoxRight:{x: 450, y: 520 },
// Connection points on the queue boxes
pblEnter: { x: 340, y: 200 }, // bottom of backlog, left side (arrivals in)
pullExit: { x: 430, y: 200 }, // bottom of backlog, right side (pulls out, straight down to the switch)
defectExit: { x: 430, y: 440 }, // top of defect queue (straight up to the switch)
backlogBox: { x: 130, y: 21, w: 320, h: 179 }, // bottom edge stays at y=200 where both tracks connect
processBox: { x: 560, y: 280, w: 400, h: 200 },
defectBox: { x: 250, y: 440, w: 200, h: 140 },
shippedBox: { x: 1080, y: 60, w: 200, h: 140 },
};
// Polylines for each transit phase (start -> end). ARRIVING ends at the balk
// turnout, where the admission decision fires: continue on the mainline into
// Process (ENTERING) or divert up to the backlog (DIVERTING). Pull comes down
// and rework comes up on the shared x=430 column, merging at the switch.
const paths = {
ARRIVING: [layout.arrivalStart, layout.pblTurn],
ENTERING: [layout.pblTurn, layout.switchNode, layout.processIn],
DIVERTING: [layout.pblTurn, layout.pblEnter],
PULLING: [layout.pullExit, layout.switchNode, layout.processIn],
SHIPPING: [layout.processOut, layout.shipTurn, layout.shipTop],
DEFECTING: [layout.defectOut, layout.defectTurn1, layout.defectTurn2, layout.defectBoxRight],
REWORKING: [layout.defectExit, layout.switchNode, layout.processIn],
};
// ===================================================================
// HELPERS
// ===================================================================
function poissonSample(lambda) {
if (lambda <= 0) return 0;
// Knuth
const L = Math.exp(-lambda);
let k = 0, p = 1;
do { k++; p *= Math.random(); } while (p > L);
return k - 1;
}
function lerp(a, b, t) { return a + (b - a) * t; }
function polylineLength(pts) {
let L = 0;
for (let i = 1; i < pts.length; i++) {
L += Math.hypot(pts[i].x - pts[i-1].x, pts[i].y - pts[i-1].y);
}
return L;
}
function pointAlongPolyline(pts, t) {
// t in [0,1]
if (t <= 0) return { x: pts[0].x, y: pts[0].y };
if (t >= 1) return { x: pts[pts.length-1].x, y: pts[pts.length-1].y };
const total = polylineLength(pts);
let target = t * total;
for (let i = 1; i < pts.length; i++) {
const seg = Math.hypot(pts[i].x - pts[i-1].x, pts[i].y - pts[i-1].y);
if (target <= seg) {
const f = target / seg;
return { x: lerp(pts[i-1].x, pts[i].x, f), y: lerp(pts[i-1].y, pts[i].y, f) };
}
target -= seg;
}
return { x: pts[pts.length-1].x, y: pts[pts.length-1].y };
}
function percentile(arr, p) {
if (arr.length === 0) return null;
const sorted = [...arr].sort((a,b) => a - b);
const idx = Math.min(sorted.length - 1, Math.floor(p * sorted.length));
return sorted[idx];
}
// ===================================================================
// SIM STATE
// ===================================================================
let state;
function freshState() {
return {
day: 0,
running: false,
lastTickMs: 0,
items: new Map(),
nextId: 1,
// Queues (arrays of item ids in FIFO order)
backlog: [],
defectQueue: [],
inProcess: [],
shipped: [],
// Stats
backlogHist: [], // backlog depth per day — the banner's collapse signal is OBSERVED growth, not parameter math
intakeSinceTick: 0, // passes entering Process since last tick (direct entries + pulls + rework)
dailyArrivals: [], // measured arrivals per day
dailyIntake: [], // measured intake (passes) per day
totalShipped: 0,
totalDefectsCreated: 0,
totalReworkCycles: 0,
leadTimes: [],
dailyShipped: [], // shipped count per day
history: { // for chart
day: [], shipped: [], defects: [], ceiling: [], backlog: [], level: [],
},
// For "items arriving at door this tick", we track items in ARRIVING transit
// and they get admitted when they reach the door.
};
}
// Labels: 1-9, 0, A-Z, a-z (61 unique chars before recycling)
const LABEL_CHARS = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function makeItem() {
const id = state.nextId++;
const item = {
id,
label: LABEL_CHARS[id % LABEL_CHARS.length],
color: "#9aa6b2", // gray initially
phase: "ARRIVING",
phaseStartMs: performance.now(),
fromPos: { ...layout.arrivalStart },
toPos: { ...layout.pblTurn },
path: paths.ARRIVING,
parkedPos: null,
createdDay: state.day,
reworkCount: 0,
// Persistent y-jitter so simultaneous items render as distinct dots
yJitter: (Math.random() - 0.5) * 28,
xJitter: (Math.random() - 0.5) * 14,
};
state.items.set(id, item);
return item;
}
// Set an item into a transit phase. The new path leads from the item's
// CURRENT visual position (whether parked or mid-tween) so transitions are
// always visually smooth — no teleport.
function setTransit(item, phaseName) {
let currentPos = null;
if (item.path) {
// mid-tween: figure out where the item actually is right now
const dur = item.tweenDurationMs || 1000;
const t = Math.max(0, Math.min(1, (performance.now() - item.phaseStartMs) / dur));
const p = pointAlongPolyline(item.path, t);
currentPos = { x: p.x, y: p.y };
} else if (item.parkedPos) {
currentPos = { x: item.parkedPos.x, y: item.parkedPos.y };
}
const base = paths[phaseName];
item.phase = phaseName;
item.path = currentPos ? [currentPos, ...base] : base;
item.fromPos = item.path[0];
item.toPos = item.path[item.path.length - 1];
item.phaseStartMs = performance.now();
item.parkedPos = null;
item.tweenDurationMs = null; // caller may override
}
// Park item in a queue slot. Fill the box in a grid sized from the box
// itself; once the box is full, overflow marches LEFT out of the box (and
// off the canvas — an unbounded queue should look unbounded), never down
// across the tracks.
function parkInBox(item, phaseName, box, indexInQueue) {
item.phase = phaseName;
item.path = null;
const cellW = 28, cellH = 21;
const cols = Math.max(1, Math.floor((box.w - 24) / cellW));
const maxRows = Math.max(1, Math.floor((box.h - 32) / cellH));
const capacity = cols * maxRows;
let x, y;
if (indexInQueue < capacity) {
const col = indexInQueue % cols;
const row = Math.floor(indexInQueue / cols);
x = box.x + 18 + col * cellW;
y = box.y + 26 + row * cellH;
} else {
const oIdx = indexInQueue - capacity;
const oCol = Math.floor(oIdx / maxRows);
const oRow = oIdx % maxRows;
x = box.x - 18 - oCol * cellW;
y = box.y + 26 + oRow * cellH;
}
item.parkedPos = { x, y };
item.phaseStartMs = performance.now();
item.fromPos = item.parkedPos;
item.toPos = item.parkedPos;
}
function parkInProcess(item, indexInQueue) {
const box = layout.processBox;
const cols = 8;
const cellW = 42, cellH = 32;
const col = indexInQueue % cols;
const row = Math.floor(indexInQueue / cols);
const x = box.x + 30 + col * cellW;
const y = box.y + 40 + row * cellH;
item.phase = "IN_PROCESS";
item.path = null;
item.parkedPos = { x, y };
item.phaseStartMs = performance.now();
item.fromPos = item.parkedPos;
item.toPos = item.parkedPos;
}
function parkInShipped(item, indexInQueue) {
const box = layout.shippedBox;
const cols = 6, cellW = 28, cellH = 22;
const col = indexInQueue % cols;
const row = Math.floor(indexInQueue / cols);
// Cap visual stacking; older items just sit in same last slot
const cappedRow = Math.min(row, 4);
const x = box.x + 18 + col * cellW;
const y = box.y + 30 + cappedRow * cellH;
item.phase = "IN_SHIPPED";
item.path = null;
item.parkedPos = { x, y };
item.phaseStartMs = performance.now();
item.fromPos = item.parkedPos;
item.toPos = item.parkedPos;
}
// ===================================================================
// SIMULATION TICK
// ===================================================================
function readParams() {
return {
arrivalMode: document.getElementById("arrivalMode").value,
arrivalRate: Math.max(0, parseFloat(document.getElementById("arrivalRate").value) || 0),
processRate: Math.max(1, Math.round(parseFloat(document.getElementById("processRate").value) || 1)),
defectRate: Math.max(0, Math.min(1, parseFloat(document.getElementById("defectRate").value) || 0)),
reworkPolicy: document.getElementById("reworkPolicy").value,
mixParam: Math.max(0, parseFloat(document.getElementById("mixParam").value) || 0),
dayMs: Math.max(60, parseInt(document.getElementById("dayMs").value) || 400),
};
}
// EVENT-DRIVEN MODEL:
// - simTick fires once per "day" (every dayMs ms). It handles end-of-day
// events (items in Process ship), start-of-day events (pull from PBL /
// defect queue at the switch), and spawns the day's arrivals with
// staggered times across the day. Arrivals head straight for Production;
// the balk turnout only sends them to the PBL when Production is full
// (or the queue is non-empty — strict FIFO, no line-jumping).
// - checkItemTransitions runs every frame. When an item's tween reaches
// t=1, its phase transition fires — the admission decision (ARRIVING
// done), park-into-process (ENTERING/PULLING/REWORKING done),
// park-into-backlog (DIVERTING done), park-into-defect-queue (DEFECTING
// done), or park-into-shipped (SHIPPING done).
// - state.inProcess always holds every item logically occupying a Process
// slot, even while it's still tweening in.
// - state.backlog holds items actually parked in the backlog box; arrivals
// still in flight join it when their ARRIVING tween completes.
function simTick(P) {
let shippedThisTick = 0;
// 0. SETTLE THE DAY THAT JUST ENDED. Every arrival spawned during it
// reaches the turnout before the day is over, so any still riding in
// (only possible if frames stalled) takes its admission decision now, in
// arrival order, against the slots as they stand at end of day. Defects
// created at the last tick are in the queue by morning, landed or not.
// After this block the sim's numbers are a function of parameters and
// random draws only — frame rate cannot change them.
for (const it of state.items.values()) {
if (it.phase === "ARRIVING") handleTransitComplete(it, P);
}
const defectsInFlight = [];
for (const it of state.items.values()) {
if (it.phase === "DEFECTING") defectsInFlight.push(it.id);
}
// Defect-queue depth at dawn — BEFORE the morning pull drains it. This is
// the chart's series; sampling after the pull always reads 0 under
// defect-first policy.
const defectsWaitingAtDawn = state.defectQueue.length + defectsInFlight.length;
// Close out the day that just ended: bank its measured intake tally.
state.dailyIntake.push(state.intakeSinceTick);
state.intakeSinceTick = 0;
if (state.dailyIntake.length > 60) state.dailyIntake.shift();
// 1. END OF DAY: every item admitted to Process during the day completes
// its work and ships (or defects) — including any whose entry tween
// hasn't visually landed yet. Admission is decided at the turnout; the
// animation never decides the logic. (Filtering on the parked phase here
// let one slow frame at the tick strand the last arrival, carry two
// items over, divert the next day's 9th, and lock the sim into routing
// everything through the backlog — the 9-in/10-cap "balk" that wasn't.)
const completing = state.inProcess.slice();
for (const id of completing) {
const idx = state.inProcess.indexOf(id);
if (idx >= 0) state.inProcess.splice(idx, 1);
const item = state.items.get(id);
if (Math.random() < P.defectRate) {
item.color = "#cc4a3a";
item.reworkCount++;
state.totalDefectsCreated++;
setTransit(item, "DEFECTING");
item.tweenDurationMs = 0.4 * P.dayMs;
} else {
item.color = "#2f7d39";
setTransit(item, "SHIPPING");
item.tweenDurationMs = 0.5 * P.dayMs;
// Count this as a ship NOW (work completed at tick boundary). The
// SHIPPING animation is visual-only; the throughput tally happens here.
state.totalShipped++;
shippedThisTick++;
state.leadTimes.push(state.day - item.createdDay);
if (state.leadTimes.length > 500) state.leadTimes.shift();
}
}
// 2. START OF DAY: with Process slots now (mostly) freed, pull from backlog
// FIFO. Only items actually parked in the backlog box are eligible —
// items still in ARRIVING transit haven't landed yet.
const capacity = P.processRate;
let slotsAvailable = Math.max(0, capacity - state.inProcess.length);
// 2a. Rework pull from defect queue (policy-controlled).
let reworkSlots = 0;
const eligibleDefects = state.defectQueue.filter(id => state.items.get(id)?.phase === "IN_DEFECT_QUEUE").concat(defectsInFlight);
if (eligibleDefects.length > 0 && slotsAvailable > 0) {
if (P.reworkPolicy === "priority") {
reworkSlots = Math.min(eligibleDefects.length, slotsAvailable);
} else if (P.reworkPolicy === "proportional") {
let rs = 0;
for (let i = 0; i < slotsAvailable && rs < eligibleDefects.length; i++) {
if (Math.random() < P.mixParam) rs++;
}
reworkSlots = rs;
} else if (P.reworkPolicy === "1perN") {
const N = Math.max(1, P.mixParam);
reworkSlots = Math.min(eligibleDefects.length, Math.max(1, Math.floor(slotsAvailable / (N + 1))));
}
}
for (let i = 0; i < reworkSlots; i++) {
const id = eligibleDefects[i];
const dIdx = state.defectQueue.indexOf(id);
if (dIdx >= 0) state.defectQueue.splice(dIdx, 1);
const it = state.items.get(id);
setTransit(it, "REWORKING");
// Staggered, visible flight: the red train climbs from the defect queue
// through the switch. All aboard well before the next tick.
it.tweenDurationMs = Math.min(0.35, 0.12 + 0.04 * i) * P.dayMs;
state.inProcess.push(id);
state.intakeSinceTick++;
}
slotsAvailable -= reworkSlots;
// 2b. Backlog pull (FIFO): items parked in the box, then items diverted
// today that are still riding up the track — they were turned away
// before the day ended, so they are in the queue by morning whether or
// not the dot has landed. (Otherwise a late diverter lands after the
// pull, the strict-FIFO gate sees a non-empty backlog, and every
// arrival diverts from then on.)
const eligibleBacklog = state.backlog.filter(id => state.items.get(id)?.phase === "IN_BACKLOG");
for (const it of state.items.values()) if (it.phase === "DIVERTING") eligibleBacklog.push(it.id);
const pullCount = Math.min(slotsAvailable, eligibleBacklog.length);
for (let i = 0; i < pullCount; i++) {
const id = eligibleBacklog[i];
const bIdx = state.backlog.indexOf(id);
if (bIdx >= 0) state.backlog.splice(bIdx, 1);
const it = state.items.get(id);
setTransit(it, "PULLING");
// Staggered, visible flight: the gray train rides down from the backlog
// through the switch — no more instant same-slot refill that read as
// "ghost dots" left behind by the shipping greens.
it.tweenDurationMs = Math.min(0.4, 0.15 + 0.03 * i) * P.dayMs;
state.inProcess.push(id);
state.intakeSinceTick++;
}
// 3. SPAWN THIS DAY'S ARRIVALS. Each item reaches the Product Backlog at a
// different fraction of the day — item i of N lands at (i+1)/(N+1) of
// the day. It becomes pullable at the next start-of-day.
let arrivals;
if (P.arrivalMode === "deterministic") {
arrivals = Math.round(P.arrivalRate);
} else {
arrivals = poissonSample(P.arrivalRate);
}
const tickStart = performance.now();
for (let i = 0; i < arrivals; i++) {
const item = makeItem();
item.phaseStartMs = tickStart;
item.tweenDurationMs = ((i + 1) / (arrivals + 1)) * P.dayMs;
}
state.dailyArrivals.push(arrivals);
if (state.dailyArrivals.length > 60) state.dailyArrivals.shift();
// 4. RE-PARK already-parked items into their (possibly shifted) slot positions.
state.backlog.forEach((id, idx) => {
const it = state.items.get(id);
if (it && it.phase === "IN_BACKLOG") parkInBox(it, "IN_BACKLOG", layout.backlogBox, idx);
});
state.defectQueue.forEach((id, idx) => {
const it = state.items.get(id);
if (it && it.phase === "IN_DEFECT_QUEUE") parkInBox(it, "IN_DEFECT_QUEUE", layout.defectBox, idx);
});
state.inProcess.forEach((id, idx) => {
const it = state.items.get(id);
if (it && it.phase === "IN_PROCESS") parkInProcess(it, idx);
});
while (state.shipped.length > 80) {
const oldId = state.shipped.shift();
state.items.delete(oldId);
}
state.shipped.forEach((id, idx) => {
const it = state.items.get(id);
if (it && it.phase === "IN_SHIPPED") parkInShipped(it, idx);
});
state.dailyShipped.push(shippedThisTick);
if (state.dailyShipped.length > 200) state.dailyShipped.shift();
// 5. Chart history.
state.history.day.push(state.day);
state.history.shipped.push(state.totalShipped);
state.history.defects.push(defectsWaitingAtDawn);
state.history.backlog.push(state.backlog.length);
const ceilingPerDay = Math.min(P.arrivalRate, P.processRate);
const prevCeiling = state.history.ceiling.length === 0 ? 0 : state.history.ceiling[state.history.ceiling.length - 1];
state.history.ceiling.push(prevCeiling + ceilingPerDay);
if (state.history.day.length > 400) {
state.history.day.shift();
state.history.shipped.shift();
state.history.defects.shift();
state.history.ceiling.shift();
state.history.backlog.shift();
}
state.day++;
// Queue pressure = the backlog still holds work this tick's pull couldn't
// take — i.e., something waited a FULL day and still didn't get in.
// Mid-day balks alone don't count: arrivals routing through the PBL
// overnight is normal cadence in a stable system, not distress.
const queuePressure = (eligibleBacklog.length - pullCount) > 0;
state.backlogHist.push(state.backlog.length);
if (state.backlogHist.length > 60) state.backlogHist.shift();
// Classify today's observed state (0 stable / 1 critical / 2 supercritical)
// — drives the banner AND the per-day state strip on the chart. The strip's
// flicker frequency IS the early warning: solid green, blinking amber,
// solid red.
const bhh = state.backlogHist;
const bGrowth = state.backlog.length - (bhh.length >= 8 ? bhh[bhh.length - 8] : 0);
const dhh = state.history.defects;
const dGrowth = (dhh.length ? dhh[dhh.length - 1] : 0) - (dhh.length >= 8 ? dhh[dhh.length - 8] : 0);
const dqNow = state.defectQueue.length;
let level = 0, reason = "stable";
if (bhh.length >= 8 && bGrowth >= 5 && state.backlog.length >= 8) { level = 2; reason = "backlog-collapse"; }
else if (dhh.length >= 8 && dGrowth >= 5 && dqNow >= 8) { level = 2; reason = "defect-collapse"; }
else if (queuePressure) { level = 1; reason = "pressure"; }
else if (dqNow >= 10 || (dhh.length >= 8 && dGrowth >= 2 && dqNow >= 5)) { level = 1; reason = "rework-debt"; }
state.history.level.push(level);
if (state.history.level.length > 400) state.history.level.shift();
return { queuePressure, capacity, reworkSlots, pulledFromBacklog: pullCount,
level, reason, bGrowth, dGrowth, dqNow };
}
// EVENT-DRIVEN per-frame transition checks. Runs every RAF frame, before
// rendering. Whenever an item's tween completes (t >= 1), fire its phase
// transition immediately — admission decisions happen at the moment the item
// reaches the door, not at tick boundaries.
function checkItemTransitions(now, P) {
for (const item of state.items.values()) {
if (!item.path) continue; // parked items have no path; skip
const dur = item.tweenDurationMs || P.dayMs;
if ((now - item.phaseStartMs) >= dur) {
handleTransitComplete(item, P);
}
}
}
function handleTransitComplete(item, P) {
switch (item.phase) {
case "ARRIVING": {
// Reached the balk turnout. The track only switches to the Product
// Backlog when Production balks at capacity — or when someone is
// already waiting there (strict FIFO, no line-jumping past the queue).
const slotsUsed = state.inProcess.length;
const backlogEmpty = state.backlog.length === 0;
// Late arrivals get a shorter ride so the dot is parked before the day
// ends (the tick settles the logic either way; this keeps the picture
// honest).
const msLeft = P.dayMs - (performance.now() - state.lastTickMs);
const landByTick = d => Math.max(0.04 * P.dayMs, Math.min(d, msLeft - 40));
if (slotsUsed < P.processRate && backlogEmpty) {
setTransit(item, "ENTERING");
item.tweenDurationMs = landByTick(0.18 * P.dayMs);
state.inProcess.push(item.id);
state.intakeSinceTick++;
} else {
setTransit(item, "DIVERTING");
item.tweenDurationMs = landByTick(0.2 * P.dayMs);
// Joins state.backlog when the DIVERTING tween completes — the box
// list stays the single source of truth for "actually in the queue."
}
break;
}
case "DIVERTING": {
// Reached the backlog box. NOW it counts as IN_BACKLOG.
state.backlog.push(item.id);
parkInBox(item, "IN_BACKLOG", layout.backlogBox, state.backlog.length - 1);
break;
}
case "ENTERING":
case "PULLING":
case "REWORKING": {
// Reached Process slot. Park in grid.
const idx = state.inProcess.indexOf(item.id);
parkInProcess(item, idx >= 0 ? idx : state.inProcess.length);
break;
}
case "SHIPPING": {
// Reached Shipped box. Park. (Throughput was already counted at simTick.)
state.shipped.push(item.id);
parkInShipped(item, state.shipped.length - 1);
break;
}
case "DEFECTING": {
// Reached defect queue. Park.
state.defectQueue.push(item.id);
parkInBox(item, "IN_DEFECT_QUEUE", layout.defectBox, state.defectQueue.length - 1);
break;
}
}
}
// ===================================================================
// RENDERING
// ===================================================================
const canvas = document.getElementById("simCanvas");
const ctx = canvas.getContext("2d");
function fitCanvas() {
// Keep internal resolution at W,H. CSS scales it.
canvas.width = W;
canvas.height = H;
}
function roundRect(x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function drawArrow(from, to, color, width=2) {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
// arrowhead
const ang = Math.atan2(to.y - from.y, to.x - from.x);
const h = 8;
ctx.beginPath();
ctx.moveTo(to.x, to.y);
ctx.lineTo(to.x - h * Math.cos(ang - Math.PI/7), to.y - h * Math.sin(ang - Math.PI/7));
ctx.lineTo(to.x - h * Math.cos(ang + Math.PI/7), to.y - h * Math.sin(ang + Math.PI/7));
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
function drawPolyArrow(pts, color, width=2) {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y);
ctx.stroke();
// arrowhead at end
const a = pts[pts.length - 2], b = pts[pts.length - 1];
const ang = Math.atan2(b.y - a.y, b.x - a.x);
const h = 9;
ctx.beginPath();
ctx.moveTo(b.x, b.y);
ctx.lineTo(b.x - h * Math.cos(ang - Math.PI/7), b.y - h * Math.sin(ang - Math.PI/7));
ctx.lineTo(b.x - h * Math.cos(ang + Math.PI/7), b.y - h * Math.sin(ang + Math.PI/7));
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
function drawBox(box, title, countText, fill, stroke) {
ctx.fillStyle = fill;
ctx.strokeStyle = stroke;
ctx.lineWidth = 1.5;
roundRect(box.x, box.y, box.w, box.h, 10);
ctx.fill();
ctx.stroke();
// title above
ctx.fillStyle = "#1f2a37";
ctx.font = "600 14px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "alphabetic";
ctx.fillText(title, box.x + box.w / 2, box.y - 8);
// count in corner
ctx.fillStyle = "#5d6b7a";
ctx.font = "600 13px system-ui";
ctx.textAlign = "right";
ctx.fillText(countText, box.x + box.w - 10, box.y + 18);
}
function drawDiagram(queuePressure) {
ctx.clearRect(0, 0, W, H);
// --- Arrows (drawn first, behind boxes) ---
const arrivalColor = "#5d6b7a";
const goodColor = "#2f7d39";
const defectColor = "#cc4a3a";
const pullColor = "#4a90e2";
const feedColor = "#8a8676";
const pblColor = queuePressure ? "#e89320" : arrivalColor;
// 0. The mainline — ONE continuous track from the left edge to Process.
// It runs unbroken under the backlog's in (x=340) and out (x=430)
// verticals; those are turnouts off the mainline, not breaks in it.
ctx.strokeStyle = feedColor;
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.moveTo(layout.arrivalStart.x, layout.arrivalStart.y);
ctx.lineTo(layout.processIn.x, layout.processIn.y);
ctx.stroke();
// 1. The balk turnout (light gray when idle; orange when arrivals are
// being diverted): only throws when Production balks at capacity.
drawPolyArrow([layout.pblTurn, layout.pblEnter], queuePressure ? "#e89320" : "#bcc3cc", queuePressure ? 3 : 1.8);
// 2. Pull DOWN (blue, ↓ ): backlog bottom -> the switch
drawPolyArrow([layout.pullExit, layout.switchNode], pullColor, 2);
// 3. Rework UP (red, ↑ ): defect queue top -> the same switch
drawPolyArrow([layout.defectExit, layout.switchNode], defectColor, 2);
// 4. Feed (dark, → ): switch -> Process
drawPolyArrow([layout.switchNode, layout.processIn], feedColor, 2.5);
// 5. Process -> shipped (green, → ↑ )
drawPolyArrow([layout.processOut, layout.shipTurn, layout.shipTop], goodColor, 2.5);
// 6. Process -> defect queue (red, → ↓ ← ) — leaves by its own lower door,
// visually distinct from the green ship track above it.
drawPolyArrow([layout.defectOut, layout.defectTurn1, layout.defectTurn2, layout.defectBoxRight], defectColor, 2.5);
// --- Boxes ---
drawBox(layout.backlogBox, "Product Backlog",
`${state.backlog.length}`, "#f1f5fb", "#bcc8d6");
// "In the system" = committed past the balk turnout, not yet done — some
// of those dots are still riding the track toward the box. Show both so
// the count reconciles with the eye.
let inbound = 0;
for (const id of state.inProcess) {
const it = state.items.get(id);
if (it && it.phase !== "IN_PROCESS") inbound++;
}
const parked = state.inProcess.length - inbound;
drawBox(layout.processBox, "Process (the team)",
inbound > 0 ? `${parked} in + ${inbound} inbound / cap ${readParams().processRate}`
: `${parked} in / cap ${readParams().processRate}`, "#eaf7ef", "#9dd9b7");
drawBox(layout.defectBox, "Defect Queue",
`${state.defectQueue.length}`, "#fdecea", "#e89687");
drawBox(layout.shippedBox, "Shipped",
`${state.totalShipped}`, "#eaf7ef", "#9dd9b7");
// THE SWITCH — one node feeds Process; the rework policy decides whether
// the next open slot pulls from the backlog (blue) or the defect queue (red).
ctx.fillStyle = "#1f2a37";
ctx.strokeStyle = "#fff";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(layout.switchNode.x, layout.switchNode.y, 9, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// Labels
ctx.fillStyle = "#5d6b7a";
ctx.font = "11px system-ui";
ctx.textAlign = "left";
ctx.textBaseline = "alphabetic";
ctx.fillText("switch", layout.switchNode.x + 14, layout.switchNode.y + 22);
ctx.fillText("(rework policy)", layout.switchNode.x + 14, layout.switchNode.y + 35);
// Track labels (small, next to each vertical arrow)
ctx.font = "11px system-ui";
ctx.fillStyle = queuePressure ? "#a85f00" : "#7c8794";
ctx.textAlign = "right";
ctx.fillText("balk ↑", layout.pblEnter.x - 6, 290);
ctx.fillStyle = "#4a90e2";
ctx.textAlign = "left";
ctx.fillText("pull ↓", layout.pullExit.x + 6, 290);
ctx.fillStyle = "#cc4a3a";
ctx.textAlign = "right";
ctx.fillText("rework ↑", layout.defectExit.x - 6, 405);
// Arrival label
ctx.fillStyle = "#5d6b7a";
ctx.font = "11px system-ui";
ctx.textAlign = "left";
const P = readParams();
ctx.fillText(`new work: ${P.arrivalRate.toFixed(1)}/day (${P.arrivalMode})`, 30, 365);
}
function drawItems(P) {
const now = performance.now();
const dayMs = P.dayMs;
const R = 10; // dot radius (bigger so label is readable)
// Overflow dots that marched off the left edge get absorbed into one black
// edge chip per queue ("+N"), instead of being drawn invisibly. Cash-out is
// automatic: parking is index-based, so as the queue drains, dots shift
// toward the head and walk back onto the canvas by themselves.
const EDGE = 34;
let offBacklog = 0, offDefect = 0;
for (const item of state.items.values()) {
let x, y;
if (item.path) {
const dur = item.tweenDurationMs || dayMs;
const t = Math.max(0, Math.min(1, (now - item.phaseStartMs) / dur));
const p = pointAlongPolyline(item.path, t);
x = p.x + (item.xJitter || 0);
y = p.y + (item.yJitter || 0);
} else if (item.parkedPos) {
x = item.parkedPos.x; y = item.parkedPos.y;
if (x < EDGE) {
if (item.phase === "IN_BACKLOG") { offBacklog++; continue; }
if (item.phase === "IN_DEFECT_QUEUE") { offDefect++; continue; }
}
} else {
continue;
}
// dot
ctx.fillStyle = item.color;
ctx.strokeStyle = "rgba(0,0,0,0.35)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x, y, R, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// rework ring (a ring around the outside, brighter than the inner dot color)
if (item.reworkCount > 0) {
ctx.strokeStyle = "rgba(255,255,255,0.85)";
ctx.lineWidth = 1.6;
ctx.beginPath();
ctx.arc(x, y, R + 2, 0, Math.PI * 2);
ctx.stroke();
}
// label
ctx.fillStyle = "#ffffff";
ctx.font = "700 11px ui-monospace, SFMono-Regular, Consolas, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(item.label, x, y + 0.5);