/** * SimEngine — continuous Modified Nodal Analysis simulator. * * Accepts a circuit, builds a net list, and advances state one dt at a time. * State (capacitor voltages, inductor currents) persists across steps so * the simulation behaves like physical hardware: connect a cap and watch * it charge; disconnect power and the charge stays. * * Topology changes (load()) try to preserve element state by: * 1. Component-ID match (primary): same component ID → same state. * 2. Net-pair fingerprint match (fallback): if a component's two pins * connect to the same pair of nets as an old component of the same * kind (identified by the full sorted pin-set of those nets), carry * the old state. Handles re-wires that preserve connectivity but * generate new component IDs. * 3. Zero-state initialization: truly new capacitors and inductors start * unenergized. Oscillator start-up must come from the oscillator model's * powered state transition, never hidden energy in unrelated passives. * * R2 — non-linear elements (diode, LED): each step runs Newton-Raphson * to convergence. Linear stamps (R, V, C, L, switch) are re-applied * each iteration (cheap) alongside the non-linear companion stamps * linearised about the last-iter voltage guess. * * R3 — adaptive step size and state snapshots: saveState()/restoreState() * let the worker roll back a rejected step; coldLoad() resets all element * state for a hard restart. */ import { type Net } from "./graph.js"; import { type BatteryDynamicState, type BatteryPhysicsProfile } from "../battery-physics.js"; import { type ThermalDeviceProfile, type ThermalDeviceState } from "../thermal-physics.js"; import type { DisplayInfo, Hcsr04EchoEvent } from "../messages.js"; import type { ElectricalSpecs } from "../../circuit/types.js"; import { type RamKind } from "../../circuit/types.js"; import { type AcDeviceContext } from "./device-registry.js"; export type { Net }; export declare const NODE_RSHUNT_G = 1e-12; export declare const ISOLATED_SECTION_ANCHOR_G = 1; export declare const N_DIODE = 1; export declare const N_LED = 2; export declare const IRATED_LED = 0.02; export declare const RESISTOR_DAMAGE_THRESHOLD = 1; export declare const FUSE_I2T_THRESHOLD = 0.3; export declare const LED_DAMAGE_THRESHOLD = 24; /** A missing, invalid, or negative series loss keeps the historical ideal model. */ export declare function seriesLossResistance(value: unknown): number; /** A missing, invalid, or non-positive parallel loss disables that branch. */ export declare function parallelLossResistance(value: unknown): number; export declare function vCritFor(Is: number, VtN: number): number; /** Physical junction thermal voltage kT/q. */ export declare function thermalVoltage(tempC: number): number; /** Empirical rated-current forward drop around the 25 °C catalog value. */ export declare function junctionForwardVoltage(vfAt25C: number, tempC: number, tempco?: number): number; /** * SPICE-style silicon saturation-current temperature scaling. This is needed * in addition to Vt(T): holding Is constant makes a BJT's Vbe rise with heat, * the opposite of real junction behaviour. */ export declare function saturationCurrentAtTemperature(isAt25C: number, tempC: number, emission?: number): number; export interface SimCircuit { id?: string; components: Array<{ id: string; kind: string; /** Exact catalog/model variant; optional only for legacy/imported circuits. */ catalogUid?: string; position?: { x: number; y: number; }; rotation?: number; pins: Array<{ id: string; }>; params: Record; }>; wires: Array<{ from_component: string; from_pin: string; to_component: string; to_pin: string; }>; environment?: { temperatureC?: number; lux?: number; }; } type SimComponent = SimCircuit["components"][number]; export interface NE555EngineState { outHigh: boolean; } /** * W6.1 — relay persistent state, carried across load() by component ID. * * iCoil: committed coil current from the previous timestep (A). The RL companion * uses i_prev to inject the history current source that carries inductive memory. * On the first step i_prev=0 (no prior current) — acceptable, the coil charges * up in a few time constants. * * energized: committed contact state from the previous timestep. Stamped at the * start of each Newton inner loop (committed-state pattern — never re-decided * from xGuess to prevent chattering). Updated post-solve using hysteresis on * the coil voltage |v_ab|. */ export interface RelayEngineState { iCoil: number; energized: boolean; } /** * W7.1 — DC motor persistent state, carried across load() by component ID. * * iWinding: committed winding current from the previous timestep (A). * The RL+back-EMF companion uses i_prev to inject the history current source * that carries inductive memory. Zero on first step (motor at rest). * * omega: committed rotor angular velocity from the previous timestep (rad/s). * Used only as a back-EMF driver (Vbemf = Ke * omega) and as a readout. * Decided/updated POST-SOLVE (committed-state pattern) and held constant * through the Newton inner loop — never re-read from within-iteration xGuess * to prevent back-EMF chattering during convergence. * * NOTE: omega is a readout and back-EMF driver ONLY — no rotor-position physics, * no torque coupling to external mechanical loads, no inertia-to-circuit feedback. * The motor is an electrical load with a speed-dependent back-EMF. */ export interface MotorEngineState { iWinding: number; omega: number; } /** * W7.2 — Hobby servo persistent state, carried across load() by component ID. * * PWM decode: a directly connected Arduino/Pico output uses its ordered, * cycle-timestamped PinEvents so pulse width is independent of the outer * electrical step. Other drivers retain post-solve threshold sampling at * HIGH ≥ 2.0 V relative to the gnd pin: * - Rising edge (0→1): record riseT = edge time. * - Falling edge (1→0): compute pulseMs = (edge time − riseT) × 1000, then * targetAngle = minAngle + * (pulseMs − minPulseMs) / (maxPulseMs − minPulseMs) * × (maxAngle − minAngle). * The target is clamped to [minAngle, maxAngle] via the pulseMs clamp. * * The shaft then travels toward the last decoded target at a finite no-load * speed scaled by the solved supply voltage. The target holds between pulses; * loss of signal therefore does not teleport or reset the shaft. * * lastSig: committed signal level from the previous step (0 or 1). * riseT: simTime of the last observed rising edge (s). * pulseMs: last measured HIGH-time in ms (updated on each falling edge). * targetAngle: last commanded angle (deg). Holds between complete pulses. * angle: actual rate-limited shaft angle (deg). * velocity: last accepted shaft velocity (deg/s). * powered/supplyVoltage: committed supply state used by telemetry and load. */ export interface ServoEngineState { lastSig: number; riseT: number; pulseMs: number; targetAngle: number; angle: number; velocity: number; moving: boolean; powered: boolean; supplyVoltage: number; /** Supply resistance that was physically stamped for the accepted step. */ loadResistance: number; } export declare function defaultServoState(): ServoEngineState; /** * W7.2 — Bipolar stepper motor persistent state, carried across load() by component ID. * * TWO RL Norton companions (one per coil) use iPrev values to carry inductive memory: * iA: committed current in coil A (a1→a2), A. Used as i_prev in the Norton companion. * iB: committed current in coil B (b1→b2), A. Used as i_prev in the Norton companion. * * Step detection (committed post-solve): * signA = sign(iA) with ±1 mA deadband → +1 / −1 / 0. * signB = sign(iB) with ±1 mA deadband → +1 / −1 / 0. * Phase lookup (signA, signB) → 0..3 per the full-step Gray-code table: * phase 0: (+1, +1) * phase 1: (−1, +1) * phase 2: (−1, −1) * phase 3: (+1, −1) * Sequential advance +1 (mod 4) → position++; −1 (mod 4) → position--. * No change or jump > 1 → hold (non-sequential drive = half-step or fault; not counted). * * phase: current (committed) phase index (0-3), or -1 when coils are unenergised / deadband. * position: signed step count. angle = position × 360 / stepsPerRev (mod 360). */ export interface StepperEngineState { iA: number; iB: number; phase: number; lastKnownPhase: number; position: number; } /** * S18b — HC-SR04 ultrasonic distance sensor persistent state, carried across * load() by component ID (mirrors ServoEngineState exactly — see its comment * above for the general pattern this follows). * * TRIG detection is committed-state edge detection, same philosophy as the * servo PWM decoder: `trigLevel` is the last-committed TRIG level. Edges are * only consulted while `phase === "idle"` — a rising edge (0→1) arms the * sensor; the matching falling edge (1→0) schedules the echo. Re-triggering * while `phase` is "pending"/"active" is ignored (real module behaviour): * `trigLevel` still tracks the net so a genuine post-echo edge is seen * cleanly, but phase transitions are gated on `phase === "idle"`. * * TRIG edge timestamps come from one of two paths (see the hcsr04 * commitState handler in devices/electromech-audio.ts): * (a) an MCU pin drives the TRIG net directly — cycle-timestamped PinEvents * give the exact edge time regardless of the outer step h (a 10 µs * digitalWrite pulse would otherwise vanish between once-per-step * samples). * (b) otherwise — committed net-voltage threshold sampling (2.0 V), timed * at `this.simTime` (the step-start value, servo precedent): acceptable * because non-MCU TRIG sources hold the level for at least one full step. * * Schedule (armed on TRIG rise, computed on TRIG fall): * echoRiseAt = tFall + 250 µs * echoFallAt = echoRiseAt + (58.0 µs/cm × distanceCm), or +38 ms if noEcho * (out-of-range timeout). * `nextScheduledEventTime()` returns the earliest of these across all * hcsr04s so sim.worker.ts can clamp the step size to land exactly on them * (event-aligned stepping — see that method's comment). * * vccV / vccOk: VCC-GND committed from the LAST step (never the live Newton * guess — the ECHO push-pull Norton stamp and the whole TRIG/echo state * machine read this so the drive decision cannot flicker mid-iteration). * Below 3.0 V the part is inert: the stamp skips the ECHO drive entirely * (real dropout behaviour — a dead chip cannot actively drive its output) * and the commit handler force-resets phase/schedule to idle every step. * echoOut: committed ECHO drive level (0/1) — a real HC-SR04 drives ECHO * push-pull continuously while powered (0 when idle, not hi-Z). * * pendingEchoEvent: a queued micro:bit ECHO-bridge event, set the instant an * echo bridged to a micro:bit edge pin is scheduled (see messages.ts * Hcsr04EchoEvent) and drained by takeHcsr04EchoEvents(). Deliberately part * of THIS map entry (not a free-standing queue): it must live inside the * saveState()/restoreState() snapshot so a rolled-back Newton step (failed * convergence) correctly un-queues a spurious event too. */ export interface Hcsr04EngineState { trigLevel: 0 | 1; phase: "idle" | "armed" | "pending" | "active"; echoRiseAt: number; echoFallAt: number; echoOut: 0 | 1; vccV: number; pendingEchoEvent: Hcsr04EchoEvent | null; } export declare function defaultHcsr04State(): Hcsr04EngineState; /** * W8.2 — HD44780 16x2 character LCD persistent state, carried across load() by component ID. * * DDRAM holds the character codes for both lines (length 0x68 = 104 bytes). * Address map: 0x00-0x27 = line 1 (40 chars, only first 16 visible), 0x40-0x67 = line 2. * * 4-bit vs 8-bit mode is detected via the function-set command DL bit (DL=0 → 4-bit). * In 4-bit mode a full byte takes two E-strobe pulses (high nibble first via D4-D7). * * RW pin is sampled but read-back is not supported — tie RW to GND in all real circuits. * CGRAM custom character data (codes 0x00-0x07) is not rendered in v1; writes go to the * address counter but are discarded. Cursor/display-shift command (0x10-0x1F) is accepted * but not rendered in v1. */ export interface Hd44780State { ddram: number[]; addr: number; fourBit: boolean; nibblePhase: 0 | 1; hiNib: number; displayOn: boolean; increment: boolean; cgram: boolean; twoLine: boolean; lastE: 0 | 1; lastRS: 0 | 1; lastData: number[]; } export declare function defaultHd44780State(): Hd44780State; export declare const DIGITAL_DELAY_PREFIX = "delay:"; export declare function eepromImageBytes(size: number, contentsB64: string): Uint8Array; export interface EepromState { bytes: Uint8Array; contentsHash: string; lastWeHigh: boolean; lastCeHigh: boolean; writeCompletesAt: number | null; pendingAddr: number | null; pendingByte: number | null; pollReads: number; /** /OE and /CE were both low at the last committed step; a read cycle is the false-to-true edge. */ prevReadCycle: boolean; sdpEnabled: boolean; sdpUnlocked: boolean; sdpStep: 0 | 1 | 2 | 3; dirty: boolean; } /** * PTC fuse session state. * * The PTC uses a stress accumulator that is NOT part of the latched failure * framework: it does not latch permanently. Instead: * tripped: whether the device is currently in high-R state. * tripStress: accumulated excess (I² − I_hold²)·h above hold current. * recoveryTime: accumulated sim-seconds at low current while tripped. * * State persists across load() by component ID, mirroring ne555s. * resetFailures() clears trip state so the toolbar "Clear failures" button * resets everything the user expects to reset — both the latched failure * framework AND the PTC. */ export interface PtcState { tripped: boolean; tripStress: number; recoveryTime: number; } export interface BatteryRuntimeState extends BatteryDynamicState { /** Authored initial SoC used to distinguish a user reset from runtime drain. */ authoredCharge: number; /** Changing exact battery identity resets incompatible chemistry state. */ catalogUid: string | null; } export interface BatteryRuntimeReadout { profileId: string; label: string; soc: number; openCircuitVoltageV: number; internalResistanceOhm: number; remainingCapacityCoulombs: number; dischargedCoulombs: number; rejectedRechargeCoulombs: number; modelTemperatureC: number; temperatureWasClamped: boolean; } export interface ThermalRuntimeState extends ThermalDeviceState { catalogUid: string; profileId: string; dissipatedPowerW: number; targetTemperatureC: number; allowedPowerW: number; withinContinuousLimits: boolean; warnings: string[]; } export interface ThermalRuntimeReadout extends ThermalRuntimeState { label: string; } export interface MosfetGateState { /** Previous accepted physical gate-to-source voltage. */ vgs: number; /** Previous accepted physical gate-to-drain voltage. */ vgd: number; } export type SimFailureKind = "resistor_overload" | "fuse_tripped" | "led_failed" | "output_sag" | "supply_overvoltage"; export interface SimFailure { componentId: string; kind: SimFailureKind; /** Simulation time, in seconds, when this failure latched. */ since: number; message: string; pinId?: string; value?: number; limit?: number; } /** * Stable engine warning codes. Additive: hosts key labels on these strings, * so a code is never renamed once published. */ export type SimWarningCode = "transistor_overcurrent" | "missing_flyback" | "rail_ic_power_chatter"; /** * A latched, session-only advisory: a condition the engine measured (or saw * in the loaded topology) that a host should surface once. Unlike a * SimFailure it never alters a stamp, so the solved trajectory is identical * with and without it. It latches per (code, component, pin) exactly the way * failures do — carried across load() for a same-id, same-kind component, * cleared by resetFailures() — which is what lets takeNewWarnings() announce * each condition once rather than once per accepted step. */ export interface SimWarning { componentId: string; code: SimWarningCode; /** Simulation time, in seconds, when this warning latched. */ since: number; message: string; pinId?: string; /** Measured quantity behind the warning, when there is one (e.g. amps). */ value?: number; /** The rating the measurement was held against, in the same unit as value. */ limit?: number; /** A short line with the numbers behind the message, for a host's hover or detail view. */ detail?: string; } export interface SolverDiagnosticsSnapshot { lastIters: number; lastConverged: boolean; lastSolveUs: number; lastMatrixSize: number; lastMatrixSingular: boolean; lastMatrixIllConditioned: boolean; lastRelativeResidual: number; } export interface DcOperatingPointResult { converged: boolean; /** Ladder stage that produced the accepted point (last stage tried on failure). */ method: "direct" | "gmin" | "source" | "pseudo-transient"; /** Total Newton iterations consumed across every stage attempted. */ iterations: number; /** Committed-regime re-solves performed (stage a plus post-homotopy settles). */ regimeIterations: number; /** Node voltages at the accepted operating point (pre-call values on failure). */ netV: Record; } /** Snapshot for save/restore during adaptive stepping in the worker. */ export interface StateSnapshot { caps: Map; /** Optional for compatibility with snapshots created before capacitor current tracking. */ capCurrents?: Map; /** Optional for compatibility with snapshots created before trapezoidal integration. */ capsI?: Map; /** Optional for compatibility with snapshots created before trapezoidal integration. */ indsV?: Map; /** Pending force-backward-Euler flag; must survive rollback so replayed trials stamp the same method. */ integrationBeNextStep?: boolean; inds: Map; /** Optional for compatibility with snapshots created before MOS gate charge. */ mosfetGates?: Map; /** Optional for compatibility with snapshots created before battery depletion. */ batteries?: Map; ne555s: Map; relays: Map; motors: Map; servos: Map; steppers: Map; lcds: Map; hcsr04: Map; failureStress: Map; failures: Map; /** Optional for compatibility with snapshots created before engine warnings. */ warnings?: Map; icState: Map>; eeproms: Map; ptcs: Map; thermalTemps: Map; /** Optional for compatibility with snapshots created before package thermal coupling. */ thermalDevices?: Map; netV: Record; elementI: Record; digitalState: Record; /** Full converged MNA vector used to derive multi-channel component currents. */ lastSolution?: Float64Array | null; /** Derived display output must roll back with the protocol state that produced it. */ displayState?: Record; /** Public solver diagnostics from the trusted state, not a rejected trial. */ solverDiagnostics?: SolverDiagnosticsSnapshot; /** Optional for compatibility with snapshots created before step breakpoints. */ stepBreakpointCount?: number; /** * Whether the last MCU step's edges still await the digital pass that * replays them into clocked ICs. Optional for compatibility with older * snapshots. */ mcuEdgesPending?: boolean; simTime: number; } /** * A committed state inside a step() interval, recorded when * `captureStepBreakpoints` is on. Today the only source is an NE555 switch: * one breakpoint at the switch instant, then one a guard sub-step later * holding the post-switch solution. A consumer that interpolates between * accepted states (a scope) needs both to draw the edge where the switch * happened instead of as a ramp across the whole step. */ export interface StepBreakpoint { time: number; netV: Record; } /** * Minimal immutable view used by the worker's coarse/refined error estimate. * It intentionally excludes EEPROM bytes, LCD buffers, display/current * readouts, the MNA vector, and diagnostics because none participate in the * local truncation-error decision. */ export type ErrorStateSnapshot = Pick; /** * Canonical key for the net-pair connected to a two-terminal element. * Normalised so swapping net0/net1 gives the same key; `flipped` tells * the caller whether to negate the stored value (for polarity consistency). */ export declare function netPairKey(net0: Net, net1: Net, excludeCompId: string): { key: string; flipped: boolean; }; /** * `rail_ic_power_chatter`'s message, the text Dev approved (rulings R89 and * R92), in this one place for both engines: the core's facade * (src/core/failures.ts) builds its warning from these two functions. The * message names the chip; the detail line (a host's hover) carries the * numbers. */ export declare function railIcPowerChatterMessage(componentId: string): string; /** * `rail_ic_power_chatter`'s detail line: the level the chip's supply is stuck * at and, when its rail is a current-limited supply at its limit, that limit; * a `limit` that is not finite (a cell, an ideal source) leaves the clause * out. Volts and milliamps to three significant figures. */ export declare function railIcPowerChatterDetail(floor: number, limit: number): string; /** The loaded graph as `missingFlybackWarning` reads it: pin to net, net to pins, and component kinds. */ export interface FlybackTopology { netIdForPin(componentId: string, pinId: string): string | null; pinsOnNet(netId: string): readonly Net["pins"][number][]; kindOf(componentId: string): string; } /** * The missing_flyback warning `comp` carries on this topology, or null when it * carries none. Pure, so that brownout/core's facade derives the same warning * from the same graph (core/README.md, W1g point 11) rather than a copy of * this rule; `_evaluateStaticWarnings` latches or drops what it returns. */ export declare function missingFlybackWarning(comp: SimComponent, since: number, topology: FlybackTopology): SimWarning | null; export declare const GATE_R_OUT = 50; export declare function regulatorQuiescentCurrent(comp: SimComponent): number; export declare const COMBINATIONAL_IC_KINDS: Set; export declare const RC_OUTPUT_EXCLUDED_COMBINATIONAL: Set; export declare const RC_OUTPUT_IC_KINDS: Set; export declare const FLOATING_INPUT_FUNCTIONS: Set; export interface LogicThresholds { vil: number; vih: number; } export interface IcPowerInfo { powered: boolean; vccPin: string | null; gndPin: string | null; vcc: number; gnd: number; vSupply: number; specs?: ElectricalSpecs; thresholds: LogicThresholds; outputResistance: number; propagationDelay: number; } /** * A RAM losing power: the state with its live words back at the preload, or * null when there is nothing to change (no preload, or the words already * match). Called from the committed pass that finds the chip unpowered, so * the words are already the preload when the solve that powers the chip up * stamps its outputs. Everything else in the state (the /WE history, the * output delay slots) is left frozen, as an unpowered chip's always was. * Exported for the RAM models (devices/digital-ics.ts). */ export declare function ramStateAfterPowerLoss(kind: RamKind, st: Readonly>): Record | null; export declare function defaultIcState(kind: string): Record; export declare function specsForComponent(comp: SimComponent): ElectricalSpecs | undefined; export declare function analogIcQuiescentCurrent(comp: SimComponent): number; export declare function supplyPinsForComponent(comp: SimComponent): { vccPin: string | null; gndPin: string | null; }; export declare function thermalProfileForComponent(comp: SimComponent): ThermalDeviceProfile | undefined; export interface BatteryModelResolution { profile: BatteryPhysicsProfile; nominalVoltageScale: number; referenceInternalResistanceOhm: number | undefined; } export declare function batteryModelForComponent(comp: SimComponent): BatteryModelResolution; export declare function authoredBatteryCharge(comp: SimComponent): number; export declare function batteryOperatingPointFor(model: BatteryModelResolution, soc: number, ambientTemperatureC: number): import("../battery-physics.js").BatteryOperatingPoint; export declare function thresholdsFor(specs: ElectricalSpecs | undefined, vSupply: number): LogicThresholds; export declare function propagationDelayForComponent(comp: SimComponent): number; /** * LDR (photoresistor) resistance as a function of ambient light. * Pure-extracted (zero behavior change) from the "ldr" stamp/current * handlers (now in devices/passives.ts) so apps/sim/lib/inspector/ * sensor-live.ts can reuse the exact same formula for the Inspector's live * resistance readout without duplicating it. */ export declare function ldrResistance(rDark: number, rLight: number, lux: number, r10?: number, gamma?: number): number; /** * NTC thermistor resistance (beta equation) as a function of ambient * temperature. Pure-extracted (zero behavior change) from the "thermistor" * stamp/current handlers (now in devices/passives.ts) — see ldrResistance * above for why. */ export declare function thermistorResistance(rNominal: number, beta: number, tempC: number): number; export declare class SimEngine { nets: Net[]; simTime: number; netV: Record; /** Last-step current through each component, keyed by compId (A, pin0→pin1). */ elementI: Record; /** Digital output level (0 or 1) for clock, gate, DFF, and 555 outputs. */ digitalState: Record; /** Per-component display state for driven display components (e.g. MAX7219, HD44780). */ private _displayState; /** Newton diagnostics from the last step — surfaced to the UI for debugging. */ lastIters: number; lastConverged: boolean; lastSolveUs: number; lastMatrixSize: number; lastMatrixSingular: boolean; lastMatrixIllConditioned: boolean; lastRelativeResidual: number; /** Monotonic diagnostic counter for optimization benchmarks. */ electricalSolveCount: number; get matrixFactorizationCount(): number; get matrixFactorizationReuseCount(): number; private nodeIdx; private vsrcIdx; private internalNodeIdx; private nodeCount; private _isolatedSectionAnchorRows; private _noSupplyReturnIds; private _powerReadings; private _heldPower; private _holdOffCounts; private _stepAtHostFloor; private _powerChatter; private _stepStart; private _dispDrivers; private mna; private _lastX; private _integrationMethod; private _beNextStep; /** Select the transient integration method for capacitors and inductors. */ setIntegrationMethod(method: "be" | "trap"): void; /** * The caller aligned the previous accepted step onto an event boundary * (source waveform edge, scheduled ECHO edge). The next step crosses or * departs that discontinuity, so it must integrate with backward Euler. */ markDiscontinuity(): void; /** Trap companions apply only in trap mode and away from discontinuities. */ private _useTrapThisSolve; private _dcSolveMode; private _homotopyGminG; private _homotopySourceScale; private _newtonMaxIterOverride; private _dcPhysicalTimeHold; private _dcDigitalHold; private _mnaLoadPatternWatermark; private state; private circuit; /** Immutable for one loaded topology; hot stamping/state paths only read it. */ private _componentById; private _pinToNetIndex; private _pinNodeIndex; private _openPinKeys; private _pinNodeByComp; private _openPinsByComp; private _floatingNoiseCache; private _thermalProfileCache; private _batteryModelCache; private _hasNe555; private _hasHcsr04; private _ne555Components; private _mcuComponents; /** Ideal voltage sources sharing a node pair with another (load-time). */ private _parallelIdealSourceIds; /** Set when a commit switches a Pico regulator's regime; load() re-solves * its seed so the published operating point is in the committed regime. */ private _picoRegimeFlipped; /** bench_psu components, compiled at load (let-go / take-back crossings). */ private _benchPsuComponents; /** Boards with an MCU supply absolute maximum (MCU_SUPPLY_ABS_MAX). */ private _supplyRatedComponents; private _stateUpdateComponents; private _digitalUpdateComponents; private _failureUpdateComponents; private _unannouncedWarnings; private _thermalComponents; private _staticIdealSourceIds; private _staticStampComponents; private _dynamicStampComponents; private _stateUpdateModels; private _digitalUpdateModels; private _failureUpdateModels; private _staticStampModels; private _dynamicStampModels; private _elementCurrentModels; private _staticStampSignature; private _fixedNodeSet; private _combinationalEvalCache; private _nextDigitalDueTimeCache; private _digitalDueCacheDirty; /** * Record StepBreakpoints for takeStepBreakpoints(). Off by default. While * on, an NE555 switch also takes an NE555_GUARD_STEP_S backward-Euler * sub-step so the state recorded just after the switch is the post-switch * solution; that sub-step is the only effect on the numerics, and it does * not depend on whether anything reads the breakpoints. */ captureStepBreakpoints: boolean; private _stepBreakpoints; digitalEvaluationCount: number; digitalEvaluationReuseCount: number; private _vPrevBJT; private _junctionLimitedThisIteration; private _bjtCache; private _currentLimitComplianceClamps; private _currentLimitCurrentBranchTried; private _currentLimitEntryClamps; private _regulatorHeadroomBranchTried; private _regulatorHeadroomSelections; private _regulatorHeadroomRegime; private _useCurrentLimitEntryClamp; private _useCurrentLimitComplianceClamp; private _envLux; private _envTempC; private _ambientTempC; private _junctionVt; private _junctionVf; private _thermalProfile; private _batteryModel; private _batteryOperatingPoint; private _elementIOut; private _digitalStateOut; private _displayStateOut; private _previousMosfetGates; private _mcuEventDrivers; private _mcuStepStartLevels; private _mcuInputEdgesWanted; private _mcuEdgesPending; private _readbackCandidates; private _readbackShadowInstalls; private _failureChannelCurrents; private _failureSpecsComp; private _failureSpecsValue; private readonly _deviceCtx; private _buildDeviceContext; saveState(): StateSnapshot; /** Capture only state inspected by estimateStepError(). */ captureErrorState(): ErrorStateSnapshot; restoreState(snap: StateSnapshot): void; /** The breakpoints committed since the last call, oldest first. See StepBreakpoint. */ takeStepBreakpoints(): StepBreakpoint[]; getFailures(): Record; /** Every currently latched engine warning, keyed like failures. */ getWarnings(): Record; /** * Warnings latched since the previous call, in latch order, then marks * them announced. A host forwards these on its warning channel once; the * full latched set stays readable through getWarnings(). A warning that * was rolled back or reloaded away before being drained is never returned. */ takeNewWarnings(): SimWarning[]; /** Returns the set of component IDs whose PTC fuse is currently tripped. */ getPtcTripped(): ReadonlySet; /** Latest committed body/junction temperature for a thermally modelled component. */ getPartTemperature(componentId: string): number | undefined; /** Exact package thermal state for structured telemetry and UI warnings. */ getThermalState(componentId: string): ThermalRuntimeReadout | undefined; resetFailures(): void; /** * Returns EEPROM byte arrays changed since the last call, then clears * their dirty flags. Empty object is the common no-op path. */ takeEepromUpdates(): Record; /** * Load a new circuit. Preserves element state for components whose ID * hasn't changed (ID match), then falls back to net-pair fingerprint * matching for components that were re-placed/renamed. Truly new * capacitors and inductors start with exactly zero stored energy. */ load(circuit: SimCircuit): void; /** * Pre-compute `vCrit` (and the per-junction `n·Vt`) for every PN-junction * element, so pnjlim doesn't take a log per stamp call. Rebuilt on every * `load()`/`coldLoad()` since params can change at the load boundary but * not within a step. */ private _rebuildJunctionCache; /** * Cold-load: zero all element state then call load(). * Used by the "Cold reset" button — caps/inductors start from exact zero * stored voltage/current before the initial operating-point solve. */ coldLoad(circuit: SimCircuit): void; /** * Robust DC operating point: true-OP stamping (capacitors open, inductors * shorted through their winding resistance) plus a homotopy rescue ladder * — direct solve at the committed regimes, gmin stepping, source stepping, * then pseudo-transient relaxation. Each stage warm-starts from the * previous iterate because a failed _solve is a rejected trial that keeps * the last trusted netV. * * Never advances simTime, MCU firmware, digital event time, or any other * physical clock: every dc solve uses the same 1 ps companion interval as * load()'s seed (stage d grows its BE pseudo-interval but pins waveform * sampling to the same instant — see _waveformSampleTime), _solve never * touches MCU cores, and the h-scaled physical integrators (thermal, * failure stress, battery charge, mechanics) hold at their entry values * for the whole ladder via _dcPhysicalTimeHold. * * On success the point is committed like an accepted solve, with the * dynamic-element state normalised to its DC meaning (see * _commitDcOperatingPointState). On total failure the engine is restored * to the state it had before the call. */ dcOperatingPoint(options?: { maxOuterRegimeIters?: number; }): DcOperatingPointResult; /** * Stage a — direct dc solve at the committed regimes. Regime and latch * state machines (op-amp saturation, regulator CC/dropout, bench_psu CC, * 555 SR, sequential logic) commit post-solve, so one solve can invalidate * the active set it was stamped with; re-solve until the committed picture * stops changing. An astable latch has no DC fixed point at all, so * hitting the cap still accepts the last converged solve (its regimes are * self-consistent for one of the two alternating phases) instead of * failing the stage. */ private _dcRegimeSettle; /** Committed let-go / CC / CV regime of every bench supply. */ private _benchPsuRegimeSignature; /** * Fingerprint of the committed regime/latch state consulted by _stampAll. * Continuous icState slots (branch currents, settled pole voltages) rest * across repeated 1 ps solves at a fixed instant; quantising to 1e-9 keeps * the fingerprint stable there while any genuine discrete transition * (regime enums, latch bits, counters) moves by >= 1. One deliberate * exception: a mid-slew op-amp pole moves ~slewRate * 1 ps per solve — * hundreds of quanta — so circuits carrying such a pole exhaust * maxOuterRegimeIters and take _dcRegimeSettle's accept-last-converged * exit. That is the documented DC_OP_COMPANION_H hold semantics (the OP is * the resting point GIVEN the carried device state, poles included), paid * for as a bounded settle budget rather than a wrong answer. */ private _dcCommittedRegimeSignature; /** One homotopy rung: a converged _solve at the given overlay strength. */ private _homotopyRungConverged; /** * Stage b — gmin stepping. A strong every-node-to-ground conductance makes * any circuit nearly linear; walking it down a decade at a time drags the * iterate along a continuous solution path to the unloaded system. On a * rung failure, retreat to the half-decade point between the last success * and the failure (geometric mean), then retry the failed rung once; a * second failure fails the stage. */ private _homotopyGminLadder; /** * Stage c — source stepping under a pinned mild gmin load. Anchors at * scale 0 (every independent source dead — the most docile system there * is), then ramps all drives together in adaptive increments: halve on * failure, double on success, floored at 1/1024 of full drive. */ private _homotopySourceLadder; /** * Stage d — pseudo-transient continuation with physical companion * stamping. Backward Euler is L-stable, so growing pseudo-steps damp * oscillatory modes instead of amplifying them and the trajectory parks at * an operating point without the trajectory itself needing to be accurate. * simTime never advances: pseudo-time is not physical time. That includes * the sources — _waveformSampleTime pins clock/pulse/signal-gen sampling * to the OP instant while _dcPhysicalTimeHold is set, so a growing h never * stamps (or lets _updateDigitalState read) a source phase up to 1 ms past * the instant the caller asked about. Digital/regime state otherwise keeps * co-settling here: the relaxation needs gate outputs and latches to * follow the trajectory to reach a mixed-signal fixed point. */ private _dcPseudoTransient; /** * Assemble the dc-mode system matrix (the Newton Jacobian) at iterate x * into a plain dense array by replaying the stamp pass through a * recording facade. This is deliberately backend-independent: dense and * sparse runs replay the identical stamp order into the same flat array, * so every stability decision below is bit-identical across backends. * dc stamping is forced for the duration so the screen always measures * the true DC Jacobian — the pseudo-transient stage's candidate was * produced under BE companion stamping, where a capacitor's 1 ps * companion conductance would mask any resistive instability. */ private _dcExtractSystemMatrix; /** * Sign of det(A + g·P) with P the identity on node rows, zero on source * branch rows. Row equilibration (a positive scaling of det) plus * partial-pivot elimination tracking swaps keeps the computation * overflow-free while preserving exactly the sign. Returns 0 when the * shifted matrix is numerically singular — callers treat that as * "screen inconclusive", never as instability. */ private _dcShiftedDetSign; /** * Run the determinant pencil screen (see DC_OP_STABILITY_MAX_SIZE) on the * committed iterate. "unknown" means the screen is inapplicable (system * too large, no committed iterate, or a numerically singular pencil * endpoint) and is treated as acceptance by callers — the screen only * ever downgrades a provably unstable point. */ private _dcCandidateStability; /** * Dense equilibrated partial-pivot LU over a shifted copy of the screen * matrix, packaged as a solve closure for the inverse iteration below. * Local on purpose: it must be bit-identical across linear backends, and * the pencil shift g·P is not expressible through the stamp interface. */ private _dcDenseSolveFactory; /** * Approximate the growing real eigenmode of a rejected saddle. The * det-sign change of p(g) on (0, gBig] is bisected down to the unstable * pencil eigenvalue, then a few steps of inverse iteration with that * shift pull out its eigenvector. Returned max-norm-1 on node rows with * a canonical orientation (largest-magnitude entry positive) so escape * kicks are bit-reproducible run to run. */ private _dcUnstableDirection; /** * Gate applied to every ladder-stage acceptance: pass the stability * screen, or escape the saddle by kicking the iterate along its growing * eigenmode and re-settling. A successful escape is accepted within the * same stage (the re-settled point is a true-system solution found by * that stage's iterate). Failure restores the saddle iterate so the next * ladder stage starts from the same trusted state it would have today. * * Known stage-d limitation: this gate runs with whatever stamping mode the * stage used, and stage d arrives with _dcSolveMode off, so the kick * re-settle solves stamp capacitors as their 1 ps companions (~C/1e-12 * siemens holds pinned at the saddle voltages) rather than dc opens. A * saddle held by a commutating capacitor bridging the switching nodes can * therefore absorb every kick and re-converge onto itself, failing the * whole OP instead of escaping. That outcome is fail-safe (the saddle is * rejected, never committed); re-settling in dc mode here would make the * escape effective for those circuits but requires the dc-mode inductor * commit as well — a deliberate tradeoff, revisit if a real circuit hits * it. */ private _dcAcceptStableOrEscape; /** * Commit an accepted operating point the way an accepted solve would. * _solve already committed netV/elementI and the digital/regime state from * the final converged rung; what remains is the capacitor/inductor and * electromechanical-winding state that dc stamping deliberately did not * integrate, plus the histories the A2 trapezoidal method reads. */ private _commitDcOperatingPointState; /** * Wave A3 seed rescue: when load()'s 1 ps seed fails, walk the same gmin * and source-stepping ladders dcOperatingPoint uses — but at the seed's * own companion stamping (NOT dc mode), preserving its hold-the-initial- * conditions semantics. Success ends with one plain warm-started re-solve * of the unmodified seed system, so a rescued load commits the same single * full post-solve update pass (digital state included) a first-try * converged seed would have; total failure restores the failed-seed state, * i.e. today's quiet give-up. Reached only when this.lastConverged is * false, so circuits whose seed converges never enter this path * (bit-identity guarantee). */ private _rescueSeedOperatingPoint; /** * Advance simulation by h seconds. * * When a NE555 is present: takes a trial full step, checks whether the * THR or TRIG node crossed the 1/3·VCC or 2/3·VCC threshold during the * step, and if so rolls back and re-solves in two sub-steps split at the * estimated crossing time. This keeps the 555 SR-flip output transition * aligned with the actual physical crossing rather than lagging by a * full step. */ step(h: number): void; private _stepSolves; /** bench_psu let-go / take-back switches a converged solution asks for. */ private _benchPsuSwitches; /** * One transient interval of length h, solved with every bench supply's * let-go regime frozen. When the converged endpoint asks a supply to let go * or take back its output, that is a crossing inside the interval, not a * switch at its end: roll back, solve up to the earliest crossing in the * old regime, switch the supplies crossing there, and solve the rest in * the new one (backward Euler across the discontinuity, as the 555 split * does). Up to BENCH_PSU_MAX_SPLITS crossings per interval; a further one * waits for the next interval. simTime is back at its entry value on * return, as after a plain _solve, and nothing outside the electrical * state is advanced, so a rolled-back trial stays firmware-neutral. */ private _solveSegment; /** * Commit the external CPU side of one converged electrical interval. * * The accepted endpoint is sampled first, then each powered core advances * exactly once. Its resulting GPIO state and ordered PinEvents are retained * for the next electrical interval. This explicit ordering keeps an MCU out * of Newton/NE555 trial solves and makes a worker retry firmware-neutral. * Once a model has asked for MCU input edges, each core's pin levels are * recorded before it steps and its edges wait for the next digital pass. */ private _advanceMcusAfterAcceptedSolve; /** This MCU's readback candidates, or null when it has none (H11). */ private _readbackCandidatesFor; /** * Scan the loaded topology once per load for registered clocked parts an * MCU can read back mid-step (H11). A part qualifies for an MCU only when * the SAME single MCU shares a net with one of its shadow inputs (it * writes the part) and with one of its shadow outputs (it reads the * part): two MCUs on any of those nets means no shadow, matching the * null rule the committed replay (mcuInputEdges) applies to two drivers. * Every other circuit — including an MCU with no clocked part — collects * nothing, and its stepping stays byte-identical. */ private _buildReadbackCandidates; /** * Run one MCU step with its readback shadows installed (H11). Each write * the core captures drives every shadow's replay walker — grouped into * writes exactly as the committed pass will group them, by cycle — and * each shadow's output levels are pushed into the core's input path as * they change. At install the current output levels are pushed once too: * the solve the core just sampled stamps the part's outputs one replay * behind, and a read before any write this step belongs to the register * as it stands now. The committed digital pass remains the state of * record; the shadows are discarded with the step. */ private _stepMcuWithReadback; /** * The edges one MCU drove onto `pinIds` in its last step (see * DeviceContext.mcuInputEdges). Pins map to MCU pins through the same * includePico driver map the servo and HC-SR04 decoders use. */ private _mcuInputEdges; private static readonly _NO_STEP_PIN_EVENTS; /** * The raw step-event handout behind ctx.mcuStepPinEvents (servo PWM * decode, hcsr04 TRIG edges): the same consumed-once lifecycle as * _mcuInputEdges and _mergedDisplayEvents. Asking arms the start-level * recording (so the next advance arms _mcuEdgesPending), and the events * are handed out only while that advance's replay is still owed; the * first completed digital pass consumes the flag, so the NE555 split's * re-solves — and every later pass — cannot re-feed one MCU step's edges * into these decoders twice (at the base the split's second feed of the * boot-time [low, high] first-observation pair on TRIG read as a complete * pulse and armed a phantom echo 250 us after boot). */ private _mcuStepPinEvents; /** Restore the trusted pre-trial state while preserving failed-solve diagnostics. */ private _restoreFailedSplitTrial; getNetV(): Record; /** Resolve a component pin to its current deterministic net id. */ getNetIdForPin(componentId: string, pinId: string): string | undefined; /** Matrix layout of the loaded topology. `size` includes branch rows; * node rows occupy [0, nodeCount). Zeros before the first load(). */ matrixDimensions(): { size: number; nodeCount: number; }; /** MNA row for a net id: -1 for gnd, undefined for an unknown net. */ netRow(netId: string): number | undefined; /** Loaded components in circuit order (empty before the first load()). */ loadedComponents(): readonly SimComponent[]; /** * Build the read-only device facade for one small-signal AC analysis. A * fresh object per call — unlike the cached _deviceCtx — because the AC * input designation is per-analysis state that must not leak between * runs. Every member aliases the exact engine expression the transient * stamps read (see AcDeviceContext in device-registry.ts); the solution * accessors read the engine's last committed solve, which after a * converged dcOperatingPoint() is precisely the held operating point. */ acDeviceContext(designation: { inputId: string | null; }): AcDeviceContext; /** Held OP solution for the AC facade's logic reads, with the same * all-zero degradation icPowerInfoAtOp uses before any solve. */ private _acOpVector; /** Reset (restart) the simulated MCU for the given component id. */ resetArduino(componentId: string): void; /** * S18b — engine simTime at which each MCU core currently in `state.arduinos` * (re)booted (cycle counter 0). PinEvent.cycle (arduino.ts / rp2040.ts) is a * cumulative-since-boot counter, NOT step-relative, at each core's native * clock (16 MHz AVR / 125 MHz RP2040 — neither exposed on the shared * MicrocontrollerCore contract, so cycle-accurate peripheral decoders need * this baseline instead of assuming boot coincided with simTime 0: a hex/ * script can be (re)flashed mid-simulation, and resetArduino() rebuilds the * core independently of any circuit reload). Captured wherever `load()` * actually constructs a NEW core object, and on resetArduino(); pruned * alongside microbitDrives above. */ private _mcuBootSimTime; /** Program-driven micro:bit edge-pin states (P0/P1/P2), pushed from the client * embedded sim. Keyed by component id → { pinId → { mode, value } }. Runtime * only; PRUNED to live boards on load() (surviving boards keep their drives — * the embedded sim keeps running across circuit edits and only re-pushes on * change; the host clears a board's entry on flash/reset/power-off). */ private microbitDrives; setMicrobitDrive(componentId: string, drives: Record): void; getElementI(): Record; /** Runtime chemistry/SoC state for battery telemetry and user readouts. */ getBatteryState(compId: string): BatteryRuntimeReadout | undefined; /** * W7.1 — Returns the committed motor state (iWinding + omega) for the given * component ID, or undefined if no motor with that ID exists. * * Used by tests and future UI indicators to read rotor speed (omega, rad/s) * and winding current without re-running the companion formula. * RPM = omega * 60 / (2π). */ getMotorState(compId: string): MotorEngineState | undefined; /** * W7.2 — Returns the committed servo state for the given component ID, or * undefined if the component is not known. * * Used by tests and future UI to read the decoded shaft angle and PWM timing. */ getServoState(compId: string): ServoEngineState | undefined; /** * W7.2 — Returns the committed stepper state for the given component ID, or * undefined if the component is not known. * * Used by tests and future UI to read coil currents, phase, and position. */ getStepperState(compId: string): StepperEngineState | undefined; /** * S18b — Returns the committed HC-SR04 state (TRIG/ECHO state machine) for * the given component ID, or undefined if the component is not known. * Used by tests and future UI to read phase/schedule without violating the * private-state encapsulation in production paths. */ getHcsr04State(compId: string): Hcsr04EngineState | undefined; /** * Earliest pending physical/discrete event across sensors and delayed logic, * or null if none are scheduled. sim.worker.ts clamps each step's h so it * lands exactly on this instant * (guarded to h >= H_MIN) instead of letting an adaptive step grow past a * µs-scale edge — the NE555 sub-step crossing split (see `step()` above) is * the in-engine precedent for aligning a step boundary to a physical edge * rather than sampling it at whatever granularity the adaptive h happens * to be at. Unlike the 555 case (always exactly one step ahead), an hcsr04 * echo can be scheduled tens of milliseconds out, so the clamp lives in the * OUTER batch loop rather than inside step() itself. */ nextScheduledEventTime(): number | null; /** * S18b — hard cap on step size (comfortably under the fixed 250 µs * TRIG-fall-to-ECHO-rise delay) whenever the circuit contains any hcsr04, * or null otherwise. sim.worker.ts's runBatch applies this ALONGSIDE the * nextScheduledEventTime() clamp, and for a different reason: that clamp * only protects a step that begins AFTER a schedule is already known. The * very step in which a TRIG fall is detected and the schedule is BORN has * no such advance warning — nextScheduledEventTime() was null when that * step's h was chosen. Without this cap, a step larger than ~250 µs could * ALSO already be "due" for the freshly-created echoRiseAt by the time * the state pass computes it (this.simTime + h already past tFall + 250 µs), * silently skipping the rise straight to "active" a full step late and * corrupting the ECHO pulse width as measured by a real pulseIn/ * time_pulse_us caller. Keeping every step under the 250 µs delay * guarantees echoRiseAt (>= stepStart + 250 µs, since tFall >= stepStart) * always exceeds this.simTime + h (<= stepStart + h < stepStart + 250 µs), * so the schedule is always seen "not yet due" in its birth step and the * outer nextScheduledEventTime() clamp gets a fair chance to react on a * later, appropriately-shrunk step. */ hcsr04MaxStepH(): number | null; /** * S18b — drains HC-SR04 -> micro:bit ECHO bridge events queued since the * last call. See Hcsr04EngineState.pendingEchoEvent for why this lives * inside the per-component state map rather than a free-standing queue. */ takeHcsr04EchoEvents(): Hcsr04EchoEvent[]; /** * Returns the committed IC state record for the given component ID, or * undefined if the component has no IC state. Used by tests to inspect * the state of ULN, buzzer, speaker, and sequential IC components, and by * physics telemetry for the buzzer/speaker sounding readout, without * violating the private-state encapsulation in production paths. */ getIcState(compId: string): Record | undefined; /** * H11 diagnostics: MCU-step readback shadows installed since the last * load(). Zero for every circuit without a registered clocked part the MCU * both writes and reads — the guard the identity tests pin. */ get readbackShadowInstalls(): number; /** Per-board runtime state for onboard LED/button art. Only boards with an MCU are included. */ getArduinoState(): Record; /** * Per-channel currents (A) for multi-junction LED parts. * * rgb_led: [r, g, b] — indices 0-2 * bicolor_led: [a1, a2] — indices 0-1 * seg7_cc/ca: [a, b, c, d, e, f, g, dp] — indices 0-7 * * The renderer uses these to decide lit/brightness state instead of reading * raw net voltages, so the display reflects real diode-level current. */ getElementChannelI(): Record; /** Per-component display state committed at the end of the last step. */ getDisplayState(): Record; /** Net ID for the net that contains (compId, pinId), or null. */ private _netIdForPin; /** * Compare pre-step and post-step 555 states to find the earliest * threshold-crossing fraction within (0,1). Returns null if no 555 flipped. * * Derivation: voltage moves approximately linearly across the step, so * frac = (V_target − V_pre) / (V_post − V_pre) * The frac is clamped to [0.02, 0.98] to keep both sub-steps non-trivial. */ /** Whether any NE555's output state differs from `preNe555s`. */ private _ne555Switched; private _find555CrossingFrac; /** Net rows anchored as isolated sections' references (see ISOLATED_SECTION_ANCHOR_G). */ isolatedSectionAnchorRows(): readonly number[]; /** * Find the electrically isolated sections of the loaded circuit and pick * one anchor row in each. A section is a union of net rows: every pin of a * component joins one group unless its model declares galvanicGroups, so * sections never depend on a switch's position, a relay contact or a * failure state, and a running circuit cannot close a path from an * anchored section to ground. Internal nodes stay out: each couples only * within its own group, which an anchored or grounded section already * fixes. * * The same union finds the supply-gated parts that have no supply return. * Such a part conducts only while powered, so it joins once its VCC and * GND rows are joined without it, and a part that joins can complete * another's return, hence the repeat. A part still waiting would return its * supply current through nothing but itself, so it cannot stay powered: its * stamps pull the floating rail onto the other one. A floating ground rail * then drops back to the shunts' 0 V and powers it again, and Newton * alternated between the two on every iterate, so no step converged (a 555 * whose ground is on a breadboard rail wired to nothing). _icPowerInfo * reads such a part as unpowered for the whole load, and it joins no * section: through its own power pins it would merge the island on one * side of its missing supply return into the section on the other, while * its off stamps leave that island without a reference row. An island left * holding charge then rested on the node shunts alone, and no step * converged at any size. The island stays what the rest of the wiring * makes it, an isolated section with its own anchor. */ private _compileIsolatedSectionAnchors; private _buildMatrix; /** * Compile topology facts that are immutable until the next load(). The old * implementation rediscovered these facts by scanning every net (and, for * open pins, every wire plus a freshly allocated Set) on each stamp/read. * Keeping the exact legacy rules here makes the hot paths O(1) without * changing what counts as an externally connected package pin. */ private _compileRuntimeMetadata; /** Compile RSHUNT plus topology-only ideal-source incidence once per load. */ private _rebuildStaticStampBase; /** * Direct callers may mutate a loaded component's params object before the * next step (tests and analysis tools rely on this). Track only values used * by compiled full stamps so that path remains exact without re-stamping the * common unchanged case. */ private _currentStaticStampSignature; private _refreshStaticStampBaseIfNeeded; private _stampIndependentVoltageSource; /** * Source-stepping homotopy scale (Wave A3), applied at stamp time to every * INDEPENDENT source magnitude. Canonical list of scaled kinds: * - voltage_source / clock / clock_gen / pulse_source / pulse_gen / * signal_gen waveform voltages * - current_source programmed current (Wave A7 — devices/sources.ts * routes both its stamp and its published element current through * this helper so I sources relax on the same ladder as V sources) * - battery_pack open-circuit voltage (internal resistance stays * unscaled — it is an impedance, not a drive) * - bench_psu voltage setpoint (iLimit stays unscaled — it is a * compliance bound enforced by the committed CC regime, not an * independent drive; the regime follows the scaled setpoint naturally) * - MCU/micro:bit USB rail sources (arduino_uno, arduino_nano, * raspberry_pi_pico, microbit vcc branches) * Deliberately NOT scaled: * - dependent/behavioral outputs (op-amp, comparator, linear_reg, lm317, * dcdc_converter, TL431, logic and MCU pin Thevenin stages, 555 output) * — they are referenced to their package rails or gated by input * UVLO/power checks, so they collapse with their scaled supplies; * - load-shaped stamps (board idle-draw resistors, IC quiescent current * sinks, companion history sources) — scaling a load or a state memory * would distort the system instead of relaxing its drives. */ private _independentSourceMagnitude; /** * Waveform sample instant for the solve in flight (Wave A3). Ordinary * stepping samples the interval endpoint, simTime + h — the identical * float expression as before, so the default path stays bit-exact. While * _dcPhysicalTimeHold is set, sampling is pinned to the OP instant * (simTime + DC_OP_COMPANION_H) no matter what companion/pseudo interval * the solve uses: stage d's backward-Euler pseudo-steps grow h to 1 ms of * NON-physical time, and sampling there would stamp — and let * _updateDigitalState latch — a source phase up to 1 ms past the instant * the operating point is being computed for (e.g. a 500 Hz clock read in * its opposite half-cycle). Every clock/pulse/signal-gen evaluation, * stamp-side and post-solve, must route through this one helper so the * stamped source and its readback never disagree. */ private _waveformSampleTime; private _pinNode; private _isOpenPin; /** * S18b — if `comp`'s ECHO pin shares a net with a micro:bit edge pin, return * the bridge target (board component id + SIM-form pin id). Used the instant * an echo is scheduled (TRIG falls) to queue the micro:bit worker event — * see Hcsr04EngineState.pendingEchoEvent. */ private _hcsr04MicrobitBridge; private _arduinoPowered; /** Whether an MCU board is powered enough to run. The Pico is USB(VBUS)-powered * (its 3V3 pin is an output, not a supply input), so use the USB switch. */ private _mcuPowered; private _icPowerInfo; private _floatingLogicHigh; /** * hash32(`${compId}:${pinId}:${bucket}`) normalised, memoised per pin: it * only changes with the 10 ms bucket, and rebuilding the string and hash on * every read of every open input was a top cost on logic boards. */ private _floatingNoise; private _logicHigh; /** * Like _logicHigh but respects IC_OPEN_HIGH_PINS: pins listed there resolve * deterministically HIGH when unconnected, instead of using the floating model. * Use for direct pin reads on ICs whose control inputs have on-chip pull-ups. */ private _logicHighH; /** * Schmitt-trigger hysteresis for parts whose catalog spec carries v_t_plus / * v_t_minus (e.g. 74HC14). The thresholds are defined at vcc_range.nominal * and scale linearly with the actual supply; state (last stable level) is * persisted in icState under "schmitt_". * * commit = false (default): read prevHigh for the dead band, compute nextHigh, * but do NOT write back to icState. This is the correct behaviour during * Newton-iteration stamping: intermediate non-physical xGuess values crossing * a threshold must not latch wrong state (worst on the canonical 74HC14 RC * relaxation oscillator). * commit = true: persist nextHigh only when it differs from prevHigh. The * post-solve _updateDigitalState path (converged x) is the only caller that * passes commit = true. * * Only called for pins that belong to a part with Schmitt thresholds — * all other parts use the unmodified _logicHigh path. */ private _schmittLogicHigh; private _logicPinMap; private _shouldTreatOpenPinAsDigitalInput; private _floatingInputResistance; private _stampFloatingDigitalInputs; private _combinationalOutputs; private _stampDigitalOutput; /** * Thevenin output referenced to real low/high rails. A fractional target is * represented by complementary conductances whose sum is 1/R, conserving * current at both rails while producing Vlow + fraction*(Vhigh-Vlow). */ private _stampRailReferencedOutput; /** * Board-level regulator/MCU/indicator load. A nominal-current resistor keeps * the stamp linear and naturally reduces draw during brown-out. Users can * override `idleCurrent` for a particular firmware/peripheral configuration. */ /** Trip / recover the Uno's USB polyfuse (F1) on the USB branch current, * whichever way it flows: a supply back-feeding the 5V pin into the host * trips it the same as an overload drawn from USB. With USB unplugged * (usb_power off) nothing drives current through F1, so a tripped fuse * cools and resets on the shared PTC model's recovery time, as unplugging * a real board does. */ private _updateUnoUsbPolyfuse; /** Latch supply_overvoltage when an accepted step puts the MCU's supply * pin past its absolute maximum. It stays latched once the supply comes * back down, as a damage risk does, until resetFailures(). */ private _checkMcuSupplyOvervoltage; private _picoRegulatorBackfed; /** Switch the Pico's 3V3 regulator between regulating and back-fed on the * accepted solution, like bench_psu's committed CV/CC regime: it turns * off once it would sink current, and back on once the pin falls below * its setpoint (the external supply is gone or lower). */ private _commitPicoRegulatorRegime; private _stampBoardIdleLoad; private _delayedOutputLevel; private _updateDelayedOutputs; private _netVoltageForPin; /** Voltage at a matrix row (or 0 for ground / unmapped). */ private _vAt; private _hasFailure; private _componentFailed; private _recordAccumulatedStress; private _latchWarning; /** * rail_ic_power_chatter: each part of `chatter` (id -> its power-on level) * alternated at the hosts' floor with no state that holds. The warning * names the part; its detail line gives the level and, when a * current-limited bench supply sits on the part's vcc net, that supply's * limit: a part starved on such a rail has the supply at its limit, since * below the limit the supply would hold the rail at its setpoint. */ private _latchPowerChatter; private _pruneUnannouncedWarnings; /** * _recordAccumulatedStress's twin for warnings: the same dwell integrator * (shared accumulator map, see warningKey), latching a SimWarning instead * of a SimFailure. A latched warning is inert to the solve. */ private _recordAccumulatedWarning; /** * Re-derive every topology warning from the current graph (see the * FLYBACK_* constants). Latches new conditions, drops ones that no longer * hold, and leaves an already-latched, still-true condition untouched so it * is not announced twice across reloads. */ private _evaluateStaticWarnings; private _solve; /** One Newton solve of a step of length h from xInit, against the system in this.mna. */ private _runNewton; /** * The load seed's last resort, after the rescue ladder has failed too: the * seed solved again with _solveHoldingUnholdableOff armed, as a step's * solve would be. Waiting for the ladder keeps every seed it rescues * exactly as before. If this fails as well, the diagnostics, the sparse * pattern and the pivot history go back to how the failed ladder left them. */ private _retrySeedHoldingUnholdableOff; /** * Last resort for a solve that failed while a supply-gated part's power * reading alternated between Newton iterates: read powered, its own draw * pulled its supply below the power-on threshold; read unpowered, the * supply recovered. A chip fed only through a charged capacitor and * resistance (a 555 blinker switched off, or with its ground wire pulled, * while its timing capacitor holds more than that threshold) has no * consistent state at any step size, so hosts retried down to their floor * and the clock stopped. * * The parts that alternated are held powered for a solve at the load * seed's 1 ps interval, where every capacitor keeps its present charge, * with every other supply-gated part held at the reading it settled on: * the probe asks only whether the alternating parts can hold their supply. * (Left free, a second chip at its own threshold could alternate at 1 ps * though not at h, and fail the probe for a reason the step does not * have.) A part whose supply still reads unpowered there is asked again at * the same instant held unpowered. Only one whose supply then reads * powered starves itself; one that reads unpowered either way sits on a * supply still below its threshold at the step's start, rising through it * within the step, and that crossing is the host's to land with a shorter * step, as it always has. So is a part that read unpowered when the host's * step began, in a 555 split's sub-step that starts inside that step just * past the threshold its supply has risen through. Only a step already at * the hosts' floor (HOST_MIN_STEP_S) has no shorter step left, so there * those parts are held unpowered too: they turn on at most that one floor * step late, where the host would otherwise stop. The step is solved again * with these parts held unpowered and the rest free; that solution is the * step's. Anything else (a probe that does not converge, parts that do hold * their supply, supplies that are still low above the floor, or a held-off * solve that fails too) rejects the step exactly as before: the trial * solves run on a scratch matrix, so this.mna keeps its pattern and pivot * history, and nothing is committed. */ private _solveHoldingUnholdableOff; /** * Stamp every element into the (already-cleared + RSHUNT-seeded) MNA * using `xGuess` as the linearisation point for non-linear elements. * Linear elements ignore `xGuess` and stamp the same values every * iteration. */ private _stampAll; /** Read a 4-bit address from pins a0..a3 of a component. */ private _readAddr4; /** Post-solve: update capacitor voltages, inductor currents, and op-amp committed outputs. */ private _thermalDissipationW; /** * Advance exact package thermal states after electrical currents have been * reconstructed from this solution. Snapshot ownership makes this one update * rollback-safe under full-step/half-step trials and rejected adaptive steps. */ private _updatePackageThermalState; private _updateState; private _buildArduinoPinDrivers; private _mergedDisplayEvents; /** * Post-solve: update digital element states (DFF edge detection, 555 SR * flip-flop) and compute the public `digitalState` map (0/1 per component). */ private _updateDigitalState; /** * Post-solve: compute and cache per-component current (pin0 → pin1). * The renderer and Inspector read these for LED brightness / probes. */ private _updateElementI; private _updateFailureStates; /** * The single RC pole a driven output's net relaxes on, when that is provable, * else null. It is provable when the driver is in RC_OUTPUT_IC_KINDS, both * its supply pins sit on fixed nodes, and every other pin on the net is a * capacitor whose far end sits on a fixed node or a high-impedance input of * such an IC. Each capacitor is its ESR and C in series with its leakage * across both: one capacitor with any ESR, or several with none, is one pole. * A resistor, source, second driver or any other part on the net, a capacitor * behind a series resistor, or two capacitors with ESR adds a jump, an * asymptote or a pole this cannot see, so the answer is null and the step * count stands. Params are read afresh, since direct callers may edit them in * place between steps. Voltages are from the IC's ground: * - vInf: where the pin settles, from R_out's rail and the leakages' far ends; * - tau: (ESR + the Thevenin resistance of R_out and the leakages) * C; * - divider: the pin's share of the capacitor's distance from vInf; * - start: the farthest from vInf the exact capacitor can be when a sag first * seen in this backward-Euler solve begins, at either end of the solve. The * capacitors' own states, stepped back by their branch currents, give where * classic held it at the solve's start, an edit's jump included. A solve * still under the old level only moved it toward that level's asymptote, * and the exact capacitor sits nearer that asymptote than classic's; both * lie within the rails and far ends, which therefore bound the rest. */ private _outputSagPole; /** Ground and every node an ideal voltage source chain pins to it. */ private _fixedNodes; private _clearOutputSagWarnings; private _drivenOutputTargets; /** * After analog solve converges: read each Arduino input pin's net voltage * and push it back into the MCU so the next step sees correct PINX registers. */ private _sampleArduinoInputs; }