layouttk 0.5.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation

layouttk is a fast, headless GDSII and OASIS toolkit powered by a single Rust core. Use it as a zero-dependency Python library, a Rust crate, or a standalone single-binary CLI designed for CI pipelines, air-gapped EDA servers, and AI coding agents.

SiEPIC openEBL MZI rendered directly to PNG NumPy image array converted to OASIS (viewed in KLayout)
Public layout examples · Visual Python workflows NumPy-to-OASIS Mona Lisa walkthrough

Why layouttk?

  • Exact integer DBU grid — Keeps coordinates in i64 database units with strict format preflight (check --json) and atomic writes, preventing silent rounding or half-grid drift.
  • Large-file streaming & hierarchical clipping — Filter layers while decoding (extract), scan cells/layers without materializing shapes (inventory), and clip multi-window ROIs directly from disk (clip / clip --keep-hierarchy) with recursive pruning of massive compact arrays.
  • Python science & mask workflows — Clipper2 Region Booleans, LayerSet filters, mask shapes & wafer templates, packed PolygonBatch exchange with NumPy/PyTorch/DLPack, and 2D binary mask / PNG conversion (raster).
  • Built for automation & coding agents — Standalone CLI with --format json, ordered JSONL batch, offline describe --json, built-in bilingual guide, and a bundled Agent Skill. Runs headless on Linux (including static musl baseline), macOS, and Windows.

Quick start

Python

Install the wheel with CPython 3.11+ (core GDSII/OASIS I/O and geometry need no third-party packages):

python -m pip install layouttk

Save as first_mask.py and run python first_mask.py. It builds a hierarchical layout on a 1 nm grid, writes both pad.gds and pad.oas, and verifies the placed geometry on layer 7/0:

from layouttk import Layer, Layout, Region

layout = Layout("MASK", dbu_nm=1)
metal = Layer(7, 0)
pad = layout.add_cell("PAD")
pad.add_region(Region.box((0, 0), (1000, 500)), layer=metal)
layout.add_cell("TOP").add_reference(pad, (2000, 3000))

for filename in ("pad.gds", "pad.oas"):
    layout.write(filename)
    restored = Layout.read(filename)
    expected = Region.box((2000, 3000), (3000, 3500))
    assert not (restored.cell("TOP").region(metal) ^ expected)

Command line

With layouttk on your PATH (download standalone binary), run these commands in the same folder:

layouttk inventory pad.oas
layouttk extract pad.oas metal.oas --top TOP --layer 7/0
layouttk check metal.oas --to gds --json
layouttk convert metal.oas metal.gds
layouttk verify pad.gds metal.gds
layouttk clip pad.oas roi.oas --top TOP --layer 7/0 --window 2100,3100,2600,3400

Getting started guide · Migrate from gdspy, gdstk, or KLayout


Common tasks at a glance

What you want to do CLI Python
Inspect cells, layers, units & array counts layouttk inventory file.oas Layout.read(path) / cell.layers()
Extract layers & keep cell hierarchy layouttk extract in.oas out.gds --top TOP --layer 7/0 Layout.read(path, top="TOP", layers=Layer(7, 0) + Layer(8, 0))
Preflight GDSII/OASIS conversion losses layouttk check in.oas --to gds --json layout.diagnostics("gds")
Compare two deliveries (records + mask XOR) layouttk verify a.gds b.oas analysis.compare_layouts(a, b)
Clip windows from huge files (flat or hierarchical) layouttk clip in.oas roi.oas --top TOP --window ... [--keep-hierarchy] Layout.clip_file(path, "TOP", windows, keep_hierarchy=True)
Boolean operations & region sizing layouttk boolean a.oas b.oas out.gds --op difference ... Region operators (+, |, &, -, ^, .sized())
Build mask geometry, marks & wafer grids layouttk create spec.json out.oas / layouttk edit shapes, templates, Polygon, FlexPath, RobustPath
Exchange coordinates with NumPy / PyTorch layouttk query polygons ... --placed PolygonBatch.from_layout() / from_region() / to_torch()
Convert 2D binary masks & render PNG / SVG / HTML layouttk raster png / layouttk view html raster.add_mask(), raster.to_mask(), write_png(), write_viewer()
Run scripted or agent batch jobs layouttk --format json ... / layouttk batch job.jsonl Native Python API + bundled Agent Skill

Installation

