-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircuit-report.js
More file actions
589 lines (532 loc) · 18.5 KB
/
circuit-report.js
File metadata and controls
589 lines (532 loc) · 18.5 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
const { definitions: gateDefinitions } = require('./client/gate-registry');
const DEFAULT_REPORT_OPTIONS = {
enabled: true,
sections: {
summary: true,
gateCounts: true,
gatePositions: true,
spatialMetrics: true,
connectionSummary: true,
floatingPins: true,
truthTable: true
},
truthTable: {
maxInputs: 6,
maxRows: 64
}
};
const POSITION_LOG_LIMIT = 40;
const FLOATING_PIN_LOG_LIMIT = 20;
const FAN_LIST_LIMIT = 5;
function mergeBoolean(value, fallback = true) {
return typeof value === 'boolean' ? value : fallback;
}
function toPositiveInteger(value, fallback) {
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric > 0) {
return Math.floor(numeric);
}
return fallback;
}
function normalizeBit(value) {
if (value === 1 || value === '1') {
return 1;
}
if (value === 0 || value === '0') {
return 0;
}
if (typeof value === 'boolean') {
return value ? 1 : 0;
}
const numeric = Number(value);
if (Number.isFinite(numeric)) {
return numeric > 0 ? 1 : 0;
}
return value ? 1 : 0;
}
function arraysEqual(a = [], b = []) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function sortGates(a, b) {
const labelA = (a.label || '').toLowerCase();
const labelB = (b.label || '').toLowerCase();
if (labelA === labelB) {
return a.id.localeCompare(b.id, undefined, { sensitivity: 'base' });
}
return labelA.localeCompare(labelB);
}
function formatGateName(gate) {
if (!gate) {
return '[unknown]';
}
const parts = [`[${gate.type || 'unknown'}]`];
if (gate.label && gate.label.trim()) {
parts.push(`"${gate.label.trim()}"`);
}
parts.push(`(${gate.id})`);
return parts.join(' ');
}
function buildCircuitModel(snapshot = {}) {
const gates = Array.isArray(snapshot.gates) ? snapshot.gates : [];
const sanitizedGates = gates
.filter((gate) => gate && gate.id)
.map((gate) => ({
id: String(gate.id),
type: typeof gate.type === 'string' ? gate.type : 'unknown',
x: Number.isFinite(Number(gate.x)) ? Number(gate.x) : 0,
y: Number.isFinite(Number(gate.y)) ? Number(gate.y) : 0,
state: normalizeBit(gate.state),
label: typeof gate.label === 'string' ? gate.label : ''
}));
const gateMap = new Map(sanitizedGates.map((gate) => [gate.id, gate]));
const connections = Array.isArray(snapshot.connections) ? snapshot.connections : [];
const sanitizedConnections = connections
.map((connection) => ({
id: connection?.id ? String(connection.id) : undefined,
from: {
gateId: connection?.from?.gateId ? String(connection.from.gateId) : undefined,
portIndex: Number.isFinite(Number(connection?.from?.portIndex)) ? Number(connection.from.portIndex) : 0
},
to: {
gateId: connection?.to?.gateId ? String(connection.to.gateId) : undefined,
portIndex: Number.isFinite(Number(connection?.to?.portIndex)) ? Number(connection.to.portIndex) : 0
}
}))
.filter((connection) => Boolean(connection.from.gateId) && Boolean(connection.to.gateId));
const inputLookup = new Map();
sanitizedConnections.forEach((connection) => {
const key = `${connection.to.gateId}:${connection.to.portIndex}`;
inputLookup.set(key, {
gateId: connection.from.gateId,
portIndex: connection.from.portIndex
});
});
const outputLookup = new Map();
sanitizedConnections.forEach((connection) => {
const { gateId } = connection.from;
if (!gateId) {
return;
}
if (!outputLookup.has(gateId)) {
outputLookup.set(gateId, []);
}
outputLookup.get(gateId).push({
gateId: connection.to.gateId,
portIndex: connection.to.portIndex
});
});
return {
gates: sanitizedGates,
connections: sanitizedConnections,
gateMap,
inputLookup,
outputLookup,
inputs: sanitizedGates.filter((gate) => gate.type === 'input'),
outputs: sanitizedGates.filter((gate) => gate.type === 'output')
};
}
function evaluateGateOutputs(runtimeGate, inputs) {
const { definition } = runtimeGate;
if (!definition) {
return [];
}
if (definition.logic) {
return definition.logic(inputs, runtimeGate) || [];
}
return [];
}
function normalizeOutputArray(values, expectedLength) {
const normalized = [];
for (let i = 0; i < expectedLength; i += 1) {
normalized.push(normalizeBit(values?.[i] ?? 0));
}
return normalized;
}
function evaluateModel(model, overrides = {}) {
const runtimeGates = new Map();
model.gates.forEach((gate) => {
const definition = gateDefinitions[gate.type];
const runtimeGate = {
id: gate.id,
type: gate.type,
label: gate.label,
state: gate.type === 'input'
? normalizeBit(Object.prototype.hasOwnProperty.call(overrides, gate.id) ? overrides[gate.id] : gate.state)
: normalizeBit(gate.state),
definition,
outputs: new Array(definition?.outputs || 0).fill(0),
inputCache: new Array(definition?.inputs || 0).fill(0)
};
runtimeGates.set(gate.id, runtimeGate);
});
const inputValueCache = new Map();
const getInputValue = (gateId, portIndex) => {
const key = `${gateId}:${portIndex}`;
if (inputValueCache.has(key)) {
return inputValueCache.get(key);
}
const source = model.inputLookup.get(key);
let value = 0;
if (source) {
const runtimeSource = runtimeGates.get(source.gateId);
if (runtimeSource && runtimeSource.outputs.length > source.portIndex) {
value = runtimeSource.outputs[source.portIndex] ?? 0;
}
}
const normalized = normalizeBit(value);
inputValueCache.set(key, normalized);
return normalized;
};
const iterationLimit = 32;
for (let iteration = 0; iteration < iterationLimit; iteration += 1) {
let changed = false;
inputValueCache.clear();
for (const runtimeGate of runtimeGates.values()) {
const definition = runtimeGate.definition;
if (!definition) {
continue;
}
const inputs = definition.inputs
? Array.from({ length: definition.inputs }, (_, index) => getInputValue(runtimeGate.id, index))
: [];
runtimeGate.inputCache = inputs;
const produced = evaluateGateOutputs(runtimeGate, inputs);
if (definition.outputs > 0) {
const normalizedOutputs = normalizeOutputArray(produced, definition.outputs);
if (!arraysEqual(runtimeGate.outputs, normalizedOutputs)) {
runtimeGate.outputs = normalizedOutputs;
changed = true;
}
}
}
if (!changed) {
break;
}
}
const outputValues = new Map();
model.outputs.forEach((gate) => {
const runtimeGate = runtimeGates.get(gate.id);
if (!runtimeGate) {
outputValues.set(gate.id, 0);
return;
}
if (runtimeGate.definition && runtimeGate.definition.inputs > 0) {
outputValues.set(gate.id, normalizeBit(runtimeGate.inputCache?.[0] ?? 0));
} else if (runtimeGate.outputs.length > 0) {
outputValues.set(gate.id, normalizeBit(runtimeGate.outputs[0]));
} else {
outputValues.set(gate.id, normalizeBit(runtimeGate.state));
}
});
return { runtimeGates, outputValues };
}
function computeGateCounts(model) {
const counts = {};
model.gates.forEach((gate) => {
const key = gate.type || 'unknown';
counts[key] = (counts[key] || 0) + 1;
});
return Object.entries(counts).sort((a, b) => {
if (b[1] === a[1]) {
return a[0].localeCompare(b[0]);
}
return b[1] - a[1];
});
}
function computeSpatialMetrics(model) {
if (!model.gates.length) {
return null;
}
const xs = model.gates.map((gate) => gate.x);
const ys = model.gates.map((gate) => gate.y);
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minY = Math.min(...ys);
const maxY = Math.max(...ys);
return {
minX,
maxX,
minY,
maxY,
width: maxX - minX,
height: maxY - minY
};
}
function computeConnectionSummary(model) {
const fanIn = new Map();
const fanOut = new Map();
model.connections.forEach((connection) => {
if (connection.from.gateId) {
fanOut.set(connection.from.gateId, (fanOut.get(connection.from.gateId) || 0) + 1);
}
if (connection.to.gateId) {
fanIn.set(connection.to.gateId, (fanIn.get(connection.to.gateId) || 0) + 1);
}
});
const gatesWithInputs = model.gates.filter((gate) => (gateDefinitions[gate.type]?.inputs || 0) > 0);
const gatesWithOutputs = model.gates.filter((gate) => (gateDefinitions[gate.type]?.outputs || 0) > 0);
const averageFanIn = gatesWithInputs.length
? model.connections.length / gatesWithInputs.length
: 0;
const averageFanOut = gatesWithOutputs.length
? model.connections.length / gatesWithOutputs.length
: 0;
const topFanIn = Array.from(fanIn.entries())
.map(([gateId, total]) => ({ gate: model.gateMap.get(gateId), total }))
.sort((a, b) => b.total - a.total)
.slice(0, FAN_LIST_LIMIT);
const topFanOut = Array.from(fanOut.entries())
.map(([gateId, total]) => ({ gate: model.gateMap.get(gateId), total }))
.sort((a, b) => b.total - a.total)
.slice(0, FAN_LIST_LIMIT);
return {
totalConnections: model.connections.length,
averageFanIn,
averageFanOut,
topFanIn,
topFanOut
};
}
function detectFloatingPins(model) {
const openInputs = [];
const floatingOutputs = [];
model.gates.forEach((gate) => {
const definition = gateDefinitions[gate.type];
if (!definition) {
return;
}
if (definition.inputs > 0 && gate.type !== 'input') {
for (let i = 0; i < definition.inputs; i += 1) {
const key = `${gate.id}:${i}`;
if (!model.inputLookup.has(key)) {
openInputs.push({ gate, portIndex: i });
}
}
}
if (definition.outputs > 0 && gate.type !== 'output') {
const fanout = model.outputLookup.get(gate.id)?.length || 0;
if (fanout === 0) {
floatingOutputs.push(gate);
}
}
});
return { openInputs, floatingOutputs };
}
function generateTruthTable(model, options) {
const orderedInputs = [...model.inputs].sort(sortGates);
const orderedOutputs = [...model.outputs].sort(sortGates);
if (!orderedOutputs.length) {
return { skipped: true, reason: 'No output gates defined' };
}
const maxInputs = toPositiveInteger(options?.maxInputs, DEFAULT_REPORT_OPTIONS.truthTable.maxInputs);
const inputCount = orderedInputs.length;
if (inputCount > maxInputs) {
return {
skipped: true,
reason: `Input count (${inputCount}) exceeds configured limit (${maxInputs})`
};
}
const maxRows = toPositiveInteger(options?.maxRows, DEFAULT_REPORT_OPTIONS.truthTable.maxRows);
const totalRows = Math.max(1, 2 ** inputCount);
const rowsToRender = Math.min(totalRows, maxRows);
const rows = [];
for (let rowIndex = 0; rowIndex < rowsToRender; rowIndex += 1) {
const assignment = {};
const inputBits = [];
for (let bitIndex = 0; bitIndex < inputCount; bitIndex += 1) {
const gate = orderedInputs[bitIndex];
const shift = inputCount - bitIndex - 1;
const bit = ((rowIndex >> shift) & 1) || 0;
assignment[gate.id] = bit;
inputBits.push(bit);
}
const evaluation = evaluateModel(model, assignment);
const outputBits = orderedOutputs.map((gate) => evaluation.outputValues.get(gate.id) || 0);
rows.push({ index: rowIndex, inputs: inputBits, outputs: outputBits });
}
return {
skipped: false,
header: {
inputs: orderedInputs,
outputs: orderedOutputs
},
rows,
totalRows,
truncated: rowsToRender < totalRows
};
}
function buildReportOptions(gateConfig = {}) {
const reportConfig = gateConfig?.exportReport || {};
const sectionOverrides = reportConfig.sections || {};
const truthTableOverrides = reportConfig.truthTable || {};
const sections = {
summary: mergeBoolean(sectionOverrides.summary, DEFAULT_REPORT_OPTIONS.sections.summary),
gateCounts: mergeBoolean(sectionOverrides.gateCounts, DEFAULT_REPORT_OPTIONS.sections.gateCounts),
gatePositions: mergeBoolean(sectionOverrides.gatePositions, DEFAULT_REPORT_OPTIONS.sections.gatePositions),
spatialMetrics: mergeBoolean(sectionOverrides.spatialMetrics, DEFAULT_REPORT_OPTIONS.sections.spatialMetrics),
connectionSummary: mergeBoolean(sectionOverrides.connectionSummary, DEFAULT_REPORT_OPTIONS.sections.connectionSummary),
floatingPins: mergeBoolean(sectionOverrides.floatingPins, DEFAULT_REPORT_OPTIONS.sections.floatingPins),
truthTable: mergeBoolean(sectionOverrides.truthTable, DEFAULT_REPORT_OPTIONS.sections.truthTable)
};
const truthTable = {
enabled: sections.truthTable && mergeBoolean(truthTableOverrides.enabled, true),
maxInputs: toPositiveInteger(truthTableOverrides.maxInputs, DEFAULT_REPORT_OPTIONS.truthTable.maxInputs),
maxRows: toPositiveInteger(truthTableOverrides.maxRows, DEFAULT_REPORT_OPTIONS.truthTable.maxRows)
};
return {
enabled: mergeBoolean(reportConfig.enabled, DEFAULT_REPORT_OPTIONS.enabled),
sections: {
...sections,
truthTable: truthTable.enabled
},
truthTable
};
}
function buildCircuitReportLines(snapshot, gateConfig = {}) {
const options = buildReportOptions(gateConfig);
if (!options.enabled) {
return [];
}
const model = buildCircuitModel(snapshot || {});
const lines = [];
const pushLine = (line = '') => {
lines.push(line);
};
pushLine('');
pushLine('=== Circuit Export Report ===');
if (options.sections.summary) {
pushLine(`Total gates: ${model.gates.length}`);
pushLine(`Total connections: ${model.connections.length}`);
pushLine(`Inputs: ${model.inputs.length} | Outputs: ${model.outputs.length}`);
}
if (options.sections.gateCounts) {
const counts = computeGateCounts(model);
if (!counts.length) {
pushLine('Gate counts: n/a (no gates present)');
} else {
pushLine('Gate counts:');
counts.forEach(([type, count]) => {
pushLine(` - ${type}: ${count}`);
});
}
}
if (options.sections.gatePositions) {
if (!model.gates.length) {
pushLine('Gate positions: n/a (no gates present)');
} else {
pushLine('Gate positions:');
model.gates.slice(0, POSITION_LOG_LIMIT).forEach((gate) => {
pushLine(` - ${formatGateName(gate)} @ (${gate.x}, ${gate.y})`);
});
if (model.gates.length > POSITION_LOG_LIMIT) {
pushLine(` ... ${model.gates.length - POSITION_LOG_LIMIT} additional gates not shown`);
}
}
}
if (options.sections.spatialMetrics) {
const metrics = computeSpatialMetrics(model);
if (!metrics) {
pushLine('Spatial metrics: n/a (no gates present)');
} else {
pushLine('Spatial metrics:');
pushLine(` - Bounds X: ${metrics.minX} → ${metrics.maxX} (width ${metrics.width})`);
pushLine(` - Bounds Y: ${metrics.minY} → ${metrics.maxY} (height ${metrics.height})`);
}
}
if (options.sections.connectionSummary) {
const summary = computeConnectionSummary(model);
pushLine('Connection summary:');
pushLine(` - Total: ${summary.totalConnections}`);
pushLine(` - Avg fan-in: ${summary.averageFanIn.toFixed(2)}`);
pushLine(` - Avg fan-out: ${summary.averageFanOut.toFixed(2)}`);
if (summary.topFanIn.length) {
pushLine(' - Highest fan-in:');
summary.topFanIn.forEach((entry) => {
pushLine(` • ${formatGateName(entry.gate)} → ${entry.total} inputs`);
});
}
if (summary.topFanOut.length) {
pushLine(' - Highest fan-out:');
summary.topFanOut.forEach((entry) => {
pushLine(` • ${formatGateName(entry.gate)} → ${entry.total} outputs`);
});
}
}
if (options.sections.floatingPins) {
const floating = detectFloatingPins(model);
if (!floating.openInputs.length && !floating.floatingOutputs.length) {
pushLine('Connectivity check: all gate inputs and outputs are connected.');
} else {
pushLine('Connectivity diagnostics:');
if (floating.openInputs.length) {
pushLine(' Unconnected gate inputs:');
floating.openInputs.slice(0, FLOATING_PIN_LOG_LIMIT).forEach((entry) => {
pushLine(` • ${formatGateName(entry.gate)} input ${entry.portIndex}`);
});
if (floating.openInputs.length > FLOATING_PIN_LOG_LIMIT) {
pushLine(` ... ${floating.openInputs.length - FLOATING_PIN_LOG_LIMIT} additional open inputs`);
}
} else {
pushLine(' Unconnected gate inputs: none');
}
if (floating.floatingOutputs.length) {
pushLine(' Gate outputs with no destinations:');
floating.floatingOutputs.slice(0, FLOATING_PIN_LOG_LIMIT).forEach((gate) => {
pushLine(` • ${formatGateName(gate)}`);
});
if (floating.floatingOutputs.length > FLOATING_PIN_LOG_LIMIT) {
pushLine(` ... ${floating.floatingOutputs.length - FLOATING_PIN_LOG_LIMIT} additional floating outputs`);
}
} else {
pushLine(' Gate outputs with no destinations: none');
}
}
}
if (options.truthTable.enabled) {
const table = generateTruthTable(model, options.truthTable);
if (table.skipped) {
pushLine(`Truth table: skipped (${table.reason})`);
} else if (!table.rows.length) {
pushLine('Truth table: no rows to display');
} else {
const inputLabels = table.header.inputs.map((gate) => gate.label || gate.id);
const outputLabels = table.header.outputs.map((gate) => gate.label || gate.id);
pushLine(`Truth table (${table.rows.length}/${table.totalRows} rows${table.truncated ? ', truncated' : ''}):`);
const leftHeader = inputLabels.length ? inputLabels.join(' ') : '(no inputs)';
const rightHeader = outputLabels.length ? outputLabels.join(' ') : '(no outputs)';
pushLine(` ${leftHeader} || ${rightHeader}`);
table.rows.forEach((row) => {
const left = row.inputs.length ? row.inputs.map((value) => (value ? 1 : 0)).join(' ') : '-';
const right = row.outputs.length ? row.outputs.map((value) => (value ? 1 : 0)).join(' ') : '-';
pushLine(` ${left} || ${right}`);
});
if (table.truncated) {
pushLine(` ... ${table.totalRows - table.rows.length} additional rows not shown`);
}
}
}
pushLine('=== End of Circuit Report ===');
pushLine('');
return lines;
}
function printCircuitReport(snapshot, gateConfig = {}) {
const lines = buildCircuitReportLines(snapshot, gateConfig);
if (!lines.length) {
return '';
}
lines.forEach((line) => console.log(line));
return lines.join('\n');
}
module.exports = {
buildReportOptions,
buildCircuitReportLines,
printCircuitReport
};