-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtest_mesh.py
More file actions
1513 lines (1192 loc) · 47.2 KB
/
test_mesh.py
File metadata and controls
1513 lines (1192 loc) · 47.2 KB
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__copyright__ = """
Copyright (C) 2020 Andreas Kloeckner
Copyright (C) 2021 University of Illinois Board of Trustees
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from functools import partial
from dataclasses import replace
import numpy as np
import numpy.linalg as la
import pytest
from meshmode import _acf # noqa: F401
from meshmode.array_context import PytestPyOpenCLArrayContextFactory
from arraycontext import pytest_generate_tests_for_array_contexts
pytest_generate_tests = pytest_generate_tests_for_array_contexts(
[PytestPyOpenCLArrayContextFactory])
from meshmode.mesh import (
Mesh,
SimplexElementGroup,
TensorProductElementGroup,
InteriorAdjacencyGroup,
BoundaryAdjacencyGroup)
from meshmode.discretization.poly_element import (
default_simplex_group_factory,
LegendreGaussLobattoTensorProductGroupFactory,
)
import meshmode.mesh.generation as mgen
import meshmode.mesh.io as mio
from meshmode.mesh.tools import AffineMap
import modepy as mp
import logging
logger = logging.getLogger(__name__)
import pathlib
thisdir = pathlib.Path(__file__).parent
def _get_rotation(amount, axis, center=None):
"""
Return a matrix (if *center* is ``None``) or
:class:`~meshmode.mesh.tools.AffineMap` (if *center* is not ``None``)
corresponding to a rotation by *amount* (in radians) through a vector *axis*
centered at *center*. *center* defaults to the origin if not specified.
"""
from meshmode.mesh.processing import _get_rotation_matrix_from_angle_and_axis
matrix = _get_rotation_matrix_from_angle_and_axis(amount, axis)
if center is None:
return matrix
else:
# x0 + matrix @ (x - x0) = matrix @ x + (I - matrix) @ x0
offset = (np.eye(3) - matrix) @ center
return AffineMap(matrix, offset)
# {{{ test_nonequal_rect_mesh_generation
@pytest.mark.parametrize(("dim", "mesh_type"), [
(1, None),
(2, None),
(2, "X"),
(3, None),
])
def test_nonequal_rect_mesh_generation(actx_factory, dim, mesh_type,
visualize=False):
"""Test that ``generate_regular_rect_mesh`` works with non-equal arguments
across axes.
"""
actx = actx_factory()
mesh = mgen.generate_regular_rect_mesh(
a=(0,)*dim, b=(5, 3, 4)[:dim], npoints_per_axis=(10, 6, 7)[:dim],
order=3, mesh_type=mesh_type)
from meshmode.discretization import Discretization
discr = Discretization(actx, mesh, default_simplex_group_factory(dim, 3))
if visualize:
from meshmode.discretization.visualization import make_visualizer
vis = make_visualizer(actx, discr, 3)
vis.write_vtk_file("nonuniform.vtu", [], overwrite=True)
# }}}
# {{{ rect/box mesh generation
def test_rect_mesh(visualize=False):
mesh = mgen.generate_regular_rect_mesh(nelements_per_axis=(4, 4))
if visualize:
from meshmode.mesh.visualization import draw_2d_mesh
draw_2d_mesh(mesh, fill=None, draw_nodal_adjacency=True)
import matplotlib.pyplot as pt
pt.show()
def test_box_mesh(actx_factory, visualize=False):
mesh = mgen.generate_box_mesh(3*(np.linspace(0, 1, 5),))
if visualize:
from meshmode.discretization import Discretization
actx = actx_factory()
discr = Discretization(actx, mesh,
default_simplex_group_factory(mesh.dim, 7))
from meshmode.discretization.visualization import make_visualizer
vis = make_visualizer(actx, discr, 7)
vis.write_vtk_file("box_mesh.vtu", [])
# Simplex, 1D
mesh = mgen.generate_box_mesh(
(np.linspace(0, 1, 3),), group_cls=SimplexElementGroup)
assert mesh.ambient_dim == 1
assert mesh.dim == 1
assert mesh.nvertices == 3
assert len(mesh.groups) == 1
assert mesh.nelements == 2
# Tensor product, 1D
mesh = mgen.generate_box_mesh(
(np.linspace(0, 1, 3),), group_cls=TensorProductElementGroup)
assert mesh.ambient_dim == 1
assert mesh.dim == 1
assert mesh.nvertices == 3
assert len(mesh.groups) == 1
assert mesh.nelements == 2
# Simplex, 2D, non-X
mesh = mgen.generate_box_mesh(
2*(np.linspace(0, 1, 3),), group_cls=SimplexElementGroup)
assert mesh.ambient_dim == 2
assert mesh.dim == 2
assert mesh.nvertices == 9
assert len(mesh.groups) == 1
assert mesh.nelements == 8
# Simplex, 2D, X
mesh = mgen.generate_box_mesh(
2*(np.linspace(0, 1, 3),), group_cls=SimplexElementGroup, mesh_type="X")
assert mesh.ambient_dim == 2
assert mesh.dim == 2
assert mesh.nvertices == 13
assert len(mesh.groups) == 1
assert mesh.nelements == 16
# Tensor product, 2D
mesh = mgen.generate_box_mesh(
2*(np.linspace(0, 1, 3),), group_cls=TensorProductElementGroup)
assert mesh.ambient_dim == 2
assert mesh.dim == 2
assert mesh.nvertices == 9
assert len(mesh.groups) == 1
assert mesh.nelements == 4
# Simplex, 3D
mesh = mgen.generate_box_mesh(
3*(np.linspace(0, 1, 3),), group_cls=SimplexElementGroup)
assert mesh.ambient_dim == 3
assert mesh.dim == 3
assert mesh.nvertices == 27
assert len(mesh.groups) == 1
assert mesh.nelements == 48
# Tensor product, 3D
mesh = mgen.generate_box_mesh(
3*(np.linspace(0, 1, 3),), group_cls=TensorProductElementGroup)
assert mesh.ambient_dim == 3
assert mesh.dim == 3
assert mesh.nvertices == 27
assert len(mesh.groups) == 1
assert mesh.nelements == 8
# Simplex, empty mesh
mesh = mgen.generate_box_mesh(
3*(np.empty((0,)),), group_cls=SimplexElementGroup)
assert mesh.ambient_dim == 3
assert mesh.dim == 3
assert mesh.nvertices == 0
assert len(mesh.groups) == 1
assert mesh.nelements == 0
# Tensor product, empty mesh
mesh = mgen.generate_box_mesh(
3*(np.empty((0,)),), group_cls=TensorProductElementGroup)
assert mesh.ambient_dim == 3
assert mesh.dim == 3
assert mesh.nvertices == 0
assert len(mesh.groups) == 1
assert mesh.nelements == 0
# }}}
# {{{ circle mesh
def test_circle_mesh(visualize=False):
from meshmode.mesh.io import generate_gmsh, FileSource
logger.info("BEGIN GEN")
mesh = generate_gmsh(
FileSource(str(thisdir / "circle.step")), 2, order=2,
force_ambient_dim=2,
other_options=[
"-string", "Mesh.CharacteristicLengthMax = 0.05;"],
target_unit="MM",
)
logger.info("END GEN")
logger.info("nelements: %d", mesh.nelements)
from meshmode.mesh.processing import affine_map
mesh = affine_map(mesh, A=3*np.eye(2))
if visualize:
from meshmode.mesh.visualization import draw_2d_mesh
draw_2d_mesh(mesh,
fill=None,
draw_vertex_numbers=False,
draw_nodal_adjacency=True,
set_bounding_box=True)
import matplotlib.pyplot as pt
pt.axis("equal")
pt.savefig("circle_mesh", dpi=300)
# }}}
def test_mesh_copy():
mesh = mgen.generate_box_mesh(3*(np.linspace(0, 1, 5),))
mesh.copy()
# {{{ as_python stringification
def test_mesh_as_python():
mesh = mgen.generate_box_mesh(3*(np.linspace(0, 1, 5),))
# These implicitly compute these adjacency structures.
assert mesh.nodal_adjacency
assert mesh.facial_adjacency_groups
from meshmode.mesh import as_python
code = as_python(mesh)
print(code)
exec_dict = {}
exec(compile(code, "gen_code.py", "exec"), exec_dict)
mesh_2 = exec_dict["make_mesh"]()
assert mesh == mesh_2
# }}}
# {{{ test_affine_map
def test_affine_map():
for d in range(1, 5):
for _ in range(100):
a = np.random.randn(d, d)+10*np.eye(d)
b = np.random.randn(d)
m = AffineMap(a, b)
assert la.norm(m.inverted().matrix - la.inv(a)) < 1e-10*la.norm(a)
x = np.random.randn(d)
m_inv = m.inverted()
assert la.norm(x-m_inv(m(x))) < 1e-10
def test_partial_affine_map(dim=2):
orig_mesh = mgen.generate_regular_rect_mesh(
a=(0,)*dim, b=(5, 3, 4)[:dim], npoints_per_axis=(10, 6, 7)[:dim],
order=1)
from meshmode.mesh.processing import affine_map
mesh = affine_map(orig_mesh, b=np.pi)
mesh = affine_map(orig_mesh, b=np.pi)
assert la.norm(orig_mesh.vertices - mesh.vertices + np.pi) < 1.0e-14
mesh = affine_map(orig_mesh, b=np.array([np.pi] * dim))
assert la.norm(orig_mesh.vertices - mesh.vertices + np.pi) < 1.0e-14
mesh = affine_map(orig_mesh, A=np.pi)
mesh = affine_map(orig_mesh, A=np.pi)
assert la.norm(orig_mesh.vertices - mesh.vertices / np.pi) < 1.0e-14
mesh = affine_map(orig_mesh, A=np.pi * np.eye(dim))
assert la.norm(orig_mesh.vertices - mesh.vertices / np.pi) < 1.0e-14
def test_affine_map_with_facial_adjacency_maps(visualize=False):
orig_mesh = mgen.generate_annular_cylinder_slice_mesh(
4, (1, 2, 0), 0.5, 1, periodic=True)
if visualize:
from meshmode.mesh.visualization import write_vertex_vtk_file
write_vertex_vtk_file(orig_mesh, "affine_map_facial_adj_original.vtu")
from meshmode.mesh.processing import affine_map
tol = 1e-12
def almost_equal(map1, map2):
def component_almost_equal(array1, array2):
if isinstance(array1, np.ndarray) and isinstance(array2, np.ndarray):
return la.norm(array1 - array2) < tol
else:
return array1 == array2
return (
component_almost_equal(map1.matrix, map2.matrix)
and component_almost_equal(map1.offset, map2.offset))
# Matrix only
mesh = affine_map(orig_mesh, A=_get_rotation(np.pi/2, axis=np.array([0, 0, 1])))
if visualize:
write_vertex_vtk_file(mesh, "affine_map_facial_adj_matrix.vtu")
int_grps = [
fagrp for fagrp in mesh.facial_adjacency_groups[0]
if isinstance(fagrp, InteriorAdjacencyGroup)]
assert len(int_grps) == 3
lower_grp = int_grps[1]
upper_grp = int_grps[2]
assert almost_equal(
lower_grp.aff_map,
_get_rotation(
np.pi/2, axis=np.array([0, 0, 1]), center=np.array([-2, 1, 0])))
assert almost_equal(
upper_grp.aff_map,
_get_rotation(
-np.pi/2, axis=np.array([0, 0, 1]), center=np.array([-2, 1, 0])))
# Offset only
mesh = affine_map(orig_mesh, b=np.array([0, -2, 0]))
if visualize:
write_vertex_vtk_file(mesh, "affine_map_facial_adj_offset.vtu")
int_grps = [
fagrp for fagrp in mesh.facial_adjacency_groups[0]
if isinstance(fagrp, InteriorAdjacencyGroup)]
assert len(int_grps) == 3
lower_grp = int_grps[1]
upper_grp = int_grps[2]
assert almost_equal(
lower_grp.aff_map,
_get_rotation(
np.pi/2, axis=np.array([0, 0, 1]), center=np.array([1, 0, 0])))
assert almost_equal(
upper_grp.aff_map,
_get_rotation(
-np.pi/2, axis=np.array([0, 0, 1]), center=np.array([1, 0, 0])))
# Matrix and offset
aff_map = _get_rotation(
np.pi/2, axis=np.array([0, 0, 1]), center=np.array([1, 1, 0]))
mesh = affine_map(orig_mesh, A=aff_map.matrix, b=aff_map.offset)
if visualize:
write_vertex_vtk_file(mesh, "affine_map_facial_adj_matrix_and_offset.vtu")
int_grps = [
fagrp for fagrp in mesh.facial_adjacency_groups[0]
if isinstance(fagrp, InteriorAdjacencyGroup)]
assert len(int_grps) == 3
lower_grp = int_grps[1]
upper_grp = int_grps[2]
assert almost_equal(
lower_grp.aff_map,
_get_rotation(
np.pi/2, axis=np.array([0, 0, 1]), center=np.array([0, 1, 0])))
assert almost_equal(
upper_grp.aff_map,
_get_rotation(
-np.pi/2, axis=np.array([0, 0, 1]), center=np.array([0, 1, 0])))
@pytest.mark.parametrize("ambient_dim", [2, 3])
def test_mesh_rotation(ambient_dim, visualize=False):
order = 3
if ambient_dim == 2:
nelements = 256
mesh = mgen.make_curve_mesh(
# partial(mgen.ellipse, 2.0),
partial(mgen.clamp_piecewise, 1.0, 2 / 3, np.pi / 6),
np.linspace(0.0, 1.0, nelements + 1),
order=order)
elif ambient_dim == 3:
mesh = mgen.generate_torus(4.0, 2.0, order=order)
else:
raise ValueError("unsupported dimension")
from meshmode.mesh.processing import _get_rotation_matrix_from_angle_and_axis
mat = _get_rotation_matrix_from_angle_and_axis(
np.pi/3.0, np.array([1.0, 2.0, 1.4]))
# check that the matrix is in the rotation group
assert abs(abs(la.det(mat)) - 1) < 10e-14
assert la.norm(mat @ mat.T - np.eye(3)) < 1.0e-14
from meshmode.mesh.processing import rotate_mesh_around_axis
rotated_mesh = rotate_mesh_around_axis(mesh,
theta=np.pi/2.0,
axis=np.array([1, 0, 0]))
if visualize:
from meshmode.mesh.visualization import write_vertex_vtk_file
write_vertex_vtk_file(mesh, "mesh_rotation_original.vtu")
write_vertex_vtk_file(rotated_mesh, "mesh_rotation_rotated.vtu")
# }}}
# {{{ test_mesh_to_tikz
def test_mesh_to_tikz():
from meshmode.mesh.io import generate_gmsh, FileSource
h = 0.3
order = 1
mesh = generate_gmsh(
FileSource(str(thisdir / "blob-2d.step")), 2, order=order,
force_ambient_dim=2,
other_options=[
"-string", "Mesh.CharacteristicLengthMax = %s;" % h],
target_unit="MM",
)
from meshmode.mesh.visualization import mesh_to_tikz
mesh_to_tikz(mesh)
# }}}
# {{{ test_quad_single_element
def test_quad_single_element(visualize=False):
vertices = np.array([
[0.91, 1.10],
[2.64, 1.27],
[0.97, 2.56],
[3.00, 3.41],
]).T
mg = mgen.make_group_from_vertices(
vertices,
np.array([[0, 1, 2, 3]], dtype=np.int32),
30, group_cls=TensorProductElementGroup)
Mesh(vertices, [mg], nodal_adjacency=None, facial_adjacency_groups=None)
if visualize:
import matplotlib.pyplot as plt
plt.plot(
mg.nodes[0].reshape(-1),
mg.nodes[1].reshape(-1), "o")
plt.show()
# }}}
# {{{ merge and map
@pytest.mark.parametrize("group_cls", [
SimplexElementGroup,
TensorProductElementGroup
])
def test_merge_and_map(actx_factory, group_cls, visualize=False):
from meshmode.mesh.io import generate_gmsh, FileSource
order = 3
mesh_order = 3
if group_cls is SimplexElementGroup:
mesh = generate_gmsh(
FileSource(str(thisdir / "blob-2d.step")), 2, order=mesh_order,
force_ambient_dim=2,
other_options=["-string", "Mesh.CharacteristicLengthMax = 0.02;"],
target_unit="MM",
)
discr_grp_factory = default_simplex_group_factory(base_dim=2, order=order)
else:
ambient_dim = 3
mesh = mgen.generate_regular_rect_mesh(
a=(0,)*ambient_dim, b=(1,)*ambient_dim,
nelements_per_axis=(4,)*ambient_dim, order=mesh_order,
group_cls=group_cls)
discr_grp_factory = LegendreGaussLobattoTensorProductGroupFactory(order)
from meshmode.mesh.processing import merge_disjoint_meshes, affine_map
mesh2 = affine_map(mesh,
A=np.eye(mesh.ambient_dim),
b=np.array([2, 0, 0])[:mesh.ambient_dim])
mesh3 = merge_disjoint_meshes((mesh2, mesh))
assert mesh3.facial_adjacency_groups
mesh4 = mesh3.copy()
if visualize:
from meshmode.discretization import Discretization
actx = actx_factory()
discr = Discretization(actx, mesh4, discr_grp_factory)
from meshmode.discretization.visualization import make_visualizer
vis = make_visualizer(actx, discr, 3, element_shrink_factor=0.8)
vis.write_vtk_file("merge_and_map.vtu", [])
# }}}
# {{{ element orientation
def test_element_orientation_via_flipping():
from meshmode.mesh.io import generate_gmsh, FileSource
mesh_order = 3
mesh = generate_gmsh(
FileSource(str(thisdir / "blob-2d.step")), 2, order=mesh_order,
force_ambient_dim=2,
other_options=["-string", "Mesh.CharacteristicLengthMax = 0.02;"],
target_unit="MM",
)
from meshmode.mesh.processing import (perform_flips,
find_volume_mesh_element_orientations)
mesh_orient = find_volume_mesh_element_orientations(mesh)
assert (mesh_orient > 0).all()
from random import randrange
flippy = np.zeros(mesh.nelements, np.int8)
for _ in range(int(0.3*mesh.nelements)):
flippy[randrange(0, mesh.nelements)] = 1
mesh = perform_flips(mesh, flippy, skip_tests=True)
mesh_orient = find_volume_mesh_element_orientations(mesh)
assert ((mesh_orient < 0) == (flippy > 0)).all()
@pytest.mark.parametrize("order", [1, 2, 3])
def test_element_orientation_via_single_elements(order):
from meshmode.mesh.processing import find_volume_mesh_element_group_orientation
def check(vertices, element_indices, tol=1e-14):
grp = mgen.make_group_from_vertices(vertices, element_indices, order)
orient = find_volume_mesh_element_group_orientation(vertices, grp)
return (
np.where(orient > tol)[0],
np.where(orient < tol)[0],
np.where(np.abs(orient) <= tol)[0])
# References:
# https://github.com/inducer/meshmode/pull/314
# https://github.com/lukeolson/mesh_orientation/blob/460bb2b634e2abb6aa32c3d02e2c732969bf08bf/check.py
# https://math.stackexchange.com/questions/4209203/signed-volume-for-tetrahedra-n-simplices
# 3D (pos)
vertices = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 0],
[0, 0, 1]])
elements = np.array([[0, 1, 2, 3]])
el_ind_pos, el_ind_neg, el_ind_zero = check(vertices.T, elements)
assert len(el_ind_pos) == 1
assert len(el_ind_neg) == 0
assert len(el_ind_zero) == 0
# (neg)
elements = np.array([[1, 0, 2, 3]])
el_ind_pos, el_ind_neg, el_ind_zero = check(vertices.T, elements)
assert len(el_ind_pos) == 0
assert len(el_ind_neg) == 1
assert len(el_ind_zero) == 0
# 2D
# CCW (positive)
vertices = np.array([[1, 0],
[0, 1],
[0, 0]])
elements = np.array([[0, 1, 2]])
el_ind_pos, el_ind_neg, el_ind_zero = check(vertices.T, elements)
assert len(el_ind_pos) == 1
assert len(el_ind_neg) == 0
assert len(el_ind_zero) == 0
# CW (negative)
elements = np.array([[0, 2, 1]])
el_ind_pos, el_ind_neg, el_ind_zero = check(vertices.T, elements)
assert len(el_ind_pos) == 0
assert len(el_ind_neg) == 1
assert len(el_ind_zero) == 0
mesh = mio.read_gmsh(str(thisdir / "testmesh.msh"), force_ambient_dim=2,
mesh_construction_kwargs={"skip_tests": True})
mgrp, = mesh.groups
el_ind_pos, el_ind_neg, el_ind_zero = check(mesh.vertices, mgrp.vertex_indices)
assert len(el_ind_pos) == 1
assert len(el_ind_neg) == 1
assert len(el_ind_zero) == 0
# }}}
# {{{ test_open_curved_mesh
@pytest.mark.parametrize("curve_name", ["ellipse", "arc"])
def test_open_curved_mesh(curve_name):
def arc_curve(t, start=0, end=np.pi):
return np.vstack([
np.cos((end - start) * t + start),
np.sin((end - start) * t + start)
])
if curve_name == "ellipse":
curve_f = partial(mgen.ellipse, 2.0)
closed = True
elif curve_name == "arc":
curve_f = arc_curve
closed = False
else:
raise ValueError("unknown curve")
nelements = 32
order = 4
mgen.make_curve_mesh(curve_f,
np.linspace(0.0, 1.0, nelements + 1),
order=order,
closed=closed)
# }}}
# {{{ test_is_affine_group_check
def _generate_cross_warped_rect_mesh(dim, order, nelements_side):
mesh = mgen.generate_regular_rect_mesh(
a=(0,)*dim, b=(1,)*dim,
nelements_per_axis=(nelements_side,)*dim, order=order)
def m(x):
results = np.empty_like(x)
results[0] = 1 + 1.5 * (x[0] + 0.25) * (x[1] + 0.3)
results[1] = x[1]
return results
from meshmode.mesh.processing import map_mesh
return map_mesh(mesh, m)
@pytest.mark.parametrize("mesh_name", [
"box2d", "box3d",
"warped_box2d", "warped_box3d", "cross_warped_box",
"circle", "ellipse",
"sphere", "torus"
])
def test_is_affine_group_check(mesh_name):
order = 4
nelements = 16
if mesh_name.startswith("box"):
dim = int(mesh_name[-2])
is_affine = True
mesh = mgen.generate_regular_rect_mesh(
a=(-0.5,)*dim, b=(0.5,)*dim,
nelements_per_axis=(nelements,)*dim, order=order)
elif mesh_name.startswith("warped_box"):
dim = int(mesh_name[-2])
is_affine = False
mesh = mgen.generate_warped_rect_mesh(dim, order, nelements_side=nelements)
elif mesh_name == "cross_warped_box":
dim = 2
is_affine = False
mesh = _generate_cross_warped_rect_mesh(dim, order, nelements)
elif mesh_name == "circle":
is_affine = False
mesh = mgen.make_curve_mesh(
lambda t: mgen.ellipse(1.0, t),
np.linspace(0.0, 1.0, nelements + 1), order=order)
elif mesh_name == "ellipse":
is_affine = False
mesh = mgen.make_curve_mesh(
lambda t: mgen.ellipse(2.0, t),
np.linspace(0.0, 1.0, nelements + 1), order=order)
elif mesh_name == "sphere":
is_affine = False
mesh = mgen.generate_sphere(r=1.0, order=order)
elif mesh_name == "torus":
is_affine = False
mesh = mgen.generate_torus(10.0, 2.0, order=order)
else:
raise ValueError(f"unknown mesh name: {mesh_name}")
assert all(grp.is_affine for grp in mesh.groups) == is_affine
# }}}
# {{{ test_quad_multi_element
def test_quad_multi_element(visualize=False):
mesh = mgen.generate_box_mesh(
(
np.linspace(3, 8, 4),
np.linspace(3, 8, 4),
np.linspace(3, 8, 4),
),
10, group_cls=TensorProductElementGroup)
if visualize:
import matplotlib.pyplot as plt
mg = mesh.groups[0]
plt.plot(
mg.nodes[0].reshape(-1),
mg.nodes[1].reshape(-1), "o")
plt.show()
# }}}
# {{{ test lookup tree for element finding
def test_lookup_tree(visualize=False):
mesh = mgen.make_curve_mesh(mgen.cloverleaf, np.linspace(0, 1, 1000), order=3)
from meshmode.mesh.tools import make_element_lookup_tree
tree = make_element_lookup_tree(mesh)
from meshmode.mesh.processing import find_bounding_box
bbox_min, bbox_max = find_bounding_box(mesh)
extent = bbox_max-bbox_min
for _ in range(20):
pt = bbox_min + np.random.rand(2) * extent
print(pt)
for igrp, iel in tree.generate_matches(pt):
print(igrp, iel)
if visualize:
with open("tree.dat", "w") as outf:
tree.visualize(outf)
# }}}
# {{{ test boundary tags
def test_boundary_tags():
from meshmode.mesh.io import read_gmsh
# ensure tags are read in
mesh = read_gmsh(str(thisdir / "annulus.msh"))
# correct answers
num_on_outer_bdy = 26
num_on_inner_bdy = 13
# check how many elements are marked on each boundary
num_marked_outer_bdy = 0
num_marked_inner_bdy = 0
for igrp in range(len(mesh.groups)):
bdry_fagrps = [
fagrp for fagrp in mesh.facial_adjacency_groups[igrp]
if isinstance(fagrp, BoundaryAdjacencyGroup)]
for bdry_fagrp in bdry_fagrps:
if bdry_fagrp.boundary_tag == "outer_bdy":
num_marked_outer_bdy += len(bdry_fagrp.elements)
if bdry_fagrp.boundary_tag == "inner_bdy":
num_marked_inner_bdy += len(bdry_fagrp.elements)
# raise errors if wrong number of elements marked
if num_marked_inner_bdy != num_on_inner_bdy:
raise ValueError("%i marked on inner boundary, should be %i" %
(num_marked_inner_bdy, num_on_inner_bdy))
if num_marked_outer_bdy != num_on_outer_bdy:
raise ValueError("%i marked on outer boundary, should be %i" %
(num_marked_outer_bdy, num_on_outer_bdy))
# ensure boundary is covered
from meshmode.mesh import check_bc_coverage
check_bc_coverage(mesh, ["inner_bdy", "outer_bdy"])
# }}}
# {{{ test volume tags
def test_volume_tags():
from meshmode.mesh.io import read_gmsh
mesh, tag_to_elements_map = read_gmsh(
str(thisdir / "testmesh_multivol.msh"), return_tag_to_elements_map=True)
assert len(tag_to_elements_map) == 2
assert "Vol1" in tag_to_elements_map
assert "Vol2" in tag_to_elements_map
assert isinstance(tag_to_elements_map["Vol1"], np.ndarray)
assert np.all(tag_to_elements_map["Vol1"] == np.array([0]))
assert np.all(tag_to_elements_map["Vol2"] == np.array([1]))
# }}}
# {{{ test custom boundary tags on box mesh
@pytest.mark.parametrize(("dim", "nelem", "mesh_type"), [
(1, 20, None),
(2, 20, None),
(2, 20, "X"),
(3, 10, None),
])
@pytest.mark.parametrize("group_cls", [
SimplexElementGroup,
TensorProductElementGroup
])
def test_box_boundary_tags(dim, nelem, mesh_type, group_cls, visualize=False):
if group_cls is TensorProductElementGroup and mesh_type is not None:
pytest.skip("mesh type not supported on tensor product elements")
from meshmode.mesh import (
mesh_has_boundary,
check_bc_coverage,
is_boundary_tag_empty)
if dim == 1:
a = (0,)
b = (1,)
nelements_per_axis = (nelem,)
btag_to_face = {"btag_test_1": ["+x"],
"btag_test_2": ["-x"]}
elif dim == 2:
a = (0, -1)
b = (1, 1)
nelements_per_axis = (nelem,)*2
btag_to_face = {"btag_test_1": ["+x", "-y"],
"btag_test_2": ["+y", "-x"]}
elif dim == 3:
a = (0, -1, -1)
b = (1, 1, 1)
nelements_per_axis = (nelem,)*3
btag_to_face = {"btag_test_1": ["+x", "-y", "-z"],
"btag_test_2": ["+y", "-x", "+z"]}
mesh = mgen.generate_regular_rect_mesh(a=a, b=b,
nelements_per_axis=nelements_per_axis, order=3,
boundary_tag_to_face=btag_to_face,
group_cls=group_cls,
mesh_type=mesh_type)
if visualize and dim == 2:
from meshmode.mesh.visualization import draw_2d_mesh
draw_2d_mesh(mesh, draw_element_numbers=False, draw_vertex_numbers=False)
import matplotlib.pyplot as plt
plt.show()
# correct answer
if dim == 1:
num_on_bdy = 1
elif group_cls is TensorProductElementGroup:
num_on_bdy = dim * nelem**(dim-1)
elif group_cls is SimplexElementGroup:
num_on_bdy = dim * (dim-1) * nelem**(dim-1)
else:
raise AssertionError()
assert mesh_has_boundary(mesh, "btag_test_1")
assert mesh_has_boundary(mesh, "btag_test_2")
# Make sure mesh_has_boundary is working
assert not mesh_has_boundary(mesh, "btag_test_3")
assert not is_boundary_tag_empty(mesh, "btag_test_1")
assert not is_boundary_tag_empty(mesh, "btag_test_2")
check_bc_coverage(mesh, ["btag_test_1", "btag_test_2"])
# check how many elements are marked on each boundary
num_marked_bdy_1 = 0
num_marked_bdy_2 = 0
for igrp in range(len(mesh.groups)):
bdry_fagrps = [
fagrp for fagrp in mesh.facial_adjacency_groups[igrp]
if isinstance(fagrp, BoundaryAdjacencyGroup)]
for bdry_fagrp in bdry_fagrps:
if bdry_fagrp.boundary_tag == "btag_test_1":
num_marked_bdy_1 += len(bdry_fagrp.elements)
if bdry_fagrp.boundary_tag == "btag_test_2":
num_marked_bdy_2 += len(bdry_fagrp.elements)
# raise errors if wrong number of elements marked
if num_marked_bdy_1 != num_on_bdy:
raise ValueError("%i marked on custom boundary 1, should be %i" %
(num_marked_bdy_1, num_on_bdy))
if num_marked_bdy_2 != num_on_bdy:
raise ValueError("%i marked on custom boundary 2, should be %i" %
(num_marked_bdy_2, num_on_bdy))
# }}}
# {{{ test_quad_mesh_2d
@pytest.mark.parametrize(("ambient_dim", "filename"),
[(2, "blob-2d.step"), (3, "ball-radius-1.step")])
def test_quad_mesh_2d(ambient_dim, filename, visualize=False):
from meshmode.mesh.io import generate_gmsh, ScriptWithFilesSource
logger.info("BEGIN GEN")
mesh = generate_gmsh(
ScriptWithFilesSource(
f"""
Merge "{filename}";
Mesh.CharacteristicLengthMax = 0.05;
Recombine Surface "*" = 0.0001;
Mesh 2;
Save "output.msh";
""",
[str(thisdir / filename)]),
order=1,
force_ambient_dim=ambient_dim,
target_unit="MM",
)
logger.info("END GEN")
logger.info("nelements: %d", mesh.nelements)
groups = []
for grp in mesh.groups:
if not isinstance(grp, TensorProductElementGroup):
# NOTE: gmsh isn't guaranteed to recombine all elements, so we
# could still have some simplices sitting around, so skip them
groups.append(grp.copy())
continue
g = mgen.make_group_from_vertices(mesh.vertices,
grp.vertex_indices, grp.order,
group_cls=TensorProductElementGroup)
assert g.nodes.shape == (mesh.ambient_dim, grp.nelements, grp.nunit_nodes)
groups.append(g)
mesh_from_vertices = Mesh(mesh.vertices, groups=groups, is_conforming=True)
if visualize:
from meshmode.mesh.visualization import write_vertex_vtk_file
write_vertex_vtk_file(mesh, "quad_mesh_2d_orig.vtu")
write_vertex_vtk_file(mesh_from_vertices, "quad_mesh_2d_groups.vtu")
# }}}
# {{{ test_quad_mesh_3d