layouttk
layouttk is a Rust library, Python extension and command-line tool for reading, writing and extracting hierarchical mask layouts. Coordinates stay on the input database grid. You can select layers during decoding and keep a cell with all its transitive dependencies. The Rust core also provides integer polygon operations, curved path construction and hierarchy editing. Python provides a cell-oriented interface, an offline viewer and packed arrays for NumPy and PyTorch.
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.
Create your first mask and check its dimensions in KLayout with Getting started. Browse the searchable manual on Read the Docs, or open the versioned guides on docs.rs.
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:
cargo install --locked --path .
python -m pip install .
Extract a layer
layouttk inspect chip.oas
layouttk extract chip.oas metal.gds --top CHIP --layer 67/20
layouttk check metal.gds --to oas
layouttk convert metal.gds metal.oas
inspect writes JSON with the physical database unit, top cells, layer/type pairs and stored element counts. 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
Python
from layouttk import Layer, Layout, Property, Region
chip = Layout("MASK", dbu_meters=1e-9)
leaf = chip.add_cell("CONTACT")
metal = Layer(67, 20)
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)]) # additional parent-frame offsets
chip.write("chip.oas")
restored = Layout.read("chip.oas", layers=[metal], top="TOP")
assert restored.cell("TOP").layers() == (metal,)
assert restored.get_properties(cell="CONTACT", element=0)[0].values[1].value == b"contact"
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.
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]
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
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")
}
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.
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 Boost Software License 1.0. 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.
Metadata
Release files for layouttk 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| layouttk-0.1.2.tar.gz | 401.6 kB | With provenance | Details for layouttk-0.1.2.tar.gz |
Built distributions (wheels)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| layouttk-0.1.2-cp311-abi3-win_amd64.whl | CPython 3.11 | abi3 | Windows x86-64 | Details for layouttk-0.1.2-cp311-abi3-win_amd64.whl |
| layouttk-0.1.2-cp311-abi3-manylinux_2_28_x86_64.whl | CPython 3.11 | abi3 | Linux glibc 2.28+ x86-64 | Details for layouttk-0.1.2-cp311-abi3-manylinux_2_28_x86_64.whl |
| layouttk-0.1.2-cp311-abi3-macosx_11_0_arm64.whl | CPython 3.11 | abi3 | macOS 11.0+ ARM64 | Details for layouttk-0.1.2-cp311-abi3-macosx_11_0_arm64.whl |
Total release size: 4.1 MB
Release files / layouttk-0.1.2.tar.gz
| Download URL | layouttk-0.1.2.tar.gz |
|---|---|
| Size | 401.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
32231b4484b1f159c8b99bf612681ecb6808e1e659be7014e18a7e383cf6efe0
|
|
BLAKE2b-256 checksum How to use checksums |
d60114231710c1ff5dcd4f77b60b21692f50f0d93064539f18d65cdd47d9f6fb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / layouttk-0.1.2-cp311-abi3-win_amd64.whl
| Download URL | layouttk-0.1.2-cp311-abi3-win_amd64.whl |
|---|---|
| Size | 1.2 MB |
| Tags | CPython 3.11 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
c520df375c1732d290c7b5f026a1752df7d6f23f12a891ab62dd1900571d74d7
|
|
BLAKE2b-256 checksum How to use checksums |
f79dc7dbb653e3b6205c92beca682192018706f7c16577d7ac6dc37ed90beaab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / layouttk-0.1.2-cp311-abi3-manylinux_2_28_x86_64.whl
| Download URL | layouttk-0.1.2-cp311-abi3-manylinux_2_28_x86_64.whl |
|---|---|
| Size | 1.3 MB |
| Tags | CPython 3.11 Linux glibc 2.28+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
b87845964b9b27238d42de2b725f31118254a0bd664b440fbf0a57daf2c0d2d9
|
|
BLAKE2b-256 checksum How to use checksums |
4dd3cf330346289d04f38dd41f282b2cddd4c2a1d8a045895bd12fcf857e2d6a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / layouttk-0.1.2-cp311-abi3-macosx_11_0_arm64.whl
| Download URL | layouttk-0.1.2-cp311-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 1.2 MB |
| Tags | CPython 3.11 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
8db42d14ae8f256c692b125e018e00c20b0ea72a499321e6978e64317d16ebab
|
|
BLAKE2b-256 checksum How to use checksums |
775f640c66b2528454f9601a4994b799b6f605eebcfb947ab4c23c4b42eade52
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logSecurity for layouttk 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 4 files in this release have been uploaded with provenance metadata.
Attestation for layouttk-0.1.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.