indierf-schematic-mcp 0.0.0-stage → 0.1.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.
Files changed (132) hide show
  1. package/LICENSE +91 -0
  2. package/README.md +96 -2
  3. package/lib/analysis/plot-axis.ts +346 -0
  4. package/lib/cascade/filter-prototype.ts +442 -0
  5. package/lib/coax/cable-copy.ts +71 -0
  6. package/lib/coax/cables.ts +1366 -0
  7. package/lib/coax/explorer.ts +386 -0
  8. package/lib/coax/fit.ts +78 -0
  9. package/lib/coax/format.ts +85 -0
  10. package/lib/coax/loss.ts +150 -0
  11. package/lib/coax/plot.ts +72 -0
  12. package/lib/filter/ladder/built-form.ts +133 -0
  13. package/lib/filter/ladder/forms.ts +492 -0
  14. package/lib/filter/ladder/index.ts +110 -0
  15. package/lib/filter/ladder/linear-phase.ts +52 -0
  16. package/lib/filter/ladder/poly.ts +209 -0
  17. package/lib/filter/ladder/prototype.ts +91 -0
  18. package/lib/filter/ladder/synthesis.ts +431 -0
  19. package/lib/filter/ladder/terminations.ts +212 -0
  20. package/lib/filter/part-table.ts +317 -0
  21. package/lib/filter/roots.ts +305 -0
  22. package/lib/filter/stop-floor.ts +15 -0
  23. package/lib/import/delimited.ts +260 -0
  24. package/lib/import/types.ts +42 -0
  25. package/lib/match/cx.ts +72 -0
  26. package/lib/match/eseries.ts +166 -0
  27. package/lib/match/units.ts +178 -0
  28. package/lib/reflection/metrics.ts +118 -0
  29. package/lib/rf-engine/math.ts +434 -0
  30. package/lib/schematic/export/sparams.ts +323 -0
  31. package/lib/schematic/headless/node.ts +103 -0
  32. package/lib/schematic/headless/source.ts +97 -0
  33. package/lib/schematic/headless/tools.ts +867 -0
  34. package/lib/schematic/optimize/apply.ts +109 -0
  35. package/lib/schematic/optimize/differential-evolution.ts +129 -0
  36. package/lib/schematic/optimize/fold.ts +5 -0
  37. package/lib/schematic/optimize/goals.ts +483 -0
  38. package/lib/schematic/optimize/levenberg-marquardt.ts +178 -0
  39. package/lib/schematic/optimize/nelder-mead.ts +145 -0
  40. package/lib/schematic/optimize/optimize.ts +883 -0
  41. package/lib/schematic/optimize/random-search.ts +70 -0
  42. package/lib/schematic/optimize/runtime-host.ts +155 -0
  43. package/lib/schematic/sim/ac-results.ts +144 -0
  44. package/lib/schematic/sim/cache-key.ts +170 -0
  45. package/lib/schematic/sim/data-provider.ts +14 -0
  46. package/lib/schematic/sim/dc-results.ts +186 -0
  47. package/lib/schematic/sim/hash.ts +5 -0
  48. package/lib/schematic/sim/hb-results.ts +600 -0
  49. package/lib/schematic/sim/load-pull.ts +627 -0
  50. package/lib/schematic/sim/result-cache.ts +289 -0
  51. package/lib/schematic/sim/results.ts +185 -0
  52. package/lib/schematic/sim/runtime.ts +1003 -0
  53. package/lib/schematic/sim/stb-results.ts +21 -0
  54. package/lib/schematic/storage/file-name.ts +15 -0
  55. package/lib/schematic/yield/boards.ts +265 -0
  56. package/lib/schematic/yield/host.ts +120 -0
  57. package/lib/schematic/yield/knobs.ts +170 -0
  58. package/lib/schematic/yield/stats.ts +104 -0
  59. package/lib/schematic/yield/yield.ts +339 -0
  60. package/lib/schematic-doc/designs.ts +50 -0
  61. package/lib/schematic-doc/document.ts +374 -0
  62. package/lib/schematic-doc/equalizer-synthesis.ts +1039 -0
  63. package/lib/schematic-doc/exact-decimal.ts +47 -0
  64. package/lib/schematic-doc/filter-synthesis.ts +1734 -0
  65. package/lib/schematic-doc/fit-to-data.ts +442 -0
  66. package/lib/schematic-doc/fixes.ts +802 -0
  67. package/lib/schematic-doc/flatten.ts +787 -0
  68. package/lib/schematic-doc/goal-ripple.ts +48 -0
  69. package/lib/schematic-doc/ids.ts +18 -0
  70. package/lib/schematic-doc/ir.ts +97 -0
  71. package/lib/schematic-doc/layout-map.ts +317 -0
  72. package/lib/schematic-doc/layout-twin.ts +47 -0
  73. package/lib/schematic-doc/layout.ts +444 -0
  74. package/lib/schematic-doc/make-subcircuit.ts +463 -0
  75. package/lib/schematic-doc/migrate-line-pins.ts +317 -0
  76. package/lib/schematic-doc/migrations.ts +53 -0
  77. package/lib/schematic-doc/mixed-mode.ts +84 -0
  78. package/lib/schematic-doc/model-card.ts +542 -0
  79. package/lib/schematic-doc/models.ts +304 -0
  80. package/lib/schematic-doc/names.ts +59 -0
  81. package/lib/schematic-doc/netlist-text.ts +172 -0
  82. package/lib/schematic-doc/netlister.ts +273 -0
  83. package/lib/schematic-doc/opamp-extension.ts +376 -0
  84. package/lib/schematic-doc/ops/apply.ts +2158 -0
  85. package/lib/schematic-doc/ops/index.ts +19 -0
  86. package/lib/schematic-doc/ops/marker-search.ts +87 -0
  87. package/lib/schematic-doc/ops/schema.ts +1056 -0
  88. package/lib/schematic-doc/ops/transact.ts +148 -0
  89. package/lib/schematic-doc/optimizer-objective.ts +31 -0
  90. package/lib/schematic-doc/order.ts +65 -0
  91. package/lib/schematic-doc/sat-tilt.ts +68 -0
  92. package/lib/schematic-doc/schema.ts +637 -0
  93. package/lib/schematic-doc/share.ts +70 -0
  94. package/lib/schematic-doc/sp-step.ts +108 -0
  95. package/lib/schematic-doc/spice-model.ts +194 -0
  96. package/lib/schematic-doc/spice-subckt.ts +1483 -0
  97. package/lib/schematic-doc/subckt-import.ts +183 -0
  98. package/lib/schematic-doc/substrate-block.ts +109 -0
  99. package/lib/schematic-doc/swap-em.ts +312 -0
  100. package/lib/schematic-doc/swap.ts +168 -0
  101. package/lib/schematic-doc/targets.ts +559 -0
  102. package/lib/schematic-doc/test-states.ts +335 -0
  103. package/lib/schematic-doc/tolerance.ts +333 -0
  104. package/lib/schematic-engine/node-engine.ts +51 -0
  105. package/lib/schematic-engine/pkg/rfsim_wasm.js +748 -0
  106. package/lib/schematic-engine/pkg/rfsim_wasm_bg.wasm +0 -0
  107. package/lib/schematic-engine/protocol.ts +1074 -0
  108. package/lib/schematic-engine/quantities.ts +863 -0
  109. package/lib/schematic-engine/worker-core.ts +707 -0
  110. package/lib/schematic-engine/worker-inline.ts +69 -0
  111. package/lib/schematic-engine/worker-pool.ts +1042 -0
  112. package/lib/schematic-library/param-meaning.ts +75 -0
  113. package/lib/schematic-library/param-visibility.ts +110 -0
  114. package/lib/schematic-library/pin-geometry.ts +354 -0
  115. package/lib/schematic-library/planned-models.ts +18 -0
  116. package/lib/schematic-library/schemas.gen.ts +6857 -0
  117. package/lib/schematic-library/substrates.ts +24 -0
  118. package/lib/schematic-library/transform.ts +80 -0
  119. package/lib/share/base64url.ts +25 -0
  120. package/lib/share/compress.ts +103 -0
  121. package/lib/sparam/complex.ts +129 -0
  122. package/lib/sparam/convert.ts +223 -0
  123. package/lib/sparam/format.ts +160 -0
  124. package/lib/sparam/parse-touchstone.ts +1683 -0
  125. package/lib/sparam/renormalize.ts +100 -0
  126. package/lib/sparam/tags.ts +80 -0
  127. package/lib/sparam/write-touchstone.ts +194 -0
  128. package/mcp/schematic/package.json +5 -0
  129. package/mcp/schematic/server.mjs +112 -0
  130. package/mcp/schematic/tools.mjs +265 -0
  131. package/package.json +33 -4
  132. package/scripts/lib/ts-hooks.mjs +152 -0
