Showing posts with label c programming. Show all posts
Showing posts with label c programming. Show all posts

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.

Saturday, July 26, 2025

handle_key_press - the "Monster Function"

> How do you recommend going after the monster function handle_key_press?

● Excellent question! The handle_key_press() function with 1,524 lines is a prime example of what needs systematic refactoring.

  Let me analyze it and provide a concrete attack strategy.

● Update Todos

  ⎿  ☐ Analyze handle_key_press function structure

     ☐ Identify key functional groups and responsibilities

     ☐ Design refactoring strategy with safe incremental steps

     ☐ Test and validate refactored implementation

     ☐ Create helper function extraction plan

     ☐ Implement command dispatch table approach

● Strategic Attack Plan for handle_key_press() Monster Function

  Based on my analysis, here's my recommended safe, incremental refactoring strategy:

  🎯 Phase 1: Extract Helper Functions (Low Risk)

  Start with the most duplicated code to get immediate wins:

  1.1 Extract Layer Selection Logic

  static void handle_layer_selection(int layer_num) {
      char n[30];
      xctx->rectcolor = layer_num;
      my_snprintf(n, S(n), "%d", xctx->rectcolor);
      tclvareval("xschem set rectcolor ", n, NULL);
      /* ... reconfigure_layers_button logic ... */
  }
  Impact: Eliminates ~200 lines of duplication across numeric keys.

  1.2 Extract Common Patterns

  static int should_handle_key(int event, KeySym key, int state, int button) {
      if(xctx->semaphore >= 2) return 0;
      if(waves_selected(event, key, state, button)) {
          waves_callback(event, mx, my, key, button, aux, state);
          return 0;
      }
      return 1;
  }

  static void start_move_operation(int infix_interface) {
      if(infix_interface) {
          xctx->mx_double_save = xctx->mousex_snap;
          xctx->my_double_save = xctx->mousey_snap;
          move_objects(START,0,0,0);
      } else {
          xctx->ui_state |= MENUSTART;
          xctx->ui_state2 = MENUSTARTMOVE;
      }
  }

  🎯 Phase 2: Key Group Extraction (Medium Risk)

  Extract logical groups one at a time, testing thoroughly:

  2.1 Start with Numeric Keys (Safest)

  static void handle_numeric_keys(KeySym key, int state, int rstate) {
      if(rstate == 0) {
          /* Logic level setting */
          if(key >= '0' && key <= '9') {
              handle_layer_selection((int)key - '0');
              return;
          }
      }
      else if(rstate == ControlMask) {
          /* Layer selection with Ctrl */
          // ... existing logic
      }
  }

  2.2 Extract File Operations

  static void handle_file_keys(KeySym key, int state, int rstate,
                              int infix_interface, const char *win_path) {
      switch(key) {
          case 's': handle_save_operation(state); break;
          case 'S': handle_save_as_operation(); break;
          case 'o': handle_open_operation(); break;
          // ... etc
      }
  }

  🎯 Phase 3: Command Dispatch Table (Higher Risk)

  Replace the massive switch with a cleaner dispatch system:

  3.1 Define Key Handler Structure

  typedef struct {
      KeySym key;
      int modifier_mask;
      void (*handler)(KeyHandlerContext *ctx);
      const char *description;
  } KeyHandler;

  typedef struct {
      int event, state, rstate, mx, my, button, aux;
      int infix_interface, enable_stretch, cadence_compat;
      int wire_draw_active, snap_cursor;
      const char *win_path;
      double c_snap;
      KeySym key;
  } KeyHandlerContext;

  3.2 Create Handler Table

  static const KeyHandler key_handlers[] = {
      {'w', 0, handle_place_wire, "Place wire"},
      {'W', 0, handle_place_snapped_wire, "Place snapped wire"},
      {'c', 0, handle_copy, "Copy selection"},
      {'m', 0, handle_move, "Move selection"},
      // ... hundreds of entries
      {0, 0, NULL, NULL} // terminator
  };

  static void handle_key_press_new(/* same params */) {
      KeyHandlerContext ctx = {/* initialize from params */};

      if(!should_handle_key(event, key, state, button)) return;

      for(const KeyHandler *h = key_handlers; h->handler; h++) {
          if(h->key == key && (state & h->modifier_mask) == h->modifier_mask) {
              h->handler(&ctx);
              return;
          }
      }

      // Handle unmapped keys
      handle_unmapped_key(&ctx);
  }

  🎯 Recommended Step-by-Step Attack Plan

  Week 1-2: Quick Wins (Helper Functions)

  1. ✅ Extract handle_layer_selection()
  2. ✅ Extract should_handle_key()
  3. ✅ Extract start_move_operation(), start_copy_operation()
  4. ✅ Extract rotation/flip helpers
  5. ✅ Run full regression tests

  Expected Impact: ~400 lines reduced, 0% risk of breaking functionality

  Week 3-4: First Group Extraction

  1. ✅ Extract handle_numeric_keys() (safest group)
  2. ✅ Extract handle_system_keys() (Delete, Escape, Return, etc.)
  3. ✅ Thorough testing with focus on these key groups
  4. ✅ Update any affected documentation

  Expected Impact: ~300 lines reduced, <5% risk

  Week 5-6: Core Groups

  1. ✅ Extract handle_file_keys() (save, load, etc.)
  2. ✅ Extract handle_navigation_keys() (zoom, pan)
  3. ✅ Extract handle_drawing_keys() (wire, line, arc)
  4. ✅ Intensive testing of drawing operations

  Expected Impact: ~600 lines reduced, 10% risk

  Week 7-8: Complex Groups

  1. ✅ Extract handle_selection_keys() (copy, move, select)
  2. ✅ Extract handle_transformation_keys() (rotate, flip)
  3. ✅ Extract handle_net_keys() (highlighting, tracing)
  4. ✅ Performance testing (these are hot paths)

  Expected Impact: ~400 lines reduced, 15% risk

  Week 9-10: Cleanup and Optimization

  1. ✅ Consider dispatch table approach for remaining keys
  2. ✅ Extract handle_special_keys() for symbols
  3. ✅ Final integration testing
  4. ✅ Performance benchmarks vs. original

  Final Result: 1,524 lines → ~200 lines main function + ~1,300 lines in focused modules

  🛡️ Risk Mitigation Strategies

  Safety Measures

  1. Git branching: Each phase gets its own branch
  2. Regression testing: Full test suite after each extraction
  3. Performance testing: Ensure no keystroke latency increase
  4. User testing: Have power users test drawing operations
  5. Rollback plan: Keep original function as handle_key_press_legacy() initially

  Testing Strategy

  1. Unit tests: Each extracted function gets unit tests
  2. Integration tests: Full drawing workflows
  3. Performance tests: Keystroke latency measurements
  4. Edge case tests: Modifier combinations, rapid key sequences
  5. Memory tests: Check for leaks in new function boundaries

  🎉 Benefits of This Approach

  Immediate Benefits (Phase 1)

  - ✅ Eliminates massive code duplication
  - ✅ Makes individual key handlers readable
  - ✅ Zero functional risk

  Medium-term Benefits (Phase 2)

  - ✅ Function becomes navigable and maintainable
  - ✅ New key handlers become trivial to add
  - ✅ Unit testing becomes possible

  Long-term Benefits (Phase 3)

  - ✅ Self-documenting key binding system
  - ✅ Runtime key remapping becomes possible
  - ✅ Help system can auto-generate from handler table
  - ✅ Plugin system for custom key handlers

  This phased approach gives you immediate wins while building toward a professional-grade architecture with minimal risk to the
  critical user interaction code.

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!