Thursday, October 22, 2026

Measurements on Simulation Output - in Xschem

Keeping the schematic tool out of the optimizer loop: where do waveform measurements actually happen?

I'm setting up a circuit optimization in our xschem fork. The topology is fixed; only device sizes and resistor values change from one iteration to the next. So the optimizer can edit the SPICE netlist directly, run ngspice, and never touch the schematic editor. That leaves one question: how does the optimizer get the measurements back? The phase margin, rise time and crossing times we define in ASE-L (our ADE-L-style simulation environment) have to come from somewhere.

My first idea was a menu item, Tools > Write measures.py, that turns the ASE-L setup into a standalone Python script. Before building it, I asked how measurements are computed today. The answer changed the design.

Two kinds of measurement, computed in two different places

1. Measurements ngspice understands. Rows defined under Outputs > Measurements are written into the netlist as ngspice meas lines. ngspice computes them during the run and writes plain name = value lines to a .meas file next to the raw file. The schematic tool only reads that file back. These rows cover:

  • delay between two edges (TRIG … TARG);
  • the value of a signal at a time, or when another signal crosses a level;
  • the time of the n-th rising, falling or either-way crossing of a value;
  • average, RMS, min, max, peak-to-peak and integral over a window;
  • unwrapped phase, Fourier/THD, and expressions over other measurements.

2. Measurements only the Calculator knows. ngspice has no built-in idea of a Cadence-style riseTime, slewRate, settlingTime, overshoot, dutyCycle, frequency, bandwidth, gainBwProd, gainMargin or phaseMargin. The same goes for cross as the Calculator defines it (every crossing, or a chosen one, with its own edge rules), and for any ASE-L Outputs expression built from these. You could approximate some of them with chains of meas lines, but they would not agree with the Calculator to the last digit. That matters when the optimizer is chasing a spec you also check by eye in ASE-L.

For this second kind, nothing outside the editor is involved. After a run, the xschem process reads the raw file into memory and evaluates every Outputs row itself.

