-
Notifications
You must be signed in to change notification settings - Fork 148
/
viewer.py
294 lines (247 loc) · 10.3 KB
/
viewer.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
from __future__ import print_function
from __future__ import unicode_literals
from builtins import object
__docformat__ = 'restructuredtext'
__all__ = ["AbstractViewer"]
from future.utils import text_to_native_str
__all__ = [text_to_native_str(n) for n in __all__]
import sys
class AbstractViewer(object):
"""
.. attention:: This class is abstract. Always create one of its subclasses.
"""
def __init__(self, vars, title=None, **kwlimits):
"""Create a `AbstractViewer` object.
Parameters
----------
vars : ~fipy.variables.cellVariable.CellVariable or list
the `CellVariable` objects to display.
title : str, optional
displayed at the top of the `Viewer` window
float xmin, xmax, ymin, ymax, zmin, zmax, datamin, datamax : float, optional
displayed range of data. Any limit set to
a (default) value of `None` will autoscale.
"""
if self.__class__ is AbstractViewer:
raise NotImplementedError("can't instantiate abstract base class")
self.vars = self._getSuitableVars(vars)
self.limits = kwlimits
if title is None:
if len(self.vars) == 1:
title = self.vars[0].name
else:
title = ''
self.title = title
def _getSuitableVars(self, vars):
if type(vars) not in [type([]), type(())]:
vars = [vars]
return [var for var in vars]
def setLimits(self, limits={}, **kwlimits):
"""
Update the limits.
Parameters
----------
limits : dict, optional
a (deprecated) alternative to limit keyword arguments
float xmin, xmax, ymin, ymax, zmin, zmax, datamin, datamax : float, optional
displayed range of data. A 1D `Viewer` will only use `xmin` and
`xmax`, a 2D viewer will also use `ymin` and `ymax`, and so on. All
viewers will use `datamin` and `datamax`. Any limit set to a
(default) value of `None` will autoscale.
"""
self.limits.update(limits)
self.limits.update(kwlimits)
def _getLimit(self, keys, default=None):
"""
Return the limit associated with the first available key in `keys`
Parameters
----------
keys : str or :obj:`tuple` of :obj:`str`
dictionary keys that identify the limits of interest
Returns
-------
float or None
the value of the limit
"""
if not (isinstance(keys, list) or isinstance(keys, tuple)):
keys = (keys,)
limit = default
for key in keys:
limit = self.limits.get(key, limit)
if limit is not None:
break
return limit
def plot(self, filename=None):
"""
Update the display of the viewed variables.
Parameters
----------
filename : str
If not `None`, the name of a file to save the image into.
"""
raise NotImplementedError
def plotMesh(self, filename=None):
"""
Display a representation of the mesh
Parameters
----------
filename : str
If not `None`, the name of a file to save the image into.
"""
pass
def _autoscale(self, vars, datamin=None, datamax=None):
from fipy.tools import numerix
if datamin is None:
datamin = 1e300
for var in vars:
datamin = min(datamin, numerix.nanmin(var))
if datamax is None:
from fipy.tools import numerix
datamax = -1e300
for var in vars:
datamax = max(datamax, numerix.nanmax(var))
return datamin, datamax
def _validFileExtensions(self):
return []
_saved_stdout = sys.stdout
@staticmethod
def _serial_doctest_raw_input(prompt):
"""Replacement for `raw_input()` that works in doctests
"""
AbstractViewer._saved_stdout.write("\n")
AbstractViewer._saved_stdout.write(prompt)
AbstractViewer._saved_stdout.flush()
return sys.stdin.readline()
@staticmethod
def _doctest_raw_input(prompt):
"""Replacement for `raw_input()` that works in doctests
This routine attempts to be savvy about running in parallel.
"""
try:
from fipy.tools import parallelComm
parallelComm.Barrier()
AbstractViewer._saved_stdout.flush()
if parallelComm.procID == 0:
txt = AbstractViewer._serial_doctest_raw_input(prompt)
else:
txt = ""
parallelComm.Barrier()
except ImportError:
txt = AbstractViewer._serial_doctest_raw_input(prompt)
return txt
def _promptForOpinion(self, prompt="Describe any problems with this figure or hit Return: "):
# This method is usually invoked from a test, which can have a weird
# state; In particular, it may have a special `raw_input` to prevent user
# interaction during the test.
opinion = self._doctest_raw_input(self.__class__.__name__ + ": " + prompt).strip()
if len(opinion) > 0:
extensions = ", ".join(self._validFileExtensions())
if len(extensions) > 0:
extensions = " (%s)" % extensions
snapshot = self._doctest_raw_input("Enter a filename%s to save a snapshot (leave blank to skip): " % extensions).strip()
self.plot(snapshot)
print(opinion)
def _test1D(**kwargs):
s = """
>>> from fipy import *
>>> mesh = Grid1D(nx=100)
>>> x, = mesh.cellCenters
>>> xVar = CellVariable(mesh=mesh, name="x", value=x)
>>> k = Variable(name="k", value=0.)
>>> viewer = VIEWERSUBSTITUTION(vars=(numerix.sin(k * xVar), numerix.cos(k * xVar / numerix.pi)),
... limits={'xmin': 10, 'xmax': 90},
... datamin=-0.9, datamax=2.0,
... title="VIEWERSUBSTITUTION test")
>>> for kval in numerix.arange(0, 0.3, 0.03):
... k.setValue(kval)
... viewer.plot()
>>> viewer._promptForOpinion()
"""
s = s.replace("VIEWERSUBSTITUTION", kwargs["viewer"])
return s
_test1D = staticmethod(_test1D)
def _test2Dbase(**kwargs):
s = """
>>> from fipy import *
>>> mesh = MESHSUBSTITUTION
>>> x, y = mesh.cellCenters
>>> xyVar = CellVariable(mesh=mesh, name="x y", value=x * y)
>>> k = Variable(name="k", value=0.)
>>> viewer = VIEWERSUBSTITUTION(vars=numerix.sin(k * xyVar),
... limits={'ymin': 0.1, 'ymax': 0.9},
... datamin=-0.9, datamax=2.0,
... title="VIEWERSUBSTITUTION test")
>>> from builtins import range
>>> for kval in range(10):
... k.setValue(kval)
... viewer.plot()
>>> viewer._promptForOpinion()
"""
s = s.replace("VIEWERSUBSTITUTION", kwargs["viewer"])
s = s.replace("MESHSUBSTITUTION", kwargs["mesh"])
return s
_test2Dbase = staticmethod(_test2Dbase)
def _test2D(**kwargs):
return AbstractViewer._test2Dbase(mesh="Grid2D(nx=50, ny=100, dx=0.1, dy=0.01)",
**kwargs)
_test2D = staticmethod(_test2D)
def _test2Dirregular(**kwargs):
""""""
return AbstractViewer._test2Dbase(mesh="""(Grid2D(nx=5, ny=10, dx=0.1, dy=0.1)
... + (Tri2D(nx=5, ny=5, dx=0.1, dy=0.1)
... + ((0.5,), (0.2,))))""", **kwargs)
_test2Dirregular = staticmethod(_test2Dirregular)
def _test2DvectorBase(**kwargs):
s = """
>>> from fipy import *
>>> mesh = MESHSUBSTITUTION
>>> x, y = mesh.cellCenters
>>> xyVar = CellVariable(mesh=mesh, name="x y", value=x * y)
>>> k = Variable(name="k", value=1.)
>>> viewer = VIEWERSUBSTITUTION(vars=numerix.sin(k * xyVar).grad,
... title="VIEWERSUBSTITUTION test")
>>> for kval in numerix.arange(1, 10):
... k.setValue(kval)
... viewer.plot()
>>> viewer._promptForOpinion()
>>> viewer = VIEWERSUBSTITUTION(vars=numerix.sin(k * xyVar).faceGrad,
... title="VIEWERSUBSTITUTION test")
>>> for kval in numerix.arange(1, 10):
... k.setValue(kval)
... viewer.plot()
>>> viewer._promptForOpinion()
"""
s = s.replace("VIEWERSUBSTITUTION", kwargs["viewer"])
s = s.replace("MESHSUBSTITUTION", kwargs["mesh"])
return s
_test2DvectorBase = staticmethod(_test2DvectorBase)
def _test2Dvector(**kwargs):
return AbstractViewer._test2DvectorBase(mesh="Grid2D(nx=50, ny=100, dx=0.1, dy=0.01)",
**kwargs)
_test2Dvector = staticmethod(_test2Dvector)
def _test2DvectorIrregular(**kwargs):
""""""
return AbstractViewer._test2DvectorBase(mesh="""(Grid2D(nx=5, ny=10, dx=0.1, dy=0.1)
... + (Tri2D(nx=5, ny=5, dx=0.1, dy=0.1)
... + ((0.5,), (0.2,))))""", **kwargs)
_test2DvectorIrregular = staticmethod(_test2DvectorIrregular)
def _test3D(**kwargs):
s = """
>>> from fipy import *
>>> mesh = Grid3D(nx=50, ny=100, nz=10, dx=0.1, dy=0.01, dz=0.1)
>>> x, y, z = mesh.cellCenters
>>> xyzVar = CellVariable(mesh=mesh, name=r"x y z", value=x * y * z)
>>> k = Variable(name="k", value=0.)
>>> viewer = VIEWERSUBSTITUTION(vars=numerix.sin(k * xyzVar),
... limits={'ymin': 0.1, 'ymax': 0.9},
... datamin=-0.9, datamax=2.0,
... title="VIEWERSUBSTITUTION test")
>>> from builtins import range
>>> for kval in range(10):
... k.setValue(kval)
... viewer.plot()
>>> viewer._promptForOpinion()
"""
s = s.replace("VIEWERSUBSTITUTION", kwargs["viewer"])
return s
_test3D = staticmethod(_test3D)