layouttk 0.4.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
# GDSII and OASIS command-line tools

Download and unpack the command-line archive for Linux x86_64, macOS arm64, or Windows x64. It runs without installing Python or Rust. On an internal network, use the archive your team has imported. The examples use layouttk 0.4.1. [Release downloads](https://github.com/zwh42/layouttk/releases/latest)

## Extract one layer from an existing layout

1. If your team has already installed `layouttk`, open a terminal in the folder containing your layout and use the commands below as written. If you unpacked the archive yourself, copy your layout file into the unpacked folder and open a terminal there. Start each command with `./layouttk` on Linux or macOS, or `.\layouttk.exe` in Windows PowerShell.
2. Run `layouttk --version` to check that it starts. Then run `layouttk inventory chip.oas`, replacing `chip.oas` with your filename. Put filenames that contain spaces in double quotes. In the results, `top_cells` lists top cells and `shape_layers` lists layers containing shapes. Each layer has a `number` and a `datatype`.
3. Run the command below. Replace `TOP` and `7/0` with the top cell and layer pair you want. `metal.gds` is the output file. Choose a filename that is free to use.

   ```sh
   layouttk extract chip.oas metal.gds --top TOP --layer 7/0
   ```

4. Look for `metal.gds` in the same folder. Run `layouttk inventory metal.gds` to check its layer, or open it in KLayout to check the shapes. If you cannot find the output, check the filename, top cell and layer against the inventory.

Run `layouttk --help` for other commands or `layouttk extract --help` for options for this command.

## Practice with a sample layout

Try three complete tasks with the standalone CLI. Extract a layer for delivery, clip a photonics window, or locate a difference between two candidate deliveries. Unpack the examples and open `layouttk/references/workflows.en.md`. Each exercise includes a sample request for a coding agent, commands to copy, and the results to check. [Download the offline examples](https://zwh42.github.io/assets/files/layouttk-agent-examples.zip)

## Other ways to install

With Rust installed, you can run `cargo install layouttk --locked`.

On Apple Silicon macOS or Linux x86_64, Homebrew can install the prebuilt CLI from the project tap.

```sh
brew tap zwh42/layouttk https://github.com/zwh42/layouttk
brew install zwh42/layouttk/layouttk
```

## Linux x86_64 baseline

Choose the `x86_64-unknown-linux-musl.tar.gz` archive for older x86_64 Linux systems. It is a statically linked executable with the original x86-64 instruction baseline, including SSE2. It requires neither AVX/AVX2 nor a system glibc or musl installation. Unpack the archive and run its `layouttk` executable directly.

The Linux CLI release check boots Debian Wheezy's Linux 3.2.0-4-amd64 kernel in QEMU with the newer instruction features disabled. It verifies GDSII creation, OASIS layer extraction, comparison, window clipping, and inventory. The CPython wheel has its own platform requirements. [Linux baseline download](https://github.com/zwh42/layouttk/releases/latest) · [QEMU CPU models](https://www.qemu.org/docs/master/system/qemu-cpu-models.html)

## Create a hierarchical layout

Save the following as `mask.json`. The parent places `PAD` on a one-nanometre grid. Coordinates are integer DBU and layers are `[layer, datatype]`.

```json
{
  "version": 1,
  "name": "MASK",
  "dbu_nm": 1,
  "cells": [
    {"name": "TOP", "elements": [
      {"kind": "reference", "target": "PAD", "origin": [300, -100]}
    ]},
    {"name": "PAD", "elements": [
      {"kind": "rectangle", "layer": [67, 20], "corner1": [0, 0], "corner2": [100, 40]}
    ]}
  ]
}
```

```sh
layouttk create mask.json mask.oas
layouttk create - mask.gds < mask.json
layouttk inspect mask.oas
```

`create` accepts a JSON file or standard input (`-`). The output extension selects GDSII or OASIS. A cell may refer to another definition later in the same request. Omitting the cell's `elements` creates an empty definition. GDSII stores `name` as the library name. OASIS reads back with the name `LIBRARY`.

Provide one positive grid spacing. Use `dbu_nm` for nanometres per DBU. Version-1 input with `dbu_meters` remains accepted.

| `kind` | Required fields | Optional fields |
| --- | --- | --- |
| `rectangle` | `layer`, `corner1`, `corner2` | |
| `polygon` | `layer`, `points` with an implicit closing edge | |
| `path` | `layer`, `points`, nonnegative `width` in DBU | |
| `circle` | `layer`, `center`, `radius` in DBU, for OASIS output | |
| `text` | `layer` with texttype as its second item, `origin`, `text` | |
| `reference` | `target`, `origin` | `angle_deg` (default `0`), `reflect_x` (default `false`), `magnification` (default `1`), `array` |

An `array` contains `columns`, `rows`, `column_step`, and `row_step`. Steps are vectors in the containing cell's coordinates. A path in this short format has flush ends. Use `model export` to see the full stored record structure, including end styles, label styles, typed properties, and other repetitions.

## Inspect, extract, and convert

```sh
layouttk inspect mask.oas
layouttk extract mask.oas metal.gds --top TOP --layer 67/20
layouttk check metal.gds --to oas --json
layouttk convert metal.gds metal.oas
```

- `inspect` prints JSON with `dbu_meters`, `top_cells`, `layers`, and stored counts. A compact array counts as one stored record.
- `extract` applies layer selection while decoding, then keeps the selected root and its dependencies. Repeat `--layer` to retain several layer/type pairs.
- `check --json` reports `can_write` and field-level diagnostics. A failed check exits nonzero. Parse JSON from stdout and read stderr for the process error.
- `create`, `extract`, and `convert` use the target encoder before replacing the destination. To encode a flush path with an odd total width in OASIS, use `--regrid-factor 2` to keep the physical size while doubling integer coordinates.

Use `--oas-budget-bytes` to set the OASIS retained-data budget for input. See the [KLayout read-back example](https://docs.rs/layouttk/0.4.1/layouttk/guides/interoperability/) for an independent geometry check. Query windows, compare geometry by XOR, and make pixel masks with the [Python workflows](https://docs.rs/layouttk/0.4.1/layouttk/guides/python_workflows/) and [binary image tutorial](https://docs.rs/layouttk/0.4.1/layouttk/guides/raster_images/).

## Inventory and verify a handoff

```sh
layouttk inventory mask.oas --top TOP --layer 67/20
layouttk verify mask.gds mask.oas --left-top TOP --right-top TOP --layer 67/20
```

`inventory` retains the reference graph and counts shapes and text while decoding. Omitting `--top` reports all definitions and unresolved names. Selecting a root reports its dependency closure. Layer summaries distinguish geometry from text, and occurrence counts account for repetitions local to each definition. They do not count globally expanded descendants.

`verify` compares the selected dependency trees on compatible physical grids. It compares stored records by cell name and category in their stored order, and separately reports placed mask XOR by layer. Different cell names or record representations can yield different stored results with equal placed material. Grid incompatibility requires explicit resampling before verification. Paths and circles are outlined at `--tolerance-dbu`, and `--limit` bounds each expansion when the placed geometry must be evaluated.

Both commands report `schema_version`, `status`, and `report` in JSON. Verification exits successfully on `equal` and exits nonzero on `different` or an operational `error`. Argument validation errors are reported by the CLI parser.

## Clip windows from a large file

```sh
layouttk clip mask.oas clips.oas --top TOP --layer 67/20 \
  --window=300,-100,350,-60 --window=650,0,700,200
```

Corners are ordered `x0,y0,x1,y1` in root DBU. A seekable source is scanned twice. The first pass retains the graph and the second keeps clipped output. Output is one atomically replaced file with independent, flat polygon cells `WIN_1`, `WIN_2`, and so on. Original coordinates are preserved. Empty and repeated windows retain their positions in the JSON report. Polygon output represents filled material. Paths and circles are outlined, arrays are expanded up to `--placement-limit`, and labels and source properties are omitted.

Use `--output-vertex-limit` to limit the total stored output across windows. The source still needs space for graph, name tables and decoder buffers. Very large compact arrays may exceed the placement limit, even for a small window. Use the in-memory `analysis.clip_windows` for already loaded layouts and `extract` for hierarchy-preserving layer selection.

## Find a command for your task

Run `layouttk --help` for the commands in your installed version. For a particular task, run the command with `--help` to see what to enter, a copyable example, and what the result means. For example, `layouttk geometry offset --help` shows the JSON for growing or shrinking shapes. Use `layouttk create -h` or `layouttk edit -h` for a short reminder.

On an internal network, run `layouttk guide --lang en` for this guide or `layouttk guide --lang zh-CN` for Simplified Chinese. An agent can run `layouttk describe --json` for the command index, or `layouttk describe --json query bounds` for just one command’s options and example.

| What you want to do | Command |
| --- | --- |
| Combine two layers or cut one from another | `boolean` for two layout files. Use `--op union`, `intersection`, `difference`, or `xor`. |
| Draw polygons, generate curves and tracks, or calculate on coordinates | `geometry` with one method and a JSON request. Use `-` as the filename to read from standard input. |
| Find the size, area, layers, references, or labels in a cell | `query bounds`, `area`, `layers`, `dependencies`, `reference-boxes`, or `elements --kind label`. |
| Get whole shapes that overlap a window or exchange packed polygon arrays | `query window` keeps the full outlines. `query polygons` returns `vertices` and `indptr`. Use `clip` to trim shapes at the edge of the window. |
| Rename, import, or flatten cells, map layers, or change properties and repetitions | `edit` takes an ordered list of changes. Run `layouttk edit --help` for all operation names and fields. |
| Save or restore the full set of stored records | `model export` and `model import` exchange versioned JSON, including typed properties and compact repetitions. |
| Change grid spacing | `resample` keeps physical size. `reinterpret-dbu` changes physical size and keeps the coordinate numbers. Both take `--dbu-nm`. |
| Build a layout from a black-and-white mask or view a layout window as pixels | `raster add-mask`, `raster to-mask`, or `raster png`. Row 0 is the top of the image. |
| Share a drawing that opens in a browser | `view svg`, `view html`, or `view fragment`. The HTML preview includes layer toggles. |
| Check GDSII units or compare content across timestamp changes | `gds units`, `gds index`, `gds hash`, and `gds timestamp`. Use `gds --help` for binary cell and record operations. |

### Combine two layers and open the result

This subtracts layer `8/0` in `b.oas` from layer `7/0` in `a.oas` and writes one flat `TOP` cell on layer `7/0` in `result.gds`. Set the top cell and layer pair separately for each input. The two files must use the same grid. The output contains filled polygons.

```sh
layouttk boolean a.oas b.oas result.gds --op difference --left-top TOP --right-top TOP --left-layer 7/0 --right-layer 8/0 --output-layer 7/0
layouttk inventory result.gds
layouttk view html result.gds result.html --cell TOP
```

Open `result.gds` in KLayout or `result.html` in a browser. If the subtraction leaves no material, `TOP` still exists and the result has zero polygons.

### Automation reference

Use `--format json` before or after a subcommand to get one JSON document on stdout. For example, `layouttk --format json extract chip.oas metal.gds --top TOP --layer 7/0` reports the written path in `report.file`. Successful reads put their data in `report`. For `check`, the same field holds `can_write` and `diagnostics`. For `model export` without `--output`, it holds the model document. Diagnostics also go to stderr.

| `status` | Exit code | Meaning |
| --- | --- | --- |
| `ok` | 0 | The command completed. |
| `equal` | 0 | Both stored records and placed geometry matched in `verify`. |
| `different` | 1 | `verify` completed and found a difference. |
| `error` | 1 or 2 | Processing failed (1) or the command arguments were invalid (2). Read `report.code` and `report.message`. |

The envelope uses `schema_version: 1`. Direct `--help` and `--version` still print text. Omitting `--format json` uses each command’s existing output. For example, `check --json` returns the preflight object directly, plain `model export` returns a document that can be piped into `model import -`, and `extract` is quiet on success. The command index reports the applicable conventions in `report.cli.stdin` and `report.cli.stdout`.

Most point lists are `[x,y]` pairs. `model` and `query elements` use the structured record representation, with coordinates as objects and explicit property value types. `query polygons --placed` packs unioned material as independent filled polygons. `edit` can insert the packed result using `add_packed_polygons`; each ring starts at an entry in `indptr`, the first entry is zero and the last is the vertex count. Model JSON and polygon arrays are file exchange formats. NumPy, PyTorch, DLPack object sharing, and user-supplied function callbacks are in-process Python or Rust APIs. Sampled coordinates and profiles can be passed to CLI geometry methods.

The built-in preview expands placements up to `--limit`. SVG is a drawing of placed geometry and labels. The raster commands sample pixel centers in the chosen cell coordinates and require the window dimensions to be multiples of `--pixel-size`. Large requests are subject to expansion and image budgets. Use `clip` to extract an area first if you only need a small part of a large file.

### Run a sequence of commands

Save these three JSON lines as `job.jsonl`. Each `args` array starts with the subcommand. Pass filenames with spaces as a single string and omit the executable name.

```json
{"id":"create","args":["create","-","chip.oas"],"input":{"version":1,"name":"MASK","dbu_nm":1,"cells":[{"name":"TOP","elements":[{"kind":"rectangle","layer":[7,0],"corner1":[0,0],"corner2":[100,40]}]}]}}
{"id":"extract","args":["extract","chip.oas","metal.gds","--top","TOP","--layer","7/0"]}
{"id":"verify","args":["verify","chip.oas","metal.gds"]}
```

```sh
layouttk batch job.jsonl > results.jsonl
```

Read `results.jsonl` one record at a time. In this example the statuses are `ok`, `ok`, and `equal`. Each result carries its one-based source `line` and optional request `id`. A command gets its own optional JSON `input` as stdin when its input argument is `-`. Omit the batch filename or use `batch -` to receive requests from stdin. Paths are relative to the current working directory. The batch’s `--oas-budget-bytes` is inherited unless a request supplies its own.

The process exits 1 if any request fails or reports `different`. By default it stops on the first such result. With `--keep-going` it continues, and earlier successful writes remain available in either case. Blank lines are skipped. Each line is limited to 1 MiB, including its newline. Pass a file path for larger inputs. Nested batches are invalid. If the request stream itself cannot be opened or read, the diagnostic goes to stderr and the batch exits 1.