@tscircuit/ngspice-spice-engine 0.0.22 → 0.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -3
  2. package/dist/index.js +132 -6
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -9,8 +9,8 @@ import { Circuit } from "tscircuit"
9
9
  const circuit = new Circuit({
10
10
  platform: {
11
11
  spiceEngineMap: {
12
- ngspice: ngspiceSpiceEngine
13
- }
14
- }
12
+ ngspice: ngspiceSpiceEngine,
13
+ },
14
+ },
15
15
  })
16
16
  ```
package/dist/index.js CHANGED
@@ -87,6 +87,107 @@ var parseTranParams = (spiceString) => {
87
87
  return params;
88
88
  };
89
89
 
90
+ // lib/normalize-pspice-initial-condition-nodes.ts
91
+ import {
92
+ parseToSpiceTokens,
93
+ significantTokens,
94
+ tokensToLogicalCards
95
+ } from "spicets";
96
+ var normalizePspiceInitialConditionNodes = (spiceString) => {
97
+ const cards = tokensToLogicalCards(parseToSpiceTokens(spiceString).tokens);
98
+ let normalizedSpice = spiceString;
99
+ for (const card of cards.toReversed()) {
100
+ const tokens = significantTokens(card.tokens);
101
+ if (tokens[0]?.raw.toLowerCase() !== ".ic") continue;
102
+ for (let voltageTokenIndex = tokens.length - 4; voltageTokenIndex >= 1; voltageTokenIndex--) {
103
+ const voltageToken = tokens[voltageTokenIndex];
104
+ if (voltageToken.raw.toLowerCase() !== "v" || tokens[voltageTokenIndex + 1]?.raw !== "(") {
105
+ continue;
106
+ }
107
+ const closingParenthesisTokenIndex = tokens.findIndex(
108
+ (token, tokenIndex) => tokenIndex > voltageTokenIndex + 1 && token.raw === ")"
109
+ );
110
+ if (closingParenthesisTokenIndex <= voltageTokenIndex + 2 || tokens[closingParenthesisTokenIndex + 1]?.raw !== "=") {
111
+ continue;
112
+ }
113
+ const firstNodeToken = tokens[voltageTokenIndex + 2];
114
+ const lastNodeToken = tokens[closingParenthesisTokenIndex - 1];
115
+ const closingParenthesisToken = tokens[closingParenthesisTokenIndex];
116
+ const nodeName = spiceString.slice(
117
+ firstNodeToken.range.start.offset,
118
+ lastNodeToken.range.end.offset
119
+ );
120
+ normalizedSpice = normalizedSpice.slice(0, voltageToken.range.start.offset) + `${voltageToken.raw}(${nodeName})` + normalizedSpice.slice(closingParenthesisToken.range.end.offset);
121
+ }
122
+ }
123
+ return normalizedSpice;
124
+ };
125
+
126
+ // lib/normalize-pspice-switch-models.ts
127
+ import {
128
+ Model,
129
+ parseSpiceNetlist as parseSpiceNetlist2,
130
+ tokenizeSpice
131
+ } from "spicets";
132
+ var getSwitchModels = (node) => node.getChildren().flatMap((child) => {
133
+ if (child instanceof Model && child.modelType.toLowerCase() === "vswitch") {
134
+ return [child];
135
+ }
136
+ return getSwitchModels(child);
137
+ });
138
+ var normalizePspiceSwitchModels = (spiceString) => {
139
+ const netlist = parseSpiceNetlist2(spiceString);
140
+ let normalizedSource = spiceString;
141
+ for (const model of getSwitchModels(netlist)) {
142
+ const ron = model.params.get("ron")?.getString();
143
+ const roff = model.params.get("roff")?.getString();
144
+ const von = model.params.get("von")?.getString();
145
+ const voff = model.params.get("voff")?.getString();
146
+ if (!ron || !roff || !von || !voff || !model.originalSource) continue;
147
+ const ronTokens = tokenizeSpice(ron).tokens;
148
+ const roffTokens = tokenizeSpice(roff).tokens;
149
+ const ronToken = ronTokens[0];
150
+ const roffToken = roffTokens[0];
151
+ if (ronTokens.length === 1 && roffTokens.length === 1 && ronToken?.type === "number" && roffToken?.type === "number" && ronToken.value !== null && roffToken.value !== null && ronToken.value <= roffToken.value) {
152
+ continue;
153
+ }
154
+ model.params.set("ron", `{min(${ron},${roff})}`);
155
+ model.params.set("roff", `{max(${ron},${roff})}`);
156
+ model.params.set("von", `{if(${ron}>${roff},${voff},${von})}`);
157
+ model.params.set("voff", `{if(${ron}>${roff},${von},${voff})}`);
158
+ normalizedSource = normalizedSource.replace(
159
+ model.originalSource,
160
+ () => model.toSource({ format: "pretty" })
161
+ );
162
+ }
163
+ return normalizedSource;
164
+ };
165
+
166
+ // lib/rewrite-pspice-current-source-units.ts
167
+ import { CurrentSource, parseSpiceNetlist as parseSpiceNetlist3 } from "spicets";
168
+ var getCurrentSources = (node) => node.getChildren().flatMap((child) => {
169
+ if (child instanceof CurrentSource) return [child];
170
+ return getCurrentSources(child);
171
+ });
172
+ var rewritePspiceCurrentSourceUnits = (spiceString) => {
173
+ const netlist = parseSpiceNetlist3(spiceString);
174
+ let rewrittenSource = spiceString;
175
+ for (const source of getCurrentSources(netlist)) {
176
+ const current = source.dc?.getString();
177
+ if (!current || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:meg|mil|[tgkmunpfa])?Adc$/i.test(
178
+ current
179
+ ) || !source.originalSource) {
180
+ continue;
181
+ }
182
+ source.dc.raw = current.slice(0, -3);
183
+ rewrittenSource = rewrittenSource.replace(
184
+ source.originalSource,
185
+ () => source.toSource({ format: "pretty" })
186
+ );
187
+ }
188
+ return rewrittenSource;
189
+ };
190
+
90
191
  // lib/rewrite-pspice-compatibility-syntax.ts
91
192
  var pspiceNumberToken = String.raw`([+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?)`;
92
193
  var rewritePspiceResistorTcPairs = (spiceString) => spiceString.split(/\r?\n/).map((line) => {
@@ -150,7 +251,15 @@ var rewritePspiceValueBooleanCarets = (spiceString) => {
150
251
  }
151
252
  return result + spiceString.slice(cursor);
152
253
  };
153
- var rewritePspiceCompatibilitySyntax = (spiceString) => rewritePspiceValueBooleanCarets(rewritePspiceResistorTcPairs(spiceString));
254
+ var rewritePspiceCompatibilitySyntax = (spiceString) => normalizePspiceSwitchModels(
255
+ rewritePspiceCurrentSourceUnits(
256
+ rewritePspiceValueBooleanCarets(
257
+ normalizePspiceInitialConditionNodes(
258
+ rewritePspiceResistorTcPairs(spiceString)
259
+ )
260
+ )
261
+ )
262
+ );
154
263
 
155
264
  // lib/create-graph-from-requested-plot.ts
156
265
  var getNetName = (spiceVector) => {
@@ -305,10 +414,10 @@ var extractCurrentProbeMetadata = (spiceString) => {
305
414
  };
306
415
 
307
416
  // lib/extract-requested-plots.ts
308
- import { Print, parseSpiceNetlist as parseSpiceNetlist2 } from "spicets";
417
+ import { Print, parseSpiceNetlist as parseSpiceNetlist4 } from "spicets";
309
418
  var extractRequestedPlots = (spiceString) => {
310
419
  const supportedAnalyses = /* @__PURE__ */ new Set(["tran", "op", "dc", "ac"]);
311
- const print = parseSpiceNetlist2(spiceString, {
420
+ const print = parseSpiceNetlist4(spiceString, {
312
421
  dialect: "ngspice"
313
422
  }).directives.find(
314
423
  (directive) => directive instanceof Print && supportedAnalyses.has(directive.analysis?.toLowerCase() ?? "")
@@ -634,9 +743,9 @@ var operatingPointResultToGraphs = ({
634
743
  };
635
744
 
636
745
  // lib/parse-simulation-analysis.ts
637
- import { Ac, Dc, Op, parseSpiceNetlist as parseSpiceNetlist3, Tran as Tran2 } from "spicets";
746
+ import { Ac, Dc, Op, parseSpiceNetlist as parseSpiceNetlist5, Tran as Tran2 } from "spicets";
638
747
  var parseSimulationAnalysis = (spiceString) => {
639
- const analyses = parseSpiceNetlist3(spiceString, {
748
+ const analyses = parseSpiceNetlist5(spiceString, {
640
749
  dialect: "ngspice"
641
750
  }).analyses;
642
751
  if (analyses.some((analysis) => analysis instanceof Tran2)) {
@@ -685,6 +794,24 @@ var eecircuitResultToSimulationGraphs = (result, spiceString) => {
685
794
  return [];
686
795
  }
687
796
  const timeSeconds = timeOutput.values;
797
+ const tranParams = parseTranParams(spiceString);
798
+ if (tranParams?.tstop !== void 0) {
799
+ const tstartSeconds = tranParams.tstart ?? 0;
800
+ const lastRequestedTimeSeconds = tranParams.tstep ? tstartSeconds + Math.floor((tranParams.tstop - tstartSeconds) / tranParams.tstep) * tranParams.tstep : tranParams.tstop;
801
+ const lastTimeSeconds = timeSeconds.at(-1);
802
+ const toleranceSeconds = Math.max(
803
+ Math.abs(lastRequestedTimeSeconds) * 1e-9,
804
+ Number.EPSILON
805
+ );
806
+ if (lastTimeSeconds === void 0 || !Number.isFinite(lastTimeSeconds)) {
807
+ throw new Error("Transient simulation produced no finite time samples.");
808
+ }
809
+ if (lastTimeSeconds + toleranceSeconds < lastRequestedTimeSeconds) {
810
+ throw new Error(
811
+ `Transient simulation stopped at ${lastTimeSeconds} s before the requested output time ${lastRequestedTimeSeconds} s.`
812
+ );
813
+ }
814
+ }
688
815
  const voltageOutputs = result.data.filter(
689
816
  (simulationOutput) => simulationOutput.type === "voltage" && Array.isArray(simulationOutput.values)
690
817
  );
@@ -760,7 +887,6 @@ var eecircuitResultToSimulationGraphs = (result, spiceString) => {
760
887
  });
761
888
  if (graph) graphs.push(graph);
762
889
  }
763
- const tranParams = parseTranParams(spiceString);
764
890
  if (tranParams?.tstep && tranParams.tstep > 0 && tranParams.tstop && graphs.length > 0) {
765
891
  const { tstep, tstop } = tranParams;
766
892
  const tstart = tranParams.tstart ?? 0;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tscircuit/ngspice-spice-engine",
3
3
  "license": "MIT",
4
- "version": "0.0.22",
4
+ "version": "0.0.24",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/tscircuit/ngspice-spice-engine"