layouttk · GDSII and OASIS layout toolkit
Read, write, extract, and verify hierarchical GDSII and OASIS files with Python, Rust, or a headless CLI. Select layers during decoding, clip windows directly from a file, and keep design coordinates on the integer database grid. Use Clipper2 polygon operations and exchange packed coordinates with NumPy or PyTorch.
Project homepage · English manual · Simplified Chinese manual · AI documentation index
Generate OASIS and run agent examples on public layouts · See the Mona Lisa go from a NumPy array to OASIS
Installation
Install the Python package with python -m pip install layouttk. The numpy and torch extras install the optional array dependencies. The image extra adds NumPy and Pillow for PNG output. Install the command-line tool with cargo install layouttk --locked, or add the Rust library to a Cargo project with cargo add layouttk.
Download a prebuilt wheel for Linux x86_64, macOS arm64, or Windows x64 and install it offline with python -m pip install --no-index --no-deps PATH_TO_WHEEL.whl. Core layout I/O and geometry require no third-party Python packages. GitHub Release downloads
The same platforms have standalone CLI archives. Unpack one and run the executable with no Python or Rust installation. Archives include English and Simplified Chinese command guides and an Agent Skill. Use layouttk guide --lang en for the built-in guide. On an internal network, agents can use layouttk describe --json query bounds to read one command’s options and example. The static Linux x86_64 baseline binary runs without AVX/AVX2 and has been tested on Linux 3.2. The project Homebrew tap installs the CLI on Apple Silicon macOS and Linux x86_64. Standalone CLI and source archives
Since 0.4.1, the CLI supports --format json for a versioned report and layouttk batch for an ordered JSONL request stream. Run layouttk batch --help locally or follow the create, extract, and verify example in the guide. Command-line guide
Start by extracting a layer from a file you already have, or generate a small test layout and check it in KLayout. Getting started · File exchange with gdspy, gdstk and KLayout
Practice layer delivery, photonics window clipping and delivery verification with the supplied sample. Each exercise includes a prompt for an internal agent and results you can check. English examples · Download the offline examples
Build from source
Use Rust 1.95 or newer. The Python package targets GIL-enabled CPython 3.11+ and uses maturin through PEP 517. From the repository root:
Inspect, extract, and verify layouts
inventory scans the file and reports the grid, selected cells, layer/type pairs, local repetitions and dependencies without loading the shapes into a layout. verify compares stored records and placed mask XOR separately. clip scans twice and writes flat material cells under an explicit placement and output budget. Repeating --layer selects multiple pairs. Extraction keeps placements and their target cells, including cells that become empty. A top-cell selection retains its dependency tree after decoding. check runs the target encoder and reports its first error without creating a file.
Use layouttk create mask.json mask.oas to generate a layout from a versioned JSON description. The command also accepts - for standard input. Command-line guide
Use boolean to combine or subtract placed layers, query to inspect shapes and cell details, and edit to apply multiple changes in one write. Use raster for masks and PNG, or view for an SVG or self-contained HTML preview. Run layouttk --help to see all groups.
Python
=
=
=
= -
=
# additional parent-frame offsets
=
assert ==
assert .. == b
Layer(67, 20) + Layer(68, 20) produces a LayerSet that can be passed directly to Layout.read(..., layers=...). To combine filled geometry, get a Region with cell.region(layer), then use +, |, &, -, or ^. Python API
Lengths and widths are integer database units (DBU). File transforms and geometry functions with an angle_deg parameter accept degrees. The curve/path drawing language accepts radians. Polygon boundaries close implicitly. A cell handle retains its layout. A snapshot returned by elements() or get_properties() can be edited independently. A repetition retains an implicit origin and preserves duplicate placements.
Use Property.named("PROCESS", 12, 5.0, b"raw") for a named OASIS property. Use PropertyValue for explicit signedness or string kind, or fractions.Fraction for exact rational values. File, cell, cell-name, layer-name and element properties have separate scopes. When equal strings refer to different annotated OASIS table entries, TableRef(value, reference) keeps their identities distinct from literal values. Use Layout.table_properties and lookup_table_properties to inspect the entries. Python raises UnsupportedFeatureError for unrepresentable features, LayoutError for invalid layouts and OSError for I/O failures.
Polygon and PolygonSet keep drafting coordinates until an explicit grid conversion or insertion. This lets a sequence of transforms preserve off-grid construction points. The polygon drafting guide covers ownership, rounding and temporary operation grids. elliptic_sector supports solid and annular elliptical sectors, with either a sampling tolerance or a fixed vertex count.
The Python workflow guide has executable examples for photonics, extraction, KLayout region comparison and tensor exchange. The gdspy functionality matrix maps the gdspy 1.6.13 drawing, hierarchy, file and viewer workflows to their layouttk equivalents and explains differences.
NumPy and PyTorch
Install NumPy support with python -m pip install "layouttk[numpy]" or install both array frameworks with python -m pip install "layouttk[torch]". Basic layout operations can run without either dependency.
=
=
=
=
=
, =
assert == and ==
Packed contours use CPU buffers with native-endian integer data. copy=False requests sharing between supported arrays. Insertion copies coordinates into the Rust layout. An exported batch owns its buffers and remains usable after the layout is released. Writable CPU tensors can share storage through PolygonBatch.from_torch, to_torch or DLPack. To work on a PyTorch device, use batch.to_torch(device="mps", copy=True) or specify a CUDA device, then bring the two result tensors back with PolygonBatch.from_torch(points, starts, copy=True). Boolean results may include holes. Use fracture() to produce independent filled polygons for layout insertion. The buffer exchange follows the published NumPy DLPack and PyTorch DLPack conventions.
Use raster.add_mask() to insert a two-dimensional NumPy image on a layer, raster.to_mask() to sample a placed window, and raster.write_png() to save that window. Binary image tutorial
Public layouts and agent examples
Run these commands from the repository root with both the layouttk Python package and CLI installed.
Generate OASIS. Read layer 10/0 from an inverter in the ASU/Arm ASAP7 predictive 7 nm cell library and place four instances in an array. The resulting top cell is INV_ROW, with a 0.25 nm DBU. ASAP7 cell library
Render PNG and add bounding boxes. The input is a Mach–Zehnder interferometer submitted to SiEPIC openEBL for fabrication. Ask Pi to render layer 1/0 as a 1210 × 820 PNG, or ask OpenCode to write a bounding rectangle for each of that layer's 108 placed shapes to the new layer 900/0. Original OASIS submission
Configure a model for the agent, then run its command from the checkout root.
Examples and expected results · Simplified Chinese · Fixture sources and licenses · KLayout Python and Ruby mapping
From a NumPy array to OASIS · Mona Lisa
| Source image | OASIS open in KLayout |
|---|---|
Run python -m pip install "layouttk[image]" in a terminal. Save the image as mona-lisa.jpg and run this Python code in the same folder. Download the source image
= >= 128
=
If you already have a 2D NumPy array, pass it to raster.add_mask as mask. Zero means background and any nonzero value means fill. The example fills grayscale values of 128 or higher on layer 67/20 of cell TOP. Each pixel is 10 nm square. Open mona-lisa.oas in KLayout to view the result.
The full script reads the OASIS file back, verifies every pixel, and writes a binary PNG. The screenshot shows mona-lisa.oas open in KLayout. Full script and instructions · Download the generated OASIS · Download the offline examples
The source image is a C2RMF reproduction of Leonardo da Vinci's public-domain painting. Wikimedia Commons
Rust
use BTreeSet;
use ;
read_from accepts a reader without seeking. write_to accepts a writer and an explicit format. Path-based writes finish encoding to a temporary file in the destination directory before replacing the target. A failed format check leaves the previous output intact. For a split-library workflow, read with allow_external_references=True, inspect external_references and supply the missing definitions. A normal file write validates the full reference graph.
Conversion and analysis
Layout.diagnostics("gds") and layouttk check input.oas --to gds --json enumerate conversion diagnostics with cell, element, layer, field and severity. File writes use the strict encoder. For an odd-width GDSII path, layouttk convert input.gds output.oas --regrid-factor 2 refines the grid while preserving the physical width. Use Layout.resample(target_dbu_meters) for an arbitrary target grid. By default it requires exact representability. Layout.reinterpret_dbu(...) keeps the numeric coordinates unchanged and deliberately changes their physical size. Passing rounding="nearest" to resample explicitly snaps each dimension to the nearest target DBU with ties away from zero.
analysis.compare_layouts reports structural, metadata and per-layer geometry differences. analysis.query_window returns complete intersecting contours. analysis.clip_windows cuts geometry at the window boundaries. Export a single cell or element as SVG with svg_fragment, or embed raw GDSII records using gds_tools.cell_bytes and gds_tools.element_bytes. The benchmark report measures layer filtering and includes the generator, data hashes, memory and elapsed time.
Format coverage
| Area | Implemented behavior | Limits of this release |
|---|---|---|
| GDSII | BOUNDARY, PATH including absolute widths and path caps/extensions, TEXT presentation and transforms, SREF, regular AREF, ordered numeric element properties, multi-XY long boundaries. Streamed cell writing, raw cells, unit inspection, timestamp edits and canonical content hashes. | Signed 32-bit output coordinates, integral array steps. BOX imports as a rectangle polygon and retains its boxtype and properties. NODE and absolute STRANS produce diagnostics. Even-length property payloads ending in NUL are ambiguous with padding and require a representability check. |
| OASIS 1.0 | Native circles, rectangles, polygons, trapezoids, paths, text, placements, all regular and explicit repetition families, CBLOCK and signature verification. Typed properties, repeated names, forward references, property modals, name tables and layer-name intervals. | Trapezoids are written back as polygons or rectangles. Derived file offsets and width bounds are normalized. Exact record order, timestamps and compression bytes can change. |
| Interchange | Units, cell references, layer/type pairs, integer geometry and compatible attributes. The OASIS standard GDS property carrier preserves numeric attribute IDs and payload bytes. | General OASIS properties, native circles and irregular repetitions require an explicit representation change to reach GDSII. Styled GDSII text and absolute-width or round-cap paths cannot be represented directly in OASIS. An odd full-width PATH requires a finer output grid. |
| Metadata | GDSII keeps the library name and writes a micrometre display unit and deterministic timestamps. OASIS input uses the library name LIBRARY. |
OASIS has no equivalent field for a GDSII library name. File properties, cell-body properties and cell-name table properties remain distinct. |
Layer filtering limits retained geometry. inspect still materializes the selected layout. For OASIS the default accounting budget for retained data is 512 MiB. Configure it with Rust ReadOptions, Python oas_budget_bytes= or CLI --oas-budget-bytes. This budget excludes decoder buffers and allocator overhead. Each compressed or uncompressed CBLOCK is limited to 64 MiB and individual strings to 1 MiB. Units and arbitrary rotations use floating-point real numbers. Hierarchy validation and layer selection preserve compact arrays. Polygon booleans use a signed winding rule. The experimental P49 MULTIGON codec is skipped pending an accessible specification and independent interoperability samples. See the development roadmap.
Silicon photonics
Use silicon photonics layout and handoff to plan layer extraction for optical ports, tight curves, simulator windows and foundry handoff.
Development and releases
Run Rust tests with cargo test --locked. For independent Python interoperability checks, build with maturin build --release --locked, install the wheel and test dependencies in a clean environment, and run python -m pytest tests. The Rust and Python distributions take their version from Cargo.toml. The release workflow verifies a matching tag, builds and checks the distributions, and publishes via registry trusted publishers. See the three-platform wheel verification guide for the exact test matrix, artifact downloads and reproduction commands, and the release guide for registry setup.
The upstream study and roadmap and community requests with acceptance criteria document the public use cases behind the API.
License and acknowledgments
layouttk is released under the MIT License. Its design draws on Lucas H. Gabrielli’s gdspy and gdstk, the contributors who built them, and the users who shared layout examples, bug reports and format expertise. The ASCII glyphs derive from gdspy.Text and the Hobby spline implementation adapts the equations in gdspy. We also thank Matthias Köfferlein and the KLayout contributors for their database API, region operations and independent file readers. Python layer identifiers, hierarchical queries and region operators draw on those conventions. See gdspy, gdstk, KLayout database API, KLayout Region, project attribution, third-party license texts, and Rust standard-library notices.