Showing posts with label donald knuth. Show all posts
Showing posts with label donald knuth. Show all posts

Sunday, November 1, 2026

Monte-Carlo with ngspice and Xschem

How our Monte Carlo drives ngspice Which ngspice we use, what it adds to stock ngspice, and how one process runs many samples
Date
2026-11-01
Simulator
ngspice-46+, built from our development fork (branch ver_51)
Context
The Monte Carlo engine behind ASE-Integrator, our open-source take on an ADE-Assembler-style test bench manager on top of xschem
Short answer
Several long-lived ngspice processes in parallel, each looping over a list of seeds it is handed. ngspice never knows it is doing an N-sample Monte Carlo.

Which ngspice

We run an ngspice-46+ build from our own fork, branch ver_51. It reports itself as ngspice-46+. The distribution's ngspice 45.2 can simulate the same decks, but our Monte Carlo refuses to use it. That refusal is on purpose; the next section explains why.

What the fork adds to stock ngspice

  1. A draw log (set rnddraws=<file>). This is the essential one. It records every random number drawn while the netlist is read: which parameter, which device, and what value. That lets us see each sample's per-device mismatch rather than only its outputs. Stock 45.2 has nothing like it. Our Monte Carlo refuses 45.2 with a clear message (mc_ngspice_min: "Monte Carlo needs an ngspice that writes the draw log") rather than run blind.
  2. Seeding fixes:
    • The startup random stream is seeded from rndseed, not from the process id.
    • The draw log is closed properly when the circuit is reset.
    • A warning is printed once when .option seed= silently overrides setseed.
  3. Resistor fixes: the resistor model survives ngspice's internal conversion of a resistor to a B-source. Without this, sky130's high-value resistor loses its temperature coefficient.
  4. Many smaller fixes: case handling of node names, .save name lookup, the exit status of a batch run, an .op card with no netlist, and others. Several have been offered upstream.

One process per sample? No.

We do not launch a new ngspice per sample. One ngspice process, which we call a lane, handles a whole range of samples. Inside its .control block it loops over the seeds it has been given. For each sample:

set rnddraws=<sample dir>/draws   * where this sample's draw log goes
setseed <seed>                     * this sample's own, literal seed
reset                              * re-read the netlist: mismatch is drawn fresh
set temp=<T>
op                                 * write this sample's raw file and measures
echo ASEMC_DONE s=<seed> ...       * tell the supervisor this sample is finished
unset rnddraws
destroy all                        * drop this sample's results from memory

The order matters, and each step is there because a measurement showed it was needed:

  • setseed has to come before reset, because the mismatch values are drawn while the netlist is read.
  • destroy all keeps memory flat over hundreds of samples.
  • The ASEMC_DONE line is how the outside world learns that a sample has finished.

Several lanes in parallel

A small Python worker sits between the GUI and ngspice:

  • It splits the N samples into contiguous ranges across L lanes. L is the smallest of the setup's job limit, the number of CPUs and N.
  • Lane 1 also runs the nominal sample (sample 0), with mismatch switched off.
  • For example, 200 samples on a 20-core machine can be 20 ngspice processes of about 10 samples each, all running at once.

The worker supervises the lanes:

  • It reads each lane's log as it is written, and it records a sample (raw file, measures and draw log) the moment that sample's ASEMC_DONE line appears.
  • A sample that errors is marked as a simulation failure, and the lane carries on.
  • A lane that stops making progress is killed. Its stalled sample is marked as timed out, and a fresh lane restarts from the next sample.
  • The Stop button kills every lane. Unfinished samples are left pending, not half-written.

Does ngspice know it is doing Monte Carlo?

No. ngspice has no "run N Monte Carlo samples" command, and we don't need one. Each lane receives a deck whose seeds are written out as a literal list. There is no arithmetic and no counter inside ngspice. It runs the loop it has been handed, without knowing that it is a Monte Carlo or how big the whole run is.

Everything Monte Carlo-specific lives in the worker:

  • N, and the seed for each sample.
  • The split into lanes, and which sample is which.
  • The nominal run.
  • Retries, stop and progress.
  • The results database the GUI reads (yield, histograms, re-evaluation).

Why it is built this way

  • Speed: the netlist is redrawn inside one long-lived process, so there is no start-up cost per sample.
  • Reproducibility: every seed is explicit, and every draw is logged. Any single sample can be re-run on its own and give exactly the same numbers.
  • Robustness: one bad sample costs one sample, not the run. A stalled lane costs one sample, then the work continues on a fresh process.
  • Simplicity: ngspice does what it is good at, simulating one circuit. The bookkeeping lives in ordinary code that can be tested.

Wednesday, October 1, 2025

ALIGN - Automated Layout - What it May Have Cost

University of Minnesota audited federal-expenditure report that lists:

- Contract: N660011824048 P00005

- Federal expenditures: $1,307,362

- Subrecipient expenditures: $743,968

NSF award CCF-2212345 : $900k/14 going by https://www.nsf.gov/awardsearch/show-award/?AWD_ID=2212345

2212346 : $300k/6 per https://www.nsf.gov/awardsearch/show-award?AWD_ID=2212346

So, let's make the most of it :)



Saturday, July 26, 2025

Stefan++ : How? Reduce Cyclomatic Complexity

What does "high cyclomatic complexity" mean?

It means your code has turned into a labyrinth, and anyone trying to maintain it will likely curse your name.

Cyclomatic complexity is a metric that counts the number of independent paths through your code. Think of it as a "how many ways can I break my brain" counter. The higher the number, the more branches, loops, and conditionals are cluttering up your code.

  • Low cyclomatic complexity (1–10): Code is simple, readable, and probably written by someone who still has hope.
  • High cyclomatic complexity (20+): Code is a minefield of if statements, while loops, and spaghetti logic.

In short, “high cyclomatic complexity” means your code is doing too much in one place and needs to be refactored into smaller, cleaner chunks.

Checklist: How to Reduce Cyclomatic Complexity

✅ 1. Split Large Functions

Break big functions into smaller, focused ones.

def process_order(order):
    if order.type == 'online':
        ...
    elif order.type == 'in-store':
        ...

# Better:
def process_order(order):
    if order.type == 'online':
        handle_online(order)
    elif order.type == 'in-store':
        handle_instore(order)

✅ 2. Replace Complex Conditionals with Polymorphism

# Bad:
if shape == 'circle':
    ...
elif shape == 'square':
    ...

# Better:
class Shape:
    def area(self): pass

class Circle(Shape):
    def area(self): return pi * r * r

✅ 3. Use Guard Clauses

# Instead of:
def process(user):
    if user.is_active:
        if user.has_permission:
            ...

# Do:
def process(user):
    if not user.is_active or not user.has_permission:
        return
    ...

✅ 4. Use Lookups Instead of Conditionals

# Instead of:
if key == 'a': do_a()
elif key == 'b': do_b()

# Do:
actions = {'a': do_a, 'b': do_b}
actions.get(key, do_default)()

✅ 5. Extract Logic from Loops

# Instead of:
for item in items:
    if item.is_valid() and not item.is_expired():
        if item.value > threshold:
            ...

# Do:
for item in items:
    handle_item(item)

✅ 6. Minimize Boolean Logic

# Instead of:
if not (x or (y and not z)):

# Do:
should_skip = x or (y and not z)
if not should_skip:
Code copied!