Target Command
Python 3.11+ (core, zero deps) python -m pip install layouttk
Python + NumPy python -m pip install "layouttk[numpy]"
Python + PyTorch python -m pip install "layouttk[torch]"
Python + PNG images (NumPy + Pillow) python -m pip install "layouttk[image]"
Standalone CLI (macOS arm64 / Linux x86_64) brew tap zwh42/layouttk https://github.com/zwh42/layouttk && brew install zwh42/layouttk/layouttk
Standalone CLI archive (no Python/Rust needed) Download latest release (Linux musl, macOS arm64, Windows x64)
Rust library / CLI (Rust 1.95+) cargo add layouttk / cargo install layouttk --locked
  • Offline Python wheels: Download the wheel for Linux x86_64, macOS arm64, or Windows x64 from GitHub Releases and install with python -m pip install --no-index --no-deps PATH_TO_WHEEL.whl.
  • Air-gapped Linux baseline: The x86_64-unknown-linux-musl.tar.gz archive is statically linked without AVX/AVX2 requirements and is verified on Linux 3.2. Every CLI archive bundles English/Chinese guides (layouttk guide --lang en), an offline command schema (layouttk describe --json query bounds), and the Agent Skill.
  • Build from source (Rust 1.95+, GIL-enabled CPython 3.11+):
    cargo install --locked --path .
    python -m pip install .
    

Workflow highlights

1. Hierarchical mask construction & Booleans in Python

Compose layer filters with LayerSet (+, |, &, -, ^), run Clipper2 Region Booleans, attach typed GDSII/OASIS properties, or assemble alignment marks, die arrays, and wafer grids with shapes and templates.

from layouttk import Layer, Layout, Property, Region

chip = Layout("MASK", dbu_nm=1)
metal = Layer(67, 20)
leaf = chip.add_cell("CONTACT")
opening = Region.box((0, 0), (100, 100)) - Region.box((20, 20), (80, 80))
leaf.add_region(opening, layer=metal)
leaf.set_properties([Property.gds(7, b"contact")], element=0)

top = chip.add_cell("TOP")
top.add_reference(leaf, (300, -100))
chip.set_repetition("TOP", 0, [(50, 30), (-40, 10)])
chip.write("chip.oas")

restored = Layout.read("chip.oas", layers=metal + Layer(68, 20), top="TOP")
assert restored.cell("TOP").layers() == (metal,)

Python API reference · Mask construction with shapes & templates · Polygon drafting & rounding

2. NumPy, PyTorch & DLPack polygon exchange

Exchange packed int64 contours (vertices of shape (N, 2) and indptr) with zero-copy CPU sharing (copy=False) or explicit GPU transfers (to_torch(device="cuda", copy=True) / "mps"):

import numpy as np
from layouttk import Layout, PolygonBatch

xy = np.array([[0, 0], [20, 0], [0, 20]], dtype=np.int64)
indptr = np.array([0, 3], dtype=np.int64)
batch = PolygonBatch.from_numpy(xy, indptr, copy=False)

mask = Layout()
mask.add_cell("TOP")
batch.add_to(mask, "TOP", (1, 0))

snapshot = PolygonBatch.from_layout(mask, "TOP", (1, 0))
vertices, boundaries = snapshot.to_numpy(copy=False)
assert vertices.shape == (3, 2) and boundaries.tolist() == [0, 3]

3. From a NumPy array to OASIS

Install python -m pip install "layouttk[image]", download mona-lisa.jpg, and convert any 2D NumPy mask directly to OASIS (0 = background, nonzero = fill, 10 nm pixel pitch):

import numpy as np
from PIL import Image
from layouttk import Layer, Layout, raster

with Image.open("mona-lisa.jpg") as image:
    mask = np.asarray(image.convert("L")) >= 128

layout = Layout("MONA_LISA", dbu_nm=1)
layout.add_cell("TOP")
raster.add_mask(layout, "TOP", Layer(67, 20), mask, pixel_size=10)
layout.write("mona-lisa.oas")

Full round-trip script & OASIS output · Binary image tutorial · Source image: public-domain C2RMF scan on Wikimedia Commons.

4. Public layouts & AI coding agents

Try verified offline exercises with ASAP7 and SiEPIC openEBL MZI layouts, or invoke the bundled skill directly from your coding agent:

# Generate an ASAP7 inverter array in OASIS
mkdir -p work
gzip -dc tests/fixtures/public_layouts/asap7-stdcell.gds.gz > work/asap7.gds
python examples/public_layouts/asap7_row.py work/asap7.gds work/asap7-row.oas
layouttk inventory work/asap7-row.oas

