/[escript]/trunk/pyvisi/py_src/renderers/vtk/ellipsoid_plot.py
ViewVC logotype

Contents of /trunk/pyvisi/py_src/renderers/vtk/ellipsoid_plot.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 720 - (show annotations)
Thu Apr 27 10:16:05 2006 UTC (13 years, 6 months ago) by gross
File MIME type: text/x-python
File size: 15611 byte(s)
formatting errors in epydoc tags fixed
1 """
2 Class and functions associated with a pyvisi EllipsoidPlot objects
3
4 @var __author__: name of author
5 @var __license__: licence agreement
6 @var __copyright__: copyrights
7 @var __url__: url entry point on documentation
8 @var __version__: version
9 @var __date__: date of the version
10 """
11
12 __copyright__=""" Copyright (c) 2006 by ACcESS MNRF
13 http://www.access.edu.au
14 Primary Business: Queensland, Australia"""
15 __license__="""Licensed under the Open Software License version 3.0
16 http://www.opensource.org/licenses/osl-3.0.php"""
17 __author__="Paul Cochrane"
18 __url__="http://www.iservo.edu.au/esys"
19 __version__="$Revision$"
20 __date__="$Date$"
21
22
23 # generic imports
24 from common import debugMsg
25 import os
26 import copy
27 import numarray
28
29 # module specific imports
30 from plot import Plot
31
32 class EllipsoidPlot(Plot):
33 """
34 Ellipsoid plot
35 """
36 def __init__(self, scene):
37 """
38 Initialisation of the EllipsoidPlot class
39
40 @param scene: The Scene to render the plot in
41 @type scene: Scene object
42 """
43 debugMsg("Called EllipsoidPlot.__init__()")
44 Plot.__init__(self, scene)
45
46 self.renderer = scene.renderer
47 self.renderer.addToInitStack("# EllipsoidPlot.__init__()")
48
49 # labels and stuff
50 self.title = None
51 self.xlabel = None
52 self.ylabel = None
53 self.zlabel = None
54
55 # default values for fname, format and tensors
56 self.fname = None
57 self.format = None
58 self.tensors = None
59
60 # default values for shared info
61 self.escriptData = False
62 self.otherData = False
63
64 # add the plot to the scene
65 scene.add(self)
66
67 def setData(self, *dataList, **options):
68 """
69 Set data to the plot
70
71 @param dataList: List of data to set to the plot
72 @type dataList: tuple
73
74 @param options: Dictionary of keyword options to the method
75 @type options: dict
76
77 @keyword fname: the name of the input vtk file
78 @type fname: string
79
80 @keyword format: the format of the input vtk file ('vtk' or 'vtk-xml')
81 @type format: string
82
83 @keyword tensors: the name of the tensor data in the vtk file to use
84 @type tensors: string
85 """
86 debugMsg("Called setData() in EllipsoidPlot()")
87
88 self.renderer.runString("# EllipsoidPlot.setData()")
89
90 # process the options, if any
91 ## fname
92 if options.has_key('fname'):
93 fname = options['fname']
94 else:
95 fname = None
96 ## format
97 if options.has_key('format'):
98 format = options['format']
99 else:
100 format = None
101 ## tensors
102 if options.has_key('tensors'):
103 tensors = options['tensors']
104 else:
105 tensors = None
106
107 # we want to pass this info around
108 self.fname = fname
109 self.format = format
110 self.tensors = tensors
111
112 # reset the default values for shared info
113 self.escriptData = False
114 self.otherData = False
115
116 # do some sanity checking on the input args
117 if len(dataList) == 0 and fname is None:
118 raise ValueError, \
119 "You must specify a data list or an input filename"
120
121 if len(dataList) != 0 and fname is not None:
122 raise ValueError, \
123 "You cannot specify a data list as well as an input file"
124
125 if fname is not None and tensors is None:
126 debugMsg("No tensors specified; using default in vtk")
127
128 if fname is not None and format is None:
129 raise ValueError, "You must specify an input file format"
130
131 if fname is None and format is not None:
132 raise ValueError, "Format specified but no input filename"
133
134 # if have just a data list, check the objects passed in to see if
135 # they are escript data objects or not
136 if len(dataList) != 0:
137 for obj in dataList:
138 try:
139 obj.convertToNumArray()
140 # ok, we've got escript data, set the flag
141 self.escriptData = True
142 except AttributeError:
143 self.otherData = True
144
145 # if we have both escript data and other data, barf as can't handle
146 # that yet
147 if self.escriptData and self.otherData:
148 raise TypeError, \
149 "Sorry can't handle both escript and other data yet"
150
151 # now generate the code for the case when we have just escript data
152 # passed into setData()
153 if self.escriptData:
154 # get the relevant bits of data
155 if len(dataList) == 1:
156 # only one data variable, will need to get the domain from it
157 escriptZ = dataList[0]
158 escriptX = escriptZ.getDomain().getX()
159 else:
160 errorString = \
161 "Expecting only 1 element in data list. I got %d" \
162 % len(dataList)
163 raise ValueError, errorString
164
165 # convert the Data objects to numarrays
166 domainData = escriptX.convertToNumArray()
167 fieldData = escriptZ.convertToNumArray()
168
169 # make sure that the shapes are correct
170 if len(domainData.shape) != 2:
171 raise ValueError, \
172 "domainData shape not 2D. I got %d dims" % \
173 len(domainData.shape)
174
175 if len(fieldData.shape) != 3:
176 raise ValueError, \
177 "fieldData shape not 3D. I got %d dims" % \
178 len(fieldData.shape)
179
180 # check the array lengths
181 if domainData.shape[0] != fieldData.shape[0]:
182 raise ValueError, \
183 "domainData and fieldData array lengths don't agree"
184
185 # check the array dimensions
186 if domainData.shape[1] != 2 and domainData.shape[1] != 3:
187 raise ValueError, \
188 "domainData array not 2D or 3D. I got %d dims" % \
189 domainData.shape[1]
190
191 if fieldData.shape[1] != 2 and fieldData.shape[1] != 3:
192 raise ValueError, \
193 "fieldData first array not 2D or 3D. I got %d dims" \
194 % fieldData.shape[1]
195
196 if fieldData.shape[2] != 2 and fieldData.shape[2] != 3:
197 raise ValueError, \
198 "fieldData second array not 2D or 3D. I got %d dims" \
199 % fieldData.shape[2]
200
201 # check that the fieldData arrays are square
202 if fieldData.shape[1] != fieldData.shape[2]:
203 errorString = "fieldData arrays not square. "
204 errorString += "First dim: %d. " % fieldData.shape[1]
205 errorString += "Second dim %d." % fieldData.shape[2]
206 raise ValueError, errorString
207
208 # get the x, y and z data from the domain
209 xData = domainData[:,0]
210 numPoints = len(xData) # handy number to keep hanging around
211 yData = domainData[:,1]
212 # handle the case where no zData is specified
213 if domainData.shape[1] == 2:
214 zData = numarray.zeros(numPoints)
215 else:
216 zData = domainData[:,2]
217
218 ####!!!! now process the data properly so that I can plot it
219 print "domainData.shape = %s" % str(domainData.shape)
220 print "fieldData.shape = %s" % str(fieldData.shape)
221
222 # now pass the data to the render dictionary so that the render
223 # code knows what it's supposed to plot
224
225 # x data
226 self.renderer.renderDict['_x'] = copy.deepcopy(xData)
227
228 # y data
229 self.renderer.renderDict['_y'] = copy.deepcopy(yData)
230
231 # z data
232 self.renderer.renderDict['_z'] = copy.deepcopy(zData)
233
234 # field data
235 self.renderer.renderDict['_data'] = copy.deepcopy(fieldData)
236
237 # make the points for the grid
238 evalString = "_points = vtk.vtkPoints()\n"
239 evalString += "_points.SetNumberOfPoints(%d)\n" % numPoints
240 evalString += "for _j in range(%d):\n" % numPoints
241 evalString += \
242 " _points.InsertPoint(_j, _x[_j], _y[_j], _z[_j])\n"
243 self.renderer.runString(evalString)
244
245 # make the array of data
246 evalString = "_tensors = vtk.vtkFloatArray()\n"
247 evalString += "_tensors.SetNumberOfComponents(9)\n"
248 evalString += "_tensors.SetNumberOfTuples(%d)\n" % numPoints
249 evalString += "_tensors.SetName(\"tensors\")\n"
250 evalString += "for _j in range(%d):\n" % numPoints
251 if fieldData.shape[1] == 2:
252 evalString += " _tensors.InsertTuple9(_j, "
253 evalString += "_data[_j][0][0], _data[_j][0][1], 0.0, "
254 evalString += "_data[_j][1][0], _data[_j][1][1], 0.0, "
255 evalString += "0.0, 0.0, 0.0)\n"
256 elif fieldData.shape[1] == 3:
257 evalString += " _tensors.InsertTuple9(_j, "
258 evalString += \
259 "_data[_j][0][0], _data[_j][0][1], _data[_j][0][2], "
260 evalString += \
261 "_data[_j][1][0], _data[_j][1][1], _data[_j][1][2], "
262 evalString += \
263 "_data[_j][2][0], _data[_j][2][1], _data[_j][2][2])\n"
264 else:
265 raise ValueError, "Incorrect fieldData shape. I got %d" % \
266 fieldData.shape[1]
267 self.renderer.runString(evalString)
268
269 # make the grid
270 evalString = "_grid = vtk.vtkUnstructuredGrid()\n"
271 evalString += "_grid.SetPoints(_points)\n"
272 evalString += "_grid.GetPointData().AddArray(_tensors)\n"
273 evalString += \
274 "_grid.GetPointData().SetActiveTensors(\"tensors\")\n"
275 self.renderer.runString(evalString)
276
277 # now extract the tensor components
278 evalString = "_extract = vtk.vtkExtractTensorComponents()\n"
279 evalString += "_extract.SetInput(_grid)\n"
280 evalString += "_extract.SetScalarModeToEffectiveStress()\n"
281 evalString += "_extract.ExtractScalarsOn()\n"
282 evalString += "_extract.PassTensorsToOutputOn()\n"
283 evalString += "_extract.ScalarIsEffectiveStress()\n"
284
285 evalString += "_extractGrid = _extract.GetOutput()\n"
286 evalString += "_extractGrid.Update()\n"
287 evalString += "_extractScalarRange = "
288 evalString += \
289 "_extractGrid.GetPointData().GetScalars().GetRange()\n"
290 self.renderer.runString(evalString)
291
292 elif self.otherData:
293
294 # do some checks to make sure have the right kind of shape for
295 # the data and then generate the code
296
297 raise ImplementationError, "Can't process plain array data yet"
298
299 if fname is not None:
300
301 # check to see if the file exists
302 if not os.path.exists(fname):
303 raise SystemError, "File %s not found" % fname
304
305 if format == 'vtk':
306 # read old-style vtk files
307 evalString = "_reader = vtk.vtkUnstructuredGridReader()\n"
308 elif format == 'vtk-xml':
309 # read vtk xml files
310 evalString = "_reader = vtk.vtkXMLUnstructuredGridReader()\n"
311 else:
312 # barf
313 raise ValueError, "Unknown format. I got %s" % format
314
315 evalString += "_reader.SetFileName(\"%s\")\n" % fname
316 evalString += "_reader.Update()"
317
318 self.renderer.runString(evalString)
319
320 # grab the grid of the data
321 self.renderer.runString("_grid = _reader.GetOutput()")
322
323 # convert the cell data to point data
324 evalString = "_c2p = vtk.vtkCellDataToPointData()\n"
325 evalString += "_c2p.SetInput(_grid)"
326 self.renderer.runString(evalString)
327
328 # now extract the tensor components
329 evalString = "_extract = vtk.vtkExtractTensorComponents()\n"
330 evalString += "_extract.SetInput(_c2p.GetOutput())\n"
331 evalString += "_extract.SetScalarModeToEffectiveStress()\n"
332 evalString += "_extract.ExtractScalarsOn()\n"
333 evalString += "_extract.PassTensorsToOutputOn()\n"
334 evalString += "_extract.ScalarIsEffectiveStress()\n"
335
336 evalString += "_extractGrid = _extract.GetOutput()\n"
337 evalString += "_extractGrid.Update()\n"
338 evalString += "_extractScalarRange = "
339 evalString += \
340 "_extractGrid.GetPointData().GetScalars().GetRange()\n"
341 self.renderer.runString(evalString)
342
343 return
344
345 def render(self):
346 """
347 Does EllipsoidPlot object specific (pre)rendering stuff
348 """
349 debugMsg("Called EllipsoidPlot.render()")
350
351 self.renderer.runString("# EllipsoidPlot.render()")
352
353 # make a sphere source for the glyphs
354 evalString = "_sphere = vtk.vtkSphereSource()\n"
355 evalString += "_sphere.SetThetaResolution(6)\n"
356 evalString += "_sphere.SetPhiResolution(6)\n"
357 evalString += "_sphere.SetRadius(0.5)"
358 self.renderer.runString(evalString)
359
360 # make tensor glyphs
361 evalString = "_glyph = vtk.vtkTensorGlyph()\n"
362 evalString += "_glyph.SetSource(_sphere.GetOutput())\n"
363 evalString += "_glyph.SetInput(_extractGrid)\n"
364 evalString += "_glyph.SetColorModeToScalars()\n"
365 evalString += "_glyph.ScalingOn()\n"
366 evalString += "_glyph.SetMaxScaleFactor(5.0)\n"
367 evalString += "_glyph.SetScaleFactor(1.0)\n"
368 evalString += "_glyph.ClampScalingOn()"
369 self.renderer.runString(evalString)
370
371 # make a stripper for faster rendering
372 evalString = "_stripper = vtk.vtkStripper()\n"
373 evalString += "_stripper.SetInput(_glyph.GetOutput())"
374 self.renderer.runString(evalString)
375
376 # make the normals of the data
377 evalString = "_normals = vtk.vtkPolyDataNormals()\n"
378 evalString += "_normals.SetInput(_stripper.GetOutput())"
379 self.renderer.runString(evalString)
380
381 # make the mapper for the data
382 evalString = "_mapper = vtk.vtkPolyDataMapper()\n"
383 evalString += "_mapper.SetInput(_normals.GetOutput())\n"
384 evalString += "_mapper.SetLookupTable(_lut)\n"
385 evalString += "_mapper.SetScalarRange(_extractScalarRange)"
386 self.renderer.runString(evalString)
387
388 # make the actor
389 evalString = "_actor = vtk.vtkActor()\n"
390 evalString += "_actor.SetMapper(_mapper)"
391 self.renderer.runString(evalString)
392
393 # add the actor
394 self.renderer.runString("_renderer.AddActor(_actor)")
395
396 # set up the text properties for nice text
397 evalString = "_textProp = vtk.vtkTextProperty()\n"
398 evalString += "_textProp.SetFontFamilyToArial()\n"
399 evalString += "_textProp.BoldOff()\n"
400 evalString += "_textProp.ItalicOff()\n"
401 evalString += "_textProp.ShadowOff()\n"
402 evalString += "_textProp.SetColor(0.0, 0.0, 0.0)"
403 self.renderer.runString(evalString)
404
405 # if a title is set, put it in here
406 if self.title is not None:
407 # make a title
408 evalString = "_title = vtk.vtkTextMapper()\n"
409 evalString += "_title.SetInput(\"%s\")\n" % self.title
410
411 # make the title text use the text properties
412 evalString += "_titleProp = _title.GetTextProperty()\n"
413 evalString += "_titleProp.ShallowCopy(_textProp)\n"
414 evalString += "_titleProp.SetJustificationToCentered()\n"
415 evalString += "_titleProp.SetVerticalJustificationToTop()\n"
416 evalString += "_titleProp.SetFontSize(20)\n"
417 evalString += "_titleProp.BoldOn()\n"
418
419 # make the actor for the title
420 evalString += "_titleActor = vtk.vtkTextActor()\n"
421 evalString += "_titleActor.SetMapper(_title)\n"
422 evalString += "_titleActor.GetPositionCoordinate()."
423 evalString += "SetCoordinateSystemToNormalizedDisplay()\n"
424 evalString += "_titleActor.GetPositionCoordinate()."
425 evalString += "SetValue(0.5, 0.95)"
426 self.renderer.runString(evalString)
427
428 # add to the renderer
429 evalString = "_renderer.AddActor(_titleActor)"
430 self.renderer.runString(evalString)
431
432 # add a scalar bar
433 evalString = "_scalarBar = vtk.vtkScalarBarActor()\n"
434 evalString += "_scalarBar.SetLookupTable(_lut)\n"
435 evalString += "_scalarBar.SetWidth(0.1)\n"
436 evalString += "_scalarBar.SetHeight(0.8)\n"
437 evalString += "_scalarBar.SetPosition(0.9, 0.15)"
438 self.renderer.runString(evalString)
439
440 # set up the label text properties
441 evalString = "_scalarBarTextProp = _scalarBar.GetLabelTextProperty()\n"
442 evalString += "_scalarBarTextProp.ShallowCopy(_textProp)\n"
443 evalString += "_scalarBarTextProp.SetFontSize(10)\n"
444
445 evalString += "_renderer.AddActor(_scalarBar)"
446 self.renderer.runString(evalString)
447
448 return
449
450
451 # vim: expandtab shiftwidth=4:

  ViewVC Help
Powered by ViewVC 1.1.26