Skip to content

Commit f7cab37

Browse files
Update docs
1 parent 42a463e commit f7cab37

4 files changed

Lines changed: 3804 additions & 9 deletions

File tree

.claude/skills/spicesharp-circuit-design/SKILL.md

Lines changed: 80 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
name: spicesharp-circuit-design
3-
description: Structured R&D problem-solving with test-driven verification for designing analog circuits using SpiceSharp and SpiceSharpParser that produces human-readable reports, netlist and tests and maintains a global backlog of active designs.
3+
description: Structured R&D problem-solving with test-driven verification for designing analog circuits using SpiceSharp and SpiceSharpParser, including modern parser features such as .MEAS, .FOUR, .PRINT, .PLOT, .STEP, .TEMP, .MC, .NOISE, behavioral and LAPLACE sources, and local documentation/test-suite validation. Produces human-readable reports, netlists, tests, and maintains a global backlog of active designs.
44
user-invocable: true
55
---
66

@@ -85,6 +85,30 @@ tests/
8585

8686
---
8787

88+
## Current SpiceSharpParser Feature Surface
89+
90+
Use the parser's current netlist features directly instead of reimplementing post-processing in ad-hoc C# when a dot statement exists. For exact syntax, read `src/docs/index.md` first, then the specific article and matching tests under `src/SpiceSharpParser.IntegrationTests/`.
91+
92+
| Category | Supported features | Primary references |
93+
|----------|--------------------|--------------------|
94+
| Analyses | `.OP`, `.DC`, `.AC`, `.TRAN`, `.NOISE` | `src/docs/articles/op.md`, `dc.md`, `ac.md`, `tran.md`, `noise.md` |
95+
| Output/post-processing | `.SAVE`, `.PRINT`, `.PLOT`, `.MEAS`/`.MEASURE`, `.FOUR`, `.WAVE` | `save.md`, `print.md`, `plot.md`, `meas.md`, `four.md`; `.WAVE` source/control code |
96+
| Parameters/expressions | `.PARAM`, `.FUNC`, `.LET`, `.SPARAM`, nested exports such as `db(V(out))`, `mag(I(R1))` | `param.md`, `func.md`, `let.md`, `sparam.md`, `meas.md` |
97+
| Sweeps/control/statistics | `.STEP`, `.ST`, `.TEMP`, `.MC`, `.DISTRIBUTION`, `.OPTIONS`, `.IC`, `.NODESET`, `.IF` | `step.md`, `st.md`, `temp.md`, `mc.md`, `distribution.md`, `options.md`, `ic.md`, `nodeset.md`, `if.md` |
98+
| Structure/models | `.SUBCKT`, `X...`, `.INCLUDE`, `.LIB`, `.GLOBAL`, `.CONNECT`, `.APPENDMODEL`, `.MODEL` | `subckt.md`, `subcircuit-instance.md`, `include.md`, `lib.md`, `global.md`, `appendmodel.md`; `DotStatements/ConnectTests.cs` |
99+
| Sources/devices | R, C, L, K, D, Q, J, M, V, I, B, E/F/G/H, S/W switches, T transmission line, BVDelay, PULSE/SIN/PWL/EXP/SFFM/AM/WAVE/wavefile, VALUE/TABLE/POLY/LAPLACE | matching component articles and integration tests |
100+
101+
Prefer netlist-native controls for reproducibility:
102+
- Use `.MEAS` for scalar acceptance criteria, including `TRIG/TARG`, `WHEN`, `FIND`, `MAX`, `MIN`, `AVG`, `RMS`, `PP`, `INTEG`, `DERIV`, and `PARAM`.
103+
- Use `.FOUR` for settled-period harmonic magnitude, phase, normalized dB, and THD from transient waveforms.
104+
- Use `.PRINT` for tabular exported data and `.PLOT` for structured XY plot data when reports need curves.
105+
- Use `.WAVE` only when a transient waveform must be exported to a WAV file as a design artifact.
106+
- Use `.STEP`, `.TEMP`, `.MC`, and `.DISTRIBUTION` for sweeps, corners, and statistical robustness instead of manual loops.
107+
108+
When `CircuitBuilder` has no dedicated helper for a current feature, use `RawLine()` with the exact netlist statement (for example `.RawLine(".FOUR 1k V(OUT)")`, `.RawLine(".STEP PARAM r LIST 1k 2k 5k")`, `.RawLine(".PLOT TRAN V(OUT) merge")`).
109+
110+
---
111+
88112
## Phases
89113

