kpex-plugin-gmsh 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ #
2
+ # --------------------------------------------------------------------------------
3
+ # SPDX-FileCopyrightText: 2026 Martin Jan Köhler and Harald Pretl
4
+ # Johannes Kepler University, Institute for Integrated Circuits.
5
+ #
6
+ # This file is part of kpex-plugin-gmsh
7
+ # (see https://github.com/iic-jku/kpex-plugin-gmsh).
8
+ #
9
+ # This program is free software: you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation, either version 3 of the License, or
12
+ # (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ # SPDX-License-Identifier: GPL-3.0-or-later
22
+ # --------------------------------------------------------------------------------
23
+ #
24
+
25
+ """
26
+ gmsh volume meshes of PEX25D scenes: the KPEX exporter ``gmsh``, and the
27
+ mesh builder the FEM exporters (Elmer, Palace) share.
28
+
29
+ gmsh and KLayout load on export, so plugin discovery works without them.
30
+ """
31
+
32
+ from .exporter import GmshSceneExporter
33
+ from .mesh import LENGTH_UNIT_M, OUTER_BOUNDARY, MeshResult, PhysicalGroup, write_mesh
34
+ from .options import GmshMeshOptions, parse_options
35
+
36
+
37
+ def create_exporter() -> GmshSceneExporter:
38
+ return GmshSceneExporter()
39
+
40
+
41
+ __all__ = [
42
+ 'GmshMeshOptions',
43
+ 'GmshSceneExporter',
44
+ 'LENGTH_UNIT_M',
45
+ 'MeshResult',
46
+ 'OUTER_BOUNDARY',
47
+ 'PhysicalGroup',
48
+ 'create_exporter',
49
+ 'parse_options',
50
+ 'write_mesh',
51
+ ]
@@ -0,0 +1,59 @@
1
+ #
2
+ # --------------------------------------------------------------------------------
3
+ # SPDX-FileCopyrightText: 2026 Martin Jan Köhler and Harald Pretl
4
+ # Johannes Kepler University, Institute for Integrated Circuits.
5
+ #
6
+ # This file is part of kpex-plugin-gmsh
7
+ # (see https://github.com/iic-jku/kpex-plugin-gmsh).
8
+ #
9
+ # This program is free software: you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation, either version 3 of the License, or
12
+ # (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ # SPDX-License-Identifier: GPL-3.0-or-later
22
+ # --------------------------------------------------------------------------------
23
+ #
24
+
25
+ """The exporter ``gmsh``: the mesh on its own, for any FEM tool or for looking at."""
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import TYPE_CHECKING, Any, ClassVar, FrozenSet, List, Mapping, Optional
30
+
31
+ from kpex.plugin_api.v1 import PEX25DSceneExporter, SceneCapability
32
+
33
+ from .mesh import write_mesh
34
+ from .options import GmshMeshOptions, parse_options
35
+
36
+ if TYPE_CHECKING:
37
+ from kpex_protobuf.kpex.pex25d.pex25d_scene_pb2 import PEX25DScene
38
+
39
+
40
+ class GmshSceneExporter(PEX25DSceneExporter):
41
+ """Write a gmsh volume mesh of a resolved PEX25D scene."""
42
+
43
+ name: ClassVar[str] = 'gmsh'
44
+ default_prefix: ClassVar[str] = ''
45
+
46
+ @classmethod
47
+ def supported_capabilities(cls) -> FrozenSet[SceneCapability]:
48
+ return frozenset({SceneCapability.GROUND_CUTOUTS, SceneCapability.ELECTRICAL_IDENTITY})
49
+
50
+ def export(self,
51
+ scene: PEX25DScene,
52
+ *,
53
+ output_dir_path: str,
54
+ prefix: str = '',
55
+ options: Optional[Mapping[str, Any]] = None) -> List[str]:
56
+ """Return the mesh first, then the JSON naming its physical groups."""
57
+ settings = parse_options(GmshMeshOptions, options, self.name)
58
+ result = write_mesh(scene, settings, output_dir_path, prefix or self.default_prefix)
59
+ return result.paths
@@ -0,0 +1,341 @@
1
+ #
2
+ # --------------------------------------------------------------------------------
3
+ # SPDX-FileCopyrightText: 2026 Martin Jan Köhler and Harald Pretl
4
+ # Johannes Kepler University, Institute for Integrated Circuits.
5
+ #
6
+ # This file is part of kpex-plugin-gmsh
7
+ # (see https://github.com/iic-jku/kpex-plugin-gmsh).
8
+ #
9
+ # This program is free software: you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation, either version 3 of the License, or
12
+ # (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ # SPDX-License-Identifier: GPL-3.0-or-later
22
+ # --------------------------------------------------------------------------------
23
+ #
24
+
25
+ """
26
+ Disjoint prisms → gmsh volume mesh for electrostatics.
27
+
28
+ The prisms are extruded with OpenCASCADE and fragmented, so that touching solids
29
+ share their faces and the mesh is conformal. Conductors are then removed: only
30
+ the dielectrics are meshed, and each net is the set of faces where it touches a
31
+ dielectric. Physical groups carry the names:
32
+
33
+ * one volume group per dielectric, the background included
34
+ * one surface group per terminal: each net, each floating conductor, the ground plane
35
+ * one surface group ``outer_boundary`` for the faces of the domain box
36
+
37
+ Tags count from 1 within each kind, so they can serve directly as Palace
38
+ attributes and Elmer body / boundary indices. Coordinates are in µm.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import contextlib
44
+ from dataclasses import asdict, dataclass, field
45
+ from importlib import metadata
46
+ import json
47
+ import math
48
+ import os
49
+ from pathlib import Path
50
+ from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
51
+
52
+ from kpex.log import debug, info
53
+ from kpex.plugin_api.v1 import ExportError, ExporterUnavailable
54
+
55
+ if TYPE_CHECKING:
56
+ from kpex_protobuf.kpex.pex25d.pex25d_scene_pb2 import PEX25DScene
57
+
58
+ from .options import GmshMeshOptions
59
+ from .solids import Body, SceneSolids
60
+
61
+ OUTER_BOUNDARY = 'outer_boundary'
62
+
63
+ LENGTH_UNIT_M = 1e-6
64
+ """Mesh coordinates are in µm."""
65
+
66
+ MAX_SIZE_PER_EDGE_SIZE = 20.0
67
+ """Default largest element, relative to the size at conductor edges."""
68
+
69
+ SIZE_GROWTH = 0.5
70
+ """How fast elements grow away from conductor edges: size increase per distance."""
71
+
72
+ MAX_EDGE_SAMPLES = 2000
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class PhysicalGroup:
77
+ dim: int
78
+ tag: int
79
+ name: str
80
+ permittivity: Optional[float] = None
81
+ """Relative permittivity of a dielectric volume."""
82
+
83
+
84
+ @dataclass
85
+ class MeshResult:
86
+ """What was written, and which physical group is what."""
87
+
88
+ msh_path: str
89
+ groups_path: str
90
+ dielectrics: List[PhysicalGroup] = field(default_factory=list)
91
+ terminals: List[PhysicalGroup] = field(default_factory=list)
92
+ outer_boundary: Optional[PhysicalGroup] = None
93
+ mesh_size_edge_um: Optional[float] = None
94
+ """Element size used at conductor edges."""
95
+
96
+ mesh_size_max_um: Optional[float] = None
97
+ """Largest element size used."""
98
+
99
+ node_count: int = 0
100
+ tetrahedron_count: int = 0
101
+ terminal_faces: List[int] = field(default_factory=list, repr=False)
102
+ """The model's faces of all terminals, for refining the mesh near conductors."""
103
+
104
+ body_names_path: Optional[str] = None
105
+ """Electrical identities when distinct bodies need disambiguated solver labels."""
106
+
107
+ @property
108
+ def paths(self) -> List[str]:
109
+ return [self.msh_path, self.groups_path] + ([self.body_names_path] if self.body_names_path else [])
110
+
111
+
112
+ def write_mesh(scene: PEX25DScene,
113
+ settings: GmshMeshOptions,
114
+ output_dir_path: str,
115
+ prefix: str = '') -> MeshResult:
116
+ """
117
+ Mesh ``scene`` and write ``<prefix>mesh.msh`` (gmsh 2.2, ASCII), plus
118
+ ``<prefix>mesh.json`` naming each physical group.
119
+ """
120
+ from kpex.plugin_api.v1 import require_scene_capabilities
121
+ from .exporter import GmshSceneExporter
122
+
123
+ require_scene_capabilities(GmshSceneExporter(), scene, GmshSceneExporter.name)
124
+ try:
125
+ import gmsh
126
+ except ImportError as exc:
127
+ raise ExporterUnavailable(f"The gmsh Python module is not installed: {exc}") from exc
128
+ from .solids import scene_solids
129
+ from kpex.plugin_api.v1 import write_solver_body_map
130
+
131
+ solids = scene_solids(scene, settings.field_margin_um)
132
+
133
+ os.makedirs(output_dir_path, exist_ok=True)
134
+ result = MeshResult(msh_path=os.path.join(output_dir_path, f"{prefix}mesh.msh"),
135
+ groups_path=os.path.join(output_dir_path, f"{prefix}mesh.json"))
136
+ with _session(gmsh, settings.verbose):
137
+ _build(gmsh, solids, result)
138
+ _generate(gmsh, settings, solids, result)
139
+ gmsh.write(result.msh_path)
140
+
141
+ with open(result.groups_path, 'w', encoding='utf-8') as file:
142
+ json.dump(_groups_document(result), file, indent=2)
143
+ file.write('\n')
144
+ result.body_names_path = write_solver_body_map(
145
+ scene, Path(output_dir_path) / f"{prefix}body_names.json")
146
+ info(f"Meshed {len(result.dielectrics)} dielectric(s) and {len(result.terminals)} "
147
+ f"terminal(s): {result.node_count} nodes, {result.tetrahedron_count} tetrahedra, "
148
+ f"{result.mesh_size_edge_um} µm at conductor edges, up to {result.mesh_size_max_um} µm")
149
+ return result
150
+
151
+
152
+ @contextlib.contextmanager
153
+ def _session(gmsh: Any, verbose: bool) -> Iterator[None]:
154
+ """A model of our own; gmsh itself is finalized only if it was not running."""
155
+ owner = not gmsh.isInitialized()
156
+ if owner:
157
+ gmsh.initialize(readConfigFiles=False)
158
+ gmsh.option.setNumber('General.Terminal', 1 if verbose else 0)
159
+ gmsh.model.add('kpex-plugin-gmsh')
160
+ try:
161
+ yield
162
+ finally:
163
+ gmsh.model.remove()
164
+ if owner:
165
+ gmsh.finalize()
166
+
167
+
168
+ def _build(gmsh: Any, solids: SceneSolids, result: MeshResult):
169
+ from .solids import BodyKind
170
+
171
+ occ = gmsh.model.occ
172
+ body_of_volume: Dict[int, Body] = {}
173
+ for prism in solids.prisms:
174
+ z = solids.um(prism.zlow)
175
+ height = solids.um(prism.zhigh - prism.zlow)
176
+ for polygon in prism.region.each():
177
+ for volume in _extrude(occ, polygon, z, height, solids.grid_um):
178
+ body_of_volume[volume] = prism.body
179
+ debug(f"{len(body_of_volume)} volumes before fragmenting")
180
+
181
+ inputs = [(3, volume) for volume in body_of_volume]
182
+ if len(inputs) > 1:
183
+ # The prisms are disjoint, so each fragment comes from exactly one of them.
184
+ _, children = occ.fragment(inputs[:1], inputs[1:])
185
+ fragments: Dict[int, Body] = {}
186
+ for (_, parent), parent_children in zip(inputs, children):
187
+ for _, child in parent_children:
188
+ if fragments.setdefault(child, body_of_volume[parent]) != body_of_volume[parent]:
189
+ raise ExportError(f"Solids of '{fragments[child].name}' and "
190
+ f"'{body_of_volume[parent].name}' overlap")
191
+ body_of_volume = fragments
192
+ occ.synchronize()
193
+
194
+ terminal_faces: Dict[Body, List[int]] = {}
195
+ outer_faces: List[int] = []
196
+ for _, face in gmsh.model.getEntities(2):
197
+ volumes, _ = gmsh.model.getAdjacencies(2, face)
198
+ bodies = [body_of_volume[volume] for volume in volumes]
199
+ conductors = [body for body in bodies if body.kind == BodyKind.CONDUCTOR]
200
+ if len(bodies) == 1 and not conductors:
201
+ outer_faces.append(face)
202
+ elif len(bodies) == 2 and len(conductors) == 1:
203
+ terminal_faces.setdefault(conductors[0], []).append(face)
204
+ elif len(conductors) == 2 and conductors[0] != conductors[1]:
205
+ raise ExportError(f"Conductors '{conductors[0].name}' and "
206
+ f"'{conductors[1].name}' touch, which shorts them")
207
+
208
+ # Only the dielectrics are meshed. Removing the conductors keeps their faces
209
+ # as the dielectrics' boundaries; faces left without a volume are dropped.
210
+ occ.remove([(3, volume) for volume, body in body_of_volume.items()
211
+ if body.kind == BodyKind.CONDUCTOR])
212
+ occ.synchronize()
213
+ dangling = [(2, face) for _, face in gmsh.model.getEntities(2)
214
+ if len(gmsh.model.getAdjacencies(2, face)[0]) == 0]
215
+ if dangling:
216
+ occ.remove(dangling, recursive=True)
217
+ occ.synchronize()
218
+
219
+ for body in solids.bodies:
220
+ volumes = [volume for volume, owner in body_of_volume.items()
221
+ if owner == body and body.kind == BodyKind.DIELECTRIC]
222
+ if volumes:
223
+ result.dielectrics.append(_physical_group(
224
+ gmsh, 3, volumes, len(result.dielectrics) + 1, body.name, body.permittivity))
225
+ for body in solids.bodies:
226
+ if terminal_faces.get(body):
227
+ result.terminals.append(_physical_group(
228
+ gmsh, 2, terminal_faces[body], len(result.terminals) + 1, body.name))
229
+ result.terminal_faces.extend(terminal_faces[body])
230
+ if any(group.name == OUTER_BOUNDARY for group in result.terminals):
231
+ raise ExportError(f"A net is named '{OUTER_BOUNDARY}', the name of the "
232
+ f"domain boundary group")
233
+ if outer_faces:
234
+ result.outer_boundary = _physical_group(
235
+ gmsh, 2, outer_faces, len(result.terminals) + 1, OUTER_BOUNDARY)
236
+
237
+
238
+ def _extrude(occ: Any, polygon: Any, z: float, height: float, scale: float) -> List[int]:
239
+ loops = [_curve_loop(occ, polygon.each_point_hull(), z, scale)]
240
+ loops.extend(_curve_loop(occ, polygon.each_point_hole(hole), z, scale)
241
+ for hole in range(polygon.holes()))
242
+ surface = occ.addPlaneSurface(loops)
243
+ return [tag for dim, tag in occ.extrude([(2, surface)], 0, 0, height) if dim == 3]
244
+
245
+
246
+ def _curve_loop(occ: Any, points: Any, z: float, scale: float) -> int:
247
+ # gmsh wants the holes wound like the hull, KLayout winds them the other
248
+ # way; opposite windings make OCC add a hole's area instead of cutting it.
249
+ points = [(point.x, point.y) for point in points]
250
+ twice_area = sum(x0 * y1 - x1 * y0
251
+ for (x0, y0), (x1, y1) in zip(points, points[1:] + points[:1]))
252
+ if twice_area < 0:
253
+ points.reverse()
254
+ tags = [occ.addPoint(x * scale, y * scale, z) for x, y in points]
255
+ lines = [occ.addLine(start, end) for start, end in zip(tags, tags[1:] + tags[:1])]
256
+ return occ.addCurveLoop(lines)
257
+
258
+
259
+ def _physical_group(gmsh: Any, dim: int, entities: List[int], tag: int, name: str,
260
+ permittivity: Optional[float] = None) -> PhysicalGroup:
261
+ gmsh.model.addPhysicalGroup(dim, entities, tag)
262
+ gmsh.model.setPhysicalName(dim, tag, name)
263
+ return PhysicalGroup(dim, tag, name, permittivity)
264
+
265
+
266
+ def _generate(gmsh: Any, settings: GmshMeshOptions, solids: SceneSolids, result: MeshResult):
267
+ gmsh.option.setNumber('Mesh.MshFileVersion', 2.2)
268
+ gmsh.option.setNumber('Mesh.Binary', 0)
269
+ gmsh.option.setNumber('Mesh.SaveAll', 0)
270
+
271
+ edge_size = settings.mesh_size_edge_um
272
+ if edge_size is None and solids.conductor_thickness:
273
+ edge_size = solids.um(solids.conductor_thickness)
274
+ max_size = settings.mesh_size_max_um
275
+ if max_size is None and edge_size is not None:
276
+ max_size = edge_size * MAX_SIZE_PER_EDGE_SIZE
277
+ if edge_size is not None and result.terminal_faces:
278
+ _refine_at_conductor_edges(gmsh, result.terminal_faces, edge_size, max_size)
279
+ result.mesh_size_edge_um = edge_size
280
+ result.mesh_size_max_um = max_size
281
+
282
+ if settings.mesh_size_min_um is not None:
283
+ gmsh.option.setNumber('Mesh.MeshSizeMin', settings.mesh_size_min_um)
284
+ if max_size is not None:
285
+ gmsh.option.setNumber('Mesh.MeshSizeMax', max_size)
286
+ gmsh.model.mesh.generate(3)
287
+
288
+ result.node_count = len(gmsh.model.mesh.getNodes()[0])
289
+ element_types, element_tags, _ = gmsh.model.mesh.getElements(3)
290
+ result.tetrahedron_count = sum(len(tags) for element_type, tags
291
+ in zip(element_types, element_tags) if element_type == 4)
292
+
293
+
294
+ def _refine_at_conductor_edges(gmsh: Any, faces: List[int], edge_size: float,
295
+ max_size: float):
296
+ """
297
+ The field concentrates at conductor edges: elements are ``edge_size`` there and
298
+ grow with the distance from the nearest edge, up to ``max_size``.
299
+ """
300
+ curves = sorted({curve for _, curve in gmsh.model.getBoundary(
301
+ [(2, face) for face in faces], combined=False, oriented=False)})
302
+ longest = max(gmsh.model.occ.getMass(1, curve) for curve in curves)
303
+
304
+ fields = gmsh.model.mesh.field
305
+ distance = fields.add('Distance')
306
+ fields.setNumbers(distance, 'CurvesList', curves)
307
+ # Sample the longest edge at the element size, so the distance is not bumpy.
308
+ fields.setNumber(distance, 'Sampling', min(MAX_EDGE_SAMPLES, max(
309
+ 2, math.ceil(longest / edge_size) + 1)))
310
+ threshold = fields.add('Threshold')
311
+ fields.setNumber(threshold, 'InField', distance)
312
+ fields.setNumber(threshold, 'SizeMin', edge_size)
313
+ fields.setNumber(threshold, 'SizeMax', max_size)
314
+ fields.setNumber(threshold, 'DistMin', 0.0)
315
+ fields.setNumber(threshold, 'DistMax', (max_size - edge_size) / SIZE_GROWTH)
316
+ fields.setAsBackgroundMesh(threshold)
317
+
318
+ # The field alone decides; sizes from points or boundaries would override it.
319
+ gmsh.option.setNumber('Mesh.MeshSizeExtendFromBoundary', 0)
320
+ gmsh.option.setNumber('Mesh.MeshSizeFromPoints', 0)
321
+ gmsh.option.setNumber('Mesh.MeshSizeFromCurvature', 0)
322
+
323
+
324
+ def _groups_document(result: MeshResult) -> Dict[str, Any]:
325
+ def entry(group: PhysicalGroup) -> Dict[str, Any]:
326
+ document = asdict(group)
327
+ document.pop('dim')
328
+ if document['permittivity'] is None:
329
+ document.pop('permittivity')
330
+ return document
331
+
332
+ return {
333
+ 'generator': f"kpex-plugin-gmsh {metadata.version('kpex-plugin-gmsh')}",
334
+ 'mesh': os.path.basename(result.msh_path),
335
+ 'length_unit_m': LENGTH_UNIT_M,
336
+ 'mesh_size_edge_um': result.mesh_size_edge_um,
337
+ 'mesh_size_max_um': result.mesh_size_max_um,
338
+ 'dielectrics': [entry(group) for group in result.dielectrics],
339
+ 'terminals': [entry(group) for group in result.terminals],
340
+ 'outer_boundary': entry(result.outer_boundary) if result.outer_boundary else None,
341
+ }
@@ -0,0 +1,96 @@
1
+ #
2
+ # --------------------------------------------------------------------------------
3
+ # SPDX-FileCopyrightText: 2026 Martin Jan Köhler and Harald Pretl
4
+ # Johannes Kepler University, Institute for Integrated Circuits.
5
+ #
6
+ # This file is part of kpex-plugin-gmsh
7
+ # (see https://github.com/iic-jku/kpex-plugin-gmsh).
8
+ #
9
+ # This program is free software: you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation, either version 3 of the License, or
12
+ # (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful,
15
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
+ # GNU General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ # SPDX-License-Identifier: GPL-3.0-or-later
22
+ # --------------------------------------------------------------------------------
23
+ #
24
+
25
+ """Mesh options, shared by the exporters built on this mesh (Elmer, Palace)."""
26
+
27
+ from __future__ import annotations
28
+
29
+ from dataclasses import dataclass, fields
30
+ from typing import Any, Mapping, Optional, Type, TypeVar
31
+
32
+ from kpex.plugin_api.v1 import ExportError
33
+
34
+ _TYPES = {
35
+ 'bool': (bool,),
36
+ 'int': (int,),
37
+ 'float': (int, float),
38
+ 'str': (str,),
39
+ }
40
+
41
+
42
+ @dataclass
43
+ class GmshMeshOptions:
44
+ """Domain and mesh settings."""
45
+
46
+ field_margin_um: float = 8.0
47
+ """
48
+ How far the domain reaches beyond the finite geometry, sideways and above the
49
+ stack. Ignored when the scene carries a domain, which says it outright. Same
50
+ name and default as the FasterCap exporters' option.
51
+ """
52
+
53
+ mesh_size_edge_um: Optional[float] = None
54
+ """
55
+ Element size at conductor edges, where the field concentrates; elements grow
56
+ away from them. Unset: the thickness of the thinnest conductor layer.
57
+ """
58
+
59
+ mesh_size_max_um: Optional[float] = None
60
+ """Largest element size. Unset: 20 times the size at conductor edges."""
61
+
62
+ mesh_size_min_um: Optional[float] = None
63
+ """Smallest element size; unset leaves it to gmsh."""
64
+
65
+ verbose: bool = False
66
+ """Show gmsh's own output."""
67
+
68
+ def __post_init__(self):
69
+ for field in fields(self):
70
+ value = getattr(self, field.name)
71
+ optional = field.type.startswith('Optional[')
72
+ type_name = field.type[len('Optional['):-1] if optional else field.type
73
+ if value is None and optional:
74
+ continue
75
+ allowed = _TYPES[type_name]
76
+ if (isinstance(value, bool) and bool not in allowed) \
77
+ or not isinstance(value, allowed):
78
+ raise TypeError(f"'{field.name}' must be {type_name}"
79
+ f"{' or None' if optional else ''}, not {value!r}")
80
+ if self.field_margin_um < 0:
81
+ raise ValueError("'field_margin_um' must not be negative")
82
+ for name in ('mesh_size_edge_um', 'mesh_size_max_um', 'mesh_size_min_um'):
83
+ if getattr(self, name) is not None and getattr(self, name) <= 0:
84
+ raise ValueError(f"'{name}' must be positive")
85
+
86
+
87
+ Options = TypeVar('Options', bound=GmshMeshOptions)
88
+
89
+
90
+ def parse_options(cls: Type[Options], options: Optional[Mapping[str, Any]],
91
+ exporter_name: str) -> Options:
92
+ """Options as ``cls``; unknown names and wrong types are an ExportError."""
93
+ try:
94
+ return cls(**(options or {}))
95
+ except (TypeError, ValueError) as exc:
96
+ raise ExportError(f"Invalid options for '{exporter_name}': {exc}") from exc