-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathgeneration.py
More file actions
1607 lines (1268 loc) · 53.5 KB
/
Copy pathgeneration.py
File metadata and controls
1607 lines (1268 loc) · 53.5 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) 2013 Andreas Kloeckner"
__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 typing import Callable, Optional, Union
import numpy as np
import numpy.linalg as la
import modepy as mp
from meshmode.mesh import Mesh, MeshElementGroup
from pytools import log_process, deprecate_keyword
import logging
logger = logging.getLogger(__name__)
__doc__ = """
Curves
------
.. autofunction:: make_curve_mesh
Curve parametrizations
^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: circle
.. autofunction:: ellipse
.. autofunction:: cloverleaf
.. autofunction:: drop
.. autofunction:: n_gon
.. autofunction:: qbx_peanut
.. autofunction:: dumbbell
.. autofunction:: wobbly_dumbbell
.. autofunction:: apple
.. autoclass:: WobblyCircle
.. autoclass:: NArmedStarfish
.. data:: starfish3
.. data:: starfish5
Surfaces
--------
.. autofunction:: generate_icosahedron
.. autofunction:: generate_cube_surface
.. autofunction:: generate_sphere
.. autofunction:: generate_torus
.. autofunction:: refine_mesh_and_get_urchin_warper
.. autofunction:: generate_urchin
.. autofunction:: generate_surface_of_revolution
Volumes
-------
.. autofunction:: generate_box_mesh
.. autofunction:: generate_regular_rect_mesh
.. autofunction:: generate_warped_rect_mesh
.. autofunction:: generate_annular_cylinder_slice_mesh
Tools for Iterative Refinement
------------------------------
.. autofunction:: warp_and_refine_until_resolved
"""
# {{{ test curve parametrizations
def circle(t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
return ellipse(1.0, t)
def ellipse(aspect_ratio: float, t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
ilength = 2*np.pi
t = t*ilength
return np.vstack([
np.cos(t),
np.sin(t)/aspect_ratio,
])
def cloverleaf(t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
ilength = 2*np.pi
t = t*ilength
a = 0.3
b = 3
return np.vstack([
np.cos(t)+a*np.sin(b*t),
np.sin(t)-a*np.cos(b*t)
])
def drop(t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
ilength = np.pi
t = t*ilength
return 1.7 * np.vstack([
np.sin(t)-0.5,
0.5*(np.cos(t)*(t-np.pi)*t),
])
def n_gon(n_corners, t):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
t = t*n_corners
result = np.empty((2,)+t.shape)
for side in range(n_corners):
indices = np.where((side <= t) & (t < side+1))
startp = np.array([
np.cos(2*np.pi/n_corners * side),
np.sin(2*np.pi/n_corners * side),
])[:, np.newaxis]
endp = np.array([
np.cos(2*np.pi/n_corners * (side+1)),
np.sin(2*np.pi/n_corners * (side+1)),
])[:, np.newaxis]
tau = t[indices]-side
result[:, indices] = (1-tau)*startp + tau*endp
return result
def qbx_peanut(t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
t = 2.0 * np.pi * t
r = (1.0 + 0.3 * np.sin(2 * t))
return np.vstack([
3 / 4 * r * np.cos(t - np.pi / 4),
r * np.sin(t - np.pi / 4),
])
def dumbbell(gamma: float, beta: float, t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
return wobbly_dumbbell(gamma, beta, 1, 0, t)
def wobbly_dumbbell(
gamma: float, beta: float, p: int, wavenumber: int,
t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
t = 2.0 * np.pi * t
r = (
gamma * (1 + beta / (1 - beta) * np.cos(t) ** 2) ** (1 / p)
+ 0.02 * np.sin(wavenumber * t) ** 2)
return np.stack([
np.cos(t),
r * np.sin(t),
])
def apple(a: float, t: np.ndarray):
"""
:arg a: roundness parameter in :math:`[0, 1/2]`, where :math:`0` gives
a circle and :math:`1/2` gives a cardioid.
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
ilength = 2*np.pi
t = t*ilength
sin = np.sin
cos = np.cos
return np.vstack([
cos(t) + a*cos(2*t),
sin(t) + a*sin(2*t)
])
class WobblyCircle:
"""
.. automethod:: random
.. automethod:: __call__
"""
def __init__(self, coeffs: np.ndarray, phase: float = 0.0) -> None:
self.coeffs = coeffs
self.phase = phase
@staticmethod
def random(ncoeffs: int, seed: int):
rng = np.random.default_rng(seed)
coeffs = rng.random(ncoeffs)
coeffs = 0.95*coeffs/np.sum(np.abs(coeffs))
return WobblyCircle(coeffs)
def __call__(self, t: np.ndarray):
"""
:arg t: the parametrization, runs from :math:`[0, 1]`.
:return: an array of shape ``(2, t.size)``.
"""
ilength = 2*np.pi
t = t*ilength
wave = 1
for i, coeff in enumerate(self.coeffs):
wave = wave + coeff*np.sin((i+1)*t + self.phase)
return np.vstack([
np.cos(t)*wave,
np.sin(t)*wave,
])
class NArmedStarfish(WobblyCircle):
"""Inherits from :class:`WobblyCircle`.
.. automethod:: __call__
"""
def __init__(self, n_arms: int, amplitude: float, phase: float = 0.0) -> None:
coeffs = np.zeros(n_arms)
coeffs[-1] = amplitude
super().__init__(coeffs, phase=phase)
starfish3 = NArmedStarfish(3, 1 / 2, phase=np.pi / 2)
starfish5 = NArmedStarfish(5, 0.25)
starfish = starfish5
# }}}
# {{{ make_curve_mesh
def make_curve_mesh(
curve_f: Callable[[np.ndarray], np.ndarray],
element_boundaries: np.ndarray, order: int, *,
unit_nodes: Optional[np.ndarray] = None,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
closed: bool = True,
return_parametrization_points: bool = False) -> Mesh:
"""
:arg curve_f: parametrization for a curve, accepting a vector of
point locations and returning an array of shape ``(2, npoints)``.
:arg element_boundaries: a vector of element boundary locations in
:math:`[0, 1]`, in order. :math:`0` must be the first entry, :math:`1`
the last one.
:arg order: order of the (simplex) elements. If *unit_nodes* is also
provided, the orders should match.
:arg unit_nodes: if given, the unit nodes to use. Must have shape
``(2, nnodes)``.
:arg node_vertex_consistency_tolerance: passed to the
:class:`~meshmode.mesh.Mesh` constructor. If *False*, no checks are
performed.
:arg closed: if *True*, the curve is assumed closed and the first and
last of the *element_boundaries* must match.
:arg return_parametrization_points: if *True*, the parametrization points
at which all the nodes in the mesh were evaluated are also returned.
:returns: a :class:`~meshmode.mesh.Mesh`, or if *return_parametrization_points*
is *True*, a tuple ``(mesh, par_points)``, where *par_points* is an array of
parametrization points.
"""
assert element_boundaries[0] == 0
assert element_boundaries[-1] == 1
nelements = len(element_boundaries) - 1
if unit_nodes is None:
unit_nodes = mp.warp_and_blend_nodes(1, order)
nodes_01 = 0.5*(unit_nodes+1)
wrap = nelements
if not closed:
wrap += 1
vertices = curve_f(element_boundaries)[:, :wrap]
vertex_indices = np.vstack([
np.arange(0, nelements, dtype=np.int32),
np.arange(1, nelements + 1, dtype=np.int32) % wrap
]).T
assert vertices.shape[1] == np.max(vertex_indices) + 1
if closed:
start_end_par = np.array([0, 1], dtype=np.float64)
start_end_curve = curve_f(start_end_par)
assert la.norm(start_end_curve[:, 0] - start_end_curve[:, 1]) < 1.0e-12
el_lengths = np.diff(element_boundaries)
el_starts = element_boundaries[:-1]
# (el_nr, node_nr)
t = el_starts[:, np.newaxis] + el_lengths[:, np.newaxis]*nodes_01
t = t.ravel()
nodes = curve_f(t).reshape(vertices.shape[0], nelements, -1)
from meshmode.mesh import Mesh, SimplexElementGroup
egroup = SimplexElementGroup.make_group(
order,
vertex_indices=vertex_indices,
nodes=nodes,
unit_nodes=unit_nodes)
mesh = Mesh(
vertices=vertices, groups=[egroup],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
if return_parametrization_points:
return mesh, t
else:
return mesh
# }}}
# {{{ make_group_from_vertices
@deprecate_keyword("group_factory", "group_cls")
def make_group_from_vertices(
vertices: np.ndarray, vertex_indices: np.ndarray, order: int, *,
group_cls: Optional[type] = None,
unit_nodes: Optional[np.ndarray] = None) -> MeshElementGroup:
# shape: (ambient_dim, nelements, nvertices)
ambient_dim = vertices.shape[0]
el_vertices = vertices[:, vertex_indices]
from meshmode.mesh import SimplexElementGroup, TensorProductElementGroup
if group_cls is None:
group_cls = SimplexElementGroup
if issubclass(group_cls, SimplexElementGroup):
if order < 1:
raise ValueError("can't represent simplices with mesh order < 1")
el_origins = el_vertices[:, :, 0][:, :, np.newaxis]
# ambient_dim, nelements, nspan_vectors
spanning_vectors = (
el_vertices[:, :, 1:] - el_origins)
nspan_vectors = spanning_vectors.shape[-1]
dim = nspan_vectors
# dim, nunit_nodes
if unit_nodes is None:
shape = mp.Simplex(dim)
space = mp.space_for_shape(shape, order)
unit_nodes = mp.edge_clustered_nodes_for_space(space, shape)
unit_nodes_01 = 0.5 + 0.5*unit_nodes
nodes = np.einsum(
"si,des->dei",
unit_nodes_01, spanning_vectors) + el_origins
elif issubclass(group_cls, TensorProductElementGroup):
nelements, nvertices = vertex_indices.shape
dim = nvertices.bit_length() - 1
if nvertices != 2**dim:
raise ValueError("invalid number of vertices for tensor-product "
"elements, must be power of two")
shape = mp.Hypercube(dim)
space = mp.space_for_shape(shape, order)
if unit_nodes is None:
unit_nodes = mp.edge_clustered_nodes_for_space(space, shape)
# shape: (dim, nnodes)
unit_nodes_01 = 0.5 + 0.5*unit_nodes
_, nnodes = unit_nodes.shape
vertex_space = mp.space_for_shape(shape, 1)
vertex_tuples = mp.node_tuples_for_space(vertex_space)
assert len(vertex_tuples) == nvertices
vdm = np.empty((nvertices, nvertices))
for i, vertex_tuple in enumerate(vertex_tuples):
for j, func_tuple in enumerate(vertex_tuples):
vertex_ref = np.array(vertex_tuple, dtype=np.float64)
vdm[i, j] = np.prod(vertex_ref**func_tuple)
# shape: (ambient_dim, nelements, nvertices)
coeffs = np.empty((ambient_dim, nelements, nvertices))
for d in range(ambient_dim):
coeffs[d] = la.solve(vdm, el_vertices[d].T).T
vdm_nodes = np.zeros((nnodes, nvertices))
for j, func_tuple in enumerate(vertex_tuples):
vdm_nodes[:, j] = np.prod(
unit_nodes_01 ** np.array(func_tuple).reshape(-1, 1),
axis=0)
nodes = np.einsum("ij,dej->dei", vdm_nodes, coeffs)
else:
raise ValueError(f"unsupported value for 'group_cls': {group_cls}")
# make contiguous
nodes = nodes.copy()
return group_cls.make_group(
order, vertex_indices, nodes,
unit_nodes=unit_nodes)
# }}}
# {{{ generate_icosahedron
def generate_icosahedron(
r: float, order: int, *,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None) -> Mesh:
# https://en.wikipedia.org/w/index.php?title=Icosahedron&oldid=387737307
phi = (1+5**(1/2))/2
from pytools import flatten
vertices = np.array(sorted(flatten([
(0, pm1*1, pm2*phi),
(pm1*1, pm2*phi, 0),
(pm1*phi, 0, pm2*1)]
for pm1 in [-1, 1]
for pm2 in [-1, 1]))).T.copy()
top_ring = [11, 7, 1, 2, 8]
bottom_ring = [10, 9, 3, 0, 4]
bottom_point = 6
top_point = 5
tris = []
m = len(top_ring)
for i in range(m):
tris.append([top_ring[i], top_ring[(i+1) % m], top_point])
tris.append([bottom_ring[i], bottom_point, bottom_ring[(i+1) % m], ])
tris.append([bottom_ring[i], bottom_ring[(i+1) % m], top_ring[i]])
tris.append([top_ring[i], bottom_ring[(i+1) % m], top_ring[(i+1) % m]])
vertices *= r/la.norm(vertices[:, 0])
vertex_indices = np.array(tris, dtype=np.int32)
grp = make_group_from_vertices(vertices, vertex_indices, order,
unit_nodes=unit_nodes)
from meshmode.mesh import Mesh
return Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
def generate_cube_surface(r: float, order: int, *,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None) -> Mesh:
shape = mp.Hypercube(3)
vertices = mp.unit_vertices_for_shape(shape)
vertices *= r / la.norm(vertices, ord=2, axis=0)
vertex_indices = np.array([
face.volume_vertex_indices for face in mp.faces_for_shape(shape)
], dtype=np.int32)
from meshmode.mesh import TensorProductElementGroup
grp = make_group_from_vertices(
vertices, vertex_indices, order,
group_cls=TensorProductElementGroup,
unit_nodes=unit_nodes)
from meshmode.mesh import Mesh
return Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
# }}}
# {{{ generate_icosphere
def generate_icosphere(r: float, order: int, *,
uniform_refinement_rounds: int = 0,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None) -> Mesh:
from warnings import warn
warn("'generate_icosphere' is deprecated and will be removed in 2023. "
"Use 'generate_sphere' instead.",
DeprecationWarning, stacklevel=2)
from meshmode.mesh import SimplexElementGroup
return generate_sphere(r, order,
uniform_refinement_rounds=uniform_refinement_rounds,
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
unit_nodes=unit_nodes,
group_cls=SimplexElementGroup)
def generate_sphere(r: float, order: int, *,
uniform_refinement_rounds: int = 0,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None,
group_cls: Optional[type] = None):
"""
:arg r: radius of the sphere.
:arg order: order of the group elements. If *unit_nodes* is also
provided, the orders should match.
:arg uniform_refinement_rounds: number of uniform refinement rounds to
perform after the initial mesh was created.
:arg node_vertex_consistency_tolerance: passed to the
:class:`~meshmode.mesh.Mesh` constructor. If *False*, no checks are
performed.
:arg unit_nodes: if given, the unit nodes to use. Must have shape
``(3, nnodes)``.
:arg group_cls: a :class:`~meshmode.mesh.MeshElementGroup` subclass.
Based on the class, a different polyhedron is used to construct the
sphere: simplices use :func:`generate_icosahedron` and tensor
products use a :func:`generate_cube_surface`.
"""
from meshmode.mesh import SimplexElementGroup, TensorProductElementGroup
if group_cls is None:
group_cls = SimplexElementGroup
if issubclass(group_cls, SimplexElementGroup):
mesh = generate_icosahedron(r, order,
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
unit_nodes=unit_nodes)
elif issubclass(group_cls, TensorProductElementGroup):
mesh = generate_cube_surface(r, order,
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
unit_nodes=unit_nodes)
else:
raise TypeError(f"unsupported 'group_cls': {group_cls}")
if uniform_refinement_rounds:
from meshmode.mesh.refinement import refine_uniformly
mesh = refine_uniformly(mesh, uniform_refinement_rounds)
# ensure vertices and nodes are still on the sphere of radius r
from dataclasses import replace
vertices = mesh.vertices * r / np.sqrt(np.sum(mesh.vertices**2, axis=0))
grp, = mesh.groups
grp = replace(grp,
nodes=grp.nodes * r / np.sqrt(np.sum(grp.nodes**2, axis=0)),
element_nr_base=None, node_nr_base=None)
from meshmode.mesh import Mesh
return Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
# }}}
# {{{ generate_surface_of_revolution
def generate_surface_of_revolution(
get_radius: Callable[[np.ndarray, np.ndarray], np.ndarray],
height_discr: np.ndarray,
angle_discr: np.ndarray,
order: int, *,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None) -> Mesh:
"""Return a cylinder aligned with the "height" axis aligned with the Z axis.
:arg get_radius: A callable function that takes in a 1D array of heights
and a 1D array of angles and returns a 1D array of radii.
:arg height_discr: A discretization of ``[0, 2*pi)``.
:arg angle_discr: A discretization of ``[0, 2*pi)``.
:arg order: order of the (simplex) elements. If *unit_nodes* is also
provided, the orders should match.
:arg node_vertex_consistency_tolerance: passed to the
:class:`~meshmode.mesh.Mesh` constructor. If *False*, no checks are
performed.
:arg unit_nodes: if given, the unit nodes to use. Must have shape
``(3, nnodes)``.
"""
n = len(angle_discr)
m = len(height_discr)
vertices = np.zeros((3, n*m))
theta, h = np.meshgrid(angle_discr, height_discr)
theta = theta.flatten()
h = h.flatten()
r = get_radius(h, theta)
vertices[0, :] = np.cos(theta)*r
vertices[1, :] = np.sin(theta)*r
vertices[2, :] = h
tris = []
for i in range(m-1):
for j in range(n):
tris.append([i*n + j, (i + 1)*n + j, (i + 1)*n + (j + 1) % n])
tris.append([i*n + j, i*n + (j + 1) % n, (i + 1)*n + (j + 1) % n])
vertex_indices = np.array(tris, dtype=np.int32)
grp = make_group_from_vertices(vertices, vertex_indices, order,
unit_nodes=unit_nodes)
from meshmode.mesh import Mesh
mesh = Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
# ensure vertices and nodes are still on the surface with radius r
def ensure_radius(arr):
res = arr.copy()
h = res[2, :].flatten()
theta = np.arctan2(res[1, :].flatten(), res[0, :].flatten())
r_expected = get_radius(h, theta).reshape(res[0, :].shape)
res[:2, :] *= r_expected/np.sum(res[:2, :]**2, axis=0)
return res
from dataclasses import replace
vertices = ensure_radius(mesh.vertices)
grp, = mesh.groups
grp = replace(grp, nodes=ensure_radius(grp.nodes),
element_nr_base=None, node_nr_base=None)
from meshmode.mesh import Mesh
return Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True)
# }}}
# {{{ generate_torus_and_cycle_vertices
def generate_torus_and_cycle_vertices(
r_major: float, r_minor: float,
n_major: int = 20, n_minor: int = 10, order: int = 1,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None,
group_cls: Optional[type] = None,
) -> Mesh:
a = r_major
b = r_minor
# {{{ create periodic grid
from meshmode.mesh import SimplexElementGroup, TensorProductElementGroup
if group_cls is None:
group_cls = SimplexElementGroup
def idx(i, j):
return i + j * (n_major + 1)
if issubclass(group_cls, SimplexElementGroup):
# NOTE: this makes two triangles from a the square like
# (i, j+1) (i+1, j+1)
# o---------o
# | \ |
# | \ |
# | \ |
# | \ |
# o---------o
# (i, j) (i+1, j)
vertex_indices = ([
(idx(i, j), idx(i+1, j), idx(i, j+1))
for i in range(n_major) for j in range(n_minor)
] + [
(idx(i+1, j), idx(i+1, j+1), idx(i, j+1))
for i in range(n_major) for j in range(n_minor)
])
elif issubclass(group_cls, TensorProductElementGroup):
# NOTE: this should match the order of the points in modepy
vertex_indices = [
(idx(i, j), idx(i+1, j), idx(i, j+1), idx(i+1, j+1))
for i in range(n_major) for j in range(n_minor)
]
else:
raise TypeError(f"unsupported 'group_cls': {group_cls}")
# NOTE: include endpoints first so that `make_group_from_vertices` can
# actually interpolate the unit nodes to each element
u = np.linspace(0.0, 2.0 * np.pi, n_major + 1)
v = np.linspace(0.0, 2.0 * np.pi, n_minor + 1)
uv = np.stack(np.meshgrid(u, v, copy=False)).reshape(2, -1)
vertex_indices = np.array(vertex_indices, dtype=np.int32)
grp = make_group_from_vertices(
uv, vertex_indices, order,
unit_nodes=unit_nodes,
group_cls=group_cls)
# }}}
# {{{ evaluate on torus
# https://web.archive.org/web/20160410151837/https://www.math.hmc.edu/~gu/curves_and_surfaces/surfaces/torus.html # noqa
# create new vertices without the endpoints
u = np.linspace(0.0, 2.0 * np.pi, n_major, endpoint=False)
v = np.linspace(0.0, 2.0 * np.pi, n_minor, endpoint=False)
u, v = np.meshgrid(u, v, copy=False)
# wrap the indices around
i = vertex_indices % (n_major + 1)
j = vertex_indices // (n_major + 1)
vertex_indices = (i % n_major) + (j % n_minor) * n_major
# evaluate vertices on torus
vertices = np.stack([
np.cos(u) * (a + b*np.cos(v)),
np.sin(u) * (a + b*np.cos(v)),
b * np.sin(v)
]).reshape(3, -1)
# evaluate nodes on torus
u, v = grp.nodes
nodes = np.stack([
np.cos(u) * (a + b*np.cos(v)),
np.sin(u) * (a + b*np.cos(v)),
b * np.sin(v)
])
# }}}
from dataclasses import replace
grp = replace(grp, vertex_indices=vertex_indices, nodes=nodes,
element_nr_base=None, node_nr_base=None)
from meshmode.mesh import Mesh
return (
Mesh(
vertices, [grp],
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
is_conforming=True),
[idx(i, 0) for i in range(n_major)],
[idx(0, j) for j in range(n_minor)])
# }}}
# {{{ generate_torus
def generate_torus(
r_major: float, r_minor: float,
n_major: int = 20, n_minor: int = 10, order: int = 1,
node_vertex_consistency_tolerance: Optional[Union[float, bool]] = None,
unit_nodes: Optional[np.ndarray] = None,
group_cls: Optional[type] = None) -> Mesh:
r"""Generate a torus.
.. tikz:: A torus with major circle (magenta) and minor circle (red).
:align: center
:xscale: 60
\pgfmathsetmacro{\a}{1.5};
\pgfmathsetmacro{\b}{0.5};
\begin{axis}[hide axis, axis equal image]
\addplot3[
mesh,
gray!20,
samples=20,
domain=0:2*pi,y domain=0:2*pi,
z buffer=sort] (
{(\a + \b*cos(deg(x))) * cos(deg(y+pi/2))},
{(\a + \b*cos(deg(x))) * sin(deg(y+pi/2))},
{\b*sin(deg(x))});
\addplot3 [red, thick, samples=40, domain=0:2*pi] (
{(\a + \b*cos(deg(x))) * cos(deg(-pi/6))},
{(\a + \b*cos(deg(x))) * sin(deg(-pi/6))},
{\b*sin(deg(x))});
\addplot3 [magenta, thick, samples=80, domain=0:2*pi] (
{(\a + \b*cos(deg(pi/2))) * cos(deg(x))},
{(\a + \b*cos(deg(pi/2))) * sin(deg(x))},
{\b*sin(deg(pi/2))});
\end{axis}
The torus is obtained as the image of the parameter domain
:math:`(u, v) \in [0, 2\pi) \times [0, 2 \pi)` under the map
.. math::
\begin{aligned}
x &= \cos(u) (r_\text{major} + r_\text{minor} \cos(v)) \\
y &= \sin(u) (r_\text{major} + r_\text{minor} \sin(v)) \\
z &= r_\text{minor} \sin(v)
\end{aligned}
where :math:`r_\text{major}` and :math:`r_\text{minor}` are the radii of the
major and minor circles, respectively. The parameter domain is tiled with
:math:`n_\text{major} \times n_\text{minor}` contiguous rectangles, and then
each rectangle is subdivided into two triangles.
:arg r_major: radius of the major circle.
:arg r_minor: radius of the minor circle.
:arg n_major: number of rectangles along major circle.
:arg n_minor: number of rectangles along minor circle.
:arg order: order of the (simplex) elements. If *unit_nodes* is also
provided, the orders should match.
:arg node_vertex_consistency_tolerance: passed to the
:class:`~meshmode.mesh.Mesh` constructor. If *False*, no checks are
performed.
:arg unit_nodes: if given, the unit nodes to use. Must have shape
``(3, nnodes)``.
:returns: a :class:`~meshmode.mesh.Mesh` of a torus.
"""
mesh, _, _ = generate_torus_and_cycle_vertices(
r_major, r_minor, n_major, n_minor, order,
node_vertex_consistency_tolerance=node_vertex_consistency_tolerance,
unit_nodes=unit_nodes,
group_cls=group_cls)
return mesh
# }}}
# {{{ get_urchin
def refine_mesh_and_get_urchin_warper(
order: int, m: int, n: int, est_rel_interp_tolerance: float,
min_rad: float = 0.2,
uniform_refinement_rounds: int = 0) -> Mesh:
"""
:arg order: order of the (simplex) elements.
:arg m: order of the spherical harmonic :math:`Y^m_n`.
:arg n: order of the spherical harmonic :math:`Y^m_n`.
:arg est_rel_interp_tolerance: a tolerance for the relative
interpolation error estimates on the warped version of the mesh.
:returns: a tuple ``(refiner, warp_mesh)``, where *refiner* is
a :class:`~meshmode.mesh.refinement.RefinerWithoutAdjacency` (from
which the unwarped mesh may be obtained), and whose
:meth:`~meshmode.mesh.refinement.RefinerWithoutAdjacency.get_current_mesh`
returns a locally-refined :class:`~meshmode.mesh.Mesh` of a sphere and
*warp_mesh* is a callable taking and returning a mesh that warps the
unwarped mesh into a smooth shape covered by a spherical harmonic of
order :math:`(m, n)`.
.. versionadded: 2018.1
"""
def sph_harm(m, n, pts):
assert abs(m) <= n
x, y, z = pts
r = np.sqrt(np.sum(pts**2, axis=0))
theta = np.arccos(z/r)
phi = np.arctan2(y, x)
import scipy.special as sps
# Note: This matches the spherical harmonic
# convention in the QBX3D paper:
# https://arxiv.org/abs/1805.06106
#
# Numpy takes arguments in the order (theta, phi)
# *and* swaps their meanings, so passing the
# arguments swapped maintains the intended meaning.
return sps.sph_harm(m, n, phi, theta) # pylint: disable=no-member
def map_coords(pts):
r = np.sqrt(np.sum(pts**2, axis=0))
sph = sph_harm(m, n, pts).real
scaled = min_rad + (sph - lo)/(hi-lo)
new_rad = scaled
return pts * new_rad / r
def warp_mesh(mesh, node_vertex_consistency_tolerance):
from dataclasses import replace
groups = [
replace(grp, nodes=map_coords(grp.nodes),
element_nr_base=None, node_nr_base=None)
for grp in mesh.groups]
from meshmode.mesh import Mesh
return Mesh(
map_coords(mesh.vertices),
groups,
node_vertex_consistency_tolerance=False,
is_conforming=mesh.is_conforming,
)
unwarped_mesh = generate_sphere(1, order=order)
from meshmode.mesh.refinement import RefinerWithoutAdjacency
# These come out conformal, so we're OK to use the faster refiner.
refiner = RefinerWithoutAdjacency(unwarped_mesh)
for _ in range(uniform_refinement_rounds):
refiner.refine_uniformly()
nodes_sph = sph_harm(m, n, unwarped_mesh.groups[0].nodes).real
lo = np.min(nodes_sph)
hi = np.max(nodes_sph)
del nodes_sph
from functools import partial
unwarped_mesh = warp_and_refine_until_resolved(
refiner,
partial(warp_mesh, node_vertex_consistency_tolerance=False),
est_rel_interp_tolerance)
return refiner, partial(
warp_mesh,
node_vertex_consistency_tolerance=est_rel_interp_tolerance)
def generate_urchin(
order: int, m: int, n: int,
est_rel_interp_tolerance: float,
min_rad: float = 0.2) -> Mesh:
"""
:arg order: order of the (simplex) elements. If *unit_nodes* is also
provided, the orders should match.
:arg m: order of the spherical harmonic :math:`Y^m_n`.
:arg n: order of the spherical harmonic :math:`Y^m_n`.
:arg est_rel_interp_tolerance: a tolerance for the relative
interpolation error estimates on the warped version of the mesh.
:returns: a refined :class:`~meshmode.mesh.Mesh` of a smooth shape covered
by a spherical harmonic of order :math:`(m, n)`.
.. versionadded: 2018.1
"""
refiner, warper = refine_mesh_and_get_urchin_warper(
order, m, n, est_rel_interp_tolerance,
min_rad=min_rad,
uniform_refinement_rounds=0,
)
return warper(refiner.get_current_mesh())
# }}}
# {{{ generate_box_mesh
@deprecate_keyword("group_factory", "group_cls")
def generate_box_mesh(axis_coords, order=1, *, coord_dtype=np.float64,
periodic=None, group_cls=None, boundary_tag_to_face=None,
mesh_type=None, unit_nodes=None) -> Mesh:
r"""Create a semi-structured mesh.
:arg axis_coords: a tuple with a number of entries corresponding
to the number of dimensions, with each entry a numpy array
specifying the coordinates to be used along that axis. The coordinates