Note
Go to the end to download the full example code.
Defining and Importing Shapes
This example shows how to manually define two-dimensional shapes, how to import shapes import shapes from OASIS layout files and how modify those shapes.
Imports
from qtcad.builder import Builder
from qtcad.builder import Mask, Polygon, Circle
Masks
A qtcad.builder.Mask is simply a collection of two dimensional shapes with
a name and a numerical id. Grouping shapes together in a mask is
useful if those shapes will often be used at once. For example in
the Adding the gate surfaces in the
sphx_glr_auto_examples_tutorials_gated_qd tutorial we put all
the gate surfaces into one mask and then added them all at once.
- class Mask(name: str | None, shapes: list[~qtcad.builder.masks.Shape] = <factory>, id: int = -1)
A collection of multiple
Shapeinstances.- Parameters:
name – Optional name of the mask.
shapes – Shapes in the mask (optional, default is an empty list).
index – Index of the mask. (optional, will be overwritten by
qtcad.builder.Builderif-1)
As we see above, we could specify the shapes upon the creation of
the mask. Or we could add them later on using
qtcad.builder.Mask.add_shape and qtcad.builder.Mask.add_shapes.
Let us define a mask that will contain the footprint of our device.
example_mask = Mask(name="example")
Note that we don’t provide an id as qtcad.builder.Builder will
take care of assigning a unique one.
Shapes
All shapes are subclasses of the Shape class which provides a
common set of properties (such as a name), as well as transformations.
- class Shape(name: str | None = '__unset')
An abstract class representing a shape.
- auto_name() Self
Automatically set the name of this shape by inspecting the stack trace and looking for an assignment to a variable of this type. If no such assignment can be found, the name is not set.
- property bbox: tuple[float, float, float, float]
Returns: The bounding box of the shape as a four-tuple (left, right, bottom, top).
- centered() Shape
- Returns:
A copy of this shape centered at its center point. The result includes all sub-shapes with similar transformations.
- id: int = -1
The index of the shape.
Automatically assigned by
qtcad.builder.Mask.
- name: str | None = '__unset'
The name of the shape.
If no name is specified, it will be automatically assigned by inspecting the stack trace and looking for an assignment to a variable of this type. See also
Shape.auto_name.
- rotated(angle: float, center: tuple[float, float] | None = None) Shape
- Returns:
A copy of this shape rotated by
angledegrees aroundcenteror around its barycenter ifcenterisNone.
- transform(translate: tuple[float, float] = (0.0, 0.0), rotate: float | tuple[float, tuple[float, float] | None] = 0.0, scale: float = 1, center: bool = False, name: str | None = '__unset', transformer: Callable[[Shape], Shape] | None = None) Shape
Apply a series of transformations to this shape and return the resulting shape.
- Parameters:
translate – A tuple
(dx, dy)specifying the translation in x and y direction. Seetranslated.rotate – The rotation angle in degrees. If a tuple (angle, center) is given, the shape is rotated by
angledegrees aroundcenter. IfcenterisNone, the shape is rotated around its barycenter. Seerotated.scale – The scaling factor. See
scaled.center – Whether to center the shape at its barycenter. See
centered.name – The name of the new shape. If
"__unset", the name will be copied from the original shape. IfNone, the new shape will be unnamed. Seenamed. transformer: An optional callable that takes a shape and returns a transformed shape. This is applied last.
Polygons
A qtcad.builder.Polygon` is simply a collection of hull points with optional
holes:
- class Polygon(name: str | None = '__unset', hull: list[tuple[float, float]] = <factory>, holes: list[~qtcad.builder.masks.Polygon] = <factory>)
A polygon with an hull (outline) defined by the points
hullandholesthat are themselves polygons.
For the most basic form of usage we can create a polygon just by supplying points:
hole = Polygon(hull=[(0, 0), (0, 1), (1, 1)]).centered()
The above creates a polygon named “hole”, which just happens to be a
triangle. We can then take this polygon as the template to create a
bigger triangle with the “hole” shape as a hole. For convenience we
used the Shape.centered method to center the polygon.
triangle = Polygon(hull=hole.scaled(2).hull, holes=[hole])
print(triangle.name)
triangle
Note that triangle was automatically named based on the name of the variable it was assigned to above.
We can then add our shape to the example mask and load that mask into
a qtcad.builder.Builder instance. As a demonstration, we extrude a
surface based on that shape:
example_mask.add_shape(triangle)
Builder().add_mask(example_mask).extrude(2).view(
surfaces=True,
volume_labels=False,
angles=(-45, 0, 0),
save="figs/triangle_hole.svg",
zoom=0.8,
).finalize()
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
There are several constructors available to create special polygons.
First, there is qtcad.builder.Polygon.box`:
- box(width: float, height: float, *args, **kwargs)
Create a polygon box with width
widthand height theheightwith the lower left corner at (0, 0). The rest arguments and keywords are passed on the constructor ofqtcad.builder.Polygon`.
box = Polygon.box(2, 3).centered().translated(3, 0)
example_mask.add_shape(box)
Builder().add_mask(example_mask).extrude(2).view(
surfaces=True,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/triangle_and_box.svg",
font_size=20,
).finalize()
<qtcad.builder.builder.Builder object at 0x7fe14a2d51d0>
To approximate circles (or create regular polygons) qtcad.builder.Polygon.regular` can be used:
- regular(num_segments: int, radius: float = 1, *args, **kwargs)
Create a regular polygon (n-gon) that approximates a circle with
num_segmentsand radiusradius.The rest arguments are passed to the constructor for
qtcad.builder.Polygon`.
octagon = Polygon.regular(num_segments=8, radius=1).translated(6, 0)
example_mask.add_shape(octagon)
Builder().add_mask(example_mask).extrude(2).view(
surfaces=True,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/triangle_and_box_and_octa.svg",
font_size=20,
).finalize()
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
Circles
A Circle is defined by a center point and a radius:
circle = Circle(center=(9, 0), radius=1)
example_mask.add_shape(circle)
Builder().add_mask(example_mask).extrude(2).view(
surfaces=True,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/triangle_and_box_and_octa_and_circle.svg",
font_size=20,
).finalize()
/home/hiro/Documents/org/roam/code/qtcad_flake/qtcad/packages/builder/src/qtcad/builder/core/builder.py:3518: UserWarning: Removing orphaned entities: [(1, 56)]
warnings.warn(
<qtcad.builder.builder.Builder object at 0x7fe14a2d51d0>
Importing shapes from OASIS layouts
Shapes can also be imported from OASIS layout files. Layers in OASIS
files are mapped to qtcad.builder.Mask objects. To load oasis files, we use
the qtcad.builder.Builder.load_layout method:
- Builder.load_layout(file_path: str | Path, cell_name: str | None = None, name_property: str = 'name') Self
[⚡ Utility] Read the cell named
cell_name(default is the top cell) from aGDSor anOASISfilefile_pathand parse its structure. Each layer will become aqtcad.builder.Maskappropriately named and the ID from the layout file (provided there are no conflicting IDs) containing polygons for each shape found in the layer. The name of each shape is taken from the user propertyname_property. The length units in the file are assumed to be10**length_unit_exponentmeters (default is nanometres).- Parameters:
file_path – The path to the
GDSorOASISfile.cell_name – The name of the cell that the device is specified in. If
None, use the top cell.name_property – The user property that contains the name of a shape.
The example layout we are loading
here contains two layers in a cell named “fancycell”. The first one
contains triangle and the second one boxes.
Fig. 14 The layout in KLayout.
A subset of the shapes are named by setting the "builder_name"
custom property.
builder = (
Builder().load_layout("layouts/demo.oas", cell_name="fancycell").print_mask_tree()
)
Layout
├── Mask 1 "boxes"
│ ├── 0 Polygon
│ ├── 1 Polygon "named box"
│ └── 2 Polygon "another box"
└── Mask 2 "triangles"
├── 0 Polygon
└── 1 Polygon "named triangle"
As can be seen above, we loaded the two layers into appropriately named masks, each containing their requisite shapes.
builder.use_mask("triangles").extrude(100).view(
surfaces=False,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/oasis_triangles.svg",
font_size=20,
)
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
The unnamed shapes are given default names based on the mask name. Similarly, we can extrude the boxes:
builder.use_mask("boxes").set_z(0).extrude(200).view(
surfaces=False,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/oasis_boxes.svg",
font_size=20,
)
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
We can also select multiple masks at once using a list argument
in qtcad.builder.Builder.use_mask:
- Builder.use_mask(mask: int | str | Mask | Callable[[Mask], bool] | list[int | str | Mask | Callable[[Mask], bool]]) Self
[🔧 Modifier] Switch to use another mask as the working one. The
maskparameter can be either the ID or name of a mask or a function taking a mask and returningTrueif the mask is to be selected. A list of the above can also be provided (seeqtcad.builder.MaskContainer.get_mask). If multiple masks are selected, they are merged into a temporary mask.This operation also selects all shapes in the mask (see also
use_shape).- Parameters:
mask – Name or identifier (index) of the mask.
builder.use_mask(["triangles", "boxes"]).view_shapes(
save="figs/boxes_and_triangles.svg",
font_size=20,
)
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
Modifying shapes loaded into qtcad.builder.Builder
Using qtcad.builder.Builder.copy_shape, we can copy shapes
within a mask or add it to another one. While copy can also apply
arbitrary transformations to the shapes.
- Builder.copy_shape(name: str | None = '__unset', to_mask: int | str | None = None, translate: tuple[float, float] = (0, 0), rotate: float = 0, scale: float = 1, transformer: Callable[[Shape], Shape] | None = None) Self
[⚡ Utility] Copy the currently active shapes (see
use_shapes,use_mask), apply transformations (translation, rotation, scaling, …) to them and select the copies. The copies will be added to the current mask or to the mask specified byto_mask(which does not have to exist yet). See alsoqtcad.builder.masks.MaskContainer.copy_shapesandqtcad.builder.masks.Shape.transform.- Parameters:
name – The name of the new shape. If
"__unset", the name will be copied from the original shape. IfNone, the new shape will be unnamed. SeeShape.named. If multiple shapes are copied, an index is appended to the name. E.g.,"my_shape_0". Usetransformerto modify the names in a more flexible way.to_mask – If specified, the copied shapes will be added to the mask with this name or index. Otherwise, they will be added to the current mask. If the specified mask does not exist and
stris provided, a new mask will be created with this name.translate – Translation vector in the x-y plane to apply to the copied shapes. See
qtcad.builder.masks.Shape.translate.rotate – The rotation angle in degrees around the barycenter of the selected shapes. If a tuple
(angle, center)is given, the selected shapes are rotated aroundcenter(which may beNonein which case the shapes are rotated about their individual barycenters). See alsoShape.rotated.scale – Scaling factor to apply to the copied shapes. See
qtcad.builder.masks.Shape.scale.transformer – A callable that takes a shape and returns a modified shape. It is applied after the above transformations. This can be used to apply arbitrary transformations to the copied shapes. See
qtcad.builder.masks.Shape.transform. This might be useful to rename the shapes.
As a demonstration, let us copy the box shape we created above, rename, translate, scale it down and rotate it. We can then extrude the new shape and visualize the result.
builder = (
Builder()
.add_mask(example_mask)
.use_shape("box")
.extrude(1)
.copy_shape(
name="copied_box",
translate=(3, 0),
scale=0.5,
rotate=20,
transformer=lambda shape: shape.named("box_this_is_applied_last"),
)
.print_mask_tree()
.extrude(1)
.view(
surfaces=True,
volume_labels=True,
angles=(-45, 0, 0),
save="figs/transformed.svg",
font_size=20,
)
)
Layout
└── Mask 0 "example"
├── 0 Polygon "triangle"
├── 1 Polygon "box"
├── 2 Polygon "octagon"
├── 3 Circle "circle"
└── 4 Polygon "box_this_is_applied_last"
We can also remove them from the current mask using
qtcad.builder.Builder.remove_shape:
- Builder.remove_shapes() Self
[⚡ Utility] Remove the currently selected shapes from the current mask. Selects all the shapes left in the current mask.
Here we remove the shape we just copied (copying selects the copied shapes).
builder.remove_shapes().print_mask_tree()
# By passing a function to :any:`qtcad.builder.Builder.use_shapes` we can
# filter the shapes we want to use.
builder.use_shapes(
lambda shape: shape.name is not None and "box" in shape.name
).remove_shapes().print_mask_tree()
Layout
└── Mask 0 "example"
├── 0 Polygon "triangle"
├── 1 Polygon "box"
├── 2 Polygon "octagon"
└── 3 Circle "circle"
Layout
└── Mask 0 "example"
├── 0 Polygon "triangle"
├── 1 Polygon "octagon"
└── 2 Circle "circle"
<qtcad.builder.builder.Builder object at 0x7fe14a2d51d0>
We can create new masks. For example we can select shapes and copy them to a new mask.
- Builder.copy_shape(name: str | None = '__unset', to_mask: int | str | None = None, translate: tuple[float, float] = (0, 0), rotate: float = 0, scale: float = 1, transformer: Callable[[Shape], Shape] | None = None) Self
[⚡ Utility] Copy the currently active shapes (see
use_shapes,use_mask), apply transformations (translation, rotation, scaling, …) to them and select the copies. The copies will be added to the current mask or to the mask specified byto_mask(which does not have to exist yet). See alsoqtcad.builder.masks.MaskContainer.copy_shapesandqtcad.builder.masks.Shape.transform.- Parameters:
name – The name of the new shape. If
"__unset", the name will be copied from the original shape. IfNone, the new shape will be unnamed. SeeShape.named. If multiple shapes are copied, an index is appended to the name. E.g.,"my_shape_0". Usetransformerto modify the names in a more flexible way.to_mask – If specified, the copied shapes will be added to the mask with this name or index. Otherwise, they will be added to the current mask. If the specified mask does not exist and
stris provided, a new mask will be created with this name.translate – Translation vector in the x-y plane to apply to the copied shapes. See
qtcad.builder.masks.Shape.translate.rotate – The rotation angle in degrees around the barycenter of the selected shapes. If a tuple
(angle, center)is given, the selected shapes are rotated aroundcenter(which may beNonein which case the shapes are rotated about their individual barycenters). See alsoShape.rotated.scale – Scaling factor to apply to the copied shapes. See
qtcad.builder.masks.Shape.scale.transformer – A callable that takes a shape and returns a modified shape. It is applied after the above transformations. This can be used to apply arbitrary transformations to the copied shapes. See
qtcad.builder.masks.Shape.transform. This might be useful to rename the shapes.
(
builder.use_shape("triangle")
.copy_shape(to_mask="only_triangle")
.print_mask_tree()
.finalize()
)
Layout
├── Mask 0 "example"
│ ├── 0 Polygon "triangle"
│ ├── 1 Polygon "octagon"
│ └── 2 Circle "circle"
└── Mask 1 "only_triangle"
└── 0 Polygon "triangle"
<qtcad.builder.builder.Builder object at 0x7fe14a2d51d0>
Using qtcad.builder.Builder.copy_mask, we can also copy entire
masks. Below, we copy the “example” mask to a new mask
“example_copy”, applying some transformations in the process:
- Builder.copy_mask(new_name: str, **kwargs) Self
[⚡ Utility] Copy current mask to an empty mask named
new_name, set the current mask to this newly created one and select all shapes in the new mask.For the keyword arguments see
copy_shape. This method is equivalent touse_mask(current_mask).copy_shape(to_mask=new_name, **kwargs).
Note that the same effect could have been achieved by using
qtcad.builder.Builder.use_mask followed by
qtcad.builder.Builder.copy_shape.
example_mask = Mask(name="example")
example_mask.add_shapes([triangle, octagon, circle])
Builder().add_mask(example_mask).use_mask("example").extrude(0.1).copy_mask(
"example_copy", scale=1.2, name="copy", rotate=20, translate=(0, 1)
).print_mask_tree().set_z(2).extrude(0.1).view(
surfaces=True,
volume_labels=True,
angles=(-60, 0, 0),
save="figs/copied_mask.svg",
font_size=15,
)
/home/hiro/Documents/org/roam/code/qtcad_flake/qtcad/packages/builder/src/qtcad/builder/core/builder.py:3518: UserWarning: Removing orphaned entities: [(1, 44)]
warnings.warn(
Layout
├── Mask 0 "example"
│ ├── 0 Polygon "triangle"
│ ├── 1 Polygon "octagon"
│ └── 2 Circle "circle"
└── Mask 1 "example_copy"
├── 0 Polygon "copy_0"
├── 1 Polygon "copy_1"
└── 2 Circle "copy_2"
/home/hiro/Documents/org/roam/code/qtcad_flake/qtcad/packages/builder/src/qtcad/builder/core/builder.py:3518: UserWarning: Removing orphaned entities: [(1, 44)]
warnings.warn(
/home/hiro/Documents/org/roam/code/qtcad_flake/qtcad/packages/builder/src/qtcad/builder/core/builder.py:3518: UserWarning: Removing orphaned entities: [(1, 44)]
warnings.warn(
/home/hiro/Documents/org/roam/code/qtcad_flake/qtcad/packages/builder/src/qtcad/builder/core/builder.py:3518: UserWarning: Removing orphaned entities: [(1, 44), (1, 89)]
warnings.warn(
<qtcad.builder.builder.Builder object at 0x7fe14a2d7250>
Note, that the names of the copied shapes have been automatically disambiguated by appending numbered suffixes.
Total running time of the script: (0 minutes 25.285 seconds)