90114
Phases are guidelines, not a rigid waterfall. Skip or merge phases when the situation warrants it (e.g., skip Phase 2 if the user specifies the topology; merge Phases 3-4 for simple circuits).
@@ -115,7 +139,7 @@ Create xUnit test project in `tests/CircuitTests/` targeting **net8.0**:
115139
1. Ask the user what circuit they want and its purpose
116140
2. **WebSearch** the circuit type for standard specs, typical values, and design trade-offs
117141
3. Elicit quantitative specs (frequency, gain, impedance, supply, bandwidth, Q, noise, timing)
118-
4. Identify required analyses (`.OP`, `.DC`, `.AC`, `.TRAN`, `.NOISE`)
142+
4. Identify required analyses (`.OP`, `.DC`, `.AC`, `.TRAN`, `.NOISE`) and post-processing controls (`.MEAS`, `.FOUR`, `.PRINT`, `.PLOT`, `.SAVE`, `.WAVE` when audio export matters)
119143
5. Create `circuits/<name>/requirements.md` with spec table, operating conditions, acceptance criteria
120144
6. Update `backlog.md`
121145

@@ -142,13 +166,18 @@ Create xUnit test project in `tests/CircuitTests/` targeting **net8.0**:
142166
1. Write netlist to `circuits/<name>/<name>.cir` — use `CircuitBuilder` for programmatic construction when beneficial
143167
2. **Run `SmokeTester.QuickCheck()`** — fix any structural issues before proceeding
144168
3. Run `NetlistLinter.Lint()` for additional validation
145-
4. Include `.MEAS` directives for ALL specs that need automated verification
169+
4. Include `.MEAS` directives for ALL scalar specs that need automated verification
170+
5. Add `.FOUR` for THD/harmonic specs, `.PRINT` for tabular report data, `.PLOT` for reusable curve data, and `.WAVE` only for requested audio artifacts
146171

147172
**SPICE quick reference**: For syntax details (devices, waveforms, analyses, expressions), read `src/SpiceSharpParser.IntegrationTests/` examples or use WebSearch. Key rules:
148173
- Ground is node `0`; every node needs DC path to ground (add 1GΩ if needed)
149174
- Every semiconductor needs `.MODEL`
150175
- AC analysis: use `VM()`/`VDB()`/`VP()`, never plain `V()`
151-
- Prefer `.MEAS` over `.SAVE` for spec verification
176+
- Prefer `.MEAS` over `.SAVE` for scalar spec verification; use `.SAVE`/`.PRINT`/`.PLOT` only when waveform/table/plot data is actually needed
177+
- Use `.LET` for reusable dynamic expressions such as power or gain, `.FUNC` for reusable equations, and `.SPARAM` only when immediate scalar evaluation is required before setup/sweeps
178+
- Use `.TEMP` for temperature corners and `.STEP PARAM temp_val` + `.OPTIONS TEMP={temp_val}` for continuous temperature sweeps
179+
- Use `.MC` with `.DISTRIBUTION`/`.APPENDMODEL` for statistical validation once nominal and deterministic corner tests pass
180+
- Use `.CONNECT` to intentionally short aliases or package pins; prefer clear shared node names when designing from scratch
152181

153182
#### LAPLACE Transfer Sources
154183

@@ -192,17 +221,50 @@ Rules and gotchas:
192221
- `G` and `F` current is defined from `out+` to `out-`; with a grounded load this may produce inverted output voltage.
193222
- For details and examples, read `src/docs/articles/laplace.md`, `src/docs/articles/laplace-basics.md`, and `src/SpiceSharpParser.IntegrationTests/AnalogBehavioralModeling/LaplaceTests.cs`.
194223

