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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26