/
mayaviDaemon.py
296 lines (232 loc) · 10.4 KB
/
mayaviDaemon.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
295
296
"""A simple script that polls a data file for changes and then updates
the Mayavi pipeline automatically.
This script is based heavily on the `poll_file.py` example in the Mayavi distribution.
This script is to be run like so::
$ mayavi2 -x mayaviDaemon.py <options>
Or::
$ python mayaviDaemon.py <options>
Run::
$ python mayaviDaemon.py --help
to see available options.
"""
from __future__ import division
from __future__ import unicode_literals
__docformat__ = 'restructuredtext'
# Standard imports.
import os
import signal
import sys
# Enthought library imports
try:
from mayavi.plugins.app import Mayavi
from mayavi.sources.vtk_file_reader import VTKFileReader
from pyface.timer.api import Timer
from mayavi import mlab
except ImportError as e:
from enthought.mayavi.plugins.app import Mayavi
from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
from enthought.pyface.timer.api import Timer
from enthought.mayavi import mlab
# FiPy library imports
from fipy.tools.numerix import array, concatenate, where, zeros
__all__ = ["MayaviDaemon"]
from future.utils import text_to_native_str
__all__ = [text_to_native_str(n) for n in __all__]
######################################################################
class MayaviDaemon(Mayavi):
"""Given a file name and a mayavi2 data reader object, this class
polls the file for any changes and automatically updates the
mayavi pipeline.
"""
_viewers = []
def parse_command_line(self, argv):
"""Parse command line options.
Parameters
----------
argv : :obj:`list` of :obj:`str`
The command line arguments
"""
from optparse import OptionParser
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-l", "--lock", action="store", dest="lock", type="string", default=None,
help="path of lock file")
parser.add_option("-c", "--cell", action="store", dest="cell", type="string", default=None,
help="path of cell vtk file")
parser.add_option("-f", "--face", action="store", dest="face", type="string", default=None,
help="path of face vtk file")
parser.add_option("--xmin", action="store", dest="xmin", type="float", default=None,
help="minimum x value")
parser.add_option("--xmax", action="store", dest="xmax", type="float", default=None,
help="maximum x value")
parser.add_option("--ymin", action="store", dest="ymin", type="float", default=None,
help="minimum y value")
parser.add_option("--ymax", action="store", dest="ymax", type="float", default=None,
help="maximum y value")
parser.add_option("--zmin", action="store", dest="zmin", type="float", default=None,
help="minimum z value")
parser.add_option("--zmax", action="store", dest="zmax", type="float", default=None,
help="maximum z value")
parser.add_option("--datamin", action="store", dest="datamin", type="float", default=None,
help="minimum data value")
parser.add_option("--datamax", action="store", dest="datamax", type="float", default=None,
help="maximum data value")
parser.add_option("--fps", action="store", dest="fps", type="float", default=1.0,
help="frames per second to attempt to display")
(options, args) = parser.parse_args(argv)
self.lockfname = options.lock
self.cellfname = options.cell
self.facefname = options.face
self.bounds = [options.xmin, options.xmax,
options.ymin, options.ymax,
options.zmin, options.zmax]
self.datamin = options.datamin
self.datamax = options.datamax
self.fps = options.fps
def run(self):
MayaviDaemon._viewers.append(self)
mlab.clf()
bounds = zeros((0, 6), 'l')
self.cellsource = self.setup_source(self.cellfname)
if self.cellsource is not None:
tmp = [out.cell_data.scalars for out in self.cellsource.outputs \
if out.cell_data.scalars is not None]
self.has_cell_scalars = (len(tmp) > 0)
tmp = [out.cell_data.vectors for out in self.cellsource.outputs \
if out.cell_data.vectors is not None]
self.has_cell_vectors = (len(tmp) > 0)
tmp = [out.cell_data.tensors for out in self.cellsource.outputs \
if out.cell_data.tensors is not None]
self.has_cell_tensors = (len(tmp) > 0)
bounds = concatenate((bounds,
[out.bounds for out in self.cellsource.outputs]),
axis=0)
self.facesource = self.setup_source(self.facefname)
if self.facesource is not None:
tmp = [out.point_data.scalars for out in self.facesource.outputs \
if out.point_data.scalars is not None]
self.has_face_scalars = (len(tmp) > 0)
tmp = [out.point_data.vectors for out in self.facesource.outputs \
if out.point_data.vectors is not None]
self.has_face_vectors = (len(tmp) > 0)
tmp = [out.point_data.tensors for out in self.facesource.outputs \
if out.point_data.tensors is not None]
self.has_face_tensors = (len(tmp) > 0)
bounds = concatenate((bounds,
[out.bounds for out in self.facesource.outputs]),
axis=0)
boundsmin = bounds.min(axis=0)
boundsmax = bounds.max(axis=0)
bounds = (boundsmin[0], boundsmax[1],
boundsmin[2], boundsmax[3],
boundsmin[4], boundsmax[5])
self.bounds = where(self.bounds == array((None,)),
bounds,
self.bounds).astype(float)
self.view_data()
# Poll the lock file.
self.timer = Timer(1000 / self.fps, self.poll_file)
def __del__(self):
dir = None
for fname in [self.cellfname, self.facefname, self.lockfname]:
if fname and os.path.isfile(fname):
os.unlink(fname)
if not dir:
dir = os.path.dirname(fname)
if dir:
os.rmdir(dir)
@staticmethod
def _sigint_handler(signum, frame):
for viewer in MayaviDaemon._viewers:
viewer.__del__()
raise SystemExit("MayaviDaemon cleaned up")
def poll_file(self):
if os.path.isfile(self.lockfname):
self.update_pipeline(self.cellsource)
self.update_pipeline(self.facesource)
lock = file(self.lockfname, 'r')
filename = lock.read()
lock.close()
if len(filename) > 0:
mlab.savefig(filename)
os.unlink(self.lockfname)
def update_pipeline(self, source):
"""Override this to do something else if needed.
"""
if source is not None:
source.scene.disable_render = True
source.scene.anti_aliasing_frames = 0
# Force the reader to re-read the file.
source.reader.modified()
source.update()
# Propagate the changes in the pipeline.
source.data_changed = True
source.scene.disable_render = False
def setup_source(self, fname):
"""Given a VTK file name `fname`, this creates a mayavi2 reader
for it and adds it to the pipeline. It returns the reader
created.
"""
if fname is None:
return None
source = VTKFileReader()
source.initialize(fname)
mlab.pipeline.add_dataset(source)
return source
def clip_data(self, src):
if hasattr(mlab.pipeline, "data_set_clipper"):
clip = mlab.pipeline.data_set_clipper(src)
clip.filter.inside_out = True
clip.widget.widget_mode = 'Box'
clip.widget.widget.place_factor = 1.
clip.widget.widget.place_widget(self.bounds)
clip.widget.update_implicit_function()
clip.widget.visible = False
else:
import warnings
warnings.warn("Mayavi r24017 or newer needed for data_set_clipper()", UserWarning, stacklevel=2)
clip = src
return clip
def view_data(self):
"""Sets up the mayavi pipeline for the visualization.
"""
has_scale_bar = False
if self.cellsource is not None:
clip = self.clip_data(self.cellsource)
if self.has_cell_scalars:
s = mlab.pipeline.surface(clip, vmin=self.datamin, vmax=self.datamax)
s.module_manager.scalar_lut_manager.show_scalar_bar = True
has_scale_bar = True
p = mlab.pipeline.cell_to_point_data(clip)
if self.has_cell_vectors:
v = mlab.pipeline.vectors(p, vmin=self.datamin, vmax=self.datamax)
if not has_scale_bar:
v.module_manager.scalar_lut_manager.show_scalar_bar = True
has_scale_bar = True
if self.facesource is not None:
clip = self.clip_data(self.facesource)
if self.has_face_scalars:
s = mlab.pipeline.surface(clip, vmin=self.datamin, vmax=self.datamax)
if not has_scale_bar:
s.module_manager.scalar_lut_manager.show_scalar_bar = True
has_scale_bar = True
if self.has_face_vectors:
v = mlab.pipeline.vectors(clip, vmin=self.datamin, vmax=self.datamax)
if not has_scale_bar:
v.module_manager.scalar_lut_manager.show_scalar_bar = True
has_scale_bar = True
signal.signal(signal.SIGINT, MayaviDaemon._sigint_handler)
try:
signal.signal(signal.SIGHUP, MayaviDaemon._sigint_handler)
except AttributeError:
# not available on Windows
pass
signal.signal(signal.SIGTERM, MayaviDaemon._sigint_handler)
def main(argv=None):
"""Simple helper to start up the mayavi application. This returns
the running application."""
m = MayaviDaemon()
m.main(argv)
return m
if __name__ == '__main__':
main(sys.argv[1:])