224+
#### `.FOUR` Fourier / THD Post-Processing
225+
226+
Use `.FOUR` when the requirement includes THD, harmonic content, distortion cleanup, phase of harmonics, square-wave harmonic ratios, or before/after filter harmonic comparison. It is netlist-driven transient post-processing; prefer it over hand-written FFT code when the desired result is a settled periodic waveform metric.
227+
228+
Syntax:
229+
230+
```spice
231+
.TRAN <step> <stop> [<start>] [<maxstep>]
232+
.FOUR <fundamental_frequency> <expr1> [<expr2> ...]
233+
```
234+
235+
Examples:
236+
237+
```spice
238+
V1 OUT 0 SIN(0 1 1k)
239+
R1 OUT 0 1k
240+
.TRAN 1u 10m 0 2u
241+
.FOUR 1k V(OUT) I(V1)
242+
```
243+
244+
Rules and gotchas:
245+
- `.FOUR` requires `.TRAN`; it analyzes the last complete period, so run long enough for startup to settle and for at least one full final period.
246+
- Choose the true repetition frequency. A wrong `f0` creates misleading harmonics and THD.
247+
- Use a small max step; aim for at least 20 samples per highest harmonic period, and 50-100 samples for good magnitudes.
248+
- Results are stored in `model.FourierAnalyses`, one result per signal per transient simulation or `.STEP` point.
249+
- Each result has `SignalName`, `SimulationName`, `FundamentalFrequency`, `TotalHarmonicDistortionPercent`, `Success`, `ErrorMessage`, and `Harmonics`.
250+
- Harmonic rows cover DC and harmonics 1-9 with `Magnitude`, `PhaseDegrees`, `NormalizedMagnitude`, and `NormalizedMagnitudeDecibels`; THD is computed from harmonics 2-9.
251+
- If using `CircuitBuilder`, add `.FOUR` with `RawLine()`; there is no dedicated builder helper.
252+
- For exact behavior and examples, read `src/docs/articles/four.md` and `src/SpiceSharpParser.IntegrationTests/DotStatements/FourTests.cs`.
253+
195254
### Phase 5: Simulation & Verification
196255

197256
**Every design MUST produce `tests/<CircuitName>Tests.cs`.**
198257

199258
- One test method per spec, descriptive names: `BandpassFilter_Has3dBBandwidthOf10kHz`
200259
- Inline netlist as string constant; use `CircuitTestHelper` methods
201-
- Use `WaveformAnalyzer` for complex analysis (FFT, THD, stability margins, rise time)
260+
- Prefer `.MEAS` assertions for scalar specs; check `.Success` before reading `.Value`
261+
- Assert `.FOUR` results from `model.FourierAnalyses` for harmonic/THD/phase specs
262+
- Assert `.PRINT` data through `model.Prints` and `.PLOT` data through `model.XyPlots` when report tables or curves are part of the acceptance criteria
263+
- Use `WaveformAnalyzer` for analysis that has no netlist-native equivalent or for C#-side cross-checks (custom FFT, extra THD checks, stability margins, rise/fall/settling metrics)
202264
- Run `dotnet test --logger "trx"` — all must pass before Phase 6
203265
- **10+ assertions per circuit is normal** — verify primary specs, boundary behavior, DC bias, passband/stopband, transient behavior, phase response, sanity checks
204266

205-
**Tolerance analysis**: After nominal passes, add tests with `.STEP`/`.MC` for ±5-10% component tolerances.
267+
**Robustness analysis**: After nominal passes, add deterministic `.STEP` tests for tolerance/corner sweeps, `.TEMP` tests for temperature corners, and `.MC` tests with explicit `SEED=` for statistical checks. Use `.DISTRIBUTION` and `.APPENDMODEL` when device/model variation matters.
206268

207269
#### Hypothesis-Driven Fix Protocol
208270

