Showing posts with label tcl. Show all posts
Showing posts with label tcl. Show all posts

Tuesday, October 27, 2026

Klayout Developer FAQ

Notes from building KLayout 0.30.12 from source on Ubuntu 26.04 (WSL2) with Qt 6, on the way to an open-source schematic-driven layout flow with Xschem. Every answer below was checked against the source tree or a real build in October 2026. Where I compare with Cadence Virtuoso, the point is how the tool feels to use, not what it can or can't do.

Building and the repo

1What do I need to install to build KLayout?

On a recent Ubuntu with Qt 6, you need a compiler, Qt 6 development packages, and Ruby and Python headers. Ruby matters because KLayout's DRC and LVS engines are written in Ruby, so they're only built when Ruby is present.

sudo apt install build-essential git ccache python3-dev ruby-dev zlib1g-dev \
  qt6-base-dev qt6-tools-dev qt6-5compat-dev qt6-svg-dev qt6-multimedia-dev \
  libgit2-dev libcurl4-openssl-dev

qt6-5compat-dev is the one that's easy to miss. The Qt 6 build needs it whenever the Qt bindings for scripts are enabled, which is the default. libgit2-dev and libcurl4-openssl-dev are optional. Ubuntu's Qt 6 has no plain qmake, so name it explicitly:

./build.sh -qmake qmake6 -rpath $HOME/dev/klayout/bin-release -j8
Tip: watch your RAM. The generated Qt bindings are memory-hungry to compile, so on a 16 GB machine I used -j8 rather than all 20 cores. Prefix the command with QMAKE_CCACHE=1 for faster rebuilds.

2How big is the code base?

About 3.2 million lines of C++. Roughly 2.2 million of those are auto-generated Qt bindings (src/gsiqt), which is why that part of the build seems to take forever. The hand-written code is about 1 million lines:

ModuleWhat it isLines
dbLayout database, geometry engine, netlist extraction and LVS core~255k
laybasicView and rendering core~196k
pluginsFile formats (GDS2, OASIS, LEF/DEF, DXF, …) and tools~144k
unit testsC++ tests~128k
drc/lvsThe DRC/LVS language itself (Ruby)~18k

