forked from julesghub/underworld3-old
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscretisation.py
More file actions
2976 lines (2347 loc) · 94.2 KB
/
discretisation.py
File metadata and controls
2976 lines (2347 loc) · 94.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
from typing import Optional, Tuple, Union
from enum import Enum
import os
import numpy
import sympy
from sympy.matrices.expressions.blockmatrix import bc_dist
import sympy.vector
from petsc4py import PETSc
import underworld3 as uw
from underworld3.utilities._api_tools import Stateful
from underworld3.utilities._api_tools import uw_object
from underworld3.coordinates import CoordinateSystem, CoordinateSystemType
from underworld3.cython import petsc_discretisation
import underworld3.timing as timing
## Introduce these two specific types of coordinate tracking vector objects
from sympy.vector import CoordSys3D
## Add the ability to inherit an Enum, so we can add standard boundary
## types to ones that are supplied by the users / the meshing module
## https://stackoverflow.com/questions/46073413/python-enum-combination
def extend_enum(inherited):
def wrapper(final):
joined = {}
inherited.append(final)
for i in inherited:
for j in i:
joined[j.name] = j.value
return Enum(final.__name__, joined)
return wrapper
@timing.routine_timer_decorator
def _from_gmsh(
filename, comm=None, markVertices=False, useRegions=True, useMultipleTags=True
):
"""Read a Gmsh .msh file from `filename`.
:kwarg comm: Optional communicator to build the mesh on (defaults to
COMM_WORLD).
"""
## NOTE: - this should be smart enough to serialise the msh conversion
## and then read back in parallel via h5. This is currently done
## by every gmesh mesh
comm = comm or PETSc.COMM_WORLD
options = PETSc.Options()
options["dm_plex_hash_location"] = None
# This option allows objects to be in multiple physical groups
# Rather than just the first one found.
if useMultipleTags:
options.setValue("dm_plex_gmsh_multiple_tags", True)
else:
options.setValue("dm_plex_gmsh_multiple_tags", False)
# This is usually True because dmplex then contains
# Labels for physical groups
if useRegions:
options["dm_plex_gmsh_use_regions"] = None
else:
options.delValue("dm_plex_gmsh_use_regions")
# Marking the vertices may be necessary to constrain isolated points
# but it means that the labels will have a mix of points, and edges / faces
if markVertices:
options.setValue("dm_plex_gmsh_mark_vertices", True)
else:
options.delValue("dm_plex_gmsh_mark_vertices")
# this process is more efficient done on the root process and then distributed
# we do this by saving the mesh as h5 which is more flexible to re-use later
if uw.mpi.rank == 0:
plex_0 = PETSc.DMPlex().createFromFile(
filename, interpolate=True, comm=PETSc.COMM_SELF
)
plex_0.setName("uw_mesh")
plex_0.markBoundaryFaces("All_Boundaries", 1001)
viewer = PETSc.ViewerHDF5().create(filename + ".h5", "w", comm=PETSc.COMM_SELF)
viewer(plex_0)
viewer.destroy()
# ## Now add some metadata to the mesh (not sure how to do this with the Viewer)
# import h5py, json
# f = h5py.File('filename + ".h5",'r+')
# boundaries_dict = {i.name: i.value for i in cs_mesh.boundaries}
# string_repr = json.dumps(boundaries_dict)
# g = f.create_group("metadata")
# g.attrs["boundaries"] = string_repr
# f.close()
# Now we have an h5 file and we can hand this to _from_plexh5
return _from_plexh5(filename + ".h5", comm, return_sf=True)
@timing.routine_timer_decorator
def _from_plexh5(
filename,
comm=None,
return_sf=False,
):
"""Read a dmplex .h5 file from `filename` provided.
comm: Optional communicator to build the mesh on (defaults to
COMM_WORLD).
"""
if comm == None:
comm = PETSc.COMM_WORLD
viewer = PETSc.ViewerHDF5().create(filename, "r", comm=comm)
# h5plex = PETSc.DMPlex().createFromFile(filename, comm=comm)
h5plex = PETSc.DMPlex().create(comm=comm)
sf0 = h5plex.topologyLoad(viewer)
h5plex.coordinatesLoad(viewer, sf0)
h5plex.labelsLoad(viewer, sf0)
# Do this as well
h5plex.setName("uw_mesh")
h5plex.markBoundaryFaces("All_Boundaries", 1001)
if not return_sf:
return h5plex
else:
return sf0, h5plex
class Mesh(Stateful, uw_object):
r"""
Mesh class for uw - documentation needed
"""
mesh_instances = 0
@timing.routine_timer_decorator
def __init__(
self,
plex_or_meshfile,
degree=1,
simplex=True,
coordinate_system_type=None,
qdegree=2,
markVertices=None,
useRegions=None,
useMultipleTags=None,
filename=None,
refinement=None,
refinement_callback=None,
return_coords_to_bounds=None,
boundaries=None,
boundary_normals=None,
name=None,
verbose=False,
*args,
**kwargs,
):
self.instance = Mesh.mesh_instances
Mesh.mesh_instances += 1
comm = PETSc.COMM_WORLD
if isinstance(plex_or_meshfile, PETSc.DMPlex):
if verbose and uw.mpi.rank == 0:
print(f"Constructing UW mesh from DMPlex object", flush=True)
name = "plexmesh"
self.dm = plex_or_meshfile
self.sf0 = None # Should we build one ?
else:
comm = kwargs.get("comm", PETSc.COMM_WORLD)
name = plex_or_meshfile
basename, ext = os.path.splitext(plex_or_meshfile)
# Note: should be able to handle a .geo as well on this pathway
if ext.lower() == ".msh":
if verbose and uw.mpi.rank == 0:
print(
f"Constructing UW mesh from gmsh {plex_or_meshfile}", flush=True
)
self.sf0, self.dm = _from_gmsh(
plex_or_meshfile,
comm,
markVertices=markVertices,
useRegions=useRegions,
useMultipleTags=useMultipleTags,
)
elif ext.lower() == ".h5":
if verbose and uw.mpi.rank == 0:
print(
f"Constructing UW mesh from DMPlex h5 file {plex_or_meshfile}",
flush=True,
)
self.sf0, self.dm = _from_plexh5(
plex_or_meshfile, PETSc.COMM_WORLD, return_sf=True
)
## We can check if there is boundary metadata in the h5 file and we
## should use it if it is present.
import h5py, json
f = h5py.File(plex_or_meshfile, "r")
# boundaries_dict = {i.name: i.value for i in cs_mesh.boundaries}
# string_repr = json.dumps(boundaries_dict)
try:
json_str = f["metadata"].attrs["boundaries"]
bdr_dict = json.loads(json_str)
boundaries = Enum("Boundaries", bdr_dict)
except KeyError:
pass
try:
json_str = f["metadata"].attrs["coordinate_system_type"]
coord_type_dict = json.loads(json_str)
coordinate_system_type = uw.discretisation.CoordinateSystemType(
coord_type_dict["value"]
)
except KeyError:
pass
f.close()
else:
raise RuntimeError(
"Mesh file %s has unknown format '%s'."
% (plex_or_meshfile, ext[1:])
)
## Patch up the boundaries to include the additional
## definitions that we do / might need. Note: the
## extend_enum decorator will replace existing members with
## the new ones.
if boundaries is None:
class replacement_boundaries(Enum):
Null_Boundary = 666
All_Boundaries = 1001
boundaries = replacement_boundaries
else:
@extend_enum([boundaries])
class replacement_boundaries(Enum):
Null_Boundary = 666
All_Boundaries = 1001
boundaries = replacement_boundaries
self.filename = filename
self.boundaries = boundaries
self.boundary_normals = boundary_normals
# options.delValue("dm_plex_gmsh_mark_vertices")
# options.delValue("dm_plex_gmsh_multiple_tags")
# options.delValue("dm_plex_gmsh_use_regions")
self.dm.setFromOptions()
# uw.adaptivity._dm_stack_bcs(self.dm, self.boundaries, "UW_Boundaries")
all_edges_label_dm = self.dm.getLabel("depth")
if all_edges_label_dm:
all_edges_IS_dm = all_edges_label_dm.getStratumIS(0)
# all_edges_IS_dm.view()
self.dm.createLabel("Null_Boundary")
all_edges_label = self.dm.getLabel("Null_Boundary")
if all_edges_label and all_edges_IS_dm:
all_edges_label.setStratumIS(
boundaries.Null_Boundary.value, all_edges_IS_dm
)
## --- UW_Boundaries label
if self.boundaries is not None:
self.dm.removeLabel("UW_Boundaries")
uw.mpi.barrier()
self.dm.createLabel("UW_Boundaries")
stacked_bc_label = self.dm.getLabel("UW_Boundaries")
for b in self.boundaries:
bc_label_name = b.name
label = self.dm.getLabel(bc_label_name)
if label:
label_is = label.getStratumIS(b.value)
# Load this up on the stacked BC label
if label_is:
stacked_bc_label.setStratumIS(b.value, label_is)
uw.mpi.barrier()
## ---
self.refinement_callback = refinement_callback
self.name = name
self.sf1 = None
self.return_coords_to_bounds = return_coords_to_bounds
## This is where we can refine the dm if required, and rebuild / redistribute
if verbose and uw.mpi.rank == 0:
print(
f"Mesh refinement levels: {refinement}",
flush=True,
)
uw.mpi.barrier()
if not refinement is None and refinement > 0:
self.dm.setRefinementUniform()
if not self.dm.isDistributed():
self.dm.distribute()
# self.dm_hierarchy = self.dm.refineHierarchy(refinement)
# This is preferable to the refineHierarchy call
# because we can repair the refined mesh at each
# step along the way
self.dm_hierarchy = [self.dm]
for i in range(refinement):
dm_refined = self.dm_hierarchy[i].refine()
dm_refined.setCoarseDM(self.dm_hierarchy[i])
if callable(refinement_callback):
refinement_callback(dm_refined)
self.dm_hierarchy.append(dm_refined)
# self.dm_hierarchy = [self.dm] + self.dm_hierarchy
self.dm_h = self.dm_hierarchy[-1]
self.dm_h.setName("uw_hierarchical_dm")
if callable(refinement_callback):
for dm in self.dm_hierarchy:
refinement_callback(dm)
# Single level equivalent dm (needed for aux vars ?? Check this - LM)
self.dm = self.dm_h.clone()
else:
if not self.dm.isDistributed():
self.dm.distribute()
self.dm_hierarchy = [self.dm]
self.dm_h = self.dm.clone()
# This will be done anyway - the mesh maybe in a
# partially adapted state
if self.sf1 and self.sf0:
self.sf = self.sf0.compose(self.sf1)
else:
self.sf = self.sf0 # could be None !
if self.name is None:
self.name = "mesh"
self.dm.setName("uw_mesh")
else:
self.dm.setName(f"uw_{self.name}")
# Set sympy constructs. First a generic, symbolic, Cartesian coordinate system
# A unique set of vectors / names for each mesh instance
#
self.CoordinateSystemType = coordinate_system_type
from sympy.vector import CoordSys3D
self._N = CoordSys3D(f"N")
# Tidy some of this printing without changing the
# underlying vector names (as these are part of the code generation system)
self._N.x._latex_form = r"\mathrm{\xi_0}"
self._N.y._latex_form = r"\mathrm{\xi_1}"
self._N.z._latex_form = r"\mathrm{\xi_2}"
self._N.i._latex_form = r"\mathbf{\hat{\mathbf{e}}_0}"
self._N.j._latex_form = r"\mathbf{\hat{\mathbf{e}}_1}"
self._N.k._latex_form = r"\mathbf{\hat{\mathbf{e}}_2}"
self._Gamma = CoordSys3D(r"\Gamma")
self._Gamma.x._latex_form = r"\Gamma_x"
self._Gamma.y._latex_form = r"\Gamma_y"
self._Gamma.z._latex_form = r"\Gamma_z"
# Now add the appropriate coordinate system for the mesh's natural geometry
# This step will usually over-write the defaults we just defined
self._CoordinateSystem = CoordinateSystem(self, coordinate_system_type)
# This was in the _jit extension but ... if
# not here then the tests fail sometimes (caching ?)
self._N.x._ccodestr = "petsc_x[0]"
self._N.y._ccodestr = "petsc_x[1]"
self._N.z._ccodestr = "petsc_x[2]"
# Surface integrals also have normal vector information as petsc_n
self._Gamma.x._ccodestr = "petsc_n[0]"
self._Gamma.y._ccodestr = "petsc_n[1]"
self._Gamma.z._ccodestr = "petsc_n[2]"
try:
self.isSimplex = self.dm.isSimplex()
except:
self.isSimplex = simplex
self._vars = {}
self._block_vars = {}
# a list of equation systems that will
# need to be rebuilt if the mesh coordinates change
self._equation_systems_register = []
self._evaluation_hash = None
self._evaluation_interpolated_results = None
self._accessed = False
self._quadrature = False
self._stale_lvec = True
self._lvec = None
self.petsc_fe = None
self.degree = degree
self.qdegree = qdegree
self.nuke_coords_and_rebuild()
if verbose and uw.mpi.rank == 0:
print(
f"Populating mesh coordinates {coordinate_system_type}",
flush=True,
)
## Coordinate System
if (
self.CoordinateSystem.coordinate_type
== CoordinateSystemType.CYLINDRICAL2D_NATIVE
or self.CoordinateSystem.coordinate_type
== CoordinateSystemType.CYLINDRICAL3D_NATIVE
):
self.vector = uw.maths.vector_calculus_cylindrical(
mesh=self,
)
elif (
self.CoordinateSystem.coordinate_type
== CoordinateSystemType.SPHERICAL_NATIVE
):
self.vector = uw.maths.vector_calculus_spherical(
mesh=self,
) ## Not yet complete or tested
elif (
self.CoordinateSystem.coordinate_type
== CoordinateSystemType.SPHERE_SURFACE_NATIVE
):
self.vector = uw.maths.vector_calculus_spherical_surface2D_lonlat(
mesh=self,
)
else:
self.vector = uw.maths.vector_calculus(mesh=self)
super().__init__()
@property
def dim(self) -> int:
"""
The mesh dimensionality.
"""
return self.dm.getDimension()
@property
def cdim(self) -> int:
"""
The mesh dimensionality.
"""
return self.dm.getCoordinateDim()
def view(self):
import numpy as np
if uw.mpi.rank == 0:
print(f"\n")
print(f"Mesh # {self.instance}: {self.name}\n")
if len(self.vars) > 0:
print(f"| Variable Name | component | degree | type |")
print(f"| ---------------------------------------------------------- |")
for vname in self.vars.keys():
v = self.vars[vname]
print(
f"| {v.clean_name:<20}|{v.num_components:^10} |{v.degree:^7} | {v.vtype.name:^15} |"
)
print(f"| ---------------------------------------------------------- |")
print("\n", flush=True)
else:
print(f"No variables are defined on the mesh\n", flush=True)
## Boundary information
if uw.mpi.rank == 0:
if len(self.boundaries) > 0:
print(
f"| Boundary Name | ID | Min Size | Max Size |",
flush=True,
)
print(
f"| ------------------------------------------------------ |",
flush=True,
)
else:
print(f"No boundary labels are defined on the mesh\n", flush=True)
for bd in self.boundaries:
l = self.dm.getLabel(bd.name)
if l:
i = l.getStratumSize(bd.value)
else:
i = 0
ii = uw.utilities.gather_data(np.array([i]), dtype="int")
if uw.mpi.rank == 0:
print(
f"| {bd.name:<20} | {bd.value:<5} | {ii.min():<8} | {ii.max():<8} |",
flush=True,
)
# ## PETSc marked boundaries:
# l = self.dm.getLabel("All_Boundaries")
# if l:
# i = l.getStratumSize(1001)
# else:
# i = 0
ii = uw.utilities.gather_data(np.array([i]), dtype="int")
if uw.mpi.rank == 0:
print(
f"| {'All_Boundaries':<20} | 1001 | {ii.min():<8} | {ii.max():<8} |",
flush=True,
)
## UW_Boundaries:
l = self.dm.getLabel("UW_Boundaries")
i = 0
if l:
for bd in self.boundaries:
i += l.getStratumSize(bd.value)
ii = uw.utilities.gather_data(np.array([i]), dtype="int")
if uw.mpi.rank == 0:
print(
f"| {'UW_Boundaries':<20} | -- | {ii.min():<8} | {ii.max():<8} |",
flush=True,
)
if uw.mpi.rank == 0:
print(f"| ------------------------------------------------------ |")
print("\n", flush=True)
## Information on the mesh DM
self.dm.view()
def view_parallel(self):
"""
returns the break down of boundary labels from each processor
"""
import numpy as np
if uw.mpi.rank == 0:
print(f"\n")
print(f"Mesh # {self.instance}: {self.name}\n")
if len(self.vars) > 0:
print(f"| Variable Name | component | degree | type |")
print(f"| ---------------------------------------------------------- |")
for vname in self.vars.keys():
v = self.vars[vname]
print(
f"| {v.clean_name:<20}|{v.num_components:^10} |{v.degree:^7} | {v.vtype.name:^15} |"
)
print(f"| ---------------------------------------------------------- |")
print("\n", flush=True)
else:
print(f"No variables are defined on the mesh\n", flush=True)
## Boundary information on each proc
if uw.mpi.rank == 0:
if len(self.boundaries) > 0:
print(f"| Boundary Name | ID | Size | Proc ID |")
print(f"| ------------------------------------------------------ |")
else:
print(f"No boundary labels are defined on the mesh\n")
### goes through each processor and gets the label size
with uw.mpi.call_pattern(pattern="sequential"):
for bd in self.boundaries:
l = self.dm.getLabel(bd.name)
if l:
i = l.getStratumSize(bd.value)
else:
i = 0
print(
f"| {bd.name:<20} | {bd.value:<5} | {i:<8} | {uw.mpi.rank:<8} |"
)
uw.mpi.barrier()
if uw.mpi.rank == 0:
print(f"| ------------------------------------------------------ |")
print("\n", flush=True)
## Information on the mesh DM
# self.dm.view()
# This only works for local - we can't access global information'
# and so this is not a suitable function for use during advection
#
# def _return_coords_to_bounds(self, coords, meshVar=None):
# """
# Restore the provided coordinates to the interior of the domain.
# The default behaviour is to find the nearest node in the kdtree to each
# coordinate and use that value. If a meshVar is provided, we can use the nearest node
# for that discretisation instead.
# This can be over-ridden for specific meshes
# (e.g. periodic) where a more appropriate choice is available.
# """
# import numpy as np
# if meshVar is None:
# target_coords = self.data
# else:
# target_coords = meshVar.coords
# ## Find which coords are invalid
# invalid = self.get_closest_local_cells(coords) == -1
# if np.count_nonzero(invalid) == 0:
# return coords
# print(f"{uw.mpi.rank}: Number of invalid coords {np.count_nonzero(invalid)}")
# kdt = uw.kdtree.KDTree(target_coords)
# idx , _ , _ = kdt.find_closest_point(coords[invalid])
# valid_coords = coords.copy()
# valid_coords[invalid] = target_coords[idx]
# return valid_coords
def clone_dm_hierarchy(self):
"""
Clone the dm hierarchy on the mesh
"""
dm_hierarchy = self.dm_hierarchy
new_dm_hierarchy = []
for dm in dm_hierarchy:
new_dm_hierarchy.append(dm.clone())
for i, dm in enumerate(new_dm_hierarchy[:-1]):
new_dm_hierarchy[i + 1].setCoarseDM(new_dm_hierarchy[i])
return new_dm_hierarchy
def nuke_coords_and_rebuild(self):
# This is a reversion to the old version (3.15 compatible which seems to work in 3.16 too)
#
#
self.dm.clearDS()
self.dm.createDS()
self._coord_array = {}
# let's go ahead and do an initial projection from linear (the default)
# to linear. this really is a nothing operation, but a
# side effect of this operation is that coordinate DM DMField is
# converted to the required `PetscFE` type. this may become necessary
# later where we call the interpolation routines to project from the linear
# mesh coordinates to other mesh coordinates.
options = PETSc.Options()
options.setValue(
f"meshproj_{self.mesh_instances}_petscspace_degree", self.degree
)
self.petsc_fe = PETSc.FE().createDefault(
self.dim,
self.cdim,
self.isSimplex,
self.qdegree,
f"meshproj_{self.mesh_instances}_",
)
if (
PETSc.Sys.getVersion() <= (3, 20, 5)
and PETSc.Sys.getVersionInfo()["release"] == True
):
self.dm.projectCoordinates(self.petsc_fe)
else:
self.dm.setCoordinateDisc(disc=self.petsc_fe, project=False)
# now set copy of this array into dictionary
arr = self.dm.getCoordinatesLocal().array
key = (
self.isSimplex,
self.degree,
True,
) # True here assumes continuous basis for coordinates ...
self._coord_array[key] = arr.reshape(-1, self.cdim).copy()
# invalidate the cell-search k-d tree and the mesh centroid data / rebuild
self._index = None
self._build_kd_tree_index()
(
self._min_size,
self._radii,
self._centroids,
self._search_lengths,
) = self._get_mesh_sizes()
self.dm.copyDS(self.dm_hierarchy[-1])
return
@timing.routine_timer_decorator
def update_lvec(self):
"""
This method creates and/or updates the mesh variable local vector.
If the local vector is already up to date, this method will do nothing.
"""
if self._stale_lvec:
if not self._lvec:
self.dm.clearDS()
self.dm.createDS()
# create the local vector (memory chunk) and attach to original dm
self._lvec = self.dm.createLocalVec()
# push avar arrays into the parent dm array
a_global = self.dm.getGlobalVec()
# The field decomposition seems to fail if coarse DMs are present
names, isets, dms = self.dm.createFieldDecomposition()
with self.access():
# traverse subdms, taking user generated data in the subdm
# local vec, pushing it into a global sub vec
for var, subiset, subdm in zip(self.vars.values(), isets, dms):
lvec = var.vec
subvec = a_global.getSubVector(subiset)
subdm.localToGlobal(lvec, subvec, addv=False)
a_global.restoreSubVector(subiset, subvec)
for iset in isets:
iset.destroy()
for dm in dms:
dm.destroy()
self.dm.globalToLocal(a_global, self._lvec)
self.dm.restoreGlobalVec(a_global)
self._stale_lvec = False
@property
def lvec(self) -> PETSc.Vec:
"""
Returns a local Petsc vector containing the flattened array
of all the mesh variables.
"""
if self._stale_lvec:
raise RuntimeError(
"Mesh `lvec` needs to be updated using the update_lvec()` method."
)
return self._lvec
def __del__(self):
if hasattr(self, "_lvec") and self._lvec:
self._lvec.destroy()
def deform_mesh(self, new_coords: numpy.ndarray, verbose=False):
"""
This method will update the mesh coordinates and reset any cached coordinates in
the mesh and in equation systems that are registered on the mesh.
The coord array that is passed in should match the shape of self.data
"""
coord_vec = self.dm.getCoordinatesLocal()
coords = coord_vec.array.reshape(-1, self.cdim)
coords[...] = new_coords[...]
self.dm.setCoordinatesLocal(coord_vec)
self.nuke_coords_and_rebuild()
# This should not be necessary any more as we now check the
# coordinates on the DM to see if they have changed (and we rebuild the
# discretisation as needed)
#
# for eq_system in self._equation_systems_register:
# eq_system._rebuild_after_mesh_update(verbose)
return
def access(self, *writeable_vars: "MeshVariable"):
"""
This context manager makes the underlying mesh variables data available to
the user. The data should be accessed via the variables `data` handle.
As default, all data is read-only. To enable writeable data, the user should
specify which variable they wish to modify.
Parameters
----------
writeable_vars
The variables for which data write access is required.
Example
-------
>>> import underworld3 as uw
>>> someMesh = uw.discretisation.FeMesh_Cartesian()
>>> with someMesh.deform_mesh():
... someMesh.data[0] = [0.1,0.1]
>>> someMesh.data[0]
array([ 0.1, 0.1])
"""
import time
timing._incrementDepth()
stime = time.time()
if writeable_vars is not None:
self._evaluation_hash = None
self._evaluation_interpolated_results = None
self._accessed = True
deaccess_list = []
for var in self.vars.values():
# if already accessed within higher level context manager, continue.
if var._is_accessed == True:
continue
# set flag so variable status can be known elsewhere
var._is_accessed = True
# add to de-access list to rewind this later
deaccess_list.append(var)
# create & set vec
var._set_vec(available=True)
# grab numpy object, setting read only if necessary
var._data = var.vec.array.reshape(-1, var.num_components)
if var not in writeable_vars:
var._old_data_flag = var._data.flags.writeable
var._data.flags.writeable = False
else:
# increment variable state
var._increment()
# make view for each var component
for i in range(0, var.shape[0]):
for j in range(0, var.shape[1]):
# var._data_ij[i, j] = var.data[:, var._data_layout(i, j)]
var._data_container[i, j] = var._data_container[i, j]._replace(
data=var.data[:, var._data_layout(i, j)],
)
class exit_manager:
def __init__(self, mesh):
self.mesh = mesh
def __enter__(self):
pass
def __exit__(self, *args):
for var in self.mesh.vars.values():
# only de-access variables we have set access for.
if var not in deaccess_list:
continue
# set this back, although possibly not required.
if var not in writeable_vars:
var._data.flags.writeable = var._old_data_flag
# perform sync for any modified vars.
if var in writeable_vars:
indexset, subdm = self.mesh.dm.createSubDM(var.field_id)
# sync ghost values
subdm.localToGlobal(var.vec, var._gvec, addv=False)
subdm.globalToLocal(var._gvec, var.vec, addv=False)
indexset.destroy()
subdm.destroy()
self.mesh._stale_lvec = True
var._data = None
var._set_vec(available=False)
var._is_accessed = False
for i in range(0, var.shape[0]):
for j in range(0, var.shape[1]):
var._data_container[i, j] = var._data_container[
i, j
]._replace(
data=f"MeshVariable[...].data is only available within mesh.access() context",
)
timing._decrementDepth()
timing.log_result(time.time() - stime, "Mesh.access", 1)
return exit_manager(self)
@property
def N(self) -> sympy.vector.CoordSys3D:
"""
The mesh coordinate system.
"""
return self._N
@property
def Gamma_N(self) -> sympy.vector.CoordSys3D:
"""
The mesh coordinate system.
"""
return self._Gamma
@property
def Gamma(self) -> sympy.vector.CoordSys3D:
"""
The mesh coordinate system.
"""
return sympy.Matrix(self._Gamma.base_scalars()[0 : self.cdim]).T
@property
def X(self) -> sympy.Matrix:
return self._CoordinateSystem.X
@property
def CoordinateSystem(self) -> CoordinateSystem:
return self._CoordinateSystem
@property
def r(self) -> Tuple[sympy.vector.BaseScalar]:
"""
The tuple of base scalar objects (N.x,N.y,N.z) for the mesh.
"""
return self._N.base_scalars()[0 : self.cdim]
@property
def rvec(self) -> sympy.vector.Vector: