Skip to main content

Module getting_started

Module getting_started 

Source
Expand description

§Create GDSII and OASIS layouts in Python

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.

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.

from layouttk import Layer, Layout, Region

metal = Layer(7, 0)
mask = Layout("FIRST_MASK", dbu_nm=1)
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.

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

TaskKLayout Pythongdspylayouttk
Create a library and choose its gridkdb.Layout(), ly.dbu = 0.001 (µm)GdsLibrary(unit=1e-6, precision=1e-9)Layout(dbu_nm=1)
Define a cellly.create_cell("PAD")lib.new_cell("PAD")mask.add_cell("PAD")
Address a drawing layerly.layer(7, 0) returns an internal indexlayer=7, datatype=0Layer(7, 0) is the file pair
Draw the tutorial padshapes(i).insert(kdb.Box(0, 0, 1000, 500)) on a cellcell.add(gdspy.Rectangle((0, 0), (1, 0.5), layer=7)) at the units abovepad.add_region(Region.box((0, 0), (1000, 500)), layer=metal)
Place a cellCellInstArray and TransCellReferencetop.add_reference(pad, (2000, 3000))
Get recursive geometrykdb.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 maskly.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 and gdspy getting started.

§Choose your next operation

GoalStarting pointWhat to check
Read an existing maskLayout.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 themPolygon, PolygonSet, ellipse, elliptic_sector, filletDrafts can carry fractional coordinates until insertion.
Draw a route or waveguideFlexPath for a polyline, RobustPath for variable profiles, Curve for a centrelineState the sampling tolerance in DBU. Inspect the outlines when bends or width vary.
Compute Boolean geometrya | b, a & b, a - b, a ^ b on RegionRegion area measures unioned material. Use hierarchy.area_by_layer for the sum over individual shapes.
Attach labels or propertiesLayout.add_text, Property.gds, Property.named, Cell.set_propertiesTEXT marks a location. Use add_polygon_text for glyphs that must become mask material. Choose the property owner explicitly.
Replicate, merge or rename cellsCell.add_reference, Layout.set_repetition, hierarchy.import_cells, hierarchy.rename_cellInspect name mappings and grid conversion when importing. Offsets are in the parent’s coordinate system for placements.
Inspect changes or cut a windowanalysis.compare_layouts, query_window, clip_windowsA query selects complete intersecting contours. A clip trims them at the boundary.
Exchange memory or arraysLayout.to_bytes, Layout.from_bytes, PolygonBatchPass the file format when producing bytes. Packed polygon data needs vertices and ring boundaries.
See or share a resultwrite_viewer for offline HTML, write_svg or svg_fragment for a drawingChoose a cell and control hierarchy depth on large designs.
Work with GDSII records directlyGdsWriter, cell_bytes, element_bytes, get_gds_units, gdsii_hashUse record hashes for content checks and per-layer XOR for filled geometry.
Use Rustread, ReadOptions, Layout::retain_tree, check_write, writeThe Rust API and CLI use the same readers and encoders. Rust API reference

§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. Continue with executable Python recipes, polygon drafting and rounding or file exchange with gdspy, gdstk and KLayout.