/[escript]/trunk/pyvisi_old/examples/ballPlotExample.py
ViewVC logotype

Contents of /trunk/pyvisi_old/examples/ballPlotExample.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 786 - (show annotations)
Tue Jul 25 04:58:05 2006 UTC (13 years, 1 month ago) by gross
File MIME type: text/x-python
File size: 14184 byte(s)
switched off pyvisi
1 """
2 Example of plotting spheres with pyvisi
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 # what plotting method are we using?
24 method = 'pyvisi'
25
26 import os, sys
27 import random
28
29 # set up some data to plot
30 from Numeric import *
31
32 # the three axes in space
33 # this will give us 10 particles (_not_ 1000)
34 x = arange(10, typecode=Float)
35 y = arange(10, typecode=Float)
36 z = arange(10, typecode=Float)
37
38 # 3D position information
39 posArray = []
40 for i in range(len(x)):
41 for j in range(len(y)):
42 for k in range(len(z)):
43 posArray.append( (x[i], y[j], z[k]) )
44
45 # radius information
46 random.seed()
47 radiiArray = zeros(len(x)*len(y)*len(z), typecode=Float)
48 for i in range(len(x)*len(y)*len(z)):
49 radiiArray[i] = random.random()*0.8
50
51 # tag information
52 random.seed()
53 tagsArray = zeros(len(x)*len(y)*len(z), typecode=Int)
54 for i in range(len(x)*len(y)*len(z)):
55 tagsArray[i] = int(random.random()*10)
56
57 # plot it using one of the three methods
58 if method == 'pyvisi':
59
60 # example code for how a user would write a script in pyvisi
61 from esys.pyvisi import * # base level visualisation stuff
62 # import the objects to render the scene using the specific renderer
63 #from esys.pyvisi.renderers.gnuplot import * # gnuplot
64 from esys.pyvisi.renderers.vtk import * # vtk
65
66 # define the scene object
67 # a Scene is a container for all of the kinds of things you want to put
68 # into your plot for instance, images, meshes, arrow/vector/quiver plots,
69 # contour plots, spheres etc.
70 scene = Scene()
71
72 # create a BallPlot object
73 plot = BallPlot(scene)
74
75 # add some helpful info to the plot
76 plot.title = 'Example ball plot'
77
78 # assign some data to the plot
79 # one way of doing it
80 # (tags indirectly determine colour of the spheres in the plot)
81 plot.setData(points=posArray, radii=radiiArray, tags=tagsArray)
82
83 # render the scene
84 scene.render(pause=True, interactive=True)
85
86 # without specifying a tags array input
87 plot.setData(points=posArray, radii=radiiArray)
88 # render the scene
89 scene.render(pause=True, interactive=True)
90
91 # another way loading an old style-vtk file
92 plot.setData(fname="cp_test_0.vtk",
93 format="vtk",
94 radii="radius",
95 colors="particleTag")
96
97 # render the scene to screen
98 scene.render(pause=True, interactive=True)
99
100 # another way loading a vtk xml file
101 plot.setData(fname="cp_test_0.xml",
102 format="vtk-xml",
103 radii="radius",
104 colors="particleTag")
105
106 # render the scene to screen
107 scene.render(pause=True, interactive=True)
108
109 # save the scene out to file
110 ## as png
111 plot.setData(fname="cp_test_0.xml",
112 format="vtk-xml",
113 radii="radius",
114 colors="particleTag")
115 scene.save(fname="ballPlotExample.png", format="png")
116 ## as postscript
117 plot.setData(fname="cp_test_0.xml",
118 format="vtk-xml",
119 radii="radius",
120 colors="particleTag")
121 scene.save(fname="ballPlotExample.ps", format="PS")
122
123 elif method == 'vtk':
124 #### original vtk code
125
126 import vtk
127 import os
128
129 # we're loading a file; make sure it exists first
130 if os.path.exists("cp_test_0.xml"):
131 pass
132 else:
133 raise IOError, "File not found"
134
135 # create the reader of the file
136 _reader = vtk.vtkXMLUnstructuredGridReader()
137 _reader.SetFileName("cp_test_0.xml")
138 _reader.Update()
139
140 # read the output into an unstructured grid
141 _grid = _reader.GetOutput()
142
143 # grab the radius data for the radii of the balls
144 _radii = _grid.GetPointData().GetScalars("radius")
145
146 # grab the tag data and use for colouring the balls
147 _tags = _grid.GetPointData().GetScalars("particleTag")
148
149 # work out dynamically the number of different tags so that can use this
150 # information to automatically set the scalar range for colouring
151 _numPoints = _tags.GetNumberOfTuples()
152 _valueDict = {}
153 for i in range(_numPoints):
154 _tagValue = _tags.GetValue(i)
155 _valueDict[_tagValue] = 1
156
157 _numTags = len(_valueDict.keys())
158
159 _tagValues = _valueDict.keys()
160 _tagValues.sort()
161
162 # count the number of tags, and make an evenly spaced array of points
163 # between zero and one, then use these as the scalars to colour by
164 _scaledTags = vtk.vtkFloatArray()
165 _scaledTags.SetNumberOfTuples(_numPoints)
166 _scaledTags.SetNumberOfComponents(1)
167 _scaledTags.SetName("tags")
168 for i in range(_numPoints):
169 _tagValue = _tags.GetValue(i)
170 for j in range(_numTags):
171 if _tagValues[j] == _tagValue:
172 _scaledTags.InsertTuple1(i, float(j)/float(_numTags-1))
173
174 # in vtk 4.2 have to set up an array of two components to get
175 # the data through the glyph object to the mapper so create this now
176 _data = vtk.vtkFloatArray()
177 _data.SetNumberOfComponents(3)
178 _data.SetNumberOfTuples(_radii.GetNumberOfTuples())
179 _data.CopyComponent(0, _radii, 0)
180 _data.CopyComponent(1, _tags, 0)
181 _data.CopyComponent(2, _scaledTags, 0)
182 _data.SetName("data")
183
184 # add the data array to the grid (again, only specific to vtk 4.2 and 4.4)
185 _grid.GetPointData().AddArray(_data)
186
187 # make the data the active scalars
188 _grid.GetPointData().SetActiveScalars("data")
189
190 # to make sphere glyphs need a sphere source
191 _sphere = vtk.vtkSphereSource()
192 _sphere.SetRadius(1.0) # set to 0.5 by default in vtk, we need it to be 1.0
193 _sphere.SetThetaResolution(5) # chunky, but will be good in large models
194 _sphere.SetPhiResolution(5)
195
196 # the spheres are 3D glyphs so set that up now
197 _glyph = vtk.vtkGlyph3D()
198 _glyph.ScalingOn()
199 _glyph.SetScaleModeToScaleByScalar() # scale by the radii scalars
200 _glyph.SetColorModeToColorByScalar() # colour by the tag scalars
201 _glyph.SetScaleFactor(1.0) # just in case
202 _glyph.SetInput(_grid)
203 _glyph.SetSource(_sphere.GetOutput()) # grab the 3D glyph to use
204 _glyph.ClampingOff() # so we even see the tiny spheres
205
206 # set up a stripper (this will speed up rendering a lot)
207 _stripper = vtk.vtkStripper()
208 _stripper.SetInput(_glyph.GetOutput())
209
210 # set up the mapper
211 _mapper = vtk.vtkPolyDataMapper()
212 _mapper.SetInput(_stripper.GetOutput())
213 _mapper.ScalarVisibilityOn()
214 _mapper.ColorByArrayComponent("data", 2)
215 _mapper.SetScalarRange(0, 1)
216
217 # set up the actor
218 _actor = vtk.vtkActor()
219 _actor.SetMapper(_mapper)
220
221 # text properties
222 _font_size = 14
223 _textProp = vtk.vtkTextProperty()
224 _textProp.SetFontSize(_font_size)
225 _textProp.SetFontFamilyToArial()
226 _textProp.BoldOff()
227 _textProp.ItalicOff()
228 _textProp.ShadowOff()
229
230 # add a title
231 _titleMapper = vtk.vtkTextMapper()
232 _title = "Example ball plot"
233 _titleMapper.SetInput(_title)
234
235 _titleProp = _titleMapper.GetTextProperty()
236 _titleProp.ShallowCopy(_textProp)
237 _titleProp.SetJustificationToCentered()
238 _titleProp.SetVerticalJustificationToTop()
239
240 # set up the text actor
241 _titleActor = vtk.vtkTextActor()
242 _titleActor.SetMapper(_titleMapper)
243 _titleActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
244 _titleActor.GetPositionCoordinate().SetValue(0.5, 0.95)
245
246 # set up the renderer and the render window
247 _ren = vtk.vtkRenderer()
248 _renWin = vtk.vtkRenderWindow()
249 _renWin.SetSize(640, 480)
250 _renWin.AddRenderer(_ren)
251
252 # add the actor
253 _ren.AddActor(_actor)
254 _ren.AddActor(_titleActor)
255
256 # render the scene
257 _iren = vtk.vtkRenderWindowInteractor()
258 _iren.SetRenderWindow(_renWin)
259 _iren.Initialize()
260 _renWin.Render()
261 _iren.Start()
262
263 # convert the render window to an image
264 _win2imgFilter = vtk.vtkWindowToImageFilter()
265 _win2imgFilter.SetInput(_renWin)
266
267 # save the image to file
268 _outWriter = vtk.vtkPNGWriter()
269 _outWriter.SetInput(_win2imgFilter.GetOutput())
270 _outWriter.SetFileName("ballPlotExample.png")
271 _outWriter.Write()
272
273 elif method == 'povray':
274 ### povray code
275
276 # load the data from the vtk file (yes, I know this is a bit dodgy)
277 import vtk
278
279 # create the reader of the file
280 _reader = vtk.vtkXMLUnstructuredGridReader()
281 _reader.SetFileName("cp_test_0.xml")
282 #_reader.SetFileName("/home/cochrane/raid2/vis4people/steffen/frame_0.xml")
283 _reader.Update()
284
285 # read the output into an unstructured grid
286 _grid = _reader.GetOutput()
287
288 _modelCentre = _grid.GetCenter()
289 _xMin, _xMax, _yMin, _yMax, _zMin, _zMax = _grid.GetBounds()
290
291 # grab the points where the data sit
292 _vtkPoints = _grid.GetPoints()
293
294 # grab the radius data for the radii of the balls
295 _vtkRadii = _grid.GetPointData().GetScalars("radius")
296
297 # grab the tag data and use for colouring the balls
298 _vtkTags = _grid.GetPointData().GetScalars("particleTag")
299
300 # work out dynamically the number of different tags so that can use this
301 # information to automatically set the scalar range for colouring
302 _numPoints = _vtkTags.GetNumberOfTuples()
303 _valueDict = {}
304 for i in range(_numPoints):
305 _tagValue = _vtkTags.GetValue(i)
306 _valueDict[_tagValue] = 1
307
308 _numTags = len(_valueDict.keys())
309
310 _tagValues = _valueDict.keys()
311 _tagValues.sort()
312
313 # count the number of tags, and make an evenly spaced array of points
314 # between zero and one, then use these as the scalars to colour by
315 _vtkScaledTags = vtk.vtkFloatArray()
316 _vtkScaledTags.SetNumberOfTuples(_numPoints)
317 _vtkScaledTags.SetNumberOfComponents(1)
318 _vtkScaledTags.SetName("tags")
319 for i in range(_numPoints):
320 _tagValue = _vtkTags.GetValue(i)
321 for j in range(_numTags):
322 if _tagValues[j] == _tagValue:
323 _vtkScaledTags.InsertTuple1(i, float(j)/float(_numTags-1))
324
325 # use vtk to generate the colour map, will have to do this myself at
326 # some point
327 _lut = vtk.vtkLookupTable()
328 _lut.Build()
329
330 _red = zeros(_numPoints, typecode=Float)
331 _green = zeros(_numPoints, typecode=Float)
332 _blue = zeros(_numPoints, typecode=Float)
333 for i in range(_numPoints):
334 _red[i], _green[i], _blue[i] = _lut.GetColor(_vtkScaledTags.GetValue(i))
335
336 # now convert the information we want (radii, colours, positions) into
337 # array objects so that I can play with them as per normal in python
338
339 # note: this is an inefficient way to do this, I can do it in one loop,
340 # but this way makes the meaning of the code a lot clearer
341
342 ### the points
343 _xData = zeros(_numPoints, typecode=Float)
344 _yData = zeros(_numPoints, typecode=Float)
345 _zData = zeros(_numPoints, typecode=Float)
346 for i in range(_numPoints):
347 _xData[i], _yData[i], _zData[i] = _vtkPoints.GetPoint(i)
348
349 ### the radii
350 _radii = zeros(_numPoints, typecode=Float)
351 for i in range(_numPoints):
352 _radii[i] = _vtkRadii.GetValue(i)
353
354 ### the tags
355 _scaledTags = zeros(_numPoints, typecode=Float)
356 _tags = zeros(_numPoints, typecode=Int)
357 for i in range(_numPoints):
358 _scaledTags[i] = _vtkScaledTags.GetValue(i)
359 _tags[i] = _vtkTags.GetValue(i)
360
361 ### generate the pov file
362
363 # open the pov file to write to
364 pov = open("ballPlotExample.pov", "w")
365
366 # the include files to add
367 pov.write("#include \"shapes.inc\"\n")
368 pov.write("#include \"colors.inc\"\n")
369
370 # the camera
371 pov.write("camera {\n")
372 pov.write(" location <%f, %f, -100>\n" %
373 (_modelCentre[0], _modelCentre[1]))
374 pov.write(" direction <0, 0, 2>\n")
375 pov.write(" up <0, 1, 0>\n")
376 pov.write(" right <4/3, 0, 0>\n")
377 pov.write(" look_at <%f, %f, %f>\n" %
378 (_modelCentre[0], _modelCentre[1], _modelCentre[2]))
379 pov.write("}\n")
380
381 # the light source
382 pov.write("light_source {\n")
383 pov.write(" <%f, %f, -300>\n" % (_modelCentre[0], _modelCentre[1]))
384 pov.write(" colour White\n")
385 pov.write("}\n")
386
387 # the spheres
388 for i in range(_numPoints):
389 pov.write("sphere { \n")
390 pov.write(" <%f, %f, %f>, %f\n" %
391 (_xData[i], _yData[i], _zData[i], _radii[i]))
392 pov.write(" pigment {\n")
393 if _tags[i] != 20:
394 pov.write(" colour red %f green %f blue %f\n" %
395 (_red[i], _green[i], _blue[i]))
396 else:
397 pov.write(" rgbt <%f, %f, %f, 0.90>\n" %
398 (_red[i], _green[i], _blue[i]))
399 pov.write(" }\n")
400 pov.write("}\n")
401
402 # put a title on it
403 pov.write("text {\n")
404 pov.write(" ttf \"timrom.ttf\" \"Example ball plot\" 0.1, 0\n")
405 pov.write(" pigment {\n")
406 pov.write(" colour White\n")
407 pov.write(" }\n")
408 pov.write(" scale <3, 3, 1>\n")
409 pov.write(" translate <%f, %f, 0>\n" %
410 (_modelCentre[0]-10, 1.2*_yMax))
411 pov.write("}\n")
412
413 # close the file
414 pov.close()
415
416 ### generate the ini file
417
418 # open the ini file to write to
419 ini = open("ballPlotExample.ini", "w")
420
421 # the output resolution
422 ini.write("Width=640\n")
423 ini.write("Height=480\n")
424
425 # anti-aliasing settings
426 ini.write("Antialias=on\n")
427
428 # generate png files
429 ini.write("Output_File_Type=N\n")
430
431 # the name of the input pov file
432 ini.write("Input_File_Name=ballPlotExample.pov\n")
433
434 # pause when done
435 ini.write("Pause_When_Done=on\n")
436
437 # close the file
438 ini.close()
439
440 # run povray on the file
441 os.system("povray ballPlotExample.ini")
442
443
444 else:
445 print "Eeek! What plotting method am I supposed to use???"
446
447 # vim: expandtab shiftwidth=4:
448

  ViewVC Help
Powered by ViewVC 1.1.26