# Python layout workflows
Each example runs independently in an empty working directory with an installed layouttk wheel. The first three write small layout files 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.
## 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_meters=1e-9)
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.
## 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_meters=1e-9)
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_meters=1e-9)
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_meters=1e-9)
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_meters=1e-9)
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.