forked from ruvnet/RuView
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsi-graph-visualizer.js
More file actions
674 lines (586 loc) · 21 KB
/
Copy pathcsi-graph-visualizer.js
File metadata and controls
674 lines (586 loc) · 21 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
#!/usr/bin/env node
/**
* ADR-075: CSI Subcarrier Correlation Graph Visualizer
*
* ASCII visualization of the subcarrier correlation graph used by the
* min-cut person counter. Shows per-person subcarrier clusters, graph
* connectivity, and correlation heatmap in real-time.
*
* Usage:
* # Live from ESP32 nodes via UDP
* node scripts/csi-graph-visualizer.js --port 5006
*
* # Replay from recorded CSI data
* node scripts/csi-graph-visualizer.js --replay data/recordings/pretrain-1775182186.csi.jsonl
*
* # Show correlation heatmap only
* node scripts/csi-graph-visualizer.js --replay FILE --mode heatmap
*
* ADR: docs/adr/ADR-075-mincut-person-separation.md
*/
'use strict';
const dgram = require('dgram');
const fs = require('fs');
const readline = require('readline');
const { parseArgs } = require('util');
// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------
const { values: args } = parseArgs({
options: {
port: { type: 'string', short: 'p', default: '5006' },
replay: { type: 'string', short: 'r' },
interval: { type: 'string', short: 'i', default: '2000' },
window: { type: 'string', short: 'w', default: '2000' },
mode: { type: 'string', short: 'm', default: 'all' },
node: { type: 'string', short: 'n', default: '0' },
'corr-threshold': { type: 'string', default: '0.3' },
'cut-threshold': { type: 'string', default: '2.0' },
'var-floor': { type: 'string', default: '0.5' },
width: { type: 'string', default: '80' },
},
strict: true,
});
const PORT = parseInt(args.port, 10);
const INTERVAL_MS = parseInt(args.interval, 10);
const WINDOW_MS = parseInt(args.window, 10);
const CORR_THRESHOLD = parseFloat(args['corr-threshold']);
const CUT_THRESHOLD = parseFloat(args['cut-threshold']);
const VAR_FLOOR = parseFloat(args['var-floor']);
const MODE = args.mode; // 'all', 'heatmap', 'clusters', 'spectrum'
const TARGET_NODE = parseInt(args.node, 10);
const WIDTH = parseInt(args.width, 10);
const CSI_MAGIC = 0xC5110001;
const HEADER_SIZE = 20;
// Color palette for person clusters (ANSI 256)
const PERSON_COLORS = [
'\x1b[31m', // red
'\x1b[32m', // green
'\x1b[34m', // blue
'\x1b[33m', // yellow
'\x1b[35m', // magenta
'\x1b[36m', // cyan
'\x1b[91m', // bright red
'\x1b[92m', // bright green
];
const RESET = '\x1b[0m';
const DIM = '\x1b[2m';
const BOLD = '\x1b[1m';
// Heatmap characters (11 levels of intensity)
const HEAT = [' ', '\u2591', '\u2591', '\u2592', '\u2592', '\u2593', '\u2593', '\u2588', '\u2588', '\u2588', '\u2588'];
// Bar chart characters
const BARS = ['\u2581', '\u2582', '\u2583', '\u2584', '\u2585', '\u2586', '\u2587', '\u2588'];
// ---------------------------------------------------------------------------
// Sliding window (same as mincut-person-counter.js)
// ---------------------------------------------------------------------------
class SubcarrierWindow {
constructor(maxAgeMs) {
this.maxAgeMs = maxAgeMs;
this.frames = [];
this.nSubcarriers = 0;
}
push(timestamp, amplitudes) {
this.nSubcarriers = amplitudes.length;
this.frames.push({ timestamp, amplitudes: Float64Array.from(amplitudes) });
const cutoff = timestamp - this.maxAgeMs;
while (this.frames.length > 0 && this.frames[0].timestamp < cutoff) {
this.frames.shift();
}
}
get length() { return this.frames.length; }
correlationMatrix() {
const nFrames = this.frames.length;
const nSc = this.nSubcarriers;
if (nFrames < 5 || nSc === 0) return null;
const mean = new Float64Array(nSc);
const std = new Float64Array(nSc);
for (let f = 0; f < nFrames; f++) {
const amp = this.frames[f].amplitudes;
for (let i = 0; i < nSc; i++) mean[i] += amp[i];
}
for (let i = 0; i < nSc; i++) mean[i] /= nFrames;
for (let f = 0; f < nFrames; f++) {
const amp = this.frames[f].amplitudes;
for (let i = 0; i < nSc; i++) {
const d = amp[i] - mean[i];
std[i] += d * d;
}
}
for (let i = 0; i < nSc; i++) std[i] = Math.sqrt(std[i] / (nFrames - 1));
const activeIndices = [];
for (let i = 0; i < nSc; i++) {
if (std[i] > VAR_FLOOR) activeIndices.push(i);
}
const n = activeIndices.length;
if (n < 2) return { matrix: null, n: 0, activeIndices, mean, std };
const matrix = new Float64Array(n * n);
for (let ai = 0; ai < n; ai++) {
matrix[ai * n + ai] = 1.0;
const si = activeIndices[ai];
for (let aj = ai + 1; aj < n; aj++) {
const sj = activeIndices[aj];
let cov = 0;
for (let f = 0; f < nFrames; f++) {
const amp = this.frames[f].amplitudes;
cov += (amp[si] - mean[si]) * (amp[sj] - mean[sj]);
}
cov /= (nFrames - 1);
const denom = std[si] * std[sj];
const r = denom > 1e-10 ? cov / denom : 0;
matrix[ai * n + aj] = r;
matrix[aj * n + ai] = r;
}
}
return { matrix, n, activeIndices, mean, std };
}
/** Get latest amplitudes */
latestAmplitudes() {
if (this.frames.length === 0) return null;
return this.frames[this.frames.length - 1].amplitudes;
}
}
// ---------------------------------------------------------------------------
// Graph + Stoer-Wagner (minimal copy from mincut-person-counter.js)
// ---------------------------------------------------------------------------
class WeightedGraph {
constructor(n) {
this.n = n;
this.adj = new Array(n);
for (let i = 0; i < n; i++) this.adj[i] = new Map();
this.edgeCount = 0;
}
addEdge(u, v, w) {
if (u === v) return;
if (!this.adj[u].has(v)) this.edgeCount++;
this.adj[u].set(v, w);
this.adj[v].set(u, w);
}
static fromCorrelation(matrix, n, threshold) {
const g = new WeightedGraph(n);
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const r = Math.abs(matrix[i * n + j]);
if (r > threshold) g.addEdge(i, j, r);
}
}
return g;
}
connectedComponents() {
const visited = new Uint8Array(this.n);
const components = [];
for (let start = 0; start < this.n; start++) {
if (visited[start]) continue;
const comp = [];
const queue = [start];
visited[start] = 1;
while (queue.length > 0) {
const u = queue.shift();
comp.push(u);
for (const [v] of this.adj[u]) {
if (!visited[v]) { visited[v] = 1; queue.push(v); }
}
}
components.push(comp);
}
return components;
}
subgraph(vertices) {
const newIdx = new Map();
vertices.forEach((v, i) => newIdx.set(v, i));
const sub = new WeightedGraph(vertices.length);
for (const u of vertices) {
for (const [v, w] of this.adj[u]) {
if (newIdx.has(v) && u < v) sub.addEdge(newIdx.get(u), newIdx.get(v), w);
}
}
return { graph: sub, mapping: vertices };
}
}
function stoerWagner(graph) {
const n = graph.n;
if (n <= 1) return { minCutValue: Infinity, partition: [Array.from({length: n}, (_, i) => i), []] };
const adj = new Array(n);
for (let i = 0; i < n; i++) adj[i] = new Map(graph.adj[i]);
const groups = new Array(n);
for (let i = 0; i < n; i++) groups[i] = [i];
let activeVertices = Array.from({length: n}, (_, i) => i);
let bestCut = Infinity;
let bestPartitionSide = null;
while (activeVertices.length > 1) {
const key = new Float64Array(n);
const inA = new Uint8Array(n);
let s = -1, t = -1;
for (let iter = 0; iter < activeVertices.length; iter++) {
let best = -1, bestKey = -Infinity;
for (const v of activeVertices) {
if (!inA[v] && key[v] > bestKey) { bestKey = key[v]; best = v; }
}
if (best === -1) {
for (const v of activeVertices) { if (!inA[v]) { best = v; break; } }
}
s = t; t = best; inA[best] = 1;
if (adj[best]) {
for (const [nb, w] of adj[best]) {
if (activeVertices.includes(nb) && !inA[nb]) key[nb] += w;
}
}
}
let cutOfPhase = 0;
if (adj[t]) {
for (const [nb, w] of adj[t]) {
if (activeVertices.includes(nb) && nb !== t) cutOfPhase += w;
}
}
if (s === -1 || t === -1) break;
if (cutOfPhase < bestCut) { bestCut = cutOfPhase; bestPartitionSide = [...groups[t]]; }
if (adj[t]) {
for (const [nb, w] of adj[t]) {
if (nb === s) continue;
const ex = adj[s].get(nb) || 0;
adj[s].set(nb, ex + w);
adj[nb].delete(t);
adj[nb].set(s, ex + w);
}
}
adj[s].delete(t);
groups[s] = groups[s].concat(groups[t]);
groups[t] = [];
activeVertices = activeVertices.filter(v => v !== t);
}
if (!bestPartitionSide || bestPartitionSide.length === 0) {
return { minCutValue: Infinity, partition: [Array.from({length: n}, (_, i) => i), []] };
}
const sideSet = new Set(bestPartitionSide);
const sideA = [], sideB = [];
for (let i = 0; i < n; i++) { (sideSet.has(i) ? sideA : sideB).push(i); }
return { minCutValue: bestCut, partition: [sideA, sideB] };
}
function separatePersons(graph, cutThreshold, maxPersons) {
const components = graph.connectedComponents();
const personGroups = [];
for (const comp of components) {
if (comp.length < 2) continue;
_split(graph, comp, cutThreshold, maxPersons, personGroups);
}
return personGroups;
}
function _split(graph, vertices, cutThreshold, maxPersons, result) {
if (vertices.length < 2 || result.length >= maxPersons) {
if (vertices.length >= 2) result.push(vertices);
return;
}
const { graph: sub, mapping } = graph.subgraph(vertices);
const { minCutValue, partition } = stoerWagner(sub);
if (minCutValue >= cutThreshold || partition[0].length === 0 || partition[1].length === 0) {
result.push(vertices);
return;
}
_split(graph, partition[0].map(i => mapping[i]), cutThreshold, maxPersons, result);
_split(graph, partition[1].map(i => mapping[i]), cutThreshold, maxPersons, result);
}
// ---------------------------------------------------------------------------
// Visualization renderers
// ---------------------------------------------------------------------------
/**
* Render correlation heatmap (downsampled to fit terminal width).
* Rows and columns = active subcarrier indices.
*/
function renderHeatmap(corr, width) {
if (!corr || !corr.matrix) return [' (insufficient data for heatmap)'];
const { matrix, n, activeIndices } = corr;
const lines = [];
lines.push(`${BOLD}Correlation Heatmap${RESET} (${n} active subcarriers, threshold=${CORR_THRESHOLD})`);
// Downsample if needed
const maxCols = Math.min(n, width - 8);
const step = Math.max(1, Math.ceil(n / maxCols));
const displayN = Math.ceil(n / step);
// Header row: subcarrier indices
let header = ' ';
for (let j = 0; j < displayN; j++) {
const sc = activeIndices[j * step];
header += (sc < 10 ? `${sc} ` : `${sc}`).slice(0, 2);
}
lines.push(DIM + header + RESET);
for (let i = 0; i < displayN; i++) {
const sc = activeIndices[i * step];
let row = ` ${String(sc).padStart(3)} `;
for (let j = 0; j < displayN; j++) {
const ii = i * step, jj = j * step;
const val = Math.abs(matrix[ii * n + jj]);
const level = Math.min(10, Math.floor(val * 10));
if (val > CORR_THRESHOLD) {
row += `\x1b[33m${HEAT[level]}${RESET} `;
} else {
row += `${DIM}${HEAT[level]}${RESET} `;
}
}
lines.push(row);
}
return lines;
}
/**
* Render subcarrier spectrum bar with person cluster coloring.
*/
function renderSpectrum(window, personGroups, activeIndices) {
const amp = window.latestAmplitudes();
if (!amp) return [' (no data)'];
const lines = [];
const nSc = window.nSubcarriers;
// Build subcarrier-to-person mapping
const scToPerson = new Int8Array(nSc).fill(-1);
if (personGroups && activeIndices) {
for (let p = 0; p < personGroups.length; p++) {
for (const graphIdx of personGroups[p]) {
if (graphIdx < activeIndices.length) {
scToPerson[activeIndices[graphIdx]] = p;
}
}
}
}
// Find max amplitude for normalization
let maxAmp = 0;
for (let i = 0; i < nSc; i++) {
if (amp[i] > maxAmp) maxAmp = amp[i];
}
if (maxAmp === 0) maxAmp = 1;
lines.push(`${BOLD}Spectrum${RESET} (${nSc} subcarriers, colored by person cluster)`);
// Render bar
let bar = ' ';
for (let i = 0; i < nSc; i++) {
const level = Math.floor((amp[i] / maxAmp) * 7.99);
const ch = BARS[Math.max(0, Math.min(7, level))];
const personIdx = scToPerson[i];
if (personIdx >= 0 && personIdx < PERSON_COLORS.length) {
bar += PERSON_COLORS[personIdx] + ch + RESET;
} else {
bar += DIM + ch + RESET;
}
}
lines.push(bar);
// Legend
let legend = ' ';
for (let i = 0; i < nSc; i++) {
const p = scToPerson[i];
if (p >= 0 && p < PERSON_COLORS.length) {
legend += PERSON_COLORS[p] + (p + 1) + RESET;
} else {
legend += DIM + '.' + RESET;
}
}
lines.push(legend);
return lines;
}
/**
* Render cluster summary with per-person statistics.
*/
function renderClusters(personGroups, activeIndices, corr) {
if (!personGroups || personGroups.length === 0) {
return [' No person clusters detected'];
}
const lines = [];
lines.push(`${BOLD}Person Clusters${RESET} (${personGroups.length} detected)`);
for (let p = 0; p < personGroups.length; p++) {
const group = personGroups[p];
const color = p < PERSON_COLORS.length ? PERSON_COLORS[p] : '';
// Map back to subcarrier indices
const scIds = group.map(i => activeIndices[i]);
const scStr = scIds.length <= 16
? scIds.join(', ')
: scIds.slice(0, 14).join(', ') + `, ...+${scIds.length - 14}`;
// Compute intra-cluster average correlation
let avgCorr = 0, count = 0;
if (corr && corr.matrix) {
for (let i = 0; i < group.length; i++) {
for (let j = i + 1; j < group.length; j++) {
avgCorr += Math.abs(corr.matrix[group[i] * corr.n + group[j]]);
count++;
}
}
if (count > 0) avgCorr /= count;
}
lines.push(` ${color}Person ${p + 1}${RESET}: ${group.length} subcarriers, avg intra-corr=${avgCorr.toFixed(3)}`);
lines.push(` ${DIM}SC: [${scStr}]${RESET}`);
}
return lines;
}
/**
* Render graph connectivity summary.
*/
function renderGraphStats(graph, corr) {
if (!graph) return [' (no graph)'];
const lines = [];
const components = graph.connectedComponents();
const density = graph.n > 1 ? (2 * graph.edgeCount) / (graph.n * (graph.n - 1)) : 0;
lines.push(`${BOLD}Graph${RESET}: ${graph.n} nodes, ${graph.edgeCount} edges, density=${density.toFixed(3)}, components=${components.length}`);
// Degree distribution summary
const degrees = new Array(graph.n);
let minDeg = Infinity, maxDeg = 0, sumDeg = 0;
for (let i = 0; i < graph.n; i++) {
degrees[i] = graph.adj[i].size;
if (degrees[i] < minDeg) minDeg = degrees[i];
if (degrees[i] > maxDeg) maxDeg = degrees[i];
sumDeg += degrees[i];
}
const avgDeg = graph.n > 0 ? sumDeg / graph.n : 0;
lines.push(` Degree: min=${minDeg} max=${maxDeg} avg=${avgDeg.toFixed(1)}`);
return lines;
}
// ---------------------------------------------------------------------------
// Full render
// ---------------------------------------------------------------------------
function render(window, nodeId) {
const corr = window.correlationMatrix();
const lines = [];
const ts = new Date().toISOString().slice(11, 19);
lines.push(`${BOLD}ADR-075 CSI Graph Visualizer${RESET} [${ts}] Node ${nodeId} | ${window.length} frames`);
lines.push('═'.repeat(WIDTH));
let graph = null;
let personGroups = null;
let activeIndices = corr ? corr.activeIndices : [];
if (corr && corr.matrix && corr.n >= 2) {
graph = WeightedGraph.fromCorrelation(corr.matrix, corr.n, CORR_THRESHOLD);
personGroups = separatePersons(graph, CUT_THRESHOLD, 8);
}
const personCount = personGroups ? personGroups.length : 0;
lines.push(`${BOLD}Persons: ${personCount}${RESET} | Active subcarriers: ${activeIndices.length}/${window.nSubcarriers}`);
lines.push('');
if (MODE === 'all' || MODE === 'spectrum') {
lines.push(...renderSpectrum(window, personGroups, activeIndices));
lines.push('');
}
if (MODE === 'all' || MODE === 'clusters') {
lines.push(...renderClusters(personGroups, activeIndices, corr));
lines.push('');
}
if (MODE === 'all' || MODE === 'heatmap') {
lines.push(...renderHeatmap(corr, WIDTH));
lines.push('');
}
if (graph) {
lines.push(...renderGraphStats(graph, corr));
}
lines.push('═'.repeat(WIDTH));
lines.push(`${DIM}Thresholds: corr=${CORR_THRESHOLD} cut=${CUT_THRESHOLD} var-floor=${VAR_FLOOR}${RESET}`);
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Packet parsing
// ---------------------------------------------------------------------------
function parseIqHex(iqHex, nSubcarriers) {
const bytes = Buffer.from(iqHex, 'hex');
const amplitudes = new Float64Array(nSubcarriers);
for (let sc = 0; sc < nSubcarriers; sc++) {
const offset = 2 + sc * 2;
if (offset + 1 >= bytes.length) break;
let I = bytes[offset]; let Q = bytes[offset + 1];
if (I > 127) I -= 256;
if (Q > 127) Q -= 256;
amplitudes[sc] = Math.sqrt(I * I + Q * Q);
}
return amplitudes;
}
function parseUdpPacket(buf) {
if (buf.length < HEADER_SIZE) return null;
const magic = buf.readUInt32LE(0);
if (magic !== CSI_MAGIC) return null;
const nodeId = buf.readUInt8(4);
const nSubcarriers = buf.readUInt16LE(6);
const amplitudes = new Float64Array(nSubcarriers);
for (let sc = 0; sc < nSubcarriers; sc++) {
const offset = HEADER_SIZE + sc * 2;
if (offset + 1 >= buf.length) break;
const I = buf.readInt8(offset);
const Q = buf.readInt8(offset + 1);
amplitudes[sc] = Math.sqrt(I * I + Q * Q);
}
return { nodeId, nSubcarriers, amplitudes, timestamp: Date.now() };
}
// ---------------------------------------------------------------------------
// Main: live mode
// ---------------------------------------------------------------------------
function startLive() {
const windows = new Map();
const server = dgram.createSocket('udp4');
server.on('message', (buf) => {
const frame = parseUdpPacket(buf);
if (!frame) return;
if (!windows.has(frame.nodeId)) {
windows.set(frame.nodeId, new SubcarrierWindow(WINDOW_MS));
}
windows.get(frame.nodeId).push(frame.timestamp, frame.amplitudes);
});
setInterval(() => {
process.stdout.write('\x1b[2J\x1b[H');
for (const [nodeId, window] of windows) {
if (TARGET_NODE !== 0 && nodeId !== TARGET_NODE) continue;
console.log(render(window, nodeId));
console.log();
}
if (windows.size === 0) {
console.log('Waiting for CSI frames on UDP port ' + PORT + '...');
}
}, INTERVAL_MS);
server.bind(PORT, () => {
console.log(`CSI Graph Visualizer listening on UDP port ${PORT}`);
});
}
// ---------------------------------------------------------------------------
// Main: replay mode
// ---------------------------------------------------------------------------
async function startReplay(filePath) {
if (!fs.existsSync(filePath)) {
console.error(`File not found: ${filePath}`);
process.exit(1);
}
const windows = new Map();
const rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity,
});
let lastRenderTs = 0;
let frameCount = 0;
for await (const line of rl) {
if (!line.trim()) continue;
let record;
try { record = JSON.parse(line); } catch { continue; }
if (record.type !== 'raw_csi' || !record.iq_hex) continue;
const nSc = record.subcarriers || 64;
const amplitudes = parseIqHex(record.iq_hex, nSc);
const nodeId = record.node_id;
const tsMs = record.timestamp * 1000;
if (!windows.has(nodeId)) {
windows.set(nodeId, new SubcarrierWindow(WINDOW_MS));
}
windows.get(nodeId).push(tsMs, amplitudes);
frameCount++;
if (lastRenderTs === 0) lastRenderTs = tsMs;
if (tsMs - lastRenderTs >= INTERVAL_MS) {
process.stdout.write('\x1b[2J\x1b[H');
for (const [nid, window] of windows) {
if (TARGET_NODE !== 0 && nid !== TARGET_NODE) continue;
console.log(render(window, nid));
console.log();
}
lastRenderTs = tsMs;
// Small delay for visual effect during replay
await new Promise(r => setTimeout(r, 100));
}
}
// Final render
console.log();
console.log('═'.repeat(WIDTH));
console.log(`${BOLD}Replay complete${RESET}: ${frameCount} frames`);
for (const [nodeId, window] of windows) {
if (TARGET_NODE !== 0 && nodeId !== TARGET_NODE) continue;
console.log();
console.log(render(window, nodeId));
}
}
// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
if (args.replay) {
startReplay(args.replay);
} else {
startLive();
}