The architecture, in one picture

                       ┌──────────────────── xschem process ────────────────────┐
 ASE-L Outputs pane ──►│ result_probe ──► calc::eval_texts  (plans each row)    │
 Calculator window  ──►│                     │                                  │
                       │                     ▼                                  │
                       │   calc::riseTime / cross / phaseMargin …   (Tcl)       │
                       │        │ build a column        ▲ samples                │
                       │        ▼                       │                        │
                       │   ┌──── `xschem raw …` commands (scheduler.c) ───────┐ │
                       │   │ raw read    raw add    raw values    raw index   │ │
                       │   └────┬───────────┬──────────────▲──────────────────┘ │
                       │        ▼           ▼              │              (C)   │
                       │   raw_read    expression engine (plot_raw_custom_data) │
                       │   (save.c) ──► the raw file as arrays of doubles in RAM│
                       └───────▲────────────────────────────────────────────────┘
                               │ reads
   netlist ──► ngspice ──► <cell>_ase.raw
                    └────► <cell>_ase.meas   (ngspice's own `meas` results)

There are three layers in two languages:

  • A raw-file reader in C (src/save.c). It loads ngspice's output into memory, splitting AC data into magnitude, phase, real and imaginary columns.
  • An expression engine in C, also in save.c. It does point-by-point maths that builds new columns, such as v(out)/v(in), db20() and integ().
  • The measurement verbs in Tcl (src/calculator.tcl). They ask the engine for a column, pull its samples into Tcl, and do the crossing, interpolation and margin arithmetic there. The only way they reach the data is through the xschem raw … commands.

Why not a standalone Python script?

A Python measures.py that recomputes everything would be a second copy of the raw reader, the expression engine and about 4,600 lines of measurement code. This code has edge cases that already took several careful fixes in our own tree:

  • a threshold that lands exactly on a rail inventing a crossing;
  • a rise-time edge pairing up with the wrong transition;
  • stateful functions such as integ() leaking across sweep boundaries.

A second copy drifts, and then the optimizer and the GUI disagree about whether a design meets spec.

Why not call just the measurement part?

That was my next question, and today the honest answer is that you can't. The Tcl measurement code only reaches the data through C commands compiled into the editor, and those keep their data in the editor's global state. Carving it out is possible:

  1. Build the raw reader, the expression engine and the raw command into a small Tcl extension.
  2. Move the measurement procs into a file that loads without any GUI.
  3. Load both from Python through the window-less Tcl interpreter that ships with Python (tkinter.Tcl()).

The editor would compile the same files, so the numbers would still match.

But it is a refactor of the file every simulation result passes through, and one measurement makes it unnecessary for now. Headless xschem starts and exits in about 0.06 seconds, using about 21 MB (three runs, no display). Any simulation worth optimizing takes far longer. So "launch the editor headless" really is "run the measurement part" plus about 60 ms. It reads the raw file once; it loads no GUI, schematic or display.

The plan

A menu item, Tools > Export for optimizer, writes three things:

  1. The netlist ASE-L would run, with the design variables marked for substitution. It keeps the write lines that produce the raw file and the meas block.
  2. A manifest saying where the raw and .meas files land, and where each measurement comes from.
  3. A small measures.py that the optimizer calls after each ngspice run. It returns one dictionary of name → value:
    • ngspice-native rows are parsed from the .meas file, with no xschem involved;
    • Calculator-only rows are evaluated by xschem --nogui --pipe --script measures.tcl <raw>, which runs the same code the Outputs pane uses.

The export also lists which rows need the Calculator, so anything ngspice can compute can be moved over.

If 60 ms per iteration ever matters, or the optimizer has to run where xschem isn't installed, the measurement layer can be carved out later behind the same measures.py interface, and the optimizer won't notice.

If you're doing this with an AI coding assistant

The useful move was asking where the numbers come from before asking for the script. Prompts that got me there:

  • "Before you build it: how are these measurements computed today? Is the waveform loaded into memory by the tool, or does an external script produce the number?"
  • "Which measurements can the simulator compute itself, and which exist only in our Calculator?"
  • "Where is that code, which files? And why can't I call just that part?"
  • "Measure the cost of the simple option before proposing a refactor." The 60 ms figure settled the design in one line.
  • "Draw the architecture as an ASCII block diagram."

Tuesday, September 15, 2026

scikit-rf - for Xschem? Why? (Asking Claude)

1. rf.Network('out.s2p') either parses or raises. That alone settles malformed-file questions.

2. It reports back what it read — port count, number of frequency points, reference impedance. If it says 50 Ω and two ports, our header means what we think it means.

3. It lets us compare the S-values it read against what ngspice computed. This is the one a parse test misses: a file can parse cleanly and still mean something different. RI read as MA, dB where we wrote linear, Hz where a reader assumes GHz — all parse, all silently wrong. That's the failure a user would hit in ADS or Qucs, weeks later, with our green suite behind it.


Why we didn't just write a parser. It would encode our own assumptions, so it would test this tree's idea of Touchstone against this tree's idea of Touchstone. That proves nothing. The whole value is that scikit-rf was written by people who never saw our code.


What it costs you. One install, pulling numpy. Measured on 2026-09-13: this machine has no skrf, no numpy, no octave, no qucs/qucsator — so there is no free path; it's install something or leave the half open.


One practical wrinkle I'd flag before you say yes: recent Ubuntu refuses pip install into the system Python. Cleanest is a throwaway virtualenv used only for this check, which touches nothing system-wide and can be deleted afterwards.


My recommendation: yes, and as a one-time check rather than a test dependency. The export is user-facing and its entire purpose is to be opened somewhere else, so it's the one artefact where our own opinion is worth least. But no suite should depend on scikit-rf, or the suite stops running on any machine without it — if a row does get written, it must skip cleanly when the library is absent.

Sunday, September 6, 2026

Getting Case Support with NGspice v50

Why your net is called v(vbg), and how to get v(VBG) back

You draw a net and label it VBG. You simulate. You plot it, and the waveform viewer calls it v(vbg). Every capital you typed is gone — START is start, EN_N is en_n, and a schematic that reads like a datasheet turns into a plot legend that reads like a shout in a library.

This is fixable, and the fix has two halves. One is a build of ngspice that can keep case. The other is one dialog in xschem's Analog Sim Environment (ASE-L), where you tell it about that build. Neither half works alone, which is why this tends to feel like it should already be working when it isn't.

Everything below was measured on Ubuntu under WSL2 against the tree as it stands today. The example design is tb_bandgap in the sky130_tests_ase library, and the starting point is the one people actually have: a saved state, ngspice_state1, that you open and re-run.

The short version

  1. Build the case-capable ngspice (about ten minutes, mostly compile time).
  2. In ASE-L: Setup → Simulators… → Add…, name it, point Program at the binary you just built.
  3. Press Detect. The Case chooser grows two new entries.
  4. Pick preserve, press OK, then set Use this one: to your new entry.
  5. Re-run. Plot. Capitals.

You do not have to edit the saved state, and you do not have to make a new one. The simulator list is global to your xschem install and the case setting rides on the entry, so a state you saved months ago picks all of this up the moment you open it.

1. Why it comes back lowercase

Released ngspice folds node names to lowercase. That is not a bug and it is not new — SPICE has been case-insensitive since the 1970s, and PDK model libraries depend on it. Your netlist goes out with the capitals intact; the results file comes back without them.

The part that costs people an afternoon is the way it fails. A stock ngspice accepts the request to keep case and then ignores it. No error, no warning, exit status zero. Here is the same deck, three ways:

* case demo
V1 START 0 DC 1.8
R1 START VBG 1k
R2 VBG 0 1k
.op
.control
run
write case.raw
.endc
.end
$ ngspice-case-capable -b case.cir          # default
    0    v(start)    voltage
    1    i(v1)       current
    2    v(vbg)      voltage

$ ngspice-case-capable -b -D casemode=preserve case.cir
    0    v(START)    voltage
    1    i(V1)       current
    2    v(VBG)      voltage

$ ngspice -b -D casemode=preserve case.cir   # stock ngspice-45.2
    0    v(start)    voltage
    1    i(v1)       current
    2    v(vbg)      voltage

Third block: asked for capitals, got none, and said nothing about it. That is why xschem defaults to fold and refuses to offer you anything better until it has actually measured your binary. It would rather ask for less than promise something your simulator will quietly drop.

2. Build an ngspice that can keep case

The case-mode work lives on the ver_50 branch of a public fork. You do not need to replace your system ngspice, and you should not: build it in your home directory, leave /usr/local alone, and point xschem at the result by full path. You can keep both and switch between them from the dialog in Part 3.

2.1 Packages

sudo apt install git build-essential automake autoconf libtool \
                 bison flex libx11-dev libxaw7-dev libreadline-dev pkg-config

Autotools (automake, autoconf, libtool) is the part people leave out. A git clone of ngspice has no configure script in it — you generate one — so without those three you get a confusing failure before compilation even starts.

2.2 Clone and build

git clone https://github.com/ananthchellappa/ngspice.git
cd ngspice
git checkout ver_50

./autogen.sh                       # generates ./configure — needs autotools

mkdir build-ver_50 && cd build-ver_50
../configure --prefix=$PWD/stage --with-readline=yes
make -j$(nproc)
make install                       # into ./stage — no sudo, nothing system-wide

Two notes on that --prefix. It is a private staging directory inside the build, so make install never touches anything outside the tree. And it is not optional: ngspice looks for its startup script (spinit, which loads the XSPICE code models) under the prefix it was configured with. Skip the install step and you get a binary that runs simple decks and then puzzles you later.

Your simulator is now:

~/ngspice/build-ver_50/src/ngspice

Write that path down. It is the one thing Part 3 needs.

2.3 Sixty-second self-test

Before going anywhere near xschem, ask the binary directly. Save this as cm.cir:

* casemode probe
.control
echo CCM=$curcasemode
quit
.endc
.end
$ ~/ngspice/build-ver_50/src/ngspice -b -D casemode=preserve cm.cir | grep CCM
CCM=preserve

That is a pass. A build without the feature prints CCM= — an empty answer, cheerfully, with a zero exit status. If you see the empty one, you are running the wrong binary; check the path before you change anything else.

2.4 If you have Claude Code

The fork carries a CLAUDE.md and an AGENTS.md at its root describing the build, the test layout and the house conventions. Clone it, run claude in that directory, and ask it to get the build going — it will read those, work out which packages your machine is missing, and drive autogen.sh / configure / make for you. That is genuinely the fastest route through a broken build environment, and it is why Part 2.1 exists at all: the manual list is for everyone else.

3. Tell xschem about it

Start xschem and open the design you care about. Two doors, use whichever fits:

  • Tools → Library Manager, then open the saved state view — sky130_tests_ase → tb_bandgap → ngspice_state1. This is the "I already have a state" route.
  • Tools → Launch ASE-L with the schematic open, for a fresh session.

Either way you get the ASE-L window. Now:

3.1 Setup → Simulators…

A list with three columns — Name, Program, Problem — and a Use this one: chooser under it. On a fresh install the list is empty, which means ASE-L falls back to whatever ngspice is on your PATH. That is the stock one. That is the lowercase one.

3.2 Add…

Four fields:

  • Name: — anything you like; ngspice-ver50 is a good habit because it will appear in the ASE-L status bar and you will want to recognise it at a glance.
  • Program: — the full path from Part 2.2, or press Browse… and go find it.
  • Case: — a dropdown. Right now it offers exactly two things: global default (fold) and fold.
  • -n: — a --no-spiceinit checkbox. Leave it alone for now; see the gotchas.

The Case dropdown is the step everybody gets stuck on, so it is worth saying plainly why it is nearly empty: xschem will only offer you case modes it has watched your binary deliver. It has not run your binary yet, so it offers the one mode no simulator can fail. It is not broken and it is not ignoring you.

3.3 Press Detect

This runs your binary a few times with a tiny throwaway deck — well under a second on a local build — and asks it, once per mode, what it actually does. Then the Case dropdown grows:

global default (fold)
fold
preserve
distinguish

and the status line under the fields tells you what was measured. If the extra entries do not appear, the binary in the Program field is not the one you built — go back to the self-test in 2.3.

Change the path and the offer follows it, immediately, as you type. Point the field at your old stock ngspice and preserve disappears again.

3.4 Pick preserve, then OK

preserve is the mode you want. VBG stays VBG everywhere you can see it, while identity still folds underneath — so VBG and vbg remain the same node, your PDK subcircuits still resolve, and nothing about the circuit changes. It is a display-and-naming change, not an electrical one.

distinguish is the strict mode: EN, en and En become three different nets. That is occasionally exactly what you want and it is a real trap otherwise, because a library written in the old assumption will silently come apart. Do not reach for it just to get capitals in your plot legend.

3.5 Use this one:

Back on the list, set Use this one: to the entry you just made. Close the dialog. The ASE-L status bar now reads:

| Status: idle | T=27 C | Simulator: ngspice-ver50 | State: ngspice_state1 |

If it reads Simulator: ngspice-ver50 — will not run, the name resolved but the program did not — usually a typo in the path, or a binary without the execute bit. The Problem column in the list spells out which.

Your list is written to ~/.xschem/ase_simulators and read back at startup. This is a one-time setup, not a per-session one.

4. Re-run and plot

Case mode is a property of a run, not of a file. A results file you already have was written lowercase and stays lowercase forever — nothing can retro-fit capitals onto it. So:

  1. Simulation → Netlist and Run.
  2. Results → Direct Plot (or Ctrl-4 on the schematic if you load cadence_style_rc), then click the wire or net label you want. ESC plots the queue.

Click the VBG net and you queue v(VBG), capitals and all. Under fold that same click queued v(vbg), because there was no point asking for a spelling the simulator was about to discard.

5. Did it actually work? Three checks

The status bar. Simulator: names your entry, with no "will not run" after it.

The results file. ASE-L writes it beside the netlist, under ~/.xschem/simulations/. Look at the variable table in the header:

$ head -c 4000 ~/.xschem/simulations/tb_bandgap_ase.raw | head -14
Variables:
        0   time     time
        1   v(CLK)   voltage
        2   i(E5)    current
        3   v(E5_int1) voltage
        4   v(EN_N)  voltage

Capitals in there mean the run really delivered preserve. All lowercase means it did not, whatever the dialog says, and the CIW will have printed a line saying so.

The plot legend. The point of the exercise.

6. Gotchas

A .spiceinit beats the flag

xschem asks for a mode with -D casemode=preserve on the command line. An ngspice init file — ~/.spiceinit, or one sitting beside the deck — overrides that, silently. If you have a set casemode=fold anywhere in one, it wins and your run folds.

That is what the -n (--no-spiceinit) checkbox in the row editor is for: tick it and ngspice reads no init file at all. Worth knowing about before you spend an hour on it; not worth ticking pre-emptively, since init files usually carry things you want.

Check the net's real name before blaming case

In tb_bandgap the enable net is labelled EN_N. There is no net called EN, in any case. Plotting v(EN) fails for the ordinary reason and it looks exactly like a case problem. The labels on that sheet are CLK, EN_N, START, TEMPERAT, VBG, VCC, VSS — worth a glance at the schematic before you go hunting.

Old runs stay old

Re-open a state and the plots come back the way they were saved. The capitals arrive on the next run, not on the next open.

The global floor

If you always want to ask for preserve, put this in ~/.xschem/xschemrc:

set sim_case_mode preserve

It is a floor, not an override: any registered simulator that names its own mode still wins. And on a stock ngspice it buys you nothing — the flag goes out, the simulator ignores it, and you get lowercase with a clear conscience. The registry entry is the reliable place to say it.

Appendix: doing it without the dialog

~/.xschem/ase_simulators is a plain file of Tcl calls, read once at startup, and you may edit it by hand:

# xschem ASE-L simulator list
ase::sim_register ngspice-ver50 /home/you/ngspice/build-ver_50/src/ngspice \
    -args {} -backend {} -casemode preserve -nospiceinit 0
ase::sim_select ngspice-ver50

Two lines: register, then select. Here is the whole chain before and after, measured headlessly:

== before registering ==
requested   : fold
netlister   : fold

== after registering with -casemode preserve ==
label       : ngspice-ver50
selectable  : fold preserve distinguish
requested   : preserve
netlister   : preserve
run flag    : -D casemode=preserve

One field, four consumers: the deck the netlister writes, the flag on the simulator's command line, the spelling Direct Plot asks for, and the label in the status bar. That is the whole mechanism. If your Case dropdown says preserve and your plot still says v(vbg), one of those four is being overridden — and the .spiceinit gotcha above is the overwhelmingly likely culprit.

Tuesday, September 1, 2026

What You Need In Your WSL to Hack Xschem

 



┌────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐

│                     group                      │                                                                   why                                                                    │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ build-essential pkg-config bison flex gawk     │ required by INSTALL; bison/flex regenerate expandlabel.c, eval_expr.c, parselabel.c                                                      │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ tcl-dev tk-dev                                 │ pulls 8.6.16 — inside the project's 8.4–8.6 window. Also gives you tclsh (runs the regression suites) and wish (the GUI gate panel)      │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ libx11-dev libxpm-dev                          │ required Xlib/Xpm                                                                                                                        │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ libcairo2-dev libxcb1-dev libx11-xcb-dev       │ the optional-but-standard rendering path (anti-aliased text)                                                                             │

│ libxrender-dev libxft-dev libfreetype-dev      │                                                                                                                                          │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ xvfb openbox x11-utils                         │ the persistent dev display. openbox is the one from issue 0645 whose absence silently made every WM measurement a bare-Xvfb measurement. │

│                                                │  x11-utils gives xdpyinfo/xprop/xwininfo/xlsclients, which devdisplay.sh and the window-mapping suites call directly                     │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ x11vnc                                         │ only for devdisplay.sh view — optional, but devdisplay.sh:341 dies with an install hint without it                                       │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ gdb valgrind                                   │ you asked; xschemtest.tcl -d 3 -l log also does allocation logging natively                                                              │

├────────────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤

│ ngspice verilator                              │ ~678 test references. Every use is auto_execok-guarded, so the ASE/cosim suites skip rather than fail without them — but skipping is     │

│                                                │ what silently hides a regression                                                                                                         │

└────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘


 sudo apt install -y \

  build-essential pkg-config bison flex gawk \

  tcl-dev tk-dev libx11-dev libxpm-dev \

  libcairo2-dev libxcb1-dev libx11-xcb-dev libxrender-dev libxft-dev libfreetype-dev \

  xvfb openbox x11-utils x11vnc \

  gdb valgrind \

  ngspice verilator

Sunday, August 30, 2026

Enh Req - Dear Holger Vogt - Add Support for save *:oppoint for ngspice

https://sourceforge.net/p/ngspice/feature-requests/106/

ngspice 47 Now Available

Ngspice-47, August 11th, 2026
============
- New features:
    + Update periodic state sim (PSS) and examples
    + Update to measure available memory for all OSs
    + Implement small signal noise simulation for code models
    + Status display 'shell' and 'gnuplot' (Windows only).
    + Enable printing outputs with engineering exponents
    + If newcompat.ki is enabled, replace /gnd and /0 (local ground symbols)
      by 0.
    + Add instance parameters td and r to the ISRC pwl source.
    + Do not replace GND by 0 f if GND is used inside of the subcircuit
      and is referenced on the .subckt line, and ps is set.
    + Add reading and writing audio files (*.wav).
    + Add dot commands .sndprint, .sndparam.
    + Vdmos bulk diode now has a soft recovery model
    + Update to the SEEgenerator as describes in README.SEEgenerator
    + No integration, if dc sweep is to return cpacitances
    + Add sweeping dc for capacitance measurement in 
      HFET, MEASFET, VDMOS models, correct it for BJT, VBIC, HICUM.
    + Add two macros TSTEP and TSTOP to XSPICE.
    + New behavioral capacitor model.
    + new capabilities to the adc/dac_bridge XSPICE code models:
      multi-bit ADC or DAC, Schmitt trigger
    + Paranoia_Parallel: a test suite for more than 100 test circuits
    + Adds a 'pyplot' command that renders simulated vectors with
      Python's matplotlib
    + Enable spice notations like 2n or 5m in filesource inputs

Getting a Useful VcXsrv Crash Dump

Winner of the first Nobel Prize in Physics ❯ tell me how to do the VcXsrv shortcut that I currently have in my Startup folder so that we get...