layouttk 0.5.0

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

Each example runs independently in an empty working directory with an installed layouttk wheel. The file examples write their output in that directory. A database unit (DBU) in these designs is one nanometre. Coordinates, widths and array steps are integer DBU. Areas are square DBU. Placement and label angles are counterclockwise degrees.

The [illustrated Python examples](https://layouttk.readthedocs.io/en/latest/python-visual-workflows.html) use public CMOS, BiCMOS and photonics layouts and show the actual outputs in KLayout.

## Build a parametric contact cell

A gdspy cell factory can map to a function that takes an explicit layout and returns a live cell handle. Here the cell name encodes both dimensions. Equal parameter values reuse one definition. The metal landing extends beyond the cut by 100 DBU on every side, and a single placement describes the six contacts. [gdspy cell and reference examples](https://gdspy.readthedocs.io/en/stable/gettingstarted.html)

```python
from layouttk import Layer, Layout, Property, Region

cut = Layer(5, 0)
metal = Layer(6, 0)


def contact(layout, width, enclosure):
    if width <= 0 or enclosure < 0:
        raise ValueError("invalid contact dimensions")
    name = f"CONTACT_{width}_{enclosure}"
    if name in layout.cell_names:
        return layout.cell(name)
    cell = layout.add_cell(name)
    cell.add_region(Region.box((0, 0), (width, width)), layer=cut)
    cell.add_region(Region.box((-enclosure, -enclosure),
                               (width + enclosure, width + enclosure)), layer=metal)
    cell.set_properties([Property.named("CUT_WIDTH_DBU", width)])
    return cell


layout = Layout("CONTACT_TEST", dbu_nm=1)
top = layout.add_cell("TOP")
tile = contact(layout, 200, 100)
top.add_reference(tile, (50, 80), columns=3, rows=2,
                  column_step=(700, 0), row_step=(0, 800))
assert contact(layout, 200, 100).name == tile.name
layout.write("contacts.oas")

restored = Layout.read("contacts.oas")
assert restored.cell(tile.name).get_properties() == [Property.named("CUT_WIDTH_DBU", 200)]
assert restored.cell("TOP").region(cut).area == 6 * 200**2
placement, = restored.cell("TOP").elements()
assert (placement["array"]["columns"], placement["array"]["rows"]) == (3, 2)
```

A `Cell` retains its layout and addresses a definition by name. Edits through the handle immediately affect every instance of that definition. Reacquire the handle with `layout.cell(new_name)` after a rename. `cell.elements()` returns independent dictionaries and point lists. `cell.region(layer)` computes an independent union of the placed geometry. This example writes OASIS to preserve its named cell property.

## Build a hierarchical mask with alignment marks

Put the annular device and the alignment cross in reusable definitions. The block template accounts for the device's negative local coordinates and stores all six die placements in one reference array. The two vernier rows have distinct pitches and layer pairs. Read back both formats and check the dependency graph, bounds, area and central opening. The [Python API reference](https://docs.rs/layouttk/0.5.0/layouttk/guides/python_api/) maps these operations to gdsCAD.

```python
from layouttk import Layer, Layout, hierarchy, shapes, templates

device, lower, upper = Layer(7, 1), Layer(10), Layer(11)
layout = Layout("MASK", dbu_nm=1)
top = layout.add_cell("TOP")
die = layout.add_cell("DIE")
ring = shapes.disk((0, 0), 100, inner_radius=45, vertices=64)
die.add_region(ring, layer=device)

assert templates.add_block(top, die, ((0, 0), (840, 560)),
                           gap=(100, 100), margin=20) == 6
marks = layout.add_cell("ALIGN")
marks.add_region(templates.alignment_mark((80, 80), width=16), layer=lower)
top.add_reference(marks, (50, -100))
top.add_reference(marks, (770, -100))
templates.vernier((8, 40), pitches=(20, 22), layers=(lower, upper),
                  gap=8).translate(410, -100).add_to(layout, top.name)

for extension in ("gds", "oas"):
    path = f"mask.{extension}"
    layout.write(path)
    restored = Layout.read(path, top="TOP")
    assert set(hierarchy.dependencies(restored, "TOP")) == {"DIE", "ALIGN"}
    mask = restored.cell("TOP").region(device)
    assert mask.area == 6 * ring.area
    assert mask.bounds == ((20, 20), (820, 520))
    assert not mask.contains((120, 120))
```

## Place a photonic taper with directional ports

This 10 µm taper widens from 450 nm to 900 nm. The two GDSII TEXT records mark its optical ports. Each label's rotation records the outward port direction. The check after reading the GDSII exercises the combined mirror and rotation in the parent placement. This follows the directional-label use case reported by gdspy users. [Port-label discussion](https://github.com/heitzmann/gdspy/issues/208)

```python
from layouttk import Layer, Layout, hierarchy, write_viewer

core = Layer(1, 0)
ports = Layer(66, 0)
layout = Layout("PHOTONICS", dbu_nm=1)
taper = layout.add_cell("TAPER")
taper.add_polygon([(0, -225), (10_000, -450), (10_000, 450), (0, 225)], layer=core)
layout.add_text(taper.name, ports, (0, 0), "IN", angle_deg=180)
layout.add_text(taper.name, ports, (10_000, 0), "OUT")
top = layout.add_cell("CHIP")
top.add_reference(taper, (3000, 2000), angle_deg=90, reflect_x=True)
layout.write("taper.gds")

device = Layout.read("taper.gds")
labels = hierarchy.labels(device, "CHIP", layer=ports)
pins = {e["text"]: (e["origin"], round(e["style"]["angle_deg"]) % 360)
        for e in labels}
assert pins == {"IN": ((3000, 2000), 270), "OUT": ((3000, 12_000), 90)}
assert device.cell("CHIP").region(core).area == 6_750_000
write_viewer(device, "taper.html", cell="CHIP", label_size=200)
```

Open `taper.html` locally to measure the distance between port centres. The ruler reports 10,000 DBU or 10 µm. Setting the hierarchy depth to zero displays the taper's placement outline. Selecting the TAPER definition shows its local coordinate system.

## Extract one layer and its hierarchy

A layer filter takes physical layer and datatype pairs, and `top` identifies the dependency tree to export. A layer-only export can retain empty referenced cells. The reader scans the input in file order and applies the layer selection while decoding. The input for this example includes an unrelated top cell and a child whose only geometry is on a discarded layer. [Public selective-read use case](https://github.com/heitzmann/gdstk/issues/280)

```python
from layouttk import Layer, Layout, Region

metal = Layer(67, 20)
annotation = Layer(99, 7)
source = Layout("SOURCE", dbu_nm=1)
wire = source.add_cell("WIRE")
wire.add_region(Region.box((0, 0), (1000, 120)), layer=metal)
marks = source.add_cell("MARKS")
source.add_text(marks.name, annotation, (10, 15), "ALIGN")
chip = source.add_cell("CHIP")
chip.add_reference(wire, (100, 200))
chip.add_reference(marks, (0, 0))
source.add_cell("UNRELATED")
source.write("source.oas")

selected = Layout.read("source.oas", top="CHIP", layers=[metal])
selected.check_write("gds")
selected.write("metal.gds")
export = Layout.read("metal.gds")
assert set(export.cell_names) == {"CHIP", "WIRE", "MARKS"}
assert export.cell("MARKS").elements() == []
assert {e["target"] for e in export.cell("CHIP").elements()} == {"WIRE", "MARKS"}
expected = Region.box((100, 200), (1100, 320))
assert not (export.cell("CHIP").region(metal) ^ expected)
```

## Check placed geometry against KLayout

Install the `klayout` Python package for this example. Two overlapping references place 40,000 square DBU of rectangles onto 35,000 square DBU of distinct material. Subtracting a 100 × 60 DBU window should leave 29,000. The final XOR checks every edge of the GDSII result with KLayout's recursive shape iterator and merged region operations. [KLayout Cell](https://www.klayout.de/doc-qt5/code/class_Cell.html) · [KLayout Region](https://www.klayout.de/doc-qt5/code/class_Region.html)

```python
import klayout.db as kdb
from layouttk import Layer, Layout, Region

metal, trimmed = Layer(7, 0), Layer(8, 0)
layout = Layout("REGION_TEST", dbu_nm=1)
leaf = layout.add_cell("RECT")
leaf.add_region(Region.box((0, 0), (200, 100)), layer=metal)
top = layout.add_cell("TOP")
top.add_reference(leaf, columns=2, column_step=(150, 0))
material = top.region(metal)
remaining = material - Region.box((125, 20), (225, 80))
assert (material.area, remaining.area) == (35_000, 29_000)
top.add_region(remaining, layer=trimmed)
layout.write("trimmed.gds")

other = kdb.Layout()
other.read("trimmed.gds")
assert abs(other.dbu - 0.001) < 1e-12  # KLayout's DBU is expressed in µm.
other_top = other.cell("TOP")
placed = kdb.Region(other_top.begin_shapes_rec(other.layer(*metal))).merged()
actual = kdb.Region(other_top.begin_shapes_rec(other.layer(*trimmed))).merged()
expected = placed - kdb.Region(kdb.Box(125, 20, 225, 80))
assert (placed.area(), actual.area()) == (35_000, 29_000)
assert (actual ^ expected).is_empty()
```

## Move packed polygons with NumPy and PyTorch

Install the `layouttk[torch]` extra for this example. Two native-endian, C-contiguous CPU `int64` buffers hold all vertices and the start index of each polygon. The final index equals the total vertex count. Each ring has an implicit closing edge. Tensor and NumPy views can share these buffers while the Rust layout owns its own copy after insertion. [PyTorch shared NumPy storage](https://docs.pytorch.org/docs/stable/generated/torch.from_numpy.html)

```python
import numpy as np
import torch
from layouttk import Layer, Layout, PolygonBatch

vertices = np.array([(0, 0), (80, 0), (80, 40), (0, 40),
                     (100, 0), (140, 0), (110, 30)], dtype=np.int64)
indptr = np.array([0, 4, 7], dtype=np.int64)
batch = PolygonBatch.from_numpy(vertices, indptr)
points, starts = batch.to_torch()
assert points.device.type == "cpu" and points.dtype == torch.int64
points[starts[1]:starts[2]] += torch.tensor([10, -5])
assert vertices[4].tolist() == [110, -5]

layout = Layout(dbu_nm=1)
top = layout.add_cell("TOP")
layer = Layer(7, 3)
PolygonBatch.from_torch(points, starts).add_to(layout, top.name, layer)
points[4, 0] += 20
stored = PolygonBatch.from_layout(layout, top.name, layer)
coords, bounds = stored.to_numpy()
assert coords[4].tolist() == [110, -5]
assert bounds.tolist() == [0, 4, 7]
assert not np.shares_memory(coords, vertices)
```

For computation on an accelerator, explicitly transfer both buffers. The batch stays in CPU memory. int64 operations on the destination depend on the installed PyTorch backend. [PyTorch device transfer](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.to.html)

```python
device = "cuda" if torch.cuda.is_available() else "mps"
if torch.cuda.is_available() or torch.backends.mps.is_available():
    points, starts = batch.to_torch(device=device, copy=True)
    points[:, 0] += 50
    translated = PolygonBatch.from_torch(points, starts, copy=True)
    assert np.array_equal(translated.vertices[:, 0], batch.vertices[:, 0] + 50)
```

Use `copy=True` on input to isolate the arrays or convert non-contiguous integer views. `from_layout` selects stored local polygons on one layer. The two buffers carry coordinates and ring boundaries. Use the element and property APIs when editing attributed shapes or placements.

## Keep an irregular array and its properties

This OASIS label-free contact pattern has three placements. The offset list supplies the second and third. Negative coordinates are valid. The `PROCESS` property belongs to the placement record. The numeric GDS property belongs to the pad element in the child.

```python
from layouttk import Layer, Layout, Property, Region

cut = Layer(5, 0)
mask = Layout(dbu_nm=1)
pad = mask.add_cell("PAD")
pad.add_region(Region.box((0, 0), (10, 10)), layer=cut)
pad.set_properties([Property.gds(7, b"via")], element=0)
top = mask.add_cell("TOP")
top.add_reference(pad, (100, 200))
offsets = [(-30, 15), (80, 40)]
mask.set_repetition("TOP", 0, offsets)
top.set_properties([Property.named("PROCESS", 3, 2.5)], element=0)

loaded = Layout.from_bytes(mask.to_bytes("oas"))
record, = loaded.cell("TOP").elements()
assert record["array"]["offsets"] == offsets
assert loaded.cell("TOP").get_properties(element=0) == [Property.named("PROCESS", 3, 2.5)]
assert loaded.cell("PAD").get_properties(element=0) == [Property.gds(7, b"via")]
assert loaded.cell("TOP").region(cut).area == 300
```

`get_properties()` on the cell without `element=` selects the cell body. Choose OASIS to keep the named property and irregular repetition in their native form. Preflight a proposed GDSII export with `diagnostics("gds")`.

## Diagnose an odd path width

A 3 nm wide path on a 1 nm grid needs an OASIS half-width of 1.5 grid units. Refine the grid when writing. The original layout retains its coordinates and the output retains the physical width.

```python
from math import isclose
from layouttk import Layout

mask = Layout(dbu_nm=1)
mask.add_cell("TOP")
mask.add_path("TOP", (7, 11), [(-5, 7), (9, 7)], 3)
errors = [d for d in mask.diagnostics("oas") if d["severity"] == "error"]
assert any(d["field"] == "path.width" and d["cell"] == "TOP" for d in errors)

mask.write("routed.oas", regrid_factor=2)
other = Layout.read("routed.oas")
path, = other.cell("TOP").elements()
assert path["width"] == 6
assert isclose(path["width"] * other.dbu_meters, 3e-9)
assert mask.cell("TOP").elements()[0]["width"] == 3
```

## Draw two tracks and clip a measurement window

Give each track a physical layer and width. Convert the paths to filled contours, then query a window on the horizontal section. The query returns the entire first track. The clip returns only the material inside the window.

```python
from layouttk import FlexPath, Layer, Layout, Region, analysis

mask = Layout(dbu_nm=1)
top = mask.add_cell("ROUTE")
route = FlexPath([(0, 0), (300, 0), (300, 300)], [40, 80], [-50, 80],
                 joins="miter", layer=[1, 7], datatype=[2, 3])
route.add_to(mask, top.name)
metal = Layer(1, 2)
assert top.region(metal).area == 28_000
window = ((50, -70), (150, -30))
hits = analysis.query_window(mask, top.name, window, layers=[metal])
assert len(hits) == 1
clipped, = analysis.clip_windows(mask, top.name, [window], layers=[metal])
assert not (clipped[metal] ^ Region.box(*window))
assert clipped[metal].area == 4_000
```

## Open a gdspy design on the same physical grid

Install gdspy 1.6.13 for this example. It creates a GDSII file using micrometres, draws a 2 × 1 µm rectangle and attaches an element property. layouttk reads it on its 1 nm database grid. gdstk independently checks the physical area and the property after a GDSII round trip.

```python
from math import isclose
import gdspy
import gdstk
from layouttk import Layer, Layout, Property

legacy = gdspy.GdsLibrary(unit=1e-6, precision=1e-9)
cell = legacy.new_cell("LEGACY_PAD", overwrite_duplicate=True)
pad = gdspy.Rectangle((0, 0), (2, 1), layer=4, datatype=1)
pad.properties[7] = "padA"
cell.add(pad)
legacy.write_gds("legacy.gds")

mask = Layout.read("legacy.gds")
assert isclose(mask.dbu_meters, 1e-9)
pad_cell = mask.cell("LEGACY_PAD")
assert pad_cell.region(Layer(4, 1)).area == 2_000_000
assert pad_cell.get_properties(element=0) == [Property.gds(7, b"padA")]
mask.write("exchanged.gds")
foreign = gdstk.read_gds("exchanged.gds", unit=1e-6)
shape, = foreign["LEGACY_PAD"].polygons
assert isclose(shape.area(), 2.0)
assert shape.get_gds_property(7).rstrip("\0") == "padA"
```

The last check strips the trailing NUL that gdstk can expose for this textual GDS property. layouttk’s property assertion above checks the payload bytes.