Most of the code base is organised around one idea, which KLayout calls GSI. Each C++ class is declared once in a gsiDecl*.cc file, and that one declaration becomes the Ruby API, the Python API and the API documentation. To find out what a script can do, grep for gsi::method ("name".

3Should I run Doxygen on it?

Probably not, at least not at first. The repo has no Doxyfile. For anything scripted (PCells, macros, tool integration) the API you program against is the GSI script API, and KLayout already documents it in its built-in help (Help → Class Index). The same docs are on klayout.de. If you go deep into the C++ later, run Doxygen only on src/{tl,gsi,db,laybasic,layui,lay,edt} and exclude src/gsiqt, which would otherwise be two thirds of the input.

4"error while loading shared libraries: libklayout_tl.so.0". What now?

Two things cause this:

  1. You ran the wrong binary. build-release/klayout is an intermediate copy. The installed app is bin-release/klayout.
  2. The binaries carry no RPATH. Unless you pass -rpath, build.sh leaves RPATH empty, so you have to run LD_LIBRARY_PATH=$PWD ./klayout from bin-release.
Gotcha: if you add -rpath to an existing build, make doesn't relink files that are already up to date just because the linker flags changed. You end up with an executable that has the path and libraries that don't. Delete the linked outputs in the build directory (*.so*, *.ut and the executables), then run make -j8 && make install. The object files are reused, so it's only a relink.

The unit tests live in the build directory, not the bin directory (the README is out of date on this):

cd build-release
TESTTMP=testtmp TESTSRC=.. LD_LIBRARY_PATH=. ./ut_runner dbBoxTests

5Why is my checkout 2 GB after building?

PartSizeNotes
build-release/1.2 GBAbout 750 MB of object files. The generated Qt bindings alone are 470 MB.
.git356 MBFull history
bin-release/209 MBThe actual install
src / testdata157 / 79 MB

You can delete the build directory once things are installed, but you lose incremental rebuilds. Building with -without-qtbinding saves about half a gigabyte and a lot of compile time. The cost is that scripts lose access to Qt classes such as QTcpServer, which I need for tool-to-tool communication.

Setup and customisation

6How do I get a black background like Virtuoso, and only set it once?

In the GUI, go to File → Setup → Display → Background. KLayout saves all settings to ~/.klayout/klayoutrc when it exits, so this is a one-time step.

If you'd rather keep settings in a version-controlled init file, as you would with .cdsinit or xschemrc, use a startup macro. Any .pym file in ~/.klayout/pymacros/ runs automatically at startup:

# ~/.klayout/pymacros/my_init.pym
import pya
mw = pya.MainWindow.instance()
mw.set_config("background-color", "#000000")

7Can I keep custom keyboard shortcuts in an init file?

Yes. In the GUI, use File → Setup → Application → Customize Menu, which saves to klayoutrc. For an init file, the script API has MainWindow.set_key_bindings, get_key_bindings and get_default_key_bindings. Bindings are keyed by menu path, and any menu entry can be bound, including your own macros:

mw.set_key_bindings({
    "zoom_menu.zoom_fit": "F",      # default is F2
    "edit_menu.undo":     "U",      # default is Ctrl+Z
})

Print get_default_key_bindings() once to see every menu path. With that, a Virtuoso-style keymap can live in a single file under version control.

8Magic has R and C parasitic extraction. Does KLayout?

  • Built in: since 0.30.2 KLayout has a pex module for resistance extraction only. It provides pex.RExtractor with square-counting and triangulation methods, plus RNetExtractor and RNetwork.
  • Add-on: KLayout-PEX (kpex) from IIC-JKU does R and C extraction on top of KLayout, with FasterCap, FastCap2 or Magic as optional backends. I haven't yet compared it with Magic on sky130.

Analog flow and sky130

9Is there an existing Xschem ↔ KLayout cross-probe?

I couldn't find one. The closest things are klink/klive, a KLayout plugin that opens a TCP server so other tools can push layouts into a running KLayout, and example projects such as mole99/klayout-sky130-inverter that use the two tools side by side through a Makefile-driven LVS flow.

Both tools have the pieces needed to build one:

  • Xschem has a Tcl TCP server and select/highlight commands that take hierarchical paths.
  • KLayout has a scriptable netlist browser, an LVS cross-reference that maps schematic objects to layout objects, selection events, and Qt networking for scripts.
Two gotchas: KLayout's embedded Python never releases the interpreter lock, so use Qt signals or timers, not Python threads or asyncio. And Xschem's TCP server evaluates any Tcl it receives, so bind it to localhost only.

10What does it take to do sky130 layout in KLayout if I already use sky130 in Xschem?

An Xschem-only setup usually has symbols and SPICE models but nothing for layout. With ciel, open_pdks ships one tarball per library, and you need two: common (6.6 MB: KLayout tech and layer files, DRC and LVS decks, the PCell library) and sky130_fd_pr (14.2 MB: device GDS, SPICE, LEF). That's about 105 MB on disk. Magic and netgen aren't required, because KLayout runs DRC and LVS itself.

The stock Xschem sky130 symbols already write LVS netlist lines such as sky130_fd_pr__nfet_01v8 L= W= nf= m=, which is the naming the KLayout LVS deck expects.

The catch: the PCells need patching. An nfet at any W/L/nf comes from a gdsfactory-based PCell library called skywater130. With current gdsfactory 9 / kfactory 3 every PCell quietly produces an empty cell, which is why so many people report it "doesn't work". The JKU IIC-OSIC-TOOLS install script carries the fixes. Install the PDK at their pinned open_pdks commit (1689ac3f) and keep gdsfactory 9.51.0 / kfactory 3.0.4 in a venv.

What I verified on my own 0.30.12 build:

  • PCells: nfet, pfet, poly resistor, MIM cap, vias and guard rings all generate.
  • DRC: sky130A_mr.drc with -rd feol=true -rd beol=true -rd offgrid=true runs 256 rule categories with 0 violations. The default .lydrc has front-end checks off, so a clean result from it means little.
  • LVS: an Xschem-style netlist matches with -rd convert_subckts=true -rd scale=true.
Things that bit me: KLayout's Python ignores PYTHONPATH; point it at the venv with KLAYOUT_PYTHONPATH. The PCell's w is per finger while Xschem's W is total, so w = W/nf. Pass gate_con_pos and bulk explicitly. Multi-finger PCells don't strap their fingers, so an nf=4 device extracts as four devices until you route it.

UI/UX compared with Cadence Virtuoso

Short version: KLayout's viewing and script API are strong. What it lacks are the things that make Virtuoso feel like an environment rather than a viewer.

VirtuosoKLayout 0.30Verdict
CIW with command log (CDS.log)Script console and a log viewer; GUI actions aren't logged as commandsMissing
Library Manager (lib/cell/view)Libraries panel: list and drag; one file = one libraryMinimal
Many windows, any monitorOne main window with tabs; side panels can floatMissing
SKILLPython and Ruby, full API, macro IDEStrong
f = zoom fit, bindkeys in .cdsinitF2; rebind anything from an init macroFine

11Does KLayout have a Command Interpreter Window that logs commands?

No. There are two partial equivalents:

  • Macro Development → Console: an interactive Python or Ruby prompt, the equivalent of typing SKILL into the CIW.
  • File → Log Viewer: info, warning and error messages. Starting with -d <level> makes it chattier.

What's missing is the part of the CIW that makes SKILL learnable: GUI actions are never echoed as replayable commands. There's no CDS.log-style journal and no macro recorder. A CIW-style dock that logs each menu action as its script call could be built as a plugin on the existing API, but it doesn't exist today.

12Is there a Library Manager?

A minimal one. The Libraries panel lists registered libraries with their cells and PCells, and you drag from it into a layout. The Cells panel shows the hierarchy within the open file. There's no library → cell → view browser, no cds.lib, no categories, and no copy, rename, delete or check-in.

The underlying difference is the data model. In Virtuoso a library is a directory of cells, each with views. In KLayout a library is a file, or a set of PCells registered by a script. A lib/cell/view layer has to be added on top, which is what my project plans to do.

13Can I look at two layouts in separate windows on two monitors?

Not from one process. KLayout allows a single main window (it's enforced in layMainWindow.cc). Extra layouts open as tabs that can't be torn off. The side panels (layers, cells, libraries, navigator) are dock widgets and can be floated onto another monitor.

The practical answer is two KLayout processes, one per monitor.

Gotcha: each process writes ~/.klayout/klayoutrc when it exits, so the last one closed wins. Start the second one with -t so it doesn't save its settings:
klayout top.gds &
klayout -t other.gds &

Within one window you can also overlay two layouts in the same tab ("add to current panel" when opening), compare them with the XOR and Diff tools, or turn on Display → Synchronized Views so switching tabs keeps the same zoom area.

14What is the command language? How good is scripting support?

Python and Ruby, both built in, and the scripting is excellent. There's no single native language like SKILL. Instead both languages get the same complete API, generated from the C++ declarations: the layout database, views, menus, the netlist and LVS engine, and even Qt widgets for building your own dialogs. It's documented in Help → Class Index.

  • Macro Development IDE: an editor, debugger and console.
  • Init files: .pym and .rbm files in ~/.klayout/pymacros and ~/.klayout/macros run at startup, the equivalent of .cdsinit.
  • Batch mode: klayout -b -r script.py.
  • DRC and LVS are rule languages (Ruby DSLs) on the same engine.
  • Standalone module: pip install klayout gives you the database without the GUI.

The gap compared with SKILL isn't power, it's discoverability. Without a command log you learn the API from the docs rather than by watching what the GUI does.

15What is the keyboard shortcut for zoom fit? (Virtuoso: f)

F2. Shift+F2 fits the selection, and Ctrl++ / Ctrl+- zoom in and out. To get Virtuoso's f, put this in your init macro:

pya.MainWindow.instance().set_key_bindings({"zoom_menu.zoom_fit": "F"})

Sunday, August 30, 2026

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

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!