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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26