@mica-js/simulator 0.3.0 → 1.0.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/README.md +10 -2
- package/dist/index.d.ts +226 -158
- package/dist/index.js +2364 -705
- package/dist/index.js.map +1 -1
- package/dist/sandbox.d.ts +6 -0
- package/dist/sandbox.js +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,49 +1,376 @@
|
|
|
1
1
|
import { n as deviceSimulationHostGuestService, t as deviceSimulationHostFileSystemService } from "./rpc-BIxQr_wd.js";
|
|
2
|
-
import { INTEGER_TYPES, SCALAR_TYPES, createIRInterpreter, createIRJIT, createIRModule, validateIR } from "@mica-js/ir";
|
|
3
|
-
import { deriveSchematicTopology, parseDeviceReference, parseSchematic, symbolRole } from "@mica-js/core/schematic";
|
|
2
|
+
import { INTEGER_TYPES, SCALAR_TYPES, createIRInterpreter, createIRJIT, createIRModule, toNumber, validateIR } from "@mica-js/ir";
|
|
3
|
+
import { deriveSchematicTopology, parseDeviceReference, parseSchematic, propertyValueProblem, readPropertyDescriptors, symbolRole } from "@mica-js/core/schematic";
|
|
4
4
|
import { Emitter, toDisposable } from "@mica-js/core/lifecycle";
|
|
5
5
|
import { createRpc } from "@mica-js/core/rpc";
|
|
6
6
|
import { loggerService } from "@mica-js/core/logging";
|
|
7
|
-
//#region src/
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
7
|
+
//#region src/electrical-authoring.ts
|
|
8
|
+
var ElectricalDefinitionError = class extends Error {
|
|
9
|
+
code;
|
|
10
|
+
name = "ElectricalDefinitionError";
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/** Resolves a JSON declaration and calls its paired synchronous factory exactly once. */
|
|
17
|
+
function prepareElectricalDevice(definition, values, factory) {
|
|
18
|
+
const raw = record(definition, "device");
|
|
19
|
+
const declarations = record(raw["pins"], "pins");
|
|
20
|
+
const pinDeclarations = [];
|
|
21
|
+
for (const [id, value] of Object.entries(declarations)) {
|
|
22
|
+
resourceId(id);
|
|
23
|
+
const pin = record(value, `pins.${id}`);
|
|
24
|
+
rejectFields(pin, [
|
|
25
|
+
"direction",
|
|
26
|
+
"role",
|
|
27
|
+
"electrical"
|
|
28
|
+
], `pins.${id}`);
|
|
29
|
+
if (![
|
|
30
|
+
"signal",
|
|
31
|
+
"power",
|
|
32
|
+
"gnd"
|
|
33
|
+
].includes(String(pin["kind"]))) fail("electrical/invalid-definition", `pins.${id}.kind must be signal, power or gnd`);
|
|
34
|
+
if (pin["side"] !== void 0 && ![
|
|
35
|
+
"left",
|
|
36
|
+
"right",
|
|
37
|
+
"top",
|
|
38
|
+
"bottom"
|
|
39
|
+
].includes(String(pin["side"]))) fail("electrical/invalid-definition", `pins.${id}.side is invalid`);
|
|
40
|
+
pinDeclarations.push([id, Object.freeze({
|
|
41
|
+
kind: pin["kind"],
|
|
42
|
+
...pin["side"] === void 0 ? {} : { side: pin["side"] }
|
|
43
|
+
})]);
|
|
44
|
+
}
|
|
45
|
+
const resistors = parseBranches(raw["resistors"], declarations, false);
|
|
46
|
+
const connections = parseBranches(raw["connections"], declarations, true);
|
|
47
|
+
const descriptors = readPropertyDescriptors(raw["properties"]);
|
|
48
|
+
const resolved = [];
|
|
49
|
+
for (const [key, descriptor] of descriptors) {
|
|
50
|
+
const value = Object.hasOwn(values, key) ? values[key] : descriptor.default;
|
|
51
|
+
if (value === void 0) continue;
|
|
52
|
+
const problem = propertyValueProblem(descriptor, value);
|
|
53
|
+
if (problem !== void 0) fail("electrical/invalid-parameter", problem.message);
|
|
54
|
+
resolved.push([key, freezeCopy(value)]);
|
|
55
|
+
}
|
|
56
|
+
const properties = Object.freeze(Object.fromEntries(resolved));
|
|
57
|
+
const initializedPins = /* @__PURE__ */ new Map();
|
|
58
|
+
const initializedResistors = /* @__PURE__ */ new Map();
|
|
59
|
+
let open = true;
|
|
60
|
+
const assertOpen = () => {
|
|
61
|
+
if (!open) fail("electrical/factory-closed", "Electrical declarations are closed");
|
|
62
|
+
};
|
|
63
|
+
const electrical = Object.freeze({
|
|
64
|
+
initializeResistor(id, initial) {
|
|
65
|
+
assertOpen();
|
|
66
|
+
const branch = resistors.get(id);
|
|
67
|
+
if (branch === void 0) fail("electrical/unknown-resource", `Unknown resistor "${id}"`);
|
|
68
|
+
if (initializedResistors.has(id)) fail("electrical/duplicate-initialization", `Resistor "${id}" is already initialized`);
|
|
69
|
+
const state = record(initial, `resistor ${id}`);
|
|
70
|
+
positive(state["resistance"], `resistor ${id}.resistance`);
|
|
71
|
+
if (typeof state["enabled"] !== "boolean") fail("electrical/invalid-parameter", `resistor ${id}.enabled must be boolean`);
|
|
72
|
+
optionalCurrent(state, `resistor ${id}`);
|
|
73
|
+
initializedResistors.set(id, freezeCopy({
|
|
74
|
+
pins: branch.pins,
|
|
75
|
+
resistance: initial.resistance,
|
|
76
|
+
enabled: initial.enabled,
|
|
77
|
+
...initial.maxAbsCurrent === void 0 ? {} : { maxAbsCurrent: initial.maxAbsCurrent }
|
|
78
|
+
}));
|
|
79
|
+
},
|
|
80
|
+
initializePin(id, initial) {
|
|
81
|
+
assertOpen();
|
|
82
|
+
if (!Object.hasOwn(declarations, id)) fail("electrical/unknown-resource", `Unknown pin "${id}"`);
|
|
83
|
+
if (initializedPins.has(id)) fail("electrical/duplicate-initialization", `Pin "${id}" is already initialized`);
|
|
84
|
+
validatePin(initial, id);
|
|
85
|
+
initializedPins.set(id, freezeCopy(initial));
|
|
28
86
|
}
|
|
87
|
+
});
|
|
88
|
+
let implementation;
|
|
89
|
+
try {
|
|
90
|
+
implementation = factory(Object.freeze({
|
|
91
|
+
properties,
|
|
92
|
+
electrical
|
|
93
|
+
}));
|
|
94
|
+
if (implementation !== null && (typeof implementation === "object" || typeof implementation === "function") && "then" in implementation) fail("electrical/invalid-definition", "The paired device factory must be synchronous");
|
|
95
|
+
} finally {
|
|
96
|
+
open = false;
|
|
29
97
|
}
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
98
|
+
for (const id of resistors.keys()) if (!initializedResistors.has(id)) fail("electrical/missing-initialization", `Resistor "${id}" has no initial state`);
|
|
99
|
+
return Object.freeze({
|
|
100
|
+
pinDeclarations: Object.freeze(Object.fromEntries(pinDeclarations)),
|
|
101
|
+
properties,
|
|
102
|
+
pins: Object.freeze(Object.fromEntries(initializedPins)),
|
|
103
|
+
resistors: Object.freeze(Object.fromEntries(initializedResistors)),
|
|
104
|
+
connections: Object.freeze(Object.fromEntries(connections)),
|
|
105
|
+
implementation
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function parseBranches(value, pins, contact) {
|
|
109
|
+
const result = /* @__PURE__ */ new Map();
|
|
110
|
+
if (value === void 0) return result;
|
|
111
|
+
for (const [id, item] of Object.entries(record(value, contact ? "connections" : "resistors"))) {
|
|
112
|
+
resourceId(id);
|
|
113
|
+
const branch = record(item, id);
|
|
114
|
+
rejectFields(branch, [
|
|
115
|
+
"resistance",
|
|
116
|
+
"adjustable",
|
|
117
|
+
"initialEnabled"
|
|
118
|
+
], id);
|
|
119
|
+
const endpoints = branch["pins"];
|
|
120
|
+
if (!Array.isArray(endpoints) || endpoints.length !== 2 || endpoints[0] === endpoints[1] || endpoints.some((pin) => typeof pin !== "string" || !Object.hasOwn(pins, pin))) fail("electrical/invalid-definition", `${id}.pins must name two distinct declared pins`);
|
|
121
|
+
const pair = [endpoints[0], endpoints[1]];
|
|
122
|
+
if (contact) {
|
|
123
|
+
const initial = branch["initial"] ?? "open";
|
|
124
|
+
if (initial !== "open" && initial !== "closed") fail("electrical/invalid-definition", `${id}.initial must be open or closed`);
|
|
125
|
+
result.set(id, freezeCopy({
|
|
126
|
+
pins: pair,
|
|
127
|
+
initial
|
|
128
|
+
}));
|
|
129
|
+
} else result.set(id, freezeCopy({ pins: pair }));
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
function validatePin(value, id) {
|
|
134
|
+
const pin = record(value, `pin ${id}`);
|
|
135
|
+
rejectFields(pin, [
|
|
136
|
+
"direction",
|
|
137
|
+
"role",
|
|
138
|
+
"interpretation"
|
|
139
|
+
], id);
|
|
140
|
+
if (![
|
|
141
|
+
"drive",
|
|
142
|
+
"bias",
|
|
143
|
+
"input"
|
|
144
|
+
].some((key) => pin[key] !== void 0)) fail("electrical/invalid-parameter", `pin ${id} needs drive, bias or input parameters`);
|
|
145
|
+
for (const category of [
|
|
146
|
+
"drive",
|
|
147
|
+
"bias",
|
|
148
|
+
"input"
|
|
149
|
+
]) {
|
|
150
|
+
if (pin[category] === void 0) continue;
|
|
151
|
+
const part = record(pin[category], `${id}.${category}`);
|
|
152
|
+
const reference = record(part["reference"], `${id}.${category}.reference`);
|
|
153
|
+
if (typeof reference["source"] !== "string" || reference["source"].length === 0) fail("electrical/invalid-parameter", `${id}.${category} needs an explicit source reference`);
|
|
154
|
+
if (category === "drive") {
|
|
155
|
+
positive(part["highResistance"], `${id}.highResistance`);
|
|
156
|
+
positive(part["lowResistance"], `${id}.lowResistance`);
|
|
157
|
+
if (part["analogResistance"] !== void 0) positive(part["analogResistance"], `${id}.analogResistance`);
|
|
158
|
+
optionalCurrent(part, id);
|
|
159
|
+
} else if (category === "bias") {
|
|
160
|
+
positive(part["upResistance"], `${id}.upResistance`);
|
|
161
|
+
positive(part["downResistance"], `${id}.downResistance`);
|
|
162
|
+
} else {
|
|
163
|
+
rejectFields(part, ["interpretation"], `${id}.input`);
|
|
164
|
+
const low = part["low"];
|
|
165
|
+
const high = part["high"];
|
|
166
|
+
if (typeof low !== "number" || typeof high !== "number" || !Number.isFinite(low) || !Number.isFinite(high) || low < 0 || low >= high || high > 1) fail("electrical/invalid-parameter", `${id} thresholds must satisfy 0 <= low < high <= 1`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function record(value, label) {
|
|
171
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) fail("electrical/invalid-definition", `${label} must be an object`);
|
|
172
|
+
return value;
|
|
173
|
+
}
|
|
174
|
+
function resourceId(id) {
|
|
175
|
+
if (id.length === 0) fail("electrical/invalid-definition", "Resource IDs must not be empty");
|
|
176
|
+
}
|
|
177
|
+
function positive(value, label) {
|
|
178
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) fail("electrical/invalid-parameter", `${label} must be finite and greater than zero`);
|
|
179
|
+
}
|
|
180
|
+
function optionalCurrent(value, label) {
|
|
181
|
+
if (value["maxAbsCurrent"] !== void 0) positive(value["maxAbsCurrent"], `${label}.maxAbsCurrent`);
|
|
182
|
+
}
|
|
183
|
+
function rejectFields(value, fields, label) {
|
|
184
|
+
for (const field of fields) if (Object.hasOwn(value, field)) fail("electrical/invalid-definition", `${label}.${field} is not part of the electrical declaration`);
|
|
185
|
+
}
|
|
186
|
+
function freezeCopy(value) {
|
|
187
|
+
const copy = structuredClone(value);
|
|
188
|
+
const freeze = (item) => {
|
|
189
|
+
if (item === null || typeof item !== "object") return;
|
|
190
|
+
for (const child of Object.values(item)) freeze(child);
|
|
191
|
+
Object.freeze(item);
|
|
192
|
+
};
|
|
193
|
+
freeze(copy);
|
|
194
|
+
return copy;
|
|
195
|
+
}
|
|
196
|
+
function fail(code, message) {
|
|
197
|
+
throw new ElectricalDefinitionError(code, message);
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/unified-ir/compiler/electrical-network.ts
|
|
201
|
+
/** Links prepared authoring resources. Only wires union nodes; resistors never do. */
|
|
202
|
+
function allocateElectricalNetwork(devices, sources, wires) {
|
|
203
|
+
const fail = (message) => {
|
|
204
|
+
throw new ElectricalDefinitionError("electrical/invalid-definition", message);
|
|
205
|
+
};
|
|
206
|
+
const parent = [];
|
|
207
|
+
const makeNode = () => {
|
|
208
|
+
const node = parent.length;
|
|
209
|
+
parent.push(node);
|
|
210
|
+
return node;
|
|
211
|
+
};
|
|
212
|
+
const root = (node) => {
|
|
213
|
+
let current = node;
|
|
214
|
+
while (parent[current] !== current) current = parent[current];
|
|
215
|
+
while (node !== current) {
|
|
216
|
+
const next = parent[node];
|
|
217
|
+
parent[node] = current;
|
|
218
|
+
node = next;
|
|
219
|
+
}
|
|
220
|
+
return current;
|
|
221
|
+
};
|
|
222
|
+
const sourceIndices = /* @__PURE__ */ new Map([["GND", 0]]);
|
|
223
|
+
const initialSources = [{
|
|
224
|
+
node: makeNode(),
|
|
225
|
+
voltage: 0,
|
|
226
|
+
enabled: true
|
|
227
|
+
}];
|
|
228
|
+
for (const [id, source] of Object.entries(sources)) {
|
|
229
|
+
if (!id || sourceIndices.has(id) || !Number.isFinite(source.voltage)) fail(`Invalid or duplicate voltage source "${id}"`);
|
|
230
|
+
sourceIndices.set(id, initialSources.length);
|
|
231
|
+
initialSources.push({
|
|
232
|
+
node: makeNode(),
|
|
233
|
+
voltage: source.voltage,
|
|
234
|
+
enabled: true
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const pinNodes = /* @__PURE__ */ new Map();
|
|
238
|
+
for (const device of devices) {
|
|
239
|
+
if (!device.id || pinNodes.has(device.id)) fail(`Invalid or duplicate device "${device.id}"`);
|
|
240
|
+
pinNodes.set(device.id, new Map(Object.keys(device.prepared.pinDeclarations).map((id) => [id, makeNode()])));
|
|
241
|
+
}
|
|
242
|
+
const reference = (name) => sourceIndices.get(name) ?? fail(`Unknown voltage source "${name}"`);
|
|
243
|
+
const endpoint = (item) => {
|
|
244
|
+
if ("source" in item) return initialSources[reference(item.source)].node;
|
|
245
|
+
return pinNodes.get(item.device)?.get(item.pin) ?? fail(`Unknown pin "${item.device}.${item.pin}"`);
|
|
246
|
+
};
|
|
247
|
+
for (const [a, b] of wires) {
|
|
248
|
+
const left = root(endpoint(a));
|
|
249
|
+
const right = root(endpoint(b));
|
|
250
|
+
if (left !== right) parent[Math.max(left, right)] = Math.min(left, right);
|
|
251
|
+
}
|
|
252
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
253
|
+
const compact = (node) => {
|
|
254
|
+
const representative = root(node);
|
|
255
|
+
let index = nodes.get(representative);
|
|
256
|
+
if (index === void 0) {
|
|
257
|
+
index = nodes.size;
|
|
258
|
+
nodes.set(representative, index);
|
|
259
|
+
}
|
|
260
|
+
return index;
|
|
261
|
+
};
|
|
262
|
+
for (let node = 0; node < parent.length; node++) compact(node);
|
|
263
|
+
const compiledSources = initialSources.map((source) => ({
|
|
264
|
+
...source,
|
|
265
|
+
node: compact(source.node)
|
|
34
266
|
}));
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
267
|
+
const compiledResistors = [];
|
|
268
|
+
const compiledContacts = [];
|
|
269
|
+
const pins = /* @__PURE__ */ new Map();
|
|
270
|
+
const resistors = /* @__PURE__ */ new Map();
|
|
271
|
+
const contacts = /* @__PURE__ */ new Map();
|
|
272
|
+
const currentLimits = /* @__PURE__ */ new Map();
|
|
273
|
+
const branch = (a, b, resistance, enabled, limit) => {
|
|
274
|
+
const index = compiledResistors.length;
|
|
275
|
+
compiledResistors.push({
|
|
276
|
+
a,
|
|
277
|
+
b,
|
|
278
|
+
resistance,
|
|
279
|
+
enabled
|
|
280
|
+
});
|
|
281
|
+
if (limit !== void 0) currentLimits.set(index, limit);
|
|
282
|
+
return index;
|
|
283
|
+
};
|
|
284
|
+
const ground = compiledSources[0].node;
|
|
285
|
+
let nodeCount = nodes.size;
|
|
286
|
+
for (const device of devices) {
|
|
287
|
+
const rawPins = pinNodes.get(device.id);
|
|
288
|
+
const pin = (id) => compact(rawPins.get(id) ?? fail(`Unknown pin "${device.id}.${id}"`));
|
|
289
|
+
const deviceResistors = /* @__PURE__ */ new Map();
|
|
290
|
+
for (const [id, resistor] of Object.entries(device.prepared.resistors)) deviceResistors.set(id, branch(pin(resistor.pins[0]), pin(resistor.pins[1]), resistor.resistance, resistor.enabled, resistor.maxAbsCurrent));
|
|
291
|
+
resistors.set(device.id, deviceResistors);
|
|
292
|
+
const deviceContacts = /* @__PURE__ */ new Map();
|
|
293
|
+
for (const [id, contact] of Object.entries(device.prepared.connections)) {
|
|
294
|
+
deviceContacts.set(id, compiledContacts.length);
|
|
295
|
+
compiledContacts.push({
|
|
296
|
+
a: pin(contact.pins[0]),
|
|
297
|
+
b: pin(contact.pins[1]),
|
|
298
|
+
closed: contact.initial === "closed"
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
contacts.set(device.id, deviceContacts);
|
|
302
|
+
const devicePins = /* @__PURE__ */ new Map();
|
|
303
|
+
for (const id of rawPins.keys()) {
|
|
304
|
+
const node = pin(id);
|
|
305
|
+
const description = Object.hasOwn(device.prepared.pins, id) ? device.prepared.pins[id] : {};
|
|
306
|
+
let drive;
|
|
307
|
+
let bias;
|
|
308
|
+
let input;
|
|
309
|
+
if (description.drive !== void 0) {
|
|
310
|
+
const config = description.drive;
|
|
311
|
+
const supply = reference(config.reference.source);
|
|
312
|
+
const high = branch(node, compiledSources[supply].node, config.highResistance, false, config.maxAbsCurrent);
|
|
313
|
+
const low = branch(node, ground, config.lowResistance, false, config.maxAbsCurrent);
|
|
314
|
+
let analog;
|
|
315
|
+
if (config.analogResistance !== void 0) {
|
|
316
|
+
const source = compiledSources.length;
|
|
317
|
+
const sourceNode = nodeCount++;
|
|
318
|
+
compiledSources.push({
|
|
319
|
+
node: sourceNode,
|
|
320
|
+
voltage: 0,
|
|
321
|
+
enabled: true
|
|
322
|
+
});
|
|
323
|
+
analog = Object.freeze({
|
|
324
|
+
source,
|
|
325
|
+
resistor: branch(node, sourceNode, config.analogResistance, false, config.maxAbsCurrent)
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
drive = Object.freeze({
|
|
329
|
+
high,
|
|
330
|
+
low,
|
|
331
|
+
reference: supply,
|
|
332
|
+
...analog === void 0 ? {} : { analog },
|
|
333
|
+
...config.maxAbsCurrent === void 0 ? {} : { maxAbsCurrent: config.maxAbsCurrent }
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
if (description.bias !== void 0) {
|
|
337
|
+
const config = description.bias;
|
|
338
|
+
const supply = reference(config.reference.source);
|
|
339
|
+
bias = Object.freeze({
|
|
340
|
+
up: branch(node, compiledSources[supply].node, config.upResistance, false),
|
|
341
|
+
down: branch(node, ground, config.downResistance, false)
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
if (description.input !== void 0) {
|
|
345
|
+
const config = description.input;
|
|
346
|
+
input = Object.freeze({
|
|
347
|
+
reference: reference(config.reference.source),
|
|
348
|
+
low: config.low,
|
|
349
|
+
high: config.high
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
devicePins.set(id, Object.freeze({
|
|
353
|
+
node,
|
|
354
|
+
...drive === void 0 ? {} : { drive },
|
|
355
|
+
...bias === void 0 ? {} : { bias },
|
|
356
|
+
...input === void 0 ? {} : { input }
|
|
357
|
+
}));
|
|
358
|
+
}
|
|
359
|
+
pins.set(device.id, devicePins);
|
|
42
360
|
}
|
|
361
|
+
const network = Object.freeze({
|
|
362
|
+
nodes: nodeCount,
|
|
363
|
+
sources: Object.freeze(compiledSources.map((source) => Object.freeze(source))),
|
|
364
|
+
resistors: Object.freeze(compiledResistors.map((resistor) => Object.freeze(resistor))),
|
|
365
|
+
contacts: Object.freeze(compiledContacts.map((contact) => Object.freeze(contact)))
|
|
366
|
+
});
|
|
43
367
|
return Object.freeze({
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
368
|
+
network,
|
|
369
|
+
pins,
|
|
370
|
+
resistors,
|
|
371
|
+
contacts,
|
|
372
|
+
sources: sourceIndices,
|
|
373
|
+
currentLimits
|
|
47
374
|
});
|
|
48
375
|
}
|
|
49
376
|
//#endregion
|
|
@@ -53,14 +380,15 @@ function createModuleValidation(module, updateResources = []) {
|
|
|
53
380
|
*
|
|
54
381
|
* Every device of a circuit shares one global pin address space, so the
|
|
55
382
|
* compiler and every device kernel must agree on the capacity, the per-device
|
|
56
|
-
* stride and the
|
|
57
|
-
*
|
|
383
|
+
* stride and the physical output configuration values. Capacity and stride are limits
|
|
384
|
+
* checked at allocation time; the shared pin memories are sized to the pins a
|
|
385
|
+
* circuit actually declares, so a larger ceiling costs no runtime memory.
|
|
58
386
|
*/
|
|
59
|
-
/** Global pin addresses available to one circuit (8 devices x
|
|
60
|
-
var UNIFIED_PIN_CAPACITY =
|
|
61
|
-
/** Global pin addresses
|
|
62
|
-
var DEVICE_PIN_STRIDE =
|
|
63
|
-
/**
|
|
387
|
+
/** Global pin addresses available to one circuit (8 devices x 512 pins). */
|
|
388
|
+
var UNIFIED_PIN_CAPACITY = 4096;
|
|
389
|
+
/** Global pin addresses one device may own; enough for the largest packages. */
|
|
390
|
+
var DEVICE_PIN_STRIDE = 512;
|
|
391
|
+
/** Physical output configuration values. */
|
|
64
392
|
var PIN_MODE = Object.freeze({
|
|
65
393
|
highZ: 0,
|
|
66
394
|
pushPull: 1,
|
|
@@ -68,6 +396,875 @@ var PIN_MODE = Object.freeze({
|
|
|
68
396
|
analog: 3
|
|
69
397
|
});
|
|
70
398
|
//#endregion
|
|
399
|
+
//#region src/unified-ir/compiler/floating-input.ts
|
|
400
|
+
var u = (b, n) => b.const("u32", n);
|
|
401
|
+
function mix(b, x) {
|
|
402
|
+
x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 16))), u(b, 2146121005));
|
|
403
|
+
x = b.int.mul(b.int.xor(x, b.int.lshr(x, u(b, 15))), u(b, 2221713035));
|
|
404
|
+
return b.int.xor(x, b.int.lshr(x, u(b, 16)));
|
|
405
|
+
}
|
|
406
|
+
function random(b, x) {
|
|
407
|
+
return b.float.div(b.convert.intToFloat("f64", x), b.const("f64", 4294967296));
|
|
408
|
+
}
|
|
409
|
+
/** mica-floating-v2 phase identity is hashed at build time except for the decimal episode count. */
|
|
410
|
+
function createFloatingInput(module, solver, clock, prefix, seed, deviceId, pinName, node, reference, sample = module.func(`${prefix}_sample`, {
|
|
411
|
+
params: [],
|
|
412
|
+
results: ["f64"]
|
|
413
|
+
})) {
|
|
414
|
+
const text = JSON.stringify([
|
|
415
|
+
"mica-floating-v2",
|
|
416
|
+
seed,
|
|
417
|
+
deviceId,
|
|
418
|
+
pinName
|
|
419
|
+
]).slice(0, -1) + ",";
|
|
420
|
+
let prefixHash = 2166136261;
|
|
421
|
+
for (const byte of new TextEncoder().encode(text)) prefixHash = Math.imul(prefixHash ^ byte, 16777619) >>> 0;
|
|
422
|
+
const count = module.state(`${prefix}_count`, "u32", 0);
|
|
423
|
+
const wasFloating = module.state(`${prefix}_floating`, "bool", false);
|
|
424
|
+
const episode = module.state(`${prefix}_episode`, "u32", 0);
|
|
425
|
+
const initialized = module.state(`${prefix}_initialized`, "bool", false);
|
|
426
|
+
const initial = module.state(`${prefix}_initial`, "f64", 0);
|
|
427
|
+
const update = module.func(`${prefix}_update`, {
|
|
428
|
+
params: [],
|
|
429
|
+
results: []
|
|
430
|
+
});
|
|
431
|
+
const ready = (b) => b.bool.and(b.array.load(solver.sourceEnabled, u(b, reference)), b.float.cmp("gt", b.array.load(solver.sourceVoltage, u(b, reference)), b.const("f64", 0)));
|
|
432
|
+
update.body((b) => {
|
|
433
|
+
const floating = b.int.cmp("eq", b.array.load(solver.voltageState, u(b, node)), b.const("u8", 1));
|
|
434
|
+
const enter = b.block([]);
|
|
435
|
+
const after = b.block([]);
|
|
436
|
+
b.branch(b.bool.and(floating, b.bool.not(b.state.load(wasFloating))), {
|
|
437
|
+
target: enter,
|
|
438
|
+
args: []
|
|
439
|
+
}, {
|
|
440
|
+
target: after,
|
|
441
|
+
args: []
|
|
442
|
+
});
|
|
443
|
+
b.at(enter, (b) => {
|
|
444
|
+
const next = b.int.add(b.state.load(count), u(b, 1));
|
|
445
|
+
b.state.store(count, next);
|
|
446
|
+
let hash = u(b, prefixHash);
|
|
447
|
+
let started = b.const("bool", false);
|
|
448
|
+
for (const power of [
|
|
449
|
+
1e9,
|
|
450
|
+
1e8,
|
|
451
|
+
1e7,
|
|
452
|
+
1e6,
|
|
453
|
+
1e5,
|
|
454
|
+
1e4,
|
|
455
|
+
1e3,
|
|
456
|
+
100,
|
|
457
|
+
10,
|
|
458
|
+
1
|
|
459
|
+
]) {
|
|
460
|
+
const digit = b.int.rem(b.int.div(next, u(b, power)), u(b, 10));
|
|
461
|
+
started = b.bool.or(started, power === 1 ? b.const("bool", true) : b.int.cmp("ne", digit, u(b, 0)));
|
|
462
|
+
hash = b.select(started, b.int.mul(b.int.xor(hash, b.int.add(digit, u(b, 48))), u(b, 16777619)), hash);
|
|
463
|
+
}
|
|
464
|
+
hash = b.int.mul(b.int.xor(hash, u(b, 93)), u(b, 16777619));
|
|
465
|
+
b.state.store(episode, b.select(b.int.cmp("eq", hash, u(b, 0)), u(b, 1), hash));
|
|
466
|
+
b.state.store(initialized, b.const("bool", false));
|
|
467
|
+
b.jump(after, []);
|
|
468
|
+
});
|
|
469
|
+
b.at(after, (b) => {
|
|
470
|
+
b.state.store(wasFloating, floating);
|
|
471
|
+
const initialize = b.block([]);
|
|
472
|
+
const done = b.block([]);
|
|
473
|
+
b.branch(b.bool.and(floating, b.bool.and(ready(b), b.bool.not(b.state.load(initialized)))), {
|
|
474
|
+
target: initialize,
|
|
475
|
+
args: []
|
|
476
|
+
}, {
|
|
477
|
+
target: done,
|
|
478
|
+
args: []
|
|
479
|
+
});
|
|
480
|
+
b.at(initialize, (b) => {
|
|
481
|
+
let value = b.state.load(episode);
|
|
482
|
+
value = b.int.xor(value, b.int.shl(value, u(b, 13)));
|
|
483
|
+
value = b.int.xor(value, b.int.lshr(value, u(b, 17)));
|
|
484
|
+
value = b.int.xor(value, b.int.shl(value, u(b, 5)));
|
|
485
|
+
b.state.store(initial, b.float.mul(random(b, value), b.array.load(solver.sourceVoltage, u(b, reference))));
|
|
486
|
+
b.state.store(initialized, b.const("bool", true));
|
|
487
|
+
b.jump(done, []);
|
|
488
|
+
});
|
|
489
|
+
b.at(done, (b) => b.return([]));
|
|
490
|
+
});
|
|
491
|
+
});
|
|
492
|
+
sample.body((b) => {
|
|
493
|
+
const active = b.block([]);
|
|
494
|
+
const gated = b.block([]);
|
|
495
|
+
b.branch(ready(b), {
|
|
496
|
+
target: active,
|
|
497
|
+
args: []
|
|
498
|
+
}, {
|
|
499
|
+
target: gated,
|
|
500
|
+
args: []
|
|
501
|
+
});
|
|
502
|
+
b.at(gated, (b) => b.return([b.const("f64", 0)]));
|
|
503
|
+
b.at(active, (b) => {
|
|
504
|
+
const physical = b.block([]);
|
|
505
|
+
const floating = b.block([]);
|
|
506
|
+
b.branch(b.int.cmp("eq", b.array.load(solver.voltageState, u(b, node)), b.const("u8", 0)), {
|
|
507
|
+
target: physical,
|
|
508
|
+
args: []
|
|
509
|
+
}, {
|
|
510
|
+
target: floating,
|
|
511
|
+
args: []
|
|
512
|
+
});
|
|
513
|
+
b.at(physical, (b) => b.return([b.array.load(solver.voltage, u(b, node))]));
|
|
514
|
+
b.at(floating, (b) => {
|
|
515
|
+
const value = mix(b, b.int.xor(mix(b, b.int.xor(b.state.load(episode), b.array.load(clock, u(b, 0)))), b.array.load(clock, u(b, 1))));
|
|
516
|
+
const noise = b.float.mul(b.float.sub(b.float.mul(random(b, value), b.const("f64", 2)), b.const("f64", 1)), b.const("f64", .1));
|
|
517
|
+
const raw = b.float.add(b.state.load(initial), noise);
|
|
518
|
+
const supply = b.array.load(solver.sourceVoltage, u(b, reference));
|
|
519
|
+
b.return([b.select(b.float.cmp("lt", raw, b.const("f64", 0)), b.const("f64", 0), b.select(b.float.cmp("gt", raw, supply), supply, raw))]);
|
|
520
|
+
});
|
|
521
|
+
});
|
|
522
|
+
});
|
|
523
|
+
return {
|
|
524
|
+
update,
|
|
525
|
+
sample
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
//#endregion
|
|
529
|
+
//#region src/unified-ir/compiler/resistive-solver.ts
|
|
530
|
+
var RESISTIVE_FAULT = Object.freeze({
|
|
531
|
+
none: 0,
|
|
532
|
+
invalidParameter: 1,
|
|
533
|
+
sourceConflict: 2,
|
|
534
|
+
numericalFailure: 3
|
|
535
|
+
});
|
|
536
|
+
Object.freeze({
|
|
537
|
+
determinate: 0,
|
|
538
|
+
floating: 1,
|
|
539
|
+
indeterminate: 2
|
|
540
|
+
});
|
|
541
|
+
var Flow = class {
|
|
542
|
+
b;
|
|
543
|
+
constructor(b) {
|
|
544
|
+
this.b = b;
|
|
545
|
+
}
|
|
546
|
+
u(value) {
|
|
547
|
+
return this.b.const("u32", value);
|
|
548
|
+
}
|
|
549
|
+
f(value) {
|
|
550
|
+
return this.b.const("f64", value);
|
|
551
|
+
}
|
|
552
|
+
load(array, index) {
|
|
553
|
+
return this.b.array.load(array, typeof index === "number" ? this.u(index) : index);
|
|
554
|
+
}
|
|
555
|
+
store(array, index, value) {
|
|
556
|
+
this.b.array.store(array, typeof index === "number" ? this.u(index) : index, value);
|
|
557
|
+
}
|
|
558
|
+
abs(value) {
|
|
559
|
+
return this.b.select(this.b.float.cmp("lt", value, this.f(0)), this.b.float.sub(this.f(0), value), value);
|
|
560
|
+
}
|
|
561
|
+
*when(condition, emit) {
|
|
562
|
+
yield {
|
|
563
|
+
kind: "when",
|
|
564
|
+
condition,
|
|
565
|
+
emit
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
*loop(count, emit) {
|
|
569
|
+
yield {
|
|
570
|
+
kind: "loop",
|
|
571
|
+
count,
|
|
572
|
+
emit
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
*guard(valid, fault, code, onFailure) {
|
|
576
|
+
yield {
|
|
577
|
+
kind: "guard",
|
|
578
|
+
valid,
|
|
579
|
+
fault,
|
|
580
|
+
code,
|
|
581
|
+
...onFailure === void 0 ? {} : { onFailure }
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
run(program) {
|
|
585
|
+
this.advance(program(), this.b, () => {});
|
|
586
|
+
}
|
|
587
|
+
advance(program, builder, finish) {
|
|
588
|
+
this.b = builder;
|
|
589
|
+
if (program === void 0) {
|
|
590
|
+
finish(this.b);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
const result = program.next();
|
|
594
|
+
if (result.done) {
|
|
595
|
+
finish(this.b);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const step = result.value;
|
|
599
|
+
const owner = this.b;
|
|
600
|
+
const done = owner.block([]);
|
|
601
|
+
if (step.kind === "guard") {
|
|
602
|
+
const failed = owner.block([]);
|
|
603
|
+
owner.branch(step.valid, {
|
|
604
|
+
target: done,
|
|
605
|
+
args: []
|
|
606
|
+
}, {
|
|
607
|
+
target: failed,
|
|
608
|
+
args: []
|
|
609
|
+
});
|
|
610
|
+
owner.at(failed, (b) => {
|
|
611
|
+
b.state.store(step.fault, b.const("u8", step.code));
|
|
612
|
+
step.onFailure?.(b);
|
|
613
|
+
b.return([]);
|
|
614
|
+
});
|
|
615
|
+
} else if (step.kind === "when") {
|
|
616
|
+
const yes = owner.block([]);
|
|
617
|
+
owner.branch(step.condition, {
|
|
618
|
+
target: yes,
|
|
619
|
+
args: []
|
|
620
|
+
}, {
|
|
621
|
+
target: done,
|
|
622
|
+
args: []
|
|
623
|
+
});
|
|
624
|
+
owner.at(yes, (b) => this.advance(step.emit(), b, (tail) => {
|
|
625
|
+
tail.jump(done, []);
|
|
626
|
+
}));
|
|
627
|
+
} else {
|
|
628
|
+
const header = owner.block(["u32"]);
|
|
629
|
+
const body = owner.block(["u32"]);
|
|
630
|
+
owner.jump(header, [owner.const("u32", 0)]);
|
|
631
|
+
owner.at(header, (b, [index]) => {
|
|
632
|
+
b.branch(b.int.cmp("lt", index, typeof step.count === "number" ? b.const("u32", step.count) : step.count), {
|
|
633
|
+
target: body,
|
|
634
|
+
args: [index]
|
|
635
|
+
}, {
|
|
636
|
+
target: done,
|
|
637
|
+
args: []
|
|
638
|
+
});
|
|
639
|
+
});
|
|
640
|
+
owner.at(body, (b, [index]) => this.advance(step.emit(index), b, (tail) => {
|
|
641
|
+
tail.jump(header, [tail.int.add(index, tail.const("u32", 1))]);
|
|
642
|
+
}));
|
|
643
|
+
}
|
|
644
|
+
owner.at(done, (b) => this.advance(program, b, finish));
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
/** Generates a linear solve inside the caller's unified module; no host solver callbacks. */
|
|
648
|
+
function generateResistiveSolver(module, network, prefix, onPublish = []) {
|
|
649
|
+
validateNetwork(network);
|
|
650
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix)) throw new Error("Invalid resistive solver prefix");
|
|
651
|
+
const n = network.nodes;
|
|
652
|
+
const matrixSize = n * n;
|
|
653
|
+
const sourceNodes = new Set(network.sources.map((source) => source.node));
|
|
654
|
+
const unknownNodes = Array.from({ length: n }, (_, i) => i).filter((i) => !sourceNodes.has(i));
|
|
655
|
+
const singleton = network.contacts.length === 0 && unknownNodes.length === 1 ? unknownNodes[0] : void 0;
|
|
656
|
+
const array = (name, type, initial) => module.array(`${prefix}_${name}`, type, initial);
|
|
657
|
+
const floats = (name, length) => array(name, "f64", Array(Math.max(1, length)).fill(0));
|
|
658
|
+
const flags = (name, length) => array(name, "bool", Array(Math.max(1, length)).fill(false));
|
|
659
|
+
const resistance = array("resistance", "f64", network.resistors.length ? network.resistors.map((r) => r.resistance) : [1]);
|
|
660
|
+
const resistorEnabled = array("resistor_enabled", "bool", network.resistors.length ? network.resistors.map((r) => r.enabled) : [false]);
|
|
661
|
+
const sourceVoltage = array("source_voltage", "f64", network.sources.length ? network.sources.map((s) => s.voltage) : [0]);
|
|
662
|
+
const sourceEnabled = array("source_enabled", "bool", network.sources.length ? network.sources.map((s) => s.enabled) : [false]);
|
|
663
|
+
const contactClosed = array("contact_closed", "bool", network.contacts.length ? network.contacts.map((c) => c.closed) : [false]);
|
|
664
|
+
const voltage = floats("voltage", n);
|
|
665
|
+
const voltageState = array("voltage_state", "u8", Array(n).fill(1));
|
|
666
|
+
const current = floats("current", network.resistors.length);
|
|
667
|
+
const currentState = array("current_state", "u8", Array(Math.max(1, network.resistors.length)).fill(2));
|
|
668
|
+
const sourceCurrent = floats("source_current", network.sources.length);
|
|
669
|
+
const sourceCurrentState = array("source_current_state", "u8", Array(Math.max(1, network.sources.length)).fill(2));
|
|
670
|
+
const contactCurrent = floats("contact_current", network.contacts.length);
|
|
671
|
+
const contactCurrentState = array("contact_current_state", "u8", Array(Math.max(1, network.contacts.length)).fill(2));
|
|
672
|
+
const candidateContactCurrent = floats("candidate_contact_current", network.contacts.length);
|
|
673
|
+
const candidateContactState = array("candidate_contact_state", "u8", Array(Math.max(1, network.contacts.length)).fill(2));
|
|
674
|
+
const contactSide = flags("contact_side", n);
|
|
675
|
+
const fault = module.state(`${prefix}_fault`, "u8", 0);
|
|
676
|
+
const faultTargetKind = module.state(`${prefix}_fault_target_kind`, "u8", 0);
|
|
677
|
+
const faultTargetIndex = module.state(`${prefix}_fault_target_index`, "u32", 0);
|
|
678
|
+
const origin = (kind, index) => (b) => {
|
|
679
|
+
b.state.store(faultTargetKind, b.const("u8", kind));
|
|
680
|
+
b.state.store(faultTargetIndex, typeof index === "number" ? b.const("u32", index) : index);
|
|
681
|
+
};
|
|
682
|
+
const factorizations = module.state(`${prefix}_factorizations`, "u32", 0);
|
|
683
|
+
const validFactors = module.state(`${prefix}_valid_factors`, "bool", false);
|
|
684
|
+
const topologyVersion = module.state(`${prefix}_topology_version`, "u32", 0);
|
|
685
|
+
const matrixVersion = module.state(`${prefix}_matrix_version`, "u32", 0);
|
|
686
|
+
const rhsVersion = module.state(`${prefix}_rhs_version`, "u32", 0);
|
|
687
|
+
const factoredTopology = module.state(`${prefix}_factored_topology`, "u32", 0);
|
|
688
|
+
const factoredMatrix = module.state(`${prefix}_factored_matrix`, "u32", 0);
|
|
689
|
+
const solvedRhs = module.state(`${prefix}_solved_rhs`, "u32", 0);
|
|
690
|
+
const hasSolution = module.state(`${prefix}_has_solution`, "bool", false);
|
|
691
|
+
const invalidator = (kind, version) => {
|
|
692
|
+
const fn = module.func(`${prefix}_invalidate_${kind}`, {
|
|
693
|
+
params: [],
|
|
694
|
+
results: []
|
|
695
|
+
});
|
|
696
|
+
fn.body((b) => {
|
|
697
|
+
b.state.store(version, b.int.add(b.state.load(version), b.const("u32", 1)));
|
|
698
|
+
b.state.store(hasSolution, b.const("bool", false));
|
|
699
|
+
if (kind !== "rhs") b.state.store(validFactors, b.const("bool", false));
|
|
700
|
+
b.return([]);
|
|
701
|
+
});
|
|
702
|
+
return fn;
|
|
703
|
+
};
|
|
704
|
+
const invalidate = Object.freeze({
|
|
705
|
+
topology: invalidator("topology", topologyVersion),
|
|
706
|
+
matrix: invalidator("matrix", matrixVersion),
|
|
707
|
+
rhs: invalidator("rhs", rhsVersion)
|
|
708
|
+
});
|
|
709
|
+
const label = array("label", "u32", Array.from({ length: n }, (_, i) => i));
|
|
710
|
+
const permutation = array("permutation", "u32", Array.from({ length: n }, (_, i) => i));
|
|
711
|
+
const known = flags("known", n);
|
|
712
|
+
const reachable = flags("reachable", n);
|
|
713
|
+
const anchor = floats("anchor", n);
|
|
714
|
+
const assigned = flags("assigned", n);
|
|
715
|
+
const conductance = floats("conductance", matrixSize);
|
|
716
|
+
const system = floats("system", matrixSize);
|
|
717
|
+
const factors = floats("factors", matrixSize);
|
|
718
|
+
const scale = floats("scale", n);
|
|
719
|
+
const rhs = floats("rhs", n);
|
|
720
|
+
const work = floats("work", n);
|
|
721
|
+
const candidate = floats("candidate", n);
|
|
722
|
+
const candidateCurrent = floats("candidate_current", network.resistors.length);
|
|
723
|
+
const candidateSourceCurrent = floats("candidate_source_current", network.sources.length);
|
|
724
|
+
const candidateSourceState = array("candidate_source_state", "u8", Array(Math.max(1, network.sources.length)).fill(2));
|
|
725
|
+
const group = array("group", "u32", Array.from({ length: n }, (_, i) => i));
|
|
726
|
+
const groupSize = array("group_size", "u32", Array(n).fill(0));
|
|
727
|
+
const groupNodes = array("group_nodes", "u32", Array(matrixSize).fill(0));
|
|
728
|
+
const groupDirty = flags("group_dirty", n);
|
|
729
|
+
const groupSolveDirty = flags("group_solve_dirty", n);
|
|
730
|
+
const groupRebuilds = array("group_rebuilds", "u32", Array(n).fill(0));
|
|
731
|
+
const groupSolves = array("group_solves", "u32", Array(n).fill(0));
|
|
732
|
+
const previousResistance = floats("previous_resistance", network.resistors.length);
|
|
733
|
+
const previousEnabled = flags("previous_enabled", network.resistors.length);
|
|
734
|
+
const previousSourceEnabled = flags("previous_source_enabled", network.sources.length);
|
|
735
|
+
const factorsInitialized = module.state(`${prefix}_factors_initialized`, "bool", false);
|
|
736
|
+
const repartition = module.state(`${prefix}_repartition`, "bool", true);
|
|
737
|
+
const relaxing = module.state(`${prefix}_relaxing`, "bool", true);
|
|
738
|
+
const pivotRow = module.state(`${prefix}_pivot_row`, "u32", 0);
|
|
739
|
+
const pivotMagnitude = module.state(`${prefix}_pivot_magnitude`, "f64", 0);
|
|
740
|
+
const accumulator = module.state(`${prefix}_accumulator`, "f64", 0);
|
|
741
|
+
const magnitude = module.state(`${prefix}_magnitude`, "f64", 0);
|
|
742
|
+
const factorGeneral = module.func(`${prefix}_factor_general`, {
|
|
743
|
+
params: [],
|
|
744
|
+
results: []
|
|
745
|
+
});
|
|
746
|
+
const factor = singleton === void 0 ? factorGeneral : module.func(`${prefix}_factor`, {
|
|
747
|
+
params: [],
|
|
748
|
+
results: []
|
|
749
|
+
});
|
|
750
|
+
const solve = module.func(`${prefix}_solve`, {
|
|
751
|
+
params: [],
|
|
752
|
+
results: []
|
|
753
|
+
});
|
|
754
|
+
const at = (q, row, column) => q.b.int.add(q.b.int.mul(row, q.u(n)), column);
|
|
755
|
+
const addAt = (q, row, column, delta) => {
|
|
756
|
+
const index = at(q, row, column);
|
|
757
|
+
q.store(conductance, index, q.b.float.add(q.load(conductance, index), delta));
|
|
758
|
+
};
|
|
759
|
+
factorGeneral.body((builder) => {
|
|
760
|
+
const q = new Flow(builder);
|
|
761
|
+
q.run(function* () {
|
|
762
|
+
q.b.state.store(validFactors, q.b.const("bool", false));
|
|
763
|
+
yield* q.loop(n, function(i) {
|
|
764
|
+
q.store(label, i, i);
|
|
765
|
+
q.store(known, i, q.b.const("bool", false));
|
|
766
|
+
q.store(reachable, i, q.b.const("bool", false));
|
|
767
|
+
});
|
|
768
|
+
q.b.state.store(relaxing, q.b.const("bool", true));
|
|
769
|
+
yield* q.loop(n, function* () {
|
|
770
|
+
yield* q.when(q.b.state.load(relaxing), function* () {
|
|
771
|
+
q.b.state.store(relaxing, q.b.const("bool", false));
|
|
772
|
+
for (const [index, contact] of network.contacts.entries()) yield* q.when(q.load(contactClosed, index), function() {
|
|
773
|
+
const a = q.load(label, contact.a);
|
|
774
|
+
const b = q.load(label, contact.b);
|
|
775
|
+
const min = q.b.select(q.b.int.cmp("lt", a, b), a, b);
|
|
776
|
+
q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp("ne", a, b)));
|
|
777
|
+
q.store(label, contact.a, min);
|
|
778
|
+
q.store(label, contact.b, min);
|
|
779
|
+
});
|
|
780
|
+
});
|
|
781
|
+
});
|
|
782
|
+
for (const [index, source] of network.sources.entries()) yield* q.when(q.load(sourceEnabled, index), function() {
|
|
783
|
+
const root = q.load(label, source.node);
|
|
784
|
+
q.store(known, root, q.b.const("bool", true));
|
|
785
|
+
q.store(reachable, root, q.b.const("bool", true));
|
|
786
|
+
});
|
|
787
|
+
q.b.state.store(relaxing, q.b.const("bool", true));
|
|
788
|
+
yield* q.loop(n, function* () {
|
|
789
|
+
yield* q.when(q.b.state.load(relaxing), function* () {
|
|
790
|
+
q.b.state.store(relaxing, q.b.const("bool", false));
|
|
791
|
+
for (const [index, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, index), function() {
|
|
792
|
+
const a = q.load(label, resistor.a);
|
|
793
|
+
const b = q.load(label, resistor.b);
|
|
794
|
+
const ra = q.load(reachable, a);
|
|
795
|
+
const rb = q.load(reachable, b);
|
|
796
|
+
const connected = q.b.bool.or(ra, rb);
|
|
797
|
+
q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.bool.xor(ra, rb)));
|
|
798
|
+
q.store(reachable, a, connected);
|
|
799
|
+
q.store(reachable, b, connected);
|
|
800
|
+
});
|
|
801
|
+
});
|
|
802
|
+
});
|
|
803
|
+
q.b.state.store(repartition, q.b.bool.or(q.b.bool.not(q.b.state.load(factorsInitialized)), q.b.int.cmp("ne", q.b.state.load(topologyVersion), q.b.state.load(factoredTopology))));
|
|
804
|
+
for (const [i] of network.sources.entries()) q.b.state.store(repartition, q.b.bool.or(q.b.state.load(repartition), q.b.bool.xor(q.load(sourceEnabled, i), q.load(previousSourceEnabled, i))));
|
|
805
|
+
yield* q.loop(n, function(i) {
|
|
806
|
+
q.store(group, i, i);
|
|
807
|
+
q.store(groupSize, i, q.u(0));
|
|
808
|
+
});
|
|
809
|
+
q.b.state.store(relaxing, q.b.const("bool", true));
|
|
810
|
+
yield* q.loop(n, function* () {
|
|
811
|
+
yield* q.when(q.b.state.load(relaxing), function* () {
|
|
812
|
+
q.b.state.store(relaxing, q.b.const("bool", false));
|
|
813
|
+
for (const resistor of network.resistors) {
|
|
814
|
+
const a = q.load(label, resistor.a);
|
|
815
|
+
const b = q.load(label, resistor.b);
|
|
816
|
+
yield* q.when(q.b.bool.not(q.b.bool.or(q.load(known, a), q.load(known, b))), function() {
|
|
817
|
+
const ga = q.load(group, a);
|
|
818
|
+
const gb = q.load(group, b);
|
|
819
|
+
const root = q.b.select(q.b.int.cmp("lt", ga, gb), ga, gb);
|
|
820
|
+
q.b.state.store(relaxing, q.b.bool.or(q.b.state.load(relaxing), q.b.int.cmp("ne", ga, gb)));
|
|
821
|
+
q.store(group, a, root);
|
|
822
|
+
q.store(group, b, root);
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
});
|
|
827
|
+
yield* q.loop(n, function(i) {
|
|
828
|
+
q.store(groupDirty, i, q.b.state.load(repartition));
|
|
829
|
+
});
|
|
830
|
+
for (const [i, resistor] of network.resistors.entries()) yield* q.when(q.b.bool.or(q.b.float.cmp("ne", q.load(resistance, i), q.load(previousResistance, i)), q.b.bool.xor(q.load(resistorEnabled, i), q.load(previousEnabled, i))), function() {
|
|
831
|
+
q.store(groupDirty, q.load(group, q.load(label, resistor.a)), q.b.const("bool", true));
|
|
832
|
+
q.store(groupDirty, q.load(group, q.load(label, resistor.b)), q.b.const("bool", true));
|
|
833
|
+
});
|
|
834
|
+
yield* q.loop(n, function* (row) {
|
|
835
|
+
yield* q.when(q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))), function() {
|
|
836
|
+
const root = q.load(group, row);
|
|
837
|
+
const size = q.load(groupSize, root);
|
|
838
|
+
q.store(groupNodes, at(q, root, size), row);
|
|
839
|
+
q.store(groupSize, root, q.b.int.add(size, q.u(1)));
|
|
840
|
+
});
|
|
841
|
+
});
|
|
842
|
+
yield* q.loop(matrixSize, function(i) {
|
|
843
|
+
q.store(conductance, i, q.f(0));
|
|
844
|
+
});
|
|
845
|
+
for (const [index, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, index), function* () {
|
|
846
|
+
const a = q.load(label, resistor.a);
|
|
847
|
+
const b = q.load(label, resistor.b);
|
|
848
|
+
const g = q.b.float.div(q.f(1), q.load(resistance, index));
|
|
849
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp("gt", g, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(1, index));
|
|
850
|
+
yield* q.when(q.b.int.cmp("ne", a, b), function() {
|
|
851
|
+
const negative = q.b.float.sub(q.f(0), g);
|
|
852
|
+
addAt(q, a, a, g);
|
|
853
|
+
addAt(q, b, b, g);
|
|
854
|
+
addAt(q, a, b, negative);
|
|
855
|
+
addAt(q, b, a, negative);
|
|
856
|
+
});
|
|
857
|
+
});
|
|
858
|
+
yield* q.loop(n, function* (row) {
|
|
859
|
+
const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));
|
|
860
|
+
const diagonal = q.load(conductance, at(q, row, row));
|
|
861
|
+
const divisor = q.b.select(active, diagonal, q.f(1));
|
|
862
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp("gt", divisor, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
863
|
+
q.store(scale, row, divisor);
|
|
864
|
+
yield* q.when(q.b.bool.and(active, q.load(groupDirty, q.load(group, row))), function* () {
|
|
865
|
+
yield* q.loop(n, function* (column) {
|
|
866
|
+
const coefficient = q.b.select(q.load(known, column), q.f(0), q.b.float.div(q.load(conductance, at(q, row, column)), divisor));
|
|
867
|
+
yield* q.guard(q.b.float.isFinite(coefficient), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
868
|
+
q.store(system, at(q, row, column), coefficient);
|
|
869
|
+
q.store(factors, at(q, row, column), coefficient);
|
|
870
|
+
});
|
|
871
|
+
q.store(permutation, row, row);
|
|
872
|
+
});
|
|
873
|
+
});
|
|
874
|
+
yield* q.loop(n, function* (root) {
|
|
875
|
+
const size = q.load(groupSize, root);
|
|
876
|
+
yield* q.when(q.b.bool.and(q.load(groupDirty, root), q.b.int.cmp("gt", size, q.u(0))), function* () {
|
|
877
|
+
q.store(groupRebuilds, root, q.b.int.add(q.load(groupRebuilds, root), q.u(1)));
|
|
878
|
+
yield* q.when(q.b.int.cmp("gt", size, q.u(1)), function* () {
|
|
879
|
+
yield* q.loop(size, function* (ki) {
|
|
880
|
+
const k = q.load(groupNodes, at(q, root, ki));
|
|
881
|
+
q.b.state.store(pivotRow, k);
|
|
882
|
+
q.b.state.store(pivotMagnitude, q.f(0));
|
|
883
|
+
yield* q.loop(size, function* (ri) {
|
|
884
|
+
yield* q.when(q.b.int.cmp("ge", ri, ki), function* () {
|
|
885
|
+
const row = q.load(groupNodes, at(q, root, ri));
|
|
886
|
+
const abs = q.abs(q.load(factors, at(q, row, k)));
|
|
887
|
+
yield* q.when(q.b.float.cmp("gt", abs, q.b.state.load(pivotMagnitude)), function() {
|
|
888
|
+
q.b.state.store(pivotMagnitude, abs);
|
|
889
|
+
q.b.state.store(pivotRow, row);
|
|
890
|
+
});
|
|
891
|
+
});
|
|
892
|
+
});
|
|
893
|
+
yield* q.guard(q.b.float.cmp("gt", q.b.state.load(pivotMagnitude), q.f(1e-14)), fault, RESISTIVE_FAULT.numericalFailure, origin(4, k));
|
|
894
|
+
const selected = q.b.state.load(pivotRow);
|
|
895
|
+
const old = q.load(permutation, k);
|
|
896
|
+
q.store(permutation, k, q.load(permutation, selected));
|
|
897
|
+
q.store(permutation, selected, old);
|
|
898
|
+
yield* q.loop(size, function(ci) {
|
|
899
|
+
const column = q.load(groupNodes, at(q, root, ci));
|
|
900
|
+
const before = q.load(factors, at(q, k, column));
|
|
901
|
+
q.store(factors, at(q, k, column), q.load(factors, at(q, selected, column)));
|
|
902
|
+
q.store(factors, at(q, selected, column), before);
|
|
903
|
+
});
|
|
904
|
+
yield* q.loop(size, function* (ri) {
|
|
905
|
+
yield* q.when(q.b.int.cmp("gt", ri, ki), function* () {
|
|
906
|
+
const row = q.load(groupNodes, at(q, root, ri));
|
|
907
|
+
const multiplier = q.b.float.div(q.load(factors, at(q, row, k)), q.load(factors, at(q, k, k)));
|
|
908
|
+
yield* q.guard(q.b.float.isFinite(multiplier), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
909
|
+
q.store(factors, at(q, row, k), multiplier);
|
|
910
|
+
yield* q.loop(size, function* (ci) {
|
|
911
|
+
yield* q.when(q.b.int.cmp("gt", ci, ki), function* () {
|
|
912
|
+
const column = q.load(groupNodes, at(q, root, ci));
|
|
913
|
+
const value = q.b.float.sub(q.load(factors, at(q, row, column)), q.b.float.mul(multiplier, q.load(factors, at(q, k, column))));
|
|
914
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
915
|
+
q.store(factors, at(q, row, column), value);
|
|
916
|
+
});
|
|
917
|
+
});
|
|
918
|
+
});
|
|
919
|
+
});
|
|
920
|
+
});
|
|
921
|
+
});
|
|
922
|
+
});
|
|
923
|
+
});
|
|
924
|
+
for (const [i] of network.resistors.entries()) {
|
|
925
|
+
q.store(previousResistance, i, q.load(resistance, i));
|
|
926
|
+
q.store(previousEnabled, i, q.load(resistorEnabled, i));
|
|
927
|
+
}
|
|
928
|
+
for (const [i] of network.sources.entries()) q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));
|
|
929
|
+
q.b.state.store(factorsInitialized, q.b.const("bool", true));
|
|
930
|
+
q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));
|
|
931
|
+
q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));
|
|
932
|
+
q.b.state.store(validFactors, q.b.const("bool", true));
|
|
933
|
+
q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));
|
|
934
|
+
q.b.return([]);
|
|
935
|
+
});
|
|
936
|
+
});
|
|
937
|
+
if (singleton !== void 0) {
|
|
938
|
+
const direct = module.func(`${prefix}_factor_singleton`, {
|
|
939
|
+
params: [],
|
|
940
|
+
results: []
|
|
941
|
+
});
|
|
942
|
+
direct.body((builder) => {
|
|
943
|
+
const q = new Flow(builder);
|
|
944
|
+
q.run(function* () {
|
|
945
|
+
q.b.state.store(validFactors, q.b.const("bool", false));
|
|
946
|
+
for (let node = 0; node < n; node++) {
|
|
947
|
+
q.store(label, node, q.u(node));
|
|
948
|
+
q.store(known, node, q.b.const("bool", node !== singleton));
|
|
949
|
+
q.store(reachable, node, q.b.const("bool", node !== singleton));
|
|
950
|
+
q.store(group, node, q.u(node));
|
|
951
|
+
q.store(groupSize, node, q.u(0));
|
|
952
|
+
q.store(groupDirty, node, q.b.const("bool", node === singleton));
|
|
953
|
+
q.store(scale, node, q.f(1));
|
|
954
|
+
q.store(conductance, singleton * n + node, q.f(0));
|
|
955
|
+
}
|
|
956
|
+
for (const [i, resistor] of network.resistors.entries()) yield* q.when(q.load(resistorEnabled, i), function* () {
|
|
957
|
+
const g = q.b.float.div(q.f(1), q.load(resistance, i));
|
|
958
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(g), q.b.float.cmp("gt", g, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(1, i));
|
|
959
|
+
if (resistor.a === singleton !== (resistor.b === singleton)) {
|
|
960
|
+
const other = resistor.a === singleton ? resistor.b : resistor.a;
|
|
961
|
+
addAt(q, q.u(singleton), q.u(singleton), g);
|
|
962
|
+
addAt(q, q.u(singleton), q.u(other), q.b.float.sub(q.f(0), g));
|
|
963
|
+
q.store(reachable, singleton, q.b.const("bool", true));
|
|
964
|
+
}
|
|
965
|
+
});
|
|
966
|
+
const active = q.load(reachable, singleton);
|
|
967
|
+
const divisor = q.b.select(active, q.load(conductance, singleton * n + singleton), q.f(1));
|
|
968
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(divisor), q.b.float.cmp("gt", divisor, q.f(0))), fault, RESISTIVE_FAULT.numericalFailure, origin(4, singleton));
|
|
969
|
+
q.store(scale, singleton, divisor);
|
|
970
|
+
for (let column = 0; column < n; column++) q.store(system, singleton * n + column, q.f(column === singleton ? 1 : 0));
|
|
971
|
+
q.store(groupSize, singleton, q.b.select(active, q.u(1), q.u(0)));
|
|
972
|
+
q.store(groupNodes, singleton * n, q.u(singleton));
|
|
973
|
+
yield* q.when(active, function() {
|
|
974
|
+
q.store(groupRebuilds, singleton, q.b.int.add(q.load(groupRebuilds, singleton), q.u(1)));
|
|
975
|
+
});
|
|
976
|
+
for (const [i] of network.sources.entries()) q.store(previousSourceEnabled, i, q.load(sourceEnabled, i));
|
|
977
|
+
q.b.state.store(factorsInitialized, q.b.const("bool", true));
|
|
978
|
+
q.b.state.store(factoredTopology, q.b.state.load(topologyVersion));
|
|
979
|
+
q.b.state.store(factoredMatrix, q.b.state.load(matrixVersion));
|
|
980
|
+
q.b.state.store(validFactors, q.b.const("bool", true));
|
|
981
|
+
q.b.state.store(factorizations, q.b.int.add(q.b.state.load(factorizations), q.u(1)));
|
|
982
|
+
q.b.return([]);
|
|
983
|
+
});
|
|
984
|
+
});
|
|
985
|
+
factor.body((b) => {
|
|
986
|
+
let fixed = b.const("bool", true);
|
|
987
|
+
for (const node of sourceNodes) {
|
|
988
|
+
let enabled = b.const("bool", false);
|
|
989
|
+
for (const [i, source] of network.sources.entries()) if (source.node === node) enabled = b.bool.or(enabled, b.array.load(sourceEnabled, b.const("u32", i)));
|
|
990
|
+
fixed = b.bool.and(fixed, enabled);
|
|
991
|
+
}
|
|
992
|
+
const yes = b.block([]);
|
|
993
|
+
const no = b.block([]);
|
|
994
|
+
b.branch(fixed, {
|
|
995
|
+
target: yes,
|
|
996
|
+
args: []
|
|
997
|
+
}, {
|
|
998
|
+
target: no,
|
|
999
|
+
args: []
|
|
1000
|
+
});
|
|
1001
|
+
b.at(yes, (b) => {
|
|
1002
|
+
b.call(direct, []);
|
|
1003
|
+
b.return([]);
|
|
1004
|
+
});
|
|
1005
|
+
b.at(no, (b) => {
|
|
1006
|
+
b.call(factorGeneral, []);
|
|
1007
|
+
b.return([]);
|
|
1008
|
+
});
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
solve.body((builder) => {
|
|
1012
|
+
const sameTopology = builder.int.cmp("eq", builder.state.load(topologyVersion), builder.state.load(factoredTopology));
|
|
1013
|
+
const sameMatrix = builder.int.cmp("eq", builder.state.load(matrixVersion), builder.state.load(factoredMatrix));
|
|
1014
|
+
const sameRhs = builder.int.cmp("eq", builder.state.load(rhsVersion), builder.state.load(solvedRhs));
|
|
1015
|
+
const sameFactors = builder.bool.and(builder.state.load(validFactors), builder.bool.and(sameTopology, sameMatrix));
|
|
1016
|
+
const cached = builder.bool.and(builder.state.load(hasSolution), builder.bool.and(sameFactors, sameRhs));
|
|
1017
|
+
const done = builder.block([]);
|
|
1018
|
+
const dirty = builder.block([]);
|
|
1019
|
+
builder.branch(cached, {
|
|
1020
|
+
target: done,
|
|
1021
|
+
args: []
|
|
1022
|
+
}, {
|
|
1023
|
+
target: dirty,
|
|
1024
|
+
args: []
|
|
1025
|
+
});
|
|
1026
|
+
builder.at(done, (b) => b.return([]));
|
|
1027
|
+
builder.at(dirty, (builder) => {
|
|
1028
|
+
const q = new Flow(builder);
|
|
1029
|
+
q.run(function* () {
|
|
1030
|
+
q.b.state.store(hasSolution, q.b.const("bool", false));
|
|
1031
|
+
q.b.state.store(fault, q.b.const("u8", 0));
|
|
1032
|
+
q.b.state.store(faultTargetKind, q.b.const("u8", 0));
|
|
1033
|
+
const changed = q.b.bool.not(sameFactors);
|
|
1034
|
+
for (const [i] of network.resistors.entries()) {
|
|
1035
|
+
const r = q.load(resistance, i);
|
|
1036
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(r), q.b.float.cmp("gt", r, q.f(0))), fault, RESISTIVE_FAULT.invalidParameter, origin(1, i));
|
|
1037
|
+
}
|
|
1038
|
+
for (const [i] of network.sources.entries()) yield* q.guard(q.b.float.isFinite(q.load(sourceVoltage, i)), fault, RESISTIVE_FAULT.invalidParameter, origin(2, i));
|
|
1039
|
+
yield* q.when(changed, function() {
|
|
1040
|
+
q.b.call(factor, []);
|
|
1041
|
+
});
|
|
1042
|
+
yield* q.guard(q.b.int.cmp("eq", q.b.state.load(fault), q.b.const("u8", 0)), fault, RESISTIVE_FAULT.numericalFailure);
|
|
1043
|
+
yield* q.loop(n, function(i) {
|
|
1044
|
+
q.store(anchor, i, q.f(0));
|
|
1045
|
+
q.store(assigned, i, q.b.const("bool", false));
|
|
1046
|
+
});
|
|
1047
|
+
for (const [i, source] of network.sources.entries()) yield* q.when(q.load(sourceEnabled, i), function* () {
|
|
1048
|
+
const root = q.load(label, source.node);
|
|
1049
|
+
const value = q.load(sourceVoltage, i);
|
|
1050
|
+
const compatible = q.b.bool.or(q.b.bool.not(q.load(assigned, root)), q.b.float.cmp("eq", q.load(anchor, root), value));
|
|
1051
|
+
yield* q.guard(compatible, fault, RESISTIVE_FAULT.sourceConflict, origin(2, i));
|
|
1052
|
+
q.store(anchor, root, value);
|
|
1053
|
+
q.store(assigned, root, q.b.const("bool", true));
|
|
1054
|
+
});
|
|
1055
|
+
yield* q.loop(n, function(root) {
|
|
1056
|
+
q.store(groupSolveDirty, root, q.b.bool.and(changed, q.load(groupDirty, root)));
|
|
1057
|
+
});
|
|
1058
|
+
yield* q.loop(n, function* (row) {
|
|
1059
|
+
const active = q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row)));
|
|
1060
|
+
q.b.state.store(accumulator, q.f(0));
|
|
1061
|
+
yield* q.when(active, function* () {
|
|
1062
|
+
yield* q.loop(n, function(column) {
|
|
1063
|
+
const sourceTerm = q.b.select(q.load(known, column), q.b.float.mul(q.b.float.div(q.load(conductance, at(q, row, column)), q.load(scale, row)), q.load(anchor, column)), q.f(0));
|
|
1064
|
+
q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), sourceTerm));
|
|
1065
|
+
});
|
|
1066
|
+
});
|
|
1067
|
+
const value = q.b.select(q.load(known, row), q.load(anchor, row), q.b.select(active, q.b.state.load(accumulator), q.f(0)));
|
|
1068
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
1069
|
+
yield* q.when(q.b.bool.and(active, q.b.float.cmp("ne", value, q.load(rhs, row))), function() {
|
|
1070
|
+
q.store(groupSolveDirty, q.load(group, row), q.b.const("bool", true));
|
|
1071
|
+
});
|
|
1072
|
+
q.store(rhs, row, value);
|
|
1073
|
+
yield* q.when(q.b.bool.not(active), function() {
|
|
1074
|
+
q.store(candidate, row, value);
|
|
1075
|
+
});
|
|
1076
|
+
});
|
|
1077
|
+
yield* q.loop(n, function* (root) {
|
|
1078
|
+
const size = q.load(groupSize, root);
|
|
1079
|
+
yield* q.when(q.b.bool.and(q.load(groupSolveDirty, root), q.b.int.cmp("gt", size, q.u(0))), function* () {
|
|
1080
|
+
q.store(groupSolves, root, q.b.int.add(q.load(groupSolves, root), q.u(1)));
|
|
1081
|
+
yield* q.when(q.b.int.cmp("eq", size, q.u(1)), function() {
|
|
1082
|
+
const row = q.load(groupNodes, at(q, root, q.u(0)));
|
|
1083
|
+
q.store(candidate, row, q.load(rhs, row));
|
|
1084
|
+
});
|
|
1085
|
+
yield* q.when(q.b.int.cmp("gt", size, q.u(1)), function* () {
|
|
1086
|
+
yield* q.loop(size, function* (ri) {
|
|
1087
|
+
const row = q.load(groupNodes, at(q, root, ri));
|
|
1088
|
+
q.b.state.store(accumulator, q.load(rhs, q.load(permutation, row)));
|
|
1089
|
+
yield* q.loop(size, function* (ci) {
|
|
1090
|
+
yield* q.when(q.b.int.cmp("lt", ci, ri), function() {
|
|
1091
|
+
const column = q.load(groupNodes, at(q, root, ci));
|
|
1092
|
+
q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), q.b.float.mul(q.load(factors, at(q, row, column)), q.load(work, column))));
|
|
1093
|
+
});
|
|
1094
|
+
});
|
|
1095
|
+
q.store(work, row, q.b.state.load(accumulator));
|
|
1096
|
+
});
|
|
1097
|
+
yield* q.loop(size, function* (reverse) {
|
|
1098
|
+
const ri = q.b.int.sub(q.b.int.sub(size, q.u(1)), reverse);
|
|
1099
|
+
const row = q.load(groupNodes, at(q, root, ri));
|
|
1100
|
+
q.b.state.store(accumulator, q.load(work, row));
|
|
1101
|
+
yield* q.loop(size, function* (ci) {
|
|
1102
|
+
yield* q.when(q.b.int.cmp("gt", ci, ri), function() {
|
|
1103
|
+
const column = q.load(groupNodes, at(q, root, ci));
|
|
1104
|
+
q.b.state.store(accumulator, q.b.float.sub(q.b.state.load(accumulator), q.b.float.mul(q.load(factors, at(q, row, column)), q.load(candidate, column))));
|
|
1105
|
+
});
|
|
1106
|
+
});
|
|
1107
|
+
const value = q.b.float.div(q.b.state.load(accumulator), q.load(factors, at(q, row, row)));
|
|
1108
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
1109
|
+
q.store(candidate, row, value);
|
|
1110
|
+
});
|
|
1111
|
+
});
|
|
1112
|
+
});
|
|
1113
|
+
});
|
|
1114
|
+
yield* q.loop(n, function* (row) {
|
|
1115
|
+
yield* q.when(q.b.bool.and(q.load(reachable, row), q.b.bool.not(q.load(known, row))), function* () {
|
|
1116
|
+
q.b.state.store(accumulator, q.f(0));
|
|
1117
|
+
q.b.state.store(magnitude, q.b.float.mul(q.f(1e-10), q.abs(q.load(rhs, row))));
|
|
1118
|
+
yield* q.loop(n, function(column) {
|
|
1119
|
+
const term = q.b.float.mul(q.load(system, at(q, row, column)), q.load(candidate, column));
|
|
1120
|
+
q.b.state.store(accumulator, q.b.float.add(q.b.state.load(accumulator), term));
|
|
1121
|
+
q.b.state.store(magnitude, q.b.float.add(q.b.state.load(magnitude), q.b.float.mul(q.f(1e-10), q.abs(term))));
|
|
1122
|
+
});
|
|
1123
|
+
const error = q.abs(q.b.float.sub(q.b.state.load(accumulator), q.load(rhs, row)));
|
|
1124
|
+
const tolerance = q.b.float.add(q.f(1e-22), q.b.state.load(magnitude));
|
|
1125
|
+
yield* q.guard(q.b.bool.and(q.b.float.isFinite(error), q.b.float.cmp("le", error, tolerance)), fault, RESISTIVE_FAULT.numericalFailure, origin(4, row));
|
|
1126
|
+
});
|
|
1127
|
+
});
|
|
1128
|
+
for (const [i, resistor] of network.resistors.entries()) {
|
|
1129
|
+
const delta = q.b.float.sub(q.load(candidate, q.load(label, resistor.a)), q.load(candidate, q.load(label, resistor.b)));
|
|
1130
|
+
const value = q.b.select(q.load(resistorEnabled, i), q.b.float.div(delta, q.load(resistance, i)), q.f(0));
|
|
1131
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(1, i));
|
|
1132
|
+
q.store(candidateCurrent, i, value);
|
|
1133
|
+
}
|
|
1134
|
+
for (const [i, source] of network.sources.entries()) {
|
|
1135
|
+
const root = q.load(label, source.node);
|
|
1136
|
+
let unique = q.b.const("bool", true);
|
|
1137
|
+
for (const [j, other] of network.sources.entries()) {
|
|
1138
|
+
if (i === j) continue;
|
|
1139
|
+
unique = q.b.bool.and(unique, q.b.bool.not(q.b.bool.and(q.load(sourceEnabled, j), q.b.int.cmp("eq", root, q.load(label, other.node)))));
|
|
1140
|
+
}
|
|
1141
|
+
q.b.state.store(accumulator, q.f(0));
|
|
1142
|
+
for (const [j, resistor] of network.resistors.entries()) {
|
|
1143
|
+
const a = q.load(label, resistor.a);
|
|
1144
|
+
const b = q.load(label, resistor.b);
|
|
1145
|
+
const outward = q.b.select(q.b.int.cmp("eq", root, a), q.load(candidateCurrent, j), q.f(0));
|
|
1146
|
+
const inward = q.b.select(q.b.int.cmp("eq", root, b), q.load(candidateCurrent, j), q.f(0));
|
|
1147
|
+
q.b.state.store(accumulator, q.b.float.add(q.b.state.load(accumulator), q.b.float.sub(outward, inward)));
|
|
1148
|
+
}
|
|
1149
|
+
const enabled = q.load(sourceEnabled, i);
|
|
1150
|
+
const value = q.b.select(q.b.bool.and(enabled, unique), q.b.state.load(accumulator), q.f(0));
|
|
1151
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(2, i));
|
|
1152
|
+
q.store(candidateSourceCurrent, i, value);
|
|
1153
|
+
q.store(candidateSourceState, i, q.b.select(q.b.bool.or(q.b.bool.not(enabled), unique), q.b.const("u8", 0), q.b.const("u8", 2)));
|
|
1154
|
+
}
|
|
1155
|
+
for (const [i, contact] of network.contacts.entries()) {
|
|
1156
|
+
q.store(candidateContactCurrent, i, q.f(0));
|
|
1157
|
+
q.store(candidateContactState, i, q.b.const("u8", 0));
|
|
1158
|
+
yield* q.when(q.load(contactClosed, i), function* () {
|
|
1159
|
+
yield* q.loop(n, function(node) {
|
|
1160
|
+
q.store(contactSide, node, q.b.int.cmp("eq", node, q.u(contact.a)));
|
|
1161
|
+
});
|
|
1162
|
+
yield* q.loop(n, function* () {
|
|
1163
|
+
for (const [j, edge] of network.contacts.entries()) {
|
|
1164
|
+
if (i === j) continue;
|
|
1165
|
+
yield* q.when(q.load(contactClosed, j), function() {
|
|
1166
|
+
const connected = q.b.bool.or(q.load(contactSide, edge.a), q.load(contactSide, edge.b));
|
|
1167
|
+
q.store(contactSide, edge.a, connected);
|
|
1168
|
+
q.store(contactSide, edge.b, connected);
|
|
1169
|
+
});
|
|
1170
|
+
}
|
|
1171
|
+
});
|
|
1172
|
+
const root = q.load(label, contact.a);
|
|
1173
|
+
let leftSource = q.b.const("bool", false);
|
|
1174
|
+
let rightSource = q.b.const("bool", false);
|
|
1175
|
+
for (const [j, source] of network.sources.entries()) {
|
|
1176
|
+
const same = q.b.bool.and(q.load(sourceEnabled, j), q.b.int.cmp("eq", root, q.load(label, source.node)));
|
|
1177
|
+
leftSource = q.b.bool.or(leftSource, q.b.bool.and(same, q.load(contactSide, source.node)));
|
|
1178
|
+
rightSource = q.b.bool.or(rightSource, q.b.bool.and(same, q.b.bool.not(q.load(contactSide, source.node))));
|
|
1179
|
+
}
|
|
1180
|
+
let leftOut = q.f(0);
|
|
1181
|
+
let rightOut = q.f(0);
|
|
1182
|
+
const right = (node) => q.b.bool.and(q.b.int.cmp("eq", root, q.load(label, node)), q.b.bool.not(q.load(contactSide, node)));
|
|
1183
|
+
for (const [j, resistor] of network.resistors.entries()) {
|
|
1184
|
+
const value = q.load(candidateCurrent, j);
|
|
1185
|
+
const netOut = (a, b) => q.b.float.sub(q.b.select(a, value, q.f(0)), q.b.select(b, value, q.f(0)));
|
|
1186
|
+
leftOut = q.b.float.add(leftOut, netOut(q.load(contactSide, resistor.a), q.load(contactSide, resistor.b)));
|
|
1187
|
+
rightOut = q.b.float.add(rightOut, netOut(right(resistor.a), right(resistor.b)));
|
|
1188
|
+
}
|
|
1189
|
+
const unique = q.b.bool.and(q.b.bool.not(q.load(contactSide, contact.b)), q.b.bool.not(q.b.bool.and(leftSource, rightSource)));
|
|
1190
|
+
const value = q.b.select(leftSource, rightOut, q.b.float.sub(q.f(0), leftOut));
|
|
1191
|
+
yield* q.guard(q.b.float.isFinite(value), fault, RESISTIVE_FAULT.numericalFailure, origin(3, i));
|
|
1192
|
+
q.store(candidateContactCurrent, i, q.b.select(unique, value, q.f(0)));
|
|
1193
|
+
q.store(candidateContactState, i, q.b.select(unique, q.b.const("u8", 0), q.b.const("u8", 2)));
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
yield* q.loop(n, function(node) {
|
|
1197
|
+
const root = q.load(label, node);
|
|
1198
|
+
q.store(voltage, node, q.load(candidate, root));
|
|
1199
|
+
q.store(voltageState, node, q.b.select(q.load(reachable, root), q.b.const("u8", 0), q.b.const("u8", 1)));
|
|
1200
|
+
});
|
|
1201
|
+
for (const [i] of network.resistors.entries()) {
|
|
1202
|
+
q.store(current, i, q.load(candidateCurrent, i));
|
|
1203
|
+
q.store(currentState, i, q.b.const("u8", 0));
|
|
1204
|
+
}
|
|
1205
|
+
for (const [i] of network.sources.entries()) {
|
|
1206
|
+
q.store(sourceCurrent, i, q.load(candidateSourceCurrent, i));
|
|
1207
|
+
q.store(sourceCurrentState, i, q.load(candidateSourceState, i));
|
|
1208
|
+
}
|
|
1209
|
+
for (const [i] of network.contacts.entries()) {
|
|
1210
|
+
q.store(contactCurrent, i, q.load(candidateContactCurrent, i));
|
|
1211
|
+
q.store(contactCurrentState, i, q.load(candidateContactState, i));
|
|
1212
|
+
}
|
|
1213
|
+
q.b.state.store(solvedRhs, q.b.state.load(rhsVersion));
|
|
1214
|
+
q.b.state.store(hasSolution, q.b.const("bool", true));
|
|
1215
|
+
for (const observer of onPublish) q.b.call(observer, []);
|
|
1216
|
+
q.b.return([]);
|
|
1217
|
+
});
|
|
1218
|
+
});
|
|
1219
|
+
});
|
|
1220
|
+
return Object.freeze({
|
|
1221
|
+
solve,
|
|
1222
|
+
resistance,
|
|
1223
|
+
resistorEnabled,
|
|
1224
|
+
sourceVoltage,
|
|
1225
|
+
sourceEnabled,
|
|
1226
|
+
contactClosed,
|
|
1227
|
+
voltage,
|
|
1228
|
+
voltageState,
|
|
1229
|
+
current,
|
|
1230
|
+
currentState,
|
|
1231
|
+
sourceCurrent,
|
|
1232
|
+
sourceCurrentState,
|
|
1233
|
+
contactCurrent,
|
|
1234
|
+
contactCurrentState,
|
|
1235
|
+
fault,
|
|
1236
|
+
faultTargetKind,
|
|
1237
|
+
faultTargetIndex,
|
|
1238
|
+
factorizations,
|
|
1239
|
+
groupRebuilds,
|
|
1240
|
+
groupSolves,
|
|
1241
|
+
topologyVersion,
|
|
1242
|
+
matrixVersion,
|
|
1243
|
+
rhsVersion,
|
|
1244
|
+
invalidate
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
function validateNetwork(network) {
|
|
1248
|
+
if (!Number.isSafeInteger(network.nodes) || network.nodes < 1) throw new Error("A resistive network needs a positive node count");
|
|
1249
|
+
const node = (index) => {
|
|
1250
|
+
if (!Number.isSafeInteger(index) || index < 0 || index >= network.nodes) throw new Error(`Invalid node ${index}`);
|
|
1251
|
+
};
|
|
1252
|
+
for (const resistor of network.resistors) {
|
|
1253
|
+
node(resistor.a);
|
|
1254
|
+
node(resistor.b);
|
|
1255
|
+
if (!Number.isFinite(resistor.resistance) || resistor.resistance <= 0 || typeof resistor.enabled !== "boolean") throw new Error("Invalid initial resistor state");
|
|
1256
|
+
}
|
|
1257
|
+
for (const source of network.sources) {
|
|
1258
|
+
node(source.node);
|
|
1259
|
+
if (!Number.isFinite(source.voltage) || typeof source.enabled !== "boolean") throw new Error("Invalid initial source state");
|
|
1260
|
+
}
|
|
1261
|
+
for (const contact of network.contacts) {
|
|
1262
|
+
node(contact.a);
|
|
1263
|
+
node(contact.b);
|
|
1264
|
+
if (typeof contact.closed !== "boolean") throw new Error("Invalid initial contact state");
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
//#endregion
|
|
71
1268
|
//#region src/unified-ir/compiler/types.ts
|
|
72
1269
|
/** Error raised while compiling a circuit. */
|
|
73
1270
|
var UnifiedIRCompilerError = class extends Error {
|
|
@@ -75,17 +1272,711 @@ var UnifiedIRCompilerError = class extends Error {
|
|
|
75
1272
|
code;
|
|
76
1273
|
deviceId;
|
|
77
1274
|
pinName;
|
|
78
|
-
netId;
|
|
79
|
-
diagnostics;
|
|
80
1275
|
constructor(code, message, options = {}) {
|
|
81
1276
|
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
82
1277
|
this.code = code;
|
|
83
1278
|
this.deviceId = options.deviceId;
|
|
84
1279
|
this.pinName = options.pinName;
|
|
85
|
-
this.netId = options.netId;
|
|
86
|
-
this.diagnostics = options.diagnostics ?? [];
|
|
87
1280
|
}
|
|
88
|
-
};
|
|
1281
|
+
};
|
|
1282
|
+
//#endregion
|
|
1283
|
+
//#region src/unified-ir/compiler/electrical-operations.ts
|
|
1284
|
+
/** Compiler-owned lowering helpers; none of their private storage is given to devices. */
|
|
1285
|
+
function createElectricalOperations(module, allocation, interpretation, prefix, floatingSeed = 0) {
|
|
1286
|
+
if (!Number.isInteger(floatingSeed) || floatingSeed < 0 || floatingSeed > 4294967295) throw new Error("floatingSeed must be a u32");
|
|
1287
|
+
if (interpretation !== "two-state" && interpretation !== "retain-in-band") throw new Error("Invalid electrical interpretation");
|
|
1288
|
+
const inputs = module.func(`${prefix}_interpret_inputs`, {
|
|
1289
|
+
params: [],
|
|
1290
|
+
results: []
|
|
1291
|
+
});
|
|
1292
|
+
const solver = generateResistiveSolver(module, allocation.network, prefix, [inputs]);
|
|
1293
|
+
const allPins = [...allocation.pins].flatMap(([deviceId, pins]) => [...pins].map(([name, pin]) => ({
|
|
1294
|
+
deviceId,
|
|
1295
|
+
name,
|
|
1296
|
+
pin
|
|
1297
|
+
})));
|
|
1298
|
+
const size = Math.max(1, allPins.length);
|
|
1299
|
+
const mode = module.array(`${prefix}_mode`, "u8", Array(size).fill(PIN_MODE.highZ));
|
|
1300
|
+
const enabled = module.array(`${prefix}_output_enabled`, "bool", Array(size).fill(false));
|
|
1301
|
+
const digital = module.array(`${prefix}_digital_intent`, "bool", Array(size).fill(false));
|
|
1302
|
+
const digitalReady = module.array(`${prefix}_digital_ready`, "bool", Array(size).fill(false));
|
|
1303
|
+
const voltageReady = module.array(`${prefix}_voltage_ready`, "bool", Array(size).fill(false));
|
|
1304
|
+
const memory = module.array(`${prefix}_input_memory`, "bool", Array(size).fill(false));
|
|
1305
|
+
const sampled = module.array(`${prefix}_digital_sample`, "bool", Array(size).fill(false));
|
|
1306
|
+
const index = (b, i) => b.const("u32", i);
|
|
1307
|
+
const badResource = (message) => {
|
|
1308
|
+
throw new UnifiedIRCompilerError("invalid-input", message);
|
|
1309
|
+
};
|
|
1310
|
+
const running = (b, emit) => {
|
|
1311
|
+
const body = b.block([]);
|
|
1312
|
+
const done = b.block([]);
|
|
1313
|
+
b.branch(b.int.cmp("eq", b.state.load(solver.fault), b.const("u8", 0)), {
|
|
1314
|
+
target: body,
|
|
1315
|
+
args: []
|
|
1316
|
+
}, {
|
|
1317
|
+
target: done,
|
|
1318
|
+
args: []
|
|
1319
|
+
});
|
|
1320
|
+
b.at(body, emit);
|
|
1321
|
+
b.at(done, (b) => b.return([]));
|
|
1322
|
+
};
|
|
1323
|
+
const checked = (b, valid, target, commit) => {
|
|
1324
|
+
const yes = b.block([]);
|
|
1325
|
+
const no = b.block([]);
|
|
1326
|
+
b.branch(valid, {
|
|
1327
|
+
target: yes,
|
|
1328
|
+
args: []
|
|
1329
|
+
}, {
|
|
1330
|
+
target: no,
|
|
1331
|
+
args: []
|
|
1332
|
+
});
|
|
1333
|
+
b.at(yes, commit);
|
|
1334
|
+
b.at(no, (b) => {
|
|
1335
|
+
b.state.store(solver.fault, b.const("u8", RESISTIVE_FAULT.invalidParameter));
|
|
1336
|
+
b.state.store(solver.faultTargetKind, b.const("u8", target.kind));
|
|
1337
|
+
b.state.store(solver.faultTargetIndex, target.index);
|
|
1338
|
+
b.return([]);
|
|
1339
|
+
});
|
|
1340
|
+
};
|
|
1341
|
+
const complete = (b, changed, kind, otherwise = (b) => b.return([])) => {
|
|
1342
|
+
const yes = b.block([]);
|
|
1343
|
+
const no = b.block([]);
|
|
1344
|
+
b.branch(changed, {
|
|
1345
|
+
target: yes,
|
|
1346
|
+
args: []
|
|
1347
|
+
}, {
|
|
1348
|
+
target: no,
|
|
1349
|
+
args: []
|
|
1350
|
+
});
|
|
1351
|
+
b.at(yes, (b) => {
|
|
1352
|
+
b.call(solver.invalidate[kind], []);
|
|
1353
|
+
b.return([]);
|
|
1354
|
+
});
|
|
1355
|
+
b.at(no, otherwise);
|
|
1356
|
+
};
|
|
1357
|
+
const loop = (b, count, emit, done) => {
|
|
1358
|
+
const header = b.block(["u32"]);
|
|
1359
|
+
const body = b.block(["u32"]);
|
|
1360
|
+
const exit = b.block([]);
|
|
1361
|
+
b.jump(header, [b.const("u32", 0)]);
|
|
1362
|
+
b.at(header, (b, [i]) => b.branch(b.int.cmp("lt", i, count), {
|
|
1363
|
+
target: body,
|
|
1364
|
+
args: [i]
|
|
1365
|
+
}, {
|
|
1366
|
+
target: exit,
|
|
1367
|
+
args: []
|
|
1368
|
+
}));
|
|
1369
|
+
b.at(body, (b, [i]) => {
|
|
1370
|
+
emit(b, i);
|
|
1371
|
+
b.jump(header, [b.int.add(i, b.const("u32", 1))]);
|
|
1372
|
+
});
|
|
1373
|
+
b.at(exit, done);
|
|
1374
|
+
};
|
|
1375
|
+
const ensure = module.func(`${prefix}_ensure`, {
|
|
1376
|
+
params: [],
|
|
1377
|
+
results: []
|
|
1378
|
+
});
|
|
1379
|
+
ensure.body((b) => running(b, (b) => {
|
|
1380
|
+
b.call(solver.solve, []);
|
|
1381
|
+
b.return([]);
|
|
1382
|
+
}));
|
|
1383
|
+
const clock = module.array(`${prefix}_time`, "u32", [0, 0]);
|
|
1384
|
+
const timeStep = module.array(`${prefix}_time_step`, "u32", [1, 0]);
|
|
1385
|
+
const advanceTime = module.func(`${prefix}_advance_time`, {
|
|
1386
|
+
params: [],
|
|
1387
|
+
results: []
|
|
1388
|
+
});
|
|
1389
|
+
const analogInputs = /* @__PURE__ */ new Map();
|
|
1390
|
+
const analogRequests = /* @__PURE__ */ new Map();
|
|
1391
|
+
let finalized = false;
|
|
1392
|
+
const finalize = () => {
|
|
1393
|
+
if (finalized) return;
|
|
1394
|
+
finalized = true;
|
|
1395
|
+
for (const [id, sample] of analogRequests) {
|
|
1396
|
+
const { deviceId, name, pin } = allPins[id];
|
|
1397
|
+
analogInputs.set(id, createFloatingInput(module, solver, clock, `${prefix}_analog_${id}`, floatingSeed, deviceId, name, pin.node, pin.input.reference, sample));
|
|
1398
|
+
}
|
|
1399
|
+
advanceTime.body((b) => {
|
|
1400
|
+
if (analogInputs.size === 0) {
|
|
1401
|
+
b.return([]);
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
const previous = b.array.load(clock, index(b, 0));
|
|
1405
|
+
const low = b.int.add(previous, b.array.load(timeStep, index(b, 0)));
|
|
1406
|
+
const carry = b.select(b.int.cmp("lt", low, previous), index(b, 1), index(b, 0));
|
|
1407
|
+
const high = b.int.add(b.int.add(b.array.load(clock, index(b, 1)), b.array.load(timeStep, index(b, 1))), carry);
|
|
1408
|
+
b.array.store(clock, index(b, 0), low);
|
|
1409
|
+
b.array.store(clock, index(b, 1), b.int.and(high, index(b, 2097151)));
|
|
1410
|
+
b.return([]);
|
|
1411
|
+
});
|
|
1412
|
+
inputs.body((b) => {
|
|
1413
|
+
allPins.forEach(({ pin }, id) => {
|
|
1414
|
+
const analog = analogInputs.get(id);
|
|
1415
|
+
if (analog !== void 0) b.call(analog.update, []);
|
|
1416
|
+
if (pin.input === void 0) return;
|
|
1417
|
+
const ref = pin.input.reference;
|
|
1418
|
+
const supply = b.array.load(solver.sourceVoltage, index(b, ref));
|
|
1419
|
+
const value = b.array.load(solver.voltage, index(b, pin.node));
|
|
1420
|
+
const low = b.float.cmp("le", value, b.float.mul(supply, b.const("f64", pin.input.low)));
|
|
1421
|
+
const high = b.float.cmp("ge", value, b.float.mul(supply, b.const("f64", pin.input.high)));
|
|
1422
|
+
const ready = b.bool.and(b.array.load(solver.sourceEnabled, index(b, ref)), b.bool.and(b.float.cmp("gt", supply, b.const("f64", 0)), b.int.cmp("eq", b.array.load(solver.voltageState, index(b, pin.node)), b.const("u8", 0))));
|
|
1423
|
+
const remembered = b.array.load(memory, index(b, id));
|
|
1424
|
+
const next = b.select(low, b.const("bool", false), b.select(high, b.const("bool", true), remembered));
|
|
1425
|
+
b.array.store(memory, index(b, id), b.select(ready, next, remembered));
|
|
1426
|
+
b.array.store(sampled, index(b, id), b.bool.and(ready, interpretation === "two-state" ? high : next));
|
|
1427
|
+
});
|
|
1428
|
+
b.return([]);
|
|
1429
|
+
});
|
|
1430
|
+
};
|
|
1431
|
+
const refresh = /* @__PURE__ */ new Map();
|
|
1432
|
+
const pinFunctions = /* @__PURE__ */ new Map();
|
|
1433
|
+
allPins.forEach(({ pin }, id) => {
|
|
1434
|
+
if (pin.drive === void 0) return;
|
|
1435
|
+
const drive = pin.drive;
|
|
1436
|
+
const recompute = module.func(`${prefix}_pin_${id}_refresh`, {
|
|
1437
|
+
params: [],
|
|
1438
|
+
results: ["bool"]
|
|
1439
|
+
});
|
|
1440
|
+
refresh.set(id, recompute);
|
|
1441
|
+
recompute.body((b) => {
|
|
1442
|
+
const at = b.const("u32", id);
|
|
1443
|
+
const active = b.array.load(enabled, at);
|
|
1444
|
+
const selection = b.array.load(mode, at);
|
|
1445
|
+
const is = (which) => b.int.cmp("eq", selection, b.const("u8", which));
|
|
1446
|
+
const pushPull = is(PIN_MODE.pushPull);
|
|
1447
|
+
const digitalActive = b.bool.and(active, b.array.load(digitalReady, at));
|
|
1448
|
+
const level = b.array.load(digital, at);
|
|
1449
|
+
const high = b.bool.and(digitalActive, b.bool.and(pushPull, level));
|
|
1450
|
+
const low = b.bool.and(digitalActive, b.bool.and(b.bool.or(pushPull, is(PIN_MODE.openDrain)), b.bool.not(level)));
|
|
1451
|
+
let changed = b.const("bool", false);
|
|
1452
|
+
const update = (branch, value) => {
|
|
1453
|
+
changed = b.bool.or(changed, b.bool.xor(b.array.load(solver.resistorEnabled, b.const("u32", branch)), value));
|
|
1454
|
+
b.array.store(solver.resistorEnabled, b.const("u32", branch), value);
|
|
1455
|
+
};
|
|
1456
|
+
update(drive.high, high);
|
|
1457
|
+
update(drive.low, low);
|
|
1458
|
+
if (drive.analog !== void 0) update(drive.analog.resistor, b.bool.and(active, b.bool.and(is(PIN_MODE.analog), b.array.load(voltageReady, at))));
|
|
1459
|
+
b.return([changed]);
|
|
1460
|
+
});
|
|
1461
|
+
const setMode = module.func(`${prefix}_pin_${id}_mode`, {
|
|
1462
|
+
params: ["u8"],
|
|
1463
|
+
results: []
|
|
1464
|
+
});
|
|
1465
|
+
setMode.body((b, [value]) => running(b, (b) => {
|
|
1466
|
+
b.array.store(mode, index(b, id), value);
|
|
1467
|
+
const [changed] = b.call(recompute, []);
|
|
1468
|
+
return complete(b, changed, "matrix");
|
|
1469
|
+
}));
|
|
1470
|
+
const setEnabled = module.func(`${prefix}_pin_${id}_enable`, {
|
|
1471
|
+
params: ["bool"],
|
|
1472
|
+
results: []
|
|
1473
|
+
});
|
|
1474
|
+
setEnabled.body((b, [value]) => running(b, (b) => {
|
|
1475
|
+
b.array.store(enabled, index(b, id), value);
|
|
1476
|
+
const [changed] = b.call(recompute, []);
|
|
1477
|
+
return complete(b, changed, "matrix");
|
|
1478
|
+
}));
|
|
1479
|
+
const writeDigital = module.func(`${prefix}_pin_${id}_digital`, {
|
|
1480
|
+
params: ["bool"],
|
|
1481
|
+
results: []
|
|
1482
|
+
});
|
|
1483
|
+
writeDigital.body((b, [value]) => running(b, (b) => {
|
|
1484
|
+
b.array.store(digital, index(b, id), value);
|
|
1485
|
+
b.array.store(digitalReady, index(b, id), b.const("bool", true));
|
|
1486
|
+
const [changed] = b.call(recompute, []);
|
|
1487
|
+
return complete(b, changed, "matrix");
|
|
1488
|
+
}));
|
|
1489
|
+
const writeVoltage = module.func(`${prefix}_pin_${id}_voltage`, {
|
|
1490
|
+
params: ["f64"],
|
|
1491
|
+
results: []
|
|
1492
|
+
});
|
|
1493
|
+
writeVoltage.body((b, [value]) => running(b, (b) => checked(b, b.float.isFinite(value), {
|
|
1494
|
+
kind: 1,
|
|
1495
|
+
index: index(b, drive.analog?.resistor ?? drive.high)
|
|
1496
|
+
}, (b) => {
|
|
1497
|
+
if (drive.analog === void 0) {
|
|
1498
|
+
b.return([]);
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
const at = index(b, drive.analog.source);
|
|
1502
|
+
const changedRhs = b.float.cmp("ne", b.array.load(solver.sourceVoltage, at), value);
|
|
1503
|
+
b.array.store(solver.sourceVoltage, at, value);
|
|
1504
|
+
b.array.store(voltageReady, index(b, id), b.const("bool", true));
|
|
1505
|
+
const [changedMatrix] = b.call(recompute, []);
|
|
1506
|
+
return complete(b, changedMatrix, "matrix", (b) => complete(b, changedRhs, "rhs"));
|
|
1507
|
+
})));
|
|
1508
|
+
pinFunctions.set(id, {
|
|
1509
|
+
setMode,
|
|
1510
|
+
setEnabled,
|
|
1511
|
+
writeDigital,
|
|
1512
|
+
writeVoltage
|
|
1513
|
+
});
|
|
1514
|
+
});
|
|
1515
|
+
const pinIds = /* @__PURE__ */ new Map();
|
|
1516
|
+
allPins.forEach(({ deviceId, name }, id) => {
|
|
1517
|
+
let pins = pinIds.get(deviceId);
|
|
1518
|
+
if (pins === void 0) {
|
|
1519
|
+
pins = /* @__PURE__ */ new Map();
|
|
1520
|
+
pinIds.set(deviceId, pins);
|
|
1521
|
+
}
|
|
1522
|
+
pins.set(name, id);
|
|
1523
|
+
});
|
|
1524
|
+
for (const deviceId of allocation.pins.keys()) if (!pinIds.has(deviceId)) pinIds.set(deviceId, /* @__PURE__ */ new Map());
|
|
1525
|
+
const deviceBinders = /* @__PURE__ */ new Map();
|
|
1526
|
+
for (const [deviceId, ids] of pinIds) {
|
|
1527
|
+
const ordinaryResistors = allocation.resistors.get(deviceId);
|
|
1528
|
+
const contacts = allocation.contacts.get(deviceId);
|
|
1529
|
+
const queueSize = Math.max(1, ids.size, ordinaryResistors.size, contacts.size);
|
|
1530
|
+
const tag = `${prefix}_device_${deviceBinders.size}`;
|
|
1531
|
+
const queueId = module.array(`${tag}_ids`, "u32", Array(queueSize).fill(0));
|
|
1532
|
+
const queueNumber = module.array(`${tag}_numbers`, "f64", Array(queueSize).fill(1));
|
|
1533
|
+
const queueBool = module.array(`${tag}_flags`, "bool", Array(queueSize).fill(false));
|
|
1534
|
+
const valid = module.state(`${tag}_valid`, "bool", true);
|
|
1535
|
+
const changed = module.state(`${tag}_changed`, "bool", false);
|
|
1536
|
+
const positive = (b, value) => b.bool.and(b.float.isFinite(value), b.float.cmp("gt", value, b.const("f64", 0)));
|
|
1537
|
+
const applyResistors = module.func(`${tag}_resistances`, {
|
|
1538
|
+
params: ["u32"],
|
|
1539
|
+
results: []
|
|
1540
|
+
});
|
|
1541
|
+
applyResistors.body((b, [count]) => running(b, (b) => {
|
|
1542
|
+
b.state.store(valid, b.const("bool", true));
|
|
1543
|
+
return loop(b, count, (b, i) => {
|
|
1544
|
+
const accepted = positive(b, b.array.load(queueNumber, i));
|
|
1545
|
+
b.state.store(solver.faultTargetIndex, b.select(accepted, b.state.load(solver.faultTargetIndex), b.array.load(queueId, i)));
|
|
1546
|
+
b.state.store(valid, b.bool.and(b.state.load(valid), accepted));
|
|
1547
|
+
}, (b) => checked(b, b.state.load(valid), {
|
|
1548
|
+
kind: 1,
|
|
1549
|
+
index: b.state.load(solver.faultTargetIndex)
|
|
1550
|
+
}, (b) => {
|
|
1551
|
+
b.state.store(changed, b.const("bool", false));
|
|
1552
|
+
return loop(b, count, (b, i) => {
|
|
1553
|
+
const target = b.array.load(queueId, i);
|
|
1554
|
+
const value = b.array.load(queueNumber, i);
|
|
1555
|
+
b.state.store(changed, b.bool.or(b.state.load(changed), b.float.cmp("ne", b.array.load(solver.resistance, target), value)));
|
|
1556
|
+
b.array.store(solver.resistance, target, value);
|
|
1557
|
+
}, (b) => complete(b, b.state.load(changed), "matrix"));
|
|
1558
|
+
}));
|
|
1559
|
+
}));
|
|
1560
|
+
const applyConnections = module.func(`${tag}_contacts`, {
|
|
1561
|
+
params: ["u32"],
|
|
1562
|
+
results: []
|
|
1563
|
+
});
|
|
1564
|
+
applyConnections.body((b, [count]) => running(b, (b) => {
|
|
1565
|
+
b.state.store(changed, b.const("bool", false));
|
|
1566
|
+
return loop(b, count, (b, i) => {
|
|
1567
|
+
const target = b.array.load(queueId, i);
|
|
1568
|
+
const value = b.array.load(queueBool, i);
|
|
1569
|
+
b.state.store(changed, b.bool.or(b.state.load(changed), b.bool.xor(b.array.load(solver.contactClosed, target), value)));
|
|
1570
|
+
b.array.store(solver.contactClosed, target, value);
|
|
1571
|
+
}, (b) => complete(b, b.state.load(changed), "topology"));
|
|
1572
|
+
}));
|
|
1573
|
+
const writeDigitalGroup = module.func(`${tag}_digital_group`, {
|
|
1574
|
+
params: ["u32"],
|
|
1575
|
+
results: []
|
|
1576
|
+
});
|
|
1577
|
+
writeDigitalGroup.body((b, [count]) => running(b, (b) => loop(b, count, (b, i) => {
|
|
1578
|
+
const target = b.array.load(queueId, i);
|
|
1579
|
+
b.array.store(digital, target, b.array.load(queueBool, i));
|
|
1580
|
+
b.array.store(digitalReady, target, b.const("bool", true));
|
|
1581
|
+
}, (b) => {
|
|
1582
|
+
let changed = b.const("bool", false);
|
|
1583
|
+
for (const id of ids.values()) {
|
|
1584
|
+
const recompute = refresh.get(id);
|
|
1585
|
+
if (recompute === void 0) continue;
|
|
1586
|
+
const [value] = b.call(recompute, []);
|
|
1587
|
+
changed = b.bool.or(changed, value);
|
|
1588
|
+
}
|
|
1589
|
+
return complete(b, changed, "matrix");
|
|
1590
|
+
})));
|
|
1591
|
+
const setResistorEnabled = module.func(`${tag}_resistor_enable`, {
|
|
1592
|
+
params: ["u32", "bool"],
|
|
1593
|
+
results: []
|
|
1594
|
+
});
|
|
1595
|
+
setResistorEnabled.body((b, [target, value]) => running(b, (b) => {
|
|
1596
|
+
const changed = b.bool.xor(b.array.load(solver.resistorEnabled, target), value);
|
|
1597
|
+
b.array.store(solver.resistorEnabled, target, value);
|
|
1598
|
+
return complete(b, changed, "matrix");
|
|
1599
|
+
}));
|
|
1600
|
+
const setPull = /* @__PURE__ */ new Map();
|
|
1601
|
+
for (const id of ids.values()) {
|
|
1602
|
+
const bias = allPins[id].pin.bias;
|
|
1603
|
+
if (bias === void 0) continue;
|
|
1604
|
+
const fn = module.func(`${prefix}_pin_${id}_pull`, {
|
|
1605
|
+
params: ["u8"],
|
|
1606
|
+
results: []
|
|
1607
|
+
});
|
|
1608
|
+
fn.body((b, [value]) => running(b, (b) => {
|
|
1609
|
+
const up = b.int.cmp("eq", value, b.const("u8", 1));
|
|
1610
|
+
const down = b.int.cmp("eq", value, b.const("u8", 2));
|
|
1611
|
+
const changed = b.bool.or(b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.up)), up), b.bool.xor(b.array.load(solver.resistorEnabled, index(b, bias.down)), down));
|
|
1612
|
+
b.array.store(solver.resistorEnabled, index(b, bias.up), up);
|
|
1613
|
+
b.array.store(solver.resistorEnabled, index(b, bias.down), down);
|
|
1614
|
+
return complete(b, changed, "matrix");
|
|
1615
|
+
}));
|
|
1616
|
+
setPull.set(id, fn);
|
|
1617
|
+
}
|
|
1618
|
+
deviceBinders.set(deviceId, (b, globalIds) => {
|
|
1619
|
+
const lookup = (names, values, resources) => {
|
|
1620
|
+
if (names.length === 0 || names.length !== values.length || new Set(names).size !== names.length) badResource(`Invalid atomic patch for "${deviceId}"`);
|
|
1621
|
+
return names.map((name) => resources.get(name) ?? badResource(`Unknown electrical resource "${deviceId}.${name}"`));
|
|
1622
|
+
};
|
|
1623
|
+
const patch = (targets, values, numeric, fn) => {
|
|
1624
|
+
targets.forEach((target, i) => {
|
|
1625
|
+
b.array.store(queueId, index(b, i), index(b, target));
|
|
1626
|
+
if (numeric) b.array.store(queueNumber, index(b, i), values[i]);
|
|
1627
|
+
else b.array.store(queueBool, index(b, i), values[i]);
|
|
1628
|
+
});
|
|
1629
|
+
b.call(fn, [index(b, targets.length)]);
|
|
1630
|
+
};
|
|
1631
|
+
const handles = /* @__PURE__ */ new Map();
|
|
1632
|
+
for (const [name, id] of ids) {
|
|
1633
|
+
const description = allPins[id].pin;
|
|
1634
|
+
const functions = () => pinFunctions.get(id) ?? badResource(`Pin "${deviceId}.${name}" has no drive capability`);
|
|
1635
|
+
const handle = Object.freeze({
|
|
1636
|
+
name,
|
|
1637
|
+
globalId: globalIds?.get(name) ?? id,
|
|
1638
|
+
configure(selection) {
|
|
1639
|
+
if (!Object.values(PIN_MODE).includes(selection)) badResource(`Invalid pin mode ${selection}`);
|
|
1640
|
+
if (selection === PIN_MODE.analog && description.drive?.analog === void 0) badResource(`Pin "${deviceId}.${name}" has no analog drive capability`);
|
|
1641
|
+
if (selection === PIN_MODE.highZ && description.drive === void 0) return;
|
|
1642
|
+
b.call(functions().setMode, [b.const("u8", selection)]);
|
|
1643
|
+
},
|
|
1644
|
+
setOutputEnabled(value) {
|
|
1645
|
+
b.call(functions().setEnabled, [value]);
|
|
1646
|
+
},
|
|
1647
|
+
setPull(selection) {
|
|
1648
|
+
if (![
|
|
1649
|
+
"none",
|
|
1650
|
+
"up",
|
|
1651
|
+
"down"
|
|
1652
|
+
].includes(selection)) badResource(`Invalid pull ${selection}`);
|
|
1653
|
+
const fn = setPull.get(id) ?? (selection === "none" ? void 0 : badResource(`Pin "${deviceId}.${name}" has no bias capability`));
|
|
1654
|
+
if (fn === void 0) return;
|
|
1655
|
+
b.call(fn, [b.const("u8", selection === "none" ? 0 : selection === "up" ? 1 : 2)]);
|
|
1656
|
+
},
|
|
1657
|
+
writeDigital(value) {
|
|
1658
|
+
b.call(functions().writeDigital, [value]);
|
|
1659
|
+
},
|
|
1660
|
+
writeVoltage(value) {
|
|
1661
|
+
if (description.drive?.analog === void 0) badResource(`Pin "${deviceId}.${name}" has no analog drive capability`);
|
|
1662
|
+
b.call(functions().writeVoltage, [value]);
|
|
1663
|
+
},
|
|
1664
|
+
sampleDigital() {
|
|
1665
|
+
if (description.input === void 0) badResource(`Pin "${deviceId}.${name}" has no input capability`);
|
|
1666
|
+
b.call(ensure, []);
|
|
1667
|
+
return b.array.load(sampled, index(b, id));
|
|
1668
|
+
},
|
|
1669
|
+
sampleVoltage() {
|
|
1670
|
+
if (description.input === void 0) badResource(`Pin "${deviceId}.${name}" has no input capability`);
|
|
1671
|
+
let sample = analogRequests.get(id);
|
|
1672
|
+
if (sample === void 0) {
|
|
1673
|
+
if (finalized) badResource("Analog sampling must be declared before electrical finalization");
|
|
1674
|
+
sample = module.func(`${prefix}_analog_${id}_sample`, {
|
|
1675
|
+
params: [],
|
|
1676
|
+
results: ["f64"]
|
|
1677
|
+
});
|
|
1678
|
+
analogRequests.set(id, sample);
|
|
1679
|
+
}
|
|
1680
|
+
b.call(ensure, []);
|
|
1681
|
+
return b.call(sample, [])[0];
|
|
1682
|
+
},
|
|
1683
|
+
readDrivenDigital() {
|
|
1684
|
+
functions();
|
|
1685
|
+
return b.array.load(digital, index(b, id));
|
|
1686
|
+
}
|
|
1687
|
+
});
|
|
1688
|
+
handles.set(name, handle);
|
|
1689
|
+
}
|
|
1690
|
+
return Object.freeze({
|
|
1691
|
+
pins: Object.freeze([...handles.values()]),
|
|
1692
|
+
outputs: Object.freeze([...handles].filter(([name]) => allPins[ids.get(name)].pin.drive !== void 0).map(([, handle]) => handle)),
|
|
1693
|
+
pin(name) {
|
|
1694
|
+
return handles.get(name) ?? badResource(`Unknown pin "${deviceId}.${name}"`);
|
|
1695
|
+
},
|
|
1696
|
+
resistor(name) {
|
|
1697
|
+
const target = ordinaryResistors.get(name) ?? badResource(`Unknown resistor "${deviceId}.${name}"`);
|
|
1698
|
+
return Object.freeze({
|
|
1699
|
+
setResistance(value) {
|
|
1700
|
+
patch([target], [value], true, applyResistors);
|
|
1701
|
+
},
|
|
1702
|
+
setEnabled(value) {
|
|
1703
|
+
b.call(setResistorEnabled, [index(b, target), value]);
|
|
1704
|
+
},
|
|
1705
|
+
sampleCurrent() {
|
|
1706
|
+
b.call(ensure, []);
|
|
1707
|
+
return b.array.load(solver.current, index(b, target));
|
|
1708
|
+
}
|
|
1709
|
+
});
|
|
1710
|
+
},
|
|
1711
|
+
writeDigitalGroup(names, values) {
|
|
1712
|
+
const targets = lookup(names, values, ids);
|
|
1713
|
+
for (const id of targets) if (!pinFunctions.has(id)) badResource(`Pin "${allPins[id].name}" has no drive capability`);
|
|
1714
|
+
patch(targets, values, false, writeDigitalGroup);
|
|
1715
|
+
},
|
|
1716
|
+
applyResistors(names, values) {
|
|
1717
|
+
patch(lookup(names, values, ordinaryResistors), values, true, applyResistors);
|
|
1718
|
+
},
|
|
1719
|
+
applyConnections(names, values) {
|
|
1720
|
+
patch(lookup(names, values, contacts), values, false, applyConnections);
|
|
1721
|
+
}
|
|
1722
|
+
});
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
return Object.freeze({
|
|
1726
|
+
solver,
|
|
1727
|
+
ensure,
|
|
1728
|
+
clock,
|
|
1729
|
+
timeStep,
|
|
1730
|
+
advanceTime,
|
|
1731
|
+
finalize,
|
|
1732
|
+
digitalSample: sampled,
|
|
1733
|
+
digitalIntent: digital,
|
|
1734
|
+
pinIndices: new Map(allPins.map(({ deviceId, name }, index) => [`${deviceId}.${name}`, index])),
|
|
1735
|
+
bindDevice(deviceId, builder, globalIds) {
|
|
1736
|
+
return (deviceBinders.get(deviceId) ?? badResource(`Unknown electrical device "${deviceId}"`))(builder, globalIds);
|
|
1737
|
+
}
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
//#endregion
|
|
1741
|
+
//#region src/unified-ir/compiler/electrical-compilation.ts
|
|
1742
|
+
var circuits = /* @__PURE__ */ new WeakMap();
|
|
1743
|
+
var electricalCompilationOf = (circuit) => circuits.get(circuit);
|
|
1744
|
+
function retainElectricalCompilation(circuit, electrical) {
|
|
1745
|
+
circuits.set(circuit, electrical);
|
|
1746
|
+
}
|
|
1747
|
+
/** Keeps prepared resources and solver storage out of the public compiled description. */
|
|
1748
|
+
function prepareElectricalCompilation(module, devices, connections, options) {
|
|
1749
|
+
const fail = (message) => {
|
|
1750
|
+
throw new UnifiedIRCompilerError("invalid-input", message);
|
|
1751
|
+
};
|
|
1752
|
+
if ("rails" in options) fail("Unsupported boolean rails; declare explicit voltage sources");
|
|
1753
|
+
if (options.interpretation !== "two-state" && options.interpretation !== "retain-in-band") fail("Resistive circuits require an explicit digital interpretation");
|
|
1754
|
+
if (options.floatingSeed !== void 0 && (!Number.isInteger(options.floatingSeed) || options.floatingSeed < 0 || options.floatingSeed > 4294967295)) fail("floatingSeed must be a u32");
|
|
1755
|
+
const sources = options.sources ?? {};
|
|
1756
|
+
if (sources === null || typeof sources !== "object" || Array.isArray(sources)) fail("Voltage sources must be an object");
|
|
1757
|
+
for (const [id, source] of Object.entries(sources)) if (!id || id === "GND" || source === null || typeof source !== "object" || !Number.isFinite(source.voltage)) fail(`Invalid voltage source "${id}"`);
|
|
1758
|
+
const prepared = devices.map((device) => {
|
|
1759
|
+
const { description } = device;
|
|
1760
|
+
if (typeof description.factory !== "function") fail(`Device "${device.id}" needs a paired electrical factory`);
|
|
1761
|
+
const properties = device.properties === void 0 ? {} : device.properties;
|
|
1762
|
+
if (properties === null || typeof properties !== "object" || Array.isArray(properties)) fail(`Invalid properties for device "${device.id}"`);
|
|
1763
|
+
const result = prepareElectricalDevice({
|
|
1764
|
+
...description,
|
|
1765
|
+
pins: description.pins instanceof Map ? Object.fromEntries(description.pins) : description.pins
|
|
1766
|
+
}, properties, description.factory);
|
|
1767
|
+
const implementation = result.implementation;
|
|
1768
|
+
if (implementation !== void 0) {
|
|
1769
|
+
if (implementation === null || typeof implementation !== "object" || Array.isArray(implementation)) fail(`Device "${device.id}" factory must return behavior hooks or undefined`);
|
|
1770
|
+
for (const [name, callback] of Object.entries(implementation)) if (![
|
|
1771
|
+
"initialize",
|
|
1772
|
+
"tick",
|
|
1773
|
+
"update",
|
|
1774
|
+
"kernel",
|
|
1775
|
+
"applyInputs",
|
|
1776
|
+
"flushOutputs"
|
|
1777
|
+
].includes(name) || callback !== void 0 && typeof callback !== "function") fail(`Invalid factory behavior "${device.id}.${name}"`);
|
|
1778
|
+
}
|
|
1779
|
+
const phases = implementation === void 0 ? description.behaviors : {
|
|
1780
|
+
...implementation.initialize === void 0 ? {} : { initialize: implementation.initialize },
|
|
1781
|
+
...implementation.tick === void 0 ? {} : { tick: implementation.tick },
|
|
1782
|
+
...implementation.update === void 0 ? {} : { update: implementation.update }
|
|
1783
|
+
};
|
|
1784
|
+
if (phases !== void 0) {
|
|
1785
|
+
for (const [phase, callback] of Object.entries(phases)) if (![
|
|
1786
|
+
"initialize",
|
|
1787
|
+
"tick",
|
|
1788
|
+
"update"
|
|
1789
|
+
].includes(phase) || callback !== void 0 && typeof callback !== "function") fail(`Invalid factory behavior "${device.id}.${phase}"`);
|
|
1790
|
+
}
|
|
1791
|
+
const hasPhases = phases !== void 0 && Object.values(phases).some((value) => value !== void 0);
|
|
1792
|
+
if (implementation !== void 0 && description.behaviors !== void 0) fail(`Device "${device.id}" declares both factory and static behaviors`);
|
|
1793
|
+
if (implementation?.kernel !== void 0 && description.kernel !== void 0) fail(`Device "${device.id}" declares two kernels`);
|
|
1794
|
+
const kernel = implementation?.kernel ?? description.kernel;
|
|
1795
|
+
if (hasPhases && kernel !== void 0) fail(`Device "${device.id}" declares both behavior hooks and a kernel`);
|
|
1796
|
+
return {
|
|
1797
|
+
id: device.id,
|
|
1798
|
+
prepared: result,
|
|
1799
|
+
device: {
|
|
1800
|
+
...device,
|
|
1801
|
+
properties: result.properties,
|
|
1802
|
+
description: {
|
|
1803
|
+
...description,
|
|
1804
|
+
...phases === void 0 || !hasPhases ? {} : { behaviors: phases },
|
|
1805
|
+
...kernel === void 0 ? {} : { kernel },
|
|
1806
|
+
...implementation?.applyInputs === void 0 ? {} : { applyInputs: implementation.applyInputs },
|
|
1807
|
+
...implementation?.flushOutputs === void 0 ? {} : { flushOutputs: implementation.flushOutputs }
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
};
|
|
1811
|
+
});
|
|
1812
|
+
const endpoint = (name) => {
|
|
1813
|
+
if (name === "GND" || Object.hasOwn(sources, name)) return { source: name };
|
|
1814
|
+
const dot = name.indexOf(".");
|
|
1815
|
+
if (dot <= 0 || dot === name.length - 1) return fail(`Unknown electrical endpoint "${name}"`);
|
|
1816
|
+
return {
|
|
1817
|
+
device: name.slice(0, dot),
|
|
1818
|
+
pin: name.slice(dot + 1)
|
|
1819
|
+
};
|
|
1820
|
+
};
|
|
1821
|
+
const allocation = allocateElectricalNetwork(prepared, sources, connections.map(({ from, to }) => [endpoint(from), endpoint(to)]));
|
|
1822
|
+
return {
|
|
1823
|
+
devices: prepared.map(({ device }) => device),
|
|
1824
|
+
allocation,
|
|
1825
|
+
operations: createElectricalOperations(module, allocation, options.interpretation, "electrical", options.floatingSeed)
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
//#endregion
|
|
1829
|
+
//#region src/unified-ir/compiler/electrical-diagnostics.ts
|
|
1830
|
+
/** Resolves a latched solver origin against the attempted topology, not the last good snapshot. */
|
|
1831
|
+
function electricalFaultContext(allocation, solver, storage) {
|
|
1832
|
+
const { network } = allocation;
|
|
1833
|
+
const resistors = /* @__PURE__ */ new Map();
|
|
1834
|
+
const contacts = /* @__PURE__ */ new Map();
|
|
1835
|
+
const sources = /* @__PURE__ */ new Map();
|
|
1836
|
+
for (const [name, index] of allocation.sources) sources.set(index, {
|
|
1837
|
+
kind: "source",
|
|
1838
|
+
name
|
|
1839
|
+
});
|
|
1840
|
+
for (const [device, entries] of allocation.resistors) for (const [name, index] of entries) resistors.set(index, {
|
|
1841
|
+
kind: "resistor",
|
|
1842
|
+
device,
|
|
1843
|
+
name
|
|
1844
|
+
});
|
|
1845
|
+
for (const [device, entries] of allocation.contacts) for (const [name, index] of entries) contacts.set(index, {
|
|
1846
|
+
kind: "contact",
|
|
1847
|
+
device,
|
|
1848
|
+
name
|
|
1849
|
+
});
|
|
1850
|
+
for (const [device, entries] of allocation.pins) for (const [pin, config] of entries) {
|
|
1851
|
+
if (config.drive !== void 0) {
|
|
1852
|
+
const target = {
|
|
1853
|
+
kind: "drive",
|
|
1854
|
+
device,
|
|
1855
|
+
pin
|
|
1856
|
+
};
|
|
1857
|
+
resistors.set(config.drive.high, target);
|
|
1858
|
+
resistors.set(config.drive.low, target);
|
|
1859
|
+
if (config.drive.analog !== void 0) {
|
|
1860
|
+
resistors.set(config.drive.analog.resistor, target);
|
|
1861
|
+
sources.set(config.drive.analog.source, target);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
if (config.bias !== void 0) {
|
|
1865
|
+
resistors.set(config.bias.up, {
|
|
1866
|
+
kind: "pull-up",
|
|
1867
|
+
device,
|
|
1868
|
+
pin
|
|
1869
|
+
});
|
|
1870
|
+
resistors.set(config.bias.down, {
|
|
1871
|
+
kind: "pull-down",
|
|
1872
|
+
device,
|
|
1873
|
+
pin
|
|
1874
|
+
});
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
const kind = storage.loadState(solver.faultTargetKind);
|
|
1878
|
+
const index = storage.loadState(solver.faultTargetIndex);
|
|
1879
|
+
const target = (kind === 1 ? resistors : kind === 2 ? sources : kind === 3 ? contacts : void 0)?.get(index);
|
|
1880
|
+
const origin = kind === 1 ? network.resistors[index] : kind === 3 ? network.contacts[index] : void 0;
|
|
1881
|
+
const seeds = origin !== void 0 ? [origin.a, origin.b] : kind === 2 && network.sources[index] !== void 0 ? [network.sources[index].node] : kind === 4 ? [index] : [];
|
|
1882
|
+
const conflict = storage.loadState(solver.fault) === RESISTIVE_FAULT.sourceConflict;
|
|
1883
|
+
const edges = network.contacts.flatMap((edge, i) => storage.loadArray(solver.contactClosed, i) ? [{
|
|
1884
|
+
...edge,
|
|
1885
|
+
ideal: true
|
|
1886
|
+
}] : []);
|
|
1887
|
+
if (!conflict) {
|
|
1888
|
+
for (const [i, edge] of network.resistors.entries()) if (storage.loadArray(solver.resistorEnabled, i)) edges.push({
|
|
1889
|
+
...edge,
|
|
1890
|
+
ideal: false
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
const anchors = new Set(network.sources.flatMap((source, i) => storage.loadArray(solver.sourceEnabled, i) ? [source.node] : []));
|
|
1894
|
+
const anchorQueue = [...anchors];
|
|
1895
|
+
for (let i = 0; i < anchorQueue.length; i++) {
|
|
1896
|
+
const node = anchorQueue[i];
|
|
1897
|
+
for (const edge of edges) {
|
|
1898
|
+
if (!edge.ideal) continue;
|
|
1899
|
+
const next = edge.a === node ? edge.b : edge.b === node ? edge.a : void 0;
|
|
1900
|
+
if (next !== void 0 && !anchors.has(next)) {
|
|
1901
|
+
anchors.add(next);
|
|
1902
|
+
anchorQueue.push(next);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
const nodes = new Set(seeds);
|
|
1907
|
+
const queue = [...seeds];
|
|
1908
|
+
for (let i = 0; i < queue.length; i++) {
|
|
1909
|
+
const node = queue[i];
|
|
1910
|
+
for (const edge of edges) {
|
|
1911
|
+
if (!edge.ideal && anchors.has(node) && !seeds.includes(node)) continue;
|
|
1912
|
+
const next = edge.a === node ? edge.b : edge.b === node ? edge.a : void 0;
|
|
1913
|
+
if (next !== void 0 && !nodes.has(next)) {
|
|
1914
|
+
nodes.add(next);
|
|
1915
|
+
queue.push(next);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
const resources = /* @__PURE__ */ new Map();
|
|
1920
|
+
const add = (resource) => {
|
|
1921
|
+
if (resource !== void 0) resources.set(JSON.stringify(resource), Object.freeze(resource));
|
|
1922
|
+
};
|
|
1923
|
+
add(target);
|
|
1924
|
+
for (const [i, source] of network.sources.entries()) if (nodes.has(source.node) && storage.loadArray(solver.sourceEnabled, i)) add(sources.get(i));
|
|
1925
|
+
for (const [i, edge] of network.contacts.entries()) if (nodes.has(edge.a) && nodes.has(edge.b) && storage.loadArray(solver.contactClosed, i)) add(contacts.get(i));
|
|
1926
|
+
if (!conflict) {
|
|
1927
|
+
for (const [i, edge] of network.resistors.entries()) if (nodes.has(edge.a) && nodes.has(edge.b) && storage.loadArray(solver.resistorEnabled, i)) add(resistors.get(i));
|
|
1928
|
+
}
|
|
1929
|
+
const pins = [];
|
|
1930
|
+
for (const [device, entries] of allocation.pins) for (const [name, pin] of entries) if (nodes.has(pin.node)) pins.push(`${device}.${name}`);
|
|
1931
|
+
return Object.freeze({
|
|
1932
|
+
...target === void 0 ? {} : { target: Object.freeze(target) },
|
|
1933
|
+
resources: Object.freeze([...resources.values()]),
|
|
1934
|
+
pins: Object.freeze(pins)
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
//#endregion
|
|
1938
|
+
//#region src/unified-ir/validation.ts
|
|
1939
|
+
/**
|
|
1940
|
+
* Builds the validation grants a module needs to run on the reference engine or
|
|
1941
|
+
* the JIT: every instruction the model uses, authorized once, plus a grant for
|
|
1942
|
+
* each declared memory.
|
|
1943
|
+
*
|
|
1944
|
+
* `@mica-js/ir` deliberately keeps its core instruction list internal, so the
|
|
1945
|
+
* names are collected from the generated bodies instead of being restated here.
|
|
1946
|
+
*
|
|
1947
|
+
* @param module - Generated module whose bodies and memories are granted.
|
|
1948
|
+
* @param updateResources - Read-only byte regions that opt into the host-only
|
|
1949
|
+
* versioned update path (for example MCU firmware patching).
|
|
1950
|
+
*/
|
|
1951
|
+
function createModuleValidation(module, updateResources = []) {
|
|
1952
|
+
const names = /* @__PURE__ */ new Set();
|
|
1953
|
+
for (const fn of module.functions) {
|
|
1954
|
+
const body = fn.body;
|
|
1955
|
+
if (body === void 0) continue;
|
|
1956
|
+
for (const block of body.blocks) {
|
|
1957
|
+
for (const instruction of block.instructions) names.add(instruction.op);
|
|
1958
|
+
if (block.terminator !== void 0) names.add(block.terminator.kind);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
const instructions = Object.freeze([...names]);
|
|
1962
|
+
const resources = module.memories.map((memory) => Object.freeze({
|
|
1963
|
+
ref: memory.ref,
|
|
1964
|
+
access: memory.writable ? "read-write" : "read"
|
|
1965
|
+
}));
|
|
1966
|
+
const memories = new Set(module.memories.map((memory) => memory.ref));
|
|
1967
|
+
for (const ref of new Set(updateResources)) {
|
|
1968
|
+
if (!memories.has(ref)) continue;
|
|
1969
|
+
resources.push(Object.freeze({
|
|
1970
|
+
ref,
|
|
1971
|
+
access: "update"
|
|
1972
|
+
}));
|
|
1973
|
+
}
|
|
1974
|
+
return Object.freeze({
|
|
1975
|
+
supportedInstructions: instructions,
|
|
1976
|
+
authorizedInstructions: instructions,
|
|
1977
|
+
resources: Object.freeze(resources)
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
89
1980
|
//#endregion
|
|
90
1981
|
//#region src/unified-ir/compiler/allocator.ts
|
|
91
1982
|
/** Generated device ids prefix IR function names, so they must be identifiers. */
|
|
@@ -97,12 +1988,11 @@ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
|
97
1988
|
* ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
|
|
98
1989
|
* |<-- drive1 -->| |<----------- sink1 ----------->|
|
|
99
1990
|
*
|
|
100
|
-
* pin_mode[256] u8 pin_output[256] bool pin_input[256] bool
|
|
101
1991
|
* device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
|
|
102
1992
|
* ```
|
|
103
1993
|
*
|
|
104
1994
|
* Pins are packed in declaration order across devices — the addresses the
|
|
105
|
-
* device IR
|
|
1995
|
+
* device IR embeds as constants. States are packed per
|
|
106
1996
|
* scalar type into one shared array, so a device's slot stays typed while all
|
|
107
1997
|
* devices share one storage region.
|
|
108
1998
|
*/
|
|
@@ -111,12 +2001,11 @@ var GlobalResourceAllocator = class {
|
|
|
111
2001
|
constructor(module) {
|
|
112
2002
|
this.module = module;
|
|
113
2003
|
}
|
|
114
|
-
/** Allocates
|
|
2004
|
+
/** Allocates pin addresses and typed device state arrays. */
|
|
115
2005
|
allocate(devices) {
|
|
116
|
-
const
|
|
2006
|
+
const pins = this.allocatePins(devices);
|
|
117
2007
|
return Object.freeze({
|
|
118
|
-
|
|
119
|
-
pins: this.allocatePins(devices),
|
|
2008
|
+
pins,
|
|
120
2009
|
states: this.allocateStates(devices)
|
|
121
2010
|
});
|
|
122
2011
|
}
|
|
@@ -134,24 +2023,19 @@ var GlobalResourceAllocator = class {
|
|
|
134
2023
|
const allocations = /* @__PURE__ */ new Map();
|
|
135
2024
|
for (const device of devices) {
|
|
136
2025
|
const entries = pinEntries(device);
|
|
137
|
-
if (entries.length >
|
|
138
|
-
if (totalPins + entries.length >
|
|
2026
|
+
if (entries.length > 512) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" declares ${entries.length} pins; one device may own at most 512`, { deviceId: device.id });
|
|
2027
|
+
if (totalPins + entries.length > 4096) throw new UnifiedIRCompilerError("capacity-exceeded", `Device "${device.id}" does not fit: the circuit already uses ${totalPins} of ${UNIFIED_PIN_CAPACITY} global pins`, { deviceId: device.id });
|
|
139
2028
|
const offset = totalPins;
|
|
140
2029
|
const devicePins = /* @__PURE__ */ new Map();
|
|
141
2030
|
const resolved = /* @__PURE__ */ new Map();
|
|
142
|
-
for (const [name
|
|
2031
|
+
for (const [name] of entries) {
|
|
143
2032
|
const globalPinId = totalPins;
|
|
144
2033
|
totalPins += 1;
|
|
145
|
-
const direction = resolvePinDirection(descriptor, device.id, name);
|
|
146
|
-
const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);
|
|
147
2034
|
devicePins.set(name, globalPinId);
|
|
148
2035
|
resolved.set(name, Object.freeze({
|
|
149
2036
|
name,
|
|
150
2037
|
deviceId: device.id,
|
|
151
|
-
globalPinId
|
|
152
|
-
direction,
|
|
153
|
-
role,
|
|
154
|
-
senses
|
|
2038
|
+
globalPinId
|
|
155
2039
|
}));
|
|
156
2040
|
pins.set(`${device.id}.${name}`, globalPinId);
|
|
157
2041
|
}
|
|
@@ -166,7 +2050,7 @@ var GlobalResourceAllocator = class {
|
|
|
166
2050
|
pins,
|
|
167
2051
|
devices: allocations,
|
|
168
2052
|
totalPins,
|
|
169
|
-
capacity:
|
|
2053
|
+
capacity: UNIFIED_PIN_CAPACITY
|
|
170
2054
|
});
|
|
171
2055
|
}
|
|
172
2056
|
/**
|
|
@@ -225,14 +2109,6 @@ var GlobalResourceAllocator = class {
|
|
|
225
2109
|
});
|
|
226
2110
|
}
|
|
227
2111
|
};
|
|
228
|
-
/** Declares the three pin memories shared by every device and net solver. */
|
|
229
|
-
function createPinMemory(module) {
|
|
230
|
-
return Object.freeze({
|
|
231
|
-
mode: module.array("pin_mode", "u8", Array.from({ length: 256 }, () => PIN_MODE.highZ)),
|
|
232
|
-
output: module.array("pin_output", "bool", Array.from({ length: 256 }, () => false)),
|
|
233
|
-
input: module.array("pin_input", "bool", Array.from({ length: 256 }, () => false))
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
2112
|
/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
|
|
237
2113
|
function stateOffsetOf(states, deviceId) {
|
|
238
2114
|
let offset = 0;
|
|
@@ -274,53 +2150,6 @@ function pinEntries(device) {
|
|
|
274
2150
|
}
|
|
275
2151
|
return entries;
|
|
276
2152
|
}
|
|
277
|
-
var PIN_DIRECTIONS = /* @__PURE__ */ new Set([
|
|
278
|
-
"input",
|
|
279
|
-
"output",
|
|
280
|
-
"bidirectional",
|
|
281
|
-
"passive"
|
|
282
|
-
]);
|
|
283
|
-
function resolvePinDirection(descriptor, deviceId, pinName) {
|
|
284
|
-
const direction = descriptor?.direction ?? "passive";
|
|
285
|
-
if (!PIN_DIRECTIONS.has(direction)) throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" pin "${pinName}" has direction ${JSON.stringify(direction)}; expected input, output, bidirectional or passive`, {
|
|
286
|
-
deviceId,
|
|
287
|
-
pinName
|
|
288
|
-
});
|
|
289
|
-
return direction;
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* Derives the electrical role and the read behavior of a pin.
|
|
293
|
-
*
|
|
294
|
-
* `output` drives only, `input`/`passive` sense only, `bidirectional` drives and
|
|
295
|
-
* senses. An explicit `role` overrides the derived drive role while
|
|
296
|
-
* `bidirectional` keeps its sense side.
|
|
297
|
-
*/
|
|
298
|
-
function resolvePinRole(direction, explicit, deviceId, pinName) {
|
|
299
|
-
if (explicit !== void 0 && explicit !== "driver" && explicit !== "load") throw new UnifiedIRCompilerError("invalid-input", `Device "${deviceId}" pin "${pinName}" has role ${JSON.stringify(explicit)}; expected driver or load`, {
|
|
300
|
-
deviceId,
|
|
301
|
-
pinName
|
|
302
|
-
});
|
|
303
|
-
if (explicit === "driver") return {
|
|
304
|
-
role: "driver",
|
|
305
|
-
senses: direction === "bidirectional"
|
|
306
|
-
};
|
|
307
|
-
if (explicit === "load") return {
|
|
308
|
-
role: "load",
|
|
309
|
-
senses: true
|
|
310
|
-
};
|
|
311
|
-
if (direction === "output") return {
|
|
312
|
-
role: "driver",
|
|
313
|
-
senses: false
|
|
314
|
-
};
|
|
315
|
-
if (direction === "bidirectional") return {
|
|
316
|
-
role: "driver",
|
|
317
|
-
senses: true
|
|
318
|
-
};
|
|
319
|
-
return {
|
|
320
|
-
role: "load",
|
|
321
|
-
senses: true
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
2153
|
function stateEntries(device) {
|
|
325
2154
|
const raw = device.description.states;
|
|
326
2155
|
if (raw === void 0) return [];
|
|
@@ -347,11 +2176,8 @@ function assertStateInitial(deviceId, name, type, initial) {
|
|
|
347
2176
|
/**
|
|
348
2177
|
* Generates one IR function per device phase into the unified module.
|
|
349
2178
|
*
|
|
350
|
-
* Domain operations
|
|
351
|
-
*
|
|
352
|
-
* on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device
|
|
353
|
-
* keeps its own module, protocol or host hop. A device without an explicit
|
|
354
|
-
* `initialize` still gets one that configures its output pins as push-pull.
|
|
2179
|
+
* Domain operations use the shared resistive electrical network, including
|
|
2180
|
+
* explicit output configuration, finite drive impedance and solved sampling.
|
|
355
2181
|
*
|
|
356
2182
|
* The compiler ships no device models: every description must declare its own
|
|
357
2183
|
* pins, states and behaviors (or a `kernel`) before it reaches this generator.
|
|
@@ -362,21 +2188,21 @@ var DeviceIRGenerator = class {
|
|
|
362
2188
|
this.context = context;
|
|
363
2189
|
}
|
|
364
2190
|
/**
|
|
365
|
-
* @throws {UnifiedIRCompilerError} when
|
|
366
|
-
*
|
|
2191
|
+
* @throws {UnifiedIRCompilerError} when a behavior reaches for a pin or state
|
|
2192
|
+
* the paired description does not declare.
|
|
367
2193
|
*/
|
|
368
2194
|
generate(device) {
|
|
369
2195
|
const allocation = this.context.pins.devices.get(device.id);
|
|
370
2196
|
if (allocation === void 0) throw new UnifiedIRCompilerError("invalid-input", `Device "${device.id}" has no pin allocation; allocate resources before generating IR`, { deviceId: device.id });
|
|
2197
|
+
const functionOffset = this.context.module.functions.length;
|
|
371
2198
|
const kernelResult = device.description.kernel?.({
|
|
372
2199
|
deviceId: device.id,
|
|
373
2200
|
config: device.config,
|
|
374
2201
|
module: this.context.module,
|
|
375
|
-
|
|
2202
|
+
bind: (builder) => this.createApi(device, allocation, builder),
|
|
376
2203
|
pins: [...allocation.resolved.values()].map((pin) => Object.freeze({
|
|
377
2204
|
name: pin.name,
|
|
378
|
-
globalPinId: pin.globalPinId
|
|
379
|
-
role: pin.role
|
|
2205
|
+
globalPinId: pin.globalPinId
|
|
380
2206
|
}))
|
|
381
2207
|
});
|
|
382
2208
|
const kernelRuntime = kernelResult !== void 0 && isKernelRuntime(kernelResult) ? kernelResult : void 0;
|
|
@@ -389,10 +2215,9 @@ var DeviceIRGenerator = class {
|
|
|
389
2215
|
tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);
|
|
390
2216
|
update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);
|
|
391
2217
|
} else {
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
update = this.generatePhase(device, allocation, "update", behaviors.update);
|
|
2218
|
+
initialize = this.generatePhase(device, allocation, "initialize", behaviors?.initialize);
|
|
2219
|
+
tick = this.generatePhase(device, allocation, "tick", behaviors?.tick);
|
|
2220
|
+
update = this.generatePhase(device, allocation, "update", behaviors?.update);
|
|
396
2221
|
}
|
|
397
2222
|
const functions = [];
|
|
398
2223
|
for (const phase of [
|
|
@@ -403,6 +2228,7 @@ var DeviceIRGenerator = class {
|
|
|
403
2228
|
const metadata = Object.freeze({
|
|
404
2229
|
deviceId: device.id,
|
|
405
2230
|
type: device.type,
|
|
2231
|
+
entries: Object.freeze(this.context.module.functions.slice(functionOffset).filter((fn) => fn.category === "entry").map((fn) => fn.ref)),
|
|
406
2232
|
pinOffset: allocation.offset,
|
|
407
2233
|
stateOffset: stateOffsetOf(this.context.states, device.id),
|
|
408
2234
|
pins: allocation.pins,
|
|
@@ -412,7 +2238,8 @@ var DeviceIRGenerator = class {
|
|
|
412
2238
|
tick: tick?.name,
|
|
413
2239
|
update: update?.name,
|
|
414
2240
|
accessor: device.description.accessor,
|
|
415
|
-
|
|
2241
|
+
...device.description.applyInputs === void 0 ? {} : { applyInputs: device.description.applyInputs },
|
|
2242
|
+
...device.description.flushOutputs === void 0 ? {} : { flushOutputs: device.description.flushOutputs }
|
|
416
2243
|
});
|
|
417
2244
|
return Object.freeze({
|
|
418
2245
|
metadata,
|
|
@@ -440,53 +2267,21 @@ var DeviceIRGenerator = class {
|
|
|
440
2267
|
ref
|
|
441
2268
|
};
|
|
442
2269
|
}
|
|
443
|
-
generateDefaultInitialize(device, allocation) {
|
|
444
|
-
const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === "driver");
|
|
445
|
-
if (outputs.length === 0) return void 0;
|
|
446
|
-
const name = `${device.id}_initialize`;
|
|
447
|
-
const ref = this.context.module.func(name, {
|
|
448
|
-
params: [],
|
|
449
|
-
results: []
|
|
450
|
-
});
|
|
451
|
-
ref.body((b) => {
|
|
452
|
-
for (const pin of outputs) b.array.store(this.context.memory.mode, b.const("u32", pin.globalPinId), b.const("u8", PIN_MODE.pushPull));
|
|
453
|
-
b.return([]);
|
|
454
|
-
});
|
|
455
|
-
return {
|
|
456
|
-
name,
|
|
457
|
-
ref
|
|
458
|
-
};
|
|
459
|
-
}
|
|
460
2270
|
createApi(device, allocation, builder) {
|
|
461
|
-
const handles = /* @__PURE__ */ new Map();
|
|
462
|
-
const pins = [];
|
|
463
|
-
const outputs = [];
|
|
464
|
-
for (const pin of allocation.resolved.values()) {
|
|
465
|
-
const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);
|
|
466
|
-
handles.set(pin.name, handle);
|
|
467
|
-
pins.push(handle);
|
|
468
|
-
if (pin.role === "driver") outputs.push(handle);
|
|
469
|
-
}
|
|
470
2271
|
const slots = this.context.states.devices.get(device.id);
|
|
2272
|
+
const electrical = this.context.electrical.bindDevice(device.id, builder, new Map([...allocation.resolved].map(([name, pin]) => [name, pin.globalPinId])));
|
|
471
2273
|
return Object.freeze({
|
|
472
2274
|
deviceId: device.id,
|
|
473
2275
|
builder,
|
|
474
2276
|
module: this.context.module,
|
|
475
|
-
memory: this.context.memory,
|
|
476
2277
|
config: device.config,
|
|
477
|
-
pins:
|
|
478
|
-
outputs:
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
deviceId: device.id,
|
|
485
|
-
pinName: name
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
return handle;
|
|
489
|
-
},
|
|
2278
|
+
pins: electrical.pins,
|
|
2279
|
+
outputs: electrical.outputs,
|
|
2280
|
+
resistor: electrical.resistor,
|
|
2281
|
+
writeDigitalGroup: electrical.writeDigitalGroup,
|
|
2282
|
+
applyResistors: electrical.applyResistors,
|
|
2283
|
+
applyConnections: electrical.applyConnections,
|
|
2284
|
+
pin: electrical.pin,
|
|
490
2285
|
state(name) {
|
|
491
2286
|
const slot = slots?.get(name);
|
|
492
2287
|
if (slot === void 0) throw new UnifiedIRCompilerError("state-not-found", `Device "${device.id}" has no state "${name}". Available: [${[...slots?.keys() ?? []].join(", ")}]`, { deviceId: device.id });
|
|
@@ -494,27 +2289,6 @@ var DeviceIRGenerator = class {
|
|
|
494
2289
|
}
|
|
495
2290
|
});
|
|
496
2291
|
}
|
|
497
|
-
createPinHandle(globalId, name, builder) {
|
|
498
|
-
const memory = this.context.memory;
|
|
499
|
-
const index = () => builder.const("u32", globalId);
|
|
500
|
-
return Object.freeze({
|
|
501
|
-
name,
|
|
502
|
-
globalId,
|
|
503
|
-
configure(mode) {
|
|
504
|
-
if (!Number.isInteger(mode) || mode < 0 || mode > 255) throw new UnifiedIRCompilerError("invalid-input", `Pin "${name}" configure(${String(mode)}) needs a u8 pin mode`);
|
|
505
|
-
builder.array.store(memory.mode, index(), builder.const("u8", mode));
|
|
506
|
-
},
|
|
507
|
-
writeDigital(level) {
|
|
508
|
-
builder.array.store(memory.output, index(), level);
|
|
509
|
-
},
|
|
510
|
-
sampleDigital() {
|
|
511
|
-
return builder.array.load(memory.input, index());
|
|
512
|
-
},
|
|
513
|
-
readDrivenDigital() {
|
|
514
|
-
return builder.array.load(memory.output, index());
|
|
515
|
-
}
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
2292
|
};
|
|
519
2293
|
function createStateHandle(deviceId, slot, builder) {
|
|
520
2294
|
const array = slot.array;
|
|
@@ -531,9 +2305,6 @@ function createStateHandle(deviceId, slot, builder) {
|
|
|
531
2305
|
}
|
|
532
2306
|
});
|
|
533
2307
|
}
|
|
534
|
-
function hasAnyBehavior(behaviors) {
|
|
535
|
-
return behaviors.initialize !== void 0 || behaviors.tick !== void 0 || behaviors.update !== void 0;
|
|
536
|
-
}
|
|
537
2308
|
/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */
|
|
538
2309
|
function isKernelRuntime(value) {
|
|
539
2310
|
if (value === null || typeof value !== "object") return false;
|
|
@@ -571,99 +2342,81 @@ var DEFAULT_ENTRY_POINT_NAMES = Object.freeze({
|
|
|
571
2342
|
*
|
|
572
2343
|
* unified_tick: // one simulation step
|
|
573
2344
|
* drive1_tick() // drivers publish their outputs
|
|
574
|
-
*
|
|
2345
|
+
* electrical_ensure() // solve only if the network changed
|
|
575
2346
|
* sink1_update() // loads observe the solved inputs
|
|
576
2347
|
*
|
|
577
2348
|
* unified_tick_batch(count): // the same step, looped inside the IR
|
|
578
2349
|
* for i in 0 .. count { <step> }
|
|
579
2350
|
* ```
|
|
580
2351
|
*
|
|
581
|
-
* Devices run in
|
|
582
|
-
*
|
|
583
|
-
* after the topological prefix, so clock cycles stay valid.
|
|
2352
|
+
* Devices run in declaration order, with all tick phases before update phases.
|
|
2353
|
+
* Typed electrical sampling ensures pending network changes are solved.
|
|
584
2354
|
*/
|
|
585
2355
|
var MainLoopGenerator = class {
|
|
2356
|
+
electrical;
|
|
586
2357
|
module;
|
|
587
|
-
constructor(module) {
|
|
2358
|
+
constructor(module, electrical) {
|
|
2359
|
+
this.electrical = electrical;
|
|
588
2360
|
this.module = module;
|
|
589
2361
|
}
|
|
590
|
-
/** Stable topological order of the devices; cycles fall back to declaration order. */
|
|
591
|
-
order(entries, netlist) {
|
|
592
|
-
const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));
|
|
593
|
-
const consumers = /* @__PURE__ */ new Map();
|
|
594
|
-
const indegree = new Map(entries.map((entry) => [entry.deviceId, 0]));
|
|
595
|
-
for (const net of netlist.nets) {
|
|
596
|
-
const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));
|
|
597
|
-
const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));
|
|
598
|
-
for (const driver of driverDevices) for (const sink of sinkDevices) {
|
|
599
|
-
if (driver === sink) continue;
|
|
600
|
-
let targets = consumers.get(driver);
|
|
601
|
-
if (targets === void 0) {
|
|
602
|
-
targets = /* @__PURE__ */ new Set();
|
|
603
|
-
consumers.set(driver, targets);
|
|
604
|
-
}
|
|
605
|
-
if (targets.has(sink)) continue;
|
|
606
|
-
targets.add(sink);
|
|
607
|
-
indegree.set(sink, (indegree.get(sink) ?? 0) + 1);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
const ready = new Set(entries.filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0).map((entry) => entry.deviceId));
|
|
611
|
-
const order = [];
|
|
612
|
-
while (ready.size > 0) {
|
|
613
|
-
let nextId;
|
|
614
|
-
let nextIndex = Number.POSITIVE_INFINITY;
|
|
615
|
-
for (const id of ready) {
|
|
616
|
-
const index = indexById.get(id) ?? 0;
|
|
617
|
-
if (index < nextIndex) {
|
|
618
|
-
nextIndex = index;
|
|
619
|
-
nextId = id;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
if (nextId === void 0) break;
|
|
623
|
-
ready.delete(nextId);
|
|
624
|
-
order.push(nextId);
|
|
625
|
-
for (const consumer of consumers.get(nextId) ?? []) {
|
|
626
|
-
const remaining = (indegree.get(consumer) ?? 0) - 1;
|
|
627
|
-
indegree.set(consumer, remaining);
|
|
628
|
-
if (remaining === 0) ready.add(consumer);
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
for (const entry of entries) if (!order.includes(entry.deviceId)) order.push(entry.deviceId);
|
|
632
|
-
return Object.freeze(order);
|
|
633
|
-
}
|
|
634
2362
|
/** Generates `initialize`, `tick` and the batched tick loop. */
|
|
635
|
-
generate(entries,
|
|
636
|
-
const order =
|
|
2363
|
+
generate(entries, names = DEFAULT_ENTRY_POINT_NAMES) {
|
|
2364
|
+
const order = Object.freeze(entries.map((entry) => entry.deviceId));
|
|
637
2365
|
const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));
|
|
638
|
-
const
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
2366
|
+
const electrical = this.electrical;
|
|
2367
|
+
electrical.finalize();
|
|
2368
|
+
const progress = this.module.state(`${names.tick}_completed`, "u32", 0);
|
|
2369
|
+
const collect = (phase) => order.flatMap((id) => {
|
|
2370
|
+
const ref = byId.get(id)?.[phase];
|
|
2371
|
+
return ref === void 0 ? [] : [ref];
|
|
2372
|
+
});
|
|
2373
|
+
const ensure = [electrical.ensure];
|
|
2374
|
+
const phases = [
|
|
2375
|
+
...collect("tick"),
|
|
2376
|
+
...ensure,
|
|
2377
|
+
...collect("update"),
|
|
2378
|
+
...ensure
|
|
2379
|
+
];
|
|
2380
|
+
const emitCalls = (b, calls, finish) => {
|
|
2381
|
+
const emit = (b, at) => {
|
|
2382
|
+
const next = b.block([]);
|
|
2383
|
+
const failed = b.block([]);
|
|
2384
|
+
b.branch(b.int.cmp("eq", b.state.load(electrical.solver.fault), b.const("u8", 0)), {
|
|
2385
|
+
target: next,
|
|
2386
|
+
args: []
|
|
2387
|
+
}, {
|
|
2388
|
+
target: failed,
|
|
2389
|
+
args: []
|
|
2390
|
+
});
|
|
2391
|
+
b.at(failed, (b) => b.return([]));
|
|
2392
|
+
b.at(next, (b) => {
|
|
2393
|
+
const call = calls[at];
|
|
2394
|
+
if (call === void 0) return finish(b);
|
|
2395
|
+
b.call(call, []);
|
|
2396
|
+
return emit(b, at + 1);
|
|
2397
|
+
});
|
|
2398
|
+
};
|
|
2399
|
+
return emit(b, 0);
|
|
2400
|
+
};
|
|
2401
|
+
const completed = (b) => {
|
|
2402
|
+
b.call(electrical.advanceTime, []);
|
|
2403
|
+
b.state.store(progress, b.int.add(b.state.load(progress), b.const("u32", 1)));
|
|
648
2404
|
};
|
|
649
2405
|
const initialize = this.module.func(names.initialize, {
|
|
650
2406
|
params: [],
|
|
651
2407
|
results: []
|
|
652
2408
|
});
|
|
653
|
-
initialize.body((b) =>
|
|
654
|
-
for (const deviceId of order) {
|
|
655
|
-
const entry = byId.get(deviceId);
|
|
656
|
-
if (entry?.initialize !== void 0) b.call(entry.initialize, []);
|
|
657
|
-
}
|
|
658
|
-
b.return([]);
|
|
659
|
-
});
|
|
2409
|
+
initialize.body((b) => emitCalls(b, [...collect("initialize"), ...ensure], (b) => b.return([])));
|
|
660
2410
|
const tick = this.module.func(names.tick, {
|
|
661
2411
|
params: [],
|
|
662
2412
|
results: []
|
|
663
2413
|
});
|
|
664
2414
|
tick.body((b) => {
|
|
665
|
-
|
|
666
|
-
|
|
2415
|
+
b.state.store(progress, b.const("u32", 0));
|
|
2416
|
+
return emitCalls(b, phases, (b) => {
|
|
2417
|
+
completed(b);
|
|
2418
|
+
b.return([]);
|
|
2419
|
+
});
|
|
667
2420
|
});
|
|
668
2421
|
const batch = this.module.func(names.batch, {
|
|
669
2422
|
params: ["u32"],
|
|
@@ -673,329 +2426,32 @@ var MainLoopGenerator = class {
|
|
|
673
2426
|
const header = b.block(["u32"]);
|
|
674
2427
|
const body = b.block(["u32"]);
|
|
675
2428
|
const done = b.block([]);
|
|
2429
|
+
b.state.store(progress, b.const("u32", 0));
|
|
676
2430
|
b.jump(header, [b.const("u32", 0)]);
|
|
677
|
-
b.at(header, (
|
|
2431
|
+
b.at(header, (b, [index]) => b.branch(b.int.cmp("lt", index, count), {
|
|
678
2432
|
target: body,
|
|
679
2433
|
args: [index]
|
|
680
2434
|
}, {
|
|
681
2435
|
target: done,
|
|
682
2436
|
args: []
|
|
683
2437
|
}));
|
|
684
|
-
b.at(body, (
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
});
|
|
688
|
-
b.at(done, (
|
|
2438
|
+
b.at(body, (b, [index]) => emitCalls(b, phases, (b) => {
|
|
2439
|
+
completed(b);
|
|
2440
|
+
b.jump(header, [b.int.add(index, b.const("u32", 1))]);
|
|
2441
|
+
}));
|
|
2442
|
+
b.at(done, (b) => b.return([]));
|
|
689
2443
|
});
|
|
690
2444
|
return Object.freeze({
|
|
691
2445
|
names,
|
|
692
2446
|
initialize,
|
|
693
2447
|
tick,
|
|
694
2448
|
batch,
|
|
2449
|
+
progress,
|
|
695
2450
|
order
|
|
696
2451
|
});
|
|
697
2452
|
}
|
|
698
2453
|
};
|
|
699
2454
|
//#endregion
|
|
700
|
-
//#region src/unified-ir/compiler/solver-gen.ts
|
|
701
|
-
/**
|
|
702
|
-
* Generates the electrical solve, one `solve_net_<id>` function per net.
|
|
703
|
-
*
|
|
704
|
-
* Single driver — the only shape v1 compiles without `allowMultiDriver` — is a
|
|
705
|
-
* branch-free path:
|
|
706
|
-
*
|
|
707
|
-
* ```text
|
|
708
|
-
* solve_net_0:
|
|
709
|
-
* let mode = PIN_MODE[driver]
|
|
710
|
-
* let output = PIN_OUTPUT[driver]
|
|
711
|
-
* let driven = mode == PUSH_PULL && output
|
|
712
|
-
* PIN_INPUT[load] = driven // once per sink
|
|
713
|
-
* ```
|
|
714
|
-
*
|
|
715
|
-
* Only a push-pull driver holds its net; high-z, open-drain and analog modes
|
|
716
|
-
* leave it floating. A driver-less net loads the constant of its rail, or
|
|
717
|
-
* `false` when it is truly floating.
|
|
718
|
-
*/
|
|
719
|
-
var ElectricalSolverGenerator = class {
|
|
720
|
-
context;
|
|
721
|
-
constructor(context) {
|
|
722
|
-
this.context = context;
|
|
723
|
-
}
|
|
724
|
-
generate(netlist) {
|
|
725
|
-
return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));
|
|
726
|
-
}
|
|
727
|
-
generateNetSolver(net) {
|
|
728
|
-
const name = `solve_net_${net.netId}`;
|
|
729
|
-
const solve = this.context.module.func(name, {
|
|
730
|
-
params: [],
|
|
731
|
-
results: []
|
|
732
|
-
});
|
|
733
|
-
solve.body((b) => {
|
|
734
|
-
if (net.sinks.length > 0) {
|
|
735
|
-
const driven = net.drivers.length === 0 ? b.const("bool", net.level) : this.combineDrivers(b, net.drivers);
|
|
736
|
-
if (driven !== void 0) for (const sink of net.sinks) b.array.store(this.context.memory.input, b.const("u32", sink.globalPinId), driven);
|
|
737
|
-
}
|
|
738
|
-
b.return([]);
|
|
739
|
-
});
|
|
740
|
-
return Object.freeze({
|
|
741
|
-
netId: net.netId,
|
|
742
|
-
name,
|
|
743
|
-
net,
|
|
744
|
-
solve
|
|
745
|
-
});
|
|
746
|
-
}
|
|
747
|
-
/**
|
|
748
|
-
* Folds the drivers of one net into the level its sinks observe.
|
|
749
|
-
*
|
|
750
|
-
* A single driver yields `mode == push-pull && output`; several drivers (only
|
|
751
|
-
* reachable with `allowMultiDriver`) are OR-ed into a wired-OR level.
|
|
752
|
-
*/
|
|
753
|
-
combineDrivers(b, drivers) {
|
|
754
|
-
let driven;
|
|
755
|
-
for (const driver of drivers) {
|
|
756
|
-
const index = b.const("u32", driver.globalPinId);
|
|
757
|
-
const mode = b.array.load(this.context.memory.mode, index);
|
|
758
|
-
const output = b.array.load(this.context.memory.output, index);
|
|
759
|
-
const pushed = b.int.cmp("eq", mode, b.const("u8", PIN_MODE.pushPull));
|
|
760
|
-
const value = b.bool.and(pushed, output);
|
|
761
|
-
driven = driven === void 0 ? value : b.bool.or(driven, value);
|
|
762
|
-
}
|
|
763
|
-
return driven;
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
//#endregion
|
|
767
|
-
//#region src/unified-ir/compiler/topology.ts
|
|
768
|
-
/** Rails every circuit understands without declaring them. */
|
|
769
|
-
var DEFAULT_RAILS = Object.freeze({
|
|
770
|
-
GND: false,
|
|
771
|
-
VCC: true,
|
|
772
|
-
VDD: true
|
|
773
|
-
});
|
|
774
|
-
/**
|
|
775
|
-
* Analyses the pin-to-pin connections of a circuit.
|
|
776
|
-
*
|
|
777
|
-
* 1. every connection edge joins two nodes (pins and rails);
|
|
778
|
-
* 2. a union-find pass collapses them into electrical nets (connected components);
|
|
779
|
-
* 3. each net gets an id in first-appearance order and is split into drivers,
|
|
780
|
-
* loads and sinks;
|
|
781
|
-
* 4. electrical conflicts (several drivers, a driver against a rail, two rails
|
|
782
|
-
* of opposite level) become diagnostics instead of silently wrong IR.
|
|
783
|
-
*
|
|
784
|
-
* The v1 electrical model supports one driver per net. `allowMultiDriver`
|
|
785
|
-
* accepts more and the solver then emits a wired-OR instead of failing.
|
|
786
|
-
*/
|
|
787
|
-
var NetworkTopologyAnalyzer = class {
|
|
788
|
-
rails;
|
|
789
|
-
allowMultiDriver;
|
|
790
|
-
constructor(options = {}) {
|
|
791
|
-
this.rails = new Map([...Object.entries(DEFAULT_RAILS), ...Object.entries(options.rails ?? {})]);
|
|
792
|
-
this.allowMultiDriver = options.allowMultiDriver ?? false;
|
|
793
|
-
}
|
|
794
|
-
/**
|
|
795
|
-
* @throws {UnifiedIRCompilerError} when a connection is malformed, names an
|
|
796
|
-
* unknown device, or names a pin the device does not declare.
|
|
797
|
-
*/
|
|
798
|
-
analyze(connections, pins) {
|
|
799
|
-
if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
|
|
800
|
-
const set = new DisjointSet();
|
|
801
|
-
const pinNodes = /* @__PURE__ */ new Map();
|
|
802
|
-
const railNodes = /* @__PURE__ */ new Map();
|
|
803
|
-
const railNodeIds = /* @__PURE__ */ new Map();
|
|
804
|
-
const connectionOrder = [];
|
|
805
|
-
for (const [index, connection] of connections.entries()) {
|
|
806
|
-
if (connection === null || typeof connection !== "object") throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] must be an object with "from" and "to"`);
|
|
807
|
-
const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);
|
|
808
|
-
const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);
|
|
809
|
-
set.union(from.nodeId, to.nodeId);
|
|
810
|
-
connectionOrder.push(from.nodeId);
|
|
811
|
-
if (from.kind === "pin") pinNodes.set(from.pin.globalPinId, toConnection(from.pin));
|
|
812
|
-
else railNodes.set(from.nodeId, Object.freeze({
|
|
813
|
-
name: from.name,
|
|
814
|
-
level: from.level
|
|
815
|
-
}));
|
|
816
|
-
if (to.kind === "pin") pinNodes.set(to.pin.globalPinId, toConnection(to.pin));
|
|
817
|
-
else railNodes.set(to.nodeId, Object.freeze({
|
|
818
|
-
name: to.name,
|
|
819
|
-
level: to.level
|
|
820
|
-
}));
|
|
821
|
-
}
|
|
822
|
-
const components = /* @__PURE__ */ new Map();
|
|
823
|
-
const componentOf = (nodeId) => {
|
|
824
|
-
const root = set.find(nodeId);
|
|
825
|
-
let component = components.get(root);
|
|
826
|
-
if (component === void 0) {
|
|
827
|
-
component = {
|
|
828
|
-
pins: [],
|
|
829
|
-
rails: [],
|
|
830
|
-
endpoints: []
|
|
831
|
-
};
|
|
832
|
-
components.set(root, component);
|
|
833
|
-
}
|
|
834
|
-
return component;
|
|
835
|
-
};
|
|
836
|
-
for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);
|
|
837
|
-
for (const [nodeId, rail] of railNodes) {
|
|
838
|
-
const component = componentOf(nodeId);
|
|
839
|
-
component.rails.push(rail);
|
|
840
|
-
component.endpoints.push(rail.name);
|
|
841
|
-
}
|
|
842
|
-
const orderedRoots = [];
|
|
843
|
-
const seen = /* @__PURE__ */ new Set();
|
|
844
|
-
for (const nodeId of connectionOrder) {
|
|
845
|
-
const root = set.find(nodeId);
|
|
846
|
-
if (seen.has(root)) continue;
|
|
847
|
-
seen.add(root);
|
|
848
|
-
orderedRoots.push(root);
|
|
849
|
-
}
|
|
850
|
-
const diagnostics = [];
|
|
851
|
-
const nets = [];
|
|
852
|
-
for (const root of orderedRoots) {
|
|
853
|
-
const component = components.get(root);
|
|
854
|
-
if (component === void 0) continue;
|
|
855
|
-
component.pins.sort((left, right) => left.globalPinId - right.globalPinId);
|
|
856
|
-
component.rails.sort((left, right) => left.name.localeCompare(right.name));
|
|
857
|
-
const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];
|
|
858
|
-
if (component.pins.length === 0) {
|
|
859
|
-
if (new Set(component.rails.map((rail) => rail.level)).size > 1) diagnostics.push(diagnostic("rail-conflict", "error", `Rails ${component.rails.map((rail) => rail.name).join(" and ")} are wired together with opposite levels`, void 0, endpoints));
|
|
860
|
-
continue;
|
|
861
|
-
}
|
|
862
|
-
const netId = nets.length;
|
|
863
|
-
const net = this.classify(netId, component.pins, component.rails, diagnostics);
|
|
864
|
-
nets.push(net);
|
|
865
|
-
}
|
|
866
|
-
return Object.freeze({
|
|
867
|
-
nets: Object.freeze(nets),
|
|
868
|
-
diagnostics: Object.freeze(diagnostics)
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
classify(netId, pins, rails, diagnostics) {
|
|
872
|
-
const drivers = pins.filter((pin) => pin.role === "driver");
|
|
873
|
-
const loads = pins.filter((pin) => pin.role === "load");
|
|
874
|
-
const sinks = pins.filter((pin) => pin.senses);
|
|
875
|
-
const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];
|
|
876
|
-
const levels = new Set(rails.map((rail) => rail.level));
|
|
877
|
-
if (rails.length > 1 && levels.size > 1) diagnostics.push(diagnostic("rail-conflict", "error", `Net ${netId} ties rails ${rails.map((rail) => rail.name).join(" and ")} with opposite levels`, netId, endpoints));
|
|
878
|
-
if (drivers.length > 1) {
|
|
879
|
-
const names = drivers.map((driver) => driver.endpoint).join(", ");
|
|
880
|
-
diagnostics.push(diagnostic("driver-conflict", this.allowMultiDriver ? "warning" : "error", this.allowMultiDriver ? `Net ${netId} has ${drivers.length} drivers (${names}); solving them as a wired-OR` : `Net ${netId} has ${drivers.length} drivers (${names}); v1 supports one driver per net (set allowMultiDriver to solve them as a wired-OR)`, netId, endpoints));
|
|
881
|
-
}
|
|
882
|
-
if (drivers.length > 0 && rails.length > 0) diagnostics.push(diagnostic("power-short", "error", `Net ${netId} shorts rail ${rails[0]?.name ?? "?"} against driver ${drivers[0]?.endpoint ?? "?"}`, netId, endpoints));
|
|
883
|
-
if (drivers.length === 0 && rails.length === 0) diagnostics.push(diagnostic("floating-net", "warning", `Net ${netId} has no driver and no rail; its loads read a constant low`, netId, endpoints));
|
|
884
|
-
const source = drivers.length > 0 ? "driver" : rails.length > 0 ? "rail" : "floating";
|
|
885
|
-
const level = rails[0]?.level ?? false;
|
|
886
|
-
return Object.freeze({
|
|
887
|
-
netId,
|
|
888
|
-
pins: Object.freeze([...pins]),
|
|
889
|
-
rails: Object.freeze([...rails]),
|
|
890
|
-
drivers: Object.freeze(drivers),
|
|
891
|
-
loads: Object.freeze(loads),
|
|
892
|
-
sinks: Object.freeze(sinks),
|
|
893
|
-
source,
|
|
894
|
-
level
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
resolveEndpoint(raw, pins, railNodeIds, index) {
|
|
898
|
-
if (typeof raw !== "string" || raw.length === 0) throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] endpoint must be a non-empty "device.pin" string or a rail name`);
|
|
899
|
-
const railLevel = this.rails.get(raw);
|
|
900
|
-
if (railLevel !== void 0) {
|
|
901
|
-
let nodeId = railNodeIds.get(raw);
|
|
902
|
-
if (nodeId === void 0) {
|
|
903
|
-
nodeId = pins.totalPins + railNodeIds.size;
|
|
904
|
-
railNodeIds.set(raw, nodeId);
|
|
905
|
-
}
|
|
906
|
-
return {
|
|
907
|
-
kind: "rail",
|
|
908
|
-
nodeId,
|
|
909
|
-
name: raw,
|
|
910
|
-
level: railLevel
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
const dot = raw.indexOf(".");
|
|
914
|
-
if (dot <= 0 || dot === raw.length - 1) throw new UnifiedIRCompilerError("invalid-connection", `Connection endpoint "${raw}" must be "device.pin" or a known rail (${[...this.rails.keys()].join(", ")})`);
|
|
915
|
-
const deviceId = raw.slice(0, dot);
|
|
916
|
-
const pinName = raw.slice(dot + 1);
|
|
917
|
-
const allocation = pins.devices.get(deviceId);
|
|
918
|
-
if (allocation === void 0) throw new UnifiedIRCompilerError("unknown-device", `Connection endpoint "${raw}" references unknown device "${deviceId}". Available: [${[...pins.devices.keys()].join(", ")}]`, { deviceId });
|
|
919
|
-
const pin = allocation.resolved.get(pinName);
|
|
920
|
-
if (pin === void 0) throw new UnifiedIRCompilerError("pin-not-found", `Pin '${raw}' not found. Available: [${[...allocation.resolved.keys()].map((name) => `${deviceId}.${name}`).join(", ")}]`, {
|
|
921
|
-
deviceId,
|
|
922
|
-
pinName
|
|
923
|
-
});
|
|
924
|
-
return {
|
|
925
|
-
kind: "pin",
|
|
926
|
-
nodeId: pin.globalPinId,
|
|
927
|
-
pin
|
|
928
|
-
};
|
|
929
|
-
}
|
|
930
|
-
};
|
|
931
|
-
/**
|
|
932
|
-
* Throws the first error diagnostic of a netlist, or returns it unchanged.
|
|
933
|
-
*
|
|
934
|
-
* @throws {UnifiedIRCompilerError} carrying every diagnostic for inspection.
|
|
935
|
-
*/
|
|
936
|
-
function assertNoElectricalErrors(netlist) {
|
|
937
|
-
const first = netlist.diagnostics.filter((entry) => entry.severity === "error")[0];
|
|
938
|
-
if (first === void 0) return netlist;
|
|
939
|
-
throw new UnifiedIRCompilerError(mapErrorCode(first.code), first.message, {
|
|
940
|
-
...first.netId === void 0 ? {} : { netId: first.netId },
|
|
941
|
-
diagnostics: netlist.diagnostics
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
function mapErrorCode(code) {
|
|
945
|
-
if (code === "driver-conflict") return "driver-conflict";
|
|
946
|
-
if (code === "rail-conflict") return "rail-conflict";
|
|
947
|
-
return "power-short";
|
|
948
|
-
}
|
|
949
|
-
function diagnostic(code, severity, message, netId, endpoints) {
|
|
950
|
-
return Object.freeze({
|
|
951
|
-
code,
|
|
952
|
-
severity,
|
|
953
|
-
message,
|
|
954
|
-
netId,
|
|
955
|
-
endpoints: Object.freeze([...endpoints])
|
|
956
|
-
});
|
|
957
|
-
}
|
|
958
|
-
function toConnection(pin) {
|
|
959
|
-
return Object.freeze({
|
|
960
|
-
endpoint: `${pin.deviceId}.${pin.name}`,
|
|
961
|
-
deviceId: pin.deviceId,
|
|
962
|
-
pinName: pin.name,
|
|
963
|
-
globalPinId: pin.globalPinId,
|
|
964
|
-
role: pin.role,
|
|
965
|
-
senses: pin.senses
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
/** Union-find over pin ids and rail node ids. */
|
|
969
|
-
var DisjointSet = class {
|
|
970
|
-
parent = /* @__PURE__ */ new Map();
|
|
971
|
-
rank = /* @__PURE__ */ new Map();
|
|
972
|
-
find(id) {
|
|
973
|
-
const parent = this.parent.get(id);
|
|
974
|
-
if (parent === void 0) {
|
|
975
|
-
this.parent.set(id, id);
|
|
976
|
-
this.rank.set(id, 0);
|
|
977
|
-
return id;
|
|
978
|
-
}
|
|
979
|
-
if (parent === id) return id;
|
|
980
|
-
const root = this.find(parent);
|
|
981
|
-
this.parent.set(id, root);
|
|
982
|
-
return root;
|
|
983
|
-
}
|
|
984
|
-
union(left, right) {
|
|
985
|
-
const leftRoot = this.find(left);
|
|
986
|
-
const rightRoot = this.find(right);
|
|
987
|
-
if (leftRoot === rightRoot) return;
|
|
988
|
-
const leftRank = this.rank.get(leftRoot) ?? 0;
|
|
989
|
-
const rightRank = this.rank.get(rightRoot) ?? 0;
|
|
990
|
-
if (leftRank < rightRank) {
|
|
991
|
-
this.parent.set(leftRoot, rightRoot);
|
|
992
|
-
return;
|
|
993
|
-
}
|
|
994
|
-
this.parent.set(rightRoot, leftRoot);
|
|
995
|
-
if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);
|
|
996
|
-
}
|
|
997
|
-
};
|
|
998
|
-
//#endregion
|
|
999
2455
|
//#region src/unified-ir/compiler/index.ts
|
|
1000
2456
|
/**
|
|
1001
2457
|
* Compiles several devices and their wiring into one unified IR module (U01).
|
|
@@ -1022,40 +2478,34 @@ var DisjointSet = class {
|
|
|
1022
2478
|
*
|
|
1023
2479
|
* The pipeline is: validate the input, allocate the global pin and state
|
|
1024
2480
|
* spaces, analyse the electrical topology, generate one function per device
|
|
1025
|
-
* phase, generate
|
|
2481
|
+
* phase, generate the resistive network solver and main loop, then validate the
|
|
1026
2482
|
* resulting module with `validateIR`.
|
|
1027
2483
|
*
|
|
1028
2484
|
* @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
|
|
1029
2485
|
* pins, electrical conflicts, or when the generated module fails validation.
|
|
1030
2486
|
*/
|
|
1031
2487
|
function compileCircuit(input, options = {}) {
|
|
1032
|
-
const
|
|
2488
|
+
const validated = validateInput(input);
|
|
2489
|
+
const { connections } = validated;
|
|
1033
2490
|
const resolvedOptions = validateOptions(options);
|
|
1034
2491
|
const names = resolveEntryNames(resolvedOptions);
|
|
1035
2492
|
const module = createIRModule();
|
|
1036
|
-
const allocation = new GlobalResourceAllocator(module).allocate(devices);
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
...resolvedOptions.allowMultiDriver === void 0 ? {} : { allowMultiDriver: resolvedOptions.allowMultiDriver }
|
|
1040
|
-
}).analyze(connections, allocation.pins);
|
|
1041
|
-
assertNoElectricalErrors(netlist);
|
|
2493
|
+
const allocation = new GlobalResourceAllocator(module).allocate(validated.devices);
|
|
2494
|
+
const electrical = prepareElectricalCompilation(module, validated.devices, connections, resolvedOptions);
|
|
2495
|
+
const devices = electrical.devices;
|
|
1042
2496
|
const generator = new DeviceIRGenerator({
|
|
1043
2497
|
module,
|
|
1044
|
-
memory: allocation.memory,
|
|
1045
2498
|
pins: allocation.pins,
|
|
1046
|
-
states: allocation.states
|
|
2499
|
+
states: allocation.states,
|
|
2500
|
+
electrical: electrical.operations
|
|
1047
2501
|
});
|
|
1048
2502
|
const generated = devices.map((device) => generator.generate(device));
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
memory: allocation.memory
|
|
1052
|
-
}).generate(netlist);
|
|
1053
|
-
assertNoNameCollisions(devices, solvers.map((solver) => solver.name), names);
|
|
1054
|
-
const loop = new MainLoopGenerator(module).generate(generated.map((device) => device.entry), solvers, netlist, names);
|
|
2503
|
+
assertNoNameCollisions(devices, names);
|
|
2504
|
+
const loop = new MainLoopGenerator(module, electrical.operations).generate(generated.map((device) => device.entry), names);
|
|
1055
2505
|
const validation = createModuleValidation(module, devices.flatMap((device) => device.description.updateResources ?? []));
|
|
1056
2506
|
if (resolvedOptions.validate !== false) validateModule(module, validation);
|
|
1057
2507
|
const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));
|
|
1058
|
-
|
|
2508
|
+
const compiled = Object.freeze({
|
|
1059
2509
|
module,
|
|
1060
2510
|
entryPoints: Object.freeze({
|
|
1061
2511
|
tick: loop.names.tick,
|
|
@@ -1067,16 +2517,17 @@ function compileCircuit(input, options = {}) {
|
|
|
1067
2517
|
batch: loop.batch
|
|
1068
2518
|
})
|
|
1069
2519
|
}),
|
|
2520
|
+
progress: loop.progress,
|
|
1070
2521
|
pinMap: allocation.pins.pins,
|
|
1071
2522
|
deviceMap,
|
|
1072
|
-
netlist,
|
|
1073
2523
|
pins: allocation.pins,
|
|
1074
2524
|
states: allocation.states,
|
|
1075
|
-
memory: allocation.memory,
|
|
1076
2525
|
validation,
|
|
1077
2526
|
executionOrder: loop.order,
|
|
1078
2527
|
functions: Object.freeze(module.functions.map((fn) => fn.name))
|
|
1079
2528
|
});
|
|
2529
|
+
retainElectricalCompilation(compiled, electrical);
|
|
2530
|
+
return compiled;
|
|
1080
2531
|
}
|
|
1081
2532
|
function validateInput(input) {
|
|
1082
2533
|
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput must be an object with devices and connections");
|
|
@@ -1092,11 +2543,6 @@ function validateOptions(options) {
|
|
|
1092
2543
|
if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
|
|
1093
2544
|
const resolved = options;
|
|
1094
2545
|
if (resolved.validate !== void 0 && typeof resolved.validate !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.validate must be a boolean");
|
|
1095
|
-
if (resolved.allowMultiDriver !== void 0 && typeof resolved.allowMultiDriver !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.allowMultiDriver must be a boolean");
|
|
1096
|
-
if (resolved.rails !== void 0) {
|
|
1097
|
-
if (resolved.rails === null || typeof resolved.rails !== "object" || Array.isArray(resolved.rails)) throw new UnifiedIRCompilerError("invalid-input", "options.rails must be a plain object");
|
|
1098
|
-
for (const [name, level] of Object.entries(resolved.rails)) if (name.length === 0 || typeof level !== "boolean") throw new UnifiedIRCompilerError("invalid-input", `options.rails["${name}"] must be a boolean`);
|
|
1099
|
-
}
|
|
1100
2546
|
return resolved;
|
|
1101
2547
|
}
|
|
1102
2548
|
function resolveEntryNames(options) {
|
|
@@ -1109,12 +2555,11 @@ function resolveEntryNames(options) {
|
|
|
1109
2555
|
if (new Set(Object.values(names)).size !== 3) throw new UnifiedIRCompilerError("invalid-input", `Entry point names must be distinct: ${JSON.stringify(names)}`);
|
|
1110
2556
|
return Object.freeze(names);
|
|
1111
2557
|
}
|
|
1112
|
-
function assertNoNameCollisions(devices,
|
|
2558
|
+
function assertNoNameCollisions(devices, names) {
|
|
1113
2559
|
const reserved = /* @__PURE__ */ new Set([
|
|
1114
2560
|
names.tick,
|
|
1115
2561
|
names.initialize,
|
|
1116
|
-
names.batch
|
|
1117
|
-
...solverNames
|
|
2562
|
+
names.batch
|
|
1118
2563
|
]);
|
|
1119
2564
|
for (const device of devices) for (const phase of [
|
|
1120
2565
|
"initialize",
|
|
@@ -1155,6 +2600,8 @@ var CircuitError = class extends Error {
|
|
|
1155
2600
|
};
|
|
1156
2601
|
//#endregion
|
|
1157
2602
|
//#region src/unified-ir/runtime/accessors.ts
|
|
2603
|
+
var bridges = /* @__PURE__ */ new WeakMap();
|
|
2604
|
+
var deviceBridgeOf = (accessor) => bridges.get(accessor) ?? accessor;
|
|
1158
2605
|
/**
|
|
1159
2606
|
* Builds one accessor per compiled device.
|
|
1160
2607
|
*
|
|
@@ -1166,22 +2613,26 @@ function buildDeviceAccessors(context) {
|
|
|
1166
2613
|
const entries = [];
|
|
1167
2614
|
for (const device of context.compiled.deviceMap.values()) {
|
|
1168
2615
|
const base = createBaseAccessor(context, device);
|
|
1169
|
-
if (device.accessor !== void 0)
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
2616
|
+
if (device.accessor !== void 0) {
|
|
2617
|
+
const custom = device.accessor({
|
|
2618
|
+
deviceId: device.deviceId,
|
|
2619
|
+
storage: context.jit.storage,
|
|
2620
|
+
assertActive: context.assertActive,
|
|
2621
|
+
step: context.step,
|
|
2622
|
+
runBatch: context.runBatch
|
|
2623
|
+
});
|
|
2624
|
+
bridges.set(custom, base);
|
|
2625
|
+
entries.push([device.deviceId, custom]);
|
|
2626
|
+
} else entries.push([device.deviceId, base]);
|
|
1177
2627
|
}
|
|
1178
2628
|
return Object.freeze(Object.fromEntries(entries));
|
|
1179
2629
|
}
|
|
1180
2630
|
function createBaseAccessor(context, device) {
|
|
1181
2631
|
const { jit } = context;
|
|
1182
2632
|
const storage = jit.storage;
|
|
1183
|
-
const
|
|
2633
|
+
const electrical = electricalCompilationOf(context.compiled);
|
|
1184
2634
|
const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;
|
|
2635
|
+
const entries = new Set(device.entries);
|
|
1185
2636
|
const accessor = {
|
|
1186
2637
|
deviceId: device.deviceId,
|
|
1187
2638
|
type: device.type,
|
|
@@ -1189,18 +2640,8 @@ function createBaseAccessor(context, device) {
|
|
|
1189
2640
|
stateNames: Object.freeze([...device.states.keys()]),
|
|
1190
2641
|
readPin(pinName) {
|
|
1191
2642
|
context.assertActive();
|
|
1192
|
-
|
|
1193
|
-
return storage.loadArray(
|
|
1194
|
-
},
|
|
1195
|
-
writePin(pinName, value) {
|
|
1196
|
-
context.assertActive();
|
|
1197
|
-
const pin = pinOf(device, resolved, pinName);
|
|
1198
|
-
if (pin.role !== "driver") throw new CircuitError("pin-not-writable", `Pin "${device.deviceId}.${pinName}" has role "${pin.role}"; only driver pins can be written. Use Circuit.setPin to override a sensed level`, {
|
|
1199
|
-
deviceId: device.deviceId,
|
|
1200
|
-
pinName
|
|
1201
|
-
});
|
|
1202
|
-
assertBoolean(device.deviceId, pinName, value);
|
|
1203
|
-
storage.storeArray(memory.output, pin.globalPinId, value);
|
|
2643
|
+
pinOf(device, resolved, pinName);
|
|
2644
|
+
return storage.loadArray(electrical.operations.digitalIntent, electrical.operations.pinIndices.get(`${device.deviceId}.${pinName}`)) === true;
|
|
1204
2645
|
},
|
|
1205
2646
|
getState(name) {
|
|
1206
2647
|
context.assertActive();
|
|
@@ -1220,7 +2661,71 @@ function createBaseAccessor(context, device) {
|
|
|
1220
2661
|
cause
|
|
1221
2662
|
});
|
|
1222
2663
|
}
|
|
1223
|
-
}
|
|
2664
|
+
},
|
|
2665
|
+
...device.applyInputs === void 0 ? {} : { applyInputs(inputs) {
|
|
2666
|
+
context.assertActive();
|
|
2667
|
+
const pending = /* @__PURE__ */ new Map();
|
|
2668
|
+
for (const input of inputs) {
|
|
2669
|
+
const values = pending.get(input.port) ?? [];
|
|
2670
|
+
values.push(input.payload);
|
|
2671
|
+
pending.set(input.port, values);
|
|
2672
|
+
}
|
|
2673
|
+
let open = true;
|
|
2674
|
+
const active = () => {
|
|
2675
|
+
context.assertActive();
|
|
2676
|
+
if (!open) throw new TypeError("Input IO is only valid during applyInputs");
|
|
2677
|
+
};
|
|
2678
|
+
try {
|
|
2679
|
+
device.applyInputs({
|
|
2680
|
+
takeInput(port) {
|
|
2681
|
+
active();
|
|
2682
|
+
const values = pending.get(port);
|
|
2683
|
+
pending.delete(port);
|
|
2684
|
+
return values?.at(-1);
|
|
2685
|
+
},
|
|
2686
|
+
takeInputs(port) {
|
|
2687
|
+
active();
|
|
2688
|
+
const values = pending.get(port) ?? [];
|
|
2689
|
+
pending.delete(port);
|
|
2690
|
+
return Object.freeze(values);
|
|
2691
|
+
},
|
|
2692
|
+
writeState(name, value) {
|
|
2693
|
+
active();
|
|
2694
|
+
accessor.setState(name, value);
|
|
2695
|
+
},
|
|
2696
|
+
call(entry, args) {
|
|
2697
|
+
active();
|
|
2698
|
+
if (!entries.has(entry)) throw new TypeError("Input entry must belong to this device");
|
|
2699
|
+
context.execute(entry, args);
|
|
2700
|
+
}
|
|
2701
|
+
});
|
|
2702
|
+
} finally {
|
|
2703
|
+
open = false;
|
|
2704
|
+
}
|
|
2705
|
+
} },
|
|
2706
|
+
...device.flushOutputs === void 0 ? {} : { flushOutputs(publish) {
|
|
2707
|
+
context.assertActive();
|
|
2708
|
+
let open = true;
|
|
2709
|
+
const active = () => {
|
|
2710
|
+
context.assertActive();
|
|
2711
|
+
if (!open) throw new TypeError("Output IO is only valid during flushOutputs");
|
|
2712
|
+
};
|
|
2713
|
+
try {
|
|
2714
|
+
device.flushOutputs({
|
|
2715
|
+
readState(name) {
|
|
2716
|
+
active();
|
|
2717
|
+
const value = accessor.getState(name);
|
|
2718
|
+
return typeof value === "object" && value !== null && "bits" in value ? toNumber(value) : value;
|
|
2719
|
+
},
|
|
2720
|
+
publish(port, payload) {
|
|
2721
|
+
active();
|
|
2722
|
+
publish(port, payload);
|
|
2723
|
+
}
|
|
2724
|
+
});
|
|
2725
|
+
} finally {
|
|
2726
|
+
open = false;
|
|
2727
|
+
}
|
|
2728
|
+
} }
|
|
1224
2729
|
};
|
|
1225
2730
|
return Object.freeze(accessor);
|
|
1226
2731
|
}
|
|
@@ -1242,12 +2747,6 @@ function stateOf(device, name) {
|
|
|
1242
2747
|
});
|
|
1243
2748
|
return slot;
|
|
1244
2749
|
}
|
|
1245
|
-
function assertBoolean(deviceId, pinName, value) {
|
|
1246
|
-
if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${deviceId}.${pinName}" needs a boolean level, received ${typeof value}`, {
|
|
1247
|
-
deviceId,
|
|
1248
|
-
pinName
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
2750
|
/**
|
|
1252
2751
|
* Validates a host-written state value against the declared scalar type.
|
|
1253
2752
|
* Range checks stay in storage, which owns the encoding.
|
|
@@ -1310,7 +2809,6 @@ var DEFAULT_INSTANCE_ID = "unified-circuit";
|
|
|
1310
2809
|
* expect(circuit.tickCount).toBe(1_000_000n);
|
|
1311
2810
|
*
|
|
1312
2811
|
* circuit.reset();
|
|
1313
|
-
* circuit.setPin('drive1.PA0', true); // host drives the pin
|
|
1314
2812
|
* circuit.step();
|
|
1315
2813
|
* expect(circuit.devices.sink1.getState('lamp')).toBe(true);
|
|
1316
2814
|
* ```
|
|
@@ -1361,6 +2859,9 @@ var Circuit = class Circuit {
|
|
|
1361
2859
|
const circuit = new Circuit(compiled, jit, resolved.instanceId, buildDeviceAccessors({
|
|
1362
2860
|
compiled,
|
|
1363
2861
|
jit,
|
|
2862
|
+
execute: (entry, args) => {
|
|
2863
|
+
jit.execute(entry, args, circuit.#context);
|
|
2864
|
+
},
|
|
1364
2865
|
assertActive: () => {
|
|
1365
2866
|
circuit.#assertActive();
|
|
1366
2867
|
},
|
|
@@ -1378,29 +2879,38 @@ var Circuit = class Circuit {
|
|
|
1378
2879
|
/**
|
|
1379
2880
|
* Runs `count` ticks inside one generated loop — the throughput path.
|
|
1380
2881
|
*
|
|
1381
|
-
* The whole batch is one engine call
|
|
1382
|
-
*
|
|
2882
|
+
* The whole batch is one engine call. The clock advances by completed ticks,
|
|
2883
|
+
* including the completed prefix of a failed batch.
|
|
1383
2884
|
*
|
|
1384
2885
|
* @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
|
|
1385
2886
|
*/
|
|
1386
|
-
runBatch(count) {
|
|
2887
|
+
runBatch(count, dt = 1) {
|
|
1387
2888
|
this.#assertActive();
|
|
1388
2889
|
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_BATCH_TICKS) throw new CircuitError("invalid-count", `runBatch(count) needs an integer in [0, ${MAX_BATCH_TICKS}], received ${String(count)}`);
|
|
2890
|
+
this.#setTimeStep(dt);
|
|
1389
2891
|
if (count === 0) return;
|
|
1390
2892
|
this.#context.virtualTime = this.#virtualTime;
|
|
1391
|
-
this.#jit.
|
|
1392
|
-
|
|
2893
|
+
this.#jit.storage.storeState(this.#compiled.progress, 0);
|
|
2894
|
+
try {
|
|
2895
|
+
this.#jit.execute(this.#compiled.entryPoints.refs.batch, [count], this.#context);
|
|
2896
|
+
} finally {
|
|
2897
|
+
this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);
|
|
2898
|
+
}
|
|
1393
2899
|
}
|
|
1394
2900
|
/**
|
|
1395
2901
|
* Advances exactly one tick — the debugging path.
|
|
1396
2902
|
*
|
|
1397
2903
|
* Every call is one engine entry, so prefer `runBatch` for throughput.
|
|
1398
2904
|
*/
|
|
1399
|
-
step() {
|
|
2905
|
+
step(dt = 1) {
|
|
1400
2906
|
this.#assertActive();
|
|
2907
|
+
this.#setTimeStep(dt);
|
|
1401
2908
|
this.#context.virtualTime = this.#virtualTime;
|
|
1402
|
-
|
|
1403
|
-
|
|
2909
|
+
try {
|
|
2910
|
+
this.#jit.execute(this.#compiled.entryPoints.refs.tick, NO_ARGS, this.#context);
|
|
2911
|
+
} finally {
|
|
2912
|
+
this.#advance(this.#jit.storage.loadState(this.#compiled.progress), dt);
|
|
2913
|
+
}
|
|
1404
2914
|
}
|
|
1405
2915
|
/**
|
|
1406
2916
|
* Restores every memory to its declared initial value, re-runs `initialize`
|
|
@@ -1436,34 +2946,133 @@ var Circuit = class Circuit {
|
|
|
1436
2946
|
/**
|
|
1437
2947
|
* Reads the level one pin observes.
|
|
1438
2948
|
*
|
|
1439
|
-
*
|
|
1440
|
-
*
|
|
1441
|
-
* `false` unless it is configured push-pull.
|
|
2949
|
+
* Requires an explicitly initialized digital input capability and applies
|
|
2950
|
+
* the circuit interpretation to the solved physical voltage.
|
|
1442
2951
|
*
|
|
1443
2952
|
* @throws {CircuitError} with code `pin-not-found`.
|
|
1444
2953
|
*/
|
|
1445
2954
|
getPin(pinName) {
|
|
1446
2955
|
this.#assertActive();
|
|
1447
|
-
|
|
2956
|
+
this.#pinRuntime(pinName);
|
|
1448
2957
|
const storage = this.#jit.storage;
|
|
1449
|
-
|
|
1450
|
-
|
|
2958
|
+
const electrical = this.#ensureElectrical();
|
|
2959
|
+
{
|
|
2960
|
+
const dot = pinName.indexOf(".");
|
|
2961
|
+
if (electrical.allocation.pins.get(pinName.slice(0, dot))?.get(pinName.slice(dot + 1))?.input === void 0) throw new CircuitError("unsupported-operation", `Pin "${pinName}" has no digital input capability`);
|
|
2962
|
+
this.#ensureElectrical();
|
|
2963
|
+
return storage.loadArray(electrical.operations.digitalSample, electrical.operations.pinIndices.get(pinName)) === true;
|
|
2964
|
+
}
|
|
1451
2965
|
}
|
|
1452
|
-
/**
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
2966
|
+
/** Physical pin voltage; floating results never contain a synthetic voltage. */
|
|
2967
|
+
getVoltage(pinName) {
|
|
2968
|
+
this.#assertActive();
|
|
2969
|
+
this.#pinRuntime(pinName);
|
|
2970
|
+
const electrical = this.#ensureElectrical();
|
|
2971
|
+
const dot = pinName.indexOf(".");
|
|
2972
|
+
const pin = electrical.allocation.pins.get(pinName.slice(0, dot)).get(pinName.slice(dot + 1));
|
|
2973
|
+
return this.#electricalReading(electrical.operations.solver.voltage, electrical.operations.solver.voltageState, pin.node);
|
|
2974
|
+
}
|
|
2975
|
+
/** Resistor/contact currents follow endpoint order; source and pin contributions flow outward. */
|
|
2976
|
+
getCurrent(resource) {
|
|
2977
|
+
this.#assertActive();
|
|
2978
|
+
const { allocation, operations: { solver } } = this.#ensureElectrical();
|
|
2979
|
+
const missing = () => {
|
|
2980
|
+
throw new CircuitError("resource-not-found", `Unknown electrical current resource ${JSON.stringify(resource)}`);
|
|
2981
|
+
};
|
|
2982
|
+
let target;
|
|
2983
|
+
if (typeof resource === "string") {
|
|
2984
|
+
const dot = resource.indexOf(".");
|
|
2985
|
+
if (dot <= 0) throw new CircuitError("resource-not-found", `Unknown resistor "${resource}"`);
|
|
2986
|
+
target = {
|
|
2987
|
+
kind: "resistor",
|
|
2988
|
+
device: resource.slice(0, dot),
|
|
2989
|
+
name: resource.slice(dot + 1)
|
|
2990
|
+
};
|
|
2991
|
+
} else if (resource !== null && typeof resource === "object") target = resource;
|
|
2992
|
+
else return missing();
|
|
2993
|
+
if (target.kind === "resistor" || target.kind === "contact") {
|
|
2994
|
+
const contact = target.kind === "contact";
|
|
2995
|
+
const index = (contact ? allocation.contacts : allocation.resistors).get(target.device)?.get(target.name);
|
|
2996
|
+
if (index === void 0) {
|
|
2997
|
+
if (typeof resource === "string") throw new CircuitError("resource-not-found", `Unknown resistor "${resource}"`);
|
|
2998
|
+
return missing();
|
|
2999
|
+
}
|
|
3000
|
+
return this.#electricalReading(contact ? solver.contactCurrent : solver.current, contact ? solver.contactCurrentState : solver.currentState, index);
|
|
3001
|
+
}
|
|
3002
|
+
if (target.kind === "source") {
|
|
3003
|
+
const index = allocation.sources.get(target.name);
|
|
3004
|
+
if (index === void 0) return missing();
|
|
3005
|
+
return this.#electricalReading(solver.sourceCurrent, solver.sourceCurrentState, index);
|
|
3006
|
+
}
|
|
3007
|
+
if (target.kind !== "drive" && target.kind !== "pull-up" && target.kind !== "pull-down") return missing();
|
|
3008
|
+
const pin = allocation.pins.get(target.device)?.get(target.pin);
|
|
3009
|
+
if (pin === void 0) return missing();
|
|
3010
|
+
const branches = target.kind === "drive" ? pin.drive === void 0 ? void 0 : [
|
|
3011
|
+
pin.drive.high,
|
|
3012
|
+
pin.drive.low,
|
|
3013
|
+
...pin.drive.analog === void 0 ? [] : [pin.drive.analog.resistor]
|
|
3014
|
+
] : pin.bias === void 0 ? void 0 : [target.kind === "pull-up" ? pin.bias.up : pin.bias.down];
|
|
3015
|
+
if (branches === void 0) return missing();
|
|
3016
|
+
let value = 0;
|
|
3017
|
+
for (const index of branches) {
|
|
3018
|
+
const current = this.#electricalReading(solver.current, solver.currentState, index);
|
|
3019
|
+
if (current.state !== "determinate") return current;
|
|
3020
|
+
value -= current.value;
|
|
3021
|
+
}
|
|
3022
|
+
return {
|
|
3023
|
+
state: "determinate",
|
|
3024
|
+
value
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
/** Pull-based active diagnostics: one warning per resource; successful recovery removes it. */
|
|
3028
|
+
getDiagnostics() {
|
|
1462
3029
|
this.#assertActive();
|
|
1463
|
-
const
|
|
1464
|
-
|
|
1465
|
-
const
|
|
1466
|
-
|
|
3030
|
+
const { allocation, operations: { solver } } = this.#ensureElectrical();
|
|
3031
|
+
const diagnostics = [];
|
|
3032
|
+
const check = (target, limit) => {
|
|
3033
|
+
if (limit === void 0) return;
|
|
3034
|
+
const current = this.getCurrent(target);
|
|
3035
|
+
if (current.state === "determinate" && Math.abs(current.value) > limit) diagnostics.push(Object.freeze({
|
|
3036
|
+
code: "electrical/overcurrent",
|
|
3037
|
+
severity: "warning",
|
|
3038
|
+
target: Object.freeze(target),
|
|
3039
|
+
current: current.value,
|
|
3040
|
+
maxAbsCurrent: limit
|
|
3041
|
+
}));
|
|
3042
|
+
};
|
|
3043
|
+
for (const [device, resistors] of allocation.resistors) for (const [name, index] of resistors) check({
|
|
3044
|
+
kind: "resistor",
|
|
3045
|
+
device,
|
|
3046
|
+
name
|
|
3047
|
+
}, allocation.currentLimits.get(index));
|
|
3048
|
+
for (const [device, pins] of allocation.pins) for (const [pin, description] of pins) check({
|
|
3049
|
+
kind: "drive",
|
|
3050
|
+
device,
|
|
3051
|
+
pin
|
|
3052
|
+
}, description.drive?.maxAbsCurrent);
|
|
3053
|
+
const fault = this.#jit.storage.loadState(solver.fault);
|
|
3054
|
+
if (fault !== 0) diagnostics.push(Object.freeze({
|
|
3055
|
+
code: fault === 1 ? "electrical/invalid-parameter" : fault === 2 ? "electrical/source-conflict" : "electrical/numerical-failure",
|
|
3056
|
+
severity: "error",
|
|
3057
|
+
...electricalFaultContext(allocation, solver, this.#jit.storage)
|
|
3058
|
+
}));
|
|
3059
|
+
return Object.freeze(diagnostics);
|
|
3060
|
+
}
|
|
3061
|
+
#ensureElectrical() {
|
|
3062
|
+
const electrical = electricalCompilationOf(this.#compiled);
|
|
3063
|
+
if (electrical === void 0) throw new CircuitError("unsupported-operation", "This circuit has no resistive electrical model");
|
|
3064
|
+
this.#context.virtualTime = this.#virtualTime;
|
|
3065
|
+
this.#jit.execute(electrical.operations.ensure, NO_ARGS, this.#context);
|
|
3066
|
+
return electrical;
|
|
3067
|
+
}
|
|
3068
|
+
#electricalReading(values, states, index) {
|
|
3069
|
+
const state = this.#jit.storage.loadArray(states, index);
|
|
3070
|
+
if (state === 1) return { state: "floating" };
|
|
3071
|
+
if (state === 2) return { state: "indeterminate" };
|
|
3072
|
+
return {
|
|
3073
|
+
state: "determinate",
|
|
3074
|
+
value: toNumber(this.#jit.storage.loadArray(values, index))
|
|
3075
|
+
};
|
|
1467
3076
|
}
|
|
1468
3077
|
/** Number of ticks completed since creation or the last `reset()`. */
|
|
1469
3078
|
get tickCount() {
|
|
@@ -1497,10 +3106,19 @@ var Circuit = class Circuit {
|
|
|
1497
3106
|
#assertActive() {
|
|
1498
3107
|
if (this.#disposed) throw new CircuitError("disposed", "Circuit has been disposed; create a new circuit to keep simulating");
|
|
1499
3108
|
}
|
|
1500
|
-
#
|
|
3109
|
+
#setTimeStep(dt) {
|
|
3110
|
+
if (!Number.isSafeInteger(dt) || dt <= 0) throw new CircuitError("invalid-options", "Tick duration must be a positive safe integer in picoseconds");
|
|
3111
|
+
const electrical = electricalCompilationOf(this.#compiled);
|
|
3112
|
+
if (electrical !== void 0) {
|
|
3113
|
+
this.#jit.storage.storeArray(electrical.operations.timeStep, 0, dt >>> 0);
|
|
3114
|
+
this.#jit.storage.storeArray(electrical.operations.timeStep, 1, Math.floor(dt / 4294967296));
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
#advance(count, dt) {
|
|
1501
3118
|
this.#tickCount += BigInt(count);
|
|
1502
|
-
const
|
|
1503
|
-
|
|
3119
|
+
const elapsed = count * dt;
|
|
3120
|
+
const next = this.#virtualTime + elapsed;
|
|
3121
|
+
this.#virtualTime = Number.isSafeInteger(next) ? next : Number((BigInt(this.#virtualTime) + BigInt(count) * BigInt(dt)) % (BigInt(MAX_VIRTUAL_TIME) + 1n));
|
|
1504
3122
|
}
|
|
1505
3123
|
#pinRuntime(pinName) {
|
|
1506
3124
|
const pin = this.#pins.get(pinName);
|
|
@@ -1511,11 +3129,7 @@ var Circuit = class Circuit {
|
|
|
1511
3129
|
/** Resolves every pin of the global address space into its runtime view. */
|
|
1512
3130
|
function pinRuntimeOf(compiled) {
|
|
1513
3131
|
const pins = /* @__PURE__ */ new Map();
|
|
1514
|
-
for (const [deviceId, allocation] of compiled.pins.devices) for (const [pinName, pin] of allocation.resolved) pins.set(`${deviceId}.${pinName}`, Object.freeze({
|
|
1515
|
-
globalPinId: pin.globalPinId,
|
|
1516
|
-
role: pin.role,
|
|
1517
|
-
senses: pin.senses
|
|
1518
|
-
}));
|
|
3132
|
+
for (const [deviceId, allocation] of compiled.pins.devices) for (const [pinName, pin] of allocation.resolved) pins.set(`${deviceId}.${pinName}`, Object.freeze({ globalPinId: pin.globalPinId }));
|
|
1519
3133
|
return pins;
|
|
1520
3134
|
}
|
|
1521
3135
|
/**
|
|
@@ -1565,8 +3179,9 @@ function createEngine(compiled, options) {
|
|
|
1565
3179
|
function compileOptionsOf(options) {
|
|
1566
3180
|
return {
|
|
1567
3181
|
validate: options.validateIR,
|
|
1568
|
-
|
|
1569
|
-
...options.
|
|
3182
|
+
...options.sources === void 0 ? {} : { sources: options.sources },
|
|
3183
|
+
...options.interpretation === void 0 ? {} : { interpretation: options.interpretation },
|
|
3184
|
+
...options.floatingSeed === void 0 ? {} : { floatingSeed: options.floatingSeed }
|
|
1570
3185
|
};
|
|
1571
3186
|
}
|
|
1572
3187
|
function resolveOptions(options) {
|
|
@@ -1579,23 +3194,18 @@ function resolveOptions(options) {
|
|
|
1579
3194
|
if (candidate.jit !== void 0) {
|
|
1580
3195
|
if (candidate.jit === null || typeof candidate.jit !== "object" || Array.isArray(candidate.jit)) throw new CircuitError("invalid-options", "jit must be a JIT tuning object");
|
|
1581
3196
|
}
|
|
1582
|
-
let allowMultiDriver = false;
|
|
1583
|
-
let rails;
|
|
1584
3197
|
if (candidate.electrical !== void 0) {
|
|
1585
3198
|
const electrical = candidate.electrical;
|
|
1586
3199
|
if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
|
|
1587
|
-
if (electrical
|
|
1588
|
-
if (typeof electrical.allowMultiDriver !== "boolean") throw new CircuitError("invalid-options", "electrical.allowMultiDriver must be a boolean");
|
|
1589
|
-
allowMultiDriver = electrical.allowMultiDriver;
|
|
1590
|
-
}
|
|
1591
|
-
rails = electrical.rails;
|
|
3200
|
+
if ("rails" in electrical) throw new CircuitError("invalid-options", "Boolean rails are unsupported; declare explicit voltage sources");
|
|
1592
3201
|
}
|
|
1593
3202
|
return Object.freeze({
|
|
1594
3203
|
engine,
|
|
1595
3204
|
jit: candidate.jit,
|
|
1596
3205
|
validateIR: candidate.validateIR ?? true,
|
|
1597
|
-
|
|
1598
|
-
|
|
3206
|
+
sources: candidate.electrical?.sources,
|
|
3207
|
+
interpretation: candidate.electrical?.interpretation,
|
|
3208
|
+
floatingSeed: candidate.electrical?.floatingSeed,
|
|
1599
3209
|
instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
|
|
1600
3210
|
});
|
|
1601
3211
|
}
|
|
@@ -1651,6 +3261,7 @@ async function createSchematicCircuit(schematic, options) {
|
|
|
1651
3261
|
id: deviceId,
|
|
1652
3262
|
type: binding.type,
|
|
1653
3263
|
description: binding.description,
|
|
3264
|
+
...symbol.properties === void 0 ? {} : { properties: symbol.properties },
|
|
1654
3265
|
...binding.config === void 0 ? {} : { config: binding.config }
|
|
1655
3266
|
});
|
|
1656
3267
|
if (reference !== void 0) bindings.push({
|
|
@@ -1665,7 +3276,7 @@ async function createSchematicCircuit(schematic, options) {
|
|
|
1665
3276
|
...tolerance === void 0 ? {} : { tolerance }
|
|
1666
3277
|
});
|
|
1667
3278
|
if (componentCount > 0 && topology.pins.length === 0) throw new CircuitError("invalid-options", "The derived topology has no pins; pass the DeviceSymbolProvider that authored the schematic so pins can be located");
|
|
1668
|
-
const railNames = /* @__PURE__ */ new Set([
|
|
3279
|
+
const railNames = /* @__PURE__ */ new Set(["GND", ...Object.keys(options.electrical?.sources ?? {})]);
|
|
1669
3280
|
const connections = [];
|
|
1670
3281
|
for (const net of topology.nets) {
|
|
1671
3282
|
const endpoints = [];
|
|
@@ -1734,7 +3345,8 @@ var DEFAULT_STEP_PS = 1e4;
|
|
|
1734
3345
|
* `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
|
|
1735
3346
|
*/
|
|
1736
3347
|
function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schematic, topics = [], stepPs = DEFAULT_STEP_PS, deliver }) {
|
|
1737
|
-
|
|
3348
|
+
if (!Number.isSafeInteger(stepPs) || stepPs <= 0) throw new TypeError("stepPs must be a positive safe integer");
|
|
3349
|
+
const simTime = () => Number(circuit.tickCount) * stepPs;
|
|
1738
3350
|
return {
|
|
1739
3351
|
async loadSchematic() {},
|
|
1740
3352
|
async reset() {
|
|
@@ -1742,10 +3354,11 @@ function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schema
|
|
|
1742
3354
|
},
|
|
1743
3355
|
async tick(dt) {
|
|
1744
3356
|
if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
|
|
1745
|
-
circuit.
|
|
3357
|
+
const before = circuit.tickCount;
|
|
3358
|
+
circuit.runBatch(1, stepPs);
|
|
1746
3359
|
return {
|
|
1747
3360
|
simTime: simTime(),
|
|
1748
|
-
executed:
|
|
3361
|
+
executed: Number(circuit.tickCount - before)
|
|
1749
3362
|
};
|
|
1750
3363
|
},
|
|
1751
3364
|
async deliver(target, payload) {
|
|
@@ -1826,7 +3439,8 @@ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
|
|
|
1826
3439
|
symbol: binding.symbolId,
|
|
1827
3440
|
designator,
|
|
1828
3441
|
binding: deviceBinding,
|
|
1829
|
-
accessor
|
|
3442
|
+
accessor,
|
|
3443
|
+
bridge: deviceBridgeOf(accessor)
|
|
1830
3444
|
};
|
|
1831
3445
|
devices.push(device);
|
|
1832
3446
|
for (const topic of deviceBinding.topics ?? []) {
|
|
@@ -1871,23 +3485,43 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1871
3485
|
let runtime;
|
|
1872
3486
|
let simTimePs = 0;
|
|
1873
3487
|
let disposed = false;
|
|
1874
|
-
const
|
|
3488
|
+
const publishOutput = (device, port, raw) => {
|
|
3489
|
+
const topic = device.binding.topics?.find((value) => value.port === port && value.direction === "output");
|
|
3490
|
+
if (topic === void 0) throw new TypeError(`Unknown output topic ${device.designator}.${port}`);
|
|
3491
|
+
const payload = topic.type === "number" && typeof raw === "object" && raw !== null && "type" in raw && (raw.type === "f32" || raw.type === "f64") && "bits" in raw && typeof raw.bits === "string" ? toNumber(raw) : raw;
|
|
3492
|
+
if (!payloadMatches(topic.type, payload)) throw new TypeError(`Invalid output payload for ${device.designator}.${port}`);
|
|
1875
3493
|
if (!publishes.hasListeners) return;
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
3494
|
+
const key = targetKey(device.symbol, port);
|
|
3495
|
+
if (published.has(key) && samePayload(published.get(key), payload)) return;
|
|
3496
|
+
published.set(key, payload);
|
|
3497
|
+
publishes.fire({
|
|
3498
|
+
target: {
|
|
3499
|
+
symbol: device.symbol,
|
|
3500
|
+
port
|
|
3501
|
+
},
|
|
3502
|
+
payload,
|
|
3503
|
+
simTime: simTimePs
|
|
3504
|
+
});
|
|
3505
|
+
};
|
|
3506
|
+
const publishOutputs = (active, diagnostics) => {
|
|
3507
|
+
for (const device of active.devices) {
|
|
3508
|
+
if (device.bridge.flushOutputs !== void 0) {
|
|
3509
|
+
try {
|
|
3510
|
+
device.bridge.flushOutputs((port, payload) => publishOutput(device, port, payload));
|
|
3511
|
+
} catch (cause) {
|
|
3512
|
+
diagnostics.push({
|
|
3513
|
+
code: "device/output-failed",
|
|
3514
|
+
deviceId: device.symbol,
|
|
3515
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
3516
|
+
});
|
|
3517
|
+
}
|
|
3518
|
+
continue;
|
|
3519
|
+
}
|
|
3520
|
+
if (!publishes.hasListeners) continue;
|
|
3521
|
+
for (const topic of device.binding.topics ?? []) {
|
|
3522
|
+
if (topic.direction !== "output" || device.binding.read === void 0) continue;
|
|
3523
|
+
publishOutput(device, topic.port, device.binding.read(device.accessor, topic.port));
|
|
3524
|
+
}
|
|
1891
3525
|
}
|
|
1892
3526
|
};
|
|
1893
3527
|
const clearRuntime = () => {
|
|
@@ -1909,6 +3543,7 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1909
3543
|
const compiled = await createSchematicCircuit(schematic, {
|
|
1910
3544
|
...symbolProvider === void 0 ? {} : { devices: symbolProvider },
|
|
1911
3545
|
resolveDevice,
|
|
3546
|
+
...options.electrical === void 0 ? {} : { electrical: options.electrical },
|
|
1912
3547
|
instanceId: INSTANCE_ID
|
|
1913
3548
|
});
|
|
1914
3549
|
const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);
|
|
@@ -1940,16 +3575,39 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1940
3575
|
};
|
|
1941
3576
|
}
|
|
1942
3577
|
const queued = pending.splice(0, pending.length);
|
|
1943
|
-
|
|
3578
|
+
const inputs = /* @__PURE__ */ new Map();
|
|
3579
|
+
for (const delivery of queued) if (delivery.device.bridge.applyInputs !== void 0) {
|
|
3580
|
+
const values = inputs.get(delivery.device) ?? [];
|
|
3581
|
+
values.push({
|
|
3582
|
+
port: delivery.port,
|
|
3583
|
+
payload: delivery.payload
|
|
3584
|
+
});
|
|
3585
|
+
inputs.set(delivery.device, values);
|
|
3586
|
+
} else {
|
|
1944
3587
|
if (delivery.device.binding.deliver === void 0) throw new TypeError(`${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`);
|
|
1945
3588
|
delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);
|
|
1946
3589
|
}
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
3590
|
+
const diagnostics = [];
|
|
3591
|
+
for (const device of active.devices) try {
|
|
3592
|
+
device.bridge.applyInputs?.(inputs.get(device) ?? []);
|
|
3593
|
+
} catch (cause) {
|
|
3594
|
+
diagnostics.push({
|
|
3595
|
+
code: "device/input-failed",
|
|
3596
|
+
deviceId: device.symbol,
|
|
3597
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
3598
|
+
});
|
|
3599
|
+
}
|
|
3600
|
+
const before = active.circuit.tickCount;
|
|
3601
|
+
try {
|
|
3602
|
+
active.circuit.runBatch(1, dt);
|
|
3603
|
+
} finally {
|
|
3604
|
+
simTimePs += dt * Number(active.circuit.tickCount - before);
|
|
3605
|
+
}
|
|
3606
|
+
publishOutputs(active, diagnostics);
|
|
1950
3607
|
return {
|
|
1951
3608
|
simTime: simTimePs,
|
|
1952
|
-
executed:
|
|
3609
|
+
executed: Number(active.circuit.tickCount - before),
|
|
3610
|
+
...diagnostics.length === 0 ? {} : { diagnostics: Object.freeze(diagnostics) }
|
|
1953
3611
|
};
|
|
1954
3612
|
},
|
|
1955
3613
|
async deliver(target, payload) {
|
|
@@ -1960,7 +3618,7 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1960
3618
|
if (binding === void 0) throw new Error(`Unknown device input ${target.symbol}.${target.port}`);
|
|
1961
3619
|
if (!payloadMatches(binding.topic.type, payload)) throw new TypeError(`${target.symbol}.${target.port} expects a ${binding.topic.type} payload`);
|
|
1962
3620
|
const device = binding.device;
|
|
1963
|
-
if (device.binding.deliver === void 0) throw new Error(`${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`);
|
|
3621
|
+
if (device.binding.deliver === void 0 && device.bridge.applyInputs === void 0) throw new Error(`${device.binding.type} has no writable topic ${JSON.stringify(target.port)}`);
|
|
1964
3622
|
pending.push({
|
|
1965
3623
|
device,
|
|
1966
3624
|
port: target.port,
|
|
@@ -2014,6 +3672,7 @@ function startDeviceSimulationHostGuest(port, options = {}) {
|
|
|
2014
3672
|
return bytes;
|
|
2015
3673
|
},
|
|
2016
3674
|
...devices === void 0 ? {} : { devices },
|
|
3675
|
+
...options.electrical === void 0 ? {} : { electrical: options.electrical },
|
|
2017
3676
|
resolveDevice: resolveDevice ?? (() => void 0)
|
|
2018
3677
|
});
|
|
2019
3678
|
let prepared;
|
|
@@ -2089,6 +3748,6 @@ function startDeviceSimulationHostGuest(port, options = {}) {
|
|
|
2089
3748
|
};
|
|
2090
3749
|
}
|
|
2091
3750
|
//#endregion
|
|
2092
|
-
export { Circuit, CircuitError,
|
|
3751
|
+
export { Circuit, CircuitError, DEVICE_PIN_STRIDE, ElectricalDefinitionError, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitDeviceSimulationHost, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
|
|
2093
3752
|
|
|
2094
3753
|
//# sourceMappingURL=index.js.map
|