Skip to main content

Module python_api

Module python_api 

Source
Expand description

§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 and the workflow examples.

See the illustrated Python examples on real GDSII and OASIS layouts for these API families in use, with screenshots and independent KLayout readback.

§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 · KLayout database model

TaskKLayout PythonKLayout Rubylayouttk Python
Create a databasekdb.Layout()RBA::Layout.newLayout()
Set a 1 nm DBUlayout.dbu = 0.001layout.dbu = 0.001Layout(dbu_nm=1)
Read a layoutlayout.read(path)layout.read(path)Layout.read(path)
Create or get a celllayout.create_cell("TOP"), layout.cell("TOP")layout.create_cell("TOP"), layout.cell("TOP")layout.add_cell("TOP"), layout.cell("TOP")
Select layer and datatypelayout.layer(7, 0)layout.layer(7, 0)Layer(7, 0)
Resolve filled geometry through hierarchykdb.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 · CLI and agent examples

§Files and coordinates

CallResult 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=..., keep_hierarchy=False)Scan a seekable input twice with recursive compact-array pruning and return window cells named WIN_1, WIN_2, and so on in root DBU. Set keep_hierarchy=True to preserve subcells and compact sub-arrays strictly inside a window. 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

CallResult 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.layersList 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, polygonsTraverse 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, flattenEdit 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.

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

RepresentationConstruction and operationsResult
Integer cell geometrycell.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 areaRegion.box(p0, p1), cell.region(layer), + or | for union, & for intersection, - for difference, ^ for XOR, sized, containsThese 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 draftsPolygon, PolygonSet, copy, translate, rotate, mirror, scale, offset, add_toAffine editing can retain fractional coordinates until insertion. For these drafts grid ties round to even. Drafting conventions
Sampled contoursrectangle, ellipse, elliptic_sector, regular_polygon, fillet, fracture, boolean, slice, insideOperate directly on points and rings. Use a sampling tolerance or sector vertex count when approximating curves.
Routes and centrelinesCurve, FlexPath, RobustPath, Path, PolyPath, L1Path and PathBuilderGenerate straight and curved segments, offset tracks and width profiles. Choose polygon outlines or a representable native PATH when adding routes to a cell.
Textlayout.add_text(name, layer, origin, text, angle_deg=...), polygon_text, add_polygon_textA label keeps its string and anchor. Polygon glyphs contribute filled material and can participate in Booleans.

§Mask shapes and templates from gdsCAD workflows

The shapes and templates modules use layouttk’s integer DBU, layer pairs and layout-owned cells. The table maps the drawing, editing and mask assembly workflows in the gdsCAD guide and template source.

gdsCAD workflowlayouttk API
Layout, Cell, CellReference, CellArray, GdsImportLayout.read, layout.add_cell, cell.add_reference, layout.write, hierarchy.import_cells. The destination layout owns the cell definitions and carries the physical DBU.
Boundary, Path, ElementsPolygon, PathBuilder, PolygonSet. Draft transforms can be chained. Region represents the filled union and supports Boolean operators, including shapes with holes.
Rectangle, Box, RegPolygon, RegPolylineRegion.box, shapes.box(..., width=...), regular_polygon, shapes.regular_outline(..., width=...). Outline widths are centered on the specified perimeter. An odd box width shifts the stroke centerline by half a DBU in both axes.
Disk, Circle, Ellipseshapes.disk, shapes.arc, shapes.ellipse. Angles are degrees, positive sweeps are counterclockwise, and a full annulus preserves its hole. Set either tolerance in DBU (default 0.25) or a sampling vertices budget. Use cell.add_region to insert the result on a layer.
Text, Label, LineLabel, showlayout.add_text for file annotations, add_polygon_text for printable glyphs using layouttk’s polygon font, and write_viewer or write_svg for visual output.
StripArray, AlignmentMarks, Vernierstemplates.strip_array and templates.vernier return editable PolygonSet drafts. Set the strip layer or both vernier layer pairs when constructing them and insert with add_to. templates.alignment_mark returns a cross-shaped Region; choose its layer at insertion.
Block, RangeBlock_1D, Wafer_GridStyletemplates.add_block, templates.add_range_block, templates.add_wafer_grid append references in an existing cell. Use shapes.disk, marks and text on separate process layers as needed.
Transform, split, relayer, slice, flattenDraft transforms, Layout.read(..., layers=...), hierarchy.remap_layers, slice and hierarchy.flatten.

Block windows use ordered lower-left and upper-right corners in the destination cell. A block packs one target from the lower-left margin, a range block packs one column per target in input order, and a wafer grid packs a lattice of one target inside a circular edge clearance. gap=(x, y) separates placed target bounds. Placement templates include shapes in descendants when computing a target footprint. They return instance counts and keep the definitions shared. limit bounds footprint traversal and the number of columns examined for a range block or rows examined for a wafer grid. The existing format encoders enforce file limits, including the GDSII AREF limit of 32,767 per axis.

When migrating dimensions, convert the source user units by dividing their physical length by layout.dbu_meters and quantize placement values to integer DBU. Existing top-level ellipse and elliptic_sector still return point lists. The namespaced shape helpers return Region, so a hole stays intact through Boolean operations and fracture. See the Python workflow examples.

§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.

CallOwnership
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

CallResult
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.