layouttk 0.4.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
# Python API reference by task

Import the public types from `layouttk`. Import `analysis` or `hierarchy` from the same package for operations on an existing layout. The tables use `layout` for a `Layout` instance and `cell` for a `Cell` handle. Arguments identified as points, pitches, widths or windows are in integer DBU unless a drawing operation explicitly accepts fractional coordinates. For copy-and-run scripts, see [Getting started](https://docs.rs/layouttk/0.4.1/layouttk/guides/getting_started/) and the [workflow examples](https://docs.rs/layouttk/0.4.1/layouttk/guides/python_workflows/).

## From KLayout Python or Ruby

KLayout exposes the same database model through `klayout.db` in standalone Python and `RBA` in Ruby macros. Use the mapping below to translate file and geometry operations to layouttk Python or to a shell command. [KLayout scripting interfaces](https://www.klayout.de/doc-qt5/programming/index.html) · [KLayout database model](https://www.klayout.de/doc-qt5/programming/database_api.html)

| Task | KLayout Python | KLayout Ruby | layouttk Python |
| --- | --- | --- | --- |
| Create a database | `kdb.Layout()` | `RBA::Layout.new` | `Layout()` |
| Set a 1 nm DBU | `layout.dbu = 0.001` | `layout.dbu = 0.001` | `Layout(dbu_nm=1)` |
| Read a layout | `layout.read(path)` | `layout.read(path)` | `Layout.read(path)` |
| Create or get a cell | `layout.create_cell("TOP")`, `layout.cell("TOP")` | `layout.create_cell("TOP")`, `layout.cell("TOP")` | `layout.add_cell("TOP")`, `layout.cell("TOP")` |
| Select layer and datatype | `layout.layer(7, 0)` | `layout.layer(7, 0)` | `Layer(7, 0)` |
| Resolve filled geometry through hierarchy | `kdb.Region(cell.begin_shapes_rec(index))` | `RBA::Region.new(cell.begin_shapes_rec(index))` | `cell.region(Layer(7, 0))` |

KLayout returns an internal index from `layout.layer` and expresses `dbu` in micrometres. layouttk passes the file's layer pair directly and expresses `dbu_nm` in nanometres. Both write a layout with `layout.write(path)`. As a first independent check, read the output with a second reader and compare the physical grid and placed geometry. [File-exchange example](https://docs.rs/layouttk/0.4.1/layouttk/guides/interoperability/) · [CLI and agent examples](https://layouttk.readthedocs.io/en/latest/public-layouts.html)

## Files and coordinates

| Call | Result and use |
| --- | --- |
| `Layout(name, dbu_nm=1)` | Create an empty layout with the physical length of one DBU in nanometres. `Layout()` defaults to 1 nm. Use either `dbu_nm` or `dbu_meters`. Both are available as read-only properties. |
| `Layout.read(path, layers=..., top=...)` | Detect the input format, filter layer/type pairs while decoding, then retain the named root and its dependencies. Omitting both selections loads all supported content. |
| `Layout.clip_file(path, top, windows, layers=...)` | Scan a seekable input twice and return flat geometry cells named `WIN_1`, `WIN_2`, and so on. Window corners are integer DBU in the named root. Limits bound placement expansion and total output vertices. |
| `Layout.from_bytes(data, layers=...)` / `layout.to_bytes("oas")` | Decode or produce a complete in-memory file. To select a root after decoding bytes, call `extract(name)`. |
| `layout.write(path, regrid_factor=1)` | Use the output filename extension to select the encoder. A successful path-based write replaces the destination after encoding. |
| `layout.diagnostics("gds")` / `layout.check_write("gds")` | Enumerate field-level conversion issues or run the target encoder and raise on the first failure. Inspect severity, cell, element, layer and field where applicable. |
| `layout.resample(dbu_meters, rounding="exact")` | Return a new layout with the same physical geometry on the target grid. Exact resampling rejects unrepresentable coordinates. Explicit `"nearest"` rounds ties away from zero. |
| `layout.regrid(factor)` / `layout.reinterpret_dbu(dbu_meters)` | Refine the grid by an integer factor to preserve physical size, or change the physical meaning of the existing integers. |

Use `allow_external_references=True` for a deliberately incomplete input, then inspect `external_references` and resolve the targets before writing a complete file. `oas_budget_bytes` controls accounting for retained OASIS data. Decoder buffers and allocator overhead contribute additional RSS. `UnsupportedFeatureError` identifies a representation the library cannot encode or decode, `LayoutError` covers invalid layouts, and `OSError` covers filesystem errors.

## Cells, layers and placements

| Call | Result and use |
| --- | --- |
| `layout.add_cell(name)` / `layout.cell(name)` | Create or retrieve a live handle to a definition owned by this layout. |
| `layout.cell_names` / `layout.top_cells` / `layout.layers` | List defined names, roots or file layer/type pairs. `Layer(number, datatype=0)` is a tuple-like pair. Text uses its texttype as the second component. |
| `cell.elements()` / `cell.layers(recursive=False)` | Get snapshots of directly stored elements or their layer inventory. `cell.layers()` includes referenced children by default. |
| `cell.add_reference(target, origin, angle_deg=..., reflect_x=...)` | Place a name or a handle from the same layout. A regular array also takes `columns`, `rows`, `column_step` and `row_step`. |
| `layout.set_repetition(name, index, offsets)` | Set extra OASIS placements for a stored record. The original location is implicit. Duplicate offsets preserve multiplicity. Omit repetition arguments to clear it. |
| `hierarchy.dependencies(layout, name)` / `layout.extract(name)` | Find referenced definitions without expanding arrays, or return a separate layout containing the root and its dependency tree. |
| `hierarchy.import_cells(dst, src, roots, conflict="rename")` | Return the source-to-destination name mapping. The default conflict policy raises an error. Use `names`, `layers` and `text_layers` for explicit simultaneous mappings. |
| `hierarchy.placed_elements`, `labels`, `paths`, `polygons` | Traverse placed data with a depth or expansion limit. `hierarchy.tags` can inventory layers without expanding every placement. |
| `hierarchy.copy_cell`, `rename_cell`, `remove_cell`, `replace_references`, `flatten` | Edit the reference graph. Reacquire name-bound handles after rename. Review the handling of instance properties before flattening. |

On `Layer` and `LayerSet`, `+` and `|` take the union, `&` the intersection, `-` the difference, and `^` the symmetric difference of layer/type pairs. Both operands can be individual layers or sets, and the result is an immutable `LayerSet`. Pass it directly to `layers=` in `Layout.read`, `Layout.from_bytes`, `Layout.clip_file`, or the filters in `analysis`. An empty `LayerSet()` selects zero layers. `layers=None` selects all layers.

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

metal, via, dummy = Layer(67, 20), Layer(68, 20), Layer(67, 44)
selected = (metal + via + dummy) - dummy
chip = Layout.read("chip.oas", top="TOP", layers=selected)
other_layers = LayerSet(chip.cell("TOP").layers()) - metal
```

## Geometry, curves and labels

| Representation | Construction and operations | Result |
| --- | --- | --- |
| Integer cell geometry | `cell.add_polygon(points, layer=...)`, `layout.add_path(name, layer, points, width)`, `layout.add_circle(name, layer, center, radius)` | Stored records on the layout grid. A native circle is an OASIS feature. |
| Filled area | `Region.box(p0, p1)`, `cell.region(layer)`, `+` or `\|` for union, `&` for intersection, `-` for difference, `^` for XOR, `sized`, `contains` | These operators act on filled geometry. A `Region` can represent holes and can be inserted into any destination layer with `cell.add_region(result, layer=...)`. `area` is net square DBU, `bounds` is the bounding box. `polygons(max_points=...)` fractures into independently filled pieces. |
| Independent drafts | `Polygon`, `PolygonSet`, `copy`, `translate`, `rotate`, `mirror`, `scale`, `offset`, `add_to` | Affine editing can retain fractional coordinates until insertion. For these drafts grid ties round to even. [Drafting conventions](https://docs.rs/layouttk/0.4.1/layouttk/guides/polygon_drafts/) |
| Sampled contours | `rectangle`, `ellipse`, `elliptic_sector`, `regular_polygon`, `fillet`, `fracture`, `boolean`, `slice`, `inside` | Operate directly on points and rings. Use a sampling tolerance or sector vertex count when approximating curves. |
| Routes and centrelines | `Curve`, `FlexPath`, `RobustPath`, `Path`, `PolyPath`, `L1Path` and `PathBuilder` | Generate straight and curved segments, offset tracks and width profiles. Choose polygon outlines or a representable native PATH when adding routes to a cell. |
| Text | `layout.add_text(name, layer, origin, text, angle_deg=...)`, `polygon_text`, `add_polygon_text` | A label keeps its string and anchor. Polygon glyphs contribute filled material and can participate in Booleans. |

## Properties, regions of interest and output

- Attach ordered element properties with `cell.set_properties(properties, element=index)`. Use `cell.get_properties(element=index)` for readback. Omitting the element selects the cell body. `layout.set_properties(properties)` selects the file scope. A cell-name table entry can have distinct metadata.
- Use `Property.gds(attribute, payload_bytes)` for numeric GDSII element properties. Use `Property.named(name, *values)` for OASIS. `PropertyValue` and `ValueType` preserve explicit signedness, exact ratios and string kinds. A `TableRef` selects a numbered OASIS name or string entry with its own annotations.
- `analysis.query_window(layout, name, ((xmin, ymin), (xmax, ymax)))` returns complete contours with positive-area intersection in root coordinates. `analysis.clip_windows(layout, name, windows)` returns one mapping of layer to clipped `Region` per input window.
- `analysis.compare_layouts(left, right)` returns separate library, cell and per-layer XOR differences. Read `geometry_equal` for filled area and `equal` for the complete comparison. Incompatible grids can give `geometry_equal is None`. Inspect `geometry_error` and select a common physical grid.
- `write_viewer(layout, path, cell=...)` writes standalone HTML. `write_svg` writes a static drawing and `svg_fragment` produces an embeddable drawing for a cell or element. Use `GdsWriter` for streaming complete GDS definitions, `get_binary_cells` for raw structures, and `gdsii_hash` for a content hash that ignores GDS timestamps.

## NumPy, PyTorch and memory ownership

`PolygonBatch` represents a set of local polygons on a single layer as `vertices` of shape `(N, 2)` and `indptr` of shape `(P + 1,)`. Both arrays use native-endian `int64`. Polygon `i` occupies `vertices[indptr[i]:indptr[i+1]]`. Omit a duplicated closing vertex. These buffers carry neither per-element properties nor cell placements.

| Call | Ownership |
| --- | --- |
| `PolygonBatch.from_numpy(vertices, indptr, copy=False)` | Borrow compatible contiguous arrays. Request a copy for an independent batch or supported integer conversion. |
| `batch.to_numpy(copy=False)` / `batch.to_torch(copy=False)` | Return buffer views. Writable CPU tensors may share storage, so edits can be visible through the other representation. |
| `batch.to_torch(device="cuda", copy=True)` / `PolygonBatch.from_torch(points, starts, copy=True)` | Explicitly transfer both buffers. The same pattern applies to supported MPS devices. Geometry insertion takes CPU coordinates. |
| `batch.add_to(layout, name, layer)` / `PolygonBatch.from_layout(layout, name, layer)` | Insertion copies into the Rust layout. Export creates a writable snapshot of directly stored local polygons. Use a hierarchy query when placed descendants are required. |
| `PolygonBatch.from_region(cell.region(layer))` | Create a writable snapshot of placed material in root coordinates. The method fractures holes into independently filled polygons. It also accepts clipped regions from `analysis.clip_windows()`. |

## Binary images and layout windows

| Call | Result |
| --- | --- |
| `raster.add_mask(layout, cell, layer, mask, origin=(0, 0), pixel_size=1)` | Insert filled pixels as polygons in one cell and layer. The 2-D boolean or integer array uses zero for empty, nonzero for filled, and row zero at the top. `origin` is the lower-left corner in cell-local DBU. |
| `raster.to_mask(layout, cell, layer, window, pixel_size=1)` | Return a NumPy `bool` array of placed material for a window in root DBU. Both dimensions must be exact multiples of the pixel size. Rasterization samples pixel centers with half-open scanlines. |
| `raster.write_png(layout, cell, layer, window, path, pixel_size=1)` | Export the same window as a grayscale PNG with white material and a black background. The `image` extra installs Pillow and NumPy. |

For full signatures while scripting, run `help(Layout.read)`, `help(hierarchy.import_cells)` or `help(PolygonBatch.from_torch)` in your interpreter. The wheel also supplies Python typing information for editor completion.