# Getting started with layouttk
This tutorial makes a small mask, saves it in both GDSII and OASIS, and checks the result. It needs no sample file, display server or optional Python dependency.
## Install the library
Use GIL-enabled CPython 3.11 or newer. Wheels are available for Linux x86-64 (glibc 2.28+), Apple Silicon macOS and 64-bit x86 Windows. In a virtual environment run the following commands.
```sh
python -m pip install layouttk
python -c "import layouttk; print(layouttk.__version__)"
```
For array exchange, install `python -m pip install "layouttk[numpy]"` or `python -m pip install "layouttk[torch]"`. For an independent reader, install `python -m pip install klayout gdstk`. The command-line executable is installed separately via `cargo install layouttk --locked`. Rust applications can use `cargo add layouttk`.
## Create your first layout
A **layout** owns named cell definitions. A **layer** is a pair of file numbers. Here `(7, 0)` means physical layer 7, datatype 0. A **reference** places one cell inside another. Coordinates in a cell are local to its definition.
Save this example as `first_mask.py` and run `python first_mask.py` in an empty directory. It writes `mask.gds` and `mask.oas`. If either filename already exists, choose another directory.
```python
from layouttk import Layer, Layout, Region
metal = Layer(7, 0)
mask = Layout("FIRST_MASK", dbu_meters=1e-9)
pad = mask.add_cell("PAD")
pad.add_region(Region.box((0, 0), (1000, 500)), layer=metal)
top = mask.add_cell("TOP")
top.add_reference(pad, (2000, 3000))
for filename in ("mask.gds", "mask.oas"):
mask.write(filename)
restored = Layout.read(filename)
assert restored.top_cells == ["TOP"]
assert restored.cell("TOP").layers() == (metal,)
expected = Region.box((2000, 3000), (3000, 3500))
assert not (restored.cell("TOP").region(metal) ^ expected)
print("PAD: 1.0 × 0.5 µm; TOP: one placed pad")
```
The DBU in this example is one nanometre. The rectangle measures 1 × 0.5 µm and has an area of 500,000 square DBU, or 0.5 µm². The exclusive-or (XOR) of two identical regions is empty. The coordinate check also catches a shape of the right area placed at the wrong location.
## Inspect the result
Open either file in KLayout and select `TOP`. The lower-left corner should be at (2, 3) µm. In Python, read `layout.cell_names` for definitions, `layout.top_cells` for roots, and `layout.cell("TOP").elements()` for directly stored records. Here the top cell stores one reference. Its rectangle lives in `PAD`. A recursive region query applies the placement and returns the filled material in the top cell's coordinate system.
With the CLI installed, run these commands in the directory containing the example output.
```sh
layouttk inspect mask.oas
layouttk extract mask.oas metal.gds --top TOP --layer 7/0
layouttk check metal.gds --to oas
```
The first command prints a JSON inventory. The second keeps the selected layer and both cell definitions. The third checks that the GDSII result can be written as OASIS. Add `--json` to `check` for individual diagnostics.
## Look up a familiar operation
| Create a library and choose its grid | `kdb.Layout()`, `ly.dbu = 0.001` (µm) | `GdsLibrary(unit=1e-6, precision=1e-9)` | `Layout(dbu_meters=1e-9)` |
| Define a cell | `ly.create_cell("PAD")` | `lib.new_cell("PAD")` | `mask.add_cell("PAD")` |
| Address a drawing layer | `ly.layer(7, 0)` returns an internal index | `layer=7, datatype=0` | `Layer(7, 0)` is the file pair |
| Draw the tutorial pad | `shapes(i).insert(kdb.Box(0, 0, 1000, 500))` on a cell | `cell.add(gdspy.Rectangle((0, 0), (1, 0.5), layer=7))` at the units above | `pad.add_region(Region.box((0, 0), (1000, 500)), layer=metal)` |
| Place a cell | `CellInstArray` and `Trans` | `CellReference` | `top.add_reference(pad, (2000, 3000))` |
| Get recursive geometry | `kdb.Region(cell.begin_shapes_rec(i))` | `cell.get_polygons(by_spec=True)` | `top.region(metal)` for a union or `hierarchy.polygons` for individual contours |
| Open and save a mask | `ly.read(path)`, `ly.write(path)` | `GdsLibrary(infile=...)`, `lib.write_gds(...)` | `Layout.read(path)`, `mask.write(path)` |
The KLayout column uses integer database coordinates. gdspy drawing arguments use the library's user unit. A coordinate of `1` in the gdspy example corresponds to `1000` DBU here. For original usage and concepts see the [KLayout database guide](https://www.klayout.de/doc/programming/database_api.html) and [gdspy getting started](https://gdspy.readthedocs.io/en/stable/gettingstarted.html).
## Choose your next operation
| Read an existing mask | `Layout.read(path, top="TOP", layers=[metal])` | Get the actual names and layer pairs from an inventory first. Selected definitions can be empty. |
| Draw separate shapes and transform them | `Polygon`, `PolygonSet`, `ellipse`, `elliptic_sector`, `fillet` | Drafts can carry fractional coordinates until insertion. |
| Draw a route or waveguide | `FlexPath` for a polyline, `RobustPath` for variable profiles, `Curve` for a centreline | State the sampling tolerance in DBU. Inspect the outlines when bends or width vary. |
| Compute Boolean geometry | `a \| b`, `a & b`, `a - b`, `a ^ b` on `Region` | Region area measures unioned material. Use `hierarchy.area_by_layer` for the sum over individual shapes. |
| Attach labels or properties | `Layout.add_text`, `Property.gds`, `Property.named`, `Cell.set_properties` | TEXT marks a location. Use `add_polygon_text` for glyphs that must become mask material. Choose the property owner explicitly. |
| Replicate, merge or rename cells | `Cell.add_reference`, `Layout.set_repetition`, `hierarchy.import_cells`, `hierarchy.rename_cell` | Inspect name mappings and grid conversion when importing. Offsets are in the parent's coordinate system for placements. |
| Inspect changes or cut a window | `analysis.compare_layouts`, `query_window`, `clip_windows` | A query selects complete intersecting contours. A clip trims them at the boundary. |
| Exchange memory or arrays | `Layout.to_bytes`, `Layout.from_bytes`, `PolygonBatch` | Pass the file format when producing bytes. Packed polygon data needs vertices and ring boundaries. |
| See or share a result | `write_viewer` for offline HTML, `write_svg` or `svg_fragment` for a drawing | Choose a cell and control hierarchy depth on large designs. |
| Work with GDSII records directly | `GdsWriter`, `cell_bytes`, `element_bytes`, `get_gds_units`, `gdsii_hash` | Use record hashes for content checks and per-layer XOR for filled geometry. |
| Use Rust | `read`, `ReadOptions`, `Layout::retain_tree`, `check_write`, `write` | The Rust API and CLI use the same readers and encoders. [Rust API reference](https://docs.rs/layouttk/0.1.1/layouttk/) |
## Troubleshooting a first script
- **An extraction looks empty.** Inspect `top_cells` and `layers` before selecting. `(7, 0)` and `(7, 1)` select different records. Ask the right parent for a recursive region. Text labels carry no filled area.
- **The drawing is a thousand times too large or small.** Print `dbu_meters`. Convert integer coordinates to µm by multiplying by `dbu_meters * 1e6`. To change grids while preserving physical size, call `resample`. Use `reinterpret_dbu` only if you intend to change the physical scale.
- **A GDSII path fails to export to OASIS.** Inspect `layout.diagnostics("oas")`. A path with an odd full width in DBU needs a half-DBU for its OASIS half-width. For that diagnostic, `write(path, regrid_factor=2)` preserves its physical dimensions. Other diagnostics need their own remedy.
- **A NumPy array or tensor cannot be shared.** Check CPU placement, integer dtype, contiguity and writability. Request `copy=True` when conversion or a device transfer is intended.
- **A selected array is too large to expand.** Inspect references, layer pairs and compact bounds first. A call to `region` needs the placed contours. A layer filter can reduce the retained shapes before that operation.
Look up signatures and ownership in the [Python API reference](https://docs.rs/layouttk/0.1.1/layouttk/guides/python_api/). Continue with [executable Python recipes](https://docs.rs/layouttk/0.1.1/layouttk/guides/python_workflows/), [polygon drafting and rounding](https://docs.rs/layouttk/0.1.1/layouttk/guides/polygon_drafts/) or the [gdspy migration reference](https://docs.rs/layouttk/0.1.1/layouttk/guides/gdspy_coverage/).