-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathmesh.py
More file actions
3128 lines (2606 loc) · 104 KB
/
Copy pathmesh.py
File metadata and controls
3128 lines (2606 loc) · 104 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 __future__ import annotations
import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterable, Sequence, Mapping
from functools import wraps
from math import pi, sqrt, atan2
from numbers import Integral, Real
from pathlib import Path
from typing import Protocol
import h5py
import lxml.etree as ET
import numpy as np
from pathlib import Path
import openmc
import openmc.checkvalue as cv
from openmc.checkvalue import PathLike
from openmc.utility_funcs import change_directory
from .bounding_box import BoundingBox
from ._xml import get_elem_list, get_text
from .mixin import IDManagerMixin
from .surface import _BOUNDARY_TYPES
from .utility_funcs import input_path
class MeshMaterialVolumes(Mapping):
"""Results from a material volume in mesh calculation.
This class provides multiple ways of accessing information about material
volumes in individual mesh elements. First, the class behaves like a
dictionary that maps material IDs to an array of volumes equal in size to
the number of mesh elements. Second, the class provides a :meth:`by_element`
method that gives all the material volumes for a specific mesh element.
.. versionadded:: 0.15.1
Parameters
----------
materials : numpy.ndarray
Array of shape (elements, max_materials) storing material IDs
volumes : numpy.ndarray
Array of shape (elements, max_materials) storing material volumes
bboxes : numpy.ndarray, optional
Array of shape (elements, max_materials, 6) storing axis-aligned
bounding boxes for each (element, material) combination with ordering
(xmin, ymin, zmin, xmax, ymax, zmax). Bounding boxes enclose the
ray-estimator prisms used to compute volumes.
See Also
--------
openmc.MeshBase.material_volumes
Examples
--------
If you want to get the volume of a specific material in every mesh element,
index the object with the material ID:
>>> volumes = mesh.material_volumes(...)
>>> volumes
{1: <32121 nonzero volumes>
2: <338186 nonzero volumes>
3: <49120 nonzero volumes>}
If you want the volume of all materials in a specific mesh element, use the
:meth:`by_element` method:
>>> volumes = mesh.material_volumes(...)
>>> volumes.by_element(42)
[(2, 31.87963824195591), (1, 6.129949130817542)]
"""
def __init__(
self,
materials: np.ndarray,
volumes: np.ndarray,
bboxes: np.ndarray | None = None
):
self._materials = materials
self._volumes = volumes
self._bboxes = bboxes
if self._bboxes is not None:
if self._bboxes.shape[:2] != self._materials.shape:
raise ValueError(
'bboxes must have shape (elements, max_materials, 6) '
'matching materials/volumes.'
)
if self._bboxes.shape[2] != 6:
raise ValueError(
'bboxes must have shape (elements, max_materials, 6).'
)
@property
def has_bounding_boxes(self) -> bool:
return self._bboxes is not None
@property
def num_elements(self) -> int:
return self._volumes.shape[0]
def __iter__(self):
for mat in np.unique(self._materials):
if mat > 0:
yield mat
def __len__(self) -> int:
return (np.unique(self._materials) > 0).sum()
def __repr__(self) -> str:
ids, counts = np.unique(self._materials, return_counts=True)
return '{' + '\n '.join(
f'{id}: <{count} nonzero volumes>' for id, count in zip(ids, counts) if id > 0) + '}'
def __getitem__(self, material_id: int) -> np.ndarray:
volumes = np.zeros(self.num_elements)
for i in range(self._volumes.shape[1]):
indices = (self._materials[:, i] == material_id)
volumes[indices] = self._volumes[indices, i]
return volumes
def by_element(
self,
index_elem: int,
include_bboxes: bool = False
) -> list[tuple[int | None, float] | tuple[int | None, float, BoundingBox | None]]:
"""Get a list of volumes for each material within a specific element.
Parameters
----------
index_elem : int
Mesh element index
Returns
-------
list of tuple
If ``include_bboxes`` is False (default), returns tuples of
(material ID, volume). If ``include_bboxes`` is True, returns
tuples of (material ID, volume, bounding box).
"""
table_size = self._volumes.shape[1]
if include_bboxes and self._bboxes is None:
raise ValueError('Bounding boxes were not computed for this object.')
results = []
for i in range(table_size):
m = self._materials[index_elem, i]
if m == -2:
continue
mat_id = m if m > -1 else None
vol = self._volumes[index_elem, i]
if include_bboxes:
vals = self._bboxes[index_elem, i]
bbox = BoundingBox(vals[0:3], vals[3:6])
results.append((mat_id, vol, bbox))
else:
results.append((mat_id, vol))
return results
def save(self, filename: PathLike):
"""Save material volumes to a .npz file.
Parameters
----------
filename : path-like
Filename where data will be saved
"""
kwargs = {'materials': self._materials, 'volumes': self._volumes}
if self._bboxes is not None:
kwargs['bboxes'] = self._bboxes
np.savez_compressed(filename, **kwargs)
@classmethod
def from_npz(cls, filename: PathLike) -> MeshMaterialVolumes:
"""Generate material volumes from a .npz file
Parameters
----------
filename : path-like
File where data will be read from
"""
filedata = np.load(filename)
bboxes = filedata['bboxes'] if 'bboxes' in filedata.files else None
return cls(filedata['materials'], filedata['volumes'], bboxes)
class MeshBase(IDManagerMixin, ABC):
"""A mesh that partitions geometry for tallying purposes.
Parameters
----------
mesh_id : int
Unique identifier for the mesh
name : str
Name of the mesh
Attributes
----------
id : int
Unique identifier for the mesh
name : str
Name of the mesh
lower_left : Iterable of float
The lower-left coordinates
upper_right : Iterable of float
The upper-right coordinates
bounding_box : openmc.BoundingBox
Axis-aligned bounding box of the mesh as defined by the upper-right and
lower-left coordinates.
indices : Iterable of tuple
An iterable of mesh indices for each mesh element, e.g. [(1, 1, 1), (2, 1, 1), ...]
n_elements : int
Number of elements in the mesh
"""
next_id = 1
used_ids = set()
def __init__(self, mesh_id: int | None = None, name: str = ''):
# Initialize Mesh class attributes
self.id = mesh_id
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name: str):
if name is not None:
cv.check_type(f'name for mesh ID="{self._id}"', name, str)
self._name = name
else:
self._name = ''
@property
@abstractmethod
def lower_left(self):
pass
@property
@abstractmethod
def upper_right(self):
pass
@property
def bounding_box(self) -> openmc.BoundingBox:
return openmc.BoundingBox(self.lower_left, self.upper_right)
@property
@abstractmethod
def indices(self):
pass
@property
@abstractmethod
def n_elements(self):
pass
def __repr__(self):
string = type(self).__name__ + '\n'
string += '{0: <16}{1}{2}\n'.format('\tID', '=\t', self._id)
string += '{0: <16}{1}{2}\n'.format('\tName', '=\t', self._name)
return string
def _volume_dim_check(self):
if self.n_dimension != 3 or \
any([d == 0 for d in self.dimension]):
raise RuntimeError(f'Mesh {self.id} is not 3D. '
'Volumes cannot be provided.')
@classmethod
def from_hdf5(cls, group: h5py.Group):
"""Create mesh from HDF5 group
Parameters
----------
group : h5py.Group
Group in HDF5 file
Returns
-------
openmc.MeshBase
Instance of a MeshBase subclass
"""
mesh_type = 'regular' if 'type' not in group.keys() else group['type'][()].decode()
mesh_id = int(group.name.split('/')[-1].lstrip('mesh '))
mesh_name = '' if not 'name' in group else group['name'][()].decode()
if mesh_type == 'regular':
return RegularMesh.from_hdf5(group, mesh_id, mesh_name)
elif mesh_type == 'rectilinear':
return RectilinearMesh.from_hdf5(group, mesh_id, mesh_name)
elif mesh_type == 'cylindrical':
return CylindricalMesh.from_hdf5(group, mesh_id, mesh_name)
elif mesh_type == 'spherical':
return SphericalMesh.from_hdf5(group, mesh_id, mesh_name)
elif mesh_type == 'unstructured':
return UnstructuredMesh.from_hdf5(group, mesh_id, mesh_name)
else:
raise ValueError('Unrecognized mesh type: "' + mesh_type + '"')
def to_xml_element(self):
"""Return XML representation of the mesh
Returns
-------
element : lxml.etree._Element
XML element containing mesh data
"""
elem = ET.Element("mesh")
elem.set("id", str(self._id))
if self.name:
elem.set("name", self.name)
return elem
@classmethod
def from_xml_element(cls, elem: ET.Element):
"""Generates a mesh from an XML element
Parameters
----------
elem : lxml.etree._Element
XML element
Returns
-------
openmc.MeshBase
an openmc mesh object
"""
mesh_type = get_text(elem, 'type')
if mesh_type == 'regular' or mesh_type is None:
mesh = RegularMesh.from_xml_element(elem)
elif mesh_type == 'rectilinear':
mesh = RectilinearMesh.from_xml_element(elem)
elif mesh_type == 'cylindrical':
mesh = CylindricalMesh.from_xml_element(elem)
elif mesh_type == 'spherical':
mesh = SphericalMesh.from_xml_element(elem)
elif mesh_type == 'unstructured':
mesh = UnstructuredMesh.from_xml_element(elem)
else:
raise ValueError(f'Unrecognized mesh type "{mesh_type}" found.')
mesh.name = get_text(elem, 'name', default='')
return mesh
def get_homogenized_materials(
self,
model: openmc.Model,
n_samples: int | tuple[int, int, int] = 10_000,
include_void: bool = True,
material_volumes: MeshMaterialVolumes | None = None,
**kwargs
) -> list[openmc.Material]:
"""Generate homogenized materials over each element in a mesh.
.. versionadded:: 0.15.0
Parameters
----------
model : openmc.Model
Model containing materials to be homogenized and the associated
geometry.
n_samples : int or 2-tuple of int
Total number of rays to sample. The number of rays in each direction
is determined by the aspect ratio of the mesh bounding box. When
specified as a 3-tuple, it is interpreted as the number of rays in
the x, y, and z dimensions.
include_void : bool, optional
Whether homogenization should include voids.
material_volumes : MeshMaterialVolumes, optional
Previously computed mesh material volumes to use for homogenization.
If not provided, they will be computed by calling
:meth:`material_volumes`.
**kwargs
Keyword-arguments passed to :meth:`material_volumes`.
Returns
-------
list of openmc.Material
Homogenized material in each mesh element
"""
if material_volumes is None:
vols = self.material_volumes(model, n_samples, **kwargs)
else:
vols = material_volumes
mat_volume_by_element = [vols.by_element(i) for i in range(vols.num_elements)]
# Get dictionary of all materials
materials = model._get_all_materials()
# Create homogenized material for each element
homogenized_materials = []
for mat_volume_list in mat_volume_by_element:
material_ids, volumes = [list(x) for x in zip(*mat_volume_list)]
total_volume = sum(volumes)
# Check for void material and remove
try:
index_void = material_ids.index(None)
except ValueError:
pass
else:
material_ids.pop(index_void)
volumes.pop(index_void)
# If void should be excluded, adjust total volume
if not include_void:
total_volume = sum(volumes)
# Compute volume fractions
volume_fracs = np.array(volumes) / total_volume
# Get list of materials and mix 'em up!
mats = [materials[uid] for uid in material_ids]
homogenized_mat = openmc.Material.mix_materials(
mats, volume_fracs, 'vo'
)
homogenized_mat.volume = total_volume
homogenized_materials.append(homogenized_mat)
return homogenized_materials
def material_volumes(
self,
model: openmc.Model,
n_samples: int | tuple[int, int, int] = 10_000,
max_materials: int = 4,
bounding_boxes: bool = False,
**kwargs
) -> MeshMaterialVolumes:
"""Determine volume of materials in each mesh element.
This method works by raytracing repeatedly through the mesh to count the
estimated volume of each material in all mesh elements. Three sets of
rays are used: one set parallel to the x-axis, one parallel to the
y-axis, and one parallel to the z-axis.
.. versionadded:: 0.15.1
Parameters
----------
model : openmc.Model
Model containing materials.
n_samples : int or 3-tuple of int
Total number of rays to sample. The number of rays in each direction
is determined by the aspect ratio of the mesh bounding box. When
specified as a 3-tuple, it is interpreted as the number of rays in
the x, y, and z dimensions.
max_materials : int, optional
Estimated maximum number of materials in any given mesh element.
bounding_boxes : bool, optional
Whether to compute an axis-aligned bounding box for each
(mesh element, material) combination. When enabled, the bounding
box encloses the ray-estimator prisms used for the volume
estimation.
**kwargs : dict
Keyword arguments passed to :func:`openmc.lib.init`
Returns
-------
Dictionary-like object that maps material IDs to an array of volumes
equal in size to the number of mesh elements.
"""
import openmc.lib
# In order to get mesh into model, we temporarily replace the
# tallies with a single mesh tally using the current mesh
original_tallies = list(model.tallies)
new_tally = openmc.Tally()
new_tally.filters = [openmc.MeshFilter(self)]
new_tally.scores = ['flux']
model.tallies = [new_tally]
# Set default arguments
kwargs.setdefault('output', True)
if 'args' in kwargs:
kwargs['args'] = ['-c'] + kwargs['args']
kwargs.setdefault('args', ['-c'])
with openmc.lib.TemporarySession(model, **kwargs):
# Get mesh from single tally
mesh = openmc.lib.tallies[new_tally.id].filters[0].mesh
# Compute material volumes
volumes = mesh.material_volumes(
n_samples, max_materials, output=kwargs['output'],
bounding_boxes=bounding_boxes)
# Restore original tallies
model.tallies = original_tallies
return volumes
class StructuredMesh(MeshBase):
"""A base class for structured mesh functionality
Parameters
----------
mesh_id : int
Unique identifier for the mesh
name : str
Name of the mesh
Attributes
----------
id : int
Unique identifier for the mesh
name : str
Name of the mesh
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
@abstractmethod
def dimension(self):
pass
@property
@abstractmethod
def n_dimension(self):
pass
@property
@abstractmethod
def _grids(self):
pass
@property
def vertices(self):
"""Return coordinates of mesh vertices in Cartesian coordinates. Also
see :meth:`CylindricalMesh.vertices_cylindrical` and
:meth:`SphericalMesh.vertices_spherical` for coordinates in other coordinate
systems.
Returns
-------
vertices : numpy.ndarray
Returns a numpy.ndarray representing the coordinates of the mesh
vertices with a shape equal to (dim1 + 1, ..., dimn + 1, ndim). X, Y, Z values
can be unpacked with xx, yy, zz = np.rollaxis(mesh.vertices, -1).
"""
return self._generate_vertices(*self._grids)
@staticmethod
def _generate_vertices(i_grid, j_grid, k_grid):
"""Returns an array with shape (i_grid.size, j_grid.size, k_grid.size, 3)
containing the corner vertices of mesh elements.
"""
return np.stack(np.meshgrid(i_grid, j_grid, k_grid, indexing='ij'), axis=-1)
@staticmethod
def _generate_edge_midpoints(grids):
"""Generates the midpoints of mesh element edges for each dimension of the mesh.
Parameters
----------
grids : numpy.ndarray
The vertex grids along each dimension of the mesh.
Returns
-------
midpoint_grids : list of numpy.ndarray
The edge midpoints for the i, j, and k midpoints of each element in
i, j, k ordering. The shapes of the resulting grids are
[(ni-1, nj, nk, 3), (ni, nj-1, nk, 3), (ni, nj, nk-1, 3)]
"""
# generate a set of edge midpoints for each dimension
midpoint_grids = []
# generate the element edge midpoints in order s.t.
# the epxected element ordering is preserved with respect to the corner vertices
# each grid is comprised of the mid points for one dimension and the
# corner vertices of the other two
for dims in ((0, 1, 2), (1, 0, 2), (2, 0, 1)):
# compute the midpoints along the last dimension
midpoints = grids[dims[0]][:-1] + 0.5 * np.diff(grids[dims[0]])
coords = (midpoints, grids[dims[1]], grids[dims[2]])
i_grid, j_grid, k_grid = [coords[dims.index(i)] for i in range(3)]
# re-use the generate vertices method to create the full mesh grid
# transpose to get (i, j, k) ordering of the gridpoints
midpoint_grid = StructuredMesh._generate_vertices(i_grid, j_grid, k_grid)
midpoint_grids.append(midpoint_grid)
return midpoint_grids
@property
def midpoint_vertices(self):
"""Create vertices that lie on the midpoint of element edges
"""
# generate edge midpoints needed for curvilinear element definition
midpoint_vertices = self._generate_edge_midpoints(self._grids)
# convert each of the midpoint grids to cartesian coordinates
for vertices in midpoint_vertices:
self._convert_to_cartesian(vertices, self.origin)
return midpoint_vertices
@property
def centroids(self):
"""Return coordinates of mesh element centroids.
Returns
-------
centroids : numpy.ndarray
Returns a numpy.ndarray representing the mesh element centroid
coordinates with a shape equal to (dim1, ..., dimn, ndim). X,
Y, Z values can be unpacked with xx, yy, zz =
np.rollaxis(mesh.centroids, -1).
"""
ndim = self.n_dimension
# this line ensures that the vertices aren't adjusted by the origin or
# converted to the Cartesian system for cylindrical and spherical meshes
vertices = StructuredMesh.vertices.fget(self)
s0 = (slice(0, -1),)*ndim + (slice(None),)
s1 = (slice(1, None),)*ndim + (slice(None),)
return (vertices[s0] + vertices[s1]) / 2
@property
def n_elements(self):
return np.prod(self.dimension)
@property
def num_mesh_cells(self):
warnings.warn(
"The 'num_mesh_cells' attribute is deprecated and will be removed in a future version. "
"Use 'n_elements' instead.",
FutureWarning, stacklevel=2
)
return self.n_elements
def write_data_to_vtk(self,
filename: PathLike,
datasets: dict | None = None,
volume_normalization: bool = True,
curvilinear: bool = False):
"""Creates a VTK object of the mesh
Parameters
----------
filename : str
Name of the VTK file to write.
datasets : dict
Dictionary whose keys are the data labels and values are the data
sets. 1D datasets are expected to be extracted directly from
statepoint data without reordering/reshaping. Multidimensional
datasets are expected to have the same dimensions as the mesh itself
with structured indexing in "C" ordering. See the "expand_dims" flag
of :meth:`~openmc.Tally.get_reshaped_data` on reshaping tally data when using
:class:`~openmc.MeshFilter`'s.
volume_normalization : bool, optional
Whether or not to normalize the data by the volume of the mesh
elements.
curvilinear : bool
Whether or not to write curvilinear elements. Only applies to
``SphericalMesh`` and ``CylindricalMesh``.
Raises
------
ValueError
When the size of a dataset doesn't match the number of mesh cells
Returns
-------
vtk.StructuredGrid or vtk.UnstructuredGrid
a VTK grid object representing the mesh
Examples
--------
1D data from a tally with only a mesh filter and heating score:
# pass the tally mean property of shape (N, 1, 1) directly to this
# method; dimensions of size 1 will automatically removed
>>> heating = tally.mean
>>> mesh.write_data_to_vtk({'heating': heating})
Multidimensional data from a tally with only a mesh
# retrieve a data array with the mesh filter expanded into three
# dimensions, ijk; additional dimensions of size one will
# automatically be removed
>>> heating = tally.get_reshaped_data(expand_dims=True)
>>> mesh.write_data_to_vtk({'heating': heating})
"""
import vtk
from vtk.util import numpy_support as nps
# write linear elements using a structured grid
if not curvilinear or isinstance(self, (RegularMesh, RectilinearMesh)):
vtk_grid = self._create_vtk_structured_grid()
writer = vtk.vtkStructuredGridWriter()
# write curvilinear elements using an unstructured grid
else:
vtk_grid = self._create_vtk_unstructured_grid()
writer = vtk.vtkUnstructuredGridWriter()
if datasets is not None:
# maintain a list of the datasets as added to the VTK arrays to
# ensure they persist in memory until the file is written
datasets_out = []
for label, dataset in datasets.items():
dataset = self._reshape_vtk_dataset(dataset)
self._check_vtk_dataset(label, dataset)
# If the array data is 3D, assume is in C ordering and transpose
# before flattening to match the ordering expected by the VTK
# array based on the way mesh indices are ordered in the Python
# API
# TODO: update to "C" ordering throughout
if dataset.ndim == 3:
dataset = dataset.T.ravel()
datasets_out.append(dataset)
if volume_normalization:
dataset /= self.volumes.T.ravel()
dataset_array = vtk.vtkDoubleArray()
dataset_array.SetName(label)
dataset_array.SetArray(nps.numpy_to_vtk(dataset), dataset.size, True)
vtk_grid.GetCellData().AddArray(dataset_array)
writer.SetFileName(str(filename))
writer.SetInputData(vtk_grid)
writer.Write()
return vtk_grid
def _create_vtk_structured_grid(self):
"""Create a structured grid
Returns
-------
vtk.vtkStructuredGrid
a VTK structured grid object representing the mesh
"""
import vtk
from vtk.util import numpy_support as nps
vtkPts = vtk.vtkPoints()
vtkPts.SetData(nps.numpy_to_vtk(np.swapaxes(self.vertices, 0, 2).reshape(-1, 3), deep=True))
vtk_grid = vtk.vtkStructuredGrid()
vtk_grid.SetPoints(vtkPts)
vtk_grid.SetDimensions(*[dim + 1 for dim in self.dimension])
return vtk_grid
def _create_vtk_unstructured_grid(self):
"""Create an unstructured grid of curvilinear elements
representing the mesh
Returns
-------
vtk.vtkUnstructuredGrid
a VTK unstructured grid object representing the mesh
"""
import vtk
from vtk.util import numpy_support as nps
corner_vertices = np.swapaxes(self.vertices, 0, 2).reshape(-1, 3)
vtkPts = vtk.vtkPoints()
vtk_grid = vtk.vtkUnstructuredGrid()
vtk_grid.SetPoints(vtkPts)
# add corner vertices to the point set for the unstructured grid
# only insert unique points, we'll get their IDs in the point set to
# define element connectivity later
vtkPts.SetData(nps.numpy_to_vtk(np.unique(corner_vertices, axis=0), deep=True))
# create a locator to assist with duplicate points
locator = vtk.vtkPointLocator()
locator.SetDataSet(vtk_grid)
locator.AutomaticOn() # autmoatically adds points to locator
locator.InitPointInsertion(vtkPts, vtkPts.GetBounds())
locator.BuildLocator()
# this function is used to add new points to the unstructured
# grid. It will return an existing point ID if the point is alread present
def _insert_point(pnt):
result = locator.IsInsertedPoint(pnt)
if result == -1:
point_id = vtkPts.InsertNextPoint(pnt)
locator.InsertPoint(point_id, pnt)
return point_id
else:
return result
# Add all points to the unstructured grid, maintaining a flat list of IDs as we go ###
# flat array storing point IDs for a given vertex
# in the grid
point_ids = []
# add element corner vertices to array
for pnt in corner_vertices:
point_ids.append(_insert_point(pnt))
# get edge midpoints and add them to the
# list of point IDs
midpoint_vertices = self.midpoint_vertices
for edge_grid in midpoint_vertices:
for pnt in np.swapaxes(edge_grid, 0, 2).reshape(-1, 3):
point_ids.append(_insert_point(pnt))
# determine how many elements in each dimension
# and how many points in each grid
n_elem = np.asarray(self.dimension)
n_pnts = n_elem + 1
# create hexes and set points for corner
# vertices
for i, j, k in self.indices:
# handle indices indexed from one
i -= 1
j -= 1
k -= 1
# create a new vtk hex
hex = vtk.vtkQuadraticHexahedron()
# set connectivity the hex corners
for n, (di, dj, dk) in enumerate(_HEX_VERTEX_CONN):
# compute flat index into the point ID list based on i, j, k
# of the vertex
flat_idx = np.ravel_multi_index((i+di, j+dj, k+dk), n_pnts, order='F')
# set corner vertices
hex.GetPointIds().SetId(n, point_ids[flat_idx])
# set connectivity of the hex midpoints
n_midpoint_vertices = [v.size // 3 for v in midpoint_vertices]
for n, (dim, (di, dj, dk)) in enumerate(_HEX_MIDPOINT_CONN):
# initial offset for corner vertices and midpoint dimension
flat_idx = corner_vertices.shape[0] + sum(n_midpoint_vertices[:dim])
# generate a flat index into the table of point IDs
midpoint_shape = midpoint_vertices[dim].shape[:-1]
flat_idx += np.ravel_multi_index((i+di, j+dj, k+dk),
midpoint_shape,
order='F')
# set hex midpoint connectivity
hex.GetPointIds().SetId(_N_HEX_VERTICES + n, point_ids[flat_idx])
# add the hex to the grid
vtk_grid.InsertNextCell(hex.GetCellType(), hex.GetPointIds())
return vtk_grid
@staticmethod
def _reshape_vtk_dataset(dataset):
"""Reshape a dataset to be compatible with VTK output
This method performs the following operations on a dataset:
1. Convert to numpy array if not already
2. Remove any trailing dimensions of size 1
3. Squeeze out any extra dimensions of size 1 beyond the first 3
Parameters
----------
dataset : array-like
The dataset to reshape
Returns
-------
numpy.ndarray
The reshaped dataset
"""
reshaped_data = np.asarray(dataset)
# detect flat array with extra dims
if all(d == 1 for d in reshaped_data.shape[1:]):
reshaped_data = reshaped_data.squeeze()
# remove any higher dimensions with size 1
if reshaped_data.ndim > 3 and all(d == 1 for d in reshaped_data.shape[3:]):
reshaped_data = reshaped_data.reshape(reshaped_data.shape[:3])
if np.shares_memory(reshaped_data, dataset):
return np.copy(reshaped_data)
else:
return reshaped_data
def _check_vtk_dataset(self, label: str, dataset: np.ndarray):
"""Perform some basic checks that a dataset is valid for this Mesh
Parameters
----------
label : str
The label for the dataset being checked
dataset : numpy.ndarray
The dataset array to check against this mesh's dimensions
"""
cv.check_type('data label', label, str)
if dataset.size != self.n_elements:
raise ValueError(
f"The size of the dataset '{label}' ({dataset.size}) should be"
f" equal to the number of mesh cells ({self.n_elements})"
)
# accept a flat array as-is, assuming it is in the correct order
if dataset.ndim == 1:
return
if dataset.shape != self.dimension:
raise ValueError(
f'Cannot apply multidimensional dataset "{label}" with '
f"shape {dataset.shape} to mesh {self.id} "
f"with dimensions {self.dimension}"
)
class HasBoundingBox(Protocol):
"""Object that has a ``bounding_box`` attribute."""
bounding_box: openmc.BoundingBox
class RegularMesh(StructuredMesh):
"""A regular Cartesian mesh in one, two, or three dimensions
Parameters
----------
mesh_id : int
Unique identifier for the mesh
name : str
Name of the mesh
Attributes
----------
id : int
Unique identifier for the mesh
name : str
Name of the mesh
dimension : Iterable of int
The number of mesh cells in each direction (x, y, z).
n_dimension : int
Number of mesh dimensions.
lower_left : Iterable of float
The lower-left corner of the structured mesh. If only two coordinate
are given, it is assumed that the mesh is an x-y mesh.
upper_right : Iterable of float
The upper-right corner of the structured mesh. If only two coordinate
are given, it is assumed that the mesh is an x-y mesh.
bounding_box : openmc.BoundingBox
Axis-aligned bounding box of the mesh as defined by the upper-right and
lower-left coordinates.
width : Iterable of float
The width of mesh cells in each direction.
indices : Iterable of tuple
An iterable of mesh indices for each mesh element, e.g. [(1, 1, 1),
(2, 1, 1), ...]
"""
def __init__(self, mesh_id: int | None = None, name: str = ''):
super().__init__(mesh_id, name)
self._dimension = None
self._lower_left = None
self._upper_right = None
self._width = None
@property
def dimension(self):
return tuple(self._dimension)
@dimension.setter
def dimension(self, dimension: Iterable[int]):
cv.check_type('mesh dimension', dimension, Iterable, Integral)
cv.check_length('mesh dimension', dimension, 1, 3)
self._dimension = dimension
@property
def n_dimension(self):
if self._dimension is not None:
return len(self._dimension)
else:
return None
@property
def lower_left(self):
return self._lower_left