-
Notifications
You must be signed in to change notification settings - Fork 4
/
domains.py
1316 lines (1036 loc) · 37.5 KB
/
domains.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
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
"""
Domain definitions. Implements various domain classes.
Meshes are generated using get(params) method of subclasses of GenericDomain.
Calling an object with params returns the mesh.
See GenericDomain.__call__ docstring for details.
Argument params is a string containing lists/numbers. The format does not need
to be Python's syntax. E.g. space separated numbers will be turned into a list.
Mathematical functions can also be used on numbers or elementwise on lists.
The string is evaluated and formatted to suit each subclass using
format method, full and default attributes of each class.
This rather strange setup was dictated by params coming from user
interaction with text inputs in GUI.
Calling an object makes it easy to use the object in multiprocessing as a
target function, with all parameters already stored in the object.
Note: Methods are not picklable, but object() is OK.
Docstrings of the domains are used in GUI as help messages and domain names.
The first line is the name. The rest constitutes the help, possibly with
long lines as paragraphs of text. These normally have backslash as last
character, but this interferes with indentation removal. Instead, docstrings
are raw strings and trailing backslash is removed with the newline character
in postprocessing (build_domain_dict function).
"""
from __future__ import division
# pylama:ignore=E731
from math import pi, sin, cos, sqrt, tan
import numpy as np
from dolfin import Mesh, MeshEditor, DynamicMeshEditor, RectangleMesh, \
UnitSquareMesh, Point, UnitCubeMesh, BoxMesh, compile_extension_module
from mshr import Circle, UnitSphereMesh, generate_mesh, Polygon
from paramchecker import evaluate, ParamChecker, clip, flatten
np.seterr(divide='ignore', invalid='ignore')
np.set_printoptions(precision=5, suppress=True)
# compile c++ code
with open("cpp/buildmesh.cpp", "r") as f:
code = f.read()
builder = compile_extension_module(code=code) # , source_directory="cpp"
# include_dirs=["."])
def CircleMesh(p, r, s):
""" mshr has no CircleMesh. """
return generate_mesh(Circle(p, r, max(int(4 * pi / s), 4)), int(2 / s))
class GenericDomain(ParamChecker):
"""
Abstract superclass of all domains used for eigenvalue calculations.
Parameters are set using eval(params) method.
Mesh can be obtained from get() method, or by calling an object.
Parameters depend on the specific domain implementation.
"""
diag = ("left", "right", "crossed")
dim = "2D"
def __call__(self, monitor=None):
"""Return the mesh. Monitor could be used to pass progress. """
self.monitor = monitor
return self.get()
def get(self):
"""
Should return mesh.
self.eval(params) should be used to parse params,
set self.params and self.values
self.params will be
the same as the argument if the argument was useful,
equal self.default if the argument was '',
otherwise the previous value of self.params
self.values contains evaluated params
"""
raise NotImplementedError("Implement this!")
def with_params(self):
"""Check if domain has any parameters."""
return self.full is not None
#
# 2D domains
#
class RegularDomain(GenericDomain):
"""
Regular polygon.
Parameter: number of sides.
"""
default = "3"
full = [3]
@staticmethod
def format(x):
"""One integer with a lower bound."""
return clip(x[:1], int, 3)
def get(self):
"""One triangle per side with common vertex at (0,0)."""
sides = self.values[0]
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(sides + 1)
editor.init_cells(sides)
editor.add_vertex(0, 0, 0)
for i in range(1, sides + 1):
editor.add_vertex(i,
cos(2 * pi * i / sides),
sin(2 * pi * i / sides))
for i in range(sides - 1):
editor.add_cell(i, 0, i + 1, i + 2)
editor.add_cell(sides - 1, 0, sides, 1)
editor.close()
return mesh
class PolygonalSectorDomain(GenericDomain):
"""
Polygonal sector.
Approximation of a circular sector using K sides of a regular N-gon.
Parameters: N, K.
"""
default = "12, 2"
full = (12, 2)
@staticmethod
def format(x):
"""Two integers with lower bounds."""
return clip(x[:2], int, [3, 2])
def get(self):
"""Part of the regular polygon construction."""
sides, angle = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2) # dimension
editor.init_vertices(angle + 2)
editor.init_cells(angle)
editor.add_vertex(0, 0, 0)
for i in range(0, angle + 1):
editor.add_vertex(i + 1,
cos(2 * pi * i / sides),
sin(2 * pi * i / sides))
editor.add_cell(0, 2, 1, 0)
for i in range(1, angle):
editor.add_cell(i, 0, i + 1, i + 2)
editor.close()
return mesh
class SquareDomain(GenericDomain):
r"""
Unit square.
Unit square [0,1]x[0,1] subdivided into NxK rectangles, with diagonal \
edge types given by L=0,1,2.
Parameters: N,K,L (all optional).
Default: 1,1,0.
"""
default = ""
full = (1, 1, 0)
@staticmethod
def format(x):
"""Two nonnegative integers. Then integer between 0 and 2."""
return clip(x[:2], int, 1) + clip(x[2:3], int, 0, 2)
def get(self):
"""Built in mesh."""
x = self.pad(self.values)
return UnitSquareMesh(x[0], x[1], self.diag[x[2]])
class RectangleDomain(GenericDomain):
r"""
Rectangle.
Rectangle centered at the origin with sides of length A and B, \
subdivided into NxK rectangles, with diagonal edge types given by L=0,1,2.
Parameters: A,B,N,K,L (all optional).
Default: 2,1,1,1,0.
"""
default = "2, 1"
full = (2, 1, 1, 1, 0)
@staticmethod
def format(x):
"""Two positive floats, then three ints."""
return clip(np.fabs(x[:2]), float, 0.0001) + clip(x[2:4], int, 1) + \
clip(x[4:5], int, 0, 2)
def get(self):
"""Built in mesh."""
x = self.pad(self.values)
return RectangleMesh(Point(-x[0] / 2.0, -x[1] / 2.0),
Point(x[0] / 2.0, x[1] / 2.0),
x[2], x[3], self.diag[x[4]])
class CircleDomain(GenericDomain):
"""
Disk.
Unit disk centered at the origin with triangles of size L.
Parameters L, (optional).
Default: 0.1.
"""
default = "0.1"
full = [0.1]
@staticmethod
def format(x):
"""One positive float."""
return clip(np.fabs(x[:1]), float, 0.003)
def get(self):
"""Built-in mesh."""
return CircleMesh(Point(0, 0), 1, self.pad(self.values)[0])
class TriangleDomain(GenericDomain):
"""
Triangle.
Triangle with vertices (0, 0), (1, 0) and (A, B).
Parameters: A, B (optional).
Default: (1/2, sqrt(3)/2) (equilateral triangle).
"""
default = "1/2, sqrt(3)/2"
full = (0.5, sqrt(3) / 2)
@staticmethod
def format(x):
"""One float. Then one positive float."""
return clip(x[:1], float) + clip(np.fabs(x[1:2]), float, 0.0001)
def get(self):
"""Just one cell."""
topx, topy = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(3)
editor.init_cells(1)
editor.add_vertex(0, 0, 0)
editor.add_vertex(1, 1, 0)
editor.add_vertex(2, topx, topy)
editor.add_cell(0, 0, 1, 2)
editor.close()
return mesh
class RightTriangleDomain(TriangleDomain):
"""
Right triangle.
Right triangle with vertices (0,0), (1,0) and smallest angle A near (0,0).
Parameters: A (optional).
Default: pi/4. (right isosceles triangle)
"""
default = "pi/4"
full = (1.0, tan(pi/4))
@staticmethod
def format(x):
"""Based on the general triangle."""
return [1] + clip(abs(tan(x[0])), float, 0.001, 1)
class ParallelogramDomain(GenericDomain):
"""
Parallelogram.
Parallelogram with vertices (0,0), (1,0), (A,B) and (1-A,-B).
Parameters: A, B (optional).
Default: 0,1.
"""
default = "0, 1"
full = (0.0, 1.0)
@staticmethod
def format(x):
"""One float. Then positive float."""
return clip(x[:1], float) + clip(np.fabs(x[1:2]), float, 0.0001)
def get(self):
"""Two cells."""
topx, topy = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(4)
editor.init_cells(2)
editor.add_vertex(0, 0, 0)
editor.add_vertex(1, 1, 0)
editor.add_vertex(2, topx, topy)
editor.add_vertex(3, 1 - topx, -topy)
editor.add_cell(0, 0, 1, 2)
editor.add_cell(1, 0, 1, 3)
editor.close()
return mesh
class KiteDomain(GenericDomain):
"""
Kite.
Kite with vertices (0,0), (1,0), (A,B) and (A,-B).
Parameters: A, B (optional).
Default: 0.25,0.5.
"""
default = "0.25, 0.5"
full = (0.25, 0.5)
@staticmethod
def format(x):
"""One float. Then positive float."""
return clip(x[:1], float) + clip(np.fabs(x[1:2]), float, 0.0001)
def get(self):
"""Two cells."""
a, b = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(4)
editor.init_cells(2)
editor.add_vertex(0, 0, 0)
editor.add_vertex(1, 1, 0)
editor.add_vertex(2, a, b)
editor.add_vertex(3, a, -b)
editor.add_cell(0, 0, 1, 2)
editor.add_cell(1, 0, 1, 3)
editor.close()
return mesh
class IsoscelesDomain(KiteDomain):
"""
Isosceles triangle.
Isosceles triangle with vertices (0,0), (1,-+?) and angle A near (0,0).
Parameters: A (optional).
Default: pi/3.
"""
default = "pi/3"
full = (1.0, tan(pi / 6))
@staticmethod
def format(x):
"""Based on kites."""
return [1] + clip(abs(tan(x[0] / 2)), float, 0.001)
class StarDomain(GenericDomain):
r"""
Star-shaped polygon.
Star-shaped polygon in polar coordinates.
The first parameter should be a list of polar angles in degrees.
(randA(n) gives a sorted list of n random angles)
The second parameter is a list of distances from the origin.
(randD(n,min) gives random distances from (min,min+1) with default \
value min=0.5)
If the list of angles contains at most 2 elements, the first is used to \
generate a new list of equally spaced angles.
If the second list is too short, it will be reused cyclically to make \
rotationally symmetric pattern.
"""
default = "24, randD(6)"
full = True
@staticmethod
def format(x):
"""Two lists of floats."""
return [clip(x[0], float), clip(x[1], float)]
def get(self):
"""Build vertices from polar coordinates."""
angle, dist = self.values
if len(angle) < 3:
angle = np.array(range(int(angle[0]))) * 360.0 / angle[0]
while len(dist) < len(angle):
dist = dist * 2
dist = np.array(dist)
sides = len(angle)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(sides + 1)
editor.init_cells(sides)
editor.add_vertex(0, 0, 0)
for i in range(1, sides + 1):
editor.add_vertex(i, dist[i - 1] * cos(angle[i - 1] / 180.0 * pi),
dist[i - 1] * sin(angle[i - 1] / 180.0 * pi))
for i in range(sides - 1):
editor.add_cell(i, 0, i + 1, i + 2)
editor.add_cell(sides - 1, 0, sides, 1)
editor.close()
return mesh
class PolygonDomain(GenericDomain):
r"""
Polygon.
Polygon with vertices given as a list ((x1, y1), (x2, y2), ...).
Parentheses can be omitted inside of the list, and rand/randU can \
be used to get N random points, see examples).
Parameters: L - list of vertices, C - convex hull (0 or 1), \
S - triangle sizes (default=0 (automatic)).
Examples:
- rand(8),0 gives arbitrary quadrilaterals,
- rand(8),1 finds convex hull giving a convex quadrilateral or a triangle,
- randU(4),1 gives four vertices on a unit circle.
"""
default = "((0, 0), (2, 0), (2, 2), (1, 2), (1, 1), (0, 1)), 0"
full = [((0, 0), (2, 0), (2, 2), (1, 2), (1, 1), (0, 1)), 0, 0]
@staticmethod
def format(x):
"""List of vertices. Then convex or not. Then integer for sizes."""
# flatten vertices, then reshape into points
temp = [np.reshape(clip(flatten(x[0]), float), (-1, 2))] + \
clip(x[1:3], int, 0, [1, 500])
if len(temp[0]) < 3:
return []
return temp
def get(self):
"""Built-in polygonal mesh."""
params = self.pad(self.values)
if params[1]:
vertices = convex_hull(params[0])
else:
vertices = params[0]
vertices = [Point(*p) for p in vertices]
size = params[2]
try:
# may fail if not counterclockwise vertices
poly = Polygon(vertices)
except:
poly = Polygon(vertices[::-1])
return generate_mesh(poly, size)
class IsospectralDomain(GenericDomain):
r"""
Isospectral drums.
Pairs of isospectral of domains.
Starting with a triangle, build a domain using a sequence of reflections.
Parameters: N,K and optional (A,B), S.
The first parameter chooses a pair of domains (N=-1 to 4), while K=0,1 \
chooses a specific domain. Generating triangle has vertices (0,0), (1,0) \
and angles 2pi/A, 2pi/B at these vertices.
The default values of A and B depends on N. Case (N=2, A=B=8) gives the \
original example due to Gordon, Webb and Wolpert.
Equilateral generator gives isometric domains (possibly with slits), \
while other triangles should lead to nonisometric examples \
(sometimes selfintersecting).
The examples are based on Figures 4 from Buser, Conway, Doyle and Semmler \
(order as on the figure). A special, two piece example can be obtained by \
taking N=-1 (due to Chapman).
Parameters 3,0,6,12 and 4,0,6,12 give the same shape, but with different \
slits, while their pairing 3,1 and 4,1 are very different.
"""
default = "2, 0"
full = [2, 0, 8, 8]
@staticmethod
def format(x):
"""Which pair. Then which one of the two. The two floats for angles."""
return clip(x[:2], int, [-1, 0], [4, 1]) + clip(x[2:4], float, 2.001)
# TODO: add more domains
# TODO: Change angle parametrization
trees = {
# generating reflections
# tree contains side numbers defining reflecion lines
# after the node reflection is performed, a list of children
# is used to perform further reflections
(2, 0): [None, [2, [0], [1, [2, [0, [1]]]]]],
(2, 1): [None, [0], [1], [2, [1, [0, [2]]]]],
(1, 0): [None, [1, [2], [0, [1]]], [2, [0]]],
(1, 1): [None, [1, [0, [2]]], [0], [2, [1]]],
(0, 0): [None, [0, [1]], [1, [2]], [2, [0]]],
(0, 1): [None, [0, [2]], [2, [1]], [1, [0]]],
(3, 0): [None, [0, [1, [2, [1]]]], [1, [2, [0, [2]]]],
[2, [0, [1, [0]]]]],
(3, 1): [None, [0, [2, [1, [2]]]], [1, [0, [2, [0]]]],
[2, [1, [0, [1]]]]],
(4, 0): [None, [2, [0, [1, [0]]]],
[1, [2, [0, [2]]], [0, [1], [2, [1]]]]],
(4, 1): [None, [2, [1], [0, [1]]],
[0, [2, [0]]], [1, [0, [2, [1, [2]]]]]],
}
# default triangle for each pair (two angles touching side of length 1)
shape = [[8, 6], [8, 6], [8, 8], [6, 11], [7, 9]]
# N=-1 vertices (for k=0 and k=1) and triangles (shared)
bothvertices = [
[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0),
(0.0, 2.0), (1.0, 2.0), (1.1, 0.0), (2.1, 1.0),
(1.1, 1.0), (1.1, 2.0)],
[(1.0, 0.0), (2.0, 0.0), (1.0, 1.0), (0.0, 0.0),
(0.0, 1.0), (0.0, 2.0), (1.1, 1.1), (2.1, 1.1),
(1.1, 2.1), (2.1, 2.1)]]
triangles = [
(0, 1, 2), (0, 2, 3), (2, 3, 4), (2, 4, 5), (6, 7, 8), (7, 8, 9)]
def generate(self, tree, indices):
"""Build triangles and vertices lists using trees of reflections."""
newindices = indices[:]
if tree[0] is None:
self.triangles.append(newindices)
else:
newvertex = reflect([self.vertices[i] for i in indices], tree[0])
newindices[tree[0]] = len(self.vertices)
self.triangles.append(newindices)
self.vertices.append(newvertex)
for node in tree[1:]:
self.generate(node, newindices)
def get(self):
"""Build mesh from the tree of triangles created by reflections."""
# get n
n, k, a, b = self.pad(self.values)
# adjust defaults based on n
self.full[2:4] = self.shape[n]
# get all parameters
n, k, a, b = self.pad(self.values)
if n == -1:
self.vertices = self.bothvertices[k]
else:
tree = self.trees[(n, k)]
self.triangles = []
# angles are 2pi/a, 2pi/b
side = np.sin(2 * pi / b) / np.sin(pi - 2 * pi / a - 2 * pi / b)
self.vertices = [
np.array([0.0, 0.0]), np.array([1.0, 0.0]), np.array(
[side * np.cos(2 * pi / a), side * np.sin(2 * pi / a)])]
self.generate(tree, [0, 1, 2])
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(len(self.vertices))
editor.init_cells(len(self.triangles))
for i, v in enumerate(self.vertices):
editor.add_vertex(i, *v)
for i, t in enumerate(self.triangles):
editor.add_cell(i, *t)
editor.close()
return mesh
class AnnulusDomain(GenericDomain):
r"""
Polygonal annulus.
Polygonal annulus formed by two nested regular polygons with the same \
number of sides N. The larger polygon is inscribed in unit circle, while
smaller in circle with radius R.
Use N=4 and Lp to Lq transform with parameters 1 2 to get circular annulus.
Parameters: N - number of sides, R - length ratio smaller to larger polygon.
"""
default = "4 0.5"
full = (5, 0.5)
@staticmethod
def format(x):
"""One integer with a lower bound. Then a positive float up to 0.99. """
return clip(np.fabs(x[:1]), int, 3) + \
clip(np.fabs(x[1:2]), float, 0.001, 0.999)
def get(self):
"""One triangle per side in smaller, two triangles in larger."""
sides, R = self.pad(self.values)
mesh = Mesh()
large = [np.array((cos(2 * pi * i / sides), sin(2 * pi * i / sides)))
for i in range(1, sides+1)]
small = np.array([v * R for v in large])
# centers of edges in large polygon
center = np.array([(v + w) / 2
for v, w in zip(large, large[1:] + [large[0]])])
large = np.array(large)
editor = MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(3 * sides)
editor.init_cells(3 * sides)
for i in range(sides):
editor.add_vertex(3 * i, *large[i])
editor.add_vertex(3 * i + 1, *small[i])
editor.add_vertex(3 * i + 2, *center[i])
for i, j in zip(range(sides), range(1, sides) + [0]):
editor.add_cell(3*i, 3*i, 3*i+1, 3*i+2)
editor.add_cell(3*i+1, 3*i+1, 3*i+2, 3*j+1)
editor.add_cell(3*i+2, 3*i+2, 3*j+1, 3*j)
editor.close()
return mesh
class FunctionDomain(GenericDomain):
r"""
Graphs of functions.
Generates top and bottom bounding curves from expressions involving x or y.
If only one is given, the set will be symmetric.
Important: Each expressions must be enclosed in " " or ' '!
Parameters: (A, B) - domain, F - top curve, B - bottom curve, N - number of\
sample points (default=100).
"""
default = '(-1, 1), "1-x^2"'
full = (-1, 1, "lambda x: 1-x**2", "lambda x: -(1-x**2)", 'x', 100)
@staticmethod
def format(x):
"""Two floats. Then at least one function. Finally an integer. """
x = flatten(x)
if len(x) < 3:
return []
domain = sorted(clip(x[:2], float))
import re
var = 'x' if re.search(r'\bx\b', ''.join(x[2:4])) else 'y'
top = "lambda {}: {}".format(var, x[2])
if len(x) == 3:
bottom = "lambda {}: -({})".format(var, x[2])
else:
bottom = "lambda {}: {}".format(var, x[3])
try:
evaluate(top)[0](domain[0])
evaluate(bottom)[0](domain[0])
except:
return []
return domain + [top, bottom, var] + clip(np.fabs(x[4:5]),
int, 1, 1000)
def get(self):
""" Generate polygon from top and bottom curves. """
m, M, top, bottom, var, N = self.pad(self.values)
top = evaluate(top)[0]
bottom = evaluate(bottom)[0]
if var == 'x':
points = [Point(x, top(x)) for x in np.linspace(m, M, N+2)]
else:
points = [Point(top(x), x) for x in np.linspace(m, M, N+2)]
if abs(top(M)-bottom(M)) < 1E-4:
points.pop()
if var == 'x':
points += [Point(x, bottom(x)) for x in np.linspace(M, m, N+2)]
else:
points += [Point(bottom(x), x) for x in np.linspace(M, m, N+2)]
if abs(top(m)-bottom(m)) < 1E-4:
points.pop()
try:
# may fail if not counterclockwise vertices
poly = Polygon(points)
except:
poly = Polygon(points[::-1])
return generate_mesh(poly, 1)
class StarlikeDomain(GenericDomain):
r"""
Starlike domain.
Generates a domain using a radius function R(theta).
Parameters: R - expression in theta, N - number of sample points \
(default=100).
"""
default = '"1+cos(theta)"'
full = ("lambda theta: 1+cos(theta)", 100)
@staticmethod
def format(x):
"""Function, then an integer. """
print x
radius = "lambda theta: {}".format(x[0])
try:
evaluate(radius)[0](0)
evaluate(radius)[0](np.pi)
except:
return []
return [radius] + clip(np.fabs(x[1:2]), int, 1, 1000)
def get(self):
""" Generate polygon from top and bottom curves. """
radius, N = self.pad(self.values)
radius = evaluate(radius)[0]
points = [Point(*(radius(theta)*np.array([cos(theta), sin(theta)])))
for theta in np.linspace(0, 2*np.pi, N+2)]
if abs(radius(0)-radius(2*np.pi)) < 1E-4:
points.pop()
try:
# may fail if not counterclockwise vertices
poly = Polygon(points)
except:
poly = Polygon(points[::-1])
return generate_mesh(poly, 1)
#
# 3D
#
class GenericDomain3D(GenericDomain):
"""Generic superclass for 3D domains."""
dim = "3D"
class CubeDomain(GenericDomain3D):
"""
Unit cube.
Unit cube [0,1]^3 subdivided into NxKxL rectangles.
Parameters: N,K,L (all optional).
Default: 1,1,1.
"""
default = ""
full = (1, 1, 1)
@staticmethod
def format(x):
"""Three positive integers."""
return clip(x[:3], int, 1)
def get(self):
"""Built-in mesh."""
return UnitCubeMesh(*self.pad(self.values))
class BoxDomain(GenericDomain3D):
r"""
Box.
Box centered at the origin with sides of length A, B and C, \
subdivided into N x K x L boxes.
Parameters: A,B,C,N,K,L (all optional).
Default: 3,2,1,1,1,1.
"""
default = "3, 2, 1"
full = (3, 2, 1, 1, 1, 1)
@staticmethod
def format(x):
"""Three positive floats. Then three positive integers."""
return clip(x[:3], float, 0.0001) + clip(x[3:6], int, 1)
def get(self):
"""Built-in mesh."""
x = self.pad(self.values)
return BoxMesh(Point(-x[0] / 2.0, -x[1] / 2.0, -x[2] / 2.0),
Point(x[0] / 2.0, x[1] / 2.0, x[2] / 2.0),
x[3], x[4], x[5])
class SphereDomain(GenericDomain3D):
"""
Sphere.
Unit sphere centered at the origin, with L boundary subdivisions.
Parameters L (optional).
Default: 10.
"""
default = "10"
full = [10]
@staticmethod
def format(x):
"""One positive float."""
return clip(x[:1], int, 1, 30)
def get(self):
"""Built-in domain."""
return UnitSphereMesh(self.pad(self.values)[0])
class TetrahedronDomain(GenericDomain3D):
"""
Tetrahedron.
Tetrahedron with permutations of (1,1,0) as vertices.
"""
def get(self):
"""One cell."""
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 3, 3)
editor.init_vertices(4)
editor.init_cells(1)
editor.add_vertex(0, 0, 0, 0)
editor.add_vertex(1, 1, 1, 0)
editor.add_vertex(2, 0, 1, 1)
editor.add_vertex(3, 1, 0, 1)
editor.add_cell(0, 0, 1, 2, 3)
editor.close()
return mesh
class OctahedronDomain(GenericDomain3D):
"""
Octahedron.
Octahedron with permutations of (+-1,0,0) as vertices.
Point (0,0,0) is the common vertex of all initial tetrahedra.
"""
def get(self):
"""Eight cells."""
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 3, 3)
editor.init_vertices(7)
editor.init_cells(8)
editor.add_vertex(0, 1, 0, 0)
editor.add_vertex(1, 0, 1, 0)
editor.add_vertex(2, 0, 0, 1)
editor.add_vertex(3, -1, 0, 0)
editor.add_vertex(4, 0, -1, 0)
editor.add_vertex(5, 0, 0, -1)
editor.add_vertex(6, 0, 0, 0)
editor.add_cell(0, 6, 0, 1, 2)
editor.add_cell(1, 6, 0, 1, 5)
editor.add_cell(2, 6, 0, 4, 2)
editor.add_cell(3, 6, 0, 4, 5)
editor.add_cell(4, 6, 3, 1, 2)
editor.add_cell(5, 6, 3, 1, 5)
editor.add_cell(6, 6, 3, 4, 2)
editor.add_cell(7, 6, 3, 4, 5)
editor.close()
return mesh
class PyramidDomain(GenericDomain3D):
r"""
Pyramid.
Pyramid with regular N-gon inscribed into the unit circle as base, \
and (X, Y, Z) as top vertex.
Parameters: N, Z, X, Y (all optional). Default: 4, 1, 0, 0.
"""
default = "4, 1"
full = [4, 1, 0, 0]
@staticmethod
def format(x):
"""Positive integer. The positive float. Then two floats."""
return clip(x[:1], int, 1) + clip(np.fabs(x[1:2]), float, 0.0001) + \
clip(x[2:4], float)
def get(self):
"""Build cells based on triangulated regular polygon."""
sides, h, x, y = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 3, 3) # dimension
editor.init_vertices(sides + 2)
editor.init_cells(sides)
editor.add_vertex(0, x, y, h)
for i in range(1, sides + 1):
editor.add_vertex(i,
cos(2 * pi * i / sides),
sin(2 * pi * i / sides),
0)
editor.add_vertex(sides + 1, 0, 0, 0)
for i in range(sides - 1):
editor.add_cell(i, 0, i + 1, i + 2, sides + 1)
editor.add_cell(sides - 1, 0, sides, 1, sides + 1)
editor.close()
return mesh
class SimplexDomain(GenericDomain3D):
"""
Simplex.
Simplex with vertices (0, 0, 0), (1, 0, 0), (A, B, 0) and (C, D, E).
Parameters: A, B, C, D, E (all optional).
Default: 0, 1, 0, 0, 1.
"""
default = "0, 1, 0, 0, 1"
full = (0, 1, 0, 0, 1)
@staticmethod
def format(x):
"""Five floats. Second and fifth positive."""
return clip(x[:1], float) + clip(np.fabs(x[1:2]), float, 0.0001) + \
clip(x[2:4], float) + clip(np.fabs(x[4:5]), float, 0.0001)
def get(self):
"""Single cell."""
a, b, c, d, e = self.pad(self.values)
mesh = Mesh()
editor = MeshEditor()
editor.open(mesh, 3, 3) # dimension
editor.init_vertices(4)
editor.init_cells(1)
editor.add_vertex(0, 0, 0, 0)
editor.add_vertex(1, 1, 0, 0)
editor.add_vertex(2, a, b, 0)