multisim2kicad 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -717,6 +717,1690 @@ function parseCiNetlist(input) {
717
717
  };
718
718
  }
719
719
 
720
+ // src/parse/dchip.ts
721
+ var spiceName = (s) => s.replace(/[^A-Za-z0-9_]/g, "_");
722
+ var SCALE = { f: 0.000000000000001, p: 0.000000000001, n: 0.000000001, u: 0.000001, m: 0.001, k: 1000, meg: 1e6, g: 1e9 };
723
+ function seconds(v) {
724
+ const m = /^([-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(meg|[fpnumkg])?s?$/i.exec(v.trim());
725
+ if (!m)
726
+ return;
727
+ return Number(m[1]) * (m[2] ? SCALE[m[2].toLowerCase()] : 1);
728
+ }
729
+ function behaviourText(modelText) {
730
+ const m = /behaviou?r\s*=\s*"([\s\S]*?)"/i.exec(modelText);
731
+ return m?.[1];
732
+ }
733
+ function parseChip(modelText) {
734
+ const text = behaviourText(modelText);
735
+ if (text === undefined)
736
+ throw new Error("no behaviour string");
737
+ const newModule = (name) => ({ name, inputs: [], outputs: [], wires: [], delays: new Map, zDelays: new Map, instances: [] });
738
+ const top = newModule("");
739
+ const modules = new Map;
740
+ let cur = top;
741
+ const stack = [];
742
+ let want;
743
+ let asyncLeft = 0;
744
+ const addDelay = (out, rise, fall, z = false) => {
745
+ if (rise === undefined && fall === undefined)
746
+ return;
747
+ const map = z ? cur.zDelays : cur.delays;
748
+ const d = map.get(out) ?? { rise: 0, fall: 0 };
749
+ d.rise = Math.max(d.rise, rise ?? (z ? 0 : fall) ?? 0);
750
+ d.fall = Math.max(d.fall, fall ?? (z ? 0 : rise) ?? 0);
751
+ map.set(out, d);
752
+ };
753
+ for (const raw of text.replace(/\r\n?/g, `
754
+ `).split(`
755
+ `)) {
756
+ if (/^\s*\*/.test(raw))
757
+ continue;
758
+ const line = raw.replace(/^\s*\+/, "").replace(/;.*$/, "").trim();
759
+ if (!line)
760
+ continue;
761
+ const tokens = line.split(/\s+/);
762
+ if (line.startsWith("/")) {
763
+ want = undefined;
764
+ const dir = tokens[0].toLowerCase();
765
+ const args = tokens.slice(1);
766
+ const count = (i) => {
767
+ const n = Number(args[i]);
768
+ if (!Number.isInteger(n) || n < 0)
769
+ throw new Error(`${dir}: bad count ${args[i]}`);
770
+ return n;
771
+ };
772
+ switch (dir) {
773
+ case "/inputs":
774
+ cur.inputs.push(...args);
775
+ break;
776
+ case "/outputs":
777
+ cur.outputs.push(...args);
778
+ break;
779
+ case "/wires":
780
+ cur.wires.push(...args);
781
+ break;
782
+ case "/module": {
783
+ stack.push(cur);
784
+ cur = newModule(args[0] ?? "");
785
+ modules.set(cur.name.toLowerCase(), cur);
786
+ break;
787
+ }
788
+ case "/endmodule":
789
+ cur = stack.pop() ?? top;
790
+ break;
791
+ case "/instance":
792
+ cur.instances.push({ module: args[0] ?? "", args: args.slice(1) });
793
+ break;
794
+ case "/table":
795
+ cur.table = [];
796
+ want = { kind: "table", left: count(0) };
797
+ break;
798
+ case "/clock": {
799
+ const edge = (args[1] ?? "").toUpperCase();
800
+ if (edge !== "+" && edge !== "-" && edge !== "X")
801
+ throw new Error(`/clock: edge ${args[1]}`);
802
+ cur.clock = { input: args[0] ?? "", edge, flags: count(2), sync: [], async: [] };
803
+ want = { kind: "sync", left: count(3) };
804
+ asyncLeft = count(4);
805
+ if (want.left === 0)
806
+ want = { kind: "async", left: asyncLeft };
807
+ break;
808
+ }
809
+ case "/delay":
810
+ want = { kind: "delay", left: args.length ? count(0) : Infinity };
811
+ break;
812
+ case "/conditional_delay":
813
+ want = { kind: "cdelay", left: args.length ? count(0) : Infinity };
814
+ break;
815
+ case "/constraint":
816
+ want = { kind: "skip", left: Infinity };
817
+ break;
818
+ default:
819
+ throw new Error(`unknown directive ${tokens[0]}`);
820
+ }
821
+ continue;
822
+ }
823
+ if (!want || want.left <= 0)
824
+ throw new Error(`unexpected row: ${line}`);
825
+ want.left--;
826
+ switch (want.kind) {
827
+ case "table":
828
+ cur.table.push(tokens);
829
+ break;
830
+ case "sync":
831
+ cur.clock.sync.push(tokens);
832
+ if (want.left === 0)
833
+ want = { kind: "async", left: asyncLeft };
834
+ break;
835
+ case "async":
836
+ cur.clock.async.push(tokens);
837
+ break;
838
+ case "delay": {
839
+ if (tokens.length < 4)
840
+ throw new Error(`/delay row: ${line}`);
841
+ addDelay(tokens[1], seconds(tokens[2]), seconds(tokens[3]));
842
+ break;
843
+ }
844
+ case "cdelay": {
845
+ const t = seconds(tokens[tokens.length - 1]);
846
+ const out = tokens[tokens.length - 3];
847
+ const event = tokens[0].toUpperCase();
848
+ if (event.includes("Z"))
849
+ addDelay(out, event.startsWith("Z") ? t : undefined, event.endsWith("Z") ? t : undefined, true);
850
+ else
851
+ addDelay(out, event.endsWith("L") ? undefined : t, event.endsWith("H") ? undefined : t);
852
+ break;
853
+ }
854
+ case "skip":
855
+ break;
856
+ }
857
+ }
858
+ if (stack.length)
859
+ throw new Error(`module ${cur.name} has no /endmodule`);
860
+ return { top, modules };
861
+ }
862
+ function splitRows(rows, nIn, nOut, what) {
863
+ return rows.map((tokens) => {
864
+ let ins = "";
865
+ let i = 0;
866
+ while (ins.length < nIn) {
867
+ const t = tokens[i++];
868
+ if (t === undefined || !/^[LHXZ01]+$/i.test(t))
869
+ throw new Error(`${what}: row "${tokens.join(" ")}" has too few input columns`);
870
+ ins += t.toUpperCase();
871
+ }
872
+ if (ins.length !== nIn)
873
+ throw new Error(`${what}: row "${tokens.join(" ")}" does not split into ${nIn} inputs`);
874
+ let outs = tokens.slice(i);
875
+ if (outs.length !== nOut)
876
+ outs = outs.flatMap((t) => /^[LHXZ]+$/i.test(t) ? [...t] : [t]);
877
+ if (outs.length !== nOut)
878
+ throw new Error(`${what}: row "${tokens.join(" ")}" does not have ${nOut} outputs`);
879
+ return { ins: ins.replace(/0/g, "L").replace(/1/g, "H").replace(/Z/g, "X"), outs };
880
+ });
881
+ }
882
+ function outputFn(token, c, what) {
883
+ const t = token;
884
+ const constant = { L: "0", H: "1", X: "X", Z: "Z", "0": "0", "1": "1" }[t.toUpperCase()];
885
+ if (constant)
886
+ return { read: [], value: () => constant };
887
+ const names = [...c.inputs, ...Array.from({ length: c.flags }, () => "\x00"), ...c.outputs, ...c.extra ?? []];
888
+ const find = (name) => {
889
+ let i = names.indexOf(name);
890
+ if (i < 0)
891
+ i = names.findIndex((n) => n.toLowerCase() === name.toLowerCase());
892
+ return i;
893
+ };
894
+ const bit = (b, invert) => (b ^ (invert ? 1 : 0)) === 1 ? "1" : "0";
895
+ const direct = find(t);
896
+ if (direct >= 0)
897
+ return { read: [direct], value: (col) => bit(col(direct), false) };
898
+ if (t.startsWith("~") && find(t.slice(1)) >= 0) {
899
+ const i = find(t.slice(1));
900
+ return { read: [i], value: (col) => bit(col(i), true) };
901
+ }
902
+ const base = c.inputs.length;
903
+ const flag = /^(~?)F(\d+)$/i.exec(t);
904
+ if (flag && Number(flag[2]) < c.flags) {
905
+ const i = base + Number(flag[2]);
906
+ return { read: [i], value: (col) => bit(col(i), !!flag[1]) };
907
+ }
908
+ const count = /^F([+-])(\d+)$/i.exec(t);
909
+ if (count && Number(count[2]) < c.flags) {
910
+ const k = Number(count[2]);
911
+ const read = Array.from({ length: k + 1 }, (_, j) => base + j);
912
+ return {
913
+ read,
914
+ value: (col) => {
915
+ let n = 0;
916
+ for (let j = 0;j <= k; j++)
917
+ n |= col(base + j) << j;
918
+ n = (n + (count[1] === "+" ? 1 : -1) + (2 << k)) % (2 << k);
919
+ return n >> k & 1 ? "1" : "0";
920
+ }
921
+ };
922
+ }
923
+ throw new Error(`${what}: unknown output value ${token}`);
924
+ }
925
+ var MAX_LUT_INPUTS = 10;
926
+ function cofactor(f, fixed) {
927
+ const rows = [];
928
+ const cols = new Set(f.fallbackReads);
929
+ for (let r = 0;r < f.rows.length; r++) {
930
+ const ins = f.rows[r].ins;
931
+ let possible = true;
932
+ for (const [i, v] of fixed)
933
+ if (ins[i] === "L" && v === 1 || ins[i] === "H" && v === 0)
934
+ possible = false;
935
+ if (!possible)
936
+ continue;
937
+ rows.push(r);
938
+ [...ins].forEach((ch, i) => ch !== "X" && cols.add(i));
939
+ for (const i of outputFn(f.rows[r].outs[f.out], f.columns, f.what).read)
940
+ cols.add(i);
941
+ if ([...ins].every((ch, i) => ch === "X" || fixed.has(i)))
942
+ break;
943
+ }
944
+ return { rows, support: [...cols].filter((i) => !fixed.has(i)).sort((a, b) => a - b) };
945
+ }
946
+ function truthTable(f, fixed) {
947
+ const { rows, support: sup } = cofactor(f, fixed);
948
+ let support = sup;
949
+ const fns = new Map(rows.map((r) => [r, outputFn(f.rows[r].outs[f.out], f.columns, f.what)]));
950
+ const pick = f.pick ?? ((v) => v);
951
+ const evaluate = (assign) => {
952
+ const col = (i) => assign.get(i) ?? fixed.get(i) ?? 0;
953
+ for (const r of rows) {
954
+ const ins = f.rows[r].ins;
955
+ let ok = true;
956
+ for (let i = 0;i < ins.length && ok; i++) {
957
+ const ch = ins[i];
958
+ if (ch === "L")
959
+ ok = col(i) === 0;
960
+ else if (ch === "H")
961
+ ok = col(i) === 1;
962
+ }
963
+ if (ok)
964
+ return pick(fns.get(r).value(col), f.rows[r].outs[f.out]);
965
+ }
966
+ return f.fallback(col);
967
+ };
968
+ let table = "";
969
+ for (let idx = 0;idx < 1 << support.length; idx++) {
970
+ const assign = new Map;
971
+ support.forEach((c, j) => assign.set(c, idx >> j & 1));
972
+ table += evaluate(assign);
973
+ }
974
+ for (let j = support.length - 1;j >= 0; j--) {
975
+ const half = 1 << j;
976
+ let same = true;
977
+ for (let idx = 0;idx < table.length && same; idx++)
978
+ if (!(idx & half) && table[idx] !== table[idx | half])
979
+ same = false;
980
+ if (!same)
981
+ continue;
982
+ let reduced = "";
983
+ for (let idx = 0;idx < table.length; idx++)
984
+ if (!(idx & half))
985
+ reduced += table[idx];
986
+ table = reduced;
987
+ support = support.filter((_, k) => k !== j);
988
+ }
989
+ return { support, table };
990
+ }
991
+ var TINY = "1e-12";
992
+
993
+ class Emitter {
994
+ base;
995
+ lines = [];
996
+ enables = new Map;
997
+ aliases = new Map;
998
+ models = new Map;
999
+ used = new Set;
1000
+ n = 0;
1001
+ constructor(base) {
1002
+ this.base = base;
1003
+ }
1004
+ node(hint) {
1005
+ const s = spiceName(hint) || "x";
1006
+ let n = s.startsWith("n_") ? s : `n_${s}`;
1007
+ while (this.used.has(n.toLowerCase()))
1008
+ n += "_";
1009
+ this.used.add(n.toLowerCase());
1010
+ return n;
1011
+ }
1012
+ reserve(name) {
1013
+ let n = spiceName(name) || "p";
1014
+ if (/^\d/.test(n))
1015
+ n = `p${n}`;
1016
+ while (this.used.has(n.toLowerCase()))
1017
+ n += "_";
1018
+ this.used.add(n.toLowerCase());
1019
+ return n;
1020
+ }
1021
+ model(type, params) {
1022
+ const def = `${type}(${params})`;
1023
+ let name = this.models.get(def);
1024
+ if (!name) {
1025
+ name = `${this.base}_${type.replace(/^d_/, "")}${this.models.size}`;
1026
+ this.models.set(def, name);
1027
+ }
1028
+ return name;
1029
+ }
1030
+ element(text) {
1031
+ this.lines.push(`a${++this.n} ${text}`);
1032
+ }
1033
+ modelLines() {
1034
+ return [...this.models].map(([def, name]) => `.model ${name} ${def}`);
1035
+ }
1036
+ }
1037
+ var fmt = (s) => String(Number(s.toPrecision(6)));
1038
+ var delayParams = (d) => `rise_delay=${d && d.rise > 0 ? fmt(d.rise) : TINY} fall_delay=${d && d.fall > 0 ? fmt(d.fall) : TINY}`;
1039
+ function lut(em, inputs, out, table, d) {
1040
+ em.element(`[${inputs.join(" ")}] ${out} ${em.model("d_lut", `table_values="${table}" ${delayParams(d)}`)}`);
1041
+ }
1042
+ function emitFn(em, f, fixed, colNode, out, d, depth = 0) {
1043
+ const { support } = cofactor(f, fixed);
1044
+ if (support.length <= MAX_LUT_INPUTS) {
1045
+ const t = truthTable(f, fixed);
1046
+ if (t.support.length === 0)
1047
+ lut(em, [colNode(support[0] ?? 0)], out, t.table + t.table, d);
1048
+ else
1049
+ lut(em, t.support.map(colNode), out, t.table, d);
1050
+ return;
1051
+ }
1052
+ if (depth > 24)
1053
+ throw new Error(`${f.what}: cannot split a ${support.length}-column function`);
1054
+ let best = support[0];
1055
+ let bestCost = Infinity;
1056
+ for (const x of support) {
1057
+ const cost = Math.max(...[0, 1].map((v) => cofactor(f, new Map([...fixed, [x, v]])).support.length));
1058
+ if (cost < bestCost)
1059
+ [best, bestCost] = [x, cost];
1060
+ }
1061
+ const halves = [0, 1].map((v) => {
1062
+ const n = em.node(`${out}_${v}`);
1063
+ emitFn(em, f, new Map([...fixed, [best, v]]), colNode, n, undefined, depth + 1);
1064
+ return n;
1065
+ });
1066
+ lut(em, [halves[0], halves[1], colNode(best)], out, "01010011", d);
1067
+ }
1068
+ function canBeOne(f) {
1069
+ return f.rows.some((r) => {
1070
+ const token = r.outs[f.out];
1071
+ const fn = outputFn(token, f.columns, f.what);
1072
+ if (fn.read.length === 0)
1073
+ return f.pick(fn.value(() => 0), token) === "1";
1074
+ return f.pick("1", token) === "1" || f.pick("0", token) === "1";
1075
+ });
1076
+ }
1077
+ function flatten(chip, mod, ports, em, scope, depth) {
1078
+ if (depth > 8)
1079
+ throw new Error("modules nested too deep");
1080
+ const what = mod.name || "top level";
1081
+ const local = new Map(ports);
1082
+ const net = (name) => {
1083
+ let n = local.get(name);
1084
+ if (!n) {
1085
+ n = em.node(`${scope}${name}`);
1086
+ local.set(name, n);
1087
+ }
1088
+ return n;
1089
+ };
1090
+ for (const w of mod.wires)
1091
+ net(w);
1092
+ const fromTable = new Set(mod.table || mod.clock ? mod.outputs : []);
1093
+ const delayedPre = new Map;
1094
+ for (const [out, d] of mod.delays) {
1095
+ if (fromTable.has(out) || !mod.outputs.includes(out))
1096
+ continue;
1097
+ const pre = em.node(`${scope}${out}_pre`);
1098
+ delayedPre.set(out, pre);
1099
+ em.element(`${pre} ${net(out)} ${em.model("d_buffer", delayParams(d))}`);
1100
+ em.aliases.set(net(out), pre);
1101
+ }
1102
+ mod.instances.forEach((inst, k) => {
1103
+ const sub = chip.modules.get(inst.module.toLowerCase());
1104
+ if (!sub)
1105
+ throw new Error(`${what}: no module ${inst.module}`);
1106
+ const pins = [...sub.inputs, ...sub.outputs];
1107
+ if (inst.args.length !== pins.length)
1108
+ throw new Error(`${what}: /instance ${inst.module} has ${inst.args.length} of ${pins.length} pins`);
1109
+ const bind = new Map;
1110
+ pins.forEach((p, i) => {
1111
+ const a = inst.args[i];
1112
+ bind.set(p, i >= sub.inputs.length && delayedPre.get(a) || net(a));
1113
+ });
1114
+ flatten(chip, sub, bind, em, `${scope}${spiceName(inst.module)}${k}_`, depth + 1);
1115
+ });
1116
+ if (!mod.table && !mod.clock)
1117
+ return;
1118
+ const flags = mod.clock?.flags ?? 0;
1119
+ const columns = { inputs: mod.inputs, flags, outputs: mod.outputs };
1120
+ const inNodes = mod.inputs.map(net);
1121
+ const flagNodes = Array.from({ length: flags }, (_, k) => em.node(`${scope}F${k}`));
1122
+ const colNode = (i) => i < inNodes.length ? inNodes[i] : i < inNodes.length + flags ? flagNodes[i - inNodes.length] : net(mod.outputs[i - inNodes.length - flags]);
1123
+ if (!inNodes.length && !flags)
1124
+ throw new Error(`${what}: no inputs`);
1125
+ const nCols = mod.inputs.length + flags;
1126
+ const none = new Map;
1127
+ const isZ = (t) => /^z$/i.test(t);
1128
+ const flagEnables = [];
1129
+ const enName = (k) => ` EN${k}`;
1130
+ if (mod.clock) {
1131
+ const c = mod.clock;
1132
+ const sync = splitRows(c.sync, nCols, flags, `${what} /clock`);
1133
+ const asynZ = splitRows(c.async, nCols, flags, `${what} /clock`);
1134
+ const asyn = asynZ.map((r) => ({ ins: r.ins, outs: r.outs.map((t, j) => isZ(t) ? `F${j}` : t) }));
1135
+ const clkIndex = mod.inputs.indexOf(c.input);
1136
+ if (clkIndex < 0)
1137
+ throw new Error(`${what}: clock ${c.input} is not an input`);
1138
+ let clk = inNodes[clkIndex];
1139
+ if (c.edge === "-") {
1140
+ const inv = em.node(`${scope}${c.input}_n`);
1141
+ em.element(`${clk} ${inv} ${em.model("d_inverter", delayParams())}`);
1142
+ clk = inv;
1143
+ } else if (c.edge === "X") {
1144
+ const low = em.node(`${scope}clk0`);
1145
+ em.element(`${low} ${em.model("d_pulldown", "")}`);
1146
+ clk = low;
1147
+ }
1148
+ for (let k = 0;k < flags; k++) {
1149
+ const own = mod.inputs.length + k;
1150
+ let data = flagNodes[k];
1151
+ if (c.edge !== "X") {
1152
+ data = em.node(`${scope}F${k}_next`);
1153
+ const f = { rows: sync, out: k, columns, fallback: (col) => col(own) ? "1" : "0", fallbackReads: [own], what: `${what} /clock sync` };
1154
+ emitFn(em, f, none, colNode, data);
1155
+ }
1156
+ const isHold = (token) => token.toUpperCase() === `F${k}`;
1157
+ const pins = ["1", "0"].map((want) => {
1158
+ const f = {
1159
+ rows: asyn,
1160
+ out: k,
1161
+ columns,
1162
+ fallback: () => "0",
1163
+ fallbackReads: [],
1164
+ pick: (v, token) => isHold(token) ? "0" : v === want ? "1" : "0",
1165
+ what: `${what} /clock async`
1166
+ };
1167
+ if (!canBeOne(f))
1168
+ return "NULL";
1169
+ const n = em.node(`${scope}F${k}_${want === "1" ? "set" : "reset"}`);
1170
+ emitFn(em, f, none, colNode, n);
1171
+ return n;
1172
+ });
1173
+ if (asynZ.some((r) => isZ(r.outs[k]))) {
1174
+ const en = em.node(`${scope}F${k}_en`);
1175
+ const rows = asynZ.map((r) => ({ ins: r.ins, outs: r.outs.map((t) => isZ(t) ? "L" : "H") }));
1176
+ emitFn(em, { rows, out: k, columns, fallback: () => "1", fallbackReads: [], what: `${what} /clock enable` }, none, colNode, en);
1177
+ flagEnables[k] = en;
1178
+ }
1179
+ em.element(`${data} ${clk} ${pins[0]} ${pins[1]} ${flagNodes[k]} NULL ${em.model("d_dff", `clk_delay=${TINY} set_delay=${TINY} reset_delay=${TINY} ${delayParams()}`)}`);
1180
+ }
1181
+ }
1182
+ if (mod.table) {
1183
+ const rows = splitRows(mod.table, nCols, mod.outputs.length, `${what} /table`);
1184
+ const enColumns = { ...columns, extra: Array.from({ length: flags }, (_, k) => enName(k)) };
1185
+ const enNode = (i) => i >= nCols + mod.outputs.length ? flagEnables[i - nCols - mod.outputs.length] : colNode(i);
1186
+ mod.outputs.forEach((out, o) => {
1187
+ const f = { rows, out: o, columns, fallback: () => "X", fallbackReads: [], what: `${what} /table` };
1188
+ emitFn(em, f, none, colNode, net(out), mod.delays.get(out));
1189
+ const enToken = (t) => {
1190
+ if (isZ(t))
1191
+ return "L";
1192
+ const k = /^~?F(\d+)$/i.exec(t)?.[1];
1193
+ return k !== undefined && flagEnables[Number(k)] && !mod.inputs.includes(t) ? enName(Number(k)) : "H";
1194
+ };
1195
+ const enRows = rows.map((r) => ({ ins: r.ins, outs: r.outs.map(enToken) }));
1196
+ if (enRows.some((r) => r.outs[o] !== "H")) {
1197
+ const en = em.node(`${net(out)}_en`);
1198
+ emitFn(em, { rows: enRows, out: o, columns: enColumns, fallback: () => "1", fallbackReads: [], what: `${what} /table enable` }, none, enNode, en, mod.zDelays.get(out) ?? mod.delays.get(out));
1199
+ em.enables.set(net(out), en);
1200
+ }
1201
+ });
1202
+ } else if (mod.clock && mod.outputs.length === flags) {
1203
+ mod.outputs.forEach((out, k) => {
1204
+ em.element(`${flagNodes[k]} ${net(out)} ${em.model("d_buffer", delayParams(mod.delays.get(out)))}`);
1205
+ if (flagEnables[k])
1206
+ em.enables.set(net(out), flagEnables[k]);
1207
+ });
1208
+ } else if (mod.clock) {
1209
+ throw new Error(`${what}: clocked module without an output /table`);
1210
+ }
1211
+ }
1212
+ function dchipSubckt(name, modelText) {
1213
+ const chip = parseChip(modelText);
1214
+ if (!chip.top.outputs.length)
1215
+ throw new Error("no /outputs");
1216
+ if (!chip.top.table && !chip.top.clock && !chip.top.instances.length)
1217
+ throw new Error("no logic (/table, /clock or /instance)");
1218
+ const safe = spiceName(name);
1219
+ const em = new Emitter(safe);
1220
+ const ports = new Map;
1221
+ const portNodes = [];
1222
+ for (const p of [...chip.top.inputs, ...chip.top.outputs]) {
1223
+ if (ports.has(p))
1224
+ throw new Error(`pin ${p} listed twice`);
1225
+ const n = em.reserve(p);
1226
+ ports.set(p, n);
1227
+ portNodes.push(n);
1228
+ }
1229
+ flatten(chip, chip.top, ports, em, "", 0);
1230
+ const enables = [];
1231
+ chip.top.outputs.forEach((p, j) => {
1232
+ const node = ports.get(p);
1233
+ const pre = em.aliases.get(node);
1234
+ const en = em.enables.get(node) ?? (pre ? em.enables.get(pre) : undefined);
1235
+ if (!en)
1236
+ return;
1237
+ const port = em.reserve(`${p}_en`);
1238
+ em.element(`${en} ${port} ${em.model("d_buffer", delayParams())}`);
1239
+ portNodes.push(port);
1240
+ enables.push(j);
1241
+ });
1242
+ const header = `* Multisim d_chip ${name}, translated: ${chip.top.inputs.join(" ")} -> ${chip.top.outputs.join(" ")}`;
1243
+ const text = [header, `.subckt ${safe} ${portNodes.join(" ")}`, ...em.lines, ...em.modelLines(), `.ends ${safe}`].join(`
1244
+ `);
1245
+ return { name: safe, pins: portNodes.length, inputs: chip.top.inputs.length, outputs: chip.top.outputs.length, enables, text };
1246
+ }
1247
+ function translateDChips(text) {
1248
+ const chips = new Map;
1249
+ const errors = [];
1250
+ const generated = [];
1251
+ const src = text.replace(/\r\n?/g, `
1252
+ `);
1253
+ if (!/\bd_chip\b/i.test(src))
1254
+ return { text, chips, errors };
1255
+ const re = /^[ \t]*\.model[ \t]+(\S+)[ \t]+d_chip\b[^"]*"[^"]*"[ \t]*\)?[ \t]*$/gim;
1256
+ let out = src.replace(re, (whole, name) => {
1257
+ try {
1258
+ const sub = dchipSubckt(name, whole);
1259
+ const chip = { name: sub.name, pins: sub.pins, inputs: sub.inputs, outputs: sub.outputs, enables: sub.enables };
1260
+ chips.set(name.toLowerCase(), chip);
1261
+ chips.set(sub.name.toLowerCase(), chip);
1262
+ generated.push(sub.text);
1263
+ return "";
1264
+ } catch (e) {
1265
+ errors.push(`d_chip ${name} not translated: ${e.message}`);
1266
+ return whole;
1267
+ }
1268
+ });
1269
+ if (!chips.size)
1270
+ return { text, chips, errors };
1271
+ out = rewriteDChipInstances(out, chips, errors);
1272
+ return { text: `${generated.join(`
1273
+
1274
+ `)}
1275
+
1276
+ ${out.trim()}`, chips, errors };
1277
+ }
1278
+ function rewriteDChipInstances(text, chips, errors = [], enables) {
1279
+ const joined = text.replace(/\r\n?/g, `
1280
+ `).replace(/\n[ \t]*\+/g, " ");
1281
+ return joined.replace(/^([ \t]*)(a\S*)[ \t]+\[([^\]]*)\][ \t]*\[([^\]]*)\][ \t]*(\S+)[ \t]*$/gim, (whole, indent, inst, ins, outs, model) => {
1282
+ const chip = chips.get(model.toLowerCase());
1283
+ if (!chip)
1284
+ return whole;
1285
+ const list = (s) => s.trim().split(/\s+/).filter(Boolean);
1286
+ const i = list(ins);
1287
+ const o = list(outs);
1288
+ if (i.length < chip.inputs || o.length < chip.outputs) {
1289
+ errors.push(`${inst}: ${i.length} inputs / ${o.length} outputs for d_chip ${model}, which has ${chip.inputs} / ${chip.outputs}`);
1290
+ return whole;
1291
+ }
1292
+ const en = chip.enables.map((j) => `${o[j]}_en`);
1293
+ for (const n of en)
1294
+ enables?.add(n);
1295
+ return `${indent}x${inst} ${[...i.slice(0, chip.inputs), ...o.slice(0, chip.outputs), ...en].join(" ")} ${chip.name}`;
1296
+ });
1297
+ }
1298
+
1299
+ // src/parse/spice.ts
1300
+ function parkingX(page) {
1301
+ const xs = [
1302
+ page.size.width + 40 + 100,
1303
+ ...page.symbols.filter((s) => !s.simOnly).map((s) => s.at.x),
1304
+ ...page.wires.flatMap((w) => w.points.map((q) => q.x)),
1305
+ ...page.labels.map((l) => l.at.x)
1306
+ ];
1307
+ return Math.max(...xs) + 60;
1308
+ }
1309
+ function supplySymbols(sheets, page) {
1310
+ const warnings = [];
1311
+ const firstByNet = new Map;
1312
+ for (const sheet of sheets) {
1313
+ for (const s of sheet.symbols) {
1314
+ if (s.kind !== "power" || !s.sim?.device || s.sim.exclude || s.pins.length !== 1)
1315
+ continue;
1316
+ const first = firstByNet.get(s.value);
1317
+ if (!first)
1318
+ firstByNet.set(s.value, s);
1319
+ else if (first.sim.name !== s.sim.name)
1320
+ warnings.push(`supply ${s.value}: symbols disagree (${first.sim.name} vs ${s.sim.name}); simulating the first`);
1321
+ }
1322
+ }
1323
+ const symbols = [];
1324
+ const x = parkingX(page);
1325
+ let y = 20;
1326
+ let n = 0;
1327
+ for (const [net, p] of firstByNet) {
1328
+ const pin = p.pins[0];
1329
+ const tip = { x: Math.round(x / 5) * 5, y: Math.round(y / 5) * 5 };
1330
+ const at = { x: tip.x - pin.at.x, y: tip.y - pin.at.y };
1331
+ const copy = { ...p, at, transform: { a: 1, b: 0, c: 0, d: 1 }, floating: false, drawnKey: undefined, sim: undefined, simOnly: true };
1332
+ const node = p.sim.pins?.[0]?.[1];
1333
+ if (!node)
1334
+ continue;
1335
+ symbols.push(copy, {
1336
+ reference: `SUP${++n}`,
1337
+ value: `${net} source`,
1338
+ kind: "part",
1339
+ at: tip,
1340
+ transform: { a: 1, b: 0, c: 0, d: 1 },
1341
+ graphics: [
1342
+ { kind: "circle", center: { x: 6, y: 0 }, radius: 3, width: 0, fill: false },
1343
+ { kind: "polyline", points: [{ x: 5, y: 0 }, { x: 7, y: 0 }], width: 0, fill: false },
1344
+ { kind: "polyline", points: [{ x: 6, y: -1 }, { x: 6, y: 1 }], width: 0, fill: false }
1345
+ ],
1346
+ pins: [{ name: net, number: "1", at: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, length: 3, electrical: "passive" }],
1347
+ refText: { text: `SUP${n}`, at: { x: 10, y: -2 }, hidden: false },
1348
+ valueText: { text: `${net} source`, at: { x: 10, y: 2 }, hidden: false },
1349
+ showPinNames: false,
1350
+ showPinNumbers: false,
1351
+ simOnly: true,
1352
+ sim: { ...p.sim, pins: [["1", node]] }
1353
+ });
1354
+ y += 30;
1355
+ }
1356
+ return { symbols, warnings };
1357
+ }
1358
+ var spiceName2 = (s) => s.replace(/[^A-Za-z0-9_]/g, "_");
1359
+ function logicalLines(text) {
1360
+ const out = [];
1361
+ for (const raw of text.replace(/\r\n?/g, `
1362
+ `).split(`
1363
+ `)) {
1364
+ if (/^\s*\+/.test(raw) && out.length)
1365
+ out[out.length - 1] += " " + raw.replace(/^\s*\+/, "");
1366
+ else
1367
+ out.push(raw);
1368
+ }
1369
+ return out;
1370
+ }
1371
+ function inlineResistorModels(text) {
1372
+ const models = new Map;
1373
+ const kept = text.replace(/^[ \t]*\.model[ \t]+(vres\S*)[ \t]+r[ \t]*\(([^)]*)\)[ \t]*$/gim, (_, name, params) => {
1374
+ const tc = [...params.matchAll(/\b(TC[12])\s*=\s*(\S+)/gi)].map((m) => `${m[1].toLowerCase()}=${m[2]}`);
1375
+ models.set(name.toLowerCase(), tc.join(" "));
1376
+ return "";
1377
+ });
1378
+ if (!models.size)
1379
+ return text;
1380
+ return kept.replace(/^([ \t]*r\S+[ \t]+\S+[ \t]+\S+[ \t]+\S+)[ \t]+(vres\S*)(.*)$/gim, (m, head, name, rest) => {
1381
+ const tc = models.get(name.toLowerCase());
1382
+ return tc === undefined ? m : `${head}${rest.trimEnd()}${tc ? ` ${tc}` : ""}`;
1383
+ }).replace(/\n{2,}/g, `
1384
+ `).trim();
1385
+ }
1386
+ var RESERVED_PARAMS = new Set(["min", "max", "abs", "sqrt", "exp", "ln", "log", "log10", "sin", "cos", "tan", "atan", "sinh", "cosh", "tanh", "pow", "pwr", "sgn", "floor", "ceil", "int", "limit", "if", "table"]);
1387
+ function renameReservedParams(text) {
1388
+ if (!/\bparams:/i.test(text))
1389
+ return text;
1390
+ const reserved = (name) => RESERVED_PARAMS.has(name.toLowerCase());
1391
+ const lines = text.split(`
1392
+ `);
1393
+ const groups = [];
1394
+ for (const l of lines) {
1395
+ if (/^\s*\+/.test(l) && groups.length)
1396
+ groups.at(-1).push(l);
1397
+ else
1398
+ groups.push([l]);
1399
+ }
1400
+ let renames;
1401
+ const out = [];
1402
+ for (const g of groups) {
1403
+ const joined = g.join(" ");
1404
+ if (/^\s*\.ends\b/i.test(joined))
1405
+ renames = undefined;
1406
+ const isHeader = /^\s*\.subckt\b/i.test(joined);
1407
+ if (isHeader) {
1408
+ const names = [...(/\bparams:(.*)$/i.exec(joined)?.[1] ?? "").matchAll(/\b([A-Za-z_]\w*)\s*=/g)].map((m) => m[1]).filter(reserved);
1409
+ renames = names.length ? new RegExp(`\\b(${names.join("|")})\\b(?!\\s*[(=])`, "gi") : undefined;
1410
+ }
1411
+ let afterParams = false;
1412
+ for (const line of g) {
1413
+ const at = afterParams ? 0 : /\bparams:/i.exec(line)?.index ?? -1;
1414
+ let l = line;
1415
+ if (at >= 0) {
1416
+ afterParams = true;
1417
+ l = l.slice(0, at) + l.slice(at).replace(/\b([A-Za-z_]\w*)(\s*=)/g, (m, n, eq) => reserved(n) ? `p_${n}${eq}` : m);
1418
+ }
1419
+ out.push(renames && !isHeader && !/^\s*\*/.test(l) ? l.replace(renames, "p_$1") : l);
1420
+ }
1421
+ }
1422
+ return out.join(`
1423
+ `);
1424
+ }
1425
+ function sdtToIntegrator(text) {
1426
+ if (!/\bsdt\s*\(/i.test(text))
1427
+ return text;
1428
+ let n = 0;
1429
+ const lines = text.split(`
1430
+ `);
1431
+ const out = [];
1432
+ const pending = [];
1433
+ const rewrite = (s) => {
1434
+ let r = "";
1435
+ let i = 0;
1436
+ for (;; ) {
1437
+ const m = /\bsdt\s*\(/gi;
1438
+ m.lastIndex = i;
1439
+ const hit = m.exec(s);
1440
+ if (!hit)
1441
+ return r + s.slice(i);
1442
+ let depth = 1;
1443
+ let j = hit.index + hit[0].length;
1444
+ for (;j < s.length && depth; j++)
1445
+ depth += s[j] === "(" ? 1 : s[j] === ")" ? -1 : 0;
1446
+ const arg = rewrite(s.slice(hit.index + hit[0].length, j - 1));
1447
+ const k = ++n;
1448
+ pending.push(`Bew_sdt${k} ew_sdt${k}_in 0 V={${arg}}`, `aew_sdt${k} ew_sdt${k}_in ew_sdt${k} ew_sdt${k}_int`, `.model ew_sdt${k}_int int(gain=1 out_ic=0 out_lower_limit=-1e12 out_upper_limit=1e12 limit_range=1e-6)`);
1449
+ r += `${s.slice(i, hit.index)}V(ew_sdt${k})`;
1450
+ i = j;
1451
+ }
1452
+ };
1453
+ lines.forEach((line, i) => {
1454
+ out.push(/^\s*\*/.test(line) ? line : rewrite(line));
1455
+ if (pending.length && !/^\s*\+/.test(lines[i + 1] ?? ""))
1456
+ out.push(...pending.splice(0));
1457
+ });
1458
+ return out.join(`
1459
+ `);
1460
+ }
1461
+ var polyMul = (a, b) => {
1462
+ const out = new Array(a.length + b.length - 1).fill(0);
1463
+ a.forEach((x, i) => b.forEach((y, j) => out[i + j] += x * y));
1464
+ return out;
1465
+ };
1466
+ var polyAdd = (a, b) => Array.from({ length: Math.max(a.length, b.length) }, (_, i) => (a[i] ?? 0) + (b[i] ?? 0));
1467
+ var SPICE_SCALE = { t: 1000000000000, g: 1e9, meg: 1e6, k: 1000, mil: 0.0000254, m: 0.001, u: 0.000001, n: 0.000000001, p: 0.000000000001, f: 0.000000000000001 };
1468
+ function parseLaplace(expr) {
1469
+ const tokens = expr.match(/\d+\.?\d*(?:e[-+]?\d+)?(?:meg|mil|[tgkmunpf])?[a-z]*|\.\d+(?:e[-+]?\d+)?(?:meg|mil|[tgkmunpf])?[a-z]*|[A-Za-z_]\w*|\*\*|[-+*/^()]|\S/gi) ?? [];
1470
+ let i = 0;
1471
+ const peek = () => tokens[i];
1472
+ const constant = (r) => r.num.length === 1 && r.den.length === 1 && r.delay === 0;
1473
+ const value = (r) => r.num[0] / r.den[0];
1474
+ const fail = () => {
1475
+ throw new Error("unsupported");
1476
+ };
1477
+ const atom = () => {
1478
+ const t = tokens[i++] ?? fail();
1479
+ if (t === "(") {
1480
+ const r = sum();
1481
+ if (tokens[i++] !== ")")
1482
+ fail();
1483
+ return r;
1484
+ }
1485
+ if (t === "-") {
1486
+ const r = power();
1487
+ return { ...r, num: r.num.map((x) => -x) };
1488
+ }
1489
+ if (t === "+")
1490
+ return power();
1491
+ if (/^s$/i.test(t))
1492
+ return { num: [0, 1], den: [1], delay: 0 };
1493
+ const num = /^(\d+\.?\d*(?:e[-+]?\d+)?|\.\d+(?:e[-+]?\d+)?)(meg|mil|[tgkmunpf])?[a-z]*$/i.exec(t);
1494
+ if (num)
1495
+ return { num: [Number(num[1]) * (num[2] ? SPICE_SCALE[num[2].toLowerCase()] : 1)], den: [1], delay: 0 };
1496
+ const isE = /^e$/i.test(t) && (peek() === "^" || peek() === "**");
1497
+ if (isE || /^exp$/i.test(t) && peek() === "(") {
1498
+ if (isE)
1499
+ i++;
1500
+ const x = atom();
1501
+ if (x.delay !== 0 || x.den.length !== 1 || x.num.length !== 2 || x.num[0] !== 0)
1502
+ fail();
1503
+ const T = -x.num[1] / x.den[0];
1504
+ if (!(T >= 0))
1505
+ fail();
1506
+ return { num: [1], den: [1], delay: T };
1507
+ }
1508
+ return fail();
1509
+ };
1510
+ const power = () => {
1511
+ const base = atom();
1512
+ if (peek() !== "^" && peek() !== "**")
1513
+ return base;
1514
+ i++;
1515
+ const e = atom();
1516
+ if (!constant(e) || !Number.isInteger(value(e)))
1517
+ fail();
1518
+ const n = value(e);
1519
+ let r = { num: [1], den: [1], delay: 0 };
1520
+ for (let k = 0;k < Math.abs(n); k++)
1521
+ r = { num: polyMul(r.num, base.num), den: polyMul(r.den, base.den), delay: r.delay + base.delay };
1522
+ return n < 0 ? { num: r.den, den: r.num, delay: -r.delay } : r;
1523
+ };
1524
+ const product = () => {
1525
+ let r = power();
1526
+ while (peek() === "*" || peek() === "/") {
1527
+ const op = tokens[i++];
1528
+ const b = power();
1529
+ r = op === "*" ? { num: polyMul(r.num, b.num), den: polyMul(r.den, b.den), delay: r.delay + b.delay } : { num: polyMul(r.num, b.den), den: polyMul(r.den, b.num), delay: r.delay - b.delay };
1530
+ }
1531
+ return r;
1532
+ };
1533
+ const sum = () => {
1534
+ let r = product();
1535
+ while (peek() === "+" || peek() === "-") {
1536
+ const op = tokens[i++];
1537
+ const b = product();
1538
+ if (b.delay !== r.delay)
1539
+ fail();
1540
+ const bn = op === "-" ? b.num.map((x) => -x) : b.num;
1541
+ r = { num: polyAdd(polyMul(r.num, b.den), polyMul(bn, r.den)), den: polyMul(r.den, b.den), delay: r.delay };
1542
+ }
1543
+ return r;
1544
+ };
1545
+ try {
1546
+ const r = sum();
1547
+ if (i !== tokens.length || r.delay < 0)
1548
+ return;
1549
+ const trim = (p) => {
1550
+ const q = [...p];
1551
+ while (q.length > 1 && q.at(-1) === 0)
1552
+ q.pop();
1553
+ return q;
1554
+ };
1555
+ return { num: trim(r.num), den: trim(r.den), delay: r.delay };
1556
+ } catch {
1557
+ return;
1558
+ }
1559
+ }
1560
+ function laplaceToXspice(text, warnings) {
1561
+ return text.replace(/^([ \t]*)([EG]\S*)[ \t]+(\S+)[ \t]+(\S+)[ \t]+LAPLACE[ \t]*=?[ \t]*\{([^{}]*)\}[ \t]*=?[ \t]*\{([^{}]*)\}[ \t]*$/gim, (all, ind, name, p, n, input, h) => {
1562
+ const r = parseLaplace(h);
1563
+ if (!r || r.num.length > r.den.length || r.den.every((x) => x === 0)) {
1564
+ warnings?.push(`${name}: LAPLACE ${h.trim()} is not a rational function of s (plus a delay) with numeric coefficients; left as is`);
1565
+ return all;
1566
+ }
1567
+ const b = `ew_lap_${spiceName2(name)}`;
1568
+ const fmt = (x) => Number(x.toPrecision(12)).toString();
1569
+ const coeffs = (poly) => `[${[...poly].reverse().map(fmt).join(" ")}]`;
1570
+ const src = r.delay > 0 ? `${b}_d` : `${b}_in`;
1571
+ return [
1572
+ `${ind}* ${name}: LAPLACE {${input.trim()}} {${h.trim()}} as XSPICE s_xfer`,
1573
+ `${ind}B${b} ${b}_in 0 V={${input}}`,
1574
+ ...r.delay > 0 ? [`${ind}T${b} ${b}_in 0 ${b}_d 0 Z0=1 TD=${fmt(r.delay)}`, `${ind}R${b} ${b}_d 0 1`] : [],
1575
+ `${ind}a${b} ${src} ${b}_out ${b}_xfer`,
1576
+ `${ind}.model ${b}_xfer s_xfer(gain=1 num_coeff=${coeffs(r.num)} den_coeff=${coeffs(r.den)})`,
1577
+ `${ind}${name} ${p} ${n} ${b}_out 0 1`
1578
+ ].join(`
1579
+ `);
1580
+ });
1581
+ }
1582
+ function schmittBridges(text) {
1583
+ const schmitt = new Map;
1584
+ let out = text.replace(/^([ \t]*\.model[ \t]+(\S+)[ \t]+)\(?[ \t]*adc_bridge\b[ \t]*\(([^)]*)\).*$/gim, (m, head, name, params) => {
1585
+ if (!/\bschmitt[ \t]*=[ \t]*true\b/i.test(params))
1586
+ return m;
1587
+ const value = (p) => Number(new RegExp(`\\b${p}\\s*=\\s*([^\\s)]+)`, "i").exec(params)?.[1]);
1588
+ const low = value("in_low");
1589
+ const high = value("in_high");
1590
+ if (!Number.isFinite(low) || !Number.isFinite(high) || high <= low)
1591
+ return m.replace(/\bschmitt[ \t]*=[ \t]*true\b/i, "");
1592
+ schmitt.set(name.toLowerCase(), { low, high });
1593
+ const mid = (low + high) / 2;
1594
+ const half = (high - low) / 2;
1595
+ const w = Math.min(half / 10, 0.01);
1596
+ return [
1597
+ `${head}adc_bridge (in_low=0.5 in_high=0.5)`,
1598
+ `${head.replace(/(\S+)([ \t]+)$/, "$1_hyst$2")}hyst (in_low=${fmtNum(mid - w)} in_high=${fmtNum(mid + w)} hyst=${fmtNum(half)} out_lower_limit=0 out_upper_limit=1 input_domain=0.01 fraction=false)`
1599
+ ].join(`
1600
+ `);
1601
+ });
1602
+ if (!schmitt.size)
1603
+ return text;
1604
+ out = out.replace(/^([ \t]*)(a\S+)([ \t]+)\[[ \t]*([^\s\]]+)[ \t]*\]([ \t]+\[[^\]]*\][ \t]+)(\S+)[ \t]*$/gim, (m, ind, a, sp, input, rest, model) => {
1605
+ if (!schmitt.has(model.toLowerCase()))
1606
+ return m;
1607
+ const mid = `${a}_hy`;
1608
+ return `${ind}${a}_h ${input} ${mid} ${model}_hyst
1609
+ ${ind}${a}${sp}[${mid}]${rest}${model}`;
1610
+ });
1611
+ return out;
1612
+ }
1613
+ var fmtNum = (x) => String(Number(x.toPrecision(6)));
1614
+ function capacitorIcNodesets(text) {
1615
+ if (!/\bic[ \t]*=/i.test(text))
1616
+ return text;
1617
+ return text.replace(/^([ \t]*)C\S*[ \t]+(\S+)[ \t]+(\S+)[ \t]+[^\n]*?\bIC[ \t]*=[ \t]*([-+]?[0-9.]+(?:e[-+]?\d+)?[a-z]*)[ \t]*$/gim, (m, ind, a, b, v) => {
1618
+ const neg = (x) => x.startsWith("-") ? x.slice(1) : `-${x.replace(/^\+/, "")}`;
1619
+ if (b === "0")
1620
+ return `${m}
1621
+ ${ind}.nodeset V(${a})=${v}`;
1622
+ if (a === "0")
1623
+ return `${m}
1624
+ ${ind}.nodeset V(${b})=${neg(v)}`;
1625
+ return m;
1626
+ });
1627
+ }
1628
+ function ngspiceDialect(text) {
1629
+ return capacitorIcNodesets(schmittBridges(laplaceToXspice(sdtToIntegrator(renameReservedParams(inlineResistorModels(text)))))).replace(/^[ \t]*\.mergenodes[ \t]+(\S+)[ \t]+(\S+)[ \t]*$/gim, (_, a, b) => `Rmerge_${spiceName2(a)}_${spiceName2(b)} ${a} ${b} 1u`).replace(/\)[ \t]*uselim\b/gi, ")").replace(/^([ \t]*)VT(?=[ \t])/gim, "$1VTx").replace(/\bI\([ \t]*VT[ \t]*\)/gi, "I(VTx)").replace(/^([ \t]*\.model[ \t]+\S+[ \t]+\(?[ \t]*)(a2vhdl|vhdl2a)\b/gim, (_, head, type) => `${head}${type.toLowerCase() === "a2vhdl" ? "adc_bridge" : "dac_bridge"}`).replace(/^([ \t]*\.model[ \t]+\S+[ \t]+)\(?[ \t]*d_constsource\b[ \t]*(\([^)]*\))?.*$/gim, (_, head, params = "") => `${head}${/\bstate[ \t]*=[ \t]*0*1\b/i.test(params) ? "d_pullup" : "d_pulldown"}`);
1630
+ }
1631
+ function modelDef(localName, textIn) {
1632
+ const dchips = translateDChips(textIn);
1633
+ const text = dchips.text;
1634
+ const lines = logicalLines(text);
1635
+ const want = spiceName2(localName).toLowerCase();
1636
+ const heads = lines.map((l) => /^\s*\.(subckt|model)\s+(\S+)(.*)$/i.exec(l)).filter((m) => !!m);
1637
+ const head = heads.find((m) => spiceName2(m[2]).toLowerCase() === want) ?? heads[0];
1638
+ if (!head)
1639
+ return;
1640
+ const kind = head[1].toLowerCase();
1641
+ const original = head[2];
1642
+ const name = /^\d+$/.test(spiceName2(original)) ? `m${spiceName2(original)}` : spiceName2(original);
1643
+ const nodes = kind === "subckt" ? head[3].replace(/[;$].*$/, "").replace(/\bparams:.*$/i, "").trim().split(/\s+/).filter((t) => t && !t.includes("=")) : [];
1644
+ const escaped = original.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1645
+ const renamed = ngspiceDialect(text.replace(/\r\n?/g, `
1646
+ `)).replace(new RegExp(`^([ \\t]*\\.${kind}[ \\t]+)${escaped}(?=\\s|\\(|$)`, "gim"), `$1${name}`).replace(new RegExp(`^([ \\t]*\\.ends[ \\t]+)${escaped}(?=\\s|$)`, "gim"), (m, head) => kind === "subckt" ? `${head}${name}` : m);
1647
+ const dchip = kind === "subckt" ? dchips.chips.get(original.toLowerCase()) : undefined;
1648
+ return { name, kind, nodes, text: renamed.trim(), ...dchip && { dchip: { ...dchip, name } }, ...dchips.errors.length > 0 && { issues: dchips.errors } };
1649
+ }
1650
+ var truthy = (v) => {
1651
+ if (v === undefined)
1652
+ return false;
1653
+ const t = v.trim();
1654
+ if (!t)
1655
+ return false;
1656
+ const n = Number(t);
1657
+ return Number.isNaN(n) ? true : n !== 0;
1658
+ };
1659
+ function expandTemplate(template, o) {
1660
+ const raw = (i) => (o.params[i] ?? "").trim();
1661
+ const usesCircuitParam = (v) => [...v.matchAll(/[A-Za-z_]\w*/g)].some((m) => o.circuitParams?.has(m[0].toLowerCase()));
1662
+ const param = (i, inExpression) => {
1663
+ const v = raw(i);
1664
+ return v && !inExpression && !isSpiceNumber(v) && !/^[{"'[]/.test(v) && usesCircuitParam(v) ? `{${v}}` : v;
1665
+ };
1666
+ const inExpression = (s, at) => {
1667
+ const line = s.slice(s.lastIndexOf(`
1668
+ `, at) + 1, at);
1669
+ const open = (c, d) => line.split(c).length - line.split(d).length;
1670
+ return open("{", "}") > 0 || /[=]\s*\(/.test(line) && open("(", ")") > 0;
1671
+ };
1672
+ const conditionals = template.replace(/%%/g, "\x00").replace(/%v(\d+)\?([\s\S]*?)%v:([\s\S]*?)%v;/g, (_, n, a, b) => truthy(o.params[Number(n)]) ? a : b).replace(/%v:([\s\S]*?)%v;/g, "").replace(/%v(\d+)\?([\s\S]*)$/, (_, n, a) => truthy(o.params[Number(n)]) ? a : "");
1673
+ return conditionals.replace(/%f(\d+)(?::(\d+):(\d+))?/g, (_, s, l, k) => {
1674
+ if (!l || !k)
1675
+ return param(Number(s), true);
1676
+ const step = Number(k) || 1;
1677
+ const count = Math.floor(Number(raw(Number(l))) / step) || 0;
1678
+ return Array.from({ length: count }, (_, j) => param(Number(s) + j * step, false)).filter(Boolean).join(" ");
1679
+ }).replace(/%[sS](\d+)/g, (_, n) => {
1680
+ const s = o.strings?.[Number(n)] ?? "";
1681
+ return s === "Param" ? "" : s;
1682
+ }).replace(/%t([^\s?]+)\?%t:([a-z]*)%t;[^\s\]]*/g, (_, t, prefix) => o.digital?.(t, prefix || "d") ?? `${prefix || "d"}_${spiceName2(t)}`).replace(/%t([^\s\]]+)/g, (_, t) => {
1683
+ const n = o.node(t);
1684
+ if (n === undefined)
1685
+ o.missing?.(t);
1686
+ return n ?? t;
1687
+ }).replace(/#(\d+)/g, (_, n, at, s) => param(Number(n), inExpression(s, at))).replace(/%p/g, o.ref).replace(/%m/g, o.model ?? "").replace(/\u0000/g, "%").replace(/%vd\s+\(/g, "%vd(");
1688
+ }
1689
+ var netlistTemplate = (comp) => collValues(ciCollStrings(comp)[1])[5] ?? "";
1690
+ var isSpiceNumber = (v) => /^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?[a-zµ]*$/i.test(v);
1691
+ function componentParams(comp, list = "parameters") {
1692
+ const pl = comp.child("Attributes")?.find("CiaParamList");
1693
+ return pl?.child(list)?.childrenNamed("Item").map((i) => i.str("Value")) ?? [];
1694
+ }
1695
+ function circuitParams(root) {
1696
+ const out = new Map;
1697
+ for (const ext of root.findAll("CCircuitParamSheetGroupExtension")) {
1698
+ const names = ext.find("CircuitParamNameList")?.childrenNamed("CircuitParamName").map((n) => n.str("NameItem")) ?? [];
1699
+ const values = ext.find("CircuitParamValueList")?.childrenNamed("CircuitParamValue").map((v) => v.str("ValueItem")) ?? [];
1700
+ const pairs = names.map((n, i) => [n.trim(), (values[i] ?? "").trim()]).filter(([n, v]) => /^[A-Za-z_]\w*$/.test(n) && v).map(([n, v]) => `.param ${n}=${isSpiceNumber(v) ? v : `{${v}}`}`);
1701
+ if (!pairs.length)
1702
+ continue;
1703
+ if (pairs.some((p) => /\bpi\b/i.test(p)) && !names.some((n) => n.toLowerCase() === "pi"))
1704
+ pairs.unshift(".param pi=3.141592653589793");
1705
+ const sheet = ext.closest((e) => e.has("SheetName"))?.str("SheetName") ?? "";
1706
+ out.set(sheet, [...out.get(sheet)?.split(`
1707
+ `) ?? [], ...pairs].join(`
1708
+ `));
1709
+ }
1710
+ return out;
1711
+ }
1712
+ function modelText(model) {
1713
+ return model.child("Attributes")?.find("CiaCString")?.str("String") ?? "";
1714
+ }
1715
+ function staticPot(lines) {
1716
+ if (!lines.includes("!!!BEGIN-INTERACT"))
1717
+ return lines;
1718
+ const total = Number(/^\*\s*(\S+)\s+constant\s+potvalue\b/im.exec(lines)?.[1]);
1719
+ const setting = Number(/^\*\s*(\S+)\s+VARIABLE\s+setting\b/im.exec(lines)?.[1]);
1720
+ if (!Number.isFinite(total) || !Number.isFinite(setting))
1721
+ return lines;
1722
+ const factor = Math.min(0.9999999, Math.max(0.0000001, setting / 100));
1723
+ const r1 = total * factor;
1724
+ const values = { R1: r1, R2: total - r1 };
1725
+ return lines.replace(/^(R[12])(\s+\S+\s+\S+\s+)\S+\s*$/gim, (m, name, nodes) => values[name.toUpperCase()] !== undefined ? `${name}${nodes}${Number(values[name.toUpperCase()].toPrecision(6))}` : m);
1726
+ }
1727
+ var NGSPICE_MODEL_TYPES = new Set(("r c l d npn pnp nmos pmos njf pjf nmf pmf sw csw ltra urc txl cpl vdmos res cap ind vswitch iswitch " + "aswitch climit cmeter core d_dt divide gain hyst ilimit int limit lmeter mult multi_input_pwl oneshot pwl " + "s_xfer sine slew square summer triangle file_source zener lcouple potentiometer delay " + "d_and d_nand d_or d_nor d_xor d_xnor d_inverter d_buffer d_tristate d_open_c d_open_e d_pullup d_pulldown " + "d_dff d_jkff d_tff d_srff d_dlatch d_srlatch d_state d_fsim d_osc d_source d_ram d_lut d_genlut d_pwm d_process " + "adc_bridge dac_bridge d_to_real real_delay real_gain real_to_v").split(" "));
1728
+ function unsupportedModelType(text) {
1729
+ for (const m of text.matchAll(/^[ \t]*\.model[ \t]+\S+[ \t]+\(?[ \t]*([A-Za-z_][A-Za-z0-9_]*)/gim)) {
1730
+ const type = m[1].toLowerCase();
1731
+ if (!NGSPICE_MODEL_TYPES.has(type))
1732
+ return type;
1733
+ }
1734
+ const source = /^[ \t]*[EG]\S*[ \t]+\S+[ \t]+\S+[ \t]+(FREQ|LAPLACE)\b/im.exec(text);
1735
+ return source ? `PSpice ${source[1].toUpperCase()}` : undefined;
1736
+ }
1737
+ var R_TEMPLATE = /^r%p %t1 %t2 #1 vres%p /;
1738
+ var CL_TEMPLATE = /^([cl])%p %t1 %t2 #1 %v4\?IC=#5%v:%v;\s*$/;
1739
+ var SUBCKT_TEMPLATE = /^x%p(?:_\w+)?((?:\s+%t\S+)+)\s+%m\s*$/;
1740
+ function pinModelDef(id, text) {
1741
+ const ideal = text.replace(/\r\n?/g, `
1742
+ `).replace(/^\*#L2[^\n]*\n[\s\S]*?^\*#L2[^\n]*(\n|$)/gm, "");
1743
+ return modelDef(id, dacOutputResistance(ideal));
1744
+ }
1745
+ function dacOutputResistance(text) {
1746
+ const dacs = new Set([...text.matchAll(/^[ \t]*\.model[ \t]+(\S+)[ \t]+\(?[ \t]*(?:dac_bridge|vhdl2a)\b/gim)].map((m) => m[1].toLowerCase()));
1747
+ if (!dacs.size)
1748
+ return text;
1749
+ return text.replace(/^([ \t]*)(a\S+)([ \t]+\[[^\]]*\][ \t]+)\[[ \t]*([^\s\]]+)[ \t]*\]([ \t]+)(\S+)[ \t]*$/gim, (m, ind, a, input, out, sp, model) => {
1750
+ if (!dacs.has(model.toLowerCase()))
1751
+ return m;
1752
+ const mid = `${out}_${a}_ro`;
1753
+ return `${ind}${a}${input}[${mid}]${sp}${model}
1754
+ ${ind}R${a}_ro ${mid} ${out} 1m`;
1755
+ });
1756
+ }
1757
+ var enableVariants = new WeakMap;
1758
+ function enablePinModel(pm) {
1759
+ const known = enableVariants.get(pm);
1760
+ if (known !== undefined)
1761
+ return known ?? undefined;
1762
+ const hiz = new Map;
1763
+ let text = pm.model.text.replace(/^([ \t]*\.model[ \t]+(\S+)[ \t]+)\(?[ \t]*(?:dac_hiz|vhdl2hiz)\b[ \t]*(\([^)]*\))?.*$/gim, (_, head, name, params = "") => {
1764
+ const value = (p) => new RegExp(`\\b${p}\\s*=\\s*([^\\s)]+)`, "i").exec(params)?.[1];
1765
+ const on = value("out_enabled") ?? "5";
1766
+ const off = value("out_disabled") ?? "0";
1767
+ hiz.set(name.toLowerCase(), name);
1768
+ return `${head}dac_bridge (out_low=${off} out_high=${on} out_undef=${off})`;
1769
+ });
1770
+ let variant;
1771
+ if (hiz.size && pm.model.kind === "subckt") {
1772
+ const name = `${pm.model.name}_EN`;
1773
+ text = text.replace(/^([ \t]*a\S+[ \t]+)\[[^\]]*\]([ \t]*\[[^\]]*\][ \t]+)(\S+)[ \t]*$/gim, (m, a, b, model) => hiz.has(model.toLowerCase()) ? `${a}[en]${b}${model}` : m).replace(/^([ \t]*\.subckt[ \t]+)(\S+)([^\n]*)/im, (_, a, _n, nodes) => `${a}${name}${nodes.trimEnd()} en`).replace(/^([ \t]*\.ends)[ \t]+\S+/im, `$1 ${name}`);
1774
+ variant = {
1775
+ model: { ...pm.model, name, text, nodes: [...pm.model.nodes, "en"] },
1776
+ template: pm.template.replace(/%m\s*$/, "%tEN %m")
1777
+ };
1778
+ }
1779
+ enableVariants.set(pm, variant ?? null);
1780
+ return variant;
1781
+ }
1782
+ function hoistSubckts(text) {
1783
+ const body = [];
1784
+ const blocks = [];
1785
+ let cur = [];
1786
+ let depth = 0;
1787
+ for (const line of text.split(`
1788
+ `)) {
1789
+ if (/^\s*\.subckt\s/i.test(line))
1790
+ depth++;
1791
+ if (depth > 0)
1792
+ cur.push(line);
1793
+ else
1794
+ body.push(line);
1795
+ if (depth > 0 && /^\s*\.ends\b/i.test(line)) {
1796
+ depth--;
1797
+ if (depth === 0) {
1798
+ blocks.push(cur.join(`
1799
+ `));
1800
+ cur = [];
1801
+ }
1802
+ }
1803
+ }
1804
+ if (cur.length)
1805
+ body.push(...cur);
1806
+ return { body: body.join(`
1807
+ `), blocks };
1808
+ }
1809
+
1810
+ class SpiceLibrary {
1811
+ models = new Map;
1812
+ wrappers = new Map;
1813
+ names = new Set;
1814
+ texts = [];
1815
+ warnings = [];
1816
+ useModel(m) {
1817
+ const prev = this.models.get(m.name);
1818
+ if (prev !== undefined && prev !== m.text)
1819
+ this.warnings.push(`model ${m.name}: two different definitions; keeping the first`);
1820
+ if (prev === undefined)
1821
+ this.models.set(m.name, m.text);
1822
+ }
1823
+ wrapper(base, nodes, linesIn, comment) {
1824
+ const { body: lines, blocks } = hoistSubckts(linesIn);
1825
+ for (const b of blocks)
1826
+ if (!this.texts.includes(b))
1827
+ this.texts.push(b);
1828
+ const body = `${nodes.join(" ")}
1829
+ ${lines}`;
1830
+ const known = this.wrappers.get(body);
1831
+ if (known)
1832
+ return known;
1833
+ let name = base;
1834
+ while (this.names.has(name.toLowerCase()))
1835
+ name += "_";
1836
+ this.names.add(name.toLowerCase());
1837
+ this.wrappers.set(body, name);
1838
+ this.texts.push(`* ${comment}
1839
+ .subckt ${name} ${nodes.join(" ")}
1840
+ ${lines}
1841
+ .ends ${name}`);
1842
+ return name;
1843
+ }
1844
+ globals = new Set;
1845
+ text(header) {
1846
+ const globals = this.globals.size ? [`.global ${[...this.globals].join(" ")}`] : [];
1847
+ const sections = [...globals, ...this.models.values(), ...this.texts];
1848
+ return sections.length ? `* ${header}
1849
+
1850
+ ${sections.join(`
1851
+
1852
+ `)}
1853
+ ` : "";
1854
+ }
1855
+ }
1856
+ var EXPR_REF = /\b([vi])\(\s*([^()]*?)\s*\)/gi;
1857
+ var inExpressions = (text, f) => text.replace(/\{[^{}]*\}/g, f);
1858
+ function crossRefs(full, ports, xref) {
1859
+ const { body, blocks } = hoistSubckts(full);
1860
+ const elements = body.split(`
1861
+ `).filter((l) => l.trim() && !/^[*.+]/.test(l.trim()));
1862
+ const local = new Set(["0", ...ports.map((p) => p.toLowerCase())]);
1863
+ for (const l of elements)
1864
+ for (const t of l.replace(/\{[^{}]*\}/g, " ").split(/[\s=(),]+/))
1865
+ if (t)
1866
+ local.add(t.toLowerCase());
1867
+ const devices = elements.map((l) => l.trim().split(/\s+/)[0]);
1868
+ const isDevice = (d) => devices.some((x) => x.toLowerCase() === d);
1869
+ const nodes = new Set;
1870
+ const currents = new Set;
1871
+ const rewritten = inExpressions(body, (expr) => expr.replace(EXPR_REF, (all, kind, args) => {
1872
+ const names = args.split(",").map((a) => a.trim());
1873
+ if (kind.toLowerCase() === "i") {
1874
+ const d = names[0].toLowerCase();
1875
+ if (isDevice(d))
1876
+ return all;
1877
+ currents.add(d);
1878
+ const g = xref.currents?.get(d);
1879
+ return g ? `V(${g})` : all;
1880
+ }
1881
+ const out = names.map((n) => {
1882
+ if (local.has(n.toLowerCase()))
1883
+ return n;
1884
+ nodes.add(n.toLowerCase());
1885
+ return xref.nodes?.get(n.toLowerCase()) ?? n;
1886
+ });
1887
+ return `${kind}(${out.join(",")})`;
1888
+ }));
1889
+ xref.devices = devices;
1890
+ xref.readsNodes = [...nodes];
1891
+ xref.readsCurrents = [...currents];
1892
+ const ks = elements.map((l) => l.trim().split(/\s+/)).filter((t) => /^k/i.test(t[0]) && t.length >= 4);
1893
+ const foreignL = (t) => t.slice(1, -1).every((x) => !isDevice(x.toLowerCase()));
1894
+ xref.couplings = ks.length && ks.length === elements.length && ks.every(foreignL) ? ks.map((t) => ({ name: t[0], inductors: t.slice(1, -1).map((x) => x.toLowerCase()), k: t.at(-1) })) : undefined;
1895
+ return [...blocks, rewritten].join(`
1896
+ `);
1897
+ }
1898
+ function simSpec(ref, sectionsIn, lib, wrapperBase = `EW_${spiceName2(ref)}`, xref) {
1899
+ const sections = sectionsIn.filter((s) => s.template.trim());
1900
+ if (sections.length === 0)
1901
+ return { exclude: true };
1902
+ for (const s of sections) {
1903
+ const unsupported = /\b(chirp)\s*\(/i.exec(s.template);
1904
+ if (unsupported) {
1905
+ lib.warnings.push(`${ref}: Multisim's ${unsupported[1].toLowerCase()}() source has no ngspice equivalent; excluded from simulation`);
1906
+ return { exclude: true };
1907
+ }
1908
+ }
1909
+ if (sections.length === 1 && !xref?.wrap) {
1910
+ const { template, params, model, pins } = sections[0];
1911
+ const t = template.trim();
1912
+ const r = R_TEMPLATE.test(t) && ![4, 6, 8, 10].some((i) => truthy(params[i]));
1913
+ const cl = CL_TEMPLATE.exec(t);
1914
+ if ((r || cl && !truthy(params[4])) && isSpiceNumber((params[1] ?? "").trim()) && pins.get("1") && pins.get("2")) {
1915
+ const device = r ? "R" : cl[1].toUpperCase();
1916
+ return {
1917
+ device,
1918
+ params: `${device.toLowerCase()}=${params[1] ?? ""}`,
1919
+ value: params[1] ?? "",
1920
+ pins: [
1921
+ [pins.get("1"), "+"],
1922
+ [pins.get("2"), "-"]
1923
+ ]
1924
+ };
1925
+ }
1926
+ const sub = SUBCKT_TEMPLATE.exec(t);
1927
+ if (sub && model?.kind === "subckt") {
1928
+ const terminals = sub[1].trim().split(/\s+/).map((x) => x.slice(2));
1929
+ const mapped = [];
1930
+ terminals.forEach((term, i) => {
1931
+ const pin = pins.get(term);
1932
+ const node = model.nodes[i];
1933
+ if (pin && node)
1934
+ mapped.push([pin, node]);
1935
+ });
1936
+ const distinct = new Set(mapped.map(([pin]) => pin)).size === mapped.length;
1937
+ if (mapped.length === terminals.length && terminals.length === model.nodes.length && distinct) {
1938
+ lib.useModel(model);
1939
+ return { device: "SUBCKT", name: model.name, library: true, pins: mapped };
1940
+ }
1941
+ lib.warnings.push(`${ref}: template pins ${terminals.join(" ")} do not match model ${model.name} (${model.nodes.join(" ")}); using a wrapper`);
1942
+ }
1943
+ }
1944
+ const modelTexts = sections.flatMap((s) => [ngspiceDialect(s.template), s.model?.text ?? "", ...[...s.pinModels?.values() ?? []].map((p) => (enablePinModel(p) ?? p).model.text)]);
1945
+ const foreign = unsupportedModelType(modelTexts.join(`
1946
+ `).replace(/^.*\bLAPLACE\b.*$/gim, ""));
1947
+ if (foreign) {
1948
+ const why = sections.flatMap((s) => s.model?.issues ?? []);
1949
+ lib.warnings.push(`${ref}: its model uses ${foreign}, which ngspice lacks${why.length ? ` (${why.join("; ")})` : ""}; excluded from simulation`);
1950
+ return { exclude: true };
1951
+ }
1952
+ const nodeOfPin = new Map;
1953
+ const used = new Set;
1954
+ const nodeFor = (pin, terminal) => {
1955
+ let n = nodeOfPin.get(pin);
1956
+ if (n)
1957
+ return n;
1958
+ n = (sections.length === 1 ? spiceName2(terminal) : `p${spiceName2(pin)}`) || "n";
1959
+ if (/^\d/.test(n))
1960
+ n = `t${n}`;
1961
+ while (used.has(n.toLowerCase()))
1962
+ n += "_";
1963
+ used.add(n.toLowerCase());
1964
+ nodeOfPin.set(pin, n);
1965
+ return n;
1966
+ };
1967
+ for (const s of sections)
1968
+ for (const [term, pin] of s.pins)
1969
+ nodeFor(pin, term);
1970
+ const missing = [];
1971
+ const chipErrors = [];
1972
+ const noInterface = new Set;
1973
+ const bridged = new Set;
1974
+ const enRead = new Set;
1975
+ const enDriven = new Set;
1976
+ const lines = sections.map((s) => {
1977
+ if (s.model)
1978
+ lib.useModel(s.model);
1979
+ const node = (term) => {
1980
+ const pin = s.pins.get(term);
1981
+ return pin === undefined ? undefined : nodeFor(pin, term);
1982
+ };
1983
+ const bridges = [];
1984
+ const digital = (term, prefix) => {
1985
+ const analog = node(term);
1986
+ const dnode = `${prefix}_${analog ?? spiceName2(term)}`;
1987
+ if (!analog || bridged.has(analog))
1988
+ return dnode;
1989
+ bridged.add(analog);
1990
+ const base = s.pinModels?.get(term);
1991
+ const pm = base && (enablePinModel(base) ?? base);
1992
+ if (pm && pm !== base)
1993
+ enRead.add(`d_${analog}_en`);
1994
+ if (!pm) {
1995
+ noInterface.add(term);
1996
+ return dnode;
1997
+ }
1998
+ lib.useModel(pm.model);
1999
+ const line = expandTemplate(pm.template.replace(/\r\n?/g, `
2000
+ `).trim(), {
2001
+ ref: `${spiceName2(ref)}_${spiceName2(term)}`,
2002
+ params: [],
2003
+ model: pm.model.name,
2004
+ node: (t) => t === "1" ? analog : t === "2" ? `d_${analog}` : t === "3" ? `r_${analog}` : t === "EN" ? `d_${analog}_en` : node(t) ?? "0"
2005
+ });
2006
+ const inverted = [];
2007
+ const call = line.replace(/(^|\s)~(\S+)/g, (_, sp, n) => {
2008
+ inverted.push(`a${n}_inv ${n} ${n}_n EW_invert`, ".model EW_invert d_inverter(rise_delay=1e-12 fall_delay=1e-12)");
2009
+ return `${sp}${n}_n`;
2010
+ });
2011
+ bridges.push(call, ...inverted);
2012
+ return dnode;
2013
+ };
2014
+ const main = expandTemplate(s.template.replace(/\r\n?/g, `
2015
+ `).trim(), {
2016
+ ref: spiceName2(ref),
2017
+ params: s.params,
2018
+ strings: s.strings,
2019
+ circuitParams: s.circuitParams,
2020
+ model: s.model?.name,
2021
+ node,
2022
+ digital,
2023
+ missing: (term) => missing.push(term)
2024
+ }).replace(/<([0-9.][^<>\n]*)>/g, "{$1}");
2025
+ const call = s.model?.dchip ? rewriteDChipInstances(main, new Map([[s.model.name.toLowerCase(), s.model.dchip]]), chipErrors, enDriven) : main;
2026
+ return ngspiceDialect(staticPot([call, ...bridges].join(`
2027
+ `)));
2028
+ });
2029
+ if (chipErrors.length) {
2030
+ lib.warnings.push(`${ref}: ${chipErrors.join("; ")}; excluded from simulation`);
2031
+ return { exclude: true };
2032
+ }
2033
+ if (noInterface.size)
2034
+ lib.warnings.push(`${ref}: digital pins ${[...noInterface].join(", ")} have no interface model; left unbridged`);
2035
+ if (missing.length)
2036
+ lib.warnings.push(`${ref}: template terminals ${[...new Set(missing)].join(", ")} have no pin; left as internal nodes`);
2037
+ const pinList = [...nodeOfPin.keys()];
2038
+ const nodes = pinList.map((p) => nodeOfPin.get(p));
2039
+ const alwaysOn = [...enRead].filter((n) => !enDriven.has(n));
2040
+ if (alwaysOn.length)
2041
+ lines.push([...alwaysOn.map((n) => `a${n}_on ${n} EW_drives`), ".model EW_drives d_pullup"].join(`
2042
+ `));
2043
+ const seenModels = new Set;
2044
+ let body = lines.join(`
2045
+ `).split(`
2046
+ `).filter((l) => !/^\.model EW_/.test(l) || !seenModels.has(l) && !!seenModels.add(l)).join(`
2047
+ `);
2048
+ const foreignExpanded = unsupportedModelType(body);
2049
+ if (foreignExpanded) {
2050
+ lib.warnings.push(`${ref}: its model uses ${foreignExpanded}, which ngspice lacks; excluded from simulation`);
2051
+ return { exclude: true };
2052
+ }
2053
+ if (/\{[^}]*\bpi\b/i.test(body))
2054
+ body = `.param pi=3.141592653589793
2055
+ ${body}`;
2056
+ if (xref) {
2057
+ body = crossRefs(body, nodes, xref);
2058
+ xref.wrapped = true;
2059
+ xref.pinNodes = new Map(nodeOfPin);
2060
+ const probes = (xref.probes ?? []).flatMap((p) => {
2061
+ const what = p.pin !== undefined ? nodeOfPin.get(p.pin) && `V(${nodeOfPin.get(p.pin)})` : p.device && `I(${p.device})`;
2062
+ return what ? [`B${p.global} ${p.global} 0 V={${what}}`] : [];
2063
+ });
2064
+ if (probes.length)
2065
+ body = `${body}
2066
+ * Probes other parts read (Multisim names are global)
2067
+ ${probes.join(`
2068
+ `)}`;
2069
+ }
2070
+ const name = lib.wrapper(wrapperBase, nodes, body, `${ref} (Multisim netlist template)`);
2071
+ return { device: "SUBCKT", name, library: true, pins: pinList.map((p) => [p, nodeOfPin.get(p)]) };
2072
+ }
2073
+ function resolveCrossRefs(parts, ciNodes, portOf, partOf, finals, namedNets, lib) {
2074
+ const plain = new Map;
2075
+ const info = new Map;
2076
+ for (const p of parts) {
2077
+ const asIs = {};
2078
+ const spec = simSpec(p.ref, p.sections, new SpiceLibrary, undefined, asIs);
2079
+ if (spec.exclude)
2080
+ continue;
2081
+ plain.set(p, !asIs.wrapped);
2082
+ const wrapped = { wrap: true };
2083
+ simSpec(p.ref, p.sections, new SpiceLibrary, undefined, wrapped);
2084
+ info.set(p, wrapped);
2085
+ }
2086
+ const readers = parts.filter((p) => !plain.get(p) && (info.get(p)?.readsNodes?.length || info.get(p)?.readsCurrents?.length));
2087
+ const couplers = parts.filter((p) => info.get(p)?.couplings);
2088
+ if (!readers.length && !couplers.length)
2089
+ return [];
2090
+ const namesOf = (p) => [...new Set(p.ids.flatMap((id) => finals.get(id) ?? [p.ref]))];
2091
+ const nets = ciNodes.map(({ body }) => ({
2092
+ name: body.str("LocalName").toLowerCase(),
2093
+ circuit: body.get("Circuit") ?? "",
2094
+ ports: (body.child("Ports")?.childrenNamed("Item") ?? []).flatMap((i) => {
2095
+ const port = portOf.get(i.get("CiID") ?? "");
2096
+ const part = port && partOf.get(port.comp);
2097
+ return port && part ? [{ part, pad: port.pad }] : [];
2098
+ })
2099
+ }));
2100
+ const probe = (target, global, at) => {
2101
+ target.xref.wrap = true;
2102
+ const probes = target.xref.probes ??= [];
2103
+ if (!probes.some((q) => q.global === global))
2104
+ probes.push({ global, ...at });
2105
+ lib.globals.add(global);
2106
+ };
2107
+ const globalNames = new Map;
2108
+ const globalFor = (prefix, name) => {
2109
+ const key = `${prefix}${name}`;
2110
+ let g = globalNames.get(key);
2111
+ if (g)
2112
+ return g;
2113
+ g = `${prefix}${spiceName2(name.replace(/\+/g, "p").replace(/-/g, "n"))}`;
2114
+ while ([...globalNames.values()].includes(g))
2115
+ g += "_";
2116
+ globalNames.set(key, g);
2117
+ return g;
2118
+ };
2119
+ const once = (p) => namesOf(p).length === 1 && info.has(p);
2120
+ const deviceNamed = (d) => {
2121
+ for (const p of parts) {
2122
+ if (!info.has(p))
2123
+ continue;
2124
+ const own = spiceName2(p.ref).toLowerCase();
2125
+ for (const dev of info.get(p).devices ?? []) {
2126
+ const lower = dev.toLowerCase();
2127
+ const at = lower.indexOf(own);
2128
+ if (at < 0)
2129
+ continue;
2130
+ const final = namesOf(p).find((f) => `${lower.slice(0, at)}${f.toLowerCase()}${lower.slice(at + own.length)}` === d);
2131
+ if (final)
2132
+ return { part: p, device: dev, final };
2133
+ }
2134
+ }
2135
+ return;
2136
+ };
2137
+ const directives = [];
2138
+ for (const p of couplers) {
2139
+ const lines = [];
2140
+ for (const c of info.get(p).couplings) {
2141
+ const names = c.inductors.map((l) => {
2142
+ const found = deviceNamed(l);
2143
+ if (!found || !once(found.part))
2144
+ return;
2145
+ return plain.get(found.part) ? found.final.startsWith("L") ? found.final : `L${found.final}` : `${found.device[0]}.x${found.final}.${found.device}`.toLowerCase();
2146
+ });
2147
+ if (names.some((n) => !n)) {
2148
+ lib.warnings.push(`${p.ref}: couples ${c.inductors.join(", ")}, which the design doesn't simulate as single inductors; excluded from simulation`);
2149
+ lines.length = 0;
2150
+ break;
2151
+ }
2152
+ const own = spiceName2(namesOf(p)[0]);
2153
+ lines.push(`${/^k/i.test(own) ? own : `K${own}`}${lines.length ? `_${lines.length}` : ""} ${names.join(" ")} ${c.k}`);
2154
+ }
2155
+ p.xref.moved = true;
2156
+ if (lines.length)
2157
+ directives.push(lines.join(`
2158
+ `));
2159
+ }
2160
+ for (const reader of readers) {
2161
+ const { readsNodes = [], readsCurrents = [] } = info.get(reader);
2162
+ const nodes = reader.xref.nodes ??= new Map;
2163
+ const currents = reader.xref.currents ??= new Map;
2164
+ for (const n of readsNodes) {
2165
+ const same = nets.filter((x) => x.name === n && x.circuit === reader.circuit);
2166
+ const numbered = same[0] ?? (nets.filter((x) => x.name === n).length === 1 ? nets.find((x) => x.name === n) : undefined);
2167
+ const named = namedNets.get(n)?.flatMap(({ refdes, pin }) => {
2168
+ const part = parts.find((p) => namesOf(p).includes(refdes));
2169
+ return part ? [{ part, pad: pin }] : [];
2170
+ });
2171
+ const net = named ? { ports: named } : numbered;
2172
+ if (!net) {
2173
+ lib.warnings.push(`${reader.ref}: its expression reads V(${n}), but the design has no net ${n}`);
2174
+ continue;
2175
+ }
2176
+ const own = net.ports.find((q) => q.part === reader);
2177
+ const ownNode = own && info.get(reader)?.pinNodes?.get(own.pad);
2178
+ if (ownNode) {
2179
+ nodes.set(n, ownNode);
2180
+ continue;
2181
+ }
2182
+ const host = [...net.ports].filter((q) => q.part !== reader && once(q.part) && info.get(q.part)?.pinNodes?.has(q.pad)).sort((a, b) => Number(plain.get(a.part)) - Number(plain.get(b.part)))[0];
2183
+ if (!host) {
2184
+ lib.warnings.push(`${reader.ref}: its expression reads V(${n}), but no simulated part on that net can carry a probe; left unconnected`);
2185
+ continue;
2186
+ }
2187
+ const g = globalFor("ew_v_", n);
2188
+ probe(host.part, g, { pin: host.pad });
2189
+ nodes.set(n, g);
2190
+ }
2191
+ for (const d of readsCurrents) {
2192
+ const found = deviceNamed(d);
2193
+ if (!found) {
2194
+ lib.warnings.push(`${reader.ref}: its expression reads I(${d}), but no part defines ${d}`);
2195
+ continue;
2196
+ }
2197
+ if (!once(found.part)) {
2198
+ lib.warnings.push(`${reader.ref}: its expression reads I(${d}), but that part is placed more than once; left as is`);
2199
+ continue;
2200
+ }
2201
+ const g = globalFor("ew_i_", d);
2202
+ probe(found.part, g, { device: found.device });
2203
+ currents.set(d, g);
2204
+ }
2205
+ }
2206
+ return directives;
2207
+ }
2208
+ function parseSpice(items, circuitParamNames = new Set, finals = new Map, namedNets = new Map) {
2209
+ const lib = new SpiceLibrary;
2210
+ const byComponent = new Map;
2211
+ const ports = new Map;
2212
+ const portOf = new Map;
2213
+ const pinModels = new Map;
2214
+ const pinModelCache = new Map;
2215
+ for (const { id, body } of items.get("CiPort") ?? []) {
2216
+ const comp = body.get("Component") ?? "";
2217
+ const terminal = body.str("LocalName");
2218
+ const pad = portPinNumbers(body)[0] ?? (terminal || undefined);
2219
+ if (!terminal || !pad)
2220
+ continue;
2221
+ portOf.set(id, { comp, pad });
2222
+ const m = ports.get(comp) ?? new Map;
2223
+ if (!m.has(terminal))
2224
+ m.set(terminal, pad);
2225
+ ports.set(comp, m);
2226
+ const [a, b] = ciCollStrings(body).map(collValues);
2227
+ const pmId = a?.[3] ?? "";
2228
+ const pmTemplate = b?.[5] ?? "";
2229
+ if (pmId && pmTemplate && a?.[5]) {
2230
+ const def = pinModelCache.get(pmId) ?? pinModelDef(pmId, a[5]);
2231
+ if (def) {
2232
+ pinModelCache.set(pmId, def);
2233
+ const pm = pinModels.get(comp) ?? new Map;
2234
+ pm.set(terminal, { model: def, template: pmTemplate });
2235
+ pinModels.set(comp, pm);
2236
+ }
2237
+ }
2238
+ }
2239
+ const models = new Map;
2240
+ for (const { id, body } of items.get("CiModel") ?? []) {
2241
+ const def = modelDef(body.str("LocalName"), modelText(body));
2242
+ if (def)
2243
+ models.set(id, def);
2244
+ else
2245
+ lib.warnings.push(`model ${body.str("LocalName")}: no .SUBCKT or .MODEL in its text`);
2246
+ }
2247
+ const parts = new Map;
2248
+ const partOf = new Map;
2249
+ for (const { id, body } of items.get("CiComponent") ?? []) {
2250
+ const ref = body.str("LocalName");
2251
+ const template = netlistTemplate(body);
2252
+ const key = /%p_\w/.test(template) ? `${body.get("Circuit") ?? ""}|${ref}` : id;
2253
+ const part = parts.get(key) ?? { ref, circuit: body.get("Circuit") ?? "", ids: [], sections: [], xref: {} };
2254
+ partOf.set(id, part);
2255
+ part.ids.push(id);
2256
+ part.sections.push({
2257
+ template,
2258
+ params: componentParams(body),
2259
+ strings: componentParams(body, "strings"),
2260
+ circuitParams: circuitParamNames,
2261
+ model: body.get("Model") ? models.get(body.get("Model")) : undefined,
2262
+ pins: ports.get(id) ?? new Map,
2263
+ pinModels: pinModels.get(id)
2264
+ });
2265
+ parts.set(key, part);
2266
+ }
2267
+ const directives = resolveCrossRefs([...parts.values()], items.get("CiNode") ?? [], portOf, partOf, finals, namedNets, lib);
2268
+ for (const { ref, ids, sections, xref } of parts.values()) {
2269
+ const spec = xref.moved ? { exclude: true } : simSpec(ref, sections, lib, undefined, xref);
2270
+ for (const id of ids)
2271
+ byComponent.set(id, spec);
2272
+ }
2273
+ return { byComponent, library: lib.text("SPICE models from the Multisim design (multisim2kicad)"), directives, warnings: lib.warnings };
2274
+ }
2275
+
2276
+ // src/parse/sim-settings.ts
2277
+ function parseSimState(t) {
2278
+ let i = 0;
2279
+ const items = () => {
2280
+ const out = [];
2281
+ for (;; ) {
2282
+ while (i < t.length && /\s/.test(t[i]))
2283
+ i++;
2284
+ if (i >= t.length || t[i] === "}")
2285
+ return out;
2286
+ const m = /^([^:{}\s]+):([a-z]+(?:\[\])?)\{/.exec(t.slice(i, i + 300));
2287
+ if (!m)
2288
+ throw new Error(`SimState: unexpected text at ${i}`);
2289
+ i += m[0].length;
2290
+ if (m[2] === "list") {
2291
+ const list = items();
2292
+ i++;
2293
+ out.push({ key: m[1], type: "list", items: list });
2294
+ } else {
2295
+ let depth = 1;
2296
+ let j = i;
2297
+ for (;j < t.length && depth; j++)
2298
+ depth += t[j] === "{" ? 1 : t[j] === "}" ? -1 : 0;
2299
+ out.push({ key: m[1], type: m[2], value: t.slice(i, j - 1) });
2300
+ i = j;
2301
+ }
2302
+ }
2303
+ };
2304
+ return items();
2305
+ }
2306
+ var child = (nodes, ...path) => {
2307
+ let cur;
2308
+ for (const p of path) {
2309
+ cur = nodes?.find((n) => n.key === p);
2310
+ nodes = cur?.items;
2311
+ }
2312
+ return cur;
2313
+ };
2314
+ var NGSPICE_OPTIONS = new Set(("acct gmin reltol abstol vntol trtol chgtol pivtol pivrel tnom itl1 itl2 itl4 itl6 gminsteps defl defw defad defas " + "bypass maxord temp oldlimit minbreak noopiter method trytocompact badmos3 keepopinfo noopalter ramptime maxevtiter " + "maxopalter convlimit convabsstep convstep autopartial rshunt").split(" "));
2315
+ var num = (v) => v !== undefined && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : undefined;
2316
+ var fmt2 = (x) => {
2317
+ const v = Number(x.toPrecision(6));
2318
+ const a = Math.abs(v);
2319
+ if (a !== 0 && (a < 0.001 || a >= 1e5)) {
2320
+ const [m, e] = v.toExponential().split("e");
2321
+ return `${m}e${e[0]}${e.slice(1).padStart(2, "0")}`;
2322
+ }
2323
+ return v.toString();
2324
+ };
2325
+ function optionsOf(analysis) {
2326
+ const opts = (child(analysis?.items, "ASYS_OPT")?.items ?? []).flatMap((o) => {
2327
+ if (child(o.items, "IsEnabled")?.value !== "1")
2328
+ return [];
2329
+ const opt = o.items.find((x) => x.key !== "IsEnabled");
2330
+ if (!opt || !NGSPICE_OPTIONS.has(opt.key.toLowerCase()))
2331
+ return [];
2332
+ return [opt.type === "flag" ? opt.key : `${opt.key}=${opt.value}`];
2333
+ });
2334
+ return opts.length ? `.options ${opts.join(" ")}` : undefined;
2335
+ }
2336
+ function tranDirective(a) {
2337
+ const v = (k) => child(a, k)?.value;
2338
+ const tstop = num(v("TSTOP"));
2339
+ if (tstop === undefined || tstop <= 0 || tstop >= 100000000000000000000)
2340
+ return;
2341
+ const tstart = num(v("TSTART")) ?? 0;
2342
+ const tmax = num(v("TMAX"));
2343
+ const tstep = num(v("TSTEP")) ?? (tstop - tstart) / 1000;
2344
+ const uic = /^(uic|zero_ic)$/i.test(v("IC") ?? "");
2345
+ const parts = [".tran", fmt2(tstep), fmt2(tstop)];
2346
+ if (tstart || tmax !== undefined || uic)
2347
+ parts.push(fmt2(tstart));
2348
+ if (tmax !== undefined)
2349
+ parts.push(fmt2(tmax));
2350
+ if (uic)
2351
+ parts.push("uic");
2352
+ return parts.join(" ");
2353
+ }
2354
+ function directiveOf(kind, analysis) {
2355
+ const a = child(analysis.items, "ANALYSIS")?.items;
2356
+ const v = (k) => child(a, k)?.value;
2357
+ if (kind === "OP")
2358
+ return [".op"];
2359
+ if (kind === "TRAN") {
2360
+ const tran = tranDirective(a);
2361
+ return tran ? [tran] : undefined;
2362
+ }
2363
+ if (kind === "FOUR") {
2364
+ const tran = child(a, "Tran")?.items ?? [];
2365
+ const tstop = num(v("TStop"));
2366
+ const settings = tstop && !num(child(tran, "TSTOP")?.value) ? [...tran, { key: "TSTOP", type: "double", value: String(tstop) }] : tran;
2367
+ const directive = tranDirective(settings);
2368
+ if (!directive)
2369
+ return;
2370
+ const fund = num(v("FundFreq"));
2371
+ const n = num(v("NumFreqs"));
2372
+ const note = fund && v("FundFreqSet") !== "0" ? `* Multisim's Fourier analysis of this transient: fundamental ${fmt2(fund)} Hz${n ? `, ${fmt2(n)} harmonics` : ""}` : "* Multisim's Fourier analysis runs this transient";
2373
+ return [directive, note];
2374
+ }
2375
+ if (kind === "AC") {
2376
+ const variation = (v("VARIATION") ?? "dec").toLowerCase();
2377
+ const n = num(v("NPOINTS_PER_VARIATION"));
2378
+ const f1 = num(v("FSTART"));
2379
+ const f2 = num(v("FSTOP"));
2380
+ if (!/^(dec|oct|lin)$/.test(variation) || n === undefined || f1 === undefined || f2 === undefined)
2381
+ return;
2382
+ return [`.ac ${variation} ${fmt2(n)} ${fmt2(f1)} ${fmt2(f2)}`];
2383
+ }
2384
+ return;
2385
+ }
2386
+ var PREFERRED = ["TRAN", "FOUR", "AC", "OP"];
2387
+ function simSettings(simState, o = {}) {
2388
+ const analyses = child(parseSimState(simState), "SIMULATION_INFO", "ANALYSES")?.items ?? [];
2389
+ const ran = analyses.filter((n) => n.type === "list" && ((num(child(n.items, "ANALYSIS_ID")?.value) ?? 0) > 0 || !!child(n.items, "RAWFILE_NAME")?.value));
2390
+ const chosen = PREFERRED.map((k) => ran.find((n) => n.key === k)).find((n) => n && directiveOf(n.key, n));
2391
+ let options = optionsOf(chosen ?? analyses.find((n) => n.key === "OP"));
2392
+ const analysis = chosen && directiveOf(chosen.key, chosen)?.join(`
2393
+ `);
2394
+ if (o.digital && analysis?.startsWith(".tran") && !/ uic$/.test(analysis.split(`
2395
+ `)[0]))
2396
+ options = options ? `${options} noopalter` : ".options noopalter";
2397
+ return {
2398
+ options,
2399
+ analysis,
2400
+ skipped: ran.filter((n) => n !== chosen).map((n) => n.key)
2401
+ };
2402
+ }
2403
+
720
2404
  // src/parse/ms-hierarchy.ts
721
2405
  var modsOf = (o) => (o.at("ElectricalObject", "ModifierInfo")?.childrenNamed("Element") ?? []).flatMap((e) => e.childrenNamed("Item").map((i) => ({ mod: e.str("NetModifier"), value: i.str("Value") })));
722
2406
  var OWNER_CLASSES = new Set([
@@ -804,6 +2488,7 @@ function indexCi(proj) {
804
2488
  }
805
2489
  return ci;
806
2490
  }
2491
+ var strColls = (body) => ciCollStrings(body).map(collValues);
807
2492
  function parseMultisimDesign(input) {
808
2493
  const warnings = [];
809
2494
  const { root: top } = docOf(input);
@@ -875,29 +2560,180 @@ function parseMultisimDesign(input) {
875
2560
  warnings,
876
2561
  finalRefdes: (inst, page, key) => irMap.get(inst.cirOf(page))?.get(key),
877
2562
  pinRemap: (inst, page, key) => remaps.get(`${inst.cirOf(page)}|${key}`),
878
- finalUnit: (inst, page, key) => unitMap.get(`${inst.cirOf(page)}|${key}`)
2563
+ finalUnit: (inst, page, key) => unitMap.get(`${inst.cirOf(page)}|${key}`),
2564
+ finalNames: () => {
2565
+ const out = new Map;
2566
+ const walk = (inst) => {
2567
+ for (const pg of pages.filter((p) => p.title === inst.sheet)) {
2568
+ for (const s of pg.symbols.values()) {
2569
+ const drawn = s.ciComp ? ci.get(s.ciComp)?.body.str("LocalName") : undefined;
2570
+ if (!drawn || s.kind === "CIITMacroComponent")
2571
+ continue;
2572
+ const final = irMap.get(inst.cirOf(pg.page))?.get(drawn + s.obj.str("DBComponentSectionName")) ?? drawn;
2573
+ const list = out.get(s.ciComp) ?? [];
2574
+ if (!list.includes(final))
2575
+ list.push(final);
2576
+ out.set(s.ciComp, list);
2577
+ }
2578
+ }
2579
+ for (const c of inst.children)
2580
+ walk(c);
2581
+ };
2582
+ walk(root);
2583
+ return out;
2584
+ }
879
2585
  };
880
2586
  }
2587
+ function flattenNetlist(design, named) {
2588
+ const { ci, pages, warnings } = design;
2589
+ const portPins = (portId) => {
2590
+ const p = portId ? ci.get(portId) : undefined;
2591
+ return p ? (strColls(p.body)[1]?.[6] ?? "").split(",").map((x) => x.trim()).filter(Boolean) : [];
2592
+ };
2593
+ const parent = new Map;
2594
+ const find = (x) => {
2595
+ if (!parent.has(x))
2596
+ parent.set(x, x);
2597
+ let r = x;
2598
+ while (parent.get(r) !== r)
2599
+ r = parent.get(r);
2600
+ let y = x;
2601
+ while (parent.get(y) !== r) {
2602
+ const n = parent.get(y);
2603
+ parent.set(y, r);
2604
+ y = n;
2605
+ }
2606
+ return r;
2607
+ };
2608
+ const union = (a, b) => {
2609
+ const ra = find(a);
2610
+ const rb = find(b);
2611
+ if (ra !== rb)
2612
+ parent.set(ra, rb);
2613
+ };
2614
+ const pinsAt = new Map;
2615
+ const supplyAt = new Map;
2616
+ const expand = (inst, ports, depth) => {
2617
+ for (const pg of pages.filter((p) => p.title === inst.sheet)) {
2618
+ const K = (id) => `${inst.path}|${pg.page}|${id}`;
2619
+ for (const [a, b] of pg.edges)
2620
+ union(K(a), K(b));
2621
+ for (const l of pg.links) {
2622
+ for (const m of l.mods) {
2623
+ if (m.mod === "NI_EWB_NET_NAME" && m.value)
2624
+ union(K(l.id), `${inst.path}|${pg.page}|NAME:${m.value}`);
2625
+ if (m.mod === "NI_EWB_NET_BUS_ENTRY")
2626
+ union(K(l.id), `${inst.path}|BUSLINE:${m.value}`);
2627
+ }
2628
+ }
2629
+ for (const p of pg.pins) {
2630
+ const pk = K(p.id);
2631
+ find(pk);
2632
+ for (const m of p.mods) {
2633
+ if (m.mod === "NI_EWB_NET_GLOBAL" || m.mod === "NI_EWB_NET_GLOBAL_GROUND")
2634
+ union(pk, `G:${m.value.toUpperCase()}`);
2635
+ else if (m.mod === "NI_EWB_NET_VIRTUAL")
2636
+ union(pk, `${inst.path}|${pg.page}|ONPAGE:${m.value}`);
2637
+ else if (m.mod === "NI_EWB_NET_OFFPAGE")
2638
+ union(pk, `${inst.path}|OFFPAGE:${m.value}`);
2639
+ else if (m.mod === "NI_EWB_NET_HIERARCHY") {
2640
+ const pkey = ports.get(m.value);
2641
+ if (pkey)
2642
+ union(pk, pkey);
2643
+ else if (depth > 0)
2644
+ warnings.push(`no parent port for ${m.value} at ${inst.path}`);
2645
+ }
2646
+ }
2647
+ const owner = pg.symbols.get(p.owner);
2648
+ if (p.ownerKind !== "CIITSymbolComp" && p.ownerKind !== "CIITAnimationSymbolComp" || !owner)
2649
+ continue;
2650
+ const comp = ci.get(owner.ciComp);
2651
+ if (!comp) {
2652
+ warnings.push(`symbol ${p.owner} CiComponent ${owner.ciComp} missing`);
2653
+ continue;
2654
+ }
2655
+ const s = strColls(comp.body);
2656
+ const drawn = comp.body.str("LocalName");
2657
+ const key = drawn + owner.obj.str("DBComponentSectionName");
2658
+ const final = design.finalRefdes(inst, pg.page, key) ?? (depth === 0 ? drawn : `${inst.path}/${drawn}`);
2659
+ if (s[0]?.[0] === "POWER_SOURCES" || s[1]?.[0] === "91") {
2660
+ if (named && s[0]?.[0] === "POWER_SOURCES")
2661
+ supplyAt.set(pk, [...supplyAt.get(pk) ?? [], { refdes: final, pin: displayText(p.pinName) || p.pinNumber }]);
2662
+ continue;
2663
+ }
2664
+ const remap = design.pinRemap(inst, pg.page, key);
2665
+ const nums = portPins(p.portId);
2666
+ const list = pinsAt.get(pk) ?? [];
2667
+ const drawnNums = drawnPinNumbers(p.pinNumber);
2668
+ const own = nums.length ? nums : drawnNums.length ? drawnNums : [displayText(p.pinName) || "?"];
2669
+ for (const n of own)
2670
+ list.push({ refdes: final, pin: remap?.get(n) ?? n });
2671
+ pinsAt.set(pk, list);
2672
+ }
2673
+ for (const child of inst.children.filter((c) => c.parentPage === pg.page)) {
2674
+ const pmap = new Map;
2675
+ for (const p of pg.pins.filter((x) => x.owner === child.macroId)) {
2676
+ const nm = p.mods.find((m) => m.mod === "NI_EWB_NET_HIERARCHY_COMP")?.value ?? p.pinName;
2677
+ pmap.set(nm, K(p.id));
2678
+ }
2679
+ expand(child, pmap, depth + 1);
2680
+ }
2681
+ }
2682
+ };
2683
+ expand(design.root, new Map, 0);
2684
+ const pinHome = new Map;
2685
+ for (const [k, ps] of pinsAt) {
2686
+ for (const p of ps) {
2687
+ if (p.pin === "?")
2688
+ continue;
2689
+ const id = JSON.stringify([p.refdes, p.pin]);
2690
+ const home = pinHome.get(id);
2691
+ if (home === undefined)
2692
+ pinHome.set(id, k);
2693
+ else
2694
+ union(k, home);
2695
+ }
2696
+ }
2697
+ const nets = new Map;
2698
+ for (const [k, ps] of pinsAt) {
2699
+ const r = find(k);
2700
+ nets.set(r, [...nets.get(r) ?? [], ...ps]);
2701
+ }
2702
+ if (named) {
2703
+ const names = [...parent.keys()].flatMap((k) => {
2704
+ const m = /^([^|]*)\|(?:[^|]*\|)?(?:NAME|ONPAGE|OFFPAGE):(.*)$/.exec(k) ?? /^()G:(.*)$/.exec(k);
2705
+ return m ? [{ depth: m[1].split("/").length, name: m[2].toLowerCase(), root: find(k) }] : [];
2706
+ });
2707
+ const supplies = new Map;
2708
+ for (const [k, ps] of supplyAt)
2709
+ supplies.set(find(k), [...supplies.get(find(k)) ?? [], ...ps]);
2710
+ for (const n of names.sort((a, b) => a.depth - b.depth)) {
2711
+ if (!named.has(n.name))
2712
+ named.set(n.name, [...nets.get(n.root) ?? [], ...supplies.get(n.root) ?? []]);
2713
+ }
2714
+ }
2715
+ return nets;
2716
+ }
881
2717
 
882
2718
  // src/parse/sch.ts
883
2719
  var items = (n, list, item = "Item") => n?.child(list)?.childrenNamed(item) ?? [];
884
- var num = (v, d = 0) => {
2720
+ var num2 = (v, d = 0) => {
885
2721
  const n = Number(v);
886
2722
  return Number.isFinite(n) ? n : d;
887
2723
  };
888
2724
  var snap = (v) => Math.abs(v - Math.round(v)) < 0.001 ? Math.round(v) : v;
889
- var pt = (x, y) => ({ x: num(x), y: num(y) });
2725
+ var pt = (x, y) => ({ x: num2(x), y: num2(y) });
890
2726
  var IDENTITY = { m00: 1, m01: 0, m10: 0, m11: 1, m20: 0, m21: 0 };
891
2727
  function affineOf(node) {
892
2728
  if (!node || node.get("Transformer-M00") === undefined)
893
2729
  return IDENTITY;
894
2730
  return {
895
- m00: num(node.get("Transformer-M00"), 1),
896
- m01: num(node.get("Transformer-M01")),
897
- m10: num(node.get("Transformer-M10")),
898
- m11: num(node.get("Transformer-M11"), 1),
899
- m20: num(node.get("Transformer-M20")),
900
- m21: num(node.get("Transformer-M21"))
2731
+ m00: num2(node.get("Transformer-M00"), 1),
2732
+ m01: num2(node.get("Transformer-M01")),
2733
+ m10: num2(node.get("Transformer-M10")),
2734
+ m11: num2(node.get("Transformer-M11"), 1),
2735
+ m20: num2(node.get("Transformer-M20")),
2736
+ m21: num2(node.get("Transformer-M21"))
901
2737
  };
902
2738
  }
903
2739
  var apply = (t, p) => ({
@@ -957,7 +2793,7 @@ function children(node) {
957
2793
  }
958
2794
  return out;
959
2795
  }
960
- var penWidth = (n) => Math.max(0, num(n?.get("Pen-Width")));
2796
+ var penWidth = (n) => Math.max(0, num2(n?.get("Pen-Width")));
961
2797
  var filled = (n) => String(n?.get("Brush-Style") ?? "1") === "0";
962
2798
  function ellipsePoints(c, rx, ry) {
963
2799
  const out = [];
@@ -995,8 +2831,8 @@ function graphicOf(cls, n, parent, raw = false) {
995
2831
  }
996
2832
  case "CODEllipseComp": {
997
2833
  const c = pt(n.get("CenterX"), n.get("CenterY"));
998
- const r1 = num(n.get("Radius1"));
999
- const r2 = num(n.get("Radius2"));
2834
+ const r1 = num2(n.get("Radius1"));
2835
+ const r2 = num2(n.get("Radius2"));
1000
2836
  if (Math.abs(r1 - r2) < 0.000001) {
1001
2837
  return { kind: "circle", center: apply(t, c), radius: r1 * affineScale(t), width: w, fill: filled(n) };
1002
2838
  }
@@ -1029,7 +2865,7 @@ function composeAffine(child, parent) {
1029
2865
  m21: child.m20 * parent.m01 + child.m21 * parent.m11 + parent.m21
1030
2866
  };
1031
2867
  }
1032
- var fontSize = (n) => Math.max(4, Math.min(12, Math.abs(num(n?.get("Font-Height"), -13)) * 0.4));
2868
+ var fontSize = (n) => Math.max(4, Math.min(12, Math.abs(num2(n?.get("Font-Height"), -13)) * 0.4));
1033
2869
  var portPins = () => [];
1034
2870
  function parsePins(pinComp, parent, extraGraphics, raw = false, sourceId = "") {
1035
2871
  const child = (n, p) => raw ? p : composeAffine(affineOf(n), p);
@@ -1132,7 +2968,7 @@ function parseSymbolLike(comp, raw = false) {
1132
2968
  value: valueText?.text ?? "",
1133
2969
  kind: "part",
1134
2970
  at: { x: 0, y: 0 },
1135
- transform: flipToDihedral(num(comp.get("OrientationFlip"))),
2971
+ transform: flipToDihedral(num2(comp.get("OrientationFlip"))),
1136
2972
  graphics,
1137
2973
  pins: parsed.map((p) => p.pin),
1138
2974
  refText,
@@ -1204,7 +3040,7 @@ function applyFit(p, f, pinPts) {
1204
3040
  }
1205
3041
  var placementStats = { symbols: 0, pins: 0, pinsOnTarget: 0, raw: 0, composed: 0, unattached: 0 };
1206
3042
  function parsePlaced(comp, pinPts) {
1207
- const flipD = flipToDihedral(num(comp.get("OrientationFlip")));
3043
+ const flipD = flipToDihedral(num2(comp.get("OrientationFlip")));
1208
3044
  const composed = parseSymbolLike(comp, false);
1209
3045
  const fc = fit(composed, pinPts, { a: 1, b: 0, c: 0, d: 1 });
1210
3046
  const raw = parseSymbolLike(comp, true);
@@ -1290,7 +3126,7 @@ function pageNets(edges, linkIds, pinIds) {
1290
3126
  isolated: (id) => !!id && !links.get(find(id)) && (pins.get(find(id)) ?? 0) <= 1
1291
3127
  };
1292
3128
  }
1293
- function parseSheet(designSheet, ci, pageIndex) {
3129
+ function parseSheet(designSheet, ci, spice, pageIndex) {
1294
3130
  const nets = pageNets(pageIndex?.edges ?? [], pageIndex?.links.map((l) => l.id) ?? [], pageIndex?.pins.map((p) => p.id) ?? []);
1295
3131
  const pinPts = new Map;
1296
3132
  const pinSkip = new Set(["CIITSymbolComp", "CVirtualConnector", "DesignSheet"]);
@@ -1315,7 +3151,8 @@ function parseSheet(designSheet, ci, pageIndex) {
1315
3151
  ];
1316
3152
  for (const comp of comps) {
1317
3153
  const placed = parsePlaced(comp, pinPts);
1318
- const ciComp = ci.componentsById.get(String(comp.get("CiComponent") ?? ""));
3154
+ const ciId = String(comp.get("CiComponent") ?? "");
3155
+ const ciComp = ci.componentsById.get(ciId);
1319
3156
  if (ciComp?.kind === "power" && placed.symbol.pins.length === 1) {
1320
3157
  placed.symbol.kind = "power";
1321
3158
  placed.symbol.value = connectorModValue(comp, "NI_EWB_NET_GLOBAL_GROUND") || connectorModValue(comp, "NI_EWB_NET_GLOBAL") || ciComp.refdes;
@@ -1333,6 +3170,9 @@ function parseSheet(designSheet, ci, pageIndex) {
1333
3170
  placed.symbol.drawnKey = ciComp.refdes + comp.str("DBComponentSectionName");
1334
3171
  if (ciComp?.part)
1335
3172
  placed.symbol.partName = ciComp.part;
3173
+ const sim = spice.byComponent.get(ciId);
3174
+ if (sim)
3175
+ placed.symbol.sim = sim;
1336
3176
  symbols.push(placed.symbol);
1337
3177
  }
1338
3178
  const labels = [];
@@ -1446,8 +3286,8 @@ function parseSheet(designSheet, ci, pageIndex) {
1446
3286
  texts.push({ text, at: apply(affineOf(t), { x: 0, y: 0 }), size: fontSize(t) });
1447
3287
  }
1448
3288
  const nmPerUnit = 250000;
1449
- let width = (num(designSheet.get("WorkAreaRight")) - num(designSheet.get("WorkAreaLeft"))) / nmPerUnit;
1450
- let height = (num(designSheet.get("WorkAreaTop")) - num(designSheet.get("WorkAreaBottom"))) / nmPerUnit;
3289
+ let width = (num2(designSheet.get("WorkAreaRight")) - num2(designSheet.get("WorkAreaLeft"))) / nmPerUnit;
3290
+ let height = (num2(designSheet.get("WorkAreaTop")) - num2(designSheet.get("WorkAreaBottom"))) / nmPerUnit;
1451
3291
  if (!(width > 0 && height > 0)) {
1452
3292
  const xs = wires.flatMap((w) => w.points.map((p) => p.x)).concat(symbols.map((s) => s.at.x));
1453
3293
  const ys = wires.flatMap((w) => w.points.map((p) => p.y)).concat(symbols.map((s) => s.at.y));
@@ -1514,7 +3354,12 @@ function parseSchematicXml(input) {
1514
3354
  if (designSheets.length === 0)
1515
3355
  throw new Error("no DesignSheet element found");
1516
3356
  const ci = parseCiNetlist(doc);
3357
+ const params = circuitParams(root);
3358
+ const paramNames = new Set([...params.values()].flatMap((d) => [...d.matchAll(/^\.param (\w+)=/gm)].map((m) => m[1].toLowerCase())));
1517
3359
  const design = parseMultisimDesign(doc);
3360
+ const namedNets = new Map;
3361
+ flattenNetlist(design, namedNets);
3362
+ const spice = parseSpice(collectCiItems(root), paramNames, design.finalNames(), namedNets);
1518
3363
  portPins = (portId) => {
1519
3364
  const port = portId ? design.ci.get(portId) : undefined;
1520
3365
  return port ? portPinNumbers(port.body) : [];
@@ -1522,20 +3367,59 @@ function parseSchematicXml(input) {
1522
3367
  const sheets = designSheets.map((ds) => {
1523
3368
  const title = ds.str("Title");
1524
3369
  const page = ds.str("PageName") || "1";
1525
- return parseSheet(ds, ci, design.pages.find((p) => p.title === title && p.page === page));
3370
+ return parseSheet(ds, ci, spice, design.pages.find((p) => p.title === title && p.page === page));
1526
3371
  });
1527
3372
  const rootSheet = design.rootTitle || sheets[0].title;
3373
+ const rootPage = sheets.find((sh) => sh.title === rootSheet) ?? sheets[0];
3374
+ const supplies = supplySymbols(sheets, rootPage);
3375
+ rootPage.symbols.push(...supplies.symbols);
3376
+ for (const [sheetName, directive] of params) {
3377
+ const page = sheets.find((sh) => sh.title === sheetName) ?? rootPage;
3378
+ const y = 20 + (page === rootPage ? 30 * (supplies.symbols.length / 2) : 0);
3379
+ page.texts.push({ text: directive, at: { x: parkingX(page), y }, size: 5 });
3380
+ }
3381
+ const rootParams = [...params.keys()].filter((name) => (sheets.find((sh) => sh.title === name) ?? rootPage) === rootPage).length;
3382
+ let parkY = 20 + 30 * (supplies.symbols.length / 2) + 30 * rootParams;
3383
+ if (spice.directives.length) {
3384
+ rootPage.texts.push({ text: spice.directives.join(`
3385
+ `), at: { x: parkingX(rootPage), y: parkY }, size: 5 });
3386
+ parkY += 10 * spice.directives.join(`
3387
+ `).split(`
3388
+ `).length + 20;
3389
+ }
3390
+ const warnings = [];
3391
+ if (spice.library) {
3392
+ const rootDs = designSheets[sheets.indexOf(rootPage)];
3393
+ const state = rootDs?.findAll((e) => e.name === "CIITDiagram").map((d) => d.str("SimState")).find(Boolean);
3394
+ let settings;
3395
+ try {
3396
+ settings = state ? simSettings(state, { digital: /\b(adc_bridge|dac_bridge)\b/i.test(spice.library) }) : undefined;
3397
+ } catch (e) {
3398
+ warnings.push(`simulation settings unreadable: ${e.message}`);
3399
+ }
3400
+ const lines = [settings?.options, settings?.analysis].filter((l) => !!l);
3401
+ if (settings?.skipped.length)
3402
+ lines.push(`* Multisim also has results for: ${settings.skipped.join(", ")}`);
3403
+ if (lines.length && lines[0].startsWith("."))
3404
+ rootPage.texts.push({ text: lines.join(`
3405
+ `), at: { x: parkingX(rootPage), y: parkY }, size: 5 });
3406
+ const cosimInputs = root.find((e) => e.name === "CCoSimConnectorManager")?.child("InputGuids")?.findAll((e) => e.name === "Guid").length ?? 0;
3407
+ if (cosimInputs)
3408
+ warnings.push(`LabVIEW co-simulation: ${cosimInputs} input(s) come from a LabVIEW VI while Multisim runs; in KiCad those nets are undriven`);
3409
+ }
1528
3410
  return {
1529
3411
  source: {
1530
3412
  application: creator?.get("application") ?? "unknown",
1531
- versionMajor: num(creator?.get("versionMajor")),
1532
- versionMinor: num(creator?.get("versionMinor")),
1533
- schema: num(root.get("Schema"))
3413
+ versionMajor: num2(creator?.get("versionMajor")),
3414
+ versionMinor: num2(creator?.get("versionMinor")),
3415
+ schema: num2(root.get("Schema"))
1534
3416
  },
1535
3417
  projectName: project?.str("Name") ?? "",
1536
3418
  rootSheet,
1537
3419
  sheets,
1538
- root: toSchInstance(design.root, sheets, design)
3420
+ root: toSchInstance(design.root, sheets, design),
3421
+ spiceLibrary: spice.library,
3422
+ warnings: [...spice.warnings, ...supplies.warnings, ...warnings]
1539
3423
  };
1540
3424
  }
1541
3425
 
@@ -2315,8 +4199,8 @@ function libParts(s, refs, dropped) {
2315
4199
  ` (pin_numbers${s.showPinNumbers && !power ? "" : " (hide yes)"})`,
2316
4200
  ` (pin_names (offset 0.254)${s.showPinNames && !power ? "" : " (hide yes)"})`,
2317
4201
  ` (exclude_from_sim no)`,
2318
- ` (in_bom ${power ? "no" : "yes"})`,
2319
- ` (on_board ${power ? "no" : "yes"})`,
4202
+ ` (in_bom ${power || s.simOnly ? "no" : "yes"})`,
4203
+ ` (on_board ${power || s.simOnly ? "no" : "yes"})`,
2320
4204
  ` (duplicate_pin_numbers_are_jumpers no)`,
2321
4205
  ` (property "Reference" ${q2(power ? "#PWR" : refPrefix(s))} (at 0 0 0) ${FONT})`
2322
4206
  ].filter(Boolean);
@@ -2439,7 +4323,7 @@ function librarySymbolsFile(specs) {
2439
4323
  box = { x0: Math.min(...pts.map((p) => p.x)), y0: Math.min(...pts.map((p) => p.y)), x1: Math.max(...pts.map((p) => p.x)), y1: Math.max(...pts.map((p) => p.y)) };
2440
4324
  }
2441
4325
  const parts = libParts(centred, [{ path: "", reference: spec.reference, unit: i + 1 }], new Set);
2442
- head = parts.head;
4326
+ head = spec.excludeFromSim ? parts.head.map((l) => l.replace("(exclude_from_sim no)", "(exclude_from_sim yes)")) : parts.head;
2443
4327
  for (const [u, lines] of parts.units)
2444
4328
  units.set(u, lines);
2445
4329
  });
@@ -2518,7 +4402,28 @@ function unitsOf(refs) {
2518
4402
  m.set(1, undefined);
2519
4403
  return m;
2520
4404
  }
2521
- function emitInstance(sym, libName, uuidStr, refs, projectName, dropped = new Set, footprint = "") {
4405
+ function simFields(s, simLibrary) {
4406
+ return s.sim ? simFieldList(s.sim, { value: s.value, prefix: refPrefix(s), library: simLibrary }) : [];
4407
+ }
4408
+ function simFieldList(sim, o) {
4409
+ if (sim.exclude || !sim.device)
4410
+ return [];
4411
+ const simLibrary = o.library;
4412
+ const standardPins = !sim.pins || sim.pins.map(([n, m]) => `${n}=${m}`).join(" ") === "1=+ 2=-";
4413
+ if (sim.value !== undefined && sim.value === o.value && standardPins && o.prefix === sim.device)
4414
+ return [];
4415
+ const fields = [["Sim.Device", sim.device]];
4416
+ if (sim.library && simLibrary)
4417
+ fields.push(["Sim.Library", simLibrary]);
4418
+ if (sim.name)
4419
+ fields.push(["Sim.Name", sim.name]);
4420
+ if (sim.params)
4421
+ fields.push(["Sim.Params", sim.params]);
4422
+ if (sim.pins?.length)
4423
+ fields.push(["Sim.Pins", sim.pins.map(([n, m]) => `${n}=${m}`).join(" ")]);
4424
+ return fields;
4425
+ }
4426
+ function emitInstance(sym, libName, uuidStr, refs, projectName, dropped = new Set, footprint = "", simLibrary = "") {
2522
4427
  const s = sym.floating ? { ...sym, at: { x: sym.at.x + NUDGE, y: sym.at.y + NUDGE } } : sym;
2523
4428
  const reference = refs[0]?.reference ?? s.reference;
2524
4429
  const { angle, mirror } = kicadOrient(s.transform);
@@ -2531,15 +4436,16 @@ function emitInstance(sym, libName, uuidStr, refs, projectName, dropped = new Se
2531
4436
  ` (lib_id ${q2(libName)})`,
2532
4437
  ` (at ${u(s.at.x)} ${u(s.at.y)} ${angle})${mirror ? ` (mirror ${mirror})` : ""}`,
2533
4438
  ` (unit ${refs[0]?.unit ?? 1})`,
2534
- ` (exclude_from_sim no)`,
2535
- ` (in_bom ${power ? "no" : "yes"})`,
2536
- ` (on_board ${power ? "no" : "yes"})`,
4439
+ ` (exclude_from_sim ${s.sim?.exclude ? "yes" : "no"})`,
4440
+ ` (in_bom ${power || s.simOnly ? "no" : "yes"})`,
4441
+ ` (on_board ${power || s.simOnly ? "no" : "yes"})`,
2537
4442
  ` (dnp no)`,
2538
4443
  ` (uuid ${q2(uuidStr)})`,
2539
4444
  property("Reference", reference, refAt, power || !!s.refText?.hidden),
2540
4445
  property("Value", s.value, valAt, !power && !!s.valueText?.hidden),
2541
4446
  property("Footprint", footprint, s.at, true),
2542
4447
  property("Datasheet", "", s.at, true),
4448
+ ...simFields(s, simLibrary).map(([k, v]) => property(k, v, s.at, true)),
2543
4449
  ...[...new Set(uniquePins(s.pins).filter((p) => !dropped.has(p.number)).flatMap((p) => [...unitsOf(refs).values()].map((m) => m?.[p.number] ?? p.number)))].map((n) => ` (pin ${q2(n)} (uuid ${q2(uuid2())}))`),
2544
4450
  ` (instances (project ${q2(projectName)} ${refs.map((r) => `(path ${q2(r.path)} (reference ${q2(r.reference)}) (unit ${r.unit}))`).join(" ")}))`,
2545
4451
  ` )`
@@ -2731,7 +4637,7 @@ function resolveContacts(symbolsIn, segmentsIn, labelsIn) {
2731
4637
  const labels = labelsIn.map((l) => l.floating ? l : { ...l, at: relocate(l.at, l.netId) });
2732
4638
  return { symbols, segments, labels };
2733
4639
  }
2734
- function renderPage(f, sch, isRoot, footprints) {
4640
+ function renderPage(f, sch, isRoot, footprints, simLibrary = "") {
2735
4641
  const importNote = `Imported from ${sch.source.application} ${sch.source.versionMajor}.${sch.source.versionMinor} via multisim2kicad`;
2736
4642
  const rawSegments = [];
2737
4643
  for (const w of f.sheet.wires)
@@ -2783,7 +4689,7 @@ function renderPage(f, sch, isRoot, footprints) {
2783
4689
  ...sheet.buses.flatMap(emitBus),
2784
4690
  ...sheet.busEntries.map(emitBusEntry),
2785
4691
  ...sheet.texts.map((t) => ` (text ${q2(t.text)} (exclude_from_sim no) (at ${u(t.at.x)} ${u(t.at.y)} 0) (effects (font (size ${u(t.size)} ${u(t.size)})) (justify left top)) (uuid ${q2(uuid2())}))`),
2786
- ...sheet.symbols.map((s, i) => emitInstance(s, f.libNames[i], f.symbolUuids[i], f.symbolRefs[i], sch.projectName, f.droppedPins[i], footprints?.get(f.symbolRefs[i][0]?.reference ?? ""))),
4692
+ ...sheet.symbols.map((s, i) => emitInstance(s, f.libNames[i], f.symbolUuids[i], f.symbolRefs[i], sch.projectName, f.droppedPins[i], footprints?.get(f.symbolRefs[i][0]?.reference ?? ""), simLibrary)),
2787
4693
  ...sheetSymbols,
2788
4694
  ...isRoot ? [` (sheet_instances (path "/" (page "1")))`] : [],
2789
4695
  ` (embedded_fonts no)`,
@@ -2920,8 +4826,11 @@ function emitKicadSchProject(source, baseName, opts = {}) {
2920
4826
  });
2921
4827
  }
2922
4828
  const out = new Map;
4829
+ const simLibrary = sch.spiceLibrary ? `${baseName}.lib` : "";
2923
4830
  for (const f of files.values())
2924
- out.set(f.fileName, renderPage(f, sch, f === rootFile, opts.footprints));
4831
+ out.set(f.fileName, renderPage(f, sch, f === rootFile, opts.footprints, simLibrary));
4832
+ if (simLibrary)
4833
+ out.set(simLibrary, sch.spiceLibrary);
2925
4834
  return { files: out, links, symbolLibrary: library.file() };
2926
4835
  }
2927
4836
  function dropSharedPins(files) {
@@ -2952,7 +4861,10 @@ function emitKicadSch(sch) {
2952
4861
  return [...emitKicadSchProject(sch, "out").files.values()][0];
2953
4862
  }
2954
4863
  function kicadProSchematicSettings() {
2955
- return { connection_grid_size: 10 };
4864
+ return {
4865
+ connection_grid_size: 10,
4866
+ ngspice: { fix_include_paths: true, fix_passive_vals: false, meta: { version: 0 }, model_mode: 2, workbook_filename: "" }
4867
+ };
2956
4868
  }
2957
4869
 
2958
4870
  // src/db/symbols.ts
@@ -3084,7 +4996,7 @@ var ELECTRICAL = {
3084
4996
  TRISTATE: "tri_state",
3085
4997
  NC: "no_connect"
3086
4998
  };
3087
- function databaseSymbols(db, footprintFor) {
4999
+ function databaseSymbols(db, footprintFor, spicePath = (family) => `${family}.lib`) {
3088
5000
  const warnings = [];
3089
5001
  const pictures = new Map;
3090
5002
  for (const r of rows(db, "SYS_SYMBOL_PICTURE")) {
@@ -3101,6 +5013,28 @@ function databaseSymbols(db, footprintFor) {
3101
5013
  const packages = new Map(rows(db, "SYS_PCB_PACKAGE").map((r) => [r.Package_ID, String(r.Package_Type ?? "")]));
3102
5014
  const sectionsOf = groupBy(rows(db, "SYS_MAPPING_COMP_SYMBOL"), (r) => r.Component_ID);
3103
5015
  const packageOf = new Map(rows(db, "SYS_MAPPING_COMP_PACKAGE").map((r) => [r.Component_ID, r]));
5016
+ const modelRowsOf = groupBy(rows(db, "SYS_MAPPING_COMP_MODEL"), (r) => r.Component_ID);
5017
+ const modelText = new Map(rows(db, "SYS_MODEL").map((r) => [String(r.MODEL_ID ?? "").toLowerCase(), String(r.DATA ?? "")]));
5018
+ const modelCache = new Map;
5019
+ const modelFor = (id) => {
5020
+ const key = id.toLowerCase();
5021
+ if (!modelCache.has(key))
5022
+ modelCache.set(key, modelText.has(key) ? modelDef(id, modelText.get(key)) : undefined);
5023
+ return modelCache.get(key);
5024
+ };
5025
+ const pinModelRows = new Map(rows(db, "SYS_MODEL_PIN").map((r) => [String(r.MODEL_ID ?? "").toLowerCase(), r]));
5026
+ const pinModelCache = new Map;
5027
+ const pinModelFor = (id) => {
5028
+ const key = id.toLowerCase();
5029
+ if (!pinModelCache.has(key)) {
5030
+ const r = pinModelRows.get(key);
5031
+ const def = r ? pinModelDef(id, String(r.DATA ?? "")) : undefined;
5032
+ pinModelCache.set(key, def && r ? { model: def, template: String(r.TEMPLATE ?? "") } : undefined);
5033
+ }
5034
+ return pinModelCache.get(key);
5035
+ };
5036
+ const spiceLibs = new Map;
5037
+ let needParams = 0;
3104
5038
  const used = new Set;
3105
5039
  const specs = [];
3106
5040
  for (const c of rows(db, "SYS_COMPONENT")) {
@@ -3196,18 +5130,75 @@ function databaseSymbols(db, footprintFor) {
3196
5130
  fields.push(["EW_Family", familyName]);
3197
5131
  if (pkgName && !footprint)
3198
5132
  fields.push(["EW_Package", pkgName]);
5133
+ const terminals = new Map;
5134
+ pinNames.forEach((n, k) => {
5135
+ const num = pads[k]?.[0] ?? (pkg ? undefined : n);
5136
+ if (!terminals.has(n) && num && placedPads.has(num))
5137
+ terminals.set(n, num);
5138
+ });
5139
+ const bySection = new Map;
5140
+ for (const r of modelRowsOf.get(c.Component_ID) ?? []) {
5141
+ if (!String(r.Template ?? "").trim())
5142
+ continue;
5143
+ const sec = Number(r.Sec_Order);
5144
+ const cur = bySection.get(sec);
5145
+ const id = String(r.Model_ID ?? "");
5146
+ const curId = String(cur?.Model_ID ?? "");
5147
+ if (!cur || id.length < curId.length || id.length === curId.length && id < curId)
5148
+ bySection.set(sec, r);
5149
+ }
5150
+ const modelRows = [...bySection].sort((a, b) => a[0] - b[0]).map(([, r]) => r);
5151
+ const reference = /^[A-Za-z_#]*/.exec(String(family?.Template ?? ""))[0] || "U";
5152
+ let excludeFromSim = modelRows.length === 0;
5153
+ if (modelRows.some((r) => /#\d|%v\d|%S\d/.test(String(r.Template)))) {
5154
+ needParams++;
5155
+ excludeFromSim = true;
5156
+ } else if (modelRows.length) {
5157
+ const fam = sanitize(familyName) || "Misc";
5158
+ const lib = spiceLibs.get(fam) ?? new SpiceLibrary;
5159
+ spiceLibs.set(fam, lib);
5160
+ const pinModels = new Map;
5161
+ lines(c.Pin_Type).forEach((t, k) => {
5162
+ const id = t.split(":")[2];
5163
+ const pm = id ? pinModelFor(id) : undefined;
5164
+ if (pm && pinNames[k] && !pinModels.has(pinNames[k]))
5165
+ pinModels.set(pinNames[k], pm);
5166
+ });
5167
+ const sections = modelRows.map((r) => {
5168
+ const id = String(r.Model_ID ?? "");
5169
+ const model = id && id !== "DUMMY" ? modelFor(id) : undefined;
5170
+ if (id && id !== "DUMMY" && !model && /%m/.test(String(r.Template)))
5171
+ lib.warnings.push(`${compName}: model ${id} not in the database`);
5172
+ return { template: String(r.Template), params: [], model, pins: terminals, pinModels };
5173
+ });
5174
+ const sim = simSpec(compName, sections, lib, `EW_${sanitize(compName).replace(/[^A-Za-z0-9_]/g, "_")}`);
5175
+ if (sim.exclude)
5176
+ excludeFromSim = true;
5177
+ else
5178
+ fields.push(...simFieldList(sim, { value: compName, prefix: reference, library: spicePath(fam) }));
5179
+ }
3199
5180
  specs.push({
3200
5181
  name,
3201
- reference: /^[A-Za-z_#]*/.exec(String(family?.Template ?? ""))[0] || "U",
5182
+ reference,
3202
5183
  value: compName,
3203
5184
  footprint,
3204
5185
  fields,
5186
+ excludeFromSim,
3205
5187
  showPinNames,
3206
5188
  showPinNumbers: true,
3207
5189
  units
3208
5190
  });
3209
5191
  }
3210
- return { specs, warnings };
5192
+ if (needParams)
5193
+ warnings.push(`${needParams} parts need instance parameters for simulation (set when placed in Multisim); excluded from simulation`);
5194
+ const spice = new Map;
5195
+ for (const [fam, lib] of spiceLibs) {
5196
+ warnings.push(...lib.warnings);
5197
+ const text = lib.text(`SPICE models for the ${fam} family (multisim2kicad)`);
5198
+ if (text)
5199
+ spice.set(fam, text);
5200
+ }
5201
+ return { specs, warnings, spice };
3211
5202
  }
3212
5203
  var PIN = 9;
3213
5204
  function pinBlock(pins) {
@@ -3644,6 +5635,13 @@ function reportSch(input, sch, fileCount) {
3644
5635
  console.log(` wires: ${sheet.wires.length} labels: ${sheet.labels.length} buses: ${sheet.buses.length}`);
3645
5636
  }
3646
5637
  console.log(` instances: ${countInstances(sch.root)} sheet instance(s), ${fileCount} file(s)`);
5638
+ const parts = sch.sheets.flatMap((sh) => sh.symbols).filter((s) => s.kind === "part");
5639
+ const modelled = parts.filter((s) => s.sim?.device && !s.simOnly).length;
5640
+ const excluded = parts.filter((s) => s.sim?.exclude).length;
5641
+ const supplies = parts.filter((s) => s.simOnly).length;
5642
+ console.log(` simulation: ${modelled} parts modelled, ${excluded} without a model (excluded), ${supplies} supply source(s)`);
5643
+ for (const w of sch.warnings ?? [])
5644
+ console.log(` warning: ${w}`);
3647
5645
  }
3648
5646
  var countInstances = (i) => 1 + i.children.reduce((n, c) => n + countInstances(c), 0);
3649
5647
  async function writeProjectFile(path, schematic, board) {
@@ -3743,9 +5741,14 @@ async function convertDatabase(input, outDir) {
3743
5741
  const syms = databaseSymbols(db, (pkg) => {
3744
5742
  const name = footprintName({ name: pkg });
3745
5743
  return h.library.has(name) ? `${lib}:${name}` : undefined;
3746
- });
5744
+ }, (family) => `\${KIPRJMOD}/${lib}.spice/${family}.lib`);
3747
5745
  const symPath = join(outDir, `${lib}.kicad_sym`);
3748
5746
  await writeFile(symPath, librarySymbolsFile(syms.specs), "utf8");
5747
+ if (syms.spice.size) {
5748
+ await mkdir(join(outDir, `${lib}.spice`), { recursive: true });
5749
+ for (const [family, text] of syms.spice)
5750
+ await writeFile(join(outDir, `${lib}.spice`, `${family}.lib`), text, "utf8");
5751
+ }
3749
5752
  await addLibTableEntry(join(outDir, "sym-lib-table"), "sym_lib_table", lib, `\${KIPRJMOD}/${lib}.kicad_sym`, `Symbols from the EW database ${basename(input)} (multisim2kicad)`);
3750
5753
  const reasons = new Map;
3751
5754
  for (const s of fps.skipped)
@@ -3753,6 +5756,8 @@ async function convertDatabase(input, outDir) {
3753
5756
  console.log(`${input}`);
3754
5757
  console.log(` footprints: ${h.library.size} -> ${pretty}`);
3755
5758
  console.log(` symbols: ${syms.specs.length} -> ${symPath} (${syms.specs.filter((x) => x.footprint).length} with a footprint here)`);
5759
+ const simulated = syms.specs.filter((x) => x.fields?.some(([k]) => k === "Sim.Device")).length;
5760
+ console.log(` simulation: ${simulated} symbols with a SPICE model (${syms.spice.size} family libraries in ${lib}.spice/), ${syms.specs.filter((x) => x.excludeFromSim).length} excluded`);
3756
5761
  for (const w of syms.warnings.slice(0, 20))
3757
5762
  console.log(` warning: ${w}`);
3758
5763
  if (syms.warnings.length > 20)