-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.py
94 lines (71 loc) · 2.63 KB
/
core.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
__all__ = ['VTK']
import typing as t
import warnings as w
from ..type import Path
if t.TYPE_CHECKING:
import numpy as np
import vtkmodules as vtk
from ..core import Foam
class VTK:
'''OpenFOAM VTK postprocessing'''
Self = __qualname__
def __init__(self, reader: 'vtk.vtkIOLegacy.vtkDataReader') -> None:
self._points = self._to_numpy(reader.GetOutput().GetPoints().GetData())
arrays = reader.GetOutput().GetPointData()
self._fields = {}
for ith in range(arrays.GetNumberOfArrays()):
array = arrays.GetArray(ith)
self._fields[array.GetName()] = self._to_numpy(array)
reader.CloseVTKFile()
def __contains__(self, key: str) -> bool:
return key in self._fields
def __getitem__(self, key: str) -> 'np.ndarray':
return self._fields[key]
@classmethod
def from_unstructured_grid(cls, path: Path) -> Self:
import vtkmodules.all as vtk
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(str(path))
reader.ReadAllFieldsOn()
reader.ReadAllNormalsOn()
reader.ReadAllScalarsOn()
reader.ReadAllTCoordsOn()
reader.ReadAllTensorsOn()
reader.ReadAllVectorsOn()
reader.Update()
return cls(reader)
@classmethod
def from_foam(cls, foam: 'Foam', options: str = '', overwrite: bool = False) -> t.Iterator[Self]:
foam.cmd.run([f'foamToVTK {options}'], overwrite=overwrite, exception=False, unsafe=True)
paths = [
path
for path in (foam._dest/'VTK').iterdir()
if path.is_file() and path.suffix=='.vtk'
]
for path in sorted(paths, key=lambda p: int(p.stem.rsplit('_', maxsplit=1)[-1])):
yield cls.from_unstructured_grid(path)
@property
def points(self) -> 'np.ndarray':
return self._points
@property
def fields(self) -> 'np.ndarray':
return self._fields
@property
def x(self) -> 'np.ndarray':
return self._points[:, 0]
@property
def y(self) -> 'np.ndarray':
return self._points[:, 1]
@property
def z(self) -> 'np.ndarray':
return self._points[:, 2]
def keys(self) -> t.List[str]:
return list(self._fields.keys())
def centroid(self, key: str) -> 'np.ndarray':
field = self.fields[key]
if len(field.shape) != 1:
w.warn('NotImplemented')
return (self.points.T @ field) / sum(field)
def _to_numpy(self, array: 'vtk.vtkCommonCore.vtkDataArray') -> 'np.ndarray':
from vtkmodules.util.numpy_support import vtk_to_numpy
return vtk_to_numpy(array)