mtex2gmsh 1.0.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.
mtex2gmsh/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """MTEX2Gmsh: generate conforming meshes from EBSD data processed with the Python port of MTEX.
2
+
3
+ Python port of the Matlab toolbox MTEX2Gmsh (Depriester & Kubler, JOSS 2020,
4
+ https://doi.org/10.21105/joss.02094), based on the ``mtex`` Python package and
5
+ the Gmsh Python SDK.
6
+
7
+ Examples
8
+ --------
9
+ >>> import mtex
10
+ >>> from mtex2gmsh import GmshGeo, LocalSize
11
+ >>> ebsd = mtex.mtexdata('small')
12
+ >>> grains = mtex.calcGrains(ebsd[ebsd.isIndexed])
13
+ >>> G = GmshGeo(grains)
14
+ >>> G.mesh('small.msh') # 3D wedge mesh, size = EBSD resolution
15
+ >>> G.mesh('small_tri.msh', element_type='Tri') # 2D triangular mesh
16
+ >>> G.savegeo('geometry.geo') # dump the Gmsh geometry
17
+ >>> G.export_grain_props('grains.csv') # grain ids, phases, orientations
18
+ """
19
+
20
+ from .bspline import bspline, bspline_auto
21
+ from .gmsh_geo import GeoSize, GmshGeo
22
+ from .graph import euler_path
23
+ from .local_size import LocalSize, LocalSizeEntry
24
+ from .mesh_plot import plot_mesh
25
+ from .model import Grain
26
+ from .segments import compute_segments
27
+ from .singular_points import SingularPoints, find_singular_points
28
+ from .mtex_compat import grain_num_pixel, grain_vertices, vtx_on_bounds
29
+
30
+ __version__ = "1.0.0"
31
+
32
+ __all__ = [
33
+ "GmshGeo",
34
+ "GeoSize",
35
+ "Grain",
36
+ "LocalSize",
37
+ "LocalSizeEntry",
38
+ "SingularPoints",
39
+ "bspline",
40
+ "bspline_auto",
41
+ "compute_segments",
42
+ "euler_path",
43
+ "find_singular_points",
44
+ "grain_num_pixel",
45
+ "grain_vertices",
46
+ "plot_mesh",
47
+ "vtx_on_bounds",
48
+ "__version__",
49
+ ]
mtex2gmsh/bspline.py ADDED
@@ -0,0 +1,95 @@
1
+ """B-spline approximation of a set of knots.
2
+
3
+ Thin wrapper around :class:`scipy.interpolate.BSpline` (de Boor's algorithm),
4
+ adding a ``periodic`` option for periodic approximation, as in the Matlab
5
+ ``BSpline.m`` and ``bspline_auto.m`` of MTEX2Gmsh.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ from scipy.interpolate import BSpline
12
+
13
+
14
+ def bspline(knots: np.ndarray, order: int = 3, nint: int = 10, periodic: bool = False) -> np.ndarray:
15
+ """B-spline approximation from a set of coordinates.
16
+
17
+ Parameters
18
+ ----------
19
+ knots : (n, 2) array_like
20
+ Knot coordinates: ``knots[i, j]`` is the ``j``-th coordinate of the
21
+ ``i``-th knot.
22
+ order : int, optional
23
+ Spline order (polynomial degree ``order - 1``), by default 3
24
+ (quadratic B-splines).
25
+ nint : int, optional
26
+ Number of sampled points per knot interval, by default 10.
27
+ periodic : bool, optional
28
+ If True, periodic conditions are used at the end knots. This remains
29
+ an approximation, not an interpolation: the knots stay control
30
+ points. By default False.
31
+
32
+ Returns
33
+ -------
34
+ (m, 2) ndarray
35
+ The sampled B-spline curve (``(nint - 1) * (n - 1) + 1`` points for
36
+ open splines; only the periodic part is kept for closed ones).
37
+ """
38
+ knots = np.asarray(knots, dtype=float)
39
+ knots_in = knots
40
+ if periodic:
41
+ knots = np.vstack([knots[-order:], knots, knots[:order]])
42
+
43
+ p, q = knots.shape
44
+ if p <= 2:
45
+ return knots.copy()
46
+
47
+ n = (nint - 1) * (p - 1) + 1 # overall number of queried points
48
+ y = np.linspace(0, 1, n)
49
+
50
+ order = min(order, p)
51
+ t = np.concatenate([np.zeros(order - 1), np.linspace(0, 1, p - order + 2), np.ones(order - 1)])
52
+
53
+ BS = BSpline(t, knots, order - 1, extrapolate=False)(y)
54
+ BS[0, :] = knots[0, :]
55
+ BS[-1, :] = knots[-1, :]
56
+
57
+ if periodic:
58
+ # 1-based bounds of the periodic part, as in the Matlab code
59
+ k = np.searchsorted(t, y[:-1], side="right") - 1
60
+ m = np.arange(1, n)
61
+ low = k <= order
62
+ high = k >= p - order + 1
63
+ m_min = int(m[low].max()) if low.any() else 1
64
+ m_max = int(m[high].min()) if high.any() else n
65
+ BS = BS[m_min - 1 : m_max - 1, :]
66
+ if BS.shape[0] == 0:
67
+ # Degenerate (too short) periodic input: fall back to the knots
68
+ return knots_in.copy()
69
+ BS[-1, :] = BS[0, :]
70
+ return BS
71
+
72
+
73
+ def bspline_auto(V: np.ndarray, nint: int = 10) -> np.ndarray:
74
+ """Automatic choice of the B-spline order for a polyline ``V``.
75
+
76
+ Closed polylines (first knot == last knot) use a periodic B-spline,
77
+ open ones a clamped B-spline of order 4.
78
+
79
+ Parameters
80
+ ----------
81
+ V : (n, 2) array_like
82
+ Coordinates of the polyline vertices.
83
+ nint : int, optional
84
+ Number of sampled points per knot interval, by default 10.
85
+
86
+ Returns
87
+ -------
88
+ (m, 2) ndarray
89
+ The sampled B-spline curve.
90
+ """
91
+ V = np.asarray(V, dtype=float)
92
+ if np.array_equal(V[0], V[-1]):
93
+ order = 3 if len(V) == 4 else 4
94
+ return bspline(V[:-1], order=order, nint=nint, periodic=True)
95
+ return bspline(V, order=4, nint=nint)
@@ -0,0 +1,500 @@
1
+ """Generation of Gmsh ``.geo`` files from a :class:`GmshGeo`.
2
+
3
+ Port of the geometry-dumping part of the Matlab ``@gmshGeo/mesh.m``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from dataclasses import dataclass, field
10
+ from datetime import datetime
11
+
12
+ import numpy as np
13
+
14
+ from .local_size import LocalSize
15
+ from .loops import border_loop, print_min, unique_loops, write_sequence
16
+
17
+ VALID_ELEMENT_TYPES = ("Wedge", "Hex", "Tet", "Tri", "Quad", "HexOnly", "QuadOnly")
18
+
19
+ _ELEMENT_TYPE_ALIASES = {
20
+ "tetrahedron": "Tet",
21
+ "hexahedron": "Hex",
22
+ "brick": "Hex",
23
+ "triangular": "Tri",
24
+ "quadrangular": "Quad",
25
+ "hexahedrononly": "HexOnly",
26
+ "brickonly": "HexOnly",
27
+ "quadrangularonly": "QuadOnly",
28
+ }
29
+
30
+
31
+ def normalize_element_type(element_type: str) -> str:
32
+ """Normalize an element type name to one of :data:`VALID_ELEMENT_TYPES`.
33
+
34
+ Parameters
35
+ ----------
36
+ element_type : str
37
+ Element type, e.g. ``'Wedge'``, ``'Tet'``, ... Aliases such as
38
+ 'Tetrahedron', 'Hexahedron', 'Brick', 'Triangular', 'Quadrangular'
39
+ (and their ``...Only`` variants) are accepted, case-insensitively.
40
+
41
+ Returns
42
+ -------
43
+ str
44
+ The canonical element type name.
45
+
46
+ Raises
47
+ ------
48
+ ValueError
49
+ If ``element_type`` is not recognized.
50
+ """
51
+ et = str(element_type)
52
+ low = et.lower()
53
+ if low in _ELEMENT_TYPE_ALIASES:
54
+ return _ELEMENT_TYPE_ALIASES[low]
55
+ for valid in VALID_ELEMENT_TYPES:
56
+ if et.lower() == valid.lower():
57
+ return valid
58
+ raise ValueError(
59
+ f"Unrecognized element type {element_type!r}. It can be: {', '.join(repr(v) for v in VALID_ELEMENT_TYPES)}."
60
+ )
61
+
62
+
63
+ @dataclass
64
+ class MeshOptions:
65
+ """Meshing options, mirroring the name-value arguments of the Matlab ``mesh``.
66
+
67
+ Attributes
68
+ ----------
69
+ element_size : float
70
+ Element size; 0 (default) means the EBSD resolution of the geometry.
71
+ thickness : float
72
+ Extrusion thickness for 3D meshes; 0 (default) means the element
73
+ size.
74
+ gradient : float
75
+ Size gradient slope ``k``: element size ``s + k*d`` at distance
76
+ ``d`` from the boundaries; 0 (default) disables it.
77
+ element_type : str
78
+ 'Wedge' (default), 'Hex', 'Tet', 'Tri', 'Quad', 'HexOnly' or
79
+ 'QuadOnly' (aliases accepted, see :func:`normalize_element_type`).
80
+ element_order : int
81
+ 1 (default) or 2 for quadratic elements.
82
+ curvature : int
83
+ Number of nodes per 2*pi for curvature-based sizing; 0 (default)
84
+ disables it.
85
+ medium : tuple of float
86
+ ``(dx, dy[, dz])`` dimensions of a surrounding medium embedding the
87
+ ROI; ``(0, 0, 0)`` (default) disables it.
88
+ medium_element_size : float
89
+ Element size at the corners of the medium; 0 (default) lets it be
90
+ computed from the distance to the ROI.
91
+ grain_prefix : str
92
+ Prefix of the physical group names (``'Grain_'`` by default); an
93
+ empty string gives plain numbering.
94
+ verbosity : int
95
+ Gmsh verbosity, 0-10 (default 4).
96
+ partition : int
97
+ Number of partitions for parallel computing; 0 (default) disables
98
+ partitioning.
99
+ periodic : str
100
+ 'x', 'y', 'both' or 'none' (default).
101
+ local_size : LocalSize or None
102
+ Per-grain element sizes, by default None.
103
+ layers : int
104
+ Number of element layers through the thickness, by default 1.
105
+ grain_boundaries_only : bool
106
+ If True, mesh only the grain boundaries (surfacic), by default False.
107
+ externalize_gbs : str
108
+ Path of an additional surfacic GB-only mesh file to write as well;
109
+ empty (default) disables it.
110
+ """
111
+
112
+ element_size: float = 0.0
113
+ thickness: float = 0.0
114
+ gradient: float = 0.0
115
+ element_type: str = "Wedge"
116
+ element_order: int = 1
117
+ curvature: int = 0
118
+ medium: tuple = (0.0, 0.0, 0.0)
119
+ medium_element_size: float = 0.0
120
+ grain_prefix: str = "Grain_"
121
+ verbosity: int = 4
122
+ partition: int = 0
123
+ periodic: str = "none"
124
+ local_size: LocalSize | None = None
125
+ layers: int = 1
126
+ grain_boundaries_only: bool = False
127
+ externalize_gbs: str = ""
128
+
129
+ @classmethod
130
+ def from_kwargs(cls, kwargs: dict) -> "MeshOptions":
131
+ """Build a :class:`MeshOptions` from a dict of keyword arguments.
132
+
133
+ Parameters
134
+ ----------
135
+ kwargs : dict
136
+ Option names and values, as accepted by
137
+ :meth:`mtex2gmsh.GmshGeo.mesh`.
138
+
139
+ Returns
140
+ -------
141
+ MeshOptions
142
+ The populated options.
143
+
144
+ Raises
145
+ ------
146
+ TypeError
147
+ If ``kwargs`` contains unknown option names.
148
+ """
149
+ known = {f for f in cls.__dataclass_fields__}
150
+ unknown = set(kwargs) - known
151
+ if unknown:
152
+ raise TypeError(f"Unknown mesh option(s): {', '.join(sorted(unknown))}")
153
+ return cls(**kwargs)
154
+
155
+
156
+ def _fmt(x) -> str:
157
+ return f"{float(x):g}"
158
+
159
+
160
+ def write_geo(G, path: str, o: MeshOptions, a_seg: np.ndarray | None = None) -> None:
161
+ """Write the Gmsh ``.geo`` file describing the geometry of ``G``.
162
+
163
+ Parameters
164
+ ----------
165
+ G : GmshGeo
166
+ The geometry to dump.
167
+ path : str
168
+ Path of the ``.geo`` file to write.
169
+ o : MeshOptions
170
+ The meshing options.
171
+ a_seg : (n, 2) array_like, optional
172
+ Pairs of symmetric segment ids (periodicity conditions), by default
173
+ None.
174
+ """
175
+ elem_type = normalize_element_type(o.element_type)
176
+ mesh3d = elem_type in ("Hex", "Wedge", "Tet", "HexOnly")
177
+
178
+ default_element_size = float(o.element_size) if o.element_size else G.resolution
179
+ medium = tuple(float(v) for v in o.medium) != (0.0, 0.0, 0.0)
180
+ medium_element_size = float(o.medium_element_size)
181
+ if medium_element_size and not medium:
182
+ raise ValueError("Specify the size of the embedding medium first with option 'medium'.")
183
+ slope = float(o.gradient)
184
+ thickness = float(np.atleast_1d(o.thickness)[0]) if o.thickness else default_element_size
185
+ if o.thickness and not mesh3d:
186
+ raise ValueError(f"{elem_type} elements are not compatible with a 2D mesh (thickness given).")
187
+ curv = int(o.curvature)
188
+ if curv and slope:
189
+ import warnings
190
+
191
+ warnings.warn(
192
+ "Non constant element sizes at boundaries are inconsistent with the 'gradient' option. "
193
+ "You might get unexpected results."
194
+ )
195
+
196
+ segments = [np.asarray(s, dtype=np.int64) for s in G.segments]
197
+ vtx = np.asarray(G.V, dtype=float)
198
+
199
+ # The microstructure is embedded in a medium
200
+ if medium:
201
+ roi = G.size().roi
202
+ dx, dy = float(o.medium[0]), float(o.medium[1])
203
+ if mesh3d:
204
+ dz = float(o.medium[2])
205
+ dmin = min((dx - roi[0]) / 2, (dy - roi[1]) / 2, dz - thickness)
206
+ if dmin < 0:
207
+ raise ValueError(
208
+ f"The dimensions of the medium must be larger than that of the ROI ({roi[0]:g} {roi[1]:g} {thickness:g})."
209
+ )
210
+ else:
211
+ dz = 0.0
212
+ dmin = min((dx - roi[0]) / 2, (dy - roi[1]) / 2)
213
+ if dmin < 0:
214
+ raise ValueError(f"The dimensions of the medium must be larger than that of the ROI ({roi[0]:g} {roi[1]:g}).")
215
+ xmin, xmax = vtx[:, 0].min(), vtx[:, 0].max()
216
+ ymin, ymax = vtx[:, 1].min(), vtx[:, 1].max()
217
+ center = np.array([(xmax + xmin) / 2, (ymax + ymin) / 2])
218
+ corners = np.array(
219
+ [
220
+ center + np.array([-dx, -dy]) / 2,
221
+ center + np.array([-dx, dy]) / 2,
222
+ center + np.array([dx, dy]) / 2,
223
+ center + np.array([dx, -dy]) / 2,
224
+ ]
225
+ )
226
+ n_vtx = len(vtx)
227
+ vtx = np.vstack([vtx, corners])
228
+ new_segments = np.array(
229
+ [[n_vtx + 1, n_vtx + 2], [n_vtx + 2, n_vtx + 3], [n_vtx + 3, n_vtx + 4], [n_vtx + 4, n_vtx + 1]],
230
+ dtype=np.int64,
231
+ )
232
+ for row in new_segments:
233
+ segments.append(row.copy())
234
+ if medium_element_size == 0:
235
+ q = 1.5
236
+ n = np.log(1 + dmin / default_element_size * (q - 1)) / np.log(q)
237
+ medium_element_size = default_element_size * q**n
238
+
239
+ # Numbering the line loops
240
+ line_loops, plane_surface = unique_loops(G.grains)
241
+
242
+ n_vtx = len(vtx)
243
+ vtx_used = np.zeros(n_vtx + 1, dtype=bool)
244
+ for s in segments:
245
+ vtx_used[s] = True
246
+ vtx_used = vtx_used[1:]
247
+
248
+ n_segments = len(segments)
249
+ n_loops = len(line_loops)
250
+ n_surfaces = len(G.grains)
251
+
252
+ thickness_name = "th"
253
+ default_element_size_name = "e_def"
254
+ medium_thickness_name = "th_med"
255
+ medium_element_size_name = "e_med"
256
+
257
+ lines: list[str] = []
258
+ lines.append(f"// File generated with MTEX2Gmsh on {datetime.now():%Y-%m-%d %H:%M:%S}\n")
259
+ lines.append("// Mesh parameters")
260
+ lines.append(f"{thickness_name}={_fmt(thickness)};")
261
+ lines.append(f"{default_element_size_name}={_fmt(default_element_size)};")
262
+ if medium:
263
+ lines.append(f"{medium_thickness_name}={_fmt(dz)};")
264
+ lines.append(f"{medium_element_size_name}={_fmt(medium_element_size)};")
265
+
266
+ # Check if local size is requested
267
+ local_size = o.local_size
268
+ local_size_names: list[str] = []
269
+ A = np.zeros((n_vtx, 0), dtype=bool)
270
+ if local_size is not None and len(local_size):
271
+ cols = []
272
+ for i, entry in enumerate(local_size):
273
+ name = f"e_Grain_{entry.grain_id}"
274
+ local_size_names.append(name)
275
+ lines.append(f"{name}={_fmt(entry.size_at_boundaries)};")
276
+ g = next((gr for gr in G.grains if gr.id == entry.grain_id), None)
277
+ if g is None:
278
+ raise ValueError(f"No grain with id {entry.grain_id} in the geometry.")
279
+ out_seg_ids = np.abs(np.asarray(g.outer_loop, dtype=np.int64))
280
+ in_seg_ids = (
281
+ np.concatenate([np.abs(np.asarray(l, dtype=np.int64)) for l in g.inner_loops])
282
+ if g.inner_loops
283
+ else np.zeros(0, dtype=np.int64)
284
+ )
285
+ seg_ids = np.concatenate([out_seg_ids, in_seg_ids])
286
+ vtx_ids = np.unique(np.concatenate([np.asarray(segments[s - 1]) for s in seg_ids]))
287
+ col = np.zeros(n_vtx, dtype=bool)
288
+ col[vtx_ids - 1] = True
289
+ cols.append(col)
290
+ A = np.column_stack(cols)
291
+
292
+ lines.append('\nSetFactory("OpenCASCADE");')
293
+
294
+ # Vertices
295
+ lines.append("\n// Vertices")
296
+ for i in range(1, n_vtx + 1):
297
+ if not vtx_used[i - 1]:
298
+ continue
299
+ x, y = vtx[i - 1]
300
+ if medium:
301
+ size_expr = medium_element_size_name
302
+ elif A.size and A[i - 1].any():
303
+ size_expr = print_min([local_size_names[j] for j in np.flatnonzero(A[i - 1])])
304
+ else:
305
+ size_expr = default_element_size_name
306
+ lines.append(f"Point({i})={{{_fmt(x)},{_fmt(y)},0,{size_expr}}};")
307
+
308
+ # (B-)Splines
309
+ lines.append("\n// Grain boundaries")
310
+ for i, seg in enumerate(segments, start=1):
311
+ if len(seg) == 2:
312
+ write_sequence(lines, "Line", i, seg)
313
+ elif len(seg) == 3 and curv != 0:
314
+ write_sequence(lines, "Spline", i, seg)
315
+ else:
316
+ write_sequence(lines, "BSpline", i, seg)
317
+
318
+ if o.grain_boundaries_only:
319
+ # The user only requests the grain boundaries
320
+ k = 1
321
+ for name, seg_ids in G.interfaces.items():
322
+ lines.append("\n// 2D Interfaces")
323
+ surfaces = np.asarray(seg_ids, dtype=np.int64)
324
+ n_surf = len(surfaces)
325
+ line_seq: list[str] = []
326
+ write_sequence(line_seq, "Line", None, surfaces)
327
+ lines.append(f"Extrude {{0,0,{thickness_name}}}{{\n\t{line_seq[0].rstrip()}\n\tLayers{{{int(o.layers)}}};}}")
328
+ lines.append(f'Physical Surface("{name}")={{{k}:{k + n_surf}}};')
329
+ k = k + n_surf + 1
330
+ else:
331
+ # Closed loops
332
+ lines.append("\n// Closed Loops")
333
+ for i, loop in enumerate(line_loops, start=1):
334
+ write_sequence(lines, "Line Loop", i, loop)
335
+
336
+ # Surfaces
337
+ lines.append("\n// Grains")
338
+ for i, ps in enumerate(plane_surface, start=1):
339
+ write_sequence(lines, "Plane Surface", i, ps)
340
+
341
+ if elem_type in ("Hex", "Quad", "HexOnly", "QuadOnly"):
342
+ lines.append("\n// Quadrangular elements")
343
+ lines.append(f"Recombine Surface{{1:{n_surfaces}}};")
344
+
345
+ # Extrusions
346
+ if mesh3d:
347
+ lines.append("\n// 3D geometry")
348
+ lines.append(f"Extrude {{0,0,{thickness_name}}}{{\n\tSurface{{1:{n_surfaces}}};\n\tLayers{{{int(o.layers)}}};" + ("\tRecombine;" if elem_type != "Tet" else "") + "\n}")
349
+
350
+ # Add surrounding medium (if requested)
351
+ if medium:
352
+ n_surfaces_tot = n_surfaces + 1
353
+ lines.append("\n// Add surrounding medium")
354
+ idx_shift = 10000
355
+
356
+ bl = border_loop(G)
357
+ if dz > thickness: # Add medium below the ROI
358
+ lines.append(f"L[]=Extrude{{0,0,{thickness_name}-{medium_thickness_name}}}{{\n\t")
359
+ write_sequence(lines, "Line", None, np.abs(bl))
360
+ lines.append("};")
361
+ n_loops += 1
362
+ seq = []
363
+ for i in range(len(bl)):
364
+ j = (i) * 4
365
+ seq.append(f"L[{j}]" if bl[i] > 0 else f"-L[{j}]")
366
+ lines.append(f"Line Loop({n_loops + idx_shift})={{{','.join(seq)}}};")
367
+ id_surface_loop = n_surfaces + 1
368
+ write_sequence(lines, "Plane Surface", id_surface_loop + idx_shift + 1, [n_loops + idx_shift])
369
+ side = [f"L[{i * 4 - 3}]," for i in range(1, len(bl) + 1)]
370
+ lines.append(
371
+ f"Surface Loop({id_surface_loop + idx_shift + 1})={{\n\t"
372
+ + "".join(side)
373
+ + f"\n\t1:{n_surfaces},{id_surface_loop + idx_shift + 1}\n}};"
374
+ )
375
+ write_sequence(lines, "Volume", n_surfaces + 1, [id_surface_loop + idx_shift + 1])
376
+ n_surfaces_tot += 2
377
+
378
+ # Create a volume surrounding the ROI
379
+ n_loops += 1
380
+ write_sequence(lines, "Line Loop", n_loops + 2 * idx_shift + 1, np.arange(n_segments - 3, n_segments + 1))
381
+ n_loops += 1
382
+ write_sequence(lines, "Line Loop", n_loops + 2 * idx_shift + 1, bl)
383
+ if mesh3d:
384
+ write_sequence(lines, "Plane Surface", n_surfaces + 2 + 2 * idx_shift, [n_loops - 1 + 2 * idx_shift + 1, n_loops + 2 * idx_shift + 1])
385
+ else:
386
+ write_sequence(lines, "Plane Surface", n_surfaces + 1 + 2 * idx_shift, [n_loops - 1 + 2 * idx_shift + 1, n_loops + 2 * idx_shift + 1])
387
+ if dz > thickness:
388
+ lines.append(f"Extrude {{0,0,{thickness_name}-{medium_thickness_name}}}{{\n\tSurface{{{n_surfaces + 2 + 2 * idx_shift}}};\n}}")
389
+ if mesh3d:
390
+ lines.append(
391
+ f"Extrude {{0,0,{thickness_name}}}{{\n\tSurface{{{n_surfaces + 2 + 2 * idx_shift}}};\n\tLayers{{1}}; Recombine;\n}}"
392
+ )
393
+
394
+ lines.append(f"Characteristic Length {{1:{n_vtx - 4}}} = {default_element_size_name};")
395
+
396
+ # Physical groups
397
+ groupname = "Volume" if mesh3d else "Surface"
398
+ ids = np.array([g.id for g in G.grains], dtype=np.int64)
399
+ lines.append("\n// Sets")
400
+ if np.array_equal(ids, np.arange(1, n_surfaces + 1)):
401
+ lines.append(f"For k In {{1:{n_surfaces}}}")
402
+ if not o.grain_prefix:
403
+ lines.append(f"\tPhysical {groupname}(k)={{k}};")
404
+ else:
405
+ lines.append(f'\tPhysical {groupname}(Sprintf("{o.grain_prefix}%g",k))={{k}};')
406
+ lines.append("EndFor")
407
+ else:
408
+ for i, gid in enumerate(ids, start=1):
409
+ if not o.grain_prefix:
410
+ lines.append(f"Physical {groupname}({int(gid)})={{{i}}};")
411
+ else:
412
+ lines.append(f'Physical {groupname}("{o.grain_prefix}_{int(gid)}")={{{i}}};')
413
+ if medium:
414
+ if mesh3d:
415
+ write_sequence(lines, f"Physical {groupname}", '"Medium"', np.arange(n_surfaces + 1, n_surfaces_tot + 1))
416
+ else:
417
+ write_sequence(lines, f"Physical {groupname}", '"Medium"', [n_surfaces + 1 + 2 * idx_shift])
418
+
419
+ if a_seg is not None and len(a_seg):
420
+ lines.append("\n// Periodicity conditions")
421
+ for row in np.atleast_2d(a_seg):
422
+ lines.append(f"Periodic Line {{{int(row[0])}}} = {{{int(row[1])}}};")
423
+
424
+ # Mesh
425
+ lines.append("\n// Mesh")
426
+ if not o.grain_boundaries_only:
427
+ lines.append("Mesh.SubdivisionAlgorithm=0;")
428
+ if elem_type in ("HexOnly", "QuadOnly"):
429
+ mesh_algo = 8
430
+ else:
431
+ mesh_algo = 7 if (slope != 0 and not mesh3d) else 6
432
+ lines.append(f"Mesh.Algorithm={mesh_algo};")
433
+ lines.append("Mesh.CharacteristicLengthExtendFromBoundary=1;")
434
+ lines.append(f"Mesh.ElementOrder={int(o.element_order)};")
435
+ if curv != 0:
436
+ lines.append("Mesh.CharacteristicLengthFromCurvature = 1;")
437
+ lines.append(f"Mesh.MinimumCirclePoints = {curv}; // points per 2*pi")
438
+ if slope != 0 or (local_size is not None and np.any(local_size.slopes != 0)):
439
+ id_field = _add_attractor_field(lines, 1, n_segments, default_element_size, slope)
440
+ if local_size is not None and len(local_size):
441
+ restrict_fields = []
442
+ surface_list = np.arange(1, n_surfaces + 1)
443
+ ls_ids = local_size.grain_ids
444
+ surfaces_with_def_size = surface_list[~np.isin(ids, ls_ids)]
445
+ id_field = _add_restrict_field(lines, id_field + 1, surfaces_with_def_size)
446
+ restrict_fields.append(id_field)
447
+ for entry in local_size:
448
+ id_field = _add_attractor_field(lines, id_field + 1, n_segments, entry.size_at_boundaries, entry.slope)
449
+ surf_ls = surface_list[np.isin(ids, [entry.grain_id])]
450
+ id_field = _add_restrict_field(lines, id_field + 1, surf_ls)
451
+ restrict_fields.append(id_field)
452
+ lines.append(f"Field[{id_field + 1}] = Min;")
453
+ lines.append(f"Field[{id_field + 1}].FieldsList = {{{','.join(str(int(f)) for f in restrict_fields)}}};")
454
+ id_field += 1
455
+ lines.append(f"Background Field={id_field};")
456
+ lines.append("Mesh.CharacteristicLengthExtendFromBoundary=0;")
457
+ lines.append("Mesh 2;")
458
+ lines.append("Mesh.CharacteristicLengthExtendFromBoundary=1;")
459
+ if elem_type in ("HexOnly", "QuadOnly"):
460
+ lines.append("Mesh.RecombineAll = 0;")
461
+ lines.append("Mesh.SaveParametric = 0;")
462
+ lines.append("Mesh.RecombinationAlgorithm = 0;")
463
+ lines.append("Mesh.SecondOrderLinear = 1;")
464
+ lines.append("Mesh.SubdivisionAlgorithm=1;")
465
+ lines.append(f"Mesh.MeshSizeFactor={_fmt(1)};")
466
+ lines.append("RefineMesh;")
467
+ if slope == 0.0:
468
+ lines.append("Mesh 2;")
469
+ if medium:
470
+ lines.append("Mesh.Algorithm3D=4;")
471
+
472
+ if mesh3d and not o.grain_boundaries_only:
473
+ lines.append("Mesh 3;")
474
+ else:
475
+ lines.append("Mesh 2;")
476
+
477
+ if o.partition:
478
+ lines.append("\n// Partition mesh")
479
+ lines.append(f"PartitionMesh {int(o.partition)};")
480
+
481
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
482
+ with open(path, "w") as f:
483
+ f.write("\n".join(lines) + "\n")
484
+
485
+
486
+ def _add_attractor_field(lines: list[str], id_field: int, n_segments: int, def_size: float, slope: float) -> int:
487
+ lines.append(f"Field[{id_field}] = Distance;")
488
+ lines.append(f"Field[{id_field}].EdgesList ={{1:{n_segments}}};")
489
+ id_field += 1
490
+ lines.append(f"Field[{id_field}] = MathEval;")
491
+ lines.append(f'Field[{id_field}].F = "F{id_field - 1}*{_fmt(slope)}+{_fmt(def_size)}";')
492
+ return id_field
493
+
494
+
495
+ def _add_restrict_field(lines: list[str], id_field: int, surface_list) -> int:
496
+ lines.append(f"Field[{id_field}] = Restrict;")
497
+ lines.append(f"Field[{id_field}].InField = {id_field - 1};")
498
+ sl = ",".join(str(int(s)) for s in np.atleast_1d(surface_list))
499
+ lines.append(f"Field[{id_field}].SurfacesList = {{{sl}}};")
500
+ return id_field