qtcad.builder package
This package provides the qtcad.builer.Builder class which is the main interface to
builder.
Also available are qtcad.builder.Polygon` to create two-dimensional shapes that can be added to
layouts contained in instances of qtcad.builder.Mask. Masks can then be used in
qtcad.builer.Builder.
The MeshAlgorithm2D and MeshAlgorithm3D enums are used to specify the
meshing algorithm in qtcad.builer.Builder.mesh.
- class Builder(name: str = 'builder', length_unit_exponent: int = -9, gmsh_log_level: int = 30)
Bases:
BuilderGenerates three dimensional Gmsh models from two dimensional shapes (see
qtcad.builder.masks.Shape,load_layout).- Parameters:
name – The name of the Gmsh model to be generated.
length_unit_exponent – Defines the scaling factor with respect to meter. E.g.
-9for nanometre. This is used to adjust the scaling when importing layouts.gmsh_log_level – Controls verbosity level for Gmsh output. By default, it is
logging.WARNbecause of the large volume of Gmsh-related output. You may wish to set this higher e.g. when diagnosing issues.
Interface
The basic workflow is inspired by physical fabrication steps. The API uses the builder pattern with methods returning
selfto allow chaining of method calls. The idea is to sequentially create three dimensional geometries from two-dimensional shapes (selected from a collection stored within the generator), while controlling how the newly created geometries are integrated into the existing model.The z-coordinate is controlled semi-manually (see
set_z,set_z_from_group,save_zandextrude), whereas the x-y coordinates are taken from the two-dimensional shapes. The x-y plane can be changed by usingrotate_modelandtranslate_model.Devicegen does not load or write to the global Gmsh options to ensure reputability.
There are three types of methods.
Modifiers
First, there are methods that modify the behaviour of operations:
set_mesh_size: Set the local mesh size for elements added after this point in units set by thelength_unit_exponent(seeqtcad.builer.Builder). Note that the mesh size may be chosen smaller due toset_min_elements.use_all_masks: Select all masks and merge them into one temporary mask.use_mask: Switch to use another mask as the working one. Themaskparameter 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.use_shapes: Select shapes in the current mask that will be used for all following operations.set_z_from_group: Set the current z-coordinate to the top (default) or bottom of the bounding box of the entities in the group namedgroup_name. Optionally, anoffsetcan be provided to shift the z-coordinate up (positive offset) or down (negative offset).set_z: Set the z-coordinate used as the basis for operations.set_min_elements: Ensure that all subsequently created volumes will have at leastmin_elementsmesh elements (triangles, tetrahedra) along their narrowest dimension. If set toNone, the mesh size set byset_mesh_sizewill be used.use_mode: Set the strategy for handling intersecting geometries for the dimensionsdim. Currently, this setting is only relevant for dimensions2and3.fill_mode: When creating new entities, inherit the physical groups where the new entities intersect with the old ones.displace_mode: When creating new entities, override the physical groups where the new entities intersect with the old ones to correspond to the physical group of the new elements.overlay_mode: Likefill_mode, but instead of inheriting the group from the intersecting entities the intersecting elements will be added to physical groups named like[intersecting_group].[new_entity_group].inherit_mesh_size: For all subsequently generated entities, inherit the mesh size of the existing intersecting entity of the same dimension with the smallest mesh size. If there are no intersecting elements, the mesh size set withset_mesh_sizeis used.override_mesh_size: For all subsequently generated entities, use the mesh size set withset_mesh_sizeand override the mesh size in the intersections with the existing geometry.minimum_mesh_size: For all subsequently generated entities, use the mesh size set withset_mesh_sizeand take the minimum of the set mesh size and the existing mesh size in the intersections with the existing geometry.set_group_name: Any entities created after calling this method will be assigned to the physical group with namename.group_from_mask: Any entities created after calling this method will be assigned to a physical group that is named according to the name of the mask they belong to.group_from_shape: Any entities created after calling this method will be assigned to a physical group that is named according the name of the shape that the entity is created from.set_geometry_tolerance: Set the geometry tolerance used by Gmsh when determining whether two points are identical. The default is1e-8length units.set_match_mesh_tolerance: Set the tolerance used when matching mesh nodes to geometry points. The default is1e-6length units. This doesn’t seem to have much effect in practice.number_hull_surfaces: Enable or disable automatic numbering of hull surfaces bounding volumes created during operations such asextrude,growandpad_volume. IfenableisNone, the setting is toggled.differentiate_hull_surfaces: Enable or disable differentiation of hull surfaces created during operations such asextrude,growandpad_volume. IfenableisNone, the setting is toggled.
Operations
Second, there are methods that perform constructive or destructive operations on the model:
add_surface: Add surfaces based on the the currently selected shapes to the model at the current z-coordinate.extrude: Create a solid extrusion of a plane shape of heightheightat the currentz_coordinate. Also advances the currentz_coordinatebyheight. The resulting surfaces are automatically named using the current naming strategy by appending the suffixesEXTRUSION_SURF_SUFFIXES.deposit_surface: Add the currently selected shapes as surfaces on top of the model, following the contours of the top surface. IfnoclipisTrue, then the surface is not clipped and can extend past the currently selected shapes.deposit: Deposit the currently selected shape(s) into the model up from the current z coordinate byheightlength units. This is done by adding new material atop the topmost surfaces of the model. Ifnoclip=True, the new material is deposited on the whole top surface of the model, rather than clipped by the currently selected shapes.grow: Emulate a physical ‘growth’ operation to add material to the current topmost volumes. In contrast todeposit, this will not only add material to the top of the volumes but also to their sides. The currently active shapes are used to horizontally clip the new volumes unlessnoclipisTrue.pad_volume: Add a padding layer ofthicknessaround the volumes in volume group with namegroup_name. The newly created padding volume will be namedgroup_name + padding_suffixand clipped horizontally by the currently selected shapes unlessnoclipisTrue.cut: Cut the currently selected shape(s) into the model up from the current z coordinate down bydepthlength units. Ifnoclip=True, the cutting is performed on the whole model rather than clipped by the selected shapes.etch: Etch the currently selected shape(s) into the model up from the current z coordinate down bydepthlength units. This is done by cutting into each top surface. IfnoclipisTrue, then the surface is not clipped to the currently selected shapes.translate_model: Translate the whole model by the vectorvec. The z-coordinate is updated by the z-component ofvec.rotate_model: Rotate the model around its centre of mass (or the point specified byaround) by a givenanglein degrees on a a specifiedaxis. The z-coordinate is updated to the new top of the model.import_model: Import a Gmsh model from filefile_path. The model can be in any format that Gmsh supports (e.g..iges,.step,.brep).
Utilities
Finally, there are methods that provide utility functions and an interface to Gmsh functionality:
add_mask: Add a mask, which is then available for usage withuse_mask. The newly added mask becomes the current mask and all shapes in it are selected (seeuse_shapes).load_layout: Read the cell namedcell_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).copy_mask: Copy current mask to an empty mask namednew_name, set the current mask to this newly created one and select all shapes in the new mask.print_mask_tree: Print a tree of all masks and shapes currently loaded usingqtcad.builder.MaskContainer.print_tree. The arguments are passed on to the above-mentioned method.rename_shape: Copy and rename the currently selected shape and select the newly created shape after adding it to the current mask.remove_shapes: Remove the currently selected shapes from the current mask. Selects all the shapes left in the current mask.copy_shape: Copy the currently active shapes (seeuse_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.get_group: Get the physical group with the specifiednameor all groups ifnameisNoneor not given. The name can also be a list of names or a callable that takes aPhysicalGroup(the group name) and returnsTrueif the group should be returned.assign_to_group: Assign one or multiple entitiestagof dimensiondimto groupgroup. If the group does not exist, it will be created. If there already exists a group with this name, but in another dimension, then make the name unique by appendingDimSuffix.rename_group: Rename an existing physical groupoldtonew.dissolve_physical_group: Dissolve (remove) the physical group(s) with namename(seeget_group). The entities in the group are not removed from the model.merge_groups: Merge multiple physical groupsgroupsinto the (potentially new) groupnew.save_z: Save the current z-coordinate undername.get_z: Get the current z-coordinate or the saved z-coordinate with the givenname.get_z_from_group: Get the top z-coordinate of the bounding box of the entities in the group namedgroup_name. IfbottomisTrue, return the bottom z-coordinate instead. The method tries to snap to the z coordinate of an existing point, but falls back to the bounding box value if there aren’t any.log: Log anlogging.INFOlevel message.clear_mesh: Clear the mesh from the current model.mesh: Generate a mesh for the current model.quick_mesh: Quickly generate a mesh for the current model using the initial mesh algorithms in Gmsh. This is useful for visualisation purposes.write: Save the model topathusinggmsh.write.set_periodic: Set a periodicity constraint between the entities in groupsmasterandmatch. The periodicity is defined by an affine transformation that maps entities inmasterto entities inmatchconsisting of an optionalrotation(3x3 matrix) and an optionaltranslation(3-vector). If not provided, no rotation and no translation is assumed.visualize: View the current model usingqtcad.device.Device.view().view: View the current model in the Gmsh GUI.view_shapes: View the currently selected shapes in gmsh. All the keyword arguments are passed on toview.snapshot: Return a clone of the object (including the Gmsh state).finalize: Stop all underlying Gmsh processes. No further operations can be performed after calling this method. This is mainly useful to clean up memory.assign_mesh_size: Assign a mesh sizesizeto all entities (and their boundaries) in the physical group namedgrouprespecting the mesh size mode (seeoverride_mesh_sizeandinherit_mesh_size). IfforceisTrue, the size will override any existing sizes. Ifforce_with_leaseisTrue, the size will override any existing sizes, but only if the new size is smaller.
- add_mask(mask: Mask) Self
[⚡ Utility] Add a mask, which is then available for usage with
use_mask. The newly added mask becomes the current mask and all shapes in it are selected (seeuse_shapes).- Parameters:
mask – The mask to add.
- add_surface() Self
[🏗️ Operation] Add surfaces based on the the currently selected shapes to the model at the current z-coordinate.
- assign_mesh_size(group: str, size: float, force: bool = False, force_with_lease: bool = False) Self
[⚡ Utility] Assign a mesh size
sizeto all entities (and their boundaries) in the physical group namedgrouprespecting the mesh size mode (seeoverride_mesh_sizeandinherit_mesh_size). IfforceisTrue, the size will override any existing sizes. Ifforce_with_leaseisTrue, the size will override any existing sizes, but only if the new size is smaller.
- assign_to_group(dim: int, tag: list[int] | int, group: str) Self
[⚡ Utility] Assign one or multiple entities
tagof dimensiondimto groupgroup. If the group does not exist, it will be created. If there already exists a group with this name, but in another dimension, then make the name unique by appendingDimSuffix.
- property bbox
Returns: The bounding box of the model.
- property canfork
Returns whether forking is supported.
- 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).
- 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.
- copy_shapes(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.
- property current_mask
The currently active mask or the first available mask.
- Raises:
ValueError – If no current mask is set and the mask container is empty.
- property current_shapes
List of shapes currently selected.
- cut(depth: float, noclip: bool = False) Self
[🏗️ Operation] Cut the currently selected shape(s) into the model up from the current z coordinate down by
depthlength units. Ifnoclip=True, the cutting is performed on the whole model rather than clipped by the selected shapes.See also
etchwhich follows the contours of the top surface.- Parameters:
depth – The distance by which to etch the selected shapes down into the model.
noclip – Whether to cut the shape without horizontally clipping to the current shapes.
- deposit(height: float, noclip: bool = False) Self
[🏗️ Operation] Deposit the currently selected shape(s) into the model up from the current z coordinate by
heightlength units. This is done by adding new material atop the topmost surfaces of the model. Ifnoclip=True, the new material is deposited on the whole top surface of the model, rather than clipped by the currently selected shapes.- Parameters:
height – The distance by which to deposit the shape(s) up into the model.
noclip – Whether to deposit the shape without horizontally clipping to the current shapes.
- deposit_surface(noclip: bool = False) Self
[🏗️ Operation] Add the currently selected shapes as surfaces on top of the model, following the contours of the top surface. If
noclipisTrue, then the surface is not clipped and can extend past the currently selected shapes.
- differentiate_hull_surfaces(enable: None | bool = None) Self
[🔧 Modifier] Enable or disable differentiation of hull surfaces created during operations such as
extrude,growandpad_volume. IfenableisNone, the setting is toggled.When differentiation is enabled, each hull surface will be assigned to a group with the name of the volume it bounds and a suffix
EXTRUSION_SURF_SUFFIXESdepending on its orientation. Ifnumber_hull_surfacesis also enabled, each hull surface will also get a unique index. When turned off all hull surfaces will be assigned to the groups with the suffixHULL_SUFFIX.
- displace_mode(dim: int | list[int] | None = None) Self
[🔧 Modifier] When creating new entities, override the physical groups where the new entities intersect with the old ones to correspond to the physical group of the new elements.
- Parameters:
dim – See
use_mode.
- dissolve_physical_group(group: GroupSpecifier) Self
[⚡ Utility] Dissolve (remove) the physical group(s) with name
name(seeget_group). The entities in the group are not removed from the model.
- etch(depth: float, noclip: bool = False) Self
[🏗️ Operation] Etch the currently selected shape(s) into the model up from the current z coordinate down by
depthlength units. This is done by cutting into each top surface. IfnoclipisTrue, then the surface is not clipped to the currently selected shapes.See also
cut,depositandgrow.- Parameters:
depth – The distance by which to etch the selected shapes down into the model. Must be positive.
- extrude(height: float) Self
[🏗️ Operation] Create a solid extrusion of a plane shape of height
heightat the currentz_coordinate. Also advances the currentz_coordinatebyheight. The resulting surfaces are automatically named using the current naming strategy by appending the suffixesEXTRUSION_SURF_SUFFIXES.- Parameters:
height – The distance by which the shape will be extruded into three dimensional space.
- fill_mode(dim: int | list[int] | None = None) Self
[🔧 Modifier] When creating new entities, inherit the physical groups where the new entities intersect with the old ones.
- Parameters:
dim – See
use_mode.
- finalize(kill: bool = False) Self
[⚡ Utility] Stop all underlying Gmsh processes. No further operations can be performed after calling this method. This is mainly useful to clean up memory.
- get_all_entities(dim: int | list[int] | None = None) list[tuple[int, int]]
Get a list of all entities in the model that are part of a group. See also
qtcad.builer.Builder._get_entities_for_group.- Parameters:
dim – Dimension. If set only the entities of that dimension will be returned, otherwise all are returned.
- get_group(name: GroupSpecifier | None = None, ret_list: bool = False) PhysicalGroup | list[PhysicalGroup]
[⚡ Utility] Get the physical group with the specified
nameor all groups ifnameisNoneor not given. The name can also be a list of names or a callable that takes aPhysicalGroup(the group name) and returnsTrueif the group should be returned.If
ret_listisTrue, always return a list.- Raises:
ValueError – If the group could not be found.
- get_groups(dim: int | list[int] | None = None, sync: bool = True) list[PhysicalGroup]
Get all groups, optionally filtered by their dimension. The result value is a list of
PhysicalGroupinstances. If no match was found an emptylistis returned.- Parameters:
dim – A dimension of the physical groups to be returned. Can also be a collection of dimensions, see
DimensionSpecifier. If unset then all dimensions will be considered.sync – Whether to synchronize the internal Builder representation of groups the physical groups with Gmsh before retrieving them.
- Returns:
A list of found groups. An empty list if none were found.
- get_z(name: str | None = None) float
[⚡ Utility] Get the current z-coordinate or the saved z-coordinate with the given
name.
- get_z_from_group(group_name: str, bottom: bool = False) float
[⚡ Utility] Get the top z-coordinate of the bounding box of the entities in the group named
group_name. IfbottomisTrue, return the bottom z-coordinate instead. The method tries to snap to the z coordinate of an existing point, but falls back to the bounding box value if there aren’t any.- Parameters:
group_name – The name of the group to use.
bottom – If
True, return the bottom of the bounding box.
- group_from_mask() Self
[🔧 Modifier] Any entities created after calling this method will be assigned to a physical group that is named according to the name of the mask they belong to.
- group_from_shape() Self
[🔧 Modifier] Any entities created after calling this method will be assigned to a physical group that is named according the name of the shape that the entity is created from.
- grow(thickness: float, noclip: bool = False, exact: bool = False, num_tries: int = 10, i_know_what_im_doing: bool = False, polygonize: bool = True) Self
[🏗️ Operation] Emulate a physical ‘growth’ operation to add material to the current topmost volumes. In contrast to
deposit, this will not only add material to the top of the volumes but also to their sides. The currently active shapes are used to horizontally clip the new volumes unlessnoclipisTrue.The resulting surfaces are labelled similar to the
extrudecommand. However, there is some ambiguity as to what surfaces are to be considered to be on top and what surfaces are on the side. Here, we choose surfaces whose (average) normal vector projected on the x-y plane is 10% larger than its projection on the z-axis to be on the “side”. Surfaces can be created/renamed usingassign_to_group,add_surfaceordeposit_surface.Warning
Due to problems in OpenCASCADE, this operation might fail. If it does it may help to retry with a different thickness or
polygonize=False. The warning can be suppressed withi_know_what_im_doing=True.- Parameters:
thickness – The distance by which to grow the selected shapes. Must be positive.
noclip – If
True, do not clip the created volumes horizontally.exact – If
exact=Truedo not try to slightly adjust the growth thickness in case growth fails and crash straightaway.num_tries – If
exact=False, try up tonum_triestimes to successively slightly reduce the thickness (by 0.1% each time) and retry.i_know_what_im_doing – If
False, a warning will be issued because this operation is known to be somewhat unstable due to problems in OpenCASCADE.polygonize – If
True, the newly created volumes will be recreated from their hull meshes to avoid problems with curved OpenCASCADE solids (default isTrue).
- import_model(file_path: str | Path, format: str = '', translate: Iterable[float] | None = None, scale: float = 1.0, rotate: float = 0.0, rotation_axis: Iterable[float] | str = Direction.z) Self
[🏗️ Operation] Import a Gmsh model from file
file_path. The model can be in any format that Gmsh supports (e.g..iges,.step,.brep).- Parameters:
file_path – The path to the file to import.
format – The format of the file. If empty (default), the format will be guessed from the file extension. Can be “iges”, “step”, “brep”.
translate – If provided, a 3-vector by which to translate the model after import.
scale – Scaling factor to apply to the model after import.
rotate – Angle in degrees by which to rotate the model around its centre of mass.
- inherit_mesh_size() Self
[🔧 Modifier] For all subsequently generated entities, inherit the mesh size of the existing intersecting entity of the same dimension with the smallest mesh size. If there are no intersecting elements, the mesh size set with
set_mesh_sizeis used.
- 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.
- log(*args, **kwargs) Self
[⚡ Utility] Log an
logging.INFOlevel message.For the arguments see
logging.info.
- merge_groups(groups: GroupSpecifier, into: str) Self
[⚡ Utility] Merge multiple physical groups
groupsinto the (potentially new) groupnew.- Parameters:
groups – Group(s) to merge. See
get_groupfor details.into – The name of a new or existing group to merge into.
- mesh(dimension: int = 3, algorithm2d: int | MeshAlgorithm2D = 2, algorithm3d: int | MeshAlgorithm3D = 1, show_gmsh_output: bool = False, check_connectivity: bool = True, exclude: GroupSpecifier = []) Self
[⚡ Utility] Generate a mesh for the current model.
- Parameters:
dimension – The dimensionality of the objects to be meshed.
save – Optional path(s) under which the meshed model will be saved.
algorithm2d – The ID of the two-dimensional mesh algorithm to use in Gmsh (see https://gmsh.info/doc/texinfo/gmsh.html#Meshing- parameters). Default is automatic. See
MeshAlgorithm2D.algorith3d – The ID of the three-dimensional mesh algorithm to use in Gmsh (see https://gmsh.info/doc/texinfo/gmsh.html#Meshing- parameters). See
MeshAlgorithm3D.show_gmsh_output – If
True, show Gmsh output in the terminal.check_connectivity – If
True, run a simple conformity check on the mesh after generation. The check consists of determining whether the mesh is fully connected which is sufficient but not necessary for conformity. (Only for three-dimensional meshes.)exclude – Physical group(s) to exclude from meshing. Can be a single group name, a list of group names or a callable that takes a
PhysicalGroupand returnsTrueif the group should be excluded.
- property mesh_size
The current mesh size.
Raises
ValueErrorif no current mesh size is set.
- property min_elements
The current minimum number of mesh elements along the narrowest dimension of subsequently created volumes.
- minimum_mesh_size() Self
[🔧 Modifier] For all subsequently generated entities, use the mesh size set with
set_mesh_sizeand take the minimum of the set mesh size and the existing mesh size in the intersections with the existing geometry.
- property mode
The current mode used for combining intersecting geometries.
See
qtcad.builer.Builder.Modefor a description of the different modes.
- number_hull_surfaces(enable: None | bool = None) Self
[🔧 Modifier] Enable or disable automatic numbering of hull surfaces bounding volumes created during operations such as
extrude,growandpad_volume. IfenableisNone, the setting is toggled.Default is
False. Has no effect if :differentiate_hull_surfaces` is turned off.
- overlay_mode(dim: int | list[int] | None = None) Self
[🔧 Modifier] Like
fill_mode, but instead of inheriting the group from the intersecting entities the intersecting elements will be added to physical groups named like[intersecting_group].[new_entity_group].- Parameters:
dim – See
use_mode.
- override_mesh_size() Self
[🔧 Modifier] For all subsequently generated entities, use the mesh size set with
set_mesh_sizeand override the mesh size in the intersections with the existing geometry.
- pad_volume(group: GroupSpecifier, thickness: float, padding_suffix: str = '_padding', noclip: bool = False, polygonize: bool = True) Self
[🏗️ Operation] Add a padding layer of
thicknessaround the volumes in volume group with namegroup_name. The newly created padding volume will be namedgroup_name + padding_suffixand clipped horizontally by the currently selected shapes unlessnoclipisTrue.- Parameters:
group – The group(s) to pad. See
get_groupfor details on the allowed types.thickness – The padding thickness.
padding_suffix – Suffix to append to the group name for the new volume.
noclip – If
True, no horizontal clipping will occur. Default isFalse.polygonize – If
True, the newly created volumes will be recreated from their hull meshes to avoid problems with curved OpenCASCADE solids (default isTrue).
- print_mask_tree(*args, **kwargs) Self
[⚡ Utility] Print a tree of all masks and shapes currently loaded using
qtcad.builder.MaskContainer.print_tree. The arguments are passed on to the above-mentioned method.
- quick_mesh(dim: int = 3, mesh_size: float | None = None) Self
[⚡ Utility] Quickly generate a mesh for the current model using the initial mesh algorithms in Gmsh. This is useful for visualisation purposes.
- Parameters:
dim – The dimensionality of the objects to be meshed.
mesh_size – If provided, use this mesh size for all entities being meshed.
- remove_shapes() Self
[⚡ Utility] Remove the currently selected shapes from the current mask. Selects all the shapes left in the current mask.
- rename_group(old: str, new: str) Self
[⚡ Utility] Rename an existing physical group
oldtonew.- Raises:
ValueError – If the group already exists.
- rename_shape(name: str) Self
[⚡ Utility] Copy and rename the currently selected shape and select the newly created shape after adding it to the current mask.
Calls
copy_shape.
- rotate_model(angle: float, axis: Iterable[float] | str, around: tuple[float, float] | Iterable[float] | Direction | None = None) Self
[🏗️ Operation] Rotate the model around its centre of mass (or the point specified by
around) by a givenanglein degrees on a a specifiedaxis. The z-coordinate is updated to the new top of the model.- Parameters:
angle – The angle to rotate by (in degrees).
axis – The direction vector of the axis of rotation. Either “x”, “y” or “z” or a 3-vector.
around – Point to rotate around. If
None(default), rotates around the centre of mass. If a string is provided, the centre of rotation will be the centre of mass of the physical group with that name.
- save_z(name: str) Self
[⚡ Utility] Save the current z-coordinate under
name.This name can then be used to restore the z-coordinate with
set_z.
- set_geometry_tolerance(tolerance: float) Self
[🔧 Modifier] Set the geometry tolerance used by Gmsh when determining whether two points are identical. The default is
1e-8length units.
- set_group_name(name: str) Self
[🔧 Modifier] Any entities created after calling this method will be assigned to the physical group with name
name.See also
group_from_maskandgroup_from_shape.
- set_match_mesh_tolerance(tolerance: float) Self
[🔧 Modifier] Set the tolerance used when matching mesh nodes to geometry points. The default is
1e-6length units. This doesn’t seem to have much effect in practice.
- set_mesh_size(size: float) Self
[🔧 Modifier] Set the local mesh size for elements added after this point in units set by the
length_unit_exponent(seeqtcad.builer.Builder). Note that the mesh size may be chosen smaller due toset_min_elements.- Parameters:
size – The new mesh characteristic length.
- set_min_elements(min_elements: int | None) Self
[🔧 Modifier] Ensure that all subsequently created volumes will have at least
min_elementsmesh elements (triangles, tetrahedra) along their narrowest dimension. If set toNone, the mesh size set byset_mesh_sizewill be used.
- set_periodic(master: GroupSpecifier, match: GroupSpecifier, translation: Iterable[float] | None = None, rotation: ndarray | None = None) Self
[⚡ Utility] Set a periodicity constraint between the entities in groups
masterandmatch. The periodicity is defined by an affine transformation that maps entities inmasterto entities inmatchconsisting of an optionalrotation(3x3 matrix) and an optionaltranslation(3-vector). If not provided, no rotation and no translation is assumed.See the Gmsh documentation for more information.
- Parameters:
master – The group(s) of the master entities. (See
get_group().)match – The group(s) of the matching entities.
translation – The translation vector of the affine transformation.
rotation – The rotation matrix of the affine transformation.
- set_z(z_coordinate: float | str | None = None, offset: float = 0) Self
[🔧 Modifier] Set the z-coordinate used as the basis for operations.
Either a float or an already defined name can be given. When using a name, it will load the saved z which was previously saved with
save_z. Ifz_coordinateisNone, the current z-coordinate will be kept.The
offsetcan be used to shift the z-coordinate (useful when using a string argument orNoneforz_coordinate).
- set_z_from_group(group_name: str, bottom: bool = False, offset: float = 0) Self
[🔧 Modifier] Set the current z-coordinate to the top (default) or bottom of the bounding box of the entities in the group named
group_name. Optionally, anoffsetcan be provided to shift the z-coordinate up (positive offset) or down (negative offset).See also
get_z_from_group.- Parameters:
group_name – The name of the group to use.
bottom – If
True, use the bottom of the bounding box.offset – Offset to add to the z-coordinate.
- snapshot()
[⚡ Utility] Return a clone of the object (including the Gmsh state).
- translate_model(vec: Iterable[float]) Self
[🏗️ Operation] Translate the whole model by the vector
vec. The z-coordinate is updated by the z-component ofvec.- Parameters:
vec – The translation vector.
- use_all_masks() Self
[🔧 Modifier] Select all masks and merge them into one temporary mask.
Equivalent to
use_mask(lambda _: True).
- 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.
- use_mode(mode: FragmentationMode, dim: int | list[int] | None = None) Self
[🔧 Modifier] Set the strategy for handling intersecting geometries for the dimensions
dim. Currently, this setting is only relevant for dimensions2and3.See
qtcad.builer.Builder.Modefor a description of the different modes.- Parameters:
mode – The mode to use for combining intersecting geometries.
dim – The dimensions to which the mode will apply for (can be a single dimension or a list of dimensions).
Nonemeans “all dimensions”.
- use_shape(shape: str | int | list[str | int] | Callable[[Shape], bool] | None = None) Self
[🔧 Modifier] Select shapes in the current mask that will be used for all following operations.
- use_shapes(shape: str | int | list[str | int] | Callable[[Shape], bool] | None = None) Self
[🔧 Modifier] Select shapes in the current mask that will be used for all following operations.
- view(block=True, volumes=False, volume_labels=False, surfaces=False, surface_labels=False, groups: GroupSpecifier | None = None, entities: Iterable[tuple[int, int]] | None = None, angles: Iterable[float] | None = None, orthographic: bool = False, save: Path | str | None = None, show: bool = True, zoom: float = 1, font_size: float = 10, show_mesh_faces: bool = False, axes: int = 0, label_type: int = 4, resolution: int = 2000, show_surface_faces: bool = False, show_volume_faces: bool = False) Self
[⚡ Utility] View the current model in the Gmsh GUI.
- Parameters:
block – Block execution until the Gmsh window is closed or quit.
volumes – Show volume markers.
volume_labels – Show labels for volume elements.
surfaces – Show surface markers.
surface_labels – Show labels for surfaces.
groups – If specified, only the groups with the names provided will be displayed. Example:
["my_group_1", "my_group_2"]See alsoget_group.entities – If specified, only the entities with the (dimension, tag) pairs provided will be displayed. Example:
[(2, 1), (2, 3)]will only show surfaces with entity tags (dim, tag) = (2, 1) and (2, 3).angles – The three Euler angles of rotation specifying the perspective. See the Gmsh documentation
orthographic – Use an orthographic projection instead of the perspective projection.
save – Save the view to a file. The file format is determined by the extension of the filename. Supported formats are
"PNG"and"SVG". If exporting SVG, inkscape is used to trim the margins of the generated SVG if available.show – Close the window straight away when exiting this method. This is useful when using
save=Trueto avoid cluttering the screen with windows.zoom – The GUI zoom factor.
font_size – The font size of the text in the render.
show_mesh_faces – Whether to show the surface mesh faces or not.
axes – Whether to show axes. See the Gmsh documentation.
label_type – The type of labels to show. See the Gmsh documentation.
resolution – The resolution (width) of the saved figure in pixels.
show_surface_faces – Whether to show the surface faces or not.
show_volume_faces – Whether to show the volume faces or not.
- view_shapes(**kwargs) Self
[⚡ Utility] View the currently selected shapes in gmsh. All the keyword arguments are passed on to
view.See also
use_shapesanduse_mask.
- visualize(**kwargs)
[⚡ Utility] View the current model using
qtcad.device.Device.view().
- property z_coordinate
- exception BuilderException
Bases:
ExceptionAn exception originating from
qtcad.builder.Builderor its methods.
- class Circle(name: str | None = '__unset', radius: float = 1, center: tuple[float, float] = (0, 0))
Bases:
ShapeA circle with radius
radiusand center pointcenter.- property bbox
Returns: The bounding box of the shape as a four-tuple (left, right, bottom, top).
- centered() Circle
- Returns:
A copy of this shape centered at its center point. The result includes all sub-shapes with similar transformations.
- class Direction(*values)
Bases:
StrEnumBehaviours choosing the group entities are assigned to.
- x = 'x'
- y = 'y'
- z = 'z'
- class FragmentationMode(*values)
Bases:
EnumBehaviours for creating new entities that overlap with existing ones.
- DISPLACE = 1
See
qtcad.builer.Builder.displace_mode
- FILL = 3
See
qtcad.builer.Builder.fill_mode
- OVERLAY = 2
See
qtcad.builer.Builder.overlay_mode
- class GroupingMode(*values)
Bases:
StrEnumBehaviours choosing the group entities are assigned to.
- from_mask = '__from_mask'
See
qtcad.builer.Builder.group_from_mask()
- from_shape = '__from_shape'
See
qtcad.builer.Builder.group_from_shape()
- class Mask(name: str | None, shapes: list[~qtcad.builder.masks.Shape] = <factory>, id: int = -1)
Bases:
objectA 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)
- add_shape(shape: Shape)
Add a
shapeto the mask and set its id.- Returns:
The added shape (with appropriate id).
- add_shapes(shapes: Iterable[Shape])
Add multiple
shapesto the mask.- Returns:
The list of added shapes (with appropriate ids).
- remove_shapes(shapes: Iterable[Shape])
Remove a
shapesfrom the mask. The ids of all shapes are updated accordingly.- Parameters:
shape – The shapes to remove.
- class MaskContainer(length_unit_exponent: int = -9)
Bases:
objectA collection of two-dimensional masks.
- add(mask: Mask)
Adds a mask into this container. If the mask’s id is
-1, it will be set to the next available index. If the mask’s id is already taken, it will be incremented until an available id is found.- Parameters:
mask – The mask to add.
- copy_shapes(shape_identifier: int | str | Shape | list[int | str | Shape] | None, from_mask: int | str | Mask, to_mask: int | str | Mask | Callable[[Mask], bool] | None = None, name: str | None = '__unset', translate: tuple[float, float] = (0, 0), rotate: float | tuple[float, tuple[float, float] | None] = 0, scale: float = 1, transformer: Callable[[Shape], Shape] | None = None) list[Shape]
Copy a shape specified by
shape_idfrom the maskfrom_maskto the maskto_maskapplying a series of transformations and a shape modifier. See alsoShape.transform.- Parameters:
shape_id – The identifier of the shape. If
None, all shapes are copied.from_mask – The mask to copy the shape from.
to_mask – The mask to add the shape to. If
None, use the same mask asfrom_mask. See alsoget_mask.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.translate – A tuple
(dx, dy)specifying the translation in x and y applied to the copied shape. SeeShape.translated.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 – The scaling factor applied to the copied shape. See
Shape.scaled.transformer – An optional callable that takes a shape and returns a transformed shape. This is applied last.
- Returns:
The newly added shape(s).
- get_mask(identifier: int | str | Mask | Callable[[Mask], bool] | list[int | str | Mask | Callable[[Mask], bool]]) Mask
Get the mask with name or id
identifier(id, name, or filter predicate – a function taking a mask and returning a boolean if it matches) or check if a mask is in the container.If a predicate is given and it matches multiple masks, all matching masks are merged and the merged mask is returned. Similarly, if a list of identifiers is given, all specified masks are merged and returned.
- Raises:
ValueError – If no such mask exists or the specified mask is not in this container.
- load_layout(file_path: str | Path, cell_name: str | None = None, name_property: str = 'name')
Read the cell named
cell_name(default is the top cell) from aGDSor anOASISfilefile_pathand parse its structure. Shape names are either parsed from thename_propertyuser property or from text labels.- Parameters:
file_path – The path to the
OASISfile.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.
- class MeshAlgorithm2D(*values)
Bases:
EnumThe available two-dimensional meshing algorithms. See the Gmsh documentation.
- Automatic = 2
- BAMG = 7
- Delaunay = 5
- FrontalDelaunay = 6
- FrontalDelaunayForQuads = 8
- Initial = 3
- MeshAdapt = 1
- PackingOfParallelograms = 9
- QuasiStructuredQuad = 11
- class MeshAlgorithm3D(*values)
Bases:
EnumThe available three-dimensional meshing algorithms. See the Gmsh documentation.
- Delaunay = 1
- Frontal = 4
- HXT = 10
- Initial = 3
- MMG3D = 7
- RTree = 9
- class MeshSizeMode(*values)
Bases:
EnumBehaviours for choosing which characteristic length or layer number to choose when creating new entities.
- inherit = 0
- minimum = 2
- override = 1
- exception NonconformalMesh(msg: str, tmpdir, *args, **kwargs)
Bases:
BuilderExceptionAn exception raised when the mesh is found to be non-conformal after performing a heat-conduction check.
- outputdir
The directory where the heat-conduction results are stored.
- class PhysicalGroup(dim: int, tag: int, name: str, entities: set[int])
Bases:
objectRepresents a Gmsh physical group and is only used internally.
- property dimtag: tuple[int, int]
The dimension and tag of the group, represented as a tuple.
See also
DimTag.
- class Polygon(name: str | None = '__unset', hull: list[tuple[float, float]] = <factory>, holes: list[~qtcad.builder.masks.Polygon] = <factory>)
Bases:
ShapeA polygon with an hull (outline) defined by the points
hullandholesthat are themselves polygons.- property bbox
Returns: The bounding box of the shape as a four-tuple (left, right, bottom, top).
- classmethod 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`.
- centered() Polygon
- Returns:
A copy of this polygon centered at its center point. The result includes all sub-shapes with similar transformations.
- classmethod from_bbox(x_min: float, y_min: float, z_min: float, x_max: float, y_max: float, z_max: float, *args, **kwargs)
Create a polygon from a bounding box.
- Parameters:
x_min – Minimum x value of the bounding box.
y_min – Minimum y value of the bounding box.
z_min – Minimum z value of the bounding box.
x_max – Maximum x value of the bounding box.
y_max – Maximum y value of the bounding box.
z_max – Maximum z value of the bounding box.
- Returns:
A polygon representing the bounding box. The rest of the arguments are passed to the constructor for
qtcad.builder.Polygon`.
- classmethod 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`.
- class Shape(name: str | None = '__unset')
Bases:
objectAn 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.
Submodules
qtcad.builder.builder_types module
- exception BuilderException
Bases:
ExceptionAn exception originating from
qtcad.builder.Builderor its methods.
- class Direction(*values)
Bases:
StrEnumBehaviours choosing the group entities are assigned to.
- x = 'x'
- y = 'y'
- z = 'z'
- class FragmentationMode(*values)
Bases:
EnumBehaviours for creating new entities that overlap with existing ones.
- DISPLACE = 1
See
qtcad.builer.Builder.displace_mode
- FILL = 3
See
qtcad.builer.Builder.fill_mode
- OVERLAY = 2
See
qtcad.builer.Builder.overlay_mode
- class GroupingMode(*values)
Bases:
StrEnumBehaviours choosing the group entities are assigned to.
- from_mask = '__from_mask'
See
qtcad.builer.Builder.group_from_mask()
- from_shape = '__from_shape'
See
qtcad.builer.Builder.group_from_shape()
- class MeshSizeMode(*values)
Bases:
EnumBehaviours for choosing which characteristic length or layer number to choose when creating new entities.
- inherit = 0
- minimum = 2
- override = 1
- exception NonconformalMesh(msg: str, tmpdir, *args, **kwargs)
Bases:
BuilderExceptionAn exception raised when the mesh is found to be non-conformal after performing a heat-conduction check.
- outputdir
The directory where the heat-conduction results are stored.
- class PhysicalGroup(dim: int, tag: int, name: str, entities: set[int])
Bases:
objectRepresents a Gmsh physical group and is only used internally.
- property dimtag: tuple[int, int]
The dimension and tag of the group, represented as a tuple.
See also
DimTag.
qtcad.builder.gmsh_types module
- Box = tuple[float, float, float, float, float, float] | numpy.ndarray[tuple[int], numpy.dtype[numpy.float64]]
A bounding box of format
(x_min, y_min, z_min, x_max, y_max, z_max).
- DimensionSpecifier = int | list[int] | None
Allowed dimension specifications.
The specification can be either a single integer, indicating the dimension; a list of integers specifying multiple dimensions; or
None, which signifies all dimensions.
- class MeshAlgorithm2D(*values)
Bases:
EnumThe available two-dimensional meshing algorithms. See the Gmsh documentation.
- Automatic = 2
- BAMG = 7
- Delaunay = 5
- FrontalDelaunay = 6
- FrontalDelaunayForQuads = 8
- Initial = 3
- MeshAdapt = 1
- PackingOfParallelograms = 9
- QuasiStructuredQuad = 11
- class MeshAlgorithm3D(*values)
Bases:
EnumThe available three-dimensional meshing algorithms. See the Gmsh documentation.
- Delaunay = 1
- Frontal = 4
- HXT = 10
- Initial = 3
- MMG3D = 7
- RTree = 9
- Point
Point represented by a tuple of x- and y-coordinates.
The same as
gmsh.model.geo.Point.
- TagList
List of tags.
See also
DimTagList.