-
Notifications
You must be signed in to change notification settings - Fork 33
/
mesh.py
642 lines (567 loc) · 27.1 KB
/
mesh.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
from collections import OrderedDict
from itertools import combinations, product
from typing import Dict, List, Optional, Tuple
import gmsh
import numpy as np
import pygmsh
import shapely
from shapely.geometry import (
LinearRing,
LineString,
MultiLineString,
MultiPolygon,
Point,
Polygon,
)
from shapely.ops import linemerge, polygonize, snap, split, unary_union
from femwell.mesh.meshtracker import MeshTracker
initial_settings = np.seterr() # remove when shapely updated to more recent geos
def break_line_(line, other_line, snap_tol):
np.seterr(invalid="ignore")
intersections = line.intersection(other_line)
np.seterr(**initial_settings)
if not intersections.is_empty:
for intersection in (
intersections.geoms if hasattr(intersections, "geoms") else [intersections]
):
# if type == "", intersection.type != 'Point':
if intersection.geom_type == "Point":
line = snap(line, intersection, snap_tol)
else:
new_coords_start, new_coords_end = intersection.boundary.geoms
line = linemerge(split(line, new_coords_start))
line = linemerge(split(line, new_coords_end))
return line
def mesh_from_Dict(
shapes_dict: Dict,
resolutions: Optional[Dict[str, Dict[str, float]]] = None,
default_resolution_min: float = 0.01,
default_resolution_max: float = 0.5,
filename: Optional[str] = None,
gmsh_algorithm: int = 5,
global_quad: Optional[bool] = False,
verbose: bool = False,
):
"""
Given a dict of shapely Polygons, creates a mesh conformal to all the BooleanFragment surfaces and interfaces from the intersection of all polygons.
Returns a mesh with physicals corresponding to the original shapes_dict boundaries (which may comprise multiple surface entities)
"""
with pygmsh.occ.geometry.Geometry() as geometry:
# geometry = pygmsh.occ.geometry.Geometry()
geometry.characteristic_length_min = default_resolution_min
geometry.characteristic_length_max = default_resolution_max
gmsh.option.setNumber("Mesh.Algorithm", gmsh_algorithm)
model = geometry
# Add overall bounding box
total = unary_union(list(shapes_dict.values()))
all_polygons = [total, *list(shapes_dict.values())]
# Break up all shapes so that plane is tiled with non-overlapping layers, get the maximal number of fragments
# Equivalent to BooleanFragments
np.seterr(invalid="ignore")
listpoly = [a.intersection(b) for a, b in combinations(all_polygons, 2)]
np.seterr(**initial_settings)
rings = [
LineString(list(object.exterior.coords))
for object in listpoly
if not (
object.geom_type in ["Point", "LineString", "MultiLineString"] or object.is_empty
)
]
union = unary_union(rings)
shapes_tiled_list = list(polygonize(union))
# Add surfaces, logging lines
meshtracker = MeshTracker(model=model)
for i, polygon in enumerate(shapes_tiled_list):
meshtracker.add_xy_surface(polygon, i, physical=False)
# Tag physicals
# TODO integrate in meshtracker
surface_name_mapping = {}
surface_resolution_mapping = {}
for polygon_name, polygons in shapes_dict.items():
surfaces = []
surface_indices = []
for polygon in polygons.geoms if hasattr(polygons, "geoms") else [polygons]:
# Identify enclosed surfaces
for index in range(len(meshtracker.shapely_xy_surfaces)):
if polygon.contains(meshtracker.shapely_xy_surfaces[index]):
surfaces.append(meshtracker.gmsh_xy_surfaces[index])
surface_indices.append(index)
if resolutions:
if index in surface_resolution_mapping:
surface_resolution_mapping[index] = min(
resolutions[polygon_name]["resolution"],
surface_resolution_mapping[index],
)
else:
surface_resolution_mapping[index] = min(
resolutions[polygon_name]["resolution"],
default_resolution_max,
)
meshtracker.model.add_physical(surfaces, polygon_name)
surface_name_mapping[polygon_name] = surface_indices
current_resolutions = []
if resolutions:
# Refinement in surfaces
n = 0
refinement_fields = []
for surface_indices in surface_name_mapping.values():
for surface_index in surface_indices:
gmsh.model.mesh.field.add("MathEval", n)
gmsh.model.mesh.field.setString(
n, "F", f"{surface_resolution_mapping[surface_index]}"
)
gmsh.model.mesh.field.add("Restrict", n + 1)
gmsh.model.mesh.field.setNumber(n + 1, "InField", n)
gmsh.model.mesh.field.setNumbers(
n + 1,
"SurfacesList",
[meshtracker.gmsh_xy_surfaces[surface_index]._id],
)
# # Around surface
# mesh_distance = mesh_setting["distance"]
# gmsh.model.mesh.field.add("Distance", n+2)
# gmsh.model.mesh.field.setNumbers(n+2, "CurvesList", meshtracker.get_gmsh_xy_lines_from_label(label))
# gmsh.model.mesh.field.setNumber(n+2, "Sampling", 100)
# gmsh.model.mesh.field.add("Threshold", n+3)
# gmsh.model.mesh.field.setNumber(n+3, "InField", n+2)
# gmsh.model.mesh.field.setNumber(n+3, "SizeMin", mesh_resolution)
# gmsh.model.mesh.field.setNumber(n+3, "SizeMax", default_resolution_max)
# gmsh.model.mesh.field.setNumber(n+3, "DistMin", 0)
# gmsh.model.mesh.field.setNumber(n+3, "DistMax", mesh_distance)
# Save and increment
refinement_fields.append(n + 1)
# refinement_fields.append(n+3)
n += 2
if global_quad:
gmsh.option.setNumber("Mesh.Algorithm", 8)
gmsh.option.setNumber("Mesh.RecombineAll", 1)
# Use the smallest element size overall
gmsh.model.mesh.field.add("Min", n)
gmsh.model.mesh.field.setNumbers(n, "FieldsList", refinement_fields)
gmsh.model.mesh.field.setAsBackgroundMesh(n)
gmsh.model.mesh.MeshSizeFromPoints = 0
gmsh.model.mesh.MeshSizeFromCurvature = 0
gmsh.model.mesh.MeshSizeExtendFromBoundary = 0
# Fuse edges (bandaid)
# gmsh.model.occ.synchronize()
# gmsh.model.occ.removeAllDuplicates()
# gmsh.model.occ.synchronize()
# Extract all unique lines (TODO: identify interfaces in label)
# i = 0
# for index, line in enumerate(meshtracker.gmsh_xy_segments):
# model.add_physical(line, f"{meshtracker.xy_segments_main_labels[index]}_{meshtracker.xy_segments_secondary_labels[index]}_{i}")
# i += 1
# For periodicity
mesh = geometry.generate_mesh(dim=2, verbose=verbose)
if filename:
gmsh.write(f"{filename}")
return mesh
def mesh_from_OrderedDict(
shapes_dict: OrderedDict,
resolutions: Optional[Dict[str, Dict[str, float]]] = None,
default_resolution_min: float = 1e-12,
default_resolution_max: float = 0.5,
filename: Optional[str] = None,
gmsh_algorithm: int = 5,
global_quad: Optional[bool] = False,
verbose: bool = False,
periodic_lines: Optional[Tuple[(str, str)]] = None,
mesh_scaling_factor: float = 1.0,
):
"""
Given an ordered dict of shapely Polygons, creates a mesh containing polygon surfaces according to the dict order.
Returns a gmsh msh with physicals corresponding to the shapes_dict boundaries (which is the minimal number of surfaces for each key)
periodic_lines: (label1, label1) tuples forcing the mesh of line[label1] to map to the mesh of line[label2]. Currently only works if the lines are not intersected.
"""
with pygmsh.occ.geometry.Geometry() as geometry:
# geometry = pygmsh.occ.geometry.Geometry()
geometry.characteristic_length_min = default_resolution_min
geometry.characteristic_length_max = default_resolution_max
gmsh.option.setNumber("Mesh.Algorithm", gmsh_algorithm)
model = geometry
meshtracker = MeshTracker(model=model)
# Break up shapes in order so that plane is tiled with non-overlapping layers, overriding shapes according to an order
shapes_tiled_dict = OrderedDict()
for lower_index, (lower_name, lower_shape) in reversed(
list(enumerate(shapes_dict.items()))
):
diff_shape = lower_shape
for higher_index, (higher_name, higher_shape) in reversed(
list(enumerate(shapes_dict.items()))[:lower_index]
):
diff_shape = diff_shape.difference(higher_shape)
shapes_tiled_dict[lower_name] = diff_shape
# Break up lines and polygon edges so that plane is tiled with no partially overlapping line segments
polygons_broken_dict = OrderedDict()
lines_broken_dict = OrderedDict()
for first_index, (first_name, first_shape) in enumerate(shapes_dict.items()):
first_shape = shapes_tiled_dict[first_name]
broken_shapes = []
for first_shape in (
first_shape.geoms if hasattr(first_shape, "geoms") else [first_shape]
):
# First line exterior
first_exterior_line = (
LineString(first_shape.exterior)
if first_shape.geom_type == "Polygon"
else first_shape
)
for second_index, (second_name, second_shapes) in enumerate(shapes_dict.items()):
# Do not compare to itself
if second_name == first_name:
continue
else:
second_shapes = shapes_tiled_dict[second_name]
for second_shape in (
second_shapes.geoms
if hasattr(second_shapes, "geoms")
else [second_shapes]
):
# Second line exterior
second_exterior_line = (
LineString(second_shape.exterior)
if second_shape.geom_type == "Polygon"
else second_shape
)
first_exterior_line = break_line_(
first_exterior_line, second_exterior_line, meshtracker.atol
)
# Second line interiors
for second_interior_line in (
second_shape.interiors
if second_shape.geom_type == "Polygon"
else []
):
second_interior_line = LineString(second_interior_line)
first_exterior_line = break_line_(
first_exterior_line, second_interior_line, meshtracker.atol
)
# First line interiors
if first_shape.geom_type in ["Polygon", "MultiPolygon"]:
first_shape_interiors = []
for first_interior_line in first_shape.interiors:
first_interior_line = LineString(first_interior_line)
for second_index, (second_name, second_shapes) in enumerate(
shapes_dict.items()
):
if second_name == first_name:
continue
else:
second_shapes = shapes_tiled_dict[second_name]
for second_shape in (
second_shapes.geoms
if hasattr(second_shapes, "geoms")
else [second_shapes]
):
# Exterior
second_exterior_line = (
LineString(second_shape.exterior)
if second_shape.geom_type == "Polygon"
else second_shape
)
first_interior_line = break_line_(
first_interior_line, second_exterior_line, meshtracker.atol
)
# Interiors
for second_interior_line in (
second_shape.interiors
if second_shape.geom_type == "Polygon"
else []
):
second_interior_line = LineString(second_interior_line)
np.seterr(invalid="ignore")
intersections = first_interior_line.intersection(
second_interior_line
)
np.seterr(**initial_settings)
first_interior_line = break_line_(
first_interior_line,
second_interior_line,
meshtracker.atol,
)
first_shape_interiors.append(first_interior_line)
if first_shape.geom_type in ["Polygon", "MultiPolygon"]:
broken_shapes.append(Polygon(first_exterior_line, holes=first_shape_interiors))
else:
broken_shapes.append(LineString(first_exterior_line))
if first_shape.geom_type in ["Polygon", "MultiPolygon"]:
polygons_broken_dict[first_name] = (
MultiPolygon(broken_shapes) if len(broken_shapes) > 1 else broken_shapes[0]
)
else:
lines_broken_dict[first_name] = (
MultiLineString(broken_shapes) if len(broken_shapes) > 1 else broken_shapes[0]
)
# Add lines, reusing line segments
for line_name, line in lines_broken_dict.items():
meshtracker.add_get_xy_line(line, line_name)
# Add surfaces, reusing lines
for polygon_name, polygon in polygons_broken_dict.items():
meshtracker.add_xy_surface(polygon, polygon_name)
# Embed lines in surfaces if required
for index_surface in range(len(meshtracker.shapely_xy_surfaces)):
polygon = meshtracker.shapely_xy_surfaces[index_surface]
for index_segment in range(len(meshtracker.shapely_xy_segments)):
line = meshtracker.shapely_xy_segments[index_segment]
intersection = line - polygon.exterior
if not intersection.is_empty and polygon.contains(intersection):
model.in_surface(
meshtracker.gmsh_xy_segments[index_segment],
meshtracker.gmsh_xy_surfaces[index_surface],
)
# Refinement in surfaces
n = 0
refinement_fields = []
for label, mesh_setting in resolutions.items():
# Inside surface
mesh_resolution = mesh_setting["resolution"]
gmsh.model.mesh.field.add("MathEval", n)
gmsh.model.mesh.field.setString(n, "F", f"{mesh_resolution}")
gmsh.model.mesh.field.add("Restrict", n + 1)
gmsh.model.mesh.field.setNumber(n + 1, "InField", n)
gmsh.model.mesh.field.setNumbers(
n + 1,
"SurfacesList",
meshtracker.get_gmsh_xy_surfaces_from_label(label),
)
gmsh.model.mesh.field.setNumbers(
n + 1,
"CurvesList",
meshtracker.get_gmsh_xy_lines_from_label(label),
)
gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0)
gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0)
gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0)
# Around surface
mesh_distance = mesh_setting["distance"]
gmsh.model.mesh.field.add("Distance", n + 2)
gmsh.model.mesh.field.setNumbers(
n + 2, "CurvesList", meshtracker.get_gmsh_xy_lines_from_label(label)
)
gmsh.model.mesh.field.setNumber(n + 2, "Sampling", 100)
gmsh.model.mesh.field.add("Threshold", n + 3)
gmsh.model.mesh.field.setNumber(n + 3, "InField", n + 2)
gmsh.model.mesh.field.setNumber(n + 3, "SizeMin", mesh_resolution)
gmsh.model.mesh.field.setNumber(
n + 3,
"SizeMax",
(
default_resolution_max
if "SizeMax" not in mesh_setting
else mesh_setting["SizeMax"]
),
)
gmsh.model.mesh.field.setNumber(n + 3, "DistMin", 0)
gmsh.model.mesh.field.setNumber(n + 3, "DistMax", mesh_distance)
gmsh.model.mesh.field.setNumber(n + 3, "StopAtDistMax", 1)
# Save and increment
refinement_fields.append(n + 1)
refinement_fields.append(n + 3)
n += 4
if global_quad:
gmsh.option.setNumber("Mesh.Algorithm", 8)
gmsh.option.setNumber("Mesh.RecombineAll", 1)
# Use the smallest element size overall
gmsh.model.mesh.field.add("Min", n)
gmsh.model.mesh.field.setNumbers(n, "FieldsList", refinement_fields)
gmsh.model.mesh.field.setAsBackgroundMesh(n)
gmsh.model.mesh.MeshSizeFromPoints = 0
gmsh.model.mesh.MeshSizeFromCurvature = 0
gmsh.model.mesh.MeshSizeExtendFromBoundary = 0
# Tag all interfacial lines
for surface1, surface2 in combinations(polygons_broken_dict.keys(), 2):
interfaces = []
for index, line in enumerate(meshtracker.gmsh_xy_segments):
if (
meshtracker.xy_segments_main_labels[index] == surface1
and meshtracker.xy_segments_secondary_labels[index] == surface2
) or (
meshtracker.xy_segments_main_labels[index] == surface2
and meshtracker.xy_segments_secondary_labels[index] == surface1
):
interfaces.append(line)
if interfaces:
model.add_physical(interfaces, f"{surface1}___{surface2}")
gmsh.model.occ.synchronize()
# Force periodicity (experimental)
def validate_lines(line1, line2):
"""TODO create a module for validating geometries."""
if periodic_lines:
for label1, label2 in periodic_lines:
# if validate_lines(): # TODO
line1 = shapes_dict[label1]
line2 = shapes_dict[label2]
gmsh.model.setCurrent("pygmsh model")
translation = np.array(line1.coords[0]) - np.array(line2.coords[0])
gmsh.model.mesh.setPeriodic(
1,
meshtracker.get_gmsh_xy_lines_from_label(label1),
meshtracker.get_gmsh_xy_lines_from_label(label2),
[1, 0, 0, translation[0], 0, 1, 0, translation[1], 0, 0, 1, 0, 0, 0, 0, 1],
)
# else: # TODO
# raise ValueError("Periodic line pairs must be parallel and have the same straight length in the final, intersected geometry.")
gmsh.option.setNumber("Mesh.ScalingFactor", mesh_scaling_factor)
mesh = geometry.generate_mesh(dim=2, verbose=verbose)
if filename:
gmsh.write(f"{filename}")
import contextlib
import tempfile
import meshio
with contextlib.redirect_stdout(None):
with tempfile.TemporaryDirectory() as tmpdirname:
gmsh.write(f"{tmpdirname}/mesh.msh")
return meshio.read(f"{tmpdirname}/mesh.msh")
if __name__ == "__main__":
from collections import OrderedDict
import gmsh
from mesh import mesh_from_OrderedDict
from shapely.geometry import LineString, Polygon
width = 4
length = 10.5
pml = 0.5
width_wg_1 = 0.5
length_wg_1 = 5
width_wg_2 = 2
length_wg_2 = 5
core = Polygon(
[
(-width_wg_1 / 2, -length_wg_1),
(-width_wg_1 / 2, 0),
(-width_wg_2 / 2, 0),
(-width_wg_2 / 2, length_wg_2),
(width_wg_2 / 2, length_wg_2),
(width_wg_2 / 2, 0),
(width_wg_1 / 2, 0),
(width_wg_1 / 2, -length_wg_1),
]
)
print(core)
box = Polygon(
[
(-width_wg_2 - 1, -6),
(-width_wg_2 - 1, 6),
(width_wg_2 - 0.5, 6),
(width_wg_2 - 0.5, -6),
]
)
print(box)
source = LineString([(width_wg_2 / 2, -length_wg_1 / 2), (-width_wg_2 / 2, -length_wg_1 / 2)])
print(source)
left_wall_up = LineString([(-width_wg_2 - 1, -2), (-width_wg_2 - 1, 6)])
right_wall_up = LineString([(width_wg_2 - 0.5, -2), (width_wg_2 - 0.5, 6)])
left_wall_dw = LineString([(-width_wg_2 - 1, -6), (-width_wg_2 - 1, -2)])
right_wall_dw = LineString([(width_wg_2 - 0.5, -6), (width_wg_2 - 0.5, -2)])
polygons = OrderedDict(
left_wall_up=left_wall_up,
right_wall_up=right_wall_up,
left_wall_dw=left_wall_dw,
right_wall_dw=right_wall_dw,
source=source,
core=core,
box=box,
# pml=core.buffer(2, resolution=4) - core.buffer(1, resolution=4),
)
resolutions = dict(
source={"resolution": 0.02, "distance": 1},
core={"resolution": 0.02, "distance": 1},
# left_wall_up={"resolution": 1, "distance": 1},
# right_wall_up={"resolution": 0.5, "distance": 1},
)
mesh = mesh_from_OrderedDict(
polygons,
resolutions,
filename="mesh.msh",
default_resolution_max=1,
# periodic_lines=[("left_wall_up", "right_wall_up"), ("left_wall_dw", "right_wall_dw")],
mesh_scaling_factor=1e-4,
)
# wmode = 1
# wsim = 2
# hclad = 2
# hbox = 2
# wcore = 0.5
# hcore = 0.22
# offset_core = -0.1
# offset_core2 = 1
# # Lines can be added, which is useful to define boundary conditions at various simulation edges
# left_edge = LineString([Point(-wsim/2, -hcore/2 - hbox),
# Point(-wsim/2, -hcore/2 + hclad)])
# right_edge = LineString([Point(wsim/2, -hcore/2 - hbox),
# Point(wsim/2, -hcore/2 + hclad)])
# top_edge = LineString([Point(-wsim/2, -hcore/2 + hclad),
# Point(wsim/2, -hcore/2 + hclad)])
# bottom_edge = LineString([Point(-wsim/2, -hcore/2 - hbox),
# Point(wsim/2, -hcore/2 - hbox)])
# # Polygons not only have an edge, but an interior
# core = Polygon([
# Point(-wcore/2, -hcore/2 + offset_core),
# Point(-wcore/2, hcore/2 + offset_core),
# Point(wcore/2, hcore/2 + offset_core),
# Point(wcore/2, -hcore/2 + offset_core),
# ])
# core2 = Polygon([
# Point(-wcore/2, -hcore/2 + offset_core2),
# Point(-wcore/2, hcore/2 + offset_core2),
# Point(wcore/2, hcore/2 + offset_core2),
# Point(wcore/2, -hcore/2 + offset_core2),
# ])
# clad = Polygon([
# Point(-wsim/2, -hcore/2),
# Point(-wsim/2, -hcore/2 + hclad),
# Point(wsim/2, -hcore/2 + hclad),
# Point(wsim/2, -hcore/2),
# ])
# box = Polygon([
# Point(-wsim/2, -hcore/2),
# Point(-wsim/2, -hcore/2 - hbox),
# Point(wsim/2, -hcore/2 - hbox),
# Point(wsim/2, -hcore/2),
# ])
# # The order in which objects are inserted into the OrderedDict determines overrrides
# # shapes = OrderedDict()
# shapes = {}
# # shapes["left_edge"] = left_edge
# # shapes["right_edge"] = right_edge
# # shapes["top_edge"] = top_edge
# # shapes["bottom_edge"] = bottom_edge
# shapes["core"] = core
# shapes["core2"] = core2
# shapes["clad"] = clad
# shapes["box"] = box
# # The resolution dict is not ordered, and can be used to set mesh resolution at various element
# # The edge of a polygon and another polygon (or entire simulation domain) will form a line object that can be refined independently
# resolutions = {}
# resolutions["core"] = {"resolution": 0.02, "distance": 2}
# resolutions["core2"] = {"resolution": 0.02, "distance": 2}
# resolutions["clad"] = {"resolution": 0.5, "distance": 2}
# resolutions["box"] = {"resolution": 0.5, "distance": 2}
# # resolutions["core_clad"] = {"resolution": 0.05, "distance": 0.5}
# # resolutions["clad_box"] = {"resolution": 0.05, "distance": 0.5}
# # resolutions["bottom_edge"] = {"resolution": 0.05, "distance": 0.5}
# # resolutions["left_edge"] = {"resolution": 0.05, "distance": 0.5}
# # resolutions["clad"] = {"resolution": 0.1, "dist_min": 0.01, "dist_max": 0.3}
# quad = False
# # mesh = mesh_from_OrderedDict(shapes, resolutions, filename="mesh.msh", default_resolution_max=.3, global_quad=quad)
# mesh = mesh_from_Dict(shapes, resolutions, filename="mesh.msh", default_resolution_max=0.5, global_quad=quad)
# # gmsh.write("mesh.msh")
# # gmsh.clear()
# # mesh.__exit__()
# import meshio
# mesh_from_file = meshio.read("mesh.msh")
# def create_mesh(mesh, cell_type, prune_z=True):
# cells = mesh.get_cells_type(cell_type)
# cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
# points = mesh.points
# return meshio.Mesh(
# points=points,
# cells={cell_type: cells},
# cell_data={"name_to_read": [cell_data]},
# )
# # line_mesh = create_mesh(mesh_from_file, "line", prune_z=True)
# # meshio.write("facet_mesh.xdmf", line_mesh)
# if quad == True:
# triangle_mesh = create_mesh(mesh_from_file, "quad", prune_z=True)
# else:
# triangle_mesh = create_mesh(mesh_from_file, "triangle", prune_z=True)
# meshio.write("mesh.xdmf", triangle_mesh)