@@ -0,0 +1,304 @@
1
+ import type { Instance, SchematicDocument } from "./schema";
2
+ import { sortedByOrder } from "./order";
3
+ import { PLANNED_MODELS } from "../schematic-library/planned-models";
4
+ import { pinOffsetsFor, type PinOffset } from "../schematic-library/pin-geometry";
5
+ import { GENERATED_MODELS } from "../schematic-library/schemas.gen";
6
+ import { transformPoint } from "../schematic-library/transform";
7
+
8
+ /**
9
+ * Model table for the document layer. Pins, parameters, defaults, units,
10
+ * domains, `groundRef`, and `substrate` are generated from the Rust manifest
11
+ * (`lib/schematic-library/schemas.gen.ts`, `npm run schematic:codegen`), with
12
+ * planned Phase 1 models filling in until the manifest lists them. Pin
13
+ * positions come from the frozen table in `lib/schematic-library/pin-geometry.ts`.
14
+ * What stays here is presentation only: labels and reference prefixes.
15
+ */
16
+ export interface ModelParam {
17
+ name: string;
18
+ unit: string;
19
+ default: string;
20
+ /** The manifest's kind (`real`, `complex`, `int`, `enum`), or `text` for a pseudo-model's name. Absent on planned models. */
21
+ kind?: string;
22
+ }
23
+
24
+ export interface ModelPin extends PinOffset {
25
+ name: string;
26
+ }
27
+
28
+ export interface ModelInfo {
29
+ id: string;
30
+ version: number;
31
+ label: string;
32
+ description: string;
33
+ refPrefix: string;
34
+ /** Pins return through ground (ground-referenced lines and data blocks). */
35
+ groundRef: boolean;
36
+ /** Pin count comes from a loaded data block; `pins` is empty. */
37
+ pinsFromData: boolean;
38
+ /** Substrate kind the model needs (`msub`), or undefined. */
39
+ substrate?: string;
40
+ /** Declared for Phase 1 but not in the engine manifest yet; the engine rejects it. */
41
+ planned: boolean;
42
+ domains: string[];
43
+ pins: ModelPin[];
44
+ params: ModelParam[];
45
+ }
46
+
47
+ export const SYS_GND = "sys.gnd";
48
+ export const SYS_PORT = "sys.port";
49
+ export const SYS_FPORT = "sys.fport";
50
+ /** Marks a pin as left open on purpose. Not a pin for any net rule. */
51
+ export const SYS_NC = "sys.nc";
52
+ /** Names a net for a DC run. Not a pin for any net rule, and never in the IR. */
53
+ export const SYS_VPROBE = "sys.vprobe";
54
+ /** Inline 0 V current probe. A wire in an S sweep: `flattenToIr` leaves it out of `ir`. */
55
+ export const PROBE_I = "probe.i";
56
+ /** Inline loop probe (card OA-12): a short in every run, where a loop-gain run injects. A wire in an S sweep, as `probe.i` is. */
57
+ export const PROBE_LOOP = "probe.loop";
58
+ export const SUBCIRCUIT = "subcircuit";
59
+ export const DATA_SNP = "data.snp";
60
+
61
+ interface ModelPresentation {
62
+ label: string;
63
+ refPrefix: string;
64
+ }
65
+
66
+ const PRESENTATION: Record<string, ModelPresentation> = {
67
+ // DC sources and the current probe (card D2). V and I are the SPICE letters.
68
+ "src.vdc": { label: "DC voltage source", refPrefix: "V" },
69
+ "src.idc": { label: "DC current source", refPrefix: "I" },
70
+ [PROBE_I]: { label: "Current probe", refPrefix: "IP" },
71
+ // Loop probe (card OA-12): LP, a whole word, so `l 10n` stays the inductor.
72
+ [PROBE_LOOP]: { label: "Loop probe", refPrefix: "LP" },
73
+ "lumped.R": { label: "Resistor", refPrefix: "R" },
74
+ "lumped.L": { label: "Inductor", refPrefix: "L" },
75
+ "lumped.C": { label: "Capacitor", refPrefix: "C" },
76
+ "lumped.srlc": { label: "Series RLC", refPrefix: "RLC" },
77
+ "lumped.prlc": { label: "Parallel RLC", refPrefix: "RLC" },
78
+ "lumped.indq": { label: "Inductor with Q", refPrefix: "LQ" },
79
+ "lumped.capq": { label: "Capacitor with Q or ESR", refPrefix: "CQ" },
80
+ // Ideal RF blocks (card S6a, engine 0.1.7). The prefixes are three letters
81
+ // where one or two would collide with R, L, C, T or P in quick entry.
82
+ "rf.atten": { label: "Attenuator", refPrefix: "ATT" },
83
+ "rf.dcblock": { label: "DC block", refPrefix: "DCB" },
84
+ "rf.dcfeed": { label: "DC feed", refPrefix: "DCF" },
85
+ "rf.phase": { label: "Phase shifter", refPrefix: "PS" },
86
+ "rf.tf": { label: "Ideal transformer", refPrefix: "TF" },
87
+ "rf.isolator": { label: "Isolator", refPrefix: "ISO" },
88
+ "rf.amp": { label: "Gain block", refPrefix: "AMP" },
89
+ // Multi-port RF blocks (card S6b, engine 0.1.8).
90
+ "rf.circulator": { label: "Circulator", refPrefix: "CIR" },
91
+ "rf.coupler": { label: "Directional coupler", refPrefix: "CPL" },
92
+ "rf.splitter": { label: "Splitter", refPrefix: "SPL" },
93
+ // Tier-0 parts (card G4, engine 0.1.35). GYR and HYB, three letters like
94
+ // the other blocks; the stubs spell the Qucs and ADS names; Z is free.
95
+ "rf.gyrator": { label: "Gyrator", refPrefix: "GYR" },
96
+ "rf.hybrid180": { label: "180° hybrid", refPrefix: "HYB" },
97
+ "tl.tloc": { label: "Ideal open stub", refPrefix: "TLOC" },
98
+ "tl.tlsc": { label: "Ideal shorted stub", refPrefix: "TLSC" },
99
+ "lumped.z": { label: "Impedance Z(f)", refPrefix: "Z" },
100
+ // Small-signal transistors and controlled sources (card S8a, engine
101
+ // 0.1.10). Q for both transistors. The sources spell their kind: a single
102
+ // G or E would take the first letter of "gnd" in quick entry.
103
+ "dev.fet": { label: "Small-signal FET", refPrefix: "Q" },
104
+ "dev.bjt": { label: "Small-signal BJT", refPrefix: "Q" },
105
+ // The first nonlinear part (card D3, engine 0.1.21).
106
+ "dev.diode": { label: "Diode", refPrefix: "D" },
107
+ // Gummel-Poon BJT (card D5, engine 0.1.23): Q, as the other transistors.
108
+ "dev.gp": { label: "Gummel-Poon NPN", refPrefix: "Q" },
109
+ "dev.gp_pnp": { label: "Gummel-Poon PNP", refPrefix: "Q" },
110
+ // With a substrate pin (card C5, engine 0.1.32).
111
+ "dev.gp4": { label: "Gummel-Poon NPN, substrate pin", refPrefix: "Q" },
112
+ "dev.gp4_pnp": { label: "Gummel-Poon PNP, substrate pin", refPrefix: "Q" },
113
+ // Statz GaAs FET (card D7, engine 0.1.25): Q, as the other transistors.
114
+ "dev.statz": { label: "Statz GaAs FET", refPrefix: "Q" },
115
+ "ctrl.vccs": { label: "VCCS", refPrefix: "VCCS" },
116
+ "ctrl.vcvs": { label: "VCVS", refPrefix: "VCVS" },
117
+ // Op-amp (card OA-01, engine 0.1.26): U, the integrated-circuit letter.
118
+ "ana.opamp": { label: "Op-amp", refPrefix: "U" },
119
+ "tl.tlin": { label: "Ideal transmission line", refPrefix: "TL" },
120
+ "tl.tlinp": { label: "Physical transmission line", refPrefix: "TP" },
121
+ "tl.mlin": { label: "Microstrip line", refPrefix: "ML" },
122
+ "tl.mloc": { label: "Microstrip open stub", refPrefix: "MO" },
123
+ "tl.mlsc": { label: "Microstrip shorted stub", refPrefix: "MS" },
124
+ // Microstrip discontinuities (card Wave B1, engine 0.1.11). MS is the
125
+ // shorted stub's, so the step spells STEP.
126
+ "tl.mbend": { label: "Microstrip bend", refPrefix: "MB" },
127
+ "tl.mstep": { label: "Microstrip step", refPrefix: "MSTEP" },
128
+ "tl.mtee": { label: "Microstrip tee", refPrefix: "MT" },
129
+ // Coupled microstrip (card Wave B3, engine 0.1.12). MC would read as a
130
+ // microstrip corner; MCL is the Qucs and ADS spelling.
131
+ "tl.mclin": { label: "Coupled microstrip lines", refPrefix: "MCL" },
132
+ // Gap, open end and via (card Wave B2, engine 0.1.14). MO is the open
133
+ // stub's and MS the shorted stub's, so these spell the Qucs names.
134
+ "tl.mgap": { label: "Microstrip gap", refPrefix: "MGAP" },
135
+ "tl.mopen": { label: "Microstrip open end", refPrefix: "MOPEN" },
136
+ "tl.mvia": { label: "Microstrip via", refPrefix: "MVIA" },
137
+ // Cross and coupled open end (card Wave B4, engine 0.1.15). MX is free and
138
+ // reads as a crossing; MCO sits beside MCL for the pair it ends.
139
+ "tl.mcross": { label: "Microstrip cross", refPrefix: "MX" },
140
+ "tl.mcopen": { label: "Coupled microstrip open end", refPrefix: "MCO" },
141
+ // Radial stub and taper (card Wave B6, engine 0.1.17). MS is the shorted
142
+ // stub's and MT the tee's, so both spell the Qucs and ADS names.
143
+ "tl.mrstub": { label: "Microstrip radial stub", refPrefix: "MRS" },
144
+ "tl.mtaper": { label: "Microstrip taper", refPrefix: "MTP" },
145
+ // Stripline and coplanar lines (card Wave B7, engine 0.1.18).
146
+ "tl.slin": { label: "Stripline", refPrefix: "SL" },
147
+ "tl.sclin": { label: "Coupled stripline", refPrefix: "SCL" },
148
+ // Stripline open ends (card SO1, engine 0.1.47), spelled as their
149
+ // microstrip twins MOPEN and MCO.
150
+ "tl.sopen": { label: "Stripline open end", refPrefix: "SOPEN" },
151
+ "tl.scopen": { label: "Coupled stripline open end", refPrefix: "SCO" },
152
+ // Stripline via (card B9-5, engine 0.1.51), spelled as its microstrip twin
153
+ // MVIA.
154
+ "tl.svia": { label: "Stripline via", refPrefix: "SVIA" },
155
+ // N-strip striplines (card B9-3, engine 0.1.50). SCL is the pair's; SCN
156
+ // reads as coupled N.
157
+ "tl.sclin3": { label: "Coupled stripline, 3 strips", refPrefix: "SCN" },
158
+ "tl.sclin4": { label: "Coupled stripline, 4 strips", refPrefix: "SCN" },
159
+ "tl.sclin5": { label: "Coupled stripline, 5 strips", refPrefix: "SCN" },
160
+ "tl.sclin6": { label: "Coupled stripline, 6 strips", refPrefix: "SCN" },
161
+ "tl.sclin7": { label: "Coupled stripline, 7 strips", refPrefix: "SCN" },
162
+ "tl.sclin8": { label: "Coupled stripline, 8 strips", refPrefix: "SCN" },
163
+ "tl.sclin9": { label: "Coupled stripline, 9 strips", refPrefix: "SCN" },
164
+ "tl.cpw": { label: "Coplanar waveguide", refPrefix: "CPW" },
165
+ "tl.gcpw": { label: "Grounded coplanar waveguide", refPrefix: "GCPW" },
166
+ // Coax, waveguide and resonator (card B8, engine 0.1.19). Y is the crystal's
167
+ // letter on a schematic; X would read as a subcircuit.
168
+ "tl.coax": { label: "Coaxial line", refPrefix: "CX" },
169
+ "tl.rwg": { label: "Rectangular waveguide", refPrefix: "WG" },
170
+ "lumped.bvd": { label: "BVD resonator", refPrefix: "Y" },
171
+ // Coupled inductors, inverters and the coupling matrix (card Wave B5,
172
+ // engine 0.1.16). K is the SPICE letter for a coupling; the inverters spell
173
+ // their kind so a K inverter never reads as a coupling.
174
+ "lumped.mutual": { label: "Coupled inductors", refPrefix: "K" },
175
+ "proto.kinv": { label: "Impedance inverter", refPrefix: "KINV" },
176
+ "proto.jinv": { label: "Admittance inverter", refPrefix: "JINV" },
177
+ "proto.cmatrix": { label: "Coupling matrix", refPrefix: "CM" },
178
+ [DATA_SNP]: { label: "N-port data block", refPrefix: "N" },
179
+ };
180
+
181
+ const generatedIds = new Set(GENERATED_MODELS.map((m) => m.id));
182
+ const planned = PLANNED_MODELS.filter((m) => !generatedIds.has(m.id));
183
+
184
+ const ENGINE_MODELS: ModelInfo[] = [
185
+ ...GENERATED_MODELS.map((model) => ({ model, planned: false })),
186
+ ...planned.map((model) => ({ model, planned: true })),
187
+ ].map(({ model, planned: isPlanned }) => {
188
+ const look = PRESENTATION[model.id] ?? { label: model.id, refPrefix: "U" };
189
+ const offsets = model.pinsFromData ? [] : (pinOffsetsFor(model.id, model.pins.length) ?? []);
190
+ return {
191
+ id: model.id,
192
+ version: model.version,
193
+ label: look.label,
194
+ description: model.description,
195
+ refPrefix: look.refPrefix,
196
+ groundRef: model.groundRef,
197
+ pinsFromData: model.pinsFromData,
198
+ ...(model.substrate !== undefined && { substrate: model.substrate }),
199
+ planned: isPlanned,
200
+ domains: model.domains,
201
+ // A model without geometry gets no pins here; the contract test fails first.
202
+ pins: offsets.length === model.pins.length ? model.pins.map((name, i) => ({ name, ...offsets[i]! })) : [],
203
+ // dataRef travels in IrElement.dataRef, never as an instance parameter.
204
+ params: model.params
205
+ .filter((p) => p.kind !== "dataRef")
206
+ .map((p) => ({ name: p.name, unit: p.unit, default: p.default, ...(p.kind !== undefined && { kind: p.kind }) })),
207
+ };
208
+ });
209
+
210
+ const pseudo = (
211
+ id: string,
212
+ label: string,
213
+ refPrefix: string,
214
+ pinNames: readonly string[],
215
+ params: ModelParam[],
216
+ ): ModelInfo => ({
217
+ id,
218
+ version: 1,
219
+ label,
220
+ description: label,
221
+ refPrefix,
222
+ groundRef: false,
223
+ pinsFromData: false,
224
+ planned: false,
225
+ domains: [],
226
+ pins: pinOffsetsFor(id, pinNames.length)!.map((offset, i) => ({ name: pinNames[i]!, ...offset })),
227
+ params,
228
+ });
229
+
230
+ /** Document-level pseudo-models. They never reach the engine as elements. */
231
+ const PSEUDO_MODELS: ModelInfo[] = [
232
+ pseudo(SYS_GND, "Ground", "GND", ["g"], []),
233
+ pseudo(SYS_PORT, "Port", "P", ["p"], [
234
+ { name: "num", unit: "", default: "", kind: "int" },
235
+ { name: "name", unit: "", default: "", kind: "text" },
236
+ { name: "Z", unit: "Ω", default: "50", kind: "complex" },
237
+ ]),
238
+ pseudo(SYS_FPORT, "Floating port", "T", ["p", "n"], [
239
+ { name: "num", unit: "", default: "", kind: "int" },
240
+ { name: "name", unit: "", default: "", kind: "text" },
241
+ { name: "Z", unit: "Ω", default: "50", kind: "complex" },
242
+ ]),
243
+ pseudo(SYS_NC, "No connect", "NC", ["p"], []),
244
+ pseudo(SYS_VPROBE, "Voltage probe", "VP", ["p"], []),
245
+ pseudo(SUBCIRCUIT, "Subcircuit", "X", [], []),
246
+ ];
247
+
248
+ const MODEL_TABLE = new Map<string, ModelInfo>(
249
+ [...ENGINE_MODELS, ...PSEUDO_MODELS].map((model) => [model.id, model]),
250
+ );
251
+
252
+ export function getModelInfo(id: string): ModelInfo | undefined {
253
+ return MODEL_TABLE.get(id);
254
+ }
255
+
256
+ export function listModelInfos(): ModelInfo[] {
257
+ return [...MODEL_TABLE.values()];
258
+ }
259
+
260
+ export interface PinLayout {
261
+ /** 1-based pin number. */
262
+ index: number;
263
+ name: string;
264
+ x: number;
265
+ y: number;
266
+ }
267
+
268
+ /** Pin names in manifest order, or null if the instance cannot be resolved. */
269
+ export function instancePinNames(
270
+ doc: SchematicDocument,
271
+ instance: Pick<Instance, "model" | "designId" | "dataId">,
272
+ ): string[] | null {
273
+ if (instance.model === SUBCIRCUIT) {
274
+ const design = instance.designId ? doc.designs[instance.designId] : undefined;
275
+ if (!design) return null;
276
+ return sortedByOrder(design.ports).map((port) => port.name);
277
+ }
278
+ if (instance.model === DATA_SNP) {
279
+ const item = instance.dataId ? doc.data[instance.dataId] : undefined;
280
+ if (!item) return null;
281
+ return Array.from({ length: item.ports }, (_, i) => String(i + 1));
282
+ }
283
+ const info = getModelInfo(instance.model);
284
+ return info ? info.pins.map((pin) => pin.name) : null;
285
+ }
286
+
287
+ /**
288
+ * Absolute pin positions from the frozen geometry: fixed offsets per model,
289
+ * or the column rule for N-port data blocks and subcircuits. Null when the
290
+ * instance cannot be resolved.
291
+ */
292
+ export function instancePins(
293
+ doc: SchematicDocument,
294
+ instance: Instance,
295
+ ): PinLayout[] | null {
296
+ const names = instancePinNames(doc, instance);
297
+ if (!names) return null;
298
+ const offsets = pinOffsetsFor(instance.model, names.length);
299
+ if (!offsets) return null;
300
+ return names.map((name, i) => {
301
+ const { x, y } = transformPoint(instance, { x: offsets[i]!.dx, y: offsets[i]!.dy });
302
+ return { index: i + 1, name, x, y };
303
+ });
304
+ }
@@ -0,0 +1,59 @@
1
+ /** Identifier rule shared by refdes, variable, parameter and port names. */
2
+ export const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
+ /**
4
+ * Net label rule. No "/" because it is the hierarchy separator in net names,
5
+ * and `_n<digits>` is reserved for automatic net names.
6
+ */
7
+ export const NET_LABEL_RE = /^(?!_n[0-9]+$)[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
8
+
9
+ /** Names the engine rejects as variable names (`expr.reserved_name`). */
10
+ export const RESERVED_NAMES: ReadonlySet<string> = new Set([
11
+ "j",
12
+ "pi",
13
+ "e",
14
+ "c0",
15
+ "k_B",
16
+ "T0",
17
+ "freq",
18
+ "sin",
19
+ "cos",
20
+ "tan",
21
+ "asin",
22
+ "acos",
23
+ "atan",
24
+ "atan2",
25
+ "sinh",
26
+ "cosh",
27
+ "tanh",
28
+ "exp",
29
+ "ln",
30
+ "log10",
31
+ "sqrt",
32
+ "abs",
33
+ "re",
34
+ "im",
35
+ "conj",
36
+ "mag",
37
+ "phase",
38
+ "phase_deg",
39
+ "db10",
40
+ "db20",
41
+ "min",
42
+ "max",
43
+ ]);
44
+
45
+ export function variableNameProblem(name: string): string | null {
46
+ if (!IDENT_RE.test(name)) return `"${name}" is not a valid identifier.`;
47
+ if (RESERVED_NAMES.has(name)) {
48
+ return `"${name}" is reserved by the expression language.`;
49
+ }
50
+ return null;
51
+ }
52
+
53
+ /** Code-unit comparison. All sorting in the flattener uses this, never locale order. */
54
+ export function cmp(a: string, b: string): number {
55
+ return a < b ? -1 : a > b ? 1 : 0;
56
+ }
57
+
58
+ /** A net label with this name is the ground node. */
59
+ export const GROUND_LABEL = "0";
@@ -0,0 +1,172 @@
1
+ import { flattenToIr } from "./flatten";
2
+ import { extractNets, nameLocalNets } from "./netlister";
3
+ import { DATA_SNP, SUBCIRCUIT, instancePinNames } from "./models";
4
+ import { mixedModeText } from "./mixed-mode";
5
+ import { readSpSteps, type SpStep } from "./sp-step";
6
+ import { cmp } from "./names";
7
+ import { sortedByOrder } from "./order";
8
+ import type { DcSweep, HbLoadPull, HbMixer, Segment, SchematicDocument, Simulation } from "./schema";
9
+
10
+ export const NETLIST_TEXT_VERSION = "v0";
11
+
12
+ const quote = (value: string) =>
13
+ /^[A-Za-z0-9_.+\-*/^]+$/.test(value) ? value : JSON.stringify(value);
14
+
15
+ function segmentText(segment: Segment): string {
16
+ if ("lin" in segment) return `lin(${segment.lin.join(",")})`;
17
+ if ("log" in segment) return `log(${segment.log.join(",")})`;
18
+ return `list(${segment.list.join(",")})`;
19
+ }
20
+
21
+ /** A sweep's target: source=V1, var=Rb, or temp for the circuit temperature in °C (card TC2). */
22
+ function targetText(target: DcSweep["target"]): string {
23
+ if ("source" in target) return `source=${target.source}`;
24
+ if ("variable" in target) return `var=${target.variable}`;
25
+ return "temp";
26
+ }
27
+
28
+ function sweepText(sweep: DcSweep): string {
29
+ return `sweep(${targetText(sweep.target)} ${sweep.values.map(segmentText).join(" ")})`;
30
+ }
31
+
32
+ /**
33
+ * The circuit temperature (card TC2), last on the line: temp=85 for a
34
+ * simulation's own, step(temp list(-40,27,85)) for an S step over it. A line
35
+ * without either is unchanged.
36
+ */
37
+ function temperatureText(sim: Simulation, step: SpStep | undefined): string[] {
38
+ const own = "temp" in sim && sim.temp !== undefined ? [`temp=${sim.temp}`] : [];
39
+ const stepped = step?.temperature ? [`step(temp ${step.values.map(segmentText).join(" ")})`] : [];
40
+ return [...own, ...stepped];
41
+ }
42
+
43
+ function loadPullText(lp: HbLoadPull): string {
44
+ const parts = [`port=${lp.port}`];
45
+ if (lp.grid?.rhoMax !== undefined) parts.push(`rho=${lp.grid.rhoMax}`);
46
+ if (lp.grid?.n !== undefined) parts.push(`n=${lp.grid.n}`);
47
+ if (lp.list) parts.push(`list=${lp.list.map(([re, im]) => `${re},${im}`).join(";")}`);
48
+ for (const h of lp.harmonics ?? []) parts.push(`h${h.k}=${h.gamma[0]},${h.gamma[1]}`);
49
+ if (lp.refine !== undefined) parts.push(`refine=${lp.refine ? "on" : "off"}`);
50
+ return `loadpull(${parts.join(" ")})`;
51
+ }
52
+
53
+ /** A mixer (card MX2) as mixer(sweep=rf lo=P2,"1.1GHz",7 if=P3 product=-1,1 hlo=16 hrf=3 order=5), saved fields only. */
54
+ function mixerText(mx: HbMixer): string {
55
+ const parts: string[] = [];
56
+ if (mx.sweep !== undefined) parts.push(`sweep=${mx.sweep}`);
57
+ for (const key of ["lo", "rf"] as const) {
58
+ const t = mx[key];
59
+ if (t) parts.push(`${key}=${t.port},${quote(t.freq)},${t.power}`);
60
+ }
61
+ if (mx.ifPort !== undefined) parts.push(`if=${mx.ifPort}`);
62
+ if (mx.ifProduct !== undefined) parts.push(`product=${mx.ifProduct[0]},${mx.ifProduct[1]}`);
63
+ if (mx.loHarmonics !== undefined) parts.push(`hlo=${mx.loHarmonics}`);
64
+ if (mx.rfHarmonics !== undefined) parts.push(`hrf=${mx.rfHarmonics}`);
65
+ if (mx.maxOrder !== undefined) parts.push(`order=${mx.maxOrder}`);
66
+ return `mixer(${parts.join(" ")})`;
67
+ }
68
+
69
+ /** What follows `sim <id> <kind>`: the frequency plan (S and AC), the HB setup, or `op` for a DC operating point. */
70
+ function simulationPlan(sim: Simulation): string {
71
+ // A differential port map (card MM1) follows the plan as diff=(1,3),(2,4); a line without one is unchanged.
72
+ if (sim.kind === "sp") return [...sim.freq.map(segmentText), ...(sim.mixedMode ? [mixedModeText(sim.mixedMode)] : [])].join(" ");
73
+ if (sim.kind === "ac") return sim.freq.map(segmentText).join(" ");
74
+ // A loop-gain run (card OA-12): its probe, then its frequency plan.
75
+ if (sim.kind === "stb") return [`probe=${sim.probe}`, ...sim.freq.map(segmentText)].join(" ");
76
+ // A harmonic balance (card HB3): its tone, harmonics, driven port and power plan in dBm.
77
+ if (sim.kind === "hb") {
78
+ // A second tone (card IM2) adds its spacing and, when saved, its order; a one-tone line is unchanged.
79
+ const second = sim.twoTone ? [`spacing=${quote(sim.twoTone.spacing)}`, ...(sim.twoTone.order !== undefined ? [`order=${sim.twoTone.order}`] : [])] : [];
80
+ // A load tuner (card LP2) follows as loadpull(port=T2 rho=0.9 n=13 h2=-0.98,0 refine=off), saved fields only; a line without one is unchanged.
81
+ const tuner = sim.loadPull ? [loadPullText(sim.loadPull)] : [];
82
+ // A mixer (card MX2) follows last; f0, port and the powers are then the swept tone. A line without one is unchanged.
83
+ const mixer = sim.mixer ? [mixerText(sim.mixer)] : [];
84
+ return [`f0=${quote(sim.f0)}`, `harmonics=${sim.harmonics}`, ...second, `port=${sim.drive.port}`, ...sim.drive.power.map(segmentText), ...tuner, ...mixer].join(" ");
85
+ }
86
+ return sim.sweeps.length === 0 ? "op" : sim.sweeps.map(sweepText).join(" ");
87
+ }
88
+
89
+ /**
90
+ * Netlist text DSL v0 (export only). One line per statement, nets by name in
91
+ * pin order, ground is "0":
92
+ *
93
+ * netlist v0
94
+ * var f0 = 2.4G
95
+ * data D1 touchstone sha256=<hex> ports=2
96
+ * substrate sub1 msub "RO4350B 20 mil" H=20mil Er=3.66
97
+ * design main "Main" top
98
+ * param W = 1u
99
+ * var w2 = 2*W
100
+ * port in
101
+ * P1 sys.port (in) num=1 Z=50
102
+ * C1 lumped.C (in out) C=1p
103
+ * X1 sub:filter (a b) W=2u
104
+ * ML1 tl.mlin (in out) substrate=sub1 W=1.1mm L=10mm
105
+ * end
106
+ * sim S1 sp lin(1G,3G,201)
107
+ * sim S4 sp lin(1G,4G,301) diff=1,(2,3) a differential port map: single-ended 1, pair (2,3)
108
+ * sim S2 dc op
109
+ * sim S3 dc sweep(source=V1 lin(0,5,51)) sweep(var=Rb list(1k,10k))
110
+ * sim S5 dc sweep(temp lin(-40,125,166)) a temperature sweep in °C (card TC2)
111
+ * sim S6 sp lin(10M,5G,101) temp=85 step(temp list(-40,27,85)) a circuit temperature and a step over it
112
+ *
113
+ * Disabled and shorted instances keep their line with a `disabled` or
114
+ * `shorted` flag after the nets. Output is deterministic.
115
+ */
116
+ export function exportNetlistText(doc: SchematicDocument): string {
117
+ const lines: string[] = [`netlist ${NETLIST_TEXT_VERSION}`, `title ${JSON.stringify(doc.meta.name)}`];
118
+ // The top design uses the IR node names, so text and engine agree. Other
119
+ // designs (and a top design that fails ERC) use scope-local names.
120
+ let topNames = new Map<number, string>();
121
+ flattenToIr(doc, (names) => {
122
+ topNames = names;
123
+ });
124
+ for (const v of sortedByOrder(doc.variables)) lines.push(`var ${v.name} = ${quote(v.expr)}`);
125
+ for (const d of sortedByOrder(doc.data)) {
126
+ lines.push(`data ${d.id} ${d.format} sha256=${d.sha256} ports=${d.ports}${d.hasNoise ? " noise" : ""}`);
127
+ }
128
+ for (const sub of sortedByOrder(doc.substrates)) {
129
+ const params = Object.keys(sub.params)
130
+ .sort(cmp)
131
+ .map((key) => ` ${key}=${quote(sub.params[key]!)}`)
132
+ .join("");
133
+ lines.push(`substrate ${sub.id} ${sub.kind} ${JSON.stringify(sub.name)}${params}`);
134
+ }
135
+ for (const design of sortedByOrder(doc.designs)) {
136
+ lines.push(
137
+ `design ${design.id} ${JSON.stringify(design.name)}${design.id === doc.topDesignId ? " top" : ""}`,
138
+ );
139
+ for (const p of sortedByOrder(design.params)) lines.push(` param ${p.name} = ${quote(p.default)}`);
140
+ for (const v of sortedByOrder(design.variables)) lines.push(` var ${v.name} = ${quote(v.expr)}`);
141
+ for (const p of sortedByOrder(design.ports)) lines.push(` port ${p.name}`);
142
+ const nets = extractNets(doc, design);
143
+ const local = nameLocalNets(nets.nets);
144
+ const names = design.id === doc.topDesignId ? new Map([...local, ...topNames]) : local;
145
+ const instances = Object.values(design.sheet.instances).sort((a, b) => cmp(a.refdes, b.refdes));
146
+ for (const instance of instances) {
147
+ const pinNames = instancePinNames(doc, instance) ?? [];
148
+ const netNames = pinNames.map((_, i) => {
149
+ const net = nets.netOfPin(instance.id, i + 1);
150
+ return (net && names.get(net.index)) ?? "?";
151
+ });
152
+ const model =
153
+ instance.model === SUBCIRCUIT ? `sub:${instance.designId}` : instance.model;
154
+ const parts = [` ${instance.refdes}`, model, `(${netNames.join(" ")})`];
155
+ if (instance.state !== "enabled") parts.push(instance.state);
156
+ if (instance.model === DATA_SNP) parts.push(`data=${instance.dataId}`);
157
+ if (instance.substrateId !== undefined) parts.push(`substrate=${instance.substrateId}`);
158
+ for (const key of Object.keys(instance.params).sort(cmp)) {
159
+ parts.push(`${key}=${quote(instance.params[key]!)}`);
160
+ }
161
+ lines.push(parts.join(" "));
162
+ }
163
+ lines.push("end");
164
+ }
165
+ const steps: Record<string, SpStep> = readSpSteps(doc).steps;
166
+ for (const sim of sortedByOrder(doc.simulations)) {
167
+ lines.push(
168
+ `sim ${sim.id} ${sim.kind}${sim.enabled ? "" : " disabled"} ${[simulationPlan(sim), ...temperatureText(sim, steps[sim.id])].join(" ")}`,
169
+ );
170
+ }
171
+ return lines.join("\n") + "\n";
172
+ }