@mica-js/simulator 0.4.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 +11 -1
- package/dist/index.d.ts +222 -144
- package/dist/index.js +2353 -681
- package/dist/index.js.map +1 -1
- package/dist/sandbox.d.ts +6 -0
- package/dist/sandbox.js +1 -1
- package/package.json +2 -1
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,7 +380,7 @@ 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
|
|
383
|
+
* stride and the physical output configuration values. Capacity and stride are limits
|
|
57
384
|
* checked at allocation time; the shared pin memories are sized to the pins a
|
|
58
385
|
* circuit actually declares, so a larger ceiling costs no runtime memory.
|
|
59
386
|
*/
|
|
@@ -61,7 +388,7 @@ function createModuleValidation(module, updateResources = []) {
|
|
|
61
388
|
var UNIFIED_PIN_CAPACITY = 4096;
|
|
62
389
|
/** Global pin addresses one device may own; enough for the largest packages. */
|
|
63
390
|
var DEVICE_PIN_STRIDE = 512;
|
|
64
|
-
/**
|
|
391
|
+
/** Physical output configuration values. */
|
|
65
392
|
var PIN_MODE = Object.freeze({
|
|
66
393
|
highZ: 0,
|
|
67
394
|
pushPull: 1,
|
|
@@ -69,6 +396,875 @@ var PIN_MODE = Object.freeze({
|
|
|
69
396
|
analog: 3
|
|
70
397
|
});
|
|
71
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
|
|
72
1268
|
//#region src/unified-ir/compiler/types.ts
|
|
73
1269
|
/** Error raised while compiling a circuit. */
|
|
74
1270
|
var UnifiedIRCompilerError = class extends Error {
|
|
@@ -76,17 +1272,711 @@ var UnifiedIRCompilerError = class extends Error {
|
|
|
76
1272
|
code;
|
|
77
1273
|
deviceId;
|
|
78
1274
|
pinName;
|
|
79
|
-
netId;
|
|
80
|
-
diagnostics;
|
|
81
1275
|
constructor(code, message, options = {}) {
|
|
82
1276
|
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
83
1277
|
this.code = code;
|
|
84
1278
|
this.deviceId = options.deviceId;
|
|
85
1279
|
this.pinName = options.pinName;
|
|
86
|
-
this.netId = options.netId;
|
|
87
|
-
this.diagnostics = options.diagnostics ?? [];
|
|
88
1280
|
}
|
|
89
|
-
};
|
|
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
|
+
}
|
|
90
1980
|
//#endregion
|
|
91
1981
|
//#region src/unified-ir/compiler/allocator.ts
|
|
92
1982
|
/** Generated device ids prefix IR function names, so they must be identifiers. */
|
|
@@ -98,12 +1988,11 @@ var DEVICE_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
|
98
1988
|
* ids: 0 = drive1.PA0 1 = drive1.PA1 2 = sink1.anode 3 = sink1.cathode
|
|
99
1989
|
* |<-- drive1 -->| |<----------- sink1 ----------->|
|
|
100
1990
|
*
|
|
101
|
-
* pin_mode[n] u8 pin_output[n] bool pin_input[n] bool (n = totalPins)
|
|
102
1991
|
* device_state_bool[n] / device_state_u32[m] / ... (one array per used type)
|
|
103
1992
|
* ```
|
|
104
1993
|
*
|
|
105
1994
|
* Pins are packed in declaration order across devices — the addresses the
|
|
106
|
-
* device IR
|
|
1995
|
+
* device IR embeds as constants. States are packed per
|
|
107
1996
|
* scalar type into one shared array, so a device's slot stays typed while all
|
|
108
1997
|
* devices share one storage region.
|
|
109
1998
|
*/
|
|
@@ -112,11 +2001,10 @@ var GlobalResourceAllocator = class {
|
|
|
112
2001
|
constructor(module) {
|
|
113
2002
|
this.module = module;
|
|
114
2003
|
}
|
|
115
|
-
/** Allocates
|
|
2004
|
+
/** Allocates pin addresses and typed device state arrays. */
|
|
116
2005
|
allocate(devices) {
|
|
117
2006
|
const pins = this.allocatePins(devices);
|
|
118
2007
|
return Object.freeze({
|
|
119
|
-
memory: createPinMemory(this.module, Math.max(1, pins.totalPins)),
|
|
120
2008
|
pins,
|
|
121
2009
|
states: this.allocateStates(devices)
|
|
122
2010
|
});
|
|
@@ -140,19 +2028,14 @@ var GlobalResourceAllocator = class {
|
|
|
140
2028
|
const offset = totalPins;
|
|
141
2029
|
const devicePins = /* @__PURE__ */ new Map();
|
|
142
2030
|
const resolved = /* @__PURE__ */ new Map();
|
|
143
|
-
for (const [name
|
|
2031
|
+
for (const [name] of entries) {
|
|
144
2032
|
const globalPinId = totalPins;
|
|
145
2033
|
totalPins += 1;
|
|
146
|
-
const direction = resolvePinDirection(descriptor, device.id, name);
|
|
147
|
-
const { role, senses } = resolvePinRole(direction, descriptor?.role, device.id, name);
|
|
148
2034
|
devicePins.set(name, globalPinId);
|
|
149
2035
|
resolved.set(name, Object.freeze({
|
|
150
2036
|
name,
|
|
151
2037
|
deviceId: device.id,
|
|
152
|
-
globalPinId
|
|
153
|
-
direction,
|
|
154
|
-
role,
|
|
155
|
-
senses
|
|
2038
|
+
globalPinId
|
|
156
2039
|
}));
|
|
157
2040
|
pins.set(`${device.id}.${name}`, globalPinId);
|
|
158
2041
|
}
|
|
@@ -226,20 +2109,6 @@ var GlobalResourceAllocator = class {
|
|
|
226
2109
|
});
|
|
227
2110
|
}
|
|
228
2111
|
};
|
|
229
|
-
/**
|
|
230
|
-
* Declares the three pin memories shared by every device and net solver.
|
|
231
|
-
*
|
|
232
|
-
* The memories are sized to the pins the circuit declares, never to
|
|
233
|
-
* {@link UNIFIED_PIN_CAPACITY}: the capacity only bounds how many pins a
|
|
234
|
-
* circuit may have, so a large ceiling costs neither memory nor setup time.
|
|
235
|
-
*/
|
|
236
|
-
function createPinMemory(module, capacity = UNIFIED_PIN_CAPACITY) {
|
|
237
|
-
return Object.freeze({
|
|
238
|
-
mode: module.array("pin_mode", "u8", Array.from({ length: capacity }, () => PIN_MODE.highZ)),
|
|
239
|
-
output: module.array("pin_output", "bool", Array.from({ length: capacity }, () => false)),
|
|
240
|
-
input: module.array("pin_input", "bool", Array.from({ length: capacity }, () => false))
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
2112
|
/** First state slot ordinal of every device; used for `DeviceMetadata.stateOffset`. */
|
|
244
2113
|
function stateOffsetOf(states, deviceId) {
|
|
245
2114
|
let offset = 0;
|
|
@@ -281,53 +2150,6 @@ function pinEntries(device) {
|
|
|
281
2150
|
}
|
|
282
2151
|
return entries;
|
|
283
2152
|
}
|
|
284
|
-
var PIN_DIRECTIONS = /* @__PURE__ */ new Set([
|
|
285
|
-
"input",
|
|
286
|
-
"output",
|
|
287
|
-
"bidirectional",
|
|
288
|
-
"passive"
|
|
289
|
-
]);
|
|
290
|
-
function resolvePinDirection(descriptor, deviceId, pinName) {
|
|
291
|
-
const direction = descriptor?.direction ?? "passive";
|
|
292
|
-
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`, {
|
|
293
|
-
deviceId,
|
|
294
|
-
pinName
|
|
295
|
-
});
|
|
296
|
-
return direction;
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Derives the electrical role and the read behavior of a pin.
|
|
300
|
-
*
|
|
301
|
-
* `output` drives only, `input`/`passive` sense only, `bidirectional` drives and
|
|
302
|
-
* senses. An explicit `role` overrides the derived drive role while
|
|
303
|
-
* `bidirectional` keeps its sense side.
|
|
304
|
-
*/
|
|
305
|
-
function resolvePinRole(direction, explicit, deviceId, pinName) {
|
|
306
|
-
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`, {
|
|
307
|
-
deviceId,
|
|
308
|
-
pinName
|
|
309
|
-
});
|
|
310
|
-
if (explicit === "driver") return {
|
|
311
|
-
role: "driver",
|
|
312
|
-
senses: direction === "bidirectional"
|
|
313
|
-
};
|
|
314
|
-
if (explicit === "load") return {
|
|
315
|
-
role: "load",
|
|
316
|
-
senses: true
|
|
317
|
-
};
|
|
318
|
-
if (direction === "output") return {
|
|
319
|
-
role: "driver",
|
|
320
|
-
senses: false
|
|
321
|
-
};
|
|
322
|
-
if (direction === "bidirectional") return {
|
|
323
|
-
role: "driver",
|
|
324
|
-
senses: true
|
|
325
|
-
};
|
|
326
|
-
return {
|
|
327
|
-
role: "load",
|
|
328
|
-
senses: true
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
2153
|
function stateEntries(device) {
|
|
332
2154
|
const raw = device.description.states;
|
|
333
2155
|
if (raw === void 0) return [];
|
|
@@ -354,11 +2176,8 @@ function assertStateInitial(deviceId, name, type, initial) {
|
|
|
354
2176
|
/**
|
|
355
2177
|
* Generates one IR function per device phase into the unified module.
|
|
356
2178
|
*
|
|
357
|
-
* Domain operations
|
|
358
|
-
*
|
|
359
|
-
* on the shared `pin_mode` / `pin_output` / `pin_input` memories, so no device
|
|
360
|
-
* keeps its own module, protocol or host hop. A device without an explicit
|
|
361
|
-
* `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.
|
|
362
2181
|
*
|
|
363
2182
|
* The compiler ships no device models: every description must declare its own
|
|
364
2183
|
* pins, states and behaviors (or a `kernel`) before it reaches this generator.
|
|
@@ -369,21 +2188,21 @@ var DeviceIRGenerator = class {
|
|
|
369
2188
|
this.context = context;
|
|
370
2189
|
}
|
|
371
2190
|
/**
|
|
372
|
-
* @throws {UnifiedIRCompilerError} when
|
|
373
|
-
*
|
|
2191
|
+
* @throws {UnifiedIRCompilerError} when a behavior reaches for a pin or state
|
|
2192
|
+
* the paired description does not declare.
|
|
374
2193
|
*/
|
|
375
2194
|
generate(device) {
|
|
376
2195
|
const allocation = this.context.pins.devices.get(device.id);
|
|
377
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;
|
|
378
2198
|
const kernelResult = device.description.kernel?.({
|
|
379
2199
|
deviceId: device.id,
|
|
380
2200
|
config: device.config,
|
|
381
2201
|
module: this.context.module,
|
|
382
|
-
|
|
2202
|
+
bind: (builder) => this.createApi(device, allocation, builder),
|
|
383
2203
|
pins: [...allocation.resolved.values()].map((pin) => Object.freeze({
|
|
384
2204
|
name: pin.name,
|
|
385
|
-
globalPinId: pin.globalPinId
|
|
386
|
-
role: pin.role
|
|
2205
|
+
globalPinId: pin.globalPinId
|
|
387
2206
|
}))
|
|
388
2207
|
});
|
|
389
2208
|
const kernelRuntime = kernelResult !== void 0 && isKernelRuntime(kernelResult) ? kernelResult : void 0;
|
|
@@ -396,10 +2215,9 @@ var DeviceIRGenerator = class {
|
|
|
396
2215
|
tick = phaseFromRef(this.context.module, device.id, kernelRuntime.tick);
|
|
397
2216
|
update = phaseFromRef(this.context.module, device.id, kernelRuntime.update);
|
|
398
2217
|
} else {
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
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);
|
|
403
2221
|
}
|
|
404
2222
|
const functions = [];
|
|
405
2223
|
for (const phase of [
|
|
@@ -410,6 +2228,7 @@ var DeviceIRGenerator = class {
|
|
|
410
2228
|
const metadata = Object.freeze({
|
|
411
2229
|
deviceId: device.id,
|
|
412
2230
|
type: device.type,
|
|
2231
|
+
entries: Object.freeze(this.context.module.functions.slice(functionOffset).filter((fn) => fn.category === "entry").map((fn) => fn.ref)),
|
|
413
2232
|
pinOffset: allocation.offset,
|
|
414
2233
|
stateOffset: stateOffsetOf(this.context.states, device.id),
|
|
415
2234
|
pins: allocation.pins,
|
|
@@ -419,7 +2238,8 @@ var DeviceIRGenerator = class {
|
|
|
419
2238
|
tick: tick?.name,
|
|
420
2239
|
update: update?.name,
|
|
421
2240
|
accessor: device.description.accessor,
|
|
422
|
-
|
|
2241
|
+
...device.description.applyInputs === void 0 ? {} : { applyInputs: device.description.applyInputs },
|
|
2242
|
+
...device.description.flushOutputs === void 0 ? {} : { flushOutputs: device.description.flushOutputs }
|
|
423
2243
|
});
|
|
424
2244
|
return Object.freeze({
|
|
425
2245
|
metadata,
|
|
@@ -447,53 +2267,21 @@ var DeviceIRGenerator = class {
|
|
|
447
2267
|
ref
|
|
448
2268
|
};
|
|
449
2269
|
}
|
|
450
|
-
generateDefaultInitialize(device, allocation) {
|
|
451
|
-
const outputs = [...allocation.resolved.values()].filter((pin) => pin.role === "driver");
|
|
452
|
-
if (outputs.length === 0) return void 0;
|
|
453
|
-
const name = `${device.id}_initialize`;
|
|
454
|
-
const ref = this.context.module.func(name, {
|
|
455
|
-
params: [],
|
|
456
|
-
results: []
|
|
457
|
-
});
|
|
458
|
-
ref.body((b) => {
|
|
459
|
-
for (const pin of outputs) b.array.store(this.context.memory.mode, b.const("u32", pin.globalPinId), b.const("u8", PIN_MODE.pushPull));
|
|
460
|
-
b.return([]);
|
|
461
|
-
});
|
|
462
|
-
return {
|
|
463
|
-
name,
|
|
464
|
-
ref
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
2270
|
createApi(device, allocation, builder) {
|
|
468
|
-
const handles = /* @__PURE__ */ new Map();
|
|
469
|
-
const pins = [];
|
|
470
|
-
const outputs = [];
|
|
471
|
-
for (const pin of allocation.resolved.values()) {
|
|
472
|
-
const handle = this.createPinHandle(pin.globalPinId, pin.name, builder);
|
|
473
|
-
handles.set(pin.name, handle);
|
|
474
|
-
pins.push(handle);
|
|
475
|
-
if (pin.role === "driver") outputs.push(handle);
|
|
476
|
-
}
|
|
477
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])));
|
|
478
2273
|
return Object.freeze({
|
|
479
2274
|
deviceId: device.id,
|
|
480
2275
|
builder,
|
|
481
2276
|
module: this.context.module,
|
|
482
|
-
memory: this.context.memory,
|
|
483
2277
|
config: device.config,
|
|
484
|
-
pins:
|
|
485
|
-
outputs:
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
deviceId: device.id,
|
|
492
|
-
pinName: name
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
return handle;
|
|
496
|
-
},
|
|
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,
|
|
497
2285
|
state(name) {
|
|
498
2286
|
const slot = slots?.get(name);
|
|
499
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 });
|
|
@@ -501,27 +2289,6 @@ var DeviceIRGenerator = class {
|
|
|
501
2289
|
}
|
|
502
2290
|
});
|
|
503
2291
|
}
|
|
504
|
-
createPinHandle(globalId, name, builder) {
|
|
505
|
-
const memory = this.context.memory;
|
|
506
|
-
const index = () => builder.const("u32", globalId);
|
|
507
|
-
return Object.freeze({
|
|
508
|
-
name,
|
|
509
|
-
globalId,
|
|
510
|
-
configure(mode) {
|
|
511
|
-
if (!Number.isInteger(mode) || mode < 0 || mode > 255) throw new UnifiedIRCompilerError("invalid-input", `Pin "${name}" configure(${String(mode)}) needs a u8 pin mode`);
|
|
512
|
-
builder.array.store(memory.mode, index(), builder.const("u8", mode));
|
|
513
|
-
},
|
|
514
|
-
writeDigital(level) {
|
|
515
|
-
builder.array.store(memory.output, index(), level);
|
|
516
|
-
},
|
|
517
|
-
sampleDigital() {
|
|
518
|
-
return builder.array.load(memory.input, index());
|
|
519
|
-
},
|
|
520
|
-
readDrivenDigital() {
|
|
521
|
-
return builder.array.load(memory.output, index());
|
|
522
|
-
}
|
|
523
|
-
});
|
|
524
|
-
}
|
|
525
2292
|
};
|
|
526
2293
|
function createStateHandle(deviceId, slot, builder) {
|
|
527
2294
|
const array = slot.array;
|
|
@@ -538,9 +2305,6 @@ function createStateHandle(deviceId, slot, builder) {
|
|
|
538
2305
|
}
|
|
539
2306
|
});
|
|
540
2307
|
}
|
|
541
|
-
function hasAnyBehavior(behaviors) {
|
|
542
|
-
return behaviors.initialize !== void 0 || behaviors.tick !== void 0 || behaviors.update !== void 0;
|
|
543
|
-
}
|
|
544
2308
|
/** Bulk kernel results carry phase refs; behaviour hooks are plain functions. */
|
|
545
2309
|
function isKernelRuntime(value) {
|
|
546
2310
|
if (value === null || typeof value !== "object") return false;
|
|
@@ -578,99 +2342,81 @@ var DEFAULT_ENTRY_POINT_NAMES = Object.freeze({
|
|
|
578
2342
|
*
|
|
579
2343
|
* unified_tick: // one simulation step
|
|
580
2344
|
* drive1_tick() // drivers publish their outputs
|
|
581
|
-
*
|
|
2345
|
+
* electrical_ensure() // solve only if the network changed
|
|
582
2346
|
* sink1_update() // loads observe the solved inputs
|
|
583
2347
|
*
|
|
584
2348
|
* unified_tick_batch(count): // the same step, looped inside the IR
|
|
585
2349
|
* for i in 0 .. count { <step> }
|
|
586
2350
|
* ```
|
|
587
2351
|
*
|
|
588
|
-
* Devices run in
|
|
589
|
-
*
|
|
590
|
-
* 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.
|
|
591
2354
|
*/
|
|
592
2355
|
var MainLoopGenerator = class {
|
|
2356
|
+
electrical;
|
|
593
2357
|
module;
|
|
594
|
-
constructor(module) {
|
|
2358
|
+
constructor(module, electrical) {
|
|
2359
|
+
this.electrical = electrical;
|
|
595
2360
|
this.module = module;
|
|
596
2361
|
}
|
|
597
|
-
/** Stable topological order of the devices; cycles fall back to declaration order. */
|
|
598
|
-
order(entries, netlist) {
|
|
599
|
-
const indexById = new Map(entries.map((entry, index) => [entry.deviceId, index]));
|
|
600
|
-
const consumers = /* @__PURE__ */ new Map();
|
|
601
|
-
const indegree = new Map(entries.map((entry) => [entry.deviceId, 0]));
|
|
602
|
-
for (const net of netlist.nets) {
|
|
603
|
-
const driverDevices = new Set(net.drivers.map((pin) => pin.deviceId));
|
|
604
|
-
const sinkDevices = new Set(net.sinks.map((pin) => pin.deviceId));
|
|
605
|
-
for (const driver of driverDevices) for (const sink of sinkDevices) {
|
|
606
|
-
if (driver === sink) continue;
|
|
607
|
-
let targets = consumers.get(driver);
|
|
608
|
-
if (targets === void 0) {
|
|
609
|
-
targets = /* @__PURE__ */ new Set();
|
|
610
|
-
consumers.set(driver, targets);
|
|
611
|
-
}
|
|
612
|
-
if (targets.has(sink)) continue;
|
|
613
|
-
targets.add(sink);
|
|
614
|
-
indegree.set(sink, (indegree.get(sink) ?? 0) + 1);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
const ready = new Set(entries.filter((entry) => (indegree.get(entry.deviceId) ?? 0) === 0).map((entry) => entry.deviceId));
|
|
618
|
-
const order = [];
|
|
619
|
-
while (ready.size > 0) {
|
|
620
|
-
let nextId;
|
|
621
|
-
let nextIndex = Number.POSITIVE_INFINITY;
|
|
622
|
-
for (const id of ready) {
|
|
623
|
-
const index = indexById.get(id) ?? 0;
|
|
624
|
-
if (index < nextIndex) {
|
|
625
|
-
nextIndex = index;
|
|
626
|
-
nextId = id;
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
if (nextId === void 0) break;
|
|
630
|
-
ready.delete(nextId);
|
|
631
|
-
order.push(nextId);
|
|
632
|
-
for (const consumer of consumers.get(nextId) ?? []) {
|
|
633
|
-
const remaining = (indegree.get(consumer) ?? 0) - 1;
|
|
634
|
-
indegree.set(consumer, remaining);
|
|
635
|
-
if (remaining === 0) ready.add(consumer);
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
for (const entry of entries) if (!order.includes(entry.deviceId)) order.push(entry.deviceId);
|
|
639
|
-
return Object.freeze(order);
|
|
640
|
-
}
|
|
641
2362
|
/** Generates `initialize`, `tick` and the batched tick loop. */
|
|
642
|
-
generate(entries,
|
|
643
|
-
const order =
|
|
2363
|
+
generate(entries, names = DEFAULT_ENTRY_POINT_NAMES) {
|
|
2364
|
+
const order = Object.freeze(entries.map((entry) => entry.deviceId));
|
|
644
2365
|
const byId = new Map(entries.map((entry) => [entry.deviceId, entry]));
|
|
645
|
-
const
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
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)));
|
|
655
2404
|
};
|
|
656
2405
|
const initialize = this.module.func(names.initialize, {
|
|
657
2406
|
params: [],
|
|
658
2407
|
results: []
|
|
659
2408
|
});
|
|
660
|
-
initialize.body((b) =>
|
|
661
|
-
for (const deviceId of order) {
|
|
662
|
-
const entry = byId.get(deviceId);
|
|
663
|
-
if (entry?.initialize !== void 0) b.call(entry.initialize, []);
|
|
664
|
-
}
|
|
665
|
-
b.return([]);
|
|
666
|
-
});
|
|
2409
|
+
initialize.body((b) => emitCalls(b, [...collect("initialize"), ...ensure], (b) => b.return([])));
|
|
667
2410
|
const tick = this.module.func(names.tick, {
|
|
668
2411
|
params: [],
|
|
669
2412
|
results: []
|
|
670
2413
|
});
|
|
671
2414
|
tick.body((b) => {
|
|
672
|
-
|
|
673
|
-
|
|
2415
|
+
b.state.store(progress, b.const("u32", 0));
|
|
2416
|
+
return emitCalls(b, phases, (b) => {
|
|
2417
|
+
completed(b);
|
|
2418
|
+
b.return([]);
|
|
2419
|
+
});
|
|
674
2420
|
});
|
|
675
2421
|
const batch = this.module.func(names.batch, {
|
|
676
2422
|
params: ["u32"],
|
|
@@ -680,320 +2426,32 @@ var MainLoopGenerator = class {
|
|
|
680
2426
|
const header = b.block(["u32"]);
|
|
681
2427
|
const body = b.block(["u32"]);
|
|
682
2428
|
const done = b.block([]);
|
|
2429
|
+
b.state.store(progress, b.const("u32", 0));
|
|
683
2430
|
b.jump(header, [b.const("u32", 0)]);
|
|
684
|
-
b.at(header, (
|
|
2431
|
+
b.at(header, (b, [index]) => b.branch(b.int.cmp("lt", index, count), {
|
|
685
2432
|
target: body,
|
|
686
2433
|
args: [index]
|
|
687
2434
|
}, {
|
|
688
2435
|
target: done,
|
|
689
2436
|
args: []
|
|
690
2437
|
}));
|
|
691
|
-
b.at(body, (
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
});
|
|
695
|
-
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([]));
|
|
696
2443
|
});
|
|
697
2444
|
return Object.freeze({
|
|
698
2445
|
names,
|
|
699
2446
|
initialize,
|
|
700
2447
|
tick,
|
|
701
2448
|
batch,
|
|
2449
|
+
progress,
|
|
702
2450
|
order
|
|
703
2451
|
});
|
|
704
2452
|
}
|
|
705
2453
|
};
|
|
706
2454
|
//#endregion
|
|
707
|
-
//#region src/unified-ir/compiler/solver-gen.ts
|
|
708
|
-
/**
|
|
709
|
-
* Generates the electrical solve, one `solve_net_<id>` function per net.
|
|
710
|
-
*
|
|
711
|
-
* Each net solves as a branch-free function. One driver is the common shape:
|
|
712
|
-
*
|
|
713
|
-
* ```text
|
|
714
|
-
* solve_net_0:
|
|
715
|
-
* let mode = PIN_MODE[driver]
|
|
716
|
-
* let output = PIN_OUTPUT[driver]
|
|
717
|
-
* let driven = mode == PUSH_PULL && output
|
|
718
|
-
* PIN_INPUT[load] = driven // once per sink
|
|
719
|
-
* ```
|
|
720
|
-
*
|
|
721
|
-
* Only a push-pull driver holds its net; high-z, open-drain and analog modes
|
|
722
|
-
* leave it floating. A driver-less net loads the constant of its rail, or
|
|
723
|
-
* `false` when it is truly floating. Several drivers OR into a wired-OR level.
|
|
724
|
-
*/
|
|
725
|
-
var ElectricalSolverGenerator = class {
|
|
726
|
-
context;
|
|
727
|
-
constructor(context) {
|
|
728
|
-
this.context = context;
|
|
729
|
-
}
|
|
730
|
-
generate(netlist) {
|
|
731
|
-
return Object.freeze(netlist.nets.map((net) => this.generateNetSolver(net)));
|
|
732
|
-
}
|
|
733
|
-
generateNetSolver(net) {
|
|
734
|
-
const name = `solve_net_${net.netId}`;
|
|
735
|
-
const solve = this.context.module.func(name, {
|
|
736
|
-
params: [],
|
|
737
|
-
results: []
|
|
738
|
-
});
|
|
739
|
-
solve.body((b) => {
|
|
740
|
-
if (net.sinks.length > 0) {
|
|
741
|
-
const driven = net.drivers.length === 0 ? b.const("bool", net.level) : this.combineDrivers(b, net.drivers);
|
|
742
|
-
if (driven !== void 0) for (const sink of net.sinks) b.array.store(this.context.memory.input, b.const("u32", sink.globalPinId), driven);
|
|
743
|
-
}
|
|
744
|
-
b.return([]);
|
|
745
|
-
});
|
|
746
|
-
return Object.freeze({
|
|
747
|
-
netId: net.netId,
|
|
748
|
-
name,
|
|
749
|
-
net,
|
|
750
|
-
solve
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
/**
|
|
754
|
-
* Folds the drivers of one net into the level its sinks observe.
|
|
755
|
-
*
|
|
756
|
-
* A single driver yields `mode == push-pull && output`; several drivers are
|
|
757
|
-
* OR-ed into a wired-OR level.
|
|
758
|
-
*/
|
|
759
|
-
combineDrivers(b, drivers) {
|
|
760
|
-
let driven;
|
|
761
|
-
for (const driver of drivers) {
|
|
762
|
-
const index = b.const("u32", driver.globalPinId);
|
|
763
|
-
const mode = b.array.load(this.context.memory.mode, index);
|
|
764
|
-
const output = b.array.load(this.context.memory.output, index);
|
|
765
|
-
const pushed = b.int.cmp("eq", mode, b.const("u8", PIN_MODE.pushPull));
|
|
766
|
-
const value = b.bool.and(pushed, output);
|
|
767
|
-
driven = driven === void 0 ? value : b.bool.or(driven, value);
|
|
768
|
-
}
|
|
769
|
-
return driven;
|
|
770
|
-
}
|
|
771
|
-
};
|
|
772
|
-
//#endregion
|
|
773
|
-
//#region src/unified-ir/compiler/topology.ts
|
|
774
|
-
/** Rails every circuit understands without declaring them. */
|
|
775
|
-
var DEFAULT_RAILS = Object.freeze({
|
|
776
|
-
GND: false,
|
|
777
|
-
VCC: true,
|
|
778
|
-
VDD: true
|
|
779
|
-
});
|
|
780
|
-
/**
|
|
781
|
-
* Analyses the pin-to-pin connections of a circuit.
|
|
782
|
-
*
|
|
783
|
-
* 1. every connection edge joins two nodes (pins and rails);
|
|
784
|
-
* 2. a union-find pass collapses them into electrical nets (connected components);
|
|
785
|
-
* 3. each net gets an id in first-appearance order and is split into drivers,
|
|
786
|
-
* loads and sinks;
|
|
787
|
-
* 4. electrical conflicts (a driver against a rail, two rails of opposite
|
|
788
|
-
* level) become diagnostics instead of silently wrong IR.
|
|
789
|
-
*
|
|
790
|
-
* Several drivers on one net are legal and solved as a wired-OR, which is what
|
|
791
|
-
* a bidirectional pin fighting a switch looks like on a bench.
|
|
792
|
-
*/
|
|
793
|
-
var NetworkTopologyAnalyzer = class {
|
|
794
|
-
rails;
|
|
795
|
-
constructor(options = {}) {
|
|
796
|
-
this.rails = new Map([...Object.entries(DEFAULT_RAILS), ...Object.entries(options.rails ?? {})]);
|
|
797
|
-
}
|
|
798
|
-
/**
|
|
799
|
-
* @throws {UnifiedIRCompilerError} when a connection is malformed, names an
|
|
800
|
-
* unknown device, or names a pin the device does not declare.
|
|
801
|
-
*/
|
|
802
|
-
analyze(connections, pins) {
|
|
803
|
-
if (!Array.isArray(connections)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput.connections must be an array");
|
|
804
|
-
const set = new DisjointSet();
|
|
805
|
-
const pinNodes = /* @__PURE__ */ new Map();
|
|
806
|
-
const railNodes = /* @__PURE__ */ new Map();
|
|
807
|
-
const railNodeIds = /* @__PURE__ */ new Map();
|
|
808
|
-
const connectionOrder = [];
|
|
809
|
-
for (const [index, connection] of connections.entries()) {
|
|
810
|
-
if (connection === null || typeof connection !== "object") throw new UnifiedIRCompilerError("invalid-connection", `Connection[${index}] must be an object with "from" and "to"`);
|
|
811
|
-
const from = this.resolveEndpoint(connection.from, pins, railNodeIds, index);
|
|
812
|
-
const to = this.resolveEndpoint(connection.to, pins, railNodeIds, index);
|
|
813
|
-
set.union(from.nodeId, to.nodeId);
|
|
814
|
-
connectionOrder.push(from.nodeId);
|
|
815
|
-
if (from.kind === "pin") pinNodes.set(from.pin.globalPinId, toConnection(from.pin));
|
|
816
|
-
else railNodes.set(from.nodeId, Object.freeze({
|
|
817
|
-
name: from.name,
|
|
818
|
-
level: from.level
|
|
819
|
-
}));
|
|
820
|
-
if (to.kind === "pin") pinNodes.set(to.pin.globalPinId, toConnection(to.pin));
|
|
821
|
-
else railNodes.set(to.nodeId, Object.freeze({
|
|
822
|
-
name: to.name,
|
|
823
|
-
level: to.level
|
|
824
|
-
}));
|
|
825
|
-
}
|
|
826
|
-
const components = /* @__PURE__ */ new Map();
|
|
827
|
-
const componentOf = (nodeId) => {
|
|
828
|
-
const root = set.find(nodeId);
|
|
829
|
-
let component = components.get(root);
|
|
830
|
-
if (component === void 0) {
|
|
831
|
-
component = {
|
|
832
|
-
pins: [],
|
|
833
|
-
rails: [],
|
|
834
|
-
endpoints: []
|
|
835
|
-
};
|
|
836
|
-
components.set(root, component);
|
|
837
|
-
}
|
|
838
|
-
return component;
|
|
839
|
-
};
|
|
840
|
-
for (const [pinId, connection] of pinNodes) componentOf(pinId).pins.push(connection);
|
|
841
|
-
for (const [nodeId, rail] of railNodes) {
|
|
842
|
-
const component = componentOf(nodeId);
|
|
843
|
-
component.rails.push(rail);
|
|
844
|
-
component.endpoints.push(rail.name);
|
|
845
|
-
}
|
|
846
|
-
const orderedRoots = [];
|
|
847
|
-
const seen = /* @__PURE__ */ new Set();
|
|
848
|
-
for (const nodeId of connectionOrder) {
|
|
849
|
-
const root = set.find(nodeId);
|
|
850
|
-
if (seen.has(root)) continue;
|
|
851
|
-
seen.add(root);
|
|
852
|
-
orderedRoots.push(root);
|
|
853
|
-
}
|
|
854
|
-
const diagnostics = [];
|
|
855
|
-
const nets = [];
|
|
856
|
-
for (const root of orderedRoots) {
|
|
857
|
-
const component = components.get(root);
|
|
858
|
-
if (component === void 0) continue;
|
|
859
|
-
component.pins.sort((left, right) => left.globalPinId - right.globalPinId);
|
|
860
|
-
component.rails.sort((left, right) => left.name.localeCompare(right.name));
|
|
861
|
-
const endpoints = [...component.endpoints, ...component.pins.map((pin) => pin.endpoint)];
|
|
862
|
-
if (component.pins.length === 0) {
|
|
863
|
-
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));
|
|
864
|
-
continue;
|
|
865
|
-
}
|
|
866
|
-
const netId = nets.length;
|
|
867
|
-
const net = this.classify(netId, component.pins, component.rails, diagnostics);
|
|
868
|
-
nets.push(net);
|
|
869
|
-
}
|
|
870
|
-
return Object.freeze({
|
|
871
|
-
nets: Object.freeze(nets),
|
|
872
|
-
diagnostics: Object.freeze(diagnostics)
|
|
873
|
-
});
|
|
874
|
-
}
|
|
875
|
-
classify(netId, pins, rails, diagnostics) {
|
|
876
|
-
const drivers = pins.filter((pin) => pin.role === "driver");
|
|
877
|
-
const loads = pins.filter((pin) => pin.role === "load");
|
|
878
|
-
const sinks = pins.filter((pin) => pin.senses);
|
|
879
|
-
const endpoints = [...rails.map((rail) => rail.name), ...pins.map((pin) => pin.endpoint)];
|
|
880
|
-
const levels = new Set(rails.map((rail) => rail.level));
|
|
881
|
-
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));
|
|
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
|
-
return code === "rail-conflict" ? "rail-conflict" : "power-short";
|
|
946
|
-
}
|
|
947
|
-
function diagnostic(code, severity, message, netId, endpoints) {
|
|
948
|
-
return Object.freeze({
|
|
949
|
-
code,
|
|
950
|
-
severity,
|
|
951
|
-
message,
|
|
952
|
-
netId,
|
|
953
|
-
endpoints: Object.freeze([...endpoints])
|
|
954
|
-
});
|
|
955
|
-
}
|
|
956
|
-
function toConnection(pin) {
|
|
957
|
-
return Object.freeze({
|
|
958
|
-
endpoint: `${pin.deviceId}.${pin.name}`,
|
|
959
|
-
deviceId: pin.deviceId,
|
|
960
|
-
pinName: pin.name,
|
|
961
|
-
globalPinId: pin.globalPinId,
|
|
962
|
-
role: pin.role,
|
|
963
|
-
senses: pin.senses
|
|
964
|
-
});
|
|
965
|
-
}
|
|
966
|
-
/** Union-find over pin ids and rail node ids. */
|
|
967
|
-
var DisjointSet = class {
|
|
968
|
-
parent = /* @__PURE__ */ new Map();
|
|
969
|
-
rank = /* @__PURE__ */ new Map();
|
|
970
|
-
find(id) {
|
|
971
|
-
const parent = this.parent.get(id);
|
|
972
|
-
if (parent === void 0) {
|
|
973
|
-
this.parent.set(id, id);
|
|
974
|
-
this.rank.set(id, 0);
|
|
975
|
-
return id;
|
|
976
|
-
}
|
|
977
|
-
if (parent === id) return id;
|
|
978
|
-
const root = this.find(parent);
|
|
979
|
-
this.parent.set(id, root);
|
|
980
|
-
return root;
|
|
981
|
-
}
|
|
982
|
-
union(left, right) {
|
|
983
|
-
const leftRoot = this.find(left);
|
|
984
|
-
const rightRoot = this.find(right);
|
|
985
|
-
if (leftRoot === rightRoot) return;
|
|
986
|
-
const leftRank = this.rank.get(leftRoot) ?? 0;
|
|
987
|
-
const rightRank = this.rank.get(rightRoot) ?? 0;
|
|
988
|
-
if (leftRank < rightRank) {
|
|
989
|
-
this.parent.set(leftRoot, rightRoot);
|
|
990
|
-
return;
|
|
991
|
-
}
|
|
992
|
-
this.parent.set(rightRoot, leftRoot);
|
|
993
|
-
if (leftRank === rightRank) this.rank.set(leftRoot, leftRank + 1);
|
|
994
|
-
}
|
|
995
|
-
};
|
|
996
|
-
//#endregion
|
|
997
2455
|
//#region src/unified-ir/compiler/index.ts
|
|
998
2456
|
/**
|
|
999
2457
|
* Compiles several devices and their wiring into one unified IR module (U01).
|
|
@@ -1020,37 +2478,34 @@ var DisjointSet = class {
|
|
|
1020
2478
|
*
|
|
1021
2479
|
* The pipeline is: validate the input, allocate the global pin and state
|
|
1022
2480
|
* spaces, analyse the electrical topology, generate one function per device
|
|
1023
|
-
* phase, generate
|
|
2481
|
+
* phase, generate the resistive network solver and main loop, then validate the
|
|
1024
2482
|
* resulting module with `validateIR`.
|
|
1025
2483
|
*
|
|
1026
2484
|
* @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
|
|
1027
2485
|
* pins, electrical conflicts, or when the generated module fails validation.
|
|
1028
2486
|
*/
|
|
1029
2487
|
function compileCircuit(input, options = {}) {
|
|
1030
|
-
const
|
|
2488
|
+
const validated = validateInput(input);
|
|
2489
|
+
const { connections } = validated;
|
|
1031
2490
|
const resolvedOptions = validateOptions(options);
|
|
1032
2491
|
const names = resolveEntryNames(resolvedOptions);
|
|
1033
2492
|
const module = createIRModule();
|
|
1034
|
-
const allocation = new GlobalResourceAllocator(module).allocate(devices);
|
|
1035
|
-
const
|
|
1036
|
-
|
|
2493
|
+
const allocation = new GlobalResourceAllocator(module).allocate(validated.devices);
|
|
2494
|
+
const electrical = prepareElectricalCompilation(module, validated.devices, connections, resolvedOptions);
|
|
2495
|
+
const devices = electrical.devices;
|
|
1037
2496
|
const generator = new DeviceIRGenerator({
|
|
1038
2497
|
module,
|
|
1039
|
-
memory: allocation.memory,
|
|
1040
2498
|
pins: allocation.pins,
|
|
1041
|
-
states: allocation.states
|
|
2499
|
+
states: allocation.states,
|
|
2500
|
+
electrical: electrical.operations
|
|
1042
2501
|
});
|
|
1043
2502
|
const generated = devices.map((device) => generator.generate(device));
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
memory: allocation.memory
|
|
1047
|
-
}).generate(netlist);
|
|
1048
|
-
assertNoNameCollisions(devices, solvers.map((solver) => solver.name), names);
|
|
1049
|
-
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);
|
|
1050
2505
|
const validation = createModuleValidation(module, devices.flatMap((device) => device.description.updateResources ?? []));
|
|
1051
2506
|
if (resolvedOptions.validate !== false) validateModule(module, validation);
|
|
1052
2507
|
const deviceMap = new Map(generated.map((device) => [device.metadata.deviceId, device.metadata]));
|
|
1053
|
-
|
|
2508
|
+
const compiled = Object.freeze({
|
|
1054
2509
|
module,
|
|
1055
2510
|
entryPoints: Object.freeze({
|
|
1056
2511
|
tick: loop.names.tick,
|
|
@@ -1062,16 +2517,17 @@ function compileCircuit(input, options = {}) {
|
|
|
1062
2517
|
batch: loop.batch
|
|
1063
2518
|
})
|
|
1064
2519
|
}),
|
|
2520
|
+
progress: loop.progress,
|
|
1065
2521
|
pinMap: allocation.pins.pins,
|
|
1066
2522
|
deviceMap,
|
|
1067
|
-
netlist,
|
|
1068
2523
|
pins: allocation.pins,
|
|
1069
2524
|
states: allocation.states,
|
|
1070
|
-
memory: allocation.memory,
|
|
1071
2525
|
validation,
|
|
1072
2526
|
executionOrder: loop.order,
|
|
1073
2527
|
functions: Object.freeze(module.functions.map((fn) => fn.name))
|
|
1074
2528
|
});
|
|
2529
|
+
retainElectricalCompilation(compiled, electrical);
|
|
2530
|
+
return compiled;
|
|
1075
2531
|
}
|
|
1076
2532
|
function validateInput(input) {
|
|
1077
2533
|
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new UnifiedIRCompilerError("invalid-input", "CircuitCompilationInput must be an object with devices and connections");
|
|
@@ -1087,10 +2543,6 @@ function validateOptions(options) {
|
|
|
1087
2543
|
if (options === null || typeof options !== "object" || Array.isArray(options)) throw new UnifiedIRCompilerError("invalid-input", "Compile options must be an object");
|
|
1088
2544
|
const resolved = options;
|
|
1089
2545
|
if (resolved.validate !== void 0 && typeof resolved.validate !== "boolean") throw new UnifiedIRCompilerError("invalid-input", "options.validate must be a boolean");
|
|
1090
|
-
if (resolved.rails !== void 0) {
|
|
1091
|
-
if (resolved.rails === null || typeof resolved.rails !== "object" || Array.isArray(resolved.rails)) throw new UnifiedIRCompilerError("invalid-input", "options.rails must be a plain object");
|
|
1092
|
-
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`);
|
|
1093
|
-
}
|
|
1094
2546
|
return resolved;
|
|
1095
2547
|
}
|
|
1096
2548
|
function resolveEntryNames(options) {
|
|
@@ -1103,12 +2555,11 @@ function resolveEntryNames(options) {
|
|
|
1103
2555
|
if (new Set(Object.values(names)).size !== 3) throw new UnifiedIRCompilerError("invalid-input", `Entry point names must be distinct: ${JSON.stringify(names)}`);
|
|
1104
2556
|
return Object.freeze(names);
|
|
1105
2557
|
}
|
|
1106
|
-
function assertNoNameCollisions(devices,
|
|
2558
|
+
function assertNoNameCollisions(devices, names) {
|
|
1107
2559
|
const reserved = /* @__PURE__ */ new Set([
|
|
1108
2560
|
names.tick,
|
|
1109
2561
|
names.initialize,
|
|
1110
|
-
names.batch
|
|
1111
|
-
...solverNames
|
|
2562
|
+
names.batch
|
|
1112
2563
|
]);
|
|
1113
2564
|
for (const device of devices) for (const phase of [
|
|
1114
2565
|
"initialize",
|
|
@@ -1149,6 +2600,8 @@ var CircuitError = class extends Error {
|
|
|
1149
2600
|
};
|
|
1150
2601
|
//#endregion
|
|
1151
2602
|
//#region src/unified-ir/runtime/accessors.ts
|
|
2603
|
+
var bridges = /* @__PURE__ */ new WeakMap();
|
|
2604
|
+
var deviceBridgeOf = (accessor) => bridges.get(accessor) ?? accessor;
|
|
1152
2605
|
/**
|
|
1153
2606
|
* Builds one accessor per compiled device.
|
|
1154
2607
|
*
|
|
@@ -1160,22 +2613,26 @@ function buildDeviceAccessors(context) {
|
|
|
1160
2613
|
const entries = [];
|
|
1161
2614
|
for (const device of context.compiled.deviceMap.values()) {
|
|
1162
2615
|
const base = createBaseAccessor(context, device);
|
|
1163
|
-
if (device.accessor !== void 0)
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
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]);
|
|
1171
2627
|
}
|
|
1172
2628
|
return Object.freeze(Object.fromEntries(entries));
|
|
1173
2629
|
}
|
|
1174
2630
|
function createBaseAccessor(context, device) {
|
|
1175
2631
|
const { jit } = context;
|
|
1176
2632
|
const storage = jit.storage;
|
|
1177
|
-
const
|
|
2633
|
+
const electrical = electricalCompilationOf(context.compiled);
|
|
1178
2634
|
const resolved = context.compiled.pins.devices.get(device.deviceId)?.resolved;
|
|
2635
|
+
const entries = new Set(device.entries);
|
|
1179
2636
|
const accessor = {
|
|
1180
2637
|
deviceId: device.deviceId,
|
|
1181
2638
|
type: device.type,
|
|
@@ -1183,18 +2640,8 @@ function createBaseAccessor(context, device) {
|
|
|
1183
2640
|
stateNames: Object.freeze([...device.states.keys()]),
|
|
1184
2641
|
readPin(pinName) {
|
|
1185
2642
|
context.assertActive();
|
|
1186
|
-
|
|
1187
|
-
return storage.loadArray(
|
|
1188
|
-
},
|
|
1189
|
-
writePin(pinName, value) {
|
|
1190
|
-
context.assertActive();
|
|
1191
|
-
const pin = pinOf(device, resolved, pinName);
|
|
1192
|
-
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`, {
|
|
1193
|
-
deviceId: device.deviceId,
|
|
1194
|
-
pinName
|
|
1195
|
-
});
|
|
1196
|
-
assertBoolean(device.deviceId, pinName, value);
|
|
1197
|
-
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;
|
|
1198
2645
|
},
|
|
1199
2646
|
getState(name) {
|
|
1200
2647
|
context.assertActive();
|
|
@@ -1214,7 +2661,71 @@ function createBaseAccessor(context, device) {
|
|
|
1214
2661
|
cause
|
|
1215
2662
|
});
|
|
1216
2663
|
}
|
|
1217
|
-
}
|
|
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
|
+
} }
|
|
1218
2729
|
};
|
|
1219
2730
|
return Object.freeze(accessor);
|
|
1220
2731
|
}
|
|
@@ -1236,12 +2747,6 @@ function stateOf(device, name) {
|
|
|
1236
2747
|
});
|
|
1237
2748
|
return slot;
|
|
1238
2749
|
}
|
|
1239
|
-
function assertBoolean(deviceId, pinName, value) {
|
|
1240
|
-
if (typeof value !== "boolean") throw new CircuitError("invalid-state-value", `Pin "${deviceId}.${pinName}" needs a boolean level, received ${typeof value}`, {
|
|
1241
|
-
deviceId,
|
|
1242
|
-
pinName
|
|
1243
|
-
});
|
|
1244
|
-
}
|
|
1245
2750
|
/**
|
|
1246
2751
|
* Validates a host-written state value against the declared scalar type.
|
|
1247
2752
|
* Range checks stay in storage, which owns the encoding.
|
|
@@ -1304,7 +2809,6 @@ var DEFAULT_INSTANCE_ID = "unified-circuit";
|
|
|
1304
2809
|
* expect(circuit.tickCount).toBe(1_000_000n);
|
|
1305
2810
|
*
|
|
1306
2811
|
* circuit.reset();
|
|
1307
|
-
* circuit.setPin('drive1.PA0', true); // host drives the pin
|
|
1308
2812
|
* circuit.step();
|
|
1309
2813
|
* expect(circuit.devices.sink1.getState('lamp')).toBe(true);
|
|
1310
2814
|
* ```
|
|
@@ -1355,6 +2859,9 @@ var Circuit = class Circuit {
|
|
|
1355
2859
|
const circuit = new Circuit(compiled, jit, resolved.instanceId, buildDeviceAccessors({
|
|
1356
2860
|
compiled,
|
|
1357
2861
|
jit,
|
|
2862
|
+
execute: (entry, args) => {
|
|
2863
|
+
jit.execute(entry, args, circuit.#context);
|
|
2864
|
+
},
|
|
1358
2865
|
assertActive: () => {
|
|
1359
2866
|
circuit.#assertActive();
|
|
1360
2867
|
},
|
|
@@ -1372,29 +2879,38 @@ var Circuit = class Circuit {
|
|
|
1372
2879
|
/**
|
|
1373
2880
|
* Runs `count` ticks inside one generated loop — the throughput path.
|
|
1374
2881
|
*
|
|
1375
|
-
* The whole batch is one engine call
|
|
1376
|
-
*
|
|
2882
|
+
* The whole batch is one engine call. The clock advances by completed ticks,
|
|
2883
|
+
* including the completed prefix of a failed batch.
|
|
1377
2884
|
*
|
|
1378
2885
|
* @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
|
|
1379
2886
|
*/
|
|
1380
|
-
runBatch(count) {
|
|
2887
|
+
runBatch(count, dt = 1) {
|
|
1381
2888
|
this.#assertActive();
|
|
1382
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);
|
|
1383
2891
|
if (count === 0) return;
|
|
1384
2892
|
this.#context.virtualTime = this.#virtualTime;
|
|
1385
|
-
this.#jit.
|
|
1386
|
-
|
|
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
|
+
}
|
|
1387
2899
|
}
|
|
1388
2900
|
/**
|
|
1389
2901
|
* Advances exactly one tick — the debugging path.
|
|
1390
2902
|
*
|
|
1391
2903
|
* Every call is one engine entry, so prefer `runBatch` for throughput.
|
|
1392
2904
|
*/
|
|
1393
|
-
step() {
|
|
2905
|
+
step(dt = 1) {
|
|
1394
2906
|
this.#assertActive();
|
|
2907
|
+
this.#setTimeStep(dt);
|
|
1395
2908
|
this.#context.virtualTime = this.#virtualTime;
|
|
1396
|
-
|
|
1397
|
-
|
|
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
|
+
}
|
|
1398
2914
|
}
|
|
1399
2915
|
/**
|
|
1400
2916
|
* Restores every memory to its declared initial value, re-runs `initialize`
|
|
@@ -1430,34 +2946,133 @@ var Circuit = class Circuit {
|
|
|
1430
2946
|
/**
|
|
1431
2947
|
* Reads the level one pin observes.
|
|
1432
2948
|
*
|
|
1433
|
-
*
|
|
1434
|
-
*
|
|
1435
|
-
* `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.
|
|
1436
2951
|
*
|
|
1437
2952
|
* @throws {CircuitError} with code `pin-not-found`.
|
|
1438
2953
|
*/
|
|
1439
2954
|
getPin(pinName) {
|
|
1440
2955
|
this.#assertActive();
|
|
1441
|
-
|
|
2956
|
+
this.#pinRuntime(pinName);
|
|
1442
2957
|
const storage = this.#jit.storage;
|
|
1443
|
-
|
|
1444
|
-
|
|
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
|
+
}
|
|
1445
2965
|
}
|
|
1446
|
-
/**
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
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() {
|
|
1456
3029
|
this.#assertActive();
|
|
1457
|
-
const
|
|
1458
|
-
|
|
1459
|
-
const
|
|
1460
|
-
|
|
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
|
+
};
|
|
1461
3076
|
}
|
|
1462
3077
|
/** Number of ticks completed since creation or the last `reset()`. */
|
|
1463
3078
|
get tickCount() {
|
|
@@ -1491,10 +3106,19 @@ var Circuit = class Circuit {
|
|
|
1491
3106
|
#assertActive() {
|
|
1492
3107
|
if (this.#disposed) throw new CircuitError("disposed", "Circuit has been disposed; create a new circuit to keep simulating");
|
|
1493
3108
|
}
|
|
1494
|
-
#
|
|
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) {
|
|
1495
3118
|
this.#tickCount += BigInt(count);
|
|
1496
|
-
const
|
|
1497
|
-
|
|
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));
|
|
1498
3122
|
}
|
|
1499
3123
|
#pinRuntime(pinName) {
|
|
1500
3124
|
const pin = this.#pins.get(pinName);
|
|
@@ -1505,11 +3129,7 @@ var Circuit = class Circuit {
|
|
|
1505
3129
|
/** Resolves every pin of the global address space into its runtime view. */
|
|
1506
3130
|
function pinRuntimeOf(compiled) {
|
|
1507
3131
|
const pins = /* @__PURE__ */ new Map();
|
|
1508
|
-
for (const [deviceId, allocation] of compiled.pins.devices) for (const [pinName, pin] of allocation.resolved) pins.set(`${deviceId}.${pinName}`, Object.freeze({
|
|
1509
|
-
globalPinId: pin.globalPinId,
|
|
1510
|
-
role: pin.role,
|
|
1511
|
-
senses: pin.senses
|
|
1512
|
-
}));
|
|
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 }));
|
|
1513
3133
|
return pins;
|
|
1514
3134
|
}
|
|
1515
3135
|
/**
|
|
@@ -1559,7 +3179,9 @@ function createEngine(compiled, options) {
|
|
|
1559
3179
|
function compileOptionsOf(options) {
|
|
1560
3180
|
return {
|
|
1561
3181
|
validate: options.validateIR,
|
|
1562
|
-
...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 }
|
|
1563
3185
|
};
|
|
1564
3186
|
}
|
|
1565
3187
|
function resolveOptions(options) {
|
|
@@ -1572,17 +3194,18 @@ function resolveOptions(options) {
|
|
|
1572
3194
|
if (candidate.jit !== void 0) {
|
|
1573
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");
|
|
1574
3196
|
}
|
|
1575
|
-
let rails;
|
|
1576
3197
|
if (candidate.electrical !== void 0) {
|
|
1577
3198
|
const electrical = candidate.electrical;
|
|
1578
3199
|
if (electrical === null || typeof electrical !== "object" || Array.isArray(electrical)) throw new CircuitError("invalid-options", "electrical must be a plain object");
|
|
1579
|
-
rails
|
|
3200
|
+
if ("rails" in electrical) throw new CircuitError("invalid-options", "Boolean rails are unsupported; declare explicit voltage sources");
|
|
1580
3201
|
}
|
|
1581
3202
|
return Object.freeze({
|
|
1582
3203
|
engine,
|
|
1583
3204
|
jit: candidate.jit,
|
|
1584
3205
|
validateIR: candidate.validateIR ?? true,
|
|
1585
|
-
|
|
3206
|
+
sources: candidate.electrical?.sources,
|
|
3207
|
+
interpretation: candidate.electrical?.interpretation,
|
|
3208
|
+
floatingSeed: candidate.electrical?.floatingSeed,
|
|
1586
3209
|
instanceId: candidate.instanceId ?? DEFAULT_INSTANCE_ID
|
|
1587
3210
|
});
|
|
1588
3211
|
}
|
|
@@ -1638,6 +3261,7 @@ async function createSchematicCircuit(schematic, options) {
|
|
|
1638
3261
|
id: deviceId,
|
|
1639
3262
|
type: binding.type,
|
|
1640
3263
|
description: binding.description,
|
|
3264
|
+
...symbol.properties === void 0 ? {} : { properties: symbol.properties },
|
|
1641
3265
|
...binding.config === void 0 ? {} : { config: binding.config }
|
|
1642
3266
|
});
|
|
1643
3267
|
if (reference !== void 0) bindings.push({
|
|
@@ -1652,7 +3276,7 @@ async function createSchematicCircuit(schematic, options) {
|
|
|
1652
3276
|
...tolerance === void 0 ? {} : { tolerance }
|
|
1653
3277
|
});
|
|
1654
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");
|
|
1655
|
-
const railNames = /* @__PURE__ */ new Set([
|
|
3279
|
+
const railNames = /* @__PURE__ */ new Set(["GND", ...Object.keys(options.electrical?.sources ?? {})]);
|
|
1656
3280
|
const connections = [];
|
|
1657
3281
|
for (const net of topology.nets) {
|
|
1658
3282
|
const endpoints = [];
|
|
@@ -1721,7 +3345,8 @@ var DEFAULT_STEP_PS = 1e4;
|
|
|
1721
3345
|
* `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
|
|
1722
3346
|
*/
|
|
1723
3347
|
function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schematic, topics = [], stepPs = DEFAULT_STEP_PS, deliver }) {
|
|
1724
|
-
|
|
3348
|
+
if (!Number.isSafeInteger(stepPs) || stepPs <= 0) throw new TypeError("stepPs must be a positive safe integer");
|
|
3349
|
+
const simTime = () => Number(circuit.tickCount) * stepPs;
|
|
1725
3350
|
return {
|
|
1726
3351
|
async loadSchematic() {},
|
|
1727
3352
|
async reset() {
|
|
@@ -1729,10 +3354,11 @@ function createCircuitDeviceSimulationHost({ circuit, ownsCircuit = true, schema
|
|
|
1729
3354
|
},
|
|
1730
3355
|
async tick(dt) {
|
|
1731
3356
|
if (!Number.isSafeInteger(dt) || dt <= 0) throw new TypeError(`DeviceSimulationHost.tick expects a positive integer dt, received ${dt}`);
|
|
1732
|
-
circuit.
|
|
3357
|
+
const before = circuit.tickCount;
|
|
3358
|
+
circuit.runBatch(1, stepPs);
|
|
1733
3359
|
return {
|
|
1734
3360
|
simTime: simTime(),
|
|
1735
|
-
executed:
|
|
3361
|
+
executed: Number(circuit.tickCount - before)
|
|
1736
3362
|
};
|
|
1737
3363
|
},
|
|
1738
3364
|
async deliver(target, payload) {
|
|
@@ -1813,7 +3439,8 @@ function buildRuntime(circuit, schematic, bindings, resolveDevice) {
|
|
|
1813
3439
|
symbol: binding.symbolId,
|
|
1814
3440
|
designator,
|
|
1815
3441
|
binding: deviceBinding,
|
|
1816
|
-
accessor
|
|
3442
|
+
accessor,
|
|
3443
|
+
bridge: deviceBridgeOf(accessor)
|
|
1817
3444
|
};
|
|
1818
3445
|
devices.push(device);
|
|
1819
3446
|
for (const topic of deviceBinding.topics ?? []) {
|
|
@@ -1858,23 +3485,43 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1858
3485
|
let runtime;
|
|
1859
3486
|
let simTimePs = 0;
|
|
1860
3487
|
let disposed = false;
|
|
1861
|
-
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}`);
|
|
1862
3493
|
if (!publishes.hasListeners) return;
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
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
|
+
}
|
|
1878
3525
|
}
|
|
1879
3526
|
};
|
|
1880
3527
|
const clearRuntime = () => {
|
|
@@ -1896,6 +3543,7 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1896
3543
|
const compiled = await createSchematicCircuit(schematic, {
|
|
1897
3544
|
...symbolProvider === void 0 ? {} : { devices: symbolProvider },
|
|
1898
3545
|
resolveDevice,
|
|
3546
|
+
...options.electrical === void 0 ? {} : { electrical: options.electrical },
|
|
1899
3547
|
instanceId: INSTANCE_ID
|
|
1900
3548
|
});
|
|
1901
3549
|
const next = buildRuntime(compiled.circuit, schematic, compiled.bindings, resolveDevice);
|
|
@@ -1927,16 +3575,39 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1927
3575
|
};
|
|
1928
3576
|
}
|
|
1929
3577
|
const queued = pending.splice(0, pending.length);
|
|
1930
|
-
|
|
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 {
|
|
1931
3587
|
if (delivery.device.binding.deliver === void 0) throw new TypeError(`${delivery.device.binding.type} has no writable topic ${JSON.stringify(delivery.port)}`);
|
|
1932
3588
|
delivery.device.binding.deliver(delivery.device.accessor, delivery.port, delivery.payload);
|
|
1933
3589
|
}
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
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);
|
|
1937
3607
|
return {
|
|
1938
3608
|
simTime: simTimePs,
|
|
1939
|
-
executed:
|
|
3609
|
+
executed: Number(active.circuit.tickCount - before),
|
|
3610
|
+
...diagnostics.length === 0 ? {} : { diagnostics: Object.freeze(diagnostics) }
|
|
1940
3611
|
};
|
|
1941
3612
|
},
|
|
1942
3613
|
async deliver(target, payload) {
|
|
@@ -1947,7 +3618,7 @@ function createSchematicDeviceSimulationHost(options) {
|
|
|
1947
3618
|
if (binding === void 0) throw new Error(`Unknown device input ${target.symbol}.${target.port}`);
|
|
1948
3619
|
if (!payloadMatches(binding.topic.type, payload)) throw new TypeError(`${target.symbol}.${target.port} expects a ${binding.topic.type} payload`);
|
|
1949
3620
|
const device = binding.device;
|
|
1950
|
-
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)}`);
|
|
1951
3622
|
pending.push({
|
|
1952
3623
|
device,
|
|
1953
3624
|
port: target.port,
|
|
@@ -2001,6 +3672,7 @@ function startDeviceSimulationHostGuest(port, options = {}) {
|
|
|
2001
3672
|
return bytes;
|
|
2002
3673
|
},
|
|
2003
3674
|
...devices === void 0 ? {} : { devices },
|
|
3675
|
+
...options.electrical === void 0 ? {} : { electrical: options.electrical },
|
|
2004
3676
|
resolveDevice: resolveDevice ?? (() => void 0)
|
|
2005
3677
|
});
|
|
2006
3678
|
let prepared;
|
|
@@ -2076,6 +3748,6 @@ function startDeviceSimulationHostGuest(port, options = {}) {
|
|
|
2076
3748
|
};
|
|
2077
3749
|
}
|
|
2078
3750
|
//#endregion
|
|
2079
|
-
export { Circuit, CircuitError,
|
|
3751
|
+
export { Circuit, CircuitError, DEVICE_PIN_STRIDE, ElectricalDefinitionError, PIN_MODE, UNIFIED_PIN_CAPACITY, UnifiedIRCompilerError, compileCircuit, createCircuitDeviceSimulationHost, createCircuitFromSchematic, createModuleValidation, createSchematicCircuit, createSchematicDeviceSimulationHost, startDeviceSimulationHostGuest };
|
|
2080
3752
|
|
|
2081
3753
|
//# sourceMappingURL=index.js.map
|