Debian Codegraph @

packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py

raw
1 # Copyright(C) 1999-2020, 2024 National Technology & Engineering Solutions
2 # of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
3 # NTESS, the U.S. Government retains certain rights in this software.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
8 #
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # * Redistributions in binary form must reproduce the above
13 # copyright notice, this list of conditions and the following
14 # disclaimer in the documentation and/or other materials provided
15 # with the distribution.
16 #
17 # * Neither the name of NTESS nor the names of its
18 # contributors may be used to endorse or promote products derived
19 # from this software without specific prior written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33
34
35 #these settings allow us to specify a particular json format (or bccolli.py)
36 #text file to use as the phactori visualization setup file.
37 #if gUseHardwiredJsonScriptFile is None, operation is normal, but if it
38 #is set to a file string, we ignore any other parsing and use the specified
39 #file
40 global gUseHardwiredJsonScriptFile
41 gUseHardwiredJsonScriptFile = None
42 #gUseHardwiredJsonScriptFile = "myscript1.json"
43 #gUseHardwiredJsonScriptFile = "sparc_phactori_catalyst_insitu.json"
44
45 def setgUseHardwiredJsonScriptFile(inScriptFileName):
46 global gUseHardwiredJsonScriptFile
47 gUseHardwiredJsonScriptFile = inScriptFileName
48
49 global gRenderingEnabled
50 gRenderingEnabled = True
51
52 global WriteDeadCellSummaryFile
53 WriteDeadCellSummaryFile = True
54
55 global gPipeAndViewsState
56 gPipeAndViewsState = None
57
58 def SetgPipeAndViewStateForTesting(testPipe):
59 global gPipeAndViewsState
60 gPipeAndViewsState = testPipe
61
62 def GetFrameTagCounter():
63 global gPipeAndViewsState
64 if gPipeAndViewsState == None:
65 return 0
66 return gPipeAndViewsState.mFrameTagCounter
67
68 try: paraview.simple
69 except: from paraview.simple import *
70
71 from paraview import coprocessing
72
73 import vtk
74 import json
75
76 global gParaViewCatalystVersionFlag
77 #gParaViewCatalystVersionFlag = 40300
78 #gParaViewCatalystVersionFlag = 40100
79 #gParaViewCatalystVersionFlag = 50400
80 #gParaViewCatalystVersionFlag = 50502
81 #gParaViewCatalystVersionFlag = 51000
82 gParaViewCatalystVersionFlag = 51100
83
84 #attempt to use paraview.simple.GetParaViewVersion() to set version
85 try:
86 versionTuple = GetParaViewVersion()
87 gParaViewCatalystVersionFlag = versionTuple.major * 10000
88 gParaViewCatalystVersionFlag += versionTuple.minor * 100
89 except:
90 raise Exception("exception while working with paraview.simple.GetParaViewVersion()")
91
92 global gPointsString
93 if gParaViewCatalystVersionFlag <= 40100:
94 gPointsString = 'POINT_DATA'
95 gCellsString = 'CELL_DATA'
96 else:
97 gPointsString = 'POINTS'
98 gCellsString = 'CELLS'
99
100 import math
101 import sys
102 import datetime
103
104 global gBypassUserData
105 #gBypassUserData = True
106 gBypassUserData = False
107
108 global gUserDataBypassStrings
109 gUserDataBypassStrings = None
110
111 global gBypassUserDataJson
112 gBypassUserDataJson = None
113
114 global TestUserDataForBypassScriptCompletedFlag
115 TestUserDataForBypassScriptCompletedFlag = False
116
117 global gTemporaryGlobalImageTextColor
118 gTemporaryGlobalImageTextColor = [1.0, 1.0, 1.0]
119
120 global bccolli_controls
121
122 global gCameraTestMode
123 gCameraTestMode = 0
124 global gSkipWriteImageForTests
125 gSkipWriteImageForTests = False
126
127 def SetCameraTestMode(onOffSetting):
128 gCameraTestMode = onOffSetting
129
130 import os
131 if "PHACTORI_TEST_CAMERA_MODE" in os.environ:
132 if os.environ["PHACTORI_TEST_CAMERA_MODE"] == "on":
133 gSkipWriteImageForTests = True
134 gCameraTestMode = 1
135
136 def HandleJsonScriptLoadProcessZero(catalyst_script_extra_file):
137 if PhactoriDbg():
138 myDebugPrint3("HandleJsonScriptLoadProcessZero entered\n")
139 myDebugPrint3("catalyst_script_extra_file: " + \
140 str(catalyst_script_extra_file) + "\n")
141 try:
142 with open(catalyst_script_extra_file) as data_file:
143 if PhactoriDbg(100):
144 myDebugPrint3("open successful: \n")
145 visDescpJson = json.load(data_file)
146 visDescpJson = convertJsonUnicodeToStrings(visDescpJson)
147 if PhactoriDbg(100):
148 myDebugPrint3("load successful:\n" + str(visDescpJson) + "\n")
149 except:
150 #couldn't open file, use default string and also try writing out default
151 #script
152 if PhactoriDbg(100):
153 myDebugPrint3("error trying to load catalyst_script_extra_file: " + \
154 str(catalyst_script_extra_file) + "\n"
155 "using default string script\n")
156 global catalyst_script_default_string_json
157
158 import os
159 if os.path.exists(catalyst_script_extra_file):
160 if PhactoriDbg(100):
161 myDebugPrint3("script file is present in directory but could not be\n"
162 "loaded. It will not be overwritten.\n")
163 else:
164 if PhactoriDbg(100):
165 myDebugPrint3("script file is not present in directory so a default\n"
166 "version will be created.\n")
167 try:
168 ff = open(catalyst_script_extra_file, "w")
169 ff.write(catalyst_script_default_string_json)
170 ff.close()
171 except:
172 if PhactoriDbg(100):
173 myDebugPrint3("could not write out default file\n")
174
175 visDescpJson = json.loads(catalyst_script_default_string_json)
176 visDescpJson = convertJsonUnicodeToStrings(visDescpJson)
177
178 #now broadcast
179 #import pdb
180 #pdb.set_trace()
181
182 #broadcast for full multiprocess functionality
183 #color range needs no broadcast, as that will be managed when color range
184 #calculated for the next frame (process 1 will share the maxes and mins
185 #it has)
186
187 try:
188 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
189 globalController = pm.GetGlobalController()
190
191 outStr = json.dumps(visDescpJson)
192
193 numberOfValues = len(outStr)
194
195 #send size of data buffer first
196 vtkInfoBufferSizeArray = vtk.vtkIntArray()
197 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
198 vtkInfoBufferSizeArray.SetValue(0, int(numberOfValues))
199 if PhactoriDbg():
200 myDebugPrint3("trying to broadcast size of array: " + str(int(numberOfValues)) + "\n")
201 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
202 if PhactoriDbg():
203 myDebugPrint3("returned from broadcasting size of array\n")
204
205 if numberOfValues == 0:
206 if PhactoriDbg():
207 myDebugPrint3("broadcast was 0 data, so we are done\n")
208 if PhactoriDbg():
209 myDebugPrint3("HandleJsonScriptLoadProcessZero returning 2\n")
210 return None;
211
212 if PhactoriDbg():
213 myDebugPrint3("now sending data\n")
214 #now fill out data and send it
215 vtkOutArray = vtk.vtkCharArray()
216 vtkOutArray.SetNumberOfTuples(numberOfValues)
217 for jj in range(0, numberOfValues):
218 vtkOutArray.SetValue(jj, outStr[jj])
219
220 globalController.Broadcast(vtkOutArray, 0)
221
222 if PhactoriDbg():
223 myDebugPrint3("done sending data\n")
224 except:
225 #broadcast error; not really recoverable;
226 if PhactoriDbg():
227 myDebugPrint3("exception trying to broadcast\n")
228 myDebugPrint3AndException("HandleJsonScriptLoadProcessZero exception returning 4\n")
229 return
230
231 if PhactoriDbg():
232 myDebugPrint3("HandleJsonScriptLoadProcessZero returning\n")
233
234 return visDescpJson
235
236 global catalyst_script_default_string_json
237 catalyst_script_default_string_json = '' \
238 '{\n' \
239 '"camera blocks":{\n' \
240 ' "camx1":{"camera type":"camera","look direction":[-1,0,0]},\n' \
241 ' "camy1":{"camera type":"camera","look direction":[0,-1,0]},\n' \
242 ' "camz1":{"camera type":"camera","look direction":[0,0,-1]},\n' \
243 ' "camz2":{"camera type":"camera","look direction":[0,0,1]},\n' \
244 ' "camxyz1":{"camera type":"camera","look direction":[-1,-1,-1],"look at relative distance":0.8},\n' \
245 ' "camxyz2":{"camera type":"camera","look direction":[1,1,1],"look at relative distance":0.8},\n' \
246 ' "camxyz3":{"camera type":"camera","look direction":[0.7,-0.3,-1],"look at relative distance":0.8},\n' \
247 ' "camxyz4":{"camera type":"camera","look direction":[0.3,-0.3,-1],"look at relative distance":1.0},\n' \
248 ' "camz3_nosezoom3":{\n' \
249 ' "camera type":"camera",\n' \
250 ' "look direction":[0,0,1],\n' \
251 ' "look at absolute point":[0.0195, 0.0, 0.0],\n' \
252 ' "look at absolute distance":0.1\n' \
253 ' }\n' \
254 '},\n' \
255 '"representation blocks":{\n' \
256 ' "rep_velocity_x":{ "color by scalar":"velocity_1", "variable type":"element"},\n' \
257 ' "rep_velocity_y":{ "color by scalar":"velocity_2", "variable type":"element"},\n' \
258 ' "rep_velocity_z":{ "color by scalar":"velocity_3", "variable type":"element"},\n' \
259 ' "rep_pressure":{ "color by scalar":"pressure", "variable type":"element"},\n' \
260 ' "rep_density":{ "color by scalar":"density", "variable type":"element"},\n' \
261 ' "rep_temperature":{ "color by scalar":"temperature", "variable type":"element"},\n' \
262 ' "rep_Ma":{ "color by scalar":"Ma", "variable type":"element"},\n' \
263 ' "rep_pressure_0_15000":{ "color by scalar":"pressure", "variable type":"element", "color legend maximum range":[0.0, 15000.0]}\n' \
264 '},\n' \
265 '"imageset blocks":{\n' \
266 ' "is_Ma_camz2":{\n' \
267 ' "camera":"camz2",\n' \
268 ' "representation":"rep_Ma",\n' \
269 ' "image basedirectory":"CatalystOutput",\n' \
270 ' "image basename":"Ma_camz2."\n' \
271 ' },\n' \
272 ' "is_Ma_camxyz1":{\n' \
273 ' "camera":"camxyz1",\n' \
274 ' "representation":"rep_Ma",\n' \
275 ' "image basedirectory":"CatalystOutput",\n' \
276 ' "image basename":"Ma_camxyz1."\n' \
277 ' },\n' \
278 ' "is_Ma_camxyz2":{\n' \
279 ' "camera":"camxyz2",\n' \
280 ' "representation":"rep_Ma",\n' \
281 ' "image basedirectory":"CatalystOutput",\n' \
282 ' "image basename":"Ma_camxyz2."\n' \
283 ' },\n' \
284 ' "is_xyslice_minz_1_Ma":{\n' \
285 ' "camera":"camz1",\n' \
286 ' "operation":"xyslice_minz_1",\n' \
287 ' "representation":"rep_Ma",\n' \
288 ' "image basedirectory":"CatalystOutput",\n' \
289 ' "image basename":"xyslice_minz_1_Ma."\n' \
290 ' },\n' \
291 ' "is_xyslice_midz_1_Ma":{\n' \
292 ' "camera":"camz1",\n' \
293 ' "operation":"xyslice_midz_1",\n' \
294 ' "representation":"rep_Ma",\n' \
295 ' "image basedirectory":"CatalystOutput",\n' \
296 ' "image basename":"xyslice_midz_1_Ma."\n' \
297 ' },\n' \
298 ' "is_xyslice_maxz_1_Ma":{\n' \
299 ' "camera":"camz1",\n' \
300 ' "operation":"xyslice_maxz_1",\n' \
301 ' "representation":"rep_Ma",\n' \
302 ' "image basedirectory":"CatalystOutput",\n' \
303 ' "image basename":"xyslice_maxz_1_Ma."\n' \
304 ' },\n' \
305 ' "is_yzslice_minx_1_Ma":{\n' \
306 ' "camera":"camx1",\n' \
307 ' "operation":"yzslice_minx_1",\n' \
308 ' "representation":"rep_Ma",\n' \
309 ' "image basedirectory":"CatalystOutput",\n' \
310 ' "image basename":"yzslice_minx_1_Ma."\n' \
311 ' },\n' \
312 ' "is_yzslice_midx_1_Ma":{\n' \
313 ' "camera":"camx1",\n' \
314 ' "operation":"yzslice_midx_1",\n' \
315 ' "representation":"rep_Ma",\n' \
316 ' "image basedirectory":"CatalystOutput",\n' \
317 ' "image basename":"yzslice_midx_1_Ma."\n' \
318 ' },\n' \
319 ' "is_yzslice_maxx_1_Ma":{\n' \
320 ' "camera":"camx1",\n' \
321 ' "operation":"yzslice_maxx_1",\n' \
322 ' "representation":"rep_Ma",\n' \
323 ' "image basedirectory":"CatalystOutput",\n' \
324 ' "image basename":"yzslice_maxx_1_Ma."\n' \
325 ' },\n' \
326 ' "is_xzslice_miny_1_Ma":{\n' \
327 ' "camera":"camy1",\n' \
328 ' "operation":"xzslice_miny_1",\n' \
329 ' "representation":"rep_Ma",\n' \
330 ' "image basedirectory":"CatalystOutput",\n' \
331 ' "image basename":"xzslice_miny_1_Ma."\n' \
332 ' },\n' \
333 ' "is_xzslice_midy_1_Ma":{\n' \
334 ' "camera":"camy1",\n' \
335 ' "operation":"xzslice_midy_1",\n' \
336 ' "representation":"rep_Ma",\n' \
337 ' "image basedirectory":"CatalystOutput",\n' \
338 ' "image basename":"xzslice_midy_1_Ma."\n' \
339 ' },\n' \
340 ' "is_xzslice_maxy_1_Ma":{\n' \
341 ' "camera":"camy1",\n' \
342 ' "operation":"xzslice_maxy_1",\n' \
343 ' "representation":"rep_Ma",\n' \
344 ' "image basedirectory":"CatalystOutput",\n' \
345 ' "image basename":"xzslice_maxy_1_Ma."\n' \
346 ' },\n' \
347 ' "is_wall_surface_cells_Ma_1":{\n' \
348 ' "camera":"camxyz4",\n' \
349 ' "operation":"find_wall_surface_cells",\n' \
350 ' "representation":"rep_Ma",\n' \
351 ' "image basedirectory":"CatalystOutput",\n' \
352 ' "image basename":"wall_surface_cells_Ma."\n' \
353 ' },\n' \
354 ' "is_wall_surface_cells_velocity_x_1":{\n' \
355 ' "camera":"camxyz4",\n' \
356 ' "operation":"find_wall_surface_cells",\n' \
357 ' "representation":"rep_velocity_x",\n' \
358 ' "image basedirectory":"CatalystOutput",\n' \
359 ' "image basename":"wall_surface_cells_velocity_x."\n' \
360 ' },\n' \
361 ' "is_wall_surface_cells_velocity_y_1":{\n' \
362 ' "camera":"camxyz4",\n' \
363 ' "operation":"find_wall_surface_cells",\n' \
364 ' "representation":"rep_velocity_y",\n' \
365 ' "image basedirectory":"CatalystOutput",\n' \
366 ' "image basename":"wall_surface_cells_velocity_y."\n' \
367 ' },\n' \
368 ' "is_wall_surface_cells_velocity_z_1":{\n' \
369 ' "camera":"camxyz4",\n' \
370 ' "operation":"find_wall_surface_cells",\n' \
371 ' "representation":"rep_velocity_z",\n' \
372 ' "image basedirectory":"CatalystOutput",\n' \
373 ' "image basename":"wall_surface_cells_velocity_z."\n' \
374 ' },\n' \
375 ' "is_wall_surface_cells_pressure_1":{\n' \
376 ' "camera":"camxyz4",\n' \
377 ' "operation":"find_wall_surface_cells",\n' \
378 ' "representation":"rep_pressure",\n' \
379 ' "image basedirectory":"CatalystOutput",\n' \
380 ' "image basename":"wall_surface_cells_pressure."\n' \
381 ' },\n' \
382 ' "is_wall_surface_cells_density_1":{\n' \
383 ' "camera":"camxyz4",\n' \
384 ' "operation":"find_wall_surface_cells",\n' \
385 ' "representation":"rep_density",\n' \
386 ' "image basedirectory":"CatalystOutput",\n' \
387 ' "image basename":"wall_surface_cells_density."\n' \
388 ' },\n' \
389 ' "is_wall_surface_cells_temperature_1":{\n' \
390 ' "camera":"camxyz4",\n' \
391 ' "operation":"find_wall_surface_cells",\n' \
392 ' "representation":"rep_temperature",\n' \
393 ' "image basedirectory":"CatalystOutput",\n' \
394 ' "image basename":"wall_surface_cells_temperature."\n' \
395 ' },\n' \
396 ' "is_three_slices_Ma_1":{\n' \
397 ' "camera":"camxyz3",\n' \
398 ' "operation":"group_xyslice_minz_1_yzslice_midx_1_xzslice_midy_1",\n' \
399 ' "representation":"rep_Ma",\n' \
400 ' "image basedirectory":"CatalystOutput",\n' \
401 ' "image basename":"three_slices_Ma_1."\n' \
402 ' }\n' \
403 '},\n' \
404 '"operation blocks":{\n' \
405 ' "xyslice_minz_1":{\n' \
406 ' "type":"slicewithplane",\n' \
407 ' "plane normal":[0.0, 0.0, 1.0],\n' \
408 ' "relative point on plane":[0.0, 0.0, -0.499999]\n' \
409 ' },\n' \
410 ' "xyslice_midz_1":{\n' \
411 ' "type":"slicewithplane",\n' \
412 ' "plane normal":[0.0, 0.0, 1.0],\n' \
413 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
414 ' },\n' \
415 ' "xyslice_maxz_1":{\n' \
416 ' "type":"slicewithplane",\n' \
417 ' "plane normal":[0.0, 0.0, 1.0],\n' \
418 ' "relative point on plane":[0.0, 0.0, 0.499999]\n' \
419 ' },\n' \
420 ' "vtm_out_xyslice_minz_1":{\n' \
421 ' "type":"vtkdataexport",\n' \
422 ' "input":"xyslice_minz_1",\n' \
423 ' "basename":"xyslice_minz_1"\n' \
424 ' },\n' \
425 ' "vtm_out_xyslice_midz_1":{\n' \
426 ' "type":"vtkdataexport",\n' \
427 ' "input":"xyslice_midz_1",\n' \
428 ' "basename":"xyslice_midz_1"\n' \
429 ' },\n' \
430 ' "vtm_out_xyslice_maxz_1":{\n' \
431 ' "type":"vtkdataexport",\n' \
432 ' "input":"xyslice_maxz_1",\n' \
433 ' "basename":"xyslice_maxz_1"\n' \
434 ' },\n' \
435 ' "yzslice_minx_1":{\n' \
436 ' "type":"slicewithplane",\n' \
437 ' "plane normal":[1.0, 0.0, 0.0],\n' \
438 ' "relative point on plane":[-0.499999, 0.0, 0.0]\n' \
439 ' },\n' \
440 ' "yzslice_midx_1":{\n' \
441 ' "type":"slicewithplane",\n' \
442 ' "plane normal":[1.0, 0.0, 0.0],\n' \
443 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
444 ' },\n' \
445 ' "yzslice_maxx_1":{\n' \
446 ' "type":"slicewithplane",\n' \
447 ' "plane normal":[1.0, 0.0, 0.0],\n' \
448 ' "relative point on plane":[0.499999, 0.0, 0.0]\n' \
449 ' },\n' \
450 ' "vtm_out_yzslice_minx_1":{\n' \
451 ' "type":"vtkdataexport",\n' \
452 ' "input":"yzslice_minx_1",\n' \
453 ' "basename":"yzslice_minx_1"\n' \
454 ' },\n' \
455 ' "vtm_out_yzslice_midx_1":{\n' \
456 ' "type":"vtkdataexport",\n' \
457 ' "input":"yzslice_midx_1",\n' \
458 ' "basename":"yzslice_midx_1"\n' \
459 ' },\n' \
460 ' "vtm_out_yzslice_maxx_1":{\n' \
461 ' "type":"vtkdataexport",\n' \
462 ' "input":"yzslice_maxx_1",\n' \
463 ' "basename":"yzslice_maxx_1"\n' \
464 ' },\n' \
465 ' "xzslice_miny_1":{\n' \
466 ' "type":"slicewithplane",\n' \
467 ' "plane normal":[0.0, 1.0, 0.0],\n' \
468 ' "relative point on plane":[0.0, -0.499999, 0.0]\n' \
469 ' },\n' \
470 ' "xzslice_midy_1":{\n' \
471 ' "type":"slicewithplane",\n' \
472 ' "plane normal":[0.0, 1.0, 0.0],\n' \
473 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
474 ' },\n' \
475 ' "xzslice_maxy_1":{\n' \
476 ' "type":"slicewithplane",\n' \
477 ' "plane normal":[0.0, 1.0, 0.0],\n' \
478 ' "relative point on plane":[0.0, 0.499999, 0.0]\n' \
479 ' },\n' \
480 ' "vtm_out_xzslice_miny_1":{\n' \
481 ' "type":"vtkdataexport",\n' \
482 ' "input":"xzslice_miny_1",\n' \
483 ' "basename":"xzslice_miny_1"\n' \
484 ' },\n' \
485 ' "vtm_out_xzslice_midy_1":{\n' \
486 ' "type":"vtkdataexport",\n' \
487 ' "input":"xzslice_midy_1",\n' \
488 ' "basename":"xzslice_midy_1"\n' \
489 ' },\n' \
490 ' "vtm_out_xzslice_maxy_1":{\n' \
491 ' "type":"vtkdataexport",\n' \
492 ' "input":"xzslice_maxy_1",\n' \
493 ' "basename":"xzslice_maxy_1"\n' \
494 ' },\n' \
495 ' "mark_cells_for_surface_extraction":{\n' \
496 ' "type":"markcellsurfacestatus2"\n' \
497 ' },\n' \
498 ' "find_wall_surface_cells":{\n' \
499 ' "type":"threshold",\n' \
500 ' "input":"mark_cells_for_surface_extraction",\n' \
501 ' "variable scalar":"surfacestatus",\n' \
502 ' "keep between":[11,100]\n' \
503 ' },\n' \
504 ' "vtm_out_wall_surface_cells":{\n' \
505 ' "type":"vtkdataexport",\n' \
506 ' "input":"find_wall_surface_cells",\n' \
507 ' "basename":"wall_surface_cells"\n' \
508 ' },\n' \
509 ' "group_xyslice_minz_1_yzslice_midx_1_xzslice_midy_1":{\n' \
510 ' "type":"group",\n' \
511 ' "operation group list":["xyslice_minz_1", "yzslice_midx_1", "xzslice_midy_1"]\n' \
512 ' }\n' \
513 '},\n' \
514 '"text annotation blocks":{},\n' \
515 '"scatter plot blocks":{},\n' \
516 '"plot over time blocks":{},\n' \
517 '"experimental blocks":{},\n' \
518 '"onoff criteria blocks":{},\n' \
519 '"visual marker blocks":{}\n' \
520 '}\n\n'
521
522 def HandleJsonScriptLoadProcessNotZero():
523 if PhactoriDbg():
524 myDebugPrint3("HandleJsonScriptLoadProcessNotZero entered\n")
525
526 try:
527 #do broadcast (receive from process 0) to receive update data
528 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
529 globalController = pm.GetGlobalController()
530
531 if PhactoriDbg():
532 myDebugPrint3("trying to receive data buffer length\n")
533
534 #first, get size of data. If it is zero, we are done and there won't be
535 #another broadcast
536 vtkInfoBufferSizeArray = vtk.vtkIntArray()
537 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
538 #vtkInfoBufferSizeArray.SetValue(0, 0)
539 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
540 bufferLen = int(vtkInfoBufferSizeArray.GetTuple1(0))
541 if bufferLen == 0:
542 if PhactoriDbg():
543 myDebugPrint3("broadcast indicated 0 data, so we are done\n")
544 if PhactoriDbg():
545 myDebugPrint3("HandleJsonScriptLoadProcessNotZero returning 2\n")
546 return None;
547
548 if PhactoriDbg():
549 myDebugPrint3("buffer length: " + str(bufferLen) + \
550 ", now trying to receive data\n")
551 #first go round, fixed buffer length, next expandable if necessary
552 vtkOutArray = vtk.vtkCharArray()
553 vtkOutArray.SetNumberOfTuples(int(bufferLen))
554 #for jj in range(0, bufferLen):
555 # vtkOutArray.SetValue(jj, 0)
556
557 #receive broadcast of info from process 0
558 globalController.Broadcast(vtkOutArray, 0)
559 if PhactoriDbg():
560 myDebugPrint3("data received successfully\n")
561 except:
562 #broadcast error; not really recoverable;
563 if PhactoriDbg():
564 myDebugPrint3("exception trying to receive broadcast\n")
565 myDebugPrint3AndException("HandleJsonScriptLoadProcessNotZero returning 2\n")
566 return
567
568 try:
569 if PhactoriDbg():
570 myDebugPrint3("converting data to json format string\n")
571 #convert to json-format string
572 jsonCharList = []
573 for ii in range(0, bufferLen):
574 oneChar = chr(int(vtkOutArray.GetTuple1(ii)))
575 jsonCharList.append(oneChar)
576
577 #if PhactoriDbg():
578 # myDebugPrint3("done making jsonCharList:\n" + str(jsonCharList) + "\n")
579
580 jsonInString = "".join(jsonCharList)
581
582 #if PhactoriDbg():
583 # myDebugPrint3("json received from broadcast (converted to string):\n" +
584 # jsonInString + "\n")
585 if PhactoriDbg():
586 myDebugPrint3("conversion to string complete:\n")
587
588 #jsonInString2 = str(jsonInString)
589
590 #if PhactoriDbg():
591 # myDebugPrint3("(converted to string 2):\n" +
592 # jsonInString2 + "\n")
593
594 #convert json format string to python dict
595 if PhactoriDbg():
596 myDebugPrint3("about to convert back to json\n")
597 jsonIn = json.loads(jsonInString)
598 jsonIn = convertJsonUnicodeToStrings(jsonIn)
599 if PhactoriDbg():
600 myDebugPrint3("done converting back to json\n")
601
602 if PhactoriDbg():
603 myDebugPrint3("json received from broadcast (converted to dict):\n" +
604 str(jsonIn) + "\n")
605
606 except:
607 #broadcast error; not really recoverable;
608 if PhactoriDbg():
609 myDebugPrint3("exception trying to use broadcast info as json set info\n")
610 myDebugPrint3AndException("HandleJsonScriptLoadProcessNotZero returning 3\n")
611 return
612
613 if PhactoriDbg():
614 myDebugPrint3("HandleJsonScriptLoadProcessNotZero returning\n")
615
616 return jsonIn
617
618 def TestUserDataForBypassScript(datadescription):
619
620 global TestUserDataForBypassScriptCompletedFlag
621 if TestUserDataForBypassScriptCompletedFlag == True:
622 #already tested before, just return
623 return
624
625 TestUserDataForBypassScriptCompletedFlag = True
626
627 global gBypassUserData
628 if gBypassUserData:
629 #already true, just return
630 return
631
632 if PhactoriDbg(100):
633 myDebugPrint3("TestUserDataForBypassScript entered\n")
634
635 global gUseHardwiredJsonScriptFile
636 if gUseHardwiredJsonScriptFile == None:
637 fd = datadescription.GetUserData()
638
639 if fd == None:
640 if PhactoriDbg(100):
641 myDebugPrint3("no user data, no catalyst_script_extra_file\n")
642 return
643
644 sa = fd.GetAbstractArray(0)
645
646 if sa == None:
647 if PhactoriDbg(100):
648 myDebugPrint3("no user data, no catalyst_script_extra_file (2)\n")
649 return
650
651 if(sa.GetNumberOfValues() > 8):
652 catalyst_script_extra_file = sa.GetValue(8)
653 if PhactoriDbg(100):
654 myDebugPrint3(" catalyst_script_extra_file: ->" + \
655 catalyst_script_extra_file + "<-\n")
656 else:
657 if PhactoriDbg(100):
658 myDebugPrint3(" catalyst_script_extra_file: ->NONE<- (no bypass)\n")
659 return
660
661 if catalyst_script_extra_file == "":
662 if PhactoriDbg(100):
663 myDebugPrint3("empty catalyst_script_extra_file, returning\n")
664 return;
665 else:
666 catalyst_script_extra_file = gUseHardwiredJsonScriptFile
667
668 global gUserDataBypassStrings
669 global gBypassUserDataJson
670
671 if catalyst_script_extra_file == "bccolli_controls.py":
672 #due to unique name for catalyst_script_extra_file, do python import
673 #to obtain json description of visualization
674
675 if PhactoriDbg(100):
676 myDebugPrint3("using bypass script bccolli_controls.py to specify\n" \
677 "vis instead of catalyst block\n")
678 gBypassUserData = True
679 global bccolli_controls
680 import bccolli_controls
681 gUserDataBypassStrings = [
682 bccolli_controls.catalystSierraInputInJsonFormatStr,
683 "_",
684 "simple",
685 "",
686 "",
687 "0",
688 "simple.e",
689 "",
690 catalyst_script_extra_file
691 ]
692 gBypassUserDataJson = bccolli_controls.catalystSierraInputInJsonFormat
693 else:
694 #since it's not the unique name bccolli_controls, treat it as a text file
695 #containing a json format data set. Read in this json and use it as
696 #the phactori json format visualization description
697
698 if PhactoriDbg(100):
699 myDebugPrint3("using json data file: " + catalyst_script_extra_file + \
700 "\nto specify vis instead of catalyst block\n")
701 gBypassUserData = True
702
703 useEmbeddedJsonCatalystScript = False
704 if useEmbeddedJsonCatalystScript:
705 gBypassUserDataJson = GetEmbeddedJsonCatalystScript()
706 if PhactoriDbg(100):
707 myDebugPrint3("using embedded json catalyst script:\n" + str(visDescpJson) + "\n")
708 else:
709 if PhactoriDbg(100):
710 myDebugPrint3("using json script file with broadcast:\n" \
711 "name of script file: " + catalyst_script_extra_file + "\n" \
712 "about to do broadcast\n")
713 if SmartGetLocalProcessId() == 0:
714 #process zero loads json script and broadcasts
715 gBypassUserDataJson = HandleJsonScriptLoadProcessZero(catalyst_script_extra_file)
716 else:
717 #other processes receive json script
718 ###gBypassUserDataJson = HandleJsonScriptLoadProcessZero(catalyst_script_extra_file)
719 gBypassUserDataJson = HandleJsonScriptLoadProcessNotZero()
720
721 gUserDataBypassStrings = [
722 str(gBypassUserDataJson),
723 "_",
724 "simple",
725 "",
726 "",
727 "0",
728 "simple.e",
729 "",
730 catalyst_script_extra_file
731 ]
732
733 if PhactoriDbg(100):
734 myDebugPrint3("TestUserDataForBypassScript returning\n")
735
736
737 def GetBypassUserDataFlag():
738 global gBypassUserData
739 return gBypassUserData
740
741
742 #test at creation time if this global was preset (above) to bypass user data
743 #if so, read in info by importing bccolli_controls.py
744 #this is used if we want to hardwire this phactori.py file to read from
745 #bccolli_controls.py, rather than setting from the input deck
746 if gBypassUserData:
747 global bccolli_controls
748 import bccolli_controls
749 myBypassJsonString = bccolli_controls.catalystSierraInputInJsonFormatStr
750 gBypassUserDataJson = bccolli_controls.catalystSierraInputInJsonFormat
751 else:
752 myBypassJsonString = """{"camera blocks":{},"representation blocks":{},"imageset blocks":{"is1":{"color by scalar": "mixture_fraction","operation":"fooOperation"},"is2":{"color by scalar": "density_ra","operation":"contour1"}},"operation blocks":{"fooOperation":{"type":"clip","plane normal":[0.0,0.0,1.0],"relative point on plane":[0.0,0.0,0.0]},"contour1":{"type":"contour","variable scalar":"mixture_fraction","contour value":[0.7]}},"scatter plot blocks":{},"plot over time blocks":{}}"""
753
754 gUserDataBypassStrings = [
755 myBypassJsonString,
756 "_",
757 "simple",
758 "",
759 "",
760 "0",
761 "simple.e",
762 "",
763 ""
764 ]
765
766 def SetViewMapCBypassJsonString(inViewMapCString):
767 global gUserDataBypassStrings
768 gUserDataBypassStrings[0] = inViewMapCString
769 if PhactoriDbg():
770 myDebugPrint3("bypass json view map string changed to:\n" + gUserDataBypassStrings[0] + "\n")
771
772 global gEnableTemporaryExtractBlockTest
773 global gExtractBlockAList
774 global gExtractBlockBList
775 global gExtractBlockAOperationName
776 global gExtractBlockBOperationName
777 gEnableTemporaryExtractBlockTest = True
778 gExtractBlockAList = ['block_1']
779 gExtractBlockBList = ['block_2']
780 gExtractBlockAOperationName = "ReplaceWithExtractBlockA_Test"
781 gExtractBlockBOperationName = "ReplaceWithExtractBlockB_Test"
782
783 global gEnableTemporaryMultiOpViewTest
784 global gMultiOpViewTestOp2Name
785 global gMultiOpViewTestRep2Name
786 global gMultiOpViewTestImagesetName
787 gEnableTemporaryMultiOpViewTest = True
788 gMultiOpViewTestOp2Name = "ReplaceWithExtractBlockB_Test"
789 gMultiOpViewTestRep2Name = "repB"
790 gMultiOpViewTestImagesetName = "multioptestimageset"
791
792 class PhactoriPhysicalEyeAndScreenSetup:
793 """contains physical dimensions of screen (in whatever screen units)
794 and location of between-the-eyes position relative to the screen
795 in screen units--(0.0, 0.0) is right at middle of screen and distance
796 from the betwee-the-eyes position and the screen"""
797
798 def __init__(self):
799 """inScreenWidth, inScreenHeight obvious, in whatever units (feet, meters,
800 inches); inIpdInScreenUnits interpupilary distance in same units as
801 screen width and height, inEyeToScreenDistance distance from the
802 between-the-eye position to the screen, in the same units;
803 inBetweenEyeX, inBetweenEyeY where the eye is looking straight ahead
804 at the screen, with (0.0, 0.0) being the center and 0.5 * width and
805 height being at the corners"""
806
807 #we operates by setting eye at (0,0,0) and setting the screen corners
808 #appropriately
809 self.mLeftEyeScreenBottomLeft = None
810 self.mLeftEyeScreenBottomRight = None
811 self.mLeftEyeScreenTopRight = None
812 self.mRightEyeScreenBottomLeft = None
813 self.mRightEyeScreenBottomRight = None
814 self.mRightEyeScreenTopRight = None
815
816 def ParseSettingsFromJson(self, inJsn):
817 jsnGoodFlag = True
818 if 'screen size' not in inJsn:
819 jsnGoodFlag = False
820 if 'screen ipd' not in inJsn:
821 jsnGoodFlag = False
822 if 'eye to screen distance' not in inJsn:
823 jsnGoodFlag = False
824 if 'between eyes projected screen position' not in inJsn:
825 jsnGoodFlag = False
826 if jsnGoodFlag == False:
827 myDebugPrint3AndException("PhactoriPhysicalEyeAndScreenSetup:"
828 "ParseSettingsFromJson:\n"
829 "incoming json needs all of 'screen size' 'screen ipd'\n"
830 "'eye to screen distance' and "
831 "'between eyes projected screen position'\n")
832
833 screenSize = inJsn['screen size']
834 halfIpd = inJsn['screen ipd'] * 0.5
835 halfW = screenSize[0] * 0.5
836 halfH = screenSize[1] * 0.5
837 eyeToScreenDistance = inJsn['eye to screen distance']
838 eyePositionOnScreen = inJsn['between eyes projected screen position']
839 betweenEyeX = eyePositionOnScreen[0]
840 betweenEyeY = eyePositionOnScreen[1]
841 self.mLeftEyeScreenBottomLeft = [
842 -halfW + halfIpd - betweenEyeX,
843 -halfH - betweenEyeY,
844 -eyeToScreenDistance
845 ]
846 self.mLeftEyeScreenBottomRight = [
847 halfW + halfIpd - betweenEyeX,
848 -halfH - betweenEyeY,
849 -eyeToScreenDistance
850 ]
851 self.mLeftEyeScreenTopRight = [
852 halfW + halfIpd - betweenEyeX,
853 halfH - betweenEyeY,
854 -eyeToScreenDistance
855 ]
856 self.mRightEyeScreenBottomLeft = [
857 -halfW - halfIpd - betweenEyeX,
858 -halfH - betweenEyeY,
859 -eyeToScreenDistance
860 ]
861 self.mRightEyeScreenBottomRight = [
862 halfW - halfIpd - betweenEyeX,
863 -halfH - betweenEyeY,
864 -eyeToScreenDistance
865 ]
866 self.mRightEyeScreenTopRight = [
867 halfW - halfIpd - betweenEyeX,
868 halfH - betweenEyeY,
869 -eyeToScreenDistance
870 ]
871
872 def GetScreenBottomLeft(self, inLeftEyeFlag):
873 if inLeftEyeFlag:
874 return self.mLeftEyeScreenBottomLeft
875 else:
876 return self.mRightEyeScreenBottomLeft
877
878 def GetScreenBottomRight(self, inLeftEyeFlag):
879 if inLeftEyeFlag:
880 return self.mLeftEyeScreenBottomRight
881 else:
882 return self.mRightEyeScreenBottomRight
883
884 def GetScreenTopRight(self, inLeftEyeFlag):
885 if inLeftEyeFlag:
886 return self.mLeftEyeScreenTopRight
887 else:
888 return self.mRightEyeScreenTopRight
889
890 def GetEyePosition(self, inLeftEyeFlag):
891 return [0.0, 0.0, 0.0]
892
893 global g1000x1000in1920x1080desktop30inch
894 #multiply factor to get, e.g. 800x800
895 global gPixFactor
896 gPixFactor = 0.8
897 #units are centimeters
898 #myXFactor = 10.0
899 myXFactor = 1.0
900 g1000x1000in1920x1080desktop30inch = {
901 'screen size' : [33.866*myXFactor*gPixFactor, 33.866*myXFactor*gPixFactor],
902 'screen ipd' : 6.2*myXFactor,
903 'eye to screen distance': 55.88*myXFactor,
904 'between eyes projected screen position': [0.0, 0.0],
905 'ipd in model units': 6.2,
906 'virtual self size multiplier': 0.25
907 #'virtual self size multiplier': 1.0
908 }
909
910 global g1008x1792in1920x1200desktop30inch
911 screendiag1 = 30.0
912 screenaspectratio1 = 9.0/16.0
913 screendiagangle1 = math.atan(screenaspectratio1)
914 screenheight1 = screendiag1 * math.sin(screendiagangle1)
915 screenwidth1 = screendiag1 * math.cos(screendiagangle1)
916 screenxpixels1 = 1920.0
917 screenypixels1 = 1200.0
918 imagexpixels1 = 1792.0
919 imageypixels1 = 1008.0
920 imagewidth1 = (imagexpixels1 / screenxpixels1) * screenwidth1
921 imageheight1 = (imageypixels1 / screenypixels1) * screenheight1
922 #print "g1008x1792in1920x1200desktop30inch calculcations:"
923 #print "screendiag1: " + str(screendiag1)
924 #print "screenwidth1: " + str(screenwidth1)
925 #print "screenheight1: " + str(screenheight1)
926 #print "imagewidth1: " + str(imagewidth1)
927 #print "imageheight1: " + str(imageheight1)
928
929 g1008x1792in1920x1200desktop30inch = {
930 'screen size' : [imagewidth1, imageheight1],
931 'screen ipd' : 6.2,
932 'eye to screen distance': 55.88,
933 'between eyes projected screen position': [0.0, 0.0],
934 'ipd in model units': 6.2,
935 #'virtual self size multiplier': 1.0,
936 'virtual self size multiplier': 0.001,
937 'auto size 1': True,
938 'auto size 1 distance ratio': 1.0,
939 'auto size 1 view angle delta in degrees': 0.0
940 }
941
942
943 global gWiff9x16FromAudienceBig
944 #units are in feet
945 gTestFactorX = 1.0
946 gWiff9x16FromAudienceBig = {
947 'screen size' : [15.33333*gTestFactorX, 8.75*gTestFactorX],
948 'screen ipd' : 0.2034121*gTestFactorX,
949 #screen to chair back is 22.41666667 feet, knock off .4 for head width
950 'eye to screen distance': 22.0*gTestFactorX,
951 #bottom of screen 3 feet above floor
952 #eyes in front row 3.75 feet above floor
953 #bottom of screen at -4.375 feet--below center
954 'between eyes projected screen position': [0.0*gTestFactorX, (3.75 - 3.0 - 4.375)*gTestFactorX],
955 #'ipd in model units': 0.2034121*gTestFactorX,
956 'ipd in model units': 0.0,
957 #'virtual self size multiplier': 0.25
958 #'virtual self size multiplier': 0.001
959 'virtual self size multiplier': 1.0
960 }
961
962 global gWiff9x16FromAudienceSmall
963 #units are in feet
964 gWiff9x16FromAudienceSmall = {
965 'screen size' : [15.33333, 8.75],
966 'screen ipd' : 0.2034121,
967 'eye to screen distance': 22.0,
968 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
969 'ipd in model units': 0.2034121,
970 'virtual self size multiplier': 1.0
971 }
972
973 global gWiff9x16FromAudienceAutoSizeA
974 #units are in feet
975 gWiff9x16FromAudienceAutoSizeA = {
976 'screen size' : [15.33333, 8.75],
977 'screen ipd' : 0.2034121,
978 'eye to screen distance': 22.0,
979 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
980 'ipd in model units': 0.2034121,
981 #'virtual self size multiplier': 0.001,
982 'virtual self size multiplier': 0.25,
983 #'virtual self size multiplier': 2.0,
984 #'auto size 1 distance ratio': 1.0,
985 #'auto size 1 distance ratio': 0.75,
986 'auto size 1 distance ratio': 0.7,
987 #'auto size 1 distance ratio': 0.001,
988 #'auto size 1 distance ratio': 0.25,
989 'auto size 1': True,
990 'auto size 1 lock nth eye position': 1,
991 'auto size 1 view angle delta in degrees': 11.0
992 #'auto size 1 view angle delta in degrees': 9.0
993 #'auto size 1 view angle delta in degrees': 0.0
994 }
995 global gWiff9x16FromAudienceAutoSizeA2
996 #units are in feet
997 gWiff9x16FromAudienceAutoSizeA2 = {
998 'screen size' : [15.33333, 8.75],
999 'screen ipd' : 0.2034121,
1000 'eye to screen distance': 22.0,
1001 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1002 'ipd in model units': 0.2034121,
1003 #'virtual self size multiplier': 0.25,
1004 #'virtual self size multiplier': 0.5,
1005 'virtual self size multiplier': 0.4,
1006 #'auto size 1 distance ratio': 0.7,
1007 'auto size 1 distance ratio': 0.85,
1008 #'auto size 1 distance ratio': 0.35,
1009 'auto size 1': True,
1010 'auto size 1 lock nth eye position': 1,
1011 'auto size 1 view angle delta in degrees': 11.0
1012 #'auto size 1 view angle delta in degrees': 9.0
1013 #'auto size 1 view angle delta in degrees': 0.0
1014 }
1015
1016
1017 global gWiff9x16FromAudienceAutoSizeB
1018 #units are in feet
1019 gWiff9x16FromAudienceAutoSizeB = {
1020 'screen size' : [15.33333, 8.75],
1021 'screen ipd' : 0.2034121,
1022 'eye to screen distance': 22.0,
1023 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1024 'ipd in model units': 0.2034121,
1025 #'virtual self size multiplier': 1.0,
1026 #'auto size 1 distance ratio': 1.0,
1027 #'virtual self size multiplier': 0.25,
1028 #'virtual self size multiplier': 0.125,
1029 #'virtual self size multiplier': 1.0,
1030 #'virtual self size multiplier': 1.5,
1031 #'virtual self size multiplier': 2.5,
1032 'virtual self size multiplier': 1.75,
1033 #'auto size 1 distance ratio': 1.0,
1034 #'auto size 1 distance ratio': 0.5,
1035 'auto size 1 distance ratio': 0.125,
1036 'auto size 1 lock nth eye position': 1,
1037 'auto size 1': True,
1038 #'auto size 1 view angle delta in degrees': 9.0
1039 #'auto size 1 view angle delta in degrees': 9.0
1040 'auto size 1 view angle delta in degrees': 9.0
1041 #'auto size 1 view angle delta in degrees': 11.0
1042 }
1043
1044 #this one has locked eye position
1045 global gWiff9x16FromAudienceAutoSizeC
1046 #units are in feet
1047 gWiff9x16FromAudienceAutoSizeC = {
1048 'screen size' : [15.33333, 8.75],
1049 'screen ipd' : 0.2034121,
1050 'eye to screen distance': 22.0,
1051 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1052 'ipd in model units': 0.2034121,
1053 #'virtual self size multiplier': 1.0,
1054 #'auto size 1 distance ratio': 0.6,
1055 'virtual self size multiplier': 2.0,
1056 #'auto size 1 distance ratio': 0.25,
1057 #'auto size 1 distance ratio': 0.125,
1058 'auto size 1 distance ratio': 0.1,
1059 'auto size 1': True,
1060 'auto size 1 lock nth eye position': 5,
1061 'auto size 1 view angle delta in degrees': 9.0
1062 }
1063
1064 global gWiff9x16FromAudienceAutoSizeD
1065 #units are in feet
1066 gWiff9x16FromAudienceAutoSizeD = {
1067 'screen size' : [15.33333, 8.75],
1068 'screen ipd' : 0.2034121,
1069 'eye to screen distance': 22.0,
1070 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1071 'ipd in model units': 0.2034121,
1072 #'virtual self size multiplier': 1.0,
1073 #'auto size 1 distance ratio': 0.9,
1074 'virtual self size multiplier': 4.0,
1075 'auto size 1 distance ratio': 0.45,
1076 'auto size 1': True,
1077 #'auto size 1 distance ratio': 1.0,
1078 'auto size 1 lock nth eye position': 5,
1079 'auto size 1 view angle delta in degrees': 9.0
1080 }
1081
1082 global gWiff9x16StandingCloseAutoSizeE
1083 gWiff9x16StandingCloseAutoSizeE = {
1084 'screen size' : [15.33333, 8.75],
1085 'screen ipd' : 0.2034121,
1086 'eye to screen distance': 5.0,
1087 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1088 'ipd in model units': 0.2034121,
1089 #'virtual self size multiplier': 1.0,
1090 'virtual self size multiplier': 0.4,
1091 #'auto size 1 distance ratio': 1.0,
1092 'auto size 1 distance ratio': 0.4,
1093 'auto size 1': True,
1094 #'auto size 1 distance ratio': 1.0,
1095 #'auto size 1 lock nth eye position': 5,
1096 #'auto size 1 view angle delta in degrees': 0.0
1097 #'auto size 1 view angle delta in degrees': 10.0
1098 'auto size 1 view angle delta in degrees': 5.0
1099 }
1100
1101 global gWiff9x16StandingCloseAutoSizeF
1102 gWiff9x16StandingCloseAutoSizeF = {
1103 'screen size' : [15.33333, 8.75],
1104 'screen ipd' : 0.2034121,
1105 'eye to screen distance': 5.0,
1106 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1107 'ipd in model units': 0.2034121,
1108 #'virtual self size multiplier': 1.0,
1109 'virtual self size multiplier': 0.8,
1110 #'auto size 1 distance ratio': 1.0,
1111 'auto size 1 distance ratio': 0.25,
1112 'auto size 1': True,
1113 #'auto size 1 distance ratio': 1.0,
1114 #'auto size 1 lock nth eye position': 5,
1115 #'auto size 1 view angle delta in degrees': 0.0
1116 #'auto size 1 view angle delta in degrees': 10.0
1117 'auto size 1 view angle delta in degrees': 5.0
1118 }
1119
1120 global gWiff9x16feetCloseJson
1121 global gWiff9x16StandingCloseAutoSizeG
1122 gWiff9x16StandingCloseAutoSizeG = {
1123 'screen size' : [15.33333, 8.75],
1124 'screen ipd' : 0.2034121,
1125 'eye to screen distance': 5.0,
1126 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1127 'ipd in model units': 0.2034121,
1128 'virtual self size multiplier': 0.6,
1129 'auto size 1 distance ratio': 0.4,
1130 'auto size 1': True,
1131 #'auto size 1 distance ratio': 1.0,
1132 #'auto size 1 lock nth eye position': 5,
1133 'auto size 1 view angle delta in degrees': 0.0
1134 }
1135
1136 global gWiff9x16feetCloseJson
1137 #units are in feet
1138 gWiff9x16feetCloseJson = {
1139 'screen size' : [15.33333, 8.75],
1140 'screen ipd' : 0.2034121,
1141 'eye to screen distance': 5.0,
1142 #bottom of screen 3 feet above floor
1143 #eyes standing in front row 5.25 feet above floor
1144 #bottom of screen at -4.375 feet--below center
1145 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1146 'ipd in model units': 0.2034121,
1147 'virtual self size multiplier': 1.0
1148 }
1149
1150 global gWiff9x16feetCloseBigJson
1151 #units are in feet
1152 gWiff9x16feetCloseBigJson = {
1153 'screen size' : [15.33333, 8.75],
1154 'screen ipd' : 0.2034121,
1155 'eye to screen distance': 5.0,
1156 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1157 'ipd in model units': 0.2034121,
1158 'virtual self size multiplier': 0.1
1159 }
1160
1161 global gModelCoordinatesIpd
1162 global gEnableTemporaryOffAxisProjectionTest
1163
1164 gEnableTemporaryOffAxisProjectionTest = True
1165
1166 #gOaptCameraNameList = [
1167 # 'OaptDesktop1',
1168 # 'OaptWiffBigInFrontOfScreen',
1169 # 'OaptWiffBigAtScreen',
1170 # 'OaptWiffBigBehindScreen',
1171 # 'OaptWiffBigWayBehindScreen',
1172 # 'OaptWiffSmallAtScreen',
1173 # 'OaptWiffSmallInFrontOfScreen',
1174 # 'OaptWiffSmallWayInFrontOfScreen',
1175 # 'OaptWiffStandingClose',
1176 # 'OaptWiffStandingCloseBig',
1177 # 'OaptWiffStandingCloseBig2',
1178 # 'OaptWiffAutoSize1AtScreen',
1179 # 'OaptWiffAutoSize2AtScreen',
1180 # 'OaptWiffAutoSize3AtScreen',
1181 # 'OaptWiffAutoSize4AtScreen',
1182 # 'OaptWiffAutoSize5AtScreen',
1183 # 'OaptWiffAutoSize6AtScreen']
1184
1185 global gOaptPhysicalSettingsForCamera
1186 gOaptPhysicalSettingsForCamera = {
1187 'OaptDesktop1': g1008x1792in1920x1200desktop30inch,
1188 'OaptWiffBigInFrontOfScreen': gWiff9x16FromAudienceBig,
1189 'OaptWiffBigAtScreen': gWiff9x16FromAudienceBig,
1190 'OaptWiffBigBehindScreen': gWiff9x16FromAudienceBig,
1191 'OaptWiffBigWayBehindScreen': gWiff9x16FromAudienceBig,
1192 'OaptWiffSmallAtScreen': gWiff9x16FromAudienceSmall,
1193 'OaptWiffSmallInFrontOfScreen': gWiff9x16FromAudienceSmall,
1194 'OaptWiffSmallWayInFrontOfScreen': gWiff9x16FromAudienceSmall,
1195 'OaptWiffStandingClose': gWiff9x16StandingCloseAutoSizeE,
1196 'OaptWiffStandingCloseBig': gWiff9x16StandingCloseAutoSizeF,
1197 'OaptWiffStandingCloseBig2': gWiff9x16StandingCloseAutoSizeG,
1198 'OaptWiffAutoSize1AtScreen': gWiff9x16FromAudienceAutoSizeA,
1199 #'OaptWiffAutoSize1AtScreen': gWiff9x16FromAudienceBig,
1200 'OaptWiffAutoSize2AtScreen': gWiff9x16FromAudienceAutoSizeB,
1201 'OaptWiffAutoSize3AtScreen': gWiff9x16FromAudienceAutoSizeA2,
1202 'OaptWiffAutoSize4AtScreen': gWiff9x16StandingCloseAutoSizeE,
1203 'OaptWiffAutoSize5AtScreen': gWiff9x16StandingCloseAutoSizeF,
1204 'OaptWiffAutoSize6AtScreen': gWiff9x16FromAudienceAutoSizeB,
1205 }
1206
1207 #list of cameras from gOaptPhysicalSettingsForCamera
1208 global gOaptCameraNameList
1209 gOaptCameraNameList = []
1210 for key, value in gOaptPhysicalSettingsForCamera.items():
1211 gOaptCameraNameList.append(key)
1212
1213
1214 notchScaleFactor = 250.0
1215 #swap out operations from input deck for testing operations which aren't
1216 #available through the input deck syntax yet
1217
1218 #rotation about z axis
1219 global gSubstituteTestOperation1Json
1220 gSubstituteTestOperation1Json = {
1221
1222 'type': 'transform',
1223 'rotate': [0.0, 0.0, -45.0]
1224
1225 #'type': 'calculator',
1226 #'function': 'damage*damage',
1227
1228 #'scale': [notchScaleFactor, notchScaleFactor, notchScaleFactor]
1229 #'scale': [100.0, 100.0, 100.0]
1230 #'scale': [10.0, 10.0, 10.0]
1231 #'scale': [1.0, 1.0, 1.0]
1232 #'scale': [5.0, 5.0, 5.0]
1233 }
1234
1235 #z displacement isolation
1236 #rotation about x axis
1237 global gSubstituteTestOperation2Json
1238 gSubstituteTestOperation2Json = {
1239 'type': 'transform',
1240 'rotate': [-90.0, 0.0, 0.0]
1241 }
1242
1243 #z displacement isolation
1244 #global gSubstituteTestOperation2Json
1245 #gSubstituteTestOperation2Json = {
1246 # 'type': 'calculator',
1247 # 'function': '0.0*iHat + 0.0*jHat + displ__Z*kHat',
1248 # 'result array name': 'displ_',
1249 # #'result array name': 'mydisp_',
1250 #}
1251
1252 global gSubstituteTestOperation3Json
1253 gSubstituteTestOperation3Json = {
1254 'type': 'warpbyvector',
1255 'variable type': 'node',
1256 'variablename': 'displ_',
1257 #'vector name': 'mydisp_',
1258 #'scale factor': 20.0 * 10000.0,
1259 'scale': 10.0 * notchScaleFactor,
1260 }
1261
1262 #x/y displacement isolation
1263 global gSubstituteTestOperation4Json
1264 gSubstituteTestOperation4Json = {
1265 'type': 'calculator',
1266 'function': 'displ__X*iHat + displ__Y*jHat + 0.0*kHat',
1267 'result array name': 'displ_',
1268 #'result array name': 'mydisp_',
1269 }
1270
1271 global gSubstituteTestOperation5Json
1272 gSubstituteTestOperation5Json = {
1273 'type': 'warpbyvector',
1274 'variable type': 'node',
1275 'variablename': 'displ_',
1276 #'vector name': 'mydisp_',
1277 #'scale factor': 20.0 * 10000.0,
1278 'scale': 10.0 * notchScaleFactor,
1279 }
1280
1281 #all displacement exaggeration
1282 global gSubstituteTestOperation6Json
1283 gSubstituteTestOperation6Json = {
1284 'type': 'warpbyvector',
1285 'variable type': 'node',
1286 'vector name': 'displ_',
1287 #'vector name': 'mydisp_',
1288 #'scale factor': 20.0 * 10000.0,
1289 #'scale factor': 10.0 * 1000.0,
1290 'scale factor': 10.0 * notchScaleFactor,
1291 }
1292
1293 #reflect operation
1294 global gSubstituteTestOperation7Json
1295 gSubstituteTestOperation7Json = {
1296 'type': 'reflect',
1297 'plane': 'Z Min',
1298 'center': 0.0,
1299 }
1300
1301 #add pointset operation
1302 global gSubstituteTestOperation8Json
1303 gSubstituteTestOperation8Json = {
1304 'type': 'add unstructured grid',
1305 'filename': 'physicalpointsandoutline.vtu',
1306 }
1307
1308 #add group operation
1309 global gSubstituteTestOperation9Json
1310 gSubstituteTestOperation9Json = {
1311 'type': 'group',
1312 'operation group list': ["ztestslice1", "ztestslice2"]
1313 }
1314
1315
1316 global gEnableSubstituteOperationTesting
1317 gEnableSubstituteOperationTesting = True
1318 global gSubstituteOperationTestingMap
1319 gSubstituteOperationTestingMap = {
1320 "SubstituteTestOperation1": gSubstituteTestOperation1Json,
1321 "SubstituteTestOperation2": gSubstituteTestOperation2Json,
1322 "SubstituteTestOperation3": gSubstituteTestOperation3Json,
1323 "SubstituteTestOperation4": gSubstituteTestOperation4Json,
1324 "SubstituteTestOperation5": gSubstituteTestOperation5Json,
1325 "SubstituteTestOperation6": gSubstituteTestOperation6Json,
1326 "SubstituteTestOperation7": gSubstituteTestOperation7Json,
1327 "SubstituteTestOperation8": gSubstituteTestOperation8Json,
1328 "SubstituteTestOperation9": gSubstituteTestOperation9Json,
1329 }
1330
1331 global gSubstituteOperationTestingList
1332 gSubstituteOperationTestingList = []
1333 for key, value in gSubstituteOperationTestingMap.items():
1334 gSubstituteOperationTestingList.append(key)
1335
1336
1337 #swap out imagesets from input deck for testing operations which aren't
1338 #available through the input deck syntax yet
1339
1340 global gSubstituteTestImageset1Json
1341 gSubstituteTestImageset1Json = {
1342 'color by vector component': 'mydisp_Z'
1343 }
1344 global gEnableSubstituteImagesetTesting
1345 gEnableSubstituteImagesetTesting = True
1346 global gSubstituteImagesetTestingMap
1347 gSubstituteImagesetTestingMap = {
1348 "SubstituteTestImageset1": gSubstituteTestImageset1Json,
1349 #"SubstituteTestImageset2": gSubstituteTestImageset2Json,
1350 #"SubstituteTestImageset3": gSubstituteTestImageset3Json,
1351 }
1352
1353 global gSubstituteImagesetTestingList
1354 gSubstituteImagesetTestingList = []
1355 for key, value in gSubstituteImagesetTestingMap.items():
1356 gSubstituteImagesetTestingList.append(key)
1357 #-----
1358
1359 global gDefaultTimeFormatString
1360 #gDefaultTimeFormatString = "Time: %.6e"
1361 #gDefaultTimeFormatString = "Time: %f"
1362 #gDefaultTimeFormatString = "Time: %.10e"
1363 gDefaultTimeFormatString = "Time: {time:.6f}"
1364
1365 global gDefaultImageSizeX
1366 gDefaultImageSizeX = 1920
1367
1368 global gDefaultImageSizeY
1369 gDefaultImageSizeY = 1080
1370
1371 global gPixelBorderRatioXY
1372 gPixelBorderRatioXY = [0.05,0.05]
1373
1374 class PhactoriAxisSettings:
1375 def __init__(self, inWhichAxis):
1376 #0-x axis, 1-yaxis, 2-zaxis
1377 self.WhichAxis = inWhichAxis
1378 self.TitleColor = [1.0, 1.0, 1.0]
1379 self.LabelColor = [1.0, 1.0, 1.0]
1380 self.TitleFontFamily = "Arial"
1381 self.TitleFontSize = 14
1382 self.LabelFontFamily = "Arial"
1383 self.LabelFontSize = 12
1384
1385 def SetInfo1(self, inTitleColor, inLabelColor,
1386 inTitleFontFamily, inTitleFontSize,
1387 inLabelFontFamily, inLabelFontSize):
1388 self.TitleColor[0] = inTitleColor[0]
1389 self.TitleColor[1] = inTitleColor[1]
1390 self.TitleColor[2] = inTitleColor[2]
1391 self.LabelColor[0] = inLabelColor[0]
1392 self.LabelColor[1] = inLabelColor[1]
1393 self.LabelColor[2] = inLabelColor[2]
1394 if inTitleFontFamily != None:
1395 self.TitleFontFamily = inTitleFontFamily
1396 if inTitleFontSize != None:
1397 self.TitleFontSize = inTitleFontSize
1398 if inLabelFontFamily != None:
1399 self.LabelFontFamily = inLabelFontFamily
1400 if inLabelFontSize != None:
1401 self.LabelFontSize = inLabelFontSize
1402
1403 def Apply(self, ioAxesGrid):
1404 if self.WhichAxis == 0:
1405 ioAxesGrid.XTitleColor[0] = self.TitleColor[0]
1406 ioAxesGrid.XTitleColor[1] = self.TitleColor[1]
1407 ioAxesGrid.XTitleColor[2] = self.TitleColor[2]
1408 ioAxesGrid.XLabelColor[0] = self.LabelColor[0]
1409 ioAxesGrid.XLabelColor[1] = self.LabelColor[1]
1410 ioAxesGrid.XLabelColor[2] = self.LabelColor[2]
1411 ioAxesGrid.XTitleFontFamily = self.TitleFontFamily
1412 ioAxesGrid.XTitleFontSize = self.TitleFontSize
1413 ioAxesGrid.XLabelFontFamily = self.LabelFontFamily
1414 ioAxesGrid.XLabelFontSize = self.LabelFontSize
1415 elif self.WhichAxis == 1:
1416 ioAxesGrid.YTitleColor[0] = self.TitleColor[0]
1417 ioAxesGrid.YTitleColor[1] = self.TitleColor[1]
1418 ioAxesGrid.YTitleColor[2] = self.TitleColor[2]
1419 ioAxesGrid.YLabelColor[0] = self.LabelColor[0]
1420 ioAxesGrid.YLabelColor[1] = self.LabelColor[1]
1421 ioAxesGrid.YLabelColor[2] = self.LabelColor[2]
1422 ioAxesGrid.YTitleFontFamily = self.TitleFontFamily
1423 ioAxesGrid.YTitleFontSize = self.TitleFontSize
1424 ioAxesGrid.YLabelFontFamily = self.LabelFontFamily
1425 ioAxesGrid.YLabelFontSize = self.LabelFontSize
1426 else:
1427 ioAxesGrid.ZTitleColor[0] = self.TitleColor[0]
1428 ioAxesGrid.ZTitleColor[1] = self.TitleColor[1]
1429 ioAxesGrid.ZTitleColor[2] = self.TitleColor[2]
1430 ioAxesGrid.ZLabelColor[0] = self.LabelColor[0]
1431 ioAxesGrid.ZLabelColor[1] = self.LabelColor[1]
1432 ioAxesGrid.ZLabelColor[2] = self.LabelColor[2]
1433 ioAxesGrid.ZTitleFontFamily = self.TitleFontFamily
1434 ioAxesGrid.ZTitleFontSize = self.TitleFontSize
1435 ioAxesGrid.ZLabelFontFamily = self.LabelFontFamily
1436 ioAxesGrid.ZLabelFontSize = self.LabelFontSize
1437
1438 class PhactoriColorSettings:
1439 def __init__(self, inUsePlotDefaultColors = False):
1440 self.mXAxisSettings = PhactoriAxisSettings(0)
1441 self.mYAxisSettings = PhactoriAxisSettings(1)
1442 self.mZAxisSettings = PhactoriAxisSettings(2)
1443 if inUsePlotDefaultColors:
1444 self.mBackground = [1.0, 1.0, 1.0]
1445 self.mEdgeColor = [0.0, 0.0, 0.5]
1446
1447 #starting in paraview 5.0.1 this is the color
1448 #(mDiffuseColor) that affects the plot line
1449 #color
1450 #self.mDiffuseColor = [0.2, 0.2, 0.2]
1451 self.mDiffuseColor = [0.0, 0.0, 0.5]
1452
1453 self.mBackfaceDiffuseColor = [0.2, 0.2, 0.2]
1454 self.mSelectionColor = [0.2, 0.2, 0.2]
1455 self.mAmbientColor = [1.0, 1.0, 1.0]
1456 self.mTextColor = [0.2, 0.2, 0.2]
1457 self.mTimeAnnotationColor = [0.2, 0.2, 0.2]
1458 self.mAxesGridColor = [0.2, 0.2, 0.2]
1459 #self.mGridAxesInfoHasBeenInitialized = True
1460 self.mXAxisSettings.SetInfo1(
1461 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1462 self.mYAxisSettings.SetInfo1(
1463 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1464 self.mZAxisSettings.SetInfo1(
1465 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1466 self.mAxesGridShowTicks = 1
1467 self.mAxesSettingsInititlized = True
1468 else:
1469 self.mBackground = [0.31999694819562063,
1470 0.3400015259021897, 0.4299992370489052]
1471 self.mEdgeColor = [0.0, 0.0, 0.5000076295109483]
1472 self.mDiffuseColor = [1.0, 1.0, 1.0]
1473 self.mBackfaceDiffuseColor = [1.0, 1.0, 1.0]
1474 self.mAmbientColor = [1.0, 1.0, 1.0]
1475 self.mSelectionColor = [1.0, 0.0, 1.0]
1476 self.mAxesGridColor = [1.0, 1.0, 1.0]
1477 self.mTextColor = [1.0, 1.0, 1.0]
1478 self.mTimeAnnotationColor = [1.0, 1.0, 1.0]
1479 #self.mGridAxesInfoHasBeenInitialized = False
1480
1481 #weird test colors
1482 #self.mBackground = [1.0, 1.0, 1.0]
1483 #self.mEdgeColor = [1.0, 1.0, 0.0]
1484 #self.mDiffuseColor = [0.0, 1.0, 1.0]
1485 #self.mBackfaceDiffuseColor = [0.0, 1.0, 1.0]
1486 #self.mAmbientColor = [1.0, 1.0, 1.0]
1487 #self.mSelectionColor = [1.0, 0.0, 1.0]
1488 #self.mTextColor = [0.0, 1.0, 0.0]
1489
1490 def SetParaviewRvRepColors(self, inParaviewRenderView,
1491 inParaviewRep):
1492 """given a paraview Representation instance, set the colors in the
1493 paraview representation instance from this color settings
1494 instance"""
1495 inParaviewRep.EdgeColor = self.mEdgeColor
1496 inParaviewRep.DiffuseColor = self.mDiffuseColor
1497 inParaviewRep.BackfaceDiffuseColor = self.mBackfaceDiffuseColor
1498 inParaviewRep.AmbientColor = self.mAmbientColor
1499 inParaviewRep.SelectionColor = self.mSelectionColor
1500 inParaviewRenderView.Background = self.mBackground
1501 inParaviewRenderView.OrientationAxesLabelColor = \
1502 self.mTextColor
1503 if inParaviewRenderView.AxesGrid == None:
1504 PvSetupProperty(inParaviewRenderView.GetProperty("AxesGrid"))
1505 if inParaviewRenderView.AxesGrid == None:
1506 myDebugPrint3AndException("SetParaviewRvRepColors:\n"
1507 "could not get/create AxesGrid property\n")
1508 self.mXAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1509 self.mYAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1510 self.mZAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1511 inParaviewRenderView.AxesGrid.GridColor = self.mAxesGridColor
1512
1513
1514 def ParsePlotColorSettingsFromJson(self, inJsn):
1515 """given a json structure, try to grab the color settings from it
1516 using plot keys rather than 3d image keys"""
1517 textColor = self.mXAxisSettings.TitleColor
1518 axesColor = self.mAxesGridColor
1519 dataColor = self.mEdgeColor
1520 surfaceColor = self.mDiffuseColor
1521 backfaceSurfaceColor = self.mBackfaceDiffuseColor
1522 if 'text color' in inJsn:
1523 textColor = inJsn['text color']
1524 if 'axes color' in inJsn:
1525 axesColor = inJsn['axes color']
1526 if 'point color' in inJsn:
1527 dataColor = inJsn['point color']
1528 if 'line color' in inJsn:
1529 dataColor = inJsn['line color']
1530 if 'surface color' in inJsn:
1531 surfaceColor = inJsn['surface color']
1532 backfaceSurfaceColor = surfaceColor
1533 if 'backface surface color' in inJsn:
1534 backfaceSurfaceColor = inJsn['backface surface color']
1535 self.mEdgeColor = dataColor
1536 self.mDiffuseColor = surfaceColor
1537 self.mBackfaceDiffuseColor = backfaceSurfaceColor
1538 self.mAxesGridColor = axesColor
1539
1540 self.mOrientationAxesLabelColor = textColor
1541 self.mTextColor = textColor
1542 self.mXAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1543 self.mYAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1544 self.mZAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1545
1546 self.mBackground = getParameterFromBlock(inJsn,
1547 'background color', self.mBackground)
1548 self.mTimeAnnotationColor = textColor
1549
1550 def ParseColorSettingsFromJson(self, inJsn):
1551 """given a json structure, try to grab the color settings from it"""
1552 self.mDiffuseColor = getParameterFromBlock(inJsn,
1553 'surface color', self.mDiffuseColor)
1554 #if 'back surface color' is not set, use surface color
1555 self.mBackfaceDiffuseColor = getParameterFromBlock(inJsn,
1556 'back surface color', self.mDiffuseColor)
1557 self.mAmbientColor = getParameterFromBlock(inJsn,
1558 'ambient color', self.mAmbientColor)
1559 self.mSelectionColor = getParameterFromBlock(inJsn,
1560 'selection color', self.mSelectionColor)
1561 self.mTextColor = getParameterFromBlock(inJsn,
1562 'text color', self.mTextColor)
1563
1564 #for now, time annotation color will be text color
1565 self.mTimeAnnotationColor = self.mTextColor
1566
1567 self.mBackground = getParameterFromBlock(inJsn,
1568 'background color', self.mBackground)
1569 self.mEdgeColor = getParameterFromBlock(inJsn,
1570 'edge color', self.mEdgeColor)
1571
1572 self.mXAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1573 None, None, None, None)
1574 self.mYAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1575 None, None, None, None)
1576 self.mZAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1577 None, None, None, None)
1578
1579 #if 'axes color' is not set, use text color
1580 self.mAxesGrid = getParameterFromBlock(inJsn,
1581 'axes color', self.mTextColor)
1582
1583 def getParameterFromBlock(inBlock, inKey, inDefault):
1584 if inKey in inBlock:
1585 return inBlock[inKey]
1586 else:
1587 return inDefault
1588
1589
1590 global gDefaultNumCounterDigits
1591 gDefaultNumCounterDigits = 4
1592 #gDefaultNumCounterDigits = 0
1593
1594 #global localCpViews
1595 #global localCpWriters
1596 #localCpViews = None
1597 #localCpWriters = None
1598
1599 global localCoProcessorReference
1600 localCoProcessorReference = None
1601
1602 global gMaxDebugPrintOutputLines
1603 global gDebugPrintOutputLineCount
1604 #gMaxDebugPrintOutputLines = 10000000
1605 gMaxDebugPrintOutputLines = 100
1606 gDebugPrintOutputLineCount = 0
1607
1608 #hacky debug printing to file mechanism
1609 def myDebugPrint(outmsg):
1610 if PhactoriDbg():
1611 myDebugPrint3(outmsg)
1612
1613 def myDebugPrint2(outmsg):
1614 if PhactoriDbg():
1615 myDebugPrint3(outmsg)
1616 #global gMaxDebugPrintOutputLines
1617 #global gDebugPrintOutputLineCount
1618 #if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1619 # return
1620 #gDebugPrintOutputLineCount += 1
1621 ##ff = open('/space/jamauld/debug_out_dir/phactori_debug.txt', 'a+')
1622 ##fname = 'proc_' + str(SmartGetLocalProcessId()) + '_debug.txt'
1623 ##ff = open(fname, 'a+')
1624 ##ff.write(outmsg)
1625 ##ff.close()
1626 #print outmsg
1627 #if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1628 # print "gMaxDebugPrintOutputLines hit\n"
1629 #x = 1
1630
1631 global gMdp3RestrictToProcessListFlag
1632 gMdp3RestrictToProcessListFlag = True
1633 #gMdp3RestrictToProcessListFlag = False
1634 global gMdp3ProcessIdList
1635 gMdp3ProcessIdList = [0]
1636 global gMdp3UseStandardOutFlag
1637 #gMdp3UseStandardOutFlag = True
1638 gMdp3UseStandardOutFlag = False
1639 global gMdp3UseFileOutFlag
1640 #gMdp3UseFileOutFlag = False
1641 gMdp3UseFileOutFlag = True
1642 global gMdp3PriorityRestriction
1643 #gMdp3PriorityRestriction = 150
1644 #gMdp3PriorityRestriction = 50
1645 gMdp3PriorityRestriction = 500
1646
1647 #priority nominally
1648 #100-very verbose info
1649 #200-verbose info
1650 #300-info
1651 #400-debug
1652 #500-warn
1653 #600-error
1654 #1000-error, and generate exception
1655 def PhactoriDbg2(inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1656 return True
1657
1658 def PhactoriDbg(inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1659 """this is a test as to whether or not debug output should be written.
1660 The idea is that you do this test before printing debug output so that
1661 complicated strings do not need to be unnecessarily created and destroyed
1662 when not doing debug output"""
1663 global gMdp3PriorityRestriction
1664 if inPriority < gMdp3PriorityRestriction:
1665 return False
1666
1667 global gMaxDebugPrintOutputLines
1668 global gDebugPrintOutputLineCount
1669 if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1670 return False
1671
1672 if inOneProcessFlag:
1673 if inOneProcessId != SmartGetLocalProcessId():
1674 return False
1675 #for parallel compatibility, we do everything on all processes _except_
1676 #do the output--so if we test for debugging then do something that requires
1677 #mpi communication, we go ahead and do it even if this process will have
1678 #no oputput
1679 #else:
1680 # global gMdp3RestrictToProcessListFlag
1681 # if gMdp3RestrictToProcessListFlag:
1682 # global gMdp3ProcessIdList
1683 # if SmartGetLocalProcessId() not in gMdp3ProcessIdList:
1684 # return False
1685
1686 return True
1687
1688 def PrintOnProcessZero(strToPrint):
1689 """prints out string if we are on process zero; typically for warnings"""
1690 if SmartGetLocalProcessId() == 0:
1691 print(strToPrint)
1692
1693 def myDebugPrint3(inMsg, inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1694 if PhactoriDbg(inPriority, inOneProcessFlag, inOneProcessId) == False:
1695 return
1696
1697 global gMdp3RestrictToProcessListFlag
1698 if gMdp3RestrictToProcessListFlag:
1699 if SmartGetLocalProcessId() not in gMdp3ProcessIdList:
1700 #if we are only outputting some processes and this isn't one of those
1701 #we don't do any output--but we still deal with exception
1702 if inPriority >= 10000:
1703 raise Exception(inMsg)
1704 return
1705
1706 global gMaxDebugPrintOutputLines
1707 global gDebugPrintOutputLineCount
1708
1709 global gMdp3UseFileOutFlag
1710 if gMdp3UseFileOutFlag:
1711 fname = 'phdb_proc_' + str(SmartGetLocalProcessId()) + '.txt'
1712 if gDebugPrintOutputLineCount == 0:
1713 ff = open(fname, 'w')
1714 else:
1715 ff = open(fname, 'a+')
1716 ff.write(inMsg)
1717 if gDebugPrintOutputLineCount == gMaxDebugPrintOutputLines:
1718 ff.write("gMaxDebugPrintOutputLines hit\n")
1719 ff.close()
1720
1721 global gMdp3UseStandardOutFlag
1722 if gMdp3UseStandardOutFlag:
1723 print(inMsg)
1724 if gDebugPrintOutputLineCount == gMaxDebugPrintOutputLines:
1725 print("gMaxDebugPrintOutputLines hit\n")
1726
1727 gDebugPrintOutputLineCount += 1
1728
1729 if inPriority >= 10000:
1730 raise Exception(inMsg)
1731
1732 def myDebugPrint3AndException(inMsg, inOneProcessFlag = False,
1733 inOneProcessId = 0):
1734 if PhactoriDbg(10000, inOneProcessFlag, inOneProcessId):
1735 myDebugPrint3(inMsg, 10000, inOneProcessFlag, inOneProcessId)
1736
1737 def DebugPrintVtkDataArraysInfo(label, theData, priority):
1738 myDebugPrint3(label, priority)
1739 if theData == None:
1740 myDebugPrint3("None")
1741 else:
1742 numArrays = theData.GetNumberOfArrays()
1743 myDebugPrint3("number of data arrays: " + str(numArrays) + "\n", priority)
1744 for arrayIndex in range(0, numArrays):
1745 oneArray = theData.GetArray(arrayIndex)
1746 myDebugPrint3(str(arrayIndex) + ": " + str(oneArray.GetName()) + " " + str(oneArray.GetNumberOfComponents()) + "\n", priority)
1747
1748 def DebugPrintCellAndPointArrayInfo(label, pvFilter, priority):
1749 myDebugPrint3(label, priority)
1750 theData = pvFilter.PointData
1751 DebugPrintVtkDataArraysInfo("PointData:\n", theData, priority)
1752 theData = pvFilter.CellData
1753 DebugPrintVtkDataArraysInfo("CellData:\n", theData, priority)
1754
1755 #def SetCpViewsAndCpWriters(inCpViews, inCpWriters):
1756 # global localCpViews
1757 # global localCpWriters
1758 # localCpViews = inCpViews
1759 # localCpWriters = inCpWriters
1760
1761 def GetSeparatorString():
1762 global gPipeAndViewsState
1763 return gPipeAndViewsState.mSeparatorString
1764
1765 def GetCurrentOutputResultsBlockCountId():
1766 global gPipeAndViewsState
1767 retStr = str(gPipeAndViewsState.mOutputResultsBlockCountId)
1768 if PhactoriDbg():
1769 myDebugPrint3('GetCurrentOutputResultsBlockCountId: ' + retStr + '\n')
1770 return retStr
1771
1772 def GetExtraFileString():
1773 global gPipeAndViewsState
1774 return gPipeAndViewsState.mRemeshRestartTag
1775
1776 def WriteImagesForCurrentPipeAndViewsState(datadescription):
1777 gPipeAndViewsState.WriteImages(datadescription)
1778
1779 def ExportOperationsDataForCurrentPipeAndViewsState(datadescription):
1780 gPipeAndViewsState.ExportOperationsData(datadescription)
1781
1782 def SetUpCoProcessor(inCoprocessor):
1783 global localCoProcessorReference
1784 localCoProcessorReference = inCoprocessor
1785
1786 #phactori_combine_to_single_python_file_parent_1
1787 from Operation.PhactoriVectorLibrary import *
1788
1789 #phactori_combine_to_single_python_file_parent_1
1790 from Operation.PhactoriVtkCellOperations import *
1791
1792 #phactori_combine_to_single_python_file_parent_1
1793 from Operation.PhactoriParaviewMultiBlockRecursion import *
1794
1795 #phactori_combine_to_single_python_file_parent_1
1796 from Operation.PhactoriOutputFileNameAndDirectoryManager import *
1797
1798 class PhactoriRenderViewInfo:
1799 def __init__(self):
1800 self.RenderView1 = None
1801 self.DataRepresentation1 = None
1802
1803 #class PhactoriRenderViewInfo:
1804 # RenderView1 = None
1805 # DataRepresentation1 = None
1806
1807
1808 global PhactoriRenderViewInfoList
1809 PhactoriRenderViewInfoList = []
1810
1811 global currentPhactoriRenderViewInfo
1812 currentPhactoriRenderViewInfo = None
1813
1814 phactoriFilterMap = {}
1815
1816 def AddFilterToFilterMap(inFilterName, inFilter):
1817 if PhactoriDbg(100):
1818 myDebugPrint3('AddFilterToFilterMap entered\n', 100)
1819 global phactoriFilterMap
1820 phactoriFilterMap[inFilterName] = inFilter
1821 count = 0
1822 for ii in phactoriFilterMap.keys():
1823 if PhactoriDbg():
1824 myDebugPrint3(str(count) + ': ' + ii + ' : ' + str(phactoriFilterMap[ii]) + '\n')
1825 count += 1
1826 if PhactoriDbg(100):
1827 myDebugPrint3('AddFilterToFilterMap returning\n', 100)
1828
1829 def SafeColorBy(inDataRepresentation, ptOrNodeAndVarname):
1830 if True:
1831 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
1832 return
1833 if PhactoriDbg(100):
1834 myDebugPrint3("SafeColorBy entered: " + str(ptOrNodeAndVarname) + "\n")
1835 if ptOrNodeAndVarname[1] == "":
1836 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
1837 if PhactoriDbg(100):
1838 myDebugPrint3("SafeColorBy returning (no variable)\n")
1839 return
1840
1841 ptOrNode = ptOrNodeAndVarname[0]
1842 if ptOrNode == gPointsString:
1843 pointData = inDataRepresentation.PointData
1844 if pointData == None:
1845 ColorBy(inDataRepresentation, (gCellsString, ''))
1846 if PhactoriDbg(100):
1847 myDebugPrint3("SafeColorBy returning (pointData was None)\n")
1848 return
1849 if pointData.Proxy == None:
1850 ColorBy(inDataRepresentation, (gCellsString, ''))
1851 if PhactoriDbg(100):
1852 myDebugPrint3("SafeColorBy returning (pointData.Proxy was None)\n")
1853 return
1854 theFieldData = pointData.GetFieldData()
1855 if theFieldData == None:
1856 ColorBy(inDataRepresentation, (gCellsString, ''))
1857 if PhactoriDbg(100):
1858 myDebugPrint3("SafeColorBy returning (theFieldData was None)\n")
1859 return
1860 if theFieldData.Proxy == None:
1861 ColorBy(inDataRepresentation, (gCellsString, ''))
1862 if PhactoriDbg(100):
1863 myDebugPrint3("SafeColorBy returning (theFieldData.Proxy was None)\n")
1864 return
1865 if pointData.GetNumberOfArrays() <= 0:
1866 ColorBy(inDataRepresentation, (gPointsString, ''))
1867 if PhactoriDbg(100):
1868 myDebugPrint3("SafeColorBy returning (no point data arrays)\n")
1869 return
1870 onePointArray = pointData.GetArray(ptOrNodeAndVarname[1])
1871 if onePointArray == None:
1872 ColorBy(inDataRepresentation, (gPointsString, ''))
1873 if PhactoriDbg(100):
1874 myDebugPrint3("SafeColorBy returning (no point array with given name)\n")
1875 return
1876 if onePointArray.GetNumberOfTuples() <= 0:
1877 ColorBy(inDataRepresentation, (gPointsString, ''))
1878 if PhactoriDbg(100):
1879 myDebugPrint3("SafeColorBy returning (zero tuples in point data array)\n")
1880 return
1881 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
1882 if PhactoriDbg(100):
1883 myDebugPrint3("SafeColorBy returning (valid point data)\n")
1884 return
1885 else:
1886 cellData = inDataRepresentation.CellData
1887 if cellData == None:
1888 ColorBy(inDataRepresentation, (gCellsString, ''))
1889 if PhactoriDbg(100):
1890 myDebugPrint3("SafeColorBy returning (cellData was None)\n")
1891 return
1892 if cellData.Proxy == None:
1893 ColorBy(inDataRepresentation, (gCellsString, ''))
1894 if PhactoriDbg(100):
1895 myDebugPrint3("SafeColorBy returning (cellData.Proxy was None)\n")
1896 return
1897 if PhactoriDbg(100):
1898 myDebugPrint3("cellData.Proxy: " + str(cellData.Proxy) + "\n")
1899 myDebugPrint3("cellData.OutputPort: " + str(cellData.OutputPort) + "\n")
1900 myDebugPrint3("cellData.FieldData: " + str(cellData.FieldData) + "\n")
1901 if cellData.OutputPort == None:
1902 ColorBy(inDataRepresentation, (gCellsString, ''))
1903 if PhactoriDbg(100):
1904 myDebugPrint3("SafeColorBy returning (cellData.OutputPort was None)\n")
1905 return
1906 if cellData.FieldData == None:
1907 ColorBy(inDataRepresentation, (gCellsString, ''))
1908 if PhactoriDbg(100):
1909 myDebugPrint3("SafeColorBy returning (cellData.FieldData was None)\n")
1910 return
1911 dataInformation = cellData.Proxy.GetDataInformation(cellData.OutputPort)
1912 myDebugPrint3("dataInformation: " + str(dataInformation) + "\n")
1913 if dataInformation == None:
1914 ColorBy(inDataRepresentation, (gCellsString, ''))
1915 if PhactoriDbg(100):
1916 myDebugPrint3("SafeColorBy returning (dataInformation was None)\n")
1917 return
1918 theFieldData = cellData.GetFieldData()
1919 if theFieldData == None:
1920 ColorBy(inDataRepresentation, (gCellsString, ''))
1921 if PhactoriDbg(100):
1922 myDebugPrint3("SafeColorBy returning (theFieldData was None)\n")
1923 return
1924 if theFieldData.Proxy == None:
1925 ColorBy(inDataRepresentation, (gCellsString, ''))
1926 if PhactoriDbg(100):
1927 myDebugPrint3("SafeColorBy returning (theFieldData.Proxy was None)\n")
1928 return
1929 if cellData.GetNumberOfArrays() <= 0:
1930 ColorBy(inDataRepresentation, (gCellsString, ''))
1931 if PhactoriDbg(100):
1932 myDebugPrint3("SafeColorBy returning (no cell data arrays)\n")
1933 return
1934 oneCellArray = cellData.GetArray(ptOrNodeAndVarname[1])
1935 if oneCellArray == None:
1936 ColorBy(inDataRepresentation, (gCellsString, ''))
1937 if PhactoriDbg(100):
1938 myDebugPrint3("SafeColorBy returning (no cell array with given name)\n")
1939 return
1940 if oneCellArray.GetNumberOfTuples() <= 0:
1941 ColorBy(inDataRepresentation, (gCellsString, ''))
1942 if PhactoriDbg(100):
1943 myDebugPrint3("SafeColorBy returning (zero tuples in cell data array)\n")
1944 return
1945 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
1946 if PhactoriDbg(100):
1947 myDebugPrint3("SafeColorBy returning (valid cell data)\n")
1948 return
1949
1950
1951 def SetDataRepresentationToDefault(inDataRepresentation):
1952
1953 #a3_vel__PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] )
1954
1955 inDataRepresentation.SelectionPointLabelColor = [0.5, 0.5, 0.5]
1956 inDataRepresentation.SelectionPointFieldDataArrayName = 'displ'
1957 inDataRepresentation.SuppressLOD = 0
1958 global gParaViewCatalystVersionFlag
1959 if gParaViewCatalystVersionFlag < 51000:
1960 inDataRepresentation.BlockVisibility = []
1961 inDataRepresentation.BlockOpacity = {}
1962 inDataRepresentation.BlockColor = {}
1963 inDataRepresentation.Position = [0.0, 0.0, 0.0]
1964 inDataRepresentation.BackfaceRepresentation = 'Follow Frontface'
1965 inDataRepresentation.SelectionOpacity = 1.0
1966 inDataRepresentation.SelectionPointLabelShadow = 0
1967 inDataRepresentation.OrientationMode = 'Direction'
1968 inDataRepresentation.ScaleMode = 'No Data Scaling Off'
1969 inDataRepresentation.Diffuse = 1.0
1970 inDataRepresentation.SelectionUseOutline = 0
1971 inDataRepresentation.SelectionPointLabelFormat = ''
1972 #shininess alteration, 1.0 is shiny
1973 inDataRepresentation.Specular = 0.1
1974 #inDataRepresentation.Specular = 1.0
1975 inDataRepresentation.SelectionVisibility = 1
1976 inDataRepresentation.InterpolateScalarsBeforeMapping = 1
1977 #inDataRepresentation.CustomRangeActive = [0, 0, 0]
1978 inDataRepresentation.Origin = [0.0, 0.0, 0.0]
1979 inDataRepresentation.Scale = [1.0, 1.0, 1.0]
1980 inDataRepresentation.SelectionCellLabelJustification = 'Left'
1981 inDataRepresentation.DiffuseColor = [1.0, 1.0, 1.0]
1982 inDataRepresentation.SelectionCellLabelOpacity = 1.0
1983 #inDataRepresentation.Source = []
1984 inDataRepresentation.Masking = 0
1985 inDataRepresentation.Opacity = 1.0
1986 inDataRepresentation.LineWidth = 1.0
1987 inDataRepresentation.MeshVisibility = 0
1988 inDataRepresentation.Visibility = 1
1989 inDataRepresentation.SelectionCellLabelFontSize = 18
1990 inDataRepresentation.SelectionPointLabelJustification = 'Left'
1991 #inDataRepresentation.OriginalBoundsRangeActive = [0, 0, 0]
1992 inDataRepresentation.SelectionPointLabelVisibility = 0
1993 inDataRepresentation.SelectOrientationVectors = ''
1994 inDataRepresentation.BackfaceDiffuseColor = [1.0, 1.0, 1.0]
1995 inDataRepresentation.SelectionPointLabelFontFamily = 'Arial'
1996 inDataRepresentation.SelectScaleArray = ''
1997
1998 if gParaViewCatalystVersionFlag <= 40100:
1999 inDataRepresentation.ColorAttributeType = gPointsString
2000 else:
2001 inDataRepresentation.RescaleTransferFunctionToDataRange(False)
2002 SafeColorBy(inDataRepresentation, (gPointsString,''))
2003 inDataRepresentation.RescaleTransferFunctionToDataRange(False)
2004
2005 #inDataRepresentation.AxesOrigin = [0.0, 0.0, 0.0]
2006 inDataRepresentation.UserTransform = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
2007 #shininess alteration, 40.0 is shiny
2008 inDataRepresentation.SpecularPower = 100.0
2009 #inDataRepresentation.SpecularPower = 40.0
2010 inDataRepresentation.Texture = []
2011 inDataRepresentation.SelectionCellLabelShadow = 0
2012 inDataRepresentation.AmbientColor = [1.0, 1.0, 1.0]
2013 inDataRepresentation.MapScalars = 1
2014 inDataRepresentation.PointSize = 2.0
2015 inDataRepresentation.SelectionCellLabelFormat = ''
2016 inDataRepresentation.Scaling = 0
2017 inDataRepresentation.StaticMode = 0
2018 inDataRepresentation.SelectionCellLabelColor = [0.0, 1.0, 0.0]
2019 inDataRepresentation.EdgeColor = [0.0, 0.0, 0.5000076295109483]
2020 inDataRepresentation.SelectionCellLabelVisibility = 0
2021 inDataRepresentation.NonlinearSubdivisionLevel = 1
2022 inDataRepresentation.Representation = 'Surface'
2023 #inDataRepresentation.CustomRange = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
2024 #inDataRepresentation.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
2025 inDataRepresentation.Orientation = [0.0, 0.0, 0.0]
2026 #inDataRepresentation.ScalarOpacityUnitDistance = 0.8230042761351323
2027 inDataRepresentation.BackfaceOpacity = 1.0
2028 inDataRepresentation.SelectionPointLabelFontSize = 18
2029 inDataRepresentation.SelectionCellFieldDataArrayName = 'GlobalElementId'
2030 inDataRepresentation.SelectionColor = [1.0, 0.0, 1.0]
2031 inDataRepresentation.Ambient = 0.0
2032 inDataRepresentation.ScaleFactor = 0.775
2033 inDataRepresentation.BackfaceAmbientColor = [1.0, 1.0, 1.0]
2034 #inDataRepresentation.ScalarOpacityFunction = a3_vel__PiecewiseFunction
2035 inDataRepresentation.SelectMaskArray = ''
2036 inDataRepresentation.SelectionLineWidth = 2.0
2037 inDataRepresentation.Interpolation = 'Gouraud'
2038 #inDataRepresentation.SelectMapper = 'Projected tetra'
2039 inDataRepresentation.SelectionCellLabelFontFamily = 'Arial'
2040 inDataRepresentation.SelectionCellLabelItalic = 0
2041 #inDataRepresentation.ExtractedBlockIndex = 2
2042 inDataRepresentation.SelectionPointLabelOpacity = 1.0
2043 #inDataRepresentation.UseAxesOrigin = 0
2044 inDataRepresentation.Pickable = 1
2045 #inDataRepresentation.CustomBoundsActive = [0, 0, 0]
2046 inDataRepresentation.SelectionRepresentation = 'Wireframe'
2047 inDataRepresentation.SelectionPointLabelBold = 0
2048 #inDataRepresentation.ColorArrayName = 'vel'
2049 inDataRepresentation.SelectionPointLabelItalic = 0
2050 #shininess alteration, 1 is shiny
2051 if gParaViewCatalystVersionFlag <= 40100:
2052 inDataRepresentation.AllowSpecularHighlightingWithScalarColoring = 0
2053 #inDataRepresentation.AllowSpecularHighlightingWithScalarColoring = 1
2054 inDataRepresentation.SpecularColor = [1.0, 1.0, 1.0]
2055 #inDataRepresentation.LookupTable = a3_vel__PVLookupTable
2056 inDataRepresentation.SelectionPointSize = 5.0
2057 inDataRepresentation.SelectionCellLabelBold = 0
2058 inDataRepresentation.Orient = 0
2059
2060 def PvSetupProperty(prop):
2061 domain = prop.FindDomain("vtkSMProxyListDomain")
2062 domain.SetDefaultValues(prop.SMProperty, False)
2063 prop.GetParent().UpdateVTKObjects()
2064
2065 def SetAxesGridVisibility(inPvRenderView, inSetting):
2066 if inPvRenderView.AxesGrid == None:
2067 PvSetupProperty(inPvRenderView.GetProperty("AxesGrid"))
2068 if inSetting:
2069 inPvRenderView.AxesGrid.Visibility = True
2070 else:
2071 inPvRenderView.AxesGrid.Visibility = False
2072 if PhactoriDbg(100):
2073 myDebugPrint3("SetAxesGridVisibility() AxesGrid.Visibility now " + \
2074 str(inPvRenderView.AxesGrid.Visibility) + "\n", 100)
2075
2076 def AddRenderView(inPhactoriImagesetInfo, inColorSettings,
2077 ImageBaseFileName, ImageType, ImageOverwriteFlag, PixelSizeX, PixelSizeY,
2078 numCounterDigits, inIsPlotFlag):
2079
2080 global localCpViews
2081 global PhactoriRenderViewInfoList
2082 global currentPhactoriRenderViewInfo
2083 global gParaViewCatalystVersionFlag
2084
2085 if PhactoriDbg(100):
2086 myDebugPrint3("AddRenderView entered\n", 100)
2087
2088 newPhactoriRenderViewInfo = PhactoriRenderViewInfo()
2089
2090 if ImageBaseFileName == None:
2091 image_base_name = "image_" + str(len(PhactoriRenderViewInfoList))
2092 else:
2093 image_base_name = ImageBaseFileName
2094
2095 if ImageOverwriteFlag:
2096 image_base_name += "." + ImageType
2097 if PhactoriDbg():
2098 myDebugPrint3("image " + image_base_name + " will be overwritten repeatedly\n")
2099 else:
2100 image_base_name += "%t." + ImageType
2101
2102 #image_base_name = "image_" + str(len(PhactoriRenderViewInfoList)) + "_%t.png"
2103
2104 #RenderView1 = CreateCPView( CreateRenderView, image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY, localCpViews )
2105 myDebugPrint3("about to create view and representation:\n"
2106 "current active source: " + str(GetActiveSource()) + "\n")
2107
2108 global localCoProcessorReference
2109
2110 global gSharedRenderView
2111 global gSharedLineChartView
2112 if inIsPlotFlag:
2113 if gSharedLineChartView == None:
2114 #gSharedLineChartView = localCoProcessorReference.CreateView("XYChartView",
2115 # image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY)
2116 gSharedLineChartView = CreateView("XYChartView")
2117 gSharedLineChartView.ViewSize = [PixelSizeX, PixelSizeY]
2118 #gSharedLineChartView.LeftAxisRangeMinimum = -1.0
2119 #gSharedLineChartView.LeftAxisRangeMaximum = 1.0
2120 #gSharedLineChartView.BottomAxisRangeMaximum = -2.0
2121 #gSharedLineChartView.RightAxisRangeMaximum = 2.0
2122 #gSharedLineChartView.TopAxisRangeMaximum = 2.0
2123 RenderView1 = gSharedLineChartView
2124 else:
2125 if gSharedRenderView == None:
2126 #if True:
2127 #import pdb
2128 #pdb.set_trace()
2129
2130 gSharedRenderView = localCoProcessorReference.CreateView(CreateRenderView,
2131 image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY)
2132
2133 RenderView1 = gSharedRenderView
2134
2135 inPhactoriImagesetInfo.mSharedPvRenderView2 = RenderView1
2136
2137 RenderView1.add_attribute("cpNumCounterDigits", numCounterDigits)
2138 RenderView1.add_attribute("outputResultsBlockCountId", GetCurrentOutputResultsBlockCountId())
2139 RenderView1.add_attribute("associatedImagesetName",
2140 inPhactoriImagesetInfo.mName)
2141
2142 if inIsPlotFlag == False:
2143 if gParaViewCatalystVersionFlag < 50502:
2144 RenderView1.LightSpecularColor = [1.0, 1.0, 1.0]
2145 RenderView1.LightIntensity = 1.0
2146 RenderView1.UseOffscreenRendering = 0
2147 RenderView1.UseOffscreenRenderingForScreenshots = 0
2148 RenderView1.LightDiffuseColor = [1.0, 1.0, 1.0]
2149 RenderView1.LightAmbientColor = [1.0, 1.0, 1.0]
2150 RenderView1.LightType = 'HeadLight'
2151 RenderView1.LightSwitch = 0
2152 RenderView1.UseOutlineForLODRendering = 0
2153 RenderView1.KeyLightAzimuth = 10.0
2154 RenderView1.UseLight = 1
2155 RenderView1.CameraPosition = [3.681775921856809, 3.2427490288581042, 6.445486324396935]
2156 RenderView1.FillLightKFRatio = 3.0
2157 RenderView1.Background2 = [0.0, 0.0, 0.165]
2158 RenderView1.FillLightAzimuth = -10.0
2159 RenderView1.LODResolution = 0.5
2160 RenderView1.BackgroundTexture = []
2161 RenderView1.InteractionMode = '3D'
2162 RenderView1.StencilCapable = 1
2163 RenderView1.CameraFocalPoint = [0.010957598686218262, 0.0, 3.6478042602539035e-05]
2164 RenderView1.ImageReductionFactor = 2
2165 RenderView1.CameraViewAngle = 30.0
2166 RenderView1.CameraParallelScale = 2.0952221328924265
2167 RenderView1.EyeAngle = 2.0
2168 RenderView1.HeadLightKHRatio = 3.0
2169 RenderView1.StereoRender = 0
2170 RenderView1.KeyLightIntensity = 0.75
2171 RenderView1.BackLightAzimuth = 110.0
2172 RenderView1.OrientationAxesInteractivity = 0
2173 if gParaViewCatalystVersionFlag <= 40100:
2174 RenderView1.UseInteractiveRenderingForSceenshots = 0
2175 RenderView1.Background = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052]
2176 RenderView1.NonInteractiveRenderDelay = 0.0
2177 RenderView1.CenterOfRotation = [-1.9375, 0.0, 2.125]
2178 RenderView1.CameraParallelProjection = 0
2179 RenderView1.CompressorConfig = 'vtkSquirtCompressor 0 3'
2180 RenderView1.HeadLightWarmth = 0.5
2181 RenderView1.MaximumNumberOfPeels = 4
2182 RenderView1.StereoType = 'Red-Blue'
2183 RenderView1.DepthPeeling = 1
2184 RenderView1.BackLightKBRatio = 3.5
2185 if gParaViewCatalystVersionFlag <= 40100:
2186 RenderView1.StereoCapableWindow = 1
2187 RenderView1.CameraViewUp = [-0.03140411320843562, 0.899940306729304, -0.43488070317911115]
2188 RenderView1.RemoteRenderThreshold = 20.0
2189 RenderView1.CacheKey = 1.0
2190 RenderView1.UseCache = 0
2191 RenderView1.KeyLightElevation = 50.0
2192 RenderView1.CenterAxesVisibility = 0
2193 RenderView1.MaintainLuminance = 0
2194 RenderView1.StillRenderImageReductionFactor = 1
2195 RenderView1.BackLightWarmth = 0.5
2196 RenderView1.FillLightElevation = -75.0
2197 RenderView1.MultiSamples = 0
2198 RenderView1.FillLightWarmth = 0.4
2199 RenderView1.AlphaBitPlanes = 1
2200 RenderView1.OrientationAxesVisibility = 1
2201 #RenderView1.CameraClippingRange = [8.69340289149996, 31.15868708101818]
2202 RenderView1.BackLightElevation = 0.0
2203 #RenderView1.ViewTime = 0.00403844503897222
2204 #RenderView1.ViewTime = 0.0
2205 RenderView1.OrientationAxesOutlineColor = [1.0, 1.0, 1.0]
2206 RenderView1.LODThreshold = 5.0
2207 RenderView1.CollectGeometryThreshold = 100.0
2208 RenderView1.KeyLightWarmth = 0.6
2209 RenderView1.OrientationAxesLabelColor = [1.0, 1.0, 1.0]
2210 #RenderView1.OrientationAxesLabelColor = inColorSettings.mOrientationAxesLabelColor
2211 #rigid_body_impact_6_ff_e = CreateProducer( datadescription, "input" )
2212
2213 if gParaViewCatalystVersionFlag < 51000:
2214 RenderView1.UseTexturedBackground = 0
2215 RenderView1.UseGradientBackground = 0
2216
2217 SetAxesGridVisibility(RenderView1, 0)
2218
2219 SetActiveView(RenderView1)
2220
2221 if inPhactoriImagesetInfo.mPvDataRepresentation2 == None:
2222 if inIsPlotFlag:
2223 if inPhactoriImagesetInfo.m_PlotType == "PhactoriPlotOverTimeBlock":
2224 DataRepresentation1 = Show(UseIndexForXAxis = 0, XArrayName = "Time",
2225 AttributeType = "Row Data")
2226 #DataRepresentation1.AttributeType = "Row Data"
2227 if PhactoriDbg():
2228 myDebugPrint3("representation made for plot over time:\n" + \
2229 str(DataRepresentation1) + "\n")
2230 #DataRepresentation1.UseIndexForXAxis = 0
2231 #DataRepresentation1.XArrayName = "Time"
2232 elif inPhactoriImagesetInfo.m_PlotType == "PhactoriScatterPlotBlock":
2233 yvarStr = GetThresholdContourHackVariableNameString(
2234 inPhactoriImagesetInfo.m_YAxisVariableInfo)
2235 xvarStr = GetThresholdContourHackVariableNameString(
2236 inPhactoriImagesetInfo.m_XAxisVariableInfo)
2237 visvars = [yvarStr]
2238 atrtype = "Point Data"
2239 if inPhactoriImagesetInfo.m_YAxisVariableInfo.mVariableType == 'element':
2240 atrtype = "Cell Data"
2241 DataRepresentation1 = Show(inPhactoriImagesetInfo.m_producer,
2242 gSharedLineChartView, SeriesVisibility = visvars,
2243 UseIndexForXAxis = 0, XArrayName = xvarStr,
2244 AttributeType = atrtype)
2245 #DataRepresentation1.AttributeType = "Cell Data"
2246 #DataRepresentation1.XArrayName = 'carea'
2247 #DataRepresentation1.SeriesVisibility = ['vel__Magnitude (block_2)']
2248 #DataRepresentation1.SeriesVisibility = ['vel__Magnitude (Element Blocks)']
2249 if PhactoriDbg():
2250 myDebugPrint3("representation made for scatter plot:\n" + str(DataRepresentation1) + "\n")
2251 myDebugPrint3("m_producer for scatter plot:\n" + str(inPhactoriImagesetInfo.m_producer) + "\n")
2252 myDebugPrint3("rep input num points " + str(DataRepresentation1.Input.GetDataInformation().DataInformation.GetNumberOfPoints()) + "\n")
2253 myDebugPrint3("DataRepresentation1.ListProperties() " + str(DataRepresentation1.ListProperties()) + "\n")
2254 myDebugPrint3("DataRepresentation1.Input " + str(DataRepresentation1.Input) + "\n")
2255 myDebugPrint3("DataRepresentation1.AttributeType " + str(DataRepresentation1.AttributeType) + "\n")
2256 myDebugPrint3("DataRepresentation1.UseIndexForXAxis " + str(DataRepresentation1.UseIndexForXAxis) + "\n")
2257 myDebugPrint3("DataRepresentation1.Visibility " + str(DataRepresentation1.Visibility) + "\n")
2258 myDebugPrint3("DataRepresentation1.XArrayName " + str(DataRepresentation1.XArrayName) + "\n")
2259 myDebugPrint3("DataRepresentation1.SeriesVisibility " + str(DataRepresentation1.SeriesVisibility) + "\n")
2260 myDebugPrint3("DataRepresentation1.SeriesLabel " + str(DataRepresentation1.SeriesLabel) + "\n")
2261 myDebugPrint3("DataRepresentation1.SeriesColor " + str(DataRepresentation1.SeriesColor) + "\n")
2262 myDebugPrint3("DataRepresentation1.SeriesPlotCorner " + str(DataRepresentation1.SeriesPlotCorner) + "\n")
2263 myDebugPrint3("DataRepresentation1.SeriesLabelPrefix " + str(DataRepresentation1.SeriesLabelPrefix) + "\n")
2264 myDebugPrint3("DataRepresentation1.SeriesLineStyle " + str(DataRepresentation1.SeriesLineStyle) + "\n")
2265 myDebugPrint3("DataRepresentation1.SeriesLineThickness " + str(DataRepresentation1.SeriesLineThickness) + "\n")
2266 myDebugPrint3("DataRepresentation1.SeriesMarkerStyle " + str(DataRepresentation1.SeriesMarkerStyle) + "\n")
2267 for ii in range(1, len(DataRepresentation1.SeriesLineStyle), 2):
2268 DataRepresentation1.SeriesLineStyle[ii] = '0'
2269 for ii in range(1, len(DataRepresentation1.SeriesMarkerStyle), 2):
2270 DataRepresentation1.SeriesMarkerStyle[ii] = '4'
2271 else:
2272 myDebugPrint3AndException("bad m_PlotType")
2273 else:
2274 SetParaViewViewToCurrentTime(RenderView1)
2275 DataRepresentation1 = Show(GetActiveSource(), RenderView1, 'UnstructuredGridRepresentation')
2276 if PhactoriDbg():
2277 myDebugPrint3("representation made for 3d view:\n" + str(DataRepresentation1) + "\n")
2278 inPhactoriImagesetInfo.mPvDataRepresentation2 = DataRepresentation1
2279 inPhactoriImagesetInfo.mVisiblePvDataReps[0] = DataRepresentation1
2280 else:
2281 DataRepresentation1 = inPhactoriImagesetInfo.mPvDataRepresentation2
2282
2283 if PhactoriDbg():
2284 myDebugPrint3("new DataRepresentation1: " + str(DataRepresentation1) + "\n")
2285 if PhactoriDbg():
2286 myDebugPrint3("new DataRepresentation1 input: " + str(DataRepresentation1.Input) + "\n")
2287
2288 if inIsPlotFlag == False:
2289 SetDataRepresentationToDefault(DataRepresentation1)
2290 inColorSettings.SetParaviewRvRepColors(RenderView1, DataRepresentation1)
2291
2292 newPhactoriRenderViewInfo.RenderView1 = RenderView1
2293 newPhactoriRenderViewInfo.DataRepresentation1 = DataRepresentation1
2294
2295 currentPhactoriRenderViewInfo = newPhactoriRenderViewInfo
2296 PhactoriRenderViewInfoList.append(newPhactoriRenderViewInfo)
2297
2298 if len(inPhactoriImagesetInfo.mVisibleOps) > 1:
2299 savedActiveSourceA = GetActiveSource()
2300 for ii in range(1,len(inPhactoriImagesetInfo.mVisibleOps)):
2301 if inPhactoriImagesetInfo.mVisiblePvDataReps[ii] == None:
2302 SetActiveSource(inPhactoriImagesetInfo.mVisibleOps[ii].\
2303 mParaViewFilter)
2304 newPvDataRep = Show(GetActiveSource(), RenderView1, 'UnstructuredGridRepresentation')
2305 SetDataRepresentationToDefault(newPvDataRep)
2306 inPhactoriImagesetInfo.mVisiblePvDataReps[ii] = newPvDataRep
2307 if PhactoriDbg(100):
2308 myDebugPrint3("added extra newPvDataRep " + str(ii) + "\n"
2309 "newPvDataRep:\n" + str(newPvDataRep) + "\n")
2310
2311 SetActiveSource(savedActiveSourceA)
2312
2313
2314 if PhactoriDbg(100):
2315 myDebugPrint3("AddRenderView returning\n", 100)
2316
2317 def SetCameraViewExplicitly(theRenderView, EyePosition,
2318 LookAtPoint = None,
2319 ClippingRange = None,
2320 ViewUpVector = [0.0, 1.0, 0.0],
2321 inCameraViewAngle = 30.0,
2322 ViewBounds = None,
2323 inPhactoriCamera = None,
2324 inUseParallelProjection = False,
2325 inParallelScale = 1.0):
2326 "Sets the camera view explicitly by specifing the camera position " \
2327 "(EyePosition), focal point (LookAtPoint), clipping range min/man " \
2328 "(ClippingRange), up view vector (ViewUpVector) " \
2329 "example: SetCameraViewExplicitly(oneRenderView, [100.0, 90.0, 70.0], " \
2330 " [0.0, 0.0, 0.0], [5.0, 200.0], [0.0, 1.0, 0.0]) " \
2331 "If ViewBounds is None and LookAtPoint is None, the global Data Bounds " \
2332 "Will be obtained by a GetGlobalDataBoundsParallel call to put the " \
2333 "LookAtPoint in the center of the data bounds. If LookAtPoint is not " \
2334 "None, ViewBounds is not used; If LookAtPoint is None and ViewBounds " \
2335 "is not None, ViewBounds will be used and GetGlobalDataBoundsParallel " \
2336 "will not be called (to save mpi calls)"
2337 if PhactoriDbg(100):
2338 myDebugPrint3('phactori.SetCameraViewExplicitly entered\n', 100)
2339
2340 if(LookAtPoint == None):
2341 if ViewBounds == None:
2342 ViewBounds = GetGlobalDataBoundsParallel()
2343 LookAtPoint = [ (ViewBounds[1] + ViewBounds[0]) * 0.5, \
2344 (ViewBounds[3] + ViewBounds[2]) * 0.5, \
2345 (ViewBounds[5] + ViewBounds[4]) * 0.5 ]
2346
2347 if inPhactoriCamera != None:
2348 inPhactoriCamera.mOffAxisProjectionInfo.SetUpIfEnabled(theRenderView,
2349 EyePosition, LookAtPoint, ViewUpVector)
2350
2351 if(ClippingRange == None):
2352 #if PhactoriDbg(100):
2353 # myDebugPrint3('ClippingRange was None, must calculate\n', 100)
2354 xdelta = LookAtPoint[0] - EyePosition[0]
2355 ydelta = LookAtPoint[1] - EyePosition[1]
2356 zdelta = LookAtPoint[2] - EyePosition[2]
2357 delta = math.sqrt(xdelta*xdelta + ydelta*ydelta + zdelta*zdelta)
2358 #ClippingRange = [delta * 0.05, delta * 2.0]
2359 ClippingRange = [delta * 0.01, delta * 10.0]
2360
2361 #ClippingRange[0] *= 0.01
2362 #if PhactoriDbg(100):
2363 # myDebugPrint3("CameraClippingRange (A): " + str(ClippingRange) + "\n")
2364 # myDebugPrint3("CameraClippingRange (B): " + str(theRenderView.CameraClippingRange) + "\n")
2365 #ClippingRange[0] *= 1000.0
2366 #ClippingRange[1] *= 0.1
2367
2368 theRenderView.CameraPosition = EyePosition
2369 theRenderView.CameraFocalPoint = LookAtPoint
2370
2371 if inUseParallelProjection == True:
2372 theRenderView.CameraParallelProjection = 1
2373 theRenderView.CameraParallelScale = inParallelScale
2374 if PhactoriDbg(100):
2375 myDebugPrint3('CameraParallelProjection: 1\n')
2376 myDebugPrint3('CameraParallelScale: ' + str(inParallelScale) + '\n')
2377 else:
2378 theRenderView.CameraParallelProjection = 0
2379 #theRenderView.CameraClippingRange = ClippingRange
2380
2381 theRenderView.CameraViewUp = ViewUpVector
2382 theRenderView.CenterOfRotation = LookAtPoint
2383 theRenderView.CameraViewAngle = inCameraViewAngle
2384
2385 if PhactoriDbg(100):
2386 myDebugPrint3("CameraPosition: " + str(EyePosition) + "\n"
2387 "CameraFocalPoint: " + str(LookAtPoint) + "\n"
2388 "CameraClippingRange (C): " + str(ClippingRange) + "\n"
2389 "CameraViewUp: " + str(ViewUpVector) + "\n"
2390 "CenterOfRotation: " + str(LookAtPoint) + "\n"
2391 "CameraViewAngle: " + str(inCameraViewAngle) + "\n")
2392
2393 if PhactoriDbg(100):
2394 myDebugPrint3('phactori.SetCameraViewExplicitly returning\n', 100)
2395
2396 #could do this different/better
2397 def CheckForParallelVector(vec1, vec2):
2398 if PhactoriDbg():
2399 myDebugPrint3("CheckForParallelVector: " + str(vec1) + " " + str(vec2) + "\n")
2400 maxcmpnt = 0
2401 maxval = abs(vec1[0])
2402 if(abs(vec1[1]) > maxval):
2403 maxcmpnt = 1
2404 maxval = abs(vec1[1])
2405 if(abs(vec1[2]) > maxval):
2406 maxcmpnt = 2
2407 maxval = abs(vec1[2])
2408 if PhactoriDbg():
2409 myDebugPrint3("maxcmpnt for vec1: " + str(maxcmpnt) + "\n")
2410 if vec2[maxcmpnt] == 0.0:
2411 if PhactoriDbg():
2412 myDebugPrint3("vec2 is zero there, not parallel\n")
2413 return False
2414 ratio = vec1[maxcmpnt] / vec2[maxcmpnt]
2415 for ii in [0,1,2]:
2416 tt1 = vec2[ii] * ratio
2417 if(abs(tt1 - vec1[ii]) > 0.000001):
2418 if PhactoriDbg():
2419 myDebugPrint3("vec2 component " + str(ii) + " is different, not parallel\n")
2420 return False
2421 if PhactoriDbg():
2422 myDebugPrint3("same ratio between vectors, parallel\n")
2423 return True
2424
2425 #given a bounds in the form [xmin, xmax, ymin, ymax, zmin, zmax], return the
2426 # maximum dimension out of all those (max of xmax-xmin, ymax-ymin, and
2427 # zmax-zmin)
2428 def GetMaximumDimensionFromBounds(inBounds):
2429 maxDim = inBounds[1] - inBounds[0]
2430 testDim = inBounds[3] - inBounds[2]
2431 if(testDim > maxDim):
2432 maxDim = testDim
2433 testDim = inBounds[5] - inBounds[4]
2434 if(testDim > maxDim):
2435 maxDim = testDim
2436 return maxDim
2437
2438 def SetCameraLookAtPointAndLookDirection(inParaViewRenderView, \
2439 inLookDirection, \
2440 inImageSettings, \
2441 inFocalPoint = None, \
2442 inEyeToFocalPointDistance = None, \
2443 inEyePositionFactor = 1.0, \
2444 inViewUp=[0.0,1.0,0.0], \
2445 inCameraViewAngle = 30.0, \
2446 inViewBounds = None,
2447 inPhactoriCamera = None):
2448 """Set up camera with position, look at point, and positioning factor
2449
2450 Sets the current camera view by looking at a focal point (inFocalPoint)
2451 along a specified vector (inLookDirection). The distance from the focal
2452 point is set using twice the largest of the data bounding box dimensions
2453 multiplied by inEyePositionFactor. To see the whole of the data,
2454 inEyePositionFactor can be about 1.0, although trying different values
2455 will give you different filling of the screen and 'zooming' into the focal
2456 point, while values greater than 1.0 can be used to zoom out, possibly to
2457 bring the entire dataset into the image. If inEyeToFocalPointDistance is
2458 something other than None, this distance will be used instead of the
2459 bounding box of the data. If inFocalPoint is None, then
2460 the center of the data bounds will be used as a focal point. inViewBounds
2461 allows calling routine to pass along data bounds or other viewing bounds
2462 which are used to calculate the viewing distance from the focal point
2463 and the focal point if they are not supplied. If inEyeToFocalPointDistance
2464 is not None and inFocalPoint is not None, than inViewBounds will not
2465 be used and the global data bounds will not be obtained.
2466 example: SetCameraLookAtPointAndLookDirection([5.0, 4.0, 3.0],
2467 [1.0, 1.0, 1.0], 1.5, [0.0, 1.0, 0.0])
2468 """
2469
2470 if PhactoriDbg(100):
2471 myDebugPrint3("SetCameraLookAtPointAndLookDirection entered\n", 100);
2472
2473 #check for look view up same as look direction
2474 #need to do better check here
2475 if CheckForParallelVector(inLookDirection, inViewUp):
2476 inViewUp = [0.0, 0.0, 1.0]
2477 if CheckForParallelVector(inLookDirection, inViewUp):
2478 inViewUp = [0.0, 1.0, 0.0]
2479
2480 #find maximum data dimension, then multiply by inEyePositionFactor
2481 if(inFocalPoint == None):
2482 if inViewBounds == None:
2483 inViewBounds = GetGlobalDataBoundsParallel()
2484 inFocalPoint = [ (inViewBounds[1] + inViewBounds[0]) * 0.5, \
2485 (inViewBounds[3] + inViewBounds[2]) * 0.5, \
2486 (inViewBounds[5] + inViewBounds[4]) * 0.5 ]
2487
2488 if inEyeToFocalPointDistance != None:
2489 eyeToFocalPointDistance = inEyeToFocalPointDistance
2490 else:
2491 if inViewBounds == None:
2492 inViewBounds = GetGlobalDataBoundsParallel()
2493 #eyeToFocalPointDistance = GetMaximumDimensionFromBounds(inViewBounds)
2494 #eyeToFocalPointDistance *= inEyePositionFactor
2495 eyeToFocalPointDistance = CalcRelativeCameraDistance2(inFocalPoint,
2496 inLookDirection, inViewUp, inCameraViewAngle, inImageSettings,
2497 inViewBounds)
2498 eyeToFocalPointDistance *= inEyePositionFactor
2499
2500
2501 if PhactoriDbg():
2502 myDebugPrint3(" eyeToFocalPointDistance: " + str(eyeToFocalPointDistance) + "\n")
2503 if PhactoriDbg():
2504 myDebugPrint3(" inFocalPoint: " + str(inFocalPoint) + "\n")
2505 if PhactoriDbg():
2506 myDebugPrint3(" inLookDirection: " + str(inLookDirection) + "\n")
2507 if PhactoriDbg():
2508 myDebugPrint3(" inEyePositionFactor: " + str(inEyePositionFactor) + "\n")
2509 if PhactoriDbg():
2510 myDebugPrint3(" inViewUp: " + str(inViewUp) + "\n")
2511
2512 #find eye position based on focal point, distance to eye point, and look direction
2513 xx = inLookDirection[0]
2514 yy = inLookDirection[1]
2515 zz = inLookDirection[2]
2516 lookDirectionMagnitude = math.sqrt(xx*xx + yy*yy + zz*zz)
2517 #lookDirectionMagnitude = 1.0
2518 if PhactoriDbg():
2519 myDebugPrint3(" lookDirectionMagnitude: " + str(lookDirectionMagnitude) + "\n")
2520 xx = xx / lookDirectionMagnitude
2521 yy = yy / lookDirectionMagnitude
2522 zz = zz / lookDirectionMagnitude
2523 eyePosition = [inFocalPoint[0] - xx * eyeToFocalPointDistance, \
2524 inFocalPoint[1] - yy * eyeToFocalPointDistance, \
2525 inFocalPoint[2] - zz * eyeToFocalPointDistance]
2526 if PhactoriDbg():
2527 myDebugPrint3(" eyePosition: " + str(eyePosition) + "\n")
2528
2529
2530 useNewClippingCalc = True
2531 if useNewClippingCalc:
2532 eyeToFocalPointDist = vecDistance(eyePosition, inFocalPoint)
2533 clippingRange = [0.01 * eyeToFocalPointDist, 100.0 * eyeToFocalPointDist]
2534 else:
2535 clippingRange = [0.01 * lookDirectionMagnitude, 100.0 * lookDirectionMagnitude]
2536
2537 localUseParallelProjection = False
2538 localParallelScale = 1.0
2539 if inPhactoriCamera != None:
2540 if inPhactoriCamera.mUseParallelProjection:
2541 localUseParallelProjection = True
2542 if inPhactoriCamera.mParallelScaleAbsoluteOrRelative == 0:
2543 localParallelScale = inPhactoriCamera.mParallelScale
2544 if PhactoriDbg():
2545 myDebugPrint3("absolute parallel scale: " + \
2546 str(localParallelScale) + "\n")
2547 else:
2548 if inViewBounds == None:
2549 inViewBounds = GetGlobalDataBoundsParallel()
2550 #for relative case, we are using the diagonal of the
2551 #bounding box to determine the parallel scale; other algorithms might
2552 #be to use the longest bounding box side, or determine all bounding
2553 #box corner positions from camera position and use the greatest
2554 #vertical or horizontal extent of those points
2555 dimx = inViewBounds[1] - inViewBounds[0]
2556 dimy = inViewBounds[3] - inViewBounds[2]
2557 dimz = inViewBounds[5] - inViewBounds[4]
2558 maxbbdim = math.sqrt(dimx*dimx + dimy*dimy + dimz*dimz)
2559 localParallelScale = maxbbdim * 0.5 * 1.05
2560 localParallelScale *= inPhactoriCamera.mParallelScale
2561 if PhactoriDbg():
2562 myDebugPrint3("relative parallel scale: " + \
2563 str(localParallelScale) + "\n")
2564
2565 SetCameraViewExplicitly(inParaViewRenderView, eyePosition, inFocalPoint,
2566 clippingRange, inViewUp, inCameraViewAngle, inViewBounds,
2567 inPhactoriCamera, localUseParallelProjection, localParallelScale)
2568
2569 if inPhactoriCamera != None:
2570 inPhactoriCamera.HandleLockingOption(eyePosition, inFocalPoint)
2571
2572 if PhactoriDbg(100):
2573 myDebugPrint3("SetCameraLookAtPointAndLookDirection returning\n", 100)
2574
2575
2576 global gLocalProcessId
2577 gLocalProcessId = -1
2578 global gNumberOfProcesses
2579 gNumberOfProcesses = -1
2580
2581 def SmartGetLocalProcessId():
2582 global gLocalProcessId
2583 #myDebugPrint3("SmartGetLocalProcessId entered\n", 100)
2584 if gLocalProcessId != -1:
2585 #print "gLocalProcessId already known: " + str(gLocalProcessId)
2586 return gLocalProcessId
2587 global gNumberOfProcesses
2588 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
2589 globalController = pm.GetGlobalController()
2590 gLocalProcessId = globalController.GetLocalProcessId()
2591 gNumberOfProcesses = globalController.GetNumberOfProcesses()
2592 #print "gLocalProcessId found: " + str(gLocalProcessId)
2593 #myDebugPrint3("exiting SmartGetLocalProcessId\n")
2594 return gLocalProcessId
2595
2596 def SmartGetNumberOfProcesses():
2597 global gNumberOfProcesses
2598 if gNumberOfProcesses != -1:
2599 return gNumberOfProcesses
2600 global gLocalProcessId
2601 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
2602 globalController = pm.GetGlobalController()
2603 gLocalProcessId = globalController.GetLocalProcessId()
2604 gNumberOfProcesses = globalController.GetNumberOfProcesses()
2605 return gNumberOfProcesses
2606
2607 #phactori_combine_to_single_python_file_parent_1
2608 from Operation.PhactoriDataArtifactMetaDataControl import *
2609
2610 global gPhactoriDataArtifactTracker
2611 gPhactoriDataArtifactTracker = None
2612
2613 def GetGlobalDataArtifactTracker():
2614 global gPhactoriDataArtifactTracker
2615 if gPhactoriDataArtifactTracker == None:
2616 gPhactoriDataArtifactTracker = PhactoriDataArtifactMetaDataControl(
2617 SmartGetLocalProcessId(), SmartGetNumberOfProcesses())
2618 return gPhactoriDataArtifactTracker
2619
2620 def UseMPIToFillInSharedListNPerProcess(
2621 inThisProcVtkArray, inCountPerProc, outVtkArray, vtkArrayTypeIndex):
2622 """given a list of N values on each process fill in on each process a list
2623 which contains all the entries from each process
2624 (i.e. it is N * number_of_processes long)
2625 will work on either vtkDoubleArray types or vtkIntArray types, with
2626 vtkArrayTypeIndex = 0 for vtkIntArray types and 1 for vtkDoubleArray
2627 types"""
2628
2629 mypid = SmartGetLocalProcessId()
2630
2631 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
2632 globalController = pm.GetGlobalController()
2633 #gLocalProcessId = globalController.GetLocalProcessId()
2634 numproc = globalController.GetNumberOfProcesses()
2635 if PhactoriDbg(100):
2636 myDebugPrint3("mypid: " + str(mypid) + " numproc: " + str(numproc) + \
2637 " count: " + str(inCountPerProc) + "\n")
2638
2639 outVtkArray.SetNumberOfValues(inCountPerProc * numproc)
2640
2641 if vtkArrayTypeIndex == 0:
2642 fromRemoteProcList = vtk.vtkIntArray()
2643 else:
2644 fromRemoteProcList = vtk.vtkDoubleArray()
2645
2646 for ii in range(0,numproc):
2647 prndx = ii * inCountPerProc
2648 if ii == mypid:
2649 globalController.Broadcast(inThisProcVtkArray, ii)
2650 for jj in range(0,inCountPerProc):
2651 outVtkArray.SetValue(prndx + jj, inThisProcVtkArray.GetValue(jj))
2652 else:
2653 fromRemoteProcList.SetNumberOfValues(inCountPerProc)
2654 globalController.Broadcast(fromRemoteProcList, ii)
2655 for jj in range(0,inCountPerProc):
2656 outVtkArray.SetValue(prndx + jj, fromRemoteProcList.GetValue(jj))
2657
2658 return mypid, numproc
2659
2660
2661 def UseMPIToCreateSharedPointList(inGlobalNodeIds, inPointXyzs):
2662 """used during finding nearest point (and distance) between one set of points
2663 and others. The idea is that we have a fairly small set of points from one
2664 data source (e.g. one block of a multiblock or a decimated set of points)
2665 which we share to all processors (using mpi broadcast), and then each
2666 processor finds the nearest point and distance from all of it's points
2667 to the shared set, and then we use mpi reduce to find which is the
2668 closest and where it is. This function takes the portion of the shared
2669 points which are local to this processor (obtained via
2670 PhactoriOperationBlock.MakeListOfAllPoints1()) and does mpi broadcasting
2671 to share with all the other processors and also to construct the whole
2672 list of shared points locally
2673 returns a vtkIntArray and vtkDoubleArray, where the int array is the list
2674 of all the global node ids and the double array is all the geometric
2675 pointx (stored x1y1z1x2y2z2...)
2676 inGlobalNodeIds is vtkIntArray
2677 inPointXyzs is vtkDoubleArray"""
2678 mypid = SmartGetLocalProcessId()
2679
2680 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
2681 globalController = pm.GetGlobalController()
2682 #gLocalProcessId = globalController.GetLocalProcessId()
2683 numproc = globalController.GetNumberOfProcesses()
2684 if PhactoriDbg(100):
2685 myDebugPrint3("mypid: " + str(mypid) + " numproc: " + str(numproc) + "\n")
2686
2687 #first let everyone know how many points are in each process
2688
2689 numptsInEachProc = vtk.vtkIntArray()
2690 numptsInEachProc.SetNumberOfValues(numproc)
2691 for ii in range(0,numproc):
2692 numptsInEachProc.SetValue(ii, 0)
2693 numptsInEachProc.SetValue(mypid, inGlobalNodeIds.GetNumberOfValues())
2694 #if PhactoriDbg(100):
2695 # myDebugPrint3("numptsInEachProc before AllReduce:\n")
2696 # for ii in range(0,numproc):
2697 # myDebugPrint3(str(ii) + ": " + str(numptsInEachProc.GetValue(ii)) + "\n")
2698
2699 glbNumptsInEachProc = vtk.vtkIntArray()
2700 glbNumptsInEachProc.SetNumberOfValues(numproc)
2701
2702 globalController.AllReduce(numptsInEachProc, glbNumptsInEachProc, 0)
2703 #if PhactoriDbg(100):
2704 # myDebugPrint3("numptsInEachProc after AllReduce:\n" + str(glbNumptsInEachProc) + "\n")
2705 # for ii in range(0,numproc):
2706 # myDebugPrint3(str(ii) + ": " + str(glbNumptsInEachProc.GetValue(ii)) + "\n")
2707
2708 #now go through and create the shared points list
2709 #first the node ids
2710 glbNodeIdList = vtk.vtkIntArray()
2711 shareIdList = vtk.vtkIntArray()
2712 for ii in range(0,numproc):
2713 numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)
2714 #if PhactoriDbg(100):
2715 # myDebugPrint3("doing broadcast for process " + str(ii) + ": numpts: " + str(numPtsFromProcii) + "\n")
2716 if ii == mypid:
2717 #if PhactoriDbg(100):
2718 #myDebugPrint3("I am this process, broadcasting to everyone\n")
2719 if(numPtsFromProcii > 0):
2720 globalController.Broadcast(inGlobalNodeIds, ii)
2721 for jj in range(0,numPtsFromProcii):
2722 glbNodeIdList.InsertNextValue(inGlobalNodeIds.GetValue(jj))
2723 else:
2724 #if PhactoriDbg(100):
2725 # myDebugPrint3("I am not this process, receiving broadcast from this process: " + str(numPtsFromProcii) + "\n")
2726 if(numPtsFromProcii > 0):
2727 shareIdList.SetNumberOfValues(numPtsFromProcii)
2728 #if PhactoriDbg(100):
2729 # myDebugPrint3("returned from broadcast call 2\n")
2730 globalController.Broadcast(shareIdList, ii)
2731 for jj in range(0,numPtsFromProcii):
2732 glbNodeIdList.InsertNextValue(shareIdList.GetValue(jj))
2733 #if PhactoriDbg(100):
2734 # myDebugPrint3("glbNodeIdList after broadcasts:\n")
2735 # for ii in range(0, glbNodeIdList.GetNumberOfValues()):
2736 # myDebugPrint3(str(ii) + ": " + str(glbNodeIdList.GetValue(ii)) + "\n")
2737
2738 #now the xyz geometry values for the nodes
2739 glbXyzList = vtk.vtkDoubleArray()
2740 shareXyzList = vtk.vtkDoubleArray()
2741 for ii in range(0,numproc):
2742 numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)
2743 #if PhactoriDbg(100):
2744 # myDebugPrint3("doing broadcast for process " + str(ii) + ": numpts: " + str(numPtsFromProcii) + "\n")
2745 if ii == mypid:
2746 #if PhactoriDbg(100):
2747 #myDebugPrint3("I am this process, broadcasting to everyone\n")
2748 if(numPtsFromProcii > 0):
2749 globalController.Broadcast(inPointXyzs, ii)
2750 for jj in range(0,numPtsFromProcii*3):
2751 glbXyzList.InsertNextValue(inPointXyzs.GetValue(jj))
2752 else:
2753 #if PhactoriDbg(100):
2754 # myDebugPrint3("I am not this process, receiving broadcast from this process: " + str(numPtsFromProcii) + "\n")
2755 if(numPtsFromProcii > 0):
2756 shareXyzList.SetNumberOfValues(numPtsFromProcii*3)
2757 #if PhactoriDbg(100):
2758 # myDebugPrint3("returned from broadcast call 2\n")
2759 globalController.Broadcast(shareXyzList, ii)
2760 for jj in range(0,numPtsFromProcii*3):
2761 glbXyzList.InsertNextValue(shareXyzList.GetValue(jj))
2762 #if PhactoriDbg(100):
2763 # myDebugPrint3("glbNodeIdList after broadcasts:\n")
2764 # for ii in range(0, glbXyzList.GetNumberOfValues()):
2765 # myDebugPrint3(str(ii) + ": " + str(glbXyzList.GetValue(ii)) + "\n")
2766
2767 return glbNodeIdList, glbXyzList
2768
2769
2770 def GetGlobalDataBoundsParallel(inFromWhichSource = None):
2771 if PhactoriDbg(100):
2772 myDebugPrint3("GetGlobalDataBoundsParallel entered\n", 100)
2773 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
2774 globalController = pm.GetGlobalController()
2775
2776 if inFromWhichSource == None:
2777 localDataBounds = GetActiveSource().GetDataInformation().GetBounds()
2778 else:
2779 localDataBounds = inFromWhichSource.GetDataInformation().GetBounds()
2780
2781 # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
2782 localarray = vtk.vtkDoubleArray()
2783 localarray.SetNumberOfTuples(6)
2784 localarray.SetValue(0, -localDataBounds[0])
2785 localarray.SetValue(1, localDataBounds[1])
2786 localarray.SetValue(2, -localDataBounds[2])
2787 localarray.SetValue(3, localDataBounds[3])
2788 localarray.SetValue(4, -localDataBounds[4])
2789 localarray.SetValue(5, localDataBounds[5])
2790 globalarray = vtk.vtkDoubleArray()
2791 globalarray.SetNumberOfTuples(6)
2792 globalController.AllReduce(localarray, globalarray, 0)
2793 globalDataBounds = [ \
2794 -globalarray.GetTuple1(0), globalarray.GetTuple1(1), \
2795 -globalarray.GetTuple1(2), globalarray.GetTuple1(3), \
2796 -globalarray.GetTuple1(4), globalarray.GetTuple1(5) \
2797 ]
2798 if PhactoriDbg():
2799 myDebugPrint3("localDataBounds: " + str(localDataBounds) + \
2800 "\nglobalDataBounds: " + str(globalDataBounds) + "\n")
2801 if PhactoriDbg(100):
2802 myDebugPrint3("GetGlobalDataBoundsParallel returning\n", 100)
2803 return globalDataBounds
2804
2805
2806 global gDefaultLookatDistanceDatasizeRelative
2807 gDefaultLookatDistanceDatasizeRelative = 1.0
2808 global gDefaultLookatDistanceDatasizeRelativeMultiplier
2809 gDefaultLookatDistanceDatasizeRelativeMultiplier = 4.0
2810
2811 def GetXyzForNodeOrElementParallelOneBlock(inInputCsData, inIdIsNode,
2812 inGlobalId, outXyz):
2813 """check for inGlobalId and set outXyz if present
2814
2815 utility function called by GetXyzForNodeOrElementParallelRecurse1, this
2816 takes one unstructured grid as input, and sees if it has the node or element
2817 with id inGlobalId. If it does, the method sets outXyz to the geometric
2818 location of the node (xyz) or center of the element bounding box (xyz) and
2819 returns true, otherwise it returns false without changing outXyz
2820 """
2821
2822 if PhactoriDbg(100):
2823 myDebugPrint3('GetXyzForNodeOrElementParallelOneBlock entered\n', 100)
2824
2825 globalIdArray = None
2826 if inIdIsNode:
2827 ptOrElData = inInputCsData.GetPointData()
2828 globalIdArray = ptOrElData.GetArray('GlobalNodeId')
2829 else:
2830 ptOrElData = inInputCsData.GetCellData()
2831 globalIdArray = ptOrElData.GetArray('GlobalElementId')
2832
2833 if globalIdArray == None:
2834 if PhactoriDbg():
2835 myDebugPrint3(" this process/block has no Global Node or Element Id array to contain " + str(inGlobalId) + "\n")
2836 return False
2837
2838 numTuples = globalIdArray.GetNumberOfTuples()
2839 thisProcessHasTheId = False
2840 idIndex = -1
2841 for ii in range(0, numTuples):
2842 #myDebugPrint3(" testing " + str(ii) + " against " + str(inGlobalNodeId) + "\n")
2843 #myDebugPrint3(" type array: " + str(type(globalNodeIdArray)) + " type ii:" + str(type(ii)) + "\n")
2844 vv = globalIdArray.GetTuple1(ii)
2845 if vv == inGlobalId:
2846 thisProcessHasTheId = True
2847 idIndex = ii
2848 break
2849
2850 if not thisProcessHasTheId:
2851 if PhactoriDbg():
2852 myDebugPrint3(" this process/block doesn't contain id" + \
2853 str(inGlobalId) + "\n")
2854 return False
2855
2856 if PhactoriDbg():
2857 myDebugPrint3(" this process/block contains id " + str(inGlobalId) + "\n")
2858
2859 if inIdIsNode:
2860 pointsArray = inInputCsData.GetPoints()
2861 numPoints = pointsArray.GetNumberOfPoints()
2862 if idIndex >= numPoints:
2863 if PhactoriDbg():
2864 myDebugPrint3(" this process/block has problem with index, setting xyz 0\n")
2865 outXyz[0] = 0.0
2866 outXyz[1] = 0.0
2867 outXyz[2] = 0.0
2868 return False
2869
2870 thePoint = pointsArray.GetPoint(idIndex, outXyz)
2871
2872 if PhactoriDbg():
2873 myDebugPrint3(" outXyz set to: " + str(outXyz) + "\n")
2874 return True
2875 else:
2876 myBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
2877 #myCells = inInputCsData.GetCells()
2878 #oneCell = myCells.GetCell(idIndex)
2879 oneCell = inInputCsData.GetCell(idIndex)
2880 oneCell.GetBounds(myBounds)
2881 #myCells.GetCellBounds(idIndex, myBounds)
2882 #ptOrElData.GetCellBounds(idIndex, myBounds)
2883 outXyz[0] = 0.5 * (myBounds[0] + myBounds[1])
2884 outXyz[1] = 0.5 * (myBounds[2] + myBounds[3])
2885 outXyz[2] = 0.5 * (myBounds[4] + myBounds[5])
2886 #xmin, xmax, ymin, ymax, zmin, zmax = myCells.GetCellBounds(idIndex)
2887 #outXyz[0] = 0.5 * (xmin + xmax)
2888 #outXyz[1] = 0.5 * (ymin + ymax)
2889 #outXyz[2] = 0.5 * (zmin + zmax)
2890 return True
2891
2892 def GetXyzForNodeOrElementParallelRecurse1(inInputCsData,
2893 inIdIsNode, inGlobalId, outXyz):
2894 """utility function used by GetXyzForNodeOrElementParallel
2895
2896 looking for inGlobalId to potentially set outXyz, recurses through
2897 structure and calls GetXyzForNodeOrElementParallelOneBlock() on
2898 unstructured grids to do the real work of checking for the id and setting
2899 outXyz
2900 """
2901
2902 #myDebugPrint3('GetXyzForNodeOrElementParallelRecurse1 entered\n', 100)
2903
2904 icsdClassname = inInputCsData.GetClassName()
2905 #if PhactoriDbg(100):
2906 # myDebugPrint3("icsdClassname 1: " + str(icsdClassname) + "\n")
2907 if icsdClassname == "vtkMultiBlockDataSet" or \
2908 icsdClassname == "vtkExodusIIMultiBlockDataSet":
2909 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
2910 numBlocks = inInputCsData.GetNumberOfBlocks()
2911 for ii in range(0, numBlocks):
2912 oneBlock = inInputCsData.GetBlock(ii)
2913 if(oneBlock != None):
2914 found = GetXyzForNodeOrElementParallelRecurse1(
2915 oneBlock, inIdIsNode, inGlobalId, outXyz)
2916 if found:
2917 return True
2918 else:
2919 found = GetXyzForNodeOrElementParallelOneBlock(
2920 inInputCsData, inIdIsNode, inGlobalId, outXyz)
2921 if found:
2922 return True
2923
2924 return False
2925
2926 def GetXyzForMinOrMaxVariable(inParaViewSource, inMinFlag,
2927 inVariableInfo, outXyz):
2928 """find the xyz location of the maximum or minimum value of the variable
2929 in the argument (at node or in element), recurses as necessary, does
2930 MPI, calls GetXyzForNodeOrElementParallel once id is found"""
2931
2932 if PhactoriDbg(100):
2933 myDebugPrint3("GetXyzForMinOrMaxVariable entered\n"
2934 " inMinFlag: " + str(inMinFlag) + "\n"
2935 " variable name: " + str(inVariableInfo.mVariableName) + "\n", 100)
2936
2937 #for now, disable output while doing parallel min/max search
2938 global gMdp3PriorityRestriction
2939 save_gMdp3PriorityRestriction = gMdp3PriorityRestriction
2940 gMdp3PriorityRestriction = 500
2941
2942 #get min or max node or element id for variable
2943 csData = inParaViewSource.GetClientSideObject().GetOutputDataObject(0)
2944 FindNodeOrElementIdForMinMax(csData, inVariableInfo)
2945 if inMinFlag:
2946 theId = inVariableInfo.mStats.mMinId
2947 else:
2948 theId = inVariableInfo.mStats.mMaxId
2949
2950 #decide if it is a node or an element
2951 detectResult = inVariableInfo.DetectVariableType(
2952 inParaViewSource, True)
2953 if detectResult == False:
2954 #myDebugPrint3AndException(
2955 # "GetXyzForMinOrMaxVariable:\n"
2956 # "could not detect element or node type\n"
2957 # "variable name is: " + inVariableInfo.mVariableName + "\n")
2958 myDebugPrint3(
2959 "GetXyzForMinOrMaxVariable:\n"
2960 "could not detect element or node type (using 0 0 0)\n"
2961 "variable name is: " + inVariableInfo.mVariableName + "\n")
2962 outXyz[0] = 0.0
2963 outXyz[1] = 0.0
2964 outXyz[2] = 0.0
2965 localProcessCouldDetect = False
2966 if inVariableInfo.mVariableType == 'node':
2967 nodeFlag = True
2968 localProcessCouldDetect = True
2969 elif inVariableInfo.mVariableType == 'element':
2970 nodeFlag = False
2971 localProcessCouldDetect = True
2972 else:
2973 myDebugPrint3AndException(
2974 "GetXyzForMinOrMaxVariable:\n"
2975 "variable is not element or node type\n"
2976 "variable name is: " + inVariableInfo.mVariableName + "\n")
2977
2978 #get xyz location of node or element
2979 GetXyzForNodeOrElementParallel(inParaViewSource, nodeFlag, theId, outXyz,
2980 localProcessCouldDetect)
2981
2982 #restore output setting
2983 gMdp3PriorityRestriction = save_gMdp3PriorityRestriction
2984
2985 if PhactoriDbg(100):
2986 myDebugPrint3(
2987 "outXyz: " + str(outXyz) + "\n"
2988 "GetXyzForMinOrMaxVariable returning\n", 100)
2989
2990
2991 def GetXyzForNodeOrElementParallel(inParaViewSource,
2992 inIdIsNode, inGlobalId, outXyz, inLocalProcessCouldDetect = True):
2993 """given a node or element id, get item xyz location in parallel
2994
2995 Recurses through all structures on all processes to find a node or element,
2996 then does allreduce to spread that information to all processes (for use in
2997 pointing cameras at a node or element with a given id; if this process has
2998 the element with the
2999 id inGlobalId, it will set outXyz and send the info around, if this
3000 process does not have inGlobalId, it will expect to receive the proper
3001 outXyz from the node that does.
3002 """
3003
3004 if PhactoriDbg(100):
3005 myDebugPrint3("GetXyzForNodeOrElementParallel entered, IdIsNode: " + str(inIdIsNode) + " id: " + str(inGlobalId) + "\n", 100)
3006
3007 #theSource = GetCurrentSource()
3008 #theSource = GetActiveSource()
3009 if inLocalProcessCouldDetect:
3010 csData = inParaViewSource.GetClientSideObject().GetOutputDataObject(0)
3011
3012 found = GetXyzForNodeOrElementParallelRecurse1(csData,
3013 inIdIsNode, inGlobalId, outXyz)
3014 else:
3015 found = False
3016
3017
3018 if found:
3019 if PhactoriDbg():
3020 myDebugPrint3(" this process has GlobalId " + str(inGlobalId) + ", doing broadcast of info\n")
3021 UseReduceToSpreadValues(outXyz)
3022 #GetXyzForNodeParallelBroadcast(thePointArrays, outXyz)
3023 else:
3024 if PhactoriDbg():
3025 myDebugPrint3(" this process does not have GlobalId " + str(inGlobalId) + ", doing receive of info\n")
3026 UseReduceToSpreadValues(outXyz)
3027 #GetXyzForNodeParallelReceive(outXyz)
3028
3029 if PhactoriDbg(100):
3030 myDebugPrint3("GetXyzForNodeOrElementParallel returning\n", 100)
3031
3032 def CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
3033 inTestPoint, inFov = 30.0):
3034 """finds point X which is along the inNormCameraDir vector starting from
3035 point inFocalPoint, such that inTestPoint is visible. This is
3036 accomplished by taking a parametric value ss to move the camera position
3037 out from the focal point (along the inNormCameraDir vector) and finding
3038 the parametric value such that the angle between the vector from the
3039 camera position to the focal point and the camera position to inTestPoint
3040 is equal to (or greater than) the camera field of view. The parametric
3041 value is returned. We use the law of sines. assumes inNormCameraDir
3042 is normalized and pointing in the direction from inFocalPoint towards
3043 where we want to place the camera (the opposite of the look direction)"""
3044
3045 #angle between camera-to-focal point vector and camera-to-testpoint vector
3046 #is equal to half the camera fOV. Call this angle AA.
3047 #The side opposite this angle has length equal to the distance between
3048 #the focal point and the test point. Call this distance aa. We also
3049 #know the angle between the focal point-to-camera vector and the focal
3050 #point-to-testpoint vector (because both vectors point in a fixed direction).
3051 #call this angle BB. The remaining angle is CC, and CC = 180 - (AA + BB).
3052 #thus the length of the parametric side is determined by the law of sines,
3053 #cc/sin(CC) = aa/sin(AA) (cc is the length of interest),
3054 #so cc = aa * sin(CC) / sin(AA)
3055 #
3056
3057 #need to set to 1/2 fov
3058 if PhactoriDbg(100):
3059 myDebugPrint3("CalcRelativeCameraDistance2_AA entered\n");
3060 if PhactoriDbg(100):
3061 myDebugPrint3("inTestPoint: " + str(inTestPoint) + "\n");
3062 angleAA = math.radians(inFov * 0.5)
3063 if PhactoriDbg(100):
3064 myDebugPrint3("angleAA: " + str(math.degrees(angleAA)) + "\n");
3065
3066 focalToTestVec = [inTestPoint[0] - inFocalPoint[0],
3067 inTestPoint[1] - inFocalPoint[1],
3068 inTestPoint[2] - inFocalPoint[2]]
3069 aa = vecMagnitude(focalToTestVec)
3070 if aa == 0.0:
3071 return 0.0
3072 focalToTestVec[0] /= aa
3073 focalToTestVec[1] /= aa
3074 focalToTestVec[2] /= aa
3075 if PhactoriDbg(100):
3076 myDebugPrint3("inNormCameraDir: " + str(inNormCameraDir) + "\n");
3077 if PhactoriDbg(100):
3078 myDebugPrint3("focalToTestVec: " + str(focalToTestVec) + "\n");
3079 cosAngleBB = vecDotProduct(inNormCameraDir, focalToTestVec)
3080 if PhactoriDbg(100):
3081 myDebugPrint3("cosAngleBB: " + str(cosAngleBB) + "\n");
3082 if cosAngleBB >= 1.0:
3083 #camera-to-test-point in line with camera-to-focal-point
3084 #and already in camera view
3085 if PhactoriDbg(100):
3086 myDebugPrint3("cosAngleBB >= 1.0 cc is 0.0\n");
3087 cc = 0.0
3088 return cc
3089 elif cosAngleBB <= -1.0:
3090 #camera-to-test-point in line with camera-to-focal-point
3091 #with camera needing movement back to test point
3092 if PhactoriDbg(100):
3093 myDebugPrint3("cosAngleBB <= -1.0, cc is camera to test point dist\n");
3094 cc = aa
3095 return cc
3096 angleBB = math.acos(cosAngleBB)
3097 if PhactoriDbg(100):
3098 myDebugPrint3("angleBB: " + str(math.degrees(angleBB)) + "\n");
3099 angleCC = math.pi - (angleAA + angleBB)
3100 if PhactoriDbg(100):
3101 myDebugPrint3("angleCC: " + str(math.degrees(angleCC)) + "\n");
3102 cc = aa * math.sin(angleCC) / math.sin(angleAA)
3103 if PhactoriDbg(100):
3104 myDebugPrint3("cc: " + str(cc) + "\n");
3105 if PhactoriDbg(100):
3106 myDebugPrint3("CalcRelativeCameraDistance2_AA returning\n");
3107 return cc
3108
3109 def projectPointOntoPlane(inPoint, inPlanePoint, inPlaneNormal):
3110 vecA = [inPoint[0] - inPlanePoint[0],
3111 inPoint[1] - inPlanePoint[1],
3112 inPoint[2] - inPlanePoint[2]]
3113 dotp1 = vecDotProduct(vecA, inPlaneNormal)
3114 projectedPoint = [inPoint[0] - dotp1 * inPlaneNormal[0],
3115 inPoint[1] - dotp1 * inPlaneNormal[1],
3116 inPoint[2] - dotp1 * inPlaneNormal[2]]
3117 return projectedPoint
3118
3119 def CalcRelativeCameraDistance2_BB(inFocalPoint, inNormCameraDir,
3120 inNormUpVector, inNormSideVector, inFovV, inFovH, inTestPoint):
3121 """takes test point and makes two test points, one projected onto the
3122 plane defined by the up vector and one onto the plane defined by the
3123 up vector/look direction cross product; uses these two points to
3124 test vs. vertical FOV and horizontal FOV, and returns the biggest
3125 result. Assumes inNormUpVector is normalized as is inNormCameraDir
3126 and also inNormSideVector"""
3127 if PhactoriDbg(100):
3128 myDebugPrint3("CalcRelativeCameraDistance2_BB entered\n");
3129 if PhactoriDbg(100):
3130 myDebugPrint3("inTestPoint: " + str(inTestPoint) + "\n");
3131
3132 pointV = projectPointOntoPlane(inTestPoint, inFocalPoint, inNormSideVector)
3133 if PhactoriDbg(100):
3134 myDebugPrint3("pointV: " + str(pointV) + "\n");
3135 #find point projected onto plane defined by inFocalPoint and localUpVector,
3136 #which will be the test point to test horizontal FOV against
3137 pointH = projectPointOntoPlane(inTestPoint, inFocalPoint, inNormUpVector)
3138 if PhactoriDbg(100):
3139 myDebugPrint3("pointH: " + str(pointH) + "\n");
3140
3141 dd1 = CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
3142 pointH, inFovH)
3143 if PhactoriDbg(100):
3144 myDebugPrint3("dd1: " + str(dd1) + "\n");
3145 dd2 = CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
3146 pointV, inFovV)
3147 if PhactoriDbg(100):
3148 myDebugPrint3("dd2: " + str(dd2) + "\n");
3149 if dd2 > dd1:
3150 dd1 = dd2
3151 if PhactoriDbg(100):
3152 myDebugPrint3("return dd: " + str(dd1) + "\n");
3153 return dd1
3154
3155
3156 def CalcRelativeCameraDistance2(inFocalPoint, inLookDirection, inUpVector,
3157 inFov, inImageSettings, inBounds):
3158 #for each focal point, see how far back from the focal point the
3159 #camera position needs to be to see the focal point. Use the largest.
3160 inXyPixelSize = inImageSettings.mImageSize
3161 inPixelBorderRatioXY = inImageSettings.mPixelBorderRatioXY
3162 if PhactoriDbg(100):
3163 myDebugPrint3("CalcRelativeCameraDistance2 entered\n");
3164 myDebugPrint3("inFocalPoint: " + str(inFocalPoint) + "\n");
3165 myDebugPrint3("inLookDirection: " + str(inLookDirection) + "\n");
3166 myDebugPrint3("inUpVector: " + str(inUpVector) + "\n");
3167 myDebugPrint3("inFov: " + str(inFov) + "\n");
3168 myDebugPrint3("inXyPixelSize: " + str(inXyPixelSize) + "\n");
3169 myDebugPrint3("inPixelBorderRatioXY: " + str(inPixelBorderRatioXY) + "\n");
3170 normCameraDir = vecNormalize(inLookDirection)
3171 normCameraDir[0] = -normCameraDir[0]
3172 normCameraDir[1] = -normCameraDir[1]
3173 normCameraDir[2] = -normCameraDir[2]
3174 if PhactoriDbg(100):
3175 myDebugPrint3("normCameraDir: " + str(normCameraDir) + "\n");
3176
3177 #find orthoganol up and side vectors,
3178 normUpVector = vecNormalize(inUpVector)
3179 sideVector = vecCrossProduct(normUpVector, normCameraDir)
3180 normUpVector = vecCrossProduct(normCameraDir, sideVector)
3181 if PhactoriDbg(100):
3182 myDebugPrint3("sideVector: " + str(sideVector) + "\n");
3183 myDebugPrint3("normUpVector: " + str(normUpVector) + "\n");
3184
3185 #find vertical fov, based on pixel border percentage
3186 vertPixX = 0.5 * float(inXyPixelSize[0])
3187 vertPixY = 0.5 * float(inXyPixelSize[1])
3188 vertPixBrdrX = inPixelBorderRatioXY[0] * float(inXyPixelSize[0])
3189 vertPixBrdrY = inPixelBorderRatioXY[1] * float(inXyPixelSize[1])
3190
3191 vertPixBrdrX = math.ceil(vertPixBrdrX)
3192 vertPixBrdrY = math.ceil(vertPixBrdrY)
3193
3194 if PhactoriDbg(100):
3195 myDebugPrint3("pixel border: " + str(vertPixBrdrX) + ", " + str(vertPixBrdrY) + "\n")
3196 tanInFov = math.tan(math.radians(inFov*0.5))
3197 if PhactoriDbg(100):
3198 myDebugPrint3("tanInFov: " + str(tanInFov) + "\n")
3199
3200 #vertPixY / ss = tan(inFov*0.5)
3201 #1/ss = tan(inFov*0.5)/vertPixY
3202 #(vertPixY - vertPixBrdrY) / ss = tan(adjFov*0.5)
3203 #(vertPixY - vertPixBrdrY) * tan(inFov*0.5)/vertPixY = tan(adjFov*0.5)
3204
3205 tanAdjustedFovV = (vertPixY - vertPixBrdrY) * tanInFov / vertPixY
3206 if PhactoriDbg(100):
3207 myDebugPrint3("tanAdjustedFovV: " + str(tanAdjustedFovV) + "\n")
3208 fovV = 2.0 * math.degrees(math.atan(tanAdjustedFovV))
3209 if PhactoriDbg(100):
3210 myDebugPrint3("fovV: " + str(fovV) + "\n");
3211
3212 pixelSizeWithBorder = [inXyPixelSize[0] - 2 * int(vertPixBrdrX),
3213 inXyPixelSize[1] - 2 * int(vertPixBrdrY)]
3214
3215 #we are special casing when the pixel ratio is the same for both
3216 #X and Y for backwards compatability of test images; We should
3217 #take out this special case and update the test images. The
3218 #difference is very minor, but detectable
3219 if inImageSettings.mPixelBorderRatioXY[0] == \
3220 inImageSettings.mPixelBorderRatioXY[1]:
3221 #this is the special case--use the original pixel size to calculate
3222 #aspect ratio, which will be very slightly different than the other
3223 #case due to the math.ceil clamping to an integer value
3224 aspectRatio = float(inXyPixelSize[0]) / float(inXyPixelSize[1])
3225 else:
3226 aspectRatio = float(pixelSizeWithBorder[0]) / float(pixelSizeWithBorder[1])
3227
3228
3229 if PhactoriDbg(100):
3230 myDebugPrint3("bordered aspectRatio: " + str(aspectRatio) + "\n");
3231 tanFovH = aspectRatio * tanAdjustedFovV
3232 fovH = 2.0 * math.degrees(math.atan(tanFovH))
3233 if PhactoriDbg(100):
3234 myDebugPrint3("fovH: " + str(fovH) + "\n");
3235
3236 #find point projected onto plane defined by inFocalPoint and sideVector,
3237 #which will be the test point to test vertical FOV against
3238 dist1 = 0.0
3239 for ii in range(0,2):
3240 for jj in range(0,2):
3241 for kk in range(0,2):
3242 testpoint = [inBounds[ii+0], inBounds[jj+2], inBounds[kk+4]]
3243 testdist = CalcRelativeCameraDistance2_BB(inFocalPoint,
3244 normCameraDir, normUpVector, sideVector, fovV, fovH,
3245 testpoint)
3246 if testdist > dist1:
3247 dist1 = testdist
3248 if PhactoriDbg(100):
3249 myDebugPrint("CalcRelativeCameraDistance2 returning dist: " + str(dist1) + "\n");
3250 return dist1
3251
3252 def SetParaViewRepresentationCameraParams(inXParaViewRenderView, inCameraC,
3253 inLookDirection, inImageSettingsX, inParaViewSource):
3254 lookDirection = inLookDirection
3255
3256 myViewBounds = None
3257 viewBoundsIo = [myViewBounds]
3258
3259 #special case--if inCameraC was set up so the camera is at a specified
3260 #point, if the look at point is specified we need to base the look
3261 #direction on the camera position and the look at point, and if
3262 #the look direction is specified, we need to base the look at point
3263 #on the camera position and the look direction
3264 if inCameraC.mUseCameraAtPointFlag:
3265 if PhactoriDbg():
3266 myDebugPrint3("SetParaViewRepresentationCameraParams: special case of camera at point setting\n")
3267 #camera at point was specified--do the right stuff
3268 cameraPoint = inCameraC.mCameraAtPointInfo.\
3269 GetCurrentGeometricPointWithDisplacement(
3270 inParaViewSource, viewBoundsIo, True)
3271 if PhactoriDbg():
3272 myDebugPrint3("cameraPoint: " + str(cameraPoint) + "\n")
3273 inCameraC.mLookAtDistanceType = 'absolute'
3274 if inCameraC.mLookDirectionSpecifiedFlag:
3275 if PhactoriDbg():
3276 myDebugPrint3("look direction was specified\n")
3277 #look direction was specified, so calculate focal point based on camera
3278 #position and look direction and set look at distance to 1.0
3279 lookDirection = inCameraC.mLookDirection
3280 aa = lookDirection[0]
3281 bb = lookDirection[1]
3282 cc = lookDirection[2]
3283 lookDirectionMagnitude = math.sqrt(aa*aa + bb*bb + cc*cc)
3284 inCameraC.mLookAtDistance = 1.0
3285 focalPoint = [cameraPoint[0] + (aa / lookDirectionMagnitude),
3286 cameraPoint[1] + (bb / lookDirectionMagnitude),
3287 cameraPoint[2] + (cc / lookDirectionMagnitude)]
3288 if PhactoriDbg():
3289 myDebugPrint3("focalPoint: " + str(focalPoint) + "\n")
3290 if PhactoriDbg():
3291 myDebugPrint3("lookDirection: " + str(lookDirection) + "\n")
3292 if PhactoriDbg():
3293 myDebugPrint3("inCameraC.mLookAtDistance is 1.0\n")
3294 else:
3295 #look direction not specified, so we use look at point. Calculate
3296 #look direction and look at distance based on camera position and
3297 #look at point
3298 if PhactoriDbg():
3299 myDebugPrint3("use look at point as look direction was not specified\n")
3300 focalPoint = inCameraC.mLookAtPointInfo. \
3301 GetCurrentGeometricPointWithDisplacement(
3302 inParaViewSource, viewBoundsIo, True)
3303 if PhactoriDbg():
3304 myDebugPrint3("focalPoint: " + str(focalPoint) + "\n")
3305 lookDirection = [focalPoint[0] - cameraPoint[0],
3306 focalPoint[1] - cameraPoint[1],
3307 focalPoint[2] - cameraPoint[2]]
3308 if PhactoriDbg():
3309 myDebugPrint3("lookDirection: " + str(lookDirection) + "\n")
3310 aa = lookDirection[0]
3311 bb = lookDirection[1]
3312 cc = lookDirection[2]
3313 inCameraC.mLookAtDistance = math.sqrt(aa*aa + bb*bb + cc*cc)
3314 if PhactoriDbg():
3315 myDebugPrint3("inCameraC.mLookAtDistance is " + str(inCameraC.mLookAtDistance) + "\n")
3316 #check for zero magnitude
3317 if inCameraC.mLookAtDistance != 0.0:
3318 inCameraC.mLookDirection = lookDirection
3319 else:
3320 if PhactoriDbg():
3321 myDebugPrint3("warning: camera position and look at point are the same\n")
3322 #try to use previous
3323 lookDirection = inCameraC.mLookDirection
3324 aa = lookDirection[0]
3325 bb = lookDirection[1]
3326 cc = lookDirection[2]
3327 inCameraC.mLookAtDistance = math.sqrt(aa*aa + bb*bb + cc*cc)
3328 if PhactoriDbg():
3329 myDebugPrint3(" coincident lookDirection: " + str(lookDirection) + "\n")
3330 if PhactoriDbg():
3331 myDebugPrint3(" coincident inCameraC.mLookAtDistance is " + str(inCameraC.mLookAtDistance) + "\n")
3332 if inCameraC.mLookAtDistance == 0.0:
3333 if PhactoriDbg():
3334 myDebugPrint3(" warning: previous camera look direction had zero magnitude\n")
3335 #previous also zero, use -1,-1,-1
3336 lookDirection = [-1.0, -1.0, -1.0]
3337 inCameraC.mLookAtDistance = math.sqrt(3.0)
3338 if PhactoriDbg():
3339 myDebugPrint3(" coincident lookDirection 2: " + str(lookDirection) + "\n")
3340 if PhactoriDbg():
3341 myDebugPrint3(" coincident inCameraC.mLookAtDistance 2 is " + str(inCameraC.mLookAtDistance) + "\n")
3342 else:
3343 UpdatePipelineWithCurrentTimeArgument(inParaViewSource)
3344 focalPoint = inCameraC.mLookAtPointInfo. \
3345 GetCurrentGeometricPointWithDisplacement(
3346 inParaViewSource, viewBoundsIo, True)
3347
3348 if PhactoriDbg():
3349 myDebugPrint3(' lookDirection ' + str(lookDirection) + '\n')
3350
3351 myViewBounds = viewBoundsIo[0]
3352
3353 if PhactoriDbg():
3354 myDebugPrint3(' focalPoint ' + str(focalPoint) + '\n')
3355
3356 #need to handle relative and error
3357
3358 global gDefaultLookatDistanceDatasizeRelativeMultiplier
3359 global gDefaultLookatDistanceDatasizeRelative
3360 if inCameraC.mLookAtDistanceType == 'datasize relative':
3361 cameraPositionFactor = inCameraC.mLookAtDistance
3362 #cameraPositionFactor *= gDefaultLookatDistanceDatasizeRelativeMultiplier
3363 cameraToFocalPointDistance = None
3364 #we'll need view bounds for distance
3365 if myViewBounds == None:
3366 myViewBounds = GetGlobalDataBoundsParallel(inParaViewSource)
3367 #elif inCameraC.mLookAtDistanceType == 'absolute':
3368 else:
3369 cameraPositionFactor = gDefaultLookatDistanceDatasizeRelative
3370 cameraPositionFactor *= gDefaultLookatDistanceDatasizeRelativeMultiplier
3371 cameraToFocalPointDistance = inCameraC.mLookAtDistance
3372
3373
3374 if PhactoriDbg():
3375 myDebugPrint3(' cameraPositionFactor: ' + str(cameraPositionFactor) + '\n')
3376 if PhactoriDbg():
3377 myDebugPrint3(' cameraToFocalPointDistance: ' + str(cameraToFocalPointDistance) + '\n')
3378
3379
3380 SetCameraLookAtPointAndLookDirection(inParaViewRenderView = inXParaViewRenderView,
3381 inLookDirection = lookDirection,
3382 inImageSettings = inImageSettingsX,
3383 inFocalPoint = focalPoint,
3384 inEyePositionFactor = cameraPositionFactor,
3385 inEyeToFocalPointDistance = cameraToFocalPointDistance,
3386 inCameraViewAngle = inCameraC.mViewAngle,
3387 inViewUp = inCameraC.mViewUpVector,
3388 inViewBounds = myViewBounds,
3389 inPhactoriCamera = inCameraC)
3390
3391
3392 def SetForCorrectColorByVariable(inImagesetInfo, inPhactoriOperation,
3393 inPvDataRepresentation, inPhactoriRepresentation,
3394 inInitializeColorLegendFlag):
3395 """sets the color by variable to a scalar, vector component/magnitude, or
3396 tensor component. Assumes we've already established we are doing this
3397 instead of solid color or color by block"""
3398
3399 if PhactoriDbg():
3400 myDebugPrint3("SetForCorrectColorByVariable entered\n")
3401
3402 savedActiveSourceX = GetActiveSource()
3403 SetActiveSource(inPhactoriOperation.GetPvFilter())
3404
3405 colorVarInfo = inPhactoriRepresentation.mColorVariableInfo
3406
3407 if PhactoriDbg():
3408 myDebugPrint3("colorVarInfo.mVariableName: " + \
3409 str(colorVarInfo.mVariableName) + "\n")
3410
3411 if colorVarInfo.mVariableName == '':
3412 myVariableArrayType = gCellsString
3413 else:
3414 global gPipeAndViewsState
3415 #the correct behavior is probably to use the imageset's filter as the
3416 #filter to use to determine info about the variable, such as POINT or
3417 #cell; however prior work used the pipeline start default incoming
3418 #filter. We are using prior to get tests to pass for now, and
3419 #we are considering switching to 'correct.'
3420 useImagesetFilterToDetectVariableType = False
3421 if useImagesetFilterToDetectVariableType:
3422 paraViewSource = inPhactoriOperation.GetPvFilter()
3423 else:
3424 paraViewSource = \
3425 gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
3426 detectResult = colorVarInfo.DetectVariableType(
3427 paraViewSource, True, False)
3428
3429 if detectResult == True:
3430 #variable type detected determine value for paraview
3431 if colorVarInfo.mVariableType == 'node':
3432 myVariableArrayType = gPointsString
3433 elif colorVarInfo.mVariableType == 'element':
3434 myVariableArrayType = gCellsString
3435 else:
3436 if PhactoriDbg():
3437 myDebugPrint3(errStr)
3438 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
3439 'image set ' + inImagesetInfo.mName + \
3440 'operation ' + inPhactoriOperation.mName + \
3441 ' representation ' + inPhactoriRepresentation.mName + \
3442 '\ncolor variable name: ' + \
3443 colorVarInfo.mVariableName +\
3444 '\nvariable should be node or element at this point and is not'
3445 raise Exception(errStr)
3446 else:
3447 #variable type not detected, deal with it
3448 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
3449 'image set ' + inImagesetInfo.mName + \
3450 'operation ' + inPhactoriOperation.mName + \
3451 ' representation ' + inPhactoriRepresentation.mName + \
3452 '\ncolor variable name: ' + \
3453 colorVarInfo.mVariableName +\
3454 '\nvariable is not point data or cell data, assuming cell'
3455 if PhactoriDbg():
3456 myDebugPrint3(errStr)
3457 #current hack--if detection of variable type fails due to missing
3458 #variable; assume it is CELLS and let mpi stuff share info
3459 #and create odd color map otherwise
3460 myVariableArrayType = gCellsString
3461
3462 if PhactoriDbg():
3463 myDebugPrint3("myVariableArrayType: " + myVariableArrayType + "\n")
3464 #("showColorLegend: " + str(showColorLegend) + "\n")
3465
3466 colorVarName = colorVarInfo.mVariableName
3467 if colorVarName != '':
3468 if colorVarInfo.mVariableIsVectorComponent:
3469 if PhactoriDbg():
3470 myDebugPrint3("mVariableIsVectorComponent is true so we do\n"
3471 "ColorByVariableComponentOrMagnitudeXX (component)\n")
3472 ColorByVariableComponentOrMagnitudeXX(
3473 inPvDataRepresentation, inPhactoriRepresentation, colorVarName,
3474 'Component', colorVarInfo.mVariableComponent, myVariableArrayType,
3475 inPhactoriRepresentation.mColorMapSettings)
3476 elif colorVarInfo.mVariableIsVectorMagnitude:
3477 if PhactoriDbg():
3478 myDebugPrint3("mVariableIsVectorMagnitude is true so we do\n"
3479 "ColorByVariableComponentOrMagnitudeXX (magnitude)\n")
3480 ColorByVariableComponentOrMagnitudeXX(
3481 inPvDataRepresentation, inPhactoriRepresentation, colorVarName,
3482 'Magnitude', colorVarInfo.mVariableComponent, myVariableArrayType,
3483 inPhactoriRepresentation.mColorMapSettings)
3484 else:
3485 if PhactoriDbg():
3486 myDebugPrint3("not component or magnitude so we do "
3487 "ColorByVariableScalarXX\n")
3488 ColorByVariableScalarXX(inPvDataRepresentation, inPhactoriRepresentation,
3489 colorVarName, myVariableArrayType,
3490 inPhactoriRepresentation.mColorMapSettings)
3491
3492 #if inInitializeColorLegendFlag:
3493 if True:
3494 if inPhactoriRepresentation.mUseFixedColorRange:
3495 fixedColorRange = inPhactoriRepresentation.mFixedColorRange
3496 SetMinimumMaximumColorValues(inPvDataRepresentation,
3497 fixedColorRange[0], fixedColorRange[1],
3498 inPhactoriOperation, inPhactoriRepresentation,
3499 colorVarName, myVariableArrayType)
3500 #else:
3501 # SetMinimumMaximumColorValues(inPvDataRepresentation,
3502 # -0.1, 0.1,
3503 # inPhactoriRepresentation, colorVarName, myVariableArrayType)
3504 else:
3505 if gParaViewCatalystVersionFlag <= 40100:
3506 inPvDataRepresentation.ColorArrayName = ""
3507 else:
3508 #if PhactoriDbg():
3509 # myDebugPrint3("using ColorBy() to set no color var 1\n")
3510 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3511 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
3512 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3513
3514 if PhactoriDbg():
3515 myDebugPrint3("SetForCorrectColorByVariable returning\n")
3516
3517 #inPvDataRepresentation.RescaleTransferFunctionToDataRange(True)
3518 SetActiveSource(savedActiveSourceX)
3519
3520 def SetForCorrectColorBy(inImagesetInfo, inPhactoriOperation,
3521 inPvDataRepresentation, inPhactoriRepresentation,
3522 inInitializeColorLegendFlag):
3523
3524 global gParaViewCatalystVersionFlag
3525
3526 if PhactoriDbg():
3527 if inPhactoriOperation != None:
3528 opStr = inPhactoriOperation.mName
3529 else:
3530 opStr = "None"
3531 myDebugPrint3("SetForCorrectColorBy entered\n"
3532 "inImagesetInfo: " + inImagesetInfo.mName + "\n"
3533 "inPhactoriOperation: " + opStr + "\n"
3534 "inPhactoriRepresentation: " + str(inPhactoriRepresentation) + "\n"
3535 "inInitializeColorLegendFlag: " + str(inInitializeColorLegendFlag) + "\n")
3536 #color by variable
3537 if inPhactoriRepresentation != None:
3538 if inPvDataRepresentation.Opacity != inPhactoriRepresentation.mOpacitySetting:
3539 inPvDataRepresentation.Opacity = inPhactoriRepresentation.mOpacitySetting
3540 SetForCorrectColorByVariable(inImagesetInfo, inPhactoriOperation,
3541 inPvDataRepresentation, inPhactoriRepresentation,
3542 inInitializeColorLegendFlag)
3543 else:
3544 if PhactoriDbg():
3545 myDebugPrint3("inPhactoriRepresentation is None, so set to no color array\n")
3546 if gParaViewCatalystVersionFlag <= 40100:
3547 inPvDataRepresentation.ColorArrayName = ""
3548 else:
3549 #if PhactoriDbg():
3550 # myDebugPrint3("using ColorBy() to set no color var 2\n")
3551 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3552 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
3553 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3554
3555 #color by block id or solid color
3556 if inPhactoriRepresentation != None:
3557 if inPhactoriRepresentation.mColorByBlockFlag == False:
3558 #clear block color
3559 if gParaViewCatalystVersionFlag < 51000:
3560 inPvDataRepresentation.BlockColor = {}
3561 if inPhactoriRepresentation.mColorByBlockFlag:
3562 if PhactoriDbg():
3563 myDebugPrint3("inPhactoriRepresentation.mColorByBlockFlag is true\n")
3564
3565 if gParaViewCatalystVersionFlag <= 40100:
3566 inPvDataRepresentation.ColorArrayName = ""
3567 else:
3568 #if PhactoriDbg():
3569 # myDebugPrint3("using ColorBy() to set no color var 3\n")
3570 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3571 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
3572 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3573
3574 ColorByBlock(GetActiveSource(),
3575 inPvDataRepresentation,
3576 inPhactoriRepresentation.mColorByBlockExplicitlySet)
3577 elif inPhactoriRepresentation.mColorBySolidColorFlag:
3578 if PhactoriDbg():
3579 myDebugPrint3("inPhactoriRepresentation.mColorBySolidColorFlag is true\n")
3580 if gParaViewCatalystVersionFlag <= 40100:
3581 inPvDataRepresentation.ColorArrayName = ""
3582 else:
3583 #if PhactoriDbg():
3584 # myDebugPrint3("using ColorBy() to set no color var 4\n")
3585 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3586 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
3587 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
3588
3589 inPvDataRepresentation.DiffuseColor = \
3590 inPhactoriRepresentation.mSolidColor
3591 else:
3592 if PhactoriDbg():
3593 myDebugPrint3("no color by block or solid color flag\n")
3594
3595 if PhactoriDbg():
3596 myDebugPrint3("SetForCorrectColorBy returning\n")
3597
3598 def SetUpOneParaViewRepresentationAndViewC(inCameraC, inLookDirection,
3599 inImagesetInfo,
3600 inColorSettingsX,
3601 inMeshRenderControl,
3602 inShowDataCubeAxes, inShowDataCubeAxesInfo, inShowOrientationAxes,
3603 inFixedColorRange,
3604 inIsPlotFlag,
3605 inViewBounds = None,
3606 inRepresentationFilenameAddon = "",
3607 inLookDirectionFilenameAddon = "",
3608 inPhactoriRepresentation = None):
3609
3610 global gRenderingEnabled
3611 if gRenderingEnabled == False:
3612 if PhactoriDbg():
3613 myDebugPrint3("SetUpOneParaViewRepresentationAndViewC returning with noop because rendering is disabled\n")
3614 return
3615
3616 inImageSettings = inImagesetInfo.mImageSettings
3617 lclImageSize = inImageSettings.mImageSize
3618 lclImageFormat = inImageSettings.mImageFormat
3619 inImageBasename = inImageSettings.mImageBasename
3620 inImageBasedirectory = inImageSettings.mImageBasedirectory
3621 inNumCounterDigits = inImageSettings.mNumCounterDigits
3622
3623 #myDebugPrint3('inCameraC: ' + str(inCameraC) + '\n')
3624 #myDebugPrint3('inLookDirection: ' + str(inLookDirection) + '\n')
3625 #myDebugPrint3('inImageBasename: ' + str(inImageBasename) + '\n')
3626 #myDebugPrint3('inImageBasedirectory: ' + str(inImageBasedirectory) + '\n')
3627 #myDebugPrint3('inNumCounterDigits: ' + str(inNumCounterDigits) + '\n')
3628 #myDebugPrint3('lclImageFormat: ' + str(lclImageFormat) + '\n')
3629 #myDebugPrint3('lclImageSize: ' + str(lclImageSize) + '\n')
3630 #myDebugPrint3('inMeshRenderControl: ' + str(inMeshRenderControl) + '\n')
3631 #myDebugPrint3('inShowDataCubeAxes: ' + str(inShowDataCubeAxes) + '\n')
3632 #myDebugPrint3('inShowOrientationAxes: ' + str(inShowOrientationAxes) + '\n')
3633 #myDebugPrint3('inViewBounds: ' + str(inViewBounds) + '\n')
3634 #myDebugPrint3('inRepresentationFilenameAddon: ' + str(inRepresentationFilenameAddon) + '\n')
3635 #myDebugPrint3('inLookDirectionFilenameAddon: ' + str(inLookDirectionFilenameAddon) + '\n')
3636
3637
3638 #need to handle absolute and error
3639
3640 nameSuffix = inRepresentationFilenameAddon + inCameraC.mFilenameAddon + inLookDirectionFilenameAddon
3641
3642 if inImageBasedirectory == None:
3643 fileBaseName = inImageBasename + nameSuffix
3644 elif inImageBasedirectory == "":
3645 fileBaseName = inImageBasename + nameSuffix
3646 else:
3647 import os
3648 fileBaseName = inImageBasedirectory + os.sep + inImageBasename + nameSuffix
3649
3650 AddRenderView(inPhactoriImagesetInfo = inImagesetInfo,
3651 inColorSettings = inColorSettingsX,
3652 ImageBaseFileName = fileBaseName, ImageType = lclImageFormat,
3653 ImageOverwriteFlag = False,
3654 PixelSizeX = lclImageSize[0], PixelSizeY = lclImageSize[1],
3655 numCounterDigits = inNumCounterDigits,
3656 inIsPlotFlag = inIsPlotFlag)
3657
3658 if inIsPlotFlag == False:
3659 SetParaViewRepresentationCameraParams(inImagesetInfo.mSharedPvRenderView2,
3660 inCameraC, inLookDirection, inImageSettings, GetActiveSource())
3661 SetForCorrectColorBy(inImagesetInfo,
3662 inImagesetInfo.GetInputPhactoriOperation(),
3663 inImagesetInfo.mPvDataRepresentation2, inPhactoriRepresentation, True)
3664
3665 inImagesetInfo.mPvDataRepresentation2.Representation = inMeshRenderControl
3666 if(inShowOrientationAxes):
3667 inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 1
3668 else:
3669 inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 0
3670
3671 UpdateRepresentationColorBy(inImagesetInfo)
3672 #if inShowColorLegend:
3673 # if PhactoriDbg():
3674 # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend on\n')
3675 # ShowDataColorLegendXX(inImagesetInfo, 'on',
3676 # inColorLegendPositionAndSize, inColorSettingsX)
3677 #else:
3678 # if PhactoriDbg():
3679 # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend off\n')
3680 # ShowDataColorLegendXX(inImagesetInfo, 'off',
3681 # inColorLegendPositionAndSize, inColorSettingsX)
3682
3683 if inShowDataCubeAxes:
3684 ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'on', inShowDataCubeAxesInfo)
3685 else:
3686 ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'off')
3687
3688 def GetLookDirectionListFromCamera(inCamera):
3689 if inCamera.mType == 'multicamera8':
3690 directionsList = [ [[-1.0, 0.0, 0.0], 'x1.'],
3691 [[ 1.0, 0.0, 0.0], 'x2.'],
3692 [[ 0.0, -1.0, 0.0], 'y1.'],
3693 [[ 0.0, 1.0, 0.0], 'y2.'],
3694 [[ 0.0, 0.0, -1.0], 'z1.'],
3695 [[ 0.0, 0.0, 1.0], 'z2.'],
3696 [[-1.0, -1.0, -1.0], 'xyz1.'],
3697 [[ 1.0, 1.0, 1.0], 'xyz2.'] ]
3698 elif inCamera.mType == 'camera':
3699 directionsList = [[inCamera.mLookDirection, '']]
3700 else:
3701 errStr = 'error! GetLookDirectionListFromCamera has illegal camera type\n'
3702 if PhactoriDbg():
3703 myDebugPrint3(errStr)
3704 raise Exception(errStr)
3705
3706 return directionsList
3707
3708
3709 def ParseOneFilterTypeFromViewMapOperation(ioOperationBlock, inTypeString, inOperationClass, inOperationParamsJson):
3710 ioOperationBlock.mType = inTypeString
3711
3712 ioOperationBlock.mOperationSpecifics = inOperationClass()
3713 ioOperationBlock.mOperationSpecifics.mPhactoriOperationBlockOwner = \
3714 ioOperationBlock
3715 ioOperationBlock.mOperationSpecifics.ParseParametersFromJson(inOperationParamsJson)
3716
3717 #if 'input operation' in inOperationParamsJson:
3718 if 'input' in inOperationParamsJson:
3719 ioOperationBlock.mInputOperationName = inOperationParamsJson['input']
3720 if PhactoriDbg(100):
3721 myDebugPrint3("ParseOneFilterTypeFromViewMapOperation: input is: \n" + ioOperationBlock.mInputOperationName, 100)
3722 else:
3723 noticeStr = 'notice! inOperationParamsJson has no input key, using default pipeline input\n'
3724 ioOperationBlock.mInputOperationName = None
3725 if PhactoriDbg():
3726 myDebugPrint3(noticeStr)
3727
3728
3729 def ConstructClipPlaneOperationFromParsedOperationBlockC(ioPipeAndViewsState, ioOperationBlock):
3730 return
3731
3732 def ConstructPipelineOperationFromParsedOperationBlockC_ForTest(ioOperationBlock, inputParaviewFilter):
3733 if PhactoriDbg(100):
3734 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC_ForTest entered\n", 100)
3735 particularOperation = ioOperationBlock.mOperationSpecifics
3736 if ioOperationBlock.mType == 'group':
3737 myDebugPrint3("not doing group yet")
3738 raise Exception("not doing group yet")
3739 else:
3740 inputSource = inputParaviewFilter
3741 newParaViewFilter = particularOperation.CreateParaViewFilter2(inputSource, None)
3742 ioOperationBlock.mParaViewFilter = newParaViewFilter
3743 if PhactoriDbg(100):
3744 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC_ForTest returning\n", 100)
3745
3746 def ConstructPipelineOperationFromParsedOperationBlockC(ioPipeAndViewsState, ioOperationBlock):
3747 if PhactoriDbg(100):
3748 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC entered\n", 100)
3749 if PhactoriDbg():
3750 myDebugPrint3(" constructing operation named " + ioOperationBlock.mName + "\n")
3751
3752 particularOperation = ioOperationBlock.mOperationSpecifics
3753
3754 if ioOperationBlock.mType == 'group':
3755 if PhactoriDbg(100):
3756 myDebugPrint3("type was 'group', different pv filter construction\n",
3757 100)
3758 newParaViewFilter = particularOperation.CreateParaViewFilter2(
3759 ioPipeAndViewsState)
3760 else:
3761 inputSource = None
3762 if ioOperationBlock.mInputOperationName == None:
3763 inputSource = GetActiveSource()
3764 if PhactoriDbg():
3765 myDebugPrint3("mInputOperationName was none so using" + str(inputSource) + '\n')
3766 else:
3767 inputOperationBlock = ioPipeAndViewsState.mOperationBlocks[
3768 ioOperationBlock.mInputOperationName]
3769 inputSource = inputOperationBlock.GetPvFilter()
3770 if PhactoriDbg():
3771 myDebugPrint3("mInputOperationName was " + ioOperationBlock.mInputOperationName + " so using" + str(inputSource) + '\n')
3772
3773 newParaViewFilter = particularOperation.CreateParaViewFilter2(inputSource, ioPipeAndViewsState)
3774
3775 ioOperationBlock.mParaViewFilter = newParaViewFilter
3776
3777 if PhactoriDbg(100):
3778 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC returning\n", 100)
3779
3780
3781 def MakeFiltersFromViewMapOperationsC(ioPipeAndViewsState, inOperationBlocksJson):
3782 if PhactoriDbg(100):
3783 myDebugPrint3('MakeFiltersFromViewMapOperationsC entered\n', 100)
3784
3785 #loop through set of filter blocks (in json dict) and parse out the filter objects
3786 for operationName, operationParams in inOperationBlocksJson.items():
3787
3788 #hack to insert filter images in/out
3789 if operationName == "ImageFilteringStartOperationOverride":
3790 if PhactoriDbg():
3791 myDebugPrint3("overriding operation to do image set on/off filtering\n")
3792 operationParams['type'] = 'image_filtering_start'
3793 ParseOneImageStartStopFilterFromViewMap(operationParams)
3794 #then go on to next operation
3795 continue
3796
3797 newOperationBlock = PhactoriOperationBlock()
3798 newOperationBlock.mName = operationName
3799 if PhactoriDbg():
3800 myDebugPrint3(' creating operation named ' + newOperationBlock.mName + '\n')
3801
3802 if 'type' not in operationParams:
3803 errStr = 'error! operation block with name ' + str(operationName) + ' has no type key in MakeFiltersFromViewMapOperationsC\n'
3804 if PhactoriDbg():
3805 myDebugPrint3(errStr)
3806 raise Exception(errStr)
3807
3808 if PhactoriDbg():
3809 myDebugPrint3(' operation type: ' + str(operationParams['type']) + '\n')
3810
3811 if operationParams['type'] == 'threshold':
3812 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3813 'threshold',
3814 PhactoriThresholdOperation,
3815 operationParams)
3816 elif operationParams['type'] == 'extractblock':
3817 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3818 'extractblock',
3819 PhactoriExtractBlockOperation,
3820 operationParams)
3821 elif operationParams['type'] == 'generatesurfacenormals':
3822 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3823 'generatesurfacenormals',
3824 PhactoriGenerateSurfaceNormalsOperation,
3825 operationParams)
3826 elif operationParams['type'] == 'extractsurface':
3827 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3828 'extractsurface',
3829 PhactoriExtractSurfaceOperation,
3830 operationParams)
3831 elif operationParams['type'] == 'ghostcellsgenerator':
3832 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3833 'ghostcellsgenerator',
3834 PhactoriGhostCellsGeneratorOperation,
3835 operationParams)
3836 elif operationParams['type'] == 'mergeblocks':
3837 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3838 'mergeblocks',
3839 PhactoriMergeBlocksOperation,
3840 operationParams)
3841 elif operationParams['type'] == 'subdivide':
3842 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3843 'subdivide',
3844 PhactoriSubdivideOperation,
3845 operationParams)
3846 elif operationParams['type'] == 'aggregatedataset':
3847 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3848 'aggregatedataset',
3849 PhactoriAggregateDatasetOperation,
3850 operationParams)
3851 elif operationParams['type'] == 'createsegmentsnormaltocells':
3852 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3853 'createsegmentsnormaltocells',
3854 PhactoriCreateSegmentsNormalToCells,
3855 operationParams)
3856 elif operationParams['type'] == 'vectorproject':
3857 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3858 'vectorproject',
3859 PhactoriVectorProject,
3860 operationParams)
3861 elif operationParams['type'] == 'glyph':
3862 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3863 'glyph',
3864 PhactoriGlyphOperation,
3865 operationParams)
3866 elif operationParams['type'] == 'triangulate':
3867 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3868 'triangulate',
3869 PhactoriTriangulateOperation,
3870 operationParams)
3871 elif operationParams['type'] == 'group':
3872 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3873 'group',
3874 PhactoriGroupOperation,
3875 operationParams)
3876 elif operationParams['type'] == 'transform':
3877 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3878 'transform',
3879 PhactoriTransformOperation,
3880 operationParams)
3881 elif operationParams['type'] == 'calculator':
3882 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3883 'calculator',
3884 PhactoriCalculatorOperation,
3885 operationParams)
3886 elif operationParams['type'] == 'add point set':
3887 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3888 'add point set',
3889 PhactoriAddPointSetOperation,
3890 operationParams)
3891 elif operationParams['type'] == 'add unstructured grid':
3892 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3893 'add unstructured grid',
3894 PhactoriAddUnstructuredGridOperation,
3895 operationParams)
3896 elif operationParams['type'] == 'reflect':
3897 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3898 'reflect',
3899 PhactoriReflectOperation,
3900 operationParams)
3901 elif operationParams['type'] == 'warpbyvector':
3902 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3903 'warpbyvector',
3904 PhactoriWarpByVectorOperation,
3905 operationParams)
3906 elif operationParams['type'] == 'clip':
3907 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3908 'clip',
3909 PhactoriClipPlaneOperation,
3910 operationParams)
3911 elif operationParams['type'] == 'slice':
3912 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3913 'slice',
3914 PhactoriSliceOperation,
3915 operationParams)
3916 elif operationParams['type'] == 'slicewithplane':
3917 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3918 'slicewithplane',
3919 PhactoriSliceWithPlaneOperation,
3920 operationParams)
3921 elif operationParams['type'] == 'boxclip':
3922 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3923 'boxclip',
3924 PhactoriBoxClipOperation,
3925 operationParams)
3926 elif operationParams['type'] == 'cylinderclip':
3927 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3928 'cylinderclip',
3929 PhactoriCylinderClipOperation,
3930 operationParams)
3931 elif (operationParams['type'] == 'element data to node data') or \
3932 (operationParams['type'] == 'elementdatatonodedata') or \
3933 (operationParams['type'] == 'cell data to point data') or \
3934 (operationParams['type'] == 'celldatatopointdata'):
3935 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3936 'element data to node data',
3937 PhactoriCellDataToPointDataOperation,
3938 operationParams)
3939 elif (operationParams['type'] == 'node data to element data') or \
3940 (operationParams['type'] == 'nodedatatoelementdata') or \
3941 (operationParams['type'] == 'point data to cell data') or \
3942 (operationParams['type'] == 'pointdatatocelldata'):
3943 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3944 'node data to element data',
3945 PhactoriPointDataToCellDataOperation,
3946 operationParams)
3947 elif operationParams['type'] == 'extractcomponent':
3948 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3949 'extractcomponent',
3950 PhactoriExtractComponentOperation,
3951 operationParams)
3952 elif operationParams['type'] == 'cellsize':
3953 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3954 'cellsize',
3955 PhactoriCellSizeOperation,
3956 operationParams)
3957 elif operationParams['type'] == 'appendlocationattributes':
3958 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3959 'appendlocationattributes',
3960 PhactoriAppendLocationAttributesOperation,
3961 operationParams)
3962 elif operationParams['type'] == 'integratevariables':
3963 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3964 'integratevariables',
3965 PhactoriIntegrateVariablesOperation,
3966 operationParams)
3967 elif operationParams['type' ] == 'nearestpoints':
3968 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3969 'nearestpoints',
3970 PhactoriNearestPointsOperation,
3971 operationParams)
3972 elif operationParams['type'] == 'castnormalrays':
3973 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3974 'castnormalrays',
3975 PhactoriIntersectNodeNormalsWithSurface,
3976 operationParams)
3977 elif operationParams['type'] == 'partitionedtomultiblock':
3978 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3979 'partitionedtomultiblock',
3980 PhactoriPartitionedToMultiBlockOperation,
3981 operationParams)
3982 elif operationParams['type'] == 'vtkdataexport':
3983 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3984 'vtkdataexport',
3985 PhactoriVtkDataExportOperation,
3986 operationParams)
3987 newOperationBlock.mOperationSpecifics.\
3988 SetPhactoriDataArtifactMetaDataControl(GetGlobalDataArtifactTracker())
3989 elif operationParams['type'] == 'exodusiiexport':
3990 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3991 'exodusiiexport',
3992 PhactoriExodusIIExportOperation,
3993 operationParams)
3994 elif operationParams['type'] == 'csvexport':
3995 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
3996 'csvexport',
3997 PhactoriCSVExportOperation,
3998 operationParams)
3999 elif operationParams['type'] == 'contour':
4000 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4001 'contour',
4002 PhactoriContourOperation,
4003 operationParams)
4004 elif operationParams['type'] == 'streamtracer':
4005 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4006 'streamtracer',
4007 PhactoriStreamTracerOperation,
4008 operationParams)
4009 elif operationParams['type'] == 'streamtracerseedsource':
4010 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4011 'streamtracerseedsource',
4012 PhactoriStreamTracerSeedSourceOperation,
4013 operationParams)
4014 elif operationParams['type'] == 'resamplewithdataset':
4015 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4016 'resamplewithdataset',
4017 PhactoriResampleWithDatasetOperation,
4018 operationParams)
4019 elif operationParams['type'] == 'pointsourcefromjsonlist':
4020 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4021 'pointsourcefromjsonlist',
4022 PhactoriPointSourceFromJsonList,
4023 operationParams)
4024 elif operationParams['type'] == 'pointsourcenearbycorrelator':
4025 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4026 'pointsourcenearbycorrelator',
4027 PhactoriPointSourceNearbyCorrelator,
4028 operationParams)
4029 elif operationParams['type'] == 'pointsourcegeometrysampler1':
4030 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4031 'pointsourcegeometrysampler1',
4032 PhactoriPointSourceGeometrySampler1,
4033 operationParams)
4034 elif operationParams['type'] == 'segmentcellsampler3':
4035 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4036 'segmentcellsampler3',
4037 PhactoriSegmentCellSampler3,
4038 operationParams)
4039 elif operationParams['type'] == 'geometriccellsampler1':
4040 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4041 'geometriccellsampler1',
4042 PhactoriGeometricCellSampler1,
4043 operationParams)
4044 elif operationParams['type'] == 'extractsubsetwithseed':
4045 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4046 'extractsubsetwithseed',
4047 PhactoriExtractSubsetWithSeed,
4048 operationParams)
4049 elif operationParams['type'] == 'extractstructuredmultiblock':
4050 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4051 'extractstructuredmultiblock',
4052 PhactoriExtractStructuredMultiBlock,
4053 operationParams)
4054 elif operationParams['type'] == 'pointsource':
4055 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4056 'pointsource',
4057 PhactoriPointSource,
4058 operationParams)
4059 elif operationParams['type'] == 'planesource':
4060 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4061 'planesource',
4062 PhactoriPlaneSource,
4063 operationParams)
4064 elif operationParams['type'] == 'findcelledgelengths':
4065 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4066 'findcelledgelengths',
4067 PhactoriFindCellEdgeLengths,
4068 operationParams)
4069 elif operationParams['type'] == 'celledgeanglemetrics':
4070 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4071 'celledgeanglemetrics',
4072 PhactoriCellEdgeAngleMetrics,
4073 operationParams)
4074 elif operationParams['type'] == 'markcellsurfacestatus2':
4075 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
4076 'markcellsurfacestatus2',
4077 PhactoriMarkCellSurfaceStatus2,
4078 operationParams)
4079 else:
4080 errStr = 'error! in MakeFiltersFromViewMapOperationsC inOperationBlocksJson operation type is unrecognized ' + str(operationParams['type']) + '\n'
4081 if PhactoriDbg():
4082 myDebugPrint3(errStr)
4083 raise Exception(errStr)
4084
4085 ioPipeAndViewsState.mOperationBlocks[newOperationBlock.mName] = \
4086 newOperationBlock
4087
4088 #check to make sure no operation block calls for an input which doesn't exist
4089 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
4090 if operationBlock.mInputOperationName != None:
4091 if operationBlock.mInputOperationName not in ioPipeAndViewsState.mOperationBlocks:
4092 errStr = 'error! in MakeFiltersFromViewMapOperationsC operation block with name ' + str(operationName) + ' calls for nonexistent input operation with name ' + str(operationBlock.mInputOperationName) + '\n'
4093 if PhactoriDbg():
4094 myDebugPrint3(errStr)
4095 raise Exception(errStr)
4096
4097 if PhactoriDbg(100):
4098 myDebugPrint3("begin constructing all operation blocks\n",100)
4099 #now construct each filter in pipeline, being careful to construct them in a valid order, which causes multiple passes through the set
4100 #first, mark all as uncreated
4101 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
4102 if operationBlock.mHasBeenConstructed == None:
4103 operationBlock.mHasBeenConstructed = False
4104
4105 #we need to keep looping through the operation blocks until all have been constructed
4106 keepConstructing = True
4107 while keepConstructing:
4108 keepConstructing = False #at the beginning of the loop, we haven't seen any unconstructed operations
4109 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
4110 if operationBlock.mHasBeenConstructed == False:
4111 #this one still needs constructing, and we'll have to loop again to
4112 #make sure all are constructed
4113 keepConstructing = True
4114
4115 #determine whether or not we can construct this operation yet, or if
4116 #we need to wait for something else to be constructed
4117 canBeConstructedNow = True
4118 inputOperationNames = operationBlock.GetListOfInputOperationNames()
4119 for opName in inputOperationNames:
4120 inputBlock = ioPipeAndViewsState.GetOperationBlockByName(opName)
4121 if inputBlock.mHasBeenConstructed == False:
4122 canBeConstructedNow = False
4123 break
4124
4125 if PhactoriDbg(100):
4126 myDebugPrint3("trying: " + str(operationName) + "\n" + \
4127 "depends on: " + str(inputOperationNames) + "\n" + \
4128 "canBeConstructedNow: " + str(canBeConstructedNow) + "\n",100)
4129 if canBeConstructedNow == True:
4130 #this operation's input has been constructed (or is None), so we can construct it
4131 ConstructPipelineOperationFromParsedOperationBlockC(ioPipeAndViewsState, operationBlock)
4132 operationBlock.mHasBeenConstructed = True
4133 if PhactoriDbg(100):
4134 myDebugPrint3("done constructing all operation blocks\n",100)
4135
4136
4137
4138 #helper method: given a block A which potentially contains a key B with
4139 #value BV, see if block set CS has key BV which indicates a refered-to
4140 #block. Return None if we can't get referred block, warn if A had key
4141 #but BV didn't exist in CS (A not having B merely returns None with no
4142 #complaint
4143 def FindReferredBlockC(referringBlock, referringKey, referredBlockset):
4144 #myDebugPrint3(' FindReferredBlockC entered\n',100)
4145 #myDebugPrint3(' referringBlock: ' + str(referringBlock) + '\n')
4146 #myDebugPrint3(' referringKey: ' + str(referringKey) + '\n')
4147 #myDebugPrint3(' referredBlockset: ' + str(referringKey) + '\n')
4148 if referringKey not in referringBlock:
4149 return None
4150 referredName = referringBlock[referringKey]
4151 if referredName in referredBlockset:
4152 return referredBlockset[referredName]
4153
4154 if PhactoriDbg():
4155 myDebugPrint3(' warning: ' + referringKey + ' was expected to be in referredBlockset but was not, returning None\n')
4156 return None
4157
4158 def UpdatePipelineWithCurrentTimeArgument(inParaViewFilter):
4159 global gPipeAndViewsState
4160 if gPipeAndViewsState == None:
4161 inParaViewFilter.UpdatePipeline()
4162 return
4163 thisTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
4164 inParaViewFilter.UpdatePipeline(thisTime)
4165
4166 def SetParaViewViewToCurrentTime(inParaViewView):
4167 global gPipeAndViewsState
4168 thisTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
4169 inParaViewView.ViewTime = thisTime
4170
4171 def CreateParaViewRepresentationAndViewFromInfoC(inImageset, inLookDirection, inLookDirectionFilenameAddonL):
4172 global gPipeAndViewsState
4173
4174 if PhactoriDbg(100):
4175 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC entered\n",100)
4176 if PhactoriDbg():
4177 myDebugPrint3(" imageset: " + inImageset.mName + "\n")
4178 if PhactoriDbg():
4179 myDebugPrint3(" lookdir : " + str(inLookDirection) + " file name addon: " + str(inLookDirectionFilenameAddonL) + "\n")
4180
4181 newLookDirection = list(inLookDirection)
4182 inImageset.mLookDirectionList.append(newLookDirection)
4183 inImageset.mLookDirectionFilenameAddon.append(inLookDirectionFilenameAddonL)
4184
4185 theRepresentation = inImageset.mRepresentation
4186 theOperation = inImageset.mOperation
4187 inCamera = inImageset.mCamera
4188
4189 #we are setting this up, for now, so that you MUST have a representation at this
4190 #point--default should have been added and referenced earlier
4191 if theRepresentation == None:
4192 errStr = 'error! theRepresentation is None in CreateParaviewItemsForImagesetC\n'
4193 if PhactoriDbg():
4194 myDebugPrint3(errStr)
4195 raise Exception(errStr)
4196
4197 meshRenderControl = theRepresentation.mMeshRenderControl
4198
4199 showColorLegend = theRepresentation.mColorLegendFlag
4200 colorLegendPositionAndSize = theRepresentation.mColorLegendPositionAndSize
4201 showDataCubeAxes = theRepresentation.mDataCubeAxesFlag
4202 showOrientationAxes = theRepresentation.mOrientationAxesFlag
4203 if theRepresentation.mUseFixedColorRange == True:
4204 fixedColorRange = theRepresentation.mFixedColorRange
4205 else:
4206 fixedColorRange = None
4207
4208 savedActiveSource = GetActiveSource()
4209 if PhactoriDbg():
4210 myDebugPrint3(" operation is " + theOperation.mName + \
4211 " with ParaView Filter " + str(theOperation.GetPvFilter()) + "\n")
4212 pvPvGeomFilterFromOp = theOperation.GetOutgoingPvGeometryFilter()
4213 if PhactoriDbg():
4214 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC:\n"
4215 "setting active source to exterior geometry filter from operation\n"
4216 "active source A: " + str(GetActiveSource()) + "\n")
4217 SetActiveSource(pvPvGeomFilterFromOp)
4218 if PhactoriDbg():
4219 myDebugPrint3("active source B1: " + str(pvPvGeomFilterFromOp) + "\n")
4220 myDebugPrint3("active source B: " + str(GetActiveSource()) + "\n")
4221 UpdatePipelineWithCurrentTimeArgument(pvPvGeomFilterFromOp)
4222
4223 if PhactoriDbg():
4224 myDebugPrint3(" operation point data arrays:\n")
4225 numArrays = pvPvGeomFilterFromOp.PointData.GetNumberOfArrays()
4226 for ii in range (0, numArrays):
4227 myDebugPrint3(" " + str(ii) + ": " + pvPvGeomFilterFromOp.PointData.GetArray(ii).GetName() + "\n")
4228
4229 if PhactoriDbg():
4230 myDebugPrint3(" operation cell data arrays:\n")
4231 numArrays = pvPvGeomFilterFromOp.CellData.GetNumberOfArrays()
4232 for ii in range (0, numArrays):
4233 myDebugPrint3(" " + str(ii) + ": " + pvPvGeomFilterFromOp.CellData.GetArray(ii).GetName() + "\n")
4234
4235 if theRepresentation.mColorVariableInfo.mVariableName == '':
4236 myVariableArrayType = gCellsString
4237 else:
4238 #paraViewSource = \
4239 # gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
4240 paraViewSource = pvPvGeomFilterFromOp
4241 detectResult = theRepresentation.mColorVariableInfo.DetectVariableType(
4242 paraViewSource, True, False)
4243
4244 if detectResult == True:
4245 #variable type detected determine value for paraview
4246 if theRepresentation.mColorVariableInfo.mVariableType == 'node':
4247 myVariableArrayType = gPointsString
4248 elif theRepresentation.mColorVariableInfo.mVariableType == 'element':
4249 myVariableArrayType = gCellsString
4250 else:
4251 if PhactoriDbg():
4252 myDebugPrint3(errStr)
4253 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
4254 'image set ' + inImageset.mName + \
4255 ' representation ' + theRepresentation.mName + \
4256 '\ncolor variable name: ' + \
4257 theRepresentation.mColorVariableInfo.mVariableName +\
4258 '\nvariable should be node or element at this point and is not'
4259 raise Exception(errStr)
4260 else:
4261 #variable type not detected, deal with it
4262 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
4263 'image set ' + inImageset.mName + \
4264 ' representation ' + theRepresentation.mName + \
4265 '\ncolor variable name: ' + \
4266 theRepresentation.mColorVariableInfo.mVariableName +\
4267 '\nvariable is not point data or cell data, assuming cell'
4268 if PhactoriDbg():
4269 myDebugPrint3(errStr)
4270 #current hack--if detection of variable type fails due to missing
4271 #variable; assume it is CELLS and let mpi stuff share info
4272 #and create odd color map otherwise
4273 myVariableArrayType = gCellsString
4274
4275 global gCameraFilenameSuffixCounter
4276 gCameraFilenameSuffixCounter = 0
4277 SetUpOneParaViewRepresentationAndViewC(inImageset.mCamera,
4278 inLookDirection,
4279 inImagesetInfo = inImageset,
4280 inColorSettingsX = inImageset.mRepresentation.mColorSettings,
4281 inMeshRenderControl = meshRenderControl,
4282 inShowDataCubeAxes = showDataCubeAxes,
4283 inShowDataCubeAxesInfo = theRepresentation.mDataCubeAxesInfo,
4284 inShowOrientationAxes = showOrientationAxes,
4285 inFixedColorRange = fixedColorRange,
4286 inIsPlotFlag = False,
4287 inRepresentationFilenameAddon = theRepresentation.mFilenameAddon,
4288 inLookDirectionFilenameAddon = inLookDirectionFilenameAddonL,
4289 inPhactoriRepresentation = theRepresentation)
4290
4291 global currentPhactoriRenderViewInfo
4292 #newParaViewRenderInfoC.mParaViewInfo = currentPhactoriRenderViewInfo
4293
4294 if PhactoriDbg(100):
4295 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC returning\n", 100)
4296
4297 SetActiveSource(savedActiveSource)
4298
4299 if 1:
4300 if PhactoriDbg(100):
4301 myDebugPrint3("trying time annotation stuff\n", 100)
4302 timeAnnStngs = inImageset.mRepresentation.mTimeAnnotationSettings
4303 #since we are now using one RenderView, we can share a single time
4304 #annotation source representation. However, it is conceivable that
4305 #we may eventually want to show different times for some reason, and
4306 #in that case we will need to have each imageset have its own time
4307 #annotation paraview stuff
4308 if timeAnnStngs.mVisible:
4309 if gPipeAndViewsState.mTimeAnnotationPv == None:
4310 gPipeAndViewsState.mTimeAnnotationPv = \
4311 PhactoriAnnotationPv(timeAnnStngs)
4312 global gTemporaryGlobalImageTextColor
4313 gPipeAndViewsState.mTimeAnnotationPv.CreateParaViewStuff(
4314 #inImageset.mRepresentation.mColorSettings.mTimeAnnotationColor,
4315 gTemporaryGlobalImageTextColor,
4316 inImageset)
4317
4318 #if newParaViewRenderInfoC.mTimeAnnotationPv == None:
4319 # newParaViewRenderInfoC.mTimeAnnotationPv = \
4320 # PhactoriAnnotationPv(timeAnnStngs)
4321 # newParaViewRenderInfoC.mTimeAnnotationPv.CreateParaViewStuff(
4322 # inImageset.mRepresentation.mColorSettings.mTimeAnnotationColor,
4323 # inImageset)
4324
4325
4326 def CreateParaviewItemsForImagesetC(inImageset):
4327 """given a json block structure as discussed in the catalyst sierra
4328 insitu wiki, create the corresponding one imageset (view) based on
4329 a particular imageset block and the availa"""
4330
4331 theCamera = inImageset.mCamera
4332
4333 #we are setting this up, for now, so that you MUST have a camera at this
4334 #point--default should have been added and referenced earlier
4335 if theCamera == None:
4336 errStr = 'error! theCamera is None in "\
4337 "CreateParaviewItemsForImagesetC\n'
4338 if PhactoriDbg():
4339 myDebugPrint3(errStr)
4340 raise Exception(errStr)
4341
4342 cameraLookDirectionAndFilenameAddonList = GetLookDirectionListFromCamera(theCamera)
4343
4344 #counter = 0
4345 for oneItem in cameraLookDirectionAndFilenameAddonList:
4346 #print oneItem
4347 oneDirection = oneItem[0]
4348 oneDirectionFilenameAddon = oneItem[1]
4349 CreateParaViewRepresentationAndViewFromInfoC(inImageset, oneDirection,
4350 oneDirectionFilenameAddon)
4351 #counter = counter + 1
4352
4353 def ParseOneCriteriaBlockC(ioCriteriaBlock, ioCriteriaBlockJson,
4354 inPipeAndViewsState):
4355 ioCriteriaBlock.ParseParametersFromJson(ioCriteriaBlockJson)
4356
4357 def ParseOneMarkerBlockC(ioMarkerBlock, ioBlockJson,
4358 inPipeAndViewsState):
4359 ioMarkerBlock.ParseMarkerSettingsFromJson(ioBlockJson)
4360
4361 def ParseOneTextAnnotationBlockC(ioTextAnnotationBlock, ioBlockJson,
4362 inPipeAndViewsState):
4363 ioTextAnnotationBlock.ParseTextAnnotationSettingsFromJson(ioBlockJson)
4364
4365 def ParseOneCameraBlockC(ioCameraBlock, ioCameraBlockJson, inPipeAndViewsState):
4366 #parse camera type
4367 if 'camera type' not in ioCameraBlockJson:
4368 errStr = 'error! camera block with name ' + str(ioCameraBlock.mName) + \
4369 ' has no camera type key in ParseCameraBlocksC\n'
4370 if PhactoriDbg():
4371 myDebugPrint3(errStr)
4372 raise Exception(errStr)
4373
4374 cameraType = ioCameraBlockJson['camera type']
4375
4376 if cameraType != 'camera' and cameraType != 'multicamera8':
4377 errStr = 'camera type entry is not recognized in camera ' + ioCameraBlock.mName + ' ParseCameraBlocksC\n'
4378 if PhactoriDbg():
4379 myDebugPrint3(errStr)
4380 raise Exception(errStr)
4381
4382 ioCameraBlock.mType = cameraType
4383
4384 #check for camera at node|element displaced settings
4385 ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \
4386 ioCameraBlockJson, "camera at ", " displaced", True)
4387 if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting == False:
4388 #check for camera at settings (not displaced) if there weren't displaced ones
4389 ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \
4390 ioCameraBlockJson, "camera at ", "", False)
4391 if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting:
4392 ioCameraBlock.mUseCameraAtPointFlag = True
4393 else:
4394 ioCameraBlock.mUseCameraAtPointFlag = False
4395
4396 if PhactoriDbg():
4397 myDebugPrint3("camera parsing look at point:\n")
4398 ioCameraBlock.mLookAtPointInfo.UserPointInfoParseParametersFromJson(ioCameraBlockJson,
4399 "look at ", "")
4400
4401 #parse look at distance
4402 if 'look at relative distance' in ioCameraBlockJson:
4403 ioCameraBlock.mLookAtDistanceType = 'datasize relative'
4404 ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at relative distance']
4405 #if 'camera at point' was specified, look at distance should not
4406 #be specified
4407 elif 'look at absolute distance' in ioCameraBlockJson:
4408 ioCameraBlock.mLookAtDistanceType = 'absolute'
4409 ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at absolute distance']
4410 #if 'camera at point' was specified, look at distance should not
4411 #be specified
4412 else:
4413 ioCameraBlock.mLookAtDistanceType = 'datasize relative'
4414 ioCameraBlock.mLookAtDistance = 1.0
4415
4416 #parse look direction (single camera, not multicamera8)
4417 if ioCameraBlock.mType == 'camera':
4418 ioCameraBlock.mLookDirection = [-1.0, -1.0, -1.0]
4419 if 'look direction' in ioCameraBlockJson:
4420 ioCameraBlock.mLookDirection = ioCameraBlockJson['look direction']
4421 ioCameraBlock.mLookDirectionSpecifiedFlag = True
4422 else:
4423 ioCameraBlock.mLookDirectionSpecifiedFlag = False
4424
4425 #get text to add to each image created with this camera, if any
4426 if "image name addon" in ioCameraBlockJson:
4427 ioCameraBlock.mFilenameAddon = ioCameraBlockJson["image name addon"]
4428
4429 #camera field of view (for default use current value which was set at
4430 #creation time--see class definition for default
4431 ioCameraBlock.mViewAngle = getParameterFromBlock(ioCameraBlockJson,
4432 'camera fov', ioCameraBlock.mViewAngle)
4433
4434 #up vector for the view (for default use current value which was set at
4435 #creation time--see class definition for default)
4436 ioCameraBlock.mViewUpVector = getParameterFromBlock(ioCameraBlockJson,
4437 'up vector', ioCameraBlock.mViewUpVector)
4438
4439 #parse off-axis projection info
4440 ioCameraBlock.mOffAxisProjectionInfo.ParseParametersFromJson(
4441 ioCameraBlockJson)
4442
4443 #parse parallel projection info
4444 perspectiveOrParallel = getParameterFromBlock(ioCameraBlockJson,
4445 'projection type', 'perspective')
4446 if perspectiveOrParallel == 'parallel':
4447 ioCameraBlock.mUseParallelProjection = True
4448 if PhactoriDbg(100):
4449 myDebugPrint3("projection type is now parallel\n", 100)
4450 if 'absolute parallel scale' in ioCameraBlockJson:
4451 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 0
4452 ioCameraBlock.mParallelScale = \
4453 ioCameraBlockJson['absolute parallel scale']
4454 if PhactoriDbg(100):
4455 myDebugPrint3("absolute parallel scale: " + \
4456 str(ioCameraBlock.mParallelScale) + "\n", 100)
4457 elif 'relative parallel scale' in ioCameraBlockJson:
4458 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1
4459 ioCameraBlock.mParallelScale = \
4460 ioCameraBlockJson['relative parallel scale']
4461 if PhactoriDbg(100):
4462 myDebugPrint3("relative parallel scale: " + \
4463 str(ioCameraBlock.mParallelScale) + "\n", 100)
4464 else:
4465 ioCameraBlock.mParallelScale = 1.0
4466 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1
4467 if PhactoriDbg(100):
4468 myDebugPrint3("default relative parallel scale: " + \
4469 str(ioCameraBlock.mParallelScale) + "\n", 100)
4470
4471 #parse locking setup
4472 ioCameraBlock.LockAfterNCalls = getParameterFromBlock(ioCameraBlockJson,
4473 'lock camera call count', -1)
4474 if "lockingcamera" in ioCameraBlock.mName:
4475 ioCameraBlock.LockAfterNCalls = 1
4476
4477
4478 def localGet1or0(inJsn, inKey, inDefault):
4479 value = getParameterFromBlock(inJsn, inKey, inDefault)
4480 if value:
4481 return 1
4482 else:
4483 return 0
4484
4485 def ParseOneRepresentationBlockC(ioRepresentationBlock, inRepresentationBlockJson, inPipeAndViewsState):
4486 ioRepresentationBlock.ParseSettingsFromJson(inRepresentationBlockJson)
4487
4488 global gDefaultImageBasename
4489 gDefaultImageBasename = "csierra.view."
4490
4491 def SetDefaultImageBasename(inNewImageBasename):
4492 global gDefaultImageBasename
4493 gDefaultImageBasename = inNewImageBasename
4494
4495 def breakSpecialVarNameIntoBaseAndComponent(inSpecialVarName,
4496 inAddSeparatorFlag):
4497
4498 twoDigitComponentFlag = False
4499
4500 varNameLen = len(inSpecialVarName)
4501 if varNameLen < 2:
4502 errStr = ' in breakSpecialVarNameIntoBaseAndComponent representation bad color by vector component name (too short)\n'
4503 if PhactoriDbg():
4504 myDebugPrint3(errStr)
4505 raise Exception(errStr)
4506 lastVarChar = inSpecialVarName[varNameLen - 1]
4507 if PhactoriDbg():
4508 myDebugPrint3(' lastVarChar: ' + str(lastVarChar) + '\n')
4509 if lastVarChar == 'X' or lastVarChar == 'x':
4510 component = 0
4511 elif lastVarChar == 'Y' or lastVarChar == 'y':
4512 component = 1
4513 elif lastVarChar == 'Z' or lastVarChar == 'z':
4514 component = 2
4515 elif str(lastVarChar).isdigit():
4516 end2car = inSpecialVarName[varNameLen-2:varNameLen]
4517 if PhactoriDbg():
4518 myDebugPrint3(' end2car: ' + end2car + ' isdigit: ' + str(end2car.isdigit()) + '\n')
4519 if end2car.isdigit():
4520 twoDigitComponentFlag = True
4521 component = int(end2car)
4522 else:
4523 component = int(str(lastVarChar))
4524 else:
4525 errStr = ' in breakSpecialVarNameIntoBaseAndComponent representation bad color by vector component name (does not end in X Y or Z or 1 or two character integer)\n'
4526 if PhactoriDbg():
4527 myDebugPrint3(errStr)
4528 raise Exception(errStr)
4529 #baseVarName = inSpecialVarName[0:(varNameLen-2)] + GetSeparatorString()
4530
4531 localinAddSeparatorFlag = inAddSeparatorFlag
4532 #for Sierra, as of 2022Aug09, we need inAddSeparatorFlag to default to
4533 #False but right here we need to strip the separator from the variable
4534 #base name
4535 #localinAddSeparatorFlag = True
4536 if localinAddSeparatorFlag:
4537 lenToGrab = varNameLen - 1 - len(GetSeparatorString())
4538 else:
4539 lenToGrab = varNameLen - 1
4540 if twoDigitComponentFlag:
4541 lenToGrab -= 1
4542
4543 varNameWithoutSeparator = inSpecialVarName[0:lenToGrab]
4544
4545 if inAddSeparatorFlag:
4546 baseVarName = varNameWithoutSeparator + GetSeparatorString()
4547 else:
4548 baseVarName = varNameWithoutSeparator
4549
4550 return [baseVarName, component, varNameWithoutSeparator]
4551
4552 def CreateDirectoryFromProcessZero(inDirname):
4553 if SmartGetLocalProcessId() != 0:
4554 if PhactoriDbg():
4555 myDebugPrint3('CreateDirectoryFromProcessZero, not process 0\n')
4556 return
4557
4558 if inDirname == '':
4559 if PhactoriDbg():
4560 myDebugPrint3('CreateDirectoryFromProcessZero, no directory to create\n')
4561 return
4562
4563 #test for directory existence, try to create if not existing
4564 import os
4565 if PhactoriDbg():
4566 myDebugPrint3('find or create directory: ' + str(inDirname) + '\n')
4567 if os.path.exists(inDirname):
4568 if os.path.isdir(inDirname) != True:
4569 errStr = \
4570 ' path to base directory exists and is not a directory\n' + \
4571 ' (' + str(inDirname) + ')\n'
4572 myDebugPrint3AndException(errStr)
4573 else:
4574 if PhactoriDbg():
4575 myDebugPrint3('inDirname found and is directory\n')
4576 else:
4577 if PhactoriDbg():
4578 myDebugPrint3(str(inDirname) + ' to be created\n')
4579 try:
4580 os.makedirs(inDirname)
4581 except:
4582 errStr = \
4583 ' failed (1) to create directory\n' + \
4584 ' (' + str(inDirname) + ')\n'
4585 myDebugPrint3AndException(errStr)
4586 if os.path.exists(inDirname) != True:
4587 errStr = \
4588 ' failed (2) to create directory\n' + \
4589 ' (' + str(inDirname) + ')\n'
4590 myDebugPrint3AndException(errStr)
4591
4592 class PhactoriImageSettings:
4593 def __init__(self):
4594 self.mImageBasename = None
4595 global gPipeAndViewsState
4596 self.mImageBasedirectory = gPipeAndViewsState.mDefaultBasedirectory
4597 global gDefaultImageSizeX
4598 global gDefaultImageSizeY
4599 self.mImageSize = [gDefaultImageSizeX, gDefaultImageSizeY]
4600 self.mImageFormat = 'png'
4601 global gDefaultNumCounterDigits
4602 self.mNumCounterDigits = gDefaultNumCounterDigits
4603 self.mUsingDefaultGeneratedImageBasename = False
4604 self.mPixelBorderRatioXY = gPixelBorderRatioXY
4605 def GetAspectRatio(self):
4606 return float(self.mImageSize[0]) / float(self.mImageSize[1])
4607 def GetAspectRatioInsidePixelBorder(self):
4608 vertPixBrdrX = self.mPixelBorderRatioXY[0] * float(self.mImageSize[0])
4609 vertPixBrdrY = self.mPixelBorderRatioXY[1] * float(self.mImageSize[1])
4610 vertPixBrdrX = math.ceil(vertPixBrdrX)
4611 vertPixBrdrY = math.ceil(vertPixBrdrY)
4612 insideVertPixX = float(self.mImageSize[0]) - 2.0 * vertPixBrdrX
4613 insideVertPixY = float(self.mImageSize[1]) - 2.0 * vertPixBrdrY
4614 insideAspectRatio = insideVertPixX / insideVertPixY
4615 return insideAspectRatio
4616
4617 def ParseImageSettingsInfo(self, inImageSettingsJson,
4618 inImageBasenameKey, inImageBaseDirectoryKey):
4619 self.mImageBasename = getParameterFromBlock(inImageSettingsJson,
4620 inImageBasenameKey, self.mImageBasename)
4621 if self.mImageBasename == None:
4622 global gDefaultImageBasename
4623 global gPipeAndViewsState
4624 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
4625 imageSetCount = gPipeAndViewsState.mImageSetCounter
4626 gPipeAndViewsState.mImageSetCounter += 1
4627 self.mImageBasename = gDefaultImageBasename + \
4628 ".b-" + blockCountIdStr + "-is-" + str(imageSetCount) + "."
4629 self.mUsingDefaultGeneratedImageBasename = True
4630
4631 self.mImageBasedirectory = getParameterFromBlock(inImageSettingsJson,
4632 inImageBaseDirectoryKey, self.mImageBasedirectory)
4633
4634 CreateDirectoryFromProcessZero(self.mImageBasedirectory)
4635
4636 global gDefaultImageSizeX
4637 global gDefaultImageSizeY
4638 self.mImageSize = getParameterFromBlock(inImageSettingsJson,
4639 'image size', self.mImageSize)
4640
4641 self.mImageFormat = getParameterFromBlock(inImageSettingsJson,
4642 'image format', self.mImageFormat)
4643
4644 self.mNumCounterDigits = getParameterFromBlock(\
4645 inImageSettingsJson,
4646 'image digit count', self.mNumCounterDigits)
4647 if PhactoriDbg():
4648 myDebugPrint3(' mNumCounterDigits is ' + str(self.mNumCounterDigits) + '\n')
4649
4650
4651 def ParseOneImagesetBlockC(ioImagesetBlock, ioImagesetBlockJson,
4652 ioPipeAndViewsState):
4653
4654 #hack--if we have an imageset with a particular name, we enable
4655 #interaction
4656 if ioImagesetBlock.mName == 'PhactoriGoInteractive':
4657 ioPipeAndViewsState.mInteractionEnabled = True
4658
4659 #we need to get text color for time annotation and text annotation
4660 #handled properly: for now we allow a "text color" setting in any
4661 #imageset block to set the global text color
4662 if 'text color' in ioImagesetBlockJson:
4663 global gTemporaryGlobalImageTextColor
4664 gTemporaryGlobalImageTextColor = getParameterFromBlock(ioImagesetBlockJson,
4665 'text color', [1.0, 1.0, 1.0])
4666
4667 ioImagesetBlock.mBackground = getParameterFromBlock(ioImagesetBlockJson,
4668 'background color', ioImagesetBlock.mBackground)
4669
4670 #parse on/off criteria
4671 if 'onoff criteria' in ioImagesetBlockJson:
4672 inCriteriaList = ioImagesetBlockJson['onoff criteria']
4673 for oneCriteriaName in inCriteriaList:
4674 if oneCriteriaName not in \
4675 ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks:
4676 myDebugPrint3AndException("ParseOneImagesetBlockC:"
4677 "imageset with name: " + ioImagesetBlock.mName + "\n"
4678 "calls for nonexistent onoff criteria with name: " + \
4679 oneCriteriaName + "\n")
4680 ioImagesetBlock.mImagesetOnOffFilter.AddStartCriteria( \
4681 ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks[oneCriteriaName])
4682
4683 if 'camera' not in ioImagesetBlockJson:
4684 #we have to construct and use a default camera, including parsing
4685 #commands in the imageset for the camera
4686 if PhactoriDbg():
4687 myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
4688 ioImagesetBlock.mName + \
4689 " there is no camera, so we must add and reference default\n")
4690 if 'camera type' not in ioImagesetBlockJson:
4691 ioImagesetBlockJson['camera type'] = 'multicamera8'
4692 defaultCameraName = ioImagesetBlock.mName + '_default_camera'
4693 defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}
4694 ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,
4695 defaultCameraBlockAndWrapper,
4696 PhactoriCameraBlock,
4697 ParseOneCameraBlockC,
4698 ioPipeAndViewsState)
4699 ioImagesetBlockJson['camera'] = defaultCameraName
4700 #myDebugPrint3( "done adding camera, here it is:\n")
4701 #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()
4702
4703
4704 #there is a camera (if there wasn't, we added it), so get the reference
4705 cameraName = ioImagesetBlockJson['camera']
4706 if cameraName not in ioPipeAndViewsState.mCameraBlocks:
4707 errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for camera (' + str(cameraName) + ') which does not exist\n'
4708 if PhactoriDbg():
4709 myDebugPrint3(errStr)
4710 raise Exception(errStr)
4711
4712 ioImagesetBlock.mCamera = ioPipeAndViewsState.mCameraBlocks[cameraName]
4713 if PhactoriDbg():
4714 myDebugPrint3(" image set " + ioImagesetBlock.mName + " is using the following camera:\n")
4715 ioImagesetBlock.mCamera.PrintSelf()
4716
4717 if 'markers' in ioImagesetBlockJson:
4718 ioImagesetBlock.mVisibleMarkerNames = ioImagesetBlockJson['markers']
4719 for oneMarkerName in ioImagesetBlock.mVisibleMarkerNames:
4720 if oneMarkerName in ioPipeAndViewsState.mMarkerBlocks:
4721 ioImagesetBlock.mVisibleMarkers.append(
4722 ioPipeAndViewsState.mMarkerBlocks[oneMarkerName])
4723 else:
4724 myDebugPrint3AndException(
4725 "ParseOneImagesetBlockC:\n" \
4726 "image set with name: " + ioImagesetBlock.mName + "\n"
4727 "calls for nonexistent marker named: " + oneMarkerName + "\n")
4728
4729 if 'text annotations' in ioImagesetBlockJson:
4730 ioImagesetBlock.mTextAnnotationNames = \
4731 ioImagesetBlockJson['text annotations']
4732 for oneMarkerName in ioImagesetBlock.mTextAnnotationNames:
4733 if oneMarkerName in ioPipeAndViewsState.mTextAnnotationBlocks:
4734 ioImagesetBlock.mTextAnnotations.append(
4735 ioPipeAndViewsState.mTextAnnotationBlocks[oneMarkerName])
4736 else:
4737 myDebugPrint3AndException(
4738 "ParseOneImagesetBlockC:\n" \
4739 "image set with name: " + ioImagesetBlock.mName + "\n"
4740 "calls for nonexistent marker named: " + oneMarkerName + "\n")
4741
4742 #if 'representation' not in ioImagesetBlockJson:
4743 # #we have to construct and use a default representation, including parsing
4744 # #commands in the imageset for the representation
4745 # if PhactoriDbg():
4746 # myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
4747 # ioImagesetBlock.mName + \
4748 # " there is no representation, " +
4749 # "so we must add and reference default\n")
4750 # defaultRepName = ioImagesetBlock.mName + '_default_representation'
4751 # defaultRepBlockAndWrapper = {defaultRepName: ioImagesetBlockJson}
4752 # ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,
4753 # defaultRepBlockAndWrapper,
4754 # PhactoriRepresentationBlock,
4755 # ParseOneRepresentationBlockC,
4756 # ioPipeAndViewsState)
4757 # ioImagesetBlockJson['representation'] = defaultRepName
4758
4759 #if 'representation' in ioImagesetBlockJson:
4760 # representationName = ioImagesetBlockJson['representation']
4761 # if representationName not in ioPipeAndViewsState.mRepresentationBlocks:
4762 # errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for representation (' + str(representationName) + ') which does not exist\n'
4763 # if PhactoriDbg():
4764 # myDebugPrint3(errStr)
4765 # raise Exception(errStr)
4766 # ioImagesetBlock.mRepresentation = ioPipeAndViewsState.mRepresentationBlocks[representationName]
4767 #else:
4768 # ioImagesetBlock.mRepresentation = None #need to use default representation
4769 #ioImagesetBlock.mVisibleReps.append(ioImagesetBlock.mRepresentation)
4770
4771 ##get the operation referred to by this image set (or the default incoming
4772 ##data)
4773 #ioImagesetBlock.mOperation =\
4774 # ioPipeAndViewsState.GetOperationReferredByJson(
4775 # 'operation', ioImagesetBlockJson)
4776 #ioImagesetBlock.mVisibleOps.append(ioImagesetBlock.mOperation)
4777
4778 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
4779 ioImagesetBlockJson, 'operation', False, 'representation', False, False)
4780 ioImagesetBlock.mOperation = ioImagesetBlock.mVisibleOps[0]
4781 ioImagesetBlock.mRepresentation = ioImagesetBlock.mVisibleReps[0]
4782
4783 #initial implementation of having more than one operation visible:
4784 #have up to 3 visible with particular parsing names
4785 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
4786 ioImagesetBlockJson, 'operation2', True, 'representation2', True, True)
4787 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
4788 ioImagesetBlockJson, 'operation3', True, 'representation3', True, True)
4789
4790 ioImagesetBlock.mImageSettings.ParseImageSettingsInfo(
4791 ioImagesetBlockJson, 'image basename', 'image basedirectory')
4792 ioImagesetBlock.mImageFileNameCountSettings.\
4793 ParseImageFileNameCountSettings(ioImagesetBlockJson)
4794
4795
4796 def SetUpPlotAxisNameDetails(inVariableInfo, ioDataCubeAxisInfo):
4797 if inVariableInfo.mVariableIsVectorComponent:
4798 if PhactoriDbg():
4799 myDebugPrint3(" vector is component, setting y axis name\n")
4800 varNameForPlot = inVariableInfo.mVectorBaseName
4801 if inVariableInfo.mVariableComponent == 0:
4802 varNameForPlot = varNameForPlot + '[x]'
4803 elif inVariableInfo.mVariableComponent == 1:
4804 varNameForPlot = varNameForPlot + '[y]'
4805 elif inVariableInfo.mVariableComponent == 2:
4806 varNameForPlot = varNameForPlot + '[z]'
4807 else:
4808 varNameForPlot = varNameForPlot + str(inVariableInfo.mVariableComponent)
4809 ioDataCubeAxisInfo.mUseLabelFlag = True
4810 ioDataCubeAxisInfo.mAxisLabel = varNameForPlot
4811 ioDataCubeAxisInfo.mBaseAxisLabel = varNameForPlot
4812 if PhactoriDbg():
4813 myDebugPrint3(" y axis name is " + ioDataCubeAxisInfo.mAxisLabel + "\n")
4814 elif inVariableInfo.mVariableIsVectorMagnitude:
4815 if PhactoriDbg():
4816 myDebugPrint3(" vector is magnitude, setting y axis name\n")
4817 varNameForPlot = inVariableInfo.mVectorBaseName
4818 varNameForPlot = varNameForPlot + " Magnitude"
4819 ioDataCubeAxisInfo.mUseLabelFlag = True
4820 ioDataCubeAxisInfo.mAxisLabel = varNameForPlot
4821 ioDataCubeAxisInfo.mBaseAxisLabel = varNameForPlot
4822 if PhactoriDbg():
4823 myDebugPrint3(" y axis name is " + ioDataCubeAxisInfo.mAxisLabel + "\n")
4824 else:
4825 ioDataCubeAxisInfo.mUseLabelFlag = True
4826 ioDataCubeAxisInfo.mAxisLabel = inVariableInfo.mVariableName
4827 ioDataCubeAxisInfo.mBaseAxisLabel = inVariableInfo.mVariableName
4828
4829 def ParseOnePlotOverTimeBlockC(ioPlotOverTimeBlock, inPlotOverTimeBlockJson, inPipeAndViewsState):
4830 if PhactoriDbg(100):
4831 myDebugPrint3('ParseOnePlotOverTimeBlockC entered\n', 100)
4832
4833 #hack test for colors start
4834 #inPlotOverTimeBlockJson['background color'] = [0.0, 0.0, 0.0]
4835 ##inJsn['axes color'] = [0.0, 1.0, 1.0]
4836 #inPlotOverTimeBlockJson['text color'] = [1.0, 1.0, 0.0]
4837 #inPlotOverTimeBlockJson['line color'] = [1.0, 1.0, 1.0]
4838 #hack test for colors end
4839
4840 ioPlotOverTimeBlock.mImageSettings.ParseImageSettingsInfo(
4841 inPlotOverTimeBlockJson, 'plot basename', 'plot basedirectory')
4842 ioPlotOverTimeBlock.mImageFileNameCountSettings.\
4843 ParseImageFileNameCountSettings(inPlotOverTimeBlockJson)
4844
4845 ioPlotOverTimeBlock.mBackground = getParameterFromBlock(inPlotOverTimeBlockJson,
4846 'background color', ioPlotOverTimeBlock.mBackground)
4847
4848 if PhactoriDbg():
4849 myDebugPrint3(str(inPlotOverTimeBlockJson) + '\n')
4850
4851 #parse y axis variable
4852 ioPlotOverTimeBlock.m_YAxisVariableInfo.\
4853 ParseVariableNameAndVectorOrTensorComponent(inPlotOverTimeBlockJson,
4854 'variable ')
4855
4856 #handle name of axis, particularly in vector component/magnitude case
4857 SetUpPlotAxisNameDetails(ioPlotOverTimeBlock.m_YAxisVariableInfo,
4858 ioPlotOverTimeBlock.m_DataCubeAxesInfo.mYAxisInfo)
4859
4860 #parse whether to draw min, max mean
4861 if 'plot minimum' in inPlotOverTimeBlockJson:
4862 ioPlotOverTimeBlock.mPlotMinimumFlag = inPlotOverTimeBlockJson['plot minimum']
4863 else:
4864 ioPlotOverTimeBlock.mPlotMinimumFlag = True
4865 if 'plot maximum' in inPlotOverTimeBlockJson:
4866 ioPlotOverTimeBlock.mPlotMaximumFlag = inPlotOverTimeBlockJson['plot maximum']
4867 else:
4868 ioPlotOverTimeBlock.mPlotMaximumFlag = True
4869 if 'plot mean' in inPlotOverTimeBlockJson:
4870 ioPlotOverTimeBlock.mPlotMeanFlag = inPlotOverTimeBlockJson['plot mean']
4871 else:
4872 ioPlotOverTimeBlock.mPlotMeanFlag = True
4873
4874 if 'plot id' in inPlotOverTimeBlockJson:
4875 idList = inPlotOverTimeBlockJson['plot id']
4876 for ii in idList:
4877 newIdPlotLine = PhactoriPlotOverTimeIdLine(ii)
4878 ioPlotOverTimeBlock.m_IdPlotLineList.append(newIdPlotLine)
4879
4880 ioPlotOverTimeBlock.m_xyzMinMaxTrkC.PlotXYZMinMaxTrkCParseJson(inPlotOverTimeBlockJson, 'axis ')
4881
4882 #hack to test missing data situations
4883 #if ioPlotOverTimeBlock.mName == "fooPlot":
4884 # myDebugPrint3("hack to test missing data, found fooPlot, using stressthresh\n")
4885 # ioPlotOverTimeBlock.mInputOperation = inPipeAndViewsState.mOperationBlocks["stressthresh"]
4886 #else:
4887 # myDebugPrint3("hack to test missing data, did not find fooPlot\n")
4888 # ioPlotOverTimeBlock.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson('operation', inJsn)
4889
4890 ioPlotOverTimeBlock.mInputOperation = \
4891 inPipeAndViewsState.GetOperationReferredByJson('operation',
4892 inPlotOverTimeBlockJson)
4893
4894 ioPlotOverTimeBlock.mColorSettings.\
4895 ParsePlotColorSettingsFromJson(inPlotOverTimeBlockJson)
4896
4897 if PhactoriDbg(100):
4898 myDebugPrint3('ParseOnePlotOverTimeBlockC returning:\n', 100)
4899 return
4900
4901 def ParseBlocksC2(ioBlockSet, inBlocksJson, inBlockClass, ioPipeAndViewsState):
4902 if PhactoriDbg(100):
4903 myDebugPrint3('ParseBlocksC2 entered\n', 100)
4904 count = 0
4905 for blockName, blockParamsJson in inBlocksJson.items():
4906 count = count + 1
4907 newBlockInstance = inBlockClass()
4908 newBlockInstance.mName = blockName
4909 if PhactoriDbg():
4910 myDebugPrint3(' creating block named ' + newBlockInstance.mName + '\n')
4911 if PhactoriDbg():
4912 myDebugPrint3(str(blockParamsJson) + '\n')
4913 newBlockInstance.ParseParametersFromJson(blockParamsJson, ioPipeAndViewsState)
4914 ioBlockSet[newBlockInstance.mName] = newBlockInstance
4915 if PhactoriDbg(100):
4916 myDebugPrint3('ParseBlocksC2 returning\n', 100)
4917 return count
4918
4919 def ParseBlocksC(ioBlockSet, inBlocksJson, inBlockClass, inParseOneBlockMethod,
4920 ioPipeAndViewsState):
4921 if PhactoriDbg(100):
4922 myDebugPrint3('ParseBlocksC entered\n', 100)
4923 count = 0
4924 for blockName, blockParamsJson in inBlocksJson.items():
4925 count = count + 1
4926 newBlockInstance = inBlockClass()
4927 newBlockInstance.mName = blockName
4928 if PhactoriDbg():
4929 myDebugPrint3(' creating block named ' + newBlockInstance.mName + '\n')
4930 if PhactoriDbg():
4931 myDebugPrint3(str(blockParamsJson) + '\n')
4932 inParseOneBlockMethod(newBlockInstance, blockParamsJson, ioPipeAndViewsState)
4933 ioBlockSet[newBlockInstance.mName] = newBlockInstance
4934 if PhactoriDbg(100):
4935 myDebugPrint3('ParseBlocksC returning\n', 100)
4936 return count
4937
4938 class PhactoriUserPointInfo:
4939 """user specified point: absolute, relative, at element, node, data value, etc."""
4940
4941 def __init__(self):
4942 #'absolute' or 'datasize relative' or 'element' or 'node'
4943 self.mPointType = "datasize relative"
4944 self.mElementOrNodeId = None
4945 self.mXyz = [0.0, 0.0, 0.0]
4946 self.mMayChangeWithData = False
4947 #flag tracking whether any information was filled in due to parsing
4948 #or if default is simply being used because of no parsed items
4949 self.mParseHadKeys = None
4950 self.mHasDisplacedInfoFlag = False
4951 self.mDisplacement = [0.0, 0.0, 0.0]
4952 self.mParsingDetectedAtLeastOneSetting = False
4953 self.mReferenceVariableInfo = None
4954
4955 #for tracking which source input to use if point is at min or max
4956 #variable
4957 self.mInputNameToUseForMinMaxVariable = None
4958 self.mInputPvSourceToUseForMinMaxVariable = None
4959
4960 def UserPointHasValidDisplacementInfo(self):
4961 return self.mHasDisplacedInfoFlag
4962
4963 def ParseIdAndDisplacement(self, inDisplacementFlag, inJson, inKey):
4964 if inDisplacementFlag:
4965 params = inJson[inKey]
4966 self.mElementOrNodeId = params[0]
4967 self.mHasDisplacedInfoFlag = True
4968 self.mDisplacement[0] = params[1]
4969 self.mDisplacement[1] = params[2]
4970 self.mDisplacement[2] = params[3]
4971 if PhactoriDbg():
4972 myDebugPrint3(" displacement is " + str(self.mDisplacement) + "\n")
4973 else:
4974 self.mElementOrNodeId = inJson[inKey]
4975
4976 def UserPointInfoParseParametersFromJson(self, inJson, inKeyPrefix, inKeySuffix,
4977 inDisplacementFlag = False):
4978 self.mParseHadKeys = False
4979 keyAbsolute = inKeyPrefix + "absolute point" + inKeySuffix
4980 keyRelative = inKeyPrefix + "relative point" + inKeySuffix
4981 keyNode = inKeyPrefix + "node" + inKeySuffix
4982 keyElement = inKeyPrefix + "element" + inKeySuffix
4983 keyMaxVar = inKeyPrefix + "max variable point" + inKeySuffix
4984 keyMinVar = inKeyPrefix + "min variable point" + inKeySuffix
4985 keyDataPt = inKeyPrefix + "data point" + inKeySuffix
4986
4987 if keyAbsolute in inJson:
4988 self.mParsingDetectedAtLeastOneSetting = True
4989 self.mPointType = "absolute"
4990 self.mXyz = inJson[keyAbsolute]
4991 self.mMayChangeWithData = False
4992 elif keyRelative in inJson:
4993 self.mParsingDetectedAtLeastOneSetting = True
4994 self.mPointType = "datasize relative"
4995 self.mXyz = inJson[keyRelative]
4996 self.mMayChangeWithData = True
4997 elif keyNode in inJson:
4998 self.mParsingDetectedAtLeastOneSetting = True
4999 if PhactoriDbg():
5000 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson node found\n")
5001 self.mPointType = "node"
5002 self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyNode)
5003 self.mMayChangeWithData = True
5004 if PhactoriDbg():
5005 myDebugPrint3(" node id is " + str(self.mElementOrNodeId) + "\n")
5006 elif keyElement in inJson:
5007 self.mParsingDetectedAtLeastOneSetting = True
5008 if PhactoriDbg():
5009 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson element found\n")
5010 self.mPointType = "element"
5011 self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyElement)
5012 self.mMayChangeWithData = True
5013 if PhactoriDbg():
5014 myDebugPrint3(" element id is " + str(self.mElementOrNodeId) + "\n")
5015 elif keyMinVar in inJson:
5016 self.mParsingDetectedAtLeastOneSetting = True
5017 self.mPointType = "min variable"
5018 #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):
5019 self.mReferenceVariableInfo = PhactoriVariableInfo()
5020 self.mReferenceVariableInfo.\
5021 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
5022 self.mMayChangeWithData = True
5023 if PhactoriDbg():
5024 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson "
5025 "min variable found\n"
5026 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
5027 varSourceKey = inKeyPrefix + "input for min variable point" + inKeySuffix
5028 if varSourceKey in inJson:
5029 self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]
5030 myDebugPrint3("input name for min variable point: " + \
5031 self.mInputNameToUseForMinMaxVariable + "\n")
5032 varDispKey = \
5033 inKeyPrefix + "displacement for min variable point" + inKeySuffix
5034 if varDispKey in inJson:
5035 self.mDisplacement = inJson[varDispKey]
5036 myDebugPrint3("displacement for min variable point: " + \
5037 str(self.mDisplacement) + "\n")
5038 elif keyDataPt in inJson:
5039 self.mParsingDetectedAtLeastOneSetting = True
5040 if PhactoriDbg():
5041 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson: "
5042 "parsing data point")
5043 params = inJson[keyDataPt]
5044 if inDisplacementFlag:
5045 #better have 7 items
5046 if len(params) != 7:
5047 myDebugPrint3AndException(
5048 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
5049 "data point displaced expected 7 parameters")
5050 else:
5051 #better have 4 items
5052 if len(params) != 4:
5053 myDebugPrint3AndException(
5054 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
5055 "data point expected 4 parameters")
5056 param0 = params[0].lower()
5057 if param0 == "min":
5058 self.mPointType = "min variable"
5059 if param0 == "max":
5060 self.mPointType = "max variable"
5061 if param0 == "center":
5062 myDebugPrint3AndException(
5063 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
5064 "data point 'center' not yet implemented")
5065 self.mReferenceVariableInfo = PhactoriVariableInfo()
5066 tempJson = {}
5067 tempJson[params[1].lower()] = params[2]
5068 if PhactoriDbg():
5069 print("tempJson: " + str(tempJson))
5070 self.mReferenceVariableInfo.\
5071 ParseVariableNameAndVectorOrTensorComponent(tempJson, '')
5072 self.mMayChangeWithData = True
5073 if PhactoriDbg():
5074 myDebugPrint3("variable found\n"
5075 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
5076 if params[3] != "default":
5077 self.mInputNameToUseForMinMaxVariable = params[3]
5078 if PhactoriDbg():
5079 myDebugPrint3("name of input operation: " +
5080 self.mInputNameToUseForMinMaxVariable + "\n")
5081 if inDisplacementFlag:
5082 self.mHasDisplacedInfoFlag = True
5083 self.mDisplacement[0] = params[4]
5084 self.mDisplacement[1] = params[5]
5085 self.mDisplacement[2] = params[6]
5086
5087 else:
5088 if PhactoriDbg():
5089 myDebugPrint3("using default input operation\n")
5090 if PhactoriDbg():
5091 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson: "
5092 "done parsing data point")
5093 elif keyMaxVar in inJson:
5094 self.mParsingDetectedAtLeastOneSetting = True
5095 self.mPointType = "max variable"
5096 #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):
5097 self.mReferenceVariableInfo = PhactoriVariableInfo()
5098 self.mReferenceVariableInfo.\
5099 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
5100 self.mMayChangeWithData = True
5101 if PhactoriDbg():
5102 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson "
5103 "max variable found\n"
5104 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
5105 varSourceKey = inKeyPrefix + "input for max variable point" + inKeySuffix
5106 if varSourceKey in inJson:
5107 self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]
5108 myDebugPrint3("input name for max variable point: " + \
5109 self.mInputNameToUseForMinMaxVariable + "\n")
5110 varDispKey = \
5111 inKeyPrefix + "displacement for max variable point" + inKeySuffix
5112 if varDispKey in inJson:
5113 self.mDisplacement = inJson[varDispKey]
5114 myDebugPrint3("displacement for max variable point: " + \
5115 str(self.mDisplacement) + "\n")
5116 else:
5117 self.mParsingDetectedAtLeastOneSetting = False
5118 if PhactoriDbg():
5119 myDebugPrint3(" no PhactoriUserPointInfo parse keys, using default\n")
5120
5121 #myDebugPrint3("PhactoriUserPoint Parsed from json:\n")
5122 #self.PrintSelf()
5123
5124 def GetCurrentGeometricPoint(self, inParaViewSource, ioViewBounds,
5125 inUpdateInputPipelineFlag):
5126 """returns the current absolute xyz of this point, calculating relative
5127 position or element or node position if necessary; if it obtains
5128 its view bounds during operation it returns them, otherwise it
5129 returns None
5130 """
5131 if inUpdateInputPipelineFlag:
5132 UpdatePipelineWithCurrentTimeArgument(inParaViewSource)
5133 if PhactoriDbg(100):
5134 myDebugPrint3("GetCurrentGeometricPoint entered\n", 100)
5135
5136 #import pdb
5137 #pdb.set_trace()
5138
5139 #self.PrintSelf()
5140 if self.mPointType == 'absolute':
5141 #focal point is exact point in coordinate system of data
5142 returnXyz = list(self.mXyz)
5143 elif self.mPointType == 'datasize relative':
5144 #focal point is offset from center of data bounding box, with offset
5145 #relative in size to the size of the overall bounding box
5146 relativeXyz = self.mXyz
5147 myViewBounds = ioViewBounds[0]
5148 if myViewBounds == None:
5149 myViewBounds = GetGlobalDataBoundsParallel(inParaViewSource)
5150 ioViewBounds[0] = myViewBounds
5151 #old style: use maximum bounding box dimension to define
5152 #relative space
5153 #maxDim = GetMaximumDimensionFromBounds(myViewBounds)
5154 #returnXyz = [ (myViewBounds[1] + myViewBounds[0]) * 0.5 + \
5155 # maxDim * relativeXyz[0], \
5156 # (myViewBounds[3] + myViewBounds[2]) * 0.5 + \
5157 # maxDim * relativeXyz[1], \
5158 # (myViewBounds[5] + myViewBounds[4]) * 0.5 + \
5159 # maxDim * relativeXyz[2] ]
5160
5161 #new style: do relative in each dimension
5162 returnXyz = [0.0,0.0,0.0]
5163 returnXyz[0] = myViewBounds[0] + (myViewBounds[1] - myViewBounds[0]) * \
5164 (relativeXyz[0] + 0.5)
5165 returnXyz[1] = myViewBounds[2] + (myViewBounds[3] - myViewBounds[2]) * \
5166 (relativeXyz[1] + 0.5)
5167 returnXyz[2] = myViewBounds[4] + (myViewBounds[5] - myViewBounds[4]) * \
5168 (relativeXyz[2] + 0.5)
5169 elif self.mPointType == 'node':
5170 nodeId = self.mElementOrNodeId
5171 returnXyz = [0.0, 0.0, 0.0]
5172 GetXyzForNodeOrElementParallel(inParaViewSource, True, nodeId, returnXyz)
5173 elif self.mPointType == 'element':
5174 elementId = self.mElementOrNodeId
5175 returnXyz = [0.0, 0.0, 0.0]
5176 GetXyzForNodeOrElementParallel(inParaViewSource, False, elementId, returnXyz)
5177 elif self.mPointType == 'min variable':
5178 returnXyz = [0.0, 0.0, 0.0]
5179 if self.mInputNameToUseForMinMaxVariable == None:
5180 pvFilter = inParaViewSource
5181 else:
5182 if self.mInputPvSourceToUseForMinMaxVariable == None:
5183 global gPipeAndViewsState
5184 operationBlock = gPipeAndViewsState.mOperationBlocks[
5185 self.mInputNameToUseForMinMaxVariable]
5186 pvFilter = operationBlock.GetPvFilter()
5187 self.mInputPvSourceToUseForMinMaxVariable = pvFilter
5188 else:
5189 pvFilter = self.mInputPvSourceToUseForMinMaxVariable
5190 if(pvFilter == None):
5191 #no pvFilter for min/max yet, just use 0,0,0
5192 returnXyz = [0.0, 0.0, 0.0]
5193 else:
5194 UpdatePipelineWithCurrentTimeArgument(pvFilter)
5195 GetXyzForMinOrMaxVariable(pvFilter, True,
5196 self.mReferenceVariableInfo, returnXyz)
5197 elif self.mPointType == 'max variable':
5198 returnXyz = [0.0, 0.0, 0.0]
5199 if self.mInputNameToUseForMinMaxVariable == None:
5200 pvFilter = inParaViewSource
5201 if PhactoriDbg():
5202 myDebugPrint3("max var point has no source, using incoming\n")
5203 else:
5204 if PhactoriDbg():
5205 myDebugPrint3("max var point has source, using instead\n")
5206 if self.mInputPvSourceToUseForMinMaxVariable == None:
5207 if PhactoriDbg():
5208 myDebugPrint3("not previously found, must locate\n")
5209 #global gPipeAndViewsState
5210 operationBlock = gPipeAndViewsState.mOperationBlocks[
5211 self.mInputNameToUseForMinMaxVariable]
5212 pvFilter = operationBlock.GetPvFilter()
5213 self.mInputPvSourceToUseForMinMaxVariable = pvFilter
5214 else:
5215 if PhactoriDbg():
5216 myDebugPrint3("previously found.\n")
5217 pvFilter = self.mInputPvSourceToUseForMinMaxVariable
5218 if PhactoriDbg():
5219 myDebugPrint3("incoming: " + str(inParaViewSource) + "\n"
5220 "using: " + str(pvFilter) + "\n")
5221 if(pvFilter == None):
5222 #no pvFilter for min/max yet, just use 0,0,0
5223 returnXyz = [0.0, 0.0, 0.0]
5224 else:
5225 UpdatePipelineWithCurrentTimeArgument(pvFilter)
5226 GetXyzForMinOrMaxVariable(pvFilter, False,
5227 self.mReferenceVariableInfo, returnXyz)
5228 else:
5229 errStr = 'GetCurrentGeometricPoint error! bad mPointType\n'
5230 if PhactoriDbg():
5231 myDebugPrint3(errStr)
5232 raise Exception(errStr)
5233
5234 if PhactoriDbg(100):
5235 myDebugPrint3("GetCurrentGeometricPoint returning: " + \
5236 str(returnXyz) + "\n", 100)
5237
5238 return returnXyz
5239
5240 def GetCurrentGeometricPointWithDisplacement(self, inParaViewSource,
5241 ioViewBounds, inUpdateInputPipelineFlag):
5242 undisplacedXyz = self.GetCurrentGeometricPoint(inParaViewSource,
5243 ioViewBounds, inUpdateInputPipelineFlag)
5244 returnXyz = [undisplacedXyz[0] + self.mDisplacement[0],
5245 undisplacedXyz[1] + self.mDisplacement[1],
5246 undisplacedXyz[2] + self.mDisplacement[2]]
5247 return returnXyz
5248
5249 def SelfToStr(self):
5250 return " PhactoriUserPointInfo:\n" \
5251 " mPointType: " + self.mPointType + \
5252 " mElementOrNodeId: " + str(self.mElementOrNodeId) + "\n" + \
5253 " mMayChangeWithData: " + str(self.mMayChangeWithData) + "\n" \
5254 " mParseHadKeys: " + str(self.mParseHadKeys) + "\n" \
5255 " mHasDisplacedInfoFlag: " + str(self.mHasDisplacedInfoFlag) + "\n" \
5256 " mDisplacement: " + str(self.mDisplacement) + "\n" \
5257 " mReferenceVariableInfo: " + str(self.mReferenceVariableInfo) + "\n"
5258
5259 def PrintSelf(self):
5260 if PhactoriDbg():
5261 myDebugPrint3(self.SelfToStr())
5262
5263 class PhactoriOffAxisProjectionInfo:
5264 def __init__(self):
5265 self.mUseOffAxisProjection = False
5266 self.mPhysicalEyeAndScreenSettings = PhactoriPhysicalEyeAndScreenSetup()
5267 self.mLeftEyeFlag = True
5268 self.mIpdInModelUnits = 6.2
5269 self.mVirtualSelfSizeMultiplier = 1.0
5270 self.mAutoSize1Enabled = False
5271 self.mAutoSize1LockEyePosition = False
5272 self.mAutoSize1LockCountdown = 1
5273 self.mAutoSize1DistanceRatio = 1.0
5274 self.mAutoSize1LockedEyePosition = None
5275 self.mAutoSize1LockedFocalPoint = None
5276 self.mAutoSize1ViewAngleDeltaInRadians = 0.0
5277
5278 def ParseParametersFromJson(self, inJsn):
5279 if 'use off axis projection' in inJsn:
5280 self.mUseOffAxisProjection = inJsn['use off axis projection']
5281 if PhactoriDbg():
5282 myDebugPrint3("PhactoriOffAxisProjectionInfo:ParseParametersFromJson\n"
5283 "mUseOffAxisProjection set to " + str(self.mUseOffAxisProjection))
5284 if self.mUseOffAxisProjection == True:
5285 self.mPhysicalEyeAndScreenSettings.ParseSettingsFromJson(inJsn)
5286 if 'which eye' in inJsn:
5287 if inJsn['which eye'] == 'left':
5288 self.mLeftEyeFlag = True
5289 else:
5290 self.mLeftEyeFlag = False
5291 else:
5292 if PhactoriDbg():
5293 myDebugPrint3("PhactoriOffAxisProjectionInfo:"
5294 "ParseParametersFromJson\n"
5295 "warning: 'which eye' not in json, defaulting to left\n")
5296 if 'ipd in model units' not in inJsn:
5297 myDebugPrint3AndException(
5298 "PhactoriOffAxisProjectionInfo::ParseParametersFromJson\n"
5299 "Error: incoming json must have 'ipd in model units'\n")
5300 self.mIpdInModelUnits = inJsn['ipd in model units']
5301 if 'virtual self size multiplier' in inJsn:
5302 self.mVirtualSelfSizeMultiplier = inJsn['virtual self size multiplier']
5303 if 'auto size 1' in inJsn:
5304 self.mAutoSize1Enabled = inJsn['auto size 1']
5305 if 'auto size 1 lock nth eye position' in inJsn:
5306 self.mAutoSize1LockEyePosition = True
5307 self.mAutoSize1LockCountdown = inJsn['auto size 1 lock nth eye position']
5308 if 'auto size 1 distance ratio' in inJsn:
5309 self.mAutoSize1DistanceRatio = inJsn['auto size 1 distance ratio']
5310 if 'auto size 1 view angle delta in degrees' in inJsn:
5311 angleInDegrees = inJsn['auto size 1 view angle delta in degrees']
5312 self.mAutoSize1ViewAngleDeltaInRadians = math.radians(angleInDegrees)
5313
5314
5315 def SetUpIfEnabled(self, inRenderView, ioCameraPosition, ioLookAtPoint,
5316 inViewUpVector):
5317 theCamera = GetActiveCamera()
5318 if self.mUseOffAxisProjection == False:
5319 theCamera.SetUseOffAxisProjection(0)
5320 return
5321
5322 projectionEyePosition = self.mPhysicalEyeAndScreenSettings.GetEyePosition(
5323 self.mLeftEyeFlag)
5324 scrnBttmLeft = self.mPhysicalEyeAndScreenSettings.GetScreenBottomLeft(
5325 self.mLeftEyeFlag)
5326 scrnBttmRight = self.mPhysicalEyeAndScreenSettings.GetScreenBottomRight(
5327 self.mLeftEyeFlag)
5328 scrnTopRight = self.mPhysicalEyeAndScreenSettings.GetScreenTopRight(
5329 self.mLeftEyeFlag)
5330
5331 if PhactoriDbg():
5332 myDebugPrint3("SetUpIfEnabled setting camera parameters:"
5333 "\n mProjectionEyePosition: " + str(projectionEyePosition) + \
5334 "\n mScreenBottomLeft: " + str(scrnBttmLeft) + \
5335 "\n mScreenBottomRight: " + str(scrnBttmRight) + \
5336 "\n mScreenTopRight: " + str(scrnTopRight) + \
5337 "\n")
5338 SetActiveView(inRenderView)
5339 theCamera.SetUseOffAxisProjection(1)
5340 #we are assuming camera is explicitly set up where you want the left or right eye
5341 #and so we don't use eye separation
5342 theCamera.SetEyeSeparation(0.0)
5343 theCamera.SetScreenBottomLeft(scrnBttmLeft)
5344 theCamera.SetScreenBottomRight(scrnBttmRight)
5345 theCamera.SetScreenTopRight(scrnTopRight)
5346 theCamera.SetEyePosition(projectionEyePosition)
5347
5348 self.ChangeEyeAndFocusInModelSpaceForStereo(ioCameraPosition,
5349 ioLookAtPoint, inViewUpVector)
5350
5351 if PhactoriDbg():
5352 myDebugPrint3("SetUpIfEnabled done setting camera parameters\n")
5353
5354 def ChangeEyeAndFocusInModelSpaceForStereo(self,
5355 ioEyePosition, ioFocalPoint, inViewUpVector):
5356
5357 #place eye and look at point so object is at screen in AutoSize1 case
5358 if self.mAutoSize1Enabled:
5359 if self.mAutoSize1LockEyePosition and self.mAutoSize1LockedEyePosition != None:
5360 ioEyePosition[0] = self.mAutoSize1LockedEyePosition[0]
5361 ioEyePosition[1] = self.mAutoSize1LockedEyePosition[1]
5362 ioEyePosition[2] = self.mAutoSize1LockedEyePosition[2]
5363 ioFocalPoint[0] = self.mAutoSize1LockedFocalPoint[0]
5364 ioFocalPoint[1] = self.mAutoSize1LockedFocalPoint[1]
5365 ioFocalPoint[2] = self.mAutoSize1LockedFocalPoint[2]
5366 if PhactoriDbg():
5367 myDebugPrint3("AutoSize1: reusing first eye position and focal point:\n" + \
5368 " eye position: " + str(ioEyePosition) + "\n"
5369 " focal point : " + str(ioFocalPoint) + "\n")
5370 else:
5371 fpToEyeVec = vecFromAToB(ioFocalPoint, ioEyePosition)
5372 fpToEyeVecNorm = vecNormalize(fpToEyeVec)
5373 dist = -self.mPhysicalEyeAndScreenSettings.mLeftEyeScreenBottomLeft[2]
5374 dist *= self.mAutoSize1DistanceRatio
5375 dist *= self.mVirtualSelfSizeMultiplier
5376
5377 if PhactoriDbg():
5378 myDebugPrint3("AutoSize1:\n"
5379 " before eye position: " + str(ioEyePosition) + "\n"
5380 " before focal point : " + str(ioFocalPoint) + "\n")
5381 ioEyePosition[0] = ioFocalPoint[0] + fpToEyeVecNorm[0] * dist
5382 ioEyePosition[1] = ioFocalPoint[1] + fpToEyeVecNorm[1] * dist
5383 ioEyePosition[2] = ioFocalPoint[2] + fpToEyeVecNorm[2] * dist
5384 #angle look direction for AutoSize1 by moving focal point up or down
5385 #simple tangent work, but need to work it out to see it (we want
5386 #same distance to screen plane but looking more angled up or down)
5387 dy1 = -dist * math.tan(self.mAutoSize1ViewAngleDeltaInRadians)
5388 ioFocalPoint[0] += inViewUpVector[0] * dy1
5389 ioFocalPoint[1] += inViewUpVector[1] * dy1
5390 ioFocalPoint[2] += inViewUpVector[2] * dy1
5391
5392 if PhactoriDbg():
5393 myDebugPrint3(
5394 " calculated eye position: " + str(ioEyePosition) + "\n"
5395 " calculated focal point : " + str(ioFocalPoint) + "\n")
5396 if self.mAutoSize1LockEyePosition:
5397 self.mAutoSize1LockCountdown -= 1
5398 if PhactoriDbg():
5399 myDebugPrint3("self.mAutoSize1LockCountdown now " + \
5400 str(self.mAutoSize1LockCountdown) + "\n")
5401 if self.mAutoSize1LockCountdown == 0:
5402 self.mAutoSize1LockedEyePosition = list(ioEyePosition)
5403 self.mAutoSize1LockedFocalPoint = list(ioFocalPoint)
5404 if PhactoriDbg():
5405 myDebugPrint3("(eye position saved for locking for next use)\n")
5406
5407 #perpendicular screen distance or put look at point on screen plane?
5408 #i think put look at point on screen plane.
5409
5410 lookDirection = vecFromAToB(ioEyePosition, ioFocalPoint)
5411 axisBetweenEyes = vecCrossProduct(lookDirection, inViewUpVector)
5412 axisBetweenEyesNorm = vecNormalize(axisBetweenEyes)
5413
5414 if self.mLeftEyeFlag:
5415 modelCsHalfIpd = -self.mIpdInModelUnits * \
5416 self.mVirtualSelfSizeMultiplier * 0.5
5417 else:
5418 modelCsHalfIpd = self.mIpdInModelUnits * \
5419 self.mVirtualSelfSizeMultiplier * 0.5
5420 dx = axisBetweenEyesNorm[0] * modelCsHalfIpd
5421 dy = axisBetweenEyesNorm[1] * modelCsHalfIpd
5422 dz = axisBetweenEyesNorm[2] * modelCsHalfIpd
5423 if PhactoriDbg():
5424 myDebugPrint3("ChangeEyeAndFocusInModelSpaceForStereo entered\n"
5425 "axisBetweenEyesNorm: " + str(axisBetweenEyesNorm) + "\n"
5426 "modelCsHalfIpd: " + str(modelCsHalfIpd) + "\n"
5427 "[dx,dy,dz]: " + str([dx,dy,dz]) + "\n"
5428 "prior ioEyePosition: " + str(ioEyePosition) + "\n"
5429 "prior ioFocalPoint: " + str(ioFocalPoint) + "\n")
5430 ioEyePosition[0] += dx
5431 ioEyePosition[1] += dy
5432 ioEyePosition[2] += dz
5433 ioFocalPoint[0] += dx
5434 ioFocalPoint[1] += dy
5435 ioFocalPoint[2] += dz
5436 if PhactoriDbg():
5437 myDebugPrint3("post ioEyePosition: " + str(ioEyePosition) + "\n"
5438 "post ioFocalPoint: " + str(ioFocalPoint) + "\n"
5439 "ChangeEyeAndFocusInModelSpaceForStereo returning\n")
5440
5441
5442 class PhactoriCameraBlock:
5443 """camera control: look at point, look direction, camera/eye position, etc.
5444
5445 PhactoriCameraBlock is the central class for controlling the camera (or eye)
5446 positioning for images. There are a number of ways the camera control can
5447 be scripted in paraview.
5448
5449 To add a PhactoriCameraBlock to the incoming script, you add
5450 a sub-block to the "camera blocks" section of the data with the "type"
5451 key given a value of "camera". Next is a simple working script, followed by
5452 a longer discussion of all the allowed controls.
5453
5454 ::
5455
5456 {
5457 "camera blocks":{
5458 "mycam1":{
5459 "type":"camera",
5460 "look direction":[-1.0, -2.0, -3.0]
5461 }
5462 },
5463 "representation blocks":{"rep_tmprtr":{"color by scalar":"temperature"}},
5464 "imageset blocks":{
5465 "temperature_on_slice_1":{
5466 "camera":"mycam1",
5467 "representation":"rep_tmprtr",
5468 "image basedirectory":"CatalystOutput",
5469 "image basename":"threshold1_temperature."
5470 }
5471 }
5472 }
5473
5474 The simplest common usage of the camera is to specify a point to look at and
5475 a direction in which to look. In this case the camera is positioned so that
5476 the center of view looks along the specified look direction towards the
5477 "look at point". If the user leaves the distance between the look at point
5478 and the camera position unspecified, the camera will automatically be placed
5479 far enough away from the look at point so that the entire bounding box of
5480 the mesh data is visible.
5481
5482 The user may specify the distance between the look at point and the camera
5483 position by adding a "look at absolute distance" key which will place the
5484 camera an exact number of specified geometrical units (in model coordinates)
5485 from the look at point. A "look at relative distance" key behaves more like
5486 a zoom factor. A "look at relative distance" of 0.25 will calculate the
5487 default distance (so the whole data bounding box is in view) but then
5488 multiply that distance by 0.25, resulting in a camera postion which is four
5489 times closer to the look at point than the default.
5490
5491 The user also has the point to specify "camera at point" to fix the camera
5492 at a 3D point. The user is allowed to specify two out of three of "look at
5493 point", "camera at point", and "look direction" but not all three. If only
5494 one is specified another will receive a default value, and if none are
5495 specified the camera takes on a default behavior with a look direction of
5496 [0.0, 0.0, -1.0] and a relative look at point of [0.0, 0.0, 0.0]. Also note
5497 that if the user specifies the camera point and the look at point, the look
5498 at distance is implied and cannot be set.
5499
5500 Both the "look at point" and the "camera at point" are instances of the
5501 PhactoriUserPointInfo class. This class is documented separately, but
5502 briefly this means that this point can be the expected absolute geometric
5503 3d point (e.g. [123.0, -37.9, 47.6]), a "relative" point specified in
5504 terms of the data bounding box (e.g. [0.0, 0.0, 0.0] is the center of the
5505 data bounding box), specified to reside at a node id or element id in the
5506 mesh (or at a specified offset therefrom), or at the location of the maximum
5507 or minimum of a data variable (e.g. pressure, temperature, velocity
5508 magnitude). Note that in all cases except the "absolute" case, the geometric
5509 position of the point might be different depending on the mesh data.
5510
5511 Generally it is best to use "look at relative point" and "look direction" for
5512 initial scripting (unless you happen to know exact geometric places of
5513 interest, in which case "look at absolute point" is better), and then create
5514 more specific cameras to hone in on areas of interest or make steady views
5515 for creating movies.
5516
5517 Remember, look at the documentation for PhactoriUserPointInfo to get the
5518 details on the options for "look at point" and "camera at point", but a
5519 number of examples of camera usage follow:
5520
5521 Looks in a direction [-1.0, -1.0, .1.0] at the default location, relative
5522 point [0,0,0] which is the center of the bounding box of the data. Camera
5523 is positioned to show entire bounding box of data:
5524
5525 ::
5526
5527 "mycam2":{
5528 "type":"camera",
5529 "look direction":[-1.0, -1.0, -1.0]
5530 }
5531
5532 Same as above, but now "zoomed in" to where the look at point to camera
5533 point distance is one fourth of what it was in the previous case:
5534
5535 ::
5536
5537 "mycam3":{
5538 "type":"camera",
5539 "look direction":[-1.0, -1.0, -1.0],
5540 "look at relative distance":0.25
5541 }
5542
5543 Same as above, but now we make the look at point on one of the corners of
5544 the bounding box of the data (max X, min Y, maz Z)
5545
5546 ::
5547
5548 "mycam4":{
5549 "type":"camera",
5550 "look direction":[-1.0, -1.0, -1.0],
5551 "look at relative point":[0.5, -0.5, 0.5]
5552 "look at relative distance":0.25
5553 }
5554
5555 The above will be a bit odd because the camera position calculation will
5556 start by getting the whole bounding box in view, which will be just on
5557 one side of the screen. It would work better to line the view up back
5558 towards the center:
5559
5560 ::
5561
5562 "mycam5":{
5563 "type":"camera",
5564 "look direction":[-1.0, 1.0, -1.0],
5565 "look at relative point":[0.5, -0.5, 0.5]
5566 "look at relative distance":0.25
5567 }
5568
5569 Now an example where you know what geometric point you need to focus on,
5570 where there might be a tip or and edge or a bend or a stress point:
5571
5572 ::
5573
5574 "mycam6":{
5575 "type":"camera",
5576 "look direction":[-1.0, -1.0, -1.0],
5577 "look at absolute point":[132.0, 145.125, -157.625]
5578 "look at relative distance":0.25
5579 }
5580
5581 This is similar to the above, but you have more precise control over what
5582 you see in the camera, and the view won't change if the mesh is changing (as
5583 in a mechanics simulation):
5584
5585 ::
5586
5587 "mycam7":{
5588 "type":"camera",
5589 "look direction":[-1.0, -1.0, -1.0],
5590 "look at absolute point":[132.0, 145.125, -157.625]
5591 "look at absolute distance":55.0
5592 }
5593
5594 Look at a particular node (or element):
5595
5596 ::
5597
5598 "mycam8":{
5599 "type":"camera",
5600 "look direction":[-1.0, -1.0, -1.0],
5601 "look at node":1942
5602 "look at relative distance":0.25
5603 }
5604
5605 look at a particular element, and put the camera at a certain distance and
5606 direction from that element:
5607
5608 ::
5609
5610 "mycam9":{
5611 "type":"camera",
5612 "look at element":1942
5613 "camera at element displaced":[1942, 5.0, 6.1, 7.2]
5614 }
5615
5616 look at the point where pressure is maximum:
5617
5618 ::
5619
5620 "mycam10":{
5621 "type":"camera",
5622 "look direction":[-1.0, -1.0, -1.0],
5623 "look at max variable point":True,
5624 "variable scalar":"pressure"
5625 }
5626
5627 For other point options see PhactoriUserPointInfo
5628
5629 You also have the option to specify a type of "multicamera8" in which you
5630 have 8 look directions: two aliagned on each axis from both directions, plus
5631 two diagonals [-1.0, -1.0, -1.0] and [1.0, 1.0, 1.0]. You can still specify
5632 a look at point and look at relative distance or look at abolute distance.
5633 If you don't specify those you'll get a relative look at point of [0,0,0],
5634 center of the data bounding box, and a relative look at distance of 1.0 so
5635 all the data is visible from each angle.
5636
5637 The result is that when this camera is chosen by an imageset block the
5638 result will be 8 images instead of 1:
5639
5640 ::
5641
5642 "mycam11":{
5643 "type":"multicamera8",
5644 "look at absolute point":[132.0, 145.125, -157.625]
5645 "look at absolute distance":100.0
5646 }
5647
5648 Eventually we plan to provide for
5649 lists of look at points and look directions so users may more tersely
5650 specify many views of the same operation/representation setup.
5651 """
5652
5653 def __init__(self):
5654 self.mName = ""
5655 self.mType = ""
5656 self.mFilenameAddon = ""
5657 self.mLookAtPointInfo = PhactoriUserPointInfo()
5658 self.mUseCameraAtPointFlag = False
5659 self.mCameraAtPointInfo = PhactoriUserPointInfo()
5660 self.mUseParallelProjection = False
5661 #0 is absolute, 1, is relative
5662 self.mParallelScaleAbsoluteOrRelative = 1
5663 self.mParallelScale = 1.0
5664
5665 #'absolute' or 'datasize relative'
5666 self.mLookAtDistanceType = ""
5667 self.mLookAtDistance = 1.0
5668 self.mLookDirection = [-1.0, -1.0, -1.0]
5669 self.mLookDirectionSpecifiedFlag = False
5670
5671 self.mViewAngle = 30.0
5672 self.mViewUpVector = [0.0, 1.0, 0.0]
5673
5674 self.mOffAxisProjectionInfo = PhactoriOffAxisProjectionInfo()
5675
5676 self.LockCount = 0
5677 self.LockAfterNCalls = -1
5678
5679 def PrintSelf(self):
5680 if PhactoriDbg():
5681 myDebugPrint3("PhactoriCameraBlock: name " + self.mName + \
5682 " type " + self.mType + "\n" +
5683 " look at distance type " + self.mLookAtDistanceType + \
5684 " setting " + str(self.mLookAtDistance) + "\n" +
5685 " look direction " + str(self.mLookDirection) + "\n")
5686 self.mLookAtPointInfo.PrintSelf()
5687
5688 def MayChangeWithData(self):
5689 if self.mLookAtDistanceType != 'absolute':
5690 return True
5691 if self.mLookAtPointInfo.mMayChangeWithData == True:
5692 return True
5693 return False
5694
5695 def HandleLockingOption(self, eyePosition, absoluteLookAtPoint):
5696 if self.LockAfterNCalls <= 0:
5697 #not locking
5698 return
5699
5700 self.LockCount += 1
5701 if self.LockCount >= self.LockAfterNCalls:
5702 #look at absolute point
5703 self.mLookAtPointInfo.mParsingDetectedAtLeastOneSetting = True
5704 self.mLookAtPointInfo.mPointType = "absolute"
5705 self.mLookAtPointInfo.mXyz = absoluteLookAtPoint
5706 self.mLookAtPointInfo.mMayChangeWithData = False
5707
5708 #look at absolute distance
5709 self.mLookAtDistanceType = 'absolute'
5710 lookAtAbsoluteDistance = vecDistance(eyePosition, absoluteLookAtPoint)
5711 self.mLookAtDistance = lookAtAbsoluteDistance
5712
5713 self.LockAfterNCalls = -1
5714
5715 #phactori_combine_to_single_python_file_parent_1
5716 from Operation.PhactoriVariableInfo import *
5717
5718 class PhactoriDataCubeOneAxisInfo:
5719 def __init__(self):
5720 self.mUseLabelFlag = False
5721 self.mAxisLabel = ""
5722 self.mBaseAxisLabel = None
5723
5724 def DcoaiParseParametersFromJson(self, parentAxesInfo, inJsn, inXyzKey):
5725
5726 theKey = 'show ' + inXyzKey + ' axis tic marks'
5727 parentAxesInfo.mShowTicks = localGet1or0(inJsn, theKey, True)
5728 #parentAxesInfo.mShowEdges = 1
5729 #theKey = 'show ' + inXyzKey + ' axis minor tic marks'
5730
5731 theKey = 'show ' + inXyzKey + ' axis label'
5732 value = getParameterFromBlock(inJsn, theKey, True)
5733 if value == False:
5734 self.mUseLabelFlag = True
5735 self.mAxisLabel = ""
5736 else:
5737 self.mUseLabelFlag = False
5738
5739 theKey = inXyzKey + ' axis label name'
5740 if theKey in inJsn:
5741 self.mUseLabelFlag = True
5742 self.mAxisLabel = getParameterFromBlock(inJsn, theKey, "")
5743
5744 if PhactoriDbg():
5745 myDebugPrint3('DcoaiParseParametersFromJson ' + inXyzKey + ' ' \
5746 + str(parentAxesInfo.mShowTicks) + ' ' \
5747 + str(self.mUseLabelFlag) + ' ' \
5748 + str(self.mAxisLabel) + '\n')
5749
5750 class PhactoriDataCubeAxesInfo:
5751 def __init__(self):
5752 self.mShowEdges = 1
5753 self.mShowTicks = 1
5754 self.mXAxisInfo = PhactoriDataCubeOneAxisInfo()
5755 self.mYAxisInfo = PhactoriDataCubeOneAxisInfo()
5756 self.mZAxisInfo = PhactoriDataCubeOneAxisInfo()
5757
5758 def DcaiParseParametersFromJson(self, inJsn):
5759 self.mXAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'x')
5760 self.mYAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'y')
5761 self.mZAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'z')
5762
5763
5764 class PhactoriColorMapSettings:
5765 def __init__(self):
5766 self.mColorMapNameId = "Default"
5767 self.mInvertColorMap = False
5768 #self.mColorMapNameId = "Blue to Yellow"
5769 #self.mColorMapNameId = "Blue to Red Rainbow"
5770
5771 def ParseColorMapSettings(self, inJsn):
5772 self.mColorMapNameId = getParameterFromBlock(inJsn,
5773 'preset color scale', self.mColorMapNameId)
5774 self.mInvertColorMap = getParameterFromBlock(inJsn,
5775 'invert color scale', self.mInvertColorMap)
5776
5777 def GetThresholdContourHackVariableNameString(inVariableInfo):
5778 """gives altered variable name for magnitude or component
5779 in paraview, coloring by a vector component or magnitude is handled
5780 differently than thresholding or contouring by a vector component or
5781 magnitude. For the Contour and Threshold case, we add _X, _Y, or _Z to
5782 the variable name for component and _Magnitude for magnitude. In
5783 the coloring case, we specify component arguments and another argument
5784 as to whether to use magnitude or component. This routine takes the
5785 given variable info (name, whether or not vector component or magnitude)
5786 and creates a properly munged name to do the right thing"""
5787
5788 if inVariableInfo.mVariableIsVectorComponent:
5789 if inVariableInfo.mVariableComponent == 0:
5790 localVariableName = inVariableInfo.mVariableName + '_X'
5791 elif inVariableInfo.mVariableComponent == 1:
5792 localVariableName = inVariableInfo.mVariableName + '_Y'
5793 elif inVariableInfo.mVariableComponent == 2:
5794 localVariableName = inVariableInfo.mVariableName + '_Z'
5795 else:
5796 if PhactoriDbg():
5797 myDebugPrint3(" variable component is not 0, 1, or 2, using 0 (X)\n")
5798 localVariableName = inVariableInfo.mVariableName + '_X'
5799 elif inVariableInfo.mVariableIsVectorMagnitude:
5800 localVariableName = inVariableInfo.mVariableName + '_Magnitude'
5801 else:
5802 localVariableName = inVariableInfo.mVariableName
5803
5804 return localVariableName
5805
5806 class PhactoriOperationSpecifics:
5807 #base class for operation specifics; probably need to reconfigure so
5808 #that we have a base operation abstract class rather than an operation
5809 #base class that has an operation specifics member which is a child
5810 #class of this class
5811 def __init__(self):
5812 if PhactoriDbg():
5813 myDebugPrint3("PhactoriOperationSpecifics::__init__ executed\n")
5814
5815 #which PhactoriOperationBlock instance owns/created this specific
5816 #operation. Set during ParseOneFilterTypeFromViewMapOperation()
5817 self.mPhactoriOperationBlockOwner = None
5818
5819 def GetListOfInputOperationNamesForThisOperationType(self):
5820 """operations which depend on additional inputs besides the default single
5821 input need to override this method and return their dependencies as a
5822 list of names"""
5823 retList = []
5824 return retList
5825
5826 def CreateParaViewFilter(self):
5827 myDebugPrint3AndException("PhactoriOperationSpecifics:CreateParaViewFilter"
5828 " or CreateParaViewFilter2 should be overwritten by child\n")
5829
5830 def CreateParaViewFilter2(self, inInputOperation, ioPipeAndViewsState):
5831 return self.CreateParaViewFilter(inInputOperation)
5832
5833 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
5834 outOutgoingPvFilter):
5835 #default behavior is to do nothing on new data
5836 if PhactoriDbg():
5837 myDebugPrint3("PhactoriOperationSpecifics::"
5838 "DoUpdateDueToChangeInData executed\n")
5839 return False
5840
5841 def ExportOperationData(self, datadescription):
5842 """this will be called once per callback (before WriteImages) to allow the
5843 operation to export any desired data which is not an image. The child
5844 class should override this method if it wants so do something"""
5845 return
5846
5847 #phactori_combine_to_single_python_file_parent_1
5848 from Operation.PhactoriThresholdOperation import *
5849
5850 #phactori_combine_to_single_python_file_parent_1
5851 from Operation.PhactoriAddUnstructuredGridOperation import *
5852
5853 #phactori_combine_to_single_python_file_parent_1
5854 from Operation.PhactoriAddPointSetOperation import *
5855
5856 #phactori_combine_to_single_python_file_parent_1
5857 from Operation.PhactoriReflectOperation import *
5858
5859 #phactori_combine_to_single_python_file_parent_1
5860 from Operation.PhactoriWarpByVectorOperation import *
5861
5862 #phactori_combine_to_single_python_file_parent_1
5863 from Operation.PhactoriCalculatorOperation import *
5864
5865 #phactori_combine_to_single_python_file_parent_1
5866 from Operation.PhactoriTransformOperation import *
5867
5868 class SharedTriangleSet():
5869 """idea is that this encapsulates a set of triangles which are the triangles
5870 from the overall surface of interest which reside on a single processor.
5871 You can store your local processor triangles in this class and broadcast
5872 from them and you can receive a broadcast of this setup from other
5873 processes"""
5874
5875 def __init__(self):
5876 self.numPoints = -1
5877 self.numTriangles = -1
5878 #triangle points in xyzxyzxyzxyz order
5879 self.PointXyzs = vtk.vtkDoubleArray()
5880 #global node id for each point to help avoid self intersection
5881 self.NodeIds = vtk.vtkIntArray()
5882 #triplets of indexes into self.PointXyzs to represent triangles, in
5883 #abcabcabcabc order
5884 self.Triangles = vtk.vtkIntArray()
5885 self.fromPid = -1
5886
5887 #to share num points and num tris
5888 self.shareSizes = vtk.vtkIntArray()
5889 self.shareSizes.SetNumberOfValues(2)
5890
5891 self.BspTree = None
5892 self.UseBSPTreeForRayIntersection = True
5893
5894 def CreateFromLocalProcess(self, inPhactoriOperation):
5895 """figure out the set of triangles from the target surface which are on
5896 this process (if any): we assume we have a triangle mesh or this code
5897 won't work"""
5898
5899 #obtain pointer to the local geometry data
5900 csdata = inPhactoriOperation.mParaViewFilter.GetClientSideObject().\
5901 GetOutputDataObject(0)
5902
5903 self.numPoints = csdata.GetNumberOfPoints()
5904 if PhactoriDbg():
5905 myDebugPrint3(str(dir(csdata)) + "\n")
5906 myDebugPrint3("num points: " + str(self.numPoints) + "\n")
5907 myDebugPrint3(str(dir(vtk)) + "\n")
5908
5909 pntData = csdata.GetPointData()
5910 cellData = csdata.GetCellData()
5911 numCells = csdata.GetNumberOfCells()
5912 gNodeIdArray = pntData.GetArray('GlobalNodeId')
5913 #gElmtIdArray = cellData.GetArray('GlobalElementId')
5914 #pntGeometryArray = csdata.GetPoints()
5915
5916 self.PointXyzs.SetNumberOfValues(self.numPoints*3)
5917 self.NodeIds = vtk.vtkIntArray()
5918 self.NodeIds.SetNumberOfValues(self.numPoints)
5919
5920 #this is stupid, there is probably a much faster way to do this
5921 ptxyz = [0.0,0.0,0.0]
5922 for ii in range(0, self.numPoints):
5923 ndx = ii*3
5924 csdata.GetPoint(ii,ptxyz)
5925 self.PointXyzs.SetValue(ndx, ptxyz[0])
5926 self.PointXyzs.SetValue(ndx+1, ptxyz[1])
5927 self.PointXyzs.SetValue(ndx+2, ptxyz[2])
5928 if(gNodeIdArray == None):
5929 self.NodeIds.SetValue(ii, ii)
5930 else:
5931 self.NodeIds.SetValue(ii, gNodeIdArray.GetValue(ii))
5932
5933 self.Triangles.SetNumberOfValues(0)
5934 cellPointIds = vtk.vtkIdList()
5935 for ii in range(0, numCells):
5936 csdata.GetCellPoints(ii, cellPointIds)
5937 #numpoints should be 3
5938 numids = cellPointIds.GetNumberOfIds()
5939 #we are only doing triangles
5940 if numids != 3:
5941 if numids < 3:
5942 #degenerate ? try just skipping
5943 if PhactoriDbg():
5944 myDebugPrint3AndException(str(ii) + " degenerate 2 point\n")
5945 continue
5946 if True: #for now we consider this fatal error
5947 myDebugPrint3AndException(
5948 "PhactoriIntersectNodeNormalsWithSurface::CreateFromLocalProcess\n"
5949 "encountered non-triangle\n")
5950 continue
5951 self.Triangles.InsertNextValue(cellPointIds.GetId(0))
5952 self.Triangles.InsertNextValue(cellPointIds.GetId(1))
5953 self.Triangles.InsertNextValue(cellPointIds.GetId(2))
5954 self.numTriangles = self.Triangles.GetNumberOfValues() // 3
5955
5956 def SendBroadcast(self, inLocalPid, globalController):
5957 """broadcast the triangle set from the local process to all the other
5958 processes"""
5959 if (self.numPoints < 0) or (self.numTriangles < 0):
5960 myDebugPrint3AndException(
5961 "PhactoriIntersectNodeNormalsWithSurface::SendBroadcast\n"
5962 "can't broadcast without being filled in first\n")
5963
5964 if PhactoriDbg():
5965 myDebugPrint3("SharedTriangleSet::SendBroadcast entered, inLocalPid " + \
5966 str(inLocalPid) + \
5967 "\nself.numPoints " + str(self.numPoints) + \
5968 " self.numTriangles " + str(self.numTriangles) + "\n")
5969
5970 #first broadcast number of points and number of triangles
5971 self.shareSizes.SetValue(0, self.numPoints)
5972 self.shareSizes.SetValue(1, self.numTriangles)
5973
5974 globalController.Broadcast(self.shareSizes, inLocalPid)
5975
5976 self.fromPid = inLocalPid
5977
5978 if self.numTriangles == 0:
5979 if PhactoriDbg():
5980 myDebugPrint3(
5981 "SharedTriangleSet::SendBroadcast returning, nothing to send\n")
5982 return
5983
5984 globalController.Broadcast(self.PointXyzs, inLocalPid)
5985 globalController.Broadcast(self.NodeIds, inLocalPid)
5986 globalController.Broadcast(self.Triangles, inLocalPid)
5987
5988 if PhactoriDbg():
5989 myDebugPrint3("SharedTriangleSet::SendBroadcast returning, inLocaPid " \
5990 + str(inLocalPid) + "\n")
5991
5992 def ReceiveBroadcast(self, inFromPid, globalController):
5993 """receive a triangle set broadcast from the another process to the local
5994 process"""
5995 if PhactoriDbg():
5996 myDebugPrint3(
5997 "SharedTriangleSet::ReceiveBroadcast entered, inFromPid " + \
5998 str(inFromPid) + "\n")
5999
6000 globalController.Broadcast(self.shareSizes, inFromPid)
6001 self.fromPid = inFromPid
6002
6003 self.numPoints = self.shareSizes.GetValue(0)
6004 self.numTriangles = self.shareSizes.GetValue(1)
6005
6006 if self.numTriangles == 0:
6007 if PhactoriDbg():
6008 myDebugPrint3(
6009 "SharedTriangleSet::ReceiveBroadcast returning, nothing to get\n")
6010 return
6011
6012 self.PointXyzs.SetNumberOfValues(3*self.numPoints)
6013 self.NodeIds.SetNumberOfValues(self.numPoints)
6014 self.Triangles.SetNumberOfValues(3*self.numTriangles)
6015
6016 globalController.Broadcast(self.PointXyzs, inFromPid)
6017 globalController.Broadcast(self.NodeIds, inFromPid)
6018 globalController.Broadcast(self.Triangles, inFromPid)
6019
6020 if PhactoriDbg():
6021 myDebugPrint3(
6022 "SharedTriangleSet::ReceiveBroadcast returning, inFromPid " + \
6023 str(inFromPid) + \
6024 "\nself.numPoints " + str(self.numPoints) + \
6025 " self.numTriangles " + str(self.numTriangles) + "\n")
6026
6027 def IntersectWithOneRayViaBSPTree(self, inIndex, inRayStart, inRayDirection,
6028 ioRaycastOperation, inPointOrCellData,
6029 inRayEnd1, inRayEnd2, inBothDirFlag):
6030 if PhactoriDbg():
6031 myDebugPrint3(
6032 "bspt ray: " + str(inIndex) + " " + str(inRayStart) + " " + \
6033 str(inRayDirection) + " " + str(inPointOrCellData) + "\n")
6034
6035 #BSPTree interect with line
6036 #V.IntersectWithLine((float, float, float), (float, float, float),
6037 # float, vtkPoints, vtkIdList) -> int
6038 #C++: virtual int IntersectWithLine(const double p1[3],
6039 # const double p2[3], const double tol, vtkPoints *points,
6040 # vtkIdList *cellIds)
6041 hitPoints = vtk.vtkPoints()
6042 hitIds = vtk.vtkIdList()
6043 segmentStart = vecMultiplyAdd(inRayStart, inRayDirection, inRayEnd1)
6044 segmentEnd = vecMultiplyAdd(inRayStart, inRayDirection, inRayEnd2)
6045 self.BspTree.IntersectWithLine(segmentStart, segmentEnd, 0.0001,
6046 hitPoints, hitIds)
6047 numhits = hitPoints.GetNumberOfPoints()
6048 if PhactoriDbg():
6049 myDebugPrint3("results from self.BspTree.IntersectWithLine:\n"
6050 "num hits: " + str(numhits) + "\n"
6051 "index, id, xyz\n")
6052 for hhpp in range(0, numhits):
6053 myDebugPrint3(str(hhpp) + ", " + str(hitIds.GetId(hhpp)) + ", " + \
6054 str(hitPoints.GetPoint(hhpp)) + "\n")
6055
6056 numhitsB = 0
6057 if inBothDirFlag:
6058 hitPointsB = vtk.vtkPoints()
6059 hitIdsB = vtk.vtkIdList()
6060 segmentStart = vecMultiplyAdd(inRayStart, inRayDirection, -inRayEnd1)
6061 segmentEnd = vecMultiplyAdd(inRayStart, inRayDirection, -inRayEnd2)
6062 self.BspTree.IntersectWithLine(segmentStart, segmentEnd, 0.0001,
6063 hitPointsB, hitIdsB)
6064 numhitsB = hitPointsB.GetNumberOfPoints()
6065 if PhactoriDbg():
6066 myDebugPrint3("other direction self.BspTree.IntersectWithLine:\n"
6067 "num hits B: " + str(numhitsB) + "\n"
6068 "index, id, xyz B\n")
6069 for hhpp in range(0, numhitsB):
6070 myDebugPrint3(str(hhpp) + ", " + str(hitIdsB.GetId(hhpp)) + ", " + \
6071 str(hitPointsB.GetPoint(hhpp)) + "\n")
6072
6073 #find nearest hit point
6074 if (numhits > 0) or (numhitsB > 0):
6075 hitxyz = [0.0,0.0,0.0]
6076 hit2xyz = [0.0,0.0,0.0]
6077 distsqrd = sys.float_info.max
6078 for ii in range(0,numhits):
6079 hitPoints.GetPoint(ii, hit2xyz)
6080 distsqrd2 = vecDistanceSquared(inRayStart, hit2xyz)
6081 if(distsqrd2 < distsqrd):
6082 distsqrd = distsqrd2
6083 vecCopy(hitxyz, hit2xyz)
6084 for ii in range(0,numhitsB):
6085 hitPointsB.GetPoint(ii, hit2xyz)
6086 distsqrd2 = vecDistanceSquared(inRayStart, hit2xyz)
6087 if(distsqrd2 < distsqrd):
6088 distsqrd = distsqrd2
6089 vecCopy(hitxyz, hit2xyz)
6090
6091 if PhactoriDbg():
6092 myDebugPrint3(
6093 "nearest hit: " + str(distsqrd) + " " + str(hitxyz) + "\n")
6094
6095 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
6096 if inPointOrCellData <= 0:
6097 ioRaycastOperation.SegmentsFromPointRays.TestAndSet(
6098 inIndex, distsqrd, inRayStart, hitxyz)
6099 else:
6100 ioRaycastOperation.SegmentsFromTriangleRays.TestAndSet(
6101 inIndex, distsqrd, inRayStart, hitxyz)
6102 else:
6103 hitdist = math.sqrt(distsqrd)
6104 if inPointOrCellData <= 0:
6105 oldvv = ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
6106 GetValue(inIndex)
6107 if (oldvv < 0.0) or (hitdist < oldvv):
6108 ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
6109 SetValue(inIndex, hitdist)
6110 else:
6111 oldvv = ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
6112 GetValue(inIndex)
6113 if (oldvv < 0.0) or (hitdist < oldvv):
6114 ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
6115 SetValue(inIndex, hitdist)
6116
6117 def IntersectWithOneRay(self, inIndex, inRayStart, inRayDirection,
6118 ioRaycastOperation, inPointOrCellData):
6119 """this is not used, but we are leaving it in as a reference for how to
6120 do a ray/triangle intersection directly"""
6121 if PhactoriDbg():
6122 myDebugPrint3(
6123 "ray: " + str(inIndex) + " " + str(inRayStart) + " " + \
6124 str(inRayDirection) + " " + str(inPointOrCellData) + "\n")
6125
6126 ptA = [0.0,0.0,0.0]
6127 ptB = [0.0,0.0,0.0]
6128 ptC = [0.0,0.0,0.0]
6129 hitPoint = [0.0, 0.0, 0.0, 0.0]
6130 saveHit = [0.0, 0.0, 0.0, -1.0]
6131 #if PhactoriDbg():
6132 # myDebugPrint3(
6133 # "self.Triangles.GetNumberOfValues() " + str(self.Triangles.GetNumberOfValues()) + "\n")
6134 # myDebugPrint3(
6135 # "self.PointXyzs.GetNumberOfValues() " + str(self.PointXyzs.GetNumberOfValues()) + "\n")
6136 hitCount = 0
6137 for ii in range(0, self.numTriangles):
6138 ndx = ii * 3
6139 ptndxA = self.Triangles.GetValue(ndx)
6140 ptndxB = self.Triangles.GetValue(ndx+1)
6141 ptndxC = self.Triangles.GetValue(ndx+2)
6142 #if PhactoriDbg():
6143 # myDebugPrint3("ptndxABC: " + str(ptndxA) + " " + str(ptndxB) + " " + str(ptndxC) + "\n");
6144 ptndxA *= 3
6145 ptA[0] = self.PointXyzs.GetValue(ptndxA)
6146 ptA[1] = self.PointXyzs.GetValue(ptndxA+1)
6147 ptA[2] = self.PointXyzs.GetValue(ptndxA+2)
6148 ptndxB *= 3
6149 ptB[0] = self.PointXyzs.GetValue(ptndxB)
6150 ptB[1] = self.PointXyzs.GetValue(ptndxB+1)
6151 ptB[2] = self.PointXyzs.GetValue(ptndxB+2)
6152 ptndxC *= 3
6153 ptC[0] = self.PointXyzs.GetValue(ptndxC)
6154 ptC[1] = self.PointXyzs.GetValue(ptndxC+1)
6155 ptC[2] = self.PointXyzs.GetValue(ptndxC+2)
6156 #if PhactoriDbg():
6157 # myDebugPrint3("try " + str(ii) + " " + str(ptA) + "\n")
6158 hitFlag = self.IntersectRayTriangle(
6159 inRayStart, inRayDirection, ptA, ptB, ptC, hitPoint)
6160 if hitFlag:
6161 hitCount += 1
6162 if PhactoriDbg():
6163 myDebugPrint3("Hit " + str(hitCount) + "! " + str(hitPoint) + "\n")
6164 vvx = vecFromAToB(inRayStart, hitPoint)
6165 vvxdist = math.sqrt(vecDotProduct(vvx,vvx))
6166 myDebugPrint3("calculated distance: " + str(vvxdist) + "\n")
6167 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
6168 #onelinesource = Line()
6169 #onelinesource.Point1 = inRayStart
6170 #onelinesource.Point2 = [hitPoint[0], hitPoint[1], hitPoint[2]]
6171 #ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)
6172 if (saveHit[3] < 0.0) or (hitPoint[3] < saveHit[3]):
6173 saveHit[0] = hitPoint[0]
6174 saveHit[1] = hitPoint[1]
6175 saveHit[2] = hitPoint[2]
6176 saveHit[3] = hitPoint[3]
6177 else:
6178 if inPointOrCellData <= 0:
6179 oldvv = ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
6180 GetValue(inIndex)
6181 newvv = hitPoint[3]
6182 if (oldvv < 0.0) or (newvv < oldvv):
6183 ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
6184 SetValue(inIndex, hitPoint[3])
6185 else:
6186 oldvv = ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
6187 GetValue(inIndex)
6188 newvv = hitPoint[3]
6189 if (oldvv < 0.0) or (newvv < oldvv):
6190 ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
6191 SetValue(inIndex, hitPoint[3])
6192
6193 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
6194 if saveHit[3] >= 0.0:
6195 onelinesource = Line()
6196 onelinesource.Point1 = inRayStart
6197 onelinesource.Point2 = [saveHit[0], saveHit[1], saveHit[2]]
6198 ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)
6199
6200
6201 def IntersectRayTriangleNumpy(self, inRayStart, inRayDirection, ptA, ptB, ptC, outPt):
6202 #we can remove this import for frozen python (IntersectRayTriangleNumpy
6203 #won't work)
6204 import numpy as np
6205
6206 edge1 = ptB - ptA
6207 edge2 = ptC - ptA
6208 EPSILON = 0.0000001
6209 hh = np.cross(inRayDirection, edge2)
6210 aa = np.dot(edge1, hh)
6211 if (aa > -EPSILON) and (aa < EPSILON):
6212 return False
6213 ff = 1.0/aa
6214 ss = inRayStart - ptA
6215 uu = np.dot(ss, hh)
6216 uu *= ff
6217 if (uu < 0.0) or (uu > 1.0):
6218 return False;
6219 qq = np.cross(ss, edge1)
6220 vv = np.dot(inRayDirection, qq)
6221 vv *= ff
6222 if (vv < 0.0) or (uu + vv > 1.0):
6223 return False;
6224 #At this stage we can compute t to find out where the intersection point
6225 #is on the line.
6226 tt = np.dot(edge2, qq)
6227 tt *= ff
6228 if (tt > EPSILON):
6229 #ray intersection
6230 outPt[0] = inRayStart[0] + inRayDirection[0] * tt
6231 outPt[1] = inRayStart[1] + inRayDirection[1] * tt
6232 outPt[2] = inRayStart[2] + inRayDirection[2] * tt
6233 outPt[3] = tt
6234 return True
6235 else:
6236 #This means that there is a line intersection but not a ray intersection
6237 return False
6238
6239 def IntersectRayTriangle(self, inRayStart, inRayDirection, ptA, ptB, ptC, outPt):
6240 #if PhactoriDbg():
6241 # myDebugPrint3("IntersectRayTriangle entered " + str(ptA) + "\n")
6242 #c function from wikipedia translated to python
6243 edge1 = vecFromAToB(ptA, ptB)
6244 edge2 = vecFromAToB(ptA, ptC)
6245 EPSILON = 0.0000001
6246 hh = vecCrossProduct(inRayDirection, edge2)
6247 aa = vecDotProduct(edge1, hh)
6248 if (aa > -EPSILON) and (aa < EPSILON):
6249 return False
6250 ff = 1.0/aa
6251 ss = vecFromAToB(ptA, inRayStart)
6252 uu = vecDotProduct(ss, hh)
6253 uu *= ff
6254 if (uu < 0.0) or (uu > 1.0):
6255 return False;
6256 qq = vecCrossProduct(ss, edge1)
6257 vv = vecDotProduct(inRayDirection, qq)
6258 vv *= ff
6259 if (vv < 0.0) or (uu + vv > 1.0):
6260 return False;
6261 #At this stage we can compute t to find out where the intersection point
6262 #is on the line.
6263 tt = vecDotProduct(edge2, qq)
6264 tt *= ff
6265 if (tt > EPSILON):
6266 #ray intersection
6267 outPt[0] = inRayStart[0] + inRayDirection[0] * tt
6268 outPt[1] = inRayStart[1] + inRayDirection[1] * tt
6269 outPt[2] = inRayStart[2] + inRayDirection[2] * tt
6270 outPt[3] = tt
6271 return True
6272 else:
6273 #This means that there is a line intersection but not a ray intersection
6274 return False
6275
6276 def CreateBspTree(self):
6277 if PhactoriDbg():
6278 myDebugPrint3("CreateBspTree entered, creating\n")
6279
6280 if self.BspTree != None:
6281 #clear/delete bsp tree to avoid memory leak; may be unnecessary
6282 if PhactoriDbg():
6283 myDebugPrint3("clearing old bsp tree\n")
6284 self.BspTree.FreeSearchStructure()
6285 #?Delete(self.BspTree)
6286 self.BspTree = None
6287
6288 self.BspTreePolyData = vtk.vtkPolyData()
6289
6290 tmpPoints = vtk.vtkPoints()
6291 ptxyz = self.PointXyzs
6292 numvls = ptxyz.GetNumberOfValues()
6293 for ii in range(0, numvls, 3):
6294 tmpPoints.InsertNextPoint(ptxyz.GetValue(ii), ptxyz.GetValue(ii+1),
6295 ptxyz.GetValue(ii+2))
6296
6297 tmpTriangles = vtk.vtkCellArray()
6298 tris = self.Triangles
6299 numtripts = tris.GetNumberOfValues()
6300 for ii in range(0, numtripts, 3):
6301 newtri = vtk.vtkTriangle()
6302 newtri.GetPointIds().SetId(0, tris.GetValue(ii))
6303 newtri.GetPointIds().SetId(1, tris.GetValue(ii+1))
6304 newtri.GetPointIds().SetId(2, tris.GetValue(ii+2))
6305 tmpTriangles.InsertNextCell(newtri)
6306
6307 self.BspTreePolyData.SetPoints(tmpPoints)
6308 self.BspTreePolyData.SetPolys(tmpTriangles)
6309 self.BspTree = vtk.vtkFiltersFlowPaths.vtkModifiedBSPTree()
6310 self.BspTree.SetDataSet(self.BspTreePolyData);
6311 self.BspTree.BuildLocator();
6312 if PhactoriDbg():
6313 myDebugPrint3("dir for self.BspTree:\n")
6314 myDebugPrint3(str(dir(self.BspTree)) + "\n")
6315 myDebugPrint3("str(self.BspTree):\n")
6316 myDebugPrint3(str(self.BspTree) + "\n")
6317 myDebugPrint3("CreateBspTree returning\n")
6318
6319 def IntersectWithNormalRaysFromSourceTriangles(self,
6320 inSourcePhactoriOp, ioRaycastOperation, inSourceSharedTriangles):
6321 if PhactoriDbg():
6322 myDebugPrint3(
6323 "IntersectWithNormalRaysFromSourceTriangles entered\n" \
6324 "target triangle set from pid " + str(self.fromPid) + "\n"\
6325 "source triangle set from pid " + \
6326 str(inSourceSharedTriangles.fromPid) + "\n"\
6327 "target num triangles, num points: " + str(self.numTriangles) + ", " +\
6328 str(self.numPoints) + "\n" + \
6329 "target num triangles, num points: " + str(self.numTriangles) + ", " +\
6330 str(self.numPoints) + "\n")
6331
6332 csdata = inSourcePhactoriOp.mParaViewFilter.GetClientSideObject().\
6333 GetOutputDataObject(0)
6334
6335 numSourceCells = csdata.GetNumberOfCells()
6336 if PhactoriDbg():
6337 myDebugPrint3("inSourcePhactoriOp.mParaViewFilter: " + \
6338 str(inSourcePhactoriOp.mParaViewFilter) + "\n")
6339 myDebugPrint3("csdata: " + str(csdata) + "\n")
6340 myDebugPrint3("numSourceCells: " + str(numSourceCells) + "\n")
6341
6342 if numSourceCells <= 0:
6343 #nothing here, but maybe need to create empty item
6344 return
6345
6346 cellData = csdata.GetPointData()
6347
6348 nrmls = cellData.GetArray("Normals")
6349 if nrmls == None:
6350 myDebugPrint3AndException("IntersectWithNormalRaysFromSourceTriangles: " \
6351 "no Normals cell data\n")
6352
6353 #pointXyza = [0.0,0.0,0.0]
6354 #pointXyzb = [0.0,0.0,0.0]
6355 #pointXyzc = [0.0,0.0,0.0]
6356 cntrd = [0.0, 0.0, 0.0]
6357 onethird = 1.0/3.0
6358 cellPointIds = vtk.vtkIdList()
6359 for ii in range(0,numSourceCells):
6360 theNormalTuple = nrmls.GetTuple3(ii)
6361 ndx = ii*3
6362 ##csdata.GetPoint(ii, pointXyz)
6363 #ptndxa = inSourceSharedTriangles.Triangles.GetValue(ndx) * 3
6364 #ptndxb = inSourceSharedTriangles.Triangles.GetValue(ndx+1) * 3
6365 #ptndxc = inSourceSharedTriangles.Triangles.GetValue(ndx+2) * 3
6366 #cntrd[0] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa)
6367 #cntrd[0] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb)
6368 #cntrd[0] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc)
6369 #cntrd[0] *= onethird
6370 #cntrd[1] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa+1)
6371 #cntrd[1] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb+1)
6372 #cntrd[1] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc+1)
6373 #cntrd[1] *= onethird
6374 #cntrd[2] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa+2)
6375 #cntrd[2] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb+2)
6376 #cntrd[2] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc+2)
6377 #cntrd[2] *= onethird
6378 csdata.GetCellPoints(ii, cellPointIds)
6379 #numpoints should be 3
6380 numids = cellPointIds.GetNumberOfIds()
6381 if numids != 3:
6382 if numids < 3:
6383 #degenerate ? try just skipping
6384 if PhactoriDbg():
6385 myDebugPrint3AndException(str(ii) + " degenerate 2 point\n")
6386 continue
6387 if True: #for now we consider this fatal error
6388 myDebugPrint3AndException(
6389 "PhactoriIntersectNodeNormalsWithSurface::CreateFromLocalProcess\n"
6390 "encountered non-triangle\n")
6391 continue
6392 ptndxa = cellPointIds.GetId(0)
6393 ptndxb = cellPointIds.GetId(1)
6394 ptndxc = cellPointIds.GetId(2)
6395 #trying to get it to work just use first point on triangle
6396 csdata.GetPoint(ptndxa, cntrd)
6397
6398 if self.UseBSPTreeForRayIntersection:
6399 self.IntersectWithOneRayViaBSPTree(ii, cntrd, theNormalTuple,
6400 ioRaycastOperation, 1, -0.1, 10.0, False)
6401 #ioRaycastOperation, 1, 0.0001, 4.0, False)
6402 else:
6403 self.IntersectWithOneRay(
6404 ii, cntrd, theNormalTuple, ioRaycastOperation, 1)
6405
6406 if PhactoriDbg():
6407 myDebugPrint3("IntersectWithNormalRaysFromSourceTriangles returning\n")
6408
6409 def IntersectWithNormalRaysFromSource(self, inSourcePhactoriOp,
6410 ioRaycastOperation):
6411 if PhactoriDbg():
6412 myDebugPrint3("IntersectWithNormalRaysFromSource entered\n" \
6413 "triangle set from pid " + str(self.fromPid) + "\n"\
6414 "num triangles, num points: " + str(self.numTriangles) + ", " +
6415 str(self.numPoints) + "\n")
6416
6417 csdata = inSourcePhactoriOp.mParaViewFilter.GetClientSideObject().\
6418 GetOutputDataObject(0)
6419
6420 if self.UseBSPTreeForRayIntersection:
6421 self.CreateBspTree()
6422
6423 numSourcePoints = csdata.GetNumberOfPoints()
6424 if PhactoriDbg():
6425 myDebugPrint3("inSourcePhactoriOp.mParaViewFilter: " + str(inSourcePhactoriOp.mParaViewFilter) + "\n")
6426 myDebugPrint3("csdata: " + str(csdata) + "\n")
6427 myDebugPrint3("numSourcePoints: " + str(numSourcePoints) + "\n")
6428
6429 if numSourcePoints <= 0:
6430 #nothing here, but maybe need to create empty item
6431 return
6432
6433 pntData = csdata.GetPointData()
6434
6435 nrmls = pntData.GetArray("Normals")
6436 if nrmls == None:
6437 myDebugPrint3AndException(
6438 "IntersectWithNormalRaysFromSource: no Normals point data\n")
6439
6440 pointXyz = [0.0,0.0,0.0]
6441 #pointXyz = np.array([0.0,0.0,0.0])
6442
6443 for ii in range(0,numSourcePoints):
6444 theNormalTuple = nrmls.GetTuple3(ii)
6445 #theNormalTuple = np.array(nrmls.GetTuple3(ii))
6446 csdata.GetPoint(ii, pointXyz)
6447 if self.UseBSPTreeForRayIntersection:
6448 self.IntersectWithOneRayViaBSPTree(ii, pointXyz, theNormalTuple,
6449 ioRaycastOperation, 0, -0.1, 10.0, False)
6450 #ioRaycastOperation, 0, 0.0001, 4.0, False)
6451 else:
6452 self.IntersectWithOneRay(
6453 ii, pointXyz, theNormalTuple, ioRaycastOperation, 0)
6454
6455 if PhactoriDbg():
6456 myDebugPrint3("IntersectWithNormalRaysFromSource returning\n")
6457
6458
6459 class PhactoriSegmentGroup1Item:
6460 """one segment in PhactoriSegmentGroup1"""
6461 def __init__(self):
6462 self.ParaViewLineSource = None
6463 self.Point1 = [0.0, 0.0, 0.0]
6464 self.Point2 = [0.0, 0.0, 0.0]
6465 self.LengthSquared = sys.float_info.max
6466 self.mVtkLine = vtk.vtkLine()
6467
6468 def UpdateVtkLine(self, inIdx, ioVtkPoints):
6469 idx = inIdx*2
6470 self.mVtkLine.GetPointIds().SetId(0,idx)
6471 self.mVtkLine.GetPointIds().SetId(1,idx+1)
6472 ioVtkPoints.SetPoint(idx, self.Point1)
6473 ioVtkPoints.SetPoint(idx+1, self.Point2)
6474
6475 def TestAndSet(self, inLengthSquared, inPt1, inPt2):
6476 if inLengthSquared < self.LengthSquared:
6477 self.LengthSquared = inLengthSquared
6478 vecCopy(self.Point1, inPt1)
6479 vecCopy(self.Point2, inPt2)
6480
6481 class PhactoriSegmentGroup1:
6482 """manage a set of segments for purposes of showing raycast results"""
6483 def __init__(self):
6484 self.Segments = []
6485 self.mVtkPoints = vtk.vtkPoints()
6486 self.mVtkPolyData = vtk.vtkPolyData()
6487 self.mVtkCellArray = vtk.vtkCellArray()
6488
6489 def SetupWithNumberOfItems(self, inCount):
6490 #we need to get arrays the right length and delete extra line sources
6491 while len(self.Segments) < inCount:
6492 self.Segments.append(PhactoriSegmentGroup1Item())
6493 while len(self.Segments) > inCount:
6494 pp = self.Segments.pop()
6495 #do we need this?
6496 #Delete(self.mVtkLine)
6497 #or this?
6498 #del self.mVtkLine
6499 exit(-1)
6500
6501 self.mVtkPoints.SetNumberOfPoints(inCount * 2)
6502
6503 for ii in self.Segments:
6504 ii.LengthSquared = sys.float_info.max
6505
6506 def UpdateParaViewSegments(self, inSegmentMinLength):
6507 self.mVtkCellArray.SetNumberOfCells(0)
6508 for idx, ii in enumerate(self.Segments):
6509 if PhactoriDbg():
6510 myDebugPrint3("UpdateParaViewSegments " + str(idx) + "\n")
6511 ii.UpdateVtkLine(idx, self.mVtkPoints)
6512 tstminsqrd = inSegmentMinLength * inSegmentMinLength
6513 if ii.LengthSquared != sys.float_info.max:
6514 if tstminsqrd <= ii.LengthSquared:
6515 self.mVtkCellArray.InsertNextCell(ii.mVtkLine)
6516
6517 self.mVtkPolyData.SetPoints(self.mVtkPoints)
6518 self.mVtkPolyData.SetLines(self.mVtkCellArray)
6519
6520 def TestAndSet(self, inIndex, inLengthSquared, inPt1, inPt2):
6521 self.Segments[inIndex].TestAndSet(inLengthSquared, inPt1, inPt2)
6522
6523 #phactori_combine_to_single_python_file_parent_1
6524 from Operation.PhactoriVtkDataExportOperation import *
6525
6526 #phactori_combine_to_single_python_file_parent_1
6527 from Operation.PhactoriPartitionedToMultiBlockOperation import *
6528
6529 #phactori_combine_to_single_python_file_parent_1
6530 from Operation.PhactoriExodusIIExportOperation import *
6531
6532 #phactori_combine_to_single_python_file_parent_1
6533 from Operation.PhactoriCSVExportOperation import *
6534
6535 class PhactoriIntersectNodeNormalsWithSurface(PhactoriOperationSpecifics):
6536 """takes each node ND from surface SS and its corresponding normal vector
6537 NN, and casts a ray RR towards the second surface TT which must be a set
6538 of triangles and finds if and where RR intersects TT at point XX. For
6539 now it creates a new nodal variable NormalRayDistance which is the
6540 length of RR between ND and XX. We may add capability in the future
6541 to store the XX as well, although this can be presumably be recovered
6542 from the normal and the distance"""
6543
6544 def __init__(self):
6545 PhactoriOperationSpecifics.__init__(self)
6546 #filled in from parsing
6547 self.mSourceOperationName = None
6548 self.mTargetOperationName = None
6549
6550 #filled in by finding operation id'd by self.mSourceOperationName
6551 self.mSourceOperation = None
6552
6553 #filled in by finding operation id'd by self.mTargetOperationName
6554 self.mTargetOperation = None
6555
6556 self.mCalculationFrameTag = -1
6557
6558 self.mLocalTriangleSet = SharedTriangleSet()
6559 self.mReceiveTriangleSet = SharedTriangleSet()
6560
6561 self.mPointRayLineSource = None
6562 self.mTriangleRayLineSource = None
6563 self.mGroupLineSource = None
6564
6565 self.mCreateIntersectionSegmentGroup = False
6566 self.mIntersectionSegmentGroupMinLength = 0.0
6567 self.mPointNormalRayIntersectDistanceArray = None
6568 self.mCellNormalRayIntersectDistanceArray = None
6569
6570 self.SegmentsFromPointRays = PhactoriSegmentGroup1()
6571 self.SegmentsFromTriangleRays = PhactoriSegmentGroup1()
6572
6573 def ParseParametersFromJson(self, inJson):
6574 if "target operation" in inJson:
6575 self.mTargetOperationName = inJson["target operation"]
6576 elif "target_operation" in inJson:
6577 self.mTargetOperationName = inJson["target_operation"]
6578 else:
6579 myDebugPrint3AndException(
6580 "PhactoriIntersectNodeNormalsWithSurface::ParseParametersFromJson\n"
6581 "Error: must have 'target operation' or 'target_operation' token\n")
6582 if "input" in inJson:
6583 self.mSourceOperationName = inJson["input"]
6584 else:
6585 #will use default input for source
6586 self.mSourceOperationName = None
6587
6588 if "create intersection segment group" in inJson:
6589 self.mCreateIntersectionSegmentGroup = \
6590 inJson["create intersection segment group"]
6591 elif "create_intersection_segment_group" in inJson:
6592 self.mCreateIntersectionSegmentGroup = \
6593 inJson["create_intersection_segment_group"]
6594
6595 isgmlkey1 = "intersection segment group minimum length"
6596 isgmlkey2 = "intersection_segment_group_minimum_length"
6597 if isgmlkey1 in inJson:
6598 self.mIntersectionSegmentGroupMinLength = inJson[isgmlkey1]
6599 elif isgmlkey2 in inJson:
6600 self.mIntersectionSegmentGroupMinLength = inJson[isgmlkey2]
6601
6602 def CreateParaViewFilter(self, inInputFilter):
6603 """create the filter for ParaView"""
6604 if PhactoriDbg(100):
6605 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
6606 "CreateParaViewFilter entered\n", 100)
6607 #info in block class should already be parsed and checked
6608
6609 savedActiveSource = GetActiveSource()
6610
6611 if self.mCreateIntersectionSegmentGroup == True:
6612
6613 self.mPointRayLineSource = PVTrivialProducer()
6614 self.mPointRayLineSource.GetClientSideObject().SetOutput(
6615 self.SegmentsFromPointRays.mVtkPolyData)
6616 self.mTriangleRayLineSource = PVTrivialProducer()
6617 self.mTriangleRayLineSource.GetClientSideObject().SetOutput(
6618 self.SegmentsFromTriangleRays.mVtkPolyData)
6619
6620 #newParaViewFilter = GroupDatasets(Input = [])
6621 #self.mGroupLineSource = newParaViewFilter
6622
6623 self.mGroupLineSource = GroupDatasets(
6624 Input = [self.mPointRayLineSource, self.mTriangleRayLineSource])
6625 self.mTubeFilter = Tube(Input = self.mGroupLineSource)
6626 #self.mTubeFilter.NumberofSides = 8
6627 self.mTubeFilter.Radius = 0.01
6628 #self.mTubeFilter.VaryRadius = 'By Scalar'
6629 newParaViewFilter = self.mTubeFilter
6630
6631 else:
6632 newParaViewFilter = PVTrivialProducer()
6633 passthru = inInputFilter.GetClientSideObject().GetOutputDataObject(0)
6634
6635 numpts = passthru.GetNumberOfPoints()
6636
6637 newvar = vtk.vtkDoubleArray()
6638 newvar.SetNumberOfComponents(1)
6639 newvar.SetName("PointNormalRayIntersectDistance")
6640 for ii in range(0, numpts):
6641 newvar.InsertNextValue(float(-1.0))
6642 passthru.GetPointData().AddArray(newvar)
6643 self.mPointNormalRayIntersectDistanceArray = \
6644 passthru.GetPointData().GetArray("PointNormalRayIntersectDistance")
6645
6646 numcells = passthru.GetNumberOfCells()
6647
6648 newvar2 = vtk.vtkDoubleArray()
6649 newvar2.SetNumberOfComponents(1)
6650 newvar2.SetName("CellNormalRayIntersectDistance")
6651 for ii in range(0, numcells):
6652 newvar2.InsertNextValue(float(-1.0))
6653 passthru.GetCellData().AddArray(newvar2)
6654 self.mCellNormalRayIntersectDistanceArray = \
6655 passthru.GetCellData().GetArray("CellNormalRayIntersectDistance")
6656
6657 if PhactoriDbg(100):
6658 numpts = passthru.GetNumberOfPoints()
6659 myDebugPrint3("numpts: " + str(numpts) + "\n")
6660 numptarrays = passthru.GetPointData().GetNumberOfArrays()
6661 myDebugPrint3("numptarrays: " + str(numptarrays) + "\n")
6662 numcells = passthru.GetNumberOfCells()
6663 myDebugPrint3("numcells: " + str(numcells) + "\n")
6664 numcellarrays = passthru.GetCellData().GetNumberOfArrays()
6665 myDebugPrint3("numcellarrays: " + str(numcellarrays) + "\n")
6666
6667 newParaViewFilter.GetClientSideObject().SetOutput(passthru)
6668
6669 SetActiveSource(newParaViewFilter)
6670 SetActiveSource(savedActiveSource)
6671
6672 if PhactoriDbg(100):
6673 myDebugPrint3(str(self.mGroupLineSource))
6674 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
6675 "CreateParaViewFilter returning\n", 100)
6676
6677 return newParaViewFilter
6678
6679 def RunCalculationToCastRays(self, ioPipeAndViewsState):
6680 """our technique is as follows: we loop through the pids of all the
6681 processes and each broadcasts the set triangles TTPID that pid holds
6682 from the target source to all the other processes. Then each process
6683 casts rays from the nodes on the source surface that it holds (along
6684 the node normals) towards TTPID and finds the intersection if any.
6685 If a closer intersection is found than the existing one, the closer is
6686 used. At the end of this loop the distance is known for each node on
6687 its own process (and if there was no intersection, which can be NAN or
6688 some arbitrary value).
6689 Initial implementation doesn't worry about self-intersection, but we
6690 can add additional features to expect certain number of 0 distance
6691 hits and ignore those or to remove self node and surrounding tris from
6692 the list of those to intersect"""
6693 if PhactoriDbg(100):
6694 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
6695 "RunCalculationToCastRays entered\n", 100)
6696 import time
6697 tmstrt = time.clock()
6698
6699 if self.mCalculationFrameTag >= ioPipeAndViewsState.mFrameTagCounter:
6700 if PhactoriDbg(100):
6701 myDebugPrint3(\
6702 "self.mCalculationFrameTag indicates we have already run calc\n")
6703 return
6704 self.mCalculationFrameTag = ioPipeAndViewsState.mFrameTagCounter
6705
6706 #get the source and target operations if necessary
6707 if(self.mTargetOperation == None):
6708 self.mTargetOperation = ioPipeAndViewsState.mOperationBlocks[
6709 self.mTargetOperationName]
6710 if(self.mTargetOperation == None):
6711 myDebugPrint3AndException("PhactoriIntersectNodeNormalsWithSurface:" \
6712 "RunCalculationToCastRays\ncouldn't find target " \
6713 "operation named " + str(self.mTargetOperationName) + "\n")
6714 if self.mSourceOperation == None:
6715 if self.mSourceOperationName == None:
6716 self.mSourceOperation = ioPipeAndViewsState.mIncomingDefaultOperation
6717 else:
6718 self.mSourceOperation = ioPipeAndViewsState.mOperationBlocks[
6719 self.mSourceOperationName]
6720 if self.mSourceOperation == None:
6721 myDebugPrint3AndException("PhactoriIntersectNodeNormalsWithSurface:" \
6722 "RunCalculationToCastRays\ncouldn't find source " \
6723 "operation named " + str(self.mSourceOperationName) + "\n")
6724
6725 #first figure out the set of triangles from the target surface are on the
6726 #local process
6727 self.mLocalTriangleSet.CreateFromLocalProcess(self.mTargetOperation)
6728
6729 #next figure out the set of nodes from the source surface are on the local
6730 #process
6731
6732 #set up to hold the results
6733
6734 #set up for line segments, if we are doing them
6735 if self.mCreateIntersectionSegmentGroup:
6736 csdata = self.mSourceOperation.mParaViewFilter.GetClientSideObject().\
6737 GetOutputDataObject(0)
6738 numSourcePoints = csdata.GetNumberOfPoints()
6739 self.SegmentsFromPointRays.SetupWithNumberOfItems(numSourcePoints)
6740 #self.SegmentsFromTriangleRays.SetupWithNumberOfItems(
6741 # self.mLocalTriangleSet.numTriangles)
6742
6743 #now loop through all processes; one process at a time share the triangles
6744 #from each process to the others and intersect with the local surface
6745 #portion
6746
6747 mypid = SmartGetLocalProcessId()
6748
6749 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
6750 globalController = pm.GetGlobalController()
6751 #gLocalProcessId = globalController.GetLocalProcessId()
6752 numproc = globalController.GetNumberOfProcesses()
6753 if PhactoriDbg(100):
6754 myDebugPrint3(
6755 "mypid: " + str(mypid) + " numproc: " + str(numproc) + "\n")
6756
6757 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
6758 globalController = pm.GetGlobalController()
6759 for ii in range(0,numproc):
6760 if ii == mypid:
6761 self.mLocalTriangleSet.SendBroadcast(ii, globalController)
6762 #self.mLocalTriangleSet.IntersectWithNormalRaysFromSourceTriangles(
6763 # self.mSourceOperation, self, self.mLocalTriangleSet)
6764 self.mLocalTriangleSet.IntersectWithNormalRaysFromSource(
6765 self.mSourceOperation, self)
6766 else:
6767 self.mReceiveTriangleSet.ReceiveBroadcast(ii, globalController)
6768 #self.mReceiveTriangleSet.IntersectWithNormalRaysFromSourceTriangles(
6769 # self.mSourceOperation, self, self.mLocalTriangleSet)
6770 self.mReceiveTriangleSet.IntersectWithNormalRaysFromSource(
6771 self.mSourceOperation, self)
6772
6773 tmend = time.clock()
6774
6775 if PhactoriDbg(100):
6776 myDebugPrint3("time for RunCalculationToCastRays: " + \
6777 str(tmend - tmstrt) + "\n")
6778 else:
6779 print("time for RunCalculationToCastRays raycasting: " + str(tmend - tmstrt))
6780
6781 #create/handle line segments, if we are doing them
6782 if self.mCreateIntersectionSegmentGroup:
6783 self.SegmentsFromPointRays.UpdateParaViewSegments(
6784 self.mIntersectionSegmentGroupMinLength)
6785 #self.SegmentsFromTriangleRays.UpdateParaViewSegments()
6786
6787 tmend2 = time.clock()
6788 if PhactoriDbg(100):
6789 myDebugPrint3(
6790 "time for RunCalculationToCastRays line segment making: " + \
6791 str(tmend2 - tmend) + "\n")
6792
6793 if PhactoriDbg(100):
6794 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
6795 "RunCalculationToCastRays returning\n", 100)
6796
6797 def ExportOperationData(self, datadescription):
6798 """this will be called once per callback (before WriteImages) to allow the
6799 operation to export any desired data which is not an image. The child
6800 class should override this method if it wants so do something.
6801 For PhactoriIntersectNodeNormalsWithSurface we will output information
6802 about the nearest and furthest intersections"""
6803
6804 if PhactoriDbg(100):
6805 myDebugPrint3(
6806 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData "
6807 "entered\n", 100)
6808
6809 UpdatePipelineWithCurrentTimeArgument(
6810 self.mPhactoriOperationBlockOwner.mParaViewFilter)
6811 self.RunCalculationToCastRays(gPipeAndViewsState)
6812 UpdatePipelineWithCurrentTimeArgument(
6813 self.mPhactoriOperationBlockOwner.mParaViewFilter)
6814
6815 if self.mPointNormalRayIntersectDistanceArray == None:
6816 if PhactoriDbg(100):
6817 myDebugPrint3("no data values, returning\n")
6818 return
6819
6820 numpts = self.mPointNormalRayIntersectDistanceArray.GetNumberOfValues()
6821 maxval = -1.0
6822 minval = -1.0
6823 minval2 = -1.0
6824 if numpts > 0:
6825 vv = self.mPointNormalRayIntersectDistanceArray.GetValue(0)
6826 maxval = vv
6827 minval = vv
6828 if vv >= -0.5:
6829 minval2 = vv
6830 for ii in range(1, numpts):
6831 vv = self.mPointNormalRayIntersectDistanceArray.GetValue(ii)
6832 if vv > maxval:
6833 maxval = vv
6834 if vv < minval:
6835 minval = vv
6836 if vv >= -0.5:
6837 if (minval2 < -0.5) or (vv < minval2):
6838 minval2 = vv
6839
6840 fname = "RayIntersectionMinMax_" + \
6841 self.mPhactoriOperationBlockOwner.mName + "_process_" + \
6842 str(SmartGetLocalProcessId()) + ".txt"
6843 try:
6844 ff = open(fname, "a+b")
6845 ff.write("minimum, maximum, nonnegative minimum\n")
6846 ff.write(str(minval) + ", " + str(maxval) + ", " + str(minval2) + "\n")
6847 except:
6848 myDebugPrint3AndException(
6849 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData\n"
6850 "Error writing file: " + str(fname) + "\n")
6851
6852 if PhactoriDbg(100):
6853 myDebugPrint3(
6854 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData "
6855 "returning\n", 100)
6856 return
6857
6858
6859 class PhactoriNearestPointsOperation(PhactoriOperationSpecifics):
6860 """finds the set of N nearest nodes between a source operation/input and
6861 a target operation input. Also outputs a table of the set of nodes
6862 and distances at render time. This operation as currently constructed
6863 pulls all the target nodes into each processor and thus may cause memory
6864 issues. It may be advisible to use, e.g. quadrature decimation to
6865 reduce the number of points in the target and/or source first. We may
6866 eventually make this a multi-stage operation to first operate on
6867 a reduced set of points to find a subset of the original sets of points
6868 to then do an exact comparison on. We may also eventually change to
6869 operated based on a space partitioning tree to avoid checking every
6870 point against every point"""
6871 def __init__(self):
6872 PhactoriOperationSpecifics.__init__(self)
6873 #filled in from parsing
6874 self.mSourceOperationName = None
6875 self.mTargetOperationName = None
6876
6877 #filled in by finding operation id'd by self.mSourceOperationName
6878 self.mSourceOperation = None
6879
6880 #filled in by finding operation id'd by self.mTargetOperationName
6881 self.mTargetOperation = None
6882
6883 #controls how many points we look for in each process, and then how many
6884 #points out of those we select as nearest
6885 #if self.mNumPointsToFind > self.mNumPointsPerProcess it is possible to
6886 #have incorrect points beyond self.mNumPointsPerProcess when all the
6887 #nearest points happen to reside on one process
6888 self.mNumPointsPerProcess = 5
6889 self.mNumPointsToFind = 5
6890
6891 #class to maintain parallel shared information
6892 self.mClosestNPointsFromEachProcess = None
6893
6894 self.mLineSource = None
6895
6896 self.mCalculationFrameTag = -1
6897
6898 self.mWriteCsvResults = True
6899 self.mCsvFileBasedirectory = gPipeAndViewsState.mDefaultBasedirectory
6900 self.mCsvFileName = None
6901
6902 #if not None, this will be a string which identifies a text annotation
6903 #which the user has to create normally. If said annotation exists, this
6904 #operation will overwrite the text for the annotation with information
6905 #on the nearest point
6906 self.mOutputToTextAnnotationName = None
6907 self.mTextAnnotationOutputTarget = None
6908
6909 self.mTxtAntnFormatString = None
6910 self.mCsvFormatString = None
6911
6912 def ParseParametersFromJson(self, inJson):
6913
6914 self.mTxtAntnFormatString = getParameterFromBlock(inJson,
6915 'text annotation float format string', self.mTxtAntnFormatString)
6916 self.mTxtAntnFormatString = getParameterFromBlock(inJson,
6917 'text_annotation_float_format_string', self.mTxtAntnFormatString)
6918 self.mCsvFormatString = getParameterFromBlock(inJson,
6919 'csv float format string', self.mCsvFormatString)
6920 self.mCsvFormatString = getParameterFromBlock(inJson,
6921 'csv_float_format_string', self.mCsvFormatString)
6922 self.mOutputToTextAnnotationName = getParameterFromBlock(inJson,
6923 'output to text annnotation', self.mOutputToTextAnnotationName)
6924 self.mOutputToTextAnnotationName = getParameterFromBlock(inJson,
6925 'output_to_text_annnotation', self.mOutputToTextAnnotationName)
6926 self.mWriteCsvResults = getParameterFromBlock(inJson,
6927 'write_results_csv_file', self.mWriteCsvResults)
6928 self.mWriteCsvResults = getParameterFromBlock(inJson,
6929 'write results csv file', self.mWriteCsvResults)
6930 self.mCsvFileName = getParameterFromBlock(inJson,
6931 'csv_results_filename', self.mCsvFileName)
6932 self.mCsvFileName = getParameterFromBlock(inJson,
6933 'csv results filename', self.mCsvFileName)
6934 self.mCsvFileBasedirectory = getParameterFromBlock(inJson,
6935 'csv_results_basedirectory', self.mCsvFileBasedirectory)
6936 self.mCsvFileBasedirectory = getParameterFromBlock(inJson,
6937 'csv results basedirectory', self.mCsvFileBasedirectory)
6938 if self.mCsvFileName == None:
6939 #make default name including operation name and datetime, without
6940 #microseconds
6941 import datetime
6942 nn = datetime.datetime.now()
6943 self.mCsvFileName = self.mPhactoriOperationBlockOwner.mName + \
6944 ".nearestpoints." + (nn.isoformat()[0:-7]) + ".csv"
6945 if 'target operation' in inJson:
6946 self.mTargetOperationName = inJson['target operation']
6947 elif 'target_operation' in inJson:
6948 self.mTargetOperationName = inJson['target_operation']
6949 else:
6950 myDebugPrint3AndException(
6951 "PhactoriNearestPointsOperation::ParseParametersFromJson\n"
6952 "Error: must have 'target operation' or 'target_operation' token\n")
6953 if 'input' in inJson:
6954 self.mSourceOperationName = inJson['input']
6955 else:
6956 #will use default input for source
6957 self.mSourceOperationName = None
6958
6959 if 'number of points per process' in inJson:
6960 self.mNumPointsPerProcess = inJson['number of points per process']
6961 elif 'number_of_points_per_process' in inJson:
6962 self.mNumPointsPerProcess = inJson['number_of_points_per_process']
6963 if 'number of points to find' in inJson:
6964 self.mNumPointsToFind = inJson['number of points to find']
6965 #unless user purposely set self.mNumPointsPerProcess different, we want
6966 #self.mNumPointsPerProcess == self.mNumPointsToFind
6967 if 'number of points per process' not in inJson:
6968 self.mNumPointsPerProcess = self.mNumPointsToFind
6969 elif 'number_of_points_to_find' in inJson:
6970 self.mNumPointsToFind = inJson['number_of_points_to_find']
6971 #unless user purposely set self.mNumPointsPerProcess different, we want
6972 #self.mNumPointsPerProcess == self.mNumPointsToFind
6973 if 'number_of_points per_process' not in inJson:
6974 self.mNumPointsPerProcess = self.mNumPointsToFind
6975
6976 def CreateParaViewFilter(self, inInputFilter):
6977 """create the group filter for ParaView"""
6978 if PhactoriDbg(100):
6979 myDebugPrint3("PhactoriNearestPointsOperation.CreateParaViewFilter "
6980 "entered\n", 100)
6981 #info in block class should already be parsed and checked
6982
6983 savedActiveSource = GetActiveSource()
6984
6985 #newParaViewFilter = Sphere()
6986 newParaViewFilter = Line()
6987 newParaViewFilter.Point1 = [0.0, 0.0, 0.0]
6988 newParaViewFilter.Point2 = [0.01, 0.01, 0.01]
6989
6990 SetActiveSource(newParaViewFilter)
6991 SetActiveSource(savedActiveSource)
6992
6993 if PhactoriDbg(100):
6994 myDebugPrint3("PhactoriNearestPointsOperation.CreateParaViewFilter "
6995 "returning\n", 100)
6996
6997 self.mLineSource = newParaViewFilter
6998 return newParaViewFilter
6999
7000 def RunCalculationToFindNearestPoints(self, ioPipeAndViewsState):
7001 if PhactoriDbg(100):
7002 myDebugPrint3("PhactoriNearestPointsOperation." \
7003 "RunCalculationToFindNearestPoints entered\n", 100)
7004
7005 if self.mCalculationFrameTag >= ioPipeAndViewsState.mFrameTagCounter:
7006 if PhactoriDbg(100):
7007 myDebugPrint3(\
7008 "self.mCalculationFrameTag indicates we have already run calc\n")
7009 return
7010 self.mCalculationFrameTag = ioPipeAndViewsState.mFrameTagCounter
7011
7012 #get the source and target operations if necessary
7013 if(self.mTargetOperation == None):
7014 self.mTargetOperation = ioPipeAndViewsState.mOperationBlocks[
7015 self.mTargetOperationName]
7016 if(self.mTargetOperation == None):
7017 myDebugPrint3AndException("PhactoriNearestPointsOperation:" \
7018 "RunCalculationToFindNearestPoints\ncouldn't find target " \
7019 "operation named " + str(self.mTargetOperationName) + "\n")
7020 if self.mSourceOperation == None:
7021 if self.mSourceOperationName == None:
7022 self.mSourceOperation = ioPipeAndViewsState.mIncomingDefaultOperation
7023 else:
7024 self.mSourceOperation = ioPipeAndViewsState.mOperationBlocks[
7025 self.mSourceOperationName]
7026 if self.mSourceOperation == None:
7027 myDebugPrint3AndException("PhactoriNearestPointsOperation:" \
7028 "RunCalculationToFindNearestPoints\ncouldn't find source " \
7029 "operation named " + str(self.mSourceOperationName) + "\n")
7030
7031
7032 #get the list of points from the target that reside on this process
7033 nodeIds, pointXyzs = self.mTargetOperation.MakeListOfAllPoints1()
7034
7035 if PhactoriDbg(100):
7036 myDebugPrint3("In this process " + str(SmartGetLocalProcessId()) + \
7037 " the target has " + str(nodeIds.GetNumberOfValues()) + " points\n")
7038 #myDebugPrint3("nodeIds in " + self.mName + \
7039 # " (count " + str(len(nodeIds)) + "):\n" + str(nodeIds) + "\n")
7040 #for jj in range(0, nodeIds.GetNumberOfValues()):
7041 # myDebugPrint3(str(jj) + ": " + str(nodeIds.GetValue(jj)) + "\n")
7042 #myDebugPrint3("points in " + self.mName + ":\n" + str(pointXyzs) + "\n")
7043
7044 #get the list of points from the target on all processes (copied to this process)
7045 allProcTgtNodeIds, allProcTgtXyzs = \
7046 UseMPIToCreateSharedPointList(nodeIds, pointXyzs)
7047
7048 if PhactoriDbg(100):
7049 myDebugPrint3("from all processes the target has " + \
7050 str(allProcTgtNodeIds.GetNumberOfValues()) + " points\n")
7051
7052 #get nearest N points from the source points on this process to all the
7053 #points on the target (which we have from all processes)
7054 nearestset = self.mSourceOperation.FindClosestNPointsToList(
7055 allProcTgtNodeIds, allProcTgtXyzs, self.mNumPointsPerProcess)
7056
7057 if PhactoriDbg(100):
7058 myDebugPrint3("nearest points from local process source points to " \
7059 "all target points:\n")
7060 myDebugPrint3(nearestset.ToStr())
7061
7062 if self.mClosestNPointsFromEachProcess == None:
7063 self.mClosestNPointsFromEachProcess = ClosestNPointsFromEachProcess()
7064
7065 #now share those N points from each process to all processes so for this and
7066 #every other process we have a list of N * numprocesses points which
7067 #represent the closestst N points from each process to the target
7068 self.mClosestNPointsFromEachProcess.\
7069 ParallelSetupFromFindClosestNPointsToList(nearestset)
7070
7071 #now find the closest M points out of that list
7072 self.mClosestNPointsFromEachProcess.FindNClosestPointsNdxInList(
7073 self.mNumPointsToFind)
7074
7075 if PhactoriDbg(100):
7076 myDebugPrint3( self.mClosestNPointsFromEachProcess.\
7077 MakeNClosestPointsNdxInListTableString())
7078
7079 ndx = self.mClosestNPointsFromEachProcess.mClosestNRefs[0][1]
7080 srcndid = self.mClosestNPointsFromEachProcess.mThisProcIds.GetValue(ndx)
7081 tgtndid = self.mClosestNPointsFromEachProcess.mTargetMatchIds.GetValue(ndx)
7082 distsqrd = self.mClosestNPointsFromEachProcess.mDistSqrds.GetValue(ndx)
7083 dist = math.sqrt(distsqrd)
7084 pndx = ndx*3
7085 srcx = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx)
7086 srcy = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx+1)
7087 srcz = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx+2)
7088 tgtx = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx)
7089 tgty = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx+1)
7090 tgtz = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx+2)
7091
7092 self.mLineSource.Point1 = [srcx, srcy, srcz]
7093 self.mLineSource.Point2 = [tgtx, tgty, tgtz]
7094 self.mLineSource.UpdatePipeline()
7095
7096 self.WriteClosestNPointsToCsvFile(ioPipeAndViewsState)
7097 self.OutputToTextAnnotation(ioPipeAndViewsState)
7098
7099 def OutputToTextAnnotation(self, ioPipeAndViewsState):
7100 if PhactoriDbg():
7101 myDebugPrint3("PhactoriNearestPointsOperation::OutputToTextAnnotation" \
7102 " called\n")
7103 if self.mOutputToTextAnnotationName == None:
7104 return
7105
7106 if self.mTextAnnotationOutputTarget == None:
7107 self.mTextAnnotationOutputTarget = \
7108 ioPipeAndViewsState.mTextAnnotationBlocks[ \
7109 self.mOutputToTextAnnotationName]
7110 if self.mTextAnnotationOutputTarget == None:
7111 if PhactoriDbg():
7112 myDebugPrint3(
7113 "PhactoriNearestPointsOperation::OutputToTextAnnotation\n" \
7114 "could not find PhactoriTextAnnotationBlock named:\n" \
7115 + str(self.mOutputToTextAnnotationName) + "\n")
7116 return
7117
7118 if PhactoriDbg():
7119 myDebugPrint3("found annotation " + \
7120 str(self.mOutputToTextAnnotationName) + "\n")
7121 clstpts = self.mClosestNPointsFromEachProcess
7122 ndx = clstpts.mClosestNRefs[0][1]
7123 srcndid = clstpts.mThisProcIds.GetValue(ndx)
7124 tgtndid = clstpts.mTargetMatchIds.GetValue(ndx)
7125 distsqrd = clstpts.mDistSqrds.GetValue(ndx)
7126 dist = math.sqrt(distsqrd)
7127 pndx = ndx*3
7128 srcx = clstpts.mThisProcXyzs.GetValue(pndx)
7129 srcy = clstpts.mThisProcXyzs.GetValue(pndx+1)
7130 srcz = clstpts.mThisProcXyzs.GetValue(pndx+2)
7131 tgtx = clstpts.mTargetMatchXyzs.GetValue(pndx)
7132 tgty = clstpts.mTargetMatchXyzs.GetValue(pndx+1)
7133 tgtz = clstpts.mTargetMatchXyzs.GetValue(pndx+2)
7134
7135 if self.mTxtAntnFormatString == None:
7136 self.mTextAnnotationOutputTarget.mTextString = \
7137 "nearest: " + str(dist) + "\n" \
7138 "node id 1: " + str(srcndid) + "\n" \
7139 "x1: " + str(srcx) + "\n" \
7140 "y1: " + str(srcy) + "\n" \
7141 "z1: " + str(srcz) + "\n" \
7142 "node id 2: " + str(tgtndid) + "\n" \
7143 "x2: " + str(tgtx) + "\n" \
7144 "y2: " + str(tgty) + "\n" \
7145 "z2: " + str(tgtz)
7146 else:
7147 diststr = self.mTxtAntnFormatString%dist
7148 id1str = str(srcndid)
7149 x1str = self.mTxtAntnFormatString%srcx
7150 y1str = self.mTxtAntnFormatString%srcy
7151 z1str = self.mTxtAntnFormatString%srcz
7152 id2str = str(tgtndid)
7153 x2str = self.mTxtAntnFormatString%tgtx
7154 y2str = self.mTxtAntnFormatString%tgty
7155 z2str = self.mTxtAntnFormatString%tgtz
7156 self.mTextAnnotationOutputTarget.mTextString = \
7157 "nearest: " + diststr + "\n" \
7158 "node id 1: " + id1str + "\n" \
7159 "x1: " + x1str + "\n" \
7160 "y1: " + y1str + "\n" \
7161 "z1: " + z1str + "\n" \
7162 "node id 2: " + id2str + "\n" \
7163 "x2: " + x2str + "\n" \
7164 "y2: " + y2str + "\n" \
7165 "z2: " + z2str
7166
7167 self.mTextAnnotationOutputTarget.mParaViewSource.Text = \
7168 self.mTextAnnotationOutputTarget.mTextString
7169 self.mTextAnnotationOutputTarget.mParaViewSource.UpdatePipeline()
7170
7171 def WriteClosestNPointsToCsvFile(self, ioPipeAndViewsState):
7172 if SmartGetLocalProcessId() != 0:
7173 return
7174 if self.mWriteCsvResults == False:
7175 return
7176
7177 if PhactoriDbg():
7178 myDebugPrint3("WriteClosestNPointsToCsvFile entered and writing\n")
7179
7180 if self.mCsvFileBasedirectory == None:
7181 ffname = self.mCsvFileName
7182 elif self.mCsvFileBasedirectory == "":
7183 ffname = self.mCsvFileName
7184 else:
7185 import os
7186 ffname = self.mCsvFileBasedirectory + os.sep + self.mCsvFileName
7187 try:
7188 cvsff = open(ffname, "a+b")
7189 if self.mCalculationFrameTag == 1:
7190 cvsff.write("call index, simulation time, position, " \
7191 "distance, distance squared, " \
7192 "source node id, source x, source y, source z, " \
7193 "target node id, target x, target y, target z\n")
7194 clstpts = self.mClosestNPointsFromEachProcess
7195 try:
7196 simtime = ioPipeAndViewsState.CurrentDatadescription.GetTime()
7197 except:
7198 simtime = 0.0
7199 for ii in range(self.mNumPointsToFind):
7200 if PhactoriDbg():
7201 myDebugPrint3("doing point\n" + str(ii) + "\n")
7202 ndx = clstpts.mClosestNRefs[ii][1]
7203 srcndid = clstpts.mThisProcIds.GetValue(ndx)
7204 tgtndid = clstpts.mTargetMatchIds.GetValue(ndx)
7205 distsqrd = clstpts.mDistSqrds.GetValue(ndx)
7206 dist = math.sqrt(distsqrd)
7207 pndx = ndx*3
7208 srcx = clstpts.mThisProcXyzs.GetValue(pndx)
7209 srcy = clstpts.mThisProcXyzs.GetValue(pndx+1)
7210 srcz = clstpts.mThisProcXyzs.GetValue(pndx+2)
7211 tgtx = clstpts.mTargetMatchXyzs.GetValue(pndx)
7212 tgty = clstpts.mTargetMatchXyzs.GetValue(pndx+1)
7213 tgtz = clstpts.mTargetMatchXyzs.GetValue(pndx+2)
7214 if self.mCsvFormatString == None:
7215 cvsff.write(
7216 str(self.mCalculationFrameTag) + ", " + \
7217 str(simtime) + ", " + \
7218 str(ii) + ", " + \
7219 str(dist) + ", " + \
7220 str(distsqrd) + ", " + \
7221 str(srcndid) + ", " + \
7222 str(srcx) + ", " + \
7223 str(srcy) + ", " + \
7224 str(srcz) + ", " + \
7225 str(tgtndid) + ", " + \
7226 str(tgtx) + ", " + \
7227 str(tgty) + ", " + \
7228 str(tgtz) + "\n"
7229 )
7230 else:
7231 tagstr = str(self.mCalculationFrameTag)
7232 simtimestr = self.mCsvFormatString%simtime
7233 posstr = str(ii)
7234 diststr = self.mCsvFormatString%dist
7235 distsqrdstr = self.mCsvFormatString%distsqrd
7236 id1str = str(srcndid)
7237 x1str = self.mCsvFormatString%srcx
7238 y1str = self.mCsvFormatString%srcy
7239 z1str = self.mCsvFormatString%srcz
7240 id2str = str(tgtndid)
7241 x2str = self.mCsvFormatString%tgtx
7242 y2str = self.mCsvFormatString%tgty
7243 z2str = self.mCsvFormatString%tgtz
7244 cvsff.write(
7245 tagstr + ", " + \
7246 simtimestr + ", " + \
7247 posstr + ", " + \
7248 diststr + ", " + \
7249 distsqrdstr + ", " + \
7250 id1str + ", " + \
7251 x1str + ", " + \
7252 y1str + ", " + \
7253 z1str + ", " + \
7254 id2str + ", " + \
7255 x2str + ", " + \
7256 y2str + ", " + \
7257 z2str + "\n"
7258 )
7259 cvsff.close()
7260 except:
7261 myDebugPrint3AndException(
7262 "PhactoriNearestPointsOperation::" \
7263 "RunCalculationToFindNearestPoints\n" \
7264 "error opening or writing to .csv file:\n" \
7265 + str(ffname) + "\n")
7266
7267 if PhactoriDbg():
7268 myDebugPrint3("WriteClosestNPointsToCsvFile returning\n")
7269
7270 #phactori_combine_to_single_python_file_parent_1
7271 from Operation.PhactoriGroupOperation import *
7272
7273 #phactori_combine_to_single_python_file_parent_1
7274 from Operation.PhactoriGenerateSurfaceNormalsOperation import *
7275
7276
7277 #phactori_combine_to_single_python_file_parent_1
7278 from Operation.PhactoriExtractSurfaceOperation import *
7279
7280
7281 #phactori_combine_to_single_python_file_parent_1
7282 from Operation.PhactoriGhostCellsGeneratorOperation import *
7283
7284
7285 #phactori_combine_to_single_python_file_parent_1
7286 from Operation.PhactoriMergeBlocksOperation import *
7287
7288
7289 #phactori_combine_to_single_python_file_parent_1
7290 from Operation.PhactoriSubdivideOperation import *
7291
7292
7293 #phactori_combine_to_single_python_file_parent_1
7294 from Operation.PhactoriAggregateDatasetOperation import *
7295
7296 #phactori_combine_to_single_python_file_parent_1
7297 from Operation.PhactoriCreateSegmentsNormalToCells import *
7298
7299 #phactori_combine_to_single_python_file_parent_1
7300 from Operation.PhactoriVectorProject import *
7301
7302 #phactori_combine_to_single_python_file_parent_1
7303 from Operation.PhactoriGlyphOperation import *
7304
7305 #phactori_combine_to_single_python_file_parent_1
7306 from Operation.PhactoriTriangulateOperation import *
7307
7308
7309 #phactori_combine_to_single_python_file_parent_1
7310 from Operation.PhactoriExtractBlockOperation import *
7311
7312 #phactori_combine_to_single_python_file_parent_1
7313 from Operation.PhactoriCellDataToPointDataOperation import *
7314
7315 #phactori_combine_to_single_python_file_parent_1
7316 from Operation.PhactoriExtractComponentOperation import *
7317
7318 #phactori_combine_to_single_python_file_parent_1
7319 from Operation.PhactoriCellSizeOperation import *
7320
7321 #phactori_combine_to_single_python_file_parent_1
7322 from Operation.PhactoriAppendLocationAttributesOperation import *
7323
7324 #phactori_combine_to_single_python_file_parent_1
7325 from Operation.PhactoriIntegrateVariablesOperation import *
7326
7327 #phactori_combine_to_single_python_file_parent_1
7328 from Operation.PhactoriContourOperation import *
7329
7330
7331 class PhactoriPlaneOpBase(PhactoriOperationSpecifics):
7332 """base operation type for slice operation and clip operation. They share
7333 parsing and settings, and just differ by which filter is created"""
7334 def __init__(self):
7335 PhactoriOperationSpecifics.__init__(self)
7336 self.mPtOnPlaneInfo = PhactoriUserPointInfo()
7337 self.mPlaneNormal = [0.0, 1.0, 0.0]
7338 self.mUseThreePointsOnPlane = False
7339 self.mPtOnPlaneInfoA = None
7340 self.mPtOnPlaneInfoB = None
7341 self.mPtOnPlaneInfoC = None
7342 self.mCrinkleSetting = None
7343 if gParaViewCatalystVersionFlag < 50502:
7344 self.mInsideOut = 1
7345 else:
7346 self.mInvert = 1
7347
7348 def ParseParametersFromJson(self, inJson):
7349 if PhactoriDbg(100):
7350 myDebugPrint3("PhactoriPlaneOpBase.ParseParametersFromJson entered\n", 100)
7351
7352 if "plane specification" in inJson:
7353 if inJson["plane specification"] == "point and normal":
7354 self.mUseThreePointsOnPlane = False
7355 elif inJson["plane specification"] == "three points":
7356 self.mUseThreePointsOnPlane = True
7357 else:
7358 myDebugPrint3AndException(
7359 "PhactoriPlaneOpBase.ParseParametersFromJson:\n"
7360 "'plane specification' must be 'point and normal' or "
7361 "'three points'\n")
7362
7363 if self.mUseThreePointsOnPlane:
7364 if PhactoriDbg():
7365 myDebugPrint3("using three points on plane instead of plane/normal:\n")
7366 self.mPtOnPlaneInfoA = PhactoriUserPointInfo()
7367 self.mPtOnPlaneInfoA.mXyz = [0.0, 0.0, 0.0]
7368 self.mPtOnPlaneInfoB = PhactoriUserPointInfo()
7369 self.mPtOnPlaneInfoB.mXyz = [0.0, 1.0, 0.0]
7370 self.mPtOnPlaneInfoC = PhactoriUserPointInfo()
7371 self.mPtOnPlaneInfoC.mXyz = [0.0, 0.0, 1.0]
7372 self.mPtOnPlaneInfoA.UserPointInfoParseParametersFromJson(
7373 inJson, "", " on plane A")
7374 self.mPtOnPlaneInfoB.UserPointInfoParseParametersFromJson(
7375 inJson, "", " on plane B")
7376 self.mPtOnPlaneInfoC.UserPointInfoParseParametersFromJson(
7377 inJson, "", " on plane C")
7378 else:
7379 if PhactoriDbg():
7380 myDebugPrint3(
7381 "using point/normal: PhactoriPlaneOpBase parsing point onplane:\n")
7382 self.mPtOnPlaneInfo.UserPointInfoParseParametersFromJson(
7383 inJson, "", " on plane")
7384
7385 if 'plane normal' in inJson:
7386 self.mPlaneNormal = inJson['plane normal']
7387 self.mPlaneNormal = vecNormalize(self.mPlaneNormal)
7388 else:
7389 self.mPlaneNormal = [0.0, 1.0, 0.0]
7390
7391 if gParaViewCatalystVersionFlag < 50502:
7392 if 'side to keep' in inJson:
7393 whichSide = inJson['side to keep']
7394 if whichSide == 'positive':
7395 self.mInsideOut = 0
7396 elif whichSide == 'negative':
7397 self.mInsideOut = 1
7398 else:
7399 if PhactoriDbg():
7400 myDebugPrint3('ParseParametersFromJson warning: side to keep \
7401 should be positive or negative, but is not, using positive\n')
7402 else:
7403 self.mInsideOut = 0
7404 else:
7405 if 'side to keep' in inJson:
7406 whichSide = inJson['side to keep']
7407 if whichSide == 'positive':
7408 self.mInvert = 0
7409 elif whichSide == 'negative':
7410 self.mInvert = 1
7411 else:
7412 if PhactoriDbg():
7413 myDebugPrint3('ParseParametersFromJson warning: side to keep \
7414 should be positive or negative, but is not, using positive\n')
7415 else:
7416 self.mInvert = 0
7417
7418 if 'cut type' in inJson:
7419 cutType = inJson['cut type']
7420 self.mCrinkleSetting = 0
7421 if cutType == 'smooth':
7422 self.mCrinkleSetting = 0
7423 elif cutType == 'crinkle':
7424 self.mCrinkleSetting = 1
7425 else:
7426 if PhactoriDbg():
7427 myDebugPrint3('ParseParametersFromJson warning: cut type \
7428 should be smooth or crinkle, but is not, using smooth\n')
7429 self.mCrinkleSetting = 0
7430 else:
7431 self.mCrinkleSetting = 0 #debatable default
7432
7433 def CreateParaViewFilter(self, inInputFilter):
7434 errStr = """error! this is a base class which should have
7435 CreateParaViewFilter method overridden and not
7436 used"""
7437 if PhactoriDbg():
7438 myDebugPrint3(errStr)
7439 raise Exception(errStr)
7440
7441 def CalculateUpdatedOriginAndNormal(
7442 self, inIncomingPvFilter, outCalculatedOrigin, outCalculatedNormal):
7443 """find a point on the plane and a normal to the plane, allowing for
7444 need to update location of points due to the point or points on the
7445 plane being relative points or data points"""
7446
7447 if PhactoriDbg():
7448 myDebugPrint3(
7449 "PhactoriPlaneOpBase::CalculateUpdatedOriginAndNormal entered\n")
7450
7451 viewBoundsArray = [None]
7452 if self.mUseThreePointsOnPlane:
7453 #defining plane by three points on plane
7454 originToUse = \
7455 self.mPtOnPlaneInfoA.GetCurrentGeometricPointWithDisplacement(
7456 inIncomingPvFilter, viewBoundsArray, True)
7457 outCalculatedOrigin[0] = originToUse[0]
7458 outCalculatedOrigin[1] = originToUse[1]
7459 outCalculatedOrigin[2] = originToUse[2]
7460 if PhactoriDbg():
7461 myDebugPrint3(' calculating normal from 3 points\n')
7462 tempPtB = self.mPtOnPlaneInfoB.GetCurrentGeometricPointWithDisplacement(
7463 inIncomingPvFilter, viewBoundsArray, False)
7464 tempPtC = self.mPtOnPlaneInfoC.GetCurrentGeometricPointWithDisplacement(
7465 inIncomingPvFilter, viewBoundsArray, False)
7466 vecAB = vecFromAToB(outCalculatedOrigin, tempPtB)
7467 vecAC = vecFromAToB(outCalculatedOrigin, tempPtC)
7468 vecCrossProduct2(outCalculatedNormal, vecAB, vecAC)
7469 #if we have 2 collinear points, our cross product will go to zero, and
7470 #we have to pick an arbitrary normal; we should be more selective
7471 #about this test
7472 if vecMagnitudeSquared(outCalculatedNormal,) < 0.000000000000000000001:
7473 if PhactoriDbg():
7474 myDebugPrint3(' two or more points are colinear, using 0,1,0\n')
7475 outCalculatedNormal[0] = 0.0
7476 outCalculatedNormal[1] = 1.0
7477 outCalculatedNormal[2] = 0.0
7478 else:
7479 vecNormalize2(outCalculatedNormal, outCalculatedNormal)
7480 else:
7481 originToUse = self.mPtOnPlaneInfo. \
7482 GetCurrentGeometricPointWithDisplacement(
7483 inIncomingPvFilter, viewBoundsArray, True)
7484 outCalculatedOrigin[0] = originToUse[0]
7485 outCalculatedOrigin[1] = originToUse[1]
7486 outCalculatedOrigin[2] = originToUse[2]
7487 outCalculatedNormal[0] = self.mPlaneNormal[0]
7488 outCalculatedNormal[1] = self.mPlaneNormal[1]
7489 outCalculatedNormal[2] = self.mPlaneNormal[2]
7490
7491 if PhactoriDbg():
7492 myDebugPrint3(
7493 "PhactoriPlaneOpBase::CalculateUpdatedOriginAndNormal returning\n")
7494
7495
7496 def MayChangeWithData(self):
7497 if self.mUseThreePointsOnPlane:
7498 return (self.mPtOnPlaneInfoA.mMayChangeWithData or \
7499 self.mPtOnPlaneInfoB.mMayChangeWithData or \
7500 self.mPtOnPlaneInfoC.mMayChangeWithData)
7501 else:
7502 return self.mPtOnPlaneInfo.mMayChangeWithData
7503
7504 #phactori_combine_to_single_python_file_parent_1
7505 from Operation.PhactoriSliceOperation import *
7506
7507 #phactori_combine_to_single_python_file_parent_1
7508 from Operation.PhactoriSliceWithPlaneOperation import *
7509
7510 #phactori_combine_to_single_python_file_parent_1
7511 from Operation.PhactoriClipPlaneOperation import *
7512
7513 #phactori_combine_to_single_python_file_parent_1
7514 from Operation.PhactoriCylinderClipOperation import *
7515
7516 #phactori_combine_to_single_python_file_parent_1
7517 from Operation.PhactoriBoxClipOperation import *
7518
7519 #phactori_combine_to_single_python_file_parent_1
7520 from Operation.PhactoriStreamTracerOperation import *
7521
7522 #phactori_combine_to_single_python_file_parent_1
7523 from Operation.PhactoriStreamTracerSeedSourceOperation import *
7524
7525 #phactori_combine_to_single_python_file_parent_1
7526 from Operation.PhactoriResampleWithDataset import *
7527
7528 #phactori_combine_to_single_python_file_parent_1
7529 from Operation.PhactoriPointSourceFromJsonList import *
7530
7531 #phactori_combine_to_single_python_file_parent_1
7532 from Operation.PhactoriPointSource import *
7533
7534 #phactori_combine_to_single_python_file_parent_1
7535 from Operation.PhactoriPlaneSource import *
7536
7537 #phactori_combine_to_single_python_file_parent_1
7538 from Operation.PhactoriPointSourceNearbyCorrelator import *
7539
7540 #phactori_combine_to_single_python_file_parent_1
7541 from Operation.PhactoriSampledCellInfo import *
7542
7543 #phactori_combine_to_single_python_file_parent_1
7544 from Operation.PhactoriPointSourceGeometrySampler1 import *
7545
7546 #phactori_combine_to_single_python_file_parent_1
7547 from Operation.PhactoriSegmentCellSampler3 import *
7548
7549 #phactori_combine_to_single_python_file_parent_1
7550 from Operation.PhactoriGeometricCellSampler1 import *
7551
7552 #phactori_combine_to_single_python_file_parent_1
7553 from Operation.PhactoriParallelGeometryUtilities import *
7554
7555 #phactori_combine_to_single_python_file_parent_1
7556 from Operation.PhactoriExtractSubsetWithSeed import *
7557
7558 #phactori_combine_to_single_python_file_parent_1
7559 from Operation.PhactoriExtractStructuredMultiBlock import *
7560
7561 class ClosestNPointsFromEachProcess:
7562 """class to manage parallel operations where we obtain a set of N points on
7563 each process and then share those points from each process to all
7564 process. used for doing things like finding closest N points from one
7565 operation to another on each process and then sharing and sorting and
7566 finding closest overall"""
7567
7568 def __init__(self):
7569 self.mPointsPerProcess = None
7570 self.mMyPid = -1
7571 self.mNumProcesses = -1
7572 self.mClosestNRefs = None
7573
7574 #closest N local points (local id and id from list and geometry xyzs
7575 #from local and from list and distance squared
7576 self.mThisProcIds = vtk.vtkIntArray()
7577 self.mTargetMatchIds = vtk.vtkIntArray()
7578 self.mThisProcXyzs = vtk.vtkDoubleArray()
7579 self.mTargetMatchXyzs = vtk.vtkDoubleArray()
7580 self.mDistSqrds = vtk.vtkDoubleArray()
7581
7582 def ParallelSetupFromFindClosestNPointsToList(self, inMyProcData):
7583 self.mPointsPerProcess = inMyProcData.mNumToFind
7584 mypid, numproc = UseMPIToFillInSharedListNPerProcess(
7585 inMyProcData.mThisProcIds, self.mPointsPerProcess, self.mThisProcIds, 0)
7586 UseMPIToFillInSharedListNPerProcess(
7587 inMyProcData.mTargetMatchIds, self.mPointsPerProcess, self.mTargetMatchIds, 0)
7588 UseMPIToFillInSharedListNPerProcess(
7589 inMyProcData.mDistSqrds, self.mPointsPerProcess, self.mDistSqrds, 1)
7590 UseMPIToFillInSharedListNPerProcess(
7591 inMyProcData.mThisProcXyzs, self.mPointsPerProcess * 3, self.mThisProcXyzs, 1)
7592 UseMPIToFillInSharedListNPerProcess(
7593 inMyProcData.mTargetMatchXyzs, self.mPointsPerProcess * 3, self.mTargetMatchXyzs, 1)
7594
7595 self.mMyPid = mypid
7596 self.mNumProcesses = numproc
7597
7598 def FindNClosestPointsNdxInList(self, inHowMany):
7599 import heapq
7600
7601 numPoints = self.mPointsPerProcess * self.mNumProcesses
7602 if PhactoriDbg():
7603 myDebugPrint3(str(inHowMany) + " " + str(numPoints) + "\n")
7604 if numPoints < inHowMany:
7605 exit(-1)
7606 topNHeap = []
7607 for ii in range(0, inHowMany):
7608 heapq.heappush(topNHeap, (-self.mDistSqrds.GetValue(ii), ii))
7609 for ii in range(inHowMany, numPoints):
7610 testval = -self.mDistSqrds.GetValue(ii)
7611 if testval > topNHeap[0][0]:
7612 heapq.heappushpop(topNHeap, (testval, ii))
7613
7614 self.mClosestNRefs = []
7615 for ii in range(0, inHowMany):
7616 item = heapq.heappop(topNHeap)
7617 self.mClosestNRefs.append((-item[0], item[1]))
7618
7619 self.mClosestNRefs.reverse()
7620
7621 if PhactoriDbg():
7622 myDebugPrint3("FindNClosestPointsNdxInList:\n" + str(self.mClosestNRefs) + "\n")
7623
7624 def MakeNClosestPointsNdxInListTableString(self, inMakeHeaderLine = True):
7625 if inMakeHeaderLine:
7626 retStr = "index, distance, distance squared, " \
7627 "source node id, source x, source y, source z, " \
7628 "target node id, target x, target y, target z\n"
7629 else:
7630 retStr = ""
7631 for ii in range(0, len(self.mClosestNRefs)):
7632 ndx = self.mClosestNRefs[ii][1]
7633 srcndid = self.mThisProcIds.GetValue(ndx)
7634 tgtndid = self.mTargetMatchIds.GetValue(ndx)
7635 distsqrd = self.mDistSqrds.GetValue(ndx)
7636 dist = math.sqrt(distsqrd)
7637 pndx = ndx*3
7638 srcx = self.mThisProcXyzs.GetValue(pndx)
7639 srcy = self.mThisProcXyzs.GetValue(pndx+1)
7640 srcz = self.mThisProcXyzs.GetValue(pndx+2)
7641 tgtx = self.mTargetMatchXyzs.GetValue(pndx)
7642 tgty = self.mTargetMatchXyzs.GetValue(pndx+1)
7643 tgtz = self.mTargetMatchXyzs.GetValue(pndx+2)
7644 retStr += str(ii) + ", " + \
7645 str(dist) + ", " + \
7646 str(distsqrd) + ", " + \
7647 str(srcndid) + ", " + \
7648 str(srcx) + ", " + \
7649 str(srcy) + ", " + \
7650 str(srcz) + ", " + \
7651 str(tgtndid) + ", " + \
7652 str(tgtx) + ", " + \
7653 str(tgty) + ", " + \
7654 str(tgtz) + "\n"
7655 return retStr
7656
7657 def ToStr(self):
7658 retStr = "parallel shared closest " + str(self.mPointsPerProcess) + " points:\n" + \
7659 "index:process:pndx source id, target id, dist sqrd: source xyz: target xyz\n"
7660 for ii in range(0, self.mPointsPerProcess * self.mNumProcesses):
7661 pp = ii*3
7662 adst = str(ii) + ":" + \
7663 str(ii/self.mPointsPerProcess) + ":" + \
7664 str(ii%self.mPointsPerProcess) + ": " + \
7665 str(self.mThisProcIds.GetValue(ii)) + ", " + \
7666 str(self.mTargetMatchIds.GetValue(ii)) + ", " + \
7667 str(self.mDistSqrds.GetValue(ii)) + ": " + \
7668 str(self.mThisProcXyzs.GetValue(pp)) + ", " + \
7669 str(self.mThisProcXyzs.GetValue(pp+1)) + ", " + \
7670 str(self.mThisProcXyzs.GetValue(pp+2)) + ": " + \
7671 str(self.mTargetMatchXyzs.GetValue(pp)) + ", " + \
7672 str(self.mTargetMatchXyzs.GetValue(pp+1)) + ", " + \
7673 str(self.mTargetMatchXyzs.GetValue(pp+2)) + "\n"
7674 retStr += adst
7675 return retStr
7676
7677 #phactori_combine_to_single_python_file_parent_1
7678 from Operation.QuadInfoGQC import *
7679
7680 #phactori_combine_to_single_python_file_parent_1
7681 from Operation.PhactoriSegment import *
7682
7683 #phactori_combine_to_single_python_file_parent_1
7684 from Operation.PhactoriOperationBlock import *
7685
7686 #phactori_combine_to_single_python_file_parent_1
7687 from Operation.PhactoriFindCellEdgeLengths import *
7688
7689 #phactori_combine_to_single_python_file_parent_1
7690 from Operation.PhactoriCellEdgeAngleMetrics import *
7691
7692 #phactori_combine_to_single_python_file_parent_1
7693 from Operation.PhactoriMarkCellSurfaceStatus2 import *
7694
7695 class PhactoriTextAnnotationBlock(PhactoriOperationSpecifics):
7696 """represents manages one text annotation item (paraview Text source).
7697 The idea is that we print a 2d text item on the window front to give
7698 information to the user. Notionally the text can change depending on
7699 data (e.g. min/max/average values from an operation), but this is not
7700 yet implemented. Imagesets can selectively turn on any desired subset
7701 of existing text annotations. The position of the text annotation
7702 on the window, the color can be set, the font size and family can be
7703 chosen, and the bold/italic/shadow flags can be set"""
7704 def __init__(self):
7705 self.mName = ""
7706 self.mTextString = ""
7707 #not implemented yet self.minputOperationName = ""
7708 #not implemented yet self.minputOperationBlock = None
7709 self.mParaViewSource = None
7710 self.mParaViewRepresentation = None
7711 self.mWindowLocation = None
7712 self.mPosition = None
7713 self.mColor = None
7714 self.mOpacity = None
7715 self.mBoldFlag = None
7716 self.mShadowFlag = None
7717 self.mItalicFlag = None
7718 self.mFontSize = None
7719 self.mFontFamily = None
7720
7721 def UpdateAndMakeVisible(self):
7722 if PhactoriDbg(100):
7723 myDebugPrint3(
7724 "PhactoriTextAnnotationBlock::UpdateAndMakeVisible entered:\n" + \
7725 self.mName + "\n", 100)
7726
7727 if self.mParaViewSource == None:
7728 #this text annotation needs to have its paraview components created
7729 if PhactoriDbg(100):
7730 myDebugPrint3("(paraview items will now be created)\n")
7731 self.CreateParaViewItems()
7732
7733 #here is where we'd get input operation and update text if it
7734 #was data dependent; see PhactoriMarkerBlock:UpdateAndMakeVisible()
7735
7736 #make it visible
7737 self.mParaViewRepresentation.Visibility = 1
7738
7739 if PhactoriDbg(100):
7740 myDebugPrint3(
7741 "PhactoriTextAnnotationBlock::UpdateAndMakeVisible returning:\n" + \
7742 self.mName + "\n", 100)
7743
7744 def MakeInvisible(self):
7745 if PhactoriDbg(100):
7746 myDebugPrint3("making text annotation invisible: " + \
7747 self.mName + "\n", 100)
7748 if self.mParaViewRepresentation != None:
7749 self.mParaViewRepresentation.Visibility = 0
7750 else:
7751 myDebugPrint3("(paraview items not yet created)\n")
7752
7753 def CreateParaViewItems(self):
7754 """creates the paraview text source and representation for this
7755 PhactoriTextAnnotationBlock instance"""
7756 if PhactoriDbg(100):
7757 myDebugPrint3(
7758 "PhactoriTextAnnotationBlock::CreateParaViewItems entered:\n" + \
7759 self.mName + "\n", 100)
7760
7761
7762 savedActiveSource = GetActiveSource()
7763
7764 #UpdatePipelineWithCurrentTimeArgument(inInputFilter)
7765 self.mParaViewSource = Text()
7766 self.mParaViewSource.Text = self.mTextString
7767
7768 self.mParaViewRepresentation = Show()
7769
7770 if self.mWindowLocation != None:
7771 self.mParaViewRepresentation.WindowLocation = self.mWindowLocation
7772 if self.mPosition != None:
7773 self.mParaViewRepresentation.Position = self.mPosition
7774 if self.mFontSize != None:
7775 self.mParaViewRepresentation.FontSize = self.mFontSize
7776 if self.mFontFamily != None:
7777 self.mParaViewRepresentation.FontFamily = self.mFontFamily
7778 if self.mColor != None:
7779 self.mParaViewRepresentation.Color = self.mColor
7780 if self.mOpacity != None:
7781 self.mParaViewRepresentation.Opacity = self.mOpacity
7782 if self.mBoldFlag != None:
7783 self.mParaViewRepresentation.Bold = self.mBoldFlag
7784 if self.mItalicFlag != None:
7785 self.mParaViewRepresentation.Italic = self.mItalicFlag
7786 if self.mShadowFlag != None:
7787 self.mParaViewRepresentation.Shadow = self.mShadowFlag
7788
7789
7790 #SetActiveSource(self.mParaViewSource)
7791 SetActiveSource(savedActiveSource)
7792
7793 if PhactoriDbg(100):
7794 myDebugPrint3(
7795 "PhactoriTextAnnotationBlock::CreateParaViewItems returning:\n" + \
7796 self.mName + "\n", 100)
7797
7798 def SelfToStr(self):
7799 return "PhactoriTextAnnotationBlock:\n" \
7800 "mName: " + self.mName + "\n" \
7801 "mTextString: " + self.mTextString + "\n" \
7802 "self.mWindowLocation: " + str(self.mWindowLocation) + "\n" \
7803 "self.mPosition: " + str(self.mPosition) + "\n" \
7804 "self.mColor: " + str(self.mColor) + "\n" \
7805 "self.mOpacity: " + str(self.mOpacity) + "\n" \
7806 "self.mBoldFlag: " + str(self.mBoldFlag) + "\n" \
7807 "self.mShadowFlag: " + str(self.mShadowFlag) + "\n" \
7808 "self.mItalicFlag: " + str(self.mItalicFlag) + "\n" \
7809 "self.mFontSize: " + str(self.mFontSize) + "\n" \
7810 "self.mFontFamily: " + str(self.mFontFamily) + "\n"
7811 #"mInputOperationName: " + str(self.mInputOperationName) + "\n" \
7812
7813 def ParseTextAnnotationSettingsFromJson(self, inJson):
7814 if PhactoriDbg(100):
7815 myDebugPrint3(
7816 "PhactoriTextAnnotationBlock::ParseTextAnnotationSettingsFromJson " \
7817 "entered\n", 100)
7818
7819 if "line1" in inJson:
7820 self.mTextString = inJson["line1"]
7821 else:
7822 myDebugPrint3AndException(
7823 "PhactoriTextAnnotationBlock::ParseParametersFromJson\n"
7824 "Error: must have 'line1' command\n")
7825
7826 for lineIndex in range(2, 10):
7827 linetoken = "line" + str(lineIndex)
7828 if linetoken not in inJson:
7829 break
7830 self.mTextString += "\n" + inJson[linetoken]
7831
7832 if PhactoriDbg(100):
7833 myDebugPrint3("final text string:\n" + self.mTextString + "\n", 100)
7834
7835 if "windowlocation" in inJson:
7836 self.mWindowLocation = inJson["windowlocation"]
7837
7838 if "position" in inJson:
7839 self.mWindowLocation = "AnyLocation"
7840 self.mPosition = inJson["position"]
7841
7842 if "fontsize" in inJson:
7843 self.mFontSize = int(inJson["fontsize"])
7844
7845 if "fontfamily" in inJson:
7846 self.mFontFamily = inJson["fontfamily"]
7847
7848 if "color" in inJson:
7849 self.mColor = inJson["color"]
7850
7851 if "opacity" in inJson:
7852 self.mOpacity = float(inJson["opacity"])
7853
7854 if "boldflag" in inJson:
7855 self.mBoldFlag = inJson["boldflag"]
7856
7857 if "italicflag" in inJson:
7858 self.mItalicFlag = inJson["italicflag"]
7859
7860 if "shadowflag" in inJson:
7861 self.mShadowFlag = inJson["shadowflag"]
7862
7863 if PhactoriDbg(100):
7864 myDebugPrint3("after parsing:\n" + self.SelfToStr())
7865 myDebugPrint3(
7866 "PhactoriTextAnnotationBlock::ParseTextAnnotationSettingsFromJson " \
7867 "returning\n", 100)
7868
7869
7870 class PhactoriMarkerBlock:
7871 """represents and manages one 'marker' item. The idea of a phactori marker
7872 is that we can place a sphere (or maybe cube or other geometric object)
7873 at a specific point in the scene to provide some kind of information to
7874 the user. Markers can be placed at absolute or relative geometric
7875 points, at an element or node, or (perhaps most valuably) at a min or
7876 max of a particular variable (with the min or max determined at the
7877 pipeline point of any selected operation, e.g. filter out block X
7878 and place a marker at the max of Temperature on block X). Imagesets
7879 can selectively turn on any desired subset of existing markers. In
7880 Paraview the markers are simply sphere (or maybe cube) sources.
7881 Additionally, the color of the marker can be set as well as the size
7882 (relative or absolute)"""
7883
7884 def __init__(self):
7885 self.mName = ""
7886 self.mInputOperationName = None
7887 self.mInputOperationBlock = None
7888 self.mShape = "sphere" #we will add others
7889 self.mParaViewSource = None
7890 self.mParaViewRepresentation = None
7891 self.mLocationPoint = PhactoriUserPointInfo()
7892 self.mSizeType = "absolute" #"or datasize relative", not handled yet
7893 self.mSize = [0.5, 0.5, 0.5]
7894 self.mOrientation = [0.0, 0.0, 0.0]
7895 self.mColor = [0.0, 1.0, 0.0]
7896 self.mResolution = 16
7897
7898 def UpdateAndMakeVisible(self):
7899 if PhactoriDbg(100):
7900 myDebugPrint3("PhactoriMarkerBlock::UpdateAndMakeVisible entered: " + \
7901 self.mName + "\n", 100)
7902
7903 if self.mParaViewSource == None:
7904 #this marker needs to have its paraview components created
7905 if PhactoriDbg(100):
7906 myDebugPrint3("(paraview items will now be created)\n")
7907 self.CreateParaViewItems()
7908
7909 #get the current location of the point (which may change for a point
7910 #at a variable min/max or a relative point)
7911 global gPipeAndViewsState
7912 myViewBounds = None
7913 viewBoundsIo = [myViewBounds]
7914
7915 if self.mInputOperationBlock == None:
7916 if self.mInputOperationName == None:
7917 self.mInputOperationBlock = \
7918 gPipeAndViewsState.mIncomingDefaultOperation
7919 if PhactoriDbg(100):
7920 myDebugPrint3("first calc, using default incoming operation\n")
7921 else:
7922 self.mInputOperationBlock = gPipeAndViewsState.mOperationBlocks[
7923 self.mInputOperationName]
7924 if self.mInputOperationBlock == None:
7925 myDebugPrint3AndException(
7926 "PhactoriMarkerBlock::UpdateAndMakeVisible:\n"
7927 "couldn't find input operation with name: " + \
7928 str(self.mInputOperationName) + "\n")
7929 if PhactoriDbg(100):
7930 myDebugPrint3("first calc, using operation named: " + \
7931 self.mInputOperationName + "\n")
7932
7933 checkPvFilter = self.mInputOperationBlock.GetPvFilter()
7934
7935 updatedMarkerLocation = self.mLocationPoint.\
7936 GetCurrentGeometricPointWithDisplacement(checkPvFilter,
7937 viewBoundsIo, True)
7938
7939 #update the paraview component to reflect the current marker location
7940 #self.mParaViewSource.Center = updatedMarkerLocation
7941 self.mParaViewRepresentation.Position = updatedMarkerLocation
7942 if PhactoriDbg(100):
7943 #myDebugPrint3("updatedMarkerLocation: " + \
7944 # str(self.mParaViewSource.Center)+ "\n", 100)
7945 myDebugPrint3("updatedMarkerLocation: " + \
7946 str(self.mParaViewRepresentation.Position)+ "\n", 100)
7947
7948 #make it visible
7949 self.mParaViewRepresentation.Visibility = 1
7950
7951 if PhactoriDbg(100):
7952 myDebugPrint3("PhactoriMarkerBlock::UpdateAndMakeVisible returning: " + \
7953 self.mName + "\n", 100)
7954
7955 def MakeInvisible(self):
7956 if PhactoriDbg(100):
7957 myDebugPrint3("making marker invisible: " + self.mName + "\n", 100)
7958 if self.mParaViewRepresentation != None:
7959 self.mParaViewRepresentation.Visibility = 0
7960 else:
7961 if PhactoriDbg(100):
7962 myDebugPrint3("(paraview items not yet created\n")
7963
7964 def CreateParaViewItems(self):
7965 """creates the paraview source (e.g box, sphere, cone, arrow) and representation
7966 for the marker"""
7967 if PhactoriDbg(100):
7968 myDebugPrint3("PhactoriMarkerBlock::CreateParaViewItems entered\n", 100)
7969 savedActiveSource = GetActiveSource()
7970 if self.mShape == "sphere":
7971 self.mParaViewSource = Sphere()
7972 #self.mParaViewRepresentation.SelectionPointFieldDataArrayName = 'Normals'
7973 self.mParaViewSource.Radius = 0.5
7974 self.mParaViewSource.ThetaResolution = self.mResolution
7975 self.mParaViewSource.PhiResolution = self.mResolution
7976 elif self.mShape == "box":
7977 self.mParaViewSource = Box()
7978 self.mParaViewRepresentation = Show()
7979 #self.mParaViewSource.ZLength = self.mSize[0]
7980 #self.mParaViewSource.XLength = self.mSize[1]
7981 #self.mParaViewSource.YLength = self.mSize[2]
7982 elif self.mShape == "arrow":
7983 self.mParaViewSource = Arrow()
7984 self.mParaViewSource.Invert = 1
7985 self.mParaViewSource.ShaftResolution = self.mResolution
7986 self.mParaViewSource.TipResolution = self.mResolution
7987 elif self.mShape == "cone":
7988 self.mParaViewSource = Cone()
7989 self.mParaViewSource.Direction = [-1.0, 0.0, 0.0]
7990 self.mParaViewSource.Center = [0.5, 0.0, 0.0]
7991 self.mParaViewSource.Resolution = self.mResolution
7992 self.mParaViewSource.Capping = 1
7993
7994 self.mParaViewRepresentation = Show()
7995
7996 self.mParaViewRepresentation.Position = [0.0, 0.0, 0.0]
7997 self.mParaViewRepresentation.Scale = self.mSize
7998 self.mParaViewRepresentation.Orientation = self.mOrientation
7999
8000 if gParaViewCatalystVersionFlag <= 40100:
8001 self.mParaViewRepresentation.\
8002 AllowSpecularHighlightingWithScalarColoring = 1
8003 self.mParaViewRepresentation.ScaleFactor = 0.1
8004 self.mParaViewRepresentation.EdgeColor = [0.0, 0.0, 0.5000076295109483]
8005 self.mParaViewRepresentation.DiffuseColor = self.mColor
8006
8007 SetActiveSource(savedActiveSource)
8008
8009 if PhactoriDbg(100):
8010 myDebugPrint3("PhactoriMarkerBlock::CreateParaViewItems returning\n", 100)
8011
8012
8013 def SelfToStr(self):
8014 return "marker:\n" \
8015 "mName: " + self.mName + "\n" \
8016 "mInputOperationName: " + str(self.mInputOperationName) + "\n" \
8017 "mShape: " + self.mShape + "\n" \
8018 "mSizeType: " + self.mSizeType + "\n" \
8019 "mSize: " + str(self.mSize) + "\n" \
8020 "mOrientation: " + str(self.mOrientation) + "\n" \
8021 "mColor: " + str(self.mColor) + "\n" \
8022 "mResolution: " + str(self.mResolution) + "\n" \
8023 "mLocationPoint:\n" + self.mLocationPoint.SelfToStr()
8024
8025 def ParseMarkerSettingsFromJson(self, inJsn):
8026 if PhactoriDbg(100):
8027 myDebugPrint3(
8028 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson entered\n", 100)
8029
8030 if 'input' in inJsn:
8031 self.mInputOperationName = inJsn['input']
8032 else:
8033 noticeStr = \
8034 'notice! inJsn has no input key, using default pipeline input\n'
8035 self.mInputOperationName = None
8036 if PhactoriDbg():
8037 myDebugPrint3(noticeStr)
8038
8039 if "color" in inJsn:
8040 self.mColor = inJsn["color"]
8041 if len(self.mColor) != 3:
8042 myDebugPrint3AndException(
8043 "'color' item was not three element list")
8044 if "relative size" in inJsn:
8045 myDebugPrint3AndException(
8046 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
8047 "'relative size' not yet implemented")
8048 if "absolute size" in inJsn:
8049 self.mSize = inJsn["absolute size"]
8050 if "orientation" in inJsn:
8051 self.mOrientation= inJsn["orientation"]
8052 if "resolution" in inJsn:
8053 self.mResolution = inJsn["resolution"]
8054 if "shape" in inJsn:
8055 self.mShape = inJsn["shape"]
8056 if self.mShape == "sphere":
8057 if PhactoriDbg(100):
8058 myDebugPrint3("shape is sphere\n", 100)
8059 elif self.mShape == "box":
8060 if PhactoriDbg(100):
8061 myDebugPrint3("shape is box\n", 100)
8062 elif self.mShape == "cone":
8063 if PhactoriDbg(100):
8064 myDebugPrint3("shape is cone\n", 100)
8065 elif self.mShape == "arrow":
8066 if PhactoriDbg(100):
8067 myDebugPrint3("shape is arrow\n", 100)
8068 else:
8069 myDebugPrint3AndException(
8070 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
8071 "'shape' must be 'sphere' or 'box' or 'cone' or 'arrow'\n"
8072 "got: " + str(self.mShape) + "\n")
8073
8074 #get point location for marker settings, e.g. marker at max variable point
8075 self.mLocationPoint.UserPointInfoParseParametersFromJson(inJsn,
8076 "marker at ", "")
8077
8078 if self.mLocationPoint.mParsingDetectedAtLeastOneSetting == False:
8079 myDebugPrint3AndException(
8080 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
8081 "must have 'marker at ... point' parameters")
8082
8083 if PhactoriDbg(100):
8084 myDebugPrint3(self.SelfToStr())
8085 myDebugPrint3(
8086 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson returning\n", 100)
8087
8088
8089
8090 #class ParaViewRenderInfoC:
8091 # def __init__(self):
8092 # self.mParaViewInfo = None
8093 # self.mLookDirection = None
8094
8095 class PhactoriAnnotationPv:
8096 '''class manages the ParaView stuff for annotation. The settings are
8097 managed in PhactoriAnnotationViewSettings, and instances of this
8098 class are used in PhactoriImageset to manage the actual paraview
8099 objects, which might be different from image set to image set,
8100 while still using the same PhactoriAnnotationViewSettings'''
8101 def __init__(self, inSettings):
8102 #paraview stuff not created yet
8103 self.mParaViewTextAnnotationSource = None
8104 self.mParaViewRepresentation = None
8105 self.mInputOperation = None
8106 self.mSettings = inSettings
8107
8108 def CreateParaViewStuff(self, inColor, inImageset = None):
8109 '''assumes inImageset is valid; creates ParaView source and
8110 representation based on internal parameters'''
8111 if PhactoriDbg():
8112 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff entered\n")
8113 if self.mSettings.mType == 'time':
8114 if inImageset == None:
8115 if PhactoriDbg():
8116 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff\n" + \
8117 "this is a time annotation, and it needs a valid imageset\n" + \
8118 "to work off, and None was supplied\n")
8119 return
8120 self.mInputOperation = inImageset.mOperation
8121
8122 savedActiveSource = GetActiveSource()
8123 inOprtn = self.mInputOperation
8124 if(inOprtn.mParaViewTimeAnnotationSource == None):
8125 SetActiveSource(inOprtn.GetPvFilter())
8126 inOprtn.mParaViewTimeAnnotationSource = AnnotateTime()
8127 #inOprtn.mParaViewTimeAnnotationSource.Format = 'Time: %.20e'
8128 inOprtn.mParaViewTimeAnnotationSource.Format = self.mSettings.mTimeFormatString
8129 else:
8130 SetActiveSource(inOprtn.mParaViewTimeAnnotationSource)
8131 #self.mParaViewAnnotationSource = Text()
8132 self.mParaViewRepresentation = Show()
8133 self.mParaViewRepresentation.Color = inColor
8134 SetActiveSource(savedActiveSource)
8135 else:
8136 self.mParaViewTextAnnotationSource = Text()
8137 self.mParaViewTextAnnotationSource.Text = self.mText
8138 self.mParaViewRepresentation = Show()
8139 self.mParaViewRepresentation.Color = inColor
8140 self.mParaViewRepresentation.FontSize = self.mSettings.mFontSize
8141 self.mParaViewRepresentation.WindowLocation = self.mSettings.mWindowLocation
8142 if PhactoriDbg():
8143 myDebugPrint3("window location: " + str(self.mParaViewRepresentation.WindowLocation) + "\n")
8144 if PhactoriDbg():
8145 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff returning\n")
8146
8147 #global gTestTimeNotation
8148 #gTestTimeNotation = 1
8149
8150 class PhactoriAnnotationViewSettings:
8151 '''class manages settings for how a text or time annotation is to be
8152 show in the window--size, position, alignment, visible/invisible,
8153 etc. An instance is a member of a PhactoriRepresentation. ParaView
8154 stuff which uses these settings is in a different class, which is
8155 associated with ImageSet. Gives access to control annotation
8156 position, size, text, and could be extended to control all the items
8157 controllable in paraview (x,y position, alignment, bold/italic/shadow'''
8158
8159 def __init__(self, inName, inAnnotationType):
8160 if PhactoriDbg():
8161 myDebugPrint3("ViewSettingsPhactoriAnnotation::__init__ entered\n")
8162 self.mName = inName
8163 self.mVisible = False
8164 if inAnnotationType == 'time':
8165 self.mType = 'time'
8166 self.mText = None
8167 self.mTimeFormatString = gDefaultTimeFormatString
8168 else:
8169 self.mType = 'text'
8170 self.mText = 'Text'
8171 self.mSizeScale = 1.0
8172 #self.mFontSize = 18
8173 self.mFontSize = 36
8174 self.mFont = 'Arial'
8175 self.mBold = False
8176 self.mItalic = False
8177 self.mShadow = False
8178 self.mOpacity = 1.0
8179 self.mAlign = 'Center'
8180 global gParaViewCatalystVersionFlag
8181 if gParaViewCatalystVersionFlag < 51000:
8182 self.mWindowLocation = 'UpperLeftCorner'
8183 else:
8184 self.mWindowLocation = 'Upper Left Corner'
8185 if PhactoriDbg():
8186 myDebugPrint3("ViewSettingsPhactoriAnnotation::__init__ returning\n")
8187
8188 def ParseAvsFromJson(self, inJsn):
8189 self.mVisible = getParameterFromBlock(inJsn, 'show time annotation',
8190 self.mVisible)
8191
8192 #global gTestTimeNotation
8193 #if gTestTimeNotation == 0:
8194 # self.mVisible = True
8195 # gTestTimeNotation = 1
8196 #else:
8197 # self.mVisible = False
8198 # gTestTimeNotation = 0
8199
8200 if 'time annotation position' in inJsn:
8201 windowPosSize = inJsn['time annotation position']
8202 winPos = windowPosSize[0]
8203 winSize = windowPosSize[1]
8204 self.SetSizeScale(winSize)
8205 global gParaViewCatalystVersionFlag
8206 if gParaViewCatalystVersionFlag < 51000:
8207 if winPos == 'top left':
8208 self.SetWindowLocation('UpperLeftCorner')
8209 elif winPos == 'top right':
8210 self.SetWindowLocation('UpperRightCorner')
8211 elif winPos == 'top':
8212 self.SetWindowLocation('UpperCenter')
8213 elif winPos == 'bottom left':
8214 self.SetWindowLocation('LowerLeftCorner')
8215 elif winPos == 'bottom right':
8216 self.SetWindowLocation('LowerRightCorner')
8217 elif winPos == 'bottom':
8218 self.SetWindowLocation('LowerCenter')
8219 else:
8220 if PhactoriDbg():
8221 myDebugPrint3("bad time annotation position, using upper left\n")
8222 self.SetWindowLocation('UpperLeftCorner')
8223 else: #gParaViewCatalystVersionFlag >= 51000
8224 if winPos == 'top left':
8225 self.SetWindowLocation('Upper Left Corner')
8226 elif winPos == 'top right':
8227 self.SetWindowLocation('Upper Right Corner')
8228 elif winPos == 'top':
8229 self.SetWindowLocation('Upper Center')
8230 elif winPos == 'bottom left':
8231 self.SetWindowLocation('Lower Left Corner')
8232 elif winPos == 'bottom right':
8233 self.SetWindowLocation('Lower Right Corner')
8234 elif winPos == 'bottom':
8235 self.SetWindowLocation('Lower Center')
8236 else:
8237 if PhactoriDbg():
8238 myDebugPrint3("bad time annotation position, using upper left\n")
8239 self.SetWindowLocation('UpperLeftCorner')
8240
8241 if 'time format string' in inJsn:
8242 self.mTimeFormatString = inJsn['time format string']
8243
8244 def SetText(self, newText):
8245 if self.mType != 'text':
8246 if PhactoriDbg():
8247 myDebugPrint3("ViewSettingsPhactoriAnnotationSource::SetText not text annotation\n")
8248 return
8249 self.mText = newText
8250 self.mParaViewTextAnnotationSource.Text = newText
8251
8252 def SetSizeScale(self, inNewSizeScale):
8253 if inNewSizeScale < 0.001:
8254 if PhactoriDbg():
8255 myDebugPrint3(
8256 "ViewSettingsPhactoriAnnotationSource::SetSizeScale not in [0.001,1000]\n")
8257 if inNewSizeScale > 1000.0:
8258 if PhactoriDbg():
8259 myDebugPrint3(
8260 "ViewSettingsPhactoriAnnotationSource::SetSizeScale not in [0.001,1000]\n")
8261 self.mSizeScale = inNewSizeScale
8262 fontSizeFloat = float(self.mFontSize)
8263 fontSizeFloat *= self.mSizeScale
8264 intSizeFloat = math.floor(fontSizeFloat)
8265 self.mFontSize = int(intSizeFloat)
8266 #self.mParaViewRepresentation.FontSize = self.mFontSize
8267
8268 def SetWindowLocation(self, inNewPosition):
8269 global gParaViewCatalystVersionFlag
8270 if gParaViewCatalystVersionFlag < 51000:
8271 validPositions = ['UpperLeftCorner', 'UpperRightCorner',
8272 'LowerLeftCorner', 'LowerRightCorner',
8273 'UpperCenter', 'LowerCenter']
8274 else:
8275 validPositions = ['Upper Left Corner', 'Upper Right Corner',
8276 'Lower Left Corner', 'Lower Right Corner',
8277 'Upper Center', 'Lower Center']
8278 if inNewPosition in validPositions:
8279 #self.mParaViewRepresentation.WindowLocation = inNewPosition
8280 self.mWindowLocation = inNewPosition
8281 else:
8282 if PhactoriDbg():
8283 myDebugPrint3("ViewSettingsPhactoriAnnotationSource::SetWindowLocation invalid " + \
8284 "position\n")
8285
8286 class PhactoriPolyDataForPlotLine:
8287 """contains time over plot data values and vtk geometry, as well as the
8288 routines to construct and maintain the vtk geometry
8289 """
8290 def __init__(self, inName):
8291 self.m_TableColumn = vtk.vtkDoubleArray()
8292 self.m_TableColumn.SetName(inName)
8293
8294 def GetRestartInfo(self):
8295 """construct, in python map/json format, the information from this
8296 PhactoriPolyDataForPlotLine instance which contains the information
8297 which would be needed to restore the instance to the proper
8298 state after a simulation restart, particularly prior data values.
8299 Return the restart info map/json"""
8300 newJsonItem = {}
8301 numValues = self.m_TableColumn.GetNumberOfValues()
8302 if numValues > 0:
8303 newJsonItem["m_HasAtLeastOnePoint"] = True
8304 else:
8305 newJsonItem["m_HasAtLeastOnePoint"] = False
8306 if self.m_HasAtLeastOnePoint:
8307 #should we not make copy and just return reference?
8308 #we don't need deepcopy because all items are floats/non-objects
8309 valueList = []
8310 for ii in range(0, self.m_TableColumn.GetNumberOfValues()):
8311 valueList.append(self.m_TableColumn.GetValue(ii))
8312 newJsonItem["m_ColumnValues"] = valueList
8313 return newJsonItem
8314
8315 def SetFromRestartInfo(self, inJson):
8316 """given a map (json format), use the info in the map to set this
8317 PhactoriPolyDataForPlotLine instance state--this reads the info
8318 created by out in GetRestartInfo. It should only occur on a restart,
8319 and it fills in the data that had been generated during the
8320 earlier run of the system"""
8321 if "m_HasAtLeastOnePoint"not in inJson:
8322 if PhactoriDbg():
8323 myDebugPrint3("PhactoriPolyDataForPlotLine::SetFromRestartInfo " + \
8324 "m_HasAtLeastOnePoint not in inJson\n")
8325 return
8326
8327 hasAtLeastOnePoint = inJson["m_HasAtLeastOnePoint"]
8328 if hasAtLeastOnePoint == False:
8329 return
8330
8331 inJsonIsGood = True
8332 if "m_ColumnValues" not in inJson:
8333 myDebugPrint("PhactoriPolyDataForPlotLine::SetFromRestartInfo " + \
8334 "m_ColumnValues not in inJson\n")
8335 inJsonIsGood = False
8336 if inJsonIsGood == False:
8337 return
8338
8339 valueList = inJson["m_ColumnValues"]
8340 self.m_ColumnValues = valueList[:]
8341 for vv in valueList:
8342 self.m_TableColumn.InsertNextValue(vv)
8343
8344 def AppendPlotValue(self, inNewValue):
8345 self.m_TableColumn.InsertNextValue(inNewValue)
8346
8347
8348 class PhactoriPlotOverTimeIdLine:
8349 """useful info for tracking a single element over time in a plot line"""
8350 def __init__(self, inIdToPlot):
8351 self.m_Id = inIdToPlot
8352 linename = "Id " + str(inIdToPlot)
8353 self.m_PlotColumn = PhactoriPolyDataForPlotLine(linename)
8354 self.m_FoundOnThisProcessorLastTime = False
8355 self.m_FoundBlockRef = None
8356 self.m_FoundIndex = None
8357
8358 class ImageFileNameCountSettings:
8359 """used to control par of how the image filenames are generated. The default
8360 is to increment a counter each time the results output block is triggered
8361 to call the catalyst stuff and make the count value part of the filename.
8362 We can optionally have a filename section that is based on the date/time,
8363 we can optionally include microseconds, and we can optionally convert the
8364 date/time to an integer which will be monotonically increasing"""
8365 def __init__(self):
8366 self.mUseDateTime = False
8367 self.mUseMicrosecondsWithDateTime = False
8368 self.mConvertDateTimeToInteger = True
8369 self.mUseSimulationTime = False
8370 #self.mSimulationTimeFormat = "simtime_%e"
8371 self.mSimulationTimeFormat = "simtime_%.6e"
8372 self.mUseCallbackCount = True
8373 self.mUseRemeshRestartTag = True
8374
8375 def ParseImageFileNameCountSettings(self, inJson):
8376 self.mUseDateTime = getParameterFromBlock(inJson,
8377 "filename use datetime", self.mUseDateTime)
8378 self.mUseMicrosecondsWithDateTime = getParameterFromBlock(inJson,
8379 "filename datetime microseconds", self.mUseMicrosecondsWithDateTime)
8380 self.mConvertDateTimeToInteger = getParameterFromBlock(inJson,
8381 "filename datetime convert to integer", self.mConvertDateTimeToInteger)
8382 self.mUseSimulationTime = getParameterFromBlock(inJson,
8383 "filename use simulation time", self.mUseSimulationTime)
8384 self.mSimulationTimeFormat = getParameterFromBlock(inJson,
8385 "filename simulation time format", self.mSimulationTimeFormat)
8386 self.mUseCallbackCount = getParameterFromBlock(inJson,
8387 "filename use call count", self.mUseCallbackCount)
8388 self.mUseRemeshRestartTag = getParameterFromBlock(inJson,
8389 "filename use restart or remesh tag", self.mUseRemeshRestartTag)
8390
8391 def GetImageFilename(self, datadescription, inImageSettings,
8392 inOneLookDirectionFilenameAddon, inRepresentationFilenameAddon,
8393 inCameraFilenameAddon):
8394 """given the imageset and the look direction filename addon, figure out the
8395 filename for the image. Due to prior implementation, we return two
8396 values, a temporary name based only on the callback count, and the
8397 entire name we intend to have so that all processes can agree on the
8398 file name when it is generated and then process zero can move the image
8399 filename to it's final correct value. If we return a None as the
8400 second value, this indicates the callback count temporary name is also
8401 the final name so no operating system move needs to happen"""
8402
8403 inImageBasename = inImageSettings.mImageBasename
8404 inImageBasedirectory = inImageSettings.mImageBasedirectory
8405 inNumCounterDigits = inImageSettings.mNumCounterDigits
8406 inImageFormat = inImageSettings.mImageFormat
8407
8408 timestep = datadescription.GetTimeStep()
8409
8410 lastImagesetName = ""
8411
8412 unusedFilenameFound = False
8413 extraCount = 0
8414 import os
8415
8416 while unusedFilenameFound == False:
8417 imageBasename = inImageBasename
8418 imageBasedirectory = inImageBasedirectory
8419 nameSuffix = inRepresentationFilenameAddon + \
8420 inCameraFilenameAddon + inOneLookDirectionFilenameAddon
8421
8422 if imageBasedirectory == None:
8423 fileBaseName = imageBasename + nameSuffix
8424 elif imageBasedirectory == "":
8425 fileBaseName = imageBasename + nameSuffix
8426 else:
8427 import os
8428 fileBaseName = imageBasedirectory + os.sep + imageBasename + \
8429 nameSuffix
8430
8431 fname = fileBaseName
8432
8433 fname += "%t." + inImageFormat
8434
8435 extraString = GetExtraFileString()
8436 if extraString != '':
8437 fname = fname.replace("%t", extraString + "-%t")
8438 timestepString = str(timestep + extraCount)
8439 while len(timestepString) < inNumCounterDigits:
8440 timestepString = "0" + timestepString
8441 myDebugPrint2("image fname: " + fname + "\ndigit count: " + str(inNumCounterDigits) + "\ntimestepString: " + timestepString + "\n")
8442
8443 rplstr1 = None
8444 if self.mUseDateTime:
8445 ttnow = gPipeAndViewsState.mCallbackDateTime
8446 if self.mUseMicrosecondsWithDateTime == False:
8447 ttnow = ttnow.replace(microsecond=0)
8448 rplstr1 = str(ttnow.isoformat('-'))
8449 if self.mConvertDateTimeToInteger:
8450 import re
8451 rplstr1 = re.sub('[-:.]', '', rplstr1)
8452
8453 if self.mUseSimulationTime:
8454 global gSharedRenderView
8455 simtm = gSharedRenderView.ViewTime
8456 simtmstr = self.mSimulationTimeFormat % simtm
8457 if rplstr1 == None:
8458 rplstr1 = simtmstr
8459 else:
8460 rplstr1 = rplstr1 + "_" + simtmstr
8461
8462 if self.mUseCallbackCount:
8463 #if rplstr1 is None, we just fall through and use the default
8464 #behavior; otherwise we need to add to the string
8465 if rplstr1 != None:
8466 rplstr1 = timestepString + "_" + rplstr1
8467
8468 if rplstr1 != None:
8469 fnameRR = fname.replace("%t", rplstr1)
8470 else:
8471 fnameRR = None
8472
8473 fname = fname.replace("%t", timestepString)
8474
8475 myDebugPrint2("fname after replace: ->" + fname + "<-\n")
8476 #if os.path.exists(fname):
8477 if False: #don't do os.path.exists; it's maybe slow
8478 #myDebugPrint2(" filename in use, try to find another\n")
8479 #unusedFilenameFound = False
8480 unusedFilenameFound = True
8481 extraCount += 1
8482 else:
8483 #myDebugPrint2(" filename is not in use, use it\n")
8484 unusedFilenameFound = True
8485
8486 if self.mUseRemeshRestartTag == False:
8487 if fnameRR != None:
8488 import re
8489 #print "removing, e.g. -s0004-"
8490 #print "before:", fnameRR
8491 fnameRR = re.sub('-s[0123456789]*-', '', fnameRR)
8492 #print "after:", fnameRR
8493
8494 return fname, fnameRR
8495
8496
8497 class PhactoriPlot1Base:
8498 def __init__(self):
8499 self.mName = ""
8500 self.m_DataCubeAxesInfo = PhactoriDataCubeAxesInfo()
8501
8502 self.m_PlotType = "PhactoriPlot1Base"
8503 self.mImageSettings = PhactoriImageSettings()
8504 self.mImageSettings.mPixelBorderRatioXY = [0.175 / self.mImageSettings.GetAspectRatio(), 0.175]
8505 self.mInputOperation = None
8506 #self.m_plotColorInfo = PlotColorInfo()
8507 self.mColorSettings = PhactoriColorSettings(inUsePlotDefaultColors = True)
8508
8509 #used to help generate paraview View and Representation
8510 self.mCamera = PhactoriCameraBlock()
8511
8512 #paraview filter created to hold geometric data
8513 self.m_producer = None
8514 self.m_PhactoriRenderViewInfo = None
8515
8516 #reference for paraview RenderView instance which is shared among all
8517 #renderings
8518 self.mSharedPvRenderView2 = None
8519
8520 #reference for paraview DataRepresentation instance for this imageset.
8521 #if the imageset has multiple view directions, they can share the same
8522 #representation
8523 self.mPvDataRepresentation2 = None
8524
8525 #for compatibility with PhactoriImagesetBlock
8526 self.mLookDirectionList = []
8527 self.mLookDirectionFilenameAddon = []
8528 self.mVisibleOps = [None]
8529 self.mVisibleReps = [None]
8530 self.mVisiblePvDataReps = [None]
8531 self.mColorLegendRepRefs = [None]
8532
8533 #used to control if we want to have image names sequentially count by
8534 #callback index, or if we want to use a date/time based count
8535 #(which can use microseconds or not, and can be converted to an integer
8536 #or not)
8537 self.mImageFileNameCountSettings = ImageFileNameCountSettings()
8538
8539 self.mBackground = [0.0, 0.0, 0.0]
8540
8541 def GetInputPhactoriOperation(self):
8542 #mainly for compatibility between plot blocks and imageset blocks, give
8543 #same access to phactori operation coming being visualized
8544 return self.mInputOperation
8545
8546 def WriteImages(self, datadescription):
8547 """write out the .png/.jpg/whatever images associated with this plot
8548 block for the current timestep/state. Must loop through camera angles
8549 and do a write for each one if necessary"""
8550 if PhactoriDbg():
8551 myDebugPrint3("PhactoriPlotBase1::WriteImages entered\n")
8552
8553 if self.mImageSettings.mUsingDefaultGeneratedImageBasename:
8554 if self.m_PlotType == "PhactoriScatterPlotBlock":
8555 oneLookDirectionFilenameAddon = "sctr."
8556 elif self.m_PlotType == "PhactoriPlotOverTimeBlock":
8557 oneLookDirectionFilenameAddon = "plot."
8558 else:
8559 oneLookDirectionFilenameAddon = ""
8560 else:
8561 oneLookDirectionFilenameAddon = ""
8562
8563 fname, fnameRR = self.mImageFileNameCountSettings.GetImageFilename(
8564 datadescription, self.mImageSettings,
8565 oneLookDirectionFilenameAddon,
8566 "", #no representation string for plot
8567 self.mCamera.mFilenameAddon)
8568
8569 #used to do this:
8570 #view.ViewTime = datadescription.GetTime()
8571 #maybe need to do this?
8572 #UpdatePipelineWithCurrentTimeArgument()
8573
8574 #SetUpViewAndRepresentationBeforeWriteImage(oneViewInfo)
8575 self.SetUpViewAndRepresentationBeforeWriteImage()
8576
8577 colorPalette = GetSettingsProxy('ColorPalette')
8578 colorPalette.Background = self.mBackground
8579
8580 #only need to update color range for first look direction, rest
8581 #are same
8582 #if self.mRepresentation.mUseFixedColorRange == False:
8583 # UseDataRangeForColorValues(self.mPvDataRepresentation2,
8584 # self.mRepresentation, self.mOperation)
8585 if PhactoriDbg(150):
8586 myDebugPrint3("writing plot image: " + fname + "\n" +
8587 str(self.mSharedPvRenderView2) + "\n")
8588
8589 self.mSharedPvRenderView2.LeftAxisUseCustomRange = 0
8590 self.mSharedPvRenderView2.BottomAxisUseCustomRange = 0
8591
8592 if self.m_PlotType == "PhactoriPlotOverTimeBlock":
8593 self.mPvDataRepresentation2.AttributeType = "Row Data"
8594 self.mSharedPvRenderView2.LeftAxisTitle = self.m_YAxisVariableInfo.GetXYPlotAxisTitle()
8595 self.mSharedPvRenderView2.BottomAxisTitle = "Time"
8596 self.mSharedPvRenderView2.ChartTitle = ""
8597 self.mSharedPvRenderView2.ShowLegend = 1
8598 else:
8599 self.m_producer.UpdatePipeline()
8600 DataRepresentation1 = self.mPvDataRepresentation2
8601 atrtype = "Point Data"
8602 if self.m_YAxisVariableInfo.mVariableType == 'element':
8603 atrtype = "Cell Data"
8604 DataRepresentation1.AttributeType = "Row Data"
8605 DataRepresentation1.AttributeType = atrtype
8606 self.mSharedPvRenderView2.LeftAxisTitle = self.m_YAxisVariableInfo.GetXYPlotAxisTitle()
8607 self.mSharedPvRenderView2.BottomAxisTitle = self.m_XAxisVariableInfo.GetXYPlotAxisTitle()
8608 #self.mSharedPvRenderView2.ChartTitle = "Scatter Plot at Time ${TIME}"
8609 self.mSharedPvRenderView2.ChartTitle = ""
8610 self.mSharedPvRenderView2.ShowLegend = 0
8611 if PhactoriDbg(150):
8612 myDebugPrint3("B representation made for scatter plot:\n" + str(DataRepresentation1) + "\n")
8613 myDebugPrint3("m_producer for scatter plot:\n" + str(self.m_producer) + "\n")
8614 myDebugPrint3("rep input num points " + str(DataRepresentation1.Input.GetDataInformation().DataInformation.GetNumberOfPoints()) + "\n")
8615 myDebugPrint3("DataRepresentation1.ListProperties() " + str(DataRepresentation1.ListProperties()) + "\n")
8616 myDebugPrint3("DataRepresentation1.Input " + str(DataRepresentation1.Input) + "\n")
8617 myDebugPrint3("DataRepresentation1.AttributeType " + str(DataRepresentation1.AttributeType) + "\n")
8618 myDebugPrint3("DataRepresentation1.UseIndexForXAxis " + str(DataRepresentation1.UseIndexForXAxis) + "\n")
8619 myDebugPrint3("DataRepresentation1.Visibility " + str(DataRepresentation1.Visibility) + "\n")
8620 myDebugPrint3("DataRepresentation1.XArrayName " + str(DataRepresentation1.XArrayName) + "\n")
8621 myDebugPrint3("DataRepresentation1.SeriesVisibility " + str(DataRepresentation1.SeriesVisibility) + "\n")
8622 myDebugPrint3("DataRepresentation1.SeriesLabel " + str(DataRepresentation1.SeriesLabel) + "\n")
8623 myDebugPrint3("DataRepresentation1.SeriesColor " + str(DataRepresentation1.SeriesColor) + "\n")
8624 myDebugPrint3("DataRepresentation1.SeriesPlotCorner " + str(DataRepresentation1.SeriesPlotCorner) + "\n")
8625 myDebugPrint3("DataRepresentation1.SeriesLabelPrefix " + str(DataRepresentation1.SeriesLabelPrefix) + "\n")
8626 myDebugPrint3("DataRepresentation1.SeriesLineStyle " + str(DataRepresentation1.SeriesLineStyle) + "\n")
8627 myDebugPrint3("DataRepresentation1.SeriesLineThickness " + str(DataRepresentation1.SeriesLineThickness) + "\n")
8628 myDebugPrint3("DataRepresentation1.SeriesMarkerStyle " + str(DataRepresentation1.SeriesMarkerStyle) + "\n")
8629
8630 yaxisstng = self.m_xyzMinMaxTrkC.mXyzTrk[1]
8631 if yaxisstng.mUseLowestBot and yaxisstng.mUseHighestBot and yaxisstng.mUseLowestTop and yaxisstng.mUseHighestTop:
8632 self.mSharedPvRenderView2.LeftAxisUseCustomRange = 1
8633 self.mSharedPvRenderView2.LeftAxisRangeMinimum = yaxisstng.mLowestBot
8634 self.mSharedPvRenderView2.LeftAxisRangeMaximum = yaxisstng.mHighestTop
8635 xaxisstng = self.m_xyzMinMaxTrkC.mXyzTrk[0]
8636 if xaxisstng.mUseLowestBot and xaxisstng.mUseHighestBot and xaxisstng.mUseLowestTop and xaxisstng.mUseHighestTop:
8637 self.mSharedPvRenderView2.BottomAxisUseCustomRange = 1
8638 self.mSharedPvRenderView2.BottomAxisRangeMinimum = xaxisstng.mLowestBot
8639 self.mSharedPvRenderView2.BottomAxisRangeMaximum = xaxisstng.mHighestTop
8640
8641 WriteImage(fname, self.mSharedPvRenderView2,
8642 Magnification=1)
8643 GetGlobalDataArtifactTracker().AddImageToDataArtifactOutputList(fname)
8644 #handle datetime naming extra work to avoid race condition
8645 if fnameRR != None:
8646 if SmartGetLocalProcessId() == 0:
8647 import os
8648 os.rename(fname, fnameRR)
8649
8650 #ClearPvViewAndPvRepAfterWriteImage(oneViewInfo)
8651 self.ClearPvViewAndPvRepAfterWriteImage()
8652
8653 def SetUpViewAndRepresentationBeforeWriteImage(self):
8654 """Since it turns out to be much more memory efficient to reuse a single
8655 render view rather than having one per image, this routine is called
8656 from PhactoriDriver immediately before WriteImage in order to set the
8657 camera, background color, image size, etc. up appropriately for the
8658 WriteImage call"""
8659 if PhactoriDbg(150):
8660 myDebugPrint3("PhactoriPlot1Base:" \
8661 "SetUpViewAndRepresentationBeforeWriteImage entered " + \
8662 str(self.mName) + "\n", 150)
8663 self.mPvDataRepresentation2.Visibility = 1
8664
8665 pvRenderView = self.mSharedPvRenderView2
8666 pvDataRep = self.mPvDataRepresentation2
8667
8668 #image size
8669 #pvRenderView.ViewSize = self.mImageSettings.mImageSize
8670 pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),
8671 int(self.mImageSettings.mImageSize[1])]
8672
8673 UpdatePlotViewLook(self)
8674
8675 def ClearPvViewAndPvRepAfterWriteImage(self):
8676 """Since it turns out to be much more memory efficient to reuse a single
8677 render view rather than having one per image, this routine is called
8678 immediately after WriteImage in order to make stuff invisible again
8679 before the next item gets a chance to do WriteImage"""
8680 #if PhactoriDbg(150):
8681 # myDebugPrint3("ClearPvViewAndPvRepAfterWriteImage entered\n", 150)
8682
8683 #3d/pointset dataset invisible (plot or 3d viewing)
8684 self.mPvDataRepresentation2.Visibility = 0
8685
8686
8687 class PhactoriPlotOverTimeBlock(PhactoriPlot1Base):
8688 """container for one time plot of variable
8689 """
8690 def __init__(self):
8691 PhactoriPlot1Base.__init__(self)
8692 self.m_PlotType = "PhactoriPlotOverTimeBlock"
8693 self.m_xyzMinMaxTrkC = PlotXYZMinMaxTrkC()
8694
8695 self.m_XAxisVariableInfo = PhactoriVariableInfo()
8696 self.m_XAxisVariableInfo.mVariableName = "Time Step"
8697
8698 self.m_YAxisVariableInfo = PhactoriVariableInfo()
8699 self.m_YAxisVariableInfo.mVariableName = None
8700
8701 self.m_NumberOfEntries = 0
8702 self.m_vtkTable = None
8703 self.m_TimeColumn = PhactoriPolyDataForPlotLine("Time")
8704 self.m_MaxPlotLine = PhactoriPolyDataForPlotLine("Max")
8705 self.m_MinPlotLine = PhactoriPolyDataForPlotLine("Min")
8706 self.m_MeanPlotLine = PhactoriPolyDataForPlotLine("Mean")
8707 self.m_IdPlotLineList = []
8708
8709 self.mPlotMaximumFlag = None
8710 self.mPlotMinimumFlag = None
8711 self.mPlotMeanFlag = None
8712
8713 def SetFromRestartInfo(self, inJson):
8714 """given a map (json format), use the info in the map to set the
8715 plot state--this reads the info created by out in
8716 GetRestartInfo. It should only occur on a restart, and
8717 it fills in the data that had been generated during the
8718 earlier run of the system"""
8719 if 'm_xyzMinMaxTrkC' not in inJson:
8720 if PhactoriDbg():
8721 myDebugPrint3("PhactoriPlotOverTimeBlock::SetFromRestartInfo " + \
8722 "m_xyzMinMaxTrkC not in inJson\n")
8723 return
8724
8725 self.m_xyzMinMaxTrkC.SetFromRestartInfo(inJson["m_xyzMinMaxTrkC"])
8726 self.m_TimeColumn.SetFromRestartInfo(inJson["m_TimeColumn"])
8727 self.m_MaxPlotLine.SetFromRestartInfo(inJson["m_MaxPlotLine"])
8728 self.m_MinPlotLine.SetFromRestartInfo(inJson["m_MinPlotLine"])
8729 self.m_MeanPlotLine.SetFromRestartInfo(inJson["m_MeanPlotLine"])
8730
8731
8732 def GetRestartInfo(self):
8733 """construct, in python map/json format, the information from this
8734 plot over time instance which contains the information
8735 which would be needed to restore the plot over time to the proper
8736 state after a simulation restart, particularly prior plot points.
8737 Return the restart info map/json"""
8738 newJsonItem = {}
8739 newJsonItem["m_xyzMinMaxTrkC"] = self.m_xyzMinMaxTrkC.GetRestartInfo()
8740 newJsonItem["m_TimeColumn"] = self.m_TimeColumn.GetRestartInfo()
8741 newJsonItem["m_MaxPlotLine"] = self.m_MaxPlotLine.GetRestartInfo()
8742 newJsonItem["m_MinPlotLine"] = self.m_MinPlotLine.GetRestartInfo()
8743 newJsonItem["m_MeanPlotLine"] = self.m_MeanPlotLine.GetRestartInfo()
8744 return newJsonItem
8745
8746 #self.m_TimeColumn = PhactoriPolyDataForPlotLine()
8747 #self.m_MaxPlotLine = PhactoriPolyDataForPlotLine()
8748 #self.m_MinPlotLine = PhactoriPolyDataForPlotLine()
8749 #self.m_MeanPlotLine = PhactoriPolyDataForPlotLine()
8750
8751 class PhactoriScatterPlotBlock(PhactoriPlot1Base):
8752 """container for one parallel scatterplot of one variable
8753 """
8754 def __init__(self):
8755 PhactoriPlot1Base.__init__(self)
8756 self.m_PlotType = "PhactoriScatterPlotBlock"
8757
8758 self.m_YAxisVariableInfo = PhactoriVariableInfo()
8759 self.m_YAxisVariableInfo.mVariableName = None
8760 self.m_XAxisVariableInfo = PhactoriVariableInfo()
8761 self.m_XAxisVariableInfo.mVariableName = None
8762
8763 self.m_xyzMinMaxTrkC = PlotXYZMinMaxTrkC()
8764 #self.m_PersistentPoints = None
8765 self.m_LimitNumberOfPointsFlag = False
8766 self.m_MaximumNumberOfPoints = 1000
8767 self.m_GrabMinsAndMaxesWhenLimitedFlag = True
8768 #self.m_Name = ""
8769 self.m_PolyData = None
8770 self.m_Points = None
8771 self.m_Vertex = None
8772
8773 #used to keep track paraview mergeblocks filter which is automatically
8774 #applied to the data before doing the ScatterPlot()
8775 self.m_MergeBlocks = None
8776
8777 #self.m_DataCubeAxesInfo = PhactoriDataCubeAxesInfo()
8778
8779 def SetVarABasedOnVarB(self, ioVarInfoA, ioVarInfoB):
8780 if PhactoriDbg():
8781 myDebugPrint3("SetVarABasedOnVarB entered\n")
8782 #see if x axis variable type needs detecting, and if so, detect it
8783 detectResult = ioVarInfoB.DetectVariableType(
8784 self.mInputOperation.GetPvFilter(), True)
8785 #if detectResult == False:
8786 #PutPlotOnListToDetectVariableTypeInFutureSteps() ?
8787 if detectResult == False:
8788 if PhactoriDbg(10000):
8789 myDebugPrint3("PhactoriScatterPlotBlock." + \
8790 "SetVarABasedOnVarB:\n" + \
8791 " error! detect variable type failed.\n",
8792 10000)
8793
8794 #set variable name and type for A based on B
8795 if ioVarInfoB.mVariableType == 'element':
8796 if PhactoriDbg():
8797 myDebugPrint3("variable B is element, setting A\n")
8798 ioVarInfoA.mVariableName = 'GlobalElementId'
8799 ioVarInfoA.mVariableType = 'element'
8800 else:
8801 if PhactoriDbg():
8802 myDebugPrint3("variable B is node, setting A\n")
8803 ioVarInfoA.mVariableName = 'GlobalNodeId'
8804 ioVarInfoA.mVariableType = 'node'
8805 if PhactoriDbg():
8806 myDebugPrint3("SetVarABasedOnVarB returning\n")
8807
8808 def ChooseDefaultVariableIfNecessary(self):
8809 if PhactoriDbg():
8810 myDebugPrint3("ChooseDefaultVariableIfNecessary entered\n")
8811 if PhactoriDbg():
8812 myDebugPrint3(" x axis var:\n" + self.m_XAxisVariableInfo.SelfToStr())
8813 if PhactoriDbg():
8814 myDebugPrint3(" y axis var:\n" + self.m_YAxisVariableInfo.SelfToStr())
8815
8816 if self.m_XAxisVariableInfo.mVariableType == None:
8817 if PhactoriDbg():
8818 myDebugPrint3(" x axis variable needs default from y axis\n")
8819 if self.m_YAxisVariableInfo.mVariableType == None:
8820 if PhactoriDbg(
8821 10000):
8822 myDebugPrint3("PhactoriScatterPlotBlock." + \
8823 "ChooseDefaultVariableIfNecessary:\n" + \
8824 " neither x axis variable or y axis variable is specified\n",
8825 10000)
8826 self.SetVarABasedOnVarB(self.m_XAxisVariableInfo,
8827 self.m_YAxisVariableInfo)
8828 SetUpPlotAxisNameDetails(self.m_XAxisVariableInfo,
8829 self.m_DataCubeAxesInfo.mXAxisInfo)
8830 elif self.m_YAxisVariableInfo.mVariableType == None:
8831 if PhactoriDbg():
8832 myDebugPrint3(" y axis variable needs default from x axis\n")
8833 self.SetVarABasedOnVarB(self.m_YAxisVariableInfo,
8834 self.m_XAxisVariableInfo)
8835 SetUpPlotAxisNameDetails(self.m_YAxisVariableInfo,
8836 self.m_DataCubeAxesInfo.mYAxisInfo)
8837 if PhactoriDbg():
8838 myDebugPrint3("ChooseDefaultVariableIfNecessary returning\n")
8839
8840 def ParseParametersFromJson(self, inJsn, inPipeAndViewsState):
8841 if PhactoriDbg():
8842 myDebugPrint3("PhactoriScatterPlotBlock.ParseParametersFromJson entered\n")
8843 self.mImageSettings.ParseImageSettingsInfo(inJsn,
8844 'plot basename', 'plot basedirectory')
8845 self.mImageFileNameCountSettings.ParseImageFileNameCountSettings(inJsn)
8846
8847 self.mBackground = getParameterFromBlock(inJsn,
8848 'background color', self.mBackground)
8849
8850 #parse x axis variable
8851 self.m_XAxisVariableInfo.ParseVariableNameAndVectorOrTensorComponent(inJsn,
8852 'x axis variable ')
8853
8854 #parse y axis variable
8855 self.m_YAxisVariableInfo.ParseVariableNameAndVectorOrTensorComponent(inJsn,
8856 'y axis variable ')
8857
8858 if self.m_YAxisVariableInfo.mVariableType == None and \
8859 self.m_XAxisVariableInfo.mVariableType:
8860 if PhactoriDbg(
8861 10000):
8862 myDebugPrint3("PhactoriScatterPlotBlock.ParseParametersFromJson " + \
8863 ":\n neither x axis variable or y axis variable is specified\n",
8864 10000)
8865
8866 #handle name of each axis, particularly in vector component/magnitude case
8867 SetUpPlotAxisNameDetails(self.m_XAxisVariableInfo,
8868 self.m_DataCubeAxesInfo.mXAxisInfo)
8869 SetUpPlotAxisNameDetails(self.m_YAxisVariableInfo,
8870 self.m_DataCubeAxesInfo.mYAxisInfo)
8871
8872 #hack to test missing data situations
8873 #if self.mName == "fooScatter":
8874 # myDebugPrint3("hack to test missing data, found fooScatter, using stressthresh\n")
8875 # self.mInputOperation = inPipeAndViewsState.mOperationBlocks["stressthresh"]
8876 #else:
8877 # myDebugPrint3("hack to test missing data, did not find fooScatter\n")
8878 # self.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson(
8879 # 'operation', inJsn)
8880
8881 self.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson(
8882 'operation', inJsn)
8883
8884 self.m_xyzMinMaxTrkC.PlotXYZMinMaxTrkCParseJson(inJsn, 'axis ')
8885
8886 self.mColorSettings.ParsePlotColorSettingsFromJson(inJsn)
8887
8888 if PhactoriDbg():
8889 myDebugPrint3(\
8890 "PhactoriScatterPlotBlock.ParseParametersFromJson returning\n")
8891
8892 global HandleShowAxesWithEmptyDataParaViewIssueFlag
8893 #HandleShowAxesWithEmptyDataParaViewIssueFlag = True
8894 HandleShowAxesWithEmptyDataParaViewIssueFlag = False
8895
8896 #for now, we are trying to have one paraview RenderView which is shared and
8897 #reused for all images everywhere; we may need to change that for plots and
8898 #multiple simulation codes in same input deck
8899 global gSharedRenderView
8900 gSharedRenderView = None
8901
8902 #shared render view to be used by all plots
8903 global gSharedLineChartView
8904 gSharedLineChartView = None
8905
8906 class PhactoriImagesetBlock:
8907 """contains information corresponding to an imageset block
8908 """
8909 def __init__(self):
8910 self.mName = ""
8911
8912 #weirdness on first image for an imageset; partial fix is to render twice
8913 #the first time
8914 #self.mWriteFirstImageTwiceFlag = 0
8915 #1 is don't render twice first time
8916 self.mWriteFirstImageTwiceFlag = 1
8917
8918 #(for now) mOperation and mRepresentation are the 'primary' data sources
8919 #for this imageset, which includes directing camera positioning if
8920 #necessary. Later we may update this to only have a list, not a
8921 #distinction between primary and other.
8922 self.mOperation = None
8923 self.mRepresentation = None
8924
8925 #(for now) allowing imageset to have additional operations visible.
8926 #later this may become the only recording of which operations are visible
8927 #and mOperation and mRepresentation will be eliminated. Also for
8928 #now, mVisibleOps[0] should be the same as mOperation and
8929 #mVisibleReps[0] should be the same as mRepresentation
8930 self.mVisibleOps = []
8931 self.mVisibleReps = []
8932 self.mVisiblePvDataReps = []
8933 self.mColorLegendRepRefs = []
8934
8935 self.mVisibleMarkerNames = []
8936 self.mVisibleMarkers = []
8937
8938 self.mTextAnnotationNames = []
8939 self.mTextAnnotations = []
8940
8941 self.mCamera = None
8942 self.mImageSettings = PhactoriImageSettings()
8943 self.mLookDirectionList = []
8944 self.mLookDirectionFilenameAddon = []
8945
8946 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 0
8947
8948 #reference for paraview RenderView instance which is shared among all
8949 #renderings
8950 self.mSharedPvRenderView2 = None
8951
8952 #reference for paraview DataRepresentation instance for this imageset.
8953 #if the imageset has multiple view directions, they can share the same
8954 #representation
8955 self.mPvDataRepresentation2 = None
8956
8957 #self.mOnOffCriteriaName = None
8958 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
8959
8960 self.DeadCellIoFf = None
8961
8962 #used to control if we want to have image names sequentially count by
8963 #callback index, or if we want to use a date/time based count
8964 #(which can use microseconds or not, and can be converted to an integer
8965 #or not)
8966 self.mImageFileNameCountSettings = ImageFileNameCountSettings()
8967
8968 self.mBackground = [0.31999694819562063, 0.3400015259021897,
8969 0.4299992370489052]
8970
8971 def GetInputPhactoriOperation(self):
8972 #mainly for compatibility between plot blocks and imageset blocks, give
8973 #same access to phactori operation coming being visualized
8974 return self.mOperation
8975
8976 def HandleShowAxesWithEmptyDataParaViewIssue(self):
8977 """we are having a paraview related issue wherein if an empty dataset
8978 (due to threshold or clip) has a show axes setting of true, VTK
8979 complains. For now, we are turning off the cube axes if the data is
8980 empty and back on if data is nonempty (assuming user has cube axes
8981 set to on"""
8982
8983 if self.mRepresentation.mDataCubeAxesFlag == False:
8984 #nothing to be done--it's off so we just return
8985 return
8986
8987 #allow this functionality to be eliminated to avoid mpi communication
8988 global HandleShowAxesWithEmptyDataParaViewIssueFlag
8989 if HandleShowAxesWithEmptyDataParaViewIssueFlag != True:
8990 return
8991
8992 if self.mHandleShowAxesWithEmptyDataParaViewIssueStatus == 2:
8993 #if PhactoriDbg():
8994 # myDebugPrint3("HandleShowAxesWithEmptyDataParaViewIssue at status 2\n")
8995 return
8996
8997 paraviewSource = self.mOperation.GetPvFilter()
8998 UpdatePipelineWithCurrentTimeArgument(paraviewSource)
8999
9000 pvsDi = paraviewSource.GetDataInformation()
9001
9002 #we find num cells and num points on this processor and share with others;
9003 #note that we use UseReduceToSpreadValues which doesn't sum values--we're
9004 #just trying to ascertain if there are ANY cells or points
9005
9006 numCells = pvsDi.GetNumberOfCells()
9007 numPoints = pvsDi.GetNumberOfPoints()
9008 cellAndPointCount = [numCells, numPoints]
9009 UseReduceToSpreadValues(cellAndPointCount)
9010
9011 #see if data is empty or nonempty
9012 if cellAndPointCount[0] + cellAndPointCount[1] != 0:
9013 datasetIsEmpty = False
9014 else:
9015 datasetIsEmpty = True
9016
9017 #if PhactoriDbg():
9018 # myDebugPrint3("HandleShowAxesWithEmptyDataParaViewIssue executing:\n")
9019 # myDebugPrint3(" num cells: " + str(pvsDi.GetNumberOfCells()) + \
9020 # "\n num points: " + str(pvsDi.GetNumberOfPoints()) + "\n")
9021 # myDebugPrint3("datasetIsEmpty is " + str(datasetIsEmpty) + "\n")
9022
9023 #thePvDataRep = self.mParaViewRenderInfoCs[0].mParaViewInfo.DataRepresentation1
9024
9025 if datasetIsEmpty:
9026 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 1
9027 ShowCubeAxesXX(self.mSharedPvRenderView2, 'off')
9028 else:
9029 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 2
9030 ShowCubeAxesXX(self.mSharedPvRenderView2, 'on')
9031
9032 def WriteImages(self, datadescription):
9033 """write out the .png/.jpg/whatever images associated with this imageset
9034 block for the current timestep/state. Must loop through camera angles
9035 and do a write for each one if necessary"""
9036 if PhactoriDbg(100):
9037 myDebugPrint3("PhactoriImagesetBlock::WriteImages entered: " + \
9038 self.mName + "\n")
9039
9040 global gPipeAndViewsState
9041 if self.mImagesetOnOffFilter.TestDrawImagesThisCallback(
9042 gPipeAndViewsState) == False:
9043 if PhactoriDbg(100):
9044 myDebugPrint3("WriteImages returning with no write due to filter\n")
9045 return
9046
9047 self.WriteImagesPassedOnOffFilter(datadescription)
9048
9049 if PhactoriDbg(100):
9050 myDebugPrint3("PhactoriImagesetBlock::WriteImages returning: " + \
9051 self.mName + "\n")
9052
9053 def WriteOutCameraInformationForTesting(self, fname):
9054 if SmartGetLocalProcessId() != 0:
9055 return
9056 camfname = fname + ".test.camera.txt"
9057 ff = open(camfname, "w")
9058 if ff == None:
9059 return
9060 pvRv = self.mSharedPvRenderView2;
9061 ff.write("{\n")
9062 ff.write(""""CameraPosition":""" + str(pvRv.CameraPosition) + ",\n")
9063 ff.write(""""CameraFocalPoint": """ + str(pvRv.CameraFocalPoint) + ",\n")
9064 ff.write(""""CameraParallelProjection": """ + str(pvRv.CameraParallelProjection) + ",\n")
9065 if pvRv.CameraParallelProjection == 0:
9066 ff.write(""""CameraParallelScale": -1.0,\n""")
9067 else:
9068 ff.write(""""CameraParallelScale": """ + str(pvRv.CameraParallelScale) + ",\n")
9069 ff.write(""""CameraViewUp": """ + str(pvRv.CameraViewUp) + ",\n")
9070 ff.write(""""CameraViewAngle": """ + str(pvRv.CameraViewAngle) + "\n")
9071 ff.write("}\n")
9072 ff.close()
9073
9074 def WriteImagesPassedOnOffFilter(self, datadescription):
9075 """write out the .png/.jpg/whatever images associated with this imageset
9076 block for the current timestep/state. Must loop through camera angles
9077 and do a write for each one if necessary"""
9078
9079 global gPipeAndViewsState
9080
9081 if PhactoriDbg(100):
9082 myDebugPrint3(
9083 "PhactoriImagesetBlock::WriteImagesPassedOnOffFilter entered\n")
9084
9085 for ii in range(len(self.mLookDirectionList)):
9086 oneLookDirection = self.mLookDirectionList[ii]
9087 oneLookDirectionFilenameAddon = self.mLookDirectionFilenameAddon[ii]
9088
9089 fname, fnameRR = self.mImageFileNameCountSettings.GetImageFilename(
9090 datadescription, self.mImageSettings,
9091 oneLookDirectionFilenameAddon,
9092 self.mRepresentation.mFilenameAddon,
9093 self.mCamera.mFilenameAddon)
9094
9095 #used to do this:
9096 #view.ViewTime = datadescription.GetTime()
9097 #maybe need to do this?
9098 #UpdatePipelineWithCurrentTimeArgument()
9099
9100 #SetUpViewAndRepresentationBeforeWriteImage(oneViewInfo)
9101 self.SetUpViewAndRepresentationBeforeWriteImage(oneLookDirection, ii)
9102
9103 colorPalette = GetSettingsProxy('ColorPalette')
9104 colorPalette.Background = self.mBackground
9105
9106 #only need to update color range for first look direction, rest
9107 #are same
9108 if ii == 0:
9109 #UpdateColorRangeImmediatelyBeforeWrite(phactoriImagesetName)
9110 if self.mRepresentation.mUseFixedColorRange == False:
9111 UseDataRangeForColorValues(self.mPvDataRepresentation2,
9112 self.mRepresentation, self.mOperation)
9113 for ii in range(1, len(self.mVisibleReps)):
9114 oneVisOp = self.mVisibleOps[ii]
9115 oneVisRep = self.mVisibleReps[ii]
9116 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
9117 UseDataRangeForColorValues(oneVisPvDataRep,
9118 oneVisRep, oneVisOp)
9119
9120 if self.mName.startswith("is_element_select") == False:
9121
9122 for onevisop in self.mVisibleOps:
9123 if onevisop.mType == "nearestpoints":
9124 onevisop.mOperationSpecifics.\
9125 RunCalculationToFindNearestPoints(gPipeAndViewsState)
9126 if onevisop.mType == "castnormalrays":
9127 onevisop.mOperationSpecifics.\
9128 RunCalculationToCastRays(gPipeAndViewsState)
9129 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
9130 if onevisop.mName == "surfaceofinterest1":
9131 global gParaViewCatalystVersionFlag
9132 if gParaViewCatalystVersionFlag < 51000:
9133 svrng = onevisop.mParaViewFilter.ThresholdRange
9134 #onevisop.mParaViewFilter.ThresholdRange = [svrng[0]*0.5, svrng[1]*0.5]
9135 onevisop.mParaViewFilter.ThresholdRange = [1.0, 10.0]
9136 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
9137 onevisop.mParaViewFilter.ThresholdRange = svrng
9138 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
9139 else:
9140 svrngLower = onevisop.mParaViewFilter.LowerThreshold
9141 svrngUpper = onevisop.mParaViewFilter.UpperThreshold
9142 onevisop.mParaViewFilter.LowerThreshold = 1.0
9143 onevisop.mParaViewFilter.UpperThreshold = 10.0
9144 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
9145 onevisop.mParaViewFilter.LowerThreshold = svrngLower
9146 onevisop.mParaViewFilter.UpperThreshold = svrngUpper
9147 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
9148
9149 if PhactoriDbg():
9150 firstop = self.mVisibleOps[0]
9151 firstPvFilter = firstop.GetPvFilter()
9152 label1 = "before WriteImage() " + fname + "\n"
9153 DebugPrintCellAndPointArrayInfo(label1, firstPvFilter, 100)
9154 myDebugPrint3("self.mPvDataRepresentation2.Representation:\n" + \
9155 str(self.mPvDataRepresentation2.Representation) + "\n")
9156
9157 if PhactoriDbg():
9158 myDebugPrint3("calling WriteImage() " + fname + "\n")
9159
9160 global gCameraTestMode
9161 if gCameraTestMode == 1:
9162 self.WriteOutCameraInformationForTesting(fname)
9163
9164 global gSkipWriteImageForTests
9165 if gSkipWriteImageForTests == False:
9166 WriteImage(fname, self.mSharedPvRenderView2,
9167 Magnification=1)
9168 GetGlobalDataArtifactTracker().AddImageToDataArtifactOutputList(fname)
9169 if PhactoriDbg():
9170 myDebugPrint3("returned from WriteImage()\n")
9171 #handle datetime naming extra work to avoid race condition
9172 if fnameRR != None:
9173 if SmartGetLocalProcessId() == 0:
9174 import os
9175 os.rename(fname, fnameRR)
9176 #hack, double write
9177 #WriteImage(fname, self.mSharedPvRenderView2,
9178 # Magnification=1)
9179
9180 #ClearPvViewAndPvRepAfterWriteImage(oneViewInfo)
9181 self.ClearPvViewAndPvRepAfterWriteImage()
9182
9183 if self.mWriteFirstImageTwiceFlag == 0:
9184 self.mWriteFirstImageTwiceFlag = 1
9185 if PhactoriDbg(100):
9186 myDebugPrint3(
9187 "mWriteFirstImageTwiceFlag triggers (3) re-render of first image\n")
9188 self.WriteImagesPassedOnOffFilter(datadescription)
9189
9190 if self.mName.startswith("is_dead_cells"):
9191 timestep = datadescription.GetTimeStep()
9192
9193 imageBasename = self.mImageSettings.mImageBasename
9194 imageBasedirectory = self.mImageSettings.mImageBasedirectory
9195 import os
9196 #dcfname = + str(timestep) + "_.csv"
9197 lpid = SmartGetLocalProcessId()
9198 #dcfname = imageBasedirectory + os.sep + imageBasename + \
9199 # str(timestep) + "." + str(lpid) + "._.csv"
9200 dcfname = imageBasedirectory + os.sep + imageBasename + \
9201 str(timestep) + "." + str(lpid) + ".csv"
9202 if PhactoriDbg(100):
9203 myDebugPrint3("is_dead_cells: writing:\n" + dcfname + "\n")
9204 rcrsnParams = self.mOperation.OutputElementListToFile(dcfname)
9205 if PhactoriDbg(100):
9206 myDebugPrint3("is_dead_cells: done writing:\n" + dcfname + "\n")
9207
9208 #write out dead cell count
9209 global WriteDeadCellSummaryFile
9210
9211 if WriteDeadCellSummaryFile:
9212 myVals = [rcrsnParams.mElementCount,
9213 rcrsnParams.mKilledByCriteriaCount[2],
9214 rcrsnParams.mKilledByCriteriaCount[3],
9215 rcrsnParams.mKilledByCriteriaCount[5]]
9216 UseReduceToSumArrayOfInts(myVals)
9217
9218 if lpid == 0:
9219 if self.DeadCellIoFf == None:
9220 dcsummaryname = imageBasedirectory + os.sep + imageBasename + \
9221 "dead_cell_info.csv"
9222 self.DeadCellIoFf = open(dcsummaryname, "w")
9223 self.DeadCellIoFf.write("step, simtime, number of dead cells, " \
9224 "killed 2, killed 3, killed 5\n")
9225 timestep = datadescription.GetTimeStep()
9226 simTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
9227 self.DeadCellIoFf.write(
9228 str(timestep) + ", " + \
9229 str(simTime) + "," + \
9230 str(myVals[0]) + ", " + \
9231 str(myVals[1]) + ", " + \
9232 str(myVals[2]) + ", " + \
9233 str(myVals[3]) + "\n")
9234 self.DeadCellIoFf.flush()
9235
9236 if self.mName.startswith("is_element_select"):
9237 timestep = datadescription.GetTimeStep()
9238 #global gPipeAndViewsState
9239 simTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
9240 imageBasename = self.mImageSettings.mImageBasename
9241 imageBasedirectory = self.mImageSettings.mImageBasedirectory
9242 import os
9243 #dcfname = imageBasedirectory + os.sep + imageBasename + ".csv"
9244 dcfname1 = imageBasedirectory + os.sep + imageBasename + "element.csv"
9245 dcfname2 = imageBasedirectory + os.sep + imageBasename + "node.csv"
9246 self.mOperation.OutputSingleElementToTimeHistoryFile(
9247 dcfname1, dcfname2, timestep, simTime)
9248
9249 if PhactoriDbg(100):
9250 myDebugPrint3(
9251 "PhactoriImagesetBlock::WriteImagesPassedOnOffFilter returning\n")
9252
9253 def SetUpViewAndRepresentationBeforeWriteImage(self, inLookDirection,
9254 inLookDirectionIndex):
9255 """Since it turns out to be much more memory efficient to reuse a single
9256 render view rather than having one per image, this routine is called
9257 immediately before WriteImage in order to set the
9258 camera, background color, image size, etc. up appropriately for the
9259 WriteImage call"""
9260 if PhactoriDbg(100):
9261 myDebugPrint3("PhactoriImagesetBlock:" \
9262 "SetUpViewAndRepresentationBeforeWriteImage entered " + \
9263 str(self.mName) + "\n", 100)
9264 self.mPvDataRepresentation2.Visibility = 1
9265
9266 pvRenderView = self.mSharedPvRenderView2
9267 pvDataRep = self.mPvDataRepresentation2
9268
9269 #image size
9270 #pvRenderView.ViewSize = self.mImageSettings.mImageSize
9271 pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),
9272 int(self.mImageSettings.mImageSize[1])]
9273
9274 #background color, text color, etc.
9275
9276 theColorSettings = self.mRepresentation.mColorSettings
9277
9278 theColorSettings.SetParaviewRvRepColors(pvRenderView, pvDataRep)
9279
9280 phactoriRep = self.mRepresentation
9281 #orientation axis on or off for this 3d mesh
9282 if phactoriRep.mOrientationAxesFlag:
9283 pvRenderView.OrientationAxesVisibility = 1
9284 else:
9285 pvRenderView.OrientationAxesVisibility = 0
9286
9287 #time annotation invisible (for 3d plot)
9288 timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings
9289 if timeAnnStngs.mVisible:
9290 global gPipeAndViewsState
9291 if gPipeAndViewsState.mTimeAnnotationPv != None:
9292 gPipeAndViewsState.mTimeAnnotationPv.\
9293 mParaViewRepresentation.Visibility = 1
9294
9295 #cube axes
9296 if phactoriRep.mDataCubeAxesFlag:
9297 ShowCubeAxesXX(pvRenderView, 'on', phactoriRep.mDataCubeAxesInfo)
9298
9299 #edges/surface/wireframe
9300 #self.mPvDataRepresentation2.Representation = \
9301 # phactoriRep.mMeshRenderControl
9302 self.mPvDataRepresentation2.SetRepresentationType(
9303 phactoriRep.mMeshRenderControl)
9304
9305 if phactoriRep.mDoingVolumeRendering:
9306 if phactoriRep.mScalarOpacityUnitDistance < 0.0:
9307 phactoriRep.CalculateDefaultScalarOpacityUnitDistance(self.mOperation)
9308 if phactoriRep.mScalarOpacityUnitDistance != \
9309 self.mPvDataRepresentation2.ScalarOpacityUnitDistance:
9310 self.mPvDataRepresentation2.ScalarOpacityUnitDistance = \
9311 phactoriRep.mScalarOpacityUnitDistance
9312
9313 #size of points
9314 self.mPvDataRepresentation2.PointSize = phactoriRep.mPointSize
9315
9316 #color legend
9317 for oneColorLegendRepRef in self.mColorLegendRepRefs:
9318 if oneColorLegendRepRef != None:
9319 oneColorLegendRepRef.Visibility = 1
9320
9321 #color by variable or solid color or color by block
9322 if inLookDirectionIndex == 0:
9323 #on multicamera 8 setups, we only do this on first (index 0)
9324 SetForCorrectColorBy(self, self.mOperation,
9325 self.mPvDataRepresentation2, phactoriRep, False)
9326 else:
9327 #for some reason, solid color doesn't stick between camera angles;
9328 #redo if it is solid color
9329 if phactoriRep.mColorBySolidColorFlag == True:
9330 SetForCorrectColorBy(self, self.mOperation,
9331 self.mPvDataRepresentation2, phactoriRep, False)
9332
9333 #markers for this imageset made visible
9334 for oneMarker in self.mVisibleMarkers:
9335 oneMarker.UpdateAndMakeVisible()
9336
9337 for oneTextAnnotation in self.mTextAnnotations:
9338 oneTextAnnotation.UpdateAndMakeVisible()
9339
9340 #do extra visible operations/representations
9341 ii = 1
9342 while ii < len(self.mVisibleReps):
9343 oneVisOp = self.mVisibleOps[ii]
9344 oneVisRep = self.mVisibleReps[ii]
9345 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
9346 if PhactoriDbg(100):
9347 myDebugPrint3("add extra visiblity " + str(ii) + " rep:\n" + \
9348 str(oneVisPvDataRep))
9349 ii += 1
9350
9351 oneVisPvDataRep.Visibility = 1
9352 #theColorSettings = self.mRepresentation.mColorSettings
9353 #theColorSettings.SetParaviewRvRepColors(pvRenderView, oneVisPvDataRep)
9354
9355 #edges/surface/wireframe
9356 oneVisPvDataRep.SetRepresentationType(oneVisRep.mMeshRenderControl)
9357
9358 if oneVisRep.mDoingVolumeRendering:
9359 if oneVisRep.mScalarOpacityUnitDistance < 0.0:
9360 oneVisRep.CalculateDefaultScalarOpacityUnitDistance(oneVisOp)
9361 if oneVisRep.mScalarOpacityUnitDistance != \
9362 oneVisPvDataRep.ScalarOpacityUnitDistance:
9363 oneVisPvDataRep.ScalarOpacityUnitDistance = \
9364 oneVisRep.mScalarOpacityUnitDistance
9365
9366
9367 #color legend
9368 #if self.mColorLegendRepRef != None:
9369 # self.mColorLegendRepRef.Visibility = 1
9370
9371 #color by variable or solid color or color by block
9372 if inLookDirectionIndex == 0:
9373 #on multicamera 8 setups, we only do this on first (index 0)
9374 SetForCorrectColorBy(self, oneVisOp,
9375 oneVisPvDataRep, oneVisRep, False)
9376 else:
9377 #for some reason, solid color doesn't stick between camera angles;
9378 #redo if it is solid color
9379 if phactoriRep.mColorBySolidColorFlag == True:
9380 #SetForCorrectColorBy(self, self.mPvDataRepresentation2,
9381 # phactoriRep, False)
9382 SetForCorrectColorBy(self, oneVisOp,
9383 oneVisPvDataRep, oneVisRep, False)
9384
9385 if PhactoriDbg(100):
9386 myDebugPrint3("start setting camera parameters for imageset: " + \
9387 self.mName + "\n", 100)
9388 SetParaViewRepresentationCameraParams(
9389 pvRenderView,
9390 self.mCamera,
9391 inLookDirection,
9392 self.mImageSettings,
9393 self.mOperation.GetPvFilter())
9394 if PhactoriDbg(100):
9395 myDebugPrint3("done setting camera parameters for imageset: " + \
9396 self.mName + "\n", 100)
9397
9398 if PhactoriDbg(100):
9399 myDebugPrint3("SetUpViewAndRepresentationBeforeWriteImage returning\n",
9400 100)
9401
9402 def ClearPvViewAndPvRepAfterWriteImage(self):
9403 """Since it turns out to be much more memory efficient to reuse a single
9404 render view rather than having one per image, this routine is called
9405 immediately after WriteImage in order to make stuff invisible again
9406 before the next item gets a chance to do WriteImage"""
9407 #if PhactoriDbg(150):
9408 # myDebugPrint3("ClearPvViewAndPvRepAfterWriteImage entered\n", 150)
9409
9410 #cube axes invisible
9411 ShowCubeAxesXX(self.mSharedPvRenderView2, 'off')
9412
9413 #3d/pointset dataset invisible (plot or 3d viewing)
9414 self.mPvDataRepresentation2.Visibility = 0
9415
9416 #color legend invisible, if 3d viewing
9417 for oneColorLegendRepRef in self.mColorLegendRepRefs:
9418 if oneColorLegendRepRef != None:
9419 if PhactoriDbg(100):
9420 myDebugPrint3("C inColorLegendRepRef was " + \
9421 str(oneColorLegendRepRef.Visibility) + \
9422 " now 0: " + str(oneColorLegendRepRef) + "\n")
9423 oneColorLegendRepRef.Visibility = 0
9424
9425 #time annotation invisible (for 3d plot)
9426 timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings
9427 if timeAnnStngs.mVisible:
9428 global gPipeAndViewsState
9429 if gPipeAndViewsState.mTimeAnnotationPv != None:
9430 gPipeAndViewsState.mTimeAnnotationPv.\
9431 mParaViewRepresentation.Visibility = 0
9432
9433 #markers for this imageset made invisible
9434 for oneMarker in self.mVisibleMarkers:
9435 oneMarker.MakeInvisible()
9436
9437 for oneTextAnnotation in self.mTextAnnotations:
9438 oneTextAnnotation.MakeInvisible()
9439
9440 #do extra visible operations/representations
9441 ii = 1
9442 while ii < len(self.mVisibleReps):
9443 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
9444 if(oneVisPvDataRep != None):
9445 oneVisPvDataRep.Visibility = 0
9446 #this is already done above
9447 #oneColorLegendRepRef = self.mColorLegendRepRefs[ii]
9448 #if(oneColorLegendRepRef != None):
9449 # oneColorLegendRepRef.Visbility = 0
9450 ii += 1
9451
9452
9453 def ParseOperationAndRepresentationPair(self, ioPipeAndViewsState, ioJson,
9454 inOperationKey, inSkipIfOperationKeyNotPresent,
9455 inRepresentationKey, inRepresentationKeyRequired,
9456 inAllowPairFromAnotherSource):
9457 """parse out the operation and associated representation from the
9458 given json; also optionally throw exception if representation
9459 is not given. Used to get multiple visible operation/representation
9460 pairs"""
9461 if PhactoriDbg():
9462 myDebugPrint3("PhactoriImagesetBlock::"
9463 "ParseOperationAndRepresentationPair entered\n")
9464 myDebugPrint3(
9465 "inOperationKey: " + str(inOperationKey) + "\n"
9466 "inRepresentationKey: " + str(inRepresentationKey) + "\n"
9467 "incoming json:\n" + str(ioJson) + "\n")
9468
9469
9470 if inOperationKey not in ioJson:
9471 if inSkipIfOperationKeyNotPresent:
9472 return
9473
9474 if inRepresentationKeyRequired == False and \
9475 inRepresentationKey not in ioJson:
9476 #we have to construct and use a default representation, including parsing
9477 #commands in the imageset for the representation
9478 if PhactoriDbg():
9479 myDebugPrint3(" ParseOperationAndRepresentationPair: for imageset " + \
9480 self.mName + \
9481 " there is no representation, " +
9482 "so we must add and reference default\n")
9483 defaultRepName = self.mName + '_default_representation'
9484 defaultRepBlockAndWrapper = {defaultRepName: ioJson}
9485 ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,
9486 defaultRepBlockAndWrapper,
9487 PhactoriRepresentationBlock,
9488 ParseOneRepresentationBlockC,
9489 ioPipeAndViewsState)
9490 ioJson[inRepresentationKey] = defaultRepName
9491
9492 pipeForPair = None
9493 if inAllowPairFromAnotherSource:
9494 anotherVisOperation, pipeForPair = ioPipeAndViewsState. \
9495 GetOperationReferredByJsonCrossPipe(inOperationKey, ioJson)
9496 else:
9497 anotherVisOperation = ioPipeAndViewsState.GetOperationReferredByJson(
9498 inOperationKey, ioJson)
9499
9500 self.mVisibleOps.append(anotherVisOperation)
9501
9502 anotherVisRepresentation = None
9503 if inRepresentationKey in ioJson:
9504 pipeForRepresentation = ioPipeAndViewsState
9505 if pipeForPair != None:
9506 pipeForRepresentation = pipeForPair
9507 representationName = ioJson[inRepresentationKey]
9508 if representationName not in pipeForRepresentation.mRepresentationBlocks:
9509 errStr = "ParseOperationAndRepresentationPair::exeception/error\n" + \
9510 " imageset (" + str(self.mName) + \
9511 ") calls for representation (" + \
9512 str(representationName) + ") which does not exist\n"
9513 myDebugPrint3AndException(errStr)
9514 else:
9515 anotherVisRepresentation = \
9516 pipeForRepresentation.mRepresentationBlocks[representationName]
9517
9518 if anotherVisRepresentation == None:
9519 #at this point we should have a representation--if we don't it
9520 #was required to be set but not set
9521 myDebugPrint3AndException(\
9522 "PhactoriImagesetBlock::ParseOperationAndRepresentationPair\n"
9523 "Exception/Error: operation missing required corresponding\n"
9524 "repesentation.\noperation key: " + inOperationKey + "\n"
9525 "missing representation key: " + inRepresentationKey + "\n")
9526
9527 self.mVisibleReps.append(anotherVisRepresentation)
9528 self.mVisiblePvDataReps.append(None)
9529 self.mColorLegendRepRefs.append(None)
9530
9531 class PhactoriPipeAndViewsState:
9532 """Top State Container--Pipeline, Cameras, Representations, Imagesets, Plots
9533
9534 This is essentially the top-level class for wrapping up everything about the
9535 phactori-controlled viewing situation. It keeps a reference to the original
9536 json (assuming that was how the state was described originally), and stores
9537 and organizes all the other information. Presently that means that there
9538 six sets, each of which stores the class instances corresponding to one
9539 block type from the json input format. The block types stored are the
9540 camera blocks, the representation blocks, the operation blocks, the
9541 imageset blocks, the scatter plot blocks, and the plot over time blocks.
9542 A set for each type of block is kept, with the block name (assigned by the
9543 json author) as a key for that block. The Operation blocks are basically
9544 analagous to the ParaView/Catalyst Filters, the imagesets are roughly
9545 analagous to the ParaView Views (but with image endpoints rather than
9546 interactive rendering endpoints), the Representation blocks plus the
9547 camera blocks are analagous to the ParaView Representations. The
9548 scatter plot and plot over time blocks are simply specialized descriptions
9549 of requested plots, which are converted into ParaView filters and views
9550 to create plots which can be calculated and/or rendered in parallel at
9551 runtime, as opposed to bringing data to the client. An imageset block will
9552 reference a camera block, a representation block, and an operation block and
9553 contains some additional parameters (e.g. image size and file basename)
9554 which will describe a view to be rendered--repeatedly at different times
9555 when using insitu. The camera blocks describe 3-D viewpoints, sometimes in
9556 absoulte 3D terms, sometimes dependent on the data. The representation
9557 blocks control how the view looks, e.g. if element surface and edges are
9558 rendered or just surfaces and if we show axes and color legends. The
9559 operation blocks can describe a potentially complex data pipeline which can
9560 allow rendering at various points along the pipeline. The pipeline is
9561 currently assumed to have operations that only have one input and one
9562 output. Multiple operations can have the same input, so a 'tree' is
9563 possible, not just a single linear pipe. Operations with multiple inputs
9564 and outputs are conceivable but not currently implemented. One obvious
9565 possible upgrade would be to allow 'geometryoutput' blocks which would
9566 output geometry rather than images, presumably geometry which is at the
9567 back end of a pipeline (e.g. to extract isosurface and the decimate).
9568 """
9569 def __init__(self):
9570 self.mJsonDescription = {}
9571 self.mCameraBlocks = {}
9572 self.mRepresentationBlocks = {}
9573 #default operation for incoming input
9574 self.mIncomingDefaultOperation = PhactoriOperationBlock()
9575 self.mIncomingDefaultOperation.mName = "default incoming input"
9576 #self.mIncomingOperationList = []
9577 self.mOperationBlocks = {}
9578 self.mImagesetBlocks = {}
9579 self.mScatterPlotBlocks = {}
9580 self.mPlotOverTimeBlocks = {}
9581 self.mImagesetOnOffCriteriaBlocks = {}
9582 self.mMarkerBlocks = {}
9583 self.mTextAnnotationBlocks = {}
9584 self.mCallbackDateTime = datetime.datetime.now()
9585
9586 #used to essentially keep track of the number of times catalyst is
9587 #called back, for keying when we do or do not need to recalculate
9588 #things such as variable mins/maxes
9589 self.mFrameTagCounter = 0
9590
9591 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
9592
9593 #the following items help id this instance to one results output block
9594 #in the input deck, and to a given restart or remesh instance
9595 self.mOutputResultsBlockId = None
9596 self.mCurrentDatabaseDummyFileName = None
9597 self.mProducer = None
9598 #self.mIncomingGridProducerList = []
9599 self.mPipeAndViewsState = None
9600 self.mRemeshRestartTag = None
9601 self.mSeparatorString = '_'
9602 self.mRemeshCount = 0
9603 self.mOutputResultsBlockCountId = -1
9604 self.mImageSetCounter = 0
9605
9606 self.CurrentDatadescription = None
9607 self.mDefaultBasedirectory = ''
9608
9609 self.mBlockIdForRestart = ''
9610
9611 #self.mInteractionEnabled = True
9612 self.mInteractionEnabled = False
9613 self.mInteractionTriggerCounter = 0
9614 self.mInteractionTriggerTries = 7
9615 self.mInteractionTriggerSleep = 1
9616 self.mInteractionRepeatPauseSim = False
9617
9618 #class instance to filter rendering of images on/off based on simulation
9619 #data
9620 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
9621
9622 #this item manges the paraview representation and color stuff for the
9623 #time annotation source.
9624 #since we are now using one RenderView, we can share a single time
9625 #annotation source representation. However, it is conceivable that
9626 #we may eventually want to show different times for some reason, and
9627 #in that case we will need to have each imageset have its own time
9628 #annotation paraview stuff
9629 self.mTimeAnnotationPv = None
9630
9631 def ExportOperationsData(self, datadescription):
9632 """go through all the operation blocks and call the ExportOperationData()
9633 method on each to allow each operation to export non-image data if
9634 they need to do so"""
9635 for operationName, operationInstance in self.mOperationBlocks.items():
9636 operationInstance.ExportOperationData(datadescription)
9637
9638 def WriteImages(self, datadescription):
9639 """go through all imageset blocks and plot blocks and have each of them
9640 write out their images"""
9641
9642 global gRenderingEnabled
9643 if gRenderingEnabled == False:
9644 if PhactoriDbg():
9645 myDebugPrint3("PhactoriPipeAndViewsState:WriteImages returning with noop because rendering is disabled\n")
9646 return
9647
9648 #since we are sharing a paraview RenderView instance, we need to go
9649 #through all the plots and imagesets and turn them all to invisible
9650 #so they can be made visible one at a time during the write image loop
9651
9652 #NOTE: when we change this it needs to work across multiple pipes
9653 #i.e. all pipes need to make selves invisible
9654 self.SetUpForWriteImageLoop()
9655
9656 for imagesetName, imagesetInstance in self.mImagesetBlocks.items():
9657 imagesetInstance.WriteImages(datadescription)
9658 for splotName, splotInstance in self.mScatterPlotBlocks.items():
9659 splotInstance.WriteImages(datadescription)
9660 for tplotName, tplotInstance in self.mPlotOverTimeBlocks.items():
9661 tplotInstance.WriteImages(datadescription)
9662
9663
9664 def SetUpForWriteImageLoop(self):
9665 """Since it turns out to be much more memory efficient to reuse a single
9666 render view rather than having one per image, this routine is called
9667 from WriteImages immediately before we start looping through the
9668 imagesets and plots to render images in order to basically set all
9669 paraview Representations to Visibility=0 so that we can turn them
9670 visible approriately as we do a WriteImage for each one."""
9671
9672 for imagesetName, imagesetInstance in self.mImagesetBlocks.items():
9673 imagesetInstance.ClearPvViewAndPvRepAfterWriteImage()
9674 for splotName, splotInstance in self.mScatterPlotBlocks.items():
9675 splotInstance.ClearPvViewAndPvRepAfterWriteImage()
9676 for tplotName, tplotInstance in self.mPlotOverTimeBlocks.items():
9677 tplotInstance.ClearPvViewAndPvRepAfterWriteImage()
9678
9679 def GetOperationReferredByJson(self, inOperationNameKey, inJsonDict):
9680 """utility function to get a reference to an operation instance given a
9681 dict (inJsonDict) which may (or may not) contain the key
9682 (inOperationNameKey) which tags the name of the operation to be
9683 found. If the key isn't there, we return mIncomingDefaultOperation,
9684 if the key grabs a name which isn't in mOperationBlocks, that is an
9685 exception"""
9686 if inOperationNameKey in inJsonDict:
9687 nameOfOperationToUse = inJsonDict[inOperationNameKey]
9688 if nameOfOperationToUse not in self.mOperationBlocks:
9689 errStr = ' in GetOperationReferredByJson operation with name ' +\
9690 str(nameOfOperationToUse) + ' does not exist\n'
9691 if PhactoriDbg():
9692 myDebugPrint3(errStr)
9693 raise Exception(errStr)
9694 returnOperation = self.mOperationBlocks[nameOfOperationToUse]
9695 else:
9696 returnOperation = self.mIncomingDefaultOperation
9697
9698 return returnOperation
9699
9700 def GetOperationReferredByJsonCrossPipe(self, inOperationNameKey, inJsonDict):
9701 """same as GetOperationReferredByJson(); however, if the operation is not
9702 in our self.mOperationBlocks, then we will also search all the other
9703 pipe and views state instances for the operation. If we find it, we
9704 will return it along with the pipe we found it in"""
9705 if inOperationNameKey in inJsonDict:
9706 nameOfOperationToUse = inJsonDict[inOperationNameKey]
9707 if nameOfOperationToUse in self.mOperationBlocks:
9708 #this operation is in our own operation blocks; return it and None
9709 #to follow the normal course of (non cross-pipe) operation
9710 returnOperation = self.mOperationBlocks[nameOfOperationToUse]
9711 returnPipe = None
9712 else:
9713 returnOperation = None
9714 returnPipe = None
9715 for onePipeKey, onePipe in gPhactoriPipeRootMap.items():
9716 if nameOfOperationToUse in onePipe.mOperationBlocks:
9717 #we found the operation in another pipe; return that and the other
9718 #pipe
9719 returnOperation = onePipe.mOperationBlocks[nameOfOperationToUse]
9720 returnPipe = onePipe
9721 break
9722 if returnOperation == None:
9723 #operation not found anywhere: this is fatal
9724 errStr = " in GetOperationReferredByJsonCrossPipe " +\
9725 "operation with name " +\
9726 str(nameOfOperationToUse) + " does not exist in any pipe\n"
9727 if PhactoriDbg():
9728 myDebugPrint3(errStr)
9729 raise Exception(errStr)
9730 else:
9731 #this code path requires an operation name, no implied default allowed
9732 errStr = " in GetOperationReferredByJsonCrossPipe " +\
9733 "requires specific operation name; no implied default allowed\n"
9734 if PhactoriDbg():
9735 myDebugPrint3(errStr)
9736 raise Exception(errStr)
9737
9738 return returnOperation, returnPipe
9739
9740 def GetOperationBlockByName(self, inName):
9741 if inName not in self.mOperationBlocks:
9742 myDebugPrint3AndException("PhactoriPipeAndViewsState:GetOperationBlockByName\n"
9743 "requesting paraview operation from nonexistent operation block: " + inName)
9744 return self.mOperationBlocks[inName]
9745
9746 def GetParaViewSourceByOperationName(self, inName):
9747 opBlock = self.GetOperationBlockByName(inName)
9748 pvSource = opBlock.GetPvFilter()
9749 if pvSource == None:
9750 myDebugPrint3AndException("PhactoriPipeAndViewsState:GetParaViewSourceByOperationName\n"
9751 "ParaView source is None for operation block: " + inName)
9752 return pvSource
9753
9754
9755 def PerRendersetInitialization(datadescription):
9756 """do setup necessary on a once-per insitu callback basis
9757
9758 There are some things that should be done once each time everything is
9759 rendered, particularly incrementing a callback counter so that we can keep
9760 track and do some things, such as getting data bounds, as few times as
9761 possible (i.e. don't get data bounds for an operation stage multiple times
9762 when once is sufficient)
9763 """
9764 global gPipeAndViewsState
9765 gPipeAndViewsState.mFrameTagCounter = gPipeAndViewsState.mFrameTagCounter + 1
9766 if PhactoriDbg(100):
9767 myDebugPrint3("-X-X-X-X- mFrameTagCounter now " + \
9768 str(gPipeAndViewsState.mFrameTagCounter) + " -X-X-X-X-\n", 100)
9769
9770 if PhactoriDbg():
9771 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
9772 pvsDi = paraviewSource.GetDataInformation()
9773 #pointDataInfo = paraviewSource.GetPointDataInformation()
9774 #cellDataInfo = paraviewSource.GetCellDataInformation()
9775 myDebugPrint3(" PerRendersetInitialization:\n num cells: " + str(pvsDi.GetNumberOfCells()) + "\n num points: " + str(pvsDi.GetNumberOfPoints()) + "\n")
9776
9777 #we assume to begin with that all global data bounds in operations are
9778 #invalid as data may have changed
9779 for oneOperationName, oneOperation in \
9780 gPipeAndViewsState.mOperationBlocks.items():
9781 oneOperation.mDataBoundsIsCurrent = False
9782
9783 #update the time tag in all views
9784 global gRenderingEnabled
9785 if gRenderingEnabled:
9786 global gSharedRenderView
9787 gSharedRenderView.ViewTime = datadescription.GetTime()
9788 else:
9789 if PhactoriDbg():
9790 myDebugPrint3("gSharedRenderView.ViewTime not set due to no rendering\n")
9791
9792 def UpdateRepresentationColorBy(ioPhactoriImagesetBlock):
9793 """given a para view representation and source and a phactori representation,
9794 set the color by variable in the paraview representation based on the
9795 phactori representation. Used to interactively change what the
9796 'color by' variable is between insitu callbacks"""
9797 if PhactoriDbg():
9798 myDebugPrint3("UpdateRepresentationColorBy entered\n")
9799
9800 for ii in range(0, len(ioPhactoriImagesetBlock.mVisibleReps)):
9801 oneVisOp = ioPhactoriImagesetBlock.mVisibleOps[ii]
9802 oneVisRep = ioPhactoriImagesetBlock.mVisibleReps[ii]
9803 oneVisPvDataRep = ioPhactoriImagesetBlock.mVisiblePvDataReps[ii]
9804 oneColorLegendRepRef = ioPhactoriImagesetBlock.mColorLegendRepRefs[ii]
9805 if oneVisRep != None:
9806 retVal = UpdateRepresentationColorBySub1(
9807 ioPhactoriImagesetBlock.mSharedPvRenderView2, oneVisPvDataRep,
9808 oneVisRep, oneVisOp, oneColorLegendRepRef)
9809 if oneColorLegendRepRef == None and retVal != None:
9810 if PhactoriDbg(100):
9811 myDebugPrint3("in PhactoriImagsetBlock named: " + \
9812 ioPhactoriImagesetBlock.mName + "\n" + \
9813 "mColorLegendRepRefs " + str(ii) +
9814 "is set to " + str(retVal) + "\n")
9815 ioPhactoriImagesetBlock.mColorLegendRepRefs[ii] = retVal
9816
9817 if PhactoriDbg():
9818 myDebugPrint3("UpdateRepresentationColorBy returning\n")
9819
9820 def UpdateRepresentationColorBySub1(inPvView, inPvRep,
9821 inPhactoriRep, inPhactoriOp, inColorLegendRepRef):
9822 if PhactoriDbg():
9823 myDebugPrint3("UpdateRepresentationColorBySub1 entered\n")
9824
9825 colorVarInfo = inPhactoriRep.mColorVariableInfo
9826
9827 if PhactoriDbg():
9828 myDebugPrint3("setting color by to:\n" + colorVarInfo.SelfToStr() + "\n")
9829
9830 colorVarName = colorVarInfo.mVariableName
9831 detectResult = colorVarInfo.DetectVariableType(
9832 inPhactoriOp.GetPvFilter(), True)
9833 if detectResult == False:
9834 if PhactoriDbg(100):
9835 myDebugPrint3('no detection: returning\n', 100)
9836 return None
9837
9838 if colorVarInfo.mVariableType == 'element':
9839 thePvVarType = gCellsString
9840 elif colorVarInfo.mVariableType == 'node':
9841 thePvVarType = gPointsString
9842 else:
9843 if PhactoriDbg(100):
9844 myDebugPrint3('bad element type: returning\n', 100)
9845 return None
9846
9847 if colorVarName != '':
9848 if inPhactoriRep.mColorVariableInfo.mVariableIsVectorComponent:
9849 ColorByVariableComponentOrMagnitudeXX(inPvRep, inPhactoriRep,
9850 colorVarName, 'Component', colorVarInfo.mVariableComponent,
9851 thePvVarType, inPhactoriRep.mColorMapSettings)
9852 if colorVarInfo.mVariableComponent == 0:
9853 componentString = "X"
9854 elif colorVarInfo.mVariableComponent == 1:
9855 componentString = "Y"
9856 elif colorVarInfo.mVariableComponent == 2:
9857 componentString = "Z"
9858 else:
9859 componentString = str(colorVarInfo.mVariableComponent)
9860 elif inPhactoriRep.mColorVariableInfo.mVariableIsVectorMagnitude:
9861 ColorByVariableComponentOrMagnitudeXX(inPvRep, inPhactoriRep,
9862 colorVarName, 'Magnitude', colorVarInfo.mVariableComponent,
9863 thePvVarType, inPhactoriRep.mColorMapSettings)
9864 componentString = "Magnitude"
9865 else:
9866 ColorByVariableScalarXX(inPvRep, inPhactoriRep, colorVarName,
9867 thePvVarType, inPhactoriRep.mColorMapSettings)
9868 componentString = ""
9869
9870 #update the color legend widget
9871 if inPhactoriRep.mColorLegendFlag:
9872 onoffFlagString = 'on'
9873 else:
9874 onoffFlagString = 'off'
9875 retVal = ShowDataColorLegendXX(inPvView, onoffFlagString,
9876 inPhactoriRep.mColorLegendPositionAndSize, inPhactoriRep.mColorSettings,
9877 inColorLegendRepRef, inPvRep, componentString)
9878
9879 if PhactoriDbg():
9880 myDebugPrint3("UpdateRepresentationColorBySub1 returning\n")
9881
9882 return retVal
9883
9884 def DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState):
9885 """used by process zero (broadcast send process) as well as other processes
9886 (broadcast recieve processes) to actually take the info in json format
9887 and set the system up for proper behavior after restart, particularly
9888 data ranges and plots over time"""
9889 #go through representations and have each add it's state info to jsonOut
9890 if "RepresentationsRestartInfo" not in jsonIn:
9891 if PhactoriDbg():
9892 myDebugPrint3("StartOfVisualizationCallback returning, no rep info\n")
9893 return
9894
9895 representationsJsonIn = jsonIn["RepresentationsRestartInfo"]
9896 for oneRepName, oneRep in \
9897 ioPipeAndViewsState.mRepresentationBlocks.items():
9898 if oneRepName in representationsJsonIn:
9899 if PhactoriDbg():
9900 myDebugPrint3("restart setup callback json for rep: " + oneRepName + "\n")
9901 oneRep.SetFromRestartInfo(representationsJsonIn[oneRepName])
9902 else:
9903 if PhactoriDbg():
9904 myDebugPrint3("warning: Representation named " + oneRepName +
9905 " not in restart info")
9906
9907 plotsOverTimeJsonIn = jsonIn["PlotsOverTimeRestartInfo"]
9908 for onePlotOtName, onePlotOt in \
9909 ioPipeAndViewsState.mPlotOverTimeBlocks.items():
9910 if onePlotOtName in plotsOverTimeJsonIn:
9911 if PhactoriDbg():
9912 myDebugPrint3("plot over time setup callback json for rep: " + \
9913 onePlotOtName + "\n")
9914 onePlotOt.SetFromRestartInfo(plotsOverTimeJsonIn[onePlotOtName])
9915 else:
9916 if PhactoriDbg():
9917 myDebugPrint3("warning: plot over time named " + onePlotOtName +
9918 " not in restart info")
9919
9920
9921 def HandleRestartUpdateProcessZero(ioPipeAndViewsState):
9922 if PhactoriDbg():
9923 myDebugPrint3("HandleRestartUpdateProcessZero entered\n")
9924 #import pdb
9925 #pdb.set_trace()
9926
9927 #broadcast for full multiprocess functionality
9928 #color range needs no broadcast, as that will be managed when color range
9929 #calculated for the next frame (process 1 will share the maxes and mins
9930 #it has)
9931 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
9932 globalController = pm.GetGlobalController()
9933
9934 #try to read file written (presumably last restart place)
9935 #and convert to json with expected string type
9936 validDataIsAvailableToBroadcast = True
9937 try:
9938 #read map/json from file
9939 import os
9940
9941 restartInfoFilename = ioPipeAndViewsState.mDefaultBasedirectory + \
9942 os.sep + ioPipeAndViewsState.mBlockIdForRestart + ".phrs"
9943
9944 inFile = open(restartInfoFilename, "rb")
9945 jsonIn = json.load(inFile)
9946 inFile.close()
9947 jsonIn = convertJsonUnicodeToStrings(jsonIn)
9948
9949 except:
9950 if PhactoriDbg():
9951 myDebugPrint3("no info file to read or json failed\n")
9952 #need to broadcast to non-zero processes that there is no info--we
9953 #do this by indicating a length of zero
9954 validDataIsAvailableToBroadcast = False
9955
9956 if validDataIsAvailableToBroadcast:
9957 try:
9958 DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState)
9959 except:
9960 if PhactoriDbg():
9961 myDebugPrint3("exception trying to use info for setting\n")
9962 validDataIsAvailableToBroadcast = False
9963
9964 #if no valid data is available (either no file read or bad data), send
9965 #indicator to other processes by sending 0 data size
9966 if validDataIsAvailableToBroadcast == False:
9967 if PhactoriDbg():
9968 myDebugPrint3("no valid restart data to send, send signal of no data\n")
9969 vtkInfoBufferSizeArray = vtk.vtkIntArray()
9970 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
9971 vtkInfoBufferSizeArray.SetValue(0, 0)
9972 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
9973 if PhactoriDbg():
9974 myDebugPrint3("HandleRestartUpdateProcessZero returning 2\n")
9975 return
9976
9977 try:
9978
9979 outStr = json.dumps(jsonIn)
9980
9981 numberOfValues = len(outStr)
9982
9983 if PhactoriDbg():
9984 myDebugPrint3("valid restart data to send. Sending size: " + \
9985 str(numberOfValues) + "\n")
9986 #send size of data buffer first
9987 vtkInfoBufferSizeArray = vtk.vtkIntArray()
9988 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
9989 vtkInfoBufferSizeArray.SetValue(0, numberOfValues)
9990 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
9991
9992 if PhactoriDbg():
9993 myDebugPrint3("now sending data\n")
9994 #now fill out data and send it
9995 vtkOutArray = vtk.vtkCharArray()
9996 vtkOutArray.SetNumberOfTuples(numberOfValues)
9997 for jj in range(0, numberOfValues):
9998 vtkOutArray.SetValue(jj, outStr[jj])
9999
10000 globalController.Broadcast(vtkOutArray, 0)
10001
10002 if PhactoriDbg():
10003 myDebugPrint3("done sending data\n")
10004 except:
10005 #broadcast error; not really recoverable;
10006 if PhactoriDbg():
10007 myDebugPrint3("exception trying to broadcast\n")
10008 if PhactoriDbg():
10009 myDebugPrint3("HandleRestartUpdateProcessZero returning 4\n")
10010 return
10011
10012 if PhactoriDbg():
10013 myDebugPrint3("HandleRestartUpdateProcessZero returning\n")
10014
10015
10016 def HandleRestartUpdateProcessNotZero(ioPipeAndViewsState):
10017
10018 if PhactoriDbg():
10019 myDebugPrint3("HandleRestartUpdateProcessNotZero entered\n")
10020
10021 try:
10022 #do broadcast (receive from process 0) to receive update data
10023 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
10024 globalController = pm.GetGlobalController()
10025
10026 if PhactoriDbg():
10027 myDebugPrint3("trying to receive data buffer length")
10028
10029 #first, get size of data. If it is zero, we are done and there won't be
10030 #another broadcast
10031 vtkInfoBufferSizeArray = vtk.vtkIntArray()
10032 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
10033 #vtkInfoBufferSizeArray.SetValue(0, 0)
10034 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
10035 bufferLen = vtkInfoBufferSizeArray.GetTuple1(0)
10036 if bufferLen == 0:
10037 if PhactoriDbg():
10038 myDebugPrint3("broadcast indicated 0 data, so we are done\n")
10039 if PhactoriDbg():
10040 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 2\n")
10041 return;
10042
10043 if PhactoriDbg():
10044 myDebugPrint3("buffer length: " + str(bufferLen) + \
10045 ", now trying to receive data\n")
10046 #first go round, fixed buffer length, next expandable if necessary
10047 vtkOutArray = vtk.vtkCharArray()
10048 vtkOutArray.SetNumberOfTuples(bufferLen)
10049 #for jj in range(0, bufferLen):
10050 # vtkOutArray.SetValue(jj, 0)
10051
10052 #receive broadcast of info from process 0
10053 globalController.Broadcast(vtkOutArray, 0)
10054 if PhactoriDbg():
10055 myDebugPrint3("data received successfully\n")
10056 except:
10057 #broadcast error; not really recoverable;
10058 if PhactoriDbg():
10059 myDebugPrint3("exception trying to receive broadcast\n")
10060 if PhactoriDbg():
10061 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 2\n")
10062 return
10063
10064 try:
10065 if PhactoriDbg():
10066 myDebugPrint3("converting data to json format string\n")
10067 #convert to json-format string
10068 jsonCharList = []
10069 for ii in range(0, bufferLen):
10070 oneChar = vtkOutArray.GetTuple1(ii)
10071 jsonCharList.append(oneChar)
10072
10073 jsonInString = "".join(jsonCharList)
10074
10075 if PhactoriDbg():
10076 myDebugPrint3("json received from broadcast (converted to string):\n" +
10077 jsonInString)
10078
10079 #convert json format string to python dict
10080 jsonIn = json.loads(jsonInString)
10081
10082 if PhactoriDbg():
10083 myDebugPrint3("json received from broadcast (converted to dict):\n" +
10084 str(jsonIn))
10085
10086 #use info to set up for post-restart (color ranges, time plots, etc.)
10087 DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState)
10088
10089 except:
10090 #broadcast error; not really recoverable;
10091 if PhactoriDbg():
10092 myDebugPrint3("exception trying to use broadcast info as json set info\n")
10093 if PhactoriDbg():
10094 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 3\n")
10095 return
10096
10097 if PhactoriDbg():
10098 myDebugPrint3("HandleRestartUpdateProcessNotZero returning\n")
10099
10100
10101 def HandleRestartUpdateForOutputResultsBlock(ioPipeAndViewsState):
10102 """this method is a companion to SaveRestartInfoCallback. It is called
10103 after the pipeline is first initialized for the given output block, and
10104 it will read the data stored by SaveRestartInfoCallback in a file.
10105 The presumption is that the pipeline will be initialized for the
10106 given output block only once when the system starts or only once
10107 when the system restarts.
10108 The intent is to deal with restart by allowing persistent
10109 information across restarts. See SaveRestartInfoCallback."""
10110 if PhactoriDbg():
10111 myDebugPrint3("HandleRestartUpdateForOutputResultsBlock entered\n")
10112
10113 #we need to behave differently for process 0 and other processes; process 0
10114 #needs to read the file and, if necessary, broadcast info to other
10115 #processes, while other processes need to receive info broadcast from 0, if
10116 #necessary
10117 if SmartGetLocalProcessId() == 0:
10118 HandleRestartUpdateProcessZero(ioPipeAndViewsState)
10119 else:
10120 HandleRestartUpdateProcessNotZero(ioPipeAndViewsState)
10121
10122
10123 if PhactoriDbg():
10124 myDebugPrint3("HandleRestartUpdateForOutputResultsBlock returning\n")
10125
10126
10127 def SaveRestartInfoCallback():
10128 """this method is called back at the tail end of the visualization
10129 from the simulation. The purpose of this function is to collect and
10130 save out information which is necessary for a restart to have the
10131 restart begin in the same state as if the simulation had run to this
10132 point. Items include things such as
10133 recording color range mins and maxes and data values in plots over time
10134 so that they can be correctly restarted in the case of a simulation
10135 restart"""
10136
10137 if PhactoriDbg():
10138 myDebugPrint3("SaveRestartInfoCallback entered\n")
10139 #only process zero gets to write anything out: info should have already
10140 #been shared appropriately to process zero and we don't want every process
10141 #hitting the disk
10142 if SmartGetLocalProcessId() != 0:
10143 if PhactoriDbg():
10144 myDebugPrint3("SaveRestartInfoCallback returning, not process zero\n")
10145 return
10146
10147 #we construct a json-format/python map style data item which we will save
10148 #out to a file. We start with a blank map and allow each image set and
10149 #plot over time to add stuff to it. Then we write it out to a file.
10150
10151 jsonOut = {}
10152 global gPipeAndViewsState
10153
10154 #go through representations and have each add it's state info to jsonOut
10155 representationsJsonOut = {}
10156 for oneRepName, oneRep in \
10157 gPipeAndViewsState.mRepresentationBlocks.items():
10158 if PhactoriDbg():
10159 myDebugPrint3("making end vis callback json for rep: " + oneRepName + "\n")
10160 representationsJsonOut[oneRepName] = oneRep.GetRestartInfo()
10161
10162 jsonOut['RepresentationsRestartInfo'] = \
10163 representationsJsonOut
10164
10165 #go through plots over time and have each add it's state info to jsonOut
10166 plotsOverTimeJsonOut = {}
10167 for onePlotOtName, onePlotOt in \
10168 gPipeAndViewsState.mPlotOverTimeBlocks.items():
10169 if PhactoriDbg():
10170 myDebugPrint3("making end vis callback json for plot over time: " +
10171 onePlotOtName + "\n")
10172 plotsOverTimeJsonOut[onePlotOtName] = onePlotOt.GetRestartInfo()
10173
10174 jsonOut['PlotsOverTimeRestartInfo'] = plotsOverTimeJsonOut
10175
10176 #write info to file
10177
10178 import os
10179 restartInfoFilename = gPipeAndViewsState.mDefaultBasedirectory + \
10180 os.sep + gPipeAndViewsState.mBlockIdForRestart + ".phrs"
10181
10182 outStr = json.dumps(jsonOut, sort_keys=True,
10183 indent = 2, separators=(',', ': '))
10184 outFile = open(restartInfoFilename, 'w+b')
10185 outFile.write(outStr)
10186 outFile.close()
10187
10188 if PhactoriDbg():
10189 myDebugPrint3("SaveRestartInfoCallback returning\n")
10190
10191 def UpdateOneImagesetViewsWhichMayChangeWithData(ioImageset):
10192 if PhactoriDbg(100):
10193 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData entered\n", 100)
10194
10195 global gRenderingEnabled
10196 if gRenderingEnabled == False:
10197 if PhactoriDbg():
10198 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData returning with noop because rendering is disabled\n")
10199 return
10200
10201 theCamera = ioImageset.mCamera
10202
10203 #this is a bit hacky--we should probably update the para view sources when
10204 #we update operations, which we aren't doing separately yet
10205 #theParaViewSource = ioImageset.mOperation.GetPvFilter()
10206 theParaViewSource = ioImageset.mOperation.GetOutgoingPvGeometryFilter()
10207
10208 UpdatePipelineWithCurrentTimeArgument(theParaViewSource)
10209
10210 UpdateRepresentationColorBy(ioImageset)
10211
10212 if theCamera.MayChangeWithData() == False:
10213 if PhactoriDbg():
10214 myDebugPrint3(" camera: " + theCamera.mName + " imageset: " + ioImageset.mName + " is set to not change with data \n")
10215 return
10216
10217 #it no longer makes sense to loop through and set stuff up here, as
10218 #we will do it right before we call WriteImage
10219 #for xx in ioImageset.mParaViewRenderInfoCs:
10220 # if PhactoriDbg():
10221 # myDebugPrint3(" renderview.CameraPosition before: " + str(xx.mParaViewInfo.RenderView1.CameraPosition) + "\n")
10222 # lookDirectionToUse = xx.mLookDirection
10223 # if theCamera.mType == 'camera':
10224 # lookDirectionToUse = theCamera.mLookDirection
10225 # if PhactoriDbg():
10226 # myDebugPrint3(" camera: " + theCamera.mName + " imageset: " + ioImageset.mName + " look dir: " + str(lookDirectionToUse) + "\n")
10227 # SetParaViewRepresentationCameraParams(xx.mParaViewInfo.RenderView1, theCamera, lookDirectionToUse, ioImageset.mImageSettings, theParaViewSource)
10228 # if PhactoriDbg():
10229 # myDebugPrint3(" renderview.CameraPosition after : " + str(xx.mParaViewInfo.RenderView1.CameraPosition) + "\n")
10230
10231 if PhactoriDbg(100):
10232 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData returning\n", 100)
10233 #SetActiveSource(savedActiveSource)
10234
10235 def UpdateAllOperationsWhichMayChangeWithData():
10236 if PhactoriDbg(100):
10237 myDebugPrint3("UpdateAllOperationsWhichMayChangeWithData entered\n", 100)
10238 global gPipeAndViewsState
10239 for oneOperationName, oneOperation in gPipeAndViewsState.mOperationBlocks.items():
10240 oneOperation.DoUpdateDueToChangeInData(gPipeAndViewsState)
10241 if PhactoriDbg(100):
10242 myDebugPrint3("UpdateAllOperationsWhichMayChangeWithData returning\n", 100)
10243
10244 def UpdateAllImagesetViewsWhichMayChangeWithData():
10245 if PhactoriDbg(100):
10246 myDebugPrint3("UpdateAllImagesetViewsWhichMayChangeWithData entered\n", 100)
10247 global gPipeAndViewsState
10248 for oneImagesetName, oneImageset in gPipeAndViewsState.mImagesetBlocks.items():
10249 if PhactoriDbg(100):
10250 myDebugPrint3("doing UpdateOneImagesetViewsWhichMayChangeWithData for imageset named:" + oneImagesetName + "\n", 100)
10251 if PhactoriDbg(100):
10252 myDebugPrint3(" doing oneImageset.HandleShowAxesWithEmptyDataParaViewIssue\n", 100)
10253 oneImageset.HandleShowAxesWithEmptyDataParaViewIssue()
10254 if PhactoriDbg(100):
10255 myDebugPrint3(" returned from oneImageset.HandleShowAxesWithEmptyDataParaViewIssue\n", 100)
10256 UpdateOneImagesetViewsWhichMayChangeWithData(oneImageset)
10257 if PhactoriDbg(100):
10258 myDebugPrint3("did UpdateOneImagesetViewsWhichMayChangeWithData for imageset named:" + oneImagesetName + "\n", 100)
10259 if PhactoriDbg(100):
10260 myDebugPrint3("UpdateAllImagesetViewsWhichMayChangeWithData returning\n", 100)
10261
10262 def HandleOperationShortcuts2(inBlockName, inJson, ioOperationBlocks, inCount):
10263 if PhactoriDbg(100):
10264 myDebugPrint3('HandleOperationShortcuts entered2\n', 100)
10265
10266 lastShortcutOperationName = None
10267
10268 opSuffix = str(inCount)
10269
10270 if "threshold" in inJson:
10271 stuff = inJson["threshold"]
10272 if len(stuff) != 4:
10273 errStr = 'HandleOperationShortcuts2 threshold shortcut bad stuff, not 4 items\n'
10274 if PhactoriDbg():
10275 myDebugPrint3(errStr)
10276 raise Exception(errStr)
10277 #stuff should have 4 items
10278 #[scalar|vector magnitude|vector component|tensor
10279 #component, component<variable name>, namekeep between|keep above|keep
10280 #below, [<val1>, <val2>]]
10281 newOperationJson = {}
10282 newOperationJson["type"] = "threshold"
10283 varkey = "variable " + stuff[0]
10284 newOperationJson[varkey] = stuff[1]
10285 thresholdValues = stuff[3]
10286 if stuff[2] == "keep between":
10287 newOperationJson["keep between"] = thresholdValues
10288 elif stuff[2] == "keep below":
10289 newOperationJson["keep below"] = thresholdValues[0]
10290 elif stuff[2] == "keep above":
10291 newOperationJson["keep above"] = thresholdValues[0]
10292 else:
10293 errStr = 'HandleOperationShortcuts2 bad stuff[2], not keep above|below|between\n'
10294 if PhactoriDbg():
10295 myDebugPrint3(errStr)
10296 raise Exception(errStr)
10297
10298 if PhactoriDbg():
10299 myDebugPrint3('got threshold operation shortcut ' + str(newOperationJson) + '\n')
10300 if lastShortcutOperationName != None:
10301 newOperationJson["input"] = lastShortcutOperationName
10302 lastShortcutOperationName = "thresholdshortcutoperation" + opSuffix
10303 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
10304
10305
10306 if "boxclip" in inJson:
10307 stuff = inJson["boxclip"]
10308 if len(stuff) != 3:
10309 errStr = 'HandleOperationShortcuts2 boxclip shortcut bad stuff, not 3 items\n'
10310 if PhactoriDbg():
10311 myDebugPrint3(errStr)
10312 raise Exception(errStr)
10313 center = stuff[0]
10314 extents = stuff[1]
10315 insideOrOutside = stuff[2]
10316
10317 newOperationJson = {}
10318 newOperationJson["type"] = "boxclip"
10319 newOperationJson["center at absolute point"] = center
10320 newOperationJson["absolute extents"] = extents
10321 if insideOrOutside == "keep inside box":
10322 newOperationJson["keep inside box"] = True
10323 elif insideOrOutside == "keep outside box":
10324 newOperationJson["keep inside box"] = False
10325 else:
10326 newOperationJson["keep inside box"] = True
10327
10328 if PhactoriDbg():
10329 myDebugPrint3('got boxclip operation shortcut ' + str(newOperationJson) + '\n')
10330 if lastShortcutOperationName != None:
10331 newOperationJson["input"] = lastShortcutOperationName
10332 lastShortcutOperationName = "boxclipshortcutoperation" + opSuffix
10333 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
10334
10335 if "clip" in inJson:
10336 stuff = inJson["clip"]
10337 if len(stuff) != 2:
10338 errStr = 'HandleOperationShortcuts2 clip shortcut bad stuff, not 2 items\n'
10339 if PhactoriDbg():
10340 myDebugPrint3(errStr)
10341 raise Exception(errStr)
10342 pointOnPlane = stuff[0]
10343 planeNormal = stuff[1]
10344 if PhactoriDbg():
10345 myDebugPrint3('got clip operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\n')
10346 newOperationJson = {"type":"clip", "absolute point on plane":pointOnPlane, "plane normal":planeNormal}
10347 if lastShortcutOperationName != None:
10348 newOperationJson["input"] = lastShortcutOperationName
10349 lastShortcutOperationName = "clipshortcutoperation" + opSuffix
10350 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
10351
10352 if "contour" in inJson:
10353 stuff = inJson["contour"]
10354 if len(stuff) != 4:
10355 errStr = 'HandleOperationShortcuts2 contour shortcut bad stuff, not 4 items\n'
10356 if PhactoriDbg():
10357 myDebugPrint3(errStr)
10358 raise Exception(errStr)
10359 variableInfo = stuff[0]
10360 variableName = stuff[1]
10361 valueListOrSequence = stuff[2]
10362 contourValues = stuff[3]
10363 newOperationJson = {}
10364 newOperationJson["type"] = "contour"
10365 varkey = "variable " + variableInfo
10366 newOperationJson[varkey] = variableName
10367 if (valueListOrSequence.lower()=="value list"):
10368 newOperationJson["contour value"] = contourValues
10369 elif (valueListOrSequence.lower()=="value sequence"):
10370 newOperationJson["contour value sequence"]=contourValues
10371 else:
10372 errStr = """error! contour shortcut did not contain 'value list' or 'value sequence' in
10373 HandleOperationShortcuts2\n"""
10374 if PhactoriDbg():
10375 myDebugPrint3(errStr)
10376 raise Exception(errStr)
10377 if lastShortcutOperationName != None:
10378 newOperationJson["input"] = lastShortcutOperationName
10379 lastShortcutOperationName = "contourshortcutoperation" + opSuffix
10380 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
10381
10382 if "slice" in inJson:
10383 stuff = inJson["slice"]
10384 if len(stuff) != 2:
10385 errStr = 'HandleOperationShortcuts2 slice shortcut bad stuff, not 2 items\n'
10386 if PhactoriDbg():
10387 myDebugPrint3(errStr)
10388 raise Exception(errStr)
10389 pointOnPlane = stuff[0]
10390 planeNormal = stuff[1]
10391 if PhactoriDbg():
10392 myDebugPrint3('got slice operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\n')
10393 newOperationJson = {"type":"slice", "absolute point on plane":pointOnPlane, "plane normal":planeNormal}
10394 if lastShortcutOperationName != None:
10395 newOperationJson["input"] = lastShortcutOperationName
10396 lastShortcutOperationName = "sliceshortcutoperation" + opSuffix
10397 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
10398
10399 if lastShortcutOperationName != None:
10400 inJson["operation"] = lastShortcutOperationName
10401 if PhactoriDbg(100):
10402 myDebugPrint3('HandleOperationShortcuts returning\n', 100)
10403
10404 #go through imageset json, and locate operation shortcuts. If found, create
10405 #json defintion of operations and add them to the structure for later
10406 #creation, and add reference to the new operations in the imageblock json
10407 def HandleOperationShortcuts(ioImagesetBlocks, ioOperationBlocks):
10408 if PhactoriDbg(100):
10409 myDebugPrint3('HandleOperationShortcuts entered\n', 100)
10410 count = 0
10411 for blockName, blockParamsJson in ioImagesetBlocks.items():
10412 count = count + 1
10413 HandleOperationShortcuts2(blockName, blockParamsJson, ioOperationBlocks, count)
10414 if PhactoriDbg(100):
10415 myDebugPrint3('HandleOperationShortcuts returning\n', 100)
10416 return count
10417
10418 def ConstructAndAddPlotsOverTimeJson(outPlotOverTimeJsonBlocks, inJsonToCopy,
10419 inYAxisVariableName, inNumComponents):
10420 """helper function for TestForAndConstructAllPlotsOverTime, creates a
10421 PlotOverTime json block, not for external use"""
10422
10423 global gPipeAndViewsState
10424 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
10425 imageSetCount = gPipeAndViewsState.mImageSetCounter
10426
10427 if 'plot basename' in inJsonToCopy:
10428 extraNameString = inJsonToCopy['plot basename']
10429 else:
10430 extraNameString = ''
10431 if inNumComponents != 3:
10432 newPlotOverTimeJson = inJsonToCopy.copy()
10433 newPlotOverTimeJson['all variables'] = False
10434 plotName = extraNameString + inYAxisVariableName + ".b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
10435 newPlotOverTimeJson['plot basename'] = plotName
10436 newPlotOverTimeJson['variable scalar'] = inYAxisVariableName
10437 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
10438 if PhactoriDbg():
10439 myDebugPrint3('added block named ' + plotName + ': ' + \
10440 str(newPlotOverTimeJson) + '\n')
10441 else:
10442 newPlotOverTimeJson = inJsonToCopy.copy()
10443 newPlotOverTimeJson['all variables'] = False
10444 plotName = extraNameString + inYAxisVariableName + "x.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
10445 newPlotOverTimeJson['plot basename'] = plotName
10446 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'x'
10447 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
10448 if PhactoriDbg():
10449 myDebugPrint3('added block named ' + plotName + ': ' + \
10450 str(newPlotOverTimeJson) + '\n')
10451 newPlotOverTimeJson = inJsonToCopy.copy()
10452 newPlotOverTimeJson['all variables'] = False
10453 plotName = extraNameString + inYAxisVariableName + "y.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
10454 newPlotOverTimeJson['plot basename'] = plotName
10455 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'y'
10456 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
10457 if PhactoriDbg():
10458 myDebugPrint3('added block named ' + plotName + ': ' + \
10459 str(newPlotOverTimeJson) + '\n')
10460 newPlotOverTimeJson = inJsonToCopy.copy()
10461 newPlotOverTimeJson['all variables'] = False
10462 plotName = extraNameString + inYAxisVariableName + "z.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
10463 newPlotOverTimeJson['plot basename'] = plotName
10464 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'z'
10465 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
10466 if PhactoriDbg():
10467 myDebugPrint3('added block named ' + plotName + ': ' + \
10468 str(newPlotOverTimeJson) + '\n')
10469 newPlotOverTimeJson = inJsonToCopy.copy()
10470 newPlotOverTimeJson['all variables'] = False
10471 plotName = extraNameString + inYAxisVariableName + "mag.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
10472 newPlotOverTimeJson['plot basename'] = plotName
10473 lenToGrab = len(inYAxisVariableName) - len(GetSeparatorString())
10474 magVarName = inYAxisVariableName[0:lenToGrab]
10475 newPlotOverTimeJson['variable vector magnitude'] = magVarName
10476 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
10477 if PhactoriDbg():
10478 myDebugPrint3('added block named ' + plotName + ': ' + \
10479 str(newPlotOverTimeJson) + '\n')
10480
10481
10482 def ConstructAndAddScatterPlotsJson(outScatterPlotJsonBlocks, inJsonToCopy,
10483 inYAxisVariableName, inNumComponents, inXAxisVariableName):
10484 """helper function for TestForAndConstructAllScatterPlots, creates a
10485 scatterplot json block, not for external use"""
10486
10487 global gPipeAndViewsState
10488 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
10489 imageSetCount = gPipeAndViewsState.mImageSetCounter
10490
10491 if 'plot basename' in inJsonToCopy:
10492 extraNameString = inJsonToCopy['plot basename']
10493 else:
10494 extraNameString = ''
10495 if inNumComponents != 3:
10496 newScatterPlotJson = inJsonToCopy.copy()
10497 newScatterPlotJson['all variables'] = False
10498 plotName = extraNameString + inYAxisVariableName + ".b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
10499 newScatterPlotJson['plot basename'] = plotName
10500 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
10501 newScatterPlotJson['y axis variable scalar'] = inYAxisVariableName
10502 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
10503 if PhactoriDbg():
10504 myDebugPrint3('added block named ' + plotName + ': ' + \
10505 str(newScatterPlotJson) + '\n')
10506 else:
10507 newScatterPlotJson = inJsonToCopy.copy()
10508 newScatterPlotJson['all variables'] = False
10509 plotName = extraNameString + inYAxisVariableName + "x.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
10510 newScatterPlotJson['plot basename'] = plotName
10511 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
10512 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'x'
10513 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
10514 if PhactoriDbg():
10515 myDebugPrint3('added block named ' + plotName + ': ' + \
10516 str(newScatterPlotJson) + '\n')
10517 newScatterPlotJson = inJsonToCopy.copy()
10518 newScatterPlotJson['all variables'] = False
10519 plotName = extraNameString + inYAxisVariableName + "y.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
10520 newScatterPlotJson['plot basename'] = plotName
10521 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
10522 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'y'
10523 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
10524 if PhactoriDbg():
10525 myDebugPrint3('added block named ' + plotName + ': ' + \
10526 str(newScatterPlotJson) + '\n')
10527 newScatterPlotJson = inJsonToCopy.copy()
10528 newScatterPlotJson['all variables'] = False
10529 plotName = extraNameString + inYAxisVariableName + "z.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
10530 newScatterPlotJson['plot basename'] = plotName
10531 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
10532 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'z'
10533 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
10534 if PhactoriDbg():
10535 myDebugPrint3('added block named ' + plotName + ': ' + \
10536 str(newScatterPlotJson) + '\n')
10537 newScatterPlotJson = inJsonToCopy.copy()
10538 newScatterPlotJson['all variables'] = False
10539 plotName = extraNameString + inYAxisVariableName + "mag.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
10540 newScatterPlotJson['plot basename'] = plotName
10541 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
10542 lenToGrab = len(inYAxisVariableName) - len(GetSeparatorString())
10543 magVarName = inYAxisVariableName[0:lenToGrab]
10544 newScatterPlotJson['y axis variable vector magnitude'] = magVarName
10545 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
10546 if PhactoriDbg():
10547 myDebugPrint3('added block named ' + plotName + ': ' + \
10548 str(newScatterPlotJson) + '\n')
10549
10550 def TestForAndConstructAllPlotsOverTime(ioPlotOverTimeBlocksJson):
10551 """tests to see if a scatterplot block contains "all variables": true and,
10552 if so, construct a scatterplot block for each variable"""
10553 if PhactoriDbg(100):
10554 myDebugPrint3('TestForAndConstructAllPlotsOverTime entered\n', 100)
10555 potBlocks = ioPlotOverTimeBlocksJson
10556 blocksToPop = []
10557 constructAllVariablesFlag = False
10558 for blockName, blockParamsJson in potBlocks.items():
10559 if PhactoriDbg():
10560 myDebugPrint3("testing block named " + blockName + " for all variables\n")
10561 if PhactoriDbg():
10562 myDebugPrint3(" json is: " + str(blockParamsJson) + "\n")
10563 testVal = getParameterFromBlock(blockParamsJson, "all variables", False)
10564 if testVal == True:
10565 constructAllVariablesFlag = True
10566 blockToPop = blockName
10567 blockToCopy = blockParamsJson
10568 #there should be only one like this
10569 break
10570
10571 if constructAllVariablesFlag == False:
10572 #don't construct all variables
10573 if PhactoriDbg(100):
10574 myDebugPrint3('TestForAndConstructAllPlotsOverTime returning, no all variables\n', 100)
10575 return
10576
10577 global gPipeAndViewsState
10578 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
10579 pointDataInfo = paraviewSource.GetPointDataInformation()
10580 cellDataInfo = paraviewSource.GetCellDataInformation()
10581 fieldDataInfo = paraviewSource.GetFieldDataInformation()
10582
10583 numPointArrays = pointDataInfo.GetNumberOfArrays()
10584 for ii in range(numPointArrays):
10585 pointArray = pointDataInfo.GetArray(ii)
10586 pointArrayName = pointArray.GetName()
10587 if pointArrayName != "GlobalNodeId":
10588 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
10589 pointArrayName, pointArray.GetNumberOfComponents())
10590 numCellArrays = cellDataInfo.GetNumberOfArrays()
10591 for ii in range(numCellArrays):
10592 cellArray = cellDataInfo.GetArray(ii)
10593 cellArrayName = cellArray.GetName()
10594 if cellArrayName != "GlobalElementId":
10595 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
10596 cellArray.GetName(), cellArray.GetNumberOfComponents())
10597 numFieldArrays = fieldDataInfo.GetNumberOfArrays()
10598 for ii in range(numFieldArrays):
10599 fieldArray = fieldDataInfo.GetArray(ii)
10600 fieldArrayName = fieldArray.GetName()
10601 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
10602 fieldArray.GetName(), fieldArray.GetNumberOfComponents())
10603
10604 gPipeAndViewsState.mImageSetCounter += 1
10605
10606 potBlocks.pop(blockToPop, None)
10607
10608 if PhactoriDbg(100):
10609 myDebugPrint3('TestForAndConstructAllPlotsOverTime returning\n', 100)
10610
10611
10612 def TestForAndConstructAllScatterPlots(ioScatterPlotBlocksJson):
10613 """tests to see if a scatterplot block contains "all variables": true and,
10614 if so, construct a scatterplot block for each variable"""
10615 if PhactoriDbg(100):
10616 myDebugPrint3('TestForAndConstructAllScatterPlots entered\n', 100)
10617 spBlocks = ioScatterPlotBlocksJson
10618 blocksToPop = []
10619 constructAllVariablesFlag = False
10620 for blockName, blockParamsJson in spBlocks.items():
10621 if PhactoriDbg():
10622 myDebugPrint3("testing block named " + blockName + " for all variables\n")
10623 if PhactoriDbg():
10624 myDebugPrint3(" json is: " + str(blockParamsJson) + "\n")
10625 testVal = getParameterFromBlock(blockParamsJson, "all variables", False)
10626 if testVal == True:
10627 constructAllVariablesFlag = True
10628 blockToPop = blockName
10629 blockToCopy = blockParamsJson
10630 #there should be only one like this
10631 break
10632
10633 if constructAllVariablesFlag == False:
10634 #don't construct all variables
10635 if PhactoriDbg(100):
10636 myDebugPrint3('TestForAndConstructAllScatterPlots returning, no all variables\n', 100)
10637 return
10638
10639 global gPipeAndViewsState
10640 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
10641 pointDataInfo = paraviewSource.GetPointDataInformation()
10642 cellDataInfo = paraviewSource.GetCellDataInformation()
10643
10644 numPointArrays = pointDataInfo.GetNumberOfArrays()
10645 for ii in range(numPointArrays):
10646 pointArray = pointDataInfo.GetArray(ii)
10647 pointArrayName = pointArray.GetName()
10648 if pointArrayName != "GlobalNodeId":
10649 ConstructAndAddScatterPlotsJson(spBlocks, blockToCopy,
10650 pointArrayName, pointArray.GetNumberOfComponents(),
10651 "GlobalNodeId")
10652 numCellArrays = cellDataInfo.GetNumberOfArrays()
10653 for ii in range(numCellArrays):
10654 cellArray = cellDataInfo.GetArray(ii)
10655 cellArrayName = cellArray.GetName()
10656 if cellArrayName != "GlobalElementId":
10657 ConstructAndAddScatterPlotsJson(spBlocks, blockToCopy,
10658 cellArray.GetName(), pointArray.GetNumberOfComponents(),
10659 "GlobalElementId")
10660
10661 gPipeAndViewsState.mImageSetCounter += 1
10662
10663 spBlocks.pop(blockToPop, None)
10664
10665 if PhactoriDbg(100):
10666 myDebugPrint3('TestForAndConstructAllScatterPlots returning\n', 100)
10667
10668 def UpdatePipeAndViewsStateFromUserA(inPipeAndViewsState, inFileName):
10669 """given a PhactoriPipeAndViewsState instance which has been previously
10670 parsed, paraview items created, etc. (and presumably used to create
10671 rendered images at least once), read in the json state from the
10672 specified file, and update the inPipeAndViewsState accordingly.
10673 Only do the update if the PhactoriUpdateTrigger.txt file has a new
10674 value since the last check. Only read the file on processor zero,
10675 and use mpi to share the update with all other processors."""
10676 if PhactoriDbg():
10677 myDebugPrint3("UpdatePipeAndViewsStateFromUserA entered\n")
10678 if SmartGetLocalProcessId() != 0:
10679 if PhactoriDbg():
10680 myDebugPrint3("UpdatePipeAndViewsStateFromUserA returning, not process 0\n")
10681 return
10682 try:
10683 inFile = open(inFileName, 'rb')
10684 userUpdateJson = json.load(inFile)
10685 inFile.close()
10686 userUpdateJson = convertJsonUnicodeToStrings(userUpdateJson)
10687
10688 if 'representation blocks' in userUpdateJson:
10689 representationBlocks = userUpdateJson['representation blocks']
10690 #could add logic to detect no change
10691 for repName, repJson in representationBlocks.items():
10692 onePhactoriRep = inPipeAndViewsState.mRepresentationBlocks[repName]
10693 if PhactoriDbg():
10694 myDebugPrint3("representation name: " + str(repName) + \
10695 "\nrepresentation json: " + str(repJson) + "\n")
10696 if onePhactoriRep != None:
10697 ParseOneRepresentationBlockC(onePhactoriRep, repJson,
10698 inPipeAndViewsState)
10699 if PhactoriDbg():
10700 myDebugPrint3("new color by variable: " +
10701 onePhactoriRep.mColorVariableInfo.SelfToStr() + "\n")
10702
10703 if 'camera blocks' in userUpdateJson:
10704 cameraBlocks = userUpdateJson['camera blocks']
10705 for cameraName, cameraJson in cameraBlocks.items():
10706 onePhactoriCamera = inPipeAndViewsState.mCameraBlocks[cameraName]
10707 if PhactoriDbg():
10708 myDebugPrint3("camera name: " + str(cameraName) + \
10709 "\ncamera json: " + str(cameraJson) + "\n")
10710 if onePhactoriCamera != None:
10711 if PhactoriDbg():
10712 myDebugPrint3("updating camera named: " + str(cameraName) + "\n")
10713 ParseOneCameraBlockC(onePhactoriCamera, cameraJson,
10714 inPipeAndViewsState)
10715 if PhactoriDbg():
10716 myDebugPrint3("new look direction: " + \
10717 str(onePhactoriCamera.mLookDirection) + "\n")
10718
10719 except:
10720 if PhactoriDbg():
10721 myDebugPrint3("error trying to get and use json from file\n")
10722 if PhactoriDbg():
10723 myDebugPrint3("UpdatePipeAndViewsStateFromUserA returning\n")
10724
10725 def SaveJsonSettingsToFile(inPipeAndViewsState, inFileName):
10726 """given a PhactoriPipeAndViewsState instance, dump the json that was
10727 used to construct it (usually called after default items have been
10728 added)"""
10729 if PhactoriDbg():
10730 myDebugPrint3("SaveJsonSettingsToFile entered\n")
10731 if SmartGetLocalProcessId() != 0:
10732 if PhactoriDbg():
10733 myDebugPrint3("SaveJsonSettingsToFile returning, not process 0\n")
10734 return
10735 try:
10736 outStr = json.dumps(inPipeAndViewsState.mJsonDescription, sort_keys=True,
10737 indent = 2, separators=(',', ': '))
10738 outFile = open(inFileName, 'w+b')
10739 outFile.write(outStr)
10740 outFile.close()
10741 outFile = open('PhactoriInteractionTrigger.txt', 'w+b')
10742 outStr = json.dumps({'InteractionTriggerCounter': 0,
10743 'InteractionState':'OncePerCallbackFromSimulation'})
10744 outFile.write(outStr)
10745 outFile.close()
10746 except:
10747 if PhactoriDbg():
10748 myDebugPrint3("error trying to create or write file or make json string\n")
10749
10750 if PhactoriDbg():
10751 myDebugPrint3("SaveJsonSettingsToFile returning\n")
10752
10753 def PreprocessExperimentalTextAnnotationBlock(
10754 inViewMapC, inExpBlkname, inExpBlk):
10755
10756 substringToSubstituteForSpace = None
10757 if 'substringtosubstituteforspace' in inExpBlk:
10758 substringToSubstituteForSpace = \
10759 str(inExpBlk['substringtosubstituteforspace'])
10760 if PhactoriDbg():
10761 myDebugPrint3("substringtosubstituteforspace: ->" + \
10762 substringToSubstituteForSpace + "<-\n")
10763
10764 if 'line1' not in inExpBlk:
10765 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
10766 "textannotation type block must have 'line1' entry")
10767
10768 myNewTxtAntnBlk = {}
10769
10770 for lineIndex in range(1, 10):
10771 oneLineString = ""
10772 lineKey = "line" + str(lineIndex)
10773 if lineKey not in inExpBlk:
10774 break
10775 oneLineString = str(inExpBlk[lineKey])
10776 if substringToSubstituteForSpace != None:
10777 oneLineString = oneLineString.replace(
10778 substringToSubstituteForSpace, " ")
10779 if PhactoriDbg():
10780 myDebugPrint3("line after sub: ->" + oneLineString + "\n")
10781 myNewTxtAntnBlk[lineKey] = oneLineString
10782
10783 if 'windowlocation' in inExpBlk:
10784 myNewTxtAntnBlk['windowlocation'] = inExpBlk['windowlocation']
10785
10786 if ('positionx' in inExpBlk) or ('positiony' in inExpBlk):
10787 if 'positiony' not in inExpBlk:
10788 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
10789 "if you have 'positionx' you need 'positiony'\n")
10790 if 'positionx' not in inExpBlk:
10791 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
10792 "if you have 'positiony' you need 'positionx'\n")
10793 posx = float(inExpBlk['positionx'])
10794 posy = float(inExpBlk['positiony'])
10795 myNewTxtAntnBlk['windowlocation'] = 'AnyLocation'
10796 myNewTxtAntnBlk['position'] = [posx, posy]
10797
10798 if 'color' in inExpBlk:
10799 colorRgb = inExpBlk['color']
10800 myNewTxtAntnBlk['color'] = \
10801 [float(colorRgb[0]), float(colorRgb[1]), float(colorRgb[2])]
10802
10803 if 'opacity' in inExpBlk:
10804 myNewTxtAntnBlk['opacity'] = float(inExpBlk['opacity'])
10805
10806 if 'boldflag' in inExpBlk:
10807 myNewTxtAntnBlk['boldflag'] = int(inExpBlk['boldflag'])
10808 if 'italicflag' in inExpBlk:
10809 myNewTxtAntnBlk['italicflag'] = int(inExpBlk['italicflag'])
10810 if 'shadowflag' in inExpBlk:
10811 myNewTxtAntnBlk['shadowflag'] = int(inExpBlk['shadowflag'])
10812
10813 if 'fontsize' in inExpBlk:
10814 myNewTxtAntnBlk['fontsize'] = int(inExpBlk['fontsize'])
10815 if 'fontfamily' in inExpBlk:
10816 myNewTxtAntnBlk['fontfamily'] = inExpBlk['fontfamily']
10817
10818 if 'text annotation blocks' not in inViewMapC:
10819 inViewMapC['text annotation blocks'] = {}
10820 inViewMapC['text annotation blocks'][inExpBlkname] = myNewTxtAntnBlk
10821
10822 if 'show_in_imageset' in inExpBlk:
10823 targetImageset = inExpBlk['show_in_imageset']
10824 imagesets = inViewMapC['imageset blocks']
10825 if targetImageset in imagesets:
10826 theImageset = imagesets[targetImageset]
10827 if 'text annotations' not in theImageset:
10828 theImageset['text annotations'] = []
10829 textAnnotationList = theImageset['text annotations']
10830 textAnnotationList.append(inExpBlkname)
10831 else:
10832 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
10833 "textannotation target imageset is not in imageset blocks")
10834 else:
10835 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
10836 "textannotation type block must have 'show_in_imageset' entry")
10837
10838
10839 def PreprocessExperimentalAddOpacityToRepBlock(
10840 inViewMapC, inExpBlkname, inExpBlk):
10841
10842 if 'representation blocks' not in inViewMapC:
10843 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
10844 "no 'representation blocks'\n")
10845
10846 repNameToAddTo = inExpBlk["target_representation"]
10847 if repNameToAddTo == None:
10848 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
10849 + str(inExpBlkname) + " missing 'target_representation'\n")
10850
10851 representationBlocks = inViewMapC["representation blocks"]
10852 targetRep = representationBlocks[repNameToAddTo]
10853 if targetRep == None:
10854 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
10855 "no representation with name: " + str(repNameToAddTo) + "\n");
10856
10857 opacitySetting = inExpBlk["opacity"]
10858 if opacitySetting == None:
10859 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
10860 + str(inExpBlkname) + " missing 'opacity'\n")
10861
10862 targetRep["opacity"] = float(opacitySetting)
10863 if PhactoriDbg():
10864 myDebugPrint3("PreprocessExperimentalAddOpacityToRepBlock:\n" \
10865 "to representation: " + repNameToAddTo + "\n" \
10866 "added opacity: " + str(opacitySetting) + "\n")
10867
10868
10869 def PreprocessOneExperimentalBlock(inViewMapC, inExpBlkname, inExpBlk):
10870 """gives us entry point to take one experimental blocks and manipulate it
10871 to produce other kinds of blocks to enter into inViewMapC"""
10872 expBlkType = inExpBlk["type"]
10873
10874 if expBlkType == "textannotation":
10875 PreprocessExperimentalTextAnnotationBlock(
10876 inViewMapC, inExpBlkname, inExpBlk)
10877
10878 if expBlkType == "addopacitysettingtorepresentation":
10879 PreprocessExperimentalAddOpacityToRepBlock(inViewMapC, inExpBlkname, inExpBlk)
10880
10881
10882 def PreprocessExperimentalBlocks(inViewMapC):
10883 """gives us entry point to take experimental blocks and manipulate them
10884 to produce other kinds of blocks to enter into inViewMapC"""
10885
10886 if 'experimental blocks' not in inViewMapC:
10887 #no experimental blocks
10888 return
10889
10890 expBlkMap = inViewMapC['experimental blocks']
10891 for expBlkName, expBlk in expBlkMap.items():
10892 PreprocessOneExperimentalBlock(inViewMapC, expBlkName, expBlk)
10893
10894 if len(expBlkMap) > 0:
10895 if PhactoriDbg():
10896 myDebugPrint3(
10897 "altered inViewMapC after experimental block handling:\n" + \
10898 str(inViewMapC) + "\n")
10899
10900 #construct a set of views from the json-structure view/pipeline description
10901 #specified in the sierra catalyst wiki/documentation
10902 def CreateViewSetFromPhactoriViewMapC(inViewMapC):
10903 """Create data pipeline, cameras, representations, and views from data struct
10904
10905 Given a dict which is a json format structure with syntax as discussed in
10906 the sierra catalyst paraview insitu wiki, create the corresponding data
10907 pipeline, representations, views, etc. The basic idea is that from the
10908 incoming datastructure, we will parse out 6 (currently) sets of blocks:
10909 operations, cameras, representations, imagesets, scatter plots, and plots
10910 over time. From these, we will construct ParaView/Catalyst data structures
10911 to do the data management and rendering. See the class
10912 PhactoriPipeAndViewsState and the lower level related classes for more
10913 explaination.
10914 """
10915
10916 if PhactoriDbg(100):
10917 myDebugPrint3('CreateViewSetFromPhactoriViewMapC entered\n', 100)
10918 if PhactoriDbg():
10919 myDebugPrint3(str(inViewMapC) + "\n")
10920 global gPipeAndViewsState
10921 gPipeAndViewsState.mJsonDescription = inViewMapC
10922
10923 #get pointers to the various block types (currently 6, camera,
10924 #representation, operation, imageset, plot over time, and scatter plot)
10925
10926 #check for 'experimental blocks' and handle them appropriately if they
10927 #are there (e.g. use them to create other blocks)
10928 PreprocessExperimentalBlocks(inViewMapC)
10929
10930 cameraBlocks = {}
10931 representationBlocks = {}
10932 imagesetBlocks = {}
10933 operationBlocks = {}
10934 scatterplotBlocks = {}
10935 timeplotBlocks = {}
10936 criteriaBlocks = {}
10937 markerBlocks = {}
10938 textannotationBlocks = {}
10939 if 'camera blocks' in inViewMapC:
10940 cameraBlocks = inViewMapC['camera blocks']
10941 if 'representation blocks' in inViewMapC:
10942 representationBlocks = inViewMapC['representation blocks']
10943 if 'imageset blocks' in inViewMapC:
10944 imagesetBlocks = inViewMapC['imageset blocks']
10945 if 'operation blocks' in inViewMapC:
10946 operationBlocks = inViewMapC['operation blocks']
10947 if 'scatter plot blocks' in inViewMapC:
10948 scatterplotBlocks = inViewMapC['scatter plot blocks']
10949 if 'plot over time blocks' in inViewMapC:
10950 timeplotBlocks = inViewMapC['plot over time blocks']
10951 if 'onoff criteria blocks' in inViewMapC:
10952 criteriaBlocks = inViewMapC['onoff criteria blocks']
10953 if 'visual marker blocks' in inViewMapC:
10954 markerBlocks = inViewMapC['visual marker blocks']
10955 if 'text annotation blocks' in inViewMapC:
10956 textannotationBlocks = inViewMapC['text annotation blocks']
10957 if PhactoriDbg():
10958 myDebugPrint3(" cameraBlocks:\n")
10959 myDebugPrint3(" " + str(cameraBlocks) + "\n")
10960 myDebugPrint3(" representationBlocks:\n")
10961 myDebugPrint3(" " + str(representationBlocks) + "\n")
10962 myDebugPrint3(" imagesetBlocks:\n")
10963 myDebugPrint3(" " + str(imagesetBlocks) + "\n")
10964 myDebugPrint3(" operationBlocks:\n")
10965 myDebugPrint3(" " + str(operationBlocks) + "\n")
10966 myDebugPrint3(" scatterplotBlocks:\n")
10967 myDebugPrint3(" " + str(scatterplotBlocks) + "\n")
10968 myDebugPrint3(" timeplotBlocks:\n")
10969 myDebugPrint3(" " + str(timeplotBlocks) + "\n")
10970 myDebugPrint3(" onoff criteria blocks:\n")
10971 myDebugPrint3(" " + str(criteriaBlocks) + "\n")
10972 myDebugPrint3(" visual marker blocks:\n")
10973 myDebugPrint3(" " + str(markerBlocks) + "\n")
10974 myDebugPrint3(" text annotation blocks:\n")
10975 myDebugPrint3(" " + str(textannotationBlocks) + "\n")
10976
10977 #go through imageset json, and locate operation shortcuts. If found, create
10978 #json defintion of operations and add them to the structure for later
10979 #creation, and add reference to the new operations in the imageblock json
10980 HandleOperationShortcuts(imagesetBlocks, operationBlocks)
10981
10982 #do pipeline stuff
10983 gPipeAndViewsState.mIncomingDefaultOperation.mParaViewFilter = GetActiveSource()
10984
10985 global gEnableTemporaryExtractBlockTest
10986 if gEnableTemporaryExtractBlockTest:
10987 #hack to test extract block filter
10988 if gExtractBlockAOperationName in operationBlocks:
10989 global gExtractBlockAList
10990 theBlock = operationBlocks[gExtractBlockAOperationName]
10991 theBlock['type'] = 'extractblock'
10992 theBlock['include blocks'] = gExtractBlockAList
10993 if gExtractBlockBOperationName in operationBlocks:
10994 global gExtractBlockBList
10995 theBlock = operationBlocks[gExtractBlockBOperationName]
10996 theBlock['type'] = 'extractblock'
10997 theBlock['include blocks'] = gExtractBlockBList
10998
10999 #to test imagesets with multiple operations visible
11000 if gEnableTemporaryMultiOpViewTest:
11001 if gMultiOpViewTestImagesetName in imagesetBlocks:
11002 theBlock = imagesetBlocks["multioptestimageset"]
11003 theBlock["operation2"] = gMultiOpViewTestOp2Name
11004 theBlock["representation2"] = gMultiOpViewTestRep2Name
11005
11006 global gEnableTemporaryOffAxisProjectionTest
11007 if gEnableTemporaryOffAxisProjectionTest:
11008 global gOaptCameraNameList
11009
11010 #go through cameras and set up stereo ones
11011 for oneOaptCameraName in gOaptCameraNameList:
11012 if oneOaptCameraName in cameraBlocks:
11013 global gOaptPhysicalSettingsForCamera
11014 physicalSettingsForCamera = \
11015 gOaptPhysicalSettingsForCamera[oneOaptCameraName]
11016 theBlock = cameraBlocks[oneOaptCameraName]
11017 theBlock['use off axis projection'] = True
11018 for key, value in physicalSettingsForCamera.items():
11019 theBlock[key] = value
11020 theBlock['which eye'] = 'left'
11021 #copy this camera to another to use for right eye
11022 rightCameraName = oneOaptCameraName + "Right"
11023 rightCameraBlock = {}
11024 for key, value in theBlock.items():
11025 rightCameraBlock[key] = value
11026 rightCameraBlock['which eye'] = 'right'
11027 cameraBlocks[rightCameraName] = rightCameraBlock
11028 if PhactoriDbg():
11029 myDebugPrint3("new camera block for right eye:\n"
11030 + str(rightCameraBlock) + "\n")
11031
11032 #go through imageset blocks and add extras for stereo
11033 blocksToReplicateForRightEye = []
11034 for imagesetName, oneImagesetBlock in imagesetBlocks.items():
11035 if 'camera' in oneImagesetBlock:
11036 if oneImagesetBlock['camera'] in gOaptCameraNameList:
11037 blocksToReplicateForRightEye.append(
11038 [imagesetName, oneImagesetBlock])
11039 if PhactoriDbg():
11040 myDebugPrint3("blocksToReplicateForRightEye:\n"
11041 + str(blocksToReplicateForRightEye) + "\n")
11042 for iterItem in blocksToReplicateForRightEye:
11043 oneImagesetName = iterItem[0]
11044 oneImagesetBlock = iterItem[1]
11045 newImagesetBlock = {}
11046 for key, value in oneImagesetBlock.items():
11047 newImagesetBlock[key] = value
11048 rightCameraName = oneImagesetBlock['camera'] + "Right"
11049 newImagesetBlock['camera'] = rightCameraName
11050 imagesetBaseName = str(oneImagesetBlock['image basename'])
11051 oneImagesetBlock['image basename'] = imagesetBaseName + "left."
11052 newImagesetBlock['image basename'] = imagesetBaseName + "right."
11053 if PhactoriDbg():
11054 myDebugPrint3("new imageset block for right eye:\n"
11055 + str(newImagesetBlock) + "\n")
11056 imagesetBlocks[oneImagesetName + "Right"] = newImagesetBlock
11057
11058 #swap out operations from input deck for testing operations which aren't
11059 #available through the input deck syntax yet
11060 global gEnableSubstituteOperationTesting
11061 if gEnableSubstituteOperationTesting:
11062 global gSubstituteOperationTestingList
11063 global gSubstituteOperationTestingMap
11064 for oneOpName in gSubstituteOperationTestingList:
11065 if oneOpName in operationBlocks:
11066 if PhactoriDbg():
11067 myDebugPrint3("substituting operation named: " + oneOpName + "\n")
11068 oneOpBlock = operationBlocks[oneOpName]
11069 subOpBlock = gSubstituteOperationTestingMap[oneOpName]
11070 if 'input' in oneOpBlock:
11071 subOpBlock['input'] = oneOpBlock['input']
11072 operationBlocks[oneOpName] = subOpBlock
11073
11074 #swap out imagesets from input deck for testing imagesets which aren't
11075 #available through the input deck syntax yet
11076 global gEnableSubstituteImagesetTesting
11077 if gEnableSubstituteImagesetTesting:
11078 global gSubstituteImagesetTestingList
11079 global gSubstituteImagesetTestingMap
11080 for oneIsName in gSubstituteImagesetTestingList:
11081 if oneIsName in imagesetBlocks:
11082 oneIsBlock = imagesetBlocks[oneIsName]
11083 subIsBlock = gSubstituteImagesetTestingMap[oneIsName]
11084 for key, value in subIsBlock.items():
11085 oneIsBlock[key] = value
11086
11087 MakeFiltersFromViewMapOperationsC(gPipeAndViewsState, operationBlocks)
11088 if PhactoriDbg():
11089 myDebugPrint3(' gPipeAndViewsState.mOperationBlocks: ' + \
11090 str(gPipeAndViewsState.mOperationBlocks) + '\n')
11091
11092 #parse scatter plot blocks
11093
11094 #special case; check for 'all variables' in a scatter plot and contruct all
11095 #plot json blocks if necessary
11096 TestForAndConstructAllScatterPlots(scatterplotBlocks)
11097
11098 #ParseScatterPlotBlocksC(gPipeAndViewsState, scatterplotBlocks)
11099 #ParseBlocksC(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,
11100 # PhactoriScatterPlotBlock, ParseOneScatterPlotBlockC,
11101 # gPipeAndViewsState)
11102 ParseBlocksC2(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,
11103 PhactoriScatterPlotBlock, gPipeAndViewsState)
11104
11105 #special case; check for 'all variables' in a plot over time and contruct all
11106 #plot json blocks if necessary
11107 TestForAndConstructAllPlotsOverTime(timeplotBlocks)
11108
11109 #parse time plot blocks
11110 ParseBlocksC(gPipeAndViewsState.mPlotOverTimeBlocks, timeplotBlocks,
11111 PhactoriPlotOverTimeBlock, ParseOnePlotOverTimeBlockC,
11112 gPipeAndViewsState)
11113
11114 #create producers for plots
11115 CreateScatterPlotProducersC(gPipeAndViewsState)
11116 CreatePlotOverTimeProducersC(gPipeAndViewsState)
11117
11118 #parse camera blocks
11119 #ParseCameraBlocksC(gPipeAndViewsState, cameraBlocks)
11120 ParseBlocksC(gPipeAndViewsState.mCameraBlocks, cameraBlocks,
11121 PhactoriCameraBlock, ParseOneCameraBlockC,
11122 gPipeAndViewsState)
11123
11124 #parse representation blocks
11125 #ParseRepresentationBlocksC(gPipeAndViewsState, representationBlocks)
11126 ParseBlocksC(gPipeAndViewsState.mRepresentationBlocks, representationBlocks,
11127 PhactoriRepresentationBlock, ParseOneRepresentationBlockC,
11128 gPipeAndViewsState)
11129
11130 #parse imageset onoff criteria blocks
11131 ParseBlocksC(gPipeAndViewsState.mImagesetOnOffCriteriaBlocks, criteriaBlocks,
11132 PhactoriImagesetOnOffFilterCriteria, ParseOneCriteriaBlockC,
11133 gPipeAndViewsState)
11134
11135 #parse visual marker blocks
11136 numMarkerBlocks = ParseBlocksC(
11137 gPipeAndViewsState.mMarkerBlocks,
11138 markerBlocks, PhactoriMarkerBlock,
11139 ParseOneMarkerBlockC, gPipeAndViewsState)
11140
11141 #parse text annotation blocks
11142 numTextAnnotationBlocks = ParseBlocksC(
11143 gPipeAndViewsState.mTextAnnotationBlocks,
11144 textannotationBlocks, PhactoriTextAnnotationBlock,
11145 ParseOneTextAnnotationBlockC, gPipeAndViewsState)
11146
11147 #construct marker paraview items (e.g. sphere or box source and the
11148 #corresponding representation
11149 #this is now done the first time the marker is made visible
11150 #for oneMarkerName, oneMarkerBlock in \
11151 # gPipeAndViewsState.mMarkerBlocks.iteritems():
11152 # oneMarkerBlock.CreateParaViewItems()
11153
11154 #parse imageset blocks
11155 #ParseImagesetBlocksC(gPipeAndViewsState, imagesetBlocks)
11156 numImagesetBlocks = ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,
11157 PhactoriImagesetBlock, ParseOneImagesetBlockC,
11158 gPipeAndViewsState)
11159
11160 #if there are no imageset blocks, create default and parse parameters in
11161 #wrappint imagesetBlock json as if they were from an imageset block
11162 if numImagesetBlocks == 0:
11163 if PhactoriDbg():
11164 myDebugPrint3(" no imagesets, creating a default imageset\n")
11165 imagesetBlocks['defaultimageset'] = {}
11166 ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,
11167 PhactoriImagesetBlock, ParseOneImagesetBlockC,
11168 gPipeAndViewsState)
11169
11170
11171 # if 'camera' not in ioImagesetBlockJson:
11172 # #we have to construct and use a default camera, including parsing
11173 # #commands in the imageset for the camera
11174 # myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
11175 # ioImagesetBlock.mName + \
11176 # " there is no camera, so we must add and reference default\n")
11177 # if 'camera type' not in ioImagesetBlockJson:
11178 # ioImagesetBlockJson['camera type'] = 'multicamera8'
11179 # defaultCameraName = ioImagesetBlock.mName + '_default_camera'
11180 # defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}
11181 # ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,
11182 # defaultCameraBlockAndWrapper,
11183 # PhactoriCameraBlock,
11184 # ParseOneCameraBlockC,
11185 # ioPipeAndViewsState)
11186 # ioImagesetBlockJson['camera'] = defaultCameraName
11187 # #myDebugPrint3( "done adding camera, here it is:\n")
11188 # #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()
11189
11190
11191 #loop through imageset blocks and create a viz for each--i.e. create a
11192 #ParaView/Catalyst Representation and View for each imageset block, and
11193 #have it render info from some stage of the above pipeline
11194
11195 for imagesetName, imagesetInstance in gPipeAndViewsState.mImagesetBlocks.items():
11196 CreateParaviewItemsForImagesetC(imagesetInstance)
11197
11198 CreateScatterPlotViewsC(gPipeAndViewsState)
11199 CreatePlotOverTimeViewsC(gPipeAndViewsState)
11200
11201 if gPipeAndViewsState.mInteractionEnabled == True:
11202 SaveJsonSettingsToFile(gPipeAndViewsState, "PhactoriJsonSettings.txt")
11203
11204 def CreateScatterPlotProducersC(inPipeAndViewsState):
11205 if PhactoriDbg(100):
11206 myDebugPrint3('CreateScatterPlotProducersC entered\n', 100)
11207 for oneScatterPlotName, oneScatterPlot in inPipeAndViewsState.mScatterPlotBlocks.items():
11208 #myDebugPrint3(' creating scatter plot producer nameed ' + oneScatterPlot.mName + '\n')
11209 CreateOneScatterPlotProducerC(oneScatterPlot)
11210 if PhactoriDbg(100):
11211 myDebugPrint3('CreateScatterPlotProducersC returning\n', 100)
11212
11213 def CreatePlotOverTimeProducersC(inPipeAndViewsState):
11214 if PhactoriDbg(100):
11215 myDebugPrint3('CreatePlotOverTimeProducersC entered\n', 100)
11216 for onePlotOverTimeName, onePlotOverTime in inPipeAndViewsState.mPlotOverTimeBlocks.items():
11217 #myDebugPrint3(' creating plot over time producer nameed ' + onePlotOverTime.mName + '\n')
11218 CreateOnePlotOverTimeProducerC(onePlotOverTime)
11219 if PhactoriDbg(100):
11220 myDebugPrint3('CreatePlotOverTimeProducersC returning\n', 100)
11221
11222 def CreateScatterPlotViewsC(inPipeAndViewsState):
11223
11224 if PhactoriDbg(100):
11225 myDebugPrint3('CreateScatterPlotViewsC entered\n', 100)
11226 #SetPlotView2StartColors(
11227 # inBackgroundColor = [1.0, 1.0, 1.0],
11228 # inEdgeColor = [0.0, 0.0, 0.5],
11229 # inCubeAxesColor = [0.2, 0.2, 0.2],
11230 # inDiffuseColor = [0.2, 0.2, 0.2],
11231 # inAmbientColor = [0.2, 0.2, 0.2],
11232 # inSelectionColor = [0.2, 0.2, 0.2],
11233 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
11234
11235 for oneScatterPlotName, oneScatterPlot in inPipeAndViewsState.mScatterPlotBlocks.items():
11236 #myDebugPrint3(' creating scatter plot view nameed ' + oneScatterPlot.mName + '\n')
11237 CreateOneScatterPlotViewC(oneScatterPlot)
11238 if PhactoriDbg(100):
11239 myDebugPrint3('CreateScatterPlotViewsC returning\n', 100)
11240
11241
11242 def CreatePlotOverTimeViewsC(inPipeAndViewsState):
11243
11244 if PhactoriDbg(100):
11245 myDebugPrint3('CreatePlotOverTimeViewsC entered\n', 100)
11246 #SetPlotView2StartColors(
11247 # inBackgroundColor = [1.0, 1.0, 1.0],
11248 # inEdgeColor = [0.0, 0.0, 0.5],
11249 # inCubeAxesColor = [0.2, 0.2, 0.2],
11250 # inDiffuseColor = [0.2, 0.2, 0.2],
11251 # inAmbientColor = [0.2, 0.2, 0.2],
11252 # inSelectionColor = [0.2, 0.2, 0.2],
11253 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
11254
11255 for onePlotOverTimeName, onePlotOverTime in inPipeAndViewsState.mPlotOverTimeBlocks.items():
11256 #myDebugPrint3(' creating scatter plot view nameed ' + onePlotOverTime.mName + '\n')
11257 CreateOnePlotOverTimeViewC(onePlotOverTime)
11258 if PhactoriDbg(100):
11259 myDebugPrint3('CreatePlotOverTimeViewsC returning\n', 100)
11260
11261
11262 def ColorByVariableComponentOrMagnitudeXX(inParaViewDataRepresentation,
11263 inPhactoriRepresentation,
11264 inVariableName, inComponentOrMagnitude, inWhichComponent,
11265 inVariableArrayType, inColorMapSettings):
11266 #myDebugPrint3("ColorByVariableComponentOrMagnitudeXX entered\n", 100)
11267 #myDebugPrint3(" inVariableName: " + inVariableName + "\n")
11268 #myDebugPrint3(" inComponentOrMagnitude: " + inComponentOrMagnitude + "\n")
11269 #myDebugPrint3(" inWhichComponent: " + str(inWhichComponent) + "\n")
11270 #myDebugPrint3(" inVariableArrayType: " + str(inVariableArrayType) + "\n")
11271
11272 if gParaViewCatalystVersionFlag >= 40300:
11273 #for paraview 4.3
11274 if inVariableArrayType == None:
11275 myDebugPrint3AndException(\
11276 "ColorByVariableComponentOrMagnitudeXX "
11277 "expecting inVariableArrayType\n")
11278 if PhactoriDbg():
11279 myDebugPrint3("using ColorBy() to set color var " + \
11280 inVariableName + " " + inVariableArrayType + " 1\n")
11281 myDebugPrint3("inComponentOrMagnitude: " + str(inComponentOrMagnitude) \
11282 + "\ninWhichComponent: " + str(inWhichComponent) + "\n")
11283 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
11284 SafeColorBy(inParaViewDataRepresentation,
11285 (inVariableArrayType, inVariableName))
11286 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
11287 #deal with vector mode, component index
11288 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
11289 if inComponentOrMagnitude == 'Magnitude':
11290 pv_4_3_LUT.VectorMode = 'Magnitude'
11291 else:
11292 pv_4_3_LUT.VectorMode = 'Component'
11293 pv_4_3_LUT.VectorComponent = inWhichComponent
11294 #need to deal with color table
11295 myRGBPoints, myColorSpace, myNanColor = \
11296 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
11297 -1.0, 1.0)
11298 pv_4_3_LUT.RGBPoints = myRGBPoints
11299 pv_4_3_LUT.ColorSpace = myColorSpace
11300 pv_4_3_LUT.NanColor = myNanColor
11301 return;
11302
11303 #after this the function is for paraview 4.1
11304
11305 if inVariableArrayType != None:
11306 inParaViewDataRepresentation.ColorAttributeType = inVariableArrayType
11307
11308 myRGBPoints, myColorSpace, myNanColor = \
11309 GetColorMapInfoFromColorLegendCollection(inColorMapSettings, -1.0, 1.0)
11310
11311 newLookupTable = None
11312 if inComponentOrMagnitude == 'Magnitude':
11313 newLookupTable = GetLookupTableForArray( inVariableName, 3, Discretize=1, RGBPoints=myRGBPoints, UseLogScale=0, VectorComponent=0, NanColor=myNanColor, NumberOfTableValues=1024, ColorSpace=myColorSpace, VectorMode='Magnitude', HSVWrap=0, ScalarRangeInitialized=1.0, LockScalarRange=0 )
11314 elif inComponentOrMagnitude == 'Component':
11315 newLookupTable = GetLookupTableForArray( inVariableName, 3, Discretize=1, RGBPoints=myRGBPoints, UseLogScale=0, VectorComponent=inWhichComponent, NanColor=myNanColor, NumberOfTableValues=1024, ColorSpace=myColorSpace, VectorMode='Component', HSVWrap=0, ScalarRangeInitialized=1.0, LockScalarRange=0 )
11316 else:
11317 #bad name, should be 'Component' or 'Magnitude'
11318 return
11319
11320 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
11321 inParaViewDataRepresentation.LookupTable = newLookupTable
11322 try:
11323 inParaViewDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
11324 except:
11325 if PhactoriDbg():
11326 myDebugPrint3('no inParaViewDataRepresentation.ScalarOpacityFunction\n');
11327
11328 inParaViewDataRepresentation.ColorArrayName = inVariableName
11329
11330
11331 def ColorByVariableScalarXX(inParaViewDataRepresentation, inPhactoriRepresentation, inVariableName, inVariableArrayType, inColorMapSettings):
11332 """Set the scalar variable (by name) which will be used to color the data
11333 presentation."""
11334 if gParaViewCatalystVersionFlag >= 40300:
11335 #for paraview 4.3
11336 if inVariableArrayType == None:
11337 myDebugPrint3AndException(\
11338 "ColorByVariableComponentOrMagnitudeXX "
11339 "expecting inVariableArrayType\n")
11340 if PhactoriDbg():
11341 myDebugPrint3("using ColorBy() to set color var " + \
11342 inVariableName + " " + inVariableArrayType + " 3\n")
11343 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
11344 SafeColorBy(inParaViewDataRepresentation,
11345 (inVariableArrayType, inVariableName))
11346 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
11347 #need to deal with color table
11348 myRGBPoints, myColorSpace, myNanColor = \
11349 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
11350 -1.0, 1.0)
11351 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
11352 pv_4_3_LUT.RGBPoints = myRGBPoints
11353 pv_4_3_LUT.ColorSpace = myColorSpace
11354 pv_4_3_LUT.NanColor = myNanColor
11355 if inPhactoriRepresentation.InterpretValuesAsCategories:
11356 if PhactoriDbg():
11357 myDebugPrint3("variable name is ObjectId, trying to do categories\n")
11358 inPhactoriRepresentation.SetUpForInterpretValuesAsCateories(pv_4_3_LUT)
11359 pv_4_3_LUT.InterpretValuesAsCategories = 1
11360 pv_4_3_LUT.AnnotationsInitialized = 1
11361 pv_4_3_LUT.Annotations = inPhactoriRepresentation.Annotations
11362 pv_4_3_LUT.IndexedColors = inPhactoriRepresentation.IndexedColors
11363 pv_4_3_LUT.IndexedOpacities = inPhactoriRepresentation.IndexedOpacities
11364 else:
11365 pv_4_3_LUT.InterpretValuesAsCategories = 0
11366 return
11367
11368 #rest of function for paraview 4.1
11369
11370 inParaViewDataRepresentation.ColorArrayName = inVariableName
11371 if inVariableArrayType != None:
11372 inParaViewDataRepresentation.ColorAttributeType = inVariableArrayType
11373
11374 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
11375
11376 myRGBPoints, myColorSpace, myNanColor = \
11377 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
11378 0.0, 1647.1430997030882)
11379
11380 new_var_PVLookupTable = GetLookupTableForArray( inVariableName, 3, Discretize=1, RGBPoints= myRGBPoints, UseLogScale=0, VectorComponent=0, NanColor=myNanColor, NumberOfTableValues=1024, ColorSpace=myColorSpace, VectorMode='Magnitude', HSVWrap=0, ScalarRangeInitialized=1.0, LockScalarRange=0 )
11381 if PhactoriDbg():
11382 myDebugPrint3("new lookup table (1):\n");
11383 if PhactoriDbg():
11384 myDebugPrint3(str(new_var_PVLookupTable) + "\n")
11385 if PhactoriDbg():
11386 myDebugPrint3("RGBPoints:\n");
11387 if PhactoriDbg():
11388 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints) + "\n")
11389
11390 if PhactoriDbg():
11391 myDebugPrint3(str(inParaViewDataRepresentation) + '\n')
11392 try:
11393 inParaViewDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
11394 except:
11395 if PhactoriDbg():
11396 myDebugPrint3('no inParaViewDataRepresentation.ScalarOpacityFunction\n');
11397 if PhactoriDbg():
11398 myDebugPrint3('new or reused lookup table: ' + str(new_var_PVLookupTable) + '\n')
11399 if PhactoriDbg():
11400 myDebugPrint3('prior inParaViewDataRepresentation.DataRepresentation.LookupTable: ' + str(inParaViewDataRepresentation.LookupTable) + '\n')
11401 inParaViewDataRepresentation.LookupTable = new_var_PVLookupTable
11402 if PhactoriDbg():
11403 myDebugPrint3(str(new_var_PVLookupTable))
11404 if PhactoriDbg():
11405 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints))
11406 if PhactoriDbg():
11407 myDebugPrint3(str(inParaViewDataRepresentation) + '\n')
11408
11409 global gNumCycleBlockColors
11410 global gCycleBlockColors
11411
11412 gNumCycleBlockColors = 12
11413 gCycleBlockColors = [[1.00, 0.00, 0.00],
11414 [1.00, 1.00, 0.00],
11415 [0.00, 1.00, 0.00],
11416 [0.00, 1.00, 1.00],
11417 [0.00, 0.00, 1.00],
11418 [1.00, 0.00, 1.00],
11419 [1.00, 0.50, 0.00],
11420 [0.50, 1.00, 0.00],
11421 [0.00, 1.00, 0.50],
11422 [0.00, 0.50, 1.00],
11423 [0.50, 0.00, 1.00],
11424 [1.00, 0.00, 0.50]]
11425
11426 def ColorByBlockOneBlock(inInputCsData, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag):
11427 #myDebugPrint3('ColorByBlockOneBlock entered\n', 100)
11428 ioBlockAndLeafBlockCounter[1] += 1
11429 #myDebugPrint3(' ioBlockAndLeafBlockCounter: ' + str(ioBlockAndLeafBlockCounter) + '\n')
11430 if inCountOnlyFlag == False:
11431 global gNumCycleBlockColors
11432 global gCycleBlockColors
11433 colorIndex = (ioBlockAndLeafBlockCounter[1] - 1) % gNumCycleBlockColors
11434 #myDebugPrint3(' colorIndex: ' + str(colorIndex) + ' color: ' + str(gCycleBlockColors[colorIndex]) + '\n')
11435 blockIndex = ioBlockAndLeafBlockCounter[0] - 1
11436 ioBlockColorData[blockIndex] = gCycleBlockColors[colorIndex]
11437
11438 #myDebugPrint3('ColorByBlockOneBlock returning\n', 100)
11439
11440 def ColorByBlockRecurse1(inInputCsData,
11441 ioBlockAndLeafBlockCounter,
11442 ioBlockColorData,
11443 inCountOnlyFlag = False,
11444 inMaximumCountFlag = False,
11445 inMaximumCount = 10000):
11446 #myDebugPrint3('ColorByBlockRecurse1 entered\n', 100)
11447
11448 ioBlockAndLeafBlockCounter[0] += 1
11449
11450 if inMaximumCountFlag:
11451 #myDebugPrint3(" inMaximumCountFlag true, inMaximumCount: " + str(inMaximumCount) + " block count: " + str(ioBlockAndLeafBlockCounter[0]) + "\n")
11452 if ioBlockAndLeafBlockCounter[0] >= inMaximumCount:
11453 #myDebugPrint3(" inMaximumCount hit, returning early\n", 100)
11454 return
11455
11456 icsdClassname = inInputCsData.GetClassName()
11457 #if PhactoriDbg(100):
11458 # myDebugPrint3("icsdClassname 2: " + str(icsdClassname) + "\n")
11459 if icsdClassname == "vtkMultiBlockDataSet" or \
11460 icsdClassname == "vtkExodusIIMultiBlockDataSet":
11461 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
11462 numBlocks = inInputCsData.GetNumberOfBlocks()
11463 for ii in range(0, numBlocks):
11464 oneBlock = inInputCsData.GetBlock(ii)
11465 if(oneBlock != None):
11466 ColorByBlockRecurse1(oneBlock, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag, inMaximumCountFlag, inMaximumCount)
11467 else:
11468 ioBlockAndLeafBlockCounter[0] += 1
11469 if inMaximumCountFlag:
11470 #myDebugPrint3(" inMaximumCountFlag (2) true, inMaximumCount: " + str(inMaximumCount) + " block count: " + str(ioBlockAndLeafBlockCounter[0]) + "\n")
11471 if ioBlockAndLeafBlockCounter[0] >= inMaximumCount:
11472 #myDebugPrint3(" inMaximumCount hit (2), returning early\n", 100)
11473 return
11474 else:
11475 ColorByBlockOneBlock(inInputCsData, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag)
11476
11477 #myDebugPrint3(' ioBlockAndLeafBlockCounter after this recursion: ' + str(ioBlockAndLeafBlockCounter) + '\n')
11478
11479 #myDebugPrint3('ColorByBlockRecurse1 returning\n', 100)
11480
11481 def ColorByBlock(inParaViewDataSource, inParaViewDataRepresentation,
11482 inBlockCountLimitOverride = False):
11483 if PhactoriDbg(100):
11484 myDebugPrint3('ColorByBlock entered\n', 100)
11485
11486 csdata = inParaViewDataSource.GetClientSideObject().GetOutputDataObject(0)
11487 blockAndLeafBlockCounter = [0,0]
11488
11489 #test for extreme case when there are too many blocks
11490 #tooManyBlocksToColor = 8
11491 tooManyBlocksToColor = 10000
11492 ColorByBlockRecurse1(csdata, blockAndLeafBlockCounter, None, True, True, tooManyBlocksToColor)
11493 if blockAndLeafBlockCounter[0] >= tooManyBlocksToColor:
11494 if inBlockCountLimitOverride:
11495 if PhactoriDbg():
11496 myDebugPrint3(' warning: color by blocks is being used with large number of blocks\n')
11497 else:
11498 if PhactoriDbg():
11499 myDebugPrint3(' too many blocks (>10000) for coloring: color data could cause issues\n')
11500 return
11501
11502 blockAndLeafBlockCounter = [0,0]
11503
11504 global gParaViewCatalystVersionFlag
11505 if gParaViewCatalystVersionFlag < 51000:
11506
11507 blockColorData = inParaViewDataRepresentation.BlockColor
11508 if PhactoriDbg(100):
11509 myDebugPrint3(' blockColorData is ' + str(blockColorData) + '\n', 100)
11510 if PhactoriDbg(100):
11511 myDebugPrint3(' blockColorData type is ' + str(type(blockColorData)) + '\n', 100)
11512
11513 ColorByBlockRecurse1(csdata, blockAndLeafBlockCounter, inParaViewDataRepresentation.BlockColor, False)
11514
11515 #inParaViewDataRepresentation.BlockColor = blockColorData
11516
11517 if PhactoriDbg(100):
11518 myDebugPrint3(' block color data: ' + str(inParaViewDataRepresentation.BlockColor) + '\n', 100)
11519 if PhactoriDbg(100):
11520 myDebugPrint3(' final count: ' + str(blockAndLeafBlockCounter) + '\n', 100)
11521
11522 if PhactoriDbg(100):
11523 myDebugPrint3('ColorByBlock returning\n', 100)
11524
11525
11526 def UseDataRangeForColorValues(inPvDataRepresentation, inRepresentation,
11527 inOperation):
11528
11529 if inRepresentation.mColorVariableInfo.mVariableIntendedForUseFlag == False:
11530 #the color by variable is not set, we do nothing
11531 return
11532
11533 if PhactoriDbg(100):
11534 myDebugPrint3("UseDataRangeForColorValues entered\n", 100)
11535
11536 rep = inPvDataRepresentation
11537
11538 localColorArrayName = inRepresentation.mColorVariableInfo.mVariableName
11539 if inRepresentation.mColorVariableInfo.mVariableType == 'node':
11540 pointsOrCellsType = gPointsString
11541 else:
11542 pointsOrCellsType = gCellsString
11543
11544 #if gParaViewCatalystVersionFlag <= 40100:
11545 # localColorArrayName = rep.ColorArrayName
11546 # pointsOrCellsType = rep.ColorAttributeType
11547 #else:
11548 # localColorArrayName = rep.ColorArrayName[1]
11549 # pointsOrCellsType = rep.ColorArrayName[0]
11550
11551 if PhactoriDbg():
11552 myDebugPrint3(' color variable is ' + localColorArrayName + '\n')
11553 myDebugPrint3(' color attribute type is ' + \
11554 pointsOrCellsType + '\n')
11555
11556 if PhactoriDbg():
11557 myDebugPrint3(" rep:" + str(rep) + "\n")
11558
11559 #if rep.ColorArrayName == '':
11560 # return
11561
11562 input = rep.Input
11563
11564 if PhactoriDbg():
11565 myDebugPrint3(" input:" + str(input) + "\n")
11566 UpdatePipelineWithCurrentTimeArgument(input)
11567
11568 #assume point info
11569 #datainformation = rep.Input.GetPointDataInformation()
11570
11571 if pointsOrCellsType == gPointsString:
11572 datainformation = input.GetPointDataInformation()
11573 elif pointsOrCellsType == gCellsString:
11574 datainformation = input.GetCellDataInformation()
11575 else:
11576 if PhactoriDbg():
11577 myDebugPrint3("something strange with color attribute type :" + \
11578 str(pointsOrCellsType) + "\n")
11579 return;
11580
11581 datarange = [sys.float_info.max, -sys.float_info.max]
11582 if gParaViewCatalystVersionFlag <= 40100:
11583 lut = rep.LookupTable
11584 else:
11585 lut = GetColorTransferFunction(rep.ColorArrayName[1])
11586
11587 if lut == None:
11588 #at this point in time, all processes should have a look up table, even
11589 #if they don't have associated data
11590 myDebugPrint3AndException(\
11591 "UseDataRangeForColorValues expecting LookupTable\n")
11592
11593 if inRepresentation.mColorVariableInfo.mVariableIsVectorComponent == True:
11594 lut.VectorMode = 'Component'
11595 index = inRepresentation.mColorVariableInfo.mVariableComponent
11596 lut.VectorComponent = index
11597 dataarray = datainformation.GetArray(localColorArrayName)
11598 if dataarray == None:
11599 #no data array, nothing to be done---screws up mpi?
11600 #return
11601 datarange = [sys.float_info.max, -sys.float_info.max]
11602 else:
11603 datarange = datainformation.GetArray(localColorArrayName).\
11604 GetRange(index)
11605 elif inRepresentation.mColorVariableInfo.\
11606 mVariableIsVectorMagnitude == True:
11607 lut.VectorMode = 'Magnitude'
11608 lut.VectorComponent = 0
11609 dataarray = datainformation.GetArray(localColorArrayName)
11610 if dataarray == None:
11611 #no data array, nothing to be done---screws up mpi?
11612 #return
11613 datarange = [sys.float_info.max, -sys.float_info.max]
11614 else:
11615 numComponents = dataarray.GetNumberOfComponents()
11616 if numComponents != 3:
11617 myDebugPrint3AndException(\
11618 "UseDataRangeForColorValues expecting 3 component item here\n")
11619 localMinMaxInfo = FindThisProcessorMinMaxForVar(inOperation,
11620 inRepresentation.mColorVariableInfo)
11621 if localMinMaxInfo[2] == False:
11622 datarange = [sys.float_info.max, -sys.float_info.max]
11623 else:
11624 datarange = [localMinMaxInfo[0], localMinMaxInfo[1]]
11625 else:
11626 #assume one component, scalar, assume one vector component and it's 0
11627 dataarray = datainformation.GetArray(localColorArrayName)
11628 if dataarray == None:
11629 #no data array, nothing to be done---screws up mpi?
11630 #return
11631 if PhactoriDbg():
11632 myDebugPrint3(\
11633 " no data array, using range "
11634 "[sys.float_info.max, -sys.float_info.max]\n")
11635 datarange = [sys.float_info.max, -sys.float_info.max]
11636 else:
11637 datarange = datainformation.GetArray(localColorArrayName).GetRange(0)
11638 if PhactoriDbg():
11639 myDebugPrint3("finding color legend datarange for " + str(localColorArrayName) + "\n")
11640 myDebugPrint3(' datarange: ' + str(datarange) + '\n')
11641
11642 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
11643 globalController = pm.GetGlobalController()
11644
11645 localarray = vtk.vtkDoubleArray()
11646 localarray.SetNumberOfTuples(2)
11647 # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
11648 localarray.SetValue(0, -datarange[0])
11649 localarray.SetValue(1, datarange[1])
11650
11651 globalarray = vtk.vtkDoubleArray()
11652 globalarray.SetNumberOfTuples(2)
11653 globalController.AllReduce(localarray, globalarray, 0)
11654 globalDatarange = [ \
11655 -globalarray.GetTuple1(0), globalarray.GetTuple1(1), \
11656 ]
11657 if PhactoriDbg():
11658 myDebugPrint3("local datarange: " + str(datarange) + \
11659 "\nglobal datarange: " + str(globalDatarange) + "\n")
11660
11661 minmaxTrk = inRepresentation.mColorRangeMinMaxTracker
11662 minmaxTrk.ResetThisCb()
11663
11664 if globalDatarange[0] >= globalDatarange[1]:
11665 #min was >= max, so we can't do a good color mapping; take steps
11666 #this means we really had no data; therefore set min and max to 0.0
11667 #and let this system handle the color mapping as if all data values
11668 #were 0.0
11669 globalDatarange[0] = 0.0
11670 globalDatarange[1] = 0.0
11671 if PhactoriDbg():
11672 myDebugPrint3("no valid data for variable; setting min/max to 0.0\n")
11673
11674 minmaxTrk.MinMaxTestAndSet(globalDatarange[0])
11675 minmaxTrk.MinMaxTestAndSet(globalDatarange[1])
11676 minmaxTrk.UpdateMinMaxToUse()
11677 #myDebugPrint3("representation color range tracking:\n")
11678 #myDebugPrint3(minmaxTrk.SelfToStr())
11679
11680 minToUse = minmaxTrk.GetMinToUse()
11681 maxToUse = minmaxTrk.GetMaxToUse()
11682
11683 if PhactoriDbg():
11684 myDebugPrint3("minmaxTrk min: " + str(minToUse) + " max: " + str(maxToUse) + "\n")
11685
11686 hadToAlterMinMaxDueToSmallRange = False
11687 if (maxToUse - minToUse) < 1.0e-20:
11688 hadToAlterMinMaxDueToSmallRange = True
11689 middle1 = 0.5 * (minToUse + maxToUse)
11690 minToUse = middle1 - 5.0e-21
11691 maxToUse = middle1 + 5.0e-21
11692 if PhactoriDbg(100):
11693 myDebugPrint3("had to change minToUse and maxToUse due to (maxToUse - minToUse) < 1.0e-20\n"
11694 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
11695 else:
11696 testMag1 = max(abs(maxToUse), abs(minToUse))
11697 if (maxToUse - minToUse) < testMag1*1.0e-6:
11698 hadToAlterMinMaxDueToSmallRange = True
11699 middle1 = 0.5 * (minToUse + maxToUse)
11700 delta2 = testMag1*5.0e-7
11701 minToUse = middle1 - delta2
11702 maxToUse = middle1 + delta2
11703 myDebugPrint3("had to change minToUse and maxToUse due to (maxToUse - minToUse) < testMag1\n"
11704 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
11705
11706 #if required, restrict color range to subset of otherwise calculated range
11707 if inRepresentation.mUseColorSubrange and (hadToAlterMinMaxDueToSmallRange == False):
11708 clrDelta = maxToUse - minToUse
11709 maxToUse = minToUse + inRepresentation.mColorSubrange[1] * clrDelta
11710 minToUse = minToUse + inRepresentation.mColorSubrange[0] * clrDelta
11711 myDebugPrint3("changed minToUse and maxToUse due to inRepresentation.mUseColorSubrange == True\n"
11712 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
11713
11714 SetMinimumMaximumColorValues(inPvDataRepresentation,
11715 minToUse, maxToUse,
11716 inOperation, inRepresentation,
11717 localColorArrayName, pointsOrCellsType)
11718
11719 if PhactoriDbg(100):
11720 myDebugPrint3("UseDataRangeForColorValues returning\n", 100)
11721
11722 #def UpdateDataRangesForColorValues():
11723 # myDebugPrint3("UpdateDataRangesForColorValues entered\n", 100)
11724 # global PhactoriRenderViewInfoList
11725 # for ii in PhactoriRenderViewInfoList:
11726 # UseDataRangeForColorValues(ii)
11727 # myDebugPrint3("UpdateDataRangesForColorValues returning\n", 100)
11728
11729 def helpFindNewRgbPoint(inBaseRgbPts, inRatio):
11730 #print "inRatio: ", inRatio
11731 positionIndex = -2
11732
11733 if inBaseRgbPts[0] >= inRatio:
11734 positionIndex = 0
11735 else:
11736 positionIndex = -1
11737 for rIndex in range(4, len(inBaseRgbPts), 4):
11738 #print "rIndex: ", rIndex
11739 #print "positionIndex: ", positionIndex
11740 #print "val: ", inBaseRgbPts[rIndex]
11741 if inRatio <= inBaseRgbPts[rIndex]:
11742 positionIndex = rIndex - 4
11743 #print "stopping"
11744 break
11745 #bad case, ratio is off end
11746 if positionIndex == -1:
11747 #print "bad case"
11748 positionIndex = len(inBaseRgbPts) - 4
11749
11750 if PhactoriDbg(100):
11751 myDebugPrint3("position index: " + str(positionIndex) + "\n", 100)
11752
11753 if positionIndex >= len(inBaseRgbPts):
11754 myDebugPrint3AndException("helpFindNewRgbPoint: ran off end\n")
11755
11756 zz1 = inBaseRgbPts[positionIndex + 0]
11757 rr1 = inBaseRgbPts[positionIndex + 1]
11758 gg1 = inBaseRgbPts[positionIndex + 2]
11759 bb1 = inBaseRgbPts[positionIndex + 3]
11760 zz2 = inBaseRgbPts[positionIndex + 4]
11761 rr2 = inBaseRgbPts[positionIndex + 5]
11762 gg2 = inBaseRgbPts[positionIndex + 6]
11763 bb2 = inBaseRgbPts[positionIndex + 7]
11764 deltaPt = zz2 - zz1
11765 ratioPt = (inRatio - zz1)/deltaPt
11766 #print "before Pt: ", zz1, rr1, gg1, bb1
11767 #print "after Pt : ", zz2, rr2, gg2, bb2
11768 #print "inRatio: ", inRatio
11769 #print "deltaPt: ", deltaPt
11770 #print "ratioPt: ", ratioPt
11771
11772 subrangePt1 = [inRatio,
11773 rr1 + ratioPt * (rr2 - rr1),
11774 gg1 + ratioPt * (gg2 - gg1),
11775 bb1 + ratioPt * (bb2 - bb1)]
11776 if PhactoriDbg(100):
11777 myDebugPrint3("subrangePt1: " + str(subrangePt1) + "\n")
11778 return subrangePt1
11779
11780
11781 def CalculateColorMapRGBPointsWithSubranges(inBaseRgbPoints,
11782 inMinimum, inMaximum, inSubrangeMin, inSubrangeMax, inSubrangeColor):
11783 """creates the rgb values for color map with highlighed subranges"""
11784
11785 if PhactoriDbg(100):
11786 myDebugPrint3("CalculateColorMapRGBPointsWithSubranges entered \n"
11787 " min, max: " + str(inMinimum) + ", " + str(inMaximum) + "\n"
11788 "subrange min, max: " + str(inSubrangeMin) + ", " + \
11789 str(inSubrangeMax) + "\n"
11790 "subrange color: " + str(inSubrangeColor) + "\n", 100)
11791
11792 #find where subrange fits in overallrange
11793 allRange = inMaximum - inMinimum
11794 minHlRatio = (inSubrangeMin - inMinimum)/allRange
11795 maxHlRatio = (inSubrangeMax - inMinimum)/allRange
11796
11797 #test for case where whole subrange is above or below overall range
11798 if minHlRatio >= 1.0 or maxHlRatio <= 0.0:
11799 if PhactoriDbg(100):
11800 myDebugPrint3("subrange is above or below overall range, returning\n"
11801 "CalculateColorMapRGBPointsWithSubranges returing \n", 100)
11802 return inBaseRgbPoints
11803
11804 if minHlRatio < 0.0:
11805 minHlRatio = 0.0
11806 if maxHlRatio > 1.0:
11807 maxHlRatio = 1.0
11808 if maxHlRatio - minHlRatio < 0.004:
11809 #very narrow subrange; use narrow bands but might color odd
11810 #issue warning?
11811 ratDelta = maxHlRatio - minHlRatio
11812 bandStep = ratDelta * 0.25
11813 else:
11814 bandStep = 0.001
11815
11816 #construct the no-subrange color map, with extra items to track the
11817 #outer range colors while changing the inner subrange colors
11818 xrgbPoints = inBaseRgbPoints
11819 #xrgbPoints = [0.0, 0.23137254902, 0.298039215686, 0.752941176471,
11820 # 0.5, 0.865, 0.865, 0.865,
11821 # 1.0, 0.705882352941, 0.0156862745098, 0.149019607843]
11822 if PhactoriDbg(100):
11823 myDebugPrint3("inBaseRgbPoints:\n" + str(inBaseRgbPoints) + "\n", 100)
11824
11825 #find the 4 points for the subrange
11826 subrangePt1 = helpFindNewRgbPoint(xrgbPoints, minHlRatio)
11827 subrangePt2 = [minHlRatio + bandStep,
11828 inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]
11829 subrangePt3 = [maxHlRatio - bandStep,
11830 inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]
11831 subrangePt4 = helpFindNewRgbPoint(xrgbPoints, maxHlRatio)
11832
11833 #construct the map with the subrange
11834 xrgbIndex = 0
11835 myRgbPoints = []
11836
11837 #first do points from original color map which are below subrange
11838 while (xrgbIndex < len(xrgbPoints)) and xrgbPoints[xrgbIndex] < subrangePt1[0]:
11839 myRgbPoints.append(xrgbPoints[xrgbIndex+0])
11840 myRgbPoints.append(xrgbPoints[xrgbIndex+1])
11841 myRgbPoints.append(xrgbPoints[xrgbIndex+2])
11842 myRgbPoints.append(xrgbPoints[xrgbIndex+3])
11843 xrgbIndex += 4
11844
11845 #add in subrange points, accounting for bottom/top cases
11846 if subrangePt1[0] > xrgbPoints[0]:
11847 for nn in subrangePt1:
11848 myRgbPoints.append(nn)
11849 for nn in subrangePt2:
11850 myRgbPoints.append(nn)
11851 else:
11852 #special case, bottom of subrange is bottom of whole range
11853 subrangePt2[0] = subrangePt1[0]
11854 for nn in subrangePt2:
11855 myRgbPoints.append(nn)
11856
11857 numXrgbPoints = int(len(xrgbPoints) / 4)
11858 if subrangePt4[0] < xrgbPoints[(numXrgbPoints-1) * 4]:
11859 for nn in subrangePt3:
11860 myRgbPoints.append(nn)
11861 for nn in subrangePt4:
11862 myRgbPoints.append(nn)
11863 else:
11864 #special case, top of subrange is top of whole range
11865 subrangePt3[0] = subrangePt4[0]
11866 for nn in subrangePt3:
11867 myRgbPoints.append(nn)
11868
11869 #add in points from original color map after subrange, skipping any points
11870 #which were subsumed in subrange
11871 while subrangePt4[0] >= xrgbPoints[xrgbIndex]:
11872 xrgbIndex += 4
11873 if xrgbIndex >= len(xrgbPoints):
11874 break
11875
11876 while xrgbIndex < len(xrgbPoints):
11877 myRgbPoints.append(xrgbPoints[xrgbIndex+0])
11878 myRgbPoints.append(xrgbPoints[xrgbIndex+1])
11879 myRgbPoints.append(xrgbPoints[xrgbIndex+2])
11880 myRgbPoints.append(xrgbPoints[xrgbIndex+3])
11881 xrgbIndex += 4
11882
11883 if PhactoriDbg(100):
11884 myDebugPrint3('subrange: [' + \
11885 str(inSubrangeMin) + ', ' + \
11886 str(inSubrangeMax) + ']\n' + \
11887 'subrange ratio: [' + \
11888 str(minHlRatio) + ', ' + \
11889 str(maxHlRatio) + ']\n' + \
11890 'myRGBPoints: \n' + str(myRgbPoints) + '\n')
11891
11892 if PhactoriDbg(100):
11893 myDebugPrint3("CalculateColorMapRGBPointsWithSubranges returing \n", 100)
11894
11895 return myRgbPoints
11896
11897
11898 global gDefault_LUT_Num_RGBPoints
11899 global gDefault_LUT_RGBPoints
11900 global gDefault_PWF_Num_Points
11901 global gDefault_PWF_Points
11902 gDefault_LUT_Num_RGBPoints = -1
11903 gDefault_LUT_RGBPoints = []
11904 gDefault_PWF_Num_Points = -1
11905 gDefault_PWF_Points = []
11906
11907 def SetMinimumMaximumColorValues(inPvDataRepresentation,
11908 inMinimum, inMaximum,
11909 inPhactoriOperation, inPhactoriRepresentation,
11910 inVariableName, inPointsOrCells):
11911 "This sets the data values which will correspond to the colors at the " \
11912 "bottom and top of the color table. Data values above or below this " \
11913 "range will be clamped to the color table bottom or top."
11914 inColorMapSettings = inPhactoriRepresentation.mColorMapSettings
11915 if PhactoriDbg(100):
11916 myDebugPrint3('phactori.SetMinimumMaximumColorValues entered, min: ' + \
11917 str(inMinimum) + ' max: ' + str(inMaximum) + '\n' + \
11918 'inVariableName: ' + inVariableName + \
11919 ' inPointsOrCells: ' + inPointsOrCells + '\n', 100)
11920
11921 if inPhactoriRepresentation.mColorVariableInfo.mVariableTypeNeedsDetection:
11922 if PhactoriDbg(100):
11923 myDebugPrint3(" variable type was undetected, returning (1)\n")
11924 return
11925 if gParaViewCatalystVersionFlag >= 40300:
11926 savedActiveSourceZ = GetActiveSource()
11927 SetActiveSource(inPhactoriOperation.GetPvFilter())
11928 if PhactoriDbg():
11929 myDebugPrint3("using ColorBy() to set color var " + \
11930 inVariableName + " " + inPointsOrCells + " 4\n")
11931 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
11932 SafeColorBy(inPvDataRepresentation, (inPointsOrCells, inVariableName))
11933 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
11934
11935 if inPhactoriRepresentation.mNameOfPresetToUse != None:
11936 if PhactoriDbg():
11937 myDebugPrint3("using preset with name: " + \
11938 inPhactoriRepresentation.mNameOfPresetToUse + "\n")
11939 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
11940 pv_4_3_PWF = GetOpacityTransferFunction(inVariableName)
11941 #second argument is rescale to data range; need to handle correctly
11942 pv_4_3_LUT.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, False)
11943 pv_4_3_PWF.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, False)
11944 #pv_4_3_LUT.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, True)
11945 #pv_4_3_PWF.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, True)
11946 allRange = inMaximum - inMinimum
11947 for ii in range(0, len(pv_4_3_LUT.RGBPoints), 4):
11948 pv_4_3_LUT.RGBPoints[ii] = inMinimum + pv_4_3_LUT.RGBPoints[ii] * allRange
11949 else:
11950 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
11951 if pv_4_3_LUT.Discretize != 1:
11952 pv_4_3_LUT.Discretize = 1
11953 if pv_4_3_LUT.NumberOfTableValues != 1024:
11954 pv_4_3_LUT.NumberOfTableValues = 1024
11955
11956 pv_4_3_PWF = GetOpacityTransferFunction(inVariableName)
11957
11958 global gDefault_LUT_Num_RGBPoints
11959 global gDefault_LUT_RGBPoints
11960 global gDefault_PWF_Num_Points
11961 global gDefault_PWF_Points
11962 if gDefault_LUT_Num_RGBPoints < 0:
11963 for ii in pv_4_3_LUT.RGBPoints:
11964 gDefault_LUT_RGBPoints.append(ii)
11965 gDefault_LUT_Num_RGBPoints = len(gDefault_LUT_RGBPoints)
11966 for ii in pv_4_3_PWF.Points:
11967 gDefault_PWF_Points.append(ii)
11968 gDefault_PWF_Num_Points = len(gDefault_PWF_Points)
11969
11970 if len(pv_4_3_LUT.RGBPoints) != gDefault_LUT_Num_RGBPoints:
11971 #revert back to default rgb points starting setup
11972 pv_4_3_LUT.RGBPoints = gDefault_LUT_RGBPoints
11973
11974 if len(pv_4_3_PWF.Points) != gDefault_PWF_Num_Points:
11975 #revert back to default points starting setup
11976 pv_4_3_PWF.Points = gDefault_PWF_Points
11977
11978 pv_4_3_LUT.ScalarRangeInitialized = 1.0
11979 pv_4_3_PWF.ScalarRangeInitialized = 1
11980
11981 pv_4_3_LUT.RescaleTransferFunction(inMinimum, inMaximum)
11982 pv_4_3_PWF.RescaleTransferFunction(inMinimum, inMaximum)
11983 #pv_4_3_LUT.LockScalarRange = 1
11984 if PhactoriDbg(100):
11985 myDebugPrint3("rgb points: " + str(pv_4_3_LUT.RGBPoints) + "\n" + \
11986 "opacity points: " + str(pv_4_3_PWF.Points) + "\n")
11987 if inPhactoriRepresentation.mUseHighlightSubranges:
11988 baseRgbPoints, myColorSpace, myNanColor = \
11989 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
11990 0.0, 1.0)
11991 if PhactoriDbg(100):
11992 myDebugPrint3(
11993 "default base rgb points: " + str( baseRgbPoints) + "\n", 100)
11994 #add each subrange into the base color map one at a time
11995 for oneSubrange in inPhactoriRepresentation.mHighlightSubranges:
11996 myRGBPoints = CalculateColorMapRGBPointsWithSubranges(baseRgbPoints,
11997 inMinimum, inMaximum, oneSubrange[0], oneSubrange[1], oneSubrange[2])
11998 baseRgbPoints = myRGBPoints
11999
12000 #adjust the color range from 0 to 1 to the overall min to max
12001 for ii in range(0, len(myRGBPoints), 4):
12002 allRange = inMaximum - inMinimum
12003 myRGBPoints[ii] = inMinimum + myRGBPoints[ii] * allRange
12004 else:
12005 myRGBPoints, myColorSpace, myNanColor = \
12006 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
12007 inMinimum, inMaximum)
12008 pv_4_3_LUT.RGBPoints = myRGBPoints
12009 pv_4_3_LUT.ColorSpace = myColorSpace
12010 pv_4_3_LUT.NanColor = myNanColor
12011 if PhactoriDbg(100):
12012 myDebugPrint3('phactori.SetMinimumMaximumColorValues returning\n')
12013
12014 SetActiveSource(savedActiveSourceZ)
12015
12016 return
12017
12018 savedActiveSourceZ = GetActiveSource()
12019 SetActiveSource(inPhactoriOperation.GetPvFilter())
12020
12021 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
12022
12023 new_var_PVLookupTable = inPvDataRepresentation.LookupTable
12024 myRGBPoints, myColorSpace, myNanColor = \
12025 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
12026 inMinimum, inMaximum)
12027 new_var_PVLookupTable.RGBPoints = myRGBPoints
12028 new_var_PVLookupTable.ColorSpace = myColorSpace
12029 if PhactoriDbg():
12030 myDebugPrint3("nan color: " + str(myNanColor) + " len: " + str(len(myNanColor)) + "\n")
12031 new_var_PVLookupTable.NanColor = myNanColor
12032
12033 if PhactoriDbg():
12034 myDebugPrint3("new lookup table (2):\n");
12035 myDebugPrint3(str(new_var_PVLookupTable) + "\n")
12036 myDebugPrint3("RGBPoints:\n");
12037 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints) + "\n")
12038
12039 try:
12040 inPvDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
12041 except:
12042 if PhactoriDbg():
12043 myDebugPrint3('no inPvDataRepresentation.ScalarOpacityFunction\n');
12044
12045 SetActiveSource(savedActiveSourceZ)
12046
12047 myDebugPrint3('phactori.SetMinimumMaximumColorValues returning (2)\n')
12048
12049 #'Closest Triad'
12050 #'Furthest Triad'
12051 #'Static Triad'
12052 #'Static Edges'
12053 #'Outer Edges'
12054 #def SetCubeAxesMode(inNewMode):
12055 # global currentPhactoriRenderViewInfo
12056 # currentPhactoriRenderViewInfo.DataRepresentation1.CubeAxesFlyMode = inNewMode
12057
12058 def ShowCubeAxesXX(inPvRenderView, inOnOrOff, inShowDataCubeAxesInfo = None):
12059 if PhactoriDbg(100):
12060 myDebugPrint3("ShowCubeAxesXX entered\n", 100)
12061 if(inOnOrOff == 'on'):
12062 if PhactoriDbg():
12063 myDebugPrint3(" ShowCubeAxesXX: turning on\n")
12064 #inPvDataRepresentation.CubeAxesVisibility = 1
12065 SetAxesGridVisibility(inPvRenderView, 1)
12066 if inShowDataCubeAxesInfo != None:
12067 inPvRenderView.AxesGrid.ShowEdges = inShowDataCubeAxesInfo.mShowEdges
12068 inPvRenderView.AxesGrid.ShowTicks = inShowDataCubeAxesInfo.mShowTicks
12069 axisXInfo = inShowDataCubeAxesInfo.mXAxisInfo
12070 axisYInfo = inShowDataCubeAxesInfo.mYAxisInfo
12071 axisZInfo = inShowDataCubeAxesInfo.mZAxisInfo
12072
12073 ##axis labels as specified
12074 if axisXInfo.mUseLabelFlag:
12075 inPvRenderView.AxesGrid.XTitle = axisXInfo.mAxisLabel
12076 if PhactoriDbg():
12077 myDebugPrint3(" x axis label set to: " + inPvRenderView.AxesGrid.XTitle + "\n")
12078 else:
12079 inPvRenderView.AxesGrid.XTitle = "X Axis"
12080 if axisYInfo.mUseLabelFlag:
12081 inPvRenderView.AxesGrid.YTitle = axisYInfo.mAxisLabel
12082 if PhactoriDbg():
12083 myDebugPrint3(" y axis label set to: " + inPvRenderView.AxesGrid.YTitle + "\n")
12084 else:
12085 inPvRenderView.AxesGrid.YTitle = "Y Axis"
12086 if axisZInfo.mUseLabelFlag:
12087 inPvRenderView.AxesGrid.ZTitle = axisZInfo.mAxisLabel
12088 if PhactoriDbg():
12089 myDebugPrint3(" z axis label set to: " + inPvRenderView.AxesGrid.ZTitle + "\n")
12090 else:
12091 inPvRenderView.AxesGrid.ZTitle = "Z Axis"
12092 else:
12093 if PhactoriDbg():
12094 myDebugPrint3(" ShowCubeAxesXX: turning off\n")
12095 #inPvDataRepresentation.CubeAxesVisibility = 0
12096 SetAxesGridVisibility(inPvRenderView, 0)
12097 if PhactoriDbg(100):
12098 myDebugPrint3("ShowCubeAxesXX returning\n", 100)
12099
12100
12101 def ShowDataColorLegendXX(inPvView,
12102 inOnOffSetting, inColorLegendPositionAndSize, inColorSettings,
12103 inColorLegendRepRef, inPvDataRep, inComponentString):
12104 """Turns on or off the display of the color bar legend showing the mapping
12105 between the color and the data value (and the name of the data value.
12106 (note this is primarily to do the paraview-side work to turn bar on or
12107 off, on to set up for rendering in the shared view, off to turn off
12108 rendering in shared view. On or off state for rendering is stored
12109 as a flag in the ioPhactoriImagesetBlock instance"""
12110
12111 global gParaViewCatalystVersionFlag
12112
12113 if PhactoriDbg(100):
12114 myDebugPrint3('phactori.ShowDataColorLegendXX entered, setting:' + \
12115 inOnOffSetting + '\n', 100)
12116 if(inOnOffSetting == 'on'):
12117 myVisibility = 1
12118 else:
12119 myVisibility = 0
12120 if inColorLegendRepRef != None:
12121 if PhactoriDbg(100):
12122 myDebugPrint3("A inColorLegendRepRef was " + \
12123 str(inColorLegendRepRef.Visibility) + \
12124 " now 0: " + str(inColorLegendRepRef) + "\n")
12125 inColorLegendRepRef.Visibility = 0
12126 myDebugPrint3(
12127 'phactori.ShowDataColorLegendXX returing with none rep: ' + \
12128 inOnOffSetting + '\n', 100)
12129 return None
12130
12131 if gParaViewCatalystVersionFlag <= 40100:
12132 localColorArrayName = \
12133 inPvDataRep.ColorArrayName
12134 else:
12135 localColorArrayName = \
12136 inPvDataRep.ColorArrayName[1]
12137
12138 if inColorLegendRepRef != None:
12139 #myDebugPrint3(' phactori.ShowDataColorLegend using rep reference\n', 100)
12140 #if inColorLegendRepRef.ColorArrayName == '':
12141 # return
12142 inPvView.OrientationAxesLabelColor = inColorSettings.mTextColor
12143 if PhactoriDbg(100):
12144 myDebugPrint3("B inColorLegendRepRef was " + \
12145 str(inColorLegendRepRef.Visibility) + \
12146 " now " + str(myVisibility) + ": " + str(inColorLegendRepRef) + "\n")
12147 inColorLegendRepRef.Visibility = myVisibility
12148 inColorLegendRepRef.LookupTable = inPvDataRep.LookupTable
12149 inColorLegendRepRef.Title = localColorArrayName
12150 inColorLegendRepRef.ComponentTitle = inComponentString
12151 #ioPhactoriImagesetBlock.mColorLegendRepRef.Color = \
12152 # inColorSettings.mTextColor
12153 if PhactoriDbg(100):
12154 myDebugPrint3(
12155 'phactori.ShowDataColorLegendXX returing with old rep: ' + \
12156 inOnOffSetting + '\n', 100)
12157 return inColorLegendRepRef
12158 #else:
12159 #myDebugPrint3(' phactori.ShowDataColorLegend have to create rep reference\n', 100)
12160
12161 if inColorLegendPositionAndSize[0] == 'parameters':
12162 legendSizeMultiplier = None
12163 legendSize = inColorLegendPositionAndSize[3]
12164 legendFontSize = inColorLegendPositionAndSize[4]
12165 else:
12166 legendSizeMultiplier = inColorLegendPositionAndSize[1]
12167 if gParaViewCatalystVersionFlag <= 40100:
12168 #our own factor to make legends smaller generally
12169 legendSizeMultiplier *= 0.6
12170 else:
12171 #legendSizeMultiplier *= 1.0
12172 legendSizeMultiplier *= 0.7
12173 #legendFontSize = int(12.0 * legendSizeMultiplier)
12174 legendFontSize = int(9.0 * legendSizeMultiplier)
12175
12176 if gParaViewCatalystVersionFlag <= 40100:
12177 colorLegendDefaultLongSize = 0.5
12178 colorLegendDefaultShortSize = 0.13
12179 else:
12180 #[0.12, 0.43]
12181 #[0.85, 0.05]
12182 colorLegendDefaultLongSize = 0.43
12183 colorLegendDefaultShortSize = 0.12
12184
12185 colorLegendAdjustedLongSize = colorLegendDefaultLongSize * legendSizeMultiplier
12186 colorLegendAdjustedShortSize = colorLegendDefaultShortSize * legendSizeMultiplier
12187 horizontalLegendSize = [colorLegendAdjustedLongSize, colorLegendAdjustedShortSize]
12188 verticalLegendSize = [colorLegendAdjustedShortSize, colorLegendAdjustedLongSize]
12189
12190 xPosForBottomTop = 0.5 - 0.5 * colorLegendAdjustedLongSize
12191 yPosForLeftRight = 0.5 - 0.5 * colorLegendAdjustedShortSize
12192
12193 if gParaViewCatalystVersionFlag < 50400:
12194 if inColorLegendPositionAndSize[0] == 'top':
12195 legendOrientation = 'Horizontal'
12196 legendSize = horizontalLegendSize
12197 legendPosition=[xPosForBottomTop, 0.85]
12198 elif inColorLegendPositionAndSize[0] == 'bottom':
12199 legendOrientation = 'Horizontal'
12200 legendSize = horizontalLegendSize
12201 legendPosition=[xPosForBottomTop, 0.02]
12202 elif inColorLegendPositionAndSize[0] == 'left':
12203 legendOrientation = 'Vertical'
12204 legendSize = verticalLegendSize
12205 legendPosition=[0.065, yPosForLeftRight]
12206 elif inColorLegendPositionAndSize[0] == 'right':
12207 legendOrientation = 'Vertical'
12208 legendSize = verticalLegendSize
12209 legendPosition=[0.9, yPosForLeftRight]
12210 elif inColorLegendPositionAndSize[0] == 'top left':
12211 legendOrientation = 'Horizontal'
12212 legendSize = horizontalLegendSize
12213 legendPosition=[0.065, 0.85]
12214 elif inColorLegendPositionAndSize[0] == 'top right':
12215 legendOrientation = 'Horizontal'
12216 legendSize = horizontalLegendSize
12217 legendPosition=[0.7, 0.85]
12218 elif inColorLegendPositionAndSize[0] == 'bottom left':
12219 legendOrientation = 'Horizontal'
12220 legendSize = horizontalLegendSize
12221 #legendPosition=[0.065, 0.85]
12222 legendPosition=[0.065, 0.01]
12223 elif inColorLegendPositionAndSize[0] == 'bottom right':
12224 legendOrientation = 'Horizontal'
12225 legendSize = horizontalLegendSize
12226 #legendPosition=[0.7, 0.05]
12227 legendPosition=[0.7, 0.01]
12228 elif inColorLegendPositionAndSize[0] == 'parameters':
12229 legendOrientation = inColorLegendPositionAndSize[1]
12230 legendSize = horizontalLegendSize
12231 legendPosition = inColorLegendPositionAndSize[2]
12232 else:
12233 legendOrientation = 'Horizontal'
12234 legendSize = horizontalLegendSize
12235 #legendPosition=[xPosForBottomTop, 0.05]
12236 legendPosition=[xPosForBottomTop, 0.01]
12237
12238 if PhactoriDbg():
12239 myDebugPrint3("legend info:\n legendSizeMultiplier: " + str(legendSizeMultiplier) + "\n" \
12240 " legendSize: " + str(legendSize) + "\n" \
12241 " legendPos: " + str(legendPosition) + "\n"\
12242 " legendOrientation: " + str(legendOrientation) + "\n"\
12243 " legendFontSize: " + str(legendFontSize) + "\n")
12244
12245 elif gParaViewCatalystVersionFlag < 51000:
12246 defaultLegendLength = 0.33
12247 defaultMidPos = 0.5 - 0.5*defaultLegendLength
12248 #legendFontSize = 16
12249 #legendSize = 1.0
12250 #validPositions = ['UpperLeftCorner', 'UpperRightCorner',
12251 # 'LowerLeftCorner', 'LowerRightCorner',
12252 # 'UpperCenter', 'LowerCenter']
12253 legendPosition=[0.0, 0.0]
12254 if inColorLegendPositionAndSize[0] == 'top':
12255 legendOrientation = 'Horizontal'
12256 legendWindowLocation = 'UpperCenter'
12257 elif inColorLegendPositionAndSize[0] == 'bottom':
12258 legendOrientation = 'Horizontal'
12259 legendWindowLocation = 'LowerCenter'
12260 elif inColorLegendPositionAndSize[0] == 'left':
12261 legendOrientation = 'Vertical'
12262 legendPosition=[0.02, defaultMidPos]
12263 legendWindowLocation = 'AnyLocation'
12264 elif inColorLegendPositionAndSize[0] == 'right':
12265 legendOrientation = 'Vertical'
12266 legendPosition=[0.89, defaultMidPos]
12267 legendWindowLocation = 'AnyLocation'
12268 elif inColorLegendPositionAndSize[0] == 'top left':
12269 legendOrientation = 'Vertical'
12270 legendWindowLocation = 'UpperLeftCorner'
12271 elif inColorLegendPositionAndSize[0] == 'top right':
12272 legendOrientation = 'Vertical'
12273 legendWindowLocation = 'UpperRightCorner'
12274 elif inColorLegendPositionAndSize[0] == 'bottom left':
12275 legendOrientation = 'Vertical'
12276 legendWindowLocation = 'LowerLeftCorner'
12277 elif inColorLegendPositionAndSize[0] == 'bottom right':
12278 legendOrientation = 'Vertical'
12279 legendWindowLocation = 'LowerRightCorner'
12280 elif inColorLegendPositionAndSize[0] == 'parameters':
12281 legendOrientation = inColorLegendPositionAndSize[1]
12282 legendPosition = inColorLegendPositionAndSize[2]
12283 legendWindowLocation = 'AnyLocation'
12284 else:
12285 legendOrientation = 'Vertical'
12286 legendWindowLocation = 'LowerRightCorner'
12287 else:
12288 defaultLegendLength = 0.33
12289 defaultMidPos = 0.5 - 0.5*defaultLegendLength
12290 #legendFontSize = 16
12291 #legendSize = 1.0
12292 #validPositions = ['UpperLeftCorner', 'UpperRightCorner',
12293 # 'LowerLeftCorner', 'LowerRightCorner',
12294 # 'UpperCenter', 'LowerCenter']
12295 legendPosition=[0.0, 0.0]
12296 if inColorLegendPositionAndSize[0] == 'top':
12297 legendOrientation = 'Horizontal'
12298 legendWindowLocation = 'Upper Center'
12299 elif inColorLegendPositionAndSize[0] == 'bottom':
12300 legendOrientation = 'Horizontal'
12301 legendWindowLocation = 'Lower Center'
12302 elif inColorLegendPositionAndSize[0] == 'left':
12303 legendOrientation = 'Vertical'
12304 legendPosition=[0.02, defaultMidPos]
12305 legendWindowLocation = 'Any Location'
12306 elif inColorLegendPositionAndSize[0] == 'right':
12307 legendOrientation = 'Vertical'
12308 legendPosition=[0.89, defaultMidPos]
12309 legendWindowLocation = 'Any Location'
12310 elif inColorLegendPositionAndSize[0] == 'top left':
12311 legendOrientation = 'Vertical'
12312 legendWindowLocation = 'Upper Left Corner'
12313 elif inColorLegendPositionAndSize[0] == 'top right':
12314 legendOrientation = 'Vertical'
12315 legendWindowLocation = 'Upper Right Corner'
12316 elif inColorLegendPositionAndSize[0] == 'bottom left':
12317 legendOrientation = 'Vertical'
12318 legendWindowLocation = 'Lower Left Corner'
12319 elif inColorLegendPositionAndSize[0] == 'bottom right':
12320 legendOrientation = 'Vertical'
12321 legendWindowLocation = 'Lower Right Corner'
12322 elif inColorLegendPositionAndSize[0] == 'parameters':
12323 legendOrientation = inColorLegendPositionAndSize[1]
12324 legendPosition = inColorLegendPositionAndSize[2]
12325 legendWindowLocation = 'Any Location'
12326 else:
12327 legendOrientation = 'Vertical'
12328 legendWindowLocation = 'Lower Right Corner'
12329
12330 #newScalarBarWidgetRepresentation = CreateScalarBar( Title=inPvDataRep.ColorArrayName, Position2=[0.13, 0.5], TitleOpacity=1.0, TitleShadow=0, AutomaticLabelFormat=1, TitleFontSize=12, TitleColor=[1.0, 1.0, 1.0], AspectRatio=20.0, NumberOfLabels=5, ComponentTitle='', Resizable=1, TitleFontFamily='Arial', Visibility=myVisibility, LabelFontSize=12, LabelFontFamily='Arial', TitleItalic=0, Selectable=0, LabelItalic=0, Enabled=0, LabelColor=[1.0, 1.0, 1.0], Position=[0.9, 0.31396255850234012], LabelBold=0, UseNonCompositedRenderer=1, LabelOpacity=1.0, TitleBold=0, LabelFormat='%-#6.3g', Orientation='Vertical', LabelShadow=0, LookupTable=inPvDataRep.LookupTable, Repositionable=1 )
12331 if gParaViewCatalystVersionFlag <= 40100:
12332 newScalarBarWidgetRepresentation = CreateScalarBar(Title=localColorArrayName,
12333 Orientation=legendOrientation,
12334 Position=legendPosition,
12335 Position2 = legendSize,
12336 Visibility=myVisibility,
12337 LookupTable=inPvDataRep.LookupTable,
12338 LabelFontSize=legendFontSize,
12339 TitleOpacity=1.0,
12340 TitleShadow=0,
12341 AutomaticLabelFormat=1,
12342 TitleFontSize=legendFontSize,
12343 TitleColor=inColorSettings.mTextColor,
12344 AspectRatio=20.0,
12345 NumberOfLabels=5,
12346 ComponentTitle='',
12347 Resizable=1,
12348 TitleFontFamily='Arial',
12349 LabelFontFamily='Arial',
12350 TitleItalic=0,
12351 Selectable=0,
12352 LabelItalic=0,
12353 Enabled=0,
12354 LabelColor=inColorSettings.mTextColor,
12355 LabelBold=0,
12356 UseNonCompositedRenderer=1,
12357 LabelOpacity=1.0,
12358 TitleBold=0,
12359 LabelFormat='%-#6.3g',
12360 LabelShadow=0,
12361 Repositionable=1)
12362 elif gParaViewCatalystVersionFlag < 50400:
12363 newScalarBarWidgetRepresentation = CreateScalarBar(Title=localColorArrayName,
12364 Orientation=legendOrientation,
12365 Position=legendPosition,
12366 Position2 = legendSize,
12367 Visibility=myVisibility,
12368 LookupTable=inPvDataRep.LookupTable,
12369 LabelFontSize=legendFontSize,
12370 #TitleOpacity=1.0,
12371 #TitleShadow=0,
12372 #AutomaticLabelFormat=1,
12373 TitleFontSize=legendFontSize,
12374 TitleColor=inColorSettings.mTextColor,
12375 AspectRatio=20.0,
12376 #NumberOfLabels=5,
12377 ComponentTitle='',
12378 #Resizable=1,
12379 #TitleFontFamily='Arial',
12380 #LabelFontFamily='Arial',
12381 #TitleItalic=0,
12382 #Selectable=0,
12383 #LabelItalic=0,
12384 #Enabled=0,
12385 LabelColor=inColorSettings.mTextColor,
12386 #LabelBold=0,
12387 #UseNonCompositedRenderer=1,
12388 #LabelOpacity=1.0,
12389 #TitleBold=0,
12390 #LabelFormat='%-#6.3g',
12391 #LabelShadow=0,
12392 #Repositionable=1
12393 )
12394 elif gParaViewCatalystVersionFlag < 51000:
12395 newScalarBarWidgetRepresentation = CreateScalarBar(
12396 Title=localColorArrayName, ComponentTitle='')
12397 newScalarBarWidgetRepresentation.Orientation = legendOrientation
12398 newScalarBarWidgetRepresentation.WindowLocation = legendWindowLocation
12399 if legendWindowLocation == 'AnyLocation':
12400 newScalarBarWidgetRepresentation.Position = legendPosition
12401 if PhactoriDbg():
12402 nbwr = newScalarBarWidgetRepresentation
12403 myDebugPrint3("newScalarBarWidgetRepresentation:\n" +\
12404 str(nbwr) + "\n" +\
12405 " Title: " + str(nbwr.Title) + "\n" +\
12406 " ComponentTitle: " + str(nbwr.ComponentTitle) + "\n" +\
12407 " WindowLocation: " + str(nbwr.WindowLocation) + "\n" +\
12408 " Position: " + str(nbwr.Position) + "\n" +\
12409 " ScalarBarLength: " + str(nbwr.ScalarBarLength) + "\n" +\
12410 " ScalarBarThickness: " + str(nbwr.ScalarBarThickness) + "\n" +\
12411 " Orientation: " + str(nbwr.Orientation) + "\n" +\
12412 " LabelFontSize: " + str(nbwr.LabelFontSize) + "\n" +\
12413 " TitleFontSize: " + str(nbwr.TitleFontSize) + "\n" +\
12414 " LabelFontFamily: " + str(nbwr.LabelFontFamily) + "\n" +\
12415 " TitleFontFamily: " + str(nbwr.TitleFontSize) + "\n")
12416 #" LockPosition: " + str(nbwr.LockPosition) + "\n" +\
12417 #" Repositionable: " + str(nbwr.Repositionable) + "\n" +\
12418 #" AutoOrient: " + str(nbwr.AutoOrient) + "\n" +\
12419 else:
12420 pv_4_3_LUT = GetColorTransferFunction(inPvDataRep.ColorArrayName[1])
12421 newScalarBarWidgetRepresentation = GetScalarBar(pv_4_3_LUT, inPvView)
12422 newScalarBarWidgetRepresentation.Orientation = legendOrientation
12423 global gTemporaryGlobalImageTextColor
12424 newScalarBarWidgetRepresentation.TitleColor = gTemporaryGlobalImageTextColor
12425 newScalarBarWidgetRepresentation.LabelColor = gTemporaryGlobalImageTextColor
12426 newScalarBarWidgetRepresentation.WindowLocation = legendWindowLocation
12427 if legendWindowLocation == 'AnyLocation':
12428 newScalarBarWidgetRepresentation.Position = legendPosition
12429 if PhactoriDbg():
12430 nbwr = newScalarBarWidgetRepresentation
12431 nbwr.ComponentTitle = ""
12432 myDebugPrint3("newScalarBarWidgetRepresentation:\n" +\
12433 str(nbwr) + "\n" +\
12434 " Title: " + str(nbwr.Title) + "\n" +\
12435 " ComponentTitle: " + str(nbwr.ComponentTitle) + "\n" +\
12436 " WindowLocation: " + str(nbwr.WindowLocation) + "\n" +\
12437 " Position: " + str(nbwr.Position) + "\n" +\
12438 " ScalarBarLength: " + str(nbwr.ScalarBarLength) + "\n" +\
12439 " ScalarBarThickness: " + str(nbwr.ScalarBarThickness) + "\n" +\
12440 " Orientation: " + str(nbwr.Orientation) + "\n" +\
12441 " LabelFontSize: " + str(nbwr.LabelFontSize) + "\n" +\
12442 " TitleFontSize: " + str(nbwr.TitleFontSize) + "\n" +\
12443 " LabelFontFamily: " + str(nbwr.LabelFontFamily) + "\n" +\
12444 " TitleFontFamily: " + str(nbwr.TitleFontSize) + "\n")
12445 #" LockPosition: " + str(nbwr.LockPosition) + "\n" +\
12446 #" Repositionable: " + str(nbwr.Repositionable) + "\n" +\
12447 #" AutoOrient: " + str(nbwr.AutoOrient) + "\n" +\
12448
12449 inPvView.OrientationAxesLabelColor = inColorSettings.mTextColor
12450 inPvView.Representations.append(newScalarBarWidgetRepresentation)
12451 #ioPhactoriImagesetBlock.mColorLegendRepRef = \
12452 # newScalarBarWidgetRepresentation
12453 if PhactoriDbg():
12454 myDebugPrint3("current lookup table:\n");
12455 if PhactoriDbg():
12456 myDebugPrint3(str(inPvDataRep.LookupTable) + '\n')
12457 if PhactoriDbg():
12458 myDebugPrint3("RGBPoints:\n");
12459 if PhactoriDbg():
12460 if gParaViewCatalystVersionFlag <= 40100:
12461 myLocalRGBPoints = inPvDataRep.LookupTable.RGBPoints
12462 else:
12463 pv_4_3_LUT = GetColorTransferFunction(
12464 inPvDataRep.ColorArrayName[1])
12465 myLocalRGBPoints = pv_4_3_LUT.RGBPoints
12466 myDebugPrint3(str(myLocalRGBPoints) + '\n')
12467 if PhactoriDbg():
12468 myDebugPrint3("widget:\n");
12469 if PhactoriDbg():
12470 myDebugPrint3(str(newScalarBarWidgetRepresentation) + '\n')
12471
12472 if PhactoriDbg(100):
12473 myDebugPrint3('phactori.ShowDataColorLegendXX returing with new rep: ' + \
12474 inOnOffSetting + '\n', 100)
12475
12476 return newScalarBarWidgetRepresentation
12477
12478 def ApplyClipPlane(inNormal, inOrigin, inClipPlaneFilterName):
12479 newClip = Clip(ClipType = "Plane")
12480 newClip.ClipType.Normal = inNormal
12481 newClip.ClipType.Origin = inOrigin
12482 SetActiveSource(newClip);
12483 AddFilterToFilterMap(inClipPlaneFilterName, newClip)
12484
12485 def TempAddTestFiltersAfterDispl():
12486 """create the clip plane filter for ParaView"""
12487 if PhactoriDbg(100):
12488 myDebugPrint3('TempAddTestFiltersAfterDispl entered\n', 100)
12489 #info in block class should already be parsed and checked
12490
12491 #savedActiveSource = GetActiveSource()
12492 #newCellToPointFilter = CellDatatoPointData()
12493
12494 ##SetActiveSource(newCellToPointFilter)
12495 ##SetActiveSource(savedActiveSource)
12496
12497 #SetActiveSource(newCellToPointFilter)
12498 #newCellToPointFilter.UpdatePipeline()
12499 #AddFilterToFilterMap('initialCellToPointFilter', newCellToPointFilter)
12500
12501 #newContourFilter = Contour(PointMergeMethod="Uniform Binning")
12502 #myDebugPrint3(" contour filter is: " + str(newContourFilter) + "\n")
12503 #newContourFilter.PointMergeMethod = "Uniform Binning"
12504 #newContourFilter.Isosurfaces = [9687]
12505 #myDebugPrint3(" variable is: " + str('VON_MISES') + "\n")
12506 #newContourFilter.ContourBy = ['POINTS', 'Global Node Id']
12507
12508 #myDebugPrint3(" still okay\n")
12509 #SetActiveSource(newContourFilter)
12510 #AddFilterToFilterMap('initialContourFilter', newContourFilter)
12511
12512 #Contour2 = Contour( guiName="Contour2", Isosurfaces=[9882.0], ComputeNormals=1, GenerateTriangles=1, ComputeGradients=0, ComputeScalars=0, ContourBy=['POINTS', 'GlobalNodeId'], PointMergeMethod="Uniform Binning" )
12513 #Contour2.PointMergeMethod.Numberofpointsperbucket = 8
12514 #Contour2.PointMergeMethod.Divisions = [50, 50, 50]
12515
12516 if PhactoriDbg(100):
12517 myDebugPrint3('TempAddTestFiltersAfterDispl returning\n', 100)
12518
12519
12520 #makes a filter which pulls a component out of a vector so it can be treated
12521 #separately
12522 def ExtractComponentFromVectorVariable(inVariableName, inWhichComponent, inResultName = 'Result', inFilterName = None):
12523
12524 if inFilterName == None:
12525 inFilterName = "ExtractComponent_" + str(inWhichComponent) + GetSeparatorString() + inVariableName
12526 if PhactoriDbg(100):
12527 myDebugPrint3('phactori.ExtractComponentFromVectorVariable entered, variable name:' + \
12528 inVariableName + ', ' + inResultName + ', ' + \
12529 str(inWhichComponent) + '\n', 100)
12530
12531 #theActiveSource = GetActiveSource()
12532 #if(theActiveSource == None):
12533 # myDebugPrint3('phactori.ColorByVectorVariable no active source, returning:\n', 100)
12534 # return
12535
12536 #debugPrintRepresentationsAndVisibility(currentRvi)
12537 newFunctionString = ""
12538 if(inWhichComponent == 0):
12539 newFunctionString = inVariableName + '_X'
12540 elif(inWhichComponent == 1):
12541 newFunctionString = inVariableName + '_Y'
12542 elif(inWhichComponent == 2):
12543 newFunctionString = inVariableName + '_Z'
12544 else:
12545 if PhactoriDbg():
12546 myDebugPrint3('phactori.ColorByVectorVariable unexpected component (needs 0, 1, or 2)\n')
12547 exit()
12548
12549 #DisplacementWarpCalculator = Calculator( guiName="Calculator1", Function=FunctionString, ReplacementValue=0.0, ResultArrayName='Result', ReplaceInvalidResults=1, AttributeMode='point_data', CoordinateResults=1 )
12550
12551 calc2Source = Calculator( guiName=inFilterName, Function=newFunctionString, ReplacementValue=0.0, ResultArrayName=inResultName, ReplaceInvalidResults=1)
12552
12553 if PhactoriDbg():
12554 myDebugPrint3('Calulator2 has ' + str(calc2Source.PointData.GetNumberOfArrays()) + ' point data items\n');
12555 PointDataList = []
12556 for ii in range(calc2Source.PointData.GetNumberOfArrays()):
12557 PointDataList.append(calc2Source.PointData.GetArray(ii).Name)
12558 if PhactoriDbg():
12559 myDebugPrint3('calc2Source point data items: ' + str(PointDataList) + '\n');
12560 #SetActiveSource(currentSi.ActiveSource);
12561
12562 #tempDataRepresentation = GetDisplayProperties(currentSi.ActiveSource)
12563 #tempDataRepresentation.Visibility = 0
12564 SetActiveSource(calc2Source);
12565 #currentSi.ActiveSource.ResultArrayName = currentSi.ActiveSource.Function
12566 #currentSi.ActiveSource = calc2Source;
12567 AddFilterToFilterMap(inFilterName, calc2Source)
12568 #myDebugPrint3('calculator function: ' + currentSi.ActiveSource.Function + '\n');
12569 #originalSi = currentSi
12570
12571 global collectFrameCount
12572 collectFrameCount = 0
12573
12574 def CollectCells2(inClientSideData, inBlockIndex, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir):
12575 if PhactoriDbg():
12576 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' Entering CollectCells2: ' + inClientSideData.GetClassName() + '\n')
12577 if inClientSideData.GetClassName() == "vtkMultiBlockDataSet":
12578 numBlocks = inClientSideData.GetNumberOfBlocks()
12579 if PhactoriDbg():
12580 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is vtkMultiBlockDataSet, recursing, numblocks: ' + str(numBlocks) + '\n')
12581 for ii in range(0, numBlocks):
12582 oneBlock = inClientSideData.GetBlock(ii)
12583 if(oneBlock != None):
12584 CollectCells2(oneBlock, ii, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir)
12585 #if oneBlock.GetClassName() == "vtkExodusIIMultiBlockDataSet":
12586 # myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' vtkExodusIIMultiBlockDataSet breaks loop\n')
12587 # break
12588 elif inClientSideData.GetClassName() == "vtkExodusIIMultiBlockDataSet":
12589 numBlocks = inClientSideData.GetNumberOfBlocks()
12590 if PhactoriDbg():
12591 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is vtkExodusIIMultiBlockDataSet, not recursing, numblocks: ' + str(numBlocks) + '\n')
12592 for ii in range(0, numBlocks):
12593 oneBlock = inClientSideData.GetBlock(ii)
12594 if(oneBlock != None):
12595 CollectCells2(oneBlock, ii, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir)
12596 else:
12597 cellData = inClientSideData.GetCellData()
12598 tearArray = cellData.GetArray(cellVariableName)
12599 #idArray = cellData.GetArray('GlobalElementId')
12600 numTuples = tearArray.GetNumberOfTuples()
12601 if PhactoriDbg():
12602 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is not vtkMultiBlockDataSet, collecting ' + str(numTuples) + '\n')
12603 global collectFrameCount
12604 appendCount = 0
12605 for jj in range(0, numTuples):
12606 ioTotalCellCount[0] = ioTotalCellCount[0] + 1
12607 tearVal = tearArray.GetTuple1(jj)
12608 testResult = False
12609 if thresholdDir == 1:
12610 if tearVal > thresholdValue:
12611 testResult = True
12612 else:
12613 if tearVal < thresholdValue:
12614 testResult = True
12615 if testResult:
12616 #elemId = idArray.GetTuple1(jj)
12617 listItem = [SmartGetLocalProcessId(), inBlockIndex, jj, tearVal, collectFrameCount]
12618 ioCollectList.append(listItem)
12619 if(appendCount == 0):
12620 if PhactoriDbg():
12621 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + 'listing first few appended (up to 20)\n')
12622 if(appendCount < 20):
12623 if PhactoriDbg():
12624 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' appending item: ' + str(listItem) + '\n')
12625 appendCount += 1
12626 if PhactoriDbg():
12627 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' Leaving CollectCells2\n')
12628
12629
12630 def CollectCells1(cellVariableName, thresholdValue, thresholdDir):
12631 if PhactoriDbg():
12632 myDebugPrint3('Entering CollectCells1 var ' + cellVariableName + '\n')
12633 global collectFrameCount
12634 collectFrameCount = collectFrameCount + 1
12635 xx = GetActiveSource()
12636 collectedCells = []
12637 xxdata = xx.GetClientSideObject().GetOutputDataObject(0)
12638 totalCellCount = [0]
12639 CollectCells2(xxdata, 0, collectedCells, totalCellCount, cellVariableName, thresholdValue, thresholdDir)
12640 #myDebugPrint3(' collection result:\n' + str(collectedCells) + '\n')
12641 if PhactoriDbg():
12642 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' total cells: ' + str(totalCellCount) + ' number of collected cells: ' + str(len(collectedCells)) + '\n')
12643 if PhactoriDbg():
12644 myDebugPrint3(' last 20: \n')
12645 for ii in range(0,20):
12646 index = len(collectedCells) - 1 - ii
12647 if index >= 0:
12648 if PhactoriDbg():
12649 myDebugPrint3(' ' + str(collectedCells[index]) + ' ')
12650 if PhactoriDbg():
12651 myDebugPrint3('\n')
12652 if PhactoriDbg():
12653 myDebugPrint3('Leaving CollectCells1\n')
12654 return collectedCells
12655
12656 def UseReduceToSumArrayOfInts(ioListOfValues):
12657 if PhactoriDbg(100):
12658 myDebugPrint3('UseReduceToSumArrayOfInts entered\n', 100)
12659 if PhactoriDbg():
12660 myDebugPrint3(' before reduced: ' + str(ioListOfValues) + '\n');
12661 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
12662 globalController = pm.GetGlobalController()
12663 localarray = vtk.vtkIntArray()
12664 numberOfValues = len(ioListOfValues)
12665 localarray.SetNumberOfTuples(numberOfValues)
12666 for jj in range(0, numberOfValues):
12667 localarray.SetValue(jj, ioListOfValues[jj])
12668 globalarray = vtk.vtkIntArray()
12669 globalarray.SetNumberOfTuples(numberOfValues)
12670 globalController.AllReduce(localarray, globalarray, 2)
12671 for jj in range(0, numberOfValues):
12672 ioListOfValues[jj] = globalarray.GetTuple1(jj)
12673 if PhactoriDbg():
12674 myDebugPrint3(' reduced: ' + str(ioListOfValues) + '\n');
12675 if PhactoriDbg(100):
12676 myDebugPrint3('UseReduceToSumArrayOfInts returning\n', 100)
12677
12678 #called by UseReduceToSpreadValues to actually do Reduce
12679 def UseReduceToSpreadPositiveValues(ioListOfValues):
12680 if PhactoriDbg(100):
12681 myDebugPrint3('UseReduceToSpreadPositiveValues entered\n', 100)
12682 if PhactoriDbg():
12683 myDebugPrint3(' before reduced: ' + str(ioListOfValues) + '\n');
12684 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
12685 globalController = pm.GetGlobalController()
12686 localarray = vtk.vtkDoubleArray()
12687 numberOfValues = len(ioListOfValues)
12688 localarray.SetNumberOfTuples(numberOfValues)
12689 for jj in range(0, numberOfValues):
12690 localarray.SetValue(jj, ioListOfValues[jj])
12691 globalarray = vtk.vtkDoubleArray()
12692 globalarray.SetNumberOfTuples(numberOfValues)
12693 globalController.AllReduce(localarray, globalarray, 0)
12694 for jj in range(0, numberOfValues):
12695 ioListOfValues[jj] = globalarray.GetTuple1(jj)
12696 if PhactoriDbg():
12697 myDebugPrint3(' reduced: ' + str(ioListOfValues) + '\n');
12698 if PhactoriDbg(100):
12699 myDebugPrint3('UseReduceToSpreadPositiveValues returning\n', 100)
12700
12701
12702 #used by GetAndReduceViewControl to read view control values from a file on
12703 #one process, then use Reduce to spread the values to all processes
12704 def UseReduceToSpreadValues(ioListOfValues):
12705 #assumes values for all processes are 0.0 except one, uses trick to only do max
12706
12707 if PhactoriDbg(100):
12708 myDebugPrint3('UseReduceToSpreadValues entered\n', 100)
12709 if PhactoriDbg():
12710 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' start values: ' + str(ioListOfValues) + '\n')
12711 listOfValuePairs = []
12712 numberOfValues = len(ioListOfValues)
12713 for ii in range(0, numberOfValues):
12714 if ioListOfValues[ii] >= 0.0:
12715 listOfValuePairs.append(ioListOfValues[ii])
12716 listOfValuePairs.append(0.0)
12717 else:
12718 listOfValuePairs.append(0.0)
12719 listOfValuePairs.append(-ioListOfValues[ii])
12720 if PhactoriDbg():
12721 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' paired values: ' + str(listOfValuePairs) + '\n')
12722 UseReduceToSpreadPositiveValues(listOfValuePairs)
12723 for ii in range(0, numberOfValues):
12724 value = listOfValuePairs[ii*2]
12725 if value == 0.0:
12726 value = listOfValuePairs[ii*2+1]
12727 if value != 0.0:
12728 value = -value
12729 ioListOfValues[ii] = value
12730
12731 if PhactoriDbg():
12732 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' final values: ' + str(ioListOfValues) + '\n')
12733 if PhactoriDbg(100):
12734 myDebugPrint3('UseReduceToSpreadValues returning\n', 100)
12735
12736 def GetCurrentSource():
12737 return GetActiveSource()
12738
12739 def dummyTest1():
12740 print('####in dummyTest1')
12741
12742 global gPlotView1Pts
12743 gPlotView1Pts = None
12744
12745 global ProgrammableSourceInput
12746 ProgrammableSourceInput = None
12747 global ProgrammableSource2
12748 ProgrammableSource2 = None
12749
12750 class PlotValMinMaxTrkC:
12751 def __init__(self):
12752 self.mThisCbMin = 0.0
12753 self.mThisCbMax = 0.0
12754 self.mThisCbInitialized = False
12755 self.mAllMin = 0.0
12756 self.mAllMax = 0.0
12757 self.mAllInitialized = False
12758
12759 #sets minimum and maximum plot ranges, and allows there to not be
12760 #a minimmum and/or maximum as well
12761 self.mLowestTop = 0.0
12762 self.mUseLowestTop = False
12763 self.mLowestBot = 0.0
12764 self.mUseLowestBot = False
12765 self.mHighestTop = 0.0
12766 self.mUseHighestTop = False
12767 self.mHighestBot = 0.0
12768 self.mUseHighestBot = False
12769
12770 self.mMinToUse = 0.0
12771 self.mMaxToUse = 0.0
12772
12773 self.mUseCumulativeRange = False
12774
12775 def SetFromRestartInfo(self, inJson):
12776 """given a map (json format), use the info in the map to set the
12777 tracker state--this reads the info created out in GetRestartInfo"""
12778
12779 inJsonIsGood = True
12780 if 'mAll' not in inJson:
12781 if PhactoriDbg():
12782 myDebugPrint3(
12783 'PlotValMinMaxTrkC::SetFromRestartInfo mAll not in inJson\n')
12784 inJsonIsGood = False
12785 if 'mLowestTop' not in inJson:
12786 if PhactoriDbg():
12787 myDebugPrint3(
12788 'PlotValMinMaxTrkC::SetFromRestartInfo mLowestTop not in inJson\n')
12789 inJsonIsGood = False
12790 if 'mLowestBot' not in inJson:
12791 if PhactoriDbg():
12792 myDebugPrint3(
12793 'PlotValMinMaxTrkC::SetFromRestartInfo mLowestBot not in inJson\n')
12794 inJsonIsGood = False
12795 if 'mHighestTop' not in inJson:
12796 if PhactoriDbg():
12797 myDebugPrint3(
12798 'PlotValMinMaxTrkC::SetFromRestartInfo mHighestTop not in inJson\n')
12799 inJsonIsGood = False
12800 if 'mHighestBot' not in inJson:
12801 if PhactoriDbg():
12802 myDebugPrint3(
12803 'PlotValMinMaxTrkC::SetFromRestartInfo mHighestBot not in inJson\n')
12804 inJsonIsGood = False
12805 if 'mMinMaxToUse' not in inJson:
12806 if PhactoriDbg():
12807 myDebugPrint3(
12808 'PlotValMinMaxTrkC::SetFromRestartInfo mMinMaxToUse not in inJson\n')
12809 inJsonIsGood = False
12810 if 'mUseCumulativeRange' not in inJson:
12811 if PhactoriDbg():
12812 myDebugPrint3('PlotValMinMaxTrkC::SetFromRestartInfo " + \
12813 "mUseCumulativeRange not in inJson\n')
12814 inJsonIsGood = False
12815 if inJsonIsGood == False:
12816 return
12817
12818 #thisCbItem = inJson['mThisCb']
12819 #self.mThisCbInitialized = thisCbItem[0]
12820 #self.mThisCbMin = thisCbItem[1]
12821 #self.mThisCbMax = thisCbItem[2]
12822
12823 allItem = inJson['mAll']
12824 self.mAllInitialized = allItem[0]
12825 self.mAllMin = allItem[1]
12826 self.mAllMax = allItem[2]
12827
12828 lowestTopItem = inJson['mLowestTop']
12829 self.mUseLowestTop = lowestTopItem[0]
12830 self.mLowestTop = lowestTopItem[1]
12831
12832 lowestBotItem = inJson['mLowestBot']
12833 self.mUseLowestBot = lowestBotItem[0]
12834 self.mLowestBot = lowestBotItem[1]
12835
12836 highestTopItem = inJson['mHighestTop']
12837 self.mUseHighestTop = highestTopItem[0]
12838 self.mHighestTop = highestTopItem[1]
12839
12840 highestBotItem = inJson['mHighestBot']
12841 self.mUseHighestBot = highestBotItem[0]
12842 self.mHighestBot = highestBotItem[1]
12843
12844 minMaxToUseItem = inJson['mMinMaxToUse']
12845 self.mMinToUse = minMaxToUseItem[0]
12846 self.mMaxToUse = minMaxToUseItem[1]
12847
12848 self.mUseCumulativeRange = inJson["mUseCumulativeRange"]
12849 if PhactoriDbg():
12850 myDebugPrint3("PlotValMinMaxTrkC::SetFromRestartInfo state loaded:\n"
12851 + self.SelfToStr())
12852
12853 def GetRestartInfo(self):
12854 """construct, in python map/json info from this PlotValMinMaxTrkC instance
12855 which contains the information which would be needed to restore the
12856 instance to the proper state after a simulation restart.
12857 Return the restart info map/json"""
12858 newJsonItem = {}
12859 #newJsonItem["mThisCb"] = [self.mThisCbInitialized,
12860 # self.mThisCbMin, self.mThisCbMax]
12861 newJsonItem["mAll"] = [self.mAllInitialized,
12862 self.mAllMin, self.mAllMax]
12863 newJsonItem["mLowestTop"] = [self.mUseLowestTop, self.mLowestTop]
12864 newJsonItem["mLowestBot"] = [self.mUseLowestBot, self.mLowestBot]
12865 newJsonItem["mHighestTop"] = [self.mUseHighestTop, self.mHighestTop]
12866 newJsonItem["mHighestBot"] = [self.mUseHighestBot, self.mHighestBot]
12867 newJsonItem["mMinMaxToUse"] = [self.mMinToUse, self.mMaxToUse]
12868 newJsonItem["mUseCumulativeRange"] = self.mUseCumulativeRange
12869 if PhactoriDbg():
12870 myDebugPrint3("PlotValMinMaxTrkC::GetRestartInfo state saved:\n"
12871 + self.SelfToStr())
12872 return newJsonItem
12873
12874 def SelfToStr(self):
12875 retStr = "PlotValMinMaxTrkC info:" +\
12876 "\n mUseCumulativeRange: " + str(self.mUseCumulativeRange) +\
12877 "\n mThisCbInitialized: " + str(self.mThisCbInitialized) +\
12878 "\n mThisCbMin: " + repr(self.mThisCbMin) +\
12879 "\n mThisCbMax: " + repr(self.mThisCbMax) +\
12880 "\n mAllInitialized: " + str(self.mAllInitialized) +\
12881 "\n mAllMin: " + repr(self.mAllMin) +\
12882 "\n mAllMax: " + repr(self.mAllMax) +\
12883 "\n mLowestBot: " + repr(self.mLowestBot) +\
12884 "\n mHighestBot: " + repr(self.mHighestBot) +\
12885 "\n mLowestTop: " + repr(self.mLowestTop) +\
12886 "\n mHighestTop: " + str(self.mHighestTop) +\
12887 "\n mUseLowestBot: " + str(self.mUseLowestBot) +\
12888 "\n mUseHighestBot: " + str(self.mUseHighestBot) +\
12889 "\n mUseLowestTop: " + str(self.mUseLowestTop) +\
12890 "\n mUseHighestTop: " + str(self.mUseHighestTop) +\
12891 "\n ---in hex--- " +\
12892 "\n mThisCbMin: " + self.mThisCbMin.hex() +\
12893 "\n mThisCbMax: " + self.mThisCbMax.hex() +\
12894 "\n mAllMin: " + self.mAllMin.hex() +\
12895 "\n mAllMax: " + self.mAllMax.hex() +\
12896 "\n mLowestBot: " + self.mLowestBot.hex() +\
12897 "\n mHighestBot: " + self.mHighestBot.hex() +\
12898 "\n mLowestTop: " + self.mLowestTop.hex() +\
12899 "\n mHighestTop: " + self.mHighestTop.hex() +\
12900 "\n"
12901 return retStr
12902
12903 def PlotValMinMaxTrkCParseJson(self, inJson, inKeyPrefix):
12904 if PhactoriDbg(100):
12905 myDebugPrint3("PlotValMinMaxTrkCParseJson entered, key prefix is ->" + inKeyPrefix + "<-\n", 100)
12906 #self.mParseHadKeys = False
12907 keyCurrentDataRange = inKeyPrefix + 'use current data range'
12908 keyCumulativeDataRange = inKeyPrefix + 'use cumulative data range'
12909 keyRange = inKeyPrefix + 'range'
12910 keyMinimumRange = inKeyPrefix + 'minimum range'
12911 keyMaximumRange = inKeyPrefix + 'maximum range'
12912
12913 if keyCurrentDataRange in inJson:
12914 self.mUseCumulativeRange = False
12915 elif keyCumulativeDataRange in inJson:
12916 self.mUseCumulativeRange = True
12917
12918 if keyRange in inJson:
12919 range = inJson[keyRange]
12920 ff0 = float(range[0])
12921 ff1 = float(range[1])
12922 range = [ff0, ff1]
12923 if PhactoriDbg():
12924 myDebugPrint3("PlotValMinMaxTrkCParseJson got range " + str(range) + "\n")
12925 self.mLowestBot = range[0]
12926 self.mUseLowestBot = True
12927 self.mHighestBot = range[0]
12928 self.mUseHighestBot = True
12929 self.mLowestTop = range[1]
12930 self.mUseLowestTop = True
12931 self.mHighestTop = range[1]
12932 self.mUseHighestTop = True
12933 else:
12934 if keyMinimumRange in inJson:
12935 range = inJson[keyMinimumRange]
12936 ff0 = float(range[0])
12937 ff1 = float(range[1])
12938 range = [ff0, ff1]
12939 if PhactoriDbg():
12940 myDebugPrint3("PlotValMinMaxTrkCParseJson got minimum range " + str(range) + "\n")
12941 self.mHighestBot = range[0]
12942 self.mUseHighestBot = True
12943 self.mLowestTop = range[1]
12944 self.mUseLowestTop = True
12945 if keyMaximumRange in inJson:
12946 range = inJson[keyMaximumRange]
12947 ff0 = float(range[0])
12948 ff1 = float(range[1])
12949 range = [ff0, ff1]
12950 if PhactoriDbg():
12951 myDebugPrint3("PlotValMinMaxTrkCParseJson got maximum range " + str(range) + "\n")
12952 self.mLowestBot = range[0]
12953 self.mUseLowestBot = True
12954 self.mHighestTop = range[1]
12955 self.mUseHighestTop = True
12956
12957 if PhactoriDbg():
12958 myDebugPrint3(self.SelfToStr())
12959
12960 def GetMinToUse(self):
12961 return self.mMinToUse
12962
12963 def GetMaxToUse(self):
12964 return self.mMaxToUse
12965
12966 def ResetThisCb(self):
12967 """indicate we are starting a new callback search for min and max, so we
12968 can use the first test value as the initial min and max"""
12969 self.mThisCbInitialized = False
12970 self.mThisCbMin = 0.0
12971 self.mThisCbMax = 0.0
12972
12973 def MinMaxTestAndSet(self, inTestXyz):
12974 if self.mAllInitialized:
12975 if inTestXyz < self.mAllMin:
12976 self.mAllMin = inTestXyz
12977 else:
12978 if inTestXyz > self.mAllMax:
12979 self.mAllMax = inTestXyz
12980 else:
12981 self.mAllMin = inTestXyz
12982 self.mAllMax = inTestXyz
12983 self.mAllInitialized = True
12984 if self.mThisCbInitialized:
12985 if inTestXyz < self.mThisCbMin:
12986 self.mThisCbMin = inTestXyz
12987 else:
12988 if inTestXyz > self.mThisCbMax:
12989 self.mThisCbMax = inTestXyz
12990 else:
12991 self.mThisCbMin = inTestXyz
12992 self.mThisCbMax = inTestXyz
12993 self.mThisCbInitialized = True
12994
12995 def UpdateMinMaxToUse(self):
12996 """assumes we have obtained this callback (ThisCb) mins and maxes; uses
12997 Initial settings and locks to determine what mins and maxes are
12998 now in force"""
12999 if self.mUseCumulativeRange:
13000 localMin = self.mAllMin
13001 else:
13002 localMin = self.mThisCbMin
13003 if self.mUseHighestBot:
13004 if localMin > self.mHighestBot:
13005 localMin = self.mHighestBot
13006 if self.mUseLowestBot:
13007 if localMin < self.mLowestBot:
13008 localMin = self.mLowestBot
13009
13010 if self.mUseCumulativeRange:
13011 localMax = self.mAllMax
13012 else:
13013 localMax = self.mThisCbMax
13014 if self.mUseHighestTop:
13015 if localMax > self.mHighestTop:
13016 localMax = self.mHighestTop
13017 if self.mUseLowestTop:
13018 if localMax < self.mLowestTop:
13019 localMax = self.mLowestTop
13020
13021 if localMin > localMax:
13022 if self.mUseLowestBot:
13023 localMax = localMin
13024 if self.mUseHighestTop:
13025 localMin = localMax
13026 if localMin > localMax:
13027 if PhactoriDbg():
13028 myDebugPrint3("UpdateMinMaxToUse: weird case with min/max\n")
13029 localMin = localMax
13030
13031 self.mMinToUse = localMin
13032 self.mMaxToUse = localMax
13033
13034 class PlotXYZMinMaxTrkC:
13035 def __init__(self):
13036 self.mXyzTrk = []
13037 self.mXyzTrk.append(PlotValMinMaxTrkC())
13038 self.mXyzTrk.append(PlotValMinMaxTrkC())
13039 self.mXyzTrk.append(PlotValMinMaxTrkC())
13040
13041 self.currentYScaleFactor = 1.0
13042
13043 #for scaling axes, use either cumulative data range or current
13044
13045 def PlotXYZMinMaxTrkCParseJson(self, inJson, inKeyPrefix):
13046 if PhactoriDbg(100):
13047 myDebugPrint3("PlotXYZMinMaxTrkCParseJson entered, key prefix is ->" + inKeyPrefix + "<-\n", 100)
13048 xPrefix = 'x ' + inKeyPrefix
13049 yPrefix = 'y ' + inKeyPrefix
13050 zPrefix = 'z ' + inKeyPrefix
13051 self.mXyzTrk[0].PlotValMinMaxTrkCParseJson(inJson, xPrefix)
13052 self.mXyzTrk[1].PlotValMinMaxTrkCParseJson(inJson, yPrefix)
13053 self.mXyzTrk[2].PlotValMinMaxTrkCParseJson(inJson, zPrefix)
13054
13055 def GetMinToUse(self):
13056 retVal = [self.mXyzTrk[0].GetMinToUse(), self.mXyzTrk[1].GetMinToUse(), self.mXyzTrk[2].GetMinToUse()]
13057 return retVal
13058
13059 def GetMaxToUse(self):
13060 retVal = [self.mXyzTrk[0].GetMaxToUse(), self.mXyzTrk[1].GetMaxToUse(), self.mXyzTrk[2].GetMaxToUse()]
13061 return retVal
13062
13063 def ResetThisCb(self):
13064 """indicate we are starting a new callback search for min and max, so we
13065 can use the first test value as the initial min and max"""
13066 self.mXyzTrk[0].ResetThisCb()
13067 self.mXyzTrk[1].ResetThisCb()
13068 self.mXyzTrk[2].ResetThisCb()
13069
13070 def MinMaxTestAndSet(self, inTestXyz):
13071 """test a data value and adjust recorded mins and maxes. Adjust overall
13072 min/max if necessary, adjust ThisCb min max if necessary, also see
13073 if this is first call since last ResetThisCb"""
13074 self.mXyzTrk[0].MinMaxTestAndSet(inTestXyz[0])
13075 self.mXyzTrk[1].MinMaxTestAndSet(inTestXyz[1])
13076 self.mXyzTrk[2].MinMaxTestAndSet(inTestXyz[2])
13077
13078 def UpdateMinMaxToUse(self):
13079 """assumes we have obtained this callback (ThisCb) mins and maxes; uses
13080 Initial settings and locks to determine what mins and maxes are
13081 now in force"""
13082 self.mXyzTrk[0].UpdateMinMaxToUse()
13083 self.mXyzTrk[1].UpdateMinMaxToUse()
13084 self.mXyzTrk[2].UpdateMinMaxToUse()
13085
13086 def SetFromRestartInfo(self, inJson):
13087 """given a map (json format), use the info in the map to set the
13088 state--this reads the info created out in GetRestartInfo"""
13089 if len(inJson) != 3:
13090 if PhactoriDbg():
13091 myDebugPrint3("PlotXYZMinMaxTrkC::SetFromRestartInfo bad inJson\n")
13092 return
13093 self.mXyzTrk[0].SetFromRestartInfo(inJson[0])
13094 self.mXyzTrk[1].SetFromRestartInfo(inJson[1])
13095 self.mXyzTrk[2].SetFromRestartInfo(inJson[2])
13096
13097 def GetRestartInfo(self):
13098 """construct, in python map/json info from this PlotXYZMinMaxTrkC instance
13099 which contains the information which would be needed to restore the
13100 instance to the proper state after a simulation restart.
13101 Basically just calls the GetRestartInfo() for each underlying axis
13102 Return the restart info map/json"""
13103 #this is a list of three items, which is an acceptable json type
13104 newJsonInfo = []
13105 newJsonInfo.append(self.mXyzTrk[0].GetRestartInfo())
13106 newJsonInfo.append(self.mXyzTrk[1].GetRestartInfo())
13107 newJsonInfo.append(self.mXyzTrk[2].GetRestartInfo())
13108 return newJsonInfo
13109
13110
13111 #class PlotColorInfo:
13112 # m_BackgroundColor = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052]
13113 # m_EdgeColor = [0.0, 0.0, 0.5000076295109483]
13114 # m_DiffuseColor = [1.0, 1.0, 1.0]
13115 # m_AmbientColor = [1.0, 1.0, 1.0]
13116 # m_SelectionColor = [1.0, 0.0, 1.0]
13117 # m_BackfaceDiffuseColor = [1.0, 1.0, 1.0]
13118 # m_CubeAxesColor = [1.0, 1.0, 1.0]
13119 # def CopyTo(self, outTarget):
13120 # outTarget.m_BackgroundColor = self.m_BackgroundColor
13121 # outTarget.m_EdgeColor = self.m_EdgeColor
13122 # outTarget.m_DiffuseColor = self.m_DiffuseColor
13123 # outTarget.m_AmbientColor = self.m_AmbientColor
13124 # outTarget.m_SelectionColor = self.m_SelectionColor
13125 # outTarget.m_BackfaceDiffuseColor = self.m_BackfaceDiffuseColor
13126 # outTarget.m_CubeAxesColor = self.m_CubeAxesColor
13127 # def SetRepresentationAndViewColors(self, ioRenderViewInfo):
13128 # myDebugPrint3('PlotColorInfo.SetRepresentationColors entered\n', 100)
13129 # rep1 = ioRenderViewInfo.DataRepresentation1
13130 # view1 = ioRenderViewInfo.RenderView1
13131 # view1.Background = self.m_BackgroundColor
13132 # rep1.EdgeColor = self.m_EdgeColor
13133 # rep1.DiffuseColor = self.m_DiffuseColor
13134 # rep1.AmbientColor = self.m_AmbientColor
13135 # rep1.SelectionColor = self.m_SelectionColor
13136 # rep1.BackfaceDiffuseColor = self.m_BackfaceDiffuseColor
13137 # rep1.CubeAxesColor = self.m_CubeAxesColor
13138 # myDebugPrint3('PlotColorInfo.SetRepresentationColors returning\n', 100)
13139
13140 #global gPlotColorInfoPreset
13141 #gPlotColorInfoPreset = PlotColorInfo()
13142
13143 global gPlotOverTimeMap
13144 gPlotOverTimeMap = {}
13145
13146 global gScatterPlotMap
13147 gScatterPlotMap = {}
13148
13149 #def SetPlotView2StartColors(
13150 # inBackgroundColor = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052],
13151 # inEdgeColor = [0.0, 0.0, 0.5000076295109483],
13152 # inDiffuseColor = [1.0, 1.0, 1.0],
13153 # inAmbientColor = [1.0, 1.0, 1.0],
13154 # inSelectionColor = [1.0, 0.0, 1.0,],
13155 # inBackfaceDiffuseColor = [1.0, 1.0, 1.0],
13156 # inCubeAxesColor = [1.0, 1.0, 1.0]):
13157 # global gPlotColorInfoPreset
13158 # gPlotColorInfoPreset.m_BackgroundColor = inBackgroundColor
13159 # gPlotColorInfoPreset.m_EdgeColor = inEdgeColor
13160 # gPlotColorInfoPreset.m_DiffuseColor = inDiffuseColor
13161 # gPlotColorInfoPreset.m_AmbientColor = inAmbientColor
13162 # gPlotColorInfoPreset.m_SelectionColor = inSelectionColor
13163 # gPlotColorInfoPreset.m_BackfaceDiffuseColor = inBackfaceDiffuseColor
13164 # gPlotColorInfoPreset.m_CubeAxesColor = inBackfaceDiffuseColor
13165
13166 def UpdatePlotView2(inPlotInfo):
13167 if PhactoriDbg(100):
13168 myDebugPrint3('UpdatePlotView2 entered (' + inPlotInfo.mName + ')\n', 100)
13169 if PhactoriDbg():
13170 myDebugPrint3(' render info(' + str(inPlotInfo.m_PhactoriRenderViewInfo) + ')\n')
13171 if PhactoriDbg():
13172 myDebugPrint3(' minmax info: ' + str(inPlotInfo.m_PhactoriRenderViewInfo) + '\n')
13173 #DataXYMinMax = [0.0, 0.0, 0.0, 0.0]
13174 UpdatePipelineWithCurrentTimeArgument(
13175 inPlotInfo.mInputOperation.GetPvFilter())
13176 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
13177 SetPlotPointsFromData(inPlotInfo)
13178 UpdatePlotViewLook(inPlotInfo)
13179 if PhactoriDbg(100):
13180 myDebugPrint3('UpdatePlotView2 returning\n', 100)
13181
13182 def UpdateAllScatterPlots():
13183 if PhactoriDbg(100):
13184 myDebugPrint3('UpdateAllScatterPlots entered\n', 100)
13185 global gScatterPlotMap
13186 for ii in list(gScatterPlotMap.values()):
13187 UpdatePlotView2(ii)
13188 if PhactoriDbg(100):
13189 myDebugPrint3('UpdateAllScatterPlots returning\n', 100)
13190
13191 def UpdateOnePlotOverTime(inPlotInfo):
13192 if PhactoriDbg(100):
13193 myDebugPrint3('UpdateOnePlotOverTime entered (' + inPlotInfo.mName + ')\n', 100)
13194 if PhactoriDbg():
13195 myDebugPrint3(' render info(' + str(inPlotInfo.m_PhactoriRenderViewInfo) + ')\n')
13196 if PhactoriDbg():
13197 myDebugPrint3(' minmax info: ' + str(inPlotInfo.m_xyzMinMaxTrkC) + '\n')
13198 #DataXYMinMax = [0.0, 0.0, 0.0, 0.0]
13199 UpdatePipelineWithCurrentTimeArgument(
13200 inPlotInfo.mInputOperation.GetPvFilter())
13201 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
13202 SetPlotOverTimePointsFromData(inPlotInfo)
13203 UpdatePipelineWithCurrentTimeArgument(
13204 inPlotInfo.mInputOperation.GetPvFilter())
13205 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
13206 UpdatePlotViewLook(inPlotInfo)
13207 if PhactoriDbg(100):
13208 myDebugPrint3('UpdateOnePlotOverTime returning\n', 100)
13209
13210 def UpdateAllPlotsOverTime():
13211 if PhactoriDbg(100):
13212 myDebugPrint3('UpdateAllPlotsOverTime entered\n', 100)
13213 global gPlotOverTimeMap
13214 for ii in list(gPlotOverTimeMap.values()):
13215 UpdateOnePlotOverTime(ii)
13216 if PhactoriDbg(100):
13217 myDebugPrint3('UpdateAllPlotsOverTime returning\n', 100)
13218
13219 def PrintAllPointsA(inPlotInfo):
13220 ppdata = inPlotInfo.m_producer.GetClientSideObject().GetOutputDataObject(0)
13221 programmableFilterPoints = ppdata.GetPoints()
13222 if PhactoriDbg():
13223 myDebugPrint3('programmableFilterPoints: ' + str(programmableFilterPoints))
13224 for ii in range(0, programmableFilterPoints.GetNumberOfPoints()):
13225 onePoint = programmableFilterPoints.GetPoint(ii)
13226 if PhactoriDbg():
13227 myDebugPrint3(str(ii) + ': ' + str(onePoint))
13228
13229 #def TryToDetectVariableCellOrElementType(inInputCsData, inVariableName, inInputIsProxy = False, inAllowGlobalVariableDetection = False):
13230 # if PhactoriDbg():
13231 # myDebugPrint3(' trying to detect variable type (node/element)\n')
13232 #
13233 # if inInputIsProxy:
13234 # pointData = inInputCsData.PointData
13235 # else:
13236 # pointData = inInputCsData.GetPointData()
13237 # if pointData != None:
13238 # testPointArray = pointData.GetArray(inVariableName)
13239 # if testPointArray != None:
13240 # if PhactoriDbg():
13241 # myDebugPrint3(' type node detected!\n')
13242 # return [True, 'node']
13243 #
13244 # if inInputIsProxy:
13245 # cellData = inInputCsData.CellData
13246 # else:
13247 # cellData = inInputCsData.GetCellData()
13248 # if cellData != None:
13249 # testCellArray = cellData.GetArray(inVariableName)
13250 # if testCellArray != None:
13251 # if PhactoriDbg():
13252 # myDebugPrint3(' type element detected!\n')
13253 # return [True, 'element']
13254 #
13255 # if inAllowGlobalVariableDetection:
13256 # if inInputIsProxy:
13257 # fieldData = inInputCsData.FieldData
13258 # else:
13259 # fieldData = inInputCsData.GetFieldData()
13260 # if fieldData != None:
13261 # testFieldArray = fieldData.GetArray(inVariableName)
13262 # if testFieldArray != None:
13263 # if PhactoriDbg():
13264 # myDebugPrint3(' type global detected!\n')
13265 # return [True, 'global']
13266 #
13267 # return [False, '']
13268
13269 def FindThisProcessorMinMaxForVarForOneBlock(inInputCsData, inVariableInfo,
13270 ioMinMaxInfo):
13271 if PhactoriDbg(100):
13272 myDebugPrint3('FindThisProcessorMinMaxForVarForOneBlock entered\n', 100)
13273 if PhactoriDbg():
13274 myDebugPrint3(' variable is ' + inVariableInfo.mVariableName + '\n')
13275
13276 #detect variable type (node/element) if necessary, and save info if detected
13277 detectResult = inVariableInfo.DetectVariableType(inInputCsData,
13278 False, False)
13279 if detectResult == False:
13280 if PhactoriDbg(100):
13281 myDebugPrint3('no detection: returning\n', 100)
13282 return
13283
13284 if(inVariableInfo.mVariableType == 'node'):
13285 cellOrPointData = inInputCsData.GetPointData()
13286 if cellOrPointData == None:
13287 if PhactoriDbg(100):
13288 myDebugPrint3('no point data: returning\n', 100)
13289 return
13290 else:
13291 cellOrPointData = inInputCsData.GetCellData()
13292 if cellOrPointData == None:
13293 if PhactoriDbg(100):
13294 myDebugPrint3('no cell data: returning\n', 100)
13295 return
13296
13297 theData = cellOrPointData.GetArray(inVariableInfo.mVariableName)
13298 if theData == None:
13299 if PhactoriDbg(100):
13300 myDebugPrint3('no theData: returning\n', 100)
13301 return
13302 if PhactoriDbg():
13303 myDebugPrint3(' theData: ' + str(theData) + '\n')
13304 if PhactoriDbg():
13305 myDebugPrint3(' theData name: ' + theData.GetName() + '\n')
13306 numTuplesX = theData.GetNumberOfTuples()
13307
13308 if numTuplesX <= 0:
13309 return
13310
13311 if ioMinMaxInfo[2] == False:
13312 if inVariableInfo.mVariableIsVectorComponent:
13313 vecVal = theData.GetTuple3(0)
13314 vv = vecVal[inVariableInfo.mVariableComponent]
13315 elif inVariableInfo.mVariableIsVectorMagnitude:
13316 vecVal = theData.GetTuple3(0)
13317 aa = vecVal[0]
13318 bb = vecVal[1]
13319 cc = vecVal[2]
13320 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13321 else:
13322 vv = theData.GetTuple1(0)
13323
13324 ioMinMaxInfo[0] = vv
13325 ioMinMaxInfo[1] = vv
13326 ioMinMaxInfo[2] = True
13327
13328 for ii in range(0, numTuplesX):
13329 if inVariableInfo.mVariableIsVectorComponent:
13330 vecVal = theData.GetTuple3(ii)
13331 vv = vecVal[inVariableInfo.mVariableComponent]
13332 elif inVariableInfo.mVariableIsVectorMagnitude:
13333 vecVal = theData.GetTuple3(ii)
13334 aa = vecVal[0]
13335 bb = vecVal[1]
13336 cc = vecVal[2]
13337 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13338 else:
13339 vv = theData.GetTuple1(ii)
13340
13341 if(vv < ioMinMaxInfo[0]):
13342 ioMinMaxInfo[0] = vv
13343 if(vv > ioMinMaxInfo[1]):
13344 ioMinMaxInfo[1] = vv
13345
13346 if PhactoriDbg():
13347 myDebugPrint3(' min max after this block: ' + str(ioMinMaxInfo) + '\n')
13348 if PhactoriDbg(100):
13349 myDebugPrint3('FindThisProcessorMinMaxForVarForOneBlock returning\n', 100)
13350
13351 def FindNodeOrElementIdForMinMaxOneBlock(inInputCsData, ioVariableInfo):
13352 if PhactoriDbg(100):
13353 myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock entered\n'
13354 ' variable is ' + ioVariableInfo.mVariableName + '\n'
13355 ' min: ' + str(ioVariableInfo.mStats.mMin) + '\n'
13356 ' max: ' + str(ioVariableInfo.mStats.mMax) + '\n', 100)
13357
13358 #detect variable type (node/element) if necessary, and save info if detected
13359 detectResult = ioVariableInfo.DetectVariableType(inInputCsData,
13360 False, True)
13361 if detectResult == False:
13362 if PhactoriDbg(100):
13363 myDebugPrint3('no detection: returning\n', 100)
13364 return
13365
13366 if(ioVariableInfo.mVariableType == 'node'):
13367 cellOrPointData = inInputCsData.GetPointData()
13368 if cellOrPointData == None:
13369 if PhactoriDbg(100):
13370 myDebugPrint3('no point data: returning\n', 100)
13371 return
13372 elif(ioVariableInfo.mVariableType == 'element'):
13373 cellOrPointData = inInputCsData.GetCellData()
13374 if cellOrPointData == None:
13375 if PhactoriDbg(100):
13376 myDebugPrint3('no cell data: returning\n', 100)
13377 return
13378 elif(ioVariableInfo.mVariableType == 'global'):
13379 cellOrPointData = inInputCsData.GetFieldData()
13380 if cellOrPointData == None:
13381 if PhactoriDbg(100):
13382 myDebugPrint3('no field data: returning\n', 100)
13383 return
13384 else:
13385 if PhactoriDbg(100):
13386 myDebugPrint3('no data type, should not be here,: returning\n', 100)
13387 return
13388
13389 varData = cellOrPointData.GetArray(ioVariableInfo.mVariableName)
13390 if varData == None:
13391 if PhactoriDbg(100):
13392 myDebugPrint3('no varData: returning\n', 100)
13393 return
13394 if PhactoriDbg():
13395 myDebugPrint3(' y data: ' + str(varData) + '\n')
13396 if PhactoriDbg():
13397 myDebugPrint3(' y data name: ' + varData.GetName() + '\n')
13398 numTuplesX = varData.GetNumberOfTuples()
13399
13400 if numTuplesX <= 0:
13401 return
13402
13403 globalIdArray = None
13404 if(ioVariableInfo.mVariableType == 'node'):
13405 globalIdArray = cellOrPointData.GetArray('GlobalNodeId')
13406 if globalIdArray == None:
13407 if PhactoriDbg():
13408 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
13409 else:
13410 globalIdArray = cellOrPointData.GetArray('GlobalElementId')
13411 if globalIdArray == None:
13412 if PhactoriDbg():
13413 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
13414
13415 for ii in range(0, numTuplesX):
13416 #vv = varData.GetTuple1(ii)
13417 if ioVariableInfo.mVariableIsVectorComponent:
13418 vecVal = varData.GetTuple3(ii)
13419 vv = vecVal[ioVariableInfo.mVariableComponent]
13420 elif ioVariableInfo.mVariableIsVectorMagnitude:
13421 vecVal = varData.GetTuple3(ii)
13422 aa = vecVal[0]
13423 bb = vecVal[1]
13424 cc = vecVal[2]
13425 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13426 else:
13427 vv = varData.GetTuple1(ii)
13428
13429 if vv == ioVariableInfo.mStats.mMin:
13430 #if ioVariableInfo.mStats.mLocalFoundMinId == False:
13431 # ioVariableInfo.mStats.mMinId = globalIdArray.GetTuple1(ii)
13432 # ioVariableInfo.mStats.mLocalFoundMinId = True
13433 # if PhactoriDbg(100):
13434 # myDebugPrint3(" found min node/element id: " + \
13435 # str(ioVariableInfo.mStats.mMinId) + "\n", 100)
13436 ioVariableInfo.mStats.mLocalMinIdCount += 1
13437 newGId = globalIdArray.GetTuple1(ii)
13438 if ioVariableInfo.mStats.mLocalMinIdCount <= 5:
13439 if PhactoriDbg(100):
13440 myDebugPrint3(" found min node/element id: " + \
13441 str(newGId) + "\n"
13442 " count: " + str(ioVariableInfo.mStats.mLocalMinIdCount) + "\n",
13443 100)
13444 if ioVariableInfo.mStats.mLocalFoundMinId == False:
13445 ioVariableInfo.mStats.mMinId = newGId
13446 ioVariableInfo.mStats.mLocalFoundMinId = True
13447 else:
13448 if newGId > ioVariableInfo.mStats.mMinId:
13449 ioVariableInfo.mStats.mMinId = newGId
13450
13451 if vv == ioVariableInfo.mStats.mMax:
13452 #if ioVariableInfo.mStats.mLocalFoundMaxId == False:
13453 # ioVariableInfo.mStats.mMaxId = globalIdArray.GetTuple1(ii)
13454 # ioVariableInfo.mStats.mLocalFoundMaxId = True
13455 # if PhactoriDbg(100):
13456 # myDebugPrint3(" found max node/element id: " + \
13457 # str(ioVariableInfo.mStats.mMaxId) + "\n", 100)
13458 ioVariableInfo.mStats.mLocalMaxIdCount += 1
13459 newGId = globalIdArray.GetTuple1(ii)
13460 if ioVariableInfo.mStats.mLocalMaxIdCount <= 5:
13461 if PhactoriDbg(100):
13462 myDebugPrint3(" found max node/element id: " + \
13463 str(newGId) + "\n"
13464 " count: " + str(ioVariableInfo.mStats.mLocalMaxIdCount) + "\n",
13465 100)
13466 if ioVariableInfo.mStats.mLocalFoundMaxId == False:
13467 ioVariableInfo.mStats.mMaxId = newGId
13468 ioVariableInfo.mStats.mLocalFoundMaxId = True
13469 else:
13470 if newGId > ioVariableInfo.mStats.mMaxId:
13471 ioVariableInfo.mStats.mMaxId = newGId
13472
13473 if PhactoriDbg(100):
13474 myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock returning\n', 100)
13475
13476 def FindNodeOrElementIdForMinMaxRecurse1(inInputCsData, ioVariableInfo):
13477 #myDebugPrint3('FindNodeOrElementIdForMinMaxRecurse1 entered\n', 100)
13478
13479 icsdClassname = inInputCsData.GetClassName()
13480 #if PhactoriDbg(100):
13481 # myDebugPrint3("icsdClassname 3: " + str(icsdClassname) + "\n")
13482 if icsdClassname == "vtkMultiBlockDataSet" or \
13483 icsdClassname == "vtkExodusIIMultiBlockDataSet":
13484 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
13485 numBlocks = inInputCsData.GetNumberOfBlocks()
13486 for ii in range(0, numBlocks):
13487 oneBlock = inInputCsData.GetBlock(ii)
13488 if(oneBlock != None):
13489 FindNodeOrElementIdForMinMaxRecurse1(oneBlock, ioVariableInfo)
13490 else:
13491 #myDebugPrint3('finding min/max: ' + icsdClassname + '\n')
13492 FindNodeOrElementIdForMinMaxOneBlock(inInputCsData, ioVariableInfo)
13493
13494 #myDebugPrint3('FindNodeOrElementIdForMinMaxRecurse1 returning\n', 100)
13495
13496 def FindNodeOrElementIdForMinMax(inputcsData, inVariableInfo):
13497 """fairly complex high level mpi-operation routine. Takes a variable,
13498 finds the min/max (global) and finds a node id or element id corresponding
13499 to the node or element for both the min and the max value. Has some
13500 intelligence to avoid recaculating and doing mpi communication if the
13501 information had already been found for this catalyst callback"""
13502
13503 if PhactoriDbg(100):
13504 myDebugPrint3("FindNodeOrElementIdForMinMax entered: " + \
13505 str(inVariableInfo.mVariableName) + "\n", 100)
13506
13507 #if already been done for this catalyst callback, just return
13508 if inVariableInfo.mStats.mIdsTestCounter == \
13509 gPipeAndViewsState.mFrameTagCounter:
13510 if PhactoriDbg(100):
13511 myDebugPrint3("already calculated for this callback, returning\n", 100)
13512 return
13513
13514 #if variable is global, this shouldn't be called
13515 if inVariableInfo.mVariableType == "global":
13516 myDebugPrint3AndException("FindNodeOrElementIdForMinMax:\n"
13517 "this should not be called with global variable " + \
13518 inVariableInfo.mVariableName + "\n")
13519
13520 #first get the min/max for the variable if necessary
13521 if inVariableInfo.mStats.mStatsTestCounter != \
13522 gPipeAndViewsState.mFrameTagCounter:
13523 if PhactoriDbg(100):
13524 myDebugPrint3("min/max not available, calculating\n", 100)
13525 DataMinMax = [0.0, 0.0, False]
13526 DataSumCnt = [0.0, 0]
13527 FindMinMaxSumCntFromData(inputcsData, inVariableInfo,
13528 None, DataMinMax, DataSumCnt,
13529 None, None)
13530 else:
13531 if PhactoriDbg(100):
13532 myDebugPrint3("min/max previously calculated\n", 100)
13533
13534 #next, get the local node/element id, if any, which contain min and max
13535 #values
13536 inVariableInfo.mStats.mLocalFoundMinId = False
13537 inVariableInfo.mStats.mLocalMinIdCount = 0
13538 inVariableInfo.mStats.mMinId = -1
13539 inVariableInfo.mStats.mLocalFoundMaxId = False
13540 inVariableInfo.mStats.mLocalMaxIdCount = 0
13541 inVariableInfo.mStats.mMaxId = -1
13542 FindNodeOrElementIdForMinMaxRecurse1(inputcsData, inVariableInfo)
13543
13544 #now get every process to agree on which node or element id contains the
13545 #max and min value; for multiple instances we choose the id with the highest
13546 #integer value
13547 idForMinAndidForMax = [inVariableInfo.mStats.mMinId,
13548 inVariableInfo.mStats.mMaxId]
13549 UseReduceToGetMaximumIntegers(idForMinAndidForMax)
13550 inVariableInfo.mStats.mMinId = idForMinAndidForMax[0]
13551 inVariableInfo.mStats.mMaxId = idForMinAndidForMax[1]
13552
13553 #mark done for this catalyst callback, so we won't do extra mpi
13554 #communication if we call this routine again
13555 inVariableInfo.mStats.mIdsTestCounter = gPipeAndViewsState.mFrameTagCounter
13556
13557 if PhactoriDbg(100):
13558 myDebugPrint3(
13559 "counter: " + str(inVariableInfo.mStats.mIdsTestCounter) + "\n"
13560 "min: " + str(inVariableInfo.mStats.mMin) + "\n"
13561 "at id: " + str(inVariableInfo.mStats.mMinId) + "\n"
13562 "max: " + str(inVariableInfo.mStats.mMax) + "\n"
13563 "at id: " + str(inVariableInfo.mStats.mMaxId) + "\n"
13564 "FindNodeOrElementIdForMinMax returning\n")
13565
13566 def FindMinMaxSumCntFromDataOneBlock(inInputCsData, ioVariableInfo,
13567 ioSecondaryVariableInfo, ioDataMinMax, ioDataSumCnt,
13568 ioDataForIds, inPlotLineList):
13569 if PhactoriDbg(100):
13570 myDebugPrint3('FindMinMaxSumCntFromDataOneBlock entered\n', 100)
13571
13572 if PhactoriDbg():
13573 myDebugPrint3(' y axis variable is ' + ioVariableInfo.mVariableName + '\n')
13574
13575 #detect variable type (node/element) if necessary, and save info if detected
13576 detectResult = ioVariableInfo.DetectVariableType(inInputCsData,
13577 False, True)
13578 if detectResult == False:
13579 if PhactoriDbg(100):
13580 myDebugPrint3('no detection: returning\n', 100)
13581 return
13582
13583 if ioSecondaryVariableInfo != None:
13584 ioSecondaryVariableInfo.CopyVariableTypeFrom(ioVariableInfo)
13585
13586 if(ioVariableInfo.mVariableType == 'node'):
13587 cellOrPointData = inInputCsData.GetPointData()
13588 if cellOrPointData == None:
13589 if PhactoriDbg(100):
13590 myDebugPrint3('no point data: returning\n', 100)
13591 return
13592 elif(ioVariableInfo.mVariableType == 'element'):
13593 cellOrPointData = inInputCsData.GetCellData()
13594 if cellOrPointData == None:
13595 if PhactoriDbg(100):
13596 myDebugPrint3('no cell data: returning\n', 100)
13597 return
13598 elif(ioVariableInfo.mVariableType == 'global'):
13599 cellOrPointData = inInputCsData.GetFieldData()
13600 if cellOrPointData == None:
13601 if PhactoriDbg(100):
13602 myDebugPrint3('no field data: returning\n', 100)
13603 return
13604 else:
13605 if PhactoriDbg(100):
13606 myDebugPrint3('no data type, should not be here,: returning\n', 100)
13607 return
13608
13609 #print all element names
13610 #myDebugPrint3('printing array names:\n')
13611 #numCellArrays = cellOrPointData.GetNumberOfArrays()
13612 #for ii in range(0, numCellArrays):
13613 # myDebugPrint3(str(ii) + ": " + cellOrPointData.GetArray(ii).GetName() + "\n")
13614
13615 yData = cellOrPointData.GetArray(ioVariableInfo.mVariableName)
13616 if yData == None:
13617 if PhactoriDbg(100):
13618 myDebugPrint3('no yData: returning\n', 100)
13619 return
13620 if PhactoriDbg():
13621 myDebugPrint3(' y data: ' + str(yData) + '\n')
13622 if PhactoriDbg():
13623 myDebugPrint3(' y data name: ' + yData.GetName() + '\n')
13624 numTuplesX = yData.GetNumberOfTuples()
13625
13626 if numTuplesX <= 0:
13627 return
13628
13629 if ioDataMinMax[2] == False:
13630 #vv = yData.GetTuple1(0)
13631 if ioVariableInfo.mVariableIsVectorComponent:
13632 vecVal = yData.GetTuple3(0)
13633 vv = vecVal[ioVariableInfo.mVariableComponent]
13634 elif ioVariableInfo.mVariableIsVectorMagnitude:
13635 vecVal = yData.GetTuple3(0)
13636 aa = vecVal[0]
13637 bb = vecVal[1]
13638 cc = vecVal[2]
13639 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13640 else:
13641 vv = yData.GetTuple1(0)
13642
13643 ioDataMinMax[0] = vv
13644 ioDataMinMax[1] = vv
13645 ioDataMinMax[2] = True
13646
13647 for ii in range(0, numTuplesX):
13648 #vv = yData.GetTuple1(ii)
13649 if ioVariableInfo.mVariableIsVectorComponent:
13650 vecVal = yData.GetTuple3(ii)
13651 vv = vecVal[ioVariableInfo.mVariableComponent]
13652 elif ioVariableInfo.mVariableIsVectorMagnitude:
13653 vecVal = yData.GetTuple3(ii)
13654 aa = vecVal[0]
13655 bb = vecVal[1]
13656 cc = vecVal[2]
13657 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13658 else:
13659 vv = yData.GetTuple1(ii)
13660
13661 if(vv < ioDataMinMax[0]):
13662 ioDataMinMax[0] = vv
13663 if(vv > ioDataMinMax[1]):
13664 ioDataMinMax[1] = vv
13665 ioDataSumCnt[0] += vv
13666 ioDataSumCnt[1] += 1
13667
13668 if ioDataForIds != None:
13669 numIds = len(inPlotLineList)
13670 globalIdArray = None
13671 if(ioVariableInfo.mVariableType == 'node'):
13672 globalIdArray = cellOrPointData.GetArray('GlobalNodeId')
13673 if globalIdArray == None:
13674 if PhactoriDbg():
13675 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
13676 else:
13677 globalIdArray = cellOrPointData.GetArray('GlobalElementId')
13678 if globalIdArray == None:
13679 if PhactoriDbg():
13680 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
13681 if globalIdArray != None:
13682 for ii in range(0, numIds):
13683 thisIdPlotLine = inPlotLineList[ii]
13684 idToFind = thisIdPlotLine.m_Id
13685 if PhactoriDbg():
13686 myDebugPrint3(' trying to find id: ' + str(idToFind) + '\n')
13687 if thisIdPlotLine.m_FoundOnThisProcessorLastTime == True:
13688 if inInputCsData == thisIdPlotLine.m_FoundBlockRef:
13689 idFromMesh = globalIdArray.GetTuple1(thisIdPlotLine.m_FoundIndex)
13690 if idFromMesh == idToFind:
13691 if PhactoriDbg():
13692 myDebugPrint3(' found id ' + str(idToFind) + ' on this processor again no search\n')
13693 #vv = yData.GetTuple1(thisIdPlotLine.m_FoundIndex)
13694 if ioVariableInfo.mVariableIsVectorComponent:
13695 vecVal = yData.GetTuple3(thisIdPlotLine.m_FoundIndex)
13696 vv = vecVal[ioVariableInfo.mVariableComponent]
13697 elif ioVariableInfo.mVariableIsVectorMagnitude:
13698 vecVal = yData.GetTuple3(thisIdPlotLine.m_FoundIndex)
13699 aa = vecVal[0]
13700 bb = vecVal[1]
13701 cc = vecVal[2]
13702 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13703 else:
13704 vv = yData.GetTuple1(thisIdPlotLine.m_FoundIndex)
13705 ioDataForIds[ii] = vv
13706 #go on to next id
13707 continue
13708 else:
13709 thisIdPlotLine.m_FoundOnThisProcessorLastTime = False
13710 for jj in range(0, numTuplesX):
13711 idFromMesh = globalIdArray.GetTuple1(jj)
13712 if idFromMesh == idToFind:
13713 if PhactoriDbg():
13714 myDebugPrint3(' found id ' + str(idToFind) + ' on this processor\n')
13715 #vv = yData.GetTuple1(jj)
13716 if ioVariableInfo.mVariableIsVectorComponent:
13717 vecVal = yData.GetTuple3(jj)
13718 vv = vecVal[ioVariableInfo.mVariableComponent]
13719 elif ioVariableInfo.mVariableIsVectorMagnitude:
13720 vecVal = yData.GetTuple3(jj)
13721 aa = vecVal[0]
13722 bb = vecVal[1]
13723 cc = vecVal[2]
13724 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
13725 else:
13726 vv = yData.GetTuple1(jj)
13727 ioDataForIds[ii] = vv
13728 thisIdPlotLine.m_FoundOnThisProcessorLastTime = True
13729 thisIdPlotLine.m_FoundBlockRef = inInputCsData
13730 thisIdPlotLine.m_FoundIndex = jj
13731
13732 if PhactoriDbg():
13733 myDebugPrint3(' min max after this block: ' + str(ioDataMinMax) + '\n')
13734
13735 if PhactoriDbg(100):
13736 myDebugPrint3('FindMinMaxSumCntFromDataOneBlock returning\n', 100)
13737
13738
13739 def SetPlotPointsFromOneBlock(inInputCsData, ioPlotInfo, ioIndex):
13740 if PhactoriDbg(100):
13741 myDebugPrint3('SetPlotPointsFromOneBlock entered\n', 100)
13742 if PhactoriDbg():
13743 myDebugPrint3(' x axis variable: ' + ioPlotInfo.m_XAxisVariableInfo.mVariableName + \
13744 '\n y axis varaible: ' + ioPlotInfo.m_YAxisVariableInfo.mVariableName + '\n')
13745
13746 #detect variable type (node/element) if necessary, and save info if detected
13747 detectResult = ioPlotInfo.m_YAxisVariableInfo.DetectVariableType(
13748 inInputCsData, False, False)
13749 if detectResult == False:
13750 if PhactoriDbg(100):
13751 myDebugPrint3('no detection: returning\n', 100)
13752 return
13753
13754 ioPlotInfo.m_XAxisVariableInfo.CopyVariableTypeFrom(
13755 ioPlotInfo.m_YAxisVariableInfo)
13756
13757 if(ioPlotInfo.m_YAxisVariableInfo.mVariableType == 'node'):
13758 cellOrPointData = inInputCsData.GetPointData()
13759 if cellOrPointData == None:
13760 if PhactoriDbg(100):
13761 myDebugPrint3('no point data: returning\n', 100)
13762 return
13763 else:
13764 cellOrPointData = inInputCsData.GetCellData()
13765 if cellOrPointData == None:
13766 if PhactoriDbg(100):
13767 myDebugPrint3('no cell data: returning\n', 100)
13768 return
13769 #nodeData = inClientSideData.GetNodeData()
13770
13771
13772 #print all element names
13773 #myDebugPrint3('printing array names:\n')
13774 #numCellArrays = cellOrPointData.GetNumberOfArrays()
13775 #for ii in range(0, numCellArrays):
13776 # myDebugPrint3(str(ii) + ": " + cellOrPointData.GetArray(ii).GetName() + "\n")
13777
13778
13779 xData = cellOrPointData.GetArray(ioPlotInfo.m_XAxisVariableInfo.mVariableName)
13780 yData = cellOrPointData.GetArray(ioPlotInfo.m_YAxisVariableInfo.mVariableName)
13781 if xData == None:
13782 if PhactoriDbg(100):
13783 myDebugPrint3('no xData: returning\n', 100)
13784 return
13785 if yData == None:
13786 if PhactoriDbg(100):
13787 myDebugPrint3('no yData: returning\n', 100)
13788 return
13789 if PhactoriDbg():
13790 myDebugPrint3(' x data: ' + str(xData) + ' y data: ' + str(yData) + '\n')
13791 if PhactoriDbg():
13792 myDebugPrint3(' x data name: ' + xData.GetName() + ' y data name : ' + yData.GetName() + '\n')
13793 numTuplesX = xData.GetNumberOfTuples()
13794 numTuplesY = yData.GetNumberOfTuples()
13795
13796 if numTuplesX != numTuplesY:
13797 if PhactoriDbg():
13798 myDebugPrint3('number of tuples do not match in SetPlotPointsFromOneBlock')
13799 return
13800
13801 if 1:
13802 ptListCount = numTuplesX
13803 if ptListCount > 100:
13804 ptListCount = 100
13805 for jj in range(0, ptListCount):
13806 if PhactoriDbg():
13807 myDebugPrint3(' cell ' + str(jj) + ': ' + str(xData.GetTuple1(jj)) + ' data: ' + str(yData.GetTuple1(jj)) + '\n')
13808
13809 outOutputPoints = ioPlotInfo.m_Points
13810
13811 #myDebugPrint3('ioIndex is ' + str(ioIndex))
13812 #myDebugPrint3('outOutputPoints is ' + str(outOutputPoints))
13813 #myDebugPrint3('outOutputPoints number of points is ' + str(outOutputPoints.GetNumberOfPoints()))
13814
13815 localIndex = ioIndex[0]
13816 for ii in range(0, numTuplesX):
13817
13818 if ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorComponent:
13819 vecVal = xData.GetTuple3(ii)
13820 xx = vecVal[ioPlotInfo.m_XAxisVariableInfo.mVariableComponent]
13821 elif ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorMagnitude:
13822 vecVal = xData.GetTuple3(ii)
13823 aa = vecVal[0]
13824 bb = vecVal[1]
13825 cc = vecVal[2]
13826 xx = math.sqrt(aa*aa + bb*bb + cc*cc)
13827 else:
13828 xx = xData.GetTuple1(ii)
13829
13830 if ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorComponent:
13831 vecVal = yData.GetTuple3(ii)
13832 yy = vecVal[ioPlotInfo.m_YAxisVariableInfo.mVariableComponent]
13833 elif ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorMagnitude:
13834 vecVal = yData.GetTuple3(ii)
13835 aa = vecVal[0]
13836 bb = vecVal[1]
13837 cc = vecVal[2]
13838 yy = math.sqrt(aa*aa + bb*bb + cc*cc)
13839 else:
13840 yy = yData.GetTuple1(ii)
13841
13842 zz = 0.0
13843 if localIndex < outOutputPoints.GetNumberOfPoints():
13844 if PhactoriDbg():
13845 myDebugPrint3(' sppfob changing existing point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\n')
13846 outOutputPoints.SetPoint(localIndex, xx, yy, zz)
13847 else:
13848 if PhactoriDbg():
13849 myDebugPrint3(' sppfob inserting new point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\n')
13850 outOutputPoints.InsertPoint(localIndex, xx, yy, zz)
13851 localIndex += 1
13852 ioIndex[0] = localIndex
13853 #PrintAllPointsA()
13854 if PhactoriDbg(100):
13855 myDebugPrint3('SetPlotPointsFromOneBlock returning\n', 100)
13856
13857 def FindMinMaxSumCntFromDataRecurse1(inInputCsData, ioVariableInfo,
13858 ioSecondaryVariableInfo, ioDataMinMax, ioDataSumCnt,
13859 ioDataForIds, inPlotIdLineList):
13860 #myDebugPrint3('FindMinMaxSumCntFromDataRecurse1 entered\n', 100)
13861
13862 icsdClassname = inInputCsData.GetClassName()
13863 #if PhactoriDbg(100):
13864 # myDebugPrint3("icsdClassname 4: " + str(icsdClassname) + "\n")
13865 if icsdClassname == "vtkMultiBlockDataSet" or \
13866 icsdClassname == "vtkExodusIIMultiBlockDataSet":
13867 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
13868 numBlocks = inInputCsData.GetNumberOfBlocks()
13869 for ii in range(0, numBlocks):
13870 oneBlock = inInputCsData.GetBlock(ii)
13871 if(oneBlock != None):
13872 FindMinMaxSumCntFromDataRecurse1(oneBlock,
13873 ioVariableInfo, ioSecondaryVariableInfo,
13874 ioDataMinMax, ioDataSumCnt, ioDataForIds, inPlotIdLineList)
13875 else:
13876 #myDebugPrint3('finding min/max: ' + icsdClassname + '\n')
13877 FindMinMaxSumCntFromDataOneBlock(inInputCsData,
13878 ioVariableInfo, ioSecondaryVariableInfo,
13879 ioDataMinMax, ioDataSumCnt, ioDataForIds, inPlotIdLineList)
13880
13881 #myDebugPrint3(' min max after this recursion: ' + str(ioDataMinMax) + '\n')
13882
13883 #myDebugPrint3('FindMinMaxFromDataSumCntRecurse1 returning\n', 100)
13884
13885
13886 def FindThisProcessorMinMaxForVarRecurse1(inInputCsData, inVariableInfo, ioMinMaxInfo):
13887 #myDebugPrint3('FindThisProcessorMinMaxForVarRecurse1 entered\n', 100)
13888
13889 icsdClassname = inInputCsData.GetClassName()
13890 #if PhactoriDbg(100):
13891 # myDebugPrint3("icsdClassname 5: " + str(icsdClassname) + "\n")
13892 if icsdClassname == "vtkMultiBlockDataSet" or \
13893 icsdClassname == "vtkExodusIIMultiBlockDataSet":
13894 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
13895 numBlocks = inInputCsData.GetNumberOfBlocks()
13896 for ii in range(0, numBlocks):
13897 oneBlock = inInputCsData.GetBlock(ii)
13898 if(oneBlock != None):
13899 FindThisProcessorMinMaxForVarRecurse1(oneBlock, inVariableInfo, ioMinMaxInfo)
13900 elif icsdClassname == "vtkPartitionedDataSet":
13901 numPartitions = inInputCsData.GetNumberOfPartitions()
13902 for ii in range(0, numPartitions):
13903 onePartition = inInputCsData.GetPartition(ii)
13904 if(onePartition != None):
13905 FindThisProcessorMinMaxForVarRecurse1(onePartition, inVariableInfo, ioMinMaxInfo)
13906 elif icsdClassname == "vtkMultiPieceDataSet":
13907 numPieces = inInputCsData.GetNumberOfPieces()
13908 for ii in range(0, numPieces):
13909 onePiece = inInputCsData.GetPiece(ii)
13910 if(onePiece != None):
13911 FindThisProcessorMinMaxForVarRecurse1(onePiece, inVariableInfo, ioMinMaxInfo)
13912 else:
13913 FindThisProcessorMinMaxForVarForOneBlock(inInputCsData, inVariableInfo, ioMinMaxInfo)
13914 #myDebugPrint3('FindThisProcessorMinMaxForVarRecurse1 returning\n', 100)
13915
13916 def SetPlotPointsFromDataRecurse1(inInputCsData, ioPlotInfo, ioIndex):
13917 #myDebugPrint3('SetPlotPointsFromDataRecurse1 entered\n', 100)
13918
13919 icsdClassname = inInputCsData.GetClassName()
13920 #if PhactoriDbg(100):
13921 # myDebugPrint3("icsdClassname 6: " + str(icsdClassname) + "\n")
13922 if icsdClassname == "vtkMultiBlockDataSet" or \
13923 icsdClassname == "vtkExodusIIMultiBlockDataSet":
13924 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
13925 numBlocks = inInputCsData.GetNumberOfBlocks()
13926 for ii in range(0, numBlocks):
13927 oneBlock = inInputCsData.GetBlock(ii)
13928 if(oneBlock != None):
13929 SetPlotPointsFromDataRecurse1(oneBlock, ioPlotInfo, ioIndex)
13930 else:
13931 #myDebugPrint3('making points: ' + icsdClassname + '\n')
13932 SetPlotPointsFromOneBlock(inInputCsData, ioPlotInfo, ioIndex)
13933 #myDebugPrint3('SetPlotPointsFromDataRecurse1 returning\n', 100)
13934
13935 def FindPlotXyzMinMaxPtLst(inPlotPointsList, ioPlotXYZMinMaxTrkC):
13936 if len(inPlotPointsList) < 1:
13937 errStr = 'FindPlotXyzMinMaxPtLst needs to have at least one item in list'
13938 if PhactoriDbg():
13939 myDebugPrint3(errStr)
13940 raise Exception(errStr)
13941
13942 #if ioPlotXYZMinMaxTrkC.mThisDbInitized == False)
13943 # myDebugPrint3('no points, returning\n', 100)
13944 # return
13945
13946 firstPointForInitialization = None
13947 for onePointGroup in inPlotPointsList:
13948 if onePointGroup.GetNumberOfPoints() > 0:
13949 firstPointForInitialization = onePointGroup.GetPoint(0)
13950 break
13951
13952 if firstPointForInitialization == None:
13953 if PhactoriDbg(100):
13954 myDebugPrint3('no points, returning\n', 100)
13955 return
13956
13957 ioPlotXYZMinMaxTrkC.ResetThisCb()
13958
13959 if PhactoriDbg():
13960 myDebugPrint3(' xyzminmax C incoming: \n' \
13961 ' x: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax) + '\n' \
13962 ' y: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax) + '\n' \
13963 ' z: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax) + '\n' \
13964 ' xot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMax) + '\n' \
13965 ' yot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMax) + '\n' \
13966 ' zot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMax) + '\n' \
13967 )
13968 if PhactoriDbg():
13969 myDebugPrint3(str(ioPlotXYZMinMaxTrkC))
13970
13971 for onePointGroup in inPlotPointsList:
13972 numPoints = onePointGroup.GetNumberOfPoints()
13973 for ii in range(0, numPoints):
13974 onePoint = onePointGroup.GetPoint(ii)
13975 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet(onePoint)
13976
13977 xmin = ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin
13978 ymin = ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin
13979 zmin = ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin
13980 xmax = ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax
13981 ymax = ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax
13982 zmax = ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax
13983 minmaxlist = [xmin, xmax, ymin, ymax, zmin, zmax]
13984 UseReduceToGetMinMaxPairs(minmaxlist)
13985 xmin = minmaxlist[0]
13986 xmax = minmaxlist[1]
13987 ymin = minmaxlist[2]
13988 ymax = minmaxlist[3]
13989 zmin = minmaxlist[4]
13990 zmax = minmaxlist[5]
13991
13992 UseReduceToGetMinMaxPairs(minmaxlist)
13993 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet([xmin, ymin, zmin])
13994 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet([xmax, ymax, zmax])
13995
13996 ioPlotXYZMinMaxTrkC.UpdateMinMaxToUse()
13997
13998 if PhactoriDbg():
13999 myDebugPrint3(' xyzminmax C outgoing: \n' \
14000 ' x: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax) + '\n' \
14001 ' y: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax) + '\n' \
14002 ' z: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax) + '\n' \
14003 ' xot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMax) + '\n' \
14004 ' yot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMax) + '\n' \
14005 ' zot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMax) + '\n' \
14006 )
14007 if PhactoriDbg():
14008 myDebugPrint3(str(ioPlotXYZMinMaxTrkC))
14009
14010
14011 def FindPlotXYZMinMax(inPlotPoints, ioPlotXYZMinMaxTrkC):
14012 FindPlotXyzMinMaxPtLst([inPlotPoints], ioPlotXYZMinMaxTrkC)
14013
14014 def ScalePlotYForFit(ioPlotPts, ioPlotXYZMinMaxTrkC, inAspectRatio):
14015
14016 xyzmin = ioPlotXYZMinMaxTrkC.GetMinToUse()
14017 xmin = xyzmin[0]
14018 ymin = xyzmin[1]
14019 zmin = xyzmin[2]
14020 xyzmax = ioPlotXYZMinMaxTrkC.GetMaxToUse()
14021 xmax = xyzmax[0]
14022 ymax = xyzmax[1]
14023 zmax = xyzmax[2]
14024
14025 xSpan = xmax - xmin
14026 ySpan = ymax - ymin
14027 if PhactoriDbg():
14028 myDebugPrint3('xSpan: ' + str(xSpan) + ' ySpan: ' + str(ySpan))
14029 yScaleFactor = 1.0
14030 if PhactoriDbg():
14031 myDebugPrint3('inAspectRatio: ' + str(inAspectRatio) + '\n')
14032
14033 if xSpan > 0.0:
14034 if ySpan > 0.0:
14035 yScaleFactor = xSpan / ySpan
14036 yScaleFactor /= inAspectRatio
14037
14038 ioPlotXYZMinMaxTrkC.currentYScaleFactor = yScaleFactor
14039 if PhactoriDbg():
14040 myDebugPrint3('yScaleFactor: ' + str(yScaleFactor))
14041
14042 numPoints = ioPlotPts.GetNumberOfPoints()
14043 for ii in range(0, numPoints):
14044 onePoint = ioPlotPts.GetPoint(ii)
14045 xx = onePoint[0]
14046 yy = onePoint[1]
14047 zz = onePoint[2]
14048 ioPlotPts.SetPoint(ii, xx, yy*yScaleFactor, zz)
14049
14050 def FindThisProcessorMinMaxForVar(inOperation, inVariableInfo):
14051
14052 myDataMinMax = [0.0, 0.0, False]
14053 pvClientSideData = inOperation.GetPvFilter().GetClientSideObject().GetOutputDataObject(0)
14054 if pvClientSideData == None:
14055 if PhactoriDbg(100):
14056 myDebugPrint3('pvClientSideData is None, returning', 100)
14057 return myDataMinMax
14058
14059 FindThisProcessorMinMaxForVarRecurse1(pvClientSideData, inVariableInfo, myDataMinMax)
14060
14061 return myDataMinMax
14062
14063
14064 def FindMinMaxSumCntFromData(inputcsData, inVariableInfo,
14065 inSecondaryVariableInfo, DataMinMax, DataSumCnt,
14066 DataForIds, inPlotIdLineList):
14067 """fairly complex high level mpi-operation routine. This takes a paraview
14068 filter client side object, gets the client side data
14069 (which is presumably a multiblock
14070 dataset) and finds the min, max, sum, and count of items for a variable.
14071 It uses MPI (if the item is not global) to share values and get them
14072 across all processors. Used for plotting min/max/mean and for evaluating
14073 boolean criteria (such as whether or not to produce images) for min/max
14074 /mean/count. Data return is a bit messy and should be updated--it fills
14075 in DataMinMax, DataSumCnt, and DataForIds if it is not None"""
14076
14077 if PhactoriDbg():
14078 myDebugPrint3("FindMinMaxSumCntFromData entered\n")
14079
14080 FindMinMaxSumCntFromDataRecurse1(inputcsData, inVariableInfo,
14081 inSecondaryVariableInfo, DataMinMax, DataSumCnt,
14082 DataForIds, inPlotIdLineList)
14083
14084 #if variable is global, it is same on all processors so we don't need to do
14085 #any mpi communication
14086 if inVariableInfo.mVariableType != 'global':
14087 #do mpi to share values around
14088 UseReduceToSumDoubleAndIntPair(DataSumCnt)
14089 if DataSumCnt[1] == 0:
14090 #no data; we shouldn't add anything to plot lines
14091 if PhactoriDbg(100):
14092 myDebugPrint3('no data for variable; returning\n', 100)
14093 return
14094
14095 #bad situation; if we have no data on this processor we don't want
14096 #it to mess up other processors min/max
14097 if DataMinMax[2] == False:
14098 DataMinMax[0] = sys.float_info.max
14099 DataMinMax[1] = -sys.float_info.max
14100
14101 UseReduceToGetMinMaxPairs(DataMinMax)
14102 if DataForIds != None:
14103 UseReduceToSpreadValues(DataForIds)
14104
14105 if PhactoriDbg():
14106 myDebugPrint3('min/max result: ' + str(DataMinMax) + '\n')
14107 if PhactoriDbg():
14108 myDebugPrint3(' sum result: ' + str(DataSumCnt[0]) + ' count result: ' + str(DataSumCnt[1]) + '\n')
14109 #myDebugPrint3(' average result: ' + str(DataSumCnt[0]/DataSumCnt[1]) + '\n')
14110 if PhactoriDbg():
14111 myDebugPrint3(' average result: ' + \
14112 str(DataSumCnt[0]/float(DataSumCnt[1])) + '\n')
14113 if PhactoriDbg():
14114 myDebugPrint3('DataForIds result: ' + str(DataForIds) + '\n')
14115
14116 inVariableInfo.mStats.mMin = DataMinMax[0]
14117 inVariableInfo.mStats.mMax = DataMinMax[1]
14118 inVariableInfo.mStats.mSum = DataSumCnt[0]
14119 inVariableInfo.mStats.mCount = DataSumCnt[1]
14120 inVariableInfo.mStats.mStatsTestCounter = \
14121 gPipeAndViewsState.mFrameTagCounter
14122
14123 if PhactoriDbg():
14124 myDebugPrint3("FindMinMaxSumCntFromData returning\n")
14125
14126
14127 def SetPlotOverTimePointsFromData(ioPlotInfo):
14128 if PhactoriDbg(100):
14129 myDebugPrint3("SetPlotOverTimePointsFromData entered\n", 100)
14130 if PhactoriDbg(100):
14131 myDebugPrint3("variable is: " + str(ioPlotInfo.m_YAxisVariableInfo.mVariableName) + "\n", 100)
14132
14133 inputcsData = ioPlotInfo.mInputOperation.GetPvFilter().GetClientSideObject().GetOutputDataObject(0)
14134 if inputcsData == None:
14135 if PhactoriDbg(100):
14136 myDebugPrint3('inputcsData is None, returning', 100)
14137 return
14138
14139 if PhactoriDbg():
14140 myDebugPrint3('finding min/max for data for this processor at this timestep\n')
14141 DataMinMax = [0.0, 0.0, False]
14142 DataSumCnt = [0.0, 0]
14143
14144 numIds = len(ioPlotInfo.m_IdPlotLineList)
14145 if numIds > 0:
14146 DataForIds = []
14147 for ii in range(0, numIds):
14148 DataForIds.append(0.0)
14149 else:
14150 DataForIds = None
14151
14152 FindMinMaxSumCntFromData(inputcsData,
14153 ioPlotInfo.m_YAxisVariableInfo, ioPlotInfo.m_XAxisVariableInfo,
14154 DataMinMax, DataSumCnt, DataForIds, ioPlotInfo.m_IdPlotLineList)
14155
14156 if DataSumCnt[1] == 0:
14157 if PhactoriDbg(100):
14158 myDebugPrint3('num elements in data is 0, returning', 100)
14159 return
14160
14161 global gPipeAndViewsState
14162 plotPointTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
14163
14164 #append time to time column
14165 ioPlotInfo.m_TimeColumn.AppendPlotValue(plotPointTime)
14166
14167 #append max value to plot
14168 plotDataVal = DataMinMax[1]
14169 ioPlotInfo.m_MaxPlotLine.AppendPlotValue(plotDataVal)
14170
14171 #append min value to plot
14172 #plotDataVal = -0.1*(DataMinMax[0] + DataMinMax[1])
14173 plotDataVal = DataMinMax[0]
14174 ioPlotInfo.m_MinPlotLine.AppendPlotValue(plotDataVal)
14175
14176 #append mean value to plot
14177 #ioPlotInfo.m_MeanPlotLine.AppendPlotValue(plotPointTime,
14178 # DataSumCnt[0]/DataSumCnt[1])
14179 plotDataVal = DataSumCnt[0]/float(DataSumCnt[1])
14180 ioPlotInfo.m_MeanPlotLine.AppendPlotValue(DataSumCnt[0]/float(DataSumCnt[1]))
14181
14182 if PhactoriDbg():
14183 myDebugPrint3("ioPlotInfo.m_vtkTable numcols B:" + str(ioPlotInfo.m_vtkTable.GetNumberOfColumns()) + "\n")
14184 myDebugPrint3("ioPlotInfo.m_vtkTable numrows B:" + str(ioPlotInfo.m_vtkTable.GetNumberOfRows()) + "\n")
14185
14186 #append node or element values (by id) to plot lines for each id
14187 numIdValues = len(ioPlotInfo.m_IdPlotLineList)
14188 for ii in range(0,numIdValues):
14189 ioPlotInfo.m_IdPlotLineList[ii].m_PlotColumn.AppendPlotValue(DataForIds[ii])
14190
14191 if PhactoriDbg():
14192 myDebugPrint3(' done updating ids\n')
14193
14194
14195 def SetPlotPointsFromData(ioPlotInfo):
14196 if PhactoriDbg(100):
14197 myDebugPrint3("SetPlotPointsFromData entered\n", 100)
14198
14199 inputcsData = ioPlotInfo.mInputOperation.GetPvFilter().\
14200 GetClientSideObject().GetOutputDataObject(0)
14201 if inputcsData == None:
14202 if PhactoriDbg(100):
14203 myDebugPrint3('inputcsData is None, returning', 100)
14204 return
14205
14206 plotPointIndex = [0]
14207 #myDebugPrint3(' inputcsData: ' + str(inputcsData) + '\n')
14208 #if ioPlotInfo.mVariableType == 'element':
14209 # cellOrPointFlag = 0
14210 #elif ioPlotInfo.mVariableType == 'node':
14211 # cellOrPointFlag = 1
14212 #else:
14213 # errStr = 'SetPlotPointsFromData error! can only handle element or node variable types for now'
14214 # myDebugPrint3(errStr)
14215 # raise Exception(errStr)
14216 #SetPlotPointsFromDataRecurse1(inputcsData, ioPlotInfo,
14217 # cellOrPointFlag, plotPointIndex)
14218 SetPlotPointsFromDataRecurse1(inputcsData, ioPlotInfo, plotPointIndex)
14219
14220 plotPts = ioPlotInfo.m_Points
14221 numPts = plotPts.GetNumberOfPoints()
14222 #myDebugPrint3(' need to update ids, get number of points: ' + str(numPts) + '\n')
14223
14224 ioPlotInfo.m_Vertex.GetPointIds().SetNumberOfIds(numPts)
14225
14226 for i in range(0,numPts):
14227 #Add the points to the line. The first value indicates
14228 #the order of the point on the line. The second value
14229 #is a reference to a point in a vtkPoints object. Depends
14230 #on the order that Points were added to vtkPoints object.
14231 #Note that this will not be associated with actual points
14232 #until it is added to a vtkPolyData object which holds a
14233 #vtkPoints object.
14234 #print str(i)
14235 ioPlotInfo.m_Vertex.GetPointIds().SetId(i, i)
14236
14237 ioPlotInfo.m_PolyData.Reset()
14238 ioPlotInfo.m_PolyData.SetPoints(plotPts)
14239 ioPlotInfo.m_PolyData.InsertNextCell(ioPlotInfo.m_Vertex.GetCellType(), ioPlotInfo.m_Vertex.GetPointIds())
14240
14241 #ioPlotInfo.m_PolyData.Modified()
14242
14243 #using ScatterPlot() now
14244 #ioPlotInfo.m_producer.GetClientSideObject().SetOutput(None)
14245 #ioPlotInfo.m_producer.GetClientSideObject().SetOutput(ioPlotInfo.m_PolyData)
14246
14247 #myDebugPrint3(' done updating ids\n')
14248
14249
14250
14251 FindPlotXYZMinMax(plotPts, ioPlotInfo.m_xyzMinMaxTrkC)
14252 ScalePlotYForFit(plotPts, ioPlotInfo.m_xyzMinMaxTrkC,
14253 ioPlotInfo.mImageSettings.GetAspectRatioInsidePixelBorder())
14254
14255 #find x and y min and max for data (current and over time)
14256
14257 #myDebugPrint3('before--->')
14258 #PrintAllPointsA()
14259
14260 #for ii in range(0,130):
14261 # onePoint = plotPts.GetPoint(ii)
14262 # xx = onePoint[0]
14263 # yy = onePoint[1]
14264 # #yy -= 10.0
14265 # yy = 50.0
14266 # zz = onePoint[2]
14267 # plotPts.SetPoint(ii, xx, yy, zz)
14268 #myDebugPrint3('after--->')
14269 if PhactoriDbg():
14270 myDebugPrint3("points in plot after updating\n")
14271 #PrintAllPointsA(ioPlotInfo)
14272 if PhactoriDbg(100):
14273 myDebugPrint3("SetPlotPointsFromData returning\n", 100)
14274
14275 def CreateOnePlotOverTimeProducerC(ioPlotOverTime):
14276 if PhactoriDbg(100):
14277 myDebugPrint3('CreateOnePlotOverTimeProducerC entered (' + ioPlotOverTime.mName + ')\n', 100)
14278
14279 global gPlotOverTimeMap
14280
14281 #ioPlotOverTime.m_YAxisVariableName = ioinYAxisVariableName
14282 #ioPlotOverTime.m_CellOrPointOrGlobalFlag = inCellOrPointOrGlobalFlag
14283
14284 UpdatePipelineWithCurrentTimeArgument(
14285 ioPlotOverTime.mInputOperation.GetPvFilter())
14286
14287 savedActiveSource = GetActiveSource()
14288
14289 if PhactoriDbg():
14290 myDebugPrint3('before active source: ' + str(savedActiveSource) + "\n")
14291
14292 SetActiveSource(ioPlotOverTime.mInputOperation.GetPvFilter())
14293
14294 ioPlotOverTime.m_vtkTable = vtk.vtkTable()
14295
14296 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_TimeColumn.m_TableColumn)
14297
14298 if ioPlotOverTime.mPlotMaximumFlag:
14299 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MaxPlotLine.m_TableColumn)
14300 if ioPlotOverTime.mPlotMinimumFlag:
14301 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MinPlotLine.m_TableColumn)
14302 if ioPlotOverTime.mPlotMeanFlag:
14303 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MeanPlotLine.m_TableColumn)
14304
14305 if PhactoriDbg():
14306 myDebugPrint3("ioPlotOverTime.m_vtkTable numcols A:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfColumns()) + "\n")
14307 myDebugPrint3("ioPlotOverTime.m_vtkTable numrows A:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfRows()) + "\n")
14308
14309 if PhactoriDbg():
14310 myDebugPrint3("initializing id plot lines (" + str(len(ioPlotOverTime.m_IdPlotLineList)) + ")\n")
14311 for oneIdPlotLine in ioPlotOverTime.m_IdPlotLineList:
14312 if PhactoriDbg():
14313 myDebugPrint3(" doing line for id " + str(oneIdPlotLine.m_Id) + "\n")
14314 ioPlotOverTime.m_vtkTable.AddColumn(oneIdPlotLine.m_PlotColumn.m_TableColumn)
14315
14316 producer = PVTrivialProducer()
14317 #producer.GetClientSideObject().SetOutput(ioPlotOverTime.m_PolyData)
14318
14319 myDebugPrint3("ioPlotOverTime.m_vtkTable numcols C:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfColumns()) + "\n")
14320 myDebugPrint3("ioPlotOverTime.m_vtkTable numrows C:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfRows()) + "\n")
14321 producer.GetClientSideObject().SetOutput(ioPlotOverTime.m_vtkTable)
14322
14323 ioPlotOverTime.m_producer = producer
14324
14325 UpdatePipelineWithCurrentTimeArgument(
14326 ioPlotOverTime.mInputOperation.GetPvFilter())
14327 UpdatePipelineWithCurrentTimeArgument(ioPlotOverTime.m_producer)
14328 SetPlotOverTimePointsFromData(ioPlotOverTime)
14329 UpdatePipelineWithCurrentTimeArgument(ioPlotOverTime.m_producer)
14330 if PhactoriDbg():
14331 myDebugPrint3('done filter output 2nd time:')
14332 if PhactoriDbg():
14333 myDebugPrint3('After 2nd update pipeline in CreatePlotOverTimeProducer:')
14334 #PrintAllPointsA(ioPlotOverTime)
14335
14336 #print ' active source after filter before reset: ' + str(GetActiveSource())
14337 SetActiveSource(savedActiveSource)
14338 if PhactoriDbg():
14339 myDebugPrint3('ioPlotOverTime.m_producer.GetDataInformation().GetBounds():\n' + str(ioPlotOverTime.m_producer.GetDataInformation().GetBounds()) + '\n')
14340
14341 gPlotOverTimeMap[ioPlotOverTime.mName] = ioPlotOverTime
14342 if PhactoriDbg():
14343 myDebugPrint3('gPlotOverTimeMap has ' + str(len(gPlotOverTimeMap)) + ' items\n')
14344 count = 0
14345 for ii in list(gPlotOverTimeMap.values()):
14346 if PhactoriDbg():
14347 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
14348 if PhactoriDbg():
14349 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
14350 count += 1
14351
14352 AddFilterToFilterMap(ioPlotOverTime.mName, ioPlotOverTime.m_producer)
14353
14354 if PhactoriDbg(100):
14355 myDebugPrint3('CreateOnePlotOverTimeProducerC returning\n', 100)
14356
14357
14358 def CreateOneScatterPlotProducerC(ioScatterPlot):
14359 if PhactoriDbg(100):
14360 myDebugPrint3('CreateOneScatterPlotProducerC entered (' + ioScatterPlot.mName + ')\n', 100)
14361
14362 global gScatterPlotMap
14363
14364 #needs to change to source specified
14365
14366 UpdatePipelineWithCurrentTimeArgument(
14367 ioScatterPlot.mInputOperation.GetPvFilter())
14368
14369 savedActiveSource = GetActiveSource()
14370 if PhactoriDbg():
14371 myDebugPrint3('before active source: ' + str(savedActiveSource) + "\n")
14372
14373 SetActiveSource(ioScatterPlot.mInputOperation.GetPvFilter())
14374
14375 #create poly data to use
14376 ioScatterPlot.m_PolyData = vtk.vtkPolyData()
14377 #ioScatterPlot.m_PolyLine = vtk.vtkPolyLine()
14378 ioScatterPlot.m_Points = vtk.vtkPoints()
14379 ioScatterPlot.m_Vertex = vtk.vtkVertex()
14380
14381 #numPts = 100
14382 #numPts = 1
14383 numPts = 0
14384 if PhactoriDbg():
14385 myDebugPrint3('numPts: ' + str(numPts) + "\n")
14386
14387 for ii in range(0, numPts):
14388 xx = float(ii) / float(numPts)
14389 yy = (float(ii) * float(ii)) / (float(numPts) * float(numPts))
14390 zz = 0.0
14391 ioScatterPlot.m_Points.InsertPoint(ii, xx,yy,zz)
14392 ioScatterPlot.m_PolyData.SetPoints(ioScatterPlot.m_Points)
14393
14394 #ioScatterPlot.m_PolyLine.GetPointIds().SetNumberOfIds(numPts)
14395 ioScatterPlot.m_Vertex.GetPointIds().SetNumberOfIds(numPts)
14396
14397 for i in range(0,numPts):
14398 #Add the points to the line. The first value indicates
14399 #the order of the point on the line. The second value
14400 #is a reference to a point in a vtkPoints object. Depends
14401 #on the order that Points were added to vtkPoints object.
14402 #Note that this will not be associated with actual points
14403 #until it is added to a vtkPolyData object which holds a
14404 #vtkPoints object.
14405 #print str(i)
14406 #ioScatterPlot.m_PolyLine.GetPointIds().SetId(i, i)
14407 ioScatterPlot.m_Vertex.GetPointIds().SetId(i, i)
14408
14409 ioScatterPlot.m_PolyData.Allocate(1, 1)
14410 ioScatterPlot.m_PolyData.InsertNextCell(ioScatterPlot.m_Vertex.GetCellType(),
14411 ioScatterPlot.m_Vertex.GetPointIds())
14412
14413 #producer = PVTrivialProducer()
14414 #producer.GetClientSideObject().SetOutput(ioScatterPlot.m_PolyData)
14415 ioScatterPlot.m_MergeBlocks = MergeBlocks(Input=ioScatterPlot.mInputOperation.GetPvFilter())
14416 producer = ScatterPlot(Input=ioScatterPlot.m_MergeBlocks)
14417
14418 if PhactoriDbg():
14419 csdoobj = producer.GetClientSideObject().GetOutputDataObject(0)
14420 myDebugPrint3("csdoobj: " + str(csdoobj) + "\n")
14421 myDebugPrint3("csdoobj.GetNumberOfPoints(): " + str(csdoobj.GetNumberOfPoints()) + "\n")
14422 myDebugPrint3("csdoobj.GetNumberOfCells(): " + str(csdoobj.GetNumberOfCells()) + "\n")
14423
14424 ioScatterPlot.m_producer = producer
14425
14426 UpdatePipelineWithCurrentTimeArgument(
14427 ioScatterPlot.mInputOperation.GetPvFilter())
14428 ioScatterPlot.ChooseDefaultVariableIfNecessary()
14429 UpdatePipelineWithCurrentTimeArgument(ioScatterPlot.m_producer)
14430 SetPlotPointsFromData(ioScatterPlot)
14431 UpdatePipelineWithCurrentTimeArgument(ioScatterPlot.m_producer)
14432 if PhactoriDbg():
14433 myDebugPrint3('done filter output 2nd time:')
14434 if PhactoriDbg():
14435 myDebugPrint3('After 2nd update pipeline in CreateScatterPlotProducer:')
14436 #PrintAllPointsA(ioScatterPlot)
14437
14438 #print ' active source after filter before reset: ' + str(GetActiveSource())
14439 SetActiveSource(savedActiveSource)
14440 if PhactoriDbg():
14441 myDebugPrint3('ioScatterPlot.m_producer.GetDataInformation().GetBounds():\n' + str(ioScatterPlot.m_producer.GetDataInformation().GetBounds()) + '\n')
14442
14443 gScatterPlotMap[ioScatterPlot.mName] = ioScatterPlot
14444 if PhactoriDbg():
14445 myDebugPrint3('gScatterPlotMap has ' + str(len(gScatterPlotMap)) + ' items\n')
14446 count = 0
14447 for ii in list(gScatterPlotMap.values()):
14448 if PhactoriDbg():
14449 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
14450 if PhactoriDbg():
14451 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
14452 count += 1
14453
14454 AddFilterToFilterMap(ioScatterPlot.mName, ioScatterPlot.m_producer)
14455
14456 if PhactoriDbg(100):
14457 myDebugPrint3('CreateOneScatterPlotProducerC returning\n', 100)
14458
14459
14460 def CreateOneScatterPlotViewC(ioScatterPlot):
14461 if PhactoriDbg(100):
14462 myDebugPrint3('CreateOneScatterPlotViewC entered (' + ioScatterPlot.mName + ')\n', 100)
14463 saveActiveSource = GetActiveSource()
14464 saveActiveView = GetActiveView()
14465 global currentPhactoriRenderViewInfo
14466 saveCurrentInfo = currentPhactoriRenderViewInfo
14467
14468 SetActiveSource(ioScatterPlot.m_producer)
14469
14470 #global gDefaultImageSizeX
14471 #global gDefaultImageSizeY
14472 #plot_view_setup_1 = { \
14473 # 'camera_setup': {'look_direction': [0.0, 0.0, -1.0] }, \
14474 # 'show_color_legend': False, \
14475 # 'show_data_cube_axes': True, \
14476 # 'show_orientation_axes': True, \
14477 # 'image_settings' : { \
14478 # 'basename': ioScatterPlot.mName, \
14479 # 'size': [gDefaultImageSizeX, gDefaultImageSizeY] \
14480 # }, \
14481 # }
14482 #
14483 #CreateViewSetFromPhactoriViewMapB(plot_view_setup_1)
14484
14485 ioScatterPlot.mCamera.mName = 'dummyscatterplotcamera'
14486 ioScatterPlot.mCamera.mType = 'camera'
14487 ioScatterPlot.mCamera.mLookAtDistanceType = 'datasize relative'
14488 ioScatterPlot.mCamera.mLookDirection = [0.0, 0.0, -1.0]
14489 ioScatterPlot.mCamera.mLookAtDistance = 1.0
14490
14491 if ioScatterPlot.mImageSettings.mUsingDefaultGeneratedImageBasename:
14492 imageBasename = ioScatterPlot.mName
14493 extraImagenameItem = "sctr."
14494 else:
14495 imageBasename = ioScatterPlot.mImageSettings.mImageBasename
14496 extraImagenameItem = ""
14497
14498 SetUpOneParaViewRepresentationAndViewC(ioScatterPlot.mCamera,
14499 [0.0, 0.0, -1.0],
14500 inImagesetInfo = ioScatterPlot,
14501 inColorSettingsX = ioScatterPlot.mColorSettings,
14502 inMeshRenderControl = 'Surface With Edges',
14503 inShowDataCubeAxes = True,
14504 inShowDataCubeAxesInfo = ioScatterPlot.m_DataCubeAxesInfo,
14505 inShowOrientationAxes = False,
14506 inFixedColorRange = None,
14507 inIsPlotFlag = True,
14508 inRepresentationFilenameAddon = "",
14509 inLookDirectionFilenameAddon = extraImagenameItem,
14510 inPhactoriRepresentation = None)
14511
14512 global gScatterPlotMap
14513 #myDebugPrint3('qqxxqq gScatterPlotMap has ' + str(len(gScatterPlotMap)) + ' items\n')
14514 count = 0
14515 for ii in list(gScatterPlotMap.values()):
14516 if PhactoriDbg():
14517 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
14518 if PhactoriDbg():
14519 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
14520 count += 1
14521
14522 if ioScatterPlot.mName in gScatterPlotMap:
14523 thePlot = gScatterPlotMap[ioScatterPlot.mName]
14524 thePlot.m_PhactoriRenderViewInfo = currentPhactoriRenderViewInfo
14525
14526 #set up colors based .on preset and then set DataRepresentation colors
14527 #global gPlotColorInfoPreset
14528 #gPlotColorInfoPreset.CopyTo(thePlot.m_plotColorInfo)
14529 #thePlot.m_plotColorInfo.SetRepresentationAndViewColors(
14530 # thePlot.m_PhactoriRenderViewInfo)
14531 #thePlot.mColorSettings.SetParaviewRvRepColors(
14532 # thePlot.m_PhactoriRenderViewInfo.RenderView1,
14533 # thePlot.m_PhactoriRenderViewInfo.DataRepresentation1)
14534
14535 UpdatePlotViewLook(thePlot)
14536 else:
14537 if PhactoriDbg():
14538 myDebugPrint3('error 3 making scatter plot')
14539
14540 SetActiveSource(saveActiveSource)
14541 SetActiveView(saveActiveView)
14542 currentPhactoriRenderViewInfo = saveCurrentInfo
14543 if PhactoriDbg(100):
14544 myDebugPrint3('CreateOneScatterPlotViewC returning\n', 100)
14545
14546 #phactori_combine_to_single_python_file_parent_1
14547 from Operation.PhactoriMpiUtilities import *
14548
14549 def UseReduceToSumDoubleAndIntPair(ioDoubleAndIntPair):
14550 if PhactoriDbg(100):
14551 myDebugPrint3("UseReduceToSumDoubleAndIntPair entered\n", 100)
14552 if PhactoriDbg():
14553 myDebugPrint3(" local double: " + str(ioDoubleAndIntPair[0]) + " local int: " + str(ioDoubleAndIntPair[1]) + "\n")
14554 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
14555 globalController = pm.GetGlobalController()
14556
14557 localarray = vtk.vtkDoubleArray()
14558 localarray.SetNumberOfTuples(1)
14559 globalarray = vtk.vtkDoubleArray()
14560 globalarray.SetNumberOfTuples(1)
14561 localarray.SetValue(0, ioDoubleAndIntPair[0])
14562
14563 #fixed bug here; 0 argument is mpi find max, while 2 argument is mpi sum
14564 #which is what we want here
14565 #globalController.AllReduce(localarray, globalarray, 0)
14566 globalController.AllReduce(localarray, globalarray, 2)
14567 ioDoubleAndIntPair[0] = globalarray.GetTuple1(0)
14568
14569 localarray = vtk.vtkIntArray()
14570 localarray.SetNumberOfTuples(1)
14571 globalarray = vtk.vtkIntArray()
14572 globalarray.SetNumberOfTuples(1)
14573 localarray.SetValue(0, ioDoubleAndIntPair[1])
14574 globalController.AllReduce(localarray, globalarray, 2)
14575 ioDoubleAndIntPair[1] = globalarray.GetTuple1(0)
14576
14577 if PhactoriDbg():
14578 myDebugPrint3(" reduced double: " + str(ioDoubleAndIntPair[0]) + " reduced int: " + str(ioDoubleAndIntPair[1]) + "\n")
14579
14580 def UseReduceToGetMaximumIntegers(ioListOfMaximumIntegers):
14581 if PhactoriDbg(100):
14582 myDebugPrint3("UseReduceToGetMaximums entered\n", 100)
14583 myDebugPrint3(" local ioListOfMaximumIntegers: " +
14584 str(ioListOfMaximumIntegers) + "\n")
14585 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
14586 globalController = pm.GetGlobalController()
14587 numMaxes = len(ioListOfMaximumIntegers)
14588 localarray = vtk.vtkIntArray()
14589 localarray.SetNumberOfTuples(numMaxes)
14590 for ii in range(0, numMaxes):
14591 localarray.SetValue(ii, int(ioListOfMaximumIntegers[ii]))
14592 globalarray = vtk.vtkIntArray()
14593 globalarray.SetNumberOfTuples(numMaxes)
14594 globalController.AllReduce(localarray, globalarray, 0)
14595 for ii in range(0, numMaxes):
14596 ioListOfMaximumIntegers[ii] = globalarray.GetTuple1(ii)
14597
14598 if PhactoriDbg():
14599 myDebugPrint3(" global ioListOfMaximumIntegers: " +
14600 str(ioListOfMaximumIntegers) + "\n")
14601
14602 def UseReduceToGetMinMaxPairs(ioListOfMinMaxPairs):
14603 if PhactoriDbg(100):
14604 myDebugPrint3("UseReduceToGetMinMaxPairs entered\n", 100)
14605 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
14606 globalController = pm.GetGlobalController()
14607 numPairs = len(ioListOfMinMaxPairs) // 2
14608 localarray = vtk.vtkDoubleArray()
14609 localarray.SetNumberOfTuples(numPairs*2)
14610 # we negate mins so we can do a single MPI_MAX reduce
14611 for ii in range(0, numPairs):
14612 ndx1 = ii*2
14613 localarray.SetValue(ndx1, -ioListOfMinMaxPairs[ndx1])
14614 ndx1 += 1
14615 localarray.SetValue(ndx1, ioListOfMinMaxPairs[ndx1])
14616 globalarray = vtk.vtkDoubleArray()
14617 globalarray.SetNumberOfTuples(numPairs*2)
14618 globalController.AllReduce(localarray, globalarray, 0)
14619 if PhactoriDbg():
14620 myDebugPrint3(" local minmax pairs: " + str(ioListOfMinMaxPairs) + "\n")
14621 for ii in range(0, numPairs):
14622 ndx1 = ii*2
14623 ioListOfMinMaxPairs[ndx1] = -globalarray.GetTuple1(ndx1)
14624 ndx1 += 1
14625 ioListOfMinMaxPairs[ndx1] = globalarray.GetTuple1(ndx1)
14626 if PhactoriDbg():
14627 myDebugPrint3(" global minmax pairs: " + str(ioListOfMinMaxPairs) + "\n")
14628 if PhactoriDbg(100):
14629 myDebugPrint3("UseReduceToGetMinMaxPairs returning\n", 100)
14630
14631 #set the 3d viewpoint to look at the xy scatter plot
14632 def UpdatePlotViewLook(inPlotInfo):
14633 return
14634
14635 def CreateOnePlotOverTimeViewC(ioPlotOverTime):
14636 if PhactoriDbg(100):
14637 myDebugPrint3('CreateOnePlotOverTimeViewC entered (' + ioPlotOverTime.mName + ')\n', 100)
14638 saveActiveSource = GetActiveSource()
14639 saveActiveView = GetActiveView()
14640 global currentPhactoriRenderViewInfo
14641 saveCurrentInfo = currentPhactoriRenderViewInfo
14642
14643 SetActiveSource(ioPlotOverTime.m_producer)
14644
14645 #global gDefaultImageSizeX
14646 #global gDefaultImageSizeY
14647 #plot_view_setup_1 = { \
14648 # 'camera_setup': {'look_direction': [0.0, 0.0, -1.0] }, \
14649 # 'show_color_legend': False, \
14650 # 'show_data_cube_axes': True, \
14651 # 'show_orientation_axes': True, \
14652 # 'image_settings' : { \
14653 # 'basename': ioPlotOverTime.mName, \
14654 # 'size': [gDefaultImageSizeX, gDefaultImageSizeY], \
14655 # }, \
14656 # }
14657
14658 #CreateViewSetFromPhactoriViewMapB(plot_view_setup_1)
14659
14660 ioPlotOverTime.mCamera.mName = 'dummyscatterplotcamera'
14661 ioPlotOverTime.mCamera.mType = 'camera'
14662 ioPlotOverTime.mCamera.mLookAtDistanceType = 'datasize relative'
14663 ioPlotOverTime.mCamera.mLookDirection = [0.0, 0.0, -1.0]
14664 ioPlotOverTime.mCamera.mLookAtDistance = 1.0
14665
14666 if ioPlotOverTime.mImageSettings.mUsingDefaultGeneratedImageBasename:
14667 imageBasename = ioPlotOverTime.mName
14668 extraImagenameItem = "plot."
14669 else:
14670 imageBasename = ioPlotOverTime.mImageSettings.mImageBasename
14671 extraImagenameItem = ""
14672
14673 if PhactoriDbg():
14674 myDebugPrint3(" use specific y axis label: " + str(ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mUseLabelFlag) + "\n")
14675 if ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mUseLabelFlag:
14676 if PhactoriDbg():
14677 myDebugPrint3(" specific y axis label: " + str(ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mAxisLabel) + "\n")
14678
14679 SetUpOneParaViewRepresentationAndViewC(ioPlotOverTime.mCamera,
14680 [0.0, 0.0, -1.0],
14681 inImagesetInfo = ioPlotOverTime,
14682 inColorSettingsX = ioPlotOverTime.mColorSettings,
14683 inMeshRenderControl = 'Surface With Edges',
14684 inShowDataCubeAxes = True,
14685 inShowDataCubeAxesInfo = ioPlotOverTime.m_DataCubeAxesInfo,
14686 inShowOrientationAxes = False,
14687 inFixedColorRange = None,
14688 inIsPlotFlag = True,
14689 inRepresentationFilenameAddon = "",
14690 inLookDirectionFilenameAddon = extraImagenameItem,
14691 inPhactoriRepresentation = None)
14692
14693
14694 global gPlotOverTimeMap
14695 if PhactoriDbg():
14696 myDebugPrint3('qqxxqq gPlotOverTimeMap has ' + str(len(gPlotOverTimeMap)) + ' items\n')
14697 count = 0
14698 for ii in list(gPlotOverTimeMap.values()):
14699 if PhactoriDbg():
14700 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
14701 if PhactoriDbg():
14702 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
14703 count += 1
14704
14705 if ioPlotOverTime.mName in gPlotOverTimeMap:
14706 thePlot = gPlotOverTimeMap[ioPlotOverTime.mName]
14707
14708 UpdatePlotViewLook(thePlot)
14709 else:
14710 if PhactoriDbg():
14711 myDebugPrint3('error 3 making plot over time')
14712
14713 SetActiveSource(saveActiveSource)
14714 SetActiveView(saveActiveView)
14715 currentPhactoriRenderViewInfo = saveCurrentInfo
14716 if PhactoriDbg(100):
14717 myDebugPrint3('CreateOnePlotOverTimeViewC returning\n', 100)
14718
14719 global gPhactoriPipeRootMap
14720 gPhactoriPipeRootMap = {}
14721
14722 def convertJsonUnicodeToStrings(inJson):
14723 """go through a dict/list/item which was loaded via json.load, and convert
14724 unicode strings to python strings"""
14725 #for python 2.6 or earlier, replace
14726 # return {convertJsonUnicodeToStrings(key): convertJsonUnicodeToStrings(value) for key, value in inJson.iteritems()}
14727 #with
14728 # return dict([(convert(key), convert(value)) for key, value in input.iteritems()])
14729 #(not tested, this routine was copied from web answer to question)
14730 if isinstance(inJson, dict):
14731 return {convertJsonUnicodeToStrings(key): convertJsonUnicodeToStrings(value) for key, value in inJson.items()}
14732 elif isinstance(inJson, list):
14733 return [convertJsonUnicodeToStrings(element) for element in inJson]
14734 elif isinstance(inJson, str):
14735 #return inJson.encode('utf-8')
14736 return str(inJson)
14737 else:
14738 return inJson
14739
14740
14741 def IssueErrorOrWarningThroughSierraIO(datadescription, outString, isErrorFlag):
14742 if PhactoriDbg():
14743 myDebugPrint3("IssueErrorOrWarningThroughSierraIO entered")
14744
14745 if datadescription == None:
14746 errStr = "IssueErrorOrWarningThroughSierraIO no datadescription\n" + \
14747 outString
14748 raise Exception(errStr)
14749 return
14750
14751 fd = datadescription.GetUserData()
14752
14753 if fd == None:
14754 errStr = "IssueErrorOrWarningThroughSierraIO, no user data\n" + \
14755 outString
14756 if PhactoriDbg():
14757 myDebugPrint3(errStr)
14758 raise Exception(errStr)
14759 return
14760
14761 #numArrays = fd.GetNumberOfArrays()
14762 #myDebugPrint3("abstract arrays: number of arrays: " + str(numArrays) + "\n")
14763 #for ii in range(numArrays):
14764 # myDebugPrint3("array " + str(ii) + ":\n")
14765 # oneArray = fd.GetAbstractArray(ii)
14766 # myDebugPrint3("name: " + oneArray.GetName() + "\n")
14767
14768 errorCodeArray = fd.GetAbstractArray("catalyst_sierra_error_codes")
14769 errorMessageArray = fd.GetAbstractArray("catalyst_sierra_error_messages")
14770
14771 if errorCodeArray == None or errorMessageArray == None:
14772 if PhactoriDbg(999):
14773 myDebugPrint3("IssueErrorOrWarningThroughSierraIO::\n"
14774 "catalyst_sierra_error_codes and/or catalyst_sierra_error_messages\n"
14775 "were missing from UserData. Item follows:\n" + outString, 999)
14776 else:
14777 if isErrorFlag:
14778 errorCode = 0
14779 else:
14780 errorCode = 1
14781 errorCodeArray.InsertNextValue(errorCode)
14782 errorMessageArray.InsertNextValue(outString)
14783
14784 if PhactoriDbg():
14785 myDebugPrint3("IssueErrorOrWarningThroughSierraIO reached end")
14786
14787 def GetUserDataStringArrayAccountingForBypass(datadescription):
14788 if datadescription == None:
14789 if gBypassUserData:
14790 if PhactoriDbg():
14791 myDebugPrint3(
14792 "GetUserDataStringArrayAccountingForBypass returning " \
14793 "bypass strings 1\n")
14794 return gUserDataBypassStrings
14795 else:
14796 if PhactoriDbg():
14797 myDebugPrint3(
14798 "GetUserDataStringArrayAccountingForBypass returning None 1\n")
14799 return None
14800
14801 fd = datadescription.GetUserData()
14802 if fd == None:
14803 if gBypassUserData:
14804 if PhactoriDbg():
14805 myDebugPrint3(
14806 "GetUserDataStringArrayAccountingForBypass returning " \
14807 "bypass strings 2\n")
14808 return gUserDataBypassStrings
14809 else:
14810 if PhactoriDbg():
14811 myDebugPrint3(
14812 "GetUserDataStringArrayAccountingForBypass returning None 2\n")
14813 return None
14814
14815 sa = fd.GetAbstractArray(0)
14816 if sa == None or sa.GetNumberOfValues() < 1:
14817 if gBypassUserData:
14818 if PhactoriDbg():
14819 myDebugPrint3(
14820 "GetUserDataStringArrayAccountingForBypass returning " \
14821 "bypass strings 3\n")
14822 return gUserDataBypassStrings
14823 else:
14824 if PhactoriDbg():
14825 myDebugPrint3(
14826 "GetUserDataStringArrayAccountingForBypass returning None 3\n")
14827 return None
14828
14829 returnStringArray = ["","","","","","","","",""]
14830
14831 for ii in range(0, sa.GetNumberOfValues()):
14832 returnStringArray[ii] = sa.GetValue(ii)
14833
14834 if gBypassUserData:
14835 #sub in json string
14836 if PhactoriDbg():
14837 myDebugPrint3("gBypassUserData is true, user data is valid, subbing\n")
14838 returnStringArray[0] = gUserDataBypassStrings[0]
14839 #also add in missing user values if sa was short
14840 for jj in range(sa.GetNumberOfValues(), len(gUserDataBypassStrings)):
14841 returnStringArray[jj] = gUserDataBypassStrings[0]
14842
14843 return returnStringArray
14844
14845
14846 def GetViewMapCFromUserData(datadescription):
14847 """given a datadescription, get the json string view map from the user data
14848 and convert it into a python dict using the json library, and return
14849 that item. Also determine the separator character and input deck
14850 filename"""
14851
14852 #the following code forces a UserData item for internal testing
14853 #myDebugPrint3("GetViewMapCFromUserData entered\n")
14854 #newFd = vtk.vtkFieldData()
14855 #newStringArray = vtk.vtkStringArray()
14856 #xxViewMapCStr = '{ "camera blocks": { }, "representation blocks": { }, \
14857 # "operation blocks": { }, "imageset blocks": {}, \
14858 # "scatter plot blocks": { }, "plot over time blocks": { } }'
14859 #newStringArray.InsertNextValue(xxViewMapCStr)
14860 #x2str = '_'
14861 #x3str = 'cool_input_deck'
14862 #newStringArray.InsertNextValue(x2str)
14863 #newStringArray.InsertNextValue(x3str)
14864 #newFd.AddArray(newStringArray)
14865
14866 #datadescription.SetUserData(newFd)
14867
14868 global gBypassUserData
14869
14870 sa = GetUserDataStringArrayAccountingForBypass(datadescription)
14871
14872 testJsonString = sa[0]
14873 separatorCharacterString = sa[1]
14874 inputDeckFilename = sa[2]
14875
14876 if PhactoriDbg():
14877 myDebugPrint3("gGetJsonViewMapCFromUserData string:\n" + \
14878 str(testJsonString) + "\n")
14879 if PhactoriDbg():
14880 myDebugPrint3("separator string: " + separatorCharacterString + \
14881 "\ninputDeckFilename: " + inputDeckFilename + "\n")
14882 #if PhactoriDbg():
14883 #myDebugPrint3("num strings2: " + str(sa.GetNumberOfValues()))
14884 if PhactoriDbg():
14885 myDebugPrint3("json.loads begin ---------------\n");
14886 myDebugPrint3(testJsonString);
14887 myDebugPrint3("\njson.loads end ---------------\n");
14888
14889 if gBypassUserData == True:
14890 global gBypassUserDataJson
14891 returnViewMapC = gBypassUserDataJson
14892 #returnViewMapC = bccolli_controls.catalystSierraInputInJsonFormat
14893 else:
14894 returnViewMapC = json.loads(testJsonString)
14895 returnViewMapC = convertJsonUnicodeToStrings(returnViewMapC)
14896
14897 SetDefaultImageBasename(inputDeckFilename)
14898
14899 if PhactoriDbg():
14900 myDebugPrint3("GetViewMapCFromUserData returning\n")
14901
14902 return returnViewMapC
14903
14904
14905 def CreatePipelineFromDataDescription(datadescription):
14906 theSource = GetCurrentSource()
14907
14908 theCellArrays = None
14909 theCellArrays = theSource.CellData
14910 thePointArrays = None
14911 thePointArrays = theSource.PointData
14912
14913 theViewMapC = GetViewMapCFromUserData(datadescription)
14914
14915 CreateViewSetFromPhactoriViewMapC(theViewMapC)
14916
14917 #SetPlotView2StartColors(
14918 # inBackgroundColor = [1.0, 1.0, 1.0],
14919 # inEdgeColor = [0.0, 0.0, 0.5],
14920 # inCubeAxesColor = [0.2, 0.2, 0.2],
14921 # inDiffuseColor = [0.2, 0.2, 0.2],
14922 # inAmbientColor = [0.2, 0.2, 0.2],
14923 # inSelectionColor = [0.2, 0.2, 0.2],
14924 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
14925
14926 def parseDbDummyFname(dbDummyFname):
14927 """given user data item which is dummy database name used for remesh and
14928 restart purposes, pull out the base name (minus -s0002, -sXXXX, etc.)
14929 and return the base name and extension (extension in an empty string
14930 if appropriate)"""
14931 remeshRestartTagIndex = dbDummyFname.rfind("-s")
14932 if remeshRestartTagIndex == -1:
14933 baseId = dbDummyFname
14934 remeshRestartTag = ''
14935 else:
14936 baseId = dbDummyFname[0:remeshRestartTagIndex]
14937 remeshRestartTag = dbDummyFname[remeshRestartTagIndex:]
14938 return baseId, remeshRestartTag
14939
14940 def DoUserInteractionWithSimulationPausedIfEnabled():
14941 if PhactoriDbg():
14942 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled entered\n")
14943 global gPipeAndViewsState
14944
14945 if gPipeAndViewsState.mInteractionRepeatPauseSim == False:
14946 if PhactoriDbg():
14947 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled returning 0\n")
14948 return 0
14949
14950 updateWasDone = HandleUserInteractionIfEnabled(gPipeAndViewsState)
14951 if updateWasDone:
14952 returnVal = 2
14953 else:
14954 returnVal = 1
14955 if PhactoriDbg():
14956 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled returning " + \
14957 str(returnVal) + "\n")
14958 return returnVal
14959
14960 def HandleUserInteractionIfEnabled(ioPipeAndViewsState):
14961 """if the pipe (or imageset maybe) is in interactive mode, check for the
14962 trigger which will cause a read-and-update of the state. Provides
14963 control to skip interaction when it is not enabled, the default case.
14964 Allows for a wait for an interaction trigger of N tries at M seconds
14965 per try, mainly to deal with situations where images are being
14966 rendered quickly. Eventually may be altered to help deal with cases
14967 where we want to keep re-rendering with changed pipeline states
14968 until we are happy and then let the simulation return to operation"""
14969 if PhactoriDbg():
14970 myDebugPrint3("HandleUserInteractionIfEnabled entered\n")
14971 if ioPipeAndViewsState.mInteractionEnabled == False:
14972 return False
14973
14974 if SmartGetLocalProcessId() != 0:
14975 return False
14976 #else:
14977 #do parallel stuff to receive info
14978
14979
14980 #check for trigger. Only update if trigger file is incremented
14981 doUpdate = False
14982 triggerTestCount = 0
14983
14984 while doUpdate == False and \
14985 triggerTestCount < ioPipeAndViewsState.mInteractionTriggerTries:
14986 if PhactoriDbg():
14987 myDebugPrint3("testing for trigger: " + str(triggerTestCount) + \
14988 " of " + str(ioPipeAndViewsState.mInteractionTriggerTries) + "\n")
14989 triggerTestCount += 1
14990 try:
14991 inFile = open('PhactoriInteractionTrigger.txt', 'rb')
14992 userTrigger = json.load(inFile)
14993 inFile.close()
14994 userTrigger = convertJsonUnicodeToStrings(userTrigger)
14995 except:
14996 if PhactoriDbg():
14997 myDebugPrint3("error dealing with PhactoriInteractionTrigger.txt\n")
14998 return
14999
15000 if 'InteractionTriggerCounter' not in userTrigger:
15001 if PhactoriDbg():
15002 myDebugPrint3("no InteractionTriggerCounter in \
15003 PhactoriInteractionTrigger.txt\n")
15004 else:
15005 testTriggerCount = userTrigger['InteractionTriggerCounter']
15006 if testTriggerCount != ioPipeAndViewsState.mInteractionTriggerCounter:
15007 ioPipeAndViewsState.mInteractionTriggerCounter = testTriggerCount
15008 doUpdate = True
15009
15010 if doUpdate == False:
15011 import time
15012 time.sleep(ioPipeAndViewsState.mInteractionTriggerSleep)
15013
15014 if doUpdate:
15015 if PhactoriDbg():
15016 myDebugPrint3("update triggered, doing update\n")
15017 UpdatePipeAndViewsStateFromUserA(ioPipeAndViewsState,
15018 "PhactoriJsonSettings.txt")
15019 if 'InteractionState' in userTrigger:
15020 if userTrigger['InteractionState'] == 'RepeatWithPausedSimulation':
15021 ioPipeAndViewsState.mInteractionRepeatPauseSim = True
15022 else:
15023 ioPipeAndViewsState.mInteractionRepeatPauseSim = False
15024 else:
15025 ioPipeAndViewsState.mInteractionRepeatPauseSim = False
15026
15027 if PhactoriDbg():
15028 myDebugPrint3("HandleUserInteractionIfEnabled returning\n")
15029 return doUpdate
15030
15031 #phactori_combine_to_single_python_file_parent_1
15032 from Operation.PhactoriRepresentationBlock import *
15033
15034 class PhactoriCriteriaThreshold:
15035 """
15036 maintains a threshold value TT, and tracks when a min/max/mean/sum/count
15037 of a variable crosses the threshold; also keeps track of how many frames
15038 it has been since the crossing and if this is within a frame count setting
15039 and also tracks how many times it has been triggered and no longer triggers
15040 after a max has been reached
15041 """
15042
15043 def __init__(self, inThresholdValue, inFramesAfterTrigger, inMaxTriggers):
15044 self.mThresholdValue = inThresholdValue
15045 self.mFramesAfterTrigger = inFramesAfterTrigger
15046 self.mMaxTriggers = inMaxTriggers
15047 self.mCrossingsSoFar = 0
15048 self.mLastTestValue = 0.0
15049 self.mObserveCallCount = 0
15050 self.mCountAtLastCrossing = 0
15051 self.mCountAtLastTrigger = 0
15052 self.mFramesSinceLastTrigger = 0
15053 self.mCurrentlyTriggered = False
15054 if PhactoriDbg(100):
15055 myDebugPrint3(
15056 "PhactoriCriteriaThreshold::__init__:\n"
15057 "self.mThresholdValue: " + str(self.mThresholdValue) + "\n"
15058 "self.mFramesAfterTrigger: " + str(self.mFramesAfterTrigger) + "\n"
15059 "self.mMaxTriggers: " + str(self.mMaxTriggers) + "\n", 100)
15060
15061
15062 def ObservePotentialCrossingValue(self, mTestValue):
15063 if PhactoriDbg(100):
15064 if self.mObserveCallCount != 0:
15065 if PhactoriDbg(100):
15066 myDebugPrint3("ObservePotentialCrossingValue:\n" +
15067 str(mTestValue) + " <> " + str(self.mThresholdValue) + " <> " + \
15068 str(self.mLastTestValue) + "\n", 100)
15069 else:
15070 if PhactoriDbg(100):
15071 myDebugPrint3("ObservePotentialCrossingValue:\n" +
15072 str(mTestValue) + " <> " + str(self.mThresholdValue) + " <> " + \
15073 str("first call") + "\n", 100)
15074
15075 if self.mObserveCallCount != 0:
15076 if((self.mLastTestValue <= self.mThresholdValue) and \
15077 (mTestValue >= self.mThresholdValue)) or \
15078 ((self.mLastTestValue >= self.mThresholdValue) and \
15079 (mTestValue <= self.mThresholdValue)):
15080 #the test value crosses the threshold from the last test value
15081 self.mCrossingsSoFar += 1
15082 self.mCountAtLastCrossing = self.mObserveCallCount
15083 if PhactoriDbg(100):
15084 myDebugPrint3("crossing occurred: " + str(self.mCrossingsSoFar) + \
15085 ", " + str(self.mCountAtLastCrossing) + "\n")
15086 if(self.mCrossingsSoFar <= self.mMaxTriggers):
15087 self.mCountAtLastTrigger = self.mObserveCallCount
15088 if PhactoriDbg(100):
15089 myDebugPrint3("self.mCountAtLastTrigger changed to " +
15090 str(self.mCountAtLastTrigger) + "\n")
15091 else:
15092 if PhactoriDbg(100):
15093 myDebugPrint3("no trigger due to self.mMaxTriggers")
15094
15095 self.mCurrentlyTriggered = False
15096 if self.mCrossingsSoFar != 0:
15097 if (self.mFramesAfterTrigger <= 0) or \
15098 (self.mObserveCallCount - self.mCountAtLastTrigger) < \
15099 self.mFramesAfterTrigger:
15100 self.mCurrentlyTriggered = True
15101
15102 if PhactoriDbg(100):
15103 myDebugPrint3("self.mCurrentlyTriggered now " + \
15104 str(self.mCurrentlyTriggered) + "\n")
15105
15106 self.mLastTestValue = mTestValue
15107 self.mObserveCallCount += 1
15108 return
15109
15110 def CurrentlyTriggered(self):
15111 return self.mCurrentlyTriggered
15112
15113 class PhactoriImagesetOnOffFilterCriteria:
15114 """
15115 this class represents one test used to determine if images are or are
15116 not shown. The general idea is that the test is whether a variable
15117 minimum/maximum/mean is above/below/between a certain value or values.
15118 The variable can be scalar, vector magnitude, vector component, or
15119 tensor component, or global, and can be cell/element or point/node
15120 """
15121
15122 def __init__(self):
15123 self.mName = ""
15124 self.mVariableInfo = PhactoriVariableInfo()
15125 self.mRange = [0.0, 1.0]
15126 #min/mean/max
15127 self.mFunctionType = "maximum"
15128 self.mInputOperationName = None
15129 self.mInputOperation = None
15130 #default number of frames after trigger is 5
15131 self.mNumberOfFramesAfterTrigger = 5
15132 self.mHasBeenTriggered = False
15133 self.mCallbackTagAtFirstTrigger = -1
15134 self.mThresholdList = []
15135 self.mMaxTriggersPerThreshold = 1
15136 self.mFrameTagCounter = -1
15137 self.mReturnValAtCurrentFrameTagCounter = False
15138
15139 def TestForTruth(self, ioPipeAndViewsState):
15140 """returns true if this criteria indicates we should render a frame, false
15141 otherwise"""
15142
15143 if PhactoriDbg(100):
15144 myDebugPrint3(
15145 "PhactoriImagesetOnOffFilterCriteria::TestForTruth entered", 100)
15146
15147 if self.mFrameTagCounter == ioPipeAndViewsState.mFrameTagCounter:
15148 if PhactoriDbg(100):
15149 myDebugPrint3(
15150 "additional call, same mFrameTagCounter, just return value", 100)
15151 return self.mReturnValAtCurrentFrameTagCounter
15152 self.mFrameTagCounter = ioPipeAndViewsState.mFrameTagCounter
15153
15154 #if this has been triggered, it remains true no matter what variables do.
15155 #if there is a limit to the number of frames this trigger is true, it
15156 #will be false after that many frames no matter what
15157 #if self.mHasBeenTriggered:
15158 # if self.mNumberOfFramesAfterTrigger < 0:
15159 # #no frame limit; always true now
15160 # return True
15161 # else:
15162 # countSoFar = ioPipeAndViewsState.mFrameTagCounter - \
15163 # self.mCallbackTagAtFirstTrigger
15164 # if PhactoriDbg(100):
15165 # myDebugPrint3(
15166 # "mFrameTagCounter: " + \
15167 # str(ioPipeAndViewsState.mFrameTagCounter) + "\n"
15168 # "mCallbackTagAtFirstTrigger: " + \
15169 # str(self.mCallbackTagAtFirstTrigger) + "\n"
15170 # "countSoFar: " + str(countSoFar) + "\n"
15171 # "mNumberOfFramesAfterTrigger: " + \
15172 # str(self.mNumberOfFramesAfterTrigger) + "\n",
15173 # 100)
15174 # if countSoFar >= self.mNumberOfFramesAfterTrigger:
15175 # #reached frame limit
15176 # return False
15177 # else:
15178 # #haven't reached frame limit, still true
15179 # return True
15180
15181 if self.mInputOperation == None:
15182 if self.mInputOperationName == None:
15183 self.mInputOperation = ioPipeAndViewsState.mIncomingDefaultOperation
15184 else:
15185 if self.mInputOperationName not in ioPipeAndViewsState.mOperationBlocks:
15186 errStr = 'error! in PhactoriImagesetOnOffFilterCriteria::TestForTruth calls for nonexistent input operation with name ' + str(self.mInputOperationName) + '\n'
15187 if PhactoriDbg():
15188 myDebugPrint3(errStr)
15189 raise Exception(errStr)
15190 else:
15191 self.mInputOperation = \
15192 ioPipeAndViewsState.mOperationBlocks[self.mInputOperationName]
15193
15194 theParaViewFilter = self.mInputOperation.GetPvFilter()
15195 UpdatePipelineWithCurrentTimeArgument(theParaViewFilter)
15196
15197 ###find min/max/avg/sum/count
15198 inputcsData = theParaViewFilter.GetClientSideObject().\
15199 GetOutputDataObject(0)
15200 if inputcsData == None:
15201 if PhactoriDbg(100):
15202 myDebugPrint3('inputcsData is None, returning false', 100)
15203 self.mReturnValAtCurrentFrameTagCounter = False
15204 return False
15205
15206 if PhactoriDbg():
15207 myDebugPrint3('finding min/max data for this processor at this timestep\n')
15208 DataMinMax = [0.0, 0.0, False]
15209 DataSumCnt = [0.0, 0]
15210
15211 FindMinMaxSumCntFromData(inputcsData, self.mVariableInfo, None,
15212 DataMinMax, DataSumCnt, None, None)
15213
15214 #just return false if there is no min/max found
15215 #if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
15216 if (DataSumCnt[1] == 0):
15217 if PhactoriDbg(100):
15218 myDebugPrint3('no data value for min/max found, returning', 100)
15219 if PhactoriDbg(100):
15220 myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
15221 100)
15222 self.mReturnValAtCurrentFrameTagCounter = False
15223 return False
15224
15225 if self.mFunctionType == "maximum":
15226 mTestValue = DataMinMax[1]
15227 if PhactoriDbg():
15228 myDebugPrint3("test is against max, " + str(mTestValue) + "\n")
15229 elif self.mFunctionType == "minimum":
15230 mTestValue = DataMinMax[0]
15231 if PhactoriDbg():
15232 myDebugPrint3("test is against min, " + str(mTestValue) + "\n")
15233 elif self.mFunctionType == "mean":
15234 mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])
15235 if PhactoriDbg():
15236 myDebugPrint3("test is against mean, " + str(mTestValue) + "\n")
15237 elif self.mFunctionType == "sum":
15238 mTestValue = DataSumCnt[0]
15239 if PhactoriDbg():
15240 myDebugPrint3("test is against sum, " + str(mTestValue) + "\n")
15241 elif self.mFunctionType == "count":
15242 mTestValue = DataSumCnt[1]
15243 if PhactoriDbg():
15244 myDebugPrint3("test is against count, " + str(mTestValue) + "\n")
15245 else:
15246 myDebugPrint3AndException("PhactoriOnOffCriteria::TestForTruth"
15247 "bad mFunctionType: " + str(self.mFunctionType) + "\n")
15248
15249 #let each threshold see if this value crossed from the previous value,
15250 #and update its internal frame count as appropriate
15251 for oneThrsld in self.mThresholdList:
15252 oneThrsld.ObservePotentialCrossingValue(mTestValue)
15253
15254 #if any threshold was just triggered or was triggered and is within
15255 #the frame count limit, issue a 'True'
15256 for oneThrsld in self.mThresholdList:
15257 if oneThrsld.CurrentlyTriggered():
15258 self.mReturnValAtCurrentFrameTagCounter = True
15259 return True
15260
15261 self.mReturnValAtCurrentFrameTagCounter = False
15262 return False
15263
15264 #if self.mFunctionType == "maximum":
15265 # #possible issue, but probably not; if min/max is 0.0 we assume no
15266 # #data existed
15267 # #DataMinMax[2] == False: don't use this, it's not mpi shared
15268 # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
15269 # if PhactoriDbg(100):
15270 # myDebugPrint3('no data value for max found, returning', 100)
15271 # if PhactoriDbg(
15272 # 100):
15273 # myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
15274 # 100)
15275 # return False
15276 # else:
15277 # mTestValue = DataMinMax[1]
15278 # if PhactoriDbg():
15279 # myDebugPrint3("test is against max, " + str(mTestValue) + "\n")
15280 #elif self.mFunctionType == "minimum":
15281 # #possible issue, but probably not; if min/max is 0.0 we assume no
15282 # #data existed
15283 # #DataMinMax[2] == False: don't use this, it's not mpi shared
15284 # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
15285 # if PhactoriDbg(100):
15286 # myDebugPrint3('no data value for min found, returning', 100)
15287 # if PhactoriDbg(
15288 # 100):
15289 # myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
15290 # 100)
15291 # return False
15292 # else:
15293 # mTestValue = DataMinMax[0]
15294 # if PhactoriDbg():
15295 # myDebugPrint3("test is against min, " + str(mTestValue) + "\n")
15296 #elif self.mFunctionType == "mean":
15297 # if DataSumCnt[1] == 0:
15298 # if PhactoriDbg(100):
15299 # myDebugPrint3('no data values for mean found, returning false', 100)
15300 # return False
15301 # else:
15302 # mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])
15303 # if PhactoriDbg():
15304 # myDebugPrint3("test is against mean, " + str(mTestValue) + "\n")
15305 #elif self.mFunctionType == "sum":
15306 # mTestValue = DataSumCnt[0]
15307 # if PhactoriDbg():
15308 # myDebugPrint3("test is against sum, " + str(mTestValue) + "\n")
15309 #elif self.mFunctionType == "count":
15310 # mTestValue = DataSumCnt[1]
15311 # if PhactoriDbg():
15312 # myDebugPrint3("test is against count, " + str(mTestValue) + "\n")
15313
15314 #if PhactoriDbg():
15315 # myDebugPrint3("test range: " + str(self.mRange) + "\n")
15316 #if mTestValue < self.mRange[0]:
15317 # if PhactoriDbg(100):
15318 # myDebugPrint3('below range, returning false', 100)
15319 # return False
15320 #if mTestValue > self.mRange[1]:
15321 # if PhactoriDbg(100):
15322 # myDebugPrint3('above range, returning false', 100)
15323 # return False
15324
15325 #if PhactoriDbg(100):
15326 # myDebugPrint3('in range, returning true', 100)
15327
15328 #if PhactoriDbg(100):
15329 # myDebugPrint3("cp 6000")
15330
15331
15332 #self.mHasBeenTriggered = True
15333 #self.mCallbackTagAtFirstTrigger = ioPipeAndViewsState.mFrameTagCounter
15334 #return True
15335
15336 def ParseParametersFromJson(self, inJson):
15337 if PhactoriDbg(100):
15338 myDebugPrint3('PhactoriImagesetOnOffFilterCriteria::'
15339 'ParseParametersFromJson entered\n', 100)
15340
15341 foundVariableFlag = self.mVariableInfo.\
15342 ParseVariableNameAndVectorOrTensorComponent(
15343 inJson, 'variable ')
15344
15345 if foundVariableFlag == False:
15346 errStr = """error! inJson has no variable info in
15347 PhactoriImagesetOnOffFilterCriteria.ParseParametersFromJson\n"""
15348 if PhactoriDbg():
15349 myDebugPrint3(errStr)
15350 raise Exception(errStr)
15351
15352 if 'input' in inJson:
15353 self.mInputOperationName = inJson['input']
15354 else:
15355 noticeStr = \
15356 'notice! inJson has no input key, using default pipeline input\n'
15357 self.mInputOperationName = None
15358 if PhactoriDbg():
15359 myDebugPrint3(noticeStr)
15360
15361 if PhactoriDbg():
15362 myDebugPrint3("variable name: " + \
15363 str(self.mVariableInfo.mVariableName) + "\n")
15364
15365 if 'type' in inJson:
15366 theType = inJson['type']
15367 #bug in parsing right now requires different if test
15368 #if theType == 'triggerthresholds':
15369 if theType == 'triggerthresholds' or theType == 'onoffcriteriablock':
15370 if 'threshold variable function' in inJson:
15371 self.mFunctionType = inJson['threshold variable function']
15372 if 'frames after trigger' in inJson:
15373 self.mNumberOfFramesAfterTrigger = \
15374 inJson['frames after trigger']
15375 if 'maximum triggers per threshold' in inJson:
15376 self.mMaxTriggersPerThreshold = \
15377 inJson['maximum triggers per threshold']
15378 for oneThreshold in inJson['threshold values']:
15379 newThrshld = PhactoriCriteriaThreshold(oneThreshold,
15380 self.mNumberOfFramesAfterTrigger,
15381 self.mMaxTriggersPerThreshold)
15382 self.mThresholdList.append(newThrshld)
15383
15384 if PhactoriDbg():
15385 myDebugPrint3("parsed min/max triggerthresholds\n")
15386 return
15387
15388 if 'keep between' in inJson:
15389 self.mRange = inJson['keep between']
15390 self.mFunctionType = "maximum"
15391 elif 'keep below' in inJson:
15392 rangeMin = -sys.float_info.max
15393 rangeMax = inJson['keep below']
15394 self.mRange = [rangeMin, rangeMax]
15395 self.mFunctionType = "minimum"
15396 elif 'keep above' in inJson:
15397 self.mFunctionType = "maximum"
15398 rangeMin = inJson['keep above']
15399 rangeMax = sys.float_info.max
15400 self.mRange = [rangeMin, rangeMax]
15401 elif 'trigger when maximum value is at or above' in inJson:
15402 self.mFunctionType = "maximum"
15403 rangeMin = inJson['trigger when maximum value is at or above']
15404 rangeMax = sys.float_info.max
15405 self.mRange = [rangeMin, rangeMax]
15406 elif 'trigger on maximum value' in inJson:
15407 self.mFunctionType = "maximum"
15408 rangeMin = inJson['trigger on maximum value']
15409 rangeMax = sys.float_info.max
15410 self.mRange = [rangeMin, rangeMax]
15411 elif 'trigger on minimum value' in inJson:
15412 self.mFunctionType = "minimum"
15413 rangeMin = -sys.float_info.max
15414 rangeMax = inJson['trigger on minimum value']
15415 self.mRange = [rangeMin, rangeMax]
15416 else:
15417 if PhactoriDbg():
15418 myDebugPrint3(" no keep between/above/below, using keep above 0.0\n")
15419 self.mFunctionType = "maximum"
15420 rangeMin = 0.0
15421 rangeMax = sys.float_info.max
15422 self.mRange = [rangeMin, rangeMax]
15423
15424 if 'number of frames after trigger' in inJson:
15425 self.mNumberOfFramesAfterTrigger = \
15426 inJson['number of frames after trigger']
15427
15428 if 'frames after trigger' in inJson:
15429 self.mNumberOfFramesAfterTrigger = \
15430 inJson['frames after trigger']
15431
15432 if PhactoriDbg():
15433 myDebugPrint3("range: " + str(self.mRange) + "\n")
15434
15435
15436 class PhactoriImagesetOnOffFilter:
15437 """
15438 this class manages the system whereby users can selectively
15439 choose to render or not render images based on simulation data. The first
15440 simple capability allows users to begin rendering after some simulation
15441 data criteria is met (e.g. maximum of element variable X is above Y), and
15442 stop rendering after some criteria is met"""
15443
15444 def __init__(self):
15445 self.mEnabled = False
15446 self.mLastStartImagesFlag = False
15447 self.mStartCriteriaList = []
15448 #self.mStopCriteriaList = []
15449
15450 def AddStartCriteria(self, inNewCriteria):
15451 self.mEnabled = True
15452 self.mStartCriteriaList.append(inNewCriteria)
15453
15454 #def AddStopCriteria(self, inNewCriteria):
15455 # self.mEnabled = True
15456 # self.mStopCriteriaList.append(inNewCriteria)
15457
15458 def TestDrawImagesThisCallback(self, ioPipeAndViewsState):
15459 """returns True if images should be rendered, False if they should not"""
15460
15461 if PhactoriDbg(
15462 100):
15463 myDebugPrint3(
15464 'PhactoriImagesetOnOffFilter::TestDrawImagesThisCallback entered\n',
15465 100)
15466
15467 #criteriaIndex = 0
15468 #for oneCriteria in self.mStartCriteriaList:
15469 # criteriaIndex += 1
15470 # myDebugPrint3("trying critera: " + str(criteriaIndex))
15471 # if oneCriteria.TestForTruth(ioPipeAndViewsState):
15472 # myDebugPrint3("criteria returned true")
15473 # else:
15474 # myDebugPrint3("criteria returned true")
15475 #return True
15476
15477 if self.mEnabled == False:
15478 if PhactoriDbg():
15479 myDebugPrint3("not enabled, return True\n")
15480 return True
15481
15482 #if images had already been started, keep doing them until a stop
15483 #criteria is hit
15484 #if self.mLastStartImagesFlag == True:
15485 # if PhactoriDbg():
15486 # myDebugPrint3(" returned true last time\n")
15487 # startImages = True
15488 #else:
15489 if True:
15490 #if no startup criteria are present, startup is assumed to be true
15491 if len(self.mStartCriteriaList) == 0:
15492 if PhactoriDbg():
15493 myDebugPrint3(" no criteria, default true\n")
15494 startImages = True
15495 else:
15496 if PhactoriDbg():
15497 myDebugPrint3(" criteria exists, default false\n")
15498 startImages = False
15499 for oneCriteria in self.mStartCriteriaList:
15500 if oneCriteria.TestForTruth(ioPipeAndViewsState):
15501 if PhactoriDbg():
15502 myDebugPrint3(" criteria returned true\n")
15503 startImages = True
15504 #at least one startup criteria is true
15505 break
15506
15507 #if images are going (even if they just started), check the stop criteria
15508 #to see if they need stopping
15509 #if startImages:
15510 # if len(self.mStopCriteriaList) != 0:
15511 # for oneCriteria in self.mStopCriteriaList:
15512 # if oneCriteria.TestForTruth(ioPipeAndViewsState):
15513 # startImages = False
15514 # #at least one stop criteria is true
15515 # break
15516
15517 self.mLastStartImagesFlag = startImages
15518 if PhactoriDbg(100):
15519 myDebugPrint3('returning with value: ' + str(startImages) + '\n', 100)
15520 return startImages
15521
15522 def ParseOneImageStartStopFilterFromViewMap(inOperationParamsJson):
15523 newFilterCriteria = PhactoriImagesetOnOffFilterCriteria()
15524 newFilterCriteria.ParseParametersFromJson(inOperationParamsJson)
15525 global gPipeAndViewsState
15526 gPipeAndViewsState.mImagesetOnOffFilter.AddStartCriteria(newFilterCriteria)
15527
15528
15529 def WriteOutImagesTest(datadescription, coprocessor):
15530 global gPipeAndViewsState
15531 return gPipeAndViewsState.mImagesetOnOffFilter.TestDrawImagesThisCallback(gPipeAndViewsState)
15532
15533 def CreateAllProducersFromAllInputDescriptions(datadescription, inCoprocessor, newRoot):
15534 global gPipeAndViewsState
15535 inputGrid0Name = datadescription.GetInputDescriptionName(0)
15536 #newRoot.mProducer = inCoprocessor.CreateProducer( datadescription, "input" )
15537 newRoot.mProducer = inCoprocessor.CreateProducer( datadescription, inputGrid0Name)
15538 newRoot.mIncomingDefaultOperation.mHasBeenConstructed = True
15539 newRoot.mIncomingDefaultOperation.mName = inputGrid0Name
15540 newRoot.mIncomingDefaultOperation.mOperationSpecifics = PhactoriOperationSpecifics()
15541 newRoot.mOperationBlocks[inputGrid0Name] = newRoot.mIncomingDefaultOperation
15542 numInputGrids = datadescription.GetNumberOfInputDescriptions()
15543 if PhactoriDbg():
15544 myDebugPrint3("numInputGrids: " + str(numInputGrids) + "\n");
15545 for ii in range(0,numInputGrids):
15546 myDebugPrint3(str(ii) + ": " + str(datadescription.GetInputDescriptionName(ii)) + "\n")
15547 defSrc = GetActiveSource();
15548 for ii in range(1,numInputGrids):
15549 incomingInputName = datadescription.GetInputDescriptionName(ii)
15550 newTrivialProducerForGrid = inCoprocessor.CreateProducer( datadescription, incomingInputName)
15551 theGrid = datadescription.GetInputDescription(ii).GetGrid()
15552 newIncomingOperationBlock = PhactoriOperationBlock()
15553 newIncomingOperationBlock.mName = incomingInputName
15554 newIncomingOperationBlock.mParaViewFilter = newTrivialProducerForGrid
15555 newIncomingOperationBlock.mHasBeenConstructed = True
15556 newIncomingOperationBlock.mOperationSpecifics = PhactoriOperationSpecifics()
15557 #newRoot.mIncomingOperationList.append(newIncomingOperationBlock)
15558 #newRoot.mIncomingGridProducerList.append(newTrivialProducerForGrid)
15559 newRoot.mOperationBlocks[newIncomingOperationBlock.mName] = newIncomingOperationBlock
15560 SetActiveSource(defSrc);
15561
15562 def InitializePerPipeRoot(datadescription, inCoprocessor):
15563 if PhactoriDbg():
15564 myDebugPrint3("InitializePerPipeRoot entered\n")
15565
15566 sa = GetUserDataStringArrayAccountingForBypass(datadescription)
15567
15568 testJsonString = sa[0]
15569 separatorCharacterString = sa[1]
15570 inputDeckFilename = sa[2]
15571 extraFileString = sa[3]
15572 sa4 = sa[4]
15573 sa5 = sa[5]
15574 dbDummyFname = sa[6]
15575 if(len(sa) > 7):
15576 defaultDirectory = sa[7]
15577 else:
15578 defaultDirectory = ""
15579 if(len(sa) > 8):
15580 catalyst_script_extra_file = sa[8]
15581 else:
15582 catalyst_script_extra_file = ""
15583
15584 outputResultBaseId, remeshRestartTag = parseDbDummyFname(dbDummyFname)
15585 if PhactoriDbg():
15586 myDebugPrint3(" extra data list:\n")
15587 if PhactoriDbg():
15588 myDebugPrint3(" separatorCharacterString: ->" + separatorCharacterString + "<-\n")
15589 if PhactoriDbg():
15590 myDebugPrint3(" inputDeckFilename: ->" + inputDeckFilename + "<-\n")
15591 if PhactoriDbg():
15592 myDebugPrint3(" extraFileString: ->" + extraFileString + "<-\n")
15593 if PhactoriDbg():
15594 myDebugPrint3(" sa4: ->" + sa4 + "<-\n")
15595 if PhactoriDbg():
15596 myDebugPrint3(" sa5: ->" + sa5 + "<-\n")
15597 if PhactoriDbg():
15598 myDebugPrint3(" dbDummyFname: ->" + dbDummyFname + "<-\n")
15599 if PhactoriDbg():
15600 myDebugPrint3(" outputResultBaseId: ->" + outputResultBaseId + "<-\n")
15601 if PhactoriDbg():
15602 myDebugPrint3(" remeshRestartTag: ->" + remeshRestartTag + "<-\n")
15603 if PhactoriDbg():
15604 myDebugPrint3(" defaultDirectory: ->" + defaultDirectory + "<-\n")
15605 if PhactoriDbg():
15606 myDebugPrint3(" catalyst_script_extra_file: ->" + catalyst_script_extra_file + "<-\n")
15607
15608 global gPipeAndViewsState
15609
15610 if outputResultBaseId in gPhactoriPipeRootMap:
15611 if PhactoriDbg():
15612 myDebugPrint3(" I've seen this outputResults block id\n")
15613 oneRoot = gPhactoriPipeRootMap[outputResultBaseId]
15614 oneRoot.CurrentDatadescription = datadescription
15615 gPipeAndViewsState = oneRoot
15616 if remeshRestartTag != oneRoot.mRemeshRestartTag:
15617 oneRoot.mRemeshRestartTag = remeshRestartTag
15618 oneRoot.mRemeshCount += 1
15619 HandleUserInteractionIfEnabled(oneRoot)
15620 else:
15621 if PhactoriDbg():
15622 myDebugPrint3(" first time for this outputResults block id\n")
15623 SetUpCoProcessor(inCoprocessor)
15624 newRoot = PhactoriPipeAndViewsState()
15625 newRoot.mDefaultBasedirectory = defaultDirectory
15626 newRoot.CurrentDatadescription = datadescription
15627 newRoot.mOutputResultsBlockId = outputResultBaseId
15628 newRoot.mCurrentDatabaseDummyFileName = dbDummyFname
15629 newRoot.mRemeshRestartTag = remeshRestartTag
15630 newRoot.mSeparatorString = separatorCharacterString
15631 newRoot.mOutputResultsBlockCountId = len(gPhactoriPipeRootMap)
15632 newRoot.mBlockIdForRestart = "restart." + str(len(gPhactoriPipeRootMap))
15633 gPhactoriPipeRootMap[outputResultBaseId] = newRoot
15634 gPipeAndViewsState = newRoot
15635 CreateAllProducersFromAllInputDescriptions(datadescription, inCoprocessor, newRoot)
15636
15637 CreatePipelineFromDataDescription(datadescription)
15638 HandleRestartUpdateForOutputResultsBlock(newRoot)
15639
15640 gPipeAndViewsState.mCallbackDateTime = datetime.datetime.now()
15641
15642 if PhactoriDbg():
15643 myDebugPrint3("InitializePerPipeRoot returning\n")
15644
15645
15646 global gColorLegendCollection
15647 gColorLegendCollection = {
15648 "Default":{
15649 "ColorSpace":"Diverging",
15650 "NanColor":[0.25, 0.0, 0.0],
15651 "RGBPoints":[
15652 0.0, 0.23000000000000001, 0.29899999999999999, 0.754,
15653 1.0, 0.70599999999999996, 0.016, 0.14999999999999999
15654 ]
15655 },
15656 "Cool to Warm":{
15657 "ColorSpace":"Diverging",
15658 "NanColor":[0.247058823529, 0.0, 0.0],
15659 "RGBPoints":[
15660 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
15661 0.5, 0.865, 0.865, 0.865,
15662 1.0, 0.705882352941, 0.0156862745098, 0.149019607843
15663 ]
15664 },
15665 "Blue to Red Rainbow":{
15666 "ColorSpace":"HSV",
15667 "NanColor":[0.498039215686, 0.498039215686, 0.498039215686],
15668 "RGBPoints":[
15669 0.0, 0.0, 0.0, 1.0,
15670 1.0, 1.0, 0.0, 0.0
15671 ]
15672 },
15673 "Red to Blue Rainbow":{
15674 "ColorSpace":"HSV",
15675 "NanColor":[0.498039215686, 0.498039215686, 0.498039215686],
15676 "RGBPoints":[
15677 0.0, 1.0, 0.0, 0.0,
15678 1.0, 0.0, 0.0, 1.0
15679 ]
15680 },
15681 "Grayscale":{
15682 "ColorSpace":"RGB",
15683 "NanColor":[1.0, 0.0, 0.0],
15684 "RGBPoints":[
15685 0.0, 0.0, 0.0, 0.0,
15686 1.0, 1.0, 1.0, 1.0
15687 ]
15688 },
15689 "X Ray":{
15690 "ColorSpace":"RGB",
15691 "NanColor":[1.0, 0.0, 0.0],
15692 "RGBPoints":[
15693 0.0, 1.0, 1.0, 1.0,
15694 1.0, 0.0, 0.0, 0.0
15695 ]
15696 },
15697 "Blue to Yellow":{
15698 "ColorSpace":"RGB",
15699 "NanColor":[1.0, 0.0, 0.0],
15700 "RGBPoints":[
15701 0.0, 0.0392156862745, 0.0392156862745, 0.949019607843,
15702 1.0, 0.949019607843, 0.949019607843, 0.0392156862745
15703 ]
15704 },
15705 #"Black-Body Radiation":{}
15706 "Black Body Radiation":{
15707 "ColorSpace":"RGB",
15708 "NanColor":[0.0, 0.498039215686, 1.0],
15709 "RGBPoints":[
15710 0.0, 0.0, 0.0, 0.0,
15711 0.4, 0.901960784314, 0.0, 0.0,
15712 0.8, 0.901960784314, 0.901960784314, 0.0,
15713 1.0, 1.0, 1.0, 1.0
15714 ]
15715 },
15716 "CIELab Blue to Red":{
15717 "ColorSpace":"Lab",
15718 "NanColor":[1.0, 1.0, 0.0],
15719 "RGBPoints":[
15720 0.0, 0.0, 0.6, 0.749019607843,
15721 1.0, 0.76862745098, 0.466666666667, 0.341176470588
15722 ]
15723 },
15724 "Black, Blue and White":{
15725 "ColorSpace":"RGB",
15726 "NanColor":[1.0, 1.0, 0.0],
15727 "RGBPoints":[
15728 0.0, 0.0, 0.0, 0.0,
15729 0.333, 0.0, 0.0, 0.501960784314,
15730 0.666, 0.0, 0.501960784314, 1.0,
15731 1.0, 1.0, 1.0, 1.0
15732 ]
15733 },
15734 "Black, Orange and White":{
15735 "ColorSpace":"RGB",
15736 "NanColor":[1.0, 1.0, 0.0],
15737 "RGBPoints":[
15738 0.0, 0.0, 0.0, 0.0,
15739 0.333, 0.501960784314, 0.0, 0.0,
15740 0.666, 1.0, 0.501960784314, 0.0,
15741 1.0, 1.0, 1.0, 1.0
15742 ]
15743 },
15744 "Cold and Hot":{
15745 "ColorSpace":"RGB",
15746 "NanColor":[1.0, 1.0, 0.0],
15747 "RGBPoints":[
15748 0.0, 0.0, 1.0, 1.0,
15749 0.45, 0.0, 0.0, 1.0,
15750 0.5, 0.0, 0.0, 0.501960784314,
15751 0.55, 1.0, 0.0, 0.0,
15752 1.0, 1.0, 1.0, 0.0
15753 ]
15754 },
15755 "Rainbow Desaturated":{
15756 "ColorSpace":"RGB",
15757 "NanColor":[1.0, 1.0, 0.0],
15758 "RGBPoints":[
15759 0.0, 0.278431372549, 0.278431372549, 0.858823529412,
15760 0.143, 0.0, 0.0, 0.360784313725,
15761 0.285, 0.0, 1.0, 1.0,
15762 0.429, 0.0, 0.501960784314, 0.0,
15763 0.571, 1.0, 1.0, 0.0,
15764 0.714, 1.0, 0.380392156863, 0.0,
15765 0.857, 0.419607843137, 0.0, 0.0,
15766 1.0, 0.878431372549, 0.301960784314, 0.301960784314
15767 ]
15768 },
15769 "Rainbow Blended White":{
15770 "ColorSpace":"RGB",
15771 "NanColor":[1.0, 1.0, 0.0],
15772 "RGBPoints":[
15773 0.0, 1.0, 1.0, 1.0,
15774 0.17, 0.0, 0.0, 1.0,
15775 0.34, 0.0, 1.0, 1.0,
15776 0.5, 0.0, 1.0, 0.0,
15777 0.67, 1.0, 1.0, 0.0,
15778 0.84, 1.0, 0.0, 0.0,
15779 1.0, 0.878431372549, 0.0, 1.0
15780 ]
15781 },
15782 "Rainbow Blended Grey":{
15783 "ColorSpace":"RGB",
15784 "NanColor":[1.0, 1.0, 0.0],
15785 "RGBPoints":[
15786 0.0, 0.317647058824, 0.341176470588, 0.43137254902,
15787 0.17, 0.0, 0.0, 1.0,
15788 0.34, 0.0, 1.0, 1.0,
15789 0.5, 0.0, 1.0, 0.0,
15790 0.67, 1.0, 1.0, 0.0,
15791 0.84, 1.0, 0.0, 0.0,
15792 1.0, 0.878431372549, 0.0, 1.0
15793 ]
15794 },
15795 #"Cool to Warm with Top":{
15796 # "ColorSpace":"Diverging",
15797 # "NanColor":[0.247058823529, 0.0, 0.0],
15798 # "RGBPoints":[
15799 # 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
15800 # 0.5, 0.865, 0.865, 0.865,
15801 # 0.98, 0.705882352941, 0.0156862745098, 0.149019607843,
15802 # 1.0, 0.0, 1.0, 1.0,
15803 # ]
15804 #},
15805 "Cool to Warm with Top":{
15806 "ColorSpace":"Diverging",
15807 #"ColorSpace":"RGB",
15808 "NanColor":[0.247058823529, 0.0, 0.0],
15809 "RGBPoints":[
15810 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
15811 0.5, 0.865, 0.865, 0.865,
15812 0.799, 0.769528, 0.355412, 0.435412,
15813 0.800, 0.0, 1.0, 1.0,
15814 0.814, 0.0, 1.0, 1.0,
15815 0.815, 0.769528, 0.355412, 0.435412,
15816 1.0, 0.705882352941, 0.0156862745098, 0.149019607843,
15817 ]
15818 },
15819 }
15820
15821 def GetColorMapInfoFromColorLegendCollection(inColorMapSettings, inMin, inMax):
15822 global gColorLegendCollection
15823
15824 inStrId = inColorMapSettings.mColorMapNameId
15825
15826 #convert underscores (if any) to spaces in key
15827 inStrId = inStrId.replace('_', ' ')
15828
15829 if inStrId not in gColorLegendCollection:
15830 if PhactoriDbg(600):
15831 myDebugPrint3("GetColorMapInfoFromColorLegendCollection: bad map name:" +\
15832 str(inStrId) + " using Default\n", 600)
15833 inStrId = "Default"
15834 colorLegendItem = gColorLegendCollection[inStrId]
15835 outRGBPoints = list(colorLegendItem["RGBPoints"])
15836 outNanColor = list(colorLegendItem["NanColor"])
15837 outColorSpace = str(colorLegendItem["ColorSpace"])
15838
15839 #invert color map if requested
15840 if inColorMapSettings.mInvertColorMap:
15841 newOutRGBPoints = list()
15842 #step through the points (4 doubles) backwards and put them on a new
15843 #list in reverse order, also reversing the position value
15844 for ii in range(len(outRGBPoints) - 4, -1, -4):
15845 newOutRGBPoints.append(1.0 - outRGBPoints[ii])
15846 newOutRGBPoints.append(outRGBPoints[ii+1])
15847 newOutRGBPoints.append(outRGBPoints[ii+2])
15848 newOutRGBPoints.append(outRGBPoints[ii+3])
15849 #myDebugPrint3("uninverted list:")
15850 #for ii in range(0, len(outRGBPoints), 4):
15851 # myDebugPrint3(" " + \
15852 # str(outRGBPoints[ii]) + ", " + \
15853 # str(outRGBPoints[ii+1]) + ", " + \
15854 # str(outRGBPoints[ii+2]) + ", " + \
15855 # str(outRGBPoints[ii+3]) + "\n")
15856 #myDebugPrint3("inverted list:")
15857 #for ii in range(0, len(newOutRGBPoints), 4):
15858 # myDebugPrint3(" " + \
15859 # str(newOutRGBPoints[ii]) + ", " + \
15860 # str(newOutRGBPoints[ii+1]) + ", " + \
15861 # str(newOutRGBPoints[ii+2]) + ", " + \
15862 # str(newOutRGBPoints[ii+3]) + "\n")
15863 outRGBPoints = newOutRGBPoints
15864
15865 numVals = len(outRGBPoints)
15866 delta = inMax - inMin
15867 for ii in range(0, numVals, 4):
15868 ratio = outRGBPoints[ii]
15869 outRGBPoints[ii] = inMin + ratio * delta
15870 return (outRGBPoints, outColorSpace, outNanColor)
15871
15872
15873
15874 myDebugPrint3("gParaViewCatalystVersionFlag is: " + str(gParaViewCatalystVersionFlag) +"\n")