-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathvisualization.py
More file actions
209 lines (159 loc) · 6.92 KB
/
Copy pathvisualization.py
File metadata and controls
209 lines (159 loc) · 6.92 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
from __future__ import division, absolute_import
__copyright__ = "Copyright (C) 2012 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.
"""
__doc__ = """
.. autofunction:: make_field_plotter_from_bbox
.. autoclass:: FieldPlotter
"""
import numpy as np
from six.moves import range
def separate_by_real_and_imag(data, real_only):
for name, field in data:
from pytools.obj_array import log_shape
ls = log_shape(field)
if ls != () and ls[0] > 1:
assert len(ls) == 1
from pytools.obj_array import (
oarray_real_copy, oarray_imag_copy,
with_object_array_or_scalar)
if field[0].dtype.kind == "c":
if real_only:
yield (name,
with_object_array_or_scalar(oarray_real_copy, field))
else:
yield (name+"_r",
with_object_array_or_scalar(oarray_real_copy, field))
yield (name+"_i",
with_object_array_or_scalar(oarray_imag_copy, field))
else:
yield (name, field)
else:
# ls == ()
if field.dtype.kind == "c":
yield (name+"_r", field.real.copy())
yield (name+"_i", field.imag.copy())
else:
yield (name, field)
def make_field_plotter_from_bbox(bbox, h, extend_factor=0):
"""
:arg bbox: a tuple (low, high) of points represented as 1D numpy arrays
indicating the low and high ends of the extent of a bounding box.
:arg h: Either a number or a sequence of numbers indicating the desired
(approximate) grid spacing in all or each of the dimensions. If a
sequence, the length must match the number of dimensions.
:arg extend_factor: A floating point number indicating by what percentage
the plot area should be grown compared to *bbox*.
"""
low, high = bbox
extent = (high-low) * (1 + extend_factor)
center = 0.5*(high+low)
dimensions = len(center)
from numbers import Number
if isinstance(h, Number):
h = (h,)*dimensions
else:
if len(h) != dimensions:
raise ValueError("length of 'h' must match number of dimensions")
from math import ceil
npoints = tuple(
int(ceil(extent[i] / h[i]))
for i in range(dimensions))
return FieldPlotter(center, extent, npoints)
class FieldPlotter(object):
"""
.. automethod:: set_matplotlib_limits
.. automethod:: show_scalar_in_matplotlib
.. automethod:: show_scalar_in_mayavi
.. automethod:: write_vtk_file
"""
def __init__(self, center, extent=1, npoints=1000):
center = np.asarray(center)
self.dimensions, = dim, = center.shape
self.a = a = center-extent*0.5
self.b = b = center+extent*0.5
from numbers import Number
if isinstance(npoints, Number):
npoints = dim*(npoints,)
else:
if len(npoints) != dim:
raise ValueError("length of npoints must match dimension")
for i in range(dim):
if npoints[i] == 1:
a[i] = center[i]
mgrid_index = tuple(
slice(a[i], b[i], 1j*npoints[i])
for i in range(dim))
mgrid = np.mgrid[mgrid_index]
# (axis, point x idx, point y idx, ...)
self.nd_points = mgrid
self.points = self.nd_points.reshape(dim, -1).copy()
from pytools import product
self.npoints = product(npoints)
def _get_nontrivial_dims(self):
return np.array(self.nd_points.shape[1:]) != 1
def _get_squeezed_bounds(self):
nontriv_dims = self._get_nontrivial_dims()
return self.a[nontriv_dims], self.b[nontriv_dims]
def show_scalar_in_matplotlib(self, fld, max_val=None,
func_name="imshow", **kwargs):
squeezed_points = self.points.squeeze()
if len(squeezed_points.shape) != 2:
raise RuntimeError(
"matplotlib plotting requires 2D geometry")
if len(fld.shape) == 1:
fld = fld.reshape(self.nd_points.shape[1:])
squeezed_fld = fld.squeeze()
if max_val is not None:
squeezed_fld[squeezed_fld > max_val] = max_val
squeezed_fld[squeezed_fld < -max_val] = -max_val
squeezed_fld = squeezed_fld[..., ::-1]
a, b = self._get_squeezed_bounds()
kwargs["extent"] = (
# (left, right, bottom, top)
a[0], b[0],
a[1], b[1])
import matplotlib.pyplot as pt
return getattr(pt, func_name)(squeezed_fld.T, **kwargs)
def set_matplotlib_limits(self):
import matplotlib.pyplot as pt
a, b = self._get_squeezed_bounds()
pt.xlim((a[0], b[0]))
pt.ylim((a[1], b[1]))
def show_vector_in_mayavi(self, fld, do_show=True, **kwargs):
c = self.points
from mayavi import mlab
mlab.quiver3d(c[0], c[1], c[2], fld[0], fld[1], fld[2],
**kwargs)
if do_show:
mlab.show()
def write_vtk_file(self, file_name, data, real_only=False):
from pyvisfile.vtk import write_structured_grid
write_structured_grid(file_name, self.nd_points,
point_data=list(separate_by_real_and_imag(data, real_only)))
def show_scalar_in_mayavi(self, fld, max_val=None, **kwargs):
if max_val is not None:
fld[fld > max_val] = max_val
fld[fld < -max_val] = -max_val
if len(fld.shape) == 1:
fld = fld.reshape(self.nd_points.shape[1:])
nd_points = self.nd_points.squeeze()[self._get_nontrivial_dims()]
squeezed_fld = fld.squeeze()
from mayavi import mlab
mlab.surf(nd_points[0], nd_points[1], squeezed_fld, **kwargs)
# vim: foldmethod=marker