<h1 align="center">layouttk</h1>
<p align="center"><strong>Headless GDSII & OASIS layout toolkit for Python, Rust, and the CLI</strong><br>Integer-grid precision · Streaming layer extraction · Hierarchical window clipping · NumPy & PyTorch interop</p>
<p align="center">
<a href="https://pypi.org/project/layouttk/"><img alt="PyPI version" src="https://img.shields.io/pypi/v/layouttk?logo=pypi&logoColor=white"></a>
<a href="https://crates.io/crates/layouttk"><img alt="crates.io version" src="https://img.shields.io/crates/v/layouttk?logo=rust"></a>
<a href="https://github.com/zwh42/layouttk/actions/workflows/ci.yml"><img alt="CI status" src="https://github.com/zwh42/layouttk/actions/workflows/ci.yml/badge.svg"></a>
<a href="https://docs.rs/layouttk/latest/layouttk/guides/"><img alt="Documentation on docs.rs" src="https://docs.rs/layouttk/badge.svg"></a>
<a href="https://github.com/zwh42/layouttk/blob/main/LICENSE"><img alt="MIT License" src="https://img.shields.io/badge/license-MIT-blue"></a>
</p>
<p align="center">
<strong>English</strong> ·
<a href="https://github.com/zwh42/layouttk/blob/main/README.zh-CN.md">Simplified Chinese</a> ·
<a href="https://zwh42.github.io/layouttk/">Homepage</a> ·
<a href="https://layouttk.readthedocs.io/">Manual</a> ·
<a href="https://layouttk.readthedocs.io/en/latest/gallery.html">Gallery</a> ·
<a href="https://zwh42.github.io/layouttk/llms.txt">AI Index (llms.txt)</a>
</p>
**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) |
| :---: | :---: |
| <img src="https://raw.githubusercontent.com/zwh42/layouttk/main/docs/images/openebl-mzi-1-0.png" width="400" alt="Layer 1/0 rendered by layouttk from the SiEPIC openEBL MZI OASIS layout"> | <img src="https://raw.githubusercontent.com/zwh42/layouttk/main/.agents/skills/layouttk/assets/mona-lisa/mona-lisa-klayout.png" width="320" alt="KLayout with mona-lisa.oas open, displaying layer 67/20 in cell TOP"> |
| [Public layout examples](https://layouttk.readthedocs.io/en/latest/public-layouts.html) · [Visual Python workflows](https://layouttk.readthedocs.io/en/latest/python-visual-workflows.html) | [NumPy-to-OASIS Mona Lisa walkthrough](#from-a-numpy-array-to-oasis) |
## 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):
```sh
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`:
```python
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](https://github.com/zwh42/layouttk/releases/latest)), run these commands in the same folder:
```sh
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](https://docs.rs/layouttk/0.5.0/layouttk/guides/getting_started/) · [Migrate from gdspy, gdstk, or KLayout](https://docs.rs/layouttk/0.5.0/layouttk/guides/interoperability/)
---
## 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](https://github.com/zwh42/layouttk/blob/main/.agents/skills/layouttk/SKILL.md) |
---
## 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](https://github.com/zwh42/layouttk/releases/latest) (Linux musl, macOS arm64, Windows x64) |
| **Rust library / CLI** (Rust 1.95+) | `cargo add layouttk` / `cargo install layouttk --locked` |
<details>
<summary>Offline wheels, air-gapped Linux 3.2 baseline & building from source</summary>
- **Offline Python wheels**: Download the wheel for Linux x86_64, macOS arm64, or Windows x64 from [GitHub Releases](https://github.com/zwh42/layouttk/releases/latest) 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+):
```sh
cargo install --locked --path .
python -m pip install .
```
</details>
---
## 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`.
```python
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](https://docs.rs/layouttk/0.5.0/layouttk/guides/python_api/) · [Mask construction with `shapes` & `templates`](https://github.com/zwh42/layouttk/blob/main/docs/en/python-workflows.md#build-a-hierarchical-mask-with-alignment-marks) · [Polygon drafting & rounding](https://docs.rs/layouttk/0.5.0/layouttk/guides/polygon_drafts/)
### 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"`):
```python
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](https://raw.githubusercontent.com/zwh42/layouttk/main/.agents/skills/layouttk/assets/mona-lisa/mona-lisa.jpg), and convert any 2D NumPy mask directly to OASIS (`0` = background, nonzero = fill, 10 nm pixel pitch):
```python
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](https://github.com/zwh42/layouttk/tree/main/.agents/skills/layouttk/assets/mona-lisa) · [Binary image tutorial](https://docs.rs/layouttk/0.5.0/layouttk/guides/raster_images/) · Source image: public-domain C2RMF scan on [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg).
### 4. Public layouts & AI coding agents
Try verified offline exercises with [ASAP7](https://github.com/The-OpenROAD-Project/asap7sc7p5t_28) and [SiEPIC openEBL MZI](https://github.com/SiEPIC/openEBL-2024-10/blob/090cd97ceaf7805570ad756166686133b5eefe04/submissions/EBeam_LukasChrostowski_MZI.oas) layouts, or invoke the bundled skill directly from your coding agent:
```sh
# 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](https://github.com/zwh42/layouttk/blob/main/.agents/skills/layouttk/references/workflows.en.md) · [Download offline example bundle](https://zwh42.github.io/assets/files/layouttk-agent-examples.zip) · [CLI automation & JSONL batch guide](https://docs.rs/layouttk/0.5.0/layouttk/guides/command_line/)
### 5. Rust library
```rust
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](https://docs.rs/layouttk/0.5.0/layouttk/guides/getting_started/) · [Online manual (Read the Docs)](https://layouttk.readthedocs.io/) · [Simplified Chinese manual](https://layouttk.readthedocs.io/en/latest/zh-CN/) |
| **CLI & automation** | [Command-line guide](https://docs.rs/layouttk/0.5.0/layouttk/guides/command_line/) · [Offline agent workflows](https://github.com/zwh42/layouttk/blob/main/.agents/skills/layouttk/references/workflows.en.md) · [AI index (`llms.txt`)](https://zwh42.github.io/layouttk/llms.txt) |
| **Python & examples** | [Python API](https://docs.rs/layouttk/0.5.0/layouttk/guides/python_api/) · [Python workflows](https://docs.rs/layouttk/0.5.0/layouttk/guides/python_workflows/) · [Illustrated Python workflows](https://layouttk.readthedocs.io/en/latest/python-visual-workflows.html) · [Layout gallery](https://layouttk.readthedocs.io/en/latest/gallery.html) |
| **Migration & interop** | [gdspy, gdstk & KLayout interop](https://docs.rs/layouttk/0.5.0/layouttk/guides/interoperability/) · [gdspy 1.6.13 coverage matrix](https://docs.rs/layouttk/0.5.0/layouttk/guides/gdspy_coverage/) · [Silicon photonics guide](https://docs.rs/layouttk/0.5.0/layouttk/guides/silicon_photonics/) |
| **Performance & design** | [Large-file filtering benchmarks](https://docs.rs/layouttk/0.5.0/layouttk/guides/benchmarks/) · [Upstream study & roadmap](https://docs.rs/layouttk/0.5.0/layouttk/guides/upstream_research_and_roadmap/) · [Community requirements](https://docs.rs/layouttk/0.5.0/layouttk/guides/community_needs/) |
| **CI & releases** | [Three-platform wheel verification](https://docs.rs/layouttk/0.5.0/layouttk/guides/ci/) · [Release process](https://docs.rs/layouttk/0.5.0/layouttk/guides/releasing/) · [Rust API on docs.rs](https://docs.rs/layouttk/0.5.0/layouttk/) |
<details>
<summary>Format coverage & technical limits</summary>
| 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. |
</details>
---
## License and acknowledgments
layouttk is released under the [MIT License](https://github.com/zwh42/layouttk/blob/main/LICENSE). Its design draws on **Lucas H. Gabrielli’s [gdspy](https://github.com/heitzmann/gdspy) and [gdstk](https://github.com/heitzmann/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](https://www.klayout.de/doc/programming/database_api.html) community** (layer identifiers, hierarchical queries, region operators, and independent file verification).
[Attribution](https://github.com/zwh42/layouttk/blob/main/NOTICE) · [Third-party licenses](https://docs.rs/crate/layouttk/0.5.0/source/THIRD-PARTY-LICENSES.txt) · [Rust stdlib notices](https://docs.rs/crate/layouttk/0.5.0/source/licenses/RUST-STDLIB-1.100.1.html)