# Run with Pi or OpenCode using the bundled Agent Skill
pi --skill .agents/skills/layouttk/SKILL.md -p '/skill:layouttk Use layouttk to render tests/fixtures/public_layouts/openebl-mzi.oas, cell EBeam_LukasChrostowski_MZI, layer 1/0, to work/mzi.png. Use window 0,0,605000,410000 DBU and 500 DBU per pixel. Create work if needed and confirm the PNG dimensions.'
opencode run 'Load the layouttk skill. Use examples/public_layouts/pattern_boxes.py to add one bounding rectangle per placed shape on layer 1/0 of EBeam_LukasChrostowski_MZI in tests/fixtures/public_layouts/openebl-mzi.oas. Create work if needed. Write layer 900/0 in work/mzi-boxes.oas, read back the rectangles, and verify the source layer.'

Offline agent examples · Download offline example bundle · CLI automation & JSONL batch guide

5. Rust library

use std::collections::BTreeSet;
use layouttk::{Format, Layer};

fn extract() -> layouttk::Result<()> {
    let layers = BTreeSet::from([Layer { number: 67, datatype: 20 }]);
    let mut chip = layouttk::read("chip.gds", Some(&layers))?;
    chip.retain_tree("TOP")?;
    layouttk::check_write(&chip, Format::Oasis)?;
    layouttk::write(&chip, "metal.oas")
}

Use layouttk::file_workflows::{inventory, verify, clip_file} for low-memory file scanning, delivery verification, and two-pass window clipping (ClipOptions { keep_hierarchy: true, .. }).


Documentation

Topic Guides & References
Getting started English tutorial · Online manual (Read the Docs) · Simplified Chinese manual
CLI & automation Command-line guide · Offline agent workflows · AI index (llms.txt)
Python & examples Python API · Python workflows · Illustrated Python workflows · Layout gallery
Migration & interop gdspy, gdstk & KLayout interop · gdspy 1.6.13 coverage matrix · Silicon photonics guide
Performance & design Large-file filtering benchmarks · Upstream study & roadmap · Community requirements
CI & releases Three-platform wheel verification · Release process · Rust API on docs.rs
Area Implemented behavior Limits of this release
GDSII BOUNDARY, PATH (including absolute widths & end extensions), TEXT presentation/transforms, SREF, regular AREF, ordered numeric properties, multi-XY long boundaries, streamed cell writing, raw cells, timestamp edits & canonical SHA-1 hashes. Signed 32-bit output coordinates, integral array steps. BOX imports as a rectangle polygon. NODE and absolute STRANS produce diagnostics. Even-length property payloads ending in NUL are checked for padding ambiguity.
OASIS 1.0 Native circles, rectangles, polygons, trapezoids, paths, text, placements, all regular & explicit repetition families, CBLOCK, CRC32/checksum32 verification, typed properties, repeated names, forward refs, name-table aliases & layer-name intervals. Trapezoids write back as polygons/rectangles. Derived offsets & width bounds are normalized. Record order, timestamps & compression bytes may differ. Experimental SEMI P49 MULTIGON is skipped pending an accessible spec and samples.
Interchange Units, cell hierarchy, layer/type pairs, integer geometry & S_GDS_PROPERTY carrier. Strict encoder preflight via diagnostics() / check --json. Exact --regrid-factor and rational resample(). General OASIS properties, native circles & irregular repetitions require explicit conversion for GDSII. Styled GDSII text and round-cap/absolute-width paths cannot encode directly in OASIS. Odd full-width paths need --regrid-factor 2.
Resource budgets Decode-time layer filtering, low-memory inventory, and two-pass clip with recursive compact-array pruning. Default OASIS retained-data budget is 512 MiB (--oas-budget-bytes / oas_budget_bytes). Per-CBLOCK limit is 64 MiB; individual strings are limited to 1 MiB. Budget tracks retained model data separately from decoder buffers and allocator overhead.

License and acknowledgments

layouttk is released under the MIT License. Its design draws on Lucas H. Gabrielli’s gdspy and gdstk (the ASCII polygon font derives from gdspy.Text and the Hobby spline adapts gdspy’s equations) and on Matthias Köfferlein and the KLayout community (layer identifiers, hierarchical queries, region operators, and independent file verification).

Attribution · Third-party licenses · Rust stdlib notices