@@ -250,7 +312,8 @@ For full API details, read the source files directly — don't rely on this summ
250312
| **NetlistLinter** | `src/SpiceSharpParser/Validation/NetlistLinter.cs` | After `ParseAndRead()`, before tests. Catches missing DC paths, missing models, duplicates. |
251313
| **SmokeTester** | `src/SpiceSharpParser/Analysis/SmokeTester.cs` | Phase 4b — one-call parse+lint+OP+device regions. `SmokeTester.QuickCheck(netlist)` |
252314
| **CircuitInspector** | `src/SpiceSharpParser/Analysis/CircuitInspector.cs` | Query topology, get/set component values, check BJT/MOSFET regions |
253-
| **WaveformAnalyzer** | `src/SpiceSharpParser/Analysis/WaveformAnalyzer.cs` | Post-sim: RiseTime, THD, FFT, BandwidthFrom3dBPoints, StabilityMargins, Overshoot |
315+
| **WaveformAnalyzer** | `src/SpiceSharpParser/Analysis/WaveformAnalyzer.cs` | C#-side post-sim analysis: RiseTime, THD, FFT, BandwidthFrom3dBPoints, StabilityMargins, Overshoot |
316+
| **.FOUR / FourierAnalysisResult** | `src/SpiceSharpParser/ModelReaders/Netlist/Spice/Readers/Controls/Fourier/` | Netlist-native transient Fourier/THD with magnitude, phase, normalized dB, harmonics 0-9 |
254317
| **SensitivityAnalyzer** | `src/SpiceSharpParser/Analysis/SensitivityAnalyzer.cs` | Hypothesis-driven debugging: find which component affects which spec |
255318
| **DesignSpaceExplorer** | `src/SpiceSharpParser/Analysis/DesignSpaceExplorer.cs` | Multi-parameter optimization with objectives and constraints |
256319
| **CircuitBuilder** | `src/SpiceSharpParser/Builder/CircuitBuilder.cs` | Fluent API for programmatic netlist construction and modification |
@@ -260,9 +323,9 @@ For full API details, read the source files directly — don't rely on this summ
260323

261324
1. **Phase 3**`StandardValues.NearestE24()` to snap values
262325
2. **Phase 4**`CircuitBuilder` to construct, `SmokeTester.QuickCheck()` to validate
263-
3. **Phase 5**`NetlistLinter.Lint()` + `.MEAS` tests + `WaveformAnalyzer` for advanced analysis
326+
3. **Phase 5**`NetlistLinter.Lint()` + `.MEAS` tests + `.FOUR` for THD/harmonics + `.PRINT`/`.PLOT` for report data
264327
4. **Phase 5 debug**`CircuitInspector` for bias/regions, `SensitivityAnalyzer.RankedByImpact()` to pick component
265-
5. **Phase 5 optimize**`DesignSpaceExplorer.Explore()` for multi-parameter tuning
328+
5. **Phase 5 optimize**`DesignSpaceExplorer.Explore()` for multi-parameter tuning, then validate with `.STEP`, `.TEMP`, and `.MC`
266329

267330
---
268331

@@ -297,6 +360,8 @@ Programmatically build netlists with a chainable API. Preferable to string conca
297360

298361
**Key methods:** `Resistor()`, `Capacitor()`, `Inductor()`, `VoltageSource()`, `VoltageSourceSine()`, `VoltageSourcePulse()`, `VoltageSourcePWL()`, `CurrentSource()`, `Diode()`, `BJT()`, `MOSFET()`, `JFET()`, `VCVS()`, `VCCS()`, `BehavioralVoltageSource()`, `BehavioralCurrentSource()`, `Model()`, `ModelRaw()`, `OP()`, `DC()`, `AC()`, `Tran()`, `Save()`, `Meas()`, `Print()`, `Param()`, `IC()`, `Options()`, `RawLine()`, `SetValue()`, `RemoveComponent()`, `ToNetlist()`, `Build()`
299362

