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