363+
Use `RawLine()` for newer dot statements without dedicated builder helpers, including `.FOUR`, `.PLOT`, `.WAVE`, `.STEP`, `.TEMP`, `.MC`, `.DISTRIBUTION`, `.GLOBAL`, `.CONNECT`, `.APPENDMODEL`, `.LET`, `.FUNC`, `.SPARAM`, `.NODESET`, and `.IF`.
364+
300365
```csharp
301366
// Build a bandpass filter netlist
302367
var netlist = CircuitBuilder.Create("Bandpass Filter")
@@ -468,6 +533,8 @@ var counts = inspector.GetComponentCounts();
468533

469534
All-static methods for analyzing simulation output waveforms. Data is passed as `List<(double, double)>` tuples collected from simulation exports.
470535

536+
For THD/harmonic acceptance criteria, prefer netlist `.FOUR` when possible because it selects the last complete transient period, reports phase and normalized dB, and stores structured results in `model.FourierAnalyses`. Use `WaveformAnalyzer.FFT()`/`THD()` when you need a custom C#-side spectrum or an independent cross-check.
537+
471538
**Time-domain methods:**
472539
- `RiseTime(data, lowPct=0.1, highPct=0.9)` — 10%-90% rise time
473540
- `FallTime(data, highPct=0.9, lowPct=0.1)` — 90%-10% fall time
@@ -698,6 +765,7 @@ When writing tests, consult these for patterns and inspiration:
698765
- **SpiceSharp**: sibling workspace folder `../SpiceSharp/SpiceSharpTest/``BasicExampleTests.cs`, `Helper.cs`, `Models/`
699766
- **SpiceSharpParser**: `src/SpiceSharpParser.IntegrationTests/``BaseTests.cs`, `Components/`, `DotStatements/`, `AnalogBehavioralModeling/`, `Examples/Circuits/*.cir`
700767
- **LAPLACE**: `src/docs/articles/laplace.md`, `src/docs/articles/laplace-basics.md`, `src/SpiceSharpParser.IntegrationTests/AnalogBehavioralModeling/LaplaceTests.cs`
768+
- **Recent dot statements**: `src/docs/articles/four.md`, `meas.md`, `print.md`, `plot.md`, `noise.md`, `step.md`, `mc.md`, `temp.md`; tests in `src/SpiceSharpParser.IntegrationTests/DotStatements/*Tests.cs`
701769

702770
Key patterns: tolerance-based assertions (RelTol=1e-3, AbsTol=1e-12), reference function comparison, `.MEAS` validation, string-array netlist construction.
703771

@@ -712,3 +780,6 @@ Key patterns: tolerance-based assertions (RelTol=1e-3, AbsTol=1e-12), reference
712780
| Zero/empty results | 3-step run pattern? (`Run``InvokeEvents``ToArray`) Exports filtered by simulation? |
713781
| Wrong AC results | Using `VM()`/`VDB()` not `V()`? Matched-system 0dB ref = 0.5V not 1V? |
714782
| Wrong values | `.MODEL` realistic? Node connectivity correct? Units in SI? Sim long enough? |
783+
| `.FOUR` missing/failed | `.TRAN` present? At least one complete final period? Signal expression valid? Check `model.FourierAnalyses[*].Success/ErrorMessage` |
784+
| `.FOUR` THD/harmonics odd | Fundamental frequency correct? Max step small enough? Final cycles settled? |
785+
| `.STEP`/`.TEMP` result count unexpected | Measurements and Fourier results produce one result per generated simulation; inspect `SimulationName` |

src/docs/articles/intro.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ Using SpiceSharpParser involves three steps:
5555
2. **Read** — translate the parse-tree model into SpiceSharp simulation objects (circuit, simulations, exports) with `SpiceSharpReader.Read()`.
5656
3. **Simulate** — run the SpiceSharp simulations and collect results via exports and events.
5757

58+
For a detailed look at how SpiceSharp solves the circuit after this handoff, including modified nodal analysis, sparse matrix solving, and component stamps, see [How SpiceSharp Solves Circuits](spicesharp-architecture.md).
59+
5860
### The SpiceSharpModel
5961

6062
`SpiceSharpReader.Read()` returns a `SpiceSharpModel` containing:

0 commit comments

Comments
 (0)