Debian Codegraph @

packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.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 try: paraview.simple
34 except: from paraview.simple import *
35
36 from paraview import coprocessing
37
38 # ----------------------- Pipeline definition -----------------------
39
40 #from phactori import *
41 ######phactori.py inserted here by PhactoriCombineToOneFile.py
42
43 # Copyright(C) 1999-2020 National Technology & Engineering Solutions
44 # of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
45 # NTESS, the U.S. Government retains certain rights in this software.
46 #
47 # Redistribution and use in source and binary forms, with or without
48 # modification, are permitted provided that the following conditions are
49 # met:
50 #
51 # * Redistributions of source code must retain the above copyright
52 # notice, this list of conditions and the following disclaimer.
53 #
54 # * Redistributions in binary form must reproduce the above
55 # copyright notice, this list of conditions and the following
56 # disclaimer in the documentation and/or other materials provided
57 # with the distribution.
58 #
59 # * Neither the name of NTESS nor the names of its
60 # contributors may be used to endorse or promote products derived
61 # from this software without specific prior written permission.
62 #
63 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
64 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
65 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
66 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
67 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
68 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
69 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
70 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
71 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
72 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
73 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74
75
76
77 #these settings allow us to specify a particular json format (or bccolli.py)
78 #text file to use as the phactori visualization setup file.
79 #if gUseHardwiredJsonScriptFile is None, operation is normal, but if it
80 #is set to a file string, we ignore any other parsing and use the specified
81 #file
82 global gUseHardwiredJsonScriptFile
83 gUseHardwiredJsonScriptFile = None
84 #gUseHardwiredJsonScriptFile = "myscript1.json"
85 #gUseHardwiredJsonScriptFile = "sparc_phactori_catalyst_insitu.json"
86
87 def setgUseHardwiredJsonScriptFile(inScriptFileName):
88 global gUseHardwiredJsonScriptFile
89 gUseHardwiredJsonScriptFile = inScriptFileName
90
91 global gRenderingEnabled
92 gRenderingEnabled = True
93
94 global WriteDeadCellSummaryFile
95 WriteDeadCellSummaryFile = True
96
97 global gPipeAndViewsState
98 gPipeAndViewsState = None
99
100 def SetgPipeAndViewStateForTesting(testPipe):
101 global gPipeAndViewsState
102 gPipeAndViewsState = testPipe
103
104 def GetFrameTagCounter():
105 global gPipeAndViewsState
106 if gPipeAndViewsState == None:
107 return 0
108 return gPipeAndViewsState.mFrameTagCounter
109
110 try: paraview.simple
111 except: from paraview.simple import *
112
113 from paraview import coprocessing
114
115 import vtk
116 import json
117
118 global gParaViewCatalystVersionFlag
119 #gParaViewCatalystVersionFlag = 40300
120 #gParaViewCatalystVersionFlag = 40100
121 #gParaViewCatalystVersionFlag = 50400
122 #gParaViewCatalystVersionFlag = 50502
123 #gParaViewCatalystVersionFlag = 51000
124 gParaViewCatalystVersionFlag = 51100
125
126 #attempt to use paraview.simple.GetParaViewVersion() to set version
127 try:
128 versionTuple = GetParaViewVersion()
129 gParaViewCatalystVersionFlag = versionTuple.major * 10000
130 gParaViewCatalystVersionFlag += versionTuple.minor * 100
131 except:
132 raise Exception("exception while working with paraview.simple.GetParaViewVersion()")
133
134 global gPointsString
135 if gParaViewCatalystVersionFlag <= 40100:
136 gPointsString = 'POINT_DATA'
137 gCellsString = 'CELL_DATA'
138 else:
139 gPointsString = 'POINTS'
140 gCellsString = 'CELLS'
141
142 import math
143 import sys
144 import datetime
145
146 global gBypassUserData
147 #gBypassUserData = True
148 gBypassUserData = False
149
150 global gUserDataBypassStrings
151 gUserDataBypassStrings = None
152
153 global gBypassUserDataJson
154 gBypassUserDataJson = None
155
156 global TestUserDataForBypassScriptCompletedFlag
157 TestUserDataForBypassScriptCompletedFlag = False
158
159 global gTemporaryGlobalImageTextColor
160 gTemporaryGlobalImageTextColor = [1.0, 1.0, 1.0]
161
162 global bccolli_controls
163
164 global gCameraTestMode
165 gCameraTestMode = 0
166 global gSkipWriteImageForTests
167 gSkipWriteImageForTests = False
168
169 def SetCameraTestMode(onOffSetting):
170 gCameraTestMode = onOffSetting
171
172 import os
173 if "PHACTORI_TEST_CAMERA_MODE" in os.environ:
174 if os.environ["PHACTORI_TEST_CAMERA_MODE"] == "on":
175 gSkipWriteImageForTests = True
176 gCameraTestMode = 1
177
178 def HandleJsonScriptLoadProcessZero(catalyst_script_extra_file):
179 if PhactoriDbg():
180 myDebugPrint3("HandleJsonScriptLoadProcessZero entered\n")
181 myDebugPrint3("catalyst_script_extra_file: " + \
182 str(catalyst_script_extra_file) + "\n")
183 try:
184 with open(catalyst_script_extra_file) as data_file:
185 if PhactoriDbg(100):
186 myDebugPrint3("open successful: \n")
187 visDescpJson = json.load(data_file)
188 visDescpJson = convertJsonUnicodeToStrings(visDescpJson)
189 if PhactoriDbg(100):
190 myDebugPrint3("load successful:\n" + str(visDescpJson) + "\n")
191 except:
192 #couldn't open file, use default string and also try writing out default
193 #script
194 if PhactoriDbg(100):
195 myDebugPrint3("error trying to load catalyst_script_extra_file: " + \
196 str(catalyst_script_extra_file) + "\n"
197 "using default string script\n")
198 global catalyst_script_default_string_json
199
200 import os
201 if os.path.exists(catalyst_script_extra_file):
202 if PhactoriDbg(100):
203 myDebugPrint3("script file is present in directory but could not be\n"
204 "loaded. It will not be overwritten.\n")
205 else:
206 if PhactoriDbg(100):
207 myDebugPrint3("script file is not present in directory so a default\n"
208 "version will be created.\n")
209 try:
210 ff = open(catalyst_script_extra_file, "w")
211 ff.write(catalyst_script_default_string_json)
212 ff.close()
213 except:
214 if PhactoriDbg(100):
215 myDebugPrint3("could not write out default file\n")
216
217 visDescpJson = json.loads(catalyst_script_default_string_json)
218 visDescpJson = convertJsonUnicodeToStrings(visDescpJson)
219
220 #now broadcast
221 #import pdb
222 #pdb.set_trace()
223
224 #broadcast for full multiprocess functionality
225 #color range needs no broadcast, as that will be managed when color range
226 #calculated for the next frame (process 1 will share the maxes and mins
227 #it has)
228
229 try:
230 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
231 globalController = pm.GetGlobalController()
232
233 outStr = json.dumps(visDescpJson)
234
235 numberOfValues = len(outStr)
236
237 #send size of data buffer first
238 vtkInfoBufferSizeArray = vtk.vtkIntArray()
239 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
240 vtkInfoBufferSizeArray.SetValue(0, int(numberOfValues))
241 if PhactoriDbg():
242 myDebugPrint3("trying to broadcast size of array: " + str(int(numberOfValues)) + "\n")
243 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
244 if PhactoriDbg():
245 myDebugPrint3("returned from broadcasting size of array\n")
246
247 if numberOfValues == 0:
248 if PhactoriDbg():
249 myDebugPrint3("broadcast was 0 data, so we are done\n")
250 if PhactoriDbg():
251 myDebugPrint3("HandleJsonScriptLoadProcessZero returning 2\n")
252 return None;
253
254 if PhactoriDbg():
255 myDebugPrint3("now sending data\n")
256 #now fill out data and send it
257 vtkOutArray = vtk.vtkCharArray()
258 vtkOutArray.SetNumberOfTuples(numberOfValues)
259 for jj in range(0, numberOfValues):
260 vtkOutArray.SetValue(jj, outStr[jj])
261
262 globalController.Broadcast(vtkOutArray, 0)
263
264 if PhactoriDbg():
265 myDebugPrint3("done sending data\n")
266 except:
267 #broadcast error; not really recoverable;
268 if PhactoriDbg():
269 myDebugPrint3("exception trying to broadcast\n")
270 myDebugPrint3AndException("HandleJsonScriptLoadProcessZero exception returning 4\n")
271 return
272
273 if PhactoriDbg():
274 myDebugPrint3("HandleJsonScriptLoadProcessZero returning\n")
275
276 return visDescpJson
277
278 global catalyst_script_default_string_json
279 catalyst_script_default_string_json = '' \
280 '{\n' \
281 '"camera blocks":{\n' \
282 ' "camx1":{"camera type":"camera","look direction":[-1,0,0]},\n' \
283 ' "camy1":{"camera type":"camera","look direction":[0,-1,0]},\n' \
284 ' "camz1":{"camera type":"camera","look direction":[0,0,-1]},\n' \
285 ' "camz2":{"camera type":"camera","look direction":[0,0,1]},\n' \
286 ' "camxyz1":{"camera type":"camera","look direction":[-1,-1,-1],"look at relative distance":0.8},\n' \
287 ' "camxyz2":{"camera type":"camera","look direction":[1,1,1],"look at relative distance":0.8},\n' \
288 ' "camxyz3":{"camera type":"camera","look direction":[0.7,-0.3,-1],"look at relative distance":0.8},\n' \
289 ' "camxyz4":{"camera type":"camera","look direction":[0.3,-0.3,-1],"look at relative distance":1.0},\n' \
290 ' "camz3_nosezoom3":{\n' \
291 ' "camera type":"camera",\n' \
292 ' "look direction":[0,0,1],\n' \
293 ' "look at absolute point":[0.0195, 0.0, 0.0],\n' \
294 ' "look at absolute distance":0.1\n' \
295 ' }\n' \
296 '},\n' \
297 '"representation blocks":{\n' \
298 ' "rep_velocity_x":{ "color by scalar":"velocity_1", "variable type":"element"},\n' \
299 ' "rep_velocity_y":{ "color by scalar":"velocity_2", "variable type":"element"},\n' \
300 ' "rep_velocity_z":{ "color by scalar":"velocity_3", "variable type":"element"},\n' \
301 ' "rep_pressure":{ "color by scalar":"pressure", "variable type":"element"},\n' \
302 ' "rep_density":{ "color by scalar":"density", "variable type":"element"},\n' \
303 ' "rep_temperature":{ "color by scalar":"temperature", "variable type":"element"},\n' \
304 ' "rep_Ma":{ "color by scalar":"Ma", "variable type":"element"},\n' \
305 ' "rep_pressure_0_15000":{ "color by scalar":"pressure", "variable type":"element", "color legend maximum range":[0.0, 15000.0]}\n' \
306 '},\n' \
307 '"imageset blocks":{\n' \
308 ' "is_Ma_camz2":{\n' \
309 ' "camera":"camz2",\n' \
310 ' "representation":"rep_Ma",\n' \
311 ' "image basedirectory":"CatalystOutput",\n' \
312 ' "image basename":"Ma_camz2."\n' \
313 ' },\n' \
314 ' "is_Ma_camxyz1":{\n' \
315 ' "camera":"camxyz1",\n' \
316 ' "representation":"rep_Ma",\n' \
317 ' "image basedirectory":"CatalystOutput",\n' \
318 ' "image basename":"Ma_camxyz1."\n' \
319 ' },\n' \
320 ' "is_Ma_camxyz2":{\n' \
321 ' "camera":"camxyz2",\n' \
322 ' "representation":"rep_Ma",\n' \
323 ' "image basedirectory":"CatalystOutput",\n' \
324 ' "image basename":"Ma_camxyz2."\n' \
325 ' },\n' \
326 ' "is_xyslice_minz_1_Ma":{\n' \
327 ' "camera":"camz1",\n' \
328 ' "operation":"xyslice_minz_1",\n' \
329 ' "representation":"rep_Ma",\n' \
330 ' "image basedirectory":"CatalystOutput",\n' \
331 ' "image basename":"xyslice_minz_1_Ma."\n' \
332 ' },\n' \
333 ' "is_xyslice_midz_1_Ma":{\n' \
334 ' "camera":"camz1",\n' \
335 ' "operation":"xyslice_midz_1",\n' \
336 ' "representation":"rep_Ma",\n' \
337 ' "image basedirectory":"CatalystOutput",\n' \
338 ' "image basename":"xyslice_midz_1_Ma."\n' \
339 ' },\n' \
340 ' "is_xyslice_maxz_1_Ma":{\n' \
341 ' "camera":"camz1",\n' \
342 ' "operation":"xyslice_maxz_1",\n' \
343 ' "representation":"rep_Ma",\n' \
344 ' "image basedirectory":"CatalystOutput",\n' \
345 ' "image basename":"xyslice_maxz_1_Ma."\n' \
346 ' },\n' \
347 ' "is_yzslice_minx_1_Ma":{\n' \
348 ' "camera":"camx1",\n' \
349 ' "operation":"yzslice_minx_1",\n' \
350 ' "representation":"rep_Ma",\n' \
351 ' "image basedirectory":"CatalystOutput",\n' \
352 ' "image basename":"yzslice_minx_1_Ma."\n' \
353 ' },\n' \
354 ' "is_yzslice_midx_1_Ma":{\n' \
355 ' "camera":"camx1",\n' \
356 ' "operation":"yzslice_midx_1",\n' \
357 ' "representation":"rep_Ma",\n' \
358 ' "image basedirectory":"CatalystOutput",\n' \
359 ' "image basename":"yzslice_midx_1_Ma."\n' \
360 ' },\n' \
361 ' "is_yzslice_maxx_1_Ma":{\n' \
362 ' "camera":"camx1",\n' \
363 ' "operation":"yzslice_maxx_1",\n' \
364 ' "representation":"rep_Ma",\n' \
365 ' "image basedirectory":"CatalystOutput",\n' \
366 ' "image basename":"yzslice_maxx_1_Ma."\n' \
367 ' },\n' \
368 ' "is_xzslice_miny_1_Ma":{\n' \
369 ' "camera":"camy1",\n' \
370 ' "operation":"xzslice_miny_1",\n' \
371 ' "representation":"rep_Ma",\n' \
372 ' "image basedirectory":"CatalystOutput",\n' \
373 ' "image basename":"xzslice_miny_1_Ma."\n' \
374 ' },\n' \
375 ' "is_xzslice_midy_1_Ma":{\n' \
376 ' "camera":"camy1",\n' \
377 ' "operation":"xzslice_midy_1",\n' \
378 ' "representation":"rep_Ma",\n' \
379 ' "image basedirectory":"CatalystOutput",\n' \
380 ' "image basename":"xzslice_midy_1_Ma."\n' \
381 ' },\n' \
382 ' "is_xzslice_maxy_1_Ma":{\n' \
383 ' "camera":"camy1",\n' \
384 ' "operation":"xzslice_maxy_1",\n' \
385 ' "representation":"rep_Ma",\n' \
386 ' "image basedirectory":"CatalystOutput",\n' \
387 ' "image basename":"xzslice_maxy_1_Ma."\n' \
388 ' },\n' \
389 ' "is_wall_surface_cells_Ma_1":{\n' \
390 ' "camera":"camxyz4",\n' \
391 ' "operation":"find_wall_surface_cells",\n' \
392 ' "representation":"rep_Ma",\n' \
393 ' "image basedirectory":"CatalystOutput",\n' \
394 ' "image basename":"wall_surface_cells_Ma."\n' \
395 ' },\n' \
396 ' "is_wall_surface_cells_velocity_x_1":{\n' \
397 ' "camera":"camxyz4",\n' \
398 ' "operation":"find_wall_surface_cells",\n' \
399 ' "representation":"rep_velocity_x",\n' \
400 ' "image basedirectory":"CatalystOutput",\n' \
401 ' "image basename":"wall_surface_cells_velocity_x."\n' \
402 ' },\n' \
403 ' "is_wall_surface_cells_velocity_y_1":{\n' \
404 ' "camera":"camxyz4",\n' \
405 ' "operation":"find_wall_surface_cells",\n' \
406 ' "representation":"rep_velocity_y",\n' \
407 ' "image basedirectory":"CatalystOutput",\n' \
408 ' "image basename":"wall_surface_cells_velocity_y."\n' \
409 ' },\n' \
410 ' "is_wall_surface_cells_velocity_z_1":{\n' \
411 ' "camera":"camxyz4",\n' \
412 ' "operation":"find_wall_surface_cells",\n' \
413 ' "representation":"rep_velocity_z",\n' \
414 ' "image basedirectory":"CatalystOutput",\n' \
415 ' "image basename":"wall_surface_cells_velocity_z."\n' \
416 ' },\n' \
417 ' "is_wall_surface_cells_pressure_1":{\n' \
418 ' "camera":"camxyz4",\n' \
419 ' "operation":"find_wall_surface_cells",\n' \
420 ' "representation":"rep_pressure",\n' \
421 ' "image basedirectory":"CatalystOutput",\n' \
422 ' "image basename":"wall_surface_cells_pressure."\n' \
423 ' },\n' \
424 ' "is_wall_surface_cells_density_1":{\n' \
425 ' "camera":"camxyz4",\n' \
426 ' "operation":"find_wall_surface_cells",\n' \
427 ' "representation":"rep_density",\n' \
428 ' "image basedirectory":"CatalystOutput",\n' \
429 ' "image basename":"wall_surface_cells_density."\n' \
430 ' },\n' \
431 ' "is_wall_surface_cells_temperature_1":{\n' \
432 ' "camera":"camxyz4",\n' \
433 ' "operation":"find_wall_surface_cells",\n' \
434 ' "representation":"rep_temperature",\n' \
435 ' "image basedirectory":"CatalystOutput",\n' \
436 ' "image basename":"wall_surface_cells_temperature."\n' \
437 ' },\n' \
438 ' "is_three_slices_Ma_1":{\n' \
439 ' "camera":"camxyz3",\n' \
440 ' "operation":"group_xyslice_minz_1_yzslice_midx_1_xzslice_midy_1",\n' \
441 ' "representation":"rep_Ma",\n' \
442 ' "image basedirectory":"CatalystOutput",\n' \
443 ' "image basename":"three_slices_Ma_1."\n' \
444 ' }\n' \
445 '},\n' \
446 '"operation blocks":{\n' \
447 ' "xyslice_minz_1":{\n' \
448 ' "type":"slicewithplane",\n' \
449 ' "plane normal":[0.0, 0.0, 1.0],\n' \
450 ' "relative point on plane":[0.0, 0.0, -0.499999]\n' \
451 ' },\n' \
452 ' "xyslice_midz_1":{\n' \
453 ' "type":"slicewithplane",\n' \
454 ' "plane normal":[0.0, 0.0, 1.0],\n' \
455 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
456 ' },\n' \
457 ' "xyslice_maxz_1":{\n' \
458 ' "type":"slicewithplane",\n' \
459 ' "plane normal":[0.0, 0.0, 1.0],\n' \
460 ' "relative point on plane":[0.0, 0.0, 0.499999]\n' \
461 ' },\n' \
462 ' "vtm_out_xyslice_minz_1":{\n' \
463 ' "type":"vtkdataexport",\n' \
464 ' "input":"xyslice_minz_1",\n' \
465 ' "basename":"xyslice_minz_1"\n' \
466 ' },\n' \
467 ' "vtm_out_xyslice_midz_1":{\n' \
468 ' "type":"vtkdataexport",\n' \
469 ' "input":"xyslice_midz_1",\n' \
470 ' "basename":"xyslice_midz_1"\n' \
471 ' },\n' \
472 ' "vtm_out_xyslice_maxz_1":{\n' \
473 ' "type":"vtkdataexport",\n' \
474 ' "input":"xyslice_maxz_1",\n' \
475 ' "basename":"xyslice_maxz_1"\n' \
476 ' },\n' \
477 ' "yzslice_minx_1":{\n' \
478 ' "type":"slicewithplane",\n' \
479 ' "plane normal":[1.0, 0.0, 0.0],\n' \
480 ' "relative point on plane":[-0.499999, 0.0, 0.0]\n' \
481 ' },\n' \
482 ' "yzslice_midx_1":{\n' \
483 ' "type":"slicewithplane",\n' \
484 ' "plane normal":[1.0, 0.0, 0.0],\n' \
485 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
486 ' },\n' \
487 ' "yzslice_maxx_1":{\n' \
488 ' "type":"slicewithplane",\n' \
489 ' "plane normal":[1.0, 0.0, 0.0],\n' \
490 ' "relative point on plane":[0.499999, 0.0, 0.0]\n' \
491 ' },\n' \
492 ' "vtm_out_yzslice_minx_1":{\n' \
493 ' "type":"vtkdataexport",\n' \
494 ' "input":"yzslice_minx_1",\n' \
495 ' "basename":"yzslice_minx_1"\n' \
496 ' },\n' \
497 ' "vtm_out_yzslice_midx_1":{\n' \
498 ' "type":"vtkdataexport",\n' \
499 ' "input":"yzslice_midx_1",\n' \
500 ' "basename":"yzslice_midx_1"\n' \
501 ' },\n' \
502 ' "vtm_out_yzslice_maxx_1":{\n' \
503 ' "type":"vtkdataexport",\n' \
504 ' "input":"yzslice_maxx_1",\n' \
505 ' "basename":"yzslice_maxx_1"\n' \
506 ' },\n' \
507 ' "xzslice_miny_1":{\n' \
508 ' "type":"slicewithplane",\n' \
509 ' "plane normal":[0.0, 1.0, 0.0],\n' \
510 ' "relative point on plane":[0.0, -0.499999, 0.0]\n' \
511 ' },\n' \
512 ' "xzslice_midy_1":{\n' \
513 ' "type":"slicewithplane",\n' \
514 ' "plane normal":[0.0, 1.0, 0.0],\n' \
515 ' "relative point on plane":[0.0, 0.0, 0.0]\n' \
516 ' },\n' \
517 ' "xzslice_maxy_1":{\n' \
518 ' "type":"slicewithplane",\n' \
519 ' "plane normal":[0.0, 1.0, 0.0],\n' \
520 ' "relative point on plane":[0.0, 0.499999, 0.0]\n' \
521 ' },\n' \
522 ' "vtm_out_xzslice_miny_1":{\n' \
523 ' "type":"vtkdataexport",\n' \
524 ' "input":"xzslice_miny_1",\n' \
525 ' "basename":"xzslice_miny_1"\n' \
526 ' },\n' \
527 ' "vtm_out_xzslice_midy_1":{\n' \
528 ' "type":"vtkdataexport",\n' \
529 ' "input":"xzslice_midy_1",\n' \
530 ' "basename":"xzslice_midy_1"\n' \
531 ' },\n' \
532 ' "vtm_out_xzslice_maxy_1":{\n' \
533 ' "type":"vtkdataexport",\n' \
534 ' "input":"xzslice_maxy_1",\n' \
535 ' "basename":"xzslice_maxy_1"\n' \
536 ' },\n' \
537 ' "mark_cells_for_surface_extraction":{\n' \
538 ' "type":"markcellsurfacestatus2"\n' \
539 ' },\n' \
540 ' "find_wall_surface_cells":{\n' \
541 ' "type":"threshold",\n' \
542 ' "input":"mark_cells_for_surface_extraction",\n' \
543 ' "variable scalar":"surfacestatus",\n' \
544 ' "keep between":[11,100]\n' \
545 ' },\n' \
546 ' "vtm_out_wall_surface_cells":{\n' \
547 ' "type":"vtkdataexport",\n' \
548 ' "input":"find_wall_surface_cells",\n' \
549 ' "basename":"wall_surface_cells"\n' \
550 ' },\n' \
551 ' "group_xyslice_minz_1_yzslice_midx_1_xzslice_midy_1":{\n' \
552 ' "type":"group",\n' \
553 ' "operation group list":["xyslice_minz_1", "yzslice_midx_1", "xzslice_midy_1"]\n' \
554 ' }\n' \
555 '},\n' \
556 '"text annotation blocks":{},\n' \
557 '"scatter plot blocks":{},\n' \
558 '"plot over time blocks":{},\n' \
559 '"experimental blocks":{},\n' \
560 '"onoff criteria blocks":{},\n' \
561 '"visual marker blocks":{}\n' \
562 '}\n\n'
563
564 def HandleJsonScriptLoadProcessNotZero():
565 if PhactoriDbg():
566 myDebugPrint3("HandleJsonScriptLoadProcessNotZero entered\n")
567
568 try:
569 #do broadcast (receive from process 0) to receive update data
570 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
571 globalController = pm.GetGlobalController()
572
573 if PhactoriDbg():
574 myDebugPrint3("trying to receive data buffer length\n")
575
576 #first, get size of data. If it is zero, we are done and there won't be
577 #another broadcast
578 vtkInfoBufferSizeArray = vtk.vtkIntArray()
579 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
580 #vtkInfoBufferSizeArray.SetValue(0, 0)
581 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
582 bufferLen = int(vtkInfoBufferSizeArray.GetTuple1(0))
583 if bufferLen == 0:
584 if PhactoriDbg():
585 myDebugPrint3("broadcast indicated 0 data, so we are done\n")
586 if PhactoriDbg():
587 myDebugPrint3("HandleJsonScriptLoadProcessNotZero returning 2\n")
588 return None;
589
590 if PhactoriDbg():
591 myDebugPrint3("buffer length: " + str(bufferLen) + \
592 ", now trying to receive data\n")
593 #first go round, fixed buffer length, next expandable if necessary
594 vtkOutArray = vtk.vtkCharArray()
595 vtkOutArray.SetNumberOfTuples(int(bufferLen))
596 #for jj in range(0, bufferLen):
597 # vtkOutArray.SetValue(jj, 0)
598
599 #receive broadcast of info from process 0
600 globalController.Broadcast(vtkOutArray, 0)
601 if PhactoriDbg():
602 myDebugPrint3("data received successfully\n")
603 except:
604 #broadcast error; not really recoverable;
605 if PhactoriDbg():
606 myDebugPrint3("exception trying to receive broadcast\n")
607 myDebugPrint3AndException("HandleJsonScriptLoadProcessNotZero returning 2\n")
608 return
609
610 try:
611 if PhactoriDbg():
612 myDebugPrint3("converting data to json format string\n")
613 #convert to json-format string
614 jsonCharList = []
615 for ii in range(0, bufferLen):
616 oneChar = chr(int(vtkOutArray.GetTuple1(ii)))
617 jsonCharList.append(oneChar)
618
619 #if PhactoriDbg():
620 # myDebugPrint3("done making jsonCharList:\n" + str(jsonCharList) + "\n")
621
622 jsonInString = "".join(jsonCharList)
623
624 #if PhactoriDbg():
625 # myDebugPrint3("json received from broadcast (converted to string):\n" +
626 # jsonInString + "\n")
627 if PhactoriDbg():
628 myDebugPrint3("conversion to string complete:\n")
629
630 #jsonInString2 = str(jsonInString)
631
632 #if PhactoriDbg():
633 # myDebugPrint3("(converted to string 2):\n" +
634 # jsonInString2 + "\n")
635
636 #convert json format string to python dict
637 if PhactoriDbg():
638 myDebugPrint3("about to convert back to json\n")
639 jsonIn = json.loads(jsonInString)
640 jsonIn = convertJsonUnicodeToStrings(jsonIn)
641 if PhactoriDbg():
642 myDebugPrint3("done converting back to json\n")
643
644 if PhactoriDbg():
645 myDebugPrint3("json received from broadcast (converted to dict):\n" +
646 str(jsonIn) + "\n")
647
648 except:
649 #broadcast error; not really recoverable;
650 if PhactoriDbg():
651 myDebugPrint3("exception trying to use broadcast info as json set info\n")
652 myDebugPrint3AndException("HandleJsonScriptLoadProcessNotZero returning 3\n")
653 return
654
655 if PhactoriDbg():
656 myDebugPrint3("HandleJsonScriptLoadProcessNotZero returning\n")
657
658 return jsonIn
659
660 def TestUserDataForBypassScript(datadescription):
661
662 global TestUserDataForBypassScriptCompletedFlag
663 if TestUserDataForBypassScriptCompletedFlag == True:
664 #already tested before, just return
665 return
666
667 TestUserDataForBypassScriptCompletedFlag = True
668
669 global gBypassUserData
670 if gBypassUserData:
671 #already true, just return
672 return
673
674 if PhactoriDbg(100):
675 myDebugPrint3("TestUserDataForBypassScript entered\n")
676
677 global gUseHardwiredJsonScriptFile
678 if gUseHardwiredJsonScriptFile == None:
679 fd = datadescription.GetUserData()
680
681 if fd == None:
682 if PhactoriDbg(100):
683 myDebugPrint3("no user data, no catalyst_script_extra_file\n")
684 return
685
686 sa = fd.GetAbstractArray(0)
687
688 if sa == None:
689 if PhactoriDbg(100):
690 myDebugPrint3("no user data, no catalyst_script_extra_file (2)\n")
691 return
692
693 if(sa.GetNumberOfValues() > 8):
694 catalyst_script_extra_file = sa.GetValue(8)
695 if PhactoriDbg(100):
696 myDebugPrint3(" catalyst_script_extra_file: ->" + \
697 catalyst_script_extra_file + "<-\n")
698 else:
699 if PhactoriDbg(100):
700 myDebugPrint3(" catalyst_script_extra_file: ->NONE<- (no bypass)\n")
701 return
702
703 if catalyst_script_extra_file == "":
704 if PhactoriDbg(100):
705 myDebugPrint3("empty catalyst_script_extra_file, returning\n")
706 return;
707 else:
708 catalyst_script_extra_file = gUseHardwiredJsonScriptFile
709
710 global gUserDataBypassStrings
711 global gBypassUserDataJson
712
713 if catalyst_script_extra_file == "bccolli_controls.py":
714 #due to unique name for catalyst_script_extra_file, do python import
715 #to obtain json description of visualization
716
717 if PhactoriDbg(100):
718 myDebugPrint3("using bypass script bccolli_controls.py to specify\n" \
719 "vis instead of catalyst block\n")
720 gBypassUserData = True
721 global bccolli_controls
722 import bccolli_controls
723 gUserDataBypassStrings = [
724 bccolli_controls.catalystSierraInputInJsonFormatStr,
725 "_",
726 "simple",
727 "",
728 "",
729 "0",
730 "simple.e",
731 "",
732 catalyst_script_extra_file
733 ]
734 gBypassUserDataJson = bccolli_controls.catalystSierraInputInJsonFormat
735 else:
736 #since it's not the unique name bccolli_controls, treat it as a text file
737 #containing a json format data set. Read in this json and use it as
738 #the phactori json format visualization description
739
740 if PhactoriDbg(100):
741 myDebugPrint3("using json data file: " + catalyst_script_extra_file + \
742 "\nto specify vis instead of catalyst block\n")
743 gBypassUserData = True
744
745 useEmbeddedJsonCatalystScript = False
746 if useEmbeddedJsonCatalystScript:
747 gBypassUserDataJson = GetEmbeddedJsonCatalystScript()
748 if PhactoriDbg(100):
749 myDebugPrint3("using embedded json catalyst script:\n" + str(visDescpJson) + "\n")
750 else:
751 if PhactoriDbg(100):
752 myDebugPrint3("using json script file with broadcast:\n" \
753 "name of script file: " + catalyst_script_extra_file + "\n" \
754 "about to do broadcast\n")
755 if SmartGetLocalProcessId() == 0:
756 #process zero loads json script and broadcasts
757 gBypassUserDataJson = HandleJsonScriptLoadProcessZero(catalyst_script_extra_file)
758 else:
759 #other processes receive json script
760 ###gBypassUserDataJson = HandleJsonScriptLoadProcessZero(catalyst_script_extra_file)
761 gBypassUserDataJson = HandleJsonScriptLoadProcessNotZero()
762
763 gUserDataBypassStrings = [
764 str(gBypassUserDataJson),
765 "_",
766 "simple",
767 "",
768 "",
769 "0",
770 "simple.e",
771 "",
772 catalyst_script_extra_file
773 ]
774
775 if PhactoriDbg(100):
776 myDebugPrint3("TestUserDataForBypassScript returning\n")
777
778
779 def GetBypassUserDataFlag():
780 global gBypassUserData
781 return gBypassUserData
782
783
784 #test at creation time if this global was preset (above) to bypass user data
785 #if so, read in info by importing bccolli_controls.py
786 #this is used if we want to hardwire this phactori.py file to read from
787 #bccolli_controls.py, rather than setting from the input deck
788 if gBypassUserData:
789 global bccolli_controls
790 import bccolli_controls
791 myBypassJsonString = bccolli_controls.catalystSierraInputInJsonFormatStr
792 gBypassUserDataJson = bccolli_controls.catalystSierraInputInJsonFormat
793 else:
794 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':{}}"
795
796 gUserDataBypassStrings = [
797 myBypassJsonString,
798 "_",
799 "simple",
800 "",
801 "",
802 "0",
803 "simple.e",
804 "",
805 ""
806 ]
807
808 def SetViewMapCBypassJsonString(inViewMapCString):
809 global gUserDataBypassStrings
810 gUserDataBypassStrings[0] = inViewMapCString
811 if PhactoriDbg():
812 myDebugPrint3("bypass json view map string changed to:\n" + gUserDataBypassStrings[0] + "\n")
813
814 global gEnableTemporaryExtractBlockTest
815 global gExtractBlockAList
816 global gExtractBlockBList
817 global gExtractBlockAOperationName
818 global gExtractBlockBOperationName
819 gEnableTemporaryExtractBlockTest = True
820 gExtractBlockAList = ['block_1']
821 gExtractBlockBList = ['block_2']
822 gExtractBlockAOperationName = "ReplaceWithExtractBlockA_Test"
823 gExtractBlockBOperationName = "ReplaceWithExtractBlockB_Test"
824
825 global gEnableTemporaryMultiOpViewTest
826 global gMultiOpViewTestOp2Name
827 global gMultiOpViewTestRep2Name
828 global gMultiOpViewTestImagesetName
829 gEnableTemporaryMultiOpViewTest = True
830 gMultiOpViewTestOp2Name = "ReplaceWithExtractBlockB_Test"
831 gMultiOpViewTestRep2Name = "repB"
832 gMultiOpViewTestImagesetName = "multioptestimageset"
833
834 class PhactoriPhysicalEyeAndScreenSetup:
835 "contains physical dimensions of screen (in whatever screen units)\n and location of between-the-eyes position relative to the screen\n in screen units--(0.0, 0.0) is right at middle of screen and distance\n from the betwee-the-eyes position and the screen"
836
837 def __init__(self):
838 "inScreenWidth, inScreenHeight obvious, in whatever units (feet, meters,\n inches); inIpdInScreenUnits interpupilary distance in same units as\n screen width and height, inEyeToScreenDistance distance from the\n between-the-eye position to the screen, in the same units;\n inBetweenEyeX, inBetweenEyeY where the eye is looking straight ahead\n at the screen, with (0.0, 0.0) being the center and 0.5 * width and\n height being at the corners"
839
840 #we operates by setting eye at (0,0,0) and setting the screen corners
841 #appropriately
842 self.mLeftEyeScreenBottomLeft = None
843 self.mLeftEyeScreenBottomRight = None
844 self.mLeftEyeScreenTopRight = None
845 self.mRightEyeScreenBottomLeft = None
846 self.mRightEyeScreenBottomRight = None
847 self.mRightEyeScreenTopRight = None
848
849 def ParseSettingsFromJson(self, inJsn):
850 jsnGoodFlag = True
851 if 'screen size' not in inJsn:
852 jsnGoodFlag = False
853 if 'screen ipd' not in inJsn:
854 jsnGoodFlag = False
855 if 'eye to screen distance' not in inJsn:
856 jsnGoodFlag = False
857 if 'between eyes projected screen position' not in inJsn:
858 jsnGoodFlag = False
859 if jsnGoodFlag == False:
860 myDebugPrint3AndException("PhactoriPhysicalEyeAndScreenSetup:"
861 "ParseSettingsFromJson:\n"
862 "incoming json needs all of 'screen size' 'screen ipd'\n"
863 "'eye to screen distance' and "
864 "'between eyes projected screen position'\n")
865
866 screenSize = inJsn['screen size']
867 halfIpd = inJsn['screen ipd'] * 0.5
868 halfW = screenSize[0] * 0.5
869 halfH = screenSize[1] * 0.5
870 eyeToScreenDistance = inJsn['eye to screen distance']
871 eyePositionOnScreen = inJsn['between eyes projected screen position']
872 betweenEyeX = eyePositionOnScreen[0]
873 betweenEyeY = eyePositionOnScreen[1]
874 self.mLeftEyeScreenBottomLeft = [
875 -halfW + halfIpd - betweenEyeX,
876 -halfH - betweenEyeY,
877 -eyeToScreenDistance
878 ]
879 self.mLeftEyeScreenBottomRight = [
880 halfW + halfIpd - betweenEyeX,
881 -halfH - betweenEyeY,
882 -eyeToScreenDistance
883 ]
884 self.mLeftEyeScreenTopRight = [
885 halfW + halfIpd - betweenEyeX,
886 halfH - betweenEyeY,
887 -eyeToScreenDistance
888 ]
889 self.mRightEyeScreenBottomLeft = [
890 -halfW - halfIpd - betweenEyeX,
891 -halfH - betweenEyeY,
892 -eyeToScreenDistance
893 ]
894 self.mRightEyeScreenBottomRight = [
895 halfW - halfIpd - betweenEyeX,
896 -halfH - betweenEyeY,
897 -eyeToScreenDistance
898 ]
899 self.mRightEyeScreenTopRight = [
900 halfW - halfIpd - betweenEyeX,
901 halfH - betweenEyeY,
902 -eyeToScreenDistance
903 ]
904
905 def GetScreenBottomLeft(self, inLeftEyeFlag):
906 if inLeftEyeFlag:
907 return self.mLeftEyeScreenBottomLeft
908 else:
909 return self.mRightEyeScreenBottomLeft
910
911 def GetScreenBottomRight(self, inLeftEyeFlag):
912 if inLeftEyeFlag:
913 return self.mLeftEyeScreenBottomRight
914 else:
915 return self.mRightEyeScreenBottomRight
916
917 def GetScreenTopRight(self, inLeftEyeFlag):
918 if inLeftEyeFlag:
919 return self.mLeftEyeScreenTopRight
920 else:
921 return self.mRightEyeScreenTopRight
922
923 def GetEyePosition(self, inLeftEyeFlag):
924 return [0.0, 0.0, 0.0]
925
926 global g1000x1000in1920x1080desktop30inch
927 #multiply factor to get, e.g. 800x800
928 global gPixFactor
929 gPixFactor = 0.8
930 #units are centimeters
931 #myXFactor = 10.0
932 myXFactor = 1.0
933 g1000x1000in1920x1080desktop30inch = {
934 'screen size' : [33.866*myXFactor*gPixFactor, 33.866*myXFactor*gPixFactor],
935 'screen ipd' : 6.2*myXFactor,
936 'eye to screen distance': 55.88*myXFactor,
937 'between eyes projected screen position': [0.0, 0.0],
938 'ipd in model units': 6.2,
939 'virtual self size multiplier': 0.25
940 #'virtual self size multiplier': 1.0
941 }
942
943 global g1008x1792in1920x1200desktop30inch
944 screendiag1 = 30.0
945 screenaspectratio1 = 9.0/16.0
946 screendiagangle1 = math.atan(screenaspectratio1)
947 screenheight1 = screendiag1 * math.sin(screendiagangle1)
948 screenwidth1 = screendiag1 * math.cos(screendiagangle1)
949 screenxpixels1 = 1920.0
950 screenypixels1 = 1200.0
951 imagexpixels1 = 1792.0
952 imageypixels1 = 1008.0
953 imagewidth1 = (imagexpixels1 / screenxpixels1) * screenwidth1
954 imageheight1 = (imageypixels1 / screenypixels1) * screenheight1
955 #print "g1008x1792in1920x1200desktop30inch calculcations:"
956 #print "screendiag1: " + str(screendiag1)
957 #print "screenwidth1: " + str(screenwidth1)
958 #print "screenheight1: " + str(screenheight1)
959 #print "imagewidth1: " + str(imagewidth1)
960 #print "imageheight1: " + str(imageheight1)
961
962 g1008x1792in1920x1200desktop30inch = {
963 'screen size' : [imagewidth1, imageheight1],
964 'screen ipd' : 6.2,
965 'eye to screen distance': 55.88,
966 'between eyes projected screen position': [0.0, 0.0],
967 'ipd in model units': 6.2,
968 #'virtual self size multiplier': 1.0,
969 'virtual self size multiplier': 0.001,
970 'auto size 1': True,
971 'auto size 1 distance ratio': 1.0,
972 'auto size 1 view angle delta in degrees': 0.0
973 }
974
975
976 global gWiff9x16FromAudienceBig
977 #units are in feet
978 gTestFactorX = 1.0
979 gWiff9x16FromAudienceBig = {
980 'screen size' : [15.33333*gTestFactorX, 8.75*gTestFactorX],
981 'screen ipd' : 0.2034121*gTestFactorX,
982 #screen to chair back is 22.41666667 feet, knock off .4 for head width
983 'eye to screen distance': 22.0*gTestFactorX,
984 #bottom of screen 3 feet above floor
985 #eyes in front row 3.75 feet above floor
986 #bottom of screen at -4.375 feet--below center
987 'between eyes projected screen position': [0.0*gTestFactorX, (3.75 - 3.0 - 4.375)*gTestFactorX],
988 #'ipd in model units': 0.2034121*gTestFactorX,
989 'ipd in model units': 0.0,
990 #'virtual self size multiplier': 0.25
991 #'virtual self size multiplier': 0.001
992 'virtual self size multiplier': 1.0
993 }
994
995 global gWiff9x16FromAudienceSmall
996 #units are in feet
997 gWiff9x16FromAudienceSmall = {
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': 1.0
1004 }
1005
1006 global gWiff9x16FromAudienceAutoSizeA
1007 #units are in feet
1008 gWiff9x16FromAudienceAutoSizeA = {
1009 'screen size' : [15.33333, 8.75],
1010 'screen ipd' : 0.2034121,
1011 'eye to screen distance': 22.0,
1012 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1013 'ipd in model units': 0.2034121,
1014 #'virtual self size multiplier': 0.001,
1015 'virtual self size multiplier': 0.25,
1016 #'virtual self size multiplier': 2.0,
1017 #'auto size 1 distance ratio': 1.0,
1018 #'auto size 1 distance ratio': 0.75,
1019 'auto size 1 distance ratio': 0.7,
1020 #'auto size 1 distance ratio': 0.001,
1021 #'auto size 1 distance ratio': 0.25,
1022 'auto size 1': True,
1023 'auto size 1 lock nth eye position': 1,
1024 'auto size 1 view angle delta in degrees': 11.0
1025 #'auto size 1 view angle delta in degrees': 9.0
1026 #'auto size 1 view angle delta in degrees': 0.0
1027 }
1028 global gWiff9x16FromAudienceAutoSizeA2
1029 #units are in feet
1030 gWiff9x16FromAudienceAutoSizeA2 = {
1031 'screen size' : [15.33333, 8.75],
1032 'screen ipd' : 0.2034121,
1033 'eye to screen distance': 22.0,
1034 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1035 'ipd in model units': 0.2034121,
1036 #'virtual self size multiplier': 0.25,
1037 #'virtual self size multiplier': 0.5,
1038 'virtual self size multiplier': 0.4,
1039 #'auto size 1 distance ratio': 0.7,
1040 'auto size 1 distance ratio': 0.85,
1041 #'auto size 1 distance ratio': 0.35,
1042 'auto size 1': True,
1043 'auto size 1 lock nth eye position': 1,
1044 'auto size 1 view angle delta in degrees': 11.0
1045 #'auto size 1 view angle delta in degrees': 9.0
1046 #'auto size 1 view angle delta in degrees': 0.0
1047 }
1048
1049
1050 global gWiff9x16FromAudienceAutoSizeB
1051 #units are in feet
1052 gWiff9x16FromAudienceAutoSizeB = {
1053 'screen size' : [15.33333, 8.75],
1054 'screen ipd' : 0.2034121,
1055 'eye to screen distance': 22.0,
1056 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1057 'ipd in model units': 0.2034121,
1058 #'virtual self size multiplier': 1.0,
1059 #'auto size 1 distance ratio': 1.0,
1060 #'virtual self size multiplier': 0.25,
1061 #'virtual self size multiplier': 0.125,
1062 #'virtual self size multiplier': 1.0,
1063 #'virtual self size multiplier': 1.5,
1064 #'virtual self size multiplier': 2.5,
1065 'virtual self size multiplier': 1.75,
1066 #'auto size 1 distance ratio': 1.0,
1067 #'auto size 1 distance ratio': 0.5,
1068 'auto size 1 distance ratio': 0.125,
1069 'auto size 1 lock nth eye position': 1,
1070 'auto size 1': True,
1071 #'auto size 1 view angle delta in degrees': 9.0
1072 #'auto size 1 view angle delta in degrees': 9.0
1073 'auto size 1 view angle delta in degrees': 9.0
1074 #'auto size 1 view angle delta in degrees': 11.0
1075 }
1076
1077 #this one has locked eye position
1078 global gWiff9x16FromAudienceAutoSizeC
1079 #units are in feet
1080 gWiff9x16FromAudienceAutoSizeC = {
1081 'screen size' : [15.33333, 8.75],
1082 'screen ipd' : 0.2034121,
1083 'eye to screen distance': 22.0,
1084 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1085 'ipd in model units': 0.2034121,
1086 #'virtual self size multiplier': 1.0,
1087 #'auto size 1 distance ratio': 0.6,
1088 'virtual self size multiplier': 2.0,
1089 #'auto size 1 distance ratio': 0.25,
1090 #'auto size 1 distance ratio': 0.125,
1091 'auto size 1 distance ratio': 0.1,
1092 'auto size 1': True,
1093 'auto size 1 lock nth eye position': 5,
1094 'auto size 1 view angle delta in degrees': 9.0
1095 }
1096
1097 global gWiff9x16FromAudienceAutoSizeD
1098 #units are in feet
1099 gWiff9x16FromAudienceAutoSizeD = {
1100 'screen size' : [15.33333, 8.75],
1101 'screen ipd' : 0.2034121,
1102 'eye to screen distance': 22.0,
1103 'between eyes projected screen position': [0.0, (3.75 - 3.0 - 4.375)],
1104 'ipd in model units': 0.2034121,
1105 #'virtual self size multiplier': 1.0,
1106 #'auto size 1 distance ratio': 0.9,
1107 'virtual self size multiplier': 4.0,
1108 'auto size 1 distance ratio': 0.45,
1109 'auto size 1': True,
1110 #'auto size 1 distance ratio': 1.0,
1111 'auto size 1 lock nth eye position': 5,
1112 'auto size 1 view angle delta in degrees': 9.0
1113 }
1114
1115 global gWiff9x16StandingCloseAutoSizeE
1116 gWiff9x16StandingCloseAutoSizeE = {
1117 'screen size' : [15.33333, 8.75],
1118 'screen ipd' : 0.2034121,
1119 'eye to screen distance': 5.0,
1120 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1121 'ipd in model units': 0.2034121,
1122 #'virtual self size multiplier': 1.0,
1123 'virtual self size multiplier': 0.4,
1124 #'auto size 1 distance ratio': 1.0,
1125 'auto size 1 distance ratio': 0.4,
1126 'auto size 1': True,
1127 #'auto size 1 distance ratio': 1.0,
1128 #'auto size 1 lock nth eye position': 5,
1129 #'auto size 1 view angle delta in degrees': 0.0
1130 #'auto size 1 view angle delta in degrees': 10.0
1131 'auto size 1 view angle delta in degrees': 5.0
1132 }
1133
1134 global gWiff9x16StandingCloseAutoSizeF
1135 gWiff9x16StandingCloseAutoSizeF = {
1136 'screen size' : [15.33333, 8.75],
1137 'screen ipd' : 0.2034121,
1138 'eye to screen distance': 5.0,
1139 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1140 'ipd in model units': 0.2034121,
1141 #'virtual self size multiplier': 1.0,
1142 'virtual self size multiplier': 0.8,
1143 #'auto size 1 distance ratio': 1.0,
1144 'auto size 1 distance ratio': 0.25,
1145 'auto size 1': True,
1146 #'auto size 1 distance ratio': 1.0,
1147 #'auto size 1 lock nth eye position': 5,
1148 #'auto size 1 view angle delta in degrees': 0.0
1149 #'auto size 1 view angle delta in degrees': 10.0
1150 'auto size 1 view angle delta in degrees': 5.0
1151 }
1152
1153 global gWiff9x16feetCloseJson
1154 global gWiff9x16StandingCloseAutoSizeG
1155 gWiff9x16StandingCloseAutoSizeG = {
1156 'screen size' : [15.33333, 8.75],
1157 'screen ipd' : 0.2034121,
1158 'eye to screen distance': 5.0,
1159 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1160 'ipd in model units': 0.2034121,
1161 'virtual self size multiplier': 0.6,
1162 'auto size 1 distance ratio': 0.4,
1163 'auto size 1': True,
1164 #'auto size 1 distance ratio': 1.0,
1165 #'auto size 1 lock nth eye position': 5,
1166 'auto size 1 view angle delta in degrees': 0.0
1167 }
1168
1169 global gWiff9x16feetCloseJson
1170 #units are in feet
1171 gWiff9x16feetCloseJson = {
1172 'screen size' : [15.33333, 8.75],
1173 'screen ipd' : 0.2034121,
1174 'eye to screen distance': 5.0,
1175 #bottom of screen 3 feet above floor
1176 #eyes standing in front row 5.25 feet above floor
1177 #bottom of screen at -4.375 feet--below center
1178 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1179 'ipd in model units': 0.2034121,
1180 'virtual self size multiplier': 1.0
1181 }
1182
1183 global gWiff9x16feetCloseBigJson
1184 #units are in feet
1185 gWiff9x16feetCloseBigJson = {
1186 'screen size' : [15.33333, 8.75],
1187 'screen ipd' : 0.2034121,
1188 'eye to screen distance': 5.0,
1189 'between eyes projected screen position': [0.0, (5.25 - 3.0 - 4.375)],
1190 'ipd in model units': 0.2034121,
1191 'virtual self size multiplier': 0.1
1192 }
1193
1194 global gModelCoordinatesIpd
1195 global gEnableTemporaryOffAxisProjectionTest
1196
1197 gEnableTemporaryOffAxisProjectionTest = True
1198
1199 #gOaptCameraNameList = [
1200 # 'OaptDesktop1',
1201 # 'OaptWiffBigInFrontOfScreen',
1202 # 'OaptWiffBigAtScreen',
1203 # 'OaptWiffBigBehindScreen',
1204 # 'OaptWiffBigWayBehindScreen',
1205 # 'OaptWiffSmallAtScreen',
1206 # 'OaptWiffSmallInFrontOfScreen',
1207 # 'OaptWiffSmallWayInFrontOfScreen',
1208 # 'OaptWiffStandingClose',
1209 # 'OaptWiffStandingCloseBig',
1210 # 'OaptWiffStandingCloseBig2',
1211 # 'OaptWiffAutoSize1AtScreen',
1212 # 'OaptWiffAutoSize2AtScreen',
1213 # 'OaptWiffAutoSize3AtScreen',
1214 # 'OaptWiffAutoSize4AtScreen',
1215 # 'OaptWiffAutoSize5AtScreen',
1216 # 'OaptWiffAutoSize6AtScreen']
1217
1218 global gOaptPhysicalSettingsForCamera
1219 gOaptPhysicalSettingsForCamera = {
1220 'OaptDesktop1': g1008x1792in1920x1200desktop30inch,
1221 'OaptWiffBigInFrontOfScreen': gWiff9x16FromAudienceBig,
1222 'OaptWiffBigAtScreen': gWiff9x16FromAudienceBig,
1223 'OaptWiffBigBehindScreen': gWiff9x16FromAudienceBig,
1224 'OaptWiffBigWayBehindScreen': gWiff9x16FromAudienceBig,
1225 'OaptWiffSmallAtScreen': gWiff9x16FromAudienceSmall,
1226 'OaptWiffSmallInFrontOfScreen': gWiff9x16FromAudienceSmall,
1227 'OaptWiffSmallWayInFrontOfScreen': gWiff9x16FromAudienceSmall,
1228 'OaptWiffStandingClose': gWiff9x16StandingCloseAutoSizeE,
1229 'OaptWiffStandingCloseBig': gWiff9x16StandingCloseAutoSizeF,
1230 'OaptWiffStandingCloseBig2': gWiff9x16StandingCloseAutoSizeG,
1231 'OaptWiffAutoSize1AtScreen': gWiff9x16FromAudienceAutoSizeA,
1232 #'OaptWiffAutoSize1AtScreen': gWiff9x16FromAudienceBig,
1233 'OaptWiffAutoSize2AtScreen': gWiff9x16FromAudienceAutoSizeB,
1234 'OaptWiffAutoSize3AtScreen': gWiff9x16FromAudienceAutoSizeA2,
1235 'OaptWiffAutoSize4AtScreen': gWiff9x16StandingCloseAutoSizeE,
1236 'OaptWiffAutoSize5AtScreen': gWiff9x16StandingCloseAutoSizeF,
1237 'OaptWiffAutoSize6AtScreen': gWiff9x16FromAudienceAutoSizeB,
1238 }
1239
1240 #list of cameras from gOaptPhysicalSettingsForCamera
1241 global gOaptCameraNameList
1242 gOaptCameraNameList = []
1243 for key, value in gOaptPhysicalSettingsForCamera.items():
1244 gOaptCameraNameList.append(key)
1245
1246
1247 notchScaleFactor = 250.0
1248 #swap out operations from input deck for testing operations which aren't
1249 #available through the input deck syntax yet
1250
1251 #rotation about z axis
1252 global gSubstituteTestOperation1Json
1253 gSubstituteTestOperation1Json = {
1254
1255 'type': 'transform',
1256 'rotate': [0.0, 0.0, -45.0]
1257
1258 #'type': 'calculator',
1259 #'function': 'damage*damage',
1260
1261 #'scale': [notchScaleFactor, notchScaleFactor, notchScaleFactor]
1262 #'scale': [100.0, 100.0, 100.0]
1263 #'scale': [10.0, 10.0, 10.0]
1264 #'scale': [1.0, 1.0, 1.0]
1265 #'scale': [5.0, 5.0, 5.0]
1266 }
1267
1268 #z displacement isolation
1269 #rotation about x axis
1270 global gSubstituteTestOperation2Json
1271 gSubstituteTestOperation2Json = {
1272 'type': 'transform',
1273 'rotate': [-90.0, 0.0, 0.0]
1274 }
1275
1276 #z displacement isolation
1277 #global gSubstituteTestOperation2Json
1278 #gSubstituteTestOperation2Json = {
1279 # 'type': 'calculator',
1280 # 'function': '0.0*iHat + 0.0*jHat + displ__Z*kHat',
1281 # 'result array name': 'displ_',
1282 # #'result array name': 'mydisp_',
1283 #}
1284
1285 global gSubstituteTestOperation3Json
1286 gSubstituteTestOperation3Json = {
1287 'type': 'warpbyvector',
1288 'variable type': 'node',
1289 'variablename': 'displ_',
1290 #'vector name': 'mydisp_',
1291 #'scale factor': 20.0 * 10000.0,
1292 'scale': 10.0 * notchScaleFactor,
1293 }
1294
1295 #x/y displacement isolation
1296 global gSubstituteTestOperation4Json
1297 gSubstituteTestOperation4Json = {
1298 'type': 'calculator',
1299 'function': 'displ__X*iHat + displ__Y*jHat + 0.0*kHat',
1300 'result array name': 'displ_',
1301 #'result array name': 'mydisp_',
1302 }
1303
1304 global gSubstituteTestOperation5Json
1305 gSubstituteTestOperation5Json = {
1306 'type': 'warpbyvector',
1307 'variable type': 'node',
1308 'variablename': 'displ_',
1309 #'vector name': 'mydisp_',
1310 #'scale factor': 20.0 * 10000.0,
1311 'scale': 10.0 * notchScaleFactor,
1312 }
1313
1314 #all displacement exaggeration
1315 global gSubstituteTestOperation6Json
1316 gSubstituteTestOperation6Json = {
1317 'type': 'warpbyvector',
1318 'variable type': 'node',
1319 'vector name': 'displ_',
1320 #'vector name': 'mydisp_',
1321 #'scale factor': 20.0 * 10000.0,
1322 #'scale factor': 10.0 * 1000.0,
1323 'scale factor': 10.0 * notchScaleFactor,
1324 }
1325
1326 #reflect operation
1327 global gSubstituteTestOperation7Json
1328 gSubstituteTestOperation7Json = {
1329 'type': 'reflect',
1330 'plane': 'Z Min',
1331 'center': 0.0,
1332 }
1333
1334 #add pointset operation
1335 global gSubstituteTestOperation8Json
1336 gSubstituteTestOperation8Json = {
1337 'type': 'add unstructured grid',
1338 'filename': 'physicalpointsandoutline.vtu',
1339 }
1340
1341 #add group operation
1342 global gSubstituteTestOperation9Json
1343 gSubstituteTestOperation9Json = {
1344 'type': 'group',
1345 'operation group list': ["ztestslice1", "ztestslice2"]
1346 }
1347
1348
1349 global gEnableSubstituteOperationTesting
1350 gEnableSubstituteOperationTesting = True
1351 global gSubstituteOperationTestingMap
1352 gSubstituteOperationTestingMap = {
1353 "SubstituteTestOperation1": gSubstituteTestOperation1Json,
1354 "SubstituteTestOperation2": gSubstituteTestOperation2Json,
1355 "SubstituteTestOperation3": gSubstituteTestOperation3Json,
1356 "SubstituteTestOperation4": gSubstituteTestOperation4Json,
1357 "SubstituteTestOperation5": gSubstituteTestOperation5Json,
1358 "SubstituteTestOperation6": gSubstituteTestOperation6Json,
1359 "SubstituteTestOperation7": gSubstituteTestOperation7Json,
1360 "SubstituteTestOperation8": gSubstituteTestOperation8Json,
1361 "SubstituteTestOperation9": gSubstituteTestOperation9Json,
1362 }
1363
1364 global gSubstituteOperationTestingList
1365 gSubstituteOperationTestingList = []
1366 for key, value in gSubstituteOperationTestingMap.items():
1367 gSubstituteOperationTestingList.append(key)
1368
1369
1370 #swap out imagesets from input deck for testing operations which aren't
1371 #available through the input deck syntax yet
1372
1373 global gSubstituteTestImageset1Json
1374 gSubstituteTestImageset1Json = {
1375 'color by vector component': 'mydisp_Z'
1376 }
1377 global gEnableSubstituteImagesetTesting
1378 gEnableSubstituteImagesetTesting = True
1379 global gSubstituteImagesetTestingMap
1380 gSubstituteImagesetTestingMap = {
1381 "SubstituteTestImageset1": gSubstituteTestImageset1Json,
1382 #"SubstituteTestImageset2": gSubstituteTestImageset2Json,
1383 #"SubstituteTestImageset3": gSubstituteTestImageset3Json,
1384 }
1385
1386 global gSubstituteImagesetTestingList
1387 gSubstituteImagesetTestingList = []
1388 for key, value in gSubstituteImagesetTestingMap.items():
1389 gSubstituteImagesetTestingList.append(key)
1390 #-----
1391
1392 global gDefaultTimeFormatString
1393 #gDefaultTimeFormatString = "Time: %.6e"
1394 #gDefaultTimeFormatString = "Time: %f"
1395 #gDefaultTimeFormatString = "Time: %.10e"
1396 gDefaultTimeFormatString = "Time: {time:.6f}"
1397
1398 global gDefaultImageSizeX
1399 gDefaultImageSizeX = 1920
1400
1401 global gDefaultImageSizeY
1402 gDefaultImageSizeY = 1080
1403
1404 global gPixelBorderRatioXY
1405 gPixelBorderRatioXY = [0.05,0.05]
1406
1407 class PhactoriAxisSettings:
1408 def __init__(self, inWhichAxis):
1409 #0-x axis, 1-yaxis, 2-zaxis
1410 self.WhichAxis = inWhichAxis
1411 self.TitleColor = [1.0, 1.0, 1.0]
1412 self.LabelColor = [1.0, 1.0, 1.0]
1413 self.TitleFontFamily = "Arial"
1414 self.TitleFontSize = 14
1415 self.LabelFontFamily = "Arial"
1416 self.LabelFontSize = 12
1417
1418 def SetInfo1(self, inTitleColor, inLabelColor,
1419 inTitleFontFamily, inTitleFontSize,
1420 inLabelFontFamily, inLabelFontSize):
1421 self.TitleColor[0] = inTitleColor[0]
1422 self.TitleColor[1] = inTitleColor[1]
1423 self.TitleColor[2] = inTitleColor[2]
1424 self.LabelColor[0] = inLabelColor[0]
1425 self.LabelColor[1] = inLabelColor[1]
1426 self.LabelColor[2] = inLabelColor[2]
1427 if inTitleFontFamily != None:
1428 self.TitleFontFamily = inTitleFontFamily
1429 if inTitleFontSize != None:
1430 self.TitleFontSize = inTitleFontSize
1431 if inLabelFontFamily != None:
1432 self.LabelFontFamily = inLabelFontFamily
1433 if inLabelFontSize != None:
1434 self.LabelFontSize = inLabelFontSize
1435
1436 def Apply(self, ioAxesGrid):
1437 if self.WhichAxis == 0:
1438 ioAxesGrid.XTitleColor[0] = self.TitleColor[0]
1439 ioAxesGrid.XTitleColor[1] = self.TitleColor[1]
1440 ioAxesGrid.XTitleColor[2] = self.TitleColor[2]
1441 ioAxesGrid.XLabelColor[0] = self.LabelColor[0]
1442 ioAxesGrid.XLabelColor[1] = self.LabelColor[1]
1443 ioAxesGrid.XLabelColor[2] = self.LabelColor[2]
1444 ioAxesGrid.XTitleFontFamily = self.TitleFontFamily
1445 ioAxesGrid.XTitleFontSize = self.TitleFontSize
1446 ioAxesGrid.XLabelFontFamily = self.LabelFontFamily
1447 ioAxesGrid.XLabelFontSize = self.LabelFontSize
1448 elif self.WhichAxis == 1:
1449 ioAxesGrid.YTitleColor[0] = self.TitleColor[0]
1450 ioAxesGrid.YTitleColor[1] = self.TitleColor[1]
1451 ioAxesGrid.YTitleColor[2] = self.TitleColor[2]
1452 ioAxesGrid.YLabelColor[0] = self.LabelColor[0]
1453 ioAxesGrid.YLabelColor[1] = self.LabelColor[1]
1454 ioAxesGrid.YLabelColor[2] = self.LabelColor[2]
1455 ioAxesGrid.YTitleFontFamily = self.TitleFontFamily
1456 ioAxesGrid.YTitleFontSize = self.TitleFontSize
1457 ioAxesGrid.YLabelFontFamily = self.LabelFontFamily
1458 ioAxesGrid.YLabelFontSize = self.LabelFontSize
1459 else:
1460 ioAxesGrid.ZTitleColor[0] = self.TitleColor[0]
1461 ioAxesGrid.ZTitleColor[1] = self.TitleColor[1]
1462 ioAxesGrid.ZTitleColor[2] = self.TitleColor[2]
1463 ioAxesGrid.ZLabelColor[0] = self.LabelColor[0]
1464 ioAxesGrid.ZLabelColor[1] = self.LabelColor[1]
1465 ioAxesGrid.ZLabelColor[2] = self.LabelColor[2]
1466 ioAxesGrid.ZTitleFontFamily = self.TitleFontFamily
1467 ioAxesGrid.ZTitleFontSize = self.TitleFontSize
1468 ioAxesGrid.ZLabelFontFamily = self.LabelFontFamily
1469 ioAxesGrid.ZLabelFontSize = self.LabelFontSize
1470
1471 class PhactoriColorSettings:
1472 def __init__(self, inUsePlotDefaultColors = False):
1473 self.mXAxisSettings = PhactoriAxisSettings(0)
1474 self.mYAxisSettings = PhactoriAxisSettings(1)
1475 self.mZAxisSettings = PhactoriAxisSettings(2)
1476 if inUsePlotDefaultColors:
1477 self.mBackground = [1.0, 1.0, 1.0]
1478 self.mEdgeColor = [0.0, 0.0, 0.5]
1479
1480 #starting in paraview 5.0.1 this is the color
1481 #(mDiffuseColor) that affects the plot line
1482 #color
1483 #self.mDiffuseColor = [0.2, 0.2, 0.2]
1484 self.mDiffuseColor = [0.0, 0.0, 0.5]
1485
1486 self.mBackfaceDiffuseColor = [0.2, 0.2, 0.2]
1487 self.mSelectionColor = [0.2, 0.2, 0.2]
1488 self.mAmbientColor = [1.0, 1.0, 1.0]
1489 self.mTextColor = [0.2, 0.2, 0.2]
1490 self.mTimeAnnotationColor = [0.2, 0.2, 0.2]
1491 self.mAxesGridColor = [0.2, 0.2, 0.2]
1492 #self.mGridAxesInfoHasBeenInitialized = True
1493 self.mXAxisSettings.SetInfo1(
1494 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1495 self.mYAxisSettings.SetInfo1(
1496 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1497 self.mZAxisSettings.SetInfo1(
1498 [0.2, 0.2, 0.2], [0.2, 0.2, 0.2], "Arial", 14, "Arial", 12)
1499 self.mAxesGridShowTicks = 1
1500 self.mAxesSettingsInititlized = True
1501 else:
1502 self.mBackground = [0.31999694819562063,
1503 0.3400015259021897, 0.4299992370489052]
1504 self.mEdgeColor = [0.0, 0.0, 0.5000076295109483]
1505 self.mDiffuseColor = [1.0, 1.0, 1.0]
1506 self.mBackfaceDiffuseColor = [1.0, 1.0, 1.0]
1507 self.mAmbientColor = [1.0, 1.0, 1.0]
1508 self.mSelectionColor = [1.0, 0.0, 1.0]
1509 self.mAxesGridColor = [1.0, 1.0, 1.0]
1510 self.mTextColor = [1.0, 1.0, 1.0]
1511 self.mTimeAnnotationColor = [1.0, 1.0, 1.0]
1512 #self.mGridAxesInfoHasBeenInitialized = False
1513
1514 #weird test colors
1515 #self.mBackground = [1.0, 1.0, 1.0]
1516 #self.mEdgeColor = [1.0, 1.0, 0.0]
1517 #self.mDiffuseColor = [0.0, 1.0, 1.0]
1518 #self.mBackfaceDiffuseColor = [0.0, 1.0, 1.0]
1519 #self.mAmbientColor = [1.0, 1.0, 1.0]
1520 #self.mSelectionColor = [1.0, 0.0, 1.0]
1521 #self.mTextColor = [0.0, 1.0, 0.0]
1522
1523 def SetParaviewRvRepColors(self, inParaviewRenderView,
1524 inParaviewRep):
1525 "given a paraview Representation instance, set the colors in the\n paraview representation instance from this color settings\n instance"
1526 inParaviewRep.EdgeColor = self.mEdgeColor
1527 inParaviewRep.DiffuseColor = self.mDiffuseColor
1528 inParaviewRep.BackfaceDiffuseColor = self.mBackfaceDiffuseColor
1529 inParaviewRep.AmbientColor = self.mAmbientColor
1530 inParaviewRep.SelectionColor = self.mSelectionColor
1531 inParaviewRenderView.Background = self.mBackground
1532 inParaviewRenderView.OrientationAxesLabelColor = \
1533 self.mTextColor
1534 if inParaviewRenderView.AxesGrid == None:
1535 PvSetupProperty(inParaviewRenderView.GetProperty("AxesGrid"))
1536 if inParaviewRenderView.AxesGrid == None:
1537 myDebugPrint3AndException("SetParaviewRvRepColors:\n"
1538 "could not get/create AxesGrid property\n")
1539 self.mXAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1540 self.mYAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1541 self.mZAxisSettings.Apply(inParaviewRenderView.AxesGrid)
1542 inParaviewRenderView.AxesGrid.GridColor = self.mAxesGridColor
1543
1544
1545 def ParsePlotColorSettingsFromJson(self, inJsn):
1546 "given a json structure, try to grab the color settings from it\n using plot keys rather than 3d image keys"
1547 textColor = self.mXAxisSettings.TitleColor
1548 axesColor = self.mAxesGridColor
1549 dataColor = self.mEdgeColor
1550 surfaceColor = self.mDiffuseColor
1551 backfaceSurfaceColor = self.mBackfaceDiffuseColor
1552 if 'text color' in inJsn:
1553 textColor = inJsn['text color']
1554 if 'axes color' in inJsn:
1555 axesColor = inJsn['axes color']
1556 if 'point color' in inJsn:
1557 dataColor = inJsn['point color']
1558 if 'line color' in inJsn:
1559 dataColor = inJsn['line color']
1560 if 'surface color' in inJsn:
1561 surfaceColor = inJsn['surface color']
1562 backfaceSurfaceColor = surfaceColor
1563 if 'backface surface color' in inJsn:
1564 backfaceSurfaceColor = inJsn['backface surface color']
1565 self.mEdgeColor = dataColor
1566 self.mDiffuseColor = surfaceColor
1567 self.mBackfaceDiffuseColor = backfaceSurfaceColor
1568 self.mAxesGridColor = axesColor
1569
1570 self.mOrientationAxesLabelColor = textColor
1571 self.mTextColor = textColor
1572 self.mXAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1573 self.mYAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1574 self.mZAxisSettings.SetInfo1(textColor, textColor, None, None, None, None)
1575
1576 self.mBackground = getParameterFromBlock(inJsn,
1577 'background color', self.mBackground)
1578 self.mTimeAnnotationColor = textColor
1579
1580 def ParseColorSettingsFromJson(self, inJsn):
1581 "given a json structure, try to grab the color settings from it"
1582 self.mDiffuseColor = getParameterFromBlock(inJsn,
1583 'surface color', self.mDiffuseColor)
1584 #if 'back surface color' is not set, use surface color
1585 self.mBackfaceDiffuseColor = getParameterFromBlock(inJsn,
1586 'back surface color', self.mDiffuseColor)
1587 self.mAmbientColor = getParameterFromBlock(inJsn,
1588 'ambient color', self.mAmbientColor)
1589 self.mSelectionColor = getParameterFromBlock(inJsn,
1590 'selection color', self.mSelectionColor)
1591 self.mTextColor = getParameterFromBlock(inJsn,
1592 'text color', self.mTextColor)
1593
1594 #for now, time annotation color will be text color
1595 self.mTimeAnnotationColor = self.mTextColor
1596
1597 self.mBackground = getParameterFromBlock(inJsn,
1598 'background color', self.mBackground)
1599 self.mEdgeColor = getParameterFromBlock(inJsn,
1600 'edge color', self.mEdgeColor)
1601
1602 self.mXAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1603 None, None, None, None)
1604 self.mYAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1605 None, None, None, None)
1606 self.mZAxisSettings.SetInfo1(self.mTextColor, self.mTextColor,
1607 None, None, None, None)
1608
1609 #if 'axes color' is not set, use text color
1610 self.mAxesGrid = getParameterFromBlock(inJsn,
1611 'axes color', self.mTextColor)
1612
1613 def getParameterFromBlock(inBlock, inKey, inDefault):
1614 if inKey in inBlock:
1615 return inBlock[inKey]
1616 else:
1617 return inDefault
1618
1619
1620 global gDefaultNumCounterDigits
1621 gDefaultNumCounterDigits = 4
1622 #gDefaultNumCounterDigits = 0
1623
1624 #global localCpViews
1625 #global localCpWriters
1626 #localCpViews = None
1627 #localCpWriters = None
1628
1629 global localCoProcessorReference
1630 localCoProcessorReference = None
1631
1632 global gMaxDebugPrintOutputLines
1633 global gDebugPrintOutputLineCount
1634 #gMaxDebugPrintOutputLines = 10000000
1635 gMaxDebugPrintOutputLines = 100
1636 gDebugPrintOutputLineCount = 0
1637
1638 #hacky debug printing to file mechanism
1639 def myDebugPrint(outmsg):
1640 if PhactoriDbg():
1641 myDebugPrint3(outmsg)
1642
1643 def myDebugPrint2(outmsg):
1644 if PhactoriDbg():
1645 myDebugPrint3(outmsg)
1646 #global gMaxDebugPrintOutputLines
1647 #global gDebugPrintOutputLineCount
1648 #if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1649 # return
1650 #gDebugPrintOutputLineCount += 1
1651 ##ff = open('/space/jamauld/debug_out_dir/phactori_debug.txt', 'a+')
1652 ##fname = 'proc_' + str(SmartGetLocalProcessId()) + '_debug.txt'
1653 ##ff = open(fname, 'a+')
1654 ##ff.write(outmsg)
1655 ##ff.close()
1656 #print outmsg
1657 #if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1658 # print "gMaxDebugPrintOutputLines hit\n"
1659 #x = 1
1660
1661 global gMdp3RestrictToProcessListFlag
1662 gMdp3RestrictToProcessListFlag = True
1663 #gMdp3RestrictToProcessListFlag = False
1664 global gMdp3ProcessIdList
1665 gMdp3ProcessIdList = [0]
1666 global gMdp3UseStandardOutFlag
1667 #gMdp3UseStandardOutFlag = True
1668 gMdp3UseStandardOutFlag = False
1669 global gMdp3UseFileOutFlag
1670 #gMdp3UseFileOutFlag = False
1671 gMdp3UseFileOutFlag = True
1672 global gMdp3PriorityRestriction
1673 #gMdp3PriorityRestriction = 150
1674 #gMdp3PriorityRestriction = 50
1675 gMdp3PriorityRestriction = 500
1676
1677 #priority nominally
1678 #100-very verbose info
1679 #200-verbose info
1680 #300-info
1681 #400-debug
1682 #500-warn
1683 #600-error
1684 #1000-error, and generate exception
1685 def PhactoriDbg2(inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1686 return True
1687
1688 def PhactoriDbg(inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1689 "this is a test as to whether or not debug output should be written.\n The idea is that you do this test before printing debug output so that\n complicated strings do not need to be unnecessarily created and destroyed\n when not doing debug output"
1690 global gMdp3PriorityRestriction
1691 if inPriority < gMdp3PriorityRestriction:
1692 return False
1693
1694 global gMaxDebugPrintOutputLines
1695 global gDebugPrintOutputLineCount
1696 if gDebugPrintOutputLineCount > gMaxDebugPrintOutputLines:
1697 return False
1698
1699 if inOneProcessFlag:
1700 if inOneProcessId != SmartGetLocalProcessId():
1701 return False
1702 #for parallel compatibility, we do everything on all processes _except_
1703 #do the output--so if we test for debugging then do something that requires
1704 #mpi communication, we go ahead and do it even if this process will have
1705 #no oputput
1706 #else:
1707 # global gMdp3RestrictToProcessListFlag
1708 # if gMdp3RestrictToProcessListFlag:
1709 # global gMdp3ProcessIdList
1710 # if SmartGetLocalProcessId() not in gMdp3ProcessIdList:
1711 # return False
1712
1713 return True
1714
1715 def PrintOnProcessZero(strToPrint):
1716 "prints out string if we are on process zero; typically for warnings"
1717 if SmartGetLocalProcessId() == 0:
1718 print(strToPrint)
1719
1720 def myDebugPrint3(inMsg, inPriority = 450, inOneProcessFlag = False, inOneProcessId = 0):
1721 if PhactoriDbg(inPriority, inOneProcessFlag, inOneProcessId) == False:
1722 return
1723
1724 global gMdp3RestrictToProcessListFlag
1725 if gMdp3RestrictToProcessListFlag:
1726 if SmartGetLocalProcessId() not in gMdp3ProcessIdList:
1727 #if we are only outputting some processes and this isn't one of those
1728 #we don't do any output--but we still deal with exception
1729 if inPriority >= 10000:
1730 raise Exception(inMsg)
1731 return
1732
1733 global gMaxDebugPrintOutputLines
1734 global gDebugPrintOutputLineCount
1735
1736 global gMdp3UseFileOutFlag
1737 if gMdp3UseFileOutFlag:
1738 fname = 'phdb_proc_' + str(SmartGetLocalProcessId()) + '.txt'
1739 if gDebugPrintOutputLineCount == 0:
1740 ff = open(fname, 'w')
1741 else:
1742 ff = open(fname, 'a+')
1743 ff.write(inMsg)
1744 if gDebugPrintOutputLineCount == gMaxDebugPrintOutputLines:
1745 ff.write("gMaxDebugPrintOutputLines hit\n")
1746 ff.close()
1747
1748 global gMdp3UseStandardOutFlag
1749 if gMdp3UseStandardOutFlag:
1750 print(inMsg)
1751 if gDebugPrintOutputLineCount == gMaxDebugPrintOutputLines:
1752 print("gMaxDebugPrintOutputLines hit\n")
1753
1754 gDebugPrintOutputLineCount += 1
1755
1756 if inPriority >= 10000:
1757 raise Exception(inMsg)
1758
1759 def myDebugPrint3AndException(inMsg, inOneProcessFlag = False,
1760 inOneProcessId = 0):
1761 if PhactoriDbg(10000, inOneProcessFlag, inOneProcessId):
1762 myDebugPrint3(inMsg, 10000, inOneProcessFlag, inOneProcessId)
1763
1764 def DebugPrintVtkDataArraysInfo(label, theData, priority):
1765 myDebugPrint3(label, priority)
1766 if theData == None:
1767 myDebugPrint3("None")
1768 else:
1769 numArrays = theData.GetNumberOfArrays()
1770 myDebugPrint3("number of data arrays: " + str(numArrays) + "\n", priority)
1771 for arrayIndex in range(0, numArrays):
1772 oneArray = theData.GetArray(arrayIndex)
1773 myDebugPrint3(str(arrayIndex) + ": " + str(oneArray.GetName()) + " " + str(oneArray.GetNumberOfComponents()) + "\n", priority)
1774
1775 def DebugPrintCellAndPointArrayInfo(label, pvFilter, priority):
1776 myDebugPrint3(label, priority)
1777 theData = pvFilter.PointData
1778 DebugPrintVtkDataArraysInfo("PointData:\n", theData, priority)
1779 theData = pvFilter.CellData
1780 DebugPrintVtkDataArraysInfo("CellData:\n", theData, priority)
1781
1782 #def SetCpViewsAndCpWriters(inCpViews, inCpWriters):
1783 # global localCpViews
1784 # global localCpWriters
1785 # localCpViews = inCpViews
1786 # localCpWriters = inCpWriters
1787
1788 def GetSeparatorString():
1789 global gPipeAndViewsState
1790 return gPipeAndViewsState.mSeparatorString
1791
1792 def GetCurrentOutputResultsBlockCountId():
1793 global gPipeAndViewsState
1794 retStr = str(gPipeAndViewsState.mOutputResultsBlockCountId)
1795 if PhactoriDbg():
1796 myDebugPrint3('GetCurrentOutputResultsBlockCountId: ' + retStr + '\n')
1797 return retStr
1798
1799 def GetExtraFileString():
1800 global gPipeAndViewsState
1801 return gPipeAndViewsState.mRemeshRestartTag
1802
1803 def WriteImagesForCurrentPipeAndViewsState(datadescription):
1804 gPipeAndViewsState.WriteImages(datadescription)
1805
1806 def ExportOperationsDataForCurrentPipeAndViewsState(datadescription):
1807 gPipeAndViewsState.ExportOperationsData(datadescription)
1808
1809 def SetUpCoProcessor(inCoprocessor):
1810 global localCoProcessorReference
1811 localCoProcessorReference = inCoprocessor
1812
1813 #phactori_combine_to_single_python_file_parent_1
1814 #from Operation.PhactoriVectorLibrary import *
1815 #phactori_combine_to_single_python_file_subpiece_begin_1
1816 def vecDotProduct(inVecA, inVecB):
1817 " returns dotproct inVecZ dot inVecB "
1818 return inVecA[0] * inVecB[0] + inVecA[1] * inVecB[1] + inVecA[2] * inVecB[2]
1819
1820 def vecCrossProduct(inVecA, inVecB):
1821 " returns inVecZ X inVecB "
1822 return [inVecA[1] * inVecB[2] - inVecA[2] * inVecB[1],
1823 inVecA[2] * inVecB[0] - inVecA[0] * inVecB[2],
1824 inVecA[0] * inVecB[1] - inVecA[1] * inVecB[0]]
1825
1826 def vecCrossProduct2(outVec, inVecA, inVecB):
1827 " calculates inVecA X inVecB and puts the result in outVec"
1828 outVec[0] = inVecA[1] * inVecB[2] - inVecA[2] * inVecB[1]
1829 outVec[1] = inVecA[2] * inVecB[0] - inVecA[0] * inVecB[2]
1830 outVec[2] = inVecA[0] * inVecB[1] - inVecA[1] * inVecB[0]
1831
1832 def vecCopy(destinationVec, sourceVec):
1833 destinationVec[0] = sourceVec[0]
1834 destinationVec[1] = sourceVec[1]
1835 destinationVec[2] = sourceVec[2]
1836
1837 def vecMagnitude(inVec):
1838 xx = inVec[0]
1839 yy = inVec[1]
1840 zz = inVec[2]
1841 return math.sqrt(xx*xx + yy*yy + zz*zz)
1842
1843 def vecMagnitudeSquared(inVec):
1844 xx = inVec[0]
1845 yy = inVec[1]
1846 zz = inVec[2]
1847 return xx*xx + yy*yy + zz*zz
1848
1849 def vecNormalizeWithSmallCheck(inVec, smallValue, smallNormal):
1850 xx = inVec[0]
1851 yy = inVec[1]
1852 zz = inVec[2]
1853 mag = math.sqrt(xx*xx + yy*yy + zz*zz)
1854 if mag <= smallValue:
1855 return smallNormal
1856 else:
1857 return [xx/mag, yy/mag, zz/mag]
1858
1859 def vecNormalize(inVec):
1860 xx = inVec[0]
1861 yy = inVec[1]
1862 zz = inVec[2]
1863 mag = math.sqrt(xx*xx + yy*yy + zz*zz)
1864 return [xx/mag, yy/mag, zz/mag]
1865
1866 def vecNormalize2(outVec, inVec):
1867 xx = inVec[0]
1868 yy = inVec[1]
1869 zz = inVec[2]
1870 mag = math.sqrt(xx*xx + yy*yy + zz*zz)
1871 outVec[0] = xx/mag
1872 outVec[1] = yy/mag
1873 outVec[2] = zz/mag
1874
1875 def vecFromAToB(inVecA, inVecB):
1876 return [inVecB[0] - inVecA[0], inVecB[1] - inVecA[1], inVecB[2] - inVecA[2]]
1877
1878 def vecDistanceSquared(inPtA, inPtB):
1879 "calculate the square of the distance between two points"
1880 ddx = inPtA[0] - inPtB[0]
1881 ddy = inPtA[1] - inPtB[1]
1882 ddz = inPtA[2] - inPtB[2]
1883 return ddx*ddx + ddy*ddy + ddz*ddz
1884
1885 def vecDistance(inPtA, inPtB):
1886 "calculate the distance between two points"
1887 return math.sqrt(vecDistanceSquared(inPtA, inPtB))
1888
1889 def vecAdd(inVecA, inVecB):
1890 return [inVecA[0]+inVecB[0],inVecA[1]+inVecB[1],inVecA[2]+inVecB[2]]
1891
1892 def vecAddInPlace(inVecA, inVecB):
1893 "changes inVecA to inVecA + inVecB"
1894 inVecA[0] += inVecB[0]
1895 inVecA[1] += inVecB[1]
1896 inVecA[2] += inVecB[2]
1897
1898 def vecScale(inScale, inVec):
1899 return [inScale*inVec[0], inScale*inVec[1], inScale*inVec[2]]
1900
1901 def vecScaleInPlace(inScale, inVec):
1902 inVec[0] *= inScale
1903 inVec[1] *= inScale
1904 inVec[2] *= inScale
1905
1906 def vecMultiplyAdd(inVecA, inVecB, inMM):
1907 "returns inVecA + (inMM * inVecB)"
1908 return [inVecA[0] + inMM * inVecB[0],
1909 inVecA[1] + inMM * inVecB[1],
1910 inVecA[2] + inMM * inVecB[2]]
1911
1912 def GetPhactoriVectorLibraryProgrammableFilterLines(pfLns):
1913 pfLns.append("def vecDotProduct(inVecA, inVecB):\n")
1914 pfLns.append(" return inVecA[0] * inVecB[0] + inVecA[1] * inVecB[1] + inVecA[2] * inVecB[2]\n")
1915 pfLns.append("def vecCrossProduct(inVecA, inVecB):\n")
1916 pfLns.append(" return [inVecA[1] * inVecB[2] - inVecA[2] * inVecB[1],\n")
1917 pfLns.append(" inVecA[2] * inVecB[0] - inVecA[0] * inVecB[2],\n")
1918 pfLns.append(" inVecA[0] * inVecB[1] - inVecA[1] * inVecB[0]]\n")
1919 pfLns.append("def vecCrossProduct2(outVec, inVecA, inVecB):\n")
1920 pfLns.append(" outVec[0] = inVecA[1] * inVecB[2] - inVecA[2] * inVecB[1]\n")
1921 pfLns.append(" outVec[1] = inVecA[2] * inVecB[0] - inVecA[0] * inVecB[2]\n")
1922 pfLns.append(" outVec[2] = inVecA[0] * inVecB[1] - inVecA[1] * inVecB[0]\n")
1923 pfLns.append("def vecCopy(destinationVec, sourceVec):\n")
1924 pfLns.append(" destinationVec[0] = sourceVec[0]\n")
1925 pfLns.append(" destinationVec[1] = sourceVec[1]\n")
1926 pfLns.append(" destinationVec[2] = sourceVec[2]\n")
1927 pfLns.append("def vecMagnitude(inVec):\n")
1928 pfLns.append(" xx = inVec[0]\n")
1929 pfLns.append(" yy = inVec[1]\n")
1930 pfLns.append(" zz = inVec[2]\n")
1931 pfLns.append(" return math.sqrt(xx*xx + yy*yy + zz*zz)\n")
1932 pfLns.append("def vecMagnitudeSquared(inVec):\n")
1933 pfLns.append(" xx = inVec[0]\n")
1934 pfLns.append(" yy = inVec[1]\n")
1935 pfLns.append(" zz = inVec[2]\n")
1936 pfLns.append(" return xx*xx + yy*yy + zz*zz\n")
1937 pfLns.append("def vecNormalizeWithSmallCheck(inVec, smallValue, smallNormal):\n")
1938 pfLns.append(" xx = inVec[0]\n")
1939 pfLns.append(" yy = inVec[1]\n")
1940 pfLns.append(" zz = inVec[2]\n")
1941 pfLns.append(" mag = math.sqrt(xx*xx + yy*yy + zz*zz)\n")
1942 pfLns.append(" if mag <= smallValue:\n")
1943 pfLns.append(" return smallNormal\n")
1944 pfLns.append(" else:\n")
1945 pfLns.append(" return [xx/mag, yy/mag, zz/mag]\n")
1946 pfLns.append("def vecNormalize(inVec):\n")
1947 pfLns.append(" xx = inVec[0]\n")
1948 pfLns.append(" yy = inVec[1]\n")
1949 pfLns.append(" zz = inVec[2]\n")
1950 pfLns.append(" mag = math.sqrt(xx*xx + yy*yy + zz*zz)\n")
1951 pfLns.append(" return [xx/mag, yy/mag, zz/mag]\n")
1952 pfLns.append("def vecNormalize2(outVec, inVec):\n")
1953 pfLns.append(" xx = inVec[0]\n")
1954 pfLns.append(" yy = inVec[1]\n")
1955 pfLns.append(" zz = inVec[2]\n")
1956 pfLns.append(" mag = math.sqrt(xx*xx + yy*yy + zz*zz)\n")
1957 pfLns.append(" outVec[0] = xx/mag\n")
1958 pfLns.append(" outVec[1] = yy/mag\n")
1959 pfLns.append(" outVec[2] = zz/mag\n")
1960 pfLns.append("def vecFromAToB(inVecA, inVecB):\n")
1961 pfLns.append(" return [inVecB[0] - inVecA[0], inVecB[1] - inVecA[1], inVecB[2] - inVecA[2]]\n")
1962 pfLns.append("def vecDistanceSquared(inPtA, inPtB):\n")
1963 pfLns.append(" ddx = inPtA[0] - inPtB[0]\n")
1964 pfLns.append(" ddy = inPtA[1] - inPtB[1]\n")
1965 pfLns.append(" ddz = inPtA[2] - inPtB[2]\n")
1966 pfLns.append(" return ddx*ddx + ddy*ddy + ddz*ddz\n")
1967 pfLns.append("def vecDistance(inPtA, inPtB):\n")
1968 pfLns.append(" return math.sqrt(vecDistanceSquared(inPtA, inPtB))\n")
1969 pfLns.append("def vecAdd(inVecA, inVecB):\n")
1970 pfLns.append(" return [inVecA[0]+inVecB[0],inVecA[1]+inVecB[1],inVecA[2]+inVecB[2]]\n")
1971 pfLns.append("def vecScale(inScale, inVec):\n")
1972 pfLns.append(" return [inScale*inVec[0], inScale*inVec[1], inScale*inVec[2]]\n")
1973 pfLns.append("def vecMultiplyAdd(inVecA, inVecB, inMM):\n")
1974 pfLns.append(" return [inVecA[0] + inMM * inVecB[0],\n")
1975 pfLns.append(" inVecA[1] + inMM * inVecB[1],\n")
1976 pfLns.append(" inVecA[2] + inMM * inVecB[2]]\n")
1977
1978 #phactori_combine_to_single_python_file_subpiece_end_1
1979
1980 #phactori_combine_to_single_python_file_parent_1
1981 #from Operation.PhactoriVtkCellOperations import *
1982 #phactori_combine_to_single_python_file_subpiece_begin_1
1983
1984 def PhactoriCalculateFaceArea(inInputCsData, targetFace):
1985 numFaceEdges = targetFace.GetNumberOfEdges()
1986 if numFaceEdges >= 3:
1987 #assumes convex polygons, weird answer if not
1988 retVal = 0.0
1989 ptIds = targetFace.GetPointIds()
1990 ptA = inInputCsData.GetPoint(ptIds.GetId(0))
1991 ptB = inInputCsData.GetPoint(ptIds.GetId(1))
1992 vecAB = vecFromAToB(ptA, ptB)
1993 for ii in range(2, numFaceEdges):
1994 ptC = inInputCsData.GetPoint(ptIds.GetId(ii))
1995 vecAC = vecFromAToB(ptA, ptC)
1996 ABxAC = vecCrossProduct(vecAB, vecAC)
1997 retVal += vecMagnitude(ABxAC)
1998 vecAB = vecAC
1999 retVal *= 0.5
2000 else:
2001 #two or fewer vertices
2002 retVal = 0.0
2003 return retVal
2004
2005 def PhactoriCalculateCellFaceAreas(inInputCsData, oneCell):
2006 faceAreaList = []
2007 numFaces = oneCell.GetNumberOfFaces()
2008 for faceNdx in range(0, numFaces):
2009 gsfslTestFace = oneCell.GetFace(faceNdx)
2010 faceAreaList.append(PhactoriCalculateFaceArea(inInputCsData, gsfslTestFace))
2011 return faceAreaList
2012
2013 def PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell):
2014 faceAreasByIndex = PhactoriCalculateCellFaceAreas(inInputCsData, oneCell)
2015 faceAreasSorted = sorted(faceAreasByIndex)
2016 return faceAreasByIndex, faceAreasSorted
2017
2018 class PhactoriCountCellsTouchingFaceData:
2019 def __init__(self, inInputCsData):
2020 self.PerFaceData = {}
2021 self.vtkGrid = inInputCsData
2022 self.totalNumFaces = 0
2023 self.totalNumFacesWithOneCellTouching = 0
2024 self.totalNumFacesWithTwoCellsTouching = 0
2025 self.totalNumFacesWith3plCellsTouching = 0
2026
2027 def DoCountForAllCellsInBlock(self):
2028 numCells = self.vtkGrid.GetNumberOfCells()
2029 for ii in range(0, numCells):
2030 self.DoCountForOneCell(ii)
2031
2032 def DoCountForOneCell(self, cellIndex):
2033 oneCell = self.vtkGrid.GetCell(cellIndex)
2034 numFaces = oneCell.GetNumberOfFaces()
2035 for jj in range(0, numFaces):
2036 self.DoCountForOneFace(oneCell, cellIndex, jj)
2037
2038 def GetFaceHash(self, oneFace):
2039 #for now we use the average of all face points to uniquely identify the
2040 #face; we could use all indices of the face but that is more complex
2041 #and we couldn't match up faces across block/processor boundaries
2042 #however, it's possible that average of vertices may fail in some
2043 #circumstances and we could use the x/y/z of all the vertices if necessary
2044 faceHash = [0.0, 0.0, 0.0]
2045 numFacePoints = oneFace.GetNumberOfPoints()
2046 facePointIds = oneFace.GetPointIds()
2047 facePointIds2 = []
2048 for kk in range(0, numFacePoints):
2049 facePointIds2.append(facePointIds.GetId(kk))
2050 facePointIds2 = sorted(facePointIds2)
2051 for pointId in facePointIds2:
2052 oneFacePoint = self.vtkGrid.GetPoint(pointId)
2053 faceHash[0] += oneFacePoint[0]
2054 faceHash[1] += oneFacePoint[1]
2055 faceHash[2] += oneFacePoint[2]
2056 return faceHash
2057
2058 def DoCountForOneFace(self, oneCell, cellIndex, faceIndex):
2059 oneFace = oneCell.GetFace(faceIndex)
2060 faceHash = self.GetFaceHash(oneFace)
2061 self.IncrementCellTouchingFaceCount(faceHash, cellIndex, faceIndex)
2062
2063 def IncrementCellTouchingFaceCount(self, faceHash, cellIndex, faceIndex):
2064
2065 if faceHash[0] not in self.PerFaceData:
2066 self.PerFaceData[faceHash[0]] = {}
2067 facelvl1 = self.PerFaceData[faceHash[0]]
2068 if faceHash[1] not in facelvl1:
2069 facelvl1[faceHash[1]] = {}
2070 facelvl2 = facelvl1[faceHash[1]]
2071 if faceHash[2] not in facelvl2:
2072 facelvl2[faceHash[2]] = [1, cellIndex, faceIndex, -1, -1]
2073 self.totalNumFaces += 1
2074 self.totalNumFacesWithOneCellTouching += 1
2075 else:
2076 facelvl3 = facelvl2[faceHash[2]]
2077 if facelvl3[0] == 1:
2078 self.totalNumFacesWithOneCellTouching -= 1
2079 self.totalNumFacesWithTwoCellsTouching += 1
2080 elif facelvl3[0] == 2:
2081 self.totalNumFacesWithTwoCellsTouching -= 1
2082 self.totalNumFacesWith3plCellsTouching += 1
2083 facelvl3[0] += 1
2084 facelvl3[3] = cellIndex
2085 facelvl3[4] = faceIndex
2086
2087 def GetNumberOfCellsTouchingFace(self, oneFace):
2088 faceHash = self.GetFaceHash(oneFace)
2089 returnCount = self.PerFaceData[faceHash[0]][faceHash[1]][faceHash[2]][0]
2090 return returnCount
2091
2092 def GetNumberOfCellsTouchingEachFaceOfOneCell(self, oneCellIndex):
2093 oneCell = self.vtkGrid.GetCell(oneCellIndex)
2094 returnCountPerFace = []
2095 numFaces = oneCell.GetNumberOfFaces()
2096 for ii in range(0, numFaces):
2097 oneFace = oneCell.GetFace(ii)
2098 returnCountPerFace.append(self.GetNumberOfCellsTouchingFace(oneFace))
2099 return returnCountPerFace
2100
2101 def GetListOfExteriorFacesOnCell(self, oneCell):
2102 returnExteriorFaceIndices = []
2103 numFaces = oneCell.GetNumberOfFaces()
2104 for ii in range(0, numFaces):
2105 oneFace = oneCell.GetFace(ii)
2106 if self.GetNumberOfCellsTouchingFace(oneFace) == 1:
2107 returnExteriorFaceIndices.append(ii)
2108 return returnExteriorFaceIndices
2109
2110 def GetListOfExteriorFacesOnCellByIndex(self, cellIndex):
2111 return self.GetListOfExteriorFacesOnCell(self.vtkGrid.GetCell(cellIndex))
2112
2113 def PhactoriCountCellTouchingEachFace(inInputCsData):
2114 "goes through each cell, and for each cell goes through each face, and for\n each of those faces creates/locates a count for that face and increments\n it. Purpose is to find cells with faces that don't neighbor other cells\n "
2115 countCellsTouchingEachFace = PhactoriCountCellsTouchingFaceData(inInputCsData)
2116 countCellsTouchingEachFace.DoCountForAllCellsInBlock()
2117 if PhactoriDbg(100):
2118 cctef = countCellsTouchingEachFace
2119 myDebugPrint3("PhactoriCountCellTouchingEachFace:" + \
2120 "\nnum cells in block: " + str(inInputCsData.GetNumberOfCells()) + \
2121 "\nnum faces: " + str(cctef.totalNumFaces) + \
2122 "\nnum faces with 1 cell: " + str(cctef.totalNumFacesWithOneCellTouching) + \
2123 "\nnum faces with 2 cells: " + str(cctef.totalNumFacesWithTwoCellsTouching) + \
2124 "\nnum faces with 3+ cells: " + str(cctef.totalNumFacesWith3plCellsTouching) + "\n")
2125
2126 return countCellsTouchingEachFace
2127
2128 def PhactoriCountCellTouchingEachPoint(inInputCsData):
2129 numCells = inInputCsData.GetNumberOfCells()
2130 numPoints = inInputCsData.GetNumberOfPoints()
2131 cellsTouchingPointCount = [0] * numPoints
2132 for ii in range(0, numCells):
2133 oneCell = inInputCsData.GetCell(ii)
2134 cellPointIds = oneCell.GetPointIds()
2135 numCellPoints = oneCell.GetNumberOfPoints()
2136 for jj in range(0, numCellPoints):
2137 oneCellPointId = cellPointIds.GetId(jj)
2138 cellsTouchingPointCount[oneCellPointId] += 1
2139 return cellsTouchingPointCount
2140
2141 def PhactoriSurfaceCornerCellFaceFacesExterior(oneFace, cellsTouchingPointCount):
2142 numFacePoints = oneFace.GetNumberOfPoints()
2143 facePointIds = oneFace.GetPointIds()
2144 numOutsideVertices = 0
2145 for ii in range(0, numFacePoints):
2146 if cellsTouchingPointCount[facePointIds.GetId(ii)] <= 1:
2147 return True
2148 return False
2149
2150 def PhactoriIsOutsideCornerHexCellFaceMaxAreaFace(oneCell, indexFaceListSize,
2151 sortedFaceSizeList, cellsTouchingPointCount, TestNthLargestFace = 2):
2152 #faces with 4 2 2 0 need to be tested
2153 numFaces = oneCell.GetNumberOfFaces()
2154 for faceIndex in range(0, numFaces):
2155 oneFace = oneCell.GetFace(faceIndex)
2156 if PhactoriSurfaceCornerCellFaceFacesExterior(oneFace, cellsTouchingPointCount):
2157 if indexFaceListSize[faceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:
2158 #this cell is facing the big area cell side
2159 return True
2160 return False
2161
2162 def PhactoriSurfaceEdgeHexCellFaceFacesExterior(oneFace, cellsTouchingPointCount):
2163 numFacePoints = oneFace.GetNumberOfPoints()
2164 facePointIds = oneFace.GetPointIds()
2165 numOutsideVertices = 0
2166 for ii in range(0, numFacePoints):
2167 if cellsTouchingPointCount[facePointIds.GetId(ii)] <= 2:
2168 numOutsideVertices += 1
2169 return (numOutsideVertices >= 2)
2170
2171 def PhactoriIsOutsideEdgeHexCellFaceMaxAreaFace(oneCell,
2172 indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount,
2173 TestNthLargestFace = 2):
2174 #faces with 4 4 2 2 need to be tested
2175 numFaces = oneCell.GetNumberOfFaces()
2176 #test cell flatness
2177 for faceIndex in range(0, numFaces):
2178 oneFace = oneCell.GetFace(faceIndex)
2179 if PhactoriSurfaceEdgeHexCellFaceFacesExterior(oneFace, cellsTouchingPointCount):
2180 if indexFaceListSize[faceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:
2181 #this cell is exterior and facing the big area cell side
2182 return True
2183 return False
2184
2185 def PhactoriIsOutsideSurfaceHexCellFaceMaxAreaFace(oneCell,
2186 indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount,
2187 TestNthLargestFace = 2):
2188 #find face which face faces exterior
2189 numFaces = oneCell.GetNumberOfFaces()
2190 for faceIndex in range(0, numFaces):
2191 oneFace = oneCell.GetFace(faceIndex)
2192 numFacePoints = oneFace.GetNumberOfPoints()
2193 facePtNdxs = oneFace.GetPointIds()
2194 outsideFaceIndex = -1
2195 for jj in range(0, numFacePoints):
2196 outsideFaceIndex = faceIndex
2197 ptNdx = facePtNdxs.GetId(jj)
2198 if cellsTouchingPointCount[ptNdx] != 4:
2199 outsideFaceIndex = -1
2200 #this is not the outward facing face
2201 break
2202 if outsideFaceIndex >= 0:
2203 #this is the outward facing face
2204 break
2205 if outsideFaceIndex < 0:
2206 #shouldn't happen, didn't find face with all 4's
2207 myDebugPrint3AndException("outsideFaceIndex < 0 error\n")
2208 return False
2209 #now see if this outward facing face is one of the Nth largest
2210 if indexFaceListSize[outsideFaceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:
2211 return True
2212 else:
2213 return False
2214
2215 def PhactoriFindSurfaceStatusForOneCellUsingFaceInfo(inInputCsData,
2216 inCellIndex, countCellsTouchingEachFace, flatnessTestRatio = 100.0,
2217 TestNthLargestFace = 2):
2218 oneCell = inInputCsData.GetCell(inCellIndex)
2219 exteriorFaceList = countCellsTouchingEachFace.GetListOfExteriorFacesOnCell(oneCell)
2220 numExteriorFaces = len(exteriorFaceList)
2221 if numExteriorFaces == 0:
2222 #interior cell
2223 retStatus = 1
2224 else:
2225 #surface cell (surface, edge, or corner)
2226 #test cell flatness
2227 indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)
2228 flatnessRatio = sortedFaceSizeList[-1] / sortedFaceSizeList[0]
2229 if len(sortedFaceSizeList) <= 0:
2230 retStatus = 11
2231 return retStatus
2232 cellIsFlat = (flatnessRatio >= flatnessTestRatio)
2233 #see if any of the exterior faces are the biggest
2234 outsideFaceIsMaxAreaFace = False
2235 for outsideFaceIndex in exteriorFaceList:
2236 if indexFaceListSize[outsideFaceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:
2237 outsideFaceIsMaxAreaFace = True
2238 break
2239 if numExteriorFaces == 1:
2240 #outside surface, not edge or corner
2241 if outsideFaceIsMaxAreaFace:
2242 if cellIsFlat:
2243 retStatus = 11
2244 else:
2245 retStatus = 8
2246 else:
2247 if cellIsFlat:
2248 retStatus = 5
2249 else:
2250 retStatus = 2
2251 elif numExteriorFaces == 2:
2252 #outside edge, not corner
2253 if outsideFaceIsMaxAreaFace:
2254 if cellIsFlat:
2255 retStatus = 12
2256 else:
2257 retStatus = 9
2258 else:
2259 if cellIsFlat:
2260 retStatus = 6
2261 else:
2262 retStatus = 3
2263 else:
2264 #outside surface corner
2265 if outsideFaceIsMaxAreaFace:
2266 if cellIsFlat:
2267 retStatus = 13
2268 else:
2269 retStatus = 10
2270 else:
2271 if cellIsFlat:
2272 retStatus = 7
2273 else:
2274 retStatus = 4
2275 return retStatus
2276
2277
2278 def PhactoriFindSurfaceStatusForOneCell(inInputCsData, inCellIndex,
2279 cellsTouchingPointCount, flatnessTestRatio = 100.0):
2280 oneCell = inInputCsData.GetCell(inCellIndex)
2281
2282 #cells with all 8 are interior
2283 #cells with 4 and 8 are outside surface
2284 #cells with 2 (and no 0) are outside edge
2285 #cells with 1 are corner
2286
2287 #not currently handling inside edge (there are count 6 cells) or inside
2288 #corner (there are count 7 cells)
2289
2290 #if cell is outside surface (4 and 8), if the face which is all 4 is the
2291 #largest or second largest area, then it is on the surface we want
2292
2293 #if the cell is edge (2 4 8), there should be two sides which are 2 2 4 4
2294 #if either of these sides is the second or largest area then it is on the
2295 #surface we want.
2296
2297 #if the cell is corner, there should be three sides which are 0 2 2 4
2298 #if any of these sides is the second or largest area then it is on the
2299 #surface we want
2300
2301 numPoints = oneCell.GetNumberOfPoints()
2302 pointIds = oneCell.GetPointIds()
2303 minCtpc = 9
2304 for ii in range(0, numPoints):
2305 testCtpc = cellsTouchingPointCount[pointIds.GetId(ii)]
2306 if testCtpc < minCtpc:
2307 minCtpc = testCtpc
2308
2309 #if inCellIndex == 172065:
2310 if inCellIndex == 5056:
2311 debugFlag = 100
2312 else:
2313 debugFlag = 25
2314 if minCtpc >= 8:
2315 #interior cell
2316 retStatus = 1
2317 else:
2318 #surface cell (surface, edge, or corner)
2319 #test cell flatness
2320 indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)
2321 flatnessRatio = sortedFaceSizeList[-1] / sortedFaceSizeList[0]
2322 if len(sortedFaceSizeList) <= 0:
2323 retStatus = 11
2324 return retStatus
2325 cellIsFlat = (flatnessRatio >= flatnessTestRatio)
2326 if minCtpc >= 4:
2327 #outside surface, not edge or corner
2328 outsideFaceIsMaxAreaFace = PhactoriIsOutsideSurfaceHexCellFaceMaxAreaFace(
2329 oneCell, indexFaceListSize, sortedFaceSizeList,
2330 cellsTouchingPointCount)
2331 if outsideFaceIsMaxAreaFace:
2332 if cellIsFlat:
2333 retStatus = 11
2334 else:
2335 retStatus = 8
2336 else:
2337 if cellIsFlat:
2338 retStatus = 5
2339 else:
2340 retStatus = 2
2341 elif minCtpc >= 2:
2342 #outside surface edge, not corner
2343 outsideFaceIsMaxAreaFace = PhactoriIsOutsideEdgeHexCellFaceMaxAreaFace(
2344 oneCell, indexFaceListSize, sortedFaceSizeList,
2345 cellsTouchingPointCount)
2346 if outsideFaceIsMaxAreaFace:
2347 if cellIsFlat:
2348 retStatus = 12
2349 else:
2350 retStatus = 9
2351 else:
2352 if cellIsFlat:
2353 retStatus = 6
2354 else:
2355 retStatus = 3
2356 elif minCtpc >= 1:
2357 #outside surface corner
2358 outsideFaceIsMaxAreaFace = PhactoriIsOutsideCornerHexCellFaceMaxAreaFace(
2359 oneCell, indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount)
2360 if outsideFaceIsMaxAreaFace:
2361 if cellIsFlat:
2362 retStatus = 13
2363 else:
2364 retStatus = 10
2365 else:
2366 if cellIsFlat:
2367 retStatus = 7
2368 else:
2369 retStatus = 4
2370 else:
2371 #should not get here
2372 myDebugPrint3AndException("bad minCtpc error\n")
2373 retStatus = -1
2374
2375 return retStatus
2376
2377 def PhactoriGetCellEdgeVector(inInputCsData, oneFaceOrCell, edgeIndex):
2378 oneFaceEdgePointIds = oneFaceOrCell.GetEdge(edgeIndex).GetPointIds()
2379 ptA = inInputCsData.GetPoint(oneFaceEdgePointIds.GetId(0))
2380 ptB = inInputCsData.GetPoint(oneFaceEdgePointIds.GetId(1))
2381 retVec = vecFromAToB(ptA,ptB)
2382 return retVec
2383
2384 def PhactoriFindFaceNormal(inInputCsData, oneFace):
2385 facePointIds = oneFace.GetPointIds()
2386 #maybe should work harder to find good normal
2387 ptA = inInputCsData.GetPoint(facePointIds.GetId(0))
2388 ptB = inInputCsData.GetPoint(facePointIds.GetId(1))
2389 ptC = inInputCsData.GetPoint(facePointIds.GetId(2))
2390 vecAB = vecFromAToB(ptA, ptB)
2391 vecBC = vecFromAToB(ptB, ptC)
2392 retNormalVec = vecCrossProduct(vecBC, vecAB)
2393 vecNormalize2(retNormalVec, retNormalVec)
2394 return retNormalVec
2395
2396 def PhactoriFindLargestCellFaceNormal(inInputCsData, oneCell):
2397 indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)
2398 biggestFaceSize = sortedFaceSizeList[-1]
2399 for faceForNormalIndex in range(0, len(indexFaceListSize)):
2400 if indexFaceListSize[faceForNormalIndex] == biggestFaceSize:
2401 break
2402 faceForNormal = oneCell.GetFace(faceForNormalIndex)
2403 retNormalVec = PhactoriFindFaceNormal(inInputCsData, faceForNormal)
2404 return retNormalVec
2405
2406 def PhactoriGetAverageOfCellPoints(inInputCsData, oneCell):
2407 numPoints = oneCell.GetNumberOfPoints()
2408 retAvgPt = [0.0, 0.0, 0.0]
2409 if numPoints <= 0:
2410 return retAvgPt
2411 ptIds = oneCell.GetPointIds()
2412 for ii in range(0, numPoints):
2413 ptA = inInputCsData.GetPoint(ptIds.GetId(ii))
2414 vecAddInPlace(retAvgPt, ptA)
2415 avgFac = 1.0/float(numPoints)
2416 vecScaleInPlace(avgFac, retAvgPt)
2417 return retAvgPt
2418
2419 def PhactoriFindSelectedAngleBetweenEdgeAndCellNormal(inInputCsData, oneCell,
2420 compareNormal, paramUseSmallestAngle, paramOffsetIndex):
2421 edgeCompareDotProdList = []
2422 numEdges = oneCell.GetNumberOfEdges()
2423 for ii in range(0, numEdges):
2424 oneEdgeVec = PhactoriGetCellEdgeVector(inInputCsData, oneCell, ii)
2425 vecNormalize2(oneEdgeVec, oneEdgeVec)
2426 edgeCompareDotProd = abs(vecDotProduct(compareNormal, oneEdgeVec))
2427 edgeCompareDotProdList.append(edgeCompareDotProd)
2428
2429 sortedEdgeCompareDotProdList = sorted(edgeCompareDotProdList)
2430
2431 if paramUseSmallestAngle:
2432 outputIndex = max(0, numEdges - 1 - paramOffsetIndex)
2433 else:
2434 outputIndex = min(paramOffsetIndex, numEdges - 1)
2435
2436 outputAngle = 90.0 - math.degrees(math.acos(sortedEdgeCompareDotProdList[outputIndex]))
2437 return outputAngle
2438
2439 def DebugPrintPhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal):
2440 if PhactoriDbg(100):
2441 dbght = []
2442 dbglen = []
2443 dbgretHeight = -1.0
2444 dbgretHeightIndex = -1
2445 for ii in range(0, numCellEdges):
2446 oneCellEdgeVec = PhactoriGetCellEdgeVector(inInputCsData, oneCell, ii)
2447 dp1 = vecDotProduct(oneCellEdgeVec, compareNormal)
2448 projectedVec = vecScale(dp1, compareNormal)
2449 oneCellEdgeHeight = vecMagnitude(projectedVec)
2450 dbght.append(oneCellEdgeHeight)
2451 dbglen.append(vecMagnitude(oneCellEdgeVec))
2452 if oneCellEdgeHeight > dbgretHeight:
2453 dbgretHeight = oneCellEdgeHeight
2454 dbgretHeightIndex = ii
2455 #how many edges before projection are longer than the height edge, and
2456 #is the height edge one of the four shortest
2457 myDebugPrint3("cell height: " + str(dbgretHeight) + " index: " + \
2458 str(dbgretHeightIndex) + " edgelen: " + str(dbglen[dbgretHeightIndex]) + "\n")
2459 myDebugPrint3("all edge length, height pairs:\n")
2460 numLonger = 0
2461 for ii in range(0, numCellEdges):
2462 if dbglen[ii] >= dbglen[dbgretHeightIndex]:
2463 numLonger += 1
2464 myDebugPrint3(str(ii) + ": " + str(dbglen[ii]) + ", " + str(dbght[ii]) + "\n")
2465 myDebugPrint3("num edges longer than cell height edge: " + str(numLonger) + "\n")
2466
2467 def PhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal):
2468 #do we need to discard eight longest sides, or will they project to less
2469 #than the four shortest sides?
2470 numCellEdges = oneCell.GetNumberOfEdges()
2471
2472 retHeight = -1.0
2473 for ii in range(0, numCellEdges):
2474 #get edge vectory and project on to normal vector (which is unit length)
2475 #and find magnitude
2476 oneCellEdgeVec = PhactoriGetCellEdgeVector(inInputCsData, oneCell, ii)
2477 dp1 = vecDotProduct(oneCellEdgeVec, compareNormal)
2478 projectedVec = vecScale(dp1, compareNormal)
2479 oneCellEdgeHeight = vecMagnitude(projectedVec)
2480 if oneCellEdgeHeight > retHeight:
2481 retHeight = oneCellEdgeHeight
2482 #if PhactoriDbg(100):
2483 # DebugPrintPhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal)
2484 return retHeight
2485
2486 def PhactoriFindCellEdgeAngleMetricsForOneCell(inInputCsData, inCellIndex,
2487 paramUseSmallestAngle, paramOffsetIndex):
2488 oneCell = inInputCsData.GetCell(inCellIndex)
2489 numEdges = oneCell.GetNumberOfEdges()
2490 if numEdges < 6:
2491 return 90.0, 0.0
2492 if oneCell.GetNumberOfFaces() < 4:
2493 return 90.0, 0.0
2494
2495 compareNormal = PhactoriFindLargestCellFaceNormal(inInputCsData, oneCell)
2496 retAngle = PhactoriFindSelectedAngleBetweenEdgeAndCellNormal(inInputCsData,
2497 oneCell, compareNormal, paramUseSmallestAngle, paramOffsetIndex)
2498 retHeight = PhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal)
2499 return retAngle, retHeight
2500
2501 def GetPhactoriVtkCellOperationsProgrammableFilterLines(pfLns):
2502 pfLns.append("def PhactoriCalculateFaceArea(inInputCsData, targetFace):\n")
2503 pfLns.append(" numFaceEdges = targetFace.GetNumberOfEdges()\n")
2504 pfLns.append(" if numFaceEdges >= 3:\n")
2505 pfLns.append(" retVal = 0.0\n")
2506 pfLns.append(" ptIds = targetFace.GetPointIds()\n")
2507 pfLns.append(" ptA = inInputCsData.GetPoint(ptIds.GetId(0))\n")
2508 pfLns.append(" ptB = inInputCsData.GetPoint(ptIds.GetId(1))\n")
2509 pfLns.append(" vecAB = vecFromAToB(ptA, ptB)\n")
2510 pfLns.append(" for ii in range(2, numFaceEdges):\n")
2511 pfLns.append(" ptC = inInputCsData.GetPoint(ptIds.GetId(ii))\n")
2512 pfLns.append(" vecAC = vecFromAToB(ptA, ptC)\n")
2513 pfLns.append(" ABxAC = vecCrossProduct(vecAB, vecAC)\n")
2514 pfLns.append(" retVal += vecMagnitude(ABxAC)\n")
2515 pfLns.append(" vecAB = vecAC\n")
2516 pfLns.append(" retVal *= 0.5\n")
2517 pfLns.append(" else:\n")
2518 pfLns.append(" retVal = 0.0\n")
2519 pfLns.append(" return retVal\n")
2520 pfLns.append("def PhactoriCalculateCellFaceAreas(inInputCsData, oneCell):\n")
2521 pfLns.append(" faceAreaList = []\n")
2522 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2523 pfLns.append(" for faceNdx in range(0, numFaces):\n")
2524 pfLns.append(" gsfslTestFace = oneCell.GetFace(faceNdx)\n")
2525 pfLns.append(" faceAreaList.append(PhactoriCalculateFaceArea(inInputCsData, gsfslTestFace))\n")
2526 pfLns.append(" return faceAreaList\n")
2527 pfLns.append("def PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell):\n")
2528 pfLns.append(" faceAreasByIndex = PhactoriCalculateCellFaceAreas(inInputCsData, oneCell)\n")
2529 pfLns.append(" faceAreasSorted = sorted(faceAreasByIndex)\n")
2530 pfLns.append(" return faceAreasByIndex, faceAreasSorted\n")
2531 pfLns.append("class PhactoriCountCellsTouchingFaceData:\n")
2532 pfLns.append(" def __init__(self, inInputCsData):\n")
2533 pfLns.append(" self.PerFaceData = {}\n")
2534 pfLns.append(" self.vtkGrid = inInputCsData\n")
2535 pfLns.append(" self.totalNumFaces = 0\n")
2536 pfLns.append(" self.totalNumFacesWithOneCellTouching = 0\n")
2537 pfLns.append(" self.totalNumFacesWithTwoCellsTouching = 0\n")
2538 pfLns.append(" self.totalNumFacesWith3plCellsTouching = 0\n")
2539 pfLns.append(" def DoCountForAllCellsInBlock(self):\n")
2540 pfLns.append(" numCells = self.vtkGrid.GetNumberOfCells()\n")
2541 pfLns.append(" for ii in range(0, numCells):\n")
2542 pfLns.append(" self.DoCountForOneCell(ii)\n")
2543 pfLns.append(" def DoCountForOneCell(self, cellIndex):\n")
2544 pfLns.append(" oneCell = self.vtkGrid.GetCell(cellIndex)\n")
2545 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2546 pfLns.append(" for jj in range(0, numFaces):\n")
2547 pfLns.append(" self.DoCountForOneFace(oneCell, cellIndex, jj)\n")
2548 pfLns.append(" def GetFaceHash(self, oneFace):\n")
2549 pfLns.append(" faceHash = [0.0, 0.0, 0.0]\n")
2550 pfLns.append(" numFacePoints = oneFace.GetNumberOfPoints()\n")
2551 pfLns.append(" facePointIds = oneFace.GetPointIds()\n")
2552 pfLns.append(" facePointIds2 = []\n")
2553 pfLns.append(" for kk in range(0, numFacePoints):\n")
2554 pfLns.append(" facePointIds2.append(facePointIds.GetId(kk))\n")
2555 pfLns.append(" facePointIds2 = sorted(facePointIds2)\n")
2556 pfLns.append(" for pointId in facePointIds2:\n")
2557 pfLns.append(" oneFacePoint = self.vtkGrid.GetPoint(pointId)\n")
2558 pfLns.append(" faceHash[0] += oneFacePoint[0]\n")
2559 pfLns.append(" faceHash[1] += oneFacePoint[1]\n")
2560 pfLns.append(" faceHash[2] += oneFacePoint[2]\n")
2561 pfLns.append(" return faceHash\n")
2562 pfLns.append(" def DoCountForOneFace(self, oneCell, cellIndex, faceIndex):\n")
2563 pfLns.append(" oneFace = oneCell.GetFace(faceIndex)\n")
2564 pfLns.append(" faceHash = self.GetFaceHash(oneFace)\n")
2565 pfLns.append(" self.IncrementCellTouchingFaceCount(faceHash, cellIndex, faceIndex)\n")
2566 pfLns.append(" def IncrementCellTouchingFaceCount(self, faceHash, cellIndex, faceIndex):\n")
2567 pfLns.append(" if faceHash[0] not in self.PerFaceData:\n")
2568 pfLns.append(" self.PerFaceData[faceHash[0]] = {}\n")
2569 pfLns.append(" facelvl1 = self.PerFaceData[faceHash[0]]\n")
2570 pfLns.append(" if faceHash[1] not in facelvl1:\n")
2571 pfLns.append(" facelvl1[faceHash[1]] = {}\n")
2572 pfLns.append(" facelvl2 = facelvl1[faceHash[1]]\n")
2573 pfLns.append(" if faceHash[2] not in facelvl2:\n")
2574 pfLns.append(" facelvl2[faceHash[2]] = [1, cellIndex, faceIndex, -1, -1]\n")
2575 pfLns.append(" self.totalNumFaces += 1\n")
2576 pfLns.append(" self.totalNumFacesWithOneCellTouching += 1\n")
2577 pfLns.append(" else:\n")
2578 pfLns.append(" facelvl3 = facelvl2[faceHash[2]]\n")
2579 pfLns.append(" if facelvl3[0] == 1:\n")
2580 pfLns.append(" self.totalNumFacesWithOneCellTouching -= 1\n")
2581 pfLns.append(" self.totalNumFacesWithTwoCellsTouching += 1\n")
2582 pfLns.append(" elif facelvl3[0] == 2:\n")
2583 pfLns.append(" self.totalNumFacesWithTwoCellsTouching -= 1\n")
2584 pfLns.append(" self.totalNumFacesWith3plCellsTouching += 1\n")
2585 pfLns.append(" facelvl3[0] += 1\n")
2586 pfLns.append(" facelvl3[3] = cellIndex\n")
2587 pfLns.append(" facelvl3[4] = faceIndex\n")
2588 pfLns.append(" def GetNumberOfCellsTouchingFace(self, oneFace):\n")
2589 pfLns.append(" faceHash = self.GetFaceHash(oneFace)\n")
2590 pfLns.append(" returnCount = self.PerFaceData[faceHash[0]][faceHash[1]][faceHash[2]][0]\n")
2591 pfLns.append(" return returnCount\n")
2592 pfLns.append(" def GetNumberOfCellsTouchingEachFaceOfOneCell(self, oneCellIndex):\n")
2593 pfLns.append(" oneCell = self.vtkGrid.GetCell(oneCellIndex)\n")
2594 pfLns.append(" returnCountPerFace = []\n")
2595 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2596 pfLns.append(" for ii in range(0, numFaces):\n")
2597 pfLns.append(" oneFace = oneCell.GetFace(ii)\n")
2598 pfLns.append(" returnCountPerFace.append(self.GetNumberOfCellsTouchingFace(oneFace))\n")
2599 pfLns.append(" return returnCountPerFace\n")
2600 pfLns.append(" def GetListOfExteriorFacesOnCell(self, oneCell):\n")
2601 pfLns.append(" returnExteriorFaceIndices = []\n")
2602 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2603 pfLns.append(" for ii in range(0, numFaces):\n")
2604 pfLns.append(" oneFace = oneCell.GetFace(ii)\n")
2605 pfLns.append(" if self.GetNumberOfCellsTouchingFace(oneFace) == 1:\n")
2606 pfLns.append(" returnExteriorFaceIndices.append(ii)\n")
2607 pfLns.append(" return returnExteriorFaceIndices\n")
2608 pfLns.append(" def GetListOfExteriorFacesOnCellByIndex(self, cellIndex):\n")
2609 pfLns.append(" return self.GetListOfExteriorFacesOnCell(self.vtkGrid.GetCell(cellIndex))\n")
2610 pfLns.append("def PhactoriCountCellTouchingEachFace(inInputCsData):\n")
2611 pfLns.append(" countCellsTouchingEachFace = PhactoriCountCellsTouchingFaceData(inInputCsData)\n")
2612 pfLns.append(" countCellsTouchingEachFace.DoCountForAllCellsInBlock()\n")
2613 pfLns.append(" return countCellsTouchingEachFace\n")
2614 pfLns.append("def PhactoriCountCellTouchingEachPoint(inInputCsData):\n")
2615 pfLns.append(" numCells = inInputCsData.GetNumberOfCells()\n")
2616 pfLns.append(" numPoints = inInputCsData.GetNumberOfPoints()\n")
2617 pfLns.append(" cellsTouchingPointCount = [0] * numPoints\n")
2618 pfLns.append(" for ii in range(0, numCells):\n")
2619 pfLns.append(" oneCell = inInputCsData.GetCell(ii)\n")
2620 pfLns.append(" cellPointIds = oneCell.GetPointIds()\n")
2621 pfLns.append(" numCellPoints = oneCell.GetNumberOfPoints()\n")
2622 pfLns.append(" for jj in range(0, numCellPoints):\n")
2623 pfLns.append(" oneCellPointId = cellPointIds.GetId(jj)\n")
2624 pfLns.append(" cellsTouchingPointCount[oneCellPointId] += 1\n")
2625 pfLns.append(" return cellsTouchingPointCount\n")
2626 pfLns.append("def PhactoriSurfaceCornerCellFaceFacesExterior(oneFace, cellsTouchingPointCount):\n")
2627 pfLns.append(" numFacePoints = oneFace.GetNumberOfPoints()\n")
2628 pfLns.append(" facePointIds = oneFace.GetPointIds()\n")
2629 pfLns.append(" numOutsideVertices = 0\n")
2630 pfLns.append(" for ii in range(0, numFacePoints):\n")
2631 pfLns.append(" if cellsTouchingPointCount[facePointIds.GetId(ii)] <= 1:\n")
2632 pfLns.append(" return True\n")
2633 pfLns.append(" return False\n")
2634 pfLns.append("def PhactoriIsOutsideCornerHexCellFaceMaxAreaFace(oneCell, indexFaceListSize,\n")
2635 pfLns.append(" sortedFaceSizeList, cellsTouchingPointCount, TestNthLargestFace = 2):\n")
2636 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2637 pfLns.append(" for faceIndex in range(0, numFaces):\n")
2638 pfLns.append(" oneFace = oneCell.GetFace(faceIndex)\n")
2639 pfLns.append(" if PhactoriSurfaceCornerCellFaceFacesExterior(oneFace, cellsTouchingPointCount):\n")
2640 pfLns.append(" if indexFaceListSize[faceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:\n")
2641 pfLns.append(" return True\n")
2642 pfLns.append(" return False\n")
2643 pfLns.append("def PhactoriSurfaceEdgeHexCellFaceFacesExterior(oneFace, cellsTouchingPointCount):\n")
2644 pfLns.append(" numFacePoints = oneFace.GetNumberOfPoints()\n")
2645 pfLns.append(" facePointIds = oneFace.GetPointIds()\n")
2646 pfLns.append(" numOutsideVertices = 0\n")
2647 pfLns.append(" for ii in range(0, numFacePoints):\n")
2648 pfLns.append(" if cellsTouchingPointCount[facePointIds.GetId(ii)] <= 2:\n")
2649 pfLns.append(" numOutsideVertices += 1\n")
2650 pfLns.append(" return (numOutsideVertices >= 2)\n")
2651 pfLns.append("def PhactoriIsOutsideEdgeHexCellFaceMaxAreaFace(oneCell,\n")
2652 pfLns.append(" indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount,\n")
2653 pfLns.append(" TestNthLargestFace = 2):\n")
2654 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2655 pfLns.append(" for faceIndex in range(0, numFaces):\n")
2656 pfLns.append(" oneFace = oneCell.GetFace(faceIndex)\n")
2657 pfLns.append(" if PhactoriSurfaceEdgeHexCellFaceFacesExterior(oneFace, cellsTouchingPointCount):\n")
2658 pfLns.append(" if indexFaceListSize[faceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:\n")
2659 pfLns.append(" return True\n")
2660 pfLns.append(" return False\n")
2661 pfLns.append("def PhactoriIsOutsideSurfaceHexCellFaceMaxAreaFace(oneCell,\n")
2662 pfLns.append(" indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount,\n")
2663 pfLns.append(" TestNthLargestFace = 2):\n")
2664 pfLns.append(" numFaces = oneCell.GetNumberOfFaces()\n")
2665 pfLns.append(" for faceIndex in range(0, numFaces):\n")
2666 pfLns.append(" oneFace = oneCell.GetFace(faceIndex)\n")
2667 pfLns.append(" numFacePoints = oneFace.GetNumberOfPoints()\n")
2668 pfLns.append(" facePtNdxs = oneFace.GetPointIds()\n")
2669 pfLns.append(" outsideFaceIndex = -1\n")
2670 pfLns.append(" for jj in range(0, numFacePoints):\n")
2671 pfLns.append(" outsideFaceIndex = faceIndex\n")
2672 pfLns.append(" ptNdx = facePtNdxs.GetId(jj)\n")
2673 pfLns.append(" if cellsTouchingPointCount[ptNdx] != 4:\n")
2674 pfLns.append(" outsideFaceIndex = -1\n")
2675 pfLns.append(" break\n")
2676 pfLns.append(" if outsideFaceIndex >= 0:\n")
2677 pfLns.append(" break\n")
2678 pfLns.append(" if outsideFaceIndex < 0:\n")
2679 pfLns.append(" return False\n")
2680 pfLns.append(" if indexFaceListSize[outsideFaceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:\n")
2681 pfLns.append(" return True\n")
2682 pfLns.append(" else:\n")
2683 pfLns.append(" return False\n")
2684 pfLns.append("def PhactoriFindSurfaceStatusForOneCellUsingFaceInfo(inInputCsData,\n")
2685 pfLns.append(" inCellIndex, countCellsTouchingEachFace, flatnessTestRatio = 100.0,\n")
2686 pfLns.append(" TestNthLargestFace = 2):\n")
2687 pfLns.append(" oneCell = inInputCsData.GetCell(inCellIndex)\n")
2688 pfLns.append(" exteriorFaceList = countCellsTouchingEachFace.GetListOfExteriorFacesOnCell(oneCell)\n")
2689 pfLns.append(" numExteriorFaces = len(exteriorFaceList)\n")
2690 pfLns.append(" if numExteriorFaces == 0:\n")
2691 pfLns.append(" retStatus = 1\n")
2692 pfLns.append(" else:\n")
2693 pfLns.append(" indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)\n")
2694 pfLns.append(" flatnessRatio = sortedFaceSizeList[-1] / sortedFaceSizeList[0]\n")
2695 pfLns.append(" if len(sortedFaceSizeList) <= 0:\n")
2696 pfLns.append(" retStatus = 11\n")
2697 pfLns.append(" return retStatus\n")
2698 pfLns.append(" cellIsFlat = (flatnessRatio >= flatnessTestRatio)\n")
2699 pfLns.append(" outsideFaceIsMaxAreaFace = False\n")
2700 pfLns.append(" for outsideFaceIndex in exteriorFaceList:\n")
2701 pfLns.append(" if indexFaceListSize[outsideFaceIndex] >= sortedFaceSizeList[-TestNthLargestFace]:\n")
2702 pfLns.append(" outsideFaceIsMaxAreaFace = True\n")
2703 pfLns.append(" break\n")
2704 pfLns.append(" if numExteriorFaces == 1:\n")
2705 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2706 pfLns.append(" if cellIsFlat:\n")
2707 pfLns.append(" retStatus = 11\n")
2708 pfLns.append(" else:\n")
2709 pfLns.append(" retStatus = 8\n")
2710 pfLns.append(" else:\n")
2711 pfLns.append(" if cellIsFlat:\n")
2712 pfLns.append(" retStatus = 5\n")
2713 pfLns.append(" else:\n")
2714 pfLns.append(" retStatus = 2\n")
2715 pfLns.append(" elif numExteriorFaces == 2:\n")
2716 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2717 pfLns.append(" if cellIsFlat:\n")
2718 pfLns.append(" retStatus = 12\n")
2719 pfLns.append(" else:\n")
2720 pfLns.append(" retStatus = 9\n")
2721 pfLns.append(" else:\n")
2722 pfLns.append(" if cellIsFlat:\n")
2723 pfLns.append(" retStatus = 6\n")
2724 pfLns.append(" else:\n")
2725 pfLns.append(" retStatus = 3\n")
2726 pfLns.append(" else:\n")
2727 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2728 pfLns.append(" if cellIsFlat:\n")
2729 pfLns.append(" retStatus = 13\n")
2730 pfLns.append(" else:\n")
2731 pfLns.append(" retStatus = 10\n")
2732 pfLns.append(" else:\n")
2733 pfLns.append(" if cellIsFlat:\n")
2734 pfLns.append(" retStatus = 7\n")
2735 pfLns.append(" else:\n")
2736 pfLns.append(" retStatus = 4\n")
2737 pfLns.append(" return retStatus\n")
2738 pfLns.append("def PhactoriFindSurfaceStatusForOneCell(inInputCsData, inCellIndex,\n")
2739 pfLns.append(" cellsTouchingPointCount, flatnessTestRatio = 100.0):\n")
2740 pfLns.append(" oneCell = inInputCsData.GetCell(inCellIndex)\n")
2741 pfLns.append(" numPoints = oneCell.GetNumberOfPoints()\n")
2742 pfLns.append(" pointIds = oneCell.GetPointIds()\n")
2743 pfLns.append(" minCtpc = 9\n")
2744 pfLns.append(" for ii in range(0, numPoints):\n")
2745 pfLns.append(" testCtpc = cellsTouchingPointCount[pointIds.GetId(ii)]\n")
2746 pfLns.append(" if testCtpc < minCtpc:\n")
2747 pfLns.append(" minCtpc = testCtpc\n")
2748 pfLns.append(" if inCellIndex == 5056:\n")
2749 pfLns.append(" debugFlag = 100\n")
2750 pfLns.append(" else:\n")
2751 pfLns.append(" debugFlag = 25\n")
2752 pfLns.append(" if minCtpc >= 8:\n")
2753 pfLns.append(" retStatus = 1\n")
2754 pfLns.append(" else:\n")
2755 pfLns.append(" indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)\n")
2756 pfLns.append(" flatnessRatio = sortedFaceSizeList[-1] / sortedFaceSizeList[0]\n")
2757 pfLns.append(" if len(sortedFaceSizeList) <= 0:\n")
2758 pfLns.append(" retStatus = 11\n")
2759 pfLns.append(" return retStatus\n")
2760 pfLns.append(" cellIsFlat = (flatnessRatio >= flatnessTestRatio)\n")
2761 pfLns.append(" if minCtpc >= 4:\n")
2762 pfLns.append(" outsideFaceIsMaxAreaFace = PhactoriIsOutsideSurfaceHexCellFaceMaxAreaFace(\n")
2763 pfLns.append(" oneCell, indexFaceListSize, sortedFaceSizeList,\n")
2764 pfLns.append(" cellsTouchingPointCount)\n")
2765 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2766 pfLns.append(" if cellIsFlat:\n")
2767 pfLns.append(" retStatus = 11\n")
2768 pfLns.append(" else:\n")
2769 pfLns.append(" retStatus = 8\n")
2770 pfLns.append(" else:\n")
2771 pfLns.append(" if cellIsFlat:\n")
2772 pfLns.append(" retStatus = 5\n")
2773 pfLns.append(" else:\n")
2774 pfLns.append(" retStatus = 2\n")
2775 pfLns.append(" elif minCtpc >= 2:\n")
2776 pfLns.append(" outsideFaceIsMaxAreaFace = PhactoriIsOutsideEdgeHexCellFaceMaxAreaFace(\n")
2777 pfLns.append(" oneCell, indexFaceListSize, sortedFaceSizeList,\n")
2778 pfLns.append(" cellsTouchingPointCount)\n")
2779 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2780 pfLns.append(" if cellIsFlat:\n")
2781 pfLns.append(" retStatus = 12\n")
2782 pfLns.append(" else:\n")
2783 pfLns.append(" retStatus = 9\n")
2784 pfLns.append(" else:\n")
2785 pfLns.append(" if cellIsFlat:\n")
2786 pfLns.append(" retStatus = 6\n")
2787 pfLns.append(" else:\n")
2788 pfLns.append(" retStatus = 3\n")
2789 pfLns.append(" elif minCtpc >= 1:\n")
2790 pfLns.append(" outsideFaceIsMaxAreaFace = PhactoriIsOutsideCornerHexCellFaceMaxAreaFace(\n")
2791 pfLns.append(" oneCell, indexFaceListSize, sortedFaceSizeList, cellsTouchingPointCount)\n")
2792 pfLns.append(" if outsideFaceIsMaxAreaFace:\n")
2793 pfLns.append(" if cellIsFlat:\n")
2794 pfLns.append(" retStatus = 13\n")
2795 pfLns.append(" else:\n")
2796 pfLns.append(" retStatus = 10\n")
2797 pfLns.append(" else:\n")
2798 pfLns.append(" if cellIsFlat:\n")
2799 pfLns.append(" retStatus = 7\n")
2800 pfLns.append(" else:\n")
2801 pfLns.append(" retStatus = 4\n")
2802 pfLns.append(" else:\n")
2803 pfLns.append(" retStatus = -1\n")
2804 pfLns.append(" return retStatus\n")
2805 pfLns.append("def PhactoriGetCellEdgeVector(inInputCsData, oneFaceOrCell, edgeIndex):\n")
2806 pfLns.append(" oneFaceEdgePointIds = oneFaceOrCell.GetEdge(edgeIndex).GetPointIds()\n")
2807 pfLns.append(" ptA = inInputCsData.GetPoint(oneFaceEdgePointIds.GetId(0))\n")
2808 pfLns.append(" ptB = inInputCsData.GetPoint(oneFaceEdgePointIds.GetId(1))\n")
2809 pfLns.append(" retVec = vecFromAToB(ptA,ptB)\n")
2810 pfLns.append(" return retVec\n")
2811 pfLns.append("def PhactoriFindFaceNormal(inInputCsData, oneFace):\n")
2812 pfLns.append(" facePointIds = oneFace.GetPointIds()\n")
2813 pfLns.append(" ptA = inInputCsData.GetPoint(facePointIds.GetId(0))\n")
2814 pfLns.append(" ptB = inInputCsData.GetPoint(facePointIds.GetId(1))\n")
2815 pfLns.append(" ptC = inInputCsData.GetPoint(facePointIds.GetId(2))\n")
2816 pfLns.append(" vecAB = vecFromAToB(ptA, ptB)\n")
2817 pfLns.append(" vecBC = vecFromAToB(ptB, ptC)\n")
2818 pfLns.append(" retNormalVec = vecCrossProduct(vecBC, vecAB)\n")
2819 pfLns.append(" vecNormalize2(retNormalVec, retNormalVec)\n")
2820 pfLns.append(" return retNormalVec\n")
2821 pfLns.append("def PhactoriFindLargestCellFaceNormal(inInputCsData, oneCell):\n")
2822 pfLns.append(" indexFaceListSize, sortedFaceSizeList = PhactoriCalculateCellFaceAreasAndSort(inInputCsData, oneCell)\n")
2823 pfLns.append(" biggestFaceSize = sortedFaceSizeList[-1]\n")
2824 pfLns.append(" for faceForNormalIndex in range(0, len(indexFaceListSize)):\n")
2825 pfLns.append(" if indexFaceListSize[faceForNormalIndex] == biggestFaceSize:\n")
2826 pfLns.append(" break\n")
2827 pfLns.append(" faceForNormal = oneCell.GetFace(faceForNormalIndex)\n")
2828 pfLns.append(" retNormalVec = PhactoriFindFaceNormal(inInputCsData, faceForNormal)\n")
2829 pfLns.append(" return retNormalVec\n")
2830 pfLns.append("def PhactoriFindSelectedAngleBetweenEdgeAndCellNormal(inInputCsData, oneCell,\n")
2831 pfLns.append(" compareNormal, paramUseSmallestAngle, paramOffsetIndex):\n")
2832 pfLns.append(" edgeCompareDotProdList = []\n")
2833 pfLns.append(" numEdges = oneCell.GetNumberOfEdges()\n")
2834 pfLns.append(" for ii in range(0, numEdges):\n")
2835 pfLns.append(" oneEdgeVec = PhactoriGetCellEdgeVector(inInputCsData, oneCell, ii)\n")
2836 pfLns.append(" vecNormalize2(oneEdgeVec, oneEdgeVec)\n")
2837 pfLns.append(" edgeCompareDotProd = abs(vecDotProduct(compareNormal, oneEdgeVec))\n")
2838 pfLns.append(" edgeCompareDotProdList.append(edgeCompareDotProd)\n")
2839 pfLns.append(" sortedEdgeCompareDotProdList = sorted(edgeCompareDotProdList)\n")
2840 pfLns.append(" if paramUseSmallestAngle:\n")
2841 pfLns.append(" outputIndex = max(0, numEdges - 1 - paramOffsetIndex)\n")
2842 pfLns.append(" else:\n")
2843 pfLns.append(" outputIndex = min(paramOffsetIndex, numEdges - 1)\n")
2844 pfLns.append(" outputAngle = 90.0 - math.degrees(math.acos(sortedEdgeCompareDotProdList[outputIndex]))\n")
2845 pfLns.append(" return outputAngle\n")
2846 pfLns.append("def PhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal):\n")
2847 pfLns.append(" numCellEdges = oneCell.GetNumberOfEdges()\n")
2848 pfLns.append(" retHeight = -1.0 \n")
2849 pfLns.append(" for ii in range(0, numCellEdges):\n")
2850 pfLns.append(" oneCellEdgeVec = PhactoriGetCellEdgeVector(inInputCsData, oneCell, ii)\n")
2851 pfLns.append(" dp1 = vecDotProduct(oneCellEdgeVec, compareNormal)\n")
2852 pfLns.append(" projectedVec = vecScale(dp1, compareNormal)\n")
2853 pfLns.append(" oneCellEdgeHeight = vecMagnitude(projectedVec)\n")
2854 pfLns.append(" if oneCellEdgeHeight > retHeight:\n")
2855 pfLns.append(" retHeight = oneCellEdgeHeight\n")
2856 pfLns.append(" return retHeight\n")
2857 pfLns.append("def PhactoriFindCellEdgeAngleMetricsForOneCell(inInputCsData, inCellIndex,\n")
2858 pfLns.append(" paramUseSmallestAngle, paramOffsetIndex):\n")
2859 pfLns.append(" oneCell = inInputCsData.GetCell(inCellIndex)\n")
2860 pfLns.append(" numEdges = oneCell.GetNumberOfEdges()\n")
2861 pfLns.append(" if numEdges < 6:\n")
2862 pfLns.append(" return 90.0, 0.0\n")
2863 pfLns.append(" if oneCell.GetNumberOfFaces() < 4:\n")
2864 pfLns.append(" return 90.0, 0.0\n")
2865 pfLns.append(" compareNormal = PhactoriFindLargestCellFaceNormal(inInputCsData, oneCell)\n")
2866 pfLns.append(" retAngle = PhactoriFindSelectedAngleBetweenEdgeAndCellNormal(inInputCsData,\n")
2867 pfLns.append(" oneCell, compareNormal, paramUseSmallestAngle, paramOffsetIndex)\n")
2868 pfLns.append(" retHeight = PhactoriFindHeightOfCell(inInputCsData, oneCell, compareNormal)\n")
2869 pfLns.append(" return retAngle, retHeight\n")
2870
2871 #phactori_combine_to_single_python_file_subpiece_end_1
2872
2873 #phactori_combine_to_single_python_file_parent_1
2874 #from Operation.PhactoriParaviewMultiBlockRecursion import *
2875 #phactori_combine_to_single_python_file_subpiece_begin_1
2876 class PhactoriParaviewMultiBlockRecursionControl:
2877 "see PhactoriDoParaviewMultiblockRecursion();\n mOperationPerBlock should be set to a method\n which takes 1 parameter, mParameters should be set to the parameter\n instance which will be passed to the mOperationPerBlock call"
2878 def __init__(self):
2879 self.mOperationToDoPerBlock = None
2880 self.mParameters = None
2881
2882 def PhactroiParaviewDoMethodPerBlockRecurse1(inInputCsData, inRecursionControlItem):
2883 "PhactroiParaviewDoMethodPerBlockRecurse1 is a generic method for doing recursion through\n the multiblock dataset and doing something (a callback) on a per leaf block\n basis. Called by PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter which got clientside data and calls\n itself on internal nodes and calls\n inRecursionControlItem.mOperationToDoPerBlock on leaf block nodes"
2884 if PhactoriDbg(100):
2885 myDebugPrint3('PhactroiParaviewDoMethodPerBlockRecurse1 entered\n', 100)
2886
2887 icsdClassname = inInputCsData.GetClassName()
2888 if icsdClassname == "vtkMultiBlockDataSet" or \
2889 icsdClassname == "vtkExodusIIMultiBlockDataSet":
2890 myDebugPrint3('recursing: ' + icsdClassname + '\n')
2891 numBlocks = inInputCsData.GetNumberOfBlocks()
2892 for ii in range(0, numBlocks):
2893 oneBlock = inInputCsData.GetBlock(ii)
2894 if PhactoriDbg(100):
2895 DebugPrintBlockName(inInputCsData, ii)
2896 if(oneBlock != None):
2897 PhactroiParaviewDoMethodPerBlockRecurse1(oneBlock, inRecursionControlItem)
2898 else:
2899 inRecursionControlItem.mOperationToDoPerBlock(inRecursionControlItem, inInputCsData,
2900 inRecursionControlItem.mParameters)
2901
2902 if PhactoriDbg(100):
2903 myDebugPrint3('PhactroiParaviewDoMethodPerBlockRecurse1 returning\n', 100)
2904
2905 def DebugPrintBlockName(csData, blockIndex):
2906 if PhactoriDbg(100):
2907 oneBlock = csData.GetBlock(blockIndex)
2908 if oneBlock != None:
2909 oneBlockMetaData = csData.GetMetaData(blockIndex)
2910 if oneBlockMetaData != None:
2911 #myDebugPrint3("oneBlockMetaData: " + str(oneBlockMetaData) + "\n")
2912 theBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME())
2913 myDebugPrint3("block index, name: " + str(blockIndex) + ", " + str(theBlockName) + "\n")
2914 else:
2915 myDebugPrint3("oneBlockMetaData is None (1)\n")
2916 else:
2917 myDebugPrint3("this block is None, now check meta data\n")
2918 oneBlockMetaData = csData.GetMetaData(blockIndex)
2919 if oneBlockMetaData != None:
2920 #myDebugPrint3("oneBlockMetaData: " + str(oneBlockMetaData) + "\n")
2921 theBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME())
2922 myDebugPrint3("block index, name (2): " + str(blockIndex) + ", " + str(theBlockName) + "\n")
2923 else:
2924 myDebugPrint3("oneBlockMetaData is None (2)\n")
2925
2926 def PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(inRecursionControlItem, inPvFilter):
2927 "grab client side data object, and use that to do recursion"
2928 pvClientSideData = inPvFilter.GetClientSideObject().GetOutputDataObject(0)
2929 if pvClientSideData == None:
2930 if PhactoriDbg(100):
2931 myDebugPrint3(
2932 'DoMethodPerBlock: pvClientSideData is None, returning',100)
2933 return
2934
2935 PhactroiParaviewDoMethodPerBlockRecurse1(pvClientSideData, inRecursionControlItem)
2936
2937 class PrintPointAndCellArrayInformationRecursionParams:
2938 def __init__(self):
2939 self.leafVisitCount = 0
2940
2941 def PrintPointAndCellArrayInformationInBlock(recursionObject, inInputCsData, inParameters):
2942 inParameters.leafVisitCount += 1
2943 myDebugPrint3("inParameters.leafVisitCount " + str(inParameters.leafVisitCount) + "\n")
2944
2945 celldata = inInputCsData.GetCellData()
2946 numcellarrays = celldata.GetNumberOfArrays()
2947 myDebugPrint3("number of cell data arrays: " + str(numcellarrays) + "\n")
2948 numcelltuples = celldata.GetNumberOfTuples()
2949 myDebugPrint3("number of cell data tuples: " + str(numcelltuples) + "\n")
2950 for ii in range(0, numcellarrays):
2951 myDebugPrint3(str(ii) + ": " + str(celldata.GetArray(ii).GetNumberOfComponents()) + ": " + str(celldata.GetArrayName(ii)) + "\n")
2952
2953 pointdata = inInputCsData.GetPointData()
2954 numpointarrays = pointdata.GetNumberOfArrays()
2955 myDebugPrint3("number of point data arrays: " + str(numpointarrays) + "\n")
2956 numpointtuples = pointdata.GetNumberOfTuples()
2957 myDebugPrint3("number of point data tuples: " + str(numpointtuples) + "\n")
2958 for ii in range(0, numpointarrays):
2959 myDebugPrint3(str(ii) + ": " + str(pointdata.GetArray(ii).GetNumberOfComponents()) + ": " + str(pointdata.GetArrayName(ii)) + "\n")
2960
2961 def RecursivelyPrintPointAndCellArrayInformation(pvFilter):
2962 if PhactoriDbg(100):
2963 myDebugPrint3("RecursivelyPrintPointAndCellArrayInformation entered\n")
2964
2965 recursionParams = PrintPointAndCellArrayInformationRecursionParams()
2966 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
2967 recursionObj.mParameters = recursionParams
2968 recursionObj.mOperationToDoPerBlock = PrintPointAndCellArrayInformationInBlock
2969
2970 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, pvFilter)
2971 if PhactoriDbg(100):
2972 myDebugPrint3("RecursivelyPrintPointAndCellArrayInformation returning\n")
2973
2974 #phactori_combine_to_single_python_file_subpiece_end_1
2975
2976 #phactori_combine_to_single_python_file_parent_1
2977 #from Operation.PhactoriOutputFileNameAndDirectoryManager import *
2978 #phactori_combine_to_single_python_file_subpiece_begin_1
2979 class PhactoriOutputFileNameAndDirectoryManager():
2980 def __init__(self, defaultBasename, defaultBasedirectory, defaultNumCounterDigits, defaultExtension):
2981 self.Basename = defaultBasename
2982 self.Basedirectory = defaultBasedirectory
2983 self.NumCounterDigits = defaultNumCounterDigits
2984 self.Extension = defaultExtension
2985
2986 def ParseOutputFileNameControl(self, inJson, keyPrefix):
2987 key1 = keyPrefix + "basename"
2988 if key1 in inJson:
2989 self.Basename = inJson[key1]
2990 key1 = keyPrefix + "basedirectory"
2991 if key1 in inJson:
2992 self.Basedirectory = inJson[key1]
2993 key1 = keyPrefix + "counterdigits"
2994 if key1 in inJson:
2995 self.NumCounterDigits = inJson[key1]
2996 key1 = keyPrefix + "extension"
2997 if key1 in inJson:
2998 self.Extension = inJson[key1]
2999
3000 def GetOutputFilePath(self, counterValue, extraBasename):
3001 if counterValue < 0:
3002 counterValue = 0
3003 retName = self.Basedirectory + "/" + self.Basename + extraBasename + \
3004 str(counterValue).zfill(self.NumCounterDigits) + self.Extension
3005 return retName
3006 #phactori_combine_to_single_python_file_subpiece_end_1
3007
3008 class PhactoriRenderViewInfo:
3009 def __init__(self):
3010 self.RenderView1 = None
3011 self.DataRepresentation1 = None
3012
3013 #class PhactoriRenderViewInfo:
3014 # RenderView1 = None
3015 # DataRepresentation1 = None
3016
3017
3018 global PhactoriRenderViewInfoList
3019 PhactoriRenderViewInfoList = []
3020
3021 global currentPhactoriRenderViewInfo
3022 currentPhactoriRenderViewInfo = None
3023
3024 phactoriFilterMap = {}
3025
3026 def AddFilterToFilterMap(inFilterName, inFilter):
3027 if PhactoriDbg(100):
3028 myDebugPrint3('AddFilterToFilterMap entered\n', 100)
3029 global phactoriFilterMap
3030 phactoriFilterMap[inFilterName] = inFilter
3031 count = 0
3032 for ii in phactoriFilterMap.keys():
3033 if PhactoriDbg():
3034 myDebugPrint3(str(count) + ': ' + ii + ' : ' + str(phactoriFilterMap[ii]) + '\n')
3035 count += 1
3036 if PhactoriDbg(100):
3037 myDebugPrint3('AddFilterToFilterMap returning\n', 100)
3038
3039 def SafeColorBy(inDataRepresentation, ptOrNodeAndVarname):
3040 if True:
3041 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
3042 return
3043 if PhactoriDbg(100):
3044 myDebugPrint3("SafeColorBy entered: " + str(ptOrNodeAndVarname) + "\n")
3045 if ptOrNodeAndVarname[1] == "":
3046 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
3047 if PhactoriDbg(100):
3048 myDebugPrint3("SafeColorBy returning (no variable)\n")
3049 return
3050
3051 ptOrNode = ptOrNodeAndVarname[0]
3052 if ptOrNode == gPointsString:
3053 pointData = inDataRepresentation.PointData
3054 if pointData == None:
3055 ColorBy(inDataRepresentation, (gCellsString, ''))
3056 if PhactoriDbg(100):
3057 myDebugPrint3("SafeColorBy returning (pointData was None)\n")
3058 return
3059 if pointData.Proxy == None:
3060 ColorBy(inDataRepresentation, (gCellsString, ''))
3061 if PhactoriDbg(100):
3062 myDebugPrint3("SafeColorBy returning (pointData.Proxy was None)\n")
3063 return
3064 theFieldData = pointData.GetFieldData()
3065 if theFieldData == None:
3066 ColorBy(inDataRepresentation, (gCellsString, ''))
3067 if PhactoriDbg(100):
3068 myDebugPrint3("SafeColorBy returning (theFieldData was None)\n")
3069 return
3070 if theFieldData.Proxy == None:
3071 ColorBy(inDataRepresentation, (gCellsString, ''))
3072 if PhactoriDbg(100):
3073 myDebugPrint3("SafeColorBy returning (theFieldData.Proxy was None)\n")
3074 return
3075 if pointData.GetNumberOfArrays() <= 0:
3076 ColorBy(inDataRepresentation, (gPointsString, ''))
3077 if PhactoriDbg(100):
3078 myDebugPrint3("SafeColorBy returning (no point data arrays)\n")
3079 return
3080 onePointArray = pointData.GetArray(ptOrNodeAndVarname[1])
3081 if onePointArray == None:
3082 ColorBy(inDataRepresentation, (gPointsString, ''))
3083 if PhactoriDbg(100):
3084 myDebugPrint3("SafeColorBy returning (no point array with given name)\n")
3085 return
3086 if onePointArray.GetNumberOfTuples() <= 0:
3087 ColorBy(inDataRepresentation, (gPointsString, ''))
3088 if PhactoriDbg(100):
3089 myDebugPrint3("SafeColorBy returning (zero tuples in point data array)\n")
3090 return
3091 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
3092 if PhactoriDbg(100):
3093 myDebugPrint3("SafeColorBy returning (valid point data)\n")
3094 return
3095 else:
3096 cellData = inDataRepresentation.CellData
3097 if cellData == None:
3098 ColorBy(inDataRepresentation, (gCellsString, ''))
3099 if PhactoriDbg(100):
3100 myDebugPrint3("SafeColorBy returning (cellData was None)\n")
3101 return
3102 if cellData.Proxy == None:
3103 ColorBy(inDataRepresentation, (gCellsString, ''))
3104 if PhactoriDbg(100):
3105 myDebugPrint3("SafeColorBy returning (cellData.Proxy was None)\n")
3106 return
3107 if PhactoriDbg(100):
3108 myDebugPrint3("cellData.Proxy: " + str(cellData.Proxy) + "\n")
3109 myDebugPrint3("cellData.OutputPort: " + str(cellData.OutputPort) + "\n")
3110 myDebugPrint3("cellData.FieldData: " + str(cellData.FieldData) + "\n")
3111 if cellData.OutputPort == None:
3112 ColorBy(inDataRepresentation, (gCellsString, ''))
3113 if PhactoriDbg(100):
3114 myDebugPrint3("SafeColorBy returning (cellData.OutputPort was None)\n")
3115 return
3116 if cellData.FieldData == None:
3117 ColorBy(inDataRepresentation, (gCellsString, ''))
3118 if PhactoriDbg(100):
3119 myDebugPrint3("SafeColorBy returning (cellData.FieldData was None)\n")
3120 return
3121 dataInformation = cellData.Proxy.GetDataInformation(cellData.OutputPort)
3122 myDebugPrint3("dataInformation: " + str(dataInformation) + "\n")
3123 if dataInformation == None:
3124 ColorBy(inDataRepresentation, (gCellsString, ''))
3125 if PhactoriDbg(100):
3126 myDebugPrint3("SafeColorBy returning (dataInformation was None)\n")
3127 return
3128 theFieldData = cellData.GetFieldData()
3129 if theFieldData == None:
3130 ColorBy(inDataRepresentation, (gCellsString, ''))
3131 if PhactoriDbg(100):
3132 myDebugPrint3("SafeColorBy returning (theFieldData was None)\n")
3133 return
3134 if theFieldData.Proxy == None:
3135 ColorBy(inDataRepresentation, (gCellsString, ''))
3136 if PhactoriDbg(100):
3137 myDebugPrint3("SafeColorBy returning (theFieldData.Proxy was None)\n")
3138 return
3139 if cellData.GetNumberOfArrays() <= 0:
3140 ColorBy(inDataRepresentation, (gCellsString, ''))
3141 if PhactoriDbg(100):
3142 myDebugPrint3("SafeColorBy returning (no cell data arrays)\n")
3143 return
3144 oneCellArray = cellData.GetArray(ptOrNodeAndVarname[1])
3145 if oneCellArray == None:
3146 ColorBy(inDataRepresentation, (gCellsString, ''))
3147 if PhactoriDbg(100):
3148 myDebugPrint3("SafeColorBy returning (no cell array with given name)\n")
3149 return
3150 if oneCellArray.GetNumberOfTuples() <= 0:
3151 ColorBy(inDataRepresentation, (gCellsString, ''))
3152 if PhactoriDbg(100):
3153 myDebugPrint3("SafeColorBy returning (zero tuples in cell data array)\n")
3154 return
3155 ColorBy(inDataRepresentation, ptOrNodeAndVarname)
3156 if PhactoriDbg(100):
3157 myDebugPrint3("SafeColorBy returning (valid cell data)\n")
3158 return
3159
3160
3161 def SetDataRepresentationToDefault(inDataRepresentation):
3162
3163 #a3_vel__PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] )
3164
3165 inDataRepresentation.SelectionPointLabelColor = [0.5, 0.5, 0.5]
3166 inDataRepresentation.SelectionPointFieldDataArrayName = 'displ'
3167 inDataRepresentation.SuppressLOD = 0
3168 global gParaViewCatalystVersionFlag
3169 if gParaViewCatalystVersionFlag < 51000:
3170 inDataRepresentation.BlockVisibility = []
3171 inDataRepresentation.BlockOpacity = {}
3172 inDataRepresentation.BlockColor = {}
3173 inDataRepresentation.Position = [0.0, 0.0, 0.0]
3174 inDataRepresentation.BackfaceRepresentation = 'Follow Frontface'
3175 inDataRepresentation.SelectionOpacity = 1.0
3176 inDataRepresentation.SelectionPointLabelShadow = 0
3177 inDataRepresentation.OrientationMode = 'Direction'
3178 inDataRepresentation.ScaleMode = 'No Data Scaling Off'
3179 inDataRepresentation.Diffuse = 1.0
3180 inDataRepresentation.SelectionUseOutline = 0
3181 inDataRepresentation.SelectionPointLabelFormat = ''
3182 #shininess alteration, 1.0 is shiny
3183 inDataRepresentation.Specular = 0.1
3184 #inDataRepresentation.Specular = 1.0
3185 inDataRepresentation.SelectionVisibility = 1
3186 inDataRepresentation.InterpolateScalarsBeforeMapping = 1
3187 #inDataRepresentation.CustomRangeActive = [0, 0, 0]
3188 inDataRepresentation.Origin = [0.0, 0.0, 0.0]
3189 inDataRepresentation.Scale = [1.0, 1.0, 1.0]
3190 inDataRepresentation.SelectionCellLabelJustification = 'Left'
3191 inDataRepresentation.DiffuseColor = [1.0, 1.0, 1.0]
3192 inDataRepresentation.SelectionCellLabelOpacity = 1.0
3193 #inDataRepresentation.Source = []
3194 inDataRepresentation.Masking = 0
3195 inDataRepresentation.Opacity = 1.0
3196 inDataRepresentation.LineWidth = 1.0
3197 inDataRepresentation.MeshVisibility = 0
3198 inDataRepresentation.Visibility = 1
3199 inDataRepresentation.SelectionCellLabelFontSize = 18
3200 inDataRepresentation.SelectionPointLabelJustification = 'Left'
3201 #inDataRepresentation.OriginalBoundsRangeActive = [0, 0, 0]
3202 inDataRepresentation.SelectionPointLabelVisibility = 0
3203 inDataRepresentation.SelectOrientationVectors = ''
3204 inDataRepresentation.BackfaceDiffuseColor = [1.0, 1.0, 1.0]
3205 inDataRepresentation.SelectionPointLabelFontFamily = 'Arial'
3206 inDataRepresentation.SelectScaleArray = ''
3207
3208 if gParaViewCatalystVersionFlag <= 40100:
3209 inDataRepresentation.ColorAttributeType = gPointsString
3210 else:
3211 inDataRepresentation.RescaleTransferFunctionToDataRange(False)
3212 SafeColorBy(inDataRepresentation, (gPointsString,''))
3213 inDataRepresentation.RescaleTransferFunctionToDataRange(False)
3214
3215 #inDataRepresentation.AxesOrigin = [0.0, 0.0, 0.0]
3216 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]
3217 #shininess alteration, 40.0 is shiny
3218 inDataRepresentation.SpecularPower = 100.0
3219 #inDataRepresentation.SpecularPower = 40.0
3220 inDataRepresentation.Texture = []
3221 inDataRepresentation.SelectionCellLabelShadow = 0
3222 inDataRepresentation.AmbientColor = [1.0, 1.0, 1.0]
3223 inDataRepresentation.MapScalars = 1
3224 inDataRepresentation.PointSize = 2.0
3225 inDataRepresentation.SelectionCellLabelFormat = ''
3226 inDataRepresentation.Scaling = 0
3227 inDataRepresentation.StaticMode = 0
3228 inDataRepresentation.SelectionCellLabelColor = [0.0, 1.0, 0.0]
3229 inDataRepresentation.EdgeColor = [0.0, 0.0, 0.5000076295109483]
3230 inDataRepresentation.SelectionCellLabelVisibility = 0
3231 inDataRepresentation.NonlinearSubdivisionLevel = 1
3232 inDataRepresentation.Representation = 'Surface'
3233 #inDataRepresentation.CustomRange = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
3234 #inDataRepresentation.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
3235 inDataRepresentation.Orientation = [0.0, 0.0, 0.0]
3236 #inDataRepresentation.ScalarOpacityUnitDistance = 0.8230042761351323
3237 inDataRepresentation.BackfaceOpacity = 1.0
3238 inDataRepresentation.SelectionPointLabelFontSize = 18
3239 inDataRepresentation.SelectionCellFieldDataArrayName = 'GlobalElementId'
3240 inDataRepresentation.SelectionColor = [1.0, 0.0, 1.0]
3241 inDataRepresentation.Ambient = 0.0
3242 inDataRepresentation.ScaleFactor = 0.775
3243 inDataRepresentation.BackfaceAmbientColor = [1.0, 1.0, 1.0]
3244 #inDataRepresentation.ScalarOpacityFunction = a3_vel__PiecewiseFunction
3245 inDataRepresentation.SelectMaskArray = ''
3246 inDataRepresentation.SelectionLineWidth = 2.0
3247 inDataRepresentation.Interpolation = 'Gouraud'
3248 #inDataRepresentation.SelectMapper = 'Projected tetra'
3249 inDataRepresentation.SelectionCellLabelFontFamily = 'Arial'
3250 inDataRepresentation.SelectionCellLabelItalic = 0
3251 #inDataRepresentation.ExtractedBlockIndex = 2
3252 inDataRepresentation.SelectionPointLabelOpacity = 1.0
3253 #inDataRepresentation.UseAxesOrigin = 0
3254 inDataRepresentation.Pickable = 1
3255 #inDataRepresentation.CustomBoundsActive = [0, 0, 0]
3256 inDataRepresentation.SelectionRepresentation = 'Wireframe'
3257 inDataRepresentation.SelectionPointLabelBold = 0
3258 #inDataRepresentation.ColorArrayName = 'vel'
3259 inDataRepresentation.SelectionPointLabelItalic = 0
3260 #shininess alteration, 1 is shiny
3261 if gParaViewCatalystVersionFlag <= 40100:
3262 inDataRepresentation.AllowSpecularHighlightingWithScalarColoring = 0
3263 #inDataRepresentation.AllowSpecularHighlightingWithScalarColoring = 1
3264 inDataRepresentation.SpecularColor = [1.0, 1.0, 1.0]
3265 #inDataRepresentation.LookupTable = a3_vel__PVLookupTable
3266 inDataRepresentation.SelectionPointSize = 5.0
3267 inDataRepresentation.SelectionCellLabelBold = 0
3268 inDataRepresentation.Orient = 0
3269
3270 def PvSetupProperty(prop):
3271 domain = prop.FindDomain("vtkSMProxyListDomain")
3272 domain.SetDefaultValues(prop.SMProperty, False)
3273 prop.GetParent().UpdateVTKObjects()
3274
3275 def SetAxesGridVisibility(inPvRenderView, inSetting):
3276 if inPvRenderView.AxesGrid == None:
3277 PvSetupProperty(inPvRenderView.GetProperty("AxesGrid"))
3278 if inSetting:
3279 inPvRenderView.AxesGrid.Visibility = True
3280 else:
3281 inPvRenderView.AxesGrid.Visibility = False
3282 if PhactoriDbg(100):
3283 myDebugPrint3("SetAxesGridVisibility() AxesGrid.Visibility now " + \
3284 str(inPvRenderView.AxesGrid.Visibility) + "\n", 100)
3285
3286 def AddRenderView(inPhactoriImagesetInfo, inColorSettings,
3287 ImageBaseFileName, ImageType, ImageOverwriteFlag, PixelSizeX, PixelSizeY,
3288 numCounterDigits, inIsPlotFlag):
3289
3290 global localCpViews
3291 global PhactoriRenderViewInfoList
3292 global currentPhactoriRenderViewInfo
3293 global gParaViewCatalystVersionFlag
3294
3295 if PhactoriDbg(100):
3296 myDebugPrint3("AddRenderView entered\n", 100)
3297
3298 newPhactoriRenderViewInfo = PhactoriRenderViewInfo()
3299
3300 if ImageBaseFileName == None:
3301 image_base_name = "image_" + str(len(PhactoriRenderViewInfoList))
3302 else:
3303 image_base_name = ImageBaseFileName
3304
3305 if ImageOverwriteFlag:
3306 image_base_name += "." + ImageType
3307 if PhactoriDbg():
3308 myDebugPrint3("image " + image_base_name + " will be overwritten repeatedly\n")
3309 else:
3310 image_base_name += "%t." + ImageType
3311
3312 #image_base_name = "image_" + str(len(PhactoriRenderViewInfoList)) + "_%t.png"
3313
3314 #RenderView1 = CreateCPView( CreateRenderView, image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY, localCpViews )
3315 myDebugPrint3("about to create view and representation:\n"
3316 "current active source: " + str(GetActiveSource()) + "\n")
3317
3318 global localCoProcessorReference
3319
3320 global gSharedRenderView
3321 global gSharedLineChartView
3322 if inIsPlotFlag:
3323 if gSharedLineChartView == None:
3324 #gSharedLineChartView = localCoProcessorReference.CreateView("XYChartView",
3325 # image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY)
3326 gSharedLineChartView = CreateView("XYChartView")
3327 gSharedLineChartView.ViewSize = [PixelSizeX, PixelSizeY]
3328 #gSharedLineChartView.LeftAxisRangeMinimum = -1.0
3329 #gSharedLineChartView.LeftAxisRangeMaximum = 1.0
3330 #gSharedLineChartView.BottomAxisRangeMaximum = -2.0
3331 #gSharedLineChartView.RightAxisRangeMaximum = 2.0
3332 #gSharedLineChartView.TopAxisRangeMaximum = 2.0
3333 RenderView1 = gSharedLineChartView
3334 else:
3335 if gSharedRenderView == None:
3336 #if True:
3337 #import pdb
3338 #pdb.set_trace()
3339
3340 gSharedRenderView = localCoProcessorReference.CreateView(CreateRenderView,
3341 image_base_name, 1, 0, 1, PixelSizeX, PixelSizeY)
3342
3343 RenderView1 = gSharedRenderView
3344
3345 inPhactoriImagesetInfo.mSharedPvRenderView2 = RenderView1
3346
3347 RenderView1.add_attribute("cpNumCounterDigits", numCounterDigits)
3348 RenderView1.add_attribute("outputResultsBlockCountId", GetCurrentOutputResultsBlockCountId())
3349 RenderView1.add_attribute("associatedImagesetName",
3350 inPhactoriImagesetInfo.mName)
3351
3352 if inIsPlotFlag == False:
3353 if gParaViewCatalystVersionFlag < 50502:
3354 RenderView1.LightSpecularColor = [1.0, 1.0, 1.0]
3355 RenderView1.LightIntensity = 1.0
3356 RenderView1.UseOffscreenRendering = 0
3357 RenderView1.UseOffscreenRenderingForScreenshots = 0
3358 RenderView1.LightDiffuseColor = [1.0, 1.0, 1.0]
3359 RenderView1.LightAmbientColor = [1.0, 1.0, 1.0]
3360 RenderView1.LightType = 'HeadLight'
3361 RenderView1.LightSwitch = 0
3362 RenderView1.UseOutlineForLODRendering = 0
3363 RenderView1.KeyLightAzimuth = 10.0
3364 RenderView1.UseLight = 1
3365 RenderView1.CameraPosition = [3.681775921856809, 3.2427490288581042, 6.445486324396935]
3366 RenderView1.FillLightKFRatio = 3.0
3367 RenderView1.Background2 = [0.0, 0.0, 0.165]
3368 RenderView1.FillLightAzimuth = -10.0
3369 RenderView1.LODResolution = 0.5
3370 RenderView1.BackgroundTexture = []
3371 RenderView1.InteractionMode = '3D'
3372 RenderView1.StencilCapable = 1
3373 RenderView1.CameraFocalPoint = [0.010957598686218262, 0.0, 3.6478042602539035e-05]
3374 RenderView1.ImageReductionFactor = 2
3375 RenderView1.CameraViewAngle = 30.0
3376 RenderView1.CameraParallelScale = 2.0952221328924265
3377 RenderView1.EyeAngle = 2.0
3378 RenderView1.HeadLightKHRatio = 3.0
3379 RenderView1.StereoRender = 0
3380 RenderView1.KeyLightIntensity = 0.75
3381 RenderView1.BackLightAzimuth = 110.0
3382 RenderView1.OrientationAxesInteractivity = 0
3383 if gParaViewCatalystVersionFlag <= 40100:
3384 RenderView1.UseInteractiveRenderingForSceenshots = 0
3385 RenderView1.Background = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052]
3386 RenderView1.NonInteractiveRenderDelay = 0.0
3387 RenderView1.CenterOfRotation = [-1.9375, 0.0, 2.125]
3388 RenderView1.CameraParallelProjection = 0
3389 RenderView1.CompressorConfig = 'vtkSquirtCompressor 0 3'
3390 RenderView1.HeadLightWarmth = 0.5
3391 RenderView1.MaximumNumberOfPeels = 4
3392 RenderView1.StereoType = 'Red-Blue'
3393 RenderView1.DepthPeeling = 1
3394 RenderView1.BackLightKBRatio = 3.5
3395 if gParaViewCatalystVersionFlag <= 40100:
3396 RenderView1.StereoCapableWindow = 1
3397 RenderView1.CameraViewUp = [-0.03140411320843562, 0.899940306729304, -0.43488070317911115]
3398 RenderView1.RemoteRenderThreshold = 20.0
3399 RenderView1.CacheKey = 1.0
3400 RenderView1.UseCache = 0
3401 RenderView1.KeyLightElevation = 50.0
3402 RenderView1.CenterAxesVisibility = 0
3403 RenderView1.MaintainLuminance = 0
3404 RenderView1.StillRenderImageReductionFactor = 1
3405 RenderView1.BackLightWarmth = 0.5
3406 RenderView1.FillLightElevation = -75.0
3407 RenderView1.MultiSamples = 0
3408 RenderView1.FillLightWarmth = 0.4
3409 RenderView1.AlphaBitPlanes = 1
3410 RenderView1.OrientationAxesVisibility = 1
3411 #RenderView1.CameraClippingRange = [8.69340289149996, 31.15868708101818]
3412 RenderView1.BackLightElevation = 0.0
3413 #RenderView1.ViewTime = 0.00403844503897222
3414 #RenderView1.ViewTime = 0.0
3415 RenderView1.OrientationAxesOutlineColor = [1.0, 1.0, 1.0]
3416 RenderView1.LODThreshold = 5.0
3417 RenderView1.CollectGeometryThreshold = 100.0
3418 RenderView1.KeyLightWarmth = 0.6
3419 RenderView1.OrientationAxesLabelColor = [1.0, 1.0, 1.0]
3420 #RenderView1.OrientationAxesLabelColor = inColorSettings.mOrientationAxesLabelColor
3421 #rigid_body_impact_6_ff_e = CreateProducer( datadescription, "input" )
3422
3423 if gParaViewCatalystVersionFlag < 51000:
3424 RenderView1.UseTexturedBackground = 0
3425 RenderView1.UseGradientBackground = 0
3426
3427 SetAxesGridVisibility(RenderView1, 0)
3428
3429 SetActiveView(RenderView1)
3430
3431 if inPhactoriImagesetInfo.mPvDataRepresentation2 == None:
3432 if inIsPlotFlag:
3433 if inPhactoriImagesetInfo.m_PlotType == "PhactoriPlotOverTimeBlock":
3434 DataRepresentation1 = Show(UseIndexForXAxis = 0, XArrayName = "Time",
3435 AttributeType = "Row Data")
3436 #DataRepresentation1.AttributeType = "Row Data"
3437 if PhactoriDbg():
3438 myDebugPrint3("representation made for plot over time:\n" + \
3439 str(DataRepresentation1) + "\n")
3440 #DataRepresentation1.UseIndexForXAxis = 0
3441 #DataRepresentation1.XArrayName = "Time"
3442 elif inPhactoriImagesetInfo.m_PlotType == "PhactoriScatterPlotBlock":
3443 yvarStr = GetThresholdContourHackVariableNameString(
3444 inPhactoriImagesetInfo.m_YAxisVariableInfo)
3445 xvarStr = GetThresholdContourHackVariableNameString(
3446 inPhactoriImagesetInfo.m_XAxisVariableInfo)
3447 visvars = [yvarStr]
3448 atrtype = "Point Data"
3449 if inPhactoriImagesetInfo.m_YAxisVariableInfo.mVariableType == 'element':
3450 atrtype = "Cell Data"
3451 DataRepresentation1 = Show(inPhactoriImagesetInfo.m_producer,
3452 gSharedLineChartView, SeriesVisibility = visvars,
3453 UseIndexForXAxis = 0, XArrayName = xvarStr,
3454 AttributeType = atrtype)
3455 #DataRepresentation1.AttributeType = "Cell Data"
3456 #DataRepresentation1.XArrayName = 'carea'
3457 #DataRepresentation1.SeriesVisibility = ['vel__Magnitude (block_2)']
3458 #DataRepresentation1.SeriesVisibility = ['vel__Magnitude (Element Blocks)']
3459 if PhactoriDbg():
3460 myDebugPrint3("representation made for scatter plot:\n" + str(DataRepresentation1) + "\n")
3461 myDebugPrint3("m_producer for scatter plot:\n" + str(inPhactoriImagesetInfo.m_producer) + "\n")
3462 myDebugPrint3("rep input num points " + str(DataRepresentation1.Input.GetDataInformation().DataInformation.GetNumberOfPoints()) + "\n")
3463 myDebugPrint3("DataRepresentation1.ListProperties() " + str(DataRepresentation1.ListProperties()) + "\n")
3464 myDebugPrint3("DataRepresentation1.Input " + str(DataRepresentation1.Input) + "\n")
3465 myDebugPrint3("DataRepresentation1.AttributeType " + str(DataRepresentation1.AttributeType) + "\n")
3466 myDebugPrint3("DataRepresentation1.UseIndexForXAxis " + str(DataRepresentation1.UseIndexForXAxis) + "\n")
3467 myDebugPrint3("DataRepresentation1.Visibility " + str(DataRepresentation1.Visibility) + "\n")
3468 myDebugPrint3("DataRepresentation1.XArrayName " + str(DataRepresentation1.XArrayName) + "\n")
3469 myDebugPrint3("DataRepresentation1.SeriesVisibility " + str(DataRepresentation1.SeriesVisibility) + "\n")
3470 myDebugPrint3("DataRepresentation1.SeriesLabel " + str(DataRepresentation1.SeriesLabel) + "\n")
3471 myDebugPrint3("DataRepresentation1.SeriesColor " + str(DataRepresentation1.SeriesColor) + "\n")
3472 myDebugPrint3("DataRepresentation1.SeriesPlotCorner " + str(DataRepresentation1.SeriesPlotCorner) + "\n")
3473 myDebugPrint3("DataRepresentation1.SeriesLabelPrefix " + str(DataRepresentation1.SeriesLabelPrefix) + "\n")
3474 myDebugPrint3("DataRepresentation1.SeriesLineStyle " + str(DataRepresentation1.SeriesLineStyle) + "\n")
3475 myDebugPrint3("DataRepresentation1.SeriesLineThickness " + str(DataRepresentation1.SeriesLineThickness) + "\n")
3476 myDebugPrint3("DataRepresentation1.SeriesMarkerStyle " + str(DataRepresentation1.SeriesMarkerStyle) + "\n")
3477 for ii in range(1, len(DataRepresentation1.SeriesLineStyle), 2):
3478 DataRepresentation1.SeriesLineStyle[ii] = '0'
3479 for ii in range(1, len(DataRepresentation1.SeriesMarkerStyle), 2):
3480 DataRepresentation1.SeriesMarkerStyle[ii] = '4'
3481 else:
3482 myDebugPrint3AndException("bad m_PlotType")
3483 else:
3484 SetParaViewViewToCurrentTime(RenderView1)
3485 DataRepresentation1 = Show(GetActiveSource(), RenderView1, 'UnstructuredGridRepresentation')
3486 if PhactoriDbg():
3487 myDebugPrint3("representation made for 3d view:\n" + str(DataRepresentation1) + "\n")
3488 inPhactoriImagesetInfo.mPvDataRepresentation2 = DataRepresentation1
3489 inPhactoriImagesetInfo.mVisiblePvDataReps[0] = DataRepresentation1
3490 else:
3491 DataRepresentation1 = inPhactoriImagesetInfo.mPvDataRepresentation2
3492
3493 if PhactoriDbg():
3494 myDebugPrint3("new DataRepresentation1: " + str(DataRepresentation1) + "\n")
3495 if PhactoriDbg():
3496 myDebugPrint3("new DataRepresentation1 input: " + str(DataRepresentation1.Input) + "\n")
3497
3498 if inIsPlotFlag == False:
3499 SetDataRepresentationToDefault(DataRepresentation1)
3500 inColorSettings.SetParaviewRvRepColors(RenderView1, DataRepresentation1)
3501
3502 newPhactoriRenderViewInfo.RenderView1 = RenderView1
3503 newPhactoriRenderViewInfo.DataRepresentation1 = DataRepresentation1
3504
3505 currentPhactoriRenderViewInfo = newPhactoriRenderViewInfo
3506 PhactoriRenderViewInfoList.append(newPhactoriRenderViewInfo)
3507
3508 if len(inPhactoriImagesetInfo.mVisibleOps) > 1:
3509 savedActiveSourceA = GetActiveSource()
3510 for ii in range(1,len(inPhactoriImagesetInfo.mVisibleOps)):
3511 if inPhactoriImagesetInfo.mVisiblePvDataReps[ii] == None:
3512 SetActiveSource(inPhactoriImagesetInfo.mVisibleOps[ii].\
3513 mParaViewFilter)
3514 newPvDataRep = Show(GetActiveSource(), RenderView1, 'UnstructuredGridRepresentation')
3515 SetDataRepresentationToDefault(newPvDataRep)
3516 inPhactoriImagesetInfo.mVisiblePvDataReps[ii] = newPvDataRep
3517 if PhactoriDbg(100):
3518 myDebugPrint3("added extra newPvDataRep " + str(ii) + "\n"
3519 "newPvDataRep:\n" + str(newPvDataRep) + "\n")
3520
3521 SetActiveSource(savedActiveSourceA)
3522
3523
3524 if PhactoriDbg(100):
3525 myDebugPrint3("AddRenderView returning\n", 100)
3526
3527 def SetCameraViewExplicitly(theRenderView, EyePosition,
3528 LookAtPoint = None,
3529 ClippingRange = None,
3530 ViewUpVector = [0.0, 1.0, 0.0],
3531 inCameraViewAngle = 30.0,
3532 ViewBounds = None,
3533 inPhactoriCamera = None,
3534 inUseParallelProjection = False,
3535 inParallelScale = 1.0):
3536 "Sets the camera view explicitly by specifing the camera position " \
3537 "(EyePosition), focal point (LookAtPoint), clipping range min/man " \
3538 "(ClippingRange), up view vector (ViewUpVector) " \
3539 "example: SetCameraViewExplicitly(oneRenderView, [100.0, 90.0, 70.0], " \
3540 " [0.0, 0.0, 0.0], [5.0, 200.0], [0.0, 1.0, 0.0]) " \
3541 "If ViewBounds is None and LookAtPoint is None, the global Data Bounds " \
3542 "Will be obtained by a GetGlobalDataBoundsParallel call to put the " \
3543 "LookAtPoint in the center of the data bounds. If LookAtPoint is not " \
3544 "None, ViewBounds is not used; If LookAtPoint is None and ViewBounds " \
3545 "is not None, ViewBounds will be used and GetGlobalDataBoundsParallel " \
3546 "will not be called (to save mpi calls)"
3547 if PhactoriDbg(100):
3548 myDebugPrint3('phactori.SetCameraViewExplicitly entered\n', 100)
3549
3550 if(LookAtPoint == None):
3551 if ViewBounds == None:
3552 ViewBounds = GetGlobalDataBoundsParallel()
3553 LookAtPoint = [ (ViewBounds[1] + ViewBounds[0]) * 0.5, \
3554 (ViewBounds[3] + ViewBounds[2]) * 0.5, \
3555 (ViewBounds[5] + ViewBounds[4]) * 0.5 ]
3556
3557 if inPhactoriCamera != None:
3558 inPhactoriCamera.mOffAxisProjectionInfo.SetUpIfEnabled(theRenderView,
3559 EyePosition, LookAtPoint, ViewUpVector)
3560
3561 if(ClippingRange == None):
3562 #if PhactoriDbg(100):
3563 # myDebugPrint3('ClippingRange was None, must calculate\n', 100)
3564 xdelta = LookAtPoint[0] - EyePosition[0]
3565 ydelta = LookAtPoint[1] - EyePosition[1]
3566 zdelta = LookAtPoint[2] - EyePosition[2]
3567 delta = math.sqrt(xdelta*xdelta + ydelta*ydelta + zdelta*zdelta)
3568 #ClippingRange = [delta * 0.05, delta * 2.0]
3569 ClippingRange = [delta * 0.01, delta * 10.0]
3570
3571 #ClippingRange[0] *= 0.01
3572 #if PhactoriDbg(100):
3573 # myDebugPrint3("CameraClippingRange (A): " + str(ClippingRange) + "\n")
3574 # myDebugPrint3("CameraClippingRange (B): " + str(theRenderView.CameraClippingRange) + "\n")
3575 #ClippingRange[0] *= 1000.0
3576 #ClippingRange[1] *= 0.1
3577
3578 theRenderView.CameraPosition = EyePosition
3579 theRenderView.CameraFocalPoint = LookAtPoint
3580
3581 if inUseParallelProjection == True:
3582 theRenderView.CameraParallelProjection = 1
3583 theRenderView.CameraParallelScale = inParallelScale
3584 if PhactoriDbg(100):
3585 myDebugPrint3('CameraParallelProjection: 1\n')
3586 myDebugPrint3('CameraParallelScale: ' + str(inParallelScale) + '\n')
3587 else:
3588 theRenderView.CameraParallelProjection = 0
3589 #theRenderView.CameraClippingRange = ClippingRange
3590
3591 theRenderView.CameraViewUp = ViewUpVector
3592 theRenderView.CenterOfRotation = LookAtPoint
3593 theRenderView.CameraViewAngle = inCameraViewAngle
3594
3595 if PhactoriDbg(100):
3596 myDebugPrint3("CameraPosition: " + str(EyePosition) + "\n"
3597 "CameraFocalPoint: " + str(LookAtPoint) + "\n"
3598 "CameraClippingRange (C): " + str(ClippingRange) + "\n"
3599 "CameraViewUp: " + str(ViewUpVector) + "\n"
3600 "CenterOfRotation: " + str(LookAtPoint) + "\n"
3601 "CameraViewAngle: " + str(inCameraViewAngle) + "\n")
3602
3603 if PhactoriDbg(100):
3604 myDebugPrint3('phactori.SetCameraViewExplicitly returning\n', 100)
3605
3606 #could do this different/better
3607 def CheckForParallelVector(vec1, vec2):
3608 if PhactoriDbg():
3609 myDebugPrint3("CheckForParallelVector: " + str(vec1) + " " + str(vec2) + "\n")
3610 maxcmpnt = 0
3611 maxval = abs(vec1[0])
3612 if(abs(vec1[1]) > maxval):
3613 maxcmpnt = 1
3614 maxval = abs(vec1[1])
3615 if(abs(vec1[2]) > maxval):
3616 maxcmpnt = 2
3617 maxval = abs(vec1[2])
3618 if PhactoriDbg():
3619 myDebugPrint3("maxcmpnt for vec1: " + str(maxcmpnt) + "\n")
3620 if vec2[maxcmpnt] == 0.0:
3621 if PhactoriDbg():
3622 myDebugPrint3("vec2 is zero there, not parallel\n")
3623 return False
3624 ratio = vec1[maxcmpnt] / vec2[maxcmpnt]
3625 for ii in [0,1,2]:
3626 tt1 = vec2[ii] * ratio
3627 if(abs(tt1 - vec1[ii]) > 0.000001):
3628 if PhactoriDbg():
3629 myDebugPrint3("vec2 component " + str(ii) + " is different, not parallel\n")
3630 return False
3631 if PhactoriDbg():
3632 myDebugPrint3("same ratio between vectors, parallel\n")
3633 return True
3634
3635 #given a bounds in the form [xmin, xmax, ymin, ymax, zmin, zmax], return the
3636 # maximum dimension out of all those (max of xmax-xmin, ymax-ymin, and
3637 # zmax-zmin)
3638 def GetMaximumDimensionFromBounds(inBounds):
3639 maxDim = inBounds[1] - inBounds[0]
3640 testDim = inBounds[3] - inBounds[2]
3641 if(testDim > maxDim):
3642 maxDim = testDim
3643 testDim = inBounds[5] - inBounds[4]
3644 if(testDim > maxDim):
3645 maxDim = testDim
3646 return maxDim
3647
3648 def SetCameraLookAtPointAndLookDirection(inParaViewRenderView, \
3649 inLookDirection, \
3650 inImageSettings, \
3651 inFocalPoint = None, \
3652 inEyeToFocalPointDistance = None, \
3653 inEyePositionFactor = 1.0, \
3654 inViewUp=[0.0,1.0,0.0], \
3655 inCameraViewAngle = 30.0, \
3656 inViewBounds = None,
3657 inPhactoriCamera = None):
3658 "Set up camera with position, look at point, and positioning factor\n\n Sets the current camera view by looking at a focal point (inFocalPoint)\n along a specified vector (inLookDirection). The distance from the focal\n point is set using twice the largest of the data bounding box dimensions\n multiplied by inEyePositionFactor. To see the whole of the data,\n inEyePositionFactor can be about 1.0, although trying different values\n will give you different filling of the screen and 'zooming' into the focal\n point, while values greater than 1.0 can be used to zoom out, possibly to\n bring the entire dataset into the image. If inEyeToFocalPointDistance is\n something other than None, this distance will be used instead of the\n bounding box of the data. If inFocalPoint is None, then\n the center of the data bounds will be used as a focal point. inViewBounds\n allows calling routine to pass along data bounds or other viewing bounds\n which are used to calculate the viewing distance from the focal point\n and the focal point if they are not supplied. If inEyeToFocalPointDistance\n is not None and inFocalPoint is not None, than inViewBounds will not\n be used and the global data bounds will not be obtained.\n example: SetCameraLookAtPointAndLookDirection([5.0, 4.0, 3.0],\n [1.0, 1.0, 1.0], 1.5, [0.0, 1.0, 0.0])\n "
3659
3660 if PhactoriDbg(100):
3661 myDebugPrint3("SetCameraLookAtPointAndLookDirection entered\n", 100);
3662
3663 #check for look view up same as look direction
3664 #need to do better check here
3665 if CheckForParallelVector(inLookDirection, inViewUp):
3666 inViewUp = [0.0, 0.0, 1.0]
3667 if CheckForParallelVector(inLookDirection, inViewUp):
3668 inViewUp = [0.0, 1.0, 0.0]
3669
3670 #find maximum data dimension, then multiply by inEyePositionFactor
3671 if(inFocalPoint == None):
3672 if inViewBounds == None:
3673 inViewBounds = GetGlobalDataBoundsParallel()
3674 inFocalPoint = [ (inViewBounds[1] + inViewBounds[0]) * 0.5, \
3675 (inViewBounds[3] + inViewBounds[2]) * 0.5, \
3676 (inViewBounds[5] + inViewBounds[4]) * 0.5 ]
3677
3678 if inEyeToFocalPointDistance != None:
3679 eyeToFocalPointDistance = inEyeToFocalPointDistance
3680 else:
3681 if inViewBounds == None:
3682 inViewBounds = GetGlobalDataBoundsParallel()
3683 #eyeToFocalPointDistance = GetMaximumDimensionFromBounds(inViewBounds)
3684 #eyeToFocalPointDistance *= inEyePositionFactor
3685 eyeToFocalPointDistance = CalcRelativeCameraDistance2(inFocalPoint,
3686 inLookDirection, inViewUp, inCameraViewAngle, inImageSettings,
3687 inViewBounds)
3688 eyeToFocalPointDistance *= inEyePositionFactor
3689
3690
3691 if PhactoriDbg():
3692 myDebugPrint3(" eyeToFocalPointDistance: " + str(eyeToFocalPointDistance) + "\n")
3693 if PhactoriDbg():
3694 myDebugPrint3(" inFocalPoint: " + str(inFocalPoint) + "\n")
3695 if PhactoriDbg():
3696 myDebugPrint3(" inLookDirection: " + str(inLookDirection) + "\n")
3697 if PhactoriDbg():
3698 myDebugPrint3(" inEyePositionFactor: " + str(inEyePositionFactor) + "\n")
3699 if PhactoriDbg():
3700 myDebugPrint3(" inViewUp: " + str(inViewUp) + "\n")
3701
3702 #find eye position based on focal point, distance to eye point, and look direction
3703 xx = inLookDirection[0]
3704 yy = inLookDirection[1]
3705 zz = inLookDirection[2]
3706 lookDirectionMagnitude = math.sqrt(xx*xx + yy*yy + zz*zz)
3707 #lookDirectionMagnitude = 1.0
3708 if PhactoriDbg():
3709 myDebugPrint3(" lookDirectionMagnitude: " + str(lookDirectionMagnitude) + "\n")
3710 xx = xx / lookDirectionMagnitude
3711 yy = yy / lookDirectionMagnitude
3712 zz = zz / lookDirectionMagnitude
3713 eyePosition = [inFocalPoint[0] - xx * eyeToFocalPointDistance, \
3714 inFocalPoint[1] - yy * eyeToFocalPointDistance, \
3715 inFocalPoint[2] - zz * eyeToFocalPointDistance]
3716 if PhactoriDbg():
3717 myDebugPrint3(" eyePosition: " + str(eyePosition) + "\n")
3718
3719
3720 useNewClippingCalc = True
3721 if useNewClippingCalc:
3722 eyeToFocalPointDist = vecDistance(eyePosition, inFocalPoint)
3723 clippingRange = [0.01 * eyeToFocalPointDist, 100.0 * eyeToFocalPointDist]
3724 else:
3725 clippingRange = [0.01 * lookDirectionMagnitude, 100.0 * lookDirectionMagnitude]
3726
3727 localUseParallelProjection = False
3728 localParallelScale = 1.0
3729 if inPhactoriCamera != None:
3730 if inPhactoriCamera.mUseParallelProjection:
3731 localUseParallelProjection = True
3732 if inPhactoriCamera.mParallelScaleAbsoluteOrRelative == 0:
3733 localParallelScale = inPhactoriCamera.mParallelScale
3734 if PhactoriDbg():
3735 myDebugPrint3("absolute parallel scale: " + \
3736 str(localParallelScale) + "\n")
3737 else:
3738 if inViewBounds == None:
3739 inViewBounds = GetGlobalDataBoundsParallel()
3740 #for relative case, we are using the diagonal of the
3741 #bounding box to determine the parallel scale; other algorithms might
3742 #be to use the longest bounding box side, or determine all bounding
3743 #box corner positions from camera position and use the greatest
3744 #vertical or horizontal extent of those points
3745 dimx = inViewBounds[1] - inViewBounds[0]
3746 dimy = inViewBounds[3] - inViewBounds[2]
3747 dimz = inViewBounds[5] - inViewBounds[4]
3748 maxbbdim = math.sqrt(dimx*dimx + dimy*dimy + dimz*dimz)
3749 localParallelScale = maxbbdim * 0.5 * 1.05
3750 localParallelScale *= inPhactoriCamera.mParallelScale
3751 if PhactoriDbg():
3752 myDebugPrint3("relative parallel scale: " + \
3753 str(localParallelScale) + "\n")
3754
3755 SetCameraViewExplicitly(inParaViewRenderView, eyePosition, inFocalPoint,
3756 clippingRange, inViewUp, inCameraViewAngle, inViewBounds,
3757 inPhactoriCamera, localUseParallelProjection, localParallelScale)
3758
3759 if inPhactoriCamera != None:
3760 inPhactoriCamera.HandleLockingOption(eyePosition, inFocalPoint)
3761
3762 if PhactoriDbg(100):
3763 myDebugPrint3("SetCameraLookAtPointAndLookDirection returning\n", 100)
3764
3765
3766 global gLocalProcessId
3767 gLocalProcessId = -1
3768 global gNumberOfProcesses
3769 gNumberOfProcesses = -1
3770
3771 def SmartGetLocalProcessId():
3772 global gLocalProcessId
3773 #myDebugPrint3("SmartGetLocalProcessId entered\n", 100)
3774 if gLocalProcessId != -1:
3775 #print "gLocalProcessId already known: " + str(gLocalProcessId)
3776 return gLocalProcessId
3777 global gNumberOfProcesses
3778 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
3779 globalController = pm.GetGlobalController()
3780 gLocalProcessId = globalController.GetLocalProcessId()
3781 gNumberOfProcesses = globalController.GetNumberOfProcesses()
3782 #print "gLocalProcessId found: " + str(gLocalProcessId)
3783 #myDebugPrint3("exiting SmartGetLocalProcessId\n")
3784 return gLocalProcessId
3785
3786 def SmartGetNumberOfProcesses():
3787 global gNumberOfProcesses
3788 if gNumberOfProcesses != -1:
3789 return gNumberOfProcesses
3790 global gLocalProcessId
3791 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
3792 globalController = pm.GetGlobalController()
3793 gLocalProcessId = globalController.GetLocalProcessId()
3794 gNumberOfProcesses = globalController.GetNumberOfProcesses()
3795 return gNumberOfProcesses
3796
3797 #phactori_combine_to_single_python_file_parent_1
3798 #from Operation.PhactoriDataArtifactMetaDataControl import *
3799 #phactori_combine_to_single_python_file_subpiece_begin_1
3800
3801 class PhactoriDataArtifactMetaDataControl:
3802 def __init__(self, myProcessId, numProcesses):
3803 self.outputEnabled = True
3804 self.artifactListCsvFileName = None
3805 self.artifactListCsvFileHandle = None
3806 self.artifactListTryOpenCount = 0
3807 self.thisProcessIsWritingProcess = -1
3808 if myProcessId == int(numProcesses/2):
3809 self.thisProcessIsWritingProcess = 1
3810 else:
3811 self.thisProcessIsWritingProcess = 0
3812 if PhactoriDbg(100):
3813 myDebugPrint3("PhactoriDataArtifactMetaDataControl:__init__ " + \
3814 str(myProcessId) + ", " + str(numProcesses) + ", " + \
3815 str(self.thisProcessIsWritingProcess) + "\n", 100)
3816
3817 def EnableOutput(self, onOff):
3818 self.outputEnabled = onOff
3819
3820 def CloseFiles(self):
3821 if self.artifactListCsvFileHandle != None:
3822 self.artifactListCsvFileHandle.close()
3823
3824 def ThisProcessIsWritingProcess(self):
3825 return self.thisProcessIsWritingProcess > 0
3826
3827 def DataArtifactOutputListOpen(self):
3828 if self.artifactListCsvFileHandle == None:
3829 if self.artifactListTryOpenCount > 0:
3830 return False
3831 self.artifactListTryOpenCount += 1
3832 myNow = datetime.datetime.now()
3833 myFormat = "%Y-%m-%d-%H:%M:%S"
3834 self.artifactListCsvFileName = "DataArtifactList_" + myNow.strftime(myFormat) + ".csv"
3835 self.artifactListCsvFileHandle = open(self.artifactListCsvFileName, "w")
3836 if self.artifactListCsvFileHandle == None:
3837 print("AddImageToDataArtifactOutputList: unable to open file:\n",
3838 self.artifactListCsvFileName)
3839 return False
3840 return True
3841
3842 def CheckIfDoOutput(self):
3843 if self.outputEnabled == False:
3844 return False
3845
3846 if self.ThisProcessIsWritingProcess() == False:
3847 return False
3848
3849 if self.DataArtifactOutputListOpen() == False:
3850 return False
3851
3852 return True
3853
3854 def AddDataArtifactToDataArtifactOutputList(self, fileName):
3855
3856 if self.CheckIfDoOutput() == False:
3857 return
3858
3859 myNow = datetime.datetime.now()
3860 outDate = str(myNow)
3861 outStr = fileName + "," + outDate + "\n"
3862 self.artifactListCsvFileHandle.write(outStr)
3863 self.artifactListCsvFileHandle.flush()
3864
3865 def AddDataExportToDataArtifactOutputList(self, fileName):
3866 self.AddDataArtifactToDataArtifactOutputList(fileName)
3867
3868 def AddImageToDataArtifactOutputList(self, fileName):
3869 self.AddDataArtifactToDataArtifactOutputList(fileName)
3870
3871 if __name__ == '__main__':
3872 pdamdc = PhactoriDataArtifactMetaDataControl(1,2)
3873 pdamdc.AddImageToDataArtifactOutputList("CatalystOutput/test1.png")
3874 pdamdc.AddDataExportToDataArtifactOutputList("CatalystVtkDataOutput/test2.vtm")
3875
3876 #phactori_combine_to_single_python_file_subpiece_end_1
3877
3878 global gPhactoriDataArtifactTracker
3879 gPhactoriDataArtifactTracker = None
3880
3881 def GetGlobalDataArtifactTracker():
3882 global gPhactoriDataArtifactTracker
3883 if gPhactoriDataArtifactTracker == None:
3884 gPhactoriDataArtifactTracker = PhactoriDataArtifactMetaDataControl(
3885 SmartGetLocalProcessId(), SmartGetNumberOfProcesses())
3886 return gPhactoriDataArtifactTracker
3887
3888 def UseMPIToFillInSharedListNPerProcess(
3889 inThisProcVtkArray, inCountPerProc, outVtkArray, vtkArrayTypeIndex):
3890 "given a list of N values on each process fill in on each process a list\n which contains all the entries from each process\n (i.e. it is N * number_of_processes long)\n will work on either vtkDoubleArray types or vtkIntArray types, with\n vtkArrayTypeIndex = 0 for vtkIntArray types and 1 for vtkDoubleArray\n types"
3891
3892 mypid = SmartGetLocalProcessId()
3893
3894 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
3895 globalController = pm.GetGlobalController()
3896 #gLocalProcessId = globalController.GetLocalProcessId()
3897 numproc = globalController.GetNumberOfProcesses()
3898 if PhactoriDbg(100):
3899 myDebugPrint3("mypid: " + str(mypid) + " numproc: " + str(numproc) + \
3900 " count: " + str(inCountPerProc) + "\n")
3901
3902 outVtkArray.SetNumberOfValues(inCountPerProc * numproc)
3903
3904 if vtkArrayTypeIndex == 0:
3905 fromRemoteProcList = vtk.vtkIntArray()
3906 else:
3907 fromRemoteProcList = vtk.vtkDoubleArray()
3908
3909 for ii in range(0,numproc):
3910 prndx = ii * inCountPerProc
3911 if ii == mypid:
3912 globalController.Broadcast(inThisProcVtkArray, ii)
3913 for jj in range(0,inCountPerProc):
3914 outVtkArray.SetValue(prndx + jj, inThisProcVtkArray.GetValue(jj))
3915 else:
3916 fromRemoteProcList.SetNumberOfValues(inCountPerProc)
3917 globalController.Broadcast(fromRemoteProcList, ii)
3918 for jj in range(0,inCountPerProc):
3919 outVtkArray.SetValue(prndx + jj, fromRemoteProcList.GetValue(jj))
3920
3921 return mypid, numproc
3922
3923
3924 def UseMPIToCreateSharedPointList(inGlobalNodeIds, inPointXyzs):
3925 "used during finding nearest point (and distance) between one set of points\n and others. The idea is that we have a fairly small set of points from one\n data source (e.g. one block of a multiblock or a decimated set of points)\n which we share to all processors (using mpi broadcast), and then each\n processor finds the nearest point and distance from all of it's points\n to the shared set, and then we use mpi reduce to find which is the\n closest and where it is. This function takes the portion of the shared\n points which are local to this processor (obtained via\n PhactoriOperationBlock.MakeListOfAllPoints1()) and does mpi broadcasting\n to share with all the other processors and also to construct the whole\n list of shared points locally\n returns a vtkIntArray and vtkDoubleArray, where the int array is the list\n of all the global node ids and the double array is all the geometric\n pointx (stored x1y1z1x2y2z2...)\n inGlobalNodeIds is vtkIntArray\n inPointXyzs is vtkDoubleArray"
3926 mypid = SmartGetLocalProcessId()
3927
3928 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
3929 globalController = pm.GetGlobalController()
3930 #gLocalProcessId = globalController.GetLocalProcessId()
3931 numproc = globalController.GetNumberOfProcesses()
3932 if PhactoriDbg(100):
3933 myDebugPrint3("mypid: " + str(mypid) + " numproc: " + str(numproc) + "\n")
3934
3935 #first let everyone know how many points are in each process
3936
3937 numptsInEachProc = vtk.vtkIntArray()
3938 numptsInEachProc.SetNumberOfValues(numproc)
3939 for ii in range(0,numproc):
3940 numptsInEachProc.SetValue(ii, 0)
3941 numptsInEachProc.SetValue(mypid, inGlobalNodeIds.GetNumberOfValues())
3942 #if PhactoriDbg(100):
3943 # myDebugPrint3("numptsInEachProc before AllReduce:\n")
3944 # for ii in range(0,numproc):
3945 # myDebugPrint3(str(ii) + ": " + str(numptsInEachProc.GetValue(ii)) + "\n")
3946
3947 glbNumptsInEachProc = vtk.vtkIntArray()
3948 glbNumptsInEachProc.SetNumberOfValues(numproc)
3949
3950 globalController.AllReduce(numptsInEachProc, glbNumptsInEachProc, 0)
3951 #if PhactoriDbg(100):
3952 # myDebugPrint3("numptsInEachProc after AllReduce:\n" + str(glbNumptsInEachProc) + "\n")
3953 # for ii in range(0,numproc):
3954 # myDebugPrint3(str(ii) + ": " + str(glbNumptsInEachProc.GetValue(ii)) + "\n")
3955
3956 #now go through and create the shared points list
3957 #first the node ids
3958 glbNodeIdList = vtk.vtkIntArray()
3959 shareIdList = vtk.vtkIntArray()
3960 for ii in range(0,numproc):
3961 numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)
3962 #if PhactoriDbg(100):
3963 # myDebugPrint3("doing broadcast for process " + str(ii) + ": numpts: " + str(numPtsFromProcii) + "\n")
3964 if ii == mypid:
3965 #if PhactoriDbg(100):
3966 #myDebugPrint3("I am this process, broadcasting to everyone\n")
3967 if(numPtsFromProcii > 0):
3968 globalController.Broadcast(inGlobalNodeIds, ii)
3969 for jj in range(0,numPtsFromProcii):
3970 glbNodeIdList.InsertNextValue(inGlobalNodeIds.GetValue(jj))
3971 else:
3972 #if PhactoriDbg(100):
3973 # myDebugPrint3("I am not this process, receiving broadcast from this process: " + str(numPtsFromProcii) + "\n")
3974 if(numPtsFromProcii > 0):
3975 shareIdList.SetNumberOfValues(numPtsFromProcii)
3976 #if PhactoriDbg(100):
3977 # myDebugPrint3("returned from broadcast call 2\n")
3978 globalController.Broadcast(shareIdList, ii)
3979 for jj in range(0,numPtsFromProcii):
3980 glbNodeIdList.InsertNextValue(shareIdList.GetValue(jj))
3981 #if PhactoriDbg(100):
3982 # myDebugPrint3("glbNodeIdList after broadcasts:\n")
3983 # for ii in range(0, glbNodeIdList.GetNumberOfValues()):
3984 # myDebugPrint3(str(ii) + ": " + str(glbNodeIdList.GetValue(ii)) + "\n")
3985
3986 #now the xyz geometry values for the nodes
3987 glbXyzList = vtk.vtkDoubleArray()
3988 shareXyzList = vtk.vtkDoubleArray()
3989 for ii in range(0,numproc):
3990 numPtsFromProcii = glbNumptsInEachProc.GetValue(ii)
3991 #if PhactoriDbg(100):
3992 # myDebugPrint3("doing broadcast for process " + str(ii) + ": numpts: " + str(numPtsFromProcii) + "\n")
3993 if ii == mypid:
3994 #if PhactoriDbg(100):
3995 #myDebugPrint3("I am this process, broadcasting to everyone\n")
3996 if(numPtsFromProcii > 0):
3997 globalController.Broadcast(inPointXyzs, ii)
3998 for jj in range(0,numPtsFromProcii*3):
3999 glbXyzList.InsertNextValue(inPointXyzs.GetValue(jj))
4000 else:
4001 #if PhactoriDbg(100):
4002 # myDebugPrint3("I am not this process, receiving broadcast from this process: " + str(numPtsFromProcii) + "\n")
4003 if(numPtsFromProcii > 0):
4004 shareXyzList.SetNumberOfValues(numPtsFromProcii*3)
4005 #if PhactoriDbg(100):
4006 # myDebugPrint3("returned from broadcast call 2\n")
4007 globalController.Broadcast(shareXyzList, ii)
4008 for jj in range(0,numPtsFromProcii*3):
4009 glbXyzList.InsertNextValue(shareXyzList.GetValue(jj))
4010 #if PhactoriDbg(100):
4011 # myDebugPrint3("glbNodeIdList after broadcasts:\n")
4012 # for ii in range(0, glbXyzList.GetNumberOfValues()):
4013 # myDebugPrint3(str(ii) + ": " + str(glbXyzList.GetValue(ii)) + "\n")
4014
4015 return glbNodeIdList, glbXyzList
4016
4017
4018 def GetGlobalDataBoundsParallel(inFromWhichSource = None):
4019 if PhactoriDbg(100):
4020 myDebugPrint3("GetGlobalDataBoundsParallel entered\n", 100)
4021 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
4022 globalController = pm.GetGlobalController()
4023
4024 if inFromWhichSource == None:
4025 localDataBounds = GetActiveSource().GetDataInformation().GetBounds()
4026 else:
4027 localDataBounds = inFromWhichSource.GetDataInformation().GetBounds()
4028
4029 # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
4030 localarray = vtk.vtkDoubleArray()
4031 localarray.SetNumberOfTuples(6)
4032 localarray.SetValue(0, -localDataBounds[0])
4033 localarray.SetValue(1, localDataBounds[1])
4034 localarray.SetValue(2, -localDataBounds[2])
4035 localarray.SetValue(3, localDataBounds[3])
4036 localarray.SetValue(4, -localDataBounds[4])
4037 localarray.SetValue(5, localDataBounds[5])
4038 globalarray = vtk.vtkDoubleArray()
4039 globalarray.SetNumberOfTuples(6)
4040 globalController.AllReduce(localarray, globalarray, 0)
4041 globalDataBounds = [ \
4042 -globalarray.GetTuple1(0), globalarray.GetTuple1(1), \
4043 -globalarray.GetTuple1(2), globalarray.GetTuple1(3), \
4044 -globalarray.GetTuple1(4), globalarray.GetTuple1(5) \
4045 ]
4046 if PhactoriDbg():
4047 myDebugPrint3("localDataBounds: " + str(localDataBounds) + \
4048 "\nglobalDataBounds: " + str(globalDataBounds) + "\n")
4049 if PhactoriDbg(100):
4050 myDebugPrint3("GetGlobalDataBoundsParallel returning\n", 100)
4051 return globalDataBounds
4052
4053
4054 global gDefaultLookatDistanceDatasizeRelative
4055 gDefaultLookatDistanceDatasizeRelative = 1.0
4056 global gDefaultLookatDistanceDatasizeRelativeMultiplier
4057 gDefaultLookatDistanceDatasizeRelativeMultiplier = 4.0
4058
4059 def GetXyzForNodeOrElementParallelOneBlock(inInputCsData, inIdIsNode,
4060 inGlobalId, outXyz):
4061 "check for inGlobalId and set outXyz if present\n\n utility function called by GetXyzForNodeOrElementParallelRecurse1, this\n takes one unstructured grid as input, and sees if it has the node or element\n with id inGlobalId. If it does, the method sets outXyz to the geometric\n location of the node (xyz) or center of the element bounding box (xyz) and\n returns true, otherwise it returns false without changing outXyz\n "
4062
4063 if PhactoriDbg(100):
4064 myDebugPrint3('GetXyzForNodeOrElementParallelOneBlock entered\n', 100)
4065
4066 globalIdArray = None
4067 if inIdIsNode:
4068 ptOrElData = inInputCsData.GetPointData()
4069 globalIdArray = ptOrElData.GetArray('GlobalNodeId')
4070 else:
4071 ptOrElData = inInputCsData.GetCellData()
4072 globalIdArray = ptOrElData.GetArray('GlobalElementId')
4073
4074 if globalIdArray == None:
4075 if PhactoriDbg():
4076 myDebugPrint3(" this process/block has no Global Node or Element Id array to contain " + str(inGlobalId) + "\n")
4077 return False
4078
4079 numTuples = globalIdArray.GetNumberOfTuples()
4080 thisProcessHasTheId = False
4081 idIndex = -1
4082 for ii in range(0, numTuples):
4083 #myDebugPrint3(" testing " + str(ii) + " against " + str(inGlobalNodeId) + "\n")
4084 #myDebugPrint3(" type array: " + str(type(globalNodeIdArray)) + " type ii:" + str(type(ii)) + "\n")
4085 vv = globalIdArray.GetTuple1(ii)
4086 if vv == inGlobalId:
4087 thisProcessHasTheId = True
4088 idIndex = ii
4089 break
4090
4091 if not thisProcessHasTheId:
4092 if PhactoriDbg():
4093 myDebugPrint3(" this process/block doesn't contain id" + \
4094 str(inGlobalId) + "\n")
4095 return False
4096
4097 if PhactoriDbg():
4098 myDebugPrint3(" this process/block contains id " + str(inGlobalId) + "\n")
4099
4100 if inIdIsNode:
4101 pointsArray = inInputCsData.GetPoints()
4102 numPoints = pointsArray.GetNumberOfPoints()
4103 if idIndex >= numPoints:
4104 if PhactoriDbg():
4105 myDebugPrint3(" this process/block has problem with index, setting xyz 0\n")
4106 outXyz[0] = 0.0
4107 outXyz[1] = 0.0
4108 outXyz[2] = 0.0
4109 return False
4110
4111 thePoint = pointsArray.GetPoint(idIndex, outXyz)
4112
4113 if PhactoriDbg():
4114 myDebugPrint3(" outXyz set to: " + str(outXyz) + "\n")
4115 return True
4116 else:
4117 myBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
4118 #myCells = inInputCsData.GetCells()
4119 #oneCell = myCells.GetCell(idIndex)
4120 oneCell = inInputCsData.GetCell(idIndex)
4121 oneCell.GetBounds(myBounds)
4122 #myCells.GetCellBounds(idIndex, myBounds)
4123 #ptOrElData.GetCellBounds(idIndex, myBounds)
4124 outXyz[0] = 0.5 * (myBounds[0] + myBounds[1])
4125 outXyz[1] = 0.5 * (myBounds[2] + myBounds[3])
4126 outXyz[2] = 0.5 * (myBounds[4] + myBounds[5])
4127 #xmin, xmax, ymin, ymax, zmin, zmax = myCells.GetCellBounds(idIndex)
4128 #outXyz[0] = 0.5 * (xmin + xmax)
4129 #outXyz[1] = 0.5 * (ymin + ymax)
4130 #outXyz[2] = 0.5 * (zmin + zmax)
4131 return True
4132
4133 def GetXyzForNodeOrElementParallelRecurse1(inInputCsData,
4134 inIdIsNode, inGlobalId, outXyz):
4135 "utility function used by GetXyzForNodeOrElementParallel\n\n looking for inGlobalId to potentially set outXyz, recurses through\n structure and calls GetXyzForNodeOrElementParallelOneBlock() on\n unstructured grids to do the real work of checking for the id and setting\n outXyz\n "
4136
4137 #myDebugPrint3('GetXyzForNodeOrElementParallelRecurse1 entered\n', 100)
4138
4139 icsdClassname = inInputCsData.GetClassName()
4140 #if PhactoriDbg(100):
4141 # myDebugPrint3("icsdClassname 1: " + str(icsdClassname) + "\n")
4142 if icsdClassname == "vtkMultiBlockDataSet" or \
4143 icsdClassname == "vtkExodusIIMultiBlockDataSet":
4144 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
4145 numBlocks = inInputCsData.GetNumberOfBlocks()
4146 for ii in range(0, numBlocks):
4147 oneBlock = inInputCsData.GetBlock(ii)
4148 if(oneBlock != None):
4149 found = GetXyzForNodeOrElementParallelRecurse1(
4150 oneBlock, inIdIsNode, inGlobalId, outXyz)
4151 if found:
4152 return True
4153 else:
4154 found = GetXyzForNodeOrElementParallelOneBlock(
4155 inInputCsData, inIdIsNode, inGlobalId, outXyz)
4156 if found:
4157 return True
4158
4159 return False
4160
4161 def GetXyzForMinOrMaxVariable(inParaViewSource, inMinFlag,
4162 inVariableInfo, outXyz):
4163 "find the xyz location of the maximum or minimum value of the variable\n in the argument (at node or in element), recurses as necessary, does\n MPI, calls GetXyzForNodeOrElementParallel once id is found"
4164
4165 if PhactoriDbg(100):
4166 myDebugPrint3("GetXyzForMinOrMaxVariable entered\n"
4167 " inMinFlag: " + str(inMinFlag) + "\n"
4168 " variable name: " + str(inVariableInfo.mVariableName) + "\n", 100)
4169
4170 #for now, disable output while doing parallel min/max search
4171 global gMdp3PriorityRestriction
4172 save_gMdp3PriorityRestriction = gMdp3PriorityRestriction
4173 gMdp3PriorityRestriction = 500
4174
4175 #get min or max node or element id for variable
4176 csData = inParaViewSource.GetClientSideObject().GetOutputDataObject(0)
4177 FindNodeOrElementIdForMinMax(csData, inVariableInfo)
4178 if inMinFlag:
4179 theId = inVariableInfo.mStats.mMinId
4180 else:
4181 theId = inVariableInfo.mStats.mMaxId
4182
4183 #decide if it is a node or an element
4184 detectResult = inVariableInfo.DetectVariableType(
4185 inParaViewSource, True)
4186 if detectResult == False:
4187 #myDebugPrint3AndException(
4188 # "GetXyzForMinOrMaxVariable:\n"
4189 # "could not detect element or node type\n"
4190 # "variable name is: " + inVariableInfo.mVariableName + "\n")
4191 myDebugPrint3(
4192 "GetXyzForMinOrMaxVariable:\n"
4193 "could not detect element or node type (using 0 0 0)\n"
4194 "variable name is: " + inVariableInfo.mVariableName + "\n")
4195 outXyz[0] = 0.0
4196 outXyz[1] = 0.0
4197 outXyz[2] = 0.0
4198 localProcessCouldDetect = False
4199 if inVariableInfo.mVariableType == 'node':
4200 nodeFlag = True
4201 localProcessCouldDetect = True
4202 elif inVariableInfo.mVariableType == 'element':
4203 nodeFlag = False
4204 localProcessCouldDetect = True
4205 else:
4206 myDebugPrint3AndException(
4207 "GetXyzForMinOrMaxVariable:\n"
4208 "variable is not element or node type\n"
4209 "variable name is: " + inVariableInfo.mVariableName + "\n")
4210
4211 #get xyz location of node or element
4212 GetXyzForNodeOrElementParallel(inParaViewSource, nodeFlag, theId, outXyz,
4213 localProcessCouldDetect)
4214
4215 #restore output setting
4216 gMdp3PriorityRestriction = save_gMdp3PriorityRestriction
4217
4218 if PhactoriDbg(100):
4219 myDebugPrint3(
4220 "outXyz: " + str(outXyz) + "\n"
4221 "GetXyzForMinOrMaxVariable returning\n", 100)
4222
4223
4224 def GetXyzForNodeOrElementParallel(inParaViewSource,
4225 inIdIsNode, inGlobalId, outXyz, inLocalProcessCouldDetect = True):
4226 "given a node or element id, get item xyz location in parallel\n\n Recurses through all structures on all processes to find a node or element,\n then does allreduce to spread that information to all processes (for use in\n pointing cameras at a node or element with a given id; if this process has\n the element with the\n id inGlobalId, it will set outXyz and send the info around, if this\n process does not have inGlobalId, it will expect to receive the proper\n outXyz from the node that does.\n "
4227
4228 if PhactoriDbg(100):
4229 myDebugPrint3("GetXyzForNodeOrElementParallel entered, IdIsNode: " + str(inIdIsNode) + " id: " + str(inGlobalId) + "\n", 100)
4230
4231 #theSource = GetCurrentSource()
4232 #theSource = GetActiveSource()
4233 if inLocalProcessCouldDetect:
4234 csData = inParaViewSource.GetClientSideObject().GetOutputDataObject(0)
4235
4236 found = GetXyzForNodeOrElementParallelRecurse1(csData,
4237 inIdIsNode, inGlobalId, outXyz)
4238 else:
4239 found = False
4240
4241
4242 if found:
4243 if PhactoriDbg():
4244 myDebugPrint3(" this process has GlobalId " + str(inGlobalId) + ", doing broadcast of info\n")
4245 UseReduceToSpreadValues(outXyz)
4246 #GetXyzForNodeParallelBroadcast(thePointArrays, outXyz)
4247 else:
4248 if PhactoriDbg():
4249 myDebugPrint3(" this process does not have GlobalId " + str(inGlobalId) + ", doing receive of info\n")
4250 UseReduceToSpreadValues(outXyz)
4251 #GetXyzForNodeParallelReceive(outXyz)
4252
4253 if PhactoriDbg(100):
4254 myDebugPrint3("GetXyzForNodeOrElementParallel returning\n", 100)
4255
4256 def CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
4257 inTestPoint, inFov = 30.0):
4258 "finds point X which is along the inNormCameraDir vector starting from\n point inFocalPoint, such that inTestPoint is visible. This is\n accomplished by taking a parametric value ss to move the camera position\n out from the focal point (along the inNormCameraDir vector) and finding\n the parametric value such that the angle between the vector from the\n camera position to the focal point and the camera position to inTestPoint\n is equal to (or greater than) the camera field of view. The parametric\n value is returned. We use the law of sines. assumes inNormCameraDir\n is normalized and pointing in the direction from inFocalPoint towards\n where we want to place the camera (the opposite of the look direction)"
4259
4260 #angle between camera-to-focal point vector and camera-to-testpoint vector
4261 #is equal to half the camera fOV. Call this angle AA.
4262 #The side opposite this angle has length equal to the distance between
4263 #the focal point and the test point. Call this distance aa. We also
4264 #know the angle between the focal point-to-camera vector and the focal
4265 #point-to-testpoint vector (because both vectors point in a fixed direction).
4266 #call this angle BB. The remaining angle is CC, and CC = 180 - (AA + BB).
4267 #thus the length of the parametric side is determined by the law of sines,
4268 #cc/sin(CC) = aa/sin(AA) (cc is the length of interest),
4269 #so cc = aa * sin(CC) / sin(AA)
4270 #
4271
4272 #need to set to 1/2 fov
4273 if PhactoriDbg(100):
4274 myDebugPrint3("CalcRelativeCameraDistance2_AA entered\n");
4275 if PhactoriDbg(100):
4276 myDebugPrint3("inTestPoint: " + str(inTestPoint) + "\n");
4277 angleAA = math.radians(inFov * 0.5)
4278 if PhactoriDbg(100):
4279 myDebugPrint3("angleAA: " + str(math.degrees(angleAA)) + "\n");
4280
4281 focalToTestVec = [inTestPoint[0] - inFocalPoint[0],
4282 inTestPoint[1] - inFocalPoint[1],
4283 inTestPoint[2] - inFocalPoint[2]]
4284 aa = vecMagnitude(focalToTestVec)
4285 if aa == 0.0:
4286 return 0.0
4287 focalToTestVec[0] /= aa
4288 focalToTestVec[1] /= aa
4289 focalToTestVec[2] /= aa
4290 if PhactoriDbg(100):
4291 myDebugPrint3("inNormCameraDir: " + str(inNormCameraDir) + "\n");
4292 if PhactoriDbg(100):
4293 myDebugPrint3("focalToTestVec: " + str(focalToTestVec) + "\n");
4294 cosAngleBB = vecDotProduct(inNormCameraDir, focalToTestVec)
4295 if PhactoriDbg(100):
4296 myDebugPrint3("cosAngleBB: " + str(cosAngleBB) + "\n");
4297 if cosAngleBB >= 1.0:
4298 #camera-to-test-point in line with camera-to-focal-point
4299 #and already in camera view
4300 if PhactoriDbg(100):
4301 myDebugPrint3("cosAngleBB >= 1.0 cc is 0.0\n");
4302 cc = 0.0
4303 return cc
4304 elif cosAngleBB <= -1.0:
4305 #camera-to-test-point in line with camera-to-focal-point
4306 #with camera needing movement back to test point
4307 if PhactoriDbg(100):
4308 myDebugPrint3("cosAngleBB <= -1.0, cc is camera to test point dist\n");
4309 cc = aa
4310 return cc
4311 angleBB = math.acos(cosAngleBB)
4312 if PhactoriDbg(100):
4313 myDebugPrint3("angleBB: " + str(math.degrees(angleBB)) + "\n");
4314 angleCC = math.pi - (angleAA + angleBB)
4315 if PhactoriDbg(100):
4316 myDebugPrint3("angleCC: " + str(math.degrees(angleCC)) + "\n");
4317 cc = aa * math.sin(angleCC) / math.sin(angleAA)
4318 if PhactoriDbg(100):
4319 myDebugPrint3("cc: " + str(cc) + "\n");
4320 if PhactoriDbg(100):
4321 myDebugPrint3("CalcRelativeCameraDistance2_AA returning\n");
4322 return cc
4323
4324 def projectPointOntoPlane(inPoint, inPlanePoint, inPlaneNormal):
4325 vecA = [inPoint[0] - inPlanePoint[0],
4326 inPoint[1] - inPlanePoint[1],
4327 inPoint[2] - inPlanePoint[2]]
4328 dotp1 = vecDotProduct(vecA, inPlaneNormal)
4329 projectedPoint = [inPoint[0] - dotp1 * inPlaneNormal[0],
4330 inPoint[1] - dotp1 * inPlaneNormal[1],
4331 inPoint[2] - dotp1 * inPlaneNormal[2]]
4332 return projectedPoint
4333
4334 def CalcRelativeCameraDistance2_BB(inFocalPoint, inNormCameraDir,
4335 inNormUpVector, inNormSideVector, inFovV, inFovH, inTestPoint):
4336 "takes test point and makes two test points, one projected onto the\n plane defined by the up vector and one onto the plane defined by the\n up vector/look direction cross product; uses these two points to\n test vs. vertical FOV and horizontal FOV, and returns the biggest\n result. Assumes inNormUpVector is normalized as is inNormCameraDir\n and also inNormSideVector"
4337 if PhactoriDbg(100):
4338 myDebugPrint3("CalcRelativeCameraDistance2_BB entered\n");
4339 if PhactoriDbg(100):
4340 myDebugPrint3("inTestPoint: " + str(inTestPoint) + "\n");
4341
4342 pointV = projectPointOntoPlane(inTestPoint, inFocalPoint, inNormSideVector)
4343 if PhactoriDbg(100):
4344 myDebugPrint3("pointV: " + str(pointV) + "\n");
4345 #find point projected onto plane defined by inFocalPoint and localUpVector,
4346 #which will be the test point to test horizontal FOV against
4347 pointH = projectPointOntoPlane(inTestPoint, inFocalPoint, inNormUpVector)
4348 if PhactoriDbg(100):
4349 myDebugPrint3("pointH: " + str(pointH) + "\n");
4350
4351 dd1 = CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
4352 pointH, inFovH)
4353 if PhactoriDbg(100):
4354 myDebugPrint3("dd1: " + str(dd1) + "\n");
4355 dd2 = CalcRelativeCameraDistance2_AA(inFocalPoint, inNormCameraDir,
4356 pointV, inFovV)
4357 if PhactoriDbg(100):
4358 myDebugPrint3("dd2: " + str(dd2) + "\n");
4359 if dd2 > dd1:
4360 dd1 = dd2
4361 if PhactoriDbg(100):
4362 myDebugPrint3("return dd: " + str(dd1) + "\n");
4363 return dd1
4364
4365
4366 def CalcRelativeCameraDistance2(inFocalPoint, inLookDirection, inUpVector,
4367 inFov, inImageSettings, inBounds):
4368 #for each focal point, see how far back from the focal point the
4369 #camera position needs to be to see the focal point. Use the largest.
4370 inXyPixelSize = inImageSettings.mImageSize
4371 inPixelBorderRatioXY = inImageSettings.mPixelBorderRatioXY
4372 if PhactoriDbg(100):
4373 myDebugPrint3("CalcRelativeCameraDistance2 entered\n");
4374 myDebugPrint3("inFocalPoint: " + str(inFocalPoint) + "\n");
4375 myDebugPrint3("inLookDirection: " + str(inLookDirection) + "\n");
4376 myDebugPrint3("inUpVector: " + str(inUpVector) + "\n");
4377 myDebugPrint3("inFov: " + str(inFov) + "\n");
4378 myDebugPrint3("inXyPixelSize: " + str(inXyPixelSize) + "\n");
4379 myDebugPrint3("inPixelBorderRatioXY: " + str(inPixelBorderRatioXY) + "\n");
4380 normCameraDir = vecNormalize(inLookDirection)
4381 normCameraDir[0] = -normCameraDir[0]
4382 normCameraDir[1] = -normCameraDir[1]
4383 normCameraDir[2] = -normCameraDir[2]
4384 if PhactoriDbg(100):
4385 myDebugPrint3("normCameraDir: " + str(normCameraDir) + "\n");
4386
4387 #find orthoganol up and side vectors,
4388 normUpVector = vecNormalize(inUpVector)
4389 sideVector = vecCrossProduct(normUpVector, normCameraDir)
4390 normUpVector = vecCrossProduct(normCameraDir, sideVector)
4391 if PhactoriDbg(100):
4392 myDebugPrint3("sideVector: " + str(sideVector) + "\n");
4393 myDebugPrint3("normUpVector: " + str(normUpVector) + "\n");
4394
4395 #find vertical fov, based on pixel border percentage
4396 vertPixX = 0.5 * float(inXyPixelSize[0])
4397 vertPixY = 0.5 * float(inXyPixelSize[1])
4398 vertPixBrdrX = inPixelBorderRatioXY[0] * float(inXyPixelSize[0])
4399 vertPixBrdrY = inPixelBorderRatioXY[1] * float(inXyPixelSize[1])
4400
4401 vertPixBrdrX = math.ceil(vertPixBrdrX)
4402 vertPixBrdrY = math.ceil(vertPixBrdrY)
4403
4404 if PhactoriDbg(100):
4405 myDebugPrint3("pixel border: " + str(vertPixBrdrX) + ", " + str(vertPixBrdrY) + "\n")
4406 tanInFov = math.tan(math.radians(inFov*0.5))
4407 if PhactoriDbg(100):
4408 myDebugPrint3("tanInFov: " + str(tanInFov) + "\n")
4409
4410 #vertPixY / ss = tan(inFov*0.5)
4411 #1/ss = tan(inFov*0.5)/vertPixY
4412 #(vertPixY - vertPixBrdrY) / ss = tan(adjFov*0.5)
4413 #(vertPixY - vertPixBrdrY) * tan(inFov*0.5)/vertPixY = tan(adjFov*0.5)
4414
4415 tanAdjustedFovV = (vertPixY - vertPixBrdrY) * tanInFov / vertPixY
4416 if PhactoriDbg(100):
4417 myDebugPrint3("tanAdjustedFovV: " + str(tanAdjustedFovV) + "\n")
4418 fovV = 2.0 * math.degrees(math.atan(tanAdjustedFovV))
4419 if PhactoriDbg(100):
4420 myDebugPrint3("fovV: " + str(fovV) + "\n");
4421
4422 pixelSizeWithBorder = [inXyPixelSize[0] - 2 * int(vertPixBrdrX),
4423 inXyPixelSize[1] - 2 * int(vertPixBrdrY)]
4424
4425 #we are special casing when the pixel ratio is the same for both
4426 #X and Y for backwards compatability of test images; We should
4427 #take out this special case and update the test images. The
4428 #difference is very minor, but detectable
4429 if inImageSettings.mPixelBorderRatioXY[0] == \
4430 inImageSettings.mPixelBorderRatioXY[1]:
4431 #this is the special case--use the original pixel size to calculate
4432 #aspect ratio, which will be very slightly different than the other
4433 #case due to the math.ceil clamping to an integer value
4434 aspectRatio = float(inXyPixelSize[0]) / float(inXyPixelSize[1])
4435 else:
4436 aspectRatio = float(pixelSizeWithBorder[0]) / float(pixelSizeWithBorder[1])
4437
4438
4439 if PhactoriDbg(100):
4440 myDebugPrint3("bordered aspectRatio: " + str(aspectRatio) + "\n");
4441 tanFovH = aspectRatio * tanAdjustedFovV
4442 fovH = 2.0 * math.degrees(math.atan(tanFovH))
4443 if PhactoriDbg(100):
4444 myDebugPrint3("fovH: " + str(fovH) + "\n");
4445
4446 #find point projected onto plane defined by inFocalPoint and sideVector,
4447 #which will be the test point to test vertical FOV against
4448 dist1 = 0.0
4449 for ii in range(0,2):
4450 for jj in range(0,2):
4451 for kk in range(0,2):
4452 testpoint = [inBounds[ii+0], inBounds[jj+2], inBounds[kk+4]]
4453 testdist = CalcRelativeCameraDistance2_BB(inFocalPoint,
4454 normCameraDir, normUpVector, sideVector, fovV, fovH,
4455 testpoint)
4456 if testdist > dist1:
4457 dist1 = testdist
4458 if PhactoriDbg(100):
4459 myDebugPrint("CalcRelativeCameraDistance2 returning dist: " + str(dist1) + "\n");
4460 return dist1
4461
4462 def SetParaViewRepresentationCameraParams(inXParaViewRenderView, inCameraC,
4463 inLookDirection, inImageSettingsX, inParaViewSource):
4464 lookDirection = inLookDirection
4465
4466 myViewBounds = None
4467 viewBoundsIo = [myViewBounds]
4468
4469 #special case--if inCameraC was set up so the camera is at a specified
4470 #point, if the look at point is specified we need to base the look
4471 #direction on the camera position and the look at point, and if
4472 #the look direction is specified, we need to base the look at point
4473 #on the camera position and the look direction
4474 if inCameraC.mUseCameraAtPointFlag:
4475 if PhactoriDbg():
4476 myDebugPrint3("SetParaViewRepresentationCameraParams: special case of camera at point setting\n")
4477 #camera at point was specified--do the right stuff
4478 cameraPoint = inCameraC.mCameraAtPointInfo.\
4479 GetCurrentGeometricPointWithDisplacement(
4480 inParaViewSource, viewBoundsIo, True)
4481 if PhactoriDbg():
4482 myDebugPrint3("cameraPoint: " + str(cameraPoint) + "\n")
4483 inCameraC.mLookAtDistanceType = 'absolute'
4484 if inCameraC.mLookDirectionSpecifiedFlag:
4485 if PhactoriDbg():
4486 myDebugPrint3("look direction was specified\n")
4487 #look direction was specified, so calculate focal point based on camera
4488 #position and look direction and set look at distance to 1.0
4489 lookDirection = inCameraC.mLookDirection
4490 aa = lookDirection[0]
4491 bb = lookDirection[1]
4492 cc = lookDirection[2]
4493 lookDirectionMagnitude = math.sqrt(aa*aa + bb*bb + cc*cc)
4494 inCameraC.mLookAtDistance = 1.0
4495 focalPoint = [cameraPoint[0] + (aa / lookDirectionMagnitude),
4496 cameraPoint[1] + (bb / lookDirectionMagnitude),
4497 cameraPoint[2] + (cc / lookDirectionMagnitude)]
4498 if PhactoriDbg():
4499 myDebugPrint3("focalPoint: " + str(focalPoint) + "\n")
4500 if PhactoriDbg():
4501 myDebugPrint3("lookDirection: " + str(lookDirection) + "\n")
4502 if PhactoriDbg():
4503 myDebugPrint3("inCameraC.mLookAtDistance is 1.0\n")
4504 else:
4505 #look direction not specified, so we use look at point. Calculate
4506 #look direction and look at distance based on camera position and
4507 #look at point
4508 if PhactoriDbg():
4509 myDebugPrint3("use look at point as look direction was not specified\n")
4510 focalPoint = inCameraC.mLookAtPointInfo. \
4511 GetCurrentGeometricPointWithDisplacement(
4512 inParaViewSource, viewBoundsIo, True)
4513 if PhactoriDbg():
4514 myDebugPrint3("focalPoint: " + str(focalPoint) + "\n")
4515 lookDirection = [focalPoint[0] - cameraPoint[0],
4516 focalPoint[1] - cameraPoint[1],
4517 focalPoint[2] - cameraPoint[2]]
4518 if PhactoriDbg():
4519 myDebugPrint3("lookDirection: " + str(lookDirection) + "\n")
4520 aa = lookDirection[0]
4521 bb = lookDirection[1]
4522 cc = lookDirection[2]
4523 inCameraC.mLookAtDistance = math.sqrt(aa*aa + bb*bb + cc*cc)
4524 if PhactoriDbg():
4525 myDebugPrint3("inCameraC.mLookAtDistance is " + str(inCameraC.mLookAtDistance) + "\n")
4526 #check for zero magnitude
4527 if inCameraC.mLookAtDistance != 0.0:
4528 inCameraC.mLookDirection = lookDirection
4529 else:
4530 if PhactoriDbg():
4531 myDebugPrint3("warning: camera position and look at point are the same\n")
4532 #try to use previous
4533 lookDirection = inCameraC.mLookDirection
4534 aa = lookDirection[0]
4535 bb = lookDirection[1]
4536 cc = lookDirection[2]
4537 inCameraC.mLookAtDistance = math.sqrt(aa*aa + bb*bb + cc*cc)
4538 if PhactoriDbg():
4539 myDebugPrint3(" coincident lookDirection: " + str(lookDirection) + "\n")
4540 if PhactoriDbg():
4541 myDebugPrint3(" coincident inCameraC.mLookAtDistance is " + str(inCameraC.mLookAtDistance) + "\n")
4542 if inCameraC.mLookAtDistance == 0.0:
4543 if PhactoriDbg():
4544 myDebugPrint3(" warning: previous camera look direction had zero magnitude\n")
4545 #previous also zero, use -1,-1,-1
4546 lookDirection = [-1.0, -1.0, -1.0]
4547 inCameraC.mLookAtDistance = math.sqrt(3.0)
4548 if PhactoriDbg():
4549 myDebugPrint3(" coincident lookDirection 2: " + str(lookDirection) + "\n")
4550 if PhactoriDbg():
4551 myDebugPrint3(" coincident inCameraC.mLookAtDistance 2 is " + str(inCameraC.mLookAtDistance) + "\n")
4552 else:
4553 UpdatePipelineWithCurrentTimeArgument(inParaViewSource)
4554 focalPoint = inCameraC.mLookAtPointInfo. \
4555 GetCurrentGeometricPointWithDisplacement(
4556 inParaViewSource, viewBoundsIo, True)
4557
4558 if PhactoriDbg():
4559 myDebugPrint3(' lookDirection ' + str(lookDirection) + '\n')
4560
4561 myViewBounds = viewBoundsIo[0]
4562
4563 if PhactoriDbg():
4564 myDebugPrint3(' focalPoint ' + str(focalPoint) + '\n')
4565
4566 #need to handle relative and error
4567
4568 global gDefaultLookatDistanceDatasizeRelativeMultiplier
4569 global gDefaultLookatDistanceDatasizeRelative
4570 if inCameraC.mLookAtDistanceType == 'datasize relative':
4571 cameraPositionFactor = inCameraC.mLookAtDistance
4572 #cameraPositionFactor *= gDefaultLookatDistanceDatasizeRelativeMultiplier
4573 cameraToFocalPointDistance = None
4574 #we'll need view bounds for distance
4575 if myViewBounds == None:
4576 myViewBounds = GetGlobalDataBoundsParallel(inParaViewSource)
4577 #elif inCameraC.mLookAtDistanceType == 'absolute':
4578 else:
4579 cameraPositionFactor = gDefaultLookatDistanceDatasizeRelative
4580 cameraPositionFactor *= gDefaultLookatDistanceDatasizeRelativeMultiplier
4581 cameraToFocalPointDistance = inCameraC.mLookAtDistance
4582
4583
4584 if PhactoriDbg():
4585 myDebugPrint3(' cameraPositionFactor: ' + str(cameraPositionFactor) + '\n')
4586 if PhactoriDbg():
4587 myDebugPrint3(' cameraToFocalPointDistance: ' + str(cameraToFocalPointDistance) + '\n')
4588
4589
4590 SetCameraLookAtPointAndLookDirection(inParaViewRenderView = inXParaViewRenderView,
4591 inLookDirection = lookDirection,
4592 inImageSettings = inImageSettingsX,
4593 inFocalPoint = focalPoint,
4594 inEyePositionFactor = cameraPositionFactor,
4595 inEyeToFocalPointDistance = cameraToFocalPointDistance,
4596 inCameraViewAngle = inCameraC.mViewAngle,
4597 inViewUp = inCameraC.mViewUpVector,
4598 inViewBounds = myViewBounds,
4599 inPhactoriCamera = inCameraC)
4600
4601
4602 def SetForCorrectColorByVariable(inImagesetInfo, inPhactoriOperation,
4603 inPvDataRepresentation, inPhactoriRepresentation,
4604 inInitializeColorLegendFlag):
4605 "sets the color by variable to a scalar, vector component/magnitude, or\n tensor component. Assumes we've already established we are doing this\n instead of solid color or color by block"
4606
4607 if PhactoriDbg():
4608 myDebugPrint3("SetForCorrectColorByVariable entered\n")
4609
4610 savedActiveSourceX = GetActiveSource()
4611 SetActiveSource(inPhactoriOperation.GetPvFilter())
4612
4613 colorVarInfo = inPhactoriRepresentation.mColorVariableInfo
4614
4615 if PhactoriDbg():
4616 myDebugPrint3("colorVarInfo.mVariableName: " + \
4617 str(colorVarInfo.mVariableName) + "\n")
4618
4619 if colorVarInfo.mVariableName == '':
4620 myVariableArrayType = gCellsString
4621 else:
4622 global gPipeAndViewsState
4623 #the correct behavior is probably to use the imageset's filter as the
4624 #filter to use to determine info about the variable, such as POINT or
4625 #cell; however prior work used the pipeline start default incoming
4626 #filter. We are using prior to get tests to pass for now, and
4627 #we are considering switching to 'correct.'
4628 useImagesetFilterToDetectVariableType = False
4629 if useImagesetFilterToDetectVariableType:
4630 paraViewSource = inPhactoriOperation.GetPvFilter()
4631 else:
4632 paraViewSource = \
4633 gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
4634 detectResult = colorVarInfo.DetectVariableType(
4635 paraViewSource, True, False)
4636
4637 if detectResult == True:
4638 #variable type detected determine value for paraview
4639 if colorVarInfo.mVariableType == 'node':
4640 myVariableArrayType = gPointsString
4641 elif colorVarInfo.mVariableType == 'element':
4642 myVariableArrayType = gCellsString
4643 else:
4644 if PhactoriDbg():
4645 myDebugPrint3(errStr)
4646 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
4647 'image set ' + inImagesetInfo.mName + \
4648 'operation ' + inPhactoriOperation.mName + \
4649 ' representation ' + inPhactoriRepresentation.mName + \
4650 '\ncolor variable name: ' + \
4651 colorVarInfo.mVariableName +\
4652 '\nvariable should be node or element at this point and is not'
4653 raise Exception(errStr)
4654 else:
4655 #variable type not detected, deal with it
4656 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
4657 'image set ' + inImagesetInfo.mName + \
4658 'operation ' + inPhactoriOperation.mName + \
4659 ' representation ' + inPhactoriRepresentation.mName + \
4660 '\ncolor variable name: ' + \
4661 colorVarInfo.mVariableName +\
4662 '\nvariable is not point data or cell data, assuming cell'
4663 if PhactoriDbg():
4664 myDebugPrint3(errStr)
4665 #current hack--if detection of variable type fails due to missing
4666 #variable; assume it is CELLS and let mpi stuff share info
4667 #and create odd color map otherwise
4668 myVariableArrayType = gCellsString
4669
4670 if PhactoriDbg():
4671 myDebugPrint3("myVariableArrayType: " + myVariableArrayType + "\n")
4672 #("showColorLegend: " + str(showColorLegend) + "\n")
4673
4674 colorVarName = colorVarInfo.mVariableName
4675 if colorVarName != '':
4676 if colorVarInfo.mVariableIsVectorComponent:
4677 if PhactoriDbg():
4678 myDebugPrint3("mVariableIsVectorComponent is true so we do\n"
4679 "ColorByVariableComponentOrMagnitudeXX (component)\n")
4680 ColorByVariableComponentOrMagnitudeXX(
4681 inPvDataRepresentation, inPhactoriRepresentation, colorVarName,
4682 'Component', colorVarInfo.mVariableComponent, myVariableArrayType,
4683 inPhactoriRepresentation.mColorMapSettings)
4684 elif colorVarInfo.mVariableIsVectorMagnitude:
4685 if PhactoriDbg():
4686 myDebugPrint3("mVariableIsVectorMagnitude is true so we do\n"
4687 "ColorByVariableComponentOrMagnitudeXX (magnitude)\n")
4688 ColorByVariableComponentOrMagnitudeXX(
4689 inPvDataRepresentation, inPhactoriRepresentation, colorVarName,
4690 'Magnitude', colorVarInfo.mVariableComponent, myVariableArrayType,
4691 inPhactoriRepresentation.mColorMapSettings)
4692 else:
4693 if PhactoriDbg():
4694 myDebugPrint3("not component or magnitude so we do "
4695 "ColorByVariableScalarXX\n")
4696 ColorByVariableScalarXX(inPvDataRepresentation, inPhactoriRepresentation,
4697 colorVarName, myVariableArrayType,
4698 inPhactoriRepresentation.mColorMapSettings)
4699
4700 #if inInitializeColorLegendFlag:
4701 if True:
4702 if inPhactoriRepresentation.mUseFixedColorRange:
4703 fixedColorRange = inPhactoriRepresentation.mFixedColorRange
4704 SetMinimumMaximumColorValues(inPvDataRepresentation,
4705 fixedColorRange[0], fixedColorRange[1],
4706 inPhactoriOperation, inPhactoriRepresentation,
4707 colorVarName, myVariableArrayType)
4708 #else:
4709 # SetMinimumMaximumColorValues(inPvDataRepresentation,
4710 # -0.1, 0.1,
4711 # inPhactoriRepresentation, colorVarName, myVariableArrayType)
4712 else:
4713 if gParaViewCatalystVersionFlag <= 40100:
4714 inPvDataRepresentation.ColorArrayName = ""
4715 else:
4716 #if PhactoriDbg():
4717 # myDebugPrint3("using ColorBy() to set no color var 1\n")
4718 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4719 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
4720 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4721
4722 if PhactoriDbg():
4723 myDebugPrint3("SetForCorrectColorByVariable returning\n")
4724
4725 #inPvDataRepresentation.RescaleTransferFunctionToDataRange(True)
4726 SetActiveSource(savedActiveSourceX)
4727
4728 def SetForCorrectColorBy(inImagesetInfo, inPhactoriOperation,
4729 inPvDataRepresentation, inPhactoriRepresentation,
4730 inInitializeColorLegendFlag):
4731
4732 global gParaViewCatalystVersionFlag
4733
4734 if PhactoriDbg():
4735 if inPhactoriOperation != None:
4736 opStr = inPhactoriOperation.mName
4737 else:
4738 opStr = "None"
4739 myDebugPrint3("SetForCorrectColorBy entered\n"
4740 "inImagesetInfo: " + inImagesetInfo.mName + "\n"
4741 "inPhactoriOperation: " + opStr + "\n"
4742 "inPhactoriRepresentation: " + str(inPhactoriRepresentation) + "\n"
4743 "inInitializeColorLegendFlag: " + str(inInitializeColorLegendFlag) + "\n")
4744 #color by variable
4745 if inPhactoriRepresentation != None:
4746 if inPvDataRepresentation.Opacity != inPhactoriRepresentation.mOpacitySetting:
4747 inPvDataRepresentation.Opacity = inPhactoriRepresentation.mOpacitySetting
4748 SetForCorrectColorByVariable(inImagesetInfo, inPhactoriOperation,
4749 inPvDataRepresentation, inPhactoriRepresentation,
4750 inInitializeColorLegendFlag)
4751 else:
4752 if PhactoriDbg():
4753 myDebugPrint3("inPhactoriRepresentation is None, so set to no color array\n")
4754 if gParaViewCatalystVersionFlag <= 40100:
4755 inPvDataRepresentation.ColorArrayName = ""
4756 else:
4757 #if PhactoriDbg():
4758 # myDebugPrint3("using ColorBy() to set no color var 2\n")
4759 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4760 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
4761 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4762
4763 #color by block id or solid color
4764 if inPhactoriRepresentation != None:
4765 if inPhactoriRepresentation.mColorByBlockFlag == False:
4766 #clear block color
4767 if gParaViewCatalystVersionFlag < 51000:
4768 inPvDataRepresentation.BlockColor = {}
4769 if inPhactoriRepresentation.mColorByBlockFlag:
4770 if PhactoriDbg():
4771 myDebugPrint3("inPhactoriRepresentation.mColorByBlockFlag is true\n")
4772
4773 if gParaViewCatalystVersionFlag <= 40100:
4774 inPvDataRepresentation.ColorArrayName = ""
4775 else:
4776 #if PhactoriDbg():
4777 # myDebugPrint3("using ColorBy() to set no color var 3\n")
4778 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4779 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
4780 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4781
4782 ColorByBlock(GetActiveSource(),
4783 inPvDataRepresentation,
4784 inPhactoriRepresentation.mColorByBlockExplicitlySet)
4785 elif inPhactoriRepresentation.mColorBySolidColorFlag:
4786 if PhactoriDbg():
4787 myDebugPrint3("inPhactoriRepresentation.mColorBySolidColorFlag is true\n")
4788 if gParaViewCatalystVersionFlag <= 40100:
4789 inPvDataRepresentation.ColorArrayName = ""
4790 else:
4791 #if PhactoriDbg():
4792 # myDebugPrint3("using ColorBy() to set no color var 4\n")
4793 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4794 SafeColorBy(inPvDataRepresentation, (gPointsString,''))
4795 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
4796
4797 inPvDataRepresentation.DiffuseColor = \
4798 inPhactoriRepresentation.mSolidColor
4799 else:
4800 if PhactoriDbg():
4801 myDebugPrint3("no color by block or solid color flag\n")
4802
4803 if PhactoriDbg():
4804 myDebugPrint3("SetForCorrectColorBy returning\n")
4805
4806 def SetUpOneParaViewRepresentationAndViewC(inCameraC, inLookDirection,
4807 inImagesetInfo,
4808 inColorSettingsX,
4809 inMeshRenderControl,
4810 inShowDataCubeAxes, inShowDataCubeAxesInfo, inShowOrientationAxes,
4811 inFixedColorRange,
4812 inIsPlotFlag,
4813 inViewBounds = None,
4814 inRepresentationFilenameAddon = "",
4815 inLookDirectionFilenameAddon = "",
4816 inPhactoriRepresentation = None):
4817
4818 global gRenderingEnabled
4819 if gRenderingEnabled == False:
4820 if PhactoriDbg():
4821 myDebugPrint3("SetUpOneParaViewRepresentationAndViewC returning with noop because rendering is disabled\n")
4822 return
4823
4824 inImageSettings = inImagesetInfo.mImageSettings
4825 lclImageSize = inImageSettings.mImageSize
4826 lclImageFormat = inImageSettings.mImageFormat
4827 inImageBasename = inImageSettings.mImageBasename
4828 inImageBasedirectory = inImageSettings.mImageBasedirectory
4829 inNumCounterDigits = inImageSettings.mNumCounterDigits
4830
4831 #myDebugPrint3('inCameraC: ' + str(inCameraC) + '\n')
4832 #myDebugPrint3('inLookDirection: ' + str(inLookDirection) + '\n')
4833 #myDebugPrint3('inImageBasename: ' + str(inImageBasename) + '\n')
4834 #myDebugPrint3('inImageBasedirectory: ' + str(inImageBasedirectory) + '\n')
4835 #myDebugPrint3('inNumCounterDigits: ' + str(inNumCounterDigits) + '\n')
4836 #myDebugPrint3('lclImageFormat: ' + str(lclImageFormat) + '\n')
4837 #myDebugPrint3('lclImageSize: ' + str(lclImageSize) + '\n')
4838 #myDebugPrint3('inMeshRenderControl: ' + str(inMeshRenderControl) + '\n')
4839 #myDebugPrint3('inShowDataCubeAxes: ' + str(inShowDataCubeAxes) + '\n')
4840 #myDebugPrint3('inShowOrientationAxes: ' + str(inShowOrientationAxes) + '\n')
4841 #myDebugPrint3('inViewBounds: ' + str(inViewBounds) + '\n')
4842 #myDebugPrint3('inRepresentationFilenameAddon: ' + str(inRepresentationFilenameAddon) + '\n')
4843 #myDebugPrint3('inLookDirectionFilenameAddon: ' + str(inLookDirectionFilenameAddon) + '\n')
4844
4845
4846 #need to handle absolute and error
4847
4848 nameSuffix = inRepresentationFilenameAddon + inCameraC.mFilenameAddon + inLookDirectionFilenameAddon
4849
4850 if inImageBasedirectory == None:
4851 fileBaseName = inImageBasename + nameSuffix
4852 elif inImageBasedirectory == "":
4853 fileBaseName = inImageBasename + nameSuffix
4854 else:
4855 import os
4856 fileBaseName = inImageBasedirectory + os.sep + inImageBasename + nameSuffix
4857
4858 AddRenderView(inPhactoriImagesetInfo = inImagesetInfo,
4859 inColorSettings = inColorSettingsX,
4860 ImageBaseFileName = fileBaseName, ImageType = lclImageFormat,
4861 ImageOverwriteFlag = False,
4862 PixelSizeX = lclImageSize[0], PixelSizeY = lclImageSize[1],
4863 numCounterDigits = inNumCounterDigits,
4864 inIsPlotFlag = inIsPlotFlag)
4865
4866 if inIsPlotFlag == False:
4867 SetParaViewRepresentationCameraParams(inImagesetInfo.mSharedPvRenderView2,
4868 inCameraC, inLookDirection, inImageSettings, GetActiveSource())
4869 SetForCorrectColorBy(inImagesetInfo,
4870 inImagesetInfo.GetInputPhactoriOperation(),
4871 inImagesetInfo.mPvDataRepresentation2, inPhactoriRepresentation, True)
4872
4873 inImagesetInfo.mPvDataRepresentation2.Representation = inMeshRenderControl
4874 if(inShowOrientationAxes):
4875 inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 1
4876 else:
4877 inImagesetInfo.mSharedPvRenderView2.OrientationAxesVisibility = 0
4878
4879 UpdateRepresentationColorBy(inImagesetInfo)
4880 #if inShowColorLegend:
4881 # if PhactoriDbg():
4882 # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend on\n')
4883 # ShowDataColorLegendXX(inImagesetInfo, 'on',
4884 # inColorLegendPositionAndSize, inColorSettingsX)
4885 #else:
4886 # if PhactoriDbg():
4887 # myDebugPrint3(' CreateOneCameraViewFromViewMapCInfo color legend off\n')
4888 # ShowDataColorLegendXX(inImagesetInfo, 'off',
4889 # inColorLegendPositionAndSize, inColorSettingsX)
4890
4891 if inShowDataCubeAxes:
4892 ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'on', inShowDataCubeAxesInfo)
4893 else:
4894 ShowCubeAxesXX(inImagesetInfo.mSharedPvRenderView2, 'off')
4895
4896 def GetLookDirectionListFromCamera(inCamera):
4897 if inCamera.mType == 'multicamera8':
4898 directionsList = [ [[-1.0, 0.0, 0.0], 'x1.'],
4899 [[ 1.0, 0.0, 0.0], 'x2.'],
4900 [[ 0.0, -1.0, 0.0], 'y1.'],
4901 [[ 0.0, 1.0, 0.0], 'y2.'],
4902 [[ 0.0, 0.0, -1.0], 'z1.'],
4903 [[ 0.0, 0.0, 1.0], 'z2.'],
4904 [[-1.0, -1.0, -1.0], 'xyz1.'],
4905 [[ 1.0, 1.0, 1.0], 'xyz2.'] ]
4906 elif inCamera.mType == 'camera':
4907 directionsList = [[inCamera.mLookDirection, '']]
4908 else:
4909 errStr = 'error! GetLookDirectionListFromCamera has illegal camera type\n'
4910 if PhactoriDbg():
4911 myDebugPrint3(errStr)
4912 raise Exception(errStr)
4913
4914 return directionsList
4915
4916
4917 def ParseOneFilterTypeFromViewMapOperation(ioOperationBlock, inTypeString, inOperationClass, inOperationParamsJson):
4918 ioOperationBlock.mType = inTypeString
4919
4920 ioOperationBlock.mOperationSpecifics = inOperationClass()
4921 ioOperationBlock.mOperationSpecifics.mPhactoriOperationBlockOwner = \
4922 ioOperationBlock
4923 ioOperationBlock.mOperationSpecifics.ParseParametersFromJson(inOperationParamsJson)
4924
4925 #if 'input operation' in inOperationParamsJson:
4926 if 'input' in inOperationParamsJson:
4927 ioOperationBlock.mInputOperationName = inOperationParamsJson['input']
4928 if PhactoriDbg(100):
4929 myDebugPrint3("ParseOneFilterTypeFromViewMapOperation: input is: \n" + ioOperationBlock.mInputOperationName, 100)
4930 else:
4931 noticeStr = 'notice! inOperationParamsJson has no input key, using default pipeline input\n'
4932 ioOperationBlock.mInputOperationName = None
4933 if PhactoriDbg():
4934 myDebugPrint3(noticeStr)
4935
4936
4937 def ConstructClipPlaneOperationFromParsedOperationBlockC(ioPipeAndViewsState, ioOperationBlock):
4938 return
4939
4940 def ConstructPipelineOperationFromParsedOperationBlockC_ForTest(ioOperationBlock, inputParaviewFilter):
4941 if PhactoriDbg(100):
4942 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC_ForTest entered\n", 100)
4943 particularOperation = ioOperationBlock.mOperationSpecifics
4944 if ioOperationBlock.mType == 'group':
4945 myDebugPrint3("not doing group yet")
4946 raise Exception("not doing group yet")
4947 else:
4948 inputSource = inputParaviewFilter
4949 newParaViewFilter = particularOperation.CreateParaViewFilter2(inputSource, None)
4950 ioOperationBlock.mParaViewFilter = newParaViewFilter
4951 if PhactoriDbg(100):
4952 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC_ForTest returning\n", 100)
4953
4954 def ConstructPipelineOperationFromParsedOperationBlockC(ioPipeAndViewsState, ioOperationBlock):
4955 if PhactoriDbg(100):
4956 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC entered\n", 100)
4957 if PhactoriDbg():
4958 myDebugPrint3(" constructing operation named " + ioOperationBlock.mName + "\n")
4959
4960 particularOperation = ioOperationBlock.mOperationSpecifics
4961
4962 if ioOperationBlock.mType == 'group':
4963 if PhactoriDbg(100):
4964 myDebugPrint3("type was 'group', different pv filter construction\n",
4965 100)
4966 newParaViewFilter = particularOperation.CreateParaViewFilter2(
4967 ioPipeAndViewsState)
4968 else:
4969 inputSource = None
4970 if ioOperationBlock.mInputOperationName == None:
4971 inputSource = GetActiveSource()
4972 if PhactoriDbg():
4973 myDebugPrint3("mInputOperationName was none so using" + str(inputSource) + '\n')
4974 else:
4975 inputOperationBlock = ioPipeAndViewsState.mOperationBlocks[
4976 ioOperationBlock.mInputOperationName]
4977 inputSource = inputOperationBlock.GetPvFilter()
4978 if PhactoriDbg():
4979 myDebugPrint3("mInputOperationName was " + ioOperationBlock.mInputOperationName + " so using" + str(inputSource) + '\n')
4980
4981 newParaViewFilter = particularOperation.CreateParaViewFilter2(inputSource, ioPipeAndViewsState)
4982
4983 ioOperationBlock.mParaViewFilter = newParaViewFilter
4984
4985 if PhactoriDbg(100):
4986 myDebugPrint3("ConstructPipelineOperationFromParsedOperationBlockC returning\n", 100)
4987
4988
4989 def MakeFiltersFromViewMapOperationsC(ioPipeAndViewsState, inOperationBlocksJson):
4990 if PhactoriDbg(100):
4991 myDebugPrint3('MakeFiltersFromViewMapOperationsC entered\n', 100)
4992
4993 #loop through set of filter blocks (in json dict) and parse out the filter objects
4994 for operationName, operationParams in inOperationBlocksJson.items():
4995
4996 #hack to insert filter images in/out
4997 if operationName == "ImageFilteringStartOperationOverride":
4998 if PhactoriDbg():
4999 myDebugPrint3("overriding operation to do image set on/off filtering\n")
5000 operationParams['type'] = 'image_filtering_start'
5001 ParseOneImageStartStopFilterFromViewMap(operationParams)
5002 #then go on to next operation
5003 continue
5004
5005 newOperationBlock = PhactoriOperationBlock()
5006 newOperationBlock.mName = operationName
5007 if PhactoriDbg():
5008 myDebugPrint3(' creating operation named ' + newOperationBlock.mName + '\n')
5009
5010 if 'type' not in operationParams:
5011 errStr = 'error! operation block with name ' + str(operationName) + ' has no type key in MakeFiltersFromViewMapOperationsC\n'
5012 if PhactoriDbg():
5013 myDebugPrint3(errStr)
5014 raise Exception(errStr)
5015
5016 if PhactoriDbg():
5017 myDebugPrint3(' operation type: ' + str(operationParams['type']) + '\n')
5018
5019 if operationParams['type'] == 'threshold':
5020 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5021 'threshold',
5022 PhactoriThresholdOperation,
5023 operationParams)
5024 elif operationParams['type'] == 'extractblock':
5025 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5026 'extractblock',
5027 PhactoriExtractBlockOperation,
5028 operationParams)
5029 elif operationParams['type'] == 'generatesurfacenormals':
5030 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5031 'generatesurfacenormals',
5032 PhactoriGenerateSurfaceNormalsOperation,
5033 operationParams)
5034 elif operationParams['type'] == 'extractsurface':
5035 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5036 'extractsurface',
5037 PhactoriExtractSurfaceOperation,
5038 operationParams)
5039 elif operationParams['type'] == 'ghostcellsgenerator':
5040 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5041 'ghostcellsgenerator',
5042 PhactoriGhostCellsGeneratorOperation,
5043 operationParams)
5044 elif operationParams['type'] == 'mergeblocks':
5045 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5046 'mergeblocks',
5047 PhactoriMergeBlocksOperation,
5048 operationParams)
5049 elif operationParams['type'] == 'subdivide':
5050 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5051 'subdivide',
5052 PhactoriSubdivideOperation,
5053 operationParams)
5054 elif operationParams['type'] == 'aggregatedataset':
5055 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5056 'aggregatedataset',
5057 PhactoriAggregateDatasetOperation,
5058 operationParams)
5059 elif operationParams['type'] == 'createsegmentsnormaltocells':
5060 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5061 'createsegmentsnormaltocells',
5062 PhactoriCreateSegmentsNormalToCells,
5063 operationParams)
5064 elif operationParams['type'] == 'vectorproject':
5065 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5066 'vectorproject',
5067 PhactoriVectorProject,
5068 operationParams)
5069 elif operationParams['type'] == 'glyph':
5070 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5071 'glyph',
5072 PhactoriGlyphOperation,
5073 operationParams)
5074 elif operationParams['type'] == 'triangulate':
5075 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5076 'triangulate',
5077 PhactoriTriangulateOperation,
5078 operationParams)
5079 elif operationParams['type'] == 'group':
5080 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5081 'group',
5082 PhactoriGroupOperation,
5083 operationParams)
5084 elif operationParams['type'] == 'transform':
5085 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5086 'transform',
5087 PhactoriTransformOperation,
5088 operationParams)
5089 elif operationParams['type'] == 'calculator':
5090 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5091 'calculator',
5092 PhactoriCalculatorOperation,
5093 operationParams)
5094 elif operationParams['type'] == 'add point set':
5095 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5096 'add point set',
5097 PhactoriAddPointSetOperation,
5098 operationParams)
5099 elif operationParams['type'] == 'add unstructured grid':
5100 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5101 'add unstructured grid',
5102 PhactoriAddUnstructuredGridOperation,
5103 operationParams)
5104 elif operationParams['type'] == 'reflect':
5105 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5106 'reflect',
5107 PhactoriReflectOperation,
5108 operationParams)
5109 elif operationParams['type'] == 'warpbyvector':
5110 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5111 'warpbyvector',
5112 PhactoriWarpByVectorOperation,
5113 operationParams)
5114 elif operationParams['type'] == 'clip':
5115 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5116 'clip',
5117 PhactoriClipPlaneOperation,
5118 operationParams)
5119 elif operationParams['type'] == 'slice':
5120 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5121 'slice',
5122 PhactoriSliceOperation,
5123 operationParams)
5124 elif operationParams['type'] == 'slicewithplane':
5125 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5126 'slicewithplane',
5127 PhactoriSliceWithPlaneOperation,
5128 operationParams)
5129 elif operationParams['type'] == 'boxclip':
5130 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5131 'boxclip',
5132 PhactoriBoxClipOperation,
5133 operationParams)
5134 elif operationParams['type'] == 'cylinderclip':
5135 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5136 'cylinderclip',
5137 PhactoriCylinderClipOperation,
5138 operationParams)
5139 elif (operationParams['type'] == 'element data to node data') or \
5140 (operationParams['type'] == 'elementdatatonodedata') or \
5141 (operationParams['type'] == 'cell data to point data') or \
5142 (operationParams['type'] == 'celldatatopointdata'):
5143 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5144 'element data to node data',
5145 PhactoriCellDataToPointDataOperation,
5146 operationParams)
5147 elif (operationParams['type'] == 'node data to element data') or \
5148 (operationParams['type'] == 'nodedatatoelementdata') or \
5149 (operationParams['type'] == 'point data to cell data') or \
5150 (operationParams['type'] == 'pointdatatocelldata'):
5151 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5152 'node data to element data',
5153 PhactoriPointDataToCellDataOperation,
5154 operationParams)
5155 elif operationParams['type'] == 'extractcomponent':
5156 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5157 'extractcomponent',
5158 PhactoriExtractComponentOperation,
5159 operationParams)
5160 elif operationParams['type'] == 'cellsize':
5161 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5162 'cellsize',
5163 PhactoriCellSizeOperation,
5164 operationParams)
5165 elif operationParams['type'] == 'appendlocationattributes':
5166 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5167 'appendlocationattributes',
5168 PhactoriAppendLocationAttributesOperation,
5169 operationParams)
5170 elif operationParams['type'] == 'integratevariables':
5171 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5172 'integratevariables',
5173 PhactoriIntegrateVariablesOperation,
5174 operationParams)
5175 elif operationParams['type' ] == 'nearestpoints':
5176 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5177 'nearestpoints',
5178 PhactoriNearestPointsOperation,
5179 operationParams)
5180 elif operationParams['type'] == 'castnormalrays':
5181 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5182 'castnormalrays',
5183 PhactoriIntersectNodeNormalsWithSurface,
5184 operationParams)
5185 elif operationParams['type'] == 'partitionedtomultiblock':
5186 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5187 'partitionedtomultiblock',
5188 PhactoriPartitionedToMultiBlockOperation,
5189 operationParams)
5190 elif operationParams['type'] == 'vtkdataexport':
5191 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5192 'vtkdataexport',
5193 PhactoriVtkDataExportOperation,
5194 operationParams)
5195 newOperationBlock.mOperationSpecifics.\
5196 SetPhactoriDataArtifactMetaDataControl(GetGlobalDataArtifactTracker())
5197 elif operationParams['type'] == 'exodusiiexport':
5198 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5199 'exodusiiexport',
5200 PhactoriExodusIIExportOperation,
5201 operationParams)
5202 elif operationParams['type'] == 'csvexport':
5203 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5204 'csvexport',
5205 PhactoriCSVExportOperation,
5206 operationParams)
5207 elif operationParams['type'] == 'contour':
5208 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5209 'contour',
5210 PhactoriContourOperation,
5211 operationParams)
5212 elif operationParams['type'] == 'streamtracer':
5213 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5214 'streamtracer',
5215 PhactoriStreamTracerOperation,
5216 operationParams)
5217 elif operationParams['type'] == 'streamtracerseedsource':
5218 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5219 'streamtracerseedsource',
5220 PhactoriStreamTracerSeedSourceOperation,
5221 operationParams)
5222 elif operationParams['type'] == 'resamplewithdataset':
5223 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5224 'resamplewithdataset',
5225 PhactoriResampleWithDatasetOperation,
5226 operationParams)
5227 elif operationParams['type'] == 'pointsourcefromjsonlist':
5228 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5229 'pointsourcefromjsonlist',
5230 PhactoriPointSourceFromJsonList,
5231 operationParams)
5232 elif operationParams['type'] == 'pointsourcenearbycorrelator':
5233 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5234 'pointsourcenearbycorrelator',
5235 PhactoriPointSourceNearbyCorrelator,
5236 operationParams)
5237 elif operationParams['type'] == 'pointsourcegeometrysampler1':
5238 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5239 'pointsourcegeometrysampler1',
5240 PhactoriPointSourceGeometrySampler1,
5241 operationParams)
5242 elif operationParams['type'] == 'segmentcellsampler3':
5243 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5244 'segmentcellsampler3',
5245 PhactoriSegmentCellSampler3,
5246 operationParams)
5247 elif operationParams['type'] == 'geometriccellsampler1':
5248 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5249 'geometriccellsampler1',
5250 PhactoriGeometricCellSampler1,
5251 operationParams)
5252 elif operationParams['type'] == 'extractsubsetwithseed':
5253 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5254 'extractsubsetwithseed',
5255 PhactoriExtractSubsetWithSeed,
5256 operationParams)
5257 elif operationParams['type'] == 'extractstructuredmultiblock':
5258 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5259 'extractstructuredmultiblock',
5260 PhactoriExtractStructuredMultiBlock,
5261 operationParams)
5262 elif operationParams['type'] == 'pointsource':
5263 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5264 'pointsource',
5265 PhactoriPointSource,
5266 operationParams)
5267 elif operationParams['type'] == 'planesource':
5268 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5269 'planesource',
5270 PhactoriPlaneSource,
5271 operationParams)
5272 elif operationParams['type'] == 'findcelledgelengths':
5273 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5274 'findcelledgelengths',
5275 PhactoriFindCellEdgeLengths,
5276 operationParams)
5277 elif operationParams['type'] == 'celledgeanglemetrics':
5278 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5279 'celledgeanglemetrics',
5280 PhactoriCellEdgeAngleMetrics,
5281 operationParams)
5282 elif operationParams['type'] == 'markcellsurfacestatus2':
5283 ParseOneFilterTypeFromViewMapOperation(newOperationBlock,
5284 'markcellsurfacestatus2',
5285 PhactoriMarkCellSurfaceStatus2,
5286 operationParams)
5287 else:
5288 errStr = 'error! in MakeFiltersFromViewMapOperationsC inOperationBlocksJson operation type is unrecognized ' + str(operationParams['type']) + '\n'
5289 if PhactoriDbg():
5290 myDebugPrint3(errStr)
5291 raise Exception(errStr)
5292
5293 ioPipeAndViewsState.mOperationBlocks[newOperationBlock.mName] = \
5294 newOperationBlock
5295
5296 #check to make sure no operation block calls for an input which doesn't exist
5297 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
5298 if operationBlock.mInputOperationName != None:
5299 if operationBlock.mInputOperationName not in ioPipeAndViewsState.mOperationBlocks:
5300 errStr = 'error! in MakeFiltersFromViewMapOperationsC operation block with name ' + str(operationName) + ' calls for nonexistent input operation with name ' + str(operationBlock.mInputOperationName) + '\n'
5301 if PhactoriDbg():
5302 myDebugPrint3(errStr)
5303 raise Exception(errStr)
5304
5305 if PhactoriDbg(100):
5306 myDebugPrint3("begin constructing all operation blocks\n",100)
5307 #now construct each filter in pipeline, being careful to construct them in a valid order, which causes multiple passes through the set
5308 #first, mark all as uncreated
5309 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
5310 if operationBlock.mHasBeenConstructed == None:
5311 operationBlock.mHasBeenConstructed = False
5312
5313 #we need to keep looping through the operation blocks until all have been constructed
5314 keepConstructing = True
5315 while keepConstructing:
5316 keepConstructing = False #at the beginning of the loop, we haven't seen any unconstructed operations
5317 for operationName, operationBlock in ioPipeAndViewsState.mOperationBlocks.items():
5318 if operationBlock.mHasBeenConstructed == False:
5319 #this one still needs constructing, and we'll have to loop again to
5320 #make sure all are constructed
5321 keepConstructing = True
5322
5323 #determine whether or not we can construct this operation yet, or if
5324 #we need to wait for something else to be constructed
5325 canBeConstructedNow = True
5326 inputOperationNames = operationBlock.GetListOfInputOperationNames()
5327 for opName in inputOperationNames:
5328 inputBlock = ioPipeAndViewsState.GetOperationBlockByName(opName)
5329 if inputBlock.mHasBeenConstructed == False:
5330 canBeConstructedNow = False
5331 break
5332
5333 if PhactoriDbg(100):
5334 myDebugPrint3("trying: " + str(operationName) + "\n" + \
5335 "depends on: " + str(inputOperationNames) + "\n" + \
5336 "canBeConstructedNow: " + str(canBeConstructedNow) + "\n",100)
5337 if canBeConstructedNow == True:
5338 #this operation's input has been constructed (or is None), so we can construct it
5339 ConstructPipelineOperationFromParsedOperationBlockC(ioPipeAndViewsState, operationBlock)
5340 operationBlock.mHasBeenConstructed = True
5341 if PhactoriDbg(100):
5342 myDebugPrint3("done constructing all operation blocks\n",100)
5343
5344
5345
5346 #helper method: given a block A which potentially contains a key B with
5347 #value BV, see if block set CS has key BV which indicates a refered-to
5348 #block. Return None if we can't get referred block, warn if A had key
5349 #but BV didn't exist in CS (A not having B merely returns None with no
5350 #complaint
5351 def FindReferredBlockC(referringBlock, referringKey, referredBlockset):
5352 #myDebugPrint3(' FindReferredBlockC entered\n',100)
5353 #myDebugPrint3(' referringBlock: ' + str(referringBlock) + '\n')
5354 #myDebugPrint3(' referringKey: ' + str(referringKey) + '\n')
5355 #myDebugPrint3(' referredBlockset: ' + str(referringKey) + '\n')
5356 if referringKey not in referringBlock:
5357 return None
5358 referredName = referringBlock[referringKey]
5359 if referredName in referredBlockset:
5360 return referredBlockset[referredName]
5361
5362 if PhactoriDbg():
5363 myDebugPrint3(' warning: ' + referringKey + ' was expected to be in referredBlockset but was not, returning None\n')
5364 return None
5365
5366 def UpdatePipelineWithCurrentTimeArgument(inParaViewFilter):
5367 global gPipeAndViewsState
5368 if gPipeAndViewsState == None:
5369 inParaViewFilter.UpdatePipeline()
5370 return
5371 thisTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
5372 inParaViewFilter.UpdatePipeline(thisTime)
5373
5374 def SetParaViewViewToCurrentTime(inParaViewView):
5375 global gPipeAndViewsState
5376 thisTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
5377 inParaViewView.ViewTime = thisTime
5378
5379 def CreateParaViewRepresentationAndViewFromInfoC(inImageset, inLookDirection, inLookDirectionFilenameAddonL):
5380 global gPipeAndViewsState
5381
5382 if PhactoriDbg(100):
5383 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC entered\n",100)
5384 if PhactoriDbg():
5385 myDebugPrint3(" imageset: " + inImageset.mName + "\n")
5386 if PhactoriDbg():
5387 myDebugPrint3(" lookdir : " + str(inLookDirection) + " file name addon: " + str(inLookDirectionFilenameAddonL) + "\n")
5388
5389 newLookDirection = list(inLookDirection)
5390 inImageset.mLookDirectionList.append(newLookDirection)
5391 inImageset.mLookDirectionFilenameAddon.append(inLookDirectionFilenameAddonL)
5392
5393 theRepresentation = inImageset.mRepresentation
5394 theOperation = inImageset.mOperation
5395 inCamera = inImageset.mCamera
5396
5397 #we are setting this up, for now, so that you MUST have a representation at this
5398 #point--default should have been added and referenced earlier
5399 if theRepresentation == None:
5400 errStr = 'error! theRepresentation is None in CreateParaviewItemsForImagesetC\n'
5401 if PhactoriDbg():
5402 myDebugPrint3(errStr)
5403 raise Exception(errStr)
5404
5405 meshRenderControl = theRepresentation.mMeshRenderControl
5406
5407 showColorLegend = theRepresentation.mColorLegendFlag
5408 colorLegendPositionAndSize = theRepresentation.mColorLegendPositionAndSize
5409 showDataCubeAxes = theRepresentation.mDataCubeAxesFlag
5410 showOrientationAxes = theRepresentation.mOrientationAxesFlag
5411 if theRepresentation.mUseFixedColorRange == True:
5412 fixedColorRange = theRepresentation.mFixedColorRange
5413 else:
5414 fixedColorRange = None
5415
5416 savedActiveSource = GetActiveSource()
5417 if PhactoriDbg():
5418 myDebugPrint3(" operation is " + theOperation.mName + \
5419 " with ParaView Filter " + str(theOperation.GetPvFilter()) + "\n")
5420 pvPvGeomFilterFromOp = theOperation.GetOutgoingPvGeometryFilter()
5421 if PhactoriDbg():
5422 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC:\n"
5423 "setting active source to exterior geometry filter from operation\n"
5424 "active source A: " + str(GetActiveSource()) + "\n")
5425 SetActiveSource(pvPvGeomFilterFromOp)
5426 if PhactoriDbg():
5427 myDebugPrint3("active source B1: " + str(pvPvGeomFilterFromOp) + "\n")
5428 myDebugPrint3("active source B: " + str(GetActiveSource()) + "\n")
5429 UpdatePipelineWithCurrentTimeArgument(pvPvGeomFilterFromOp)
5430
5431 if PhactoriDbg():
5432 myDebugPrint3(" operation point data arrays:\n")
5433 numArrays = pvPvGeomFilterFromOp.PointData.GetNumberOfArrays()
5434 for ii in range (0, numArrays):
5435 myDebugPrint3(" " + str(ii) + ": " + pvPvGeomFilterFromOp.PointData.GetArray(ii).GetName() + "\n")
5436
5437 if PhactoriDbg():
5438 myDebugPrint3(" operation cell data arrays:\n")
5439 numArrays = pvPvGeomFilterFromOp.CellData.GetNumberOfArrays()
5440 for ii in range (0, numArrays):
5441 myDebugPrint3(" " + str(ii) + ": " + pvPvGeomFilterFromOp.CellData.GetArray(ii).GetName() + "\n")
5442
5443 if theRepresentation.mColorVariableInfo.mVariableName == '':
5444 myVariableArrayType = gCellsString
5445 else:
5446 #paraViewSource = \
5447 # gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
5448 paraViewSource = pvPvGeomFilterFromOp
5449 detectResult = theRepresentation.mColorVariableInfo.DetectVariableType(
5450 paraViewSource, True, False)
5451
5452 if detectResult == True:
5453 #variable type detected determine value for paraview
5454 if theRepresentation.mColorVariableInfo.mVariableType == 'node':
5455 myVariableArrayType = gPointsString
5456 elif theRepresentation.mColorVariableInfo.mVariableType == 'element':
5457 myVariableArrayType = gCellsString
5458 else:
5459 if PhactoriDbg():
5460 myDebugPrint3(errStr)
5461 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
5462 'image set ' + inImageset.mName + \
5463 ' representation ' + theRepresentation.mName + \
5464 '\ncolor variable name: ' + \
5465 theRepresentation.mColorVariableInfo.mVariableName +\
5466 '\nvariable should be node or element at this point and is not'
5467 raise Exception(errStr)
5468 else:
5469 #variable type not detected, deal with it
5470 errStr = 'CreateParaviewItemsForImagesetC error:\n'\
5471 'image set ' + inImageset.mName + \
5472 ' representation ' + theRepresentation.mName + \
5473 '\ncolor variable name: ' + \
5474 theRepresentation.mColorVariableInfo.mVariableName +\
5475 '\nvariable is not point data or cell data, assuming cell'
5476 if PhactoriDbg():
5477 myDebugPrint3(errStr)
5478 #current hack--if detection of variable type fails due to missing
5479 #variable; assume it is CELLS and let mpi stuff share info
5480 #and create odd color map otherwise
5481 myVariableArrayType = gCellsString
5482
5483 global gCameraFilenameSuffixCounter
5484 gCameraFilenameSuffixCounter = 0
5485 SetUpOneParaViewRepresentationAndViewC(inImageset.mCamera,
5486 inLookDirection,
5487 inImagesetInfo = inImageset,
5488 inColorSettingsX = inImageset.mRepresentation.mColorSettings,
5489 inMeshRenderControl = meshRenderControl,
5490 inShowDataCubeAxes = showDataCubeAxes,
5491 inShowDataCubeAxesInfo = theRepresentation.mDataCubeAxesInfo,
5492 inShowOrientationAxes = showOrientationAxes,
5493 inFixedColorRange = fixedColorRange,
5494 inIsPlotFlag = False,
5495 inRepresentationFilenameAddon = theRepresentation.mFilenameAddon,
5496 inLookDirectionFilenameAddon = inLookDirectionFilenameAddonL,
5497 inPhactoriRepresentation = theRepresentation)
5498
5499 global currentPhactoriRenderViewInfo
5500 #newParaViewRenderInfoC.mParaViewInfo = currentPhactoriRenderViewInfo
5501
5502 if PhactoriDbg(100):
5503 myDebugPrint3("CreateParaViewRepresentationAndViewFromInfoC returning\n", 100)
5504
5505 SetActiveSource(savedActiveSource)
5506
5507 if 1:
5508 if PhactoriDbg(100):
5509 myDebugPrint3("trying time annotation stuff\n", 100)
5510 timeAnnStngs = inImageset.mRepresentation.mTimeAnnotationSettings
5511 #since we are now using one RenderView, we can share a single time
5512 #annotation source representation. However, it is conceivable that
5513 #we may eventually want to show different times for some reason, and
5514 #in that case we will need to have each imageset have its own time
5515 #annotation paraview stuff
5516 if timeAnnStngs.mVisible:
5517 if gPipeAndViewsState.mTimeAnnotationPv == None:
5518 gPipeAndViewsState.mTimeAnnotationPv = \
5519 PhactoriAnnotationPv(timeAnnStngs)
5520 global gTemporaryGlobalImageTextColor
5521 gPipeAndViewsState.mTimeAnnotationPv.CreateParaViewStuff(
5522 #inImageset.mRepresentation.mColorSettings.mTimeAnnotationColor,
5523 gTemporaryGlobalImageTextColor,
5524 inImageset)
5525
5526 #if newParaViewRenderInfoC.mTimeAnnotationPv == None:
5527 # newParaViewRenderInfoC.mTimeAnnotationPv = \
5528 # PhactoriAnnotationPv(timeAnnStngs)
5529 # newParaViewRenderInfoC.mTimeAnnotationPv.CreateParaViewStuff(
5530 # inImageset.mRepresentation.mColorSettings.mTimeAnnotationColor,
5531 # inImageset)
5532
5533
5534 def CreateParaviewItemsForImagesetC(inImageset):
5535 "given a json block structure as discussed in the catalyst sierra\n insitu wiki, create the corresponding one imageset (view) based on\n a particular imageset block and the availa"
5536
5537 theCamera = inImageset.mCamera
5538
5539 #we are setting this up, for now, so that you MUST have a camera at this
5540 #point--default should have been added and referenced earlier
5541 if theCamera == None:
5542 errStr = 'error! theCamera is None in "\
5543 "CreateParaviewItemsForImagesetC\n'
5544 if PhactoriDbg():
5545 myDebugPrint3(errStr)
5546 raise Exception(errStr)
5547
5548 cameraLookDirectionAndFilenameAddonList = GetLookDirectionListFromCamera(theCamera)
5549
5550 #counter = 0
5551 for oneItem in cameraLookDirectionAndFilenameAddonList:
5552 #print oneItem
5553 oneDirection = oneItem[0]
5554 oneDirectionFilenameAddon = oneItem[1]
5555 CreateParaViewRepresentationAndViewFromInfoC(inImageset, oneDirection,
5556 oneDirectionFilenameAddon)
5557 #counter = counter + 1
5558
5559 def ParseOneCriteriaBlockC(ioCriteriaBlock, ioCriteriaBlockJson,
5560 inPipeAndViewsState):
5561 ioCriteriaBlock.ParseParametersFromJson(ioCriteriaBlockJson)
5562
5563 def ParseOneMarkerBlockC(ioMarkerBlock, ioBlockJson,
5564 inPipeAndViewsState):
5565 ioMarkerBlock.ParseMarkerSettingsFromJson(ioBlockJson)
5566
5567 def ParseOneTextAnnotationBlockC(ioTextAnnotationBlock, ioBlockJson,
5568 inPipeAndViewsState):
5569 ioTextAnnotationBlock.ParseTextAnnotationSettingsFromJson(ioBlockJson)
5570
5571 def ParseOneCameraBlockC(ioCameraBlock, ioCameraBlockJson, inPipeAndViewsState):
5572 #parse camera type
5573 if 'camera type' not in ioCameraBlockJson:
5574 errStr = 'error! camera block with name ' + str(ioCameraBlock.mName) + \
5575 ' has no camera type key in ParseCameraBlocksC\n'
5576 if PhactoriDbg():
5577 myDebugPrint3(errStr)
5578 raise Exception(errStr)
5579
5580 cameraType = ioCameraBlockJson['camera type']
5581
5582 if cameraType != 'camera' and cameraType != 'multicamera8':
5583 errStr = 'camera type entry is not recognized in camera ' + ioCameraBlock.mName + ' ParseCameraBlocksC\n'
5584 if PhactoriDbg():
5585 myDebugPrint3(errStr)
5586 raise Exception(errStr)
5587
5588 ioCameraBlock.mType = cameraType
5589
5590 #check for camera at node|element displaced settings
5591 ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \
5592 ioCameraBlockJson, "camera at ", " displaced", True)
5593 if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting == False:
5594 #check for camera at settings (not displaced) if there weren't displaced ones
5595 ioCameraBlock.mCameraAtPointInfo.UserPointInfoParseParametersFromJson( \
5596 ioCameraBlockJson, "camera at ", "", False)
5597 if ioCameraBlock.mCameraAtPointInfo.mParsingDetectedAtLeastOneSetting:
5598 ioCameraBlock.mUseCameraAtPointFlag = True
5599 else:
5600 ioCameraBlock.mUseCameraAtPointFlag = False
5601
5602 if PhactoriDbg():
5603 myDebugPrint3("camera parsing look at point:\n")
5604 ioCameraBlock.mLookAtPointInfo.UserPointInfoParseParametersFromJson(ioCameraBlockJson,
5605 "look at ", "")
5606
5607 #parse look at distance
5608 if 'look at relative distance' in ioCameraBlockJson:
5609 ioCameraBlock.mLookAtDistanceType = 'datasize relative'
5610 ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at relative distance']
5611 #if 'camera at point' was specified, look at distance should not
5612 #be specified
5613 elif 'look at absolute distance' in ioCameraBlockJson:
5614 ioCameraBlock.mLookAtDistanceType = 'absolute'
5615 ioCameraBlock.mLookAtDistance = ioCameraBlockJson['look at absolute distance']
5616 #if 'camera at point' was specified, look at distance should not
5617 #be specified
5618 else:
5619 ioCameraBlock.mLookAtDistanceType = 'datasize relative'
5620 ioCameraBlock.mLookAtDistance = 1.0
5621
5622 #parse look direction (single camera, not multicamera8)
5623 if ioCameraBlock.mType == 'camera':
5624 ioCameraBlock.mLookDirection = [-1.0, -1.0, -1.0]
5625 if 'look direction' in ioCameraBlockJson:
5626 ioCameraBlock.mLookDirection = ioCameraBlockJson['look direction']
5627 ioCameraBlock.mLookDirectionSpecifiedFlag = True
5628 else:
5629 ioCameraBlock.mLookDirectionSpecifiedFlag = False
5630
5631 #get text to add to each image created with this camera, if any
5632 if "image name addon" in ioCameraBlockJson:
5633 ioCameraBlock.mFilenameAddon = ioCameraBlockJson["image name addon"]
5634
5635 #camera field of view (for default use current value which was set at
5636 #creation time--see class definition for default
5637 ioCameraBlock.mViewAngle = getParameterFromBlock(ioCameraBlockJson,
5638 'camera fov', ioCameraBlock.mViewAngle)
5639
5640 #up vector for the view (for default use current value which was set at
5641 #creation time--see class definition for default)
5642 ioCameraBlock.mViewUpVector = getParameterFromBlock(ioCameraBlockJson,
5643 'up vector', ioCameraBlock.mViewUpVector)
5644
5645 #parse off-axis projection info
5646 ioCameraBlock.mOffAxisProjectionInfo.ParseParametersFromJson(
5647 ioCameraBlockJson)
5648
5649 #parse parallel projection info
5650 perspectiveOrParallel = getParameterFromBlock(ioCameraBlockJson,
5651 'projection type', 'perspective')
5652 if perspectiveOrParallel == 'parallel':
5653 ioCameraBlock.mUseParallelProjection = True
5654 if PhactoriDbg(100):
5655 myDebugPrint3("projection type is now parallel\n", 100)
5656 if 'absolute parallel scale' in ioCameraBlockJson:
5657 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 0
5658 ioCameraBlock.mParallelScale = \
5659 ioCameraBlockJson['absolute parallel scale']
5660 if PhactoriDbg(100):
5661 myDebugPrint3("absolute parallel scale: " + \
5662 str(ioCameraBlock.mParallelScale) + "\n", 100)
5663 elif 'relative parallel scale' in ioCameraBlockJson:
5664 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1
5665 ioCameraBlock.mParallelScale = \
5666 ioCameraBlockJson['relative parallel scale']
5667 if PhactoriDbg(100):
5668 myDebugPrint3("relative parallel scale: " + \
5669 str(ioCameraBlock.mParallelScale) + "\n", 100)
5670 else:
5671 ioCameraBlock.mParallelScale = 1.0
5672 ioCameraBlock.mParallelScaleAbsoluteOrRelative = 1
5673 if PhactoriDbg(100):
5674 myDebugPrint3("default relative parallel scale: " + \
5675 str(ioCameraBlock.mParallelScale) + "\n", 100)
5676
5677 #parse locking setup
5678 ioCameraBlock.LockAfterNCalls = getParameterFromBlock(ioCameraBlockJson,
5679 'lock camera call count', -1)
5680 if "lockingcamera" in ioCameraBlock.mName:
5681 ioCameraBlock.LockAfterNCalls = 1
5682
5683
5684 def localGet1or0(inJsn, inKey, inDefault):
5685 value = getParameterFromBlock(inJsn, inKey, inDefault)
5686 if value:
5687 return 1
5688 else:
5689 return 0
5690
5691 def ParseOneRepresentationBlockC(ioRepresentationBlock, inRepresentationBlockJson, inPipeAndViewsState):
5692 ioRepresentationBlock.ParseSettingsFromJson(inRepresentationBlockJson)
5693
5694 global gDefaultImageBasename
5695 gDefaultImageBasename = "csierra.view."
5696
5697 def SetDefaultImageBasename(inNewImageBasename):
5698 global gDefaultImageBasename
5699 gDefaultImageBasename = inNewImageBasename
5700
5701 def breakSpecialVarNameIntoBaseAndComponent(inSpecialVarName,
5702 inAddSeparatorFlag):
5703
5704 twoDigitComponentFlag = False
5705
5706 varNameLen = len(inSpecialVarName)
5707 if varNameLen < 2:
5708 errStr = ' in breakSpecialVarNameIntoBaseAndComponent representation bad color by vector component name (too short)\n'
5709 if PhactoriDbg():
5710 myDebugPrint3(errStr)
5711 raise Exception(errStr)
5712 lastVarChar = inSpecialVarName[varNameLen - 1]
5713 if PhactoriDbg():
5714 myDebugPrint3(' lastVarChar: ' + str(lastVarChar) + '\n')
5715 if lastVarChar == 'X' or lastVarChar == 'x':
5716 component = 0
5717 elif lastVarChar == 'Y' or lastVarChar == 'y':
5718 component = 1
5719 elif lastVarChar == 'Z' or lastVarChar == 'z':
5720 component = 2
5721 elif str(lastVarChar).isdigit():
5722 end2car = inSpecialVarName[varNameLen-2:varNameLen]
5723 if PhactoriDbg():
5724 myDebugPrint3(' end2car: ' + end2car + ' isdigit: ' + str(end2car.isdigit()) + '\n')
5725 if end2car.isdigit():
5726 twoDigitComponentFlag = True
5727 component = int(end2car)
5728 else:
5729 component = int(str(lastVarChar))
5730 else:
5731 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'
5732 if PhactoriDbg():
5733 myDebugPrint3(errStr)
5734 raise Exception(errStr)
5735 #baseVarName = inSpecialVarName[0:(varNameLen-2)] + GetSeparatorString()
5736
5737 localinAddSeparatorFlag = inAddSeparatorFlag
5738 #for Sierra, as of 2022Aug09, we need inAddSeparatorFlag to default to
5739 #False but right here we need to strip the separator from the variable
5740 #base name
5741 #localinAddSeparatorFlag = True
5742 if localinAddSeparatorFlag:
5743 lenToGrab = varNameLen - 1 - len(GetSeparatorString())
5744 else:
5745 lenToGrab = varNameLen - 1
5746 if twoDigitComponentFlag:
5747 lenToGrab -= 1
5748
5749 varNameWithoutSeparator = inSpecialVarName[0:lenToGrab]
5750
5751 if inAddSeparatorFlag:
5752 baseVarName = varNameWithoutSeparator + GetSeparatorString()
5753 else:
5754 baseVarName = varNameWithoutSeparator
5755
5756 return [baseVarName, component, varNameWithoutSeparator]
5757
5758 def CreateDirectoryFromProcessZero(inDirname):
5759 if SmartGetLocalProcessId() != 0:
5760 if PhactoriDbg():
5761 myDebugPrint3('CreateDirectoryFromProcessZero, not process 0\n')
5762 return
5763
5764 if inDirname == '':
5765 if PhactoriDbg():
5766 myDebugPrint3('CreateDirectoryFromProcessZero, no directory to create\n')
5767 return
5768
5769 #test for directory existence, try to create if not existing
5770 import os
5771 if PhactoriDbg():
5772 myDebugPrint3('find or create directory: ' + str(inDirname) + '\n')
5773 if os.path.exists(inDirname):
5774 if os.path.isdir(inDirname) != True:
5775 errStr = \
5776 ' path to base directory exists and is not a directory\n' + \
5777 ' (' + str(inDirname) + ')\n'
5778 myDebugPrint3AndException(errStr)
5779 else:
5780 if PhactoriDbg():
5781 myDebugPrint3('inDirname found and is directory\n')
5782 else:
5783 if PhactoriDbg():
5784 myDebugPrint3(str(inDirname) + ' to be created\n')
5785 try:
5786 os.makedirs(inDirname)
5787 except:
5788 errStr = \
5789 ' failed (1) to create directory\n' + \
5790 ' (' + str(inDirname) + ')\n'
5791 myDebugPrint3AndException(errStr)
5792 if os.path.exists(inDirname) != True:
5793 errStr = \
5794 ' failed (2) to create directory\n' + \
5795 ' (' + str(inDirname) + ')\n'
5796 myDebugPrint3AndException(errStr)
5797
5798 class PhactoriImageSettings:
5799 def __init__(self):
5800 self.mImageBasename = None
5801 global gPipeAndViewsState
5802 self.mImageBasedirectory = gPipeAndViewsState.mDefaultBasedirectory
5803 global gDefaultImageSizeX
5804 global gDefaultImageSizeY
5805 self.mImageSize = [gDefaultImageSizeX, gDefaultImageSizeY]
5806 self.mImageFormat = 'png'
5807 global gDefaultNumCounterDigits
5808 self.mNumCounterDigits = gDefaultNumCounterDigits
5809 self.mUsingDefaultGeneratedImageBasename = False
5810 self.mPixelBorderRatioXY = gPixelBorderRatioXY
5811 def GetAspectRatio(self):
5812 return float(self.mImageSize[0]) / float(self.mImageSize[1])
5813 def GetAspectRatioInsidePixelBorder(self):
5814 vertPixBrdrX = self.mPixelBorderRatioXY[0] * float(self.mImageSize[0])
5815 vertPixBrdrY = self.mPixelBorderRatioXY[1] * float(self.mImageSize[1])
5816 vertPixBrdrX = math.ceil(vertPixBrdrX)
5817 vertPixBrdrY = math.ceil(vertPixBrdrY)
5818 insideVertPixX = float(self.mImageSize[0]) - 2.0 * vertPixBrdrX
5819 insideVertPixY = float(self.mImageSize[1]) - 2.0 * vertPixBrdrY
5820 insideAspectRatio = insideVertPixX / insideVertPixY
5821 return insideAspectRatio
5822
5823 def ParseImageSettingsInfo(self, inImageSettingsJson,
5824 inImageBasenameKey, inImageBaseDirectoryKey):
5825 self.mImageBasename = getParameterFromBlock(inImageSettingsJson,
5826 inImageBasenameKey, self.mImageBasename)
5827 if self.mImageBasename == None:
5828 global gDefaultImageBasename
5829 global gPipeAndViewsState
5830 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
5831 imageSetCount = gPipeAndViewsState.mImageSetCounter
5832 gPipeAndViewsState.mImageSetCounter += 1
5833 self.mImageBasename = gDefaultImageBasename + \
5834 ".b-" + blockCountIdStr + "-is-" + str(imageSetCount) + "."
5835 self.mUsingDefaultGeneratedImageBasename = True
5836
5837 self.mImageBasedirectory = getParameterFromBlock(inImageSettingsJson,
5838 inImageBaseDirectoryKey, self.mImageBasedirectory)
5839
5840 CreateDirectoryFromProcessZero(self.mImageBasedirectory)
5841
5842 global gDefaultImageSizeX
5843 global gDefaultImageSizeY
5844 self.mImageSize = getParameterFromBlock(inImageSettingsJson,
5845 'image size', self.mImageSize)
5846
5847 self.mImageFormat = getParameterFromBlock(inImageSettingsJson,
5848 'image format', self.mImageFormat)
5849
5850 self.mNumCounterDigits = getParameterFromBlock(\
5851 inImageSettingsJson,
5852 'image digit count', self.mNumCounterDigits)
5853 if PhactoriDbg():
5854 myDebugPrint3(' mNumCounterDigits is ' + str(self.mNumCounterDigits) + '\n')
5855
5856
5857 def ParseOneImagesetBlockC(ioImagesetBlock, ioImagesetBlockJson,
5858 ioPipeAndViewsState):
5859
5860 #hack--if we have an imageset with a particular name, we enable
5861 #interaction
5862 if ioImagesetBlock.mName == 'PhactoriGoInteractive':
5863 ioPipeAndViewsState.mInteractionEnabled = True
5864
5865 #we need to get text color for time annotation and text annotation
5866 #handled properly: for now we allow a "text color" setting in any
5867 #imageset block to set the global text color
5868 if 'text color' in ioImagesetBlockJson:
5869 global gTemporaryGlobalImageTextColor
5870 gTemporaryGlobalImageTextColor = getParameterFromBlock(ioImagesetBlockJson,
5871 'text color', [1.0, 1.0, 1.0])
5872
5873 ioImagesetBlock.mBackground = getParameterFromBlock(ioImagesetBlockJson,
5874 'background color', ioImagesetBlock.mBackground)
5875
5876 #parse on/off criteria
5877 if 'onoff criteria' in ioImagesetBlockJson:
5878 inCriteriaList = ioImagesetBlockJson['onoff criteria']
5879 for oneCriteriaName in inCriteriaList:
5880 if oneCriteriaName not in \
5881 ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks:
5882 myDebugPrint3AndException("ParseOneImagesetBlockC:"
5883 "imageset with name: " + ioImagesetBlock.mName + "\n"
5884 "calls for nonexistent onoff criteria with name: " + \
5885 oneCriteriaName + "\n")
5886 ioImagesetBlock.mImagesetOnOffFilter.AddStartCriteria( \
5887 ioPipeAndViewsState.mImagesetOnOffCriteriaBlocks[oneCriteriaName])
5888
5889 if 'camera' not in ioImagesetBlockJson:
5890 #we have to construct and use a default camera, including parsing
5891 #commands in the imageset for the camera
5892 if PhactoriDbg():
5893 myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
5894 ioImagesetBlock.mName + \
5895 " there is no camera, so we must add and reference default\n")
5896 if 'camera type' not in ioImagesetBlockJson:
5897 ioImagesetBlockJson['camera type'] = 'multicamera8'
5898 defaultCameraName = ioImagesetBlock.mName + '_default_camera'
5899 defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}
5900 ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,
5901 defaultCameraBlockAndWrapper,
5902 PhactoriCameraBlock,
5903 ParseOneCameraBlockC,
5904 ioPipeAndViewsState)
5905 ioImagesetBlockJson['camera'] = defaultCameraName
5906 #myDebugPrint3( "done adding camera, here it is:\n")
5907 #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()
5908
5909
5910 #there is a camera (if there wasn't, we added it), so get the reference
5911 cameraName = ioImagesetBlockJson['camera']
5912 if cameraName not in ioPipeAndViewsState.mCameraBlocks:
5913 errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for camera (' + str(cameraName) + ') which does not exist\n'
5914 if PhactoriDbg():
5915 myDebugPrint3(errStr)
5916 raise Exception(errStr)
5917
5918 ioImagesetBlock.mCamera = ioPipeAndViewsState.mCameraBlocks[cameraName]
5919 if PhactoriDbg():
5920 myDebugPrint3(" image set " + ioImagesetBlock.mName + " is using the following camera:\n")
5921 ioImagesetBlock.mCamera.PrintSelf()
5922
5923 if 'markers' in ioImagesetBlockJson:
5924 ioImagesetBlock.mVisibleMarkerNames = ioImagesetBlockJson['markers']
5925 for oneMarkerName in ioImagesetBlock.mVisibleMarkerNames:
5926 if oneMarkerName in ioPipeAndViewsState.mMarkerBlocks:
5927 ioImagesetBlock.mVisibleMarkers.append(
5928 ioPipeAndViewsState.mMarkerBlocks[oneMarkerName])
5929 else:
5930 myDebugPrint3AndException(
5931 "ParseOneImagesetBlockC:\n" \
5932 "image set with name: " + ioImagesetBlock.mName + "\n"
5933 "calls for nonexistent marker named: " + oneMarkerName + "\n")
5934
5935 if 'text annotations' in ioImagesetBlockJson:
5936 ioImagesetBlock.mTextAnnotationNames = \
5937 ioImagesetBlockJson['text annotations']
5938 for oneMarkerName in ioImagesetBlock.mTextAnnotationNames:
5939 if oneMarkerName in ioPipeAndViewsState.mTextAnnotationBlocks:
5940 ioImagesetBlock.mTextAnnotations.append(
5941 ioPipeAndViewsState.mTextAnnotationBlocks[oneMarkerName])
5942 else:
5943 myDebugPrint3AndException(
5944 "ParseOneImagesetBlockC:\n" \
5945 "image set with name: " + ioImagesetBlock.mName + "\n"
5946 "calls for nonexistent marker named: " + oneMarkerName + "\n")
5947
5948 #if 'representation' not in ioImagesetBlockJson:
5949 # #we have to construct and use a default representation, including parsing
5950 # #commands in the imageset for the representation
5951 # if PhactoriDbg():
5952 # myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
5953 # ioImagesetBlock.mName + \
5954 # " there is no representation, " +
5955 # "so we must add and reference default\n")
5956 # defaultRepName = ioImagesetBlock.mName + '_default_representation'
5957 # defaultRepBlockAndWrapper = {defaultRepName: ioImagesetBlockJson}
5958 # ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,
5959 # defaultRepBlockAndWrapper,
5960 # PhactoriRepresentationBlock,
5961 # ParseOneRepresentationBlockC,
5962 # ioPipeAndViewsState)
5963 # ioImagesetBlockJson['representation'] = defaultRepName
5964
5965 #if 'representation' in ioImagesetBlockJson:
5966 # representationName = ioImagesetBlockJson['representation']
5967 # if representationName not in ioPipeAndViewsState.mRepresentationBlocks:
5968 # errStr = ' in ParseOneImagesetBlockC imageset (' + str(ioImagesetBlock.mName) + ') calls for representation (' + str(representationName) + ') which does not exist\n'
5969 # if PhactoriDbg():
5970 # myDebugPrint3(errStr)
5971 # raise Exception(errStr)
5972 # ioImagesetBlock.mRepresentation = ioPipeAndViewsState.mRepresentationBlocks[representationName]
5973 #else:
5974 # ioImagesetBlock.mRepresentation = None #need to use default representation
5975 #ioImagesetBlock.mVisibleReps.append(ioImagesetBlock.mRepresentation)
5976
5977 ##get the operation referred to by this image set (or the default incoming
5978 ##data)
5979 #ioImagesetBlock.mOperation =\
5980 # ioPipeAndViewsState.GetOperationReferredByJson(
5981 # 'operation', ioImagesetBlockJson)
5982 #ioImagesetBlock.mVisibleOps.append(ioImagesetBlock.mOperation)
5983
5984 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
5985 ioImagesetBlockJson, 'operation', False, 'representation', False, False)
5986 ioImagesetBlock.mOperation = ioImagesetBlock.mVisibleOps[0]
5987 ioImagesetBlock.mRepresentation = ioImagesetBlock.mVisibleReps[0]
5988
5989 #initial implementation of having more than one operation visible:
5990 #have up to 3 visible with particular parsing names
5991 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
5992 ioImagesetBlockJson, 'operation2', True, 'representation2', True, True)
5993 ioImagesetBlock.ParseOperationAndRepresentationPair(ioPipeAndViewsState,
5994 ioImagesetBlockJson, 'operation3', True, 'representation3', True, True)
5995
5996 ioImagesetBlock.mImageSettings.ParseImageSettingsInfo(
5997 ioImagesetBlockJson, 'image basename', 'image basedirectory')
5998 ioImagesetBlock.mImageFileNameCountSettings.\
5999 ParseImageFileNameCountSettings(ioImagesetBlockJson)
6000
6001
6002 def SetUpPlotAxisNameDetails(inVariableInfo, ioDataCubeAxisInfo):
6003 if inVariableInfo.mVariableIsVectorComponent:
6004 if PhactoriDbg():
6005 myDebugPrint3(" vector is component, setting y axis name\n")
6006 varNameForPlot = inVariableInfo.mVectorBaseName
6007 if inVariableInfo.mVariableComponent == 0:
6008 varNameForPlot = varNameForPlot + '[x]'
6009 elif inVariableInfo.mVariableComponent == 1:
6010 varNameForPlot = varNameForPlot + '[y]'
6011 elif inVariableInfo.mVariableComponent == 2:
6012 varNameForPlot = varNameForPlot + '[z]'
6013 else:
6014 varNameForPlot = varNameForPlot + str(inVariableInfo.mVariableComponent)
6015 ioDataCubeAxisInfo.mUseLabelFlag = True
6016 ioDataCubeAxisInfo.mAxisLabel = varNameForPlot
6017 ioDataCubeAxisInfo.mBaseAxisLabel = varNameForPlot
6018 if PhactoriDbg():
6019 myDebugPrint3(" y axis name is " + ioDataCubeAxisInfo.mAxisLabel + "\n")
6020 elif inVariableInfo.mVariableIsVectorMagnitude:
6021 if PhactoriDbg():
6022 myDebugPrint3(" vector is magnitude, setting y axis name\n")
6023 varNameForPlot = inVariableInfo.mVectorBaseName
6024 varNameForPlot = varNameForPlot + " Magnitude"
6025 ioDataCubeAxisInfo.mUseLabelFlag = True
6026 ioDataCubeAxisInfo.mAxisLabel = varNameForPlot
6027 ioDataCubeAxisInfo.mBaseAxisLabel = varNameForPlot
6028 if PhactoriDbg():
6029 myDebugPrint3(" y axis name is " + ioDataCubeAxisInfo.mAxisLabel + "\n")
6030 else:
6031 ioDataCubeAxisInfo.mUseLabelFlag = True
6032 ioDataCubeAxisInfo.mAxisLabel = inVariableInfo.mVariableName
6033 ioDataCubeAxisInfo.mBaseAxisLabel = inVariableInfo.mVariableName
6034
6035 def ParseOnePlotOverTimeBlockC(ioPlotOverTimeBlock, inPlotOverTimeBlockJson, inPipeAndViewsState):
6036 if PhactoriDbg(100):
6037 myDebugPrint3('ParseOnePlotOverTimeBlockC entered\n', 100)
6038
6039 #hack test for colors start
6040 #inPlotOverTimeBlockJson['background color'] = [0.0, 0.0, 0.0]
6041 ##inJsn['axes color'] = [0.0, 1.0, 1.0]
6042 #inPlotOverTimeBlockJson['text color'] = [1.0, 1.0, 0.0]
6043 #inPlotOverTimeBlockJson['line color'] = [1.0, 1.0, 1.0]
6044 #hack test for colors end
6045
6046 ioPlotOverTimeBlock.mImageSettings.ParseImageSettingsInfo(
6047 inPlotOverTimeBlockJson, 'plot basename', 'plot basedirectory')
6048 ioPlotOverTimeBlock.mImageFileNameCountSettings.\
6049 ParseImageFileNameCountSettings(inPlotOverTimeBlockJson)
6050
6051 ioPlotOverTimeBlock.mBackground = getParameterFromBlock(inPlotOverTimeBlockJson,
6052 'background color', ioPlotOverTimeBlock.mBackground)
6053
6054 if PhactoriDbg():
6055 myDebugPrint3(str(inPlotOverTimeBlockJson) + '\n')
6056
6057 #parse y axis variable
6058 ioPlotOverTimeBlock.m_YAxisVariableInfo.\
6059 ParseVariableNameAndVectorOrTensorComponent(inPlotOverTimeBlockJson,
6060 'variable ')
6061
6062 #handle name of axis, particularly in vector component/magnitude case
6063 SetUpPlotAxisNameDetails(ioPlotOverTimeBlock.m_YAxisVariableInfo,
6064 ioPlotOverTimeBlock.m_DataCubeAxesInfo.mYAxisInfo)
6065
6066 #parse whether to draw min, max mean
6067 if 'plot minimum' in inPlotOverTimeBlockJson:
6068 ioPlotOverTimeBlock.mPlotMinimumFlag = inPlotOverTimeBlockJson['plot minimum']
6069 else:
6070 ioPlotOverTimeBlock.mPlotMinimumFlag = True
6071 if 'plot maximum' in inPlotOverTimeBlockJson:
6072 ioPlotOverTimeBlock.mPlotMaximumFlag = inPlotOverTimeBlockJson['plot maximum']
6073 else:
6074 ioPlotOverTimeBlock.mPlotMaximumFlag = True
6075 if 'plot mean' in inPlotOverTimeBlockJson:
6076 ioPlotOverTimeBlock.mPlotMeanFlag = inPlotOverTimeBlockJson['plot mean']
6077 else:
6078 ioPlotOverTimeBlock.mPlotMeanFlag = True
6079
6080 if 'plot id' in inPlotOverTimeBlockJson:
6081 idList = inPlotOverTimeBlockJson['plot id']
6082 for ii in idList:
6083 newIdPlotLine = PhactoriPlotOverTimeIdLine(ii)
6084 ioPlotOverTimeBlock.m_IdPlotLineList.append(newIdPlotLine)
6085
6086 ioPlotOverTimeBlock.m_xyzMinMaxTrkC.PlotXYZMinMaxTrkCParseJson(inPlotOverTimeBlockJson, 'axis ')
6087
6088 #hack to test missing data situations
6089 #if ioPlotOverTimeBlock.mName == "fooPlot":
6090 # myDebugPrint3("hack to test missing data, found fooPlot, using stressthresh\n")
6091 # ioPlotOverTimeBlock.mInputOperation = inPipeAndViewsState.mOperationBlocks["stressthresh"]
6092 #else:
6093 # myDebugPrint3("hack to test missing data, did not find fooPlot\n")
6094 # ioPlotOverTimeBlock.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson('operation', inJsn)
6095
6096 ioPlotOverTimeBlock.mInputOperation = \
6097 inPipeAndViewsState.GetOperationReferredByJson('operation',
6098 inPlotOverTimeBlockJson)
6099
6100 ioPlotOverTimeBlock.mColorSettings.\
6101 ParsePlotColorSettingsFromJson(inPlotOverTimeBlockJson)
6102
6103 if PhactoriDbg(100):
6104 myDebugPrint3('ParseOnePlotOverTimeBlockC returning:\n', 100)
6105 return
6106
6107 def ParseBlocksC2(ioBlockSet, inBlocksJson, inBlockClass, ioPipeAndViewsState):
6108 if PhactoriDbg(100):
6109 myDebugPrint3('ParseBlocksC2 entered\n', 100)
6110 count = 0
6111 for blockName, blockParamsJson in inBlocksJson.items():
6112 count = count + 1
6113 newBlockInstance = inBlockClass()
6114 newBlockInstance.mName = blockName
6115 if PhactoriDbg():
6116 myDebugPrint3(' creating block named ' + newBlockInstance.mName + '\n')
6117 if PhactoriDbg():
6118 myDebugPrint3(str(blockParamsJson) + '\n')
6119 newBlockInstance.ParseParametersFromJson(blockParamsJson, ioPipeAndViewsState)
6120 ioBlockSet[newBlockInstance.mName] = newBlockInstance
6121 if PhactoriDbg(100):
6122 myDebugPrint3('ParseBlocksC2 returning\n', 100)
6123 return count
6124
6125 def ParseBlocksC(ioBlockSet, inBlocksJson, inBlockClass, inParseOneBlockMethod,
6126 ioPipeAndViewsState):
6127 if PhactoriDbg(100):
6128 myDebugPrint3('ParseBlocksC entered\n', 100)
6129 count = 0
6130 for blockName, blockParamsJson in inBlocksJson.items():
6131 count = count + 1
6132 newBlockInstance = inBlockClass()
6133 newBlockInstance.mName = blockName
6134 if PhactoriDbg():
6135 myDebugPrint3(' creating block named ' + newBlockInstance.mName + '\n')
6136 if PhactoriDbg():
6137 myDebugPrint3(str(blockParamsJson) + '\n')
6138 inParseOneBlockMethod(newBlockInstance, blockParamsJson, ioPipeAndViewsState)
6139 ioBlockSet[newBlockInstance.mName] = newBlockInstance
6140 if PhactoriDbg(100):
6141 myDebugPrint3('ParseBlocksC returning\n', 100)
6142 return count
6143
6144 class PhactoriUserPointInfo:
6145 "user specified point: absolute, relative, at element, node, data value, etc."
6146
6147 def __init__(self):
6148 #'absolute' or 'datasize relative' or 'element' or 'node'
6149 self.mPointType = "datasize relative"
6150 self.mElementOrNodeId = None
6151 self.mXyz = [0.0, 0.0, 0.0]
6152 self.mMayChangeWithData = False
6153 #flag tracking whether any information was filled in due to parsing
6154 #or if default is simply being used because of no parsed items
6155 self.mParseHadKeys = None
6156 self.mHasDisplacedInfoFlag = False
6157 self.mDisplacement = [0.0, 0.0, 0.0]
6158 self.mParsingDetectedAtLeastOneSetting = False
6159 self.mReferenceVariableInfo = None
6160
6161 #for tracking which source input to use if point is at min or max
6162 #variable
6163 self.mInputNameToUseForMinMaxVariable = None
6164 self.mInputPvSourceToUseForMinMaxVariable = None
6165
6166 def UserPointHasValidDisplacementInfo(self):
6167 return self.mHasDisplacedInfoFlag
6168
6169 def ParseIdAndDisplacement(self, inDisplacementFlag, inJson, inKey):
6170 if inDisplacementFlag:
6171 params = inJson[inKey]
6172 self.mElementOrNodeId = params[0]
6173 self.mHasDisplacedInfoFlag = True
6174 self.mDisplacement[0] = params[1]
6175 self.mDisplacement[1] = params[2]
6176 self.mDisplacement[2] = params[3]
6177 if PhactoriDbg():
6178 myDebugPrint3(" displacement is " + str(self.mDisplacement) + "\n")
6179 else:
6180 self.mElementOrNodeId = inJson[inKey]
6181
6182 def UserPointInfoParseParametersFromJson(self, inJson, inKeyPrefix, inKeySuffix,
6183 inDisplacementFlag = False):
6184 self.mParseHadKeys = False
6185 keyAbsolute = inKeyPrefix + "absolute point" + inKeySuffix
6186 keyRelative = inKeyPrefix + "relative point" + inKeySuffix
6187 keyNode = inKeyPrefix + "node" + inKeySuffix
6188 keyElement = inKeyPrefix + "element" + inKeySuffix
6189 keyMaxVar = inKeyPrefix + "max variable point" + inKeySuffix
6190 keyMinVar = inKeyPrefix + "min variable point" + inKeySuffix
6191 keyDataPt = inKeyPrefix + "data point" + inKeySuffix
6192
6193 if keyAbsolute in inJson:
6194 self.mParsingDetectedAtLeastOneSetting = True
6195 self.mPointType = "absolute"
6196 self.mXyz = inJson[keyAbsolute]
6197 self.mMayChangeWithData = False
6198 elif keyRelative in inJson:
6199 self.mParsingDetectedAtLeastOneSetting = True
6200 self.mPointType = "datasize relative"
6201 self.mXyz = inJson[keyRelative]
6202 self.mMayChangeWithData = True
6203 elif keyNode in inJson:
6204 self.mParsingDetectedAtLeastOneSetting = True
6205 if PhactoriDbg():
6206 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson node found\n")
6207 self.mPointType = "node"
6208 self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyNode)
6209 self.mMayChangeWithData = True
6210 if PhactoriDbg():
6211 myDebugPrint3(" node id is " + str(self.mElementOrNodeId) + "\n")
6212 elif keyElement in inJson:
6213 self.mParsingDetectedAtLeastOneSetting = True
6214 if PhactoriDbg():
6215 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson element found\n")
6216 self.mPointType = "element"
6217 self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyElement)
6218 self.mMayChangeWithData = True
6219 if PhactoriDbg():
6220 myDebugPrint3(" element id is " + str(self.mElementOrNodeId) + "\n")
6221 elif keyMinVar in inJson:
6222 self.mParsingDetectedAtLeastOneSetting = True
6223 self.mPointType = "min variable"
6224 #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):
6225 self.mReferenceVariableInfo = PhactoriVariableInfo()
6226 self.mReferenceVariableInfo.\
6227 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
6228 self.mMayChangeWithData = True
6229 if PhactoriDbg():
6230 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson "
6231 "min variable found\n"
6232 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
6233 varSourceKey = inKeyPrefix + "input for min variable point" + inKeySuffix
6234 if varSourceKey in inJson:
6235 self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]
6236 myDebugPrint3("input name for min variable point: " + \
6237 self.mInputNameToUseForMinMaxVariable + "\n")
6238 varDispKey = \
6239 inKeyPrefix + "displacement for min variable point" + inKeySuffix
6240 if varDispKey in inJson:
6241 self.mDisplacement = inJson[varDispKey]
6242 myDebugPrint3("displacement for min variable point: " + \
6243 str(self.mDisplacement) + "\n")
6244 elif keyDataPt in inJson:
6245 self.mParsingDetectedAtLeastOneSetting = True
6246 if PhactoriDbg():
6247 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson: "
6248 "parsing data point")
6249 params = inJson[keyDataPt]
6250 if inDisplacementFlag:
6251 #better have 7 items
6252 if len(params) != 7:
6253 myDebugPrint3AndException(
6254 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
6255 "data point displaced expected 7 parameters")
6256 else:
6257 #better have 4 items
6258 if len(params) != 4:
6259 myDebugPrint3AndException(
6260 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
6261 "data point expected 4 parameters")
6262 param0 = params[0].lower()
6263 if param0 == "min":
6264 self.mPointType = "min variable"
6265 if param0 == "max":
6266 self.mPointType = "max variable"
6267 if param0 == "center":
6268 myDebugPrint3AndException(
6269 "PhactoriUserPointInfo.ParseParametersFromJson:\n"
6270 "data point 'center' not yet implemented")
6271 self.mReferenceVariableInfo = PhactoriVariableInfo()
6272 tempJson = {}
6273 tempJson[params[1].lower()] = params[2]
6274 if PhactoriDbg():
6275 print("tempJson: " + str(tempJson))
6276 self.mReferenceVariableInfo.\
6277 ParseVariableNameAndVectorOrTensorComponent(tempJson, '')
6278 self.mMayChangeWithData = True
6279 if PhactoriDbg():
6280 myDebugPrint3("variable found\n"
6281 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
6282 if params[3] != "default":
6283 self.mInputNameToUseForMinMaxVariable = params[3]
6284 if PhactoriDbg():
6285 myDebugPrint3("name of input operation: " +
6286 self.mInputNameToUseForMinMaxVariable + "\n")
6287 if inDisplacementFlag:
6288 self.mHasDisplacedInfoFlag = True
6289 self.mDisplacement[0] = params[4]
6290 self.mDisplacement[1] = params[5]
6291 self.mDisplacement[2] = params[6]
6292
6293 else:
6294 if PhactoriDbg():
6295 myDebugPrint3("using default input operation\n")
6296 if PhactoriDbg():
6297 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson: "
6298 "done parsing data point")
6299 elif keyMaxVar in inJson:
6300 self.mParsingDetectedAtLeastOneSetting = True
6301 self.mPointType = "max variable"
6302 #self.ParseIdAndDisplacement(inDisplacementFlag, inJson, keyMinNode):
6303 self.mReferenceVariableInfo = PhactoriVariableInfo()
6304 self.mReferenceVariableInfo.\
6305 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
6306 self.mMayChangeWithData = True
6307 if PhactoriDbg():
6308 myDebugPrint3("PhactoriUserPointInfo.ParseParametersFromJson "
6309 "max variable found\n"
6310 "var info: " + self.mReferenceVariableInfo.SelfToStr() + "\n")
6311 varSourceKey = inKeyPrefix + "input for max variable point" + inKeySuffix
6312 if varSourceKey in inJson:
6313 self.mInputNameToUseForMinMaxVariable = inJson[varSourceKey]
6314 myDebugPrint3("input name for max variable point: " + \
6315 self.mInputNameToUseForMinMaxVariable + "\n")
6316 varDispKey = \
6317 inKeyPrefix + "displacement for max variable point" + inKeySuffix
6318 if varDispKey in inJson:
6319 self.mDisplacement = inJson[varDispKey]
6320 myDebugPrint3("displacement for max variable point: " + \
6321 str(self.mDisplacement) + "\n")
6322 else:
6323 self.mParsingDetectedAtLeastOneSetting = False
6324 if PhactoriDbg():
6325 myDebugPrint3(" no PhactoriUserPointInfo parse keys, using default\n")
6326
6327 #myDebugPrint3("PhactoriUserPoint Parsed from json:\n")
6328 #self.PrintSelf()
6329
6330 def GetCurrentGeometricPoint(self, inParaViewSource, ioViewBounds,
6331 inUpdateInputPipelineFlag):
6332 "returns the current absolute xyz of this point, calculating relative\n position or element or node position if necessary; if it obtains\n its view bounds during operation it returns them, otherwise it\n returns None\n "
6333 if inUpdateInputPipelineFlag:
6334 UpdatePipelineWithCurrentTimeArgument(inParaViewSource)
6335 if PhactoriDbg(100):
6336 myDebugPrint3("GetCurrentGeometricPoint entered\n", 100)
6337
6338 #import pdb
6339 #pdb.set_trace()
6340
6341 #self.PrintSelf()
6342 if self.mPointType == 'absolute':
6343 #focal point is exact point in coordinate system of data
6344 returnXyz = list(self.mXyz)
6345 elif self.mPointType == 'datasize relative':
6346 #focal point is offset from center of data bounding box, with offset
6347 #relative in size to the size of the overall bounding box
6348 relativeXyz = self.mXyz
6349 myViewBounds = ioViewBounds[0]
6350 if myViewBounds == None:
6351 myViewBounds = GetGlobalDataBoundsParallel(inParaViewSource)
6352 ioViewBounds[0] = myViewBounds
6353 #old style: use maximum bounding box dimension to define
6354 #relative space
6355 #maxDim = GetMaximumDimensionFromBounds(myViewBounds)
6356 #returnXyz = [ (myViewBounds[1] + myViewBounds[0]) * 0.5 + \
6357 # maxDim * relativeXyz[0], \
6358 # (myViewBounds[3] + myViewBounds[2]) * 0.5 + \
6359 # maxDim * relativeXyz[1], \
6360 # (myViewBounds[5] + myViewBounds[4]) * 0.5 + \
6361 # maxDim * relativeXyz[2] ]
6362
6363 #new style: do relative in each dimension
6364 returnXyz = [0.0,0.0,0.0]
6365 returnXyz[0] = myViewBounds[0] + (myViewBounds[1] - myViewBounds[0]) * \
6366 (relativeXyz[0] + 0.5)
6367 returnXyz[1] = myViewBounds[2] + (myViewBounds[3] - myViewBounds[2]) * \
6368 (relativeXyz[1] + 0.5)
6369 returnXyz[2] = myViewBounds[4] + (myViewBounds[5] - myViewBounds[4]) * \
6370 (relativeXyz[2] + 0.5)
6371 elif self.mPointType == 'node':
6372 nodeId = self.mElementOrNodeId
6373 returnXyz = [0.0, 0.0, 0.0]
6374 GetXyzForNodeOrElementParallel(inParaViewSource, True, nodeId, returnXyz)
6375 elif self.mPointType == 'element':
6376 elementId = self.mElementOrNodeId
6377 returnXyz = [0.0, 0.0, 0.0]
6378 GetXyzForNodeOrElementParallel(inParaViewSource, False, elementId, returnXyz)
6379 elif self.mPointType == 'min variable':
6380 returnXyz = [0.0, 0.0, 0.0]
6381 if self.mInputNameToUseForMinMaxVariable == None:
6382 pvFilter = inParaViewSource
6383 else:
6384 if self.mInputPvSourceToUseForMinMaxVariable == None:
6385 global gPipeAndViewsState
6386 operationBlock = gPipeAndViewsState.mOperationBlocks[
6387 self.mInputNameToUseForMinMaxVariable]
6388 pvFilter = operationBlock.GetPvFilter()
6389 self.mInputPvSourceToUseForMinMaxVariable = pvFilter
6390 else:
6391 pvFilter = self.mInputPvSourceToUseForMinMaxVariable
6392 if(pvFilter == None):
6393 #no pvFilter for min/max yet, just use 0,0,0
6394 returnXyz = [0.0, 0.0, 0.0]
6395 else:
6396 UpdatePipelineWithCurrentTimeArgument(pvFilter)
6397 GetXyzForMinOrMaxVariable(pvFilter, True,
6398 self.mReferenceVariableInfo, returnXyz)
6399 elif self.mPointType == 'max variable':
6400 returnXyz = [0.0, 0.0, 0.0]
6401 if self.mInputNameToUseForMinMaxVariable == None:
6402 pvFilter = inParaViewSource
6403 if PhactoriDbg():
6404 myDebugPrint3("max var point has no source, using incoming\n")
6405 else:
6406 if PhactoriDbg():
6407 myDebugPrint3("max var point has source, using instead\n")
6408 if self.mInputPvSourceToUseForMinMaxVariable == None:
6409 if PhactoriDbg():
6410 myDebugPrint3("not previously found, must locate\n")
6411 #global gPipeAndViewsState
6412 operationBlock = gPipeAndViewsState.mOperationBlocks[
6413 self.mInputNameToUseForMinMaxVariable]
6414 pvFilter = operationBlock.GetPvFilter()
6415 self.mInputPvSourceToUseForMinMaxVariable = pvFilter
6416 else:
6417 if PhactoriDbg():
6418 myDebugPrint3("previously found.\n")
6419 pvFilter = self.mInputPvSourceToUseForMinMaxVariable
6420 if PhactoriDbg():
6421 myDebugPrint3("incoming: " + str(inParaViewSource) + "\n"
6422 "using: " + str(pvFilter) + "\n")
6423 if(pvFilter == None):
6424 #no pvFilter for min/max yet, just use 0,0,0
6425 returnXyz = [0.0, 0.0, 0.0]
6426 else:
6427 UpdatePipelineWithCurrentTimeArgument(pvFilter)
6428 GetXyzForMinOrMaxVariable(pvFilter, False,
6429 self.mReferenceVariableInfo, returnXyz)
6430 else:
6431 errStr = 'GetCurrentGeometricPoint error! bad mPointType\n'
6432 if PhactoriDbg():
6433 myDebugPrint3(errStr)
6434 raise Exception(errStr)
6435
6436 if PhactoriDbg(100):
6437 myDebugPrint3("GetCurrentGeometricPoint returning: " + \
6438 str(returnXyz) + "\n", 100)
6439
6440 return returnXyz
6441
6442 def GetCurrentGeometricPointWithDisplacement(self, inParaViewSource,
6443 ioViewBounds, inUpdateInputPipelineFlag):
6444 undisplacedXyz = self.GetCurrentGeometricPoint(inParaViewSource,
6445 ioViewBounds, inUpdateInputPipelineFlag)
6446 returnXyz = [undisplacedXyz[0] + self.mDisplacement[0],
6447 undisplacedXyz[1] + self.mDisplacement[1],
6448 undisplacedXyz[2] + self.mDisplacement[2]]
6449 return returnXyz
6450
6451 def SelfToStr(self):
6452 return " PhactoriUserPointInfo:\n" \
6453 " mPointType: " + self.mPointType + \
6454 " mElementOrNodeId: " + str(self.mElementOrNodeId) + "\n" + \
6455 " mMayChangeWithData: " + str(self.mMayChangeWithData) + "\n" \
6456 " mParseHadKeys: " + str(self.mParseHadKeys) + "\n" \
6457 " mHasDisplacedInfoFlag: " + str(self.mHasDisplacedInfoFlag) + "\n" \
6458 " mDisplacement: " + str(self.mDisplacement) + "\n" \
6459 " mReferenceVariableInfo: " + str(self.mReferenceVariableInfo) + "\n"
6460
6461 def PrintSelf(self):
6462 if PhactoriDbg():
6463 myDebugPrint3(self.SelfToStr())
6464
6465 class PhactoriOffAxisProjectionInfo:
6466 def __init__(self):
6467 self.mUseOffAxisProjection = False
6468 self.mPhysicalEyeAndScreenSettings = PhactoriPhysicalEyeAndScreenSetup()
6469 self.mLeftEyeFlag = True
6470 self.mIpdInModelUnits = 6.2
6471 self.mVirtualSelfSizeMultiplier = 1.0
6472 self.mAutoSize1Enabled = False
6473 self.mAutoSize1LockEyePosition = False
6474 self.mAutoSize1LockCountdown = 1
6475 self.mAutoSize1DistanceRatio = 1.0
6476 self.mAutoSize1LockedEyePosition = None
6477 self.mAutoSize1LockedFocalPoint = None
6478 self.mAutoSize1ViewAngleDeltaInRadians = 0.0
6479
6480 def ParseParametersFromJson(self, inJsn):
6481 if 'use off axis projection' in inJsn:
6482 self.mUseOffAxisProjection = inJsn['use off axis projection']
6483 if PhactoriDbg():
6484 myDebugPrint3("PhactoriOffAxisProjectionInfo:ParseParametersFromJson\n"
6485 "mUseOffAxisProjection set to " + str(self.mUseOffAxisProjection))
6486 if self.mUseOffAxisProjection == True:
6487 self.mPhysicalEyeAndScreenSettings.ParseSettingsFromJson(inJsn)
6488 if 'which eye' in inJsn:
6489 if inJsn['which eye'] == 'left':
6490 self.mLeftEyeFlag = True
6491 else:
6492 self.mLeftEyeFlag = False
6493 else:
6494 if PhactoriDbg():
6495 myDebugPrint3("PhactoriOffAxisProjectionInfo:"
6496 "ParseParametersFromJson\n"
6497 "warning: 'which eye' not in json, defaulting to left\n")
6498 if 'ipd in model units' not in inJsn:
6499 myDebugPrint3AndException(
6500 "PhactoriOffAxisProjectionInfo::ParseParametersFromJson\n"
6501 "Error: incoming json must have 'ipd in model units'\n")
6502 self.mIpdInModelUnits = inJsn['ipd in model units']
6503 if 'virtual self size multiplier' in inJsn:
6504 self.mVirtualSelfSizeMultiplier = inJsn['virtual self size multiplier']
6505 if 'auto size 1' in inJsn:
6506 self.mAutoSize1Enabled = inJsn['auto size 1']
6507 if 'auto size 1 lock nth eye position' in inJsn:
6508 self.mAutoSize1LockEyePosition = True
6509 self.mAutoSize1LockCountdown = inJsn['auto size 1 lock nth eye position']
6510 if 'auto size 1 distance ratio' in inJsn:
6511 self.mAutoSize1DistanceRatio = inJsn['auto size 1 distance ratio']
6512 if 'auto size 1 view angle delta in degrees' in inJsn:
6513 angleInDegrees = inJsn['auto size 1 view angle delta in degrees']
6514 self.mAutoSize1ViewAngleDeltaInRadians = math.radians(angleInDegrees)
6515
6516
6517 def SetUpIfEnabled(self, inRenderView, ioCameraPosition, ioLookAtPoint,
6518 inViewUpVector):
6519 theCamera = GetActiveCamera()
6520 if self.mUseOffAxisProjection == False:
6521 theCamera.SetUseOffAxisProjection(0)
6522 return
6523
6524 projectionEyePosition = self.mPhysicalEyeAndScreenSettings.GetEyePosition(
6525 self.mLeftEyeFlag)
6526 scrnBttmLeft = self.mPhysicalEyeAndScreenSettings.GetScreenBottomLeft(
6527 self.mLeftEyeFlag)
6528 scrnBttmRight = self.mPhysicalEyeAndScreenSettings.GetScreenBottomRight(
6529 self.mLeftEyeFlag)
6530 scrnTopRight = self.mPhysicalEyeAndScreenSettings.GetScreenTopRight(
6531 self.mLeftEyeFlag)
6532
6533 if PhactoriDbg():
6534 myDebugPrint3("SetUpIfEnabled setting camera parameters:"
6535 "\n mProjectionEyePosition: " + str(projectionEyePosition) + \
6536 "\n mScreenBottomLeft: " + str(scrnBttmLeft) + \
6537 "\n mScreenBottomRight: " + str(scrnBttmRight) + \
6538 "\n mScreenTopRight: " + str(scrnTopRight) + \
6539 "\n")
6540 SetActiveView(inRenderView)
6541 theCamera.SetUseOffAxisProjection(1)
6542 #we are assuming camera is explicitly set up where you want the left or right eye
6543 #and so we don't use eye separation
6544 theCamera.SetEyeSeparation(0.0)
6545 theCamera.SetScreenBottomLeft(scrnBttmLeft)
6546 theCamera.SetScreenBottomRight(scrnBttmRight)
6547 theCamera.SetScreenTopRight(scrnTopRight)
6548 theCamera.SetEyePosition(projectionEyePosition)
6549
6550 self.ChangeEyeAndFocusInModelSpaceForStereo(ioCameraPosition,
6551 ioLookAtPoint, inViewUpVector)
6552
6553 if PhactoriDbg():
6554 myDebugPrint3("SetUpIfEnabled done setting camera parameters\n")
6555
6556 def ChangeEyeAndFocusInModelSpaceForStereo(self,
6557 ioEyePosition, ioFocalPoint, inViewUpVector):
6558
6559 #place eye and look at point so object is at screen in AutoSize1 case
6560 if self.mAutoSize1Enabled:
6561 if self.mAutoSize1LockEyePosition and self.mAutoSize1LockedEyePosition != None:
6562 ioEyePosition[0] = self.mAutoSize1LockedEyePosition[0]
6563 ioEyePosition[1] = self.mAutoSize1LockedEyePosition[1]
6564 ioEyePosition[2] = self.mAutoSize1LockedEyePosition[2]
6565 ioFocalPoint[0] = self.mAutoSize1LockedFocalPoint[0]
6566 ioFocalPoint[1] = self.mAutoSize1LockedFocalPoint[1]
6567 ioFocalPoint[2] = self.mAutoSize1LockedFocalPoint[2]
6568 if PhactoriDbg():
6569 myDebugPrint3("AutoSize1: reusing first eye position and focal point:\n" + \
6570 " eye position: " + str(ioEyePosition) + "\n"
6571 " focal point : " + str(ioFocalPoint) + "\n")
6572 else:
6573 fpToEyeVec = vecFromAToB(ioFocalPoint, ioEyePosition)
6574 fpToEyeVecNorm = vecNormalize(fpToEyeVec)
6575 dist = -self.mPhysicalEyeAndScreenSettings.mLeftEyeScreenBottomLeft[2]
6576 dist *= self.mAutoSize1DistanceRatio
6577 dist *= self.mVirtualSelfSizeMultiplier
6578
6579 if PhactoriDbg():
6580 myDebugPrint3("AutoSize1:\n"
6581 " before eye position: " + str(ioEyePosition) + "\n"
6582 " before focal point : " + str(ioFocalPoint) + "\n")
6583 ioEyePosition[0] = ioFocalPoint[0] + fpToEyeVecNorm[0] * dist
6584 ioEyePosition[1] = ioFocalPoint[1] + fpToEyeVecNorm[1] * dist
6585 ioEyePosition[2] = ioFocalPoint[2] + fpToEyeVecNorm[2] * dist
6586 #angle look direction for AutoSize1 by moving focal point up or down
6587 #simple tangent work, but need to work it out to see it (we want
6588 #same distance to screen plane but looking more angled up or down)
6589 dy1 = -dist * math.tan(self.mAutoSize1ViewAngleDeltaInRadians)
6590 ioFocalPoint[0] += inViewUpVector[0] * dy1
6591 ioFocalPoint[1] += inViewUpVector[1] * dy1
6592 ioFocalPoint[2] += inViewUpVector[2] * dy1
6593
6594 if PhactoriDbg():
6595 myDebugPrint3(
6596 " calculated eye position: " + str(ioEyePosition) + "\n"
6597 " calculated focal point : " + str(ioFocalPoint) + "\n")
6598 if self.mAutoSize1LockEyePosition:
6599 self.mAutoSize1LockCountdown -= 1
6600 if PhactoriDbg():
6601 myDebugPrint3("self.mAutoSize1LockCountdown now " + \
6602 str(self.mAutoSize1LockCountdown) + "\n")
6603 if self.mAutoSize1LockCountdown == 0:
6604 self.mAutoSize1LockedEyePosition = list(ioEyePosition)
6605 self.mAutoSize1LockedFocalPoint = list(ioFocalPoint)
6606 if PhactoriDbg():
6607 myDebugPrint3("(eye position saved for locking for next use)\n")
6608
6609 #perpendicular screen distance or put look at point on screen plane?
6610 #i think put look at point on screen plane.
6611
6612 lookDirection = vecFromAToB(ioEyePosition, ioFocalPoint)
6613 axisBetweenEyes = vecCrossProduct(lookDirection, inViewUpVector)
6614 axisBetweenEyesNorm = vecNormalize(axisBetweenEyes)
6615
6616 if self.mLeftEyeFlag:
6617 modelCsHalfIpd = -self.mIpdInModelUnits * \
6618 self.mVirtualSelfSizeMultiplier * 0.5
6619 else:
6620 modelCsHalfIpd = self.mIpdInModelUnits * \
6621 self.mVirtualSelfSizeMultiplier * 0.5
6622 dx = axisBetweenEyesNorm[0] * modelCsHalfIpd
6623 dy = axisBetweenEyesNorm[1] * modelCsHalfIpd
6624 dz = axisBetweenEyesNorm[2] * modelCsHalfIpd
6625 if PhactoriDbg():
6626 myDebugPrint3("ChangeEyeAndFocusInModelSpaceForStereo entered\n"
6627 "axisBetweenEyesNorm: " + str(axisBetweenEyesNorm) + "\n"
6628 "modelCsHalfIpd: " + str(modelCsHalfIpd) + "\n"
6629 "[dx,dy,dz]: " + str([dx,dy,dz]) + "\n"
6630 "prior ioEyePosition: " + str(ioEyePosition) + "\n"
6631 "prior ioFocalPoint: " + str(ioFocalPoint) + "\n")
6632 ioEyePosition[0] += dx
6633 ioEyePosition[1] += dy
6634 ioEyePosition[2] += dz
6635 ioFocalPoint[0] += dx
6636 ioFocalPoint[1] += dy
6637 ioFocalPoint[2] += dz
6638 if PhactoriDbg():
6639 myDebugPrint3("post ioEyePosition: " + str(ioEyePosition) + "\n"
6640 "post ioFocalPoint: " + str(ioFocalPoint) + "\n"
6641 "ChangeEyeAndFocusInModelSpaceForStereo returning\n")
6642
6643
6644 class PhactoriCameraBlock:
6645 "camera control: look at point, look direction, camera/eye position, etc.\n\nPhactoriCameraBlock is the central class for controlling the camera (or eye)\npositioning for images. There are a number of ways the camera control can\nbe scripted in paraview.\n\nTo add a PhactoriCameraBlock to the incoming script, you add\na sub-block to the 'camera blocks' section of the data with the 'type'\nkey given a value of 'camera'. Next is a simple working script, followed by\na longer discussion of all the allowed controls.\n\n::\n\n {\n 'camera blocks':{\n 'mycam1':{\n 'type':'camera',\n 'look direction':[-1.0, -2.0, -3.0]\n }\n },\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_on_slice_1':{\n 'camera':'mycam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'threshold1_temperature.'\n }\n }\n }\n\nThe simplest common usage of the camera is to specify a point to look at and\na direction in which to look. In this case the camera is positioned so that\nthe center of view looks along the specified look direction towards the\n'look at point'. If the user leaves the distance between the look at point\nand the camera position unspecified, the camera will automatically be placed\nfar enough away from the look at point so that the entire bounding box of\nthe mesh data is visible.\n\nThe user may specify the distance between the look at point and the camera\nposition by adding a 'look at absolute distance' key which will place the\ncamera an exact number of specified geometrical units (in model coordinates)\nfrom the look at point. A 'look at relative distance' key behaves more like\na zoom factor. A 'look at relative distance' of 0.25 will calculate the\ndefault distance (so the whole data bounding box is in view) but then\nmultiply that distance by 0.25, resulting in a camera postion which is four\ntimes closer to the look at point than the default.\n\nThe user also has the point to specify 'camera at point' to fix the camera\nat a 3D point. The user is allowed to specify two out of three of 'look at\npoint', 'camera at point', and 'look direction' but not all three. If only\none is specified another will receive a default value, and if none are\nspecified the camera takes on a default behavior with a look direction of\n[0.0, 0.0, -1.0] and a relative look at point of [0.0, 0.0, 0.0]. Also note\nthat if the user specifies the camera point and the look at point, the look\nat distance is implied and cannot be set.\n\nBoth the 'look at point' and the 'camera at point' are instances of the\nPhactoriUserPointInfo class. This class is documented separately, but\nbriefly this means that this point can be the expected absolute geometric\n3d point (e.g. [123.0, -37.9, 47.6]), a 'relative' point specified in\nterms of the data bounding box (e.g. [0.0, 0.0, 0.0] is the center of the\ndata bounding box), specified to reside at a node id or element id in the\nmesh (or at a specified offset therefrom), or at the location of the maximum\nor minimum of a data variable (e.g. pressure, temperature, velocity\nmagnitude). Note that in all cases except the 'absolute' case, the geometric\nposition of the point might be different depending on the mesh data.\n\nGenerally it is best to use 'look at relative point' and 'look direction' for\ninitial scripting (unless you happen to know exact geometric places of\ninterest, in which case 'look at absolute point' is better), and then create\nmore specific cameras to hone in on areas of interest or make steady views\nfor creating movies.\n\nRemember, look at the documentation for PhactoriUserPointInfo to get the\ndetails on the options for 'look at point' and 'camera at point', but a\nnumber of examples of camera usage follow:\n\nLooks in a direction [-1.0, -1.0, .1.0] at the default location, relative\npoint [0,0,0] which is the center of the bounding box of the data. Camera\nis positioned to show entire bounding box of data:\n\n::\n\n 'mycam2':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0]\n }\n\nSame as above, but now 'zoomed in' to where the look at point to camera\npoint distance is one fourth of what it was in the previous case:\n\n::\n\n 'mycam3':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at relative distance':0.25\n }\n\nSame as above, but now we make the look at point on one of the corners of\nthe bounding box of the data (max X, min Y, maz Z)\n\n::\n\n 'mycam4':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at relative point':[0.5, -0.5, 0.5]\n 'look at relative distance':0.25\n }\n\nThe above will be a bit odd because the camera position calculation will\nstart by getting the whole bounding box in view, which will be just on\none side of the screen. It would work better to line the view up back\ntowards the center:\n\n::\n\n 'mycam5':{\n 'type':'camera',\n 'look direction':[-1.0, 1.0, -1.0],\n 'look at relative point':[0.5, -0.5, 0.5]\n 'look at relative distance':0.25\n }\n\nNow an example where you know what geometric point you need to focus on,\nwhere there might be a tip or and edge or a bend or a stress point:\n\n::\n\n 'mycam6':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at absolute point':[132.0, 145.125, -157.625]\n 'look at relative distance':0.25\n }\n\nThis is similar to the above, but you have more precise control over what\nyou see in the camera, and the view won't change if the mesh is changing (as\nin a mechanics simulation):\n\n::\n\n 'mycam7':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at absolute point':[132.0, 145.125, -157.625]\n 'look at absolute distance':55.0\n }\n\nLook at a particular node (or element):\n\n::\n\n 'mycam8':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at node':1942\n 'look at relative distance':0.25\n }\n\nlook at a particular element, and put the camera at a certain distance and\ndirection from that element:\n\n::\n\n 'mycam9':{\n 'type':'camera',\n 'look at element':1942\n 'camera at element displaced':[1942, 5.0, 6.1, 7.2]\n }\n\n look at the point where pressure is maximum:\n\n:: \n\n 'mycam10':{\n 'type':'camera',\n 'look direction':[-1.0, -1.0, -1.0],\n 'look at max variable point':True,\n 'variable scalar':'pressure'\n }\n\nFor other point options see PhactoriUserPointInfo\n\nYou also have the option to specify a type of 'multicamera8' in which you\nhave 8 look directions: two aliagned on each axis from both directions, plus\ntwo diagonals [-1.0, -1.0, -1.0] and [1.0, 1.0, 1.0]. You can still specify\na look at point and look at relative distance or look at abolute distance.\nIf you don't specify those you'll get a relative look at point of [0,0,0],\ncenter of the data bounding box, and a relative look at distance of 1.0 so\nall the data is visible from each angle.\n\nThe result is that when this camera is chosen by an imageset block the\nresult will be 8 images instead of 1:\n\n::\n\n 'mycam11':{\n 'type':'multicamera8',\n 'look at absolute point':[132.0, 145.125, -157.625]\n 'look at absolute distance':100.0\n }\n\nEventually we plan to provide for\nlists of look at points and look directions so users may more tersely\nspecify many views of the same operation/representation setup.\n"
6646
6647 def __init__(self):
6648 self.mName = ""
6649 self.mType = ""
6650 self.mFilenameAddon = ""
6651 self.mLookAtPointInfo = PhactoriUserPointInfo()
6652 self.mUseCameraAtPointFlag = False
6653 self.mCameraAtPointInfo = PhactoriUserPointInfo()
6654 self.mUseParallelProjection = False
6655 #0 is absolute, 1, is relative
6656 self.mParallelScaleAbsoluteOrRelative = 1
6657 self.mParallelScale = 1.0
6658
6659 #'absolute' or 'datasize relative'
6660 self.mLookAtDistanceType = ""
6661 self.mLookAtDistance = 1.0
6662 self.mLookDirection = [-1.0, -1.0, -1.0]
6663 self.mLookDirectionSpecifiedFlag = False
6664
6665 self.mViewAngle = 30.0
6666 self.mViewUpVector = [0.0, 1.0, 0.0]
6667
6668 self.mOffAxisProjectionInfo = PhactoriOffAxisProjectionInfo()
6669
6670 self.LockCount = 0
6671 self.LockAfterNCalls = -1
6672
6673 def PrintSelf(self):
6674 if PhactoriDbg():
6675 myDebugPrint3("PhactoriCameraBlock: name " + self.mName + \
6676 " type " + self.mType + "\n" +
6677 " look at distance type " + self.mLookAtDistanceType + \
6678 " setting " + str(self.mLookAtDistance) + "\n" +
6679 " look direction " + str(self.mLookDirection) + "\n")
6680 self.mLookAtPointInfo.PrintSelf()
6681
6682 def MayChangeWithData(self):
6683 if self.mLookAtDistanceType != 'absolute':
6684 return True
6685 if self.mLookAtPointInfo.mMayChangeWithData == True:
6686 return True
6687 return False
6688
6689 def HandleLockingOption(self, eyePosition, absoluteLookAtPoint):
6690 if self.LockAfterNCalls <= 0:
6691 #not locking
6692 return
6693
6694 self.LockCount += 1
6695 if self.LockCount >= self.LockAfterNCalls:
6696 #look at absolute point
6697 self.mLookAtPointInfo.mParsingDetectedAtLeastOneSetting = True
6698 self.mLookAtPointInfo.mPointType = "absolute"
6699 self.mLookAtPointInfo.mXyz = absoluteLookAtPoint
6700 self.mLookAtPointInfo.mMayChangeWithData = False
6701
6702 #look at absolute distance
6703 self.mLookAtDistanceType = 'absolute'
6704 lookAtAbsoluteDistance = vecDistance(eyePosition, absoluteLookAtPoint)
6705 self.mLookAtDistance = lookAtAbsoluteDistance
6706
6707 self.LockAfterNCalls = -1
6708
6709 #phactori_combine_to_single_python_file_parent_1
6710 #from Operation.PhactoriVariableInfo import *
6711 #phactori_combine_to_single_python_file_subpiece_begin_1
6712 class PhactoriVariableMinMaxAvgSumCntSave:
6713 def __init__(self):
6714 self.mStatsTestCounter = -1
6715 self.mMin = 0.0
6716 self.mMax = 0.0
6717 self.mSum = 0.0
6718 self.mCount = 0
6719 self.mIdsTestCounter = -1
6720 self.mLocalFoundMinId = False
6721 self.mLocalMinIdCount = -1
6722 self.mMinId = -1;
6723 self.mLocalFoundMaxId = False
6724 self.mLocalMaxIdCount = -1
6725 self.mMaxId = -1;
6726
6727 class PhactoriVariableInfo:
6728 def __init__(self):
6729 self.mVariableIntendedForUseFlag = False
6730 self.mVariableName = ""
6731 self.mVariableComponent = None
6732 self.mVariableType = None
6733 self.mVariableTypeNeedsDetection = False
6734 self.mVariableTypeWasDetected = False
6735 self.mVariableTypeWasCopied = False
6736 self.mVariableIsVectorMagnitude = False
6737 self.mVariableIsVectorComponent = False
6738 self.mVectorBaseName = None
6739 self.mStats = PhactoriVariableMinMaxAvgSumCntSave()
6740 #as of 2022Aug09 we want this to default to False
6741 self.mAddSeparatorToVectorVariableName = False
6742
6743 def SelfToStr(self):
6744 retStr = "PhactoriVariableInfo:\n" +\
6745 "\n mVariableName: " + str(self.mVariableName) +\
6746 "\n mVariableComponent: " + str(self.mVariableComponent) +\
6747 "\n mVariableType: " + str(self.mVariableType) +\
6748 "\n mVariableTypeNeedsDetection: " + str(self.mVariableTypeNeedsDetection) +\
6749 "\n mVariableTypeWasDetected: " + str(self.mVariableTypeWasDetected) +\
6750 "\n mVariableTypeWasCopied: " + str(self.mVariableTypeWasCopied) +\
6751 "\n mVariableIsVectorMagnitude: " + \
6752 str(self.mVariableIsVectorMagnitude) +\
6753 "\n mVariableIsVectorComponent: " + \
6754 str(self.mVariableIsVectorComponent) +\
6755 "\n mVectorBaseName: " + str(self.mVectorBaseName) +\
6756 "\n mVariableIntendedForUseFlag: " + str(self.mVariableIntendedForUseFlag) +\
6757 "\n"
6758 return retStr
6759
6760 def CheckAndParseScalarVariable1(self, inJson, inBaseString):
6761 testKey = inBaseString + 'scalar'
6762 if testKey in inJson:
6763 self.mVariableName = inJson[testKey]
6764 self.mVariableComponent = None
6765 return True
6766 else:
6767 return False
6768
6769 def CheckAndParseVectorComponentNumber1(self, inJson, inBaseString):
6770 testKey = inBaseString + 'vector component number'
6771 if testKey in inJson:
6772 self.mVariableIsVectorComponent = True
6773 varCompNumPair = inJson[testKey]
6774 self.mVariableName = varCompNumPair[0]
6775 self.mVariableComponent = int(varCompNumPair[1])
6776 return True
6777 else:
6778 return False
6779
6780 def CheckAndParseVectorComponentSuffix(self, inJson, inBaseString):
6781 testKey = inBaseString + 'vector component'
6782 if testKey in inJson:
6783 self.mVariableIsVectorComponent = True
6784 varName = inJson[testKey]
6785 resultPair = breakSpecialVarNameIntoBaseAndComponent(varName,
6786 self.mAddSeparatorToVectorVariableName)
6787 self.mVariableName = resultPair[0]
6788 self.mVariableComponent = resultPair[1]
6789 self.mVectorBaseName = resultPair[2]
6790 return True
6791 else:
6792 return False
6793
6794 def CheckAndParseVectorMagnitude(self, inJson, inBaseString):
6795 testKey = inBaseString + 'vector magnitude'
6796 if testKey in inJson:
6797 self.mVariableIsVectorMagnitude = True
6798 if self.mAddSeparatorToVectorVariableName:
6799 self.mVariableName = inJson[testKey] + GetSeparatorString()
6800 else:
6801 self.mVariableName = inJson[testKey]
6802 self.mVectorBaseName = inJson[testKey]
6803 return True
6804 else:
6805 return False
6806
6807 def CheckAndParseTensorComponent(self, inJson, inBaseString):
6808 testKey = inBaseString + 'tensor component'
6809 if testKey in inJson:
6810 self.mVariableName = inJson[testKey]
6811 return True
6812 else:
6813 return False
6814
6815 def CheckAndParseVectorVariable1(self, inJson, inBaseString):
6816 variableFoundFlag = False
6817 variableFoundFlag = self.CheckAndParseVectorComponentNumber1(inJson, inBaseString)
6818 if not variableFoundFlag:
6819 variableFoundFlag = self.CheckAndParseVectorComponentSuffix(inJson, inBaseString)
6820 if not variableFoundFlag:
6821 variableFoundFlag = self.CheckAndParseVectorMagnitude(inJson, inBaseString)
6822 if not variableFoundFlag:
6823 variableFoundFlag = self.CheckAndParseTensorComponent(inJson, inBaseString)
6824 if not variableFoundFlag:
6825 variableFoundFlag = False
6826 self.mVariableName = ''
6827 self.mComponent = None
6828 return variableFoundFlag
6829
6830 def ParseVariableNameAndVectorOrTensorComponent(self, inJson, inBaseString):
6831 "take a base string such as 'y axis variable ' or 'variable ', use it\n to construct keys to define a scalar variable, vector component, vector\n magnitude, or tensor component, and see if the json has those keys.\n If the json has a key, use it to grab the variable name and setup.\n Also look to see if the type of the variable is specifically defined\n (node or element) or needs to be detected\n "
6832 variableFoundFlag = False
6833 self.mVariableIsVectorComponent = False
6834 self.mVariableIsVectorMagnitude = False
6835
6836 if 'add separator to vector variable name' in inJson:
6837 self.mAddSeparatorToVectorVariableName = \
6838 inJson['add separator to vector variable name']
6839
6840 variableFoundFlag = self.CheckAndParseScalarVariable1(inJson, inBaseString)
6841 if not variableFoundFlag:
6842 variableFoundFlag = self.CheckAndParseVectorVariable1(inJson, inBaseString)
6843 if variableFoundFlag:
6844 #it is now apparent variable is intended to be used, not ignored
6845 self.mVariableIntendedForUseFlag = True
6846 if 'variable type' in inJson:
6847 variableType = inJson['variable type']
6848 self.mVariableType = variableType
6849 if variableType != 'element' \
6850 and variableType != 'node' \
6851 and variableType != 'global' \
6852 and variableType != 'detect':
6853 errStr = 'error! inJson has variable type is neither node nor '\
6854 'element nor detect nor global in ParseVariableNameAndVectorOrTensorComponent\n'
6855 if PhactoriDbg():
6856 myDebugPrint3(errStr)
6857 raise Exception(errStr)
6858 if variableType == 'detect':
6859 self.mVariableType = 'element'
6860 self.mVariableTypeNeedsDetection = True
6861 self.mVariableTypeWasDetected = False
6862 elif variableType == 'element':
6863 self.mVariableType = 'element'
6864 self.mVariableTypeNeedsDetection = False
6865 self.mVariableTypeWasDetected = True
6866 elif variableType == 'node':
6867 self.mVariableType = 'node'
6868 self.mVariableTypeNeedsDetection = False
6869 self.mVariableTypeWasDetected = True
6870 elif variableType == 'global':
6871 self.mVariableType = 'global'
6872 self.mVariableTypeNeedsDetection = False
6873 self.mVariableTypeWasDetected = True
6874 else:
6875 self.mVariableType = 'element'
6876 self.mVariableTypeNeedsDetection = True
6877 self.mVariableTypeWasDetected = False
6878 else:
6879 self.mVariableType = None
6880
6881 if PhactoriDbg():
6882 str1 = "ParseVariableNameAndVectorOrTensorComponent:\n"
6883 str2 = "inBaseString:\n" + str(inBaseString) + "\n"
6884 str3 = "inJson:\n" + str(inJson) + "\n"
6885 str4 = "instance state after parsing:\n" + self.SelfToStr()
6886 myDebugPrint3(str1 + str2 + str3 + str4)
6887 return variableFoundFlag
6888
6889 def CopyVariableTypeFrom(self, inSourceVariableInfo):
6890 self.mVariableType = inSourceVariableInfo.mVariableType
6891 self.mVariableTypeNeedsDetection = False
6892 self.mVariableTypeWasDetected = True
6893 self.mVariableTypeWasCopied = True
6894
6895 def DetectVariableType(self, inInputCsData, inInputIsProxy = False,
6896 inAllowGlobalVariableDetection = False):
6897
6898 if self.mVariableTypeNeedsDetection == False:
6899 return True
6900
6901 #testing hack--force to cell
6902 #self.mVariableTypeNeedsDetection = False
6903 #self.mVariableTypeWasDetected = True
6904 #self.mVariableType = 'element'
6905 #return
6906
6907 if PhactoriDbg():
6908 myDebugPrint3('PhactoriVariableInfo::DetectVariableType entered\n')
6909
6910 if inInputIsProxy:
6911 pointData = inInputCsData.PointData
6912 else:
6913 pointData = inInputCsData.GetPointData()
6914 if pointData != None:
6915 testPointArray = pointData.GetArray(self.mVariableName)
6916 if testPointArray != None:
6917 if PhactoriDbg():
6918 myDebugPrint3(' type node detected!\n')
6919 self.mVariableType = 'node'
6920 self.mVariableTypeNeedsDetection = False
6921 self.mVariableTypeWasDetected = True
6922 return True
6923
6924 if inInputIsProxy:
6925 cellData = inInputCsData.CellData
6926 else:
6927 cellData = inInputCsData.GetCellData()
6928 if cellData != None:
6929 testCellArray = cellData.GetArray(self.mVariableName)
6930 if testCellArray != None:
6931 if PhactoriDbg():
6932 myDebugPrint3(' type element detected!\n')
6933 self.mVariableType = 'element'
6934 self.mVariableTypeNeedsDetection = False
6935 self.mVariableTypeWasDetected = True
6936 return True
6937
6938 if inAllowGlobalVariableDetection:
6939 if inInputIsProxy:
6940 fieldData = inInputCsData.FieldData
6941 else:
6942 fieldData = inInputCsData.GetFieldData()
6943 if fieldData != None:
6944 testFieldArray = fieldData.GetArray(self.mVariableName)
6945 if testFieldArray != None:
6946 if PhactoriDbg():
6947 myDebugPrint3(' type global detected!\n')
6948 self.mVariableType = 'global'
6949 self.mVariableTypeNeedsDetection = False
6950 self.mVariableTypeWasDetected = True
6951 return True
6952
6953 if PhactoriDbg():
6954 myDebugPrint3(' type not detected!\n')
6955 #default to 'element' type knowing assumption may be wrong,
6956 #leave mVariableTypeNeedsDetection set to True so we know the variable
6957 #type has not yet been successfully detected
6958 self.mVariableType = 'element'
6959 #self.mVariableType = 'node'
6960 return False
6961
6962 def GetXYPlotAxisTitle(self):
6963 "for this variable info, construct the name to put on the axis of an XY\n plot, e.g. with magnitude or component information"
6964
6965 if self.mVariableName[-1] == '_':
6966 axisTitle = str(self.mVariableName[0:-1])
6967 else:
6968 axisTitle = self.mVariableName
6969
6970 if self.mVariableIsVectorComponent:
6971 if self.mVariableComponent == 0:
6972 axisTitle += ' X component'
6973 elif self.mVariableComponent == 1:
6974 axisTitle += ' Y component'
6975 elif self.mVariableComponent == 2:
6976 axisTitle += ' Z component'
6977 else:
6978 if PhactoriDbg():
6979 myDebugPrint3(" variable component is not 0, 1, or 2, using 0 (X)\n")
6980 localVariableName = self.mVariableName + '_X'
6981 elif self.mVariableIsVectorMagnitude:
6982 axisTitle += " Magnitude"
6983
6984 return axisTitle
6985
6986 #phactori_combine_to_single_python_file_subpiece_end_1
6987
6988 class PhactoriDataCubeOneAxisInfo:
6989 def __init__(self):
6990 self.mUseLabelFlag = False
6991 self.mAxisLabel = ""
6992 self.mBaseAxisLabel = None
6993
6994 def DcoaiParseParametersFromJson(self, parentAxesInfo, inJsn, inXyzKey):
6995
6996 theKey = 'show ' + inXyzKey + ' axis tic marks'
6997 parentAxesInfo.mShowTicks = localGet1or0(inJsn, theKey, True)
6998 #parentAxesInfo.mShowEdges = 1
6999 #theKey = 'show ' + inXyzKey + ' axis minor tic marks'
7000
7001 theKey = 'show ' + inXyzKey + ' axis label'
7002 value = getParameterFromBlock(inJsn, theKey, True)
7003 if value == False:
7004 self.mUseLabelFlag = True
7005 self.mAxisLabel = ""
7006 else:
7007 self.mUseLabelFlag = False
7008
7009 theKey = inXyzKey + ' axis label name'
7010 if theKey in inJsn:
7011 self.mUseLabelFlag = True
7012 self.mAxisLabel = getParameterFromBlock(inJsn, theKey, "")
7013
7014 if PhactoriDbg():
7015 myDebugPrint3('DcoaiParseParametersFromJson ' + inXyzKey + ' ' \
7016 + str(parentAxesInfo.mShowTicks) + ' ' \
7017 + str(self.mUseLabelFlag) + ' ' \
7018 + str(self.mAxisLabel) + '\n')
7019
7020 class PhactoriDataCubeAxesInfo:
7021 def __init__(self):
7022 self.mShowEdges = 1
7023 self.mShowTicks = 1
7024 self.mXAxisInfo = PhactoriDataCubeOneAxisInfo()
7025 self.mYAxisInfo = PhactoriDataCubeOneAxisInfo()
7026 self.mZAxisInfo = PhactoriDataCubeOneAxisInfo()
7027
7028 def DcaiParseParametersFromJson(self, inJsn):
7029 self.mXAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'x')
7030 self.mYAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'y')
7031 self.mZAxisInfo.DcoaiParseParametersFromJson(self, inJsn, 'z')
7032
7033
7034 class PhactoriColorMapSettings:
7035 def __init__(self):
7036 self.mColorMapNameId = "Default"
7037 self.mInvertColorMap = False
7038 #self.mColorMapNameId = "Blue to Yellow"
7039 #self.mColorMapNameId = "Blue to Red Rainbow"
7040
7041 def ParseColorMapSettings(self, inJsn):
7042 self.mColorMapNameId = getParameterFromBlock(inJsn,
7043 'preset color scale', self.mColorMapNameId)
7044 self.mInvertColorMap = getParameterFromBlock(inJsn,
7045 'invert color scale', self.mInvertColorMap)
7046
7047 def GetThresholdContourHackVariableNameString(inVariableInfo):
7048 "gives altered variable name for magnitude or component\n in paraview, coloring by a vector component or magnitude is handled\n differently than thresholding or contouring by a vector component or\n magnitude. For the Contour and Threshold case, we add _X, _Y, or _Z to\n the variable name for component and _Magnitude for magnitude. In\n the coloring case, we specify component arguments and another argument\n as to whether to use magnitude or component. This routine takes the\n given variable info (name, whether or not vector component or magnitude)\n and creates a properly munged name to do the right thing"
7049
7050 if inVariableInfo.mVariableIsVectorComponent:
7051 if inVariableInfo.mVariableComponent == 0:
7052 localVariableName = inVariableInfo.mVariableName + '_X'
7053 elif inVariableInfo.mVariableComponent == 1:
7054 localVariableName = inVariableInfo.mVariableName + '_Y'
7055 elif inVariableInfo.mVariableComponent == 2:
7056 localVariableName = inVariableInfo.mVariableName + '_Z'
7057 else:
7058 if PhactoriDbg():
7059 myDebugPrint3(" variable component is not 0, 1, or 2, using 0 (X)\n")
7060 localVariableName = inVariableInfo.mVariableName + '_X'
7061 elif inVariableInfo.mVariableIsVectorMagnitude:
7062 localVariableName = inVariableInfo.mVariableName + '_Magnitude'
7063 else:
7064 localVariableName = inVariableInfo.mVariableName
7065
7066 return localVariableName
7067
7068 class PhactoriOperationSpecifics:
7069 #base class for operation specifics; probably need to reconfigure so
7070 #that we have a base operation abstract class rather than an operation
7071 #base class that has an operation specifics member which is a child
7072 #class of this class
7073 def __init__(self):
7074 if PhactoriDbg():
7075 myDebugPrint3("PhactoriOperationSpecifics::__init__ executed\n")
7076
7077 #which PhactoriOperationBlock instance owns/created this specific
7078 #operation. Set during ParseOneFilterTypeFromViewMapOperation()
7079 self.mPhactoriOperationBlockOwner = None
7080
7081 def GetListOfInputOperationNamesForThisOperationType(self):
7082 "operations which depend on additional inputs besides the default single\n input need to override this method and return their dependencies as a\n list of names"
7083 retList = []
7084 return retList
7085
7086 def CreateParaViewFilter(self):
7087 myDebugPrint3AndException("PhactoriOperationSpecifics:CreateParaViewFilter"
7088 " or CreateParaViewFilter2 should be overwritten by child\n")
7089
7090 def CreateParaViewFilter2(self, inInputOperation, ioPipeAndViewsState):
7091 return self.CreateParaViewFilter(inInputOperation)
7092
7093 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
7094 outOutgoingPvFilter):
7095 #default behavior is to do nothing on new data
7096 if PhactoriDbg():
7097 myDebugPrint3("PhactoriOperationSpecifics::"
7098 "DoUpdateDueToChangeInData executed\n")
7099 return False
7100
7101 def ExportOperationData(self, datadescription):
7102 "this will be called once per callback (before WriteImages) to allow the\n operation to export any desired data which is not an image. The child\n class should override this method if it wants so do something"
7103 return
7104
7105 #phactori_combine_to_single_python_file_parent_1
7106 #from Operation.PhactoriThresholdOperation import *
7107 #phactori_combine_to_single_python_file_subpiece_begin_1
7108 class PhactoriThresholdOperation(PhactoriOperationSpecifics):
7109 "Threshold operation, phactori interface adapter to the catalyst filter\n\n PhactoriThresholdOperation is the phactori manager for working with the\n paraview/catalyst Threshold() operation and its paramters, providing\n access and pipeline/input/output managment via the json, lexx/yacc, or soon\n yaml interface. The user may specify a named input to the filter, with the\n unnamed default being the incoming data mesh.\n\n For detailed information on the Threshold filter from ParaView, see the\n ParaView Documentation. The basic operation of the Threshold filter is to\n extract all cells and points for which cell or point mesh variable (e.g.\n pressure, temperature, vonmises, displacement) is inside a specified range.\n\n To add a PhactoriThresholdOperation to the incoming script, you add\n a sub-block to the 'operation blocks' section of the data with the 'type'\n key given a value of 'threshold'. You also specify one of a range of values\n to keep, a value below which to keep values above, or a value above which to\n keep points/nodes. One complete but simple example\n script:\n\n::\n\n {\n 'camera blocks':{'mycam1':{'type':'camera', 'look direction':[1.0, 2.0, 3.0]}},\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_on_slice_1':{\n 'operation':'mytempthrsh1',\n 'camera':'mycam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'threshold1_temperature.'\n }\n },\n 'operation blocks':{\n 'mytempthrsh1':{\n 'type':'threshold',\n 'variable scalar':'temperature',\n 'keep between':[10.0, 100.0]\n }\n }\n }\n\nRather than 'keep between' with a min/max range you can also have 'keep above' with a single value or 'keep below' with a single value, e.g.\n\n::\n\n 'keep above': 100.0\n or\n 'keep below': 10.0\n\n"
7110
7111 def __init__(self):
7112 PhactoriOperationSpecifics.__init__(self)
7113 #self.mVariableName = None
7114 #self.mElementOrNode = ""
7115 self.mVariableInfo = PhactoriVariableInfo()
7116 self.mRange = [0.0, 1.0]
7117
7118 #flag allows system to be set up to bypass this operation, especially
7119 #for testing camera settings against geometry without thresholds,
7120 #iso surfaces messing the tests up
7121 self.mBypassFlag = False
7122
7123 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
7124 outOutgoingPvFilter):
7125 "the PhactoriThresholdOperation may need to update if the variable type\n was not detectable in a previous callback, but is now detectable"
7126 if PhactoriDbg():
7127 myDebugPrint3("PhactoriThresholdOperation::"
7128 "DoUpdateDueToChangeInData override executing\n")
7129
7130 #BarrierLock("PhactoriThresholdOperation sync 700")
7131
7132 if self.mVariableInfo.mVariableTypeNeedsDetection == True:
7133 UpdatePipelineWithCurrentTimeArgument(inIncomingPvFilter)
7134 self.HandleVariableNeedingDetection(inIncomingPvFilter,
7135 outOutgoingPvFilter)
7136 if self.mVariableInfo.mVariableTypeNeedsDetection == False:
7137 UpdatePipelineWithCurrentTimeArgument(outOutgoingPvFilter)
7138
7139
7140 def ParseParametersFromJson(self, inJson):
7141
7142 self.mBypassFlag = getParameterFromBlock(inJson, 'bypass flag',
7143 self.mBypassFlag)
7144 if self.mBypassFlag == True:
7145 #this operation is bypassed: don't do other parsing
7146 return
7147
7148 foundVariableFlag = self.mVariableInfo.\
7149 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
7150
7151 if foundVariableFlag == False:
7152 errStr = "error! inJson has no variable info in\n PhactoriThresholdOperation.ParseParametersFromJson\n"
7153 if PhactoriDbg():
7154 myDebugPrint3(errStr)
7155 raise Exception(errStr)
7156
7157 #self.mVariableName = inJson['variable']
7158
7159 #if 'variable type' in inJson:
7160 # self.mElementOrNode = inJson['variable type']
7161 # if self.mElementOrNode != 'element' and self.mElementOrNode != 'node':
7162 # errStr = "error! inJson 'variable type' is neither node nor\nelement PhactoriThresholdOperation.ParseParametersFromJson\n"
7163 # myDebugPrint3(errStr)
7164 # raise Exception(errStr)
7165 #else:
7166 # errStr = "error! inJson has no 'variable type' key in\nPhactoriThresholdOperation.ParseParametersFromJson\n"
7167 # myDebugPrint3(errStr)
7168 # raise Exception(errStr)
7169
7170 if 'keep between' in inJson:
7171 self.mRange = inJson['keep between']
7172 elif 'keep below' in inJson:
7173 rangeMin = -sys.float_info.max
7174 rangeMax = inJson['keep below']
7175 self.mRange = [rangeMin, rangeMax]
7176 elif 'keep above' in inJson:
7177 rangeMin = inJson['keep above']
7178 rangeMax = sys.float_info.max
7179 self.mRange = [rangeMin, rangeMax]
7180 else:
7181 if PhactoriDbg():
7182 myDebugPrint3(" no keep between/above/below, using keep above 0.0\n")
7183 rangeMin = 0.0
7184 rangeMax = sys.float_info.max
7185 self.mRange = [rangeMin, rangeMax]
7186
7187 def HandleVariableNeedingDetection(self, inIncomingPvFilter,
7188 outOutgoingPvFilter):
7189
7190 detectResult = self.mVariableInfo.DetectVariableType(
7191 inIncomingPvFilter, True)
7192
7193 if self.mVariableInfo.mVariableType == 'element':
7194 scalarType = 'CELLS'
7195 elif self.mVariableInfo.mVariableType == 'node':
7196 scalarType = 'POINTS'
7197 else:
7198 errStr = "error! in PhactoriThresholdOperation.CreateParaViewFilter\n variable type is not element or node or detect but:\n " + \
7199 str(self.mVariableInfo.mVariableType) + \
7200 "\n"
7201 if PhactoriDbg():
7202 myDebugPrint3(errStr)
7203 raise Exception(errStr)
7204
7205 #hack to deal with how paraview/catalyst expects naming of threshold
7206 #variables which are vector components or magnitudes
7207
7208 localVariableName = GetThresholdContourHackVariableNameString(self.mVariableInfo)
7209
7210 if PhactoriDbg():
7211 myDebugPrint3(' name for variable in threshold: ' + localVariableName + '\n')
7212 outOutgoingPvFilter.Scalars = [scalarType, localVariableName]
7213
7214 def CreateParaViewFilter(self, inInputFilter):
7215 "create the threshold filter for ParaView"
7216 if PhactoriDbg(100):
7217 myDebugPrint3('PhactoriThresholdOperation.CreateParaViewFilter entered\n', 100)
7218 #info in block class should already be parsed and checked
7219
7220 #if the operation bypass flag is set to true, we want this
7221 #operation to do nothing and just pass the input to the output
7222 if self.mBypassFlag == True:
7223 if PhactoriDbg():
7224 myDebugPrint3("PhactoriThresholdOperation::CreateParaViewFilter\n" +
7225 "mBypassFlag was true, so paraview output filter is input filter")
7226 return inInputFilter
7227
7228 savedActiveSource = GetActiveSource()
7229
7230 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
7231
7232 #BarrierLock("PhactoriThresholdOperation sync 100")
7233 if PhactoriDbg():
7234 numCellArrays = inInputFilter.CellData.GetNumberOfArrays()
7235 myDebugPrint3("before threshold cell numCellArrays: " + str(numCellArrays) + "\n")
7236 for ii in range(0, numCellArrays):
7237 myDebugPrint3(inInputFilter.CellData.GetArray(ii).Name + "\n")
7238
7239 newParaViewFilter = Threshold(inInputFilter)
7240 global gParaViewCatalystVersionFlag
7241 if gParaViewCatalystVersionFlag < 51000:
7242 newParaViewFilter.ThresholdRange = self.mRange
7243 else:
7244 newParaViewFilter.LowerThreshold = self.mRange[0]
7245 newParaViewFilter.UpperThreshold = self.mRange[1]
7246 newParaViewFilter.ThresholdMethod = vtk.vtkThreshold.THRESHOLD_BETWEEN
7247
7248 self.HandleVariableNeedingDetection(inInputFilter, newParaViewFilter)
7249
7250 SetActiveSource(newParaViewFilter)
7251 SetActiveSource(savedActiveSource)
7252 #AddFilterToFilterMap(ioOperationBlock.mName, newParaViewFilter)
7253
7254 if PhactoriDbg(100):
7255 RecursivelyPrintPointAndCellArrayInformation(inInputFilter)
7256
7257 #inputSource = GetActiveSource()
7258 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7259 if PhactoriDbg():
7260 numCellArrays = newParaViewFilter.CellData.GetNumberOfArrays()
7261 myDebugPrint3("after threshold cell numCellArrays: " + str(numCellArrays) + "\n")
7262 for ii in range(0, numCellArrays):
7263 myDebugPrint3(newParaViewFilter.CellData.GetArray(ii).Name + "\n")
7264
7265 if PhactoriDbg(100):
7266 myDebugPrint3('PhactoriThresholdOperation.CreateParaViewFilter returning\n', 100)
7267
7268 return newParaViewFilter
7269
7270 #phactori_combine_to_single_python_file_subpiece_end_1
7271
7272 #phactori_combine_to_single_python_file_parent_1
7273 #from Operation.PhactoriAddUnstructuredGridOperation import *
7274 #phactori_combine_to_single_python_file_subpiece_begin_1
7275 class PhactoriAddUnstructuredGridOperation(PhactoriOperationSpecifics):
7276 "filter/operation which reads in a .vtu file which is an unstructured\n grid and creates a new source from that and groups it with the\n input source"
7277 def __init__(self):
7278 self.mFilename = None
7279 self.mInternalPvUnstructuredGridReader = None
7280
7281 def ParseParametersFromJson(self, inJson):
7282 if 'filename' in inJson:
7283 self.mFilename = inJson['filename']
7284 else:
7285 myDebugPrint3AndException(
7286 "PhactoriAddUnstructuredGridOperation::ParseParametersFromJson\n"
7287 "Error: must have 'filename' key\n")
7288
7289 def CreateParaViewFilter(self, inInputFilter):
7290 "create the read unstructured grid (and group) filter for ParaView"
7291 if PhactoriDbg(100):
7292 myDebugPrint3("PhactoriAddUnstructuredGridOperation.CreateParaViewFilter "
7293 "entered\n", 100)
7294
7295 savedActiveSource = GetActiveSource()
7296
7297 #csv reader
7298 self.mInternalPvUnstructuredGridReader = XMLUnstructuredGridReader( FileName=[self.mFilename] )
7299
7300 #don't know if this is necessary here
7301 UpdatePipelineWithCurrentTimeArgument(self.mInternalPvUnstructuredGridReader)
7302
7303 #now group this new point set source with the original one
7304 newParaViewFilter = GroupDatasets()
7305 newParaViewFilter.Input = [self.mInternalPvUnstructuredGridReader, inInputFilter]
7306
7307 SetActiveSource(newParaViewFilter)
7308 SetActiveSource(savedActiveSource)
7309
7310 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7311
7312 if PhactoriDbg(100):
7313 myDebugPrint3(
7314 "filename: " + str(self.mInternalPvUnstructuredGridReader.FileName) + "\n")
7315 myDebugPrint3("PhactoriAddUnstructuredGridOperation.CreateParaViewFilter "
7316 "returning\n", 100)
7317
7318 return newParaViewFilter
7319 #phactori_combine_to_single_python_file_subpiece_end_1
7320
7321 #phactori_combine_to_single_python_file_parent_1
7322 #from Operation.PhactoriAddPointSetOperation import *
7323 #phactori_combine_to_single_python_file_subpiece_begin_1
7324 class PhactoriAddPointSetOperation(PhactoriOperationSpecifics):
7325 "filter/operation which reads in a .csv file which is a set of points and\n creates a new source from that and groups it with the input source"
7326 def __init__(self):
7327 self.mXColumn = 'x column'
7328 self.mYColumn = 'y column'
7329 self.mZColumn = 'z column'
7330 self.m2dPointsFlag = False
7331 self.mFieldDelimeterCharacters = ','
7332 self.mFilename = None
7333 self.mInternalPvCSVReader = None
7334 self.mInternalPvTableToPoints = None
7335
7336 def ParseParametersFromJson(self, inJson):
7337 if 'filename' in inJson:
7338 self.mFilename = inJson['filename']
7339 else:
7340 myDebugPrint3AndException(
7341 "PhactoriAddPointSetOperation::ParseParametersFromJson\n"
7342 "Error: must have 'filename' key\n")
7343 if 'x column' in inJson:
7344 self.mXColumn = inJson['x column']
7345 if 'y column' in inJson:
7346 self.mYColumn = inJson['y column']
7347 if 'z column' in inJson:
7348 self.mZColumn = inJson['z column']
7349 if '2d points flag' in inJson:
7350 self.m2dPointsFlag = inJson['2d points flag']
7351 if 'field delimeter' in inJson:
7352 self.mFieldDelimeterCharacters = inJson['field delimeter']
7353
7354 def CreateParaViewFilter(self, inInputFilter):
7355 "create the read pointset (and group) filter for ParaView"
7356 if PhactoriDbg(100):
7357 myDebugPrint3("PhactoriAddPointSetOperation.CreateParaViewFilter "
7358 "entered\n", 100)
7359
7360 savedActiveSource = GetActiveSource()
7361
7362 #csv reader
7363 self.mInternalPvCSVReader = CSVReader( FileName=[self.mFilename] )
7364 self.mInternalPvCSVReader.FieldDelimiterCharacters = self.mFieldDelimeterCharacters
7365 #don't know if this is necessary here
7366 UpdatePipelineWithCurrentTimeArgument(self.mInternalPvCSVReader)
7367
7368 #table to points
7369 self.mInternalPvTableToPoints = TableToPoints(self.mInternalPvCSVReader)
7370 self.mInternalPvTableToPoints.XColumn = self.mXColumn
7371 self.mInternalPvTableToPoints.YColumn = self.mYColumn
7372 self.mInternalPvTableToPoints.ZColumn = self.mZColumn
7373 if self.m2dPointsFlag:
7374 self.mInternalPvTableToPoints.a2DPoints = 1
7375 else:
7376 self.mInternalPvTableToPoints.a2DPoints = 0
7377 #don't know if this is necessary here
7378 UpdatePipelineWithCurrentTimeArgument(self.mInternalPvTableToPoints)
7379
7380 #now group this new point set source with the original one
7381 newParaViewFilter = GroupDatasets()
7382 newParaViewFilter.Input = [self.mInternalPvTableToPoints, inInputFilter]
7383 #newParaViewFilter = self.mInternalPvTableToPoints
7384
7385 SetActiveSource(newParaViewFilter)
7386 SetActiveSource(savedActiveSource)
7387
7388 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7389
7390 if PhactoriDbg(100):
7391 myDebugPrint3(
7392 "filename: " + str(self.mInternalPvCSVReader.FileName) + "\n"
7393 "delimeter: -->" + str(self.mInternalPvCSVReader.FieldDelimiterCharacters) + "<--\n"
7394 "x column: " + str(self.mInternalPvTableToPoints.XColumn) + "\n"
7395 "y column: " + str(self.mInternalPvTableToPoints.YColumn) + "\n"
7396 "z column: " + str(self.mInternalPvTableToPoints.ZColumn) + "\n"
7397 "2d points flag: " + str(self.mInternalPvTableToPoints.a2DPoints) + "\n")
7398 myDebugPrint3("PhactoriAddPointSetOperation.CreateParaViewFilter "
7399 "returning\n", 100)
7400
7401 return newParaViewFilter
7402
7403 #phactori_combine_to_single_python_file_subpiece_end_1
7404
7405 #phactori_combine_to_single_python_file_parent_1
7406 #from Operation.PhactoriReflectOperation import *
7407 #phactori_combine_to_single_python_file_subpiece_begin_1
7408 class PhactoriReflectOperation(PhactoriOperationSpecifics):
7409 "manages reflect filter, also inserts group filter"
7410 def __init__(self):
7411 PhactoriOperationSpecifics.__init__(self)
7412 self.mPlane = "X Min"
7413 self.mCenter = 0.0
7414
7415 #we keep internal reflect filter, because group filter is the one exposed
7416 #to the rest of the world
7417 self.mInternalReflectFilter = None
7418
7419 def ParseParametersFromJson(self, inJson):
7420 if 'plane' in inJson:
7421 self.mPlane = inJson['plane']
7422 else:
7423 myDebugPrint3AndException(
7424 "PhactoriReflectOperation::ParseParametersFromJson\n"
7425 "Error: must have 'plane' key\n")
7426 if 'center' in inJson:
7427 self.mCenter = inJson['center']
7428
7429 def CreateParaViewFilter(self, inInputFilter):
7430 "create the reflect (and group) filter for ParaView"
7431 if PhactoriDbg(100):
7432 myDebugPrint3("PhactoriReflectOperation.CreateParaViewFilter "
7433 "entered\n", 100)
7434
7435 savedActiveSource = GetActiveSource()
7436
7437 self.mInternalReflectFilter = Reflect(inInputFilter)
7438 self.mInternalReflectFilter.Plane = self.mPlane
7439 self.mInternalReflectFilter.Center = self.mCenter
7440 #don't know if this is necessary here
7441 UpdatePipelineWithCurrentTimeArgument(self.mInternalReflectFilter)
7442
7443 #now grop this new source with the original non-reflected one
7444 newParaViewFilter = GroupDatasets()
7445 newParaViewFilter.Input = [self.mInternalReflectFilter, inInputFilter]
7446
7447 SetActiveSource(newParaViewFilter)
7448 SetActiveSource(savedActiveSource)
7449
7450 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7451
7452 if PhactoriDbg(100):
7453 myDebugPrint3("reflect plane: " + str(self.mInternalReflectFilter.Plane) + "\n"
7454 "reflect center: " + str(self.mInternalReflectFilter.Center) + "\n")
7455 myDebugPrint3("PhactoriReflectOperation.CreateParaViewFilter "
7456 "returning\n", 100)
7457
7458 return newParaViewFilter
7459
7460 #phactori_combine_to_single_python_file_subpiece_end_1
7461
7462 #phactori_combine_to_single_python_file_parent_1
7463 #from Operation.PhactoriWarpByVectorOperation import *
7464 #phactori_combine_to_single_python_file_subpiece_begin_1
7465 class PhactoriWarpByVectorOperation(PhactoriOperationSpecifics):
7466 "manages warpbyvector filter"
7467 def __init__(self):
7468 PhactoriOperationSpecifics.__init__(self)
7469 self.mVectorName = ""
7470 self.mVariableType = "node"
7471 self.mScaleFactor = 1.0
7472
7473 def ParseParametersFromJson(self, inJson):
7474 if 'variable type' in inJson:
7475 self.mVariableType = inJson['variable type']
7476 elif 'variablename' in inJson:
7477 self.mVectorName = inJson['variablename']
7478 elif 'variable vector' in inJson:
7479 self.mVectorName = inJson['variable vector']
7480 else:
7481 myDebugPrint3AndException(
7482 "PhactoriWarpByVectorOperation::ParseParametersFromJson\n"
7483 "Error: must have 'vector name' key\n")
7484 if 'scale' in inJson:
7485 self.mScaleFactor = inJson['scale']
7486
7487 def CreateParaViewFilter(self, inInputFilter):
7488 "create the warp by vector filter for ParaView"
7489 if PhactoriDbg(100):
7490 myDebugPrint3("PhactoriWarpByVectorOperation.CreateParaViewFilter "
7491 "entered\n", 100)
7492
7493 savedActiveSource = GetActiveSource()
7494
7495 newParaViewFilter = WarpByVector(inInputFilter)
7496 newParaViewFilter.ScaleFactor = self.mScaleFactor
7497 if self.mVariableType == 'cell':
7498 varTypeString = 'CELLS'
7499 else:
7500 varTypeString = 'POINTS'
7501 newParaViewFilter.Vectors = [varTypeString, self.mVectorName]
7502
7503 SetActiveSource(newParaViewFilter)
7504 SetActiveSource(savedActiveSource)
7505
7506 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7507
7508 if PhactoriDbg(100):
7509 myDebugPrint3("vector name: " + self.mVectorName + "\n"
7510 "variable type: " + varTypeString + "\n"
7511 "scale factor: " + str(newParaViewFilter.ScaleFactor) + "\n")
7512 myDebugPrint3("PhactoriWarpByVectorOperation.CreateParaViewFilter "
7513 "returning\n", 100)
7514
7515 return newParaViewFilter
7516
7517 #phactori_combine_to_single_python_file_subpiece_end_1
7518
7519 #phactori_combine_to_single_python_file_parent_1
7520 #from Operation.PhactoriCalculatorOperation import *
7521 #phactori_combine_to_single_python_file_subpiece_begin_1
7522 class PhactoriCalculatorOperation(PhactoriOperationSpecifics):
7523 "manages calculator filter"
7524 def __init__(self):
7525 PhactoriOperationSpecifics.__init__(self)
7526 self.mFunction = ""
7527 self.mResultArrayName = 'Result'
7528 self.mPointOrCell = 'Point Data'
7529
7530 def ParseParametersFromJson(self, inJson):
7531 if 'function' in inJson:
7532 #function is supposed to be array of terms as strings; concatenate them
7533 #to get actual function string; this is this way due to sierra parsing
7534 #self.mFunction = "".join(inJson['function'])
7535 #
7536 #since numbers are coming across as floats, we need to convert them
7537 #to strings for the paraview calculator function as well
7538 functionStringItems = []
7539 for oneItem in inJson['function']:
7540 functionStringItems.append(str(oneItem))
7541 self.mFunction = "".join(functionStringItems)
7542 else:
7543 myDebugPrint3AndException(
7544 "PhactoriCalculatorOperation::ParseParametersFromJson\n"
7545 "Error: must have 'function' key\n")
7546 if 'resultname' in inJson:
7547 self.mResultArrayName = inJson['resultname']
7548 if 'output variable name' in inJson:
7549 self.mResultArrayName = inJson['output variable name']
7550 if 'vector ' in inJson:
7551 self.mResultArrayName = inJson['resultname']
7552 if 'element or node data' in inJson:
7553 if inJson['element or node data'] == 'node':
7554 self.mPointOrCell = 'Point Data'
7555 elif inJson['element or node data'] == 'element':
7556 self.mPointOrCell = 'Cell Data'
7557 else:
7558 myDebugPrint3AndException(
7559 "PhactoriCalculatorOperation::ParseParametersFromJson\n"
7560 "element or node data must be 'node' or 'element'\n")
7561 elif 'nodeorelement' in inJson:
7562 if inJson['nodeorelement'] == 'node':
7563 self.mPointOrCell = 'Point Data'
7564 elif inJson['nodeorelement'] == 'element':
7565 self.mPointOrCell = 'Cell Data'
7566 else:
7567 myDebugPrint3AndException(
7568 "PhactoriCalculatorOperation::ParseParametersFromJson\n"
7569 "nodeorelement data must be 'node' or 'element'\n")
7570 elif 'pointorcell' in inJson:
7571 if inJson['pointorcell'] == 'point':
7572 self.mPointOrCell = 'Point Data'
7573 elif inJson['pointorcell'] == 'cell':
7574 self.mPointOrCell = 'Cell Data'
7575 else:
7576 myDebugPrint3AndException(
7577 "PhactoriCalculatorOperation::ParseParametersFromJson\n"
7578 "node or element data must be 'node' or 'point' or 'element' or 'cell'\n")
7579
7580 def CreateParaViewFilter(self, inInputFilter):
7581 "create the calculator filter for ParaView"
7582 if PhactoriDbg(100):
7583 myDebugPrint3("PhactoriCalculatorOperation.CreateParaViewFilter "
7584 "entered\n", 100)
7585
7586 savedActiveSource = GetActiveSource()
7587
7588 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
7589
7590 if PhactoriDbg():
7591 myDebugPrint3(" calculator inInputFilter point data arrays:\n")
7592 numArrays = inInputFilter.PointData.GetNumberOfArrays()
7593 for ii in range (0, numArrays):
7594 myDebugPrint3(" " + str(ii) + ": " + inInputFilter.PointData.GetArray(ii).GetName() + "\n")
7595
7596 if PhactoriDbg():
7597 myDebugPrint3(" calculator inInputFilter cell data arrays:\n")
7598 numArrays = inInputFilter.CellData.GetNumberOfArrays()
7599 for ii in range (0, numArrays):
7600 myDebugPrint3(" " + str(ii) + ": " + inInputFilter.CellData.GetArray(ii).GetName() + "\n")
7601
7602
7603 newParaViewFilter = Calculator(inInputFilter)
7604 mypid = SmartGetLocalProcessId()
7605 if self.mFunction.find("Hat") < 0:
7606 constfunc = "11.5"
7607 else:
7608 constfunc = "1.0*iHat+2.0*jHat+3.0*kHat"
7609
7610 #self.mPointOrCell = 'Cell Data'
7611
7612 if self.mPointOrCell == "Cell Data":
7613 if inInputFilter.CellData.GetNumberOfArrays() == 0:
7614 myDebugPrint3("process " + str(mypid) + " has no cell arrays, using function " + constfunc + "\n")
7615 newParaViewFilter.Function = constfunc
7616 #elif str(inInputFilter.CellData.GetArray(0).GetName()) != "V":
7617 # myDebugPrint3("process " + str(mypid) + " 0th cell array not V, using function " + constfunc + "\n")
7618 # newParaViewFilter.Function = constfunc
7619 else:
7620 myDebugPrint3("process " + str(mypid) + " has cell arrays, using function " + self.mFunction + "\n")
7621 newParaViewFilter.Function = self.mFunction
7622 else:
7623 if inInputFilter.PointData.GetNumberOfArrays() == 0:
7624 myDebugPrint3("process " + str(mypid) + " has no point arrays, using function " + constfunc + "\n")
7625 newParaViewFilter.Function = constfunc
7626 else:
7627 myDebugPrint3("process " + str(mypid) + " has cell arrays, using function " + self.mFunction + "\n")
7628 newParaViewFilter.Function = self.mFunction
7629 #newParaViewFilter.AttributeMode = 'Cell Data'
7630 #newParaViewFilter.AttributeMode = 'Point Data'
7631
7632 if gParaViewCatalystVersionFlag < 50502:
7633 newParaViewFilter.AttributeMode = self.mPointOrCell
7634 else:
7635 newParaViewFilter.AttributeType = self.mPointOrCell
7636
7637 newParaViewFilter.ResultArrayName = self.mResultArrayName
7638
7639 SetActiveSource(newParaViewFilter)
7640 SetActiveSource(savedActiveSource)
7641
7642 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
7643
7644 if PhactoriDbg(100):
7645 myDebugPrint3("function: " + str(newParaViewFilter.Function) + "\n"
7646 "result array name: " + str(newParaViewFilter.ResultArrayName) + "\n"
7647 "PhactoriTransformOperation.CreateParaViewFilter returning\n", 100)
7648
7649 return newParaViewFilter
7650 #phactori_combine_to_single_python_file_subpiece_end_1
7651
7652 #phactori_combine_to_single_python_file_parent_1
7653 #from Operation.PhactoriTransformOperation import *
7654 #phactori_combine_to_single_python_file_subpiece_begin_1
7655 class PhactoriTransformOperation(PhactoriOperationSpecifics):
7656 "manages transform filter--scale, rotate, translate"
7657 def __init__(self):
7658 PhactoriOperationSpecifics.__init__(self)
7659 self.mTranslate = [0.0, 0.0, 0.0]
7660 self.mRotate = [0.0, 0.0, 0.0]
7661 self.mScale = [1.0, 1.0, 1.0]
7662
7663 def ParseParametersFromJson(self, inJson):
7664 if 'scale' in inJson:
7665 self.mScale = inJson['scale']
7666 if 'translate' in inJson:
7667 self.mTranslate = inJson['translate']
7668 if 'rotate' in inJson:
7669 self.mRotate = inJson['rotate']
7670
7671 def CreateParaViewFilter(self, inInputFilter):
7672 "create the transform filter for ParaView"
7673 if PhactoriDbg(100):
7674 myDebugPrint3("PhactoriTransformOperation.CreateParaViewFilter "
7675 "entered\n", 100)
7676
7677 savedActiveSource = GetActiveSource()
7678
7679 #newParaViewFilter = Transform(inInputFilter, Transform = "Transform")
7680 SetActiveSource(inInputFilter)
7681 inInputFilter.UpdatePipeline()
7682 newParaViewFilter = Transform(Transform = "Transform")
7683 newParaViewFilter.Transform = "Transform"
7684 newParaViewFilter.Transform.Scale = self.mScale
7685 newParaViewFilter.Transform.Translate = self.mTranslate
7686 newParaViewFilter.Transform.Rotate = self.mRotate
7687
7688 SetActiveSource(newParaViewFilter)
7689 SetActiveSource(savedActiveSource)
7690
7691 if PhactoriDbg(100):
7692 myDebugPrint3(
7693 "translate: " + str(newParaViewFilter.Transform.Translate) + "\n"
7694 "rotate: " + str(newParaViewFilter.Transform.Rotate) + "\n"
7695 "scale: " + str(newParaViewFilter.Transform.Scale) + "\n"
7696 "input: " + str(newParaViewFilter.Input) + "\n")
7697 myDebugPrint3("PhactoriTransformOperation.CreateParaViewFilter "
7698 "returning\n", 100)
7699
7700 return newParaViewFilter
7701
7702 #phactori_combine_to_single_python_file_subpiece_end_1
7703
7704 class SharedTriangleSet():
7705 "idea is that this encapsulates a set of triangles which are the triangles\n from the overall surface of interest which reside on a single processor.\n You can store your local processor triangles in this class and broadcast\n from them and you can receive a broadcast of this setup from other\n processes"
7706
7707 def __init__(self):
7708 self.numPoints = -1
7709 self.numTriangles = -1
7710 #triangle points in xyzxyzxyzxyz order
7711 self.PointXyzs = vtk.vtkDoubleArray()
7712 #global node id for each point to help avoid self intersection
7713 self.NodeIds = vtk.vtkIntArray()
7714 #triplets of indexes into self.PointXyzs to represent triangles, in
7715 #abcabcabcabc order
7716 self.Triangles = vtk.vtkIntArray()
7717 self.fromPid = -1
7718
7719 #to share num points and num tris
7720 self.shareSizes = vtk.vtkIntArray()
7721 self.shareSizes.SetNumberOfValues(2)
7722
7723 self.BspTree = None
7724 self.UseBSPTreeForRayIntersection = True
7725
7726 def CreateFromLocalProcess(self, inPhactoriOperation):
7727 "figure out the set of triangles from the target surface which are on\n this process (if any): we assume we have a triangle mesh or this code\n won't work"
7728
7729 #obtain pointer to the local geometry data
7730 csdata = inPhactoriOperation.mParaViewFilter.GetClientSideObject().\
7731 GetOutputDataObject(0)
7732
7733 self.numPoints = csdata.GetNumberOfPoints()
7734 if PhactoriDbg():
7735 myDebugPrint3(str(dir(csdata)) + "\n")
7736 myDebugPrint3("num points: " + str(self.numPoints) + "\n")
7737 myDebugPrint3(str(dir(vtk)) + "\n")
7738
7739 pntData = csdata.GetPointData()
7740 cellData = csdata.GetCellData()
7741 numCells = csdata.GetNumberOfCells()
7742 gNodeIdArray = pntData.GetArray('GlobalNodeId')
7743 #gElmtIdArray = cellData.GetArray('GlobalElementId')
7744 #pntGeometryArray = csdata.GetPoints()
7745
7746 self.PointXyzs.SetNumberOfValues(self.numPoints*3)
7747 self.NodeIds = vtk.vtkIntArray()
7748 self.NodeIds.SetNumberOfValues(self.numPoints)
7749
7750 #this is stupid, there is probably a much faster way to do this
7751 ptxyz = [0.0,0.0,0.0]
7752 for ii in range(0, self.numPoints):
7753 ndx = ii*3
7754 csdata.GetPoint(ii,ptxyz)
7755 self.PointXyzs.SetValue(ndx, ptxyz[0])
7756 self.PointXyzs.SetValue(ndx+1, ptxyz[1])
7757 self.PointXyzs.SetValue(ndx+2, ptxyz[2])
7758 if(gNodeIdArray == None):
7759 self.NodeIds.SetValue(ii, ii)
7760 else:
7761 self.NodeIds.SetValue(ii, gNodeIdArray.GetValue(ii))
7762
7763 self.Triangles.SetNumberOfValues(0)
7764 cellPointIds = vtk.vtkIdList()
7765 for ii in range(0, numCells):
7766 csdata.GetCellPoints(ii, cellPointIds)
7767 #numpoints should be 3
7768 numids = cellPointIds.GetNumberOfIds()
7769 #we are only doing triangles
7770 if numids != 3:
7771 if numids < 3:
7772 #degenerate ? try just skipping
7773 if PhactoriDbg():
7774 myDebugPrint3AndException(str(ii) + " degenerate 2 point\n")
7775 continue
7776 if True: #for now we consider this fatal error
7777 myDebugPrint3AndException(
7778 "PhactoriIntersectNodeNormalsWithSurface::CreateFromLocalProcess\n"
7779 "encountered non-triangle\n")
7780 continue
7781 self.Triangles.InsertNextValue(cellPointIds.GetId(0))
7782 self.Triangles.InsertNextValue(cellPointIds.GetId(1))
7783 self.Triangles.InsertNextValue(cellPointIds.GetId(2))
7784 self.numTriangles = self.Triangles.GetNumberOfValues() // 3
7785
7786 def SendBroadcast(self, inLocalPid, globalController):
7787 "broadcast the triangle set from the local process to all the other\n processes"
7788 if (self.numPoints < 0) or (self.numTriangles < 0):
7789 myDebugPrint3AndException(
7790 "PhactoriIntersectNodeNormalsWithSurface::SendBroadcast\n"
7791 "can't broadcast without being filled in first\n")
7792
7793 if PhactoriDbg():
7794 myDebugPrint3("SharedTriangleSet::SendBroadcast entered, inLocalPid " + \
7795 str(inLocalPid) + \
7796 "\nself.numPoints " + str(self.numPoints) + \
7797 " self.numTriangles " + str(self.numTriangles) + "\n")
7798
7799 #first broadcast number of points and number of triangles
7800 self.shareSizes.SetValue(0, self.numPoints)
7801 self.shareSizes.SetValue(1, self.numTriangles)
7802
7803 globalController.Broadcast(self.shareSizes, inLocalPid)
7804
7805 self.fromPid = inLocalPid
7806
7807 if self.numTriangles == 0:
7808 if PhactoriDbg():
7809 myDebugPrint3(
7810 "SharedTriangleSet::SendBroadcast returning, nothing to send\n")
7811 return
7812
7813 globalController.Broadcast(self.PointXyzs, inLocalPid)
7814 globalController.Broadcast(self.NodeIds, inLocalPid)
7815 globalController.Broadcast(self.Triangles, inLocalPid)
7816
7817 if PhactoriDbg():
7818 myDebugPrint3("SharedTriangleSet::SendBroadcast returning, inLocaPid " \
7819 + str(inLocalPid) + "\n")
7820
7821 def ReceiveBroadcast(self, inFromPid, globalController):
7822 "receive a triangle set broadcast from the another process to the local\n process"
7823 if PhactoriDbg():
7824 myDebugPrint3(
7825 "SharedTriangleSet::ReceiveBroadcast entered, inFromPid " + \
7826 str(inFromPid) + "\n")
7827
7828 globalController.Broadcast(self.shareSizes, inFromPid)
7829 self.fromPid = inFromPid
7830
7831 self.numPoints = self.shareSizes.GetValue(0)
7832 self.numTriangles = self.shareSizes.GetValue(1)
7833
7834 if self.numTriangles == 0:
7835 if PhactoriDbg():
7836 myDebugPrint3(
7837 "SharedTriangleSet::ReceiveBroadcast returning, nothing to get\n")
7838 return
7839
7840 self.PointXyzs.SetNumberOfValues(3*self.numPoints)
7841 self.NodeIds.SetNumberOfValues(self.numPoints)
7842 self.Triangles.SetNumberOfValues(3*self.numTriangles)
7843
7844 globalController.Broadcast(self.PointXyzs, inFromPid)
7845 globalController.Broadcast(self.NodeIds, inFromPid)
7846 globalController.Broadcast(self.Triangles, inFromPid)
7847
7848 if PhactoriDbg():
7849 myDebugPrint3(
7850 "SharedTriangleSet::ReceiveBroadcast returning, inFromPid " + \
7851 str(inFromPid) + \
7852 "\nself.numPoints " + str(self.numPoints) + \
7853 " self.numTriangles " + str(self.numTriangles) + "\n")
7854
7855 def IntersectWithOneRayViaBSPTree(self, inIndex, inRayStart, inRayDirection,
7856 ioRaycastOperation, inPointOrCellData,
7857 inRayEnd1, inRayEnd2, inBothDirFlag):
7858 if PhactoriDbg():
7859 myDebugPrint3(
7860 "bspt ray: " + str(inIndex) + " " + str(inRayStart) + " " + \
7861 str(inRayDirection) + " " + str(inPointOrCellData) + "\n")
7862
7863 #BSPTree interect with line
7864 #V.IntersectWithLine((float, float, float), (float, float, float),
7865 # float, vtkPoints, vtkIdList) -> int
7866 #C++: virtual int IntersectWithLine(const double p1[3],
7867 # const double p2[3], const double tol, vtkPoints *points,
7868 # vtkIdList *cellIds)
7869 hitPoints = vtk.vtkPoints()
7870 hitIds = vtk.vtkIdList()
7871 segmentStart = vecMultiplyAdd(inRayStart, inRayDirection, inRayEnd1)
7872 segmentEnd = vecMultiplyAdd(inRayStart, inRayDirection, inRayEnd2)
7873 self.BspTree.IntersectWithLine(segmentStart, segmentEnd, 0.0001,
7874 hitPoints, hitIds)
7875 numhits = hitPoints.GetNumberOfPoints()
7876 if PhactoriDbg():
7877 myDebugPrint3("results from self.BspTree.IntersectWithLine:\n"
7878 "num hits: " + str(numhits) + "\n"
7879 "index, id, xyz\n")
7880 for hhpp in range(0, numhits):
7881 myDebugPrint3(str(hhpp) + ", " + str(hitIds.GetId(hhpp)) + ", " + \
7882 str(hitPoints.GetPoint(hhpp)) + "\n")
7883
7884 numhitsB = 0
7885 if inBothDirFlag:
7886 hitPointsB = vtk.vtkPoints()
7887 hitIdsB = vtk.vtkIdList()
7888 segmentStart = vecMultiplyAdd(inRayStart, inRayDirection, -inRayEnd1)
7889 segmentEnd = vecMultiplyAdd(inRayStart, inRayDirection, -inRayEnd2)
7890 self.BspTree.IntersectWithLine(segmentStart, segmentEnd, 0.0001,
7891 hitPointsB, hitIdsB)
7892 numhitsB = hitPointsB.GetNumberOfPoints()
7893 if PhactoriDbg():
7894 myDebugPrint3("other direction self.BspTree.IntersectWithLine:\n"
7895 "num hits B: " + str(numhitsB) + "\n"
7896 "index, id, xyz B\n")
7897 for hhpp in range(0, numhitsB):
7898 myDebugPrint3(str(hhpp) + ", " + str(hitIdsB.GetId(hhpp)) + ", " + \
7899 str(hitPointsB.GetPoint(hhpp)) + "\n")
7900
7901 #find nearest hit point
7902 if (numhits > 0) or (numhitsB > 0):
7903 hitxyz = [0.0,0.0,0.0]
7904 hit2xyz = [0.0,0.0,0.0]
7905 distsqrd = sys.float_info.max
7906 for ii in range(0,numhits):
7907 hitPoints.GetPoint(ii, hit2xyz)
7908 distsqrd2 = vecDistanceSquared(inRayStart, hit2xyz)
7909 if(distsqrd2 < distsqrd):
7910 distsqrd = distsqrd2
7911 vecCopy(hitxyz, hit2xyz)
7912 for ii in range(0,numhitsB):
7913 hitPointsB.GetPoint(ii, hit2xyz)
7914 distsqrd2 = vecDistanceSquared(inRayStart, hit2xyz)
7915 if(distsqrd2 < distsqrd):
7916 distsqrd = distsqrd2
7917 vecCopy(hitxyz, hit2xyz)
7918
7919 if PhactoriDbg():
7920 myDebugPrint3(
7921 "nearest hit: " + str(distsqrd) + " " + str(hitxyz) + "\n")
7922
7923 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
7924 if inPointOrCellData <= 0:
7925 ioRaycastOperation.SegmentsFromPointRays.TestAndSet(
7926 inIndex, distsqrd, inRayStart, hitxyz)
7927 else:
7928 ioRaycastOperation.SegmentsFromTriangleRays.TestAndSet(
7929 inIndex, distsqrd, inRayStart, hitxyz)
7930 else:
7931 hitdist = math.sqrt(distsqrd)
7932 if inPointOrCellData <= 0:
7933 oldvv = ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
7934 GetValue(inIndex)
7935 if (oldvv < 0.0) or (hitdist < oldvv):
7936 ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
7937 SetValue(inIndex, hitdist)
7938 else:
7939 oldvv = ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
7940 GetValue(inIndex)
7941 if (oldvv < 0.0) or (hitdist < oldvv):
7942 ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
7943 SetValue(inIndex, hitdist)
7944
7945 def IntersectWithOneRay(self, inIndex, inRayStart, inRayDirection,
7946 ioRaycastOperation, inPointOrCellData):
7947 "this is not used, but we are leaving it in as a reference for how to\n do a ray/triangle intersection directly"
7948 if PhactoriDbg():
7949 myDebugPrint3(
7950 "ray: " + str(inIndex) + " " + str(inRayStart) + " " + \
7951 str(inRayDirection) + " " + str(inPointOrCellData) + "\n")
7952
7953 ptA = [0.0,0.0,0.0]
7954 ptB = [0.0,0.0,0.0]
7955 ptC = [0.0,0.0,0.0]
7956 hitPoint = [0.0, 0.0, 0.0, 0.0]
7957 saveHit = [0.0, 0.0, 0.0, -1.0]
7958 #if PhactoriDbg():
7959 # myDebugPrint3(
7960 # "self.Triangles.GetNumberOfValues() " + str(self.Triangles.GetNumberOfValues()) + "\n")
7961 # myDebugPrint3(
7962 # "self.PointXyzs.GetNumberOfValues() " + str(self.PointXyzs.GetNumberOfValues()) + "\n")
7963 hitCount = 0
7964 for ii in range(0, self.numTriangles):
7965 ndx = ii * 3
7966 ptndxA = self.Triangles.GetValue(ndx)
7967 ptndxB = self.Triangles.GetValue(ndx+1)
7968 ptndxC = self.Triangles.GetValue(ndx+2)
7969 #if PhactoriDbg():
7970 # myDebugPrint3("ptndxABC: " + str(ptndxA) + " " + str(ptndxB) + " " + str(ptndxC) + "\n");
7971 ptndxA *= 3
7972 ptA[0] = self.PointXyzs.GetValue(ptndxA)
7973 ptA[1] = self.PointXyzs.GetValue(ptndxA+1)
7974 ptA[2] = self.PointXyzs.GetValue(ptndxA+2)
7975 ptndxB *= 3
7976 ptB[0] = self.PointXyzs.GetValue(ptndxB)
7977 ptB[1] = self.PointXyzs.GetValue(ptndxB+1)
7978 ptB[2] = self.PointXyzs.GetValue(ptndxB+2)
7979 ptndxC *= 3
7980 ptC[0] = self.PointXyzs.GetValue(ptndxC)
7981 ptC[1] = self.PointXyzs.GetValue(ptndxC+1)
7982 ptC[2] = self.PointXyzs.GetValue(ptndxC+2)
7983 #if PhactoriDbg():
7984 # myDebugPrint3("try " + str(ii) + " " + str(ptA) + "\n")
7985 hitFlag = self.IntersectRayTriangle(
7986 inRayStart, inRayDirection, ptA, ptB, ptC, hitPoint)
7987 if hitFlag:
7988 hitCount += 1
7989 if PhactoriDbg():
7990 myDebugPrint3("Hit " + str(hitCount) + "! " + str(hitPoint) + "\n")
7991 vvx = vecFromAToB(inRayStart, hitPoint)
7992 vvxdist = math.sqrt(vecDotProduct(vvx,vvx))
7993 myDebugPrint3("calculated distance: " + str(vvxdist) + "\n")
7994 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
7995 #onelinesource = Line()
7996 #onelinesource.Point1 = inRayStart
7997 #onelinesource.Point2 = [hitPoint[0], hitPoint[1], hitPoint[2]]
7998 #ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)
7999 if (saveHit[3] < 0.0) or (hitPoint[3] < saveHit[3]):
8000 saveHit[0] = hitPoint[0]
8001 saveHit[1] = hitPoint[1]
8002 saveHit[2] = hitPoint[2]
8003 saveHit[3] = hitPoint[3]
8004 else:
8005 if inPointOrCellData <= 0:
8006 oldvv = ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
8007 GetValue(inIndex)
8008 newvv = hitPoint[3]
8009 if (oldvv < 0.0) or (newvv < oldvv):
8010 ioRaycastOperation.mPointNormalRayIntersectDistanceArray.\
8011 SetValue(inIndex, hitPoint[3])
8012 else:
8013 oldvv = ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
8014 GetValue(inIndex)
8015 newvv = hitPoint[3]
8016 if (oldvv < 0.0) or (newvv < oldvv):
8017 ioRaycastOperation.mCellNormalRayIntersectDistanceArray.\
8018 SetValue(inIndex, hitPoint[3])
8019
8020 if ioRaycastOperation.mCreateIntersectionSegmentGroup:
8021 if saveHit[3] >= 0.0:
8022 onelinesource = Line()
8023 onelinesource.Point1 = inRayStart
8024 onelinesource.Point2 = [saveHit[0], saveHit[1], saveHit[2]]
8025 ioRaycastOperation.mGroupLineSource.Input.append(onelinesource)
8026
8027
8028 def IntersectRayTriangleNumpy(self, inRayStart, inRayDirection, ptA, ptB, ptC, outPt):
8029 #we can remove this import for frozen python (IntersectRayTriangleNumpy
8030 #won't work)
8031 import numpy as np
8032
8033 edge1 = ptB - ptA
8034 edge2 = ptC - ptA
8035 EPSILON = 0.0000001
8036 hh = np.cross(inRayDirection, edge2)
8037 aa = np.dot(edge1, hh)
8038 if (aa > -EPSILON) and (aa < EPSILON):
8039 return False
8040 ff = 1.0/aa
8041 ss = inRayStart - ptA
8042 uu = np.dot(ss, hh)
8043 uu *= ff
8044 if (uu < 0.0) or (uu > 1.0):
8045 return False;
8046 qq = np.cross(ss, edge1)
8047 vv = np.dot(inRayDirection, qq)
8048 vv *= ff
8049 if (vv < 0.0) or (uu + vv > 1.0):
8050 return False;
8051 #At this stage we can compute t to find out where the intersection point
8052 #is on the line.
8053 tt = np.dot(edge2, qq)
8054 tt *= ff
8055 if (tt > EPSILON):
8056 #ray intersection
8057 outPt[0] = inRayStart[0] + inRayDirection[0] * tt
8058 outPt[1] = inRayStart[1] + inRayDirection[1] * tt
8059 outPt[2] = inRayStart[2] + inRayDirection[2] * tt
8060 outPt[3] = tt
8061 return True
8062 else:
8063 #This means that there is a line intersection but not a ray intersection
8064 return False
8065
8066 def IntersectRayTriangle(self, inRayStart, inRayDirection, ptA, ptB, ptC, outPt):
8067 #if PhactoriDbg():
8068 # myDebugPrint3("IntersectRayTriangle entered " + str(ptA) + "\n")
8069 #c function from wikipedia translated to python
8070 edge1 = vecFromAToB(ptA, ptB)
8071 edge2 = vecFromAToB(ptA, ptC)
8072 EPSILON = 0.0000001
8073 hh = vecCrossProduct(inRayDirection, edge2)
8074 aa = vecDotProduct(edge1, hh)
8075 if (aa > -EPSILON) and (aa < EPSILON):
8076 return False
8077 ff = 1.0/aa
8078 ss = vecFromAToB(ptA, inRayStart)
8079 uu = vecDotProduct(ss, hh)
8080 uu *= ff
8081 if (uu < 0.0) or (uu > 1.0):
8082 return False;
8083 qq = vecCrossProduct(ss, edge1)
8084 vv = vecDotProduct(inRayDirection, qq)
8085 vv *= ff
8086 if (vv < 0.0) or (uu + vv > 1.0):
8087 return False;
8088 #At this stage we can compute t to find out where the intersection point
8089 #is on the line.
8090 tt = vecDotProduct(edge2, qq)
8091 tt *= ff
8092 if (tt > EPSILON):
8093 #ray intersection
8094 outPt[0] = inRayStart[0] + inRayDirection[0] * tt
8095 outPt[1] = inRayStart[1] + inRayDirection[1] * tt
8096 outPt[2] = inRayStart[2] + inRayDirection[2] * tt
8097 outPt[3] = tt
8098 return True
8099 else:
8100 #This means that there is a line intersection but not a ray intersection
8101 return False
8102
8103 def CreateBspTree(self):
8104 if PhactoriDbg():
8105 myDebugPrint3("CreateBspTree entered, creating\n")
8106
8107 if self.BspTree != None:
8108 #clear/delete bsp tree to avoid memory leak; may be unnecessary
8109 if PhactoriDbg():
8110 myDebugPrint3("clearing old bsp tree\n")
8111 self.BspTree.FreeSearchStructure()
8112 #?Delete(self.BspTree)
8113 self.BspTree = None
8114
8115 self.BspTreePolyData = vtk.vtkPolyData()
8116
8117 tmpPoints = vtk.vtkPoints()
8118 ptxyz = self.PointXyzs
8119 numvls = ptxyz.GetNumberOfValues()
8120 for ii in range(0, numvls, 3):
8121 tmpPoints.InsertNextPoint(ptxyz.GetValue(ii), ptxyz.GetValue(ii+1),
8122 ptxyz.GetValue(ii+2))
8123
8124 tmpTriangles = vtk.vtkCellArray()
8125 tris = self.Triangles
8126 numtripts = tris.GetNumberOfValues()
8127 for ii in range(0, numtripts, 3):
8128 newtri = vtk.vtkTriangle()
8129 newtri.GetPointIds().SetId(0, tris.GetValue(ii))
8130 newtri.GetPointIds().SetId(1, tris.GetValue(ii+1))
8131 newtri.GetPointIds().SetId(2, tris.GetValue(ii+2))
8132 tmpTriangles.InsertNextCell(newtri)
8133
8134 self.BspTreePolyData.SetPoints(tmpPoints)
8135 self.BspTreePolyData.SetPolys(tmpTriangles)
8136 self.BspTree = vtk.vtkFiltersFlowPaths.vtkModifiedBSPTree()
8137 self.BspTree.SetDataSet(self.BspTreePolyData);
8138 self.BspTree.BuildLocator();
8139 if PhactoriDbg():
8140 myDebugPrint3("dir for self.BspTree:\n")
8141 myDebugPrint3(str(dir(self.BspTree)) + "\n")
8142 myDebugPrint3("str(self.BspTree):\n")
8143 myDebugPrint3(str(self.BspTree) + "\n")
8144 myDebugPrint3("CreateBspTree returning\n")
8145
8146 def IntersectWithNormalRaysFromSourceTriangles(self,
8147 inSourcePhactoriOp, ioRaycastOperation, inSourceSharedTriangles):
8148 if PhactoriDbg():
8149 myDebugPrint3(
8150 "IntersectWithNormalRaysFromSourceTriangles entered\n" \
8151 "target triangle set from pid " + str(self.fromPid) + "\n"\
8152 "source triangle set from pid " + \
8153 str(inSourceSharedTriangles.fromPid) + "\n"\
8154 "target num triangles, num points: " + str(self.numTriangles) + ", " +\
8155 str(self.numPoints) + "\n" + \
8156 "target num triangles, num points: " + str(self.numTriangles) + ", " +\
8157 str(self.numPoints) + "\n")
8158
8159 csdata = inSourcePhactoriOp.mParaViewFilter.GetClientSideObject().\
8160 GetOutputDataObject(0)
8161
8162 numSourceCells = csdata.GetNumberOfCells()
8163 if PhactoriDbg():
8164 myDebugPrint3("inSourcePhactoriOp.mParaViewFilter: " + \
8165 str(inSourcePhactoriOp.mParaViewFilter) + "\n")
8166 myDebugPrint3("csdata: " + str(csdata) + "\n")
8167 myDebugPrint3("numSourceCells: " + str(numSourceCells) + "\n")
8168
8169 if numSourceCells <= 0:
8170 #nothing here, but maybe need to create empty item
8171 return
8172
8173 cellData = csdata.GetPointData()
8174
8175 nrmls = cellData.GetArray("Normals")
8176 if nrmls == None:
8177 myDebugPrint3AndException("IntersectWithNormalRaysFromSourceTriangles: " \
8178 "no Normals cell data\n")
8179
8180 #pointXyza = [0.0,0.0,0.0]
8181 #pointXyzb = [0.0,0.0,0.0]
8182 #pointXyzc = [0.0,0.0,0.0]
8183 cntrd = [0.0, 0.0, 0.0]
8184 onethird = 1.0/3.0
8185 cellPointIds = vtk.vtkIdList()
8186 for ii in range(0,numSourceCells):
8187 theNormalTuple = nrmls.GetTuple3(ii)
8188 ndx = ii*3
8189 ##csdata.GetPoint(ii, pointXyz)
8190 #ptndxa = inSourceSharedTriangles.Triangles.GetValue(ndx) * 3
8191 #ptndxb = inSourceSharedTriangles.Triangles.GetValue(ndx+1) * 3
8192 #ptndxc = inSourceSharedTriangles.Triangles.GetValue(ndx+2) * 3
8193 #cntrd[0] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa)
8194 #cntrd[0] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb)
8195 #cntrd[0] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc)
8196 #cntrd[0] *= onethird
8197 #cntrd[1] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa+1)
8198 #cntrd[1] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb+1)
8199 #cntrd[1] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc+1)
8200 #cntrd[1] *= onethird
8201 #cntrd[2] = inSourceSharedTriangles.PointXyzs.GetValue(ptndxa+2)
8202 #cntrd[2] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxb+2)
8203 #cntrd[2] += inSourceSharedTriangles.PointXyzs.GetValue(ptndxc+2)
8204 #cntrd[2] *= onethird
8205 csdata.GetCellPoints(ii, cellPointIds)
8206 #numpoints should be 3
8207 numids = cellPointIds.GetNumberOfIds()
8208 if numids != 3:
8209 if numids < 3:
8210 #degenerate ? try just skipping
8211 if PhactoriDbg():
8212 myDebugPrint3AndException(str(ii) + " degenerate 2 point\n")
8213 continue
8214 if True: #for now we consider this fatal error
8215 myDebugPrint3AndException(
8216 "PhactoriIntersectNodeNormalsWithSurface::CreateFromLocalProcess\n"
8217 "encountered non-triangle\n")
8218 continue
8219 ptndxa = cellPointIds.GetId(0)
8220 ptndxb = cellPointIds.GetId(1)
8221 ptndxc = cellPointIds.GetId(2)
8222 #trying to get it to work just use first point on triangle
8223 csdata.GetPoint(ptndxa, cntrd)
8224
8225 if self.UseBSPTreeForRayIntersection:
8226 self.IntersectWithOneRayViaBSPTree(ii, cntrd, theNormalTuple,
8227 ioRaycastOperation, 1, -0.1, 10.0, False)
8228 #ioRaycastOperation, 1, 0.0001, 4.0, False)
8229 else:
8230 self.IntersectWithOneRay(
8231 ii, cntrd, theNormalTuple, ioRaycastOperation, 1)
8232
8233 if PhactoriDbg():
8234 myDebugPrint3("IntersectWithNormalRaysFromSourceTriangles returning\n")
8235
8236 def IntersectWithNormalRaysFromSource(self, inSourcePhactoriOp,
8237 ioRaycastOperation):
8238 if PhactoriDbg():
8239 myDebugPrint3("IntersectWithNormalRaysFromSource entered\n" \
8240 "triangle set from pid " + str(self.fromPid) + "\n"\
8241 "num triangles, num points: " + str(self.numTriangles) + ", " +
8242 str(self.numPoints) + "\n")
8243
8244 csdata = inSourcePhactoriOp.mParaViewFilter.GetClientSideObject().\
8245 GetOutputDataObject(0)
8246
8247 if self.UseBSPTreeForRayIntersection:
8248 self.CreateBspTree()
8249
8250 numSourcePoints = csdata.GetNumberOfPoints()
8251 if PhactoriDbg():
8252 myDebugPrint3("inSourcePhactoriOp.mParaViewFilter: " + str(inSourcePhactoriOp.mParaViewFilter) + "\n")
8253 myDebugPrint3("csdata: " + str(csdata) + "\n")
8254 myDebugPrint3("numSourcePoints: " + str(numSourcePoints) + "\n")
8255
8256 if numSourcePoints <= 0:
8257 #nothing here, but maybe need to create empty item
8258 return
8259
8260 pntData = csdata.GetPointData()
8261
8262 nrmls = pntData.GetArray("Normals")
8263 if nrmls == None:
8264 myDebugPrint3AndException(
8265 "IntersectWithNormalRaysFromSource: no Normals point data\n")
8266
8267 pointXyz = [0.0,0.0,0.0]
8268 #pointXyz = np.array([0.0,0.0,0.0])
8269
8270 for ii in range(0,numSourcePoints):
8271 theNormalTuple = nrmls.GetTuple3(ii)
8272 #theNormalTuple = np.array(nrmls.GetTuple3(ii))
8273 csdata.GetPoint(ii, pointXyz)
8274 if self.UseBSPTreeForRayIntersection:
8275 self.IntersectWithOneRayViaBSPTree(ii, pointXyz, theNormalTuple,
8276 ioRaycastOperation, 0, -0.1, 10.0, False)
8277 #ioRaycastOperation, 0, 0.0001, 4.0, False)
8278 else:
8279 self.IntersectWithOneRay(
8280 ii, pointXyz, theNormalTuple, ioRaycastOperation, 0)
8281
8282 if PhactoriDbg():
8283 myDebugPrint3("IntersectWithNormalRaysFromSource returning\n")
8284
8285
8286 class PhactoriSegmentGroup1Item:
8287 "one segment in PhactoriSegmentGroup1"
8288 def __init__(self):
8289 self.ParaViewLineSource = None
8290 self.Point1 = [0.0, 0.0, 0.0]
8291 self.Point2 = [0.0, 0.0, 0.0]
8292 self.LengthSquared = sys.float_info.max
8293 self.mVtkLine = vtk.vtkLine()
8294
8295 def UpdateVtkLine(self, inIdx, ioVtkPoints):
8296 idx = inIdx*2
8297 self.mVtkLine.GetPointIds().SetId(0,idx)
8298 self.mVtkLine.GetPointIds().SetId(1,idx+1)
8299 ioVtkPoints.SetPoint(idx, self.Point1)
8300 ioVtkPoints.SetPoint(idx+1, self.Point2)
8301
8302 def TestAndSet(self, inLengthSquared, inPt1, inPt2):
8303 if inLengthSquared < self.LengthSquared:
8304 self.LengthSquared = inLengthSquared
8305 vecCopy(self.Point1, inPt1)
8306 vecCopy(self.Point2, inPt2)
8307
8308 class PhactoriSegmentGroup1:
8309 "manage a set of segments for purposes of showing raycast results"
8310 def __init__(self):
8311 self.Segments = []
8312 self.mVtkPoints = vtk.vtkPoints()
8313 self.mVtkPolyData = vtk.vtkPolyData()
8314 self.mVtkCellArray = vtk.vtkCellArray()
8315
8316 def SetupWithNumberOfItems(self, inCount):
8317 #we need to get arrays the right length and delete extra line sources
8318 while len(self.Segments) < inCount:
8319 self.Segments.append(PhactoriSegmentGroup1Item())
8320 while len(self.Segments) > inCount:
8321 pp = self.Segments.pop()
8322 #do we need this?
8323 #Delete(self.mVtkLine)
8324 #or this?
8325 #del self.mVtkLine
8326 exit(-1)
8327
8328 self.mVtkPoints.SetNumberOfPoints(inCount * 2)
8329
8330 for ii in self.Segments:
8331 ii.LengthSquared = sys.float_info.max
8332
8333 def UpdateParaViewSegments(self, inSegmentMinLength):
8334 self.mVtkCellArray.SetNumberOfCells(0)
8335 for idx, ii in enumerate(self.Segments):
8336 if PhactoriDbg():
8337 myDebugPrint3("UpdateParaViewSegments " + str(idx) + "\n")
8338 ii.UpdateVtkLine(idx, self.mVtkPoints)
8339 tstminsqrd = inSegmentMinLength * inSegmentMinLength
8340 if ii.LengthSquared != sys.float_info.max:
8341 if tstminsqrd <= ii.LengthSquared:
8342 self.mVtkCellArray.InsertNextCell(ii.mVtkLine)
8343
8344 self.mVtkPolyData.SetPoints(self.mVtkPoints)
8345 self.mVtkPolyData.SetLines(self.mVtkCellArray)
8346
8347 def TestAndSet(self, inIndex, inLengthSquared, inPt1, inPt2):
8348 self.Segments[inIndex].TestAndSet(inLengthSquared, inPt1, inPt2)
8349
8350 #phactori_combine_to_single_python_file_parent_1
8351 #from Operation.PhactoriVtkDataExportOperation import *
8352 #phactori_combine_to_single_python_file_subpiece_begin_1
8353
8354 class PhactoriVtkDataExportOperation(PhactoriOperationSpecifics):
8355 "passes through it's input to it's output, but also does an\n ExportOperation which is a parallel vtk writer, .vtm or .vtp"
8356 def __init__(self):
8357 PhactoriOperationSpecifics.__init__(self)
8358 self.mOutputFileBasename = "myvtk1"
8359 self.mOutputFileBasedirectory = "CatalystVtkDataOutput"
8360 self.mFilterToWriteDataFrom = None
8361 self.mWriter = None
8362 self.mNumCounterDigits = 4
8363 #should be "vtkmultiblockdataset" or "vtkpolydata" or "vtkunstructureddata"
8364 self.mVtkDataType = "vtkmultiblockdataset"
8365 self.mVtkDataTypeExtention = ".vtm"
8366 self.mDataArtifactLister = None
8367
8368 def SetPhactoriDataArtifactMetaDataControl(self, inDataArtifactLister):
8369 self.mDataArtifactLister = inDataArtifactLister
8370
8371 def ParseOutputFilenameParametersFromJson(self, inJson):
8372 self.mOutputFileBasename = getParameterFromBlock(inJson,
8373 "basename", self.mPhactoriOperationBlockOwner.mName)
8374
8375 self.mOutputFileBasedirectory = getParameterFromBlock(inJson,
8376 "basedirectory", self.mOutputFileBasedirectory)
8377 CreateDirectoryFromProcessZero(self.mOutputFileBasedirectory)
8378
8379 self.mNumCounterDigits = getParameterFromBlock(inJson,
8380 'name digit count', self.mNumCounterDigits)
8381
8382 def ParseParametersFromJson(self, inJson):
8383 self.ParseOutputFilenameParametersFromJson(inJson)
8384
8385 param1 = getParameterFromBlock(inJson,
8386 "vtkdatatype", self.mVtkDataType)
8387 self.mVtkDataType = param1.lower()
8388 if self.mVtkDataType == "vtkmultiblockdataset":
8389 if PhactoriDbg(100):
8390 myDebugPrint3("self.mVtkDataType set to vtkmultiblockdataset\n")
8391 self.mVtkDataTypeExtention = ".vtm"
8392 elif self.mVtkDataType == "vtkpolydata":
8393 if PhactoriDbg(100):
8394 myDebugPrint3("self.mVtkDataType set to vtkpolydata\n")
8395 self.mVtkDataTypeExtention = ".vtp"
8396 elif self.mVtkDataType == "vtkunstructureddata":
8397 if PhactoriDbg(100):
8398 myDebugPrint3("self.mVtkDataType set to vtkunstructureddata\n")
8399 self.mVtkDataTypeExtention = ".vtu"
8400 else:
8401 myDebugPrint3AndException(
8402 "PhactoriVtkDataExportOperation::ParseParametersFromJson\n"
8403 "Error: vtkdatatype must be 'vtkmultiblockdataset' \
8404 or 'vtkpolydata'\n")
8405
8406 def CreateParaViewFilter(self, inInputFilter):
8407 self.mFilterToWriteDataFrom = inInputFilter
8408 return self.mFilterToWriteDataFrom
8409
8410 def CreateVtkMultiBlockDataWriter(self):
8411 mypid = SmartGetLocalProcessId()
8412 numproc = SmartGetNumberOfProcesses()
8413
8414 if PhactoriDbg(100):
8415 myDebugPrint3("numproc " + str(numproc) + " mypid " + str(mypid) + "\n")
8416
8417 self.mWriter = vtk.vtkXMLPMultiBlockDataWriter()
8418 self.mWriter.SetInputData(self.mFilterToWriteDataFrom.GetClientSideObject().GetOutputDataObject(0))
8419 self.mWriter.SetNumberOfPieces(numproc)
8420 self.mWriter.SetStartPiece(mypid)
8421
8422 if PhactoriDbg(100):
8423 myDebugPrint3("self.mWriter: " + str(self.mWriter) + "\n")
8424
8425 def CreateVtkPolyDataWriter(self):
8426 mypid = SmartGetLocalProcessId()
8427
8428 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
8429 globalController = pm.GetGlobalController()
8430 #gLocalProcessId = globalController.GetLocalProcessId()
8431 numproc = globalController.GetNumberOfProcesses()
8432
8433 if PhactoriDbg(100):
8434 myDebugPrint3("numproc " + str(numproc) + " mypid " + str(mypid) + "\n")
8435 self.mWriter = vtk.vtkXMLPPolyDataWriter()
8436 self.mWriter.SetInputData(self.mFilterToWriteDataFrom.GetClientSideObject().GetOutputDataObject(0))
8437 self.mWriter.SetNumberOfPieces(numproc)
8438 self.mWriter.SetStartPiece(mypid)
8439 self.mWriter.SetEndPiece(mypid)
8440 self.mWriter.SetUseSubdirectory(True)
8441
8442 def CreateVtkUnstructuredDataWriter(self):
8443 mypid = SmartGetLocalProcessId()
8444
8445 #pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
8446 #globalController = pm.GetGlobalController()
8447 #gLocalProcessId = globalController.GetLocalProcessId()
8448 #numproc = globalController.GetNumberOfProcesses()
8449
8450 #if PhactoriDbg(100):
8451 # myDebugPrint3("numproc " + str(numproc) + " mypid " + str(mypid) + "\n")
8452 self.mWriter = vtk.vtkXMLUnstructuredGridWriter()
8453 self.mWriter.SetInputData(self.mFilterToWriteDataFrom.GetClientSideObject().GetOutputDataObject(0))
8454
8455 def CreateCurrentCallbackOutputFilename(self):
8456 ftc = GetFrameTagCounter()
8457 outName = self.mOutputFileBasedirectory + "/" + \
8458 self.mOutputFileBasename + "_" + \
8459 str(ftc).zfill(self.mNumCounterDigits) + \
8460 self.mVtkDataTypeExtention
8461 return outName
8462
8463 def ExportOperationData(self, datadescription):
8464 "overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files"
8465 if PhactoriDbg(100):
8466 myDebugPrint3("PhactoriVtkDataExportOperation." \
8467 "ExportOperationData entered\n", 100)
8468
8469 self.mFilterToWriteDataFrom.UpdatePipeline()
8470
8471 if self.mWriter == None:
8472 if(self.mVtkDataType == "vtkmultiblockdataset"):
8473 self.CreateVtkMultiBlockDataWriter()
8474 elif(self.mVtkDataType == "vtkpolydata"):
8475 self.CreateVtkPolyDataWriter()
8476 elif(self.mVtkDataType == "vtkunstructureddata"):
8477 self.CreateVtkUnstructuredDataWriter()
8478
8479 outfilename = self.CreateCurrentCallbackOutputFilename()
8480 if PhactoriDbg(100):
8481 myDebugPrint3("outfilename: " + str(outfilename) + "\n")
8482 self.mWriter.SetFileName(outfilename)
8483
8484 #if PhactoriDbg(100):
8485 # myDebugPrint3("multiblock info right before self.mWriter.Write (start):\n")
8486 # RecursivelyPrintMultiBlockStats(self.mFilterToWriteDataFrom)
8487 # myDebugPrint3("multiblock info right before self.mWriter.Write (end):\n")
8488 # BarrierLock("barrier lock before self.mWriter.Write")
8489 self.mWriter.Write()
8490
8491 if self.mDataArtifactLister != None:
8492 self.mDataArtifactLister.AddDataExportToDataArtifactOutputList(outfilename)
8493
8494 if PhactoriDbg(100):
8495 myDebugPrint3("PhactoriVtkDataExportOperation." \
8496 "ExportOperationData returning\n", 100)
8497
8498 #phactori_combine_to_single_python_file_subpiece_end_1
8499
8500 #phactori_combine_to_single_python_file_parent_1
8501 #from Operation.PhactoriPartitionedToMultiBlockOperation import *
8502 #phactori_combine_to_single_python_file_subpiece_begin_1
8503 class PhactoriPartitionedToMultiBlockOperation(PhactoriOperationSpecifics):
8504 "manages PartitionedToMultiBlock filter"
8505 def __init__(self):
8506 PhactoriOperationSpecifics.__init__(self)
8507 self.InputFilter = None
8508 self.OutVtkMultiBlockDataSet = None
8509 self.OutputPVTrivialProducer = None
8510
8511 def ParseParametersFromJson(self, inJson):
8512 dummy = 0
8513
8514 def GetNodeType(self, inNode):
8515 if inNode == None:
8516 myDebugPrint3AndException("PhactoriVtkDataExportOperation::GetNodeType\n"
8517 "fix to handle None inNode\n")
8518 icsdClassname = inNode.GetClassName()
8519 if icsdClassname == "vtkMultiBlockDataSet":
8520 nodeType = 0
8521 elif icsdClassname == "vtkExodusIIMultiBlockDataSet":
8522 nodeType = 1
8523 elif icsdClassname == "vtkMultiPieceDataSet":
8524 nodeType = 2
8525 elif icsdClassname == "vtkPartitionedDataSet":
8526 nodeType = 3
8527 elif icsdClassname == "vtkStructuredGrid":
8528 nodeType = 4
8529 elif icsdClassname == "vtkUntructuredGrid":
8530 nodeType = 5
8531 else:
8532 nodeType = 6
8533 return nodeType
8534
8535 def AddItemToMultiblockOrMultiPiece(self, nonLeafType, inCurrentAlteredNode, oneChild, childName):
8536 if nonLeafType == 2:
8537 newChildIndex = inCurrentAlteredNode.GetNumberOfPieces()
8538 inCurrentAlteredNode.SetPiece(newChildIndex, oneChild)
8539 elif nonLeafType == 3:
8540 #newChildIndex = inCurrentAlteredNode.GetNumberOfPartitions()
8541 #inCurrentAlteredNode.SetPartition(newChildIndex, oneChild)
8542 myDebugPrint3AndException(
8543 "PhactoriVtkDataExportOperation::ParseParametersFromJson\n"
8544 "unexpected nonLeafType (vtkPartitionedDataSet) at this place\n")
8545 else:
8546 newChildIndex = inCurrentAlteredNode.GetNumberOfBlocks()
8547 inCurrentAlteredNode.SetBlock(newChildIndex, oneChild)
8548 if childName != None:
8549 newAlteredNodeMetaData = inCurrentAlteredNode.GetMetaData(newChildIndex)
8550 newAlteredNodeMetaData.Set(vtk.vtkCompositeDataSet.NAME(), childName)
8551
8552 def UpdateAlteredVtkMultiBlockDataSetRecurse1(self, inCurrentAlteredNode, inCurrentSourceNode):
8553 #at this point, both inputs are not leafs, and inCurrentSource is not
8554 #VtkPartitionedDataSet
8555 if PhactoriDbg(100):
8556 myDebugPrint3("PhactoriVtkDataExportOperation." \
8557 "UpdateAlteredVtkMultiBlockDataSetRecurse1 entered\n"
8558 "inCurrentAlteredNode type: " + str(inCurrentAlteredNode.GetClassName()) + "\n"
8559 "inCurrentSourceNode type: " + str(inCurrentSourceNode.GetClassName()) + "\n", 100)
8560
8561 nonLeafType = self.GetNodeType(inCurrentSourceNode)
8562 if PhactoriDbg(100):
8563 myDebugPrint3("inCurrentAlteredNode nonLeafType " + str(nonLeafType) + "\n")
8564
8565 if nonLeafType > 3:
8566 myDebugPrint3AndException(
8567 "PhactoriVtkDataExportOperation::UpdateAlteredVtkMultiBlockDataSetRecurse1\n"
8568 "this is a leaf node or unexpected class here.\n"
8569 "GetClassName(): " + str(inCurrentSourceNode.GetClassName()) + "\n")
8570
8571 if nonLeafType == 2:
8572 numChildren = inCurrentSourceNode.GetNumberOfPieces()
8573 elif nonLeafType == 3:
8574 numChildren = inCurrentSourceNode.GetNumberOfPartitions()
8575 else:
8576 numChildren = inCurrentSourceNode.GetNumberOfBlocks()
8577
8578 if PhactoriDbg(100):
8579 myDebugPrint3("nonLeafType: " + str(nonLeafType) + " numChildren: " + str(numChildren) + "\n")
8580
8581 if PhactoriDbg(100):
8582 myDebugPrint3("begin quick children check\n")
8583 for childIndex in range(0, numChildren):
8584 if nonLeafType == 2:
8585 oneChild = inCurrentSourceNode.GetPiece(childIndex)
8586 elif nonLeafType == 3:
8587 oneChild = inCurrentSourceNode.GetPartition(childIndex)
8588 else:
8589 oneChild = inCurrentSourceNode.GetBlock(childIndex)
8590 if oneChild != None:
8591 myDebugPrint3("childIndex " + str(childIndex) + " is " + str(oneChild.GetClassName()) + "\n")
8592 else:
8593 myDebugPrint3("childIndex " + str(childIndex) + " is None\n")
8594 myDebugPrint3("end quick children check\n")
8595
8596 for childIndex in range(0, numChildren):
8597 if PhactoriDbg(100):
8598 myDebugPrint3("doing childIndex: " + str(childIndex) + "\n")
8599
8600 if nonLeafType == 2:
8601 oneChild = inCurrentSourceNode.GetPiece(childIndex)
8602 elif nonLeafType == 3:
8603 oneChild = inCurrentSourceNode.GetPartition(childIndex)
8604 else:
8605 oneChild = inCurrentSourceNode.GetBlock(childIndex)
8606
8607 childMetaData = inCurrentSourceNode.GetMetaData(childIndex)
8608 if childMetaData != None:
8609 childName = childMetaData.Get(vtk.vtkCompositeDataSet.NAME())
8610 else:
8611 childName = None
8612
8613 if oneChild == None:
8614 #for now, just add a None block to match
8615 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, oneChild, childName)
8616 if PhactoriDbg(100):
8617 myDebugPrint3("done childIndex: " + str(childIndex) + " (oneChild was None)\n")
8618 continue
8619
8620 childNodeType = self.GetNodeType(oneChild)
8621
8622 if PhactoriDbg(100):
8623 myDebugPrint3("childIndex " + str(childIndex) + " childNodeType " + str(childNodeType) + " childName " + str(childName) + "\n")
8624 if (childNodeType == 4) or (childNodeType == 5):
8625 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, oneChild, childName)
8626 elif (childNodeType == 0) or (childNodeType == 1):
8627 #newAlteredNode = vtk.VtkMultiBlockDataSet()
8628 #newAlteredNode = oneChild.NewInstance()
8629 #we are just using self.OutVtkMultiBlockDataSet here to get
8630 #access to the desired type of NewInstance regardless if
8631 #childNodeType is 0 or 1
8632 newAlteredNode = self.OutVtkMultiBlockDataSet.NewInstance()
8633 newChildIndex = inCurrentAlteredNode.GetNumberOfBlocks()
8634 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, newAlteredNode, childName)
8635 self.UpdateAlteredVtkMultiBlockDataSetRecurse1(newAlteredNode, oneChild)
8636 elif childNodeType == 2:
8637 #newAlteredNode = vtk.VtkMultiPieceDataSet()
8638 newAlteredNode = oneChild.NewInstance()
8639 newChildIndex = inCurrentAlteredNode.GetNumberOfPieces()
8640 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, newAlteredNode, childName)
8641 self.UpdateAlteredVtkMultiBlockDataSetRecurse1(newAlteredNode, oneChild)
8642 elif childNodeType == 3:
8643 #for now we're making assumption all the partitions under here are leaf grids
8644 numSubChildren = oneChild.GetNumberOfPartitions()
8645 if PhactoriDbg(100):
8646 myDebugPrint3("numSubChildren: " + str(numSubChildren) + "\n")
8647 for subChildIndex in range(0, numSubChildren):
8648 if PhactoriDbg(100):
8649 myDebugPrint3("doing subChildIndex: " + str(subChildIndex) + "\n")
8650 oneSubChild = oneChild.GetPartition(subChildIndex)
8651
8652 if oneSubChild == None:
8653 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, oneSubChild, childName)
8654 if PhactoriDbg(100):
8655 myDebugPrint3("done subChildIndex: " + str(subChildIndex) + " (which was a None subchild)\n")
8656 continue
8657
8658 subChildNodeType = self.GetNodeType(oneSubChild)
8659 if PhactoriDbg(100):
8660 myDebugPrint3("subChildIndex " + str(subChildIndex) + " subChildNodeType " + str(subChildNodeType) + "\n")
8661 if (subChildNodeType == 4) or (subChildNodeType == 5):
8662 if (nonLeafType == 0) or (nonLeafType == 1) or (nonLeafType == 2):
8663 self.AddItemToMultiblockOrMultiPiece(nonLeafType, inCurrentAlteredNode, oneSubChild, childName)
8664 else:
8665 myDebugPrint3AndException(
8666 "PhactoriVtkDataExportOperation::ParseParametersFromJson\n"
8667 "unexpected nonLeafType at this place: " + str(nonLeafType) + "\n")
8668 else:
8669 myDebugPrint3AndException(
8670 "PhactoriVtkDataExportOperation::ParseParametersFromJson\n"
8671 "unexpected subChildNodeType at this place: " + str(subChildNodeType) + "\n")
8672 if PhactoriDbg(100):
8673 myDebugPrint3("done subChildIndex: " + str(subChildIndex) + "\n")
8674 else:
8675 myDebugPrint3AndException(
8676 "PhactoriVtkDataExportOperation::ParseParametersFromJson\n"
8677 "unexpected childNodeType\n")
8678 if PhactoriDbg(100):
8679 myDebugPrint3("done childIndex: " + str(childIndex) + "\n")
8680
8681 if PhactoriDbg(100):
8682 myDebugPrint3("PhactoriVtkDataExportOperation.ExportOperationData returning\n")
8683
8684
8685 def MakeOrUpdateVtkMultiBlockDataSetWithtoutVtkPartitionedDataSets(self, inVtkMultiBlockDataSet):
8686 if self.OutVtkMultiBlockDataSet == None:
8687 self.OutVtkMultiBlockDataSet = inVtkMultiBlockDataSet.NewInstance()
8688 else:
8689 self.OutVtkMultiBlockDataSet.SetNumberOfBlocks(0)
8690 self.UpdateAlteredVtkMultiBlockDataSetRecurse1(self.OutVtkMultiBlockDataSet, inVtkMultiBlockDataSet)
8691
8692 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
8693 outOutgoingPvFilter):
8694 #default behavior is to do nothing on new data
8695 if PhactoriDbg():
8696 myDebugPrint3("PhactoriPartitionedToMultiBlockOperation.DoUpdateDueToChangeInData entered\n")
8697 if self.InputFilter != None:
8698 if PhactoriDbg():
8699 myDebugPrint3("self.InputFilter != None; updating\n")
8700 UpdatePipelineWithCurrentTimeArgument(self.InputFilter)
8701 theVtkMultiBlockDataSetObject = self.InputFilter.GetClientSideObject().GetOutputDataObject(0)
8702 self.MakeOrUpdateVtkMultiBlockDataSetWithtoutVtkPartitionedDataSets(theVtkMultiBlockDataSetObject)
8703 UpdatePipelineWithCurrentTimeArgument(self.OutputPVTrivialProducer)
8704 if PhactoriDbg():
8705 myDebugPrint3("PhactoriPartitionedToMultiBlockOperation.DoUpdateDueToChangeInData returning\n")
8706 return True
8707
8708 def CreateParaViewFilter(self, inInputFilter):
8709 "create the PartitionedToMultiBlock filter for ParaView"
8710 if PhactoriDbg(100):
8711 myDebugPrint3("PhactoriPartitionedToMultiBlockOperation.CreateParaViewFilter "
8712 "entered\n", 100)
8713
8714 savedActiveSource = GetActiveSource()
8715
8716 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
8717
8718 self.InputFilter = inInputFilter
8719 theVtkMultiBlockDataSetObject = self.InputFilter.GetClientSideObject().GetOutputDataObject(0)
8720
8721 self.MakeOrUpdateVtkMultiBlockDataSetWithtoutVtkPartitionedDataSets(theVtkMultiBlockDataSetObject)
8722
8723 #make trivial producer with this block
8724 newParaViewFilter = PVTrivialProducer()
8725 newParaViewFilter.GetClientSideObject().SetOutput(self.OutVtkMultiBlockDataSet)
8726
8727 self.OutputPVTrivialProducer = newParaViewFilter
8728
8729 if PhactoriDbg(100):
8730 myDebugPrint3("PhactoriPartitionedToMultiBlockOperation.CreateParaViewFilter "
8731 "returning\n", 100)
8732
8733 return newParaViewFilter
8734
8735 #phactori_combine_to_single_python_file_subpiece_end_1
8736
8737 #phactori_combine_to_single_python_file_parent_1
8738 #from Operation.PhactoriExodusIIExportOperation import *
8739 #phactori_combine_to_single_python_file_subpiece_begin_1
8740
8741 class PhactoriExodusIIExportOperation(PhactoriOperationSpecifics):
8742 "passes through it's input to it's output, but also does an\n ExportOperation which is an exodusII writer, .exo "
8743 def __init__(self):
8744 PhactoriOperationSpecifics.__init__(self)
8745 self.mOutputFileBasename = "myexo1"
8746 self.mOutputFileBasedirectory = "CatalystExodusIIOutput"
8747 self.mFilterToWriteDataFrom = None
8748 self.mWriter = None
8749 self.mNumCounterDigits = 4
8750 #should be "vtkmultiblockdataset" or "vtkpolydata"
8751 self.mExodusIIType = "vtkmultiblockdataset"
8752 self.mExodusIITypeExtention = ".exo"
8753 #self.mExodusIITypeExtention = ".e-s"
8754
8755 def ParseOutputFilenameParametersFromJson(self, inJson):
8756 self.mOutputFileBasename = getParameterFromBlock(inJson,
8757 "basename", self.mPhactoriOperationBlockOwner.mName)
8758
8759 self.mOutputFileBasedirectory = getParameterFromBlock(inJson,
8760 "basedirectory", self.mOutputFileBasedirectory)
8761 CreateDirectoryFromProcessZero(self.mOutputFileBasedirectory)
8762
8763 self.mNumCounterDigits = getParameterFromBlock(inJson,
8764 'name digit count', self.mNumCounterDigits)
8765
8766 def ParseParametersFromJson(self, inJson):
8767 self.ParseOutputFilenameParametersFromJson(inJson)
8768
8769 def CreateParaViewFilter(self, inInputFilter):
8770 self.mFilterToWriteDataFrom = inInputFilter
8771 return self.mFilterToWriteDataFrom
8772
8773 def CreateCurrentCallbackOutputFilename(self):
8774 ftc = GetFrameTagCounter()
8775 outName = self.mOutputFileBasedirectory + "/" + \
8776 self.mOutputFileBasename + "_" + \
8777 str(ftc).zfill(self.mNumCounterDigits) + \
8778 self.mExodusIITypeExtention
8779 return outName
8780
8781 def ExportOperationData(self, datadescription):
8782 "overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files"
8783 if PhactoriDbg(100):
8784 myDebugPrint3("PhactoriExodusIIExportOperation." \
8785 "ExportOperationData entered\n", 100)
8786
8787 self.mFilterToWriteDataFrom.UpdatePipeline()
8788
8789 #outfilename = "MySlice5." + str(GetFrameTagCounter()) + ".e-s"
8790 outfilename = self.CreateCurrentCallbackOutputFilename()
8791 if PhactoriDbg(100):
8792 myDebugPrint3("outfilename: " + str(outfilename) + "\n")
8793 if self.mWriter == None:
8794 self.mWriter = ExodusIIWriter(Input=self.mFilterToWriteDataFrom, IgnoreMetaDataWarning=True, FileName=outfilename)
8795 #exodusIIWriter1 = servermanager.writers.ExodusIIWriter(Input=slice1)
8796 #coprocessor.RegisterWriter(exodusIIWriter1, filename='Slice1.e-s', freq=1, paddingamount=0, DataMode='None', HeaderType='None', EncodeAppendedData=None, CompressorType='None', CompressionLevel='None')
8797 else:
8798 self.mWriter.FileName = outfilename
8799
8800
8801 ##self.mWriter.UpdatePipeline()
8802 UpdatePipelineWithCurrentTimeArgument(self.mWriter)
8803
8804 if PhactoriDbg(100):
8805 myDebugPrint3("PhactoriExodusIIExportOperation." \
8806 "ExportOperationData returning\n", 100)
8807
8808 #phactori_combine_to_single_python_file_subpiece_end_1
8809
8810 #phactori_combine_to_single_python_file_parent_1
8811 #from Operation.PhactoriCSVExportOperation import *
8812 #phactori_combine_to_single_python_file_subpiece_begin_1
8813
8814 class PhactoriCSVExportOperation(PhactoriOperationSpecifics):
8815 "passes through it's input to it's output, but also does an\n ExportOperation which is an csv writer, .exo "
8816 def __init__(self):
8817 PhactoriOperationSpecifics.__init__(self)
8818 self.mOutputFileBasename = "myexo1"
8819 self.mOutputFileBasedirectory = "CatalystCSVOutput"
8820 self.mFilterToWriteDataFrom = None
8821 self.mCsvCellWriter = None
8822 self.mCsvPointWriter = None
8823 self.mNumCounterDigits = 4
8824 self.mCSVTypeExtention = ".csv"
8825 self.Precision = 9
8826
8827 def ParseOutputFilenameParametersFromJson(self, inJson):
8828 self.mOutputFileBasename = getParameterFromBlock(inJson,
8829 "basename", self.mPhactoriOperationBlockOwner.mName)
8830
8831 self.mOutputFileBasedirectory = getParameterFromBlock(inJson,
8832 "basedirectory", self.mOutputFileBasedirectory)
8833 CreateDirectoryFromProcessZero(self.mOutputFileBasedirectory)
8834
8835 self.mNumCounterDigits = getParameterFromBlock(inJson,
8836 "name digit count", self.mNumCounterDigits)
8837
8838 self.Precision = getParameterFromBlock(inJson,
8839 "precision", self.Precision)
8840 if (self.Precision < 1) or (self.Precision > 100):
8841 myDebugPrint3AndException("PhactoriCSVExportOperation:\n"
8842 "precision must be 1-100, not " + str(self.Precision) + "\n")
8843
8844
8845 def ParseParametersFromJson(self, inJson):
8846 self.ParseOutputFilenameParametersFromJson(inJson)
8847
8848 def CreateParaViewFilter(self, inInputFilter):
8849 self.mFilterToWriteDataFrom = inInputFilter
8850 return self.mFilterToWriteDataFrom
8851
8852 def CreateCurrentCallbackOutputFilename(self):
8853 ftc = GetFrameTagCounter()
8854 outName_cell = self.mOutputFileBasedirectory + "/" + \
8855 self.mOutputFileBasename + "_cell_" + \
8856 str(ftc).zfill(self.mNumCounterDigits) + \
8857 self.mCSVTypeExtention
8858 outName_point = self.mOutputFileBasedirectory + "/" + \
8859 self.mOutputFileBasename + "_point_" + \
8860 str(ftc).zfill(self.mNumCounterDigits) + \
8861 self.mCSVTypeExtention
8862 return (outName_cell, outName_point)
8863
8864 def ExportOperationData(self, datadescription):
8865 "overrides parent class method in order to output .vtm or .vtp\n (vtkMultiBlockData or vtkPolyData) files"
8866 if PhactoriDbg(100):
8867 myDebugPrint3("PhactoriCSVExportOperation." \
8868 "ExportOperationData entered\n", 100)
8869
8870 self.mFilterToWriteDataFrom.UpdatePipeline()
8871
8872 outfilenames = self.CreateCurrentCallbackOutputFilename()
8873 if PhactoriDbg(100):
8874 myDebugPrint3("outfilenames: " + str(outfilenames) + "\n")
8875
8876 if self.mCsvCellWriter == None:
8877 self.mCsvCellWriter = CSVWriter(Input=self.mFilterToWriteDataFrom,
8878 Precision=self.Precision, FieldAssociation="Cell Data")
8879 if self.mCsvPointWriter == None:
8880 self.mCsvPointWriter = CSVWriter(Input=self.mFilterToWriteDataFrom,
8881 Precision=self.Precision, FieldAssociation="Point Data")
8882
8883 if self.mCsvCellWriter != None:
8884 self.mCsvCellWriter.FileName = outfilenames[0]
8885 UpdatePipelineWithCurrentTimeArgument(self.mCsvCellWriter)
8886 if self.mCsvPointWriter != None:
8887 self.mCsvPointWriter.FileName = outfilenames[1]
8888 UpdatePipelineWithCurrentTimeArgument(self.mCsvPointWriter)
8889
8890 if PhactoriDbg(100):
8891 myDebugPrint3("PhactoriCSVExportOperation." \
8892 "ExportOperationData returning\n", 100)
8893
8894 #phactori_combine_to_single_python_file_subpiece_end_1
8895
8896 class PhactoriIntersectNodeNormalsWithSurface(PhactoriOperationSpecifics):
8897 "takes each node ND from surface SS and its corresponding normal vector\n NN, and casts a ray RR towards the second surface TT which must be a set\n of triangles and finds if and where RR intersects TT at point XX. For\n now it creates a new nodal variable NormalRayDistance which is the\n length of RR between ND and XX. We may add capability in the future\n to store the XX as well, although this can be presumably be recovered\n from the normal and the distance"
8898
8899 def __init__(self):
8900 PhactoriOperationSpecifics.__init__(self)
8901 #filled in from parsing
8902 self.mSourceOperationName = None
8903 self.mTargetOperationName = None
8904
8905 #filled in by finding operation id'd by self.mSourceOperationName
8906 self.mSourceOperation = None
8907
8908 #filled in by finding operation id'd by self.mTargetOperationName
8909 self.mTargetOperation = None
8910
8911 self.mCalculationFrameTag = -1
8912
8913 self.mLocalTriangleSet = SharedTriangleSet()
8914 self.mReceiveTriangleSet = SharedTriangleSet()
8915
8916 self.mPointRayLineSource = None
8917 self.mTriangleRayLineSource = None
8918 self.mGroupLineSource = None
8919
8920 self.mCreateIntersectionSegmentGroup = False
8921 self.mIntersectionSegmentGroupMinLength = 0.0
8922 self.mPointNormalRayIntersectDistanceArray = None
8923 self.mCellNormalRayIntersectDistanceArray = None
8924
8925 self.SegmentsFromPointRays = PhactoriSegmentGroup1()
8926 self.SegmentsFromTriangleRays = PhactoriSegmentGroup1()
8927
8928 def ParseParametersFromJson(self, inJson):
8929 if "target operation" in inJson:
8930 self.mTargetOperationName = inJson["target operation"]
8931 elif "target_operation" in inJson:
8932 self.mTargetOperationName = inJson["target_operation"]
8933 else:
8934 myDebugPrint3AndException(
8935 "PhactoriIntersectNodeNormalsWithSurface::ParseParametersFromJson\n"
8936 "Error: must have 'target operation' or 'target_operation' token\n")
8937 if "input" in inJson:
8938 self.mSourceOperationName = inJson["input"]
8939 else:
8940 #will use default input for source
8941 self.mSourceOperationName = None
8942
8943 if "create intersection segment group" in inJson:
8944 self.mCreateIntersectionSegmentGroup = \
8945 inJson["create intersection segment group"]
8946 elif "create_intersection_segment_group" in inJson:
8947 self.mCreateIntersectionSegmentGroup = \
8948 inJson["create_intersection_segment_group"]
8949
8950 isgmlkey1 = "intersection segment group minimum length"
8951 isgmlkey2 = "intersection_segment_group_minimum_length"
8952 if isgmlkey1 in inJson:
8953 self.mIntersectionSegmentGroupMinLength = inJson[isgmlkey1]
8954 elif isgmlkey2 in inJson:
8955 self.mIntersectionSegmentGroupMinLength = inJson[isgmlkey2]
8956
8957 def CreateParaViewFilter(self, inInputFilter):
8958 "create the filter for ParaView"
8959 if PhactoriDbg(100):
8960 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
8961 "CreateParaViewFilter entered\n", 100)
8962 #info in block class should already be parsed and checked
8963
8964 savedActiveSource = GetActiveSource()
8965
8966 if self.mCreateIntersectionSegmentGroup == True:
8967
8968 self.mPointRayLineSource = PVTrivialProducer()
8969 self.mPointRayLineSource.GetClientSideObject().SetOutput(
8970 self.SegmentsFromPointRays.mVtkPolyData)
8971 self.mTriangleRayLineSource = PVTrivialProducer()
8972 self.mTriangleRayLineSource.GetClientSideObject().SetOutput(
8973 self.SegmentsFromTriangleRays.mVtkPolyData)
8974
8975 #newParaViewFilter = GroupDatasets(Input = [])
8976 #self.mGroupLineSource = newParaViewFilter
8977
8978 self.mGroupLineSource = GroupDatasets(
8979 Input = [self.mPointRayLineSource, self.mTriangleRayLineSource])
8980 self.mTubeFilter = Tube(Input = self.mGroupLineSource)
8981 #self.mTubeFilter.NumberofSides = 8
8982 self.mTubeFilter.Radius = 0.01
8983 #self.mTubeFilter.VaryRadius = 'By Scalar'
8984 newParaViewFilter = self.mTubeFilter
8985
8986 else:
8987 newParaViewFilter = PVTrivialProducer()
8988 passthru = inInputFilter.GetClientSideObject().GetOutputDataObject(0)
8989
8990 numpts = passthru.GetNumberOfPoints()
8991
8992 newvar = vtk.vtkDoubleArray()
8993 newvar.SetNumberOfComponents(1)
8994 newvar.SetName("PointNormalRayIntersectDistance")
8995 for ii in range(0, numpts):
8996 newvar.InsertNextValue(float(-1.0))
8997 passthru.GetPointData().AddArray(newvar)
8998 self.mPointNormalRayIntersectDistanceArray = \
8999 passthru.GetPointData().GetArray("PointNormalRayIntersectDistance")
9000
9001 numcells = passthru.GetNumberOfCells()
9002
9003 newvar2 = vtk.vtkDoubleArray()
9004 newvar2.SetNumberOfComponents(1)
9005 newvar2.SetName("CellNormalRayIntersectDistance")
9006 for ii in range(0, numcells):
9007 newvar2.InsertNextValue(float(-1.0))
9008 passthru.GetCellData().AddArray(newvar2)
9009 self.mCellNormalRayIntersectDistanceArray = \
9010 passthru.GetCellData().GetArray("CellNormalRayIntersectDistance")
9011
9012 if PhactoriDbg(100):
9013 numpts = passthru.GetNumberOfPoints()
9014 myDebugPrint3("numpts: " + str(numpts) + "\n")
9015 numptarrays = passthru.GetPointData().GetNumberOfArrays()
9016 myDebugPrint3("numptarrays: " + str(numptarrays) + "\n")
9017 numcells = passthru.GetNumberOfCells()
9018 myDebugPrint3("numcells: " + str(numcells) + "\n")
9019 numcellarrays = passthru.GetCellData().GetNumberOfArrays()
9020 myDebugPrint3("numcellarrays: " + str(numcellarrays) + "\n")
9021
9022 newParaViewFilter.GetClientSideObject().SetOutput(passthru)
9023
9024 SetActiveSource(newParaViewFilter)
9025 SetActiveSource(savedActiveSource)
9026
9027 if PhactoriDbg(100):
9028 myDebugPrint3(str(self.mGroupLineSource))
9029 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
9030 "CreateParaViewFilter returning\n", 100)
9031
9032 return newParaViewFilter
9033
9034 def RunCalculationToCastRays(self, ioPipeAndViewsState):
9035 "our technique is as follows: we loop through the pids of all the\n processes and each broadcasts the set triangles TTPID that pid holds\n from the target source to all the other processes. Then each process\n casts rays from the nodes on the source surface that it holds (along\n the node normals) towards TTPID and finds the intersection if any.\n If a closer intersection is found than the existing one, the closer is\n used. At the end of this loop the distance is known for each node on\n its own process (and if there was no intersection, which can be NAN or\n some arbitrary value).\n Initial implementation doesn't worry about self-intersection, but we\n can add additional features to expect certain number of 0 distance\n hits and ignore those or to remove self node and surrounding tris from\n the list of those to intersect"
9036 if PhactoriDbg(100):
9037 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
9038 "RunCalculationToCastRays entered\n", 100)
9039 import time
9040 tmstrt = time.clock()
9041
9042 if self.mCalculationFrameTag >= ioPipeAndViewsState.mFrameTagCounter:
9043 if PhactoriDbg(100):
9044 myDebugPrint3(\
9045 "self.mCalculationFrameTag indicates we have already run calc\n")
9046 return
9047 self.mCalculationFrameTag = ioPipeAndViewsState.mFrameTagCounter
9048
9049 #get the source and target operations if necessary
9050 if(self.mTargetOperation == None):
9051 self.mTargetOperation = ioPipeAndViewsState.mOperationBlocks[
9052 self.mTargetOperationName]
9053 if(self.mTargetOperation == None):
9054 myDebugPrint3AndException("PhactoriIntersectNodeNormalsWithSurface:" \
9055 "RunCalculationToCastRays\ncouldn't find target " \
9056 "operation named " + str(self.mTargetOperationName) + "\n")
9057 if self.mSourceOperation == None:
9058 if self.mSourceOperationName == None:
9059 self.mSourceOperation = ioPipeAndViewsState.mIncomingDefaultOperation
9060 else:
9061 self.mSourceOperation = ioPipeAndViewsState.mOperationBlocks[
9062 self.mSourceOperationName]
9063 if self.mSourceOperation == None:
9064 myDebugPrint3AndException("PhactoriIntersectNodeNormalsWithSurface:" \
9065 "RunCalculationToCastRays\ncouldn't find source " \
9066 "operation named " + str(self.mSourceOperationName) + "\n")
9067
9068 #first figure out the set of triangles from the target surface are on the
9069 #local process
9070 self.mLocalTriangleSet.CreateFromLocalProcess(self.mTargetOperation)
9071
9072 #next figure out the set of nodes from the source surface are on the local
9073 #process
9074
9075 #set up to hold the results
9076
9077 #set up for line segments, if we are doing them
9078 if self.mCreateIntersectionSegmentGroup:
9079 csdata = self.mSourceOperation.mParaViewFilter.GetClientSideObject().\
9080 GetOutputDataObject(0)
9081 numSourcePoints = csdata.GetNumberOfPoints()
9082 self.SegmentsFromPointRays.SetupWithNumberOfItems(numSourcePoints)
9083 #self.SegmentsFromTriangleRays.SetupWithNumberOfItems(
9084 # self.mLocalTriangleSet.numTriangles)
9085
9086 #now loop through all processes; one process at a time share the triangles
9087 #from each process to the others and intersect with the local surface
9088 #portion
9089
9090 mypid = SmartGetLocalProcessId()
9091
9092 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
9093 globalController = pm.GetGlobalController()
9094 #gLocalProcessId = globalController.GetLocalProcessId()
9095 numproc = globalController.GetNumberOfProcesses()
9096 if PhactoriDbg(100):
9097 myDebugPrint3(
9098 "mypid: " + str(mypid) + " numproc: " + str(numproc) + "\n")
9099
9100 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
9101 globalController = pm.GetGlobalController()
9102 for ii in range(0,numproc):
9103 if ii == mypid:
9104 self.mLocalTriangleSet.SendBroadcast(ii, globalController)
9105 #self.mLocalTriangleSet.IntersectWithNormalRaysFromSourceTriangles(
9106 # self.mSourceOperation, self, self.mLocalTriangleSet)
9107 self.mLocalTriangleSet.IntersectWithNormalRaysFromSource(
9108 self.mSourceOperation, self)
9109 else:
9110 self.mReceiveTriangleSet.ReceiveBroadcast(ii, globalController)
9111 #self.mReceiveTriangleSet.IntersectWithNormalRaysFromSourceTriangles(
9112 # self.mSourceOperation, self, self.mLocalTriangleSet)
9113 self.mReceiveTriangleSet.IntersectWithNormalRaysFromSource(
9114 self.mSourceOperation, self)
9115
9116 tmend = time.clock()
9117
9118 if PhactoriDbg(100):
9119 myDebugPrint3("time for RunCalculationToCastRays: " + \
9120 str(tmend - tmstrt) + "\n")
9121 else:
9122 print("time for RunCalculationToCastRays raycasting: " + str(tmend - tmstrt))
9123
9124 #create/handle line segments, if we are doing them
9125 if self.mCreateIntersectionSegmentGroup:
9126 self.SegmentsFromPointRays.UpdateParaViewSegments(
9127 self.mIntersectionSegmentGroupMinLength)
9128 #self.SegmentsFromTriangleRays.UpdateParaViewSegments()
9129
9130 tmend2 = time.clock()
9131 if PhactoriDbg(100):
9132 myDebugPrint3(
9133 "time for RunCalculationToCastRays line segment making: " + \
9134 str(tmend2 - tmend) + "\n")
9135
9136 if PhactoriDbg(100):
9137 myDebugPrint3("PhactoriIntersectNodeNormalsWithSurface." \
9138 "RunCalculationToCastRays returning\n", 100)
9139
9140 def ExportOperationData(self, datadescription):
9141 "this will be called once per callback (before WriteImages) to allow the\n operation to export any desired data which is not an image. The child\n class should override this method if it wants so do something.\n For PhactoriIntersectNodeNormalsWithSurface we will output information\n about the nearest and furthest intersections"
9142
9143 if PhactoriDbg(100):
9144 myDebugPrint3(
9145 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData "
9146 "entered\n", 100)
9147
9148 UpdatePipelineWithCurrentTimeArgument(
9149 self.mPhactoriOperationBlockOwner.mParaViewFilter)
9150 self.RunCalculationToCastRays(gPipeAndViewsState)
9151 UpdatePipelineWithCurrentTimeArgument(
9152 self.mPhactoriOperationBlockOwner.mParaViewFilter)
9153
9154 if self.mPointNormalRayIntersectDistanceArray == None:
9155 if PhactoriDbg(100):
9156 myDebugPrint3("no data values, returning\n")
9157 return
9158
9159 numpts = self.mPointNormalRayIntersectDistanceArray.GetNumberOfValues()
9160 maxval = -1.0
9161 minval = -1.0
9162 minval2 = -1.0
9163 if numpts > 0:
9164 vv = self.mPointNormalRayIntersectDistanceArray.GetValue(0)
9165 maxval = vv
9166 minval = vv
9167 if vv >= -0.5:
9168 minval2 = vv
9169 for ii in range(1, numpts):
9170 vv = self.mPointNormalRayIntersectDistanceArray.GetValue(ii)
9171 if vv > maxval:
9172 maxval = vv
9173 if vv < minval:
9174 minval = vv
9175 if vv >= -0.5:
9176 if (minval2 < -0.5) or (vv < minval2):
9177 minval2 = vv
9178
9179 fname = "RayIntersectionMinMax_" + \
9180 self.mPhactoriOperationBlockOwner.mName + "_process_" + \
9181 str(SmartGetLocalProcessId()) + ".txt"
9182 try:
9183 ff = open(fname, "a+b")
9184 ff.write("minimum, maximum, nonnegative minimum\n")
9185 ff.write(str(minval) + ", " + str(maxval) + ", " + str(minval2) + "\n")
9186 except:
9187 myDebugPrint3AndException(
9188 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData\n"
9189 "Error writing file: " + str(fname) + "\n")
9190
9191 if PhactoriDbg(100):
9192 myDebugPrint3(
9193 "PhactoriIntersectNodeNormalsWithSurface::ExportOperationData "
9194 "returning\n", 100)
9195 return
9196
9197
9198 class PhactoriNearestPointsOperation(PhactoriOperationSpecifics):
9199 "finds the set of N nearest nodes between a source operation/input and\n a target operation input. Also outputs a table of the set of nodes\n and distances at render time. This operation as currently constructed\n pulls all the target nodes into each processor and thus may cause memory\n issues. It may be advisible to use, e.g. quadrature decimation to\n reduce the number of points in the target and/or source first. We may\n eventually make this a multi-stage operation to first operate on\n a reduced set of points to find a subset of the original sets of points\n to then do an exact comparison on. We may also eventually change to\n operated based on a space partitioning tree to avoid checking every\n point against every point"
9200 def __init__(self):
9201 PhactoriOperationSpecifics.__init__(self)
9202 #filled in from parsing
9203 self.mSourceOperationName = None
9204 self.mTargetOperationName = None
9205
9206 #filled in by finding operation id'd by self.mSourceOperationName
9207 self.mSourceOperation = None
9208
9209 #filled in by finding operation id'd by self.mTargetOperationName
9210 self.mTargetOperation = None
9211
9212 #controls how many points we look for in each process, and then how many
9213 #points out of those we select as nearest
9214 #if self.mNumPointsToFind > self.mNumPointsPerProcess it is possible to
9215 #have incorrect points beyond self.mNumPointsPerProcess when all the
9216 #nearest points happen to reside on one process
9217 self.mNumPointsPerProcess = 5
9218 self.mNumPointsToFind = 5
9219
9220 #class to maintain parallel shared information
9221 self.mClosestNPointsFromEachProcess = None
9222
9223 self.mLineSource = None
9224
9225 self.mCalculationFrameTag = -1
9226
9227 self.mWriteCsvResults = True
9228 self.mCsvFileBasedirectory = gPipeAndViewsState.mDefaultBasedirectory
9229 self.mCsvFileName = None
9230
9231 #if not None, this will be a string which identifies a text annotation
9232 #which the user has to create normally. If said annotation exists, this
9233 #operation will overwrite the text for the annotation with information
9234 #on the nearest point
9235 self.mOutputToTextAnnotationName = None
9236 self.mTextAnnotationOutputTarget = None
9237
9238 self.mTxtAntnFormatString = None
9239 self.mCsvFormatString = None
9240
9241 def ParseParametersFromJson(self, inJson):
9242
9243 self.mTxtAntnFormatString = getParameterFromBlock(inJson,
9244 'text annotation float format string', self.mTxtAntnFormatString)
9245 self.mTxtAntnFormatString = getParameterFromBlock(inJson,
9246 'text_annotation_float_format_string', self.mTxtAntnFormatString)
9247 self.mCsvFormatString = getParameterFromBlock(inJson,
9248 'csv float format string', self.mCsvFormatString)
9249 self.mCsvFormatString = getParameterFromBlock(inJson,
9250 'csv_float_format_string', self.mCsvFormatString)
9251 self.mOutputToTextAnnotationName = getParameterFromBlock(inJson,
9252 'output to text annnotation', self.mOutputToTextAnnotationName)
9253 self.mOutputToTextAnnotationName = getParameterFromBlock(inJson,
9254 'output_to_text_annnotation', self.mOutputToTextAnnotationName)
9255 self.mWriteCsvResults = getParameterFromBlock(inJson,
9256 'write_results_csv_file', self.mWriteCsvResults)
9257 self.mWriteCsvResults = getParameterFromBlock(inJson,
9258 'write results csv file', self.mWriteCsvResults)
9259 self.mCsvFileName = getParameterFromBlock(inJson,
9260 'csv_results_filename', self.mCsvFileName)
9261 self.mCsvFileName = getParameterFromBlock(inJson,
9262 'csv results filename', self.mCsvFileName)
9263 self.mCsvFileBasedirectory = getParameterFromBlock(inJson,
9264 'csv_results_basedirectory', self.mCsvFileBasedirectory)
9265 self.mCsvFileBasedirectory = getParameterFromBlock(inJson,
9266 'csv results basedirectory', self.mCsvFileBasedirectory)
9267 if self.mCsvFileName == None:
9268 #make default name including operation name and datetime, without
9269 #microseconds
9270 import datetime
9271 nn = datetime.datetime.now()
9272 self.mCsvFileName = self.mPhactoriOperationBlockOwner.mName + \
9273 ".nearestpoints." + (nn.isoformat()[0:-7]) + ".csv"
9274 if 'target operation' in inJson:
9275 self.mTargetOperationName = inJson['target operation']
9276 elif 'target_operation' in inJson:
9277 self.mTargetOperationName = inJson['target_operation']
9278 else:
9279 myDebugPrint3AndException(
9280 "PhactoriNearestPointsOperation::ParseParametersFromJson\n"
9281 "Error: must have 'target operation' or 'target_operation' token\n")
9282 if 'input' in inJson:
9283 self.mSourceOperationName = inJson['input']
9284 else:
9285 #will use default input for source
9286 self.mSourceOperationName = None
9287
9288 if 'number of points per process' in inJson:
9289 self.mNumPointsPerProcess = inJson['number of points per process']
9290 elif 'number_of_points_per_process' in inJson:
9291 self.mNumPointsPerProcess = inJson['number_of_points_per_process']
9292 if 'number of points to find' in inJson:
9293 self.mNumPointsToFind = inJson['number of points to find']
9294 #unless user purposely set self.mNumPointsPerProcess different, we want
9295 #self.mNumPointsPerProcess == self.mNumPointsToFind
9296 if 'number of points per process' not in inJson:
9297 self.mNumPointsPerProcess = self.mNumPointsToFind
9298 elif 'number_of_points_to_find' in inJson:
9299 self.mNumPointsToFind = inJson['number_of_points_to_find']
9300 #unless user purposely set self.mNumPointsPerProcess different, we want
9301 #self.mNumPointsPerProcess == self.mNumPointsToFind
9302 if 'number_of_points per_process' not in inJson:
9303 self.mNumPointsPerProcess = self.mNumPointsToFind
9304
9305 def CreateParaViewFilter(self, inInputFilter):
9306 "create the group filter for ParaView"
9307 if PhactoriDbg(100):
9308 myDebugPrint3("PhactoriNearestPointsOperation.CreateParaViewFilter "
9309 "entered\n", 100)
9310 #info in block class should already be parsed and checked
9311
9312 savedActiveSource = GetActiveSource()
9313
9314 #newParaViewFilter = Sphere()
9315 newParaViewFilter = Line()
9316 newParaViewFilter.Point1 = [0.0, 0.0, 0.0]
9317 newParaViewFilter.Point2 = [0.01, 0.01, 0.01]
9318
9319 SetActiveSource(newParaViewFilter)
9320 SetActiveSource(savedActiveSource)
9321
9322 if PhactoriDbg(100):
9323 myDebugPrint3("PhactoriNearestPointsOperation.CreateParaViewFilter "
9324 "returning\n", 100)
9325
9326 self.mLineSource = newParaViewFilter
9327 return newParaViewFilter
9328
9329 def RunCalculationToFindNearestPoints(self, ioPipeAndViewsState):
9330 if PhactoriDbg(100):
9331 myDebugPrint3("PhactoriNearestPointsOperation." \
9332 "RunCalculationToFindNearestPoints entered\n", 100)
9333
9334 if self.mCalculationFrameTag >= ioPipeAndViewsState.mFrameTagCounter:
9335 if PhactoriDbg(100):
9336 myDebugPrint3(\
9337 "self.mCalculationFrameTag indicates we have already run calc\n")
9338 return
9339 self.mCalculationFrameTag = ioPipeAndViewsState.mFrameTagCounter
9340
9341 #get the source and target operations if necessary
9342 if(self.mTargetOperation == None):
9343 self.mTargetOperation = ioPipeAndViewsState.mOperationBlocks[
9344 self.mTargetOperationName]
9345 if(self.mTargetOperation == None):
9346 myDebugPrint3AndException("PhactoriNearestPointsOperation:" \
9347 "RunCalculationToFindNearestPoints\ncouldn't find target " \
9348 "operation named " + str(self.mTargetOperationName) + "\n")
9349 if self.mSourceOperation == None:
9350 if self.mSourceOperationName == None:
9351 self.mSourceOperation = ioPipeAndViewsState.mIncomingDefaultOperation
9352 else:
9353 self.mSourceOperation = ioPipeAndViewsState.mOperationBlocks[
9354 self.mSourceOperationName]
9355 if self.mSourceOperation == None:
9356 myDebugPrint3AndException("PhactoriNearestPointsOperation:" \
9357 "RunCalculationToFindNearestPoints\ncouldn't find source " \
9358 "operation named " + str(self.mSourceOperationName) + "\n")
9359
9360
9361 #get the list of points from the target that reside on this process
9362 nodeIds, pointXyzs = self.mTargetOperation.MakeListOfAllPoints1()
9363
9364 if PhactoriDbg(100):
9365 myDebugPrint3("In this process " + str(SmartGetLocalProcessId()) + \
9366 " the target has " + str(nodeIds.GetNumberOfValues()) + " points\n")
9367 #myDebugPrint3("nodeIds in " + self.mName + \
9368 # " (count " + str(len(nodeIds)) + "):\n" + str(nodeIds) + "\n")
9369 #for jj in range(0, nodeIds.GetNumberOfValues()):
9370 # myDebugPrint3(str(jj) + ": " + str(nodeIds.GetValue(jj)) + "\n")
9371 #myDebugPrint3("points in " + self.mName + ":\n" + str(pointXyzs) + "\n")
9372
9373 #get the list of points from the target on all processes (copied to this process)
9374 allProcTgtNodeIds, allProcTgtXyzs = \
9375 UseMPIToCreateSharedPointList(nodeIds, pointXyzs)
9376
9377 if PhactoriDbg(100):
9378 myDebugPrint3("from all processes the target has " + \
9379 str(allProcTgtNodeIds.GetNumberOfValues()) + " points\n")
9380
9381 #get nearest N points from the source points on this process to all the
9382 #points on the target (which we have from all processes)
9383 nearestset = self.mSourceOperation.FindClosestNPointsToList(
9384 allProcTgtNodeIds, allProcTgtXyzs, self.mNumPointsPerProcess)
9385
9386 if PhactoriDbg(100):
9387 myDebugPrint3("nearest points from local process source points to " \
9388 "all target points:\n")
9389 myDebugPrint3(nearestset.ToStr())
9390
9391 if self.mClosestNPointsFromEachProcess == None:
9392 self.mClosestNPointsFromEachProcess = ClosestNPointsFromEachProcess()
9393
9394 #now share those N points from each process to all processes so for this and
9395 #every other process we have a list of N * numprocesses points which
9396 #represent the closestst N points from each process to the target
9397 self.mClosestNPointsFromEachProcess.\
9398 ParallelSetupFromFindClosestNPointsToList(nearestset)
9399
9400 #now find the closest M points out of that list
9401 self.mClosestNPointsFromEachProcess.FindNClosestPointsNdxInList(
9402 self.mNumPointsToFind)
9403
9404 if PhactoriDbg(100):
9405 myDebugPrint3( self.mClosestNPointsFromEachProcess.\
9406 MakeNClosestPointsNdxInListTableString())
9407
9408 ndx = self.mClosestNPointsFromEachProcess.mClosestNRefs[0][1]
9409 srcndid = self.mClosestNPointsFromEachProcess.mThisProcIds.GetValue(ndx)
9410 tgtndid = self.mClosestNPointsFromEachProcess.mTargetMatchIds.GetValue(ndx)
9411 distsqrd = self.mClosestNPointsFromEachProcess.mDistSqrds.GetValue(ndx)
9412 dist = math.sqrt(distsqrd)
9413 pndx = ndx*3
9414 srcx = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx)
9415 srcy = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx+1)
9416 srcz = self.mClosestNPointsFromEachProcess.mThisProcXyzs.GetValue(pndx+2)
9417 tgtx = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx)
9418 tgty = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx+1)
9419 tgtz = self.mClosestNPointsFromEachProcess.mTargetMatchXyzs.GetValue(pndx+2)
9420
9421 self.mLineSource.Point1 = [srcx, srcy, srcz]
9422 self.mLineSource.Point2 = [tgtx, tgty, tgtz]
9423 self.mLineSource.UpdatePipeline()
9424
9425 self.WriteClosestNPointsToCsvFile(ioPipeAndViewsState)
9426 self.OutputToTextAnnotation(ioPipeAndViewsState)
9427
9428 def OutputToTextAnnotation(self, ioPipeAndViewsState):
9429 if PhactoriDbg():
9430 myDebugPrint3("PhactoriNearestPointsOperation::OutputToTextAnnotation" \
9431 " called\n")
9432 if self.mOutputToTextAnnotationName == None:
9433 return
9434
9435 if self.mTextAnnotationOutputTarget == None:
9436 self.mTextAnnotationOutputTarget = \
9437 ioPipeAndViewsState.mTextAnnotationBlocks[ \
9438 self.mOutputToTextAnnotationName]
9439 if self.mTextAnnotationOutputTarget == None:
9440 if PhactoriDbg():
9441 myDebugPrint3(
9442 "PhactoriNearestPointsOperation::OutputToTextAnnotation\n" \
9443 "could not find PhactoriTextAnnotationBlock named:\n" \
9444 + str(self.mOutputToTextAnnotationName) + "\n")
9445 return
9446
9447 if PhactoriDbg():
9448 myDebugPrint3("found annotation " + \
9449 str(self.mOutputToTextAnnotationName) + "\n")
9450 clstpts = self.mClosestNPointsFromEachProcess
9451 ndx = clstpts.mClosestNRefs[0][1]
9452 srcndid = clstpts.mThisProcIds.GetValue(ndx)
9453 tgtndid = clstpts.mTargetMatchIds.GetValue(ndx)
9454 distsqrd = clstpts.mDistSqrds.GetValue(ndx)
9455 dist = math.sqrt(distsqrd)
9456 pndx = ndx*3
9457 srcx = clstpts.mThisProcXyzs.GetValue(pndx)
9458 srcy = clstpts.mThisProcXyzs.GetValue(pndx+1)
9459 srcz = clstpts.mThisProcXyzs.GetValue(pndx+2)
9460 tgtx = clstpts.mTargetMatchXyzs.GetValue(pndx)
9461 tgty = clstpts.mTargetMatchXyzs.GetValue(pndx+1)
9462 tgtz = clstpts.mTargetMatchXyzs.GetValue(pndx+2)
9463
9464 if self.mTxtAntnFormatString == None:
9465 self.mTextAnnotationOutputTarget.mTextString = \
9466 "nearest: " + str(dist) + "\n" \
9467 "node id 1: " + str(srcndid) + "\n" \
9468 "x1: " + str(srcx) + "\n" \
9469 "y1: " + str(srcy) + "\n" \
9470 "z1: " + str(srcz) + "\n" \
9471 "node id 2: " + str(tgtndid) + "\n" \
9472 "x2: " + str(tgtx) + "\n" \
9473 "y2: " + str(tgty) + "\n" \
9474 "z2: " + str(tgtz)
9475 else:
9476 diststr = self.mTxtAntnFormatString%dist
9477 id1str = str(srcndid)
9478 x1str = self.mTxtAntnFormatString%srcx
9479 y1str = self.mTxtAntnFormatString%srcy
9480 z1str = self.mTxtAntnFormatString%srcz
9481 id2str = str(tgtndid)
9482 x2str = self.mTxtAntnFormatString%tgtx
9483 y2str = self.mTxtAntnFormatString%tgty
9484 z2str = self.mTxtAntnFormatString%tgtz
9485 self.mTextAnnotationOutputTarget.mTextString = \
9486 "nearest: " + diststr + "\n" \
9487 "node id 1: " + id1str + "\n" \
9488 "x1: " + x1str + "\n" \
9489 "y1: " + y1str + "\n" \
9490 "z1: " + z1str + "\n" \
9491 "node id 2: " + id2str + "\n" \
9492 "x2: " + x2str + "\n" \
9493 "y2: " + y2str + "\n" \
9494 "z2: " + z2str
9495
9496 self.mTextAnnotationOutputTarget.mParaViewSource.Text = \
9497 self.mTextAnnotationOutputTarget.mTextString
9498 self.mTextAnnotationOutputTarget.mParaViewSource.UpdatePipeline()
9499
9500 def WriteClosestNPointsToCsvFile(self, ioPipeAndViewsState):
9501 if SmartGetLocalProcessId() != 0:
9502 return
9503 if self.mWriteCsvResults == False:
9504 return
9505
9506 if PhactoriDbg():
9507 myDebugPrint3("WriteClosestNPointsToCsvFile entered and writing\n")
9508
9509 if self.mCsvFileBasedirectory == None:
9510 ffname = self.mCsvFileName
9511 elif self.mCsvFileBasedirectory == "":
9512 ffname = self.mCsvFileName
9513 else:
9514 import os
9515 ffname = self.mCsvFileBasedirectory + os.sep + self.mCsvFileName
9516 try:
9517 cvsff = open(ffname, "a+b")
9518 if self.mCalculationFrameTag == 1:
9519 cvsff.write("call index, simulation time, position, " \
9520 "distance, distance squared, " \
9521 "source node id, source x, source y, source z, " \
9522 "target node id, target x, target y, target z\n")
9523 clstpts = self.mClosestNPointsFromEachProcess
9524 try:
9525 simtime = ioPipeAndViewsState.CurrentDatadescription.GetTime()
9526 except:
9527 simtime = 0.0
9528 for ii in range(self.mNumPointsToFind):
9529 if PhactoriDbg():
9530 myDebugPrint3("doing point\n" + str(ii) + "\n")
9531 ndx = clstpts.mClosestNRefs[ii][1]
9532 srcndid = clstpts.mThisProcIds.GetValue(ndx)
9533 tgtndid = clstpts.mTargetMatchIds.GetValue(ndx)
9534 distsqrd = clstpts.mDistSqrds.GetValue(ndx)
9535 dist = math.sqrt(distsqrd)
9536 pndx = ndx*3
9537 srcx = clstpts.mThisProcXyzs.GetValue(pndx)
9538 srcy = clstpts.mThisProcXyzs.GetValue(pndx+1)
9539 srcz = clstpts.mThisProcXyzs.GetValue(pndx+2)
9540 tgtx = clstpts.mTargetMatchXyzs.GetValue(pndx)
9541 tgty = clstpts.mTargetMatchXyzs.GetValue(pndx+1)
9542 tgtz = clstpts.mTargetMatchXyzs.GetValue(pndx+2)
9543 if self.mCsvFormatString == None:
9544 cvsff.write(
9545 str(self.mCalculationFrameTag) + ", " + \
9546 str(simtime) + ", " + \
9547 str(ii) + ", " + \
9548 str(dist) + ", " + \
9549 str(distsqrd) + ", " + \
9550 str(srcndid) + ", " + \
9551 str(srcx) + ", " + \
9552 str(srcy) + ", " + \
9553 str(srcz) + ", " + \
9554 str(tgtndid) + ", " + \
9555 str(tgtx) + ", " + \
9556 str(tgty) + ", " + \
9557 str(tgtz) + "\n"
9558 )
9559 else:
9560 tagstr = str(self.mCalculationFrameTag)
9561 simtimestr = self.mCsvFormatString%simtime
9562 posstr = str(ii)
9563 diststr = self.mCsvFormatString%dist
9564 distsqrdstr = self.mCsvFormatString%distsqrd
9565 id1str = str(srcndid)
9566 x1str = self.mCsvFormatString%srcx
9567 y1str = self.mCsvFormatString%srcy
9568 z1str = self.mCsvFormatString%srcz
9569 id2str = str(tgtndid)
9570 x2str = self.mCsvFormatString%tgtx
9571 y2str = self.mCsvFormatString%tgty
9572 z2str = self.mCsvFormatString%tgtz
9573 cvsff.write(
9574 tagstr + ", " + \
9575 simtimestr + ", " + \
9576 posstr + ", " + \
9577 diststr + ", " + \
9578 distsqrdstr + ", " + \
9579 id1str + ", " + \
9580 x1str + ", " + \
9581 y1str + ", " + \
9582 z1str + ", " + \
9583 id2str + ", " + \
9584 x2str + ", " + \
9585 y2str + ", " + \
9586 z2str + "\n"
9587 )
9588 cvsff.close()
9589 except:
9590 myDebugPrint3AndException(
9591 "PhactoriNearestPointsOperation::" \
9592 "RunCalculationToFindNearestPoints\n" \
9593 "error opening or writing to .csv file:\n" \
9594 + str(ffname) + "\n")
9595
9596 if PhactoriDbg():
9597 myDebugPrint3("WriteClosestNPointsToCsvFile returning\n")
9598
9599 #phactori_combine_to_single_python_file_parent_1
9600 #from Operation.PhactoriGroupOperation import *
9601 #phactori_combine_to_single_python_file_subpiece_begin_1
9602 class PhactoriGroupOperation(PhactoriOperationSpecifics):
9603 "manages group filter: group the results of two or more operations into\n a single multiblock source"
9604 def __init__(self):
9605 PhactoriOperationSpecifics.__init__(self)
9606 #filled in from parsing
9607 self.mOperationNameList = None
9608 #filled in by finding operations id'd by self.mOperationNameList
9609 self.mOperationList = None
9610
9611 def ParseParametersFromJson(self, inJson):
9612
9613 if 'operation group list' in inJson:
9614 self.mOperationNameList = inJson['operation group list']
9615 else:
9616 myDebugPrint3AndException(
9617 "PhactoriGroupOperation::ParseParametersFromJson\n"
9618 "Error: must have 'operation group list' token\n")
9619
9620 def GetListOfInputOperationNamesForThisOperationType(self):
9621 "the group operation depends on all the operations in\n self.mOperationNameList"
9622 retList = list(self.mOperationNameList)
9623 return retList
9624
9625 def CreateParaViewFilter2(self, ioPipeAndViewsState):
9626 "create the group filter for ParaView"
9627 if PhactoriDbg(100):
9628 myDebugPrint3("PhactoriGroupOperation.CreateParaViewFilter "
9629 "entered\n", 100)
9630 #info in block class should already be parsed and checked
9631
9632 savedActiveSource = GetActiveSource()
9633
9634 #get direct list of operations (not through name list)
9635 #should be valid here
9636 self.mOperationList = []
9637 for ii in self.mOperationNameList:
9638 if ii not in ioPipeAndViewsState.mOperationBlocks:
9639 myDebugPrint3AndException(
9640 "PhactoriGroupOperation::CreateParaViewFilter\n"
9641 "Error: operation '" + str(ii) + "' not available\n")
9642 inputOperationBlock = ioPipeAndViewsState.mOperationBlocks[ii]
9643 if inputOperationBlock.GetPvFilter() == None:
9644 myDebugPrint3AndException(
9645 "PhactoriGroupOperation::CreateParaViewFilter\n"
9646 "Error: operation '" + str(ii) + "' paraview filter not "
9647 "constructed\n")
9648 self.mOperationList.append(inputOperationBlock.GetPvFilter())
9649
9650 newParaViewFilter = GroupDatasets(Input = self.mOperationList)
9651
9652 SetActiveSource(newParaViewFilter)
9653 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
9654 SetActiveSource(savedActiveSource)
9655
9656 if PhactoriDbg(100):
9657 myDebugPrint3("PhactoriGroupOperation.CreateParaViewFilter "
9658 "returning\n", 100)
9659
9660 return newParaViewFilter
9661 #phactori_combine_to_single_python_file_subpiece_end_1
9662
9663 #phactori_combine_to_single_python_file_parent_1
9664 #from Operation.PhactoriGenerateSurfaceNormalsOperation import *
9665 #phactori_combine_to_single_python_file_subpiece_begin_1
9666 class PhactoriGenerateSurfaceNormalsOperation(PhactoriOperationSpecifics):
9667 "manages ExtractSurface filter"
9668 def __init__(self):
9669 PhactoriOperationSpecifics.__init__(self)
9670 self.ComputeCellNormals = True
9671
9672 def ParseParametersFromJson(self, inJson):
9673 if "compute cell normals" in inJson:
9674 self.ComputeCellNormals = inJson["compute cell normals"]
9675 elif "compute_cell_normals" in inJson:
9676 self.ComputeCellNormals = inJson["compute_cell_normals"]
9677
9678 def CreateParaViewFilter(self, inInputFilter):
9679 "create the GenerateSurfaceNormals filter for ParaView"
9680 if PhactoriDbg(100):
9681 myDebugPrint3("PhactoriGenerateSurfaceNormalsOperation.CreateParaViewFilter "
9682 "entered\n", 100)
9683
9684 savedActiveSource = GetActiveSource()
9685
9686 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9687 newParaViewFilter = GenerateSurfaceNormals(inInputFilter)
9688 if self.ComputeCellNormals:
9689 newParaViewFilter.ComputeCellNormals = 1
9690 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
9691
9692 SetActiveSource(newParaViewFilter)
9693 SetActiveSource(savedActiveSource)
9694
9695 if PhactoriDbg(100):
9696 pvsDi = newParaViewFilter.GetDataInformation()
9697 numCells = pvsDi.GetNumberOfCells()
9698 numPoints = pvsDi.GetNumberOfPoints()
9699 myDebugPrint3("numCells, numPoints " + str(numCells) + " " + str(numPoints) + "\n")
9700 myDebugPrint3("newParaViewFilter: " + str(newParaViewFilter) + "\n")
9701
9702
9703 if PhactoriDbg(100):
9704 myDebugPrint3("PhactoriGenerateSurfaceNormalsOperation.CreateParaViewFilter "
9705 "returning\n", 100)
9706
9707 return newParaViewFilter
9708
9709 #phactori_combine_to_single_python_file_subpiece_end_1
9710
9711
9712 #phactori_combine_to_single_python_file_parent_1
9713 #from Operation.PhactoriExtractSurfaceOperation import *
9714 #phactori_combine_to_single_python_file_subpiece_begin_1
9715 class PhactoriExtractSurfaceOperation(PhactoriOperationSpecifics):
9716 "manages ExtractSurface filter"
9717 def __init__(self):
9718 PhactoriOperationSpecifics.__init__(self)
9719
9720 def ParseParametersFromJson(self, inJson):
9721 dummy = 0
9722
9723 def CreateParaViewFilter(self, inInputFilter):
9724 "create the ExtractSurface filter for ParaView"
9725 if PhactoriDbg(100):
9726 myDebugPrint3("PhactoriExtractSurfaceOperation.CreateParaViewFilter "
9727 "entered\n", 100)
9728
9729 savedActiveSource = GetActiveSource()
9730
9731 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9732 newParaViewFilter = ExtractSurface(inInputFilter)
9733
9734 SetActiveSource(newParaViewFilter)
9735 SetActiveSource(savedActiveSource)
9736
9737 if PhactoriDbg(100):
9738 myDebugPrint3("PhactoriExtractSurfaceOperation.CreateParaViewFilter "
9739 "returning\n", 100)
9740
9741 return newParaViewFilter
9742
9743 #phactori_combine_to_single_python_file_subpiece_end_1
9744
9745
9746 #phactori_combine_to_single_python_file_parent_1
9747 #from Operation.PhactoriGhostCellsGeneratorOperation import *
9748 #phactori_combine_to_single_python_file_subpiece_begin_1
9749 class PhactoriGhostCellsGeneratorOperation(PhactoriOperationSpecifics):
9750 "manages GhostCellsGenerator filter"
9751 def __init__(self):
9752 PhactoriOperationSpecifics.__init__(self)
9753
9754 def ParseParametersFromJson(self, inJson):
9755 dummy = 0
9756
9757 def CreateParaViewFilter(self, inInputFilter):
9758 "create the GhostCellsGenerator filter for ParaView"
9759 if PhactoriDbg(100):
9760 myDebugPrint3(
9761 "PhactoriGhostCellsGeneratorOperation.CreateParaViewFilter "
9762 "entered\n", 100)
9763
9764 savedActiveSource = GetActiveSource()
9765
9766 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9767 newParaViewFilter = GhostCellsGenerator(inInputFilter)
9768 #newParaViewFilter = D3(inInputFilter)
9769
9770 SetActiveSource(newParaViewFilter)
9771 SetActiveSource(savedActiveSource)
9772
9773 if PhactoriDbg(100):
9774 myDebugPrint3(
9775 "PhactoriGhostCellsGeneratorOperation.CreateParaViewFilter "
9776 "returning\n", 100)
9777
9778 return newParaViewFilter
9779
9780 #phactori_combine_to_single_python_file_subpiece_end_1
9781
9782
9783 #phactori_combine_to_single_python_file_parent_1
9784 #from Operation.PhactoriMergeBlocksOperation import *
9785 #phactori_combine_to_single_python_file_subpiece_begin_1
9786 class PhactoriMergeBlocksOperation(PhactoriOperationSpecifics):
9787 "merge blocks (MergeBlocks) operation, adapter to the catalyst filter\n\nPhactoriMergeBlocksOperation is the phactori manager for working with the\nParaView/Catalyst MergeBlocks() filter and its parameters, providing\naccess and pipeline/input/output managment via the json, lexx/yacc, or soon\nyaml interface. The user may specify a named input to the filter, with the\nunnamed default being the incoming data mesh.\n\nThe MergeBlocks filter combines all the elements from all blocks of a\nmultiblock dataset into a single block with one set of elemeeents and one set\nof points. The input is, e.g., a vtkMultiBlockDataset, and the output is\nusually an vtkUnstructuredGrid or vtkPoly. Sometimes other filters which are\nfailing will succeed when placed after a MergeBlocks filter.\n\nFor moree information on the MergeBlocks() filter from ParaView, see the\nParaView Documentation.\n\nTo control the MergeBlocks you have a section in the\n'operation blocks' section of the phactori control script which looks like:\n\n::\n\n 'operation blocks':{\n 'mymergeblocks1':{\n 'type':'mergeblocks'\n }\n }\n\nAs with other pipeline operations, you can add an\n'input':'other_op_name' line to place this after another operation in the\npipeline such as a clip or a slice or a contour.\n"
9788
9789 def __init__(self):
9790 PhactoriOperationSpecifics.__init__(self)
9791 self.mergePoints = True
9792 self.mergePartitionsOnly = False
9793
9794 def ParseParametersFromJson(self, inJson):
9795 key1 = "merge points"
9796 if key1 in inJson:
9797 self.mergePoints = inJson[key1]
9798 key1 = "merge partitions only"
9799 if key1 in inJson:
9800 self.mergePartitionsOnly = inJson[key1]
9801 dummy = 0
9802
9803 def CreateParaViewFilter(self, inInputFilter):
9804 "create the MergeBlocks filter for ParaView"
9805 if PhactoriDbg(100):
9806 myDebugPrint3("PhactoriMergeBlocksOperation.CreateParaViewFilter "
9807 "entered\n", 100)
9808
9809 savedActiveSource = GetActiveSource()
9810
9811 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9812 newParaViewFilter = MergeBlocks(inInputFilter)
9813 if self.mergePoints:
9814 newParaViewFilter.MergePoints = 1
9815 else:
9816 newParaViewFilter.MergePoints = 0
9817 if self.mergePartitionsOnly:
9818 newParaViewFilter.MergePartitionsOnly = 1
9819 else:
9820 newParaViewFilter.MergePartitionsOnly = 0
9821
9822 SetActiveSource(newParaViewFilter)
9823 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
9824 SetActiveSource(savedActiveSource)
9825
9826 if PhactoriDbg(100):
9827 myDebugPrint3("PhactoriMergeBlocksOperation.CreateParaViewFilter "
9828 "returning\n", 100)
9829
9830 return newParaViewFilter
9831
9832 #phactori_combine_to_single_python_file_subpiece_end_1
9833
9834
9835 #phactori_combine_to_single_python_file_parent_1
9836 #from Operation.PhactoriSubdivideOperation import *
9837 #phactori_combine_to_single_python_file_subpiece_begin_1
9838 class PhactoriSubdivideOperation(PhactoriOperationSpecifics):
9839 "manages Subdivide filter"
9840 def __init__(self):
9841 PhactoriOperationSpecifics.__init__(self)
9842 self.NumberOfSubdivisions = 1
9843
9844 def ParseParametersFromJson(self, inJson):
9845 if "number of subdivisions" in inJson:
9846 self.NumberOfSubdivisions = inJson["number of subdivisions"]
9847 elif "number_of_subdivisions" in inJson:
9848 self.NumberOfSubdivisions = inJson["number_of_subdivisions"]
9849
9850 def CreateParaViewFilter(self, inInputFilter):
9851 "create the Subdivide filter for ParaView"
9852 if PhactoriDbg(100):
9853 myDebugPrint3("PhactoriSubdivideOperation.CreateParaViewFilter "
9854 "entered\n", 100)
9855
9856 savedActiveSource = GetActiveSource()
9857
9858 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9859 newParaViewFilter = Subdivide(inInputFilter)
9860 if self.NumberOfSubdivisions != 1:
9861 newParaViewFilter.NumberofSubdivisions = self.NumberOfSubdivisions
9862
9863 SetActiveSource(newParaViewFilter)
9864 SetActiveSource(savedActiveSource)
9865
9866 if PhactoriDbg(100):
9867 myDebugPrint3("PhactoriSubdivideOperation.CreateParaViewFilter "
9868 "returning\n", 100)
9869
9870 return newParaViewFilter
9871
9872 #phactori_combine_to_single_python_file_subpiece_end_1
9873
9874
9875 #phactori_combine_to_single_python_file_parent_1
9876 #from Operation.PhactoriAggregateDatasetOperation import *
9877 #phactori_combine_to_single_python_file_subpiece_begin_1
9878 class PhactoriAggregateDatasetOperation(PhactoriOperationSpecifics):
9879 "manages AggregateDataset filter"
9880 def __init__(self):
9881 PhactoriOperationSpecifics.__init__(self)
9882 self.NumberOfTargetProcesses = 1
9883
9884 def ParseParametersFromJson(self, inJson):
9885 if "number of target processes" in inJson:
9886 self.NumberOfTargetProcesses = inJson["number of target processes"]
9887
9888 def CreateParaViewFilter(self, inInputFilter):
9889 "create the AggregateDataset filter for ParaView"
9890 if PhactoriDbg(100):
9891 myDebugPrint3("PhactoriAggregateDatasetOperation.CreateParaViewFilter "
9892 "entered\n", 100)
9893
9894 savedActiveSource = GetActiveSource()
9895
9896 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
9897 newParaViewFilter = AggregateDataset(inInputFilter)
9898 newParaViewFilter.NumberOfTargetProcesses = self.NumberOfTargetProcesses
9899
9900 SetActiveSource(newParaViewFilter)
9901 SetActiveSource(savedActiveSource)
9902
9903 if PhactoriDbg(100):
9904 myDebugPrint3("PhactoriAggregateDatasetOperation.CreateParaViewFilter "
9905 "returning\n", 100)
9906
9907 return newParaViewFilter
9908
9909 #phactori_combine_to_single_python_file_subpiece_end_1
9910
9911 #phactori_combine_to_single_python_file_parent_1
9912 #from Operation.PhactoriCreateSegmentsNormalToCells import *
9913 #phactori_combine_to_single_python_file_subpiece_begin_1
9914
9915 class SegmentCollectionRecursionParameters():
9916 def __init__(self):
9917 self.SegmentLength = 1.0
9918 self.SegmentResolution = 10
9919 self.DirectionReferencePoint = [0.0, 0.0, 0.0]
9920 self.DirectionFlag = -1
9921 self.SegmentCollection = None
9922 self.workingBlockIndex = 0
9923
9924 def Initialize(self, inLen, inRes, inRefPt, inDrctnFlg):
9925 self.SegmentLength = inLen
9926 self.SegmentResolution = inRes
9927 self.DirectionReferencePoint = inRefPt
9928 self.DirectionFlag = inDrctnFlg
9929 self.workingBlockIndex = 0
9930 self.SegmentCollection = []
9931
9932 class PcsntcSegment:
9933 def __init__(self, inBlockIndex, inCellIndex, inSegPtA, inSegDir):
9934 self.blockIndex = inBlockIndex
9935 self.cellIndex = inCellIndex
9936 self.ptA = inSegPtA
9937 self.segDir = inSegDir
9938 self.segmentLength = 1.0
9939 self.ptB = None
9940
9941 class PhactoriCreateSegmentsNormalToCells(PhactoriOperationSpecifics):
9942 "takes a grid with cells and for each cell creates a line segment\n which starts in the middle of the cell and goes 'normal' to the cell.\n Normal is defined by finding the largest face on the cell and using\n that face to define the cell normal"
9943
9944 def __init__(self):
9945 PhactoriOperationSpecifics.__init__(self)
9946 self.SegmentLength = 1.0
9947 self.SegmentResolution = 10
9948 self.DirectionReferencePoint = [0.0, 0.0, 0.0]
9949 self.DirectionFlag = 1
9950 self.RecursionResults = None
9951 self.IncomingPvFilter = None
9952 self.OutgoingGroupFilter = None
9953 self.myVtkPoints = None
9954 self.myVtkCellArray = None
9955 self.myVtkPolyData = None
9956 self.addPerPointCoordinateSystem = True
9957 self.localCrdSysXName = "localcrdsysx"
9958 self.localCrdSysYName = "localcrdsysy"
9959 self.localCrdSysZName = "localcrdsysz"
9960 self.addPerPointSegmentId = True
9961 self.segmentIdArrayName = "segmentid"
9962 self.localAxisXReference = [1.0, 0.0, 0.0]
9963 self.localAxisXReference2 = [0.0, 1.0, 0.0]
9964 self.geometricSamplingMultiplier = 1.0
9965 self.segmentSampleMethod = "linear"
9966
9967 def ParseCheckFor3ValueList(self, itemToCheck, itemKey):
9968 if (type(itemToCheck) is not list) or (len(itemToCheck) != 3):
9969 myDebugPrint3AndException(
9970 "PhactoriCreateSegmentsNormalToCells.ParseParametersFromJson:\n"
9971 "'" + itemKey + "' must be 3 value list\n")
9972
9973 def ParseParametersFromJson(self, inJson):
9974 key1 = "segment length"
9975 if key1 in inJson:
9976 self.SegmentLength = inJson[key1]
9977 if self.SegmentLength <= 0.0:
9978 myDebugPrint3AndException(
9979 "PhactoriCreateSegmentsNormalToCells.ParseParametersFromJson:\n"
9980 "'" + key1 + "' must be > 0.0\n")
9981 key1 = "segment resolution"
9982 if key1 in inJson:
9983 self.SegmentResolution = inJson[key1]
9984 if self.SegmentResolution < 2:
9985 myDebugPrint3AndException(
9986 "PhactoriCreateSegmentsNormalToCells.ParseParametersFromJson:\n"
9987 "'" + key1 + "' must be >= 2\n")
9988 key1 = "segment direction reference point"
9989 if key1 in inJson:
9990 self.DirectionReferencePoint = inJson[key1]
9991 self.ParseCheckFor3ValueList(self.DirectionReferencePoint, key1)
9992 key1 = "segment direction flag"
9993 if key1 in inJson:
9994 self.DirectionFlag = inJson[key1]
9995 key1 = "geometric progression sampling"
9996 if key1 in inJson:
9997 self.segmentSampleMethod = "geometric"
9998 self.geometricSamplingMultiplier = inJson[key1]
9999 if self.geometricSamplingMultiplier <= 0.0:
10000 myDebugPrint3AndException(
10001 "PhactoriCreateSegmentsNormalToCells.ParseParametersFromJson:\n"
10002 "'" + key1 + "' must be > 0.0\n")
10003 key1 = "global x axis"
10004 if key1 in inJson:
10005 self.localAxisXReference = inJson[key1]
10006 self.ParseCheckFor3ValueList(self.localAxisXReference, key1)
10007 self.localAxisXReference = vecNormalize(self.localAxisXReference)
10008 key2 = "global x axis backup"
10009 if key2 in inJson:
10010 self.localAxisXReference2 = inJson[key2]
10011 self.ParseCheckFor3ValueList(self.localAxisXReference2, key2)
10012 self.localAxisXReference2 = vecNormalize(self.localAxisXReference2)
10013 else:
10014 #construct second axis for when segment is parallel to this one
10015 dpxa = abs(vecDotProduct(self.localAxisXReference, [1.0, 0.0, 0.0]))
10016 dpya = abs(vecDotProduct(self.localAxisXReference, [0.0, 1.0, 0.0]))
10017 dpza = abs(vecDotProduct(self.localAxisXReference, [0.0, 0.0, 1.0]))
10018 if (dpxa <= dpya) and (dpxa <= dpza):
10019 self.localAxisXReference2 = [1.0, 0.0, 0.0]
10020 elif (dpya <= dpxa) and (dpya <= dpza):
10021 self.localAxisXReference2 = [0.0, 1.0, 0.0]
10022 else:
10023 self.localAxisXReference2 = [0.0, 0.0, 1.0]
10024 key1 = "add per point coordinate system"
10025 if key1 in inJson:
10026 self.addPerPointCoordinateSystem = inJson[key1]
10027 key1 = "add per point segment id"
10028 if key1 in inJson:
10029 self.addPerPointSegmentId = inJson[key1]
10030
10031 @staticmethod
10032 def CreateSegmentsNormalToCellsInBlock(recursionObject, inInputCsData, inParameters):
10033 if PhactoriDbg(100):
10034 myDebugPrint3("FindCellEdgeAngleMetricsInBlock entered\n")
10035
10036 inParameters.workingBlockIndex += 1
10037
10038 numCells = inInputCsData.GetNumberOfCells()
10039 numPoints = inInputCsData.GetNumberOfPoints()
10040 if PhactoriDbg(100):
10041 myDebugPrint3("numCells: " + str(numCells) + \
10042 " numPoints: " + str(numPoints) + "\n")
10043
10044 for cellIndex in range(0, numCells):
10045 oneCell = inInputCsData.GetCell(cellIndex)
10046 cellFaceNormal = PhactoriFindLargestCellFaceNormal(inInputCsData, oneCell)
10047 cellPtAvg = PhactoriGetAverageOfCellPoints(inInputCsData, oneCell)
10048 if PhactoriDbg(100):
10049 if cellIndex % 1000 == 0:
10050 myDebugPrint3("cellIndex: " + str(cellIndex) + " c: " + \
10051 str(cellPtAvg) + " n: " + str(cellFaceNormal) + "\n")
10052 newSegmentItem = PcsntcSegment(inParameters.workingBlockIndex, cellIndex,
10053 cellPtAvg, cellFaceNormal)
10054 inParameters.SegmentCollection.append(newSegmentItem)
10055
10056 if PhactoriDbg(100):
10057 myDebugPrint3("FindCellEdgeAngleMetricsInBlock returning\n")
10058
10059 def FindSecondPointForSegments(self):
10060 for oneLineInfo in self.RecursionResults.SegmentCollection:
10061 vecFromCellToRef = vecNormalize(vecFromAToB(oneLineInfo.ptA, self.DirectionReferencePoint))
10062 testDotProd = vecDotProduct(oneLineInfo.segDir, vecFromCellToRef)
10063 if testDotProd < 0.0:
10064 if self.DirectionFlag < 0:
10065 vecScaleInPlace(-1.0, oneLineInfo.segDir)
10066 else:
10067 if self.DirectionFlag >= 0:
10068 vecScaleInPlace(-1.0, oneLineInfo.segDir)
10069 oneSegLen = self.SegmentLength
10070 oneLineInfo.segmentLength = oneSegLen
10071 oneLineInfo.ptB = vecMultiplyAdd(oneLineInfo.ptA, oneLineInfo.segDir, oneSegLen)
10072
10073 def AddPerPointSegmentIdIfRequested(self):
10074 if self.addPerPointSegmentId == False:
10075 return
10076 #find most segments out of any processes and use that to construct unique
10077 #for each segment
10078 localNumSegmentsArray = [len(self.RecursionResults.SegmentCollection)]
10079 maxNumSegmentsArray = UseReduceOnIntegerList(localNumSegmentsArray, 0)
10080 maxNumSegmentsOnAnyProcess = maxNumSegmentsArray[0]
10081 totalNumPts = len(self.RecursionResults.SegmentCollection)*self.SegmentResolution
10082 segIdArray = vtk.vtkIntArray()
10083 segIdArray.SetNumberOfComponents(3)
10084 segIdArray.SetNumberOfTuples(totalNumPts)
10085 segIdArray.SetName(self.segmentIdArrayName)
10086 localPid = SmartGetLocalProcessId()
10087 numPid = SmartGetNumberOfProcesses()
10088 ptNdx = 0
10089 segNdx = 0
10090 #using +1 guarantees sequence gap between each process so which segments
10091 #went with which proceses can be reconstructed if necessary
10092 localSegIdCntr = localPid * (maxNumSegmentsOnAnyProcess+1)
10093 idTuple = [localSegIdCntr, segNdx, 0]
10094 for oneLineInfo in self.RecursionResults.SegmentCollection:
10095 thisSegmentPointIndex = 0
10096 for resNdx in range(0,self.SegmentResolution):
10097 idTuple[2] = thisSegmentPointIndex
10098 segIdArray.SetTuple(ptNdx, idTuple)
10099 ptNdx += 1
10100 thisSegmentPointIndex += 1
10101 localSegIdCntr += 1
10102 segNdx += 1
10103 idTuple[0] = localSegIdCntr
10104 idTuple[1] = segNdx
10105 self.myVtkPolyData.GetPointData().AddArray(segIdArray)
10106
10107 def AddPerPointCoordinateSystemIfRequested(self):
10108 if self.addPerPointCoordinateSystem == False:
10109 return
10110 ptNdx = 0
10111 totalNumPts = len(self.RecursionResults.SegmentCollection)*self.SegmentResolution
10112 crdSysXArray = vtk.vtkDoubleArray()
10113 crdSysXArray.SetNumberOfComponents(3)
10114 crdSysXArray.SetNumberOfTuples(totalNumPts)
10115 crdSysXArray.SetName(self.localCrdSysXName)
10116 crdSysYArray = vtk.vtkDoubleArray()
10117 crdSysYArray.SetNumberOfComponents(3)
10118 crdSysYArray.SetNumberOfTuples(totalNumPts)
10119 crdSysYArray.SetName(self.localCrdSysYName)
10120 crdSysZArray = vtk.vtkDoubleArray()
10121 crdSysZArray.SetNumberOfComponents(3)
10122 crdSysZArray.SetNumberOfTuples(totalNumPts)
10123 crdSysZArray.SetName(self.localCrdSysZName)
10124 for oneLineInfo in self.RecursionResults.SegmentCollection:
10125 localYAxis = vecNormalize(oneLineInfo.segDir)
10126 localZAxis = vecCrossProduct(self.localAxisXReference, localYAxis)
10127 zAxisLen = vecMagnitude(localZAxis)
10128 if zAxisLen < 1.0e-20:
10129 localZAxis = vecCrossProduct(self.localAxisXReference2, localYAxis)
10130 vecNormalize2(localZAxis, localZAxis)
10131 localXAxis = vecCrossProduct(localYAxis, localZAxis)
10132 vecNormalize2(localXAxis, localXAxis)
10133 for resNdx in range(0,self.SegmentResolution):
10134 crdSysXArray.SetTuple(ptNdx, localXAxis)
10135 crdSysYArray.SetTuple(ptNdx, localYAxis)
10136 crdSysZArray.SetTuple(ptNdx, localZAxis)
10137 ptNdx += 1
10138 self.myVtkPolyData.GetPointData().AddArray(crdSysXArray)
10139 self.myVtkPolyData.GetPointData().AddArray(crdSysYArray)
10140 self.myVtkPolyData.GetPointData().AddArray(crdSysZArray)
10141
10142 def CalculateGeometricProgressionSampleValues(self, oneLineInfo):
10143 samplePos = [0.0]
10144 samplePt = 0.0
10145 sampleSpacing = self.geometricSamplingMultiplier
10146 for ii in range(0, self.SegmentResolution-1):
10147 samplePt += sampleSpacing
10148 samplePos.append(samplePt)
10149 sampleSpacing *= self.geometricSamplingMultiplier
10150 maxSamplePt = samplePos[-1]
10151 adj1 = oneLineInfo.segmentLength/maxSamplePt
10152 for ii in range(0, self.SegmentResolution-1):
10153 samplePos[ii] *= adj1
10154 samplePos[-1] = oneLineInfo.segmentLength
10155 return samplePos
10156
10157 def CreateSegmentWithChosenSamplingMethod(self, oneLineInfo, ptNdx):
10158 myNewPolyLine = vtk.vtkPolyLine()
10159 myPlyLnIds = myNewPolyLine.GetPointIds()
10160 myPlyLnIds.SetNumberOfIds(self.SegmentResolution)
10161 if self.segmentSampleMethod == "linear" or self.segmentSampleMethod == "geometric":
10162 if self.segmentSampleMethod == "linear":
10163 self.geometricSamplingMultiplier = 1.0
10164 samplePos = self.CalculateGeometricProgressionSampleValues(oneLineInfo)
10165 for resNdx in range(0,self.SegmentResolution):
10166 ratio1 = samplePos[resNdx]
10167 newPtAlongLine = vecMultiplyAdd(oneLineInfo.ptA, oneLineInfo.segDir, ratio1)
10168 self.myVtkPoints.SetPoint(ptNdx, newPtAlongLine)
10169 myPlyLnIds.SetId(resNdx, ptNdx)
10170 ptNdx += 1
10171 else:
10172 myDebugPrint3AndException(
10173 "PhactoriCreateSegmentsNormalToCells.CreateSegmentWithChosenSamplingMethod:\n"
10174 "bad self.segmentSampleMethod: " + str(self.segmentSampleMethod) + "\n")
10175 return myNewPolyLine
10176
10177 def CreateParaViewSourcesForSegments(self):
10178 pvLineList = []
10179 if PhactoriDbg(100):
10180 myDebugPrint3("CreateParaViewSourcesForSegments\n" + \
10181 "self.SegmentLength: " + str(self.SegmentLength) + "\n" + \
10182 "self.SegmentResolution: " + str(self.SegmentResolution) + "\n" + \
10183 "self.DirectionReferencePoint: " + str(self.DirectionReferencePoint) + "\n" + \
10184 "self.DirectionFlag: " + str(self.DirectionFlag) + "\n")
10185
10186 self.myVtkPoints = vtk.vtkPoints()
10187 self.myVtkCellArray = vtk.vtkCellArray()
10188 self.myVtkPolyData = vtk.vtkPolyData()
10189
10190 self.FindSecondPointForSegments()
10191 ptNdx = 0
10192 totalNumPts = len(self.RecursionResults.SegmentCollection)*self.SegmentResolution
10193 self.myVtkPoints.SetNumberOfPoints(totalNumPts)
10194 for oneLineInfo in self.RecursionResults.SegmentCollection:
10195 myNewPolyLine = self.CreateSegmentWithChosenSamplingMethod(oneLineInfo, ptNdx)
10196 ptNdx += self.SegmentResolution
10197 self.myVtkCellArray.InsertNextCell(myNewPolyLine)
10198
10199 self.myVtkPolyData.SetPoints(self.myVtkPoints)
10200 #self.myVtkPolyData.SetVerts(self.myVtkCellArray)
10201 self.myVtkPolyData.SetLines(self.myVtkCellArray)
10202
10203 self.AddPerPointCoordinateSystemIfRequested()
10204 self.AddPerPointSegmentIdIfRequested()
10205
10206 newParaViewFilter = PVTrivialProducer()
10207 newParaViewFilter.GetClientSideObject().SetOutput(self.myVtkPolyData)
10208 return newParaViewFilter
10209
10210 def CreateSegmentsForAllCells(self, inInputFilter):
10211 recursionControlObj = PhactoriParaviewMultiBlockRecursionControl()
10212 self.RecursionResults = SegmentCollectionRecursionParameters()
10213 self.RecursionResults.Initialize(
10214 self.SegmentLength,
10215 self.SegmentResolution,
10216 self.DirectionReferencePoint,
10217 self.DirectionFlag)
10218 recursionControlObj.mParameters = self.RecursionResults
10219 recursionControlObj.mOperationToDoPerBlock = self.CreateSegmentsNormalToCellsInBlock
10220 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionControlObj, inInputFilter)
10221
10222 def CreateParaViewFilter(self, inInputFilter):
10223 if PhactoriDbg(100):
10224 myDebugPrint3("PhactoriCreateSegmentsNormalToCells.CreateParaViewFilter "
10225 "entered\n", 100)
10226
10227 self.IncomingPvFilter = inInputFilter
10228 savedActiveSource = GetActiveSource()
10229
10230 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10231
10232 #go through all cells and create a segment for each one.
10233 #(find the geometry for all segments)
10234 self.CreateSegmentsForAllCells(inInputFilter)
10235
10236 self.OutgoingGroupFilter = self.CreateParaViewSourcesForSegments()
10237 UpdatePipelineWithCurrentTimeArgument(self.OutgoingGroupFilter)
10238
10239 SetActiveSource(self.OutgoingGroupFilter)
10240 SetActiveSource(savedActiveSource)
10241
10242 if PhactoriDbg(100):
10243 myDebugPrint3("PhactoriCreateSegmentsNormalToCells.CreateParaViewFilter "
10244 "returning\n", 100)
10245
10246 return self.OutgoingGroupFilter
10247
10248 #phactori_combine_to_single_python_file_subpiece_end_1
10249
10250 #phactori_combine_to_single_python_file_parent_1
10251 #from Operation.PhactoriVectorProject import *
10252 #phactori_combine_to_single_python_file_subpiece_begin_1
10253 class PhactoriVectorProject(PhactoriOperationSpecifics):
10254 "manages calculator filter"
10255 def __init__(self):
10256 PhactoriOperationSpecifics.__init__(self)
10257 self.projectionList = None
10258 self.pvCalcs = None
10259
10260 def ParseParametersFromJson(self, inJson):
10261 key1 = "project list"
10262 if key1 not in inJson:
10263 myDebugPrint3AndException(
10264 "PhactoriVectorProject::ParseParametersFromJson\n"
10265 "Error: must have key " + key1 + "\n")
10266 self.projectionList = inJson[key1]
10267 if len(self.projectionList) % 3 != 0:
10268 myDebugPrint3AndException(
10269 "PhactoriVectorProject::ParseParametersFromJson\n"
10270 "projection list must have three entries per projection")
10271
10272 def CreateParaViewFilter(self, inInputFilter):
10273 "create the projection calculators for ParaView"
10274 if PhactoriDbg(100):
10275 myDebugPrint3("PhactoriVectorProject.CreateParaViewFilter "
10276 "entered\n", 100)
10277
10278 savedActiveSource = GetActiveSource()
10279
10280 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10281
10282 ndx = 0
10283 testend = len(self.projectionList) - 1
10284 self.pvCalcs = []
10285 nextInput = inInputFilter
10286 while ndx < testend:
10287 vecToProj = self.projectionList[ndx]
10288 vecToProjOnTo = self.projectionList[ndx+1]
10289 targetProjLenName = self.projectionList[ndx+2]
10290 ndx += 3
10291 functionstr = vecToProj + "." + vecToProjOnTo
10292 #functionstr = \
10293 # vecToProj + "_X*" + vecToProjOnTo + "_X+" + \
10294 # vecToProj + "_Y*" + vecToProjOnTo + "_Y+" + \
10295 # vecToProj + "_Z*" + vecToProjOnTo + "_Z"
10296 if PhactoriDbg(100):
10297 myDebugPrint3("ndx " + str(ndx) + "\n"
10298 "vecToProj " + str(vecToProj) + "\n"
10299 "vecToProjOnTo " + str(vecToProjOnTo) + "\n"
10300 "targetProjLenName " + str(targetProjLenName) + "\n"
10301 "functionstr " + str(functionstr) + "\n")
10302 newPvCalc = Calculator(nextInput)
10303 newPvCalc.Function = functionstr
10304 newPvCalc.ResultArrayName = targetProjLenName
10305 #newParaViewFilter.AttributeType = self.mPointOrCell
10306 newPvCalc.AttributeType = "Point Data"
10307 self.pvCalcs.append(newPvCalc)
10308 nextInput = newPvCalc
10309 UpdatePipelineWithCurrentTimeArgument(newPvCalc)
10310
10311 newParaViewFilter = self.pvCalcs[-1]
10312 SetActiveSource(newParaViewFilter)
10313 SetActiveSource(savedActiveSource)
10314
10315 if PhactoriDbg(100):
10316 myDebugPrint3(
10317 "PhactoriTransformOperation.CreateParaViewFilter returning\n", 100)
10318
10319 return newParaViewFilter
10320 #phactori_combine_to_single_python_file_subpiece_end_1
10321
10322 #phactori_combine_to_single_python_file_parent_1
10323 #from Operation.PhactoriGlyphOperation import *
10324 #phactori_combine_to_single_python_file_subpiece_begin_1
10325 class PhactoriGlyphOperation(PhactoriOperationSpecifics):
10326 "manages Glyph filter"
10327 def __init__(self):
10328 PhactoriOperationSpecifics.__init__(self)
10329 self.scaleFactor = None
10330 self.glyphType = "Arrow"
10331 self.ArrowTipResolution = None
10332 self.ArrowTipRadius = None
10333 self.ArrowTipLength = None
10334 self.ArrowShaftResolution = None
10335 self.ArrowShaftRadius = None
10336 self.scaleArray = None
10337 self.orientationArray = None
10338
10339 def ParseParametersFromJson(self, inJson):
10340 if PhactoriDbg(100):
10341 myDebugPrint3("PhactoriGlyphOperation.ParseParametersFromJson "
10342 "entered\n", 100)
10343
10344 key1 = "scale factor"
10345 if key1 in inJson:
10346 self.scaleFactor = inJson[key1]
10347 if self.scaleFactor <= 0.0:
10348 myDebugPrint3AndException(
10349 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10350 key1 + "\n")
10351 exit(-1)
10352
10353 glyphSet = {}
10354 glyphSet["arrow"] = "Arrow"
10355 glyphSet["box"] = "Box"
10356 key1 = "glyph type"
10357 if key1 in inJson:
10358 glyphkey1 = inJson[key1]
10359 if glyphkey1 not in glyphSet:
10360 myDebugPrint3AndException(
10361 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10362 key1 + "\n")
10363 exit(-1)
10364 self.glyphType = glyphSet[glyphkey1]
10365
10366 key1 = "scale array"
10367 if key1 in inJson:
10368 self.scaleArray = inJson[key1]
10369
10370 key1 = "orientation array"
10371 if key1 in inJson:
10372 self.orientationArray = inJson[key1]
10373
10374 if PhactoriDbg(100):
10375 myDebugPrint3("self.scaleArray " + str(self.scaleArray) + "\n")
10376 myDebugPrint3("self.orientationArray " + str(self.orientationArray) + "\n")
10377
10378 if self.glyphType == "Arrow":
10379 key1 = "tip resolution"
10380 if key1 in inJson:
10381 self.ArrowTipResolution = inJson[key1]
10382 if self.ArrowTipResolution <= 0:
10383 myDebugPrint3AndException(
10384 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10385 key1 + "\n")
10386 exit(-1)
10387 key1 = "tip length"
10388 if key1 in inJson:
10389 self.ArrowTipLength = inJson[key1]
10390 if self.ArrowTipLength < 0.0:
10391 myDebugPrint3AndException(
10392 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10393 key1 + "\n")
10394 exit(-1)
10395 key1 = "tip radius"
10396 if key1 in inJson:
10397 self.ArrowTipRadius = inJson[key1]
10398 if self.ArrowTipRadius <= 0.0:
10399 myDebugPrint3AndException(
10400 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10401 key1 + "\n")
10402 exit(-1)
10403 key1 = "shaft resolution"
10404 if key1 in inJson:
10405 self.ArrowShaftResolution = inJson[key1]
10406 if self.ArrowShaftResolution <= 0:
10407 myDebugPrint3AndException(
10408 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10409 key1 + "\n")
10410 exit(-1)
10411 key1 = "shaft radius"
10412 if key1 in inJson:
10413 self.ArrowShaftRadius = inJson[key1]
10414 if self.ArrowShaftRadius <= 0.0:
10415 myDebugPrint3AndException(
10416 "PhactoriGlyphOperation.ParseParametersFromJson:\nbad " + \
10417 key1 + "\n")
10418 exit(-1)
10419
10420 if PhactoriDbg(100):
10421 myDebugPrint3("PhactoriGlyphOperation.ParseParametersFromJson "
10422 "returning\n", 100)
10423
10424 def CreateParaViewFilter(self, inInputFilter):
10425 "create the Glyph filter for ParaView"
10426 if PhactoriDbg(100):
10427 myDebugPrint3("PhactoriGlyphOperation.CreateParaViewFilter "
10428 "entered\n", 100)
10429
10430 savedActiveSource = GetActiveSource()
10431
10432 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10433
10434 if PhactoriDbg(100):
10435 myDebugPrint3("self.glyphType: " + str(self.glyphType) + "\n")
10436
10437 newParaViewFilter = Glyph(Input=inInputFilter, GlyphType=self.glyphType)
10438 #newParaViewFilter.OrientationArray = ['POINTS', 'No orientation array']
10439 #newParaViewFilter.ScaleArray = ['POINTS', 'No scale array']
10440 #newParaViewFilter.ScaleFactor = 0.1753620492294431
10441 newParaViewFilter.GlyphTransform = 'Transform2'
10442 if self.scaleArray != None:
10443 newParaViewFilter.ScaleArray = self.scaleArray
10444 else:
10445 newParaViewFilter.ScaleArray = ['POINTS', 'velocity_xyz']
10446 if self.orientationArray != None:
10447 newParaViewFilter.OrientationArray = self.orientationArray
10448 else:
10449 newParaViewFilter.OrientationArray = ['POINTS', 'velocity_xyz']
10450 if PhactoriDbg(100):
10451 myDebugPrint3("newParaViewFilter.ScaleArray " + str(newParaViewFilter.ScaleArray) + "\n")
10452 myDebugPrint3("newParaViewFilter.OrientationArray " + str(newParaViewFilter.OrientationArray) + "\n")
10453 #newParaViewFilter.ScaleFactor = 1e-05
10454 newParaViewFilter.GlyphMode = 'All Points'
10455 if self.scaleFactor != None:
10456 newParaViewFilter.ScaleFactor = self.scaleFactor
10457 if self.ArrowTipResolution != None:
10458 newParaViewFilter.GlyphType.TipResolution = self.ArrowTipResolution
10459 if self.ArrowShaftResolution != None:
10460 newParaViewFilter.GlyphType.ShaftResolution = self.ArrowShaftResolution
10461 if self.ArrowTipRadius != None:
10462 newParaViewFilter.GlyphType.TipRadius = self.ArrowTipRadius
10463 if self.ArrowShaftRadius != None:
10464 newParaViewFilter.GlyphType.ShaftRadius = self.ArrowShaftRadius
10465 if self.ArrowTipLength != None:
10466 newParaViewFilter.GlyphType.TipLength = self.ArrowTipLength
10467
10468 # init the 'Arrow' selected for 'GlyphType'
10469 #newParaViewFilter.GlyphType.TipResolution = 6
10470 #newParaViewFilter.GlyphType.TipRadius = 0.05
10471 #newParaViewFilter.GlyphType.TipLength = 0.3
10472 #newParaViewFilter.GlyphType.ShaftResolution = 6
10473 #newParaViewFilter.GlyphType.ShaftRadius = 0.05
10474
10475 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10476 SetActiveSource(newParaViewFilter)
10477 SetActiveSource(savedActiveSource)
10478
10479 if PhactoriDbg(100):
10480 myDebugPrint3("PhactoriGlyphOperation.CreateParaViewFilter "
10481 "returning\n", 100)
10482
10483 return newParaViewFilter
10484
10485 #phactori_combine_to_single_python_file_subpiece_end_1
10486
10487 #phactori_combine_to_single_python_file_parent_1
10488 #from Operation.PhactoriTriangulateOperation import *
10489 #phactori_combine_to_single_python_file_subpiece_begin_1
10490 class PhactoriTriangulateOperation(PhactoriOperationSpecifics):
10491 "manages Triangulate filter"
10492 def __init__(self):
10493 PhactoriOperationSpecifics.__init__(self)
10494
10495 def ParseParametersFromJson(self, inJson):
10496 dummy = 0
10497
10498 def CreateParaViewFilter(self, inInputFilter):
10499 "create the Triangulate filter for ParaView"
10500 if PhactoriDbg(100):
10501 myDebugPrint3("PhactoriTriangulateOperation.CreateParaViewFilter "
10502 "entered\n", 100)
10503
10504 savedActiveSource = GetActiveSource()
10505
10506 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10507 newParaViewFilter = Triangulate(inInputFilter)
10508
10509 SetActiveSource(newParaViewFilter)
10510 SetActiveSource(savedActiveSource)
10511
10512 if PhactoriDbg(100):
10513 myDebugPrint3("PhactoriTriangulateOperation.CreateParaViewFilter "
10514 "returning\n", 100)
10515
10516 return newParaViewFilter
10517
10518 #phactori_combine_to_single_python_file_subpiece_end_1
10519
10520
10521 #phactori_combine_to_single_python_file_parent_1
10522 #from Operation.PhactoriExtractBlockOperation import *
10523 #phactori_combine_to_single_python_file_subpiece_begin_1
10524 global gDuplicateNameCounter
10525 gDuplicateNameCounter = {}
10526
10527 class PhactoriExtractBlockOperation(PhactoriOperationSpecifics):
10528 "Extract Block operation, phactori interface adapter to the catalyst filter\nFor detailed information on the ExtractBlock() filter from ParaView, see the\nParaView Documentation. The basic operation of this filter is to take a list\nof block names and create a new mesh which includes only the blocks in the\nwhich have the names in the given list (and their children). Alternatively\nthe list can contain blocks to be excluded instead of included. The current\nParaView (5.8) implementation of this filter takes a list of block indices\nwhich can become inaccurate if the mesh structure is unexpected, so this\nPhactori adapter uses the block names to create the block index list at\nrun time rather than at script creation time.\n\nTo add a PhactoriExtractBlock to the incoming script, you add\na sub-block to the 'operation blocks' section of the data with the 'type'\nkey given a value of 'extractblock'. You also supply a list of block names\nwith a key of either 'include blocks' or 'exclude blocks'. One complete but\nsimple example script:\n\n::\n\n {\n 'camera blocks':{'mycam1':{'type':'camera', 'look direction':[1.0, 2.0, 3.0]}},\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_on_slice_1':{\n 'operation':'myincludeblocks1',\n 'camera':'mycam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'myincludeblocks1_temperature.'\n }\n },\n 'operation blocks':{\n 'myincludeblocks1':{\n 'type':'extractblock',\n 'include blocks':['blk-2', 'blk-3', 'blk-7']\n }\n }\n }\n\nAs mentioned previously, you can specify 'exclude blocks' instead of\n'include blocks', but you may not specify both.\n\n"
10529
10530 def __init__(self):
10531 PhactoriOperationSpecifics.__init__(self)
10532 #mIncludeblockList OR mExcludeBlockList will be filled in from parsing
10533 self.mIncludeBlockList = None
10534 self.mExpandedIncludeBlockList = None
10535 self.mExcludeBlockList = None
10536 self.mRemoveBlanksAndDashes = True
10537
10538 def ParseParametersFromJson(self, inJson):
10539
10540 if 'include blocks' in inJson:
10541 self.mIncludeBlockList = inJson['include blocks']
10542
10543 if 'exclude blocks' in inJson:
10544 self.mExcludeBlockList = inJson['exclude blocks']
10545
10546 if self.mIncludeBlockList == None and self.mExcludeBlockList == None:
10547 myDebugPrint3AndException(
10548 "PhactoriExtractBlockOperation::ParseParametersFromJson\n"
10549 "Error: must have 'include block list' or 'exclude block list'\n")
10550
10551 #2022Aug09 only include blocks is working
10552 if self.mIncludeBlockList == None:
10553 myDebugPrint3AndException(
10554 "PhactoriExtractBlockOperation::ParseParametersFromJson\n"
10555 "Error: must have 'include block list'\n"
10556 "currently (2022Aug09) exclude blocks is not working\n")
10557
10558 def MakeExpandedIncludeBlockList(self):
10559 if self.mExpandedIncludeBlockList == None:
10560 self.mExpandedIncludeBlockList = list(self.mIncludeBlockList)
10561 for oneItem in self.mIncludeBlockList:
10562 #add leader, remove spaces and dashes, this might change
10563 if self.mRemoveBlanksAndDashes:
10564 baseItem = oneItem.replace(" ","")
10565 baseItem = baseItem.replace("-","")
10566 else:
10567 baseItem = oneItem
10568 extraItem = "/Root/ElementBlocks/" + baseItem
10569 self.mExpandedIncludeBlockList.append(extraItem)
10570 extraItem = "/Root/Bases/Base/Zones/" + baseItem
10571 self.mExpandedIncludeBlockList.append(extraItem)
10572 if PhactoriDbg(100):
10573 myDebugPrint3("self.mExpandedIncludeBlockList:\n" + \
10574 str(self.mExpandedIncludeBlockList) + "\n")
10575
10576 def CreateParaViewFilter(self, inInputFilter):
10577 "create the extract block filter for ParaView"
10578 if PhactoriDbg(100):
10579 myDebugPrint3("PhactoriExtractBlockOperation.CreateParaViewFilter "
10580 "entered\n", 100)
10581 #info in block class should already be parsed and checked
10582
10583 savedActiveSource = GetActiveSource()
10584
10585 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10586
10587 if PhactoriDbg():
10588 myDebugPrint3(" extractblock inInputFilter point data arrays:\n")
10589 numArrays = inInputFilter.PointData.GetNumberOfArrays()
10590 for ii in range (0, numArrays):
10591 myDebugPrint3(" " + str(ii) + ": " + inInputFilter.PointData.GetArray(ii).GetName() + "\n")
10592
10593 if PhactoriDbg():
10594 myDebugPrint3(" extractblock inInputFilter cell data arrays:\n")
10595 numArrays = inInputFilter.CellData.GetNumberOfArrays()
10596 for ii in range (0, numArrays):
10597 myDebugPrint3(" " + str(ii) + ": " + inInputFilter.CellData.GetArray(ii).GetName() + "\n")
10598
10599 newParaViewFilter = ExtractBlock(inInputFilter)
10600 self.MakeExpandedIncludeBlockList()
10601 newParaViewFilter.Selectors = self.mExpandedIncludeBlockList
10602
10603 SetActiveSource(newParaViewFilter)
10604
10605 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10606 if PhactoriDbg():
10607 myDebugPrint3(" extractblock newParaViewFilter point data arrays:\n")
10608 numArrays = newParaViewFilter.PointData.GetNumberOfArrays()
10609 for ii in range (0, numArrays):
10610 myDebugPrint3(" " + str(ii) + ": " + newParaViewFilter.PointData.GetArray(ii).GetName() + "\n")
10611
10612 if PhactoriDbg():
10613 myDebugPrint3(" extractblock newParaViewFilter cell data arrays:\n")
10614 numArrays = newParaViewFilter.CellData.GetNumberOfArrays()
10615 for ii in range (0, numArrays):
10616 myDebugPrint3(" " + str(ii) + ": " + newParaViewFilter.CellData.GetArray(ii).GetName() + "\n")
10617
10618 SetActiveSource(savedActiveSource)
10619
10620 if PhactoriDbg(100):
10621 myDebugPrint3("PhactoriExtractBlockOperation.CreateParaViewFilter "
10622 "returning\n", 100)
10623
10624 return newParaViewFilter
10625 #phactori_combine_to_single_python_file_subpiece_end_1
10626
10627 #phactori_combine_to_single_python_file_parent_1
10628 #from Operation.PhactoriCellDataToPointDataOperation import *
10629 #phactori_combine_to_single_python_file_subpiece_begin_1
10630 class PhactoriCellDataToPointDataOperation(PhactoriOperationSpecifics):
10631 def __init__(self):
10632 PhactoriOperationSpecifics.__init__(self)
10633 self.passCellData = 0
10634 self.pieceInvariant = 0
10635 return
10636
10637 def ParseParametersFromJson(self, inJson):
10638 key1 = "pass cell data"
10639 if key1 in inJson:
10640 self.passCellData = inJson[key1]
10641 key1 = "piece invariant"
10642 if key1 in inJson:
10643 self.pieceInvariant = inJson[key1]
10644 return
10645
10646 def CreateParaViewFilter(self, inInputFilter):
10647 if PhactoriDbg(100):
10648 myDebugPrint3('PhactoriCellDataToPointDataOperation:CreateParaViewFilter entered\n', 100)
10649
10650 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10651
10652 savedActiveSource = GetActiveSource()
10653 newParaViewFilter = CellDatatoPointData(Input = inInputFilter)
10654 if self.passCellData:
10655 newParaViewFilter.PassCellData = 1
10656 else:
10657 newParaViewFilter.PassCellData = 0
10658 if self.pieceInvariant:
10659 newParaViewFilter.PieceInvariant = 1
10660 else:
10661 newParaViewFilter.PieceInvariant = 0
10662
10663 SetActiveSource(newParaViewFilter)
10664 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10665 SetActiveSource(savedActiveSource)
10666
10667 if PhactoriDbg(100):
10668 myDebugPrint3('PhactoriCellDataToPointDataOperation.CreateParaViewFilter returning\n', 100)
10669
10670 return newParaViewFilter
10671
10672 #phactori_combine_to_single_python_file_subpiece_end_1
10673
10674 #phactori_combine_to_single_python_file_parent_1
10675 #from Operation.PhactoriExtractComponentOperation import *
10676 #phactori_combine_to_single_python_file_subpiece_begin_1
10677 class PhactoriExtractComponentOperation(PhactoriOperationSpecifics):
10678 def __init__(self):
10679 PhactoriOperationSpecifics.__init__(self)
10680 self.Component = 0
10681 self.InputArrayName = "None"
10682 self.InputArrayCellsOrPoints = "POINTS"
10683 self.OutputArrayName = "Result"
10684 return
10685
10686 def ParseParametersFromJson(self, inJson):
10687 keyval1 = "component"
10688 if keyval1 in inJson:
10689 self.Component = inJson[keyval1]
10690
10691 keyval2 = "output array name"
10692 if keyval2 in inJson:
10693 self.OutputArrayName = inJson[keyval2]
10694
10695 keyval3 = "input array name"
10696 if keyval3 in inJson:
10697 self.InputArrayName = inJson[keyval3]
10698 else:
10699 myDebugPrint3AndException(
10700 "PhactoriExtractComponentOperation:ParseParametersFromJson\n"
10701 "must have keys 'input array name' and 'input array type'\n")
10702
10703 keyval4 = "input array type"
10704 if keyval4 in inJson:
10705 typeval = inJson[keyval4]
10706 if typeval == "points":
10707 self.InputArrayCellsOrPoints = "POINTS"
10708 elif typeval == "cells":
10709 self.InputArrayCellsOrPoints = "CELLS"
10710 elif typeval == "nodes":
10711 self.InputArrayCellsOrPoints = "POINTS"
10712 elif typeval == "elements":
10713 self.InputArrayCellsOrPoints = "CELLS"
10714 else:
10715 myDebugPrint3AndException(
10716 "PhactoriExtractComponentOperation:ParseParametersFromJson\n"
10717 "'input array type' must be 'points' 'cells' 'nodes' or 'elements'\n")
10718 else:
10719 myDebugPrint3AndException(
10720 "PhactoriExtractComponentOperation:ParseParametersFromJson\n"
10721 "must have keys 'input array name' and 'input array type'\n")
10722
10723 def CreateParaViewFilter(self, inInputFilter):
10724 if PhactoriDbg(100):
10725 myDebugPrint3("PhactoriExtractComponentOperation:CreateParaViewFilter entered\n", 100)
10726 #info in block class should already be parsed and checked
10727
10728 if PhactoriDbg(100):
10729 myDebugPrint3("about to call UpdatePipelineWithCurrentTimeArgument\n", 100)
10730 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10731
10732 savedActiveSource = GetActiveSource()
10733 newParaViewFilter = ExtractComponent(Input = inInputFilter)
10734 newParaViewFilter.Component = self.Component
10735 newParaViewFilter.OutputArrayName = self.OutputArrayName
10736 newParaViewFilter.InputArray = [self.InputArrayCellsOrPoints, self.InputArrayName]
10737 if PhactoriDbg(100):
10738 myDebugPrint3(
10739 "newParaViewFilter.Component" + str(newParaViewFilter.Component) + "\n"
10740 "newParaViewFilter.OutputArrayName" + str(newParaViewFilter.OutputArrayName) + "\n"
10741 "newParaViewFilter.InputArray" + str(newParaViewFilter.InputArray) + "\n", 100)
10742
10743 SetActiveSource(newParaViewFilter)
10744 if PhactoriDbg(100):
10745 myDebugPrint3("about to call UpdatePipelineWithCurrentTimeArgument\n", 100)
10746 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10747 SetActiveSource(savedActiveSource)
10748
10749 if PhactoriDbg(100):
10750 myDebugPrint3("PhactoriExtractComponentOperation.CreateParaViewFilter returning\n", 100)
10751
10752 return newParaViewFilter
10753
10754 #phactori_combine_to_single_python_file_subpiece_end_1
10755
10756 #phactori_combine_to_single_python_file_parent_1
10757 #from Operation.PhactoriCellSizeOperation import *
10758 #phactori_combine_to_single_python_file_subpiece_begin_1
10759 class PhactoriCellSizeOperation(PhactoriOperationSpecifics):
10760 def __init__(self):
10761 PhactoriOperationSpecifics.__init__(self)
10762 return
10763
10764 def ParseParametersFromJson(self, inJson):
10765 return
10766
10767 def CreateParaViewFilter(self, inInputFilter):
10768 if PhactoriDbg(100):
10769 myDebugPrint3('PhactoriCellSizeOperation:CreateParaViewFilter entered\n', 100)
10770 #info in block class should already be parsed and checked
10771
10772
10773 if PhactoriDbg(100):
10774 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10775 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10776
10777 savedActiveSource = GetActiveSource()
10778 if PhactoriDbg(100):
10779 myDebugPrint3('about to call CellSize\n', 100)
10780 newParaViewFilter = CellSize(Input = inInputFilter)
10781
10782 SetActiveSource(newParaViewFilter)
10783 if PhactoriDbg(100):
10784 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10785 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10786 SetActiveSource(savedActiveSource)
10787
10788 if PhactoriDbg(100):
10789 myDebugPrint3('PhactoriCellSizeOperation.CreateParaViewFilter returning\n', 100)
10790
10791 return newParaViewFilter
10792
10793 #phactori_combine_to_single_python_file_subpiece_end_1
10794
10795 #phactori_combine_to_single_python_file_parent_1
10796 #from Operation.PhactoriAppendLocationAttributesOperation import *
10797 #phactori_combine_to_single_python_file_subpiece_begin_1
10798 class PhactoriAppendLocationAttributesOperation(PhactoriOperationSpecifics):
10799 def __init__(self):
10800 PhactoriOperationSpecifics.__init__(self)
10801 self.AppendPointLocations = 1
10802 self.AppendCellCenters = 1
10803 return
10804
10805 def ParseParametersFromJson(self, inJson):
10806 key1 = "append point locations"
10807 if key1 in inJson:
10808 testval = inJson[key1]
10809 if testval:
10810 self.AppendPointLocations = 1
10811 else:
10812 self.AppendPointLocations = 0
10813 else:
10814 key1 = "append_point_locations"
10815 if key1 in inJson:
10816 testval = inJson[key1]
10817 if testval:
10818 self.AppendPointLocations = 1
10819 else:
10820 self.AppendPointLocations = 0
10821
10822 key2 = "append cell centers"
10823 if key2 in inJson:
10824 testval = inJson[key2]
10825 if testval:
10826 self.AppendCellCenters = 1
10827 else:
10828 self.AppendCellCenters = 0
10829 else:
10830 key2 = "append_cell_centers"
10831 if key2 in inJson:
10832 testval = inJson[key2]
10833 if testval:
10834 self.AppendCellCenters = 1
10835 else:
10836 self.AppendCellCenters = 0
10837
10838 return
10839
10840 def CreateParaViewFilter(self, inInputFilter):
10841 if PhactoriDbg(100):
10842 myDebugPrint3('PhactoriAppendLocationAttributesOperation:CreateParaViewFilter entered\n', 100)
10843 #info in block class should already be parsed and checked
10844
10845 if PhactoriDbg(100):
10846 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10847 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10848
10849 savedActiveSource = GetActiveSource()
10850 if PhactoriDbg(100):
10851 myDebugPrint3('about to call AppendLocationAttributes\n', 100)
10852 newParaViewFilter = AppendLocationAttributes(Input = inInputFilter)
10853
10854 newParaViewFilter.AppendPointLocations = self.AppendPointLocations
10855 newParaViewFilter.AppendCellCenters = self.AppendCellCenters
10856
10857 SetActiveSource(newParaViewFilter)
10858 if PhactoriDbg(100):
10859 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10860 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10861 SetActiveSource(savedActiveSource)
10862
10863 if PhactoriDbg(100):
10864 myDebugPrint3('PhactoriAppendLocationAttributesOperation.CreateParaViewFilter returning\n', 100)
10865
10866 return newParaViewFilter
10867
10868 #phactori_combine_to_single_python_file_subpiece_end_1
10869
10870 #phactori_combine_to_single_python_file_parent_1
10871 #from Operation.PhactoriIntegrateVariablesOperation import *
10872 #phactori_combine_to_single_python_file_subpiece_begin_1
10873 class PhactoriIntegrateVariablesOperation(PhactoriOperationSpecifics):
10874 def __init__(self):
10875 PhactoriOperationSpecifics.__init__(self)
10876 self.myCopyOfInputFilter = None
10877 self.myCopyOfIntegrationFilter = None
10878 self.outfileNameManager = PhactoriOutputFileNameAndDirectoryManager(
10879 "PhactoriIntegrateVariablesOperation_", ".", 5, ".csv")
10880 return
10881
10882 def ParseParametersFromJson(self, inJson):
10883 self.outfileNameManager.ParseOutputFileNameControl(inJson, "output file ")
10884 return
10885
10886 def CreateParaViewFilter(self, inInputFilter):
10887 if PhactoriDbg(100):
10888 myDebugPrint3('PhactoriIntegrateVariablesOperation:CreateParaViewFilter entered\n', 100)
10889 #info in block class should already be parsed and checked
10890
10891
10892 if PhactoriDbg(100):
10893 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10894 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
10895
10896 savedActiveSource = GetActiveSource()
10897 if PhactoriDbg(100):
10898 myDebugPrint3('about to call IntegrateVariables\n', 100)
10899 newParaViewFilter = IntegrateVariables(Input = inInputFilter)
10900
10901 SetActiveSource(newParaViewFilter)
10902 if PhactoriDbg(100):
10903 myDebugPrint3('about to call UpdatePipelineWithCurrentTimeArgument\n', 100)
10904 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
10905 SetActiveSource(savedActiveSource)
10906
10907 self.myCopyOfInputFilter = inInputFilter
10908 self.myCopyOfIntegrationFilter = newParaViewFilter
10909
10910 if PhactoriDbg(100):
10911 myDebugPrint3('PhactoriIntegrateVariablesOperation.CreateParaViewFilter returning\n', 100)
10912
10913 return newParaViewFilter
10914
10915 def ExportOperationData(self, datadescription):
10916 if PhactoriDbg(100):
10917 myDebugPrint3("PhactoriIntegrateVariablesOperation.ExportOperationData entered\n", 100)
10918
10919 myPid = SmartGetLocalProcessId()
10920 ftc = GetFrameTagCounter()
10921 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
10922 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfIntegrationFilter)
10923
10924 #self.myCopyOfIntegrationFilter = IntegrateVariables(Input = self.myCopyOfInputFilter)
10925 #UpdatePipelineWithCurrentTimeArgument(self.myCopyOfIntegrationFilter)
10926
10927 pointDataFileName = self.outfileNameManager.GetOutputFilePath(ftc, "_points_")
10928 cellDataFileName = self.outfileNameManager.GetOutputFilePath(ftc, "_cells_")
10929 SaveData(pointDataFileName, proxy=self.myCopyOfIntegrationFilter, FieldAssociation='Points')
10930 SaveData(cellDataFileName, proxy=self.myCopyOfIntegrationFilter, FieldAssociation='Cells')
10931
10932 if PhactoriDbg(100):
10933 myDebugPrint3("PhactoriIntegrateVariablesOperation.ExportOperationData returning\n", 100)
10934
10935 #phactori_combine_to_single_python_file_subpiece_end_1
10936
10937 #phactori_combine_to_single_python_file_parent_1
10938 #from Operation.PhactoriContourOperation import *
10939 #phactori_combine_to_single_python_file_subpiece_begin_1
10940 class PhactoriContourOperation(PhactoriOperationSpecifics):
10941 "clip plane operation, adapter to the catalyst Contour filter\n\nPhactoriContourOperation is the phactori manager for working with the\nParaView/Catalyst Contour() filter and its parameters, providing\naccess and pipeline/input/output managment via the json, lexx/yacc, or soon\nyaml interface. The user may specify a named input to the filter, with the\nunnamed default being the incoming data mesh. i\n\nFor information on the Contour() filter from ParaView, see the ParaView\nDocumentation. The basic operation is to take a value and a variable and\ncalculate an iso surface in the mesh corresponding to the value and create\na 3D surface at that iso value. Multiple values can be specified in the same\noperation, resulting in multiple surface.\n\nThe user must specify the variable to be used and one or more isosurface\nvalues.\n\nTo add a PhactoriContourOperation to the incoming script, you add\na sub-block to the 'operation blocks' section of the data with the 'type'\nkey given a value of 'contour'. One complete but simple example script:\n\n::\n\n {\n 'camera blocks':{'mycam1':{'type':'camera', 'look direction':[1.0, 2.0, 3.0]}},\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_contour_1':{\n 'operation':'myclipwithplane1',\n 'camera':'mycam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'contour1_temperature.'\n }\n },\n 'operation blocks':{\n 'mycontour1':{\n 'type':'contour',\n 'variable scalar':'temperature',\n 'contour value':[100.0, 150.0, 200.0, 1000.0]\n }\n }\n\n\nAs an alternative to 'contour value' you are allowed to specify a key\n'contour value sequence' with a start value, a step value, and an end value.\nContour values will automatically be created from start, spacing by step,\nuntil a value greater than or equal to end is reached. For example:\n\n\n::\n\n 'contour value sequence': [100.0, 200.0, 1100.0]\n\n\nwill get 100, 300, 500, 700, and 900. If it is 1101.0 for end, 1100.0 will\nalso be used.\n\n"
10942
10943 def __init__(self):
10944 PhactoriOperationSpecifics.__init__(self)
10945 self.mVariableInfo = PhactoriVariableInfo()
10946 self.mContourValue = [0.0]
10947
10948 #flag allows system to be set up to bypass this operation, especially
10949 #for testing camera settings against geometry without thresholds,
10950 #iso surfaces messing the tests up
10951 self.mBypassFlag = False
10952
10953 def ParseParametersFromJson(self, inJson):
10954
10955 self.mBypassFlag = getParameterFromBlock(inJson, 'bypass flag',
10956 self.mBypassFlag)
10957 if self.mBypassFlag == True:
10958 #this operation is bypassed: don't do other parsing
10959 return
10960
10961 foundVariableFlag = self.mVariableInfo.\
10962 ParseVariableNameAndVectorOrTensorComponent(inJson, 'variable ')
10963
10964 if foundVariableFlag == False:
10965 errStr = "error! inJson has no variable info in\n PhactoriContourOperation.ParseParametersFromJson\n"
10966 if PhactoriDbg():
10967 myDebugPrint3(errStr)
10968 raise Exception(errStr)
10969
10970 if 'contour value' in inJson:
10971 self.mContourValue = inJson['contour value']
10972 elif 'contour value sequence' in inJson:
10973 seqCntrl = inJson['contour value sequence']
10974 rStart = seqCntrl[0]
10975 rStep = seqCntrl[1]
10976 rEnd = seqCntrl[2]
10977 self.mContourValue = []
10978 rVal = rStart
10979 if rEnd > rStart:
10980 if rStep <= 0.0:
10981 errStr = "error! bad contour value sequence in\n PhactoriContourOperation.ParseParametersFromJson\n"
10982 if PhactoriDbg():
10983 myDebugPrint3(errStr)
10984 raise Exception(errStr)
10985 while rVal < rEnd:
10986 self.mContourValue.append(rVal)
10987 rVal += rStep
10988 else:
10989 if rStep >= 0.0:
10990 errStr = "error! bad contour value sequence in\n PhactoriContourOperation.ParseParametersFromJson\n"
10991 if PhactoriDbg():
10992 myDebugPrint3(errStr)
10993 raise Exception(errStr)
10994 while rVal > rEnd:
10995 self.mContourValue.append(rVal)
10996 rVal += rStep
10997 else:
10998 errStr = "error! inJson has no 'contour value' or 'contour value sequence' key in\n PhactoriContourOperation.ParseParametersFromJson\n"
10999 if PhactoriDbg():
11000 myDebugPrint3(errStr)
11001 raise Exception(errStr)
11002
11003
11004 def CreateParaViewFilter(self, inInputFilter):
11005 "create the clip plane filter for ParaView"
11006 if PhactoriDbg(100):
11007 myDebugPrint3('PhactoriContourOperation.CreateParaViewFilter entered\n', 100)
11008 #info in block class should already be parsed and checked
11009
11010 #if the operation bypass flag is set to true, we want this
11011 #operation to do nothing and just pass the input to the output
11012 if self.mBypassFlag == True:
11013 if PhactoriDbg():
11014 myDebugPrint3("PhactoriContourOperation::CreateParaViewFilter\n" +
11015 "mBypassFlag was true, so paraview output filter is input filter")
11016 return inInputFilter
11017
11018 savedActiveSource = GetActiveSource()
11019 SetActiveSource(inInputFilter)
11020 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
11021
11022 newParaViewFilter = Contour(Input = inInputFilter,
11023 PointMergeMethod="Uniform Binning")
11024 newParaViewFilter.ComputeScalars = 1
11025
11026 if PhactoriDbg():
11027 myDebugPrint3(" contour filter is: " + str(newParaViewFilter) + "\n")
11028 newParaViewFilter.PointMergeMethod = "Uniform Binning"
11029
11030 detectResult = self.mVariableInfo.DetectVariableType(inInputFilter, True)
11031 #if detectResult == False:
11032 #PutOperationOnListToDetectVariableTypeInFutureSteps()
11033
11034 #hack to deal with how paraview/catalyst expects naming of threshold
11035 #variables which are vector components or magnitudes
11036
11037 localVariableName = GetThresholdContourHackVariableNameString(self.mVariableInfo)
11038
11039 newParaViewFilter.Isosurfaces = self.mContourValue
11040
11041 if PhactoriDbg():
11042 myDebugPrint3(' name for variable in threshold: ' + localVariableName + '\n')
11043
11044 #for contour, if data type is 'element'/'CELLS', the contour filter will
11045 #(apparently) automatically add a cell-to-point filter
11046 newParaViewFilter.ContourBy = ['POINTS', localVariableName]
11047
11048 if PhactoriDbg():
11049 myDebugPrint3(" still okay\n")
11050 SetActiveSource(newParaViewFilter)
11051 SetActiveSource(savedActiveSource)
11052
11053 #debugging contour error
11054 #if PhactoriDbg():
11055 # newParaViewFilter.UpdatePipeline()
11056 # pointData = newParaViewFilter.PointData
11057 # numPointArrays = pointData.GetNumberOfArrays()
11058 # myDebugPrint3("number of point arrays: " + str(numPointArrays) + "\n"
11059 # "ComputeScalars: " + str(newParaViewFilter.ComputeScalars) + "\n")
11060 # for ii in range(numPointArrays):
11061 # onePointArray = pointData.GetArray(ii)
11062 # myDebugPrint3(str(ii) + ": " + onePointArray.GetName() + ": " + \
11063 # str(onePointArray.GetNumberOfTuples()) + "\n")
11064
11065 if PhactoriDbg(100):
11066 myDebugPrint3('PhactoriContourOperation.CreateParaViewFilter returning\n', 100)
11067
11068 return newParaViewFilter
11069 #phactori_combine_to_single_python_file_subpiece_end_1
11070
11071
11072 class PhactoriPlaneOpBase(PhactoriOperationSpecifics):
11073 "base operation type for slice operation and clip operation. They share\n parsing and settings, and just differ by which filter is created"
11074 def __init__(self):
11075 PhactoriOperationSpecifics.__init__(self)
11076 self.mPtOnPlaneInfo = PhactoriUserPointInfo()
11077 self.mPlaneNormal = [0.0, 1.0, 0.0]
11078 self.mUseThreePointsOnPlane = False
11079 self.mPtOnPlaneInfoA = None
11080 self.mPtOnPlaneInfoB = None
11081 self.mPtOnPlaneInfoC = None
11082 self.mCrinkleSetting = None
11083 if gParaViewCatalystVersionFlag < 50502:
11084 self.mInsideOut = 1
11085 else:
11086 self.mInvert = 1
11087
11088 def ParseParametersFromJson(self, inJson):
11089 if PhactoriDbg(100):
11090 myDebugPrint3("PhactoriPlaneOpBase.ParseParametersFromJson entered\n", 100)
11091
11092 if "plane specification" in inJson:
11093 if inJson["plane specification"] == "point and normal":
11094 self.mUseThreePointsOnPlane = False
11095 elif inJson["plane specification"] == "three points":
11096 self.mUseThreePointsOnPlane = True
11097 else:
11098 myDebugPrint3AndException(
11099 "PhactoriPlaneOpBase.ParseParametersFromJson:\n"
11100 "'plane specification' must be 'point and normal' or "
11101 "'three points'\n")
11102
11103 if self.mUseThreePointsOnPlane:
11104 if PhactoriDbg():
11105 myDebugPrint3("using three points on plane instead of plane/normal:\n")
11106 self.mPtOnPlaneInfoA = PhactoriUserPointInfo()
11107 self.mPtOnPlaneInfoA.mXyz = [0.0, 0.0, 0.0]
11108 self.mPtOnPlaneInfoB = PhactoriUserPointInfo()
11109 self.mPtOnPlaneInfoB.mXyz = [0.0, 1.0, 0.0]
11110 self.mPtOnPlaneInfoC = PhactoriUserPointInfo()
11111 self.mPtOnPlaneInfoC.mXyz = [0.0, 0.0, 1.0]
11112 self.mPtOnPlaneInfoA.UserPointInfoParseParametersFromJson(
11113 inJson, "", " on plane A")
11114 self.mPtOnPlaneInfoB.UserPointInfoParseParametersFromJson(
11115 inJson, "", " on plane B")
11116 self.mPtOnPlaneInfoC.UserPointInfoParseParametersFromJson(
11117 inJson, "", " on plane C")
11118 else:
11119 if PhactoriDbg():
11120 myDebugPrint3(
11121 "using point/normal: PhactoriPlaneOpBase parsing point onplane:\n")
11122 self.mPtOnPlaneInfo.UserPointInfoParseParametersFromJson(
11123 inJson, "", " on plane")
11124
11125 if 'plane normal' in inJson:
11126 self.mPlaneNormal = inJson['plane normal']
11127 self.mPlaneNormal = vecNormalize(self.mPlaneNormal)
11128 else:
11129 self.mPlaneNormal = [0.0, 1.0, 0.0]
11130
11131 if gParaViewCatalystVersionFlag < 50502:
11132 if 'side to keep' in inJson:
11133 whichSide = inJson['side to keep']
11134 if whichSide == 'positive':
11135 self.mInsideOut = 0
11136 elif whichSide == 'negative':
11137 self.mInsideOut = 1
11138 else:
11139 if PhactoriDbg():
11140 myDebugPrint3('ParseParametersFromJson warning: side to keep \
11141 should be positive or negative, but is not, using positive\n')
11142 else:
11143 self.mInsideOut = 0
11144 else:
11145 if 'side to keep' in inJson:
11146 whichSide = inJson['side to keep']
11147 if whichSide == 'positive':
11148 self.mInvert = 0
11149 elif whichSide == 'negative':
11150 self.mInvert = 1
11151 else:
11152 if PhactoriDbg():
11153 myDebugPrint3('ParseParametersFromJson warning: side to keep \
11154 should be positive or negative, but is not, using positive\n')
11155 else:
11156 self.mInvert = 0
11157
11158 if 'cut type' in inJson:
11159 cutType = inJson['cut type']
11160 self.mCrinkleSetting = 0
11161 if cutType == 'smooth':
11162 self.mCrinkleSetting = 0
11163 elif cutType == 'crinkle':
11164 self.mCrinkleSetting = 1
11165 else:
11166 if PhactoriDbg():
11167 myDebugPrint3('ParseParametersFromJson warning: cut type \
11168 should be smooth or crinkle, but is not, using smooth\n')
11169 self.mCrinkleSetting = 0
11170 else:
11171 self.mCrinkleSetting = 0 #debatable default
11172
11173 def CreateParaViewFilter(self, inInputFilter):
11174 errStr = "error! this is a base class which should have\n CreateParaViewFilter method overridden and not\n used"
11175 if PhactoriDbg():
11176 myDebugPrint3(errStr)
11177 raise Exception(errStr)
11178
11179 def CalculateUpdatedOriginAndNormal(
11180 self, inIncomingPvFilter, outCalculatedOrigin, outCalculatedNormal):
11181 "find a point on the plane and a normal to the plane, allowing for\n need to update location of points due to the point or points on the\n plane being relative points or data points"
11182
11183 if PhactoriDbg():
11184 myDebugPrint3(
11185 "PhactoriPlaneOpBase::CalculateUpdatedOriginAndNormal entered\n")
11186
11187 viewBoundsArray = [None]
11188 if self.mUseThreePointsOnPlane:
11189 #defining plane by three points on plane
11190 originToUse = \
11191 self.mPtOnPlaneInfoA.GetCurrentGeometricPointWithDisplacement(
11192 inIncomingPvFilter, viewBoundsArray, True)
11193 outCalculatedOrigin[0] = originToUse[0]
11194 outCalculatedOrigin[1] = originToUse[1]
11195 outCalculatedOrigin[2] = originToUse[2]
11196 if PhactoriDbg():
11197 myDebugPrint3(' calculating normal from 3 points\n')
11198 tempPtB = self.mPtOnPlaneInfoB.GetCurrentGeometricPointWithDisplacement(
11199 inIncomingPvFilter, viewBoundsArray, False)
11200 tempPtC = self.mPtOnPlaneInfoC.GetCurrentGeometricPointWithDisplacement(
11201 inIncomingPvFilter, viewBoundsArray, False)
11202 vecAB = vecFromAToB(outCalculatedOrigin, tempPtB)
11203 vecAC = vecFromAToB(outCalculatedOrigin, tempPtC)
11204 vecCrossProduct2(outCalculatedNormal, vecAB, vecAC)
11205 #if we have 2 collinear points, our cross product will go to zero, and
11206 #we have to pick an arbitrary normal; we should be more selective
11207 #about this test
11208 if vecMagnitudeSquared(outCalculatedNormal,) < 0.000000000000000000001:
11209 if PhactoriDbg():
11210 myDebugPrint3(' two or more points are colinear, using 0,1,0\n')
11211 outCalculatedNormal[0] = 0.0
11212 outCalculatedNormal[1] = 1.0
11213 outCalculatedNormal[2] = 0.0
11214 else:
11215 vecNormalize2(outCalculatedNormal, outCalculatedNormal)
11216 else:
11217 originToUse = self.mPtOnPlaneInfo. \
11218 GetCurrentGeometricPointWithDisplacement(
11219 inIncomingPvFilter, viewBoundsArray, True)
11220 outCalculatedOrigin[0] = originToUse[0]
11221 outCalculatedOrigin[1] = originToUse[1]
11222 outCalculatedOrigin[2] = originToUse[2]
11223 outCalculatedNormal[0] = self.mPlaneNormal[0]
11224 outCalculatedNormal[1] = self.mPlaneNormal[1]
11225 outCalculatedNormal[2] = self.mPlaneNormal[2]
11226
11227 if PhactoriDbg():
11228 myDebugPrint3(
11229 "PhactoriPlaneOpBase::CalculateUpdatedOriginAndNormal returning\n")
11230
11231
11232 def MayChangeWithData(self):
11233 if self.mUseThreePointsOnPlane:
11234 return (self.mPtOnPlaneInfoA.mMayChangeWithData or \
11235 self.mPtOnPlaneInfoB.mMayChangeWithData or \
11236 self.mPtOnPlaneInfoC.mMayChangeWithData)
11237 else:
11238 return self.mPtOnPlaneInfo.mMayChangeWithData
11239
11240 #phactori_combine_to_single_python_file_parent_1
11241 #from Operation.PhactoriSliceOperation import *
11242 #phactori_combine_to_single_python_file_subpiece_begin_1
11243 class PhactoriSliceOperation(PhactoriPlaneOpBase):
11244 "slice operation, settings and handling of slice filter"
11245
11246 def CreateParaViewFilter(self, inInputFilter):
11247
11248 #don't need our own init code at this point, but this is how it would be
11249 #added
11250 #def __init__(self):
11251 # MySuperClass.__init__(self)
11252
11253 "create the slice plane filter for ParaView"
11254 if PhactoriDbg(100):
11255 myDebugPrint3('PhactoriSliceOperation.CreateParaViewFilter entered\n', 100)
11256 #info in block class should already be parsed and checked
11257
11258 savedActiveSource = GetActiveSource()
11259 newParaViewFilter = Slice(Input = inInputFilter, SliceType = "Plane")
11260 newParaViewFilter.Triangulatetheslice = 0
11261
11262 self.UpdateSlice(inInputFilter, newParaViewFilter)
11263
11264 SetActiveSource(newParaViewFilter)
11265 SetActiveSource(savedActiveSource)
11266
11267 if PhactoriDbg(100):
11268 myDebugPrint3('PhactoriSliceOperation.CreateParaViewFilter returning\n', 100)
11269
11270 return newParaViewFilter
11271
11272 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
11273 outOutgoingPvFilter):
11274 "the PhactoriSliceOperation may need to update if the point on\n the slice plane was tied to a node, element, or variable min/max\n location"
11275 if PhactoriDbg():
11276 myDebugPrint3("PhactoriSliceOperation::"
11277 "DoUpdateDueToChangeInData override executing\n")
11278
11279 if self.MayChangeWithData() == False:
11280 if PhactoriDbg():
11281 myDebugPrint3("PhactoriSlicePlaneOperation::"
11282 "DoUpdateDueToChangeInData returning (absolute point or points)\n")
11283 return
11284
11285 self.UpdateSlice(inIncomingPvFilter, outOutgoingPvFilter)
11286
11287 if PhactoriDbg():
11288 myDebugPrint3("PhactoriSlicePlaneOperation::"
11289 "DoUpdateDueToChangeInData override returning\n")
11290
11291 def UpdateSlice(self, inIncomingPvFilter, ioOutgoingPvFilter):
11292 "using the current info on the slice, get all the paraview stuff\n set up correctly"
11293
11294 if PhactoriDbg():
11295 myDebugPrint3("PhactoriSlicePlaneOperation::UpdateSlice entered\n")
11296
11297 originToUse = [0,0,0]
11298 normalToUse = [0,1,0]
11299 self.CalculateUpdatedOriginAndNormal(
11300 inIncomingPvFilter, originToUse, normalToUse)
11301
11302 if PhactoriDbg():
11303 myDebugPrint3(' updateslice using normal: ' + \
11304 str(normalToUse) + '\n')
11305 ioOutgoingPvFilter.SliceType.Normal = normalToUse
11306
11307 if PhactoriDbg():
11308 myDebugPrint3(' updateslice using origin: ' + str(originToUse) + '\n')
11309 ioOutgoingPvFilter.SliceType.Origin = originToUse
11310
11311 #these aren't changing yet
11312 ioOutgoingPvFilter.Crinkleslice = self.mCrinkleSetting
11313
11314 if PhactoriDbg():
11315 myDebugPrint3("PhactoriSlicePlaneOperation::UpdateSlice returning\n")
11316
11317 #phactori_combine_to_single_python_file_subpiece_end_1
11318
11319 #phactori_combine_to_single_python_file_parent_1
11320 #from Operation.PhactoriSliceWithPlaneOperation import *
11321 #phactori_combine_to_single_python_file_subpiece_begin_1
11322 class PhactoriSliceWithPlaneOperation(PhactoriPlaneOpBase):
11323 "slice with plane operation, adapter to the catalyst filter\n\nPhactoriSliceWithPlaneOperation is the phactori manager for working with the\nParaView/Catalyst SliceWithPlane() filter and its parameters, providing\naccess and pipeline/input/output managment via the json, lexx/yacc, or soon\nyaml interface. The user may specify a named input to the filter, with the\nunnamed default being the incoming data mesh.\n\nFor information on the SliceWithPlane() filter from ParaView, see the\nParaView Documentation.\n\nOur experience has been that as of ParaView 5.8 there are some mesh\ngeometries where the paraview Slice() filter with a plane slice type will\ncrash while SliceWithPlane() behaves correctly.\n\nThe user must define the plane with a point and normal or with three points.\nThere are defaults which will be used if the user does not supply some or\nall of the definition. PhactoriSliceWithPlaneOperation is a child class of\nPhactoriPlaneOpBase, along with PhactoriSliceOperation and\nPhactoriClipPlaneOperation. Check the documentation for PhactoriPlaneOpBase\nfor the many options for defining the plane point(s), including absolute or\nrelative 3D points, dynamic data-driven point locations, or collocating with\nmesh nodes or elements (or offset therefrom).\n\nTo add a PhactoriSliceWithPlaneOperation to the incoming script, you add\na sub-block to the 'operation blocks' section of the data with the 'type'\nkey given a value of 'slicewithplane'. One complete but simple example\nscript:\n\n::\n\n {\n 'camera blocks':{'myslicecam1':{'type':'camera', 'look direction':[1.0, 2.0, 3.0]}},\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_on_slice_1':{\n 'operation':'myslicewithplane1',\n 'camera':'myslicecam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'slice1_temperature.'\n }\n },\n 'operation blocks':{\n 'myslicewithplane1':{\n 'type':'slicewithplane',\n 'relative point on plane':[0.1, -0.2, 0.3],\n 'plane normal':[1.0, 2.0, 3.0]\n }\n }\n } \n\nthe plane normal does not need to be a unit vector: Phactori will normalize\nit for you (again, see PhactoriClipPlaneOperation)\n\nA minimalist example script using all default behavior will produce 8 images\nwith autogenerated names with 6 axis aligned views and 2 diagonal xyz views\ncolored by block index number (cylically).\n\n::\n\n { 'camera blocks':{},\n 'representation blocks':{},\n 'imageset blocks':{'slice_1_imageset':{'operation':'myslicewithplane1'}},\n 'operation blocks':{'myslicewithplane1':{'type':'slicewithplane'}} }\n\n"
11324
11325 def CreateParaViewFilter(self, inInputFilter):
11326
11327 #don't need our own init code at this point, but this is how it would be
11328 #added
11329 #def __init__(self):
11330 # MySuperClass.__init__(self)
11331
11332 "create the slice plane filter for ParaView"
11333 if PhactoriDbg(100):
11334 myDebugPrint3('PhactoriSliceWithPlaneOperation.CreateParaViewFilter entered\n', 100)
11335 #info in block class should already be parsed and checked
11336
11337 savedActiveSource = GetActiveSource()
11338
11339 newParaViewFilter = SliceWithPlane(Input=inInputFilter)
11340 global gParaViewCatalystVersionFlag
11341 if gParaViewCatalystVersionFlag < 51100:
11342 newParaViewFilter.Plane = 'Plane'
11343 else:
11344 newParaViewFilter.PlaneType = 'Plane'
11345
11346 self.UpdateSlice(inInputFilter, newParaViewFilter)
11347
11348 SetActiveSource(newParaViewFilter)
11349 SetActiveSource(savedActiveSource)
11350
11351 if PhactoriDbg(100):
11352 myDebugPrint3('PhactoriSliceWithPlaneOperation.CreateParaViewFilter returning\n', 100)
11353
11354 return newParaViewFilter
11355
11356 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
11357 outOutgoingPvFilter):
11358 "the PhactoriSliceWithPlaneOperation may need to update if the point on\n the slice plane was tied to a node, element, or variable min/max\n location"
11359 if PhactoriDbg():
11360 myDebugPrint3("PhactoriSliceWithPlaneOperation::"
11361 "DoUpdateDueToChangeInData override executing\n")
11362
11363 if self.MayChangeWithData() == False:
11364 if PhactoriDbg():
11365 myDebugPrint3("PhactoriSliceWithPlanePlaneOperation::"
11366 "DoUpdateDueToChangeInData returning (absolute point or points)\n")
11367 return
11368
11369 self.UpdateSlice(inIncomingPvFilter, outOutgoingPvFilter)
11370
11371 if PhactoriDbg():
11372 myDebugPrint3("PhactoriSliceWithPlanePlaneOperation::"
11373 "DoUpdateDueToChangeInData override returning\n")
11374
11375 def UpdateSlice(self, inIncomingPvFilter, ioOutgoingPvFilter):
11376 "using the current info on the slice, get all the paraview stuff\n set up correctly"
11377
11378 if PhactoriDbg():
11379 myDebugPrint3("PhactoriSliceWithPlanePlaneOperation::UpdateSlice entered\n")
11380
11381 originToUse = [0,0,0]
11382 normalToUse = [0,1,0]
11383 self.CalculateUpdatedOriginAndNormal(
11384 inIncomingPvFilter, originToUse, normalToUse)
11385
11386 if PhactoriDbg():
11387 myDebugPrint3(' updateslice using normal: ' + \
11388 str(normalToUse) + '\n')
11389 myDebugPrint3(' updateslice using origin: ' + str(originToUse) + '\n')
11390 global gParaViewCatalystVersionFlag
11391 if gParaViewCatalystVersionFlag < 51100:
11392 ioOutgoingPvFilter.Plane.Normal = normalToUse
11393 ioOutgoingPvFilter.Plane.Origin = originToUse
11394 else:
11395 ioOutgoingPvFilter.PlaneType.Normal = normalToUse
11396 ioOutgoingPvFilter.PlaneType.Origin = originToUse
11397
11398 if PhactoriDbg():
11399 myDebugPrint3("PhactoriSliceWithPlanePlaneOperation::UpdateSlice returning\n")
11400
11401 #phactori_combine_to_single_python_file_subpiece_end_1
11402
11403 #phactori_combine_to_single_python_file_parent_1
11404 #from Operation.PhactoriClipPlaneOperation import *
11405 #phactori_combine_to_single_python_file_subpiece_begin_1
11406 class PhactoriClipPlaneOperation(PhactoriPlaneOpBase):
11407 "clip plane operation, adapter to the catalyst filter\n\nPhactoriSliceWithPlaneOperation is the phactori manager for working with the\nParaView/Catalyst Clip() filter and its parameters, providing\naccess and pipeline/input/output managment via the json, lexx/yacc, or soon\nyaml interface. The user may specify a named input to the filter, with the\nunnamed default being the incoming data mesh. This class is confined to a\nParaView Clip operation with a clip type of plane. See\nPhactoriBoxClipOperation and PhactoriCylinderClipOperation for clipping with\na type of box and cylinder, and other classes may be added for other clip\ntypes.\n\nFor information on the Clip() filter from ParaView, see the ParaView\nDocumentation.\n\nThe user must define the plane with a point and normal or with three points.\nThere are defaults which will be used if the user does not supply some or\nall of the definition. PhactoriClipPlaneOperation is a child class of\nPhactoriPlaneOpBase, along with PhactoriSliceWithPlaneOperation and\nPhactoriSliceOperation. Check the documentation for PhactoriPlaneOpBase\nfor the many options for defining the plane point(s), including absolute or\nrelative 3D points, dynamic data-driven point locations, or collocating with\nmesh nodes or elements (or offset therefrom).\n\nThe user may also choose to make a 'crinkle' or 'smooth' cut with the\n'cut type' key, defaulting to\nsmooth. A smooth cut makes a two dimentional plane, while a crinkle cut\nincludes all elements cut by the plane and creates no new elements which\nwere not in the original mesh. The user may also choose to keep either side\nof the plane by using the key 'side to keep' and setting to 'positive' or\n'negative'.\n\nTo add a PhactoriClipPlaneOperation to the incoming script, you add\na sub-block to the 'operation blocks' section of the data with the 'type'\nkey given a value of 'clip'. One complete but simple example\nscript:\n\n::\n\n {\n 'camera blocks':{'myclipcam1':{'type':'camera', 'look direction':[1.0, 2.0, 3.0]}},\n 'representation blocks':{'rep_tmprtr':{'color by scalar':'temperature'}},\n 'imageset blocks':{\n 'temperature_clip_1':{\n 'operation':'myclipwithplane1',\n 'camera':'myclipcam1',\n 'representation':'rep_tmprtr',\n 'image basedirectory':'CatalystOutput',\n 'image basename':'clip1_temperature.'\n }\n },\n 'operation blocks':{\n 'myclipwithplane1':{\n 'type':'clip',\n 'cut type':'crinkle',\n 'side to keep':'negative',\n 'relative point on plane':[0.1, -0.2, 0.3],\n 'plane normal':[1.0, 2.0, 3.0]\n }\n }\n\nThe 'point on plane' is a PhactoriUserPointInfo instance, which means it can\nbe an absolute point, a relative point, a data point (at min or max of a data\narray), at a node/point, at an element/cell, or at a data min max or cell or\nelement but displaced by a vector. See the PhactoriUserPointInfo class for more\ndetailed info.\n\nFurther, the plane may also be define with three points instead of a point and\na normal. To use this format, omit the 'plane normal' and '... point on plane'\nkeys and instead have keys with 'point on plane A', 'point and plane B', and\n'point on plane C'. For example:\n\n::\n\n 'absolute point on plane A':[0.0, 1.0, 2.0],\n 'relative point on plane B':[0.0, 0.2, -0.3],\n 'relative point on plane C':[0.0, 0.0, -0.0],\n\n"
11408
11409 def CreateParaViewFilter(self, inInputFilter):
11410
11411 #don't need our own init code at this point, but this is how it would be
11412 #added
11413 #def __init__(self):
11414 # MySuperClass.__init__(self)
11415
11416 "create the clip plane filter for ParaView"
11417 if PhactoriDbg(100):
11418 myDebugPrint3('PhactoriClipPlaneOperation.CreateParaViewFilter entered\n', 100)
11419 #info in block class should already be parsed and checked
11420
11421 savedActiveSource = GetActiveSource()
11422 newParaViewFilter = Clip(Input = inInputFilter, ClipType = "Plane")
11423 self.UpdateClip(inInputFilter, newParaViewFilter)
11424
11425 SetActiveSource(newParaViewFilter)
11426 SetActiveSource(savedActiveSource)
11427
11428 if PhactoriDbg(100):
11429 myDebugPrint3('PhactoriClipPlaneOperation.CreateParaViewFilter returning\n', 100)
11430
11431 return newParaViewFilter
11432
11433 def DoUpdateDueToChangeInData(self, inIncomingPvFilter,
11434 outOutgoingPvFilter):
11435 "the PhactoriClipPlaneOperation may need to update if the point on\n the clip plane was tied to a node, element, or variable min/max\n location"
11436 if PhactoriDbg():
11437 myDebugPrint3("PhactoriClipPlaneOperation::"
11438 "DoUpdateDueToChangeInData override executing\n")
11439
11440 if self.MayChangeWithData() == False:
11441 if PhactoriDbg():
11442 myDebugPrint3("PhactoriClipPlaneOperation::"
11443 "DoUpdateDueToChangeInData returning (absolute point or points)\n")
11444 return
11445
11446 self.UpdateClip(inIncomingPvFilter, outOutgoingPvFilter)
11447
11448 if PhactoriDbg():
11449 myDebugPrint3("PhactoriClipPlaneOperation::"
11450 "DoUpdateDueToChangeInData override returning\n")
11451
11452 def UpdateClip(self, inIncomingPvFilter, ioOutgoingPvFilter):
11453 "using the current info on the clip, get all the paraview stuff\n set up correctly"
11454
11455 if PhactoriDbg():
11456 myDebugPrint3("PhactoriClipPlaneOperation::UpdateClip entered\n")
11457
11458 originToUse = [0,0,0]
11459 normalToUse = [0,1,0]
11460 self.CalculateUpdatedOriginAndNormal(
11461 inIncomingPvFilter, originToUse, normalToUse)
11462
11463 if PhactoriDbg():
11464 myDebugPrint3(' updateclip using normal: ' + \
11465 str(normalToUse) + '\n')
11466 ioOutgoingPvFilter.ClipType.Normal = normalToUse
11467
11468 if PhactoriDbg():
11469 myDebugPrint3(' updateclip using origin: ' + str(originToUse) + '\n')
11470 ioOutgoingPvFilter.ClipType.Origin = originToUse
11471
11472 #these aren't changing yet
11473 ioOutgoingPvFilter.Crinkleclip = self.mCrinkleSetting
11474 if gParaViewCatalystVersionFlag < 50502:
11475 ioOutgoingPvFilter.InsideOut = self.mInsideOut
11476 else:
11477 ioOutgoingPvFilter.Invert = self.mInvert
11478
11479 if PhactoriDbg():
11480 myDebugPrint3("PhactoriClipPlaneOperation::UpdateClip returning\n")
11481 #phactori_combine_to_single_python_file_subpiece_end_1
11482
11483 #phactori_combine_to_single_python_file_parent_1
11484 #from Operation.PhactoriCylinderClipOperation import *
11485 #phactori_combine_to_single_python_file_subpiece_begin_1
11486 class PhactoriCylinderClipOperation(PhactoriOperationSpecifics):
11487 def __init__(self):
11488 PhactoriOperationSpecifics.__init__(self)
11489 self.mCenterPtInfo = PhactoriUserPointInfo()
11490 self.mAxis = [0.0, 1.0, 0.0]
11491 self.mRadius = 0.5
11492 self.mRadiusRelAbsFlag = True
11493 self.mKeepInside = True
11494 self.mCrinkleSetting = None
11495
11496 def ParseParametersFromJson(self, inJson):
11497 if PhactoriDbg(100):
11498 myDebugPrint3(
11499 'PhactoriCylinderClipOperation.ParseParametersFromJson entered\n', 100)
11500 self.mCenterPtInfo.UserPointInfoParseParametersFromJson(
11501 inJson, "center at ", "")
11502
11503 absRadiusKey = 'absolute radius'
11504 relRadiusKey = 'relative radius'
11505 if absRadiusKey in inJson:
11506 self.mRadius = inJson[absRadiusKey]
11507 self.mRadiusRelAbsFlag = False
11508 elif relRadiusKey in inJson:
11509 self.mRadius = inJson[relRadiusKey]
11510 self.mRadiusRelAbsFlag = True
11511 else:
11512 self.mRadius = 0.5
11513 self.mRadiusRelAbsFlag = True
11514
11515 axisKey = 'axis'
11516 if axisKey in inJson:
11517 self.mAxis = inJson[axisKey]
11518
11519 if 'keep inside cylinder' in inJson:
11520 self.mKeepInside = inJson['keep inside cylinder']
11521 else:
11522 self.mKeepInside = True
11523
11524 if 'cut type' in inJson:
11525 cutType = inJson['cut type']
11526 self.mCrinkleSetting = 0
11527 if cutType == 'smooth':
11528 self.mCrinkleSetting = 0
11529 elif cutType == 'crinkle':
11530 self.mCrinkleSetting = 1
11531 else:
11532 if PhactoriDbg():
11533 myDebugPrint3('ParseParametersFromJson warning: cut type \
11534 should be smooth or crinkle, but is not, using smooth\n')
11535 self.mCrinkleSetting = 0
11536 else:
11537 self.mCrinkleSetting = 0 #debatable default
11538
11539 #self.PrintSelf()
11540 if PhactoriDbg(100):
11541 myDebugPrint3(
11542 'PhactoriCylinderClipOperation.ParseParametersFromJson returning\n',
11543 100)
11544
11545 def PrintSelf(self):
11546 if PhactoriDbg(100):
11547 myDebugPrint3('PhactoriCylinderClipOperation.PrintSelf entered\n" + \
11548 "Center Point:', 100)
11549 self.mCenterPtInfo.PrintSelf()
11550 if PhactoriDbg():
11551 myDebugPrint3('mRadiusRelAbsFlag: ' + str(self.mRadiusRelAbsFlag) + '\n')
11552 if PhactoriDbg():
11553 myDebugPrint3('mRadius: ' + str(self.mRadius) + '\n')
11554 if PhactoriDbg():
11555 myDebugPrint3('mAxis: ' + str(self.mAxis) + '\n')
11556 if PhactoriDbg():
11557 myDebugPrint3('mKeepInside: ' + str(self.mKeepInside) + '\n')
11558 if PhactoriDbg():
11559 myDebugPrint3('mCrinkleSetting: ' + str(self.mCrinkleSetting) + '\n')
11560
11561 def CreateParaViewFilter(self, inInputFilter):
11562 "create the cylinder clip filter for ParaView"
11563 if PhactoriDbg(100):
11564 myDebugPrint3('PhactoriCylinderClipOperation.CreateParaViewFilter ' +\
11565 'entered\n', 100)
11566 #info in block class should already be parsed and checked
11567
11568 savedActiveSource = GetActiveSource()
11569
11570 newParaViewFilter = Clip(Input = inInputFilter, ClipType = "Cylinder")
11571 ## Properties modified on clip4.ClipType
11572 #clip4.ClipType.Center = [10.93421983718872, -0.8890213072299957, 0.0]
11573 #clip4.ClipType.Axis = [1.0, 0.0, 0.0]
11574 #clip4.ClipType.Radius = 0.75
11575
11576 newParaViewFilter.ClipType.Axis = self.mAxis
11577
11578 viewBoundsArray = [None]
11579 centerToUse = self.mCenterPtInfo.GetCurrentGeometricPointWithDisplacement(
11580 inInputFilter, viewBoundsArray, True)
11581
11582 newParaViewFilter.ClipType.Center = [centerToUse[0],
11583 centerToUse[1],
11584 centerToUse[2]]
11585
11586 if PhactoriDbg():
11587 myDebugPrint3(" about to find radius--absolute or calced from relative\n")
11588 myViewBounds = viewBoundsArray[0]
11589 if self.mRadiusRelAbsFlag:
11590 if myViewBounds == None:
11591 myViewBounds = GetGlobalDataBoundsParallel(inInputFilter)
11592 dxx = myViewBounds[1] - myViewBounds[0]
11593 dyy = myViewBounds[3] - myViewBounds[2]
11594 dzz = myViewBounds[5] - myViewBounds[4]
11595 bounds_diagonal = math.sqrt(dxx*dxx + dyy*dyy + dzz*dzz)
11596 newParaViewFilter.ClipType.Radius = self.mRadius * bounds_diagonal
11597 else:
11598 newParaViewFilter.ClipType.Radius = self.mRadius
11599
11600 newParaViewFilter.Crinkleclip = self.mCrinkleSetting
11601 if self.mKeepInside:
11602 newParaViewFilter.InsideOut = 1
11603 else:
11604 newParaViewFilter.InsideOut = 0
11605
11606 SetActiveSource(newParaViewFilter)
11607 SetActiveSource(savedActiveSource)
11608
11609 if PhactoriDbg(100):
11610 myDebugPrint3(
11611 'PhactoriCylinderClipOperation.CreateParaViewFilter returning\n', 100)
11612
11613 return newParaViewFilter
11614
11615 def MayChangeWithData(self):
11616 if self.mCenterPtInfo.mMayChangeWithData == True:
11617 return True
11618 if self.mRadiusRelAbsFlag == True:
11619 return True
11620 return False
11621 #phactori_combine_to_single_python_file_subpiece_end_1
11622
11623 #phactori_combine_to_single_python_file_parent_1
11624 #from Operation.PhactoriBoxClipOperation import *
11625 #phactori_combine_to_single_python_file_subpiece_begin_1
11626 class PhactoriBoxClipOperation(PhactoriOperationSpecifics):
11627 "clip operation with a clip type of 'box', adapter to the catalyst filter\n\nPhactori Adapter interface to the ParaView Clip filter with a clip type\nof 'box'. Refere to the ParaView documentation for extensive\ndocumentation of the clip filter.\n\nTo control the BoxClipOperation you have a section in the\n'operation blocks' section of the phactori control script which looks like:\n\n::\n\n 'operation blocks':{\n 'myboxclip1':{\n 'type':'boxclip',\n 'center at absolute point':[1.1, -2.2, 3.5],\n 'absolute extents':[5.0, 6.2, 7.3]\n }\n }\n\n'center at absolute point' may also be 'center at relative point' or\n'center at element' or 'center at node' or 'center at data point', as it is\na 'phactori use point'. 'absolute extents' may be 'relative extents' in\nwhich case the extents of the clip box are determined relative to the size\nof the bounding box of the data.\n\n"
11628
11629 def __init__(self):
11630 PhactoriOperationSpecifics.__init__(self)
11631 self.mCenterPtInfo = PhactoriUserPointInfo()
11632 self.mExtentsRelAbsFlag = [True, True, True]
11633 self.mExtents = [0.5, 0.5, 0.5]
11634 self.mRotations = [0.0, 0.0, 0.0]
11635 self.mKeepInside = True
11636 self.mCrinkleSetting = None
11637
11638 def ParseParametersFromJson(self, inJson):
11639 if PhactoriDbg(100):
11640 myDebugPrint3(
11641 'PhactoriBoxClipOperation.ParseParametersFromJson entered\n', 100)
11642 self.mCenterPtInfo.UserPointInfoParseParametersFromJson(
11643 inJson, "center at ", "")
11644
11645 absExtentsKey = 'absolute extents'
11646 relExtentsKey = 'relative extents'
11647 if absExtentsKey in inJson:
11648 self.mExtents = inJson[absExtentsKey]
11649 self.mExtentsRelAbsFlag = [False, False, False]
11650 elif relExtentsKey in inJson:
11651 self.mExtents = inJson[relExtentsKey]
11652 self.mExtentsRelAbsFlag = [True, True, True]
11653 else:
11654 self.mExtents = [0.5, 0.5, 0.5]
11655 self.mExtentsRelAbsFlag = [True, True, True]
11656
11657 rotationsKey = 'rotations'
11658 if rotationsKey in inJson:
11659 self.mRotations = inJson[rotationsKey]
11660
11661 if 'keep inside box' in inJson:
11662 self.mKeepInside = inJson['keep inside box']
11663 else:
11664 self.mKeepInside = True
11665
11666 if 'cut type' in inJson:
11667 cutType = inJson['cut type']
11668 self.mCrinkleSetting = 0
11669 if cutType == 'smooth':
11670 self.mCrinkleSetting = 0
11671 elif cutType == 'crinkle':
11672 self.mCrinkleSetting = 1
11673 else:
11674 if PhactoriDbg():
11675 myDebugPrint3('ParseParametersFromJson warning: cut type \
11676 should be smooth or crinkle, but is not, using smooth\n')
11677 self.mCrinkleSetting = 0
11678 else:
11679 self.mCrinkleSetting = 0 #debatable default
11680
11681 #self.PrintSelf()
11682 if PhactoriDbg(100):
11683 myDebugPrint3('PhactoriBoxClipOperation.ParseParametersFromJson returning\n', 100)
11684
11685 def PrintSelf(self):
11686 if PhactoriDbg(100):
11687 myDebugPrint3('PhactoriBoxClipOperation.PrintSelf entered\nCenter Point:', 100)
11688 self.mCenterPtInfo.PrintSelf()
11689 if PhactoriDbg():
11690 myDebugPrint3('mExtentsRelAbsFlag: ' + str(self.mExtentsRelAbsFlag) + '\n')
11691 if PhactoriDbg():
11692 myDebugPrint3('mExtents: ' + str(self.mExtents) + '\n')
11693 if PhactoriDbg():
11694 myDebugPrint3('mRotations: ' + str(self.mRotations) + '\n')
11695 if PhactoriDbg():
11696 myDebugPrint3('mKeepInside: ' + str(self.mKeepInside) + '\n')
11697 if PhactoriDbg():
11698 myDebugPrint3('mCrinkleSetting: ' + str(self.mCrinkleSetting) + '\n')
11699
11700 def CreateParaViewFilter(self, inInputFilter):
11701 "create the box clip box for ParaView"
11702 if PhactoriDbg(100):
11703 myDebugPrint3('PhactoriBoxClipOperation.CreateParaViewFilter entered\n', 100)
11704 #info in block class should already be parsed and checked
11705
11706 savedActiveSource = GetActiveSource()
11707
11708 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
11709
11710 if PhactoriDbg(100):
11711 DebugPrintCellAndPointArrayInfo("data arrays coming into PhactoriBoxClipOperation.CreateParaViewFilter\n", inInputFilter, 100)
11712
11713 newParaViewFilter = Clip(Input = inInputFilter, ClipType = "Box")
11714
11715 viewBoundsArray = [None]
11716 centerToUse = self.mCenterPtInfo.GetCurrentGeometricPointWithDisplacement(
11717 inInputFilter, viewBoundsArray, True)
11718
11719 if PhactoriDbg():
11720 myDebugPrint3(" about to find extents--absolute or calced from relative\n")
11721 myViewBounds = viewBoundsArray[0]
11722 if self.mExtentsRelAbsFlag[0]:
11723 if myViewBounds == None:
11724 myViewBounds = GetGlobalDataBoundsParallel(inInputFilter)
11725 halfXExt = self.mExtents[0] * (myViewBounds[1] - myViewBounds[0]) * 0.5
11726 if halfXExt <= 1e-20:
11727 halfXExt = 0.001
11728 else:
11729 halfXExt = self.mExtents[0] * 0.5
11730
11731 if self.mExtentsRelAbsFlag[1]:
11732 if myViewBounds == None:
11733 myViewBounds = GetGlobalDataBoundsParallel(inInputFilter)
11734 halfYExt = self.mExtents[1] * (myViewBounds[3] - myViewBounds[2]) * 0.5
11735 if halfYExt <= 1e-20:
11736 halfYExt = 0.001
11737 else:
11738 halfYExt = self.mExtents[1] * 0.5
11739
11740 if self.mExtentsRelAbsFlag[2]:
11741 if myViewBounds == None:
11742 myViewBounds = GetGlobalDataBoundsParallel(inInputFilter)
11743 halfZExt = self.mExtents[2] * (myViewBounds[5] - myViewBounds[4]) * 0.5
11744 if halfZExt <= 1e-20:
11745 halfZExt = 0.001
11746 else:
11747 halfZExt = self.mExtents[2] * 0.5
11748
11749 if PhactoriDbg():
11750 myDebugPrint3(" halfExtents: " + str(halfXExt) + ", " + str(halfYExt) + ", " + str(halfZExt) + "\n")
11751
11752 #newParaViewFilter.ClipType.Position = [centerToUse[0],
11753 # centerToUse[1],
11754 # centerToUse[2]]
11755 #newParaViewFilter.ClipType.Bounds = [-halfXExt, halfXExt,
11756 # -halfYExt, halfYExt, -halfZExt, halfZExt]
11757 newParaViewFilter.ClipType.Position = [centerToUse[0] - halfXExt,
11758 centerToUse[1] - halfYExt,
11759 centerToUse[2] - halfZExt]
11760 newParaViewFilter.ClipType.Length = [halfXExt * 2.0, halfYExt * 2.0, halfZExt * 2.0]
11761 newParaViewFilter.ClipType.Rotation = [self.mRotations[0],
11762 self.mRotations[1],
11763 self.mRotations[2]]
11764
11765 newParaViewFilter.Crinkleclip = self.mCrinkleSetting
11766 if gParaViewCatalystVersionFlag < 50502:
11767 if self.mKeepInside:
11768 newParaViewFilter.InsideOut = 1
11769 else:
11770 newParaViewFilter.InsideOut = 0
11771 else:
11772 if self.mKeepInside:
11773 newParaViewFilter.Invert = 1
11774 else:
11775 newParaViewFilter.Invert = 0
11776
11777 SetActiveSource(newParaViewFilter)
11778 SetActiveSource(savedActiveSource)
11779
11780 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
11781
11782 if PhactoriDbg(100):
11783 DebugPrintCellAndPointArrayInfo("data arrays coming out of PhactoriBoxClipOperation.CreateParaViewFilter\n", newParaViewFilter, 100)
11784
11785 if PhactoriDbg(100):
11786 myDebugPrint3('PhactoriBoxClipOperation.CreateParaViewFilter returning\n', 100)
11787
11788 return newParaViewFilter
11789
11790 def MayChangeWithData(self):
11791 if self.mCenterPtInfo.mMayChangeWithData == True:
11792 return True
11793 if self.mExtentsRelAbsFlag[0] == True:
11794 return True
11795 if self.mExtentsRelAbsFlag[1] == True:
11796 return True
11797 if self.mExtentsRelAbsFlag[2] == True:
11798 return True
11799 return False
11800 #phactori_combine_to_single_python_file_subpiece_end_1
11801
11802 #phactori_combine_to_single_python_file_parent_1
11803 #from Operation.PhactoriStreamTracerOperation import *
11804 #phactori_combine_to_single_python_file_subpiece_begin_1
11805 class PhactoriStreamTracerOperation(PhactoriOperationSpecifics):
11806 def __init__(self):
11807 PhactoriOperationSpecifics.__init__(self)
11808 self.LineSourcePoint1 = [-0.5, -0.5, -0.5]
11809 self.LineSourcePoint2 = [0.5, 0.5, 0.5]
11810 self.Resolution = 500
11811 return
11812
11813 def ParseParametersFromJson(self, inJson):
11814 key1 = "line source point 1"
11815 self.LineSourcePoint1 = getParameterFromBlock(inJson, key1, self.LineSourcePoint1)
11816 if len(self.LineSourcePoint1) != 3:
11817 myDebugPrint3AndException(
11818 "'" + key1 + "' must be list with three floats for x, y, z\n")
11819
11820 key2 = "line source point 2"
11821 self.LineSourcePoint2 = getParameterFromBlock(inJson, key2, self.LineSourcePoint2)
11822 if len(self.LineSourcePoint2) != 3:
11823 myDebugPrint3AndException(
11824 "'" + key2 + "' must be list with three floats for x, y, z\n")
11825
11826 key3 = "resolution"
11827 self.Resolution = getParameterFromBlock(inJson, key3, self.Resolution)
11828 if isinstance(self.Resolution, int) == False:
11829 myDebugPrint3AndException(
11830 "'" + key3 + "' must be an integer\n")
11831
11832
11833 def CreateParaViewFilter(self, inInputFilter):
11834 "create the clip plane filter for ParaView"
11835 if PhactoriDbg(100):
11836 myDebugPrint3('PhactoriStreamTracerOperation:CreateParaViewFilter entered\n', 100)
11837 #info in block class should already be parsed and checked
11838
11839 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
11840
11841 savedActiveSource = GetActiveSource()
11842
11843 newParaViewFilter = StreamTracer(Input = inInputFilter, SeedType="High Resolution Line Source")
11844 newParaViewFilter.Vectors = ["CELLS", "velocity_xyz"]
11845 newParaViewFilter.MaximumStreamlineLength = 100.0
11846 newParaViewFilter.SeedType.Point1 = self.LineSourcePoint1
11847 newParaViewFilter.SeedType.Point2 = self.LineSourcePoint2
11848 newParaViewFilter.SeedType.Resolution = self.Resolution
11849 newParaViewFilter.IntegrationDirection = 'FORWARD'
11850 newParaViewFilter.MaximumSteps = 5000
11851 #newParaViewFilter.InitialStepLength = 0.01
11852
11853 if PhactoriDbg(100):
11854 stcso = newParaViewFilter.GetClientSideObject()
11855 stodo = stcso.GetOutputDataObject(0)
11856 myDebugPrint3("stodo st: " + str(stodo.GetClassName()) + " numcells " + str(stodo.GetNumberOfCells()) + " numpoints " + str(stodo.GetNumberOfPoints()) + "\n")
11857 stido0 = stcso.GetInputDataObject(0,0)
11858 myDebugPrint3("stido0 st: " + str(stido0.GetClassName()) + "\n")
11859 stido1 = stcso.GetInputDataObject(1,0)
11860 myDebugPrint3("stido1 st: " + str(stido1.GetClassName()) + " numcells " + str(stido1.GetNumberOfCells()) + " numpoints " + str(stido1.GetNumberOfPoints()) + "\n")
11861
11862 SetActiveSource(newParaViewFilter)
11863 SetActiveSource(savedActiveSource)
11864
11865 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
11866
11867 if PhactoriDbg(100):
11868 stcso = newParaViewFilter.GetClientSideObject()
11869 stodo = stcso.GetOutputDataObject(0)
11870 myDebugPrint3("B stodo st: " + str(stodo.GetClassName()) + " numcells " + str(stodo.GetNumberOfCells()) + " numpoints " + str(stodo.GetNumberOfPoints()) + "\n")
11871 stido0 = stcso.GetInputDataObject(0,0)
11872 myDebugPrint3("B stido0 st: " + str(stido0.GetClassName()) + "\n")
11873 stido1 = stcso.GetInputDataObject(1,0)
11874 myDebugPrint3("B stido1 st: " + str(stido1.GetClassName()) + " numcells " + str(stido1.GetNumberOfCells()) + " numpoints " + str(stido1.GetNumberOfPoints()) + "\n")
11875
11876 if PhactoriDbg(100):
11877 myDebugPrint3('PhactoriStreamTracerOperation.CreateParaViewFilter returning\n', 100)
11878
11879 return newParaViewFilter
11880
11881 #phactori_combine_to_single_python_file_subpiece_end_1
11882
11883 #phactori_combine_to_single_python_file_parent_1
11884 #from Operation.PhactoriStreamTracerSeedSourceOperation import *
11885 #phactori_combine_to_single_python_file_subpiece_begin_1
11886 class PhactoriStreamTracerSeedSourceOperation(PhactoriOperationSpecifics):
11887 def __init__(self):
11888 PhactoriOperationSpecifics.__init__(self)
11889 self.SeedSourceName = None
11890 self.InternalParaViewFilterPtr = None
11891 return
11892
11893 def ParseParametersFromJson(self, inJson):
11894 key1 = "seed source"
11895 if key1 not in inJson:
11896 myDebugPrint3AndException("PhactoriStreamTracerSeedSourceOperation:ParseParametersFromJson\n"
11897 "'" + key1 + "' must be in block to specify source for seed points\n")
11898 self.SeedSourceName = inJson[key1]
11899
11900 def GetListOfInputOperationNamesForThisOperationType(self):
11901 "PhactoriStreamTracerSeedSourceOperation depends on the seed sources as\n well as the input source"
11902 retList = []
11903 retList.append(self.SeedSourceName)
11904 return retList
11905
11906 def DebugPrintInputPortAndOutputPortInfo(self, infoTag):
11907 if PhactoriDbg(100):
11908 myDebugPrint3(infoTag)
11909 stcso = self.InternalParaViewFilterPtr.GetClientSideObject()
11910 stodo = stcso.GetOutputDataObject(0)
11911 myDebugPrint3("stodo: " + str(stodo.GetClassName()) + " numcells " + str(stodo.GetNumberOfCells()) + " numpoints " + str(stodo.GetNumberOfPoints()) + "\n")
11912 stido0 = stcso.GetInputDataObject(0,0)
11913 myDebugPrint3("stido0: " + str(stido0.GetClassName()) + "\n")
11914 stido1 = stcso.GetInputDataObject(1,0)
11915 myDebugPrint3("stido1: " + str(stido1.GetClassName()) + " numcells " + str(stido1.GetNumberOfCells()) + " numpoints " + str(stido1.GetNumberOfPoints()) + "\n")
11916
11917 def CreateParaViewFilter2(self, inInputFilter, inPipeAndViewsState):
11918 "create the clip plane filter for ParaView"
11919 if PhactoriDbg(100):
11920 myDebugPrint3('PhactoriStreamTracerSeedSourceOperation:CreateParaViewFilter entered\n', 100)
11921 #info in block class should already be parsed and checked
11922
11923 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
11924
11925 #get seed source operation
11926 paraviewSeedSource = inPipeAndViewsState.GetParaViewSourceByOperationName(self.SeedSourceName)
11927 if PhactoriDbg(100):
11928 myDebugPrint3("self.SeedSourceName: " + str(self.SeedSourceName) + \
11929 "\nparaviewSeedSource: " + str(paraviewSeedSource) + "\n", 100)
11930
11931 UpdatePipelineWithCurrentTimeArgument(paraviewSeedSource)
11932
11933 if PhactoriDbg(100):
11934 psscso = paraviewSeedSource.GetClientSideObject()
11935 pssodo = psscso.GetOutputDataObject(0)
11936 myDebugPrint3("pssodo: " + str(pssodo.GetClassName()) + " numcells " + str(pssodo.GetNumberOfCells()) + " numpoints " + str(pssodo.GetNumberOfPoints()) + "\n")
11937
11938 savedActiveSource = GetActiveSource()
11939
11940 self.InternalParaViewFilterPtr = StreamTracerWithCustomSource(Input = inInputFilter, SeedSource=paraviewSeedSource)
11941
11942 #psscso = paraviewSeedSource.GetClientSideObject()
11943 #pssodo = psscso.GetOutputDataObject(0)
11944 #stcso = self.InternalParaViewFilterPtr.GetClientSideObject()
11945 #stcso.SetInputDataObject(1,pssodo)
11946
11947 self.InternalParaViewFilterPtr.Vectors = ["CELLS", "velocity_xyz"]
11948 #self.InternalParaViewFilterPtr.Vectors = ["POINTS", "velocity_xyz"]
11949 self.InternalParaViewFilterPtr.MaximumStreamlineLength = 100.0
11950 self.InternalParaViewFilterPtr.IntegrationDirection = 'FORWARD'
11951 self.InternalParaViewFilterPtr.MaximumSteps = 5000
11952 #self.InternalParaViewFilterPtr.InitialStepLength = 0.01
11953
11954 self.DebugPrintInputPortAndOutputPortInfo("pre filter update 1\n")
11955
11956 SetActiveSource(self.InternalParaViewFilterPtr)
11957 SetActiveSource(savedActiveSource)
11958
11959 UpdatePipelineWithCurrentTimeArgument(self.InternalParaViewFilterPtr)
11960
11961 self.DebugPrintInputPortAndOutputPortInfo("post filter update 1\n")
11962
11963 if PhactoriDbg(100):
11964 myDebugPrint3("self.InternalParaViewFilterPtr: " + str(self.InternalParaViewFilterPtr) + "\n", 100)
11965
11966 if PhactoriDbg(100):
11967 myDebugPrint3('PhactoriStreamTracerSeedSourceOperation.CreateParaViewFilter returning\n', 100)
11968
11969 return self.InternalParaViewFilterPtr
11970
11971 #phactori_combine_to_single_python_file_subpiece_end_1
11972
11973 #phactori_combine_to_single_python_file_parent_1
11974 #from Operation.PhactoriResampleWithDataset import *
11975 #phactori_combine_to_single_python_file_subpiece_begin_1
11976 class PhactoriResampleWithDatasetOperation(PhactoriOperationSpecifics):
11977 def __init__(self):
11978 PhactoriOperationSpecifics.__init__(self)
11979 self.ResampleDatasetName = None
11980 self.InternalParaViewFilterPtr = None
11981 return
11982
11983 def ParseParametersFromJson(self, inJson):
11984 key1 = "sample dataset"
11985 if key1 not in inJson:
11986 myDebugPrint3AndException("PhactoriResampleWithDatasetOperation:ParseParametersFromJson\n"
11987 "'" + key1 + "' must be in block to specify dataset as source for the resampling\n")
11988 self.ResampleDatasetName = inJson[key1]
11989
11990 def GetListOfInputOperationNamesForThisOperationType(self):
11991 "PhactoriResampleWithDatasetOperation depends on the sampling source as\n well as the input source"
11992 retList = []
11993 retList.append(self.ResampleDatasetName)
11994 return retList
11995
11996 def DebugPrintInputPortAndOutputPortInfo(self, infoTag):
11997 if PhactoriDbg(100):
11998 myDebugPrint3(infoTag)
11999 stcso = self.InternalParaViewFilterPtr.GetClientSideObject()
12000 myDebugPrint3(str(stcso) + "\n")
12001 myDebugPrint3(str(stcso.GetClassName()) + "\n")
12002 stodo = stcso.GetOutputDataObject(0)
12003 myDebugPrint3(str(stodo) + "\n")
12004 myDebugPrint3(str(stodo.GetClassName()) + "\n")
12005 stido0 = stcso.GetInputDataObject(0,0)
12006 myDebugPrint3(str(stido0) + "\n")
12007 myDebugPrint3(str(stido0.GetClassName()) + "\n")
12008 stido1 = stcso.GetInputDataObject(1,0)
12009 myDebugPrint3(str(stido1) + "\n")
12010 myDebugPrint3(str(stido1.GetClassName()) + "\n")
12011 # myDebugPrint3("stodo: " + str(stodo.GetClassName()) + " numcells " + str(stodo.GetNumberOfCells()) + " numpoints " + str(stodo.GetNumberOfPoints()) + "\n")
12012 # myDebugPrint3("stido0: " + str(stido0.GetClassName()) + "\n")
12013 # myDebugPrint3("stido1: " + str(stido1.GetClassName()) + " numcells " + str(stido1.GetNumberOfCells()) + " numpoints " + str(stido1.GetNumberOfPoints()) + "\n")
12014
12015 def CreateParaViewFilter2(self, inInputFilter, inPipeAndViewsState):
12016 "create the clip plane filter for ParaView"
12017 if PhactoriDbg(100):
12018 myDebugPrint3('PhactoriResampleWithDatasetOperation:CreateParaViewFilter entered\n', 100)
12019 #info in block class should already be parsed and checked
12020
12021 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
12022
12023 #get seed source operation
12024 paraviewResampleDataset = inPipeAndViewsState.GetParaViewSourceByOperationName(self.ResampleDatasetName)
12025 if PhactoriDbg(100):
12026 myDebugPrint3("self.ResampleDatasetName: " + str(self.ResampleDatasetName) + \
12027 "\nparaviewResampleDataset: " + str(paraviewResampleDataset) + "\n", 100)
12028
12029 UpdatePipelineWithCurrentTimeArgument(paraviewResampleDataset)
12030
12031 if PhactoriDbg(100):
12032 psscso = paraviewResampleDataset.GetClientSideObject()
12033 pssodo = psscso.GetOutputDataObject(0)
12034 myDebugPrint3("pssodo: " + str(pssodo.GetClassName()) + " numcells " + str(pssodo.GetNumberOfCells()) + " numpoints " + str(pssodo.GetNumberOfPoints()) + "\n")
12035
12036 savedActiveSource = GetActiveSource()
12037
12038 #self.InternalParaViewFilterPtr = ResampleWithDataset(Input = inInputFilter, Source=paraviewResampleDataset)
12039 self.InternalParaViewFilterPtr = ResampleWithDataset(SourceDataArrays = inInputFilter, DestinationMesh=paraviewResampleDataset)
12040 self.InternalParaViewFilterPtr.PassCellArrays = 1
12041 self.InternalParaViewFilterPtr.PassPointArrays = 1
12042
12043 self.InternalParaViewFilterPtr.CellLocator = 'Static Cell Locator'
12044
12045 self.DebugPrintInputPortAndOutputPortInfo("pre filter update 1\n")
12046
12047 SetActiveSource(self.InternalParaViewFilterPtr)
12048 SetActiveSource(savedActiveSource)
12049
12050 self.DebugPrintInputPortAndOutputPortInfo("pre filter update 2\n")
12051
12052 #UpdatePipelineWithCurrentTimeArgument(self.InternalParaViewFilterPtr)
12053
12054 if PhactoriDbg(100):
12055 myDebugPrint3("about to call self.InternalParaViewFilterPtr.UpdatePipeline()\n")
12056
12057 self.InternalParaViewFilterPtr.UpdatePipeline()
12058
12059 self.DebugPrintInputPortAndOutputPortInfo("post filter update 1\n")
12060
12061 if PhactoriDbg(100):
12062 myDebugPrint3("self.InternalParaViewFilterPtr: " + str(self.InternalParaViewFilterPtr) + "\n", 100)
12063
12064 if PhactoriDbg(100):
12065 myDebugPrint3('PhactoriResampleWithDatasetOperation.CreateParaViewFilter returning\n', 100)
12066
12067 return self.InternalParaViewFilterPtr
12068
12069 #phactori_combine_to_single_python_file_subpiece_end_1
12070
12071 #phactori_combine_to_single_python_file_parent_1
12072 #from Operation.PhactoriPointSourceFromJsonList import *
12073 #phactori_combine_to_single_python_file_subpiece_begin_1
12074
12075 class PhactoriPointSourceFromJsonList(PhactoriOperationSpecifics):
12076 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates and creates a new point source from that list. Resulting\n point source will have 1 element an N points. This source is intented\n to work correctly in parallel for Catalyst or pvbatch symmetric mode.\n The json file which is read in will only be read on one process and\n mpi broadcast is used to distribute the list, rather than having each\n process read the json file."
12077 def __init__(self):
12078 self.JsonListFileName = "PhactoriPointSourceFromJsonList.json"
12079 self.JsonList = None
12080 self.ParaviewPointSource = None
12081 self.SourceVtkPolyData = None
12082 self.myVtkPoints = vtk.vtkPoints()
12083 self.myVtkPolyVertex = vtk.vtkPolyVertex()
12084 self.myVtkCellArray = vtk.vtkCellArray()
12085 self.myVtkPolyData = vtk.vtkPolyData()
12086
12087 def ValidateJsonPointList(self):
12088 numPoints = len(self.JsonList)
12089 if numPoints < 1:
12090 myDebugPrint3AndException(
12091 "PhactoriPointSourceFromJsonList::ValidateJsonPointList\n"
12092 "list must have at least one element\n")
12093
12094 for ptNdx in range(0,numPoints):
12095 jsonPt = self.JsonList[ptNdx]
12096 if len(jsonPt) != 3:
12097 errStr = "PhactoriPointSourceFromJsonList::ValidateJsonPointList\n" \
12098 "point with index " + str(ptNdx) + "does not have three elements\n"
12099 myDebugPrint3AndException(errStr)
12100
12101 return True
12102
12103 def ParseParametersFromJson(self, inJson):
12104 if 'filename' in inJson:
12105 self.JsonListFileName = inJson['filename']
12106 else:
12107 myDebugPrint3AndException(
12108 "PhactoriPointSourceFromJsonList::ParseParametersFromJson\n"
12109 "Error: must have 'filename' key\n")
12110
12111 def CreateVtkPolyDataFromJsonList(self):
12112 numPoints = len(self.JsonList)
12113 self.myVtkPoints.SetNumberOfPoints(numPoints)
12114 self.myVtkPolyVertex.GetPointIds().SetNumberOfIds(numPoints)
12115
12116 vtkPolyVertPtIds = self.myVtkPolyVertex.GetPointIds()
12117 usePoint = [0.0, 0.0, 0.0]
12118 for ptNdx in range(0,numPoints):
12119 #self.myVtkPoints.SetPoint(ptNdx, self.JsonList[ptNdx])
12120 jsonPt = self.JsonList[ptNdx]
12121 usePoint[0] = jsonPt[0]
12122 usePoint[1] = jsonPt[1]
12123 usePoint[2] = jsonPt[2]
12124 self.myVtkPoints.SetPoint(ptNdx, usePoint)
12125 vtkPolyVertPtIds.SetId(ptNdx, ptNdx)
12126
12127 self.myVtkPolyData.SetPoints(self.myVtkPoints)
12128 self.myVtkCellArray.InsertNextCell(self.myVtkPolyVertex)
12129 self.myVtkPolyData.SetVerts(self.myVtkCellArray)
12130
12131 def CreateParaViewFilter(self, inInputFilter):
12132 if PhactoriDbg(100):
12133 myDebugPrint3("PhactoriPointSourceFromJsonList.CreateParaViewFilter entered\n", 100)
12134
12135 savedActiveSource = GetActiveSource()
12136
12137 self.JsonList = ReadAndMpiBroadcastJsonFile(self.JsonListFileName)
12138
12139 self.ValidateJsonPointList()
12140
12141 self.CreateVtkPolyDataFromJsonList()
12142
12143 self.ParaviewPointSource = PVTrivialProducer()
12144 self.ParaviewPointSource.GetClientSideObject().SetOutput(self.myVtkPolyData)
12145
12146 SetActiveSource(self.ParaviewPointSource)
12147 SetActiveSource(savedActiveSource)
12148
12149 UpdatePipelineWithCurrentTimeArgument(self.ParaviewPointSource)
12150
12151 if PhactoriDbg(100):
12152 pssfjlcso = self.ParaviewPointSource.GetClientSideObject()
12153 pssfjlodo = pssfjlcso.GetOutputDataObject(0)
12154 myDebugPrint3("pssfjlodo: " + str(pssfjlodo.GetClassName()) + " numcells " + str(pssfjlodo.GetNumberOfCells()) + " numpoints " + str(pssfjlodo.GetNumberOfPoints()) + "\n")
12155
12156 if PhactoriDbg(100):
12157 myDebugPrint3("PhactoriPointSourceFromJsonList.CreateParaViewFilter returning\n", 100)
12158 return self.ParaviewPointSource
12159
12160 #phactori_combine_to_single_python_file_subpiece_end_1
12161
12162 #phactori_combine_to_single_python_file_parent_1
12163 #from Operation.PhactoriPointSource import *
12164 #phactori_combine_to_single_python_file_subpiece_begin_1
12165
12166 class PhactoriPointSource(PhactoriOperationSpecifics):
12167 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates and creates a new point source from that list. Resulting\n point source will have 1 element an N points. This source is intented\n to work correctly in parallel for Catalyst or pvbatch symmetric mode.\n The json file which is read in will only be read on one process and\n mpi broadcast is used to distribute the list, rather than having each\n process read the json file."
12168 def __init__(self):
12169 self.UseDefaultRadius = True
12170 self.Radius = 0.0
12171 self.UseDefaultNumPoints = True
12172 self.NumPoints = 1
12173 self.UseDefaultCenter = True
12174 self.Center = [0.0,0.0,0.0]
12175
12176 def ParseParametersFromJson(self, inJson):
12177 key1 = "radius"
12178 if key1 in inJson:
12179 self.UseDefaultRadius = False
12180 self.Radius = float(inJson[key1])
12181 key1 = "number of points"
12182 if key1 in inJson:
12183 self.UseDefaultNumPoints = False
12184 self.NumPoints = int(inJson[key1])
12185 key1 = "center"
12186 if key1 in inJson:
12187 self.UseDefaultCenter = False
12188 self.Center = inJson[key1]
12189 if len(self.Center) != 3:
12190 myDebugPrint3AndException("PhactoriPointSource:ParseParametersFromJson:\n"
12191 "bad center, need like [0.1,2.3,4.5]\n")
12192
12193 def CreateParaViewFilter(self, inInputFilter):
12194 if PhactoriDbg(100):
12195 myDebugPrint3("PhactoriPointSource.CreateParaViewFilter entered\n", 100)
12196
12197 savedActiveSource = GetActiveSource()
12198
12199 newParaViewFilter = PointSource()
12200 if self.UseDefaultRadius == False:
12201 newParaViewFilter.Radius = self.Radius
12202 if self.UseDefaultNumPoints == False:
12203 newParaViewFilter.NumberOfPoints = self.NumPoints
12204 if self.UseDefaultCenter == False:
12205 newParaViewFilter.Center = self.Center
12206
12207 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
12208
12209 SetActiveSource(newParaViewFilter)
12210 SetActiveSource(savedActiveSource)
12211
12212 if PhactoriDbg(100):
12213 myDebugPrint3("Radius: " + str(newParaViewFilter.Radius) + "\n" + \
12214 "NumberOfPoints: " + str(newParaViewFilter.NumberOfPoints) + "\n" + \
12215 "Center: " + str(newParaViewFilter.Center) + "\n")
12216
12217 if PhactoriDbg(100):
12218 myDebugPrint3("PhactoriPointSource.CreateParaViewFilter returning\n", 100)
12219
12220 return newParaViewFilter
12221
12222 #phactori_combine_to_single_python_file_subpiece_end_1
12223
12224 #phactori_combine_to_single_python_file_parent_1
12225 #from Operation.PhactoriPlaneSource import *
12226 #phactori_combine_to_single_python_file_subpiece_begin_1
12227
12228 class PhactoriPlaneSource(PhactoriOperationSpecifics):
12229 "Phactori interface to the ParaView Plane Geometric Source. Allows user to\n specify a plane (rectangle) by 3 points in space and a tesselation\n resolution in each dimension of the rectangle"
12230
12231 def __init__(self):
12232 self.PlaneOrigin = [-0.5, -0.5, 0.0]
12233 self.PlanePoint1 = [ 0.5, -0.5, 0.0]
12234 self.PlanePoint2 = [-0.5, 0.5, 0.0]
12235 self.PlaneXResolution = 1
12236 self.PlaneYResolution = 1
12237
12238 def ParseParametersFromJson(self, inJson):
12239 key1 = "origin"
12240 if key1 in inJson:
12241 self.PlaneOrigin = inJson[key1]
12242 try:
12243 if len(self.PlaneOrigin) != 3:
12244 myDebugPrint3AndException(
12245 "PhactoriPlaneSource:ParseParametersFromJson\n"
12246 "bad 'origin', must be 3 number list list [1.1,2.3,-4.5]\n")
12247 except:
12248 myDebugPrint3AndException(
12249 "PhactoriPlaneSource:ParseParametersFromJson\n"
12250 "bad 'origin', must be 3 number list list [1.1,2.3,-4.5]\n")
12251
12252 key1 = "point1"
12253 if key1 in inJson:
12254 self.PlanePoint1 = inJson[key1]
12255 try:
12256 if len(self.PlanePoint1) != 3:
12257 myDebugPrint3AndException(
12258 "PhactoriPlaneSource:ParseParametersFromJson\n"
12259 "bad 'point1', must be 3 number list list [1.1,2.3,-4.5]\n")
12260 except:
12261 myDebugPrint3AndException(
12262 "PhactoriPlaneSource:ParseParametersFromJson\n"
12263 "bad 'point1', must be 3 number list list [1.1,2.3,-4.5]\n")
12264
12265 key1 = "point2"
12266 if key1 in inJson:
12267 self.PlanePoint2 = inJson[key1]
12268 try:
12269 if len(self.PlanePoint2) != 3:
12270 myDebugPrint3AndException(
12271 "PhactoriPlaneSource:ParseParametersFromJson\n"
12272 "bad 'point2', must be 3 number list list [1.1,2.3,-4.5]\n")
12273 except:
12274 myDebugPrint3AndException(
12275 "PhactoriPlaneSource:ParseParametersFromJson\n"
12276 "bad 'point2', must be 3 number list list [1.1,2.3,-4.5]\n")
12277
12278 key1 = "xresolution"
12279 if key1 in inJson:
12280 self.PlaneXResolution = inJson[key1]
12281 if isinstance(self.PlaneXResolution, int):
12282 if self.PlaneXResolution < 1:
12283 myDebugPrint3AndException(
12284 "PhactoriPlaneSource:ParseParametersFromJson\n"
12285 "'xresolution' must be integer >= 1\n")
12286 else:
12287 myDebugPrint3AndException(
12288 "PhactoriPlaneSource:ParseParametersFromJson\n"
12289 "'xresolution' must be integer >= 1\n")
12290
12291 key1 = "yresolution"
12292 if key1 in inJson:
12293 self.PlaneYResolution = inJson[key1]
12294 if isinstance(self.PlaneYResolution, int):
12295 if self.PlaneYResolution < 1:
12296 myDebugPrint3AndException(
12297 "PhactoriPlaneSource:ParseParametersFromJson\n"
12298 "'yresolution' must be integer >= 1\n")
12299 else:
12300 myDebugPrint3AndException(
12301 "PhactoriPlaneSource:ParseParametersFromJson\n"
12302 "'yresolution' must be integer >= 1\n")
12303
12304 def CreateParaViewFilter(self, inInputFilter):
12305 if PhactoriDbg(100):
12306 myDebugPrint3("PhactoriPlaneSource.CreateParaViewFilter entered\n", 100)
12307
12308 savedActiveSource = GetActiveSource()
12309
12310 newParaViewFilter = Plane()
12311
12312 newParaViewFilter.Origin = self.PlaneOrigin
12313 newParaViewFilter.Point1 = self.PlanePoint1
12314 newParaViewFilter.Point2 = self.PlanePoint2
12315 newParaViewFilter.XResolution = self.PlaneXResolution
12316 newParaViewFilter.YResolution = self.PlaneYResolution
12317
12318 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
12319
12320 SetActiveSource(newParaViewFilter)
12321 SetActiveSource(savedActiveSource)
12322
12323 if PhactoriDbg(100):
12324 myDebugPrint3(
12325 "Origin: " + str(newParaViewFilter.Origin) + "\n" + \
12326 "Point1: " + str(newParaViewFilter.Point1) + "\n" + \
12327 "Point2: " + str(newParaViewFilter.Point2) + "\n" + \
12328 "XResolution: " + str(newParaViewFilter.XResolution) + "\n" + \
12329 "YResolution: " + str(newParaViewFilter.YResolution) + "\n")
12330
12331 if PhactoriDbg(100):
12332 myDebugPrint3("PhactoriPlaneSource.CreateParaViewFilter returning\n", 100)
12333
12334 return newParaViewFilter
12335
12336 #phactori_combine_to_single_python_file_subpiece_end_1
12337
12338 #phactori_combine_to_single_python_file_parent_1
12339 #from Operation.PhactoriPointSourceNearbyCorrelator import *
12340 #phactori_combine_to_single_python_file_subpiece_begin_1
12341
12342 class PhactoriPointSourceNearbyCorrelator(PhactoriOperationSpecifics):
12343 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates and creates a new point source from that list. Resulting\n point source will have 1 element an N points. This source is intented\n to work correctly in parallel for Catalyst or pvbatch symmetric mode.\n The json file which is read in will only be read on one process and\n mpi broadcast is used to distribute the list, rather than having each\n process read the json file."
12344 def __init__(self):
12345 self.JsonListFileName = "PhactoriPointSourceFromJsonList.json"
12346 self.JsonList = None
12347 self.NearestDatapointList = None
12348 self.DisplacedPointList = None
12349 self.DisplacementDistance = 0.0
12350 self.ParaviewPointSource = None
12351 self.SourceVtkPolyData = None
12352 self.myVtkPoints = vtk.vtkPoints()
12353 self.myVtkPolyVertex = vtk.vtkPolyVertex()
12354 self.myVtkCellArray = vtk.vtkCellArray()
12355 self.myVtkPolyData = vtk.vtkPolyData()
12356
12357 def ValidateJsonPointList(self):
12358 numPoints = len(self.JsonList)
12359 if numPoints < 1:
12360 myDebugPrint3AndException(
12361 "PhactoriPointSourceFromJsonList::ValidateJsonPointList\n"
12362 "list must have at least one element\n")
12363
12364 for ptNdx in range(0,numPoints):
12365 jsonPt = self.JsonList[ptNdx]
12366 if len(jsonPt) != 3:
12367 errStr = "PhactoriPointSourceFromJsonList::ValidateJsonPointList\n" \
12368 "point with index " + str(ptNdx) + "does not have three elements\n"
12369 myDebugPrint3AndException(errStr)
12370
12371
12372 def ParseParametersFromJson(self, inJson):
12373 if 'filename' in inJson:
12374 self.JsonListFileName = inJson['filename']
12375 else:
12376 myDebugPrint3AndException(
12377 "PhactoriPointSourceFromJsonList::ParseParametersFromJson\n"
12378 "Error: must have 'filename' key\n")
12379
12380 self.DisplacementDistance = getParameterFromBlock(inJson, "absolute displacement", self.DisplacementDistance)
12381
12382 def CalculateNearestPointDistanceSquaredList(self, inSourcePointList, inTargetPointList):
12383 if PhactoriDbg(100):
12384 myDebugPrint3("CalculateNearestPointDistanceSquaredList entered\n")
12385 resultDistancedSquaredList = []
12386 resultClosestTargetIndexList = []
12387 localmaxfloat = sys.float_info.max
12388 if len(inTargetPointList) == 0:
12389 if PhactoriDbg(100):
12390 myDebugPrint3("no points on this process, returning noresult list\n")
12391 for idx in range(0, len(inSourcePointList)):
12392 resultDistancedSquaredList.append(localmaxfloat)
12393 return resultDistancedSquaredList
12394
12395 for srcPnt in inSourcePointList:
12396 if PhactoriDbg(100):
12397 myDebugPrint3("doing point: " + str(srcPnt) + "\n")
12398 tgtPnt = inTargetPointList[0]
12399 closetsDistSqrd = vecDistanceSquared(srcPnt, tgtPnt)
12400 closestIndex = 0
12401 for idx, tgtPnt in enumerate(inTargetPointList):
12402 testDist = vecDistanceSquared(srcPnt, tgtPnt)
12403 if testDist < closetsDistSqrd:
12404 closetsDistSqrd = testDist
12405 closestIndex = idx
12406 if PhactoriDbg(100):
12407 myDebugPrint3("result: " + str(closetsDistSqrd) + " " + str(closestIndex) + "\n")
12408 resultDistancedSquaredList.append(closetsDistSqrd)
12409 resultClosestTargetIndexList.append(closestIndex)
12410 if PhactoriDbg(100):
12411 myDebugPrint3("CalculateNearestPointDistanceSquaredList returning\n")
12412 return resultDistancedSquaredList, resultClosestTargetIndexList
12413
12414 def UseMpiToFindGlobalNearestPointList(self, inTargetPointList, inDistanceSquaredList, inTargetPointIndexList):
12415 if PhactoriDbg(100):
12416 myDebugPrint3("UseMpiToFindGlobalNearestPointList entered\n")
12417 globalMinDistanceSquaredList = UseReduceOnFloatList(inDistanceSquaredList, 1)
12418 myPid = SmartGetLocalProcessId()
12419 numSrcPnts = len(inDistanceSquaredList)
12420 localPidWithClosestPoint = []
12421 for idx in range(0,numSrcPnts):
12422 if inDistanceSquaredList[idx] == globalMinDistanceSquaredList[idx]:
12423 if PhactoriDbg(100):
12424 myDebugPrint3("I match closest " + str(idx) + " " + \
12425 str(inDistanceSquaredList[idx]) + " " + str(myPid) + "\n")
12426 localPidWithClosestPoint.append(myPid)
12427 else:
12428 localPidWithClosestPoint.append(-1)
12429
12430 globalPidWithClosestList = UseReduceOnIntegerList(localPidWithClosestPoint, 0)
12431
12432 localXyzList = []
12433 localNodeIdList = []
12434 for idx in range(0,numSrcPnts):
12435 if globalPidWithClosestList[idx] == myPid:
12436 nearestPt = inTargetPointList[inTargetPointIndexList[idx]]
12437 if PhactoriDbg(100):
12438 myDebugPrint3("I am closest with highest pid " + str(idx) + " " + \
12439 str(inTargetPointIndexList[idx]) + " " + str(myPid) + "\n" + str(nearestPt) + "\n")
12440 localXyzList.append(nearestPt[0])
12441 localXyzList.append(nearestPt[1])
12442 localXyzList.append(nearestPt[2])
12443 localNodeIdList.append(int(nearestPt[3]))
12444 else:
12445 localXyzList.append(0.0)
12446 localXyzList.append(0.0)
12447 localXyzList.append(0.0)
12448 localNodeIdList.append(0)
12449
12450 if PhactoriDbg(100):
12451 myDebugPrint3("localXyzList:\n" + str(localXyzList) + "\nlocalNodIdList:\n" + str(localNodeIdList) + "\n")
12452 globalXyz = UseReduceOnFloatList(localXyzList, 2)
12453 globalNodeId = UseReduceOnIntegerList(localNodeIdList, 2)
12454 if PhactoriDbg(100):
12455 myDebugPrint3("globalXyz:\n" + str(globalXyz) + "\nglobalNodeId:\n" + str(globalNodeId) + "\n")
12456
12457 resultPoints = []
12458 for idx in range(0, numSrcPnts):
12459 xyzIdx = idx*3
12460 resultPoints.append([globalXyz[xyzIdx], globalXyz[xyzIdx+1], globalXyz[xyzIdx+2], globalNodeId[idx]])
12461
12462 if PhactoriDbg(100):
12463 myDebugPrint3("resultPoints:\n" + str(resultPoints) + "\n")
12464
12465 if PhactoriDbg(100):
12466 myDebugPrint3("UseMpiToFindGlobalNearestPointList returning\n")
12467 return resultPoints
12468
12469 def CalculateOneDisplacedPoint(self, srcPt, tgtPt, dispDist):
12470 deltaVec = vecFromAToB(srcPt, tgtPt)
12471 moveVec = vecNormalizeWithSmallCheck(deltaVec, 1e-10, [0.0, 1.0, 0.0])
12472 displacedPoint = vecMultiplyAdd(tgtPt, moveVec, dispDist)
12473 return displacedPoint
12474
12475 def CalculateDisplacedPointList(self):
12476 "take the nearest data point list, move each a displacment amount along\n the vector from the source point to that point to get a set of\n displaced points"
12477 if PhactoriDbg(100):
12478 myDebugPrint3("CalculateDisplacedPointList: " + str(self.DisplacementDistance) + "\n")
12479
12480 if self.DisplacementDistance == 0.0:
12481 self.DisplacedPointList = self.NearestDatapointList
12482 return
12483
12484 self.DisplacedPointList = []
12485 numPts = len(self.JsonList)
12486 for ptNdx in range(0,numPts):
12487 srcPt = self.JsonList[ptNdx]
12488 tgtPt = self.NearestDatapointList[ptNdx]
12489 displacedPt = self.CalculateOneDisplacedPoint(srcPt, tgtPt, self.DisplacementDistance)
12490 self.DisplacedPointList.append(displacedPt)
12491
12492 def FindCorrelatedInputOperationPoints(self, inInputFilter):
12493 "in parallel, using mpi to help, find the nodes from the input filter\n which are closest to the points in self.mJsonPointList, and record the\n 3d location of those points"
12494
12495 #grab local process points
12496 thisProcessPointList = self.mPhactoriOperationBlockOwner.MakeListOfAllPointsAndNodeIdsOnThisProcessFromParaViewFilter(inInputFilter)
12497
12498 #calc local nearest points
12499 nearestPointDistanceSquaredList, targetPointIndexList = self.CalculateNearestPointDistanceSquaredList(self.JsonList, thisProcessPointList)
12500
12501 #use mpi to figure out global closest points
12502 self.NearestDatapointList = self.UseMpiToFindGlobalNearestPointList(thisProcessPointList, nearestPointDistanceSquaredList,
12503 targetPointIndexList)
12504
12505 #get set of points (presumably slightly) displaced from self.NearestDatapointList
12506 self.CalculateDisplacedPointList()
12507
12508 if PhactoriDbg(100):
12509 myDebugPrint3("FindCorrelatedInputOperationPoints result:\nNearest points:\n")
12510 for ndx, sourcePt in enumerate(self.JsonList):
12511 nearestTargetPoint = self.NearestDatapointList[ndx]
12512 distSqrd = vecDistanceSquared(sourcePt, nearestTargetPoint)
12513 distx = math.sqrt(distSqrd)
12514 myDebugPrint3(str(ndx) + ": " + str(sourcePt) + " " + str(distSqrd) + " " + str(distx) + " " + str(self.NearestDatapointList[ndx]) + "\n")
12515 myDebugPrint3("Displaced points:\n")
12516 for ndx, sourcePt in enumerate(self.JsonList):
12517 matchingDisplacedPoint = self.DisplacedPointList[ndx]
12518 distSqrd = vecDistanceSquared(sourcePt, matchingDisplacedPoint)
12519 distx = math.sqrt(distSqrd)
12520 myDebugPrint3(str(ndx) + ": " + str(sourcePt) + " " + str(distSqrd) + " " + str(distx) + " " + str(self.DisplacedPointList[ndx]) + "\n")
12521
12522
12523 def CreateParaViewFilter(self, inInputFilter):
12524 if PhactoriDbg(100):
12525 myDebugPrint3("PhactoriPointSourceFromJsonList.CreateParaViewFilter entered\n", 100)
12526
12527 savedActiveSource = GetActiveSource()
12528
12529 self.JsonList = ReadAndMpiBroadcastJsonFile(self.JsonListFileName)
12530
12531 self.ValidateJsonPointList()
12532
12533 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
12534 self.FindCorrelatedInputOperationPoints(inInputFilter)
12535
12536 numPoints = len(self.DisplacedPointList)
12537 self.myVtkPoints.SetNumberOfPoints(numPoints)
12538 self.myVtkPolyVertex.GetPointIds().SetNumberOfIds(numPoints)
12539
12540 vtkPolyVertPtIds = self.myVtkPolyVertex.GetPointIds()
12541 usePoint = [0.0, 0.0, 0.0]
12542 for ptNdx in range(0,numPoints):
12543 #self.myVtkPoints.SetPoint(ptNdx, self.DisplacedPointList[ptNdx])
12544 jsonPt = self.DisplacedPointList[ptNdx]
12545 usePoint[0] = jsonPt[0]
12546 usePoint[1] = jsonPt[1]
12547 usePoint[2] = jsonPt[2]
12548 self.myVtkPoints.SetPoint(ptNdx, usePoint)
12549 vtkPolyVertPtIds.SetId(ptNdx, ptNdx)
12550
12551 self.myVtkPolyData.SetPoints(self.myVtkPoints)
12552 self.myVtkCellArray.InsertNextCell(self.myVtkPolyVertex)
12553 self.myVtkPolyData.SetVerts(self.myVtkCellArray)
12554
12555 self.ParaviewPointSource = PVTrivialProducer()
12556 self.ParaviewPointSource.GetClientSideObject().SetOutput(self.myVtkPolyData)
12557
12558 SetActiveSource(self.ParaviewPointSource)
12559 SetActiveSource(savedActiveSource)
12560
12561 UpdatePipelineWithCurrentTimeArgument(self.ParaviewPointSource)
12562
12563 if PhactoriDbg(100):
12564 pssfjlcso = self.ParaviewPointSource.GetClientSideObject()
12565 pssfjlodo = pssfjlcso.GetOutputDataObject(0)
12566 myDebugPrint3("pssfjlodo: " + str(pssfjlodo.GetClassName()) + " numcells " + str(pssfjlodo.GetNumberOfCells()) + " numpoints " + str(pssfjlodo.GetNumberOfPoints()) + "\n")
12567
12568 if PhactoriDbg(100):
12569 myDebugPrint3("PhactoriPointSourceFromJsonList.CreateParaViewFilter returning\n", 100)
12570 return self.ParaviewPointSource
12571
12572 #phactori_combine_to_single_python_file_subpiece_end_1
12573
12574 #phactori_combine_to_single_python_file_parent_1
12575 #from Operation.PhactoriSampledCellInfo import *
12576 #phactori_combine_to_single_python_file_subpiece_begin_1
12577
12578 def GetCellTestPoint(theCell):
12579 theCellBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
12580 theCell.GetBounds(theCellBounds)
12581 retXyz = [0.5 * (theCellBounds[0] + theCellBounds[1]),
12582 0.5 * (theCellBounds[2] + theCellBounds[3]),
12583 0.5 * (theCellBounds[4] + theCellBounds[5])]
12584 return retXyz
12585
12586 def localGetCellijk(ii, jj, kk, inInputCsData, myExtent):
12587 #returnCell = inInputCsData.GetCell(ii, jj, kk)
12588 computedIndex = vtk.vtkStructuredData.ComputeCellIdForExtent(myExtent, [ii,jj,kk])
12589 returnCell = inInputCsData.GetCell(computedIndex)
12590 return returnCell
12591
12592 class PhactoriSampledCellInfo:
12593 def __init__(self):
12594 self.cellTestPoint = [0.0,0.0,0.0]
12595 self.pid = -1
12596 self.leafVisitCount = -1
12597 self.ijk = [-1,-1,-1]
12598 self.dataTuple = []
12599 self.index = -1
12600 self.segmentIndex = -1
12601 self.collectionAxis = 2
12602
12603 def ToStr(self):
12604 outStr = "PhactoriSampledCellInfo:\n" +\
12605 "cellTestPoint: " + str(self.cellTestPoint) + "\n" +\
12606 "pid: " + str(self.pid) + "\n" +\
12607 "leafVisitCount: " + str(self.leafVisitCount) + "\n" +\
12608 "ijk: " + str(self.ijk) + "\n" +\
12609 "index: " + str(self.index) + "\n" +\
12610 "segmentIndex: " + str(self.segmentIndex) + "\n" +\
12611 "collectionAxis: " + str(self.collectionAxis) + "\n" +\
12612 "dataTuple: " + str(self.dataTuple) + "\n"
12613 return outStr
12614
12615 def SetFromList(self, newValues):
12616 tripletVal = newValues[0]
12617 self.cellTestPoint[0] = tripletVal[0]
12618 self.cellTestPoint[1] = tripletVal[1]
12619 self.cellTestPoint[2] = tripletVal[2]
12620 tripletVal = newValues[1]
12621 self.ijk[0] = tripletVal[0]
12622 self.ijk[1] = tripletVal[1]
12623 self.ijk[2] = tripletVal[2]
12624 if newValues[2] == None:
12625 self.dataTuple = None
12626 else:
12627 self.dataTuple = list(newValues[2])
12628 self.pid = newValues[3]
12629 self.leafVisitCount = newValues[4]
12630 self.index = newValues[5]
12631 self.segmentIndex = newValues[6]
12632 self.collectionAxis = newValues[7]
12633
12634 def GetAsList(self):
12635 return [self.cellTestPoint, self.ijk, self.dataTuple, self.pid, self.leafVisitCount, self.index, self.segmentIndex, self.collectionAxis]
12636
12637 def ToStrTerseOneLineList(self):
12638 return str(self.GetAsList())
12639 #outStr = "[" + \
12640 # str(self.cellTestPoint) + "," + \
12641 # str(self.ijk) + "," + \
12642 # str(self.dataTuple) + "," + \
12643 # str(self.pid) + "," + \
12644 # str(self.index) + "," + \
12645 # str(self.segmentIndex) + "," + \
12646 # str(self.collectionAxis) + \
12647 # "]"
12648 #return outStr
12649
12650 @staticmethod
12651 def TerseOneLineJsonFormatComment():
12652 outStr = '{"PhactoriSampledCellInfo output format 1 info":[\n' + \
12653 '" [cellTestPoint, ijk, dataTuple, pid, index, segmentIndex, collectionAxis]",\n' + \
12654 '" cellTestPoint is [X, Y, Z], ijk is [i, j, k], dataTuple is [c1, c2, ... cN]"]}'
12655 return outStr
12656
12657 def SetIndex(self, newIndex):
12658 self.index = newIndex
12659
12660 def SetCollectionAxis(self, newCollectionAxis):
12661 self.collectionAxis = newCollectionAxis
12662
12663 def AxisCrossesExtent(self, myExtent, whichAxis):
12664 # i -> 0
12665 # j -> 1
12666 # k -> 2
12667 # ij -> 3
12668 # ik -> 4
12669 # jk -> 5
12670 if whichAxis < 3:
12671 if whichAxis != 0:
12672 if self.ijk[0] < myExtent[0]:
12673 return False
12674 if self.ijk[0] >= myExtent[1]:
12675 return False
12676 if whichAxis != 1:
12677 if self.ijk[1] < myExtent[2]:
12678 return False
12679 if self.ijk[1] >= myExtent[3]:
12680 return False
12681 if whichAxis != 2:
12682 if self.ijk[2] < myExtent[4]:
12683 return False
12684 if self.ijk[2] >= myExtent[5]:
12685 return False
12686 else:
12687 if whichAxis == 3:
12688 if self.ijk[2] < myExtent[4]:
12689 return False
12690 if self.ijk[2] >= myExtent[5]:
12691 return False
12692 if whichAxis == 4:
12693 if self.ijk[1] < myExtent[2]:
12694 return False
12695 if self.ijk[1] >= myExtent[3]:
12696 return False
12697 if whichAxis == 5:
12698 if self.ijk[0] < myExtent[0]:
12699 return False
12700 if self.ijk[0] >= myExtent[1]:
12701 return False
12702 return True
12703
12704 def GetIntersectingCollectionExtent(self, whichExtent, whichAxis):
12705 # i -> 0
12706 # j -> 1
12707 # k -> 2
12708 # ij -> 3
12709 # ik -> 4
12710 # jk -> 5
12711 retext = list(whichExtent)
12712 if self.AxisCrossesExtent(whichExtent, whichAxis) == False:
12713 retExt[1] = retExt[0]
12714 retExt[3] = retExt[2]
12715 retExt[5] = retExt[4]
12716 return retExt
12717 if (whichAxis != 0) and (whichAxis != 3) and (whichAxis != 4):
12718 retext[0] = self.ijk[0]
12719 retext[1] = self.ijk[0] + 1
12720 if (whichAxis != 1) and (whichAxis != 3) and (whichAxis != 5):
12721 retext[2] = self.ijk[1]
12722 retext[3] = self.ijk[1] + 1
12723 if (whichAxis != 2) and (whichAxis != 4) and (whichAxis != 5):
12724 retext[4] = self.ijk[2]
12725 retext[5] = self.ijk[2] + 1
12726 return retext
12727
12728 def SetCellTestPoint(self, inPt):
12729 self.cellTestPoint[0] = inPt[0]
12730 self.cellTestPoint[1] = inPt[1]
12731 self.cellTestPoint[2] = inPt[2]
12732
12733 def SetIjk(self, ii, jj, kk):
12734 self.ijk[0] = ii
12735 self.ijk[1] = jj
12736 self.ijk[2] = kk
12737
12738 def SetDataTuple(self, inDataTuple):
12739 self.dataTuple = list(inDataTuple)
12740
12741 def SerializeAppendToFloatAndIntArray(self, outSerialFloatArray, outSerialIntArray, inTupleSize = 0):
12742 outSerialFloatArray.append(self.cellTestPoint[0])
12743 outSerialFloatArray.append(self.cellTestPoint[1])
12744 outSerialFloatArray.append(self.cellTestPoint[2])
12745 if self.dataTuple != None:
12746 localTupleLen = len(self.dataTuple)
12747 for ii in range(0,inTupleSize):
12748 if ii >= localTupleLen:
12749 outSerialFloatArray.append(0.0)
12750 else:
12751 outSerialFloatArray.append(self.dataTuple[ii])
12752 else:
12753 for ii in range(0,inTupleSize):
12754 outSerialFloatArray.append(0.0)
12755 outSerialIntArray.append(self.pid)
12756 outSerialIntArray.append(self.leafVisitCount)
12757 outSerialIntArray.append(self.ijk[0])
12758 outSerialIntArray.append(self.ijk[1])
12759 outSerialIntArray.append(self.ijk[2])
12760 outSerialIntArray.append(self.segmentIndex)
12761
12762 def SerializeAppendToFloatAndIntArrayZeroVersion(self, outSerialFloatArray, outSerialIntArray, inTupleSize = -1):
12763 outSerialFloatArray.append(0.0)
12764 outSerialFloatArray.append(0.0)
12765 outSerialFloatArray.append(0.0)
12766 if inTupleSize < 0:
12767 for ffval in self.dataTuple:
12768 outSerialFloatArray.append(0.0)
12769 else:
12770 for ffval in range(0, inTupleSize):
12771 outSerialFloatArray.append(0.0)
12772 outSerialIntArray.append(0)
12773 outSerialIntArray.append(0)
12774 outSerialIntArray.append(0)
12775 outSerialIntArray.append(0)
12776 outSerialIntArray.append(0)
12777 outSerialIntArray.append(0)
12778
12779 @staticmethod
12780 def GetSerializeFloatAndIntSize(tupleSize = 0):
12781 floatsize = 3 + tupleSize
12782 intsize = 6
12783 return floatsize, intsize
12784
12785 def SerializeSetFromFloatAndIntArray(self, inSerialFloatArray, inSerialIntArray, inIndex, inTupleSize = 0):
12786 #floatsize, intsize = GetSerializeFloatAndIntSize()
12787 floatsize = 3 + inTupleSize
12788 intsize = 6
12789 floatIndex = floatsize * inIndex
12790 intIndex = intsize * inIndex
12791 self.cellTestPoint[0] = inSerialFloatArray[floatIndex+0]
12792 self.cellTestPoint[1] = inSerialFloatArray[floatIndex+1]
12793 self.cellTestPoint[2] = inSerialFloatArray[floatIndex+2]
12794 self.dataTuple = []
12795 if inTupleSize > 0:
12796 for ii in range(0, inTupleSize):
12797 self.dataTuple.append(inSerialFloatArray[floatIndex+3+ii])
12798 self.pid = inSerialIntArray[intIndex + 0]
12799 self.leafVisitCount = inSerialIntArray[intIndex + 1]
12800 self.ijk[0] = inSerialIntArray[intIndex + 2]
12801 self.ijk[1] = inSerialIntArray[intIndex + 3]
12802 self.ijk[2] = inSerialIntArray[intIndex + 4]
12803 self.segmentIndex = inSerialIntArray[intIndex + 5]
12804
12805 def Populate1(self, ii, jj, kk, myPid, leafVisitCount, seedCellIndex,
12806 inInputCsData, myExtent, numCells, outputCellArray, dataArrayNumCmpnts, defaultTuple):
12807 #used during recursion to set up the cell based on the ii, jj, kk indices
12808 self.SetIjk(ii,jj,kk)
12809 self.pid = myPid
12810 self.leafVisitCount = leafVisitCount
12811 self.segmentIndex = seedCellIndex
12812 #dataCell = inInputCsData.GetCell(ii, jj, kk)
12813 dataCell = localGetCellijk(ii, jj, kk, inInputCsData, myExtent)
12814 cellTestPoint = GetCellTestPoint(dataCell)
12815 self.SetCellTestPoint(cellTestPoint)
12816 cellId = vtk.vtkStructuredData.ComputeCellIdForExtent(myExtent, [ii,jj,kk])
12817 self.SetIndex(cellId)
12818 if dataArrayNumCmpnts > 0:
12819 if (cellId < numCells) and (cellId >= 0):
12820 dataTuple = outputCellArray.GetTuple(cellId)
12821 self.SetDataTuple(dataTuple)
12822 else:
12823 self.SetDataTuple(defaultTuple)
12824
12825 class PhactoriFindCellWithMinMaxDataOnThisProcessRecursionParams:
12826 def __init__(self):
12827 self.leafVisitCount = 0
12828 self.dataArrayName = "noname"
12829 self.minCell = sys.float_info.max
12830 self.maxCell = None
12831 self.dataTotal = 0.0
12832 self.dataCount = 0
12833 self.currentMinVal = sys.float_info.max
12834 self.currentMaxVal = -sys.float_info.max
12835
12836 def SetUpForRecursion(self, cellDataArrayName):
12837 self.dataTotal = 0.0
12838 self.dataCount = 0
12839 self.currentMinVal = sys.float_info.max
12840 self.currentMaxVal = -sys.float_info.max
12841 self.dataArrayName = cellDataArrayName
12842 self.minCell = PhactoriSampledCellInfo()
12843 self.minCell.SetFromList([[0.0,0.0,0.0], [-1,-1,-1], [self.currentMinVal], -1, -1, -1, -1, -1])
12844 self.maxCell = PhactoriSampledCellInfo()
12845 self.maxCell.SetFromList([[0.0,0.0,0.0], [-1,-1,-1], [self.currentMaxVal], -1, -1, -1, -1, -1])
12846
12847 def PhactoriFindCellWithMinMaxDataOnThisProcessInBlock(recursionObject, inInputCsData, inParameters):
12848 if PhactoriDbg(100):
12849 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcessInBlock entered\n")
12850
12851 inParameters.leafVisitCount += 1
12852
12853 numCells = inInputCsData.GetNumberOfCells()
12854 numPoints = inInputCsData.GetNumberOfPoints()
12855 if (numCells == 0) or (numPoints == 0):
12856 if PhactoriDbg(100):
12857 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcessInBlock returning 1\n")
12858 #no cells here
12859 return
12860
12861 cellData = inInputCsData.GetCellData()
12862 if cellData == None:
12863 if PhactoriDbg(100):
12864 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcessInBlock returning 2\n")
12865
12866 outputCellArray = None
12867 outputCellArray = cellData.GetArray(inParameters.dataArrayName)
12868
12869 if outputCellArray == None:
12870 if PhactoriDbg(100):
12871 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcessInBlock returning 3\n")
12872
12873 myPid = SmartGetLocalProcessId()
12874 for cellIndex in range(0,numCells):
12875 thisCellDataTuple = outputCellArray.GetTuple(cellIndex)
12876 cellDataVal = thisCellDataTuple[0]
12877 inParameters.dataTotal += cellDataVal
12878 inParameters.dataCount += 1
12879 if cellDataVal < inParameters.currentMinVal:
12880 inParameters.currentMinVal = cellDataVal
12881 oneCell = inInputCsData.GetCell(cellIndex)
12882 cellTestPoint = GetCellTestPoint(oneCell)
12883 inParameters.minCell.index = cellIndex
12884 inParameters.minCell.dataTuple[0] = cellDataVal
12885 inParameters.minCell.cellTestPoint[0] = cellTestPoint[0]
12886 inParameters.minCell.cellTestPoint[1] = cellTestPoint[1]
12887 inParameters.minCell.cellTestPoint[2] = cellTestPoint[2]
12888 inParameters.minCell.pid = myPid
12889 inParameters.leafVisitCount = inParameters.leafVisitCount
12890 if cellDataVal > inParameters.currentMaxVal:
12891 inParameters.currentMaxVal = cellDataVal
12892 oneCell = inInputCsData.GetCell(cellIndex)
12893 cellTestPoint = GetCellTestPoint(oneCell)
12894 inParameters.currentMinVal = cellDataVal
12895 cellTestPoint = GetCellTestPoint(oneCell)
12896 inParameters.maxCell.index = cellIndex
12897 inParameters.maxCell.dataTuple[0] = cellDataVal
12898 inParameters.maxCell.cellTestPoint[0] = cellTestPoint[0]
12899 inParameters.maxCell.cellTestPoint[1] = cellTestPoint[1]
12900 inParameters.maxCell.cellTestPoint[2] = cellTestPoint[2]
12901 inParameters.maxCell.pid = myPid
12902 inParameters.leafVisitCount = inParameters.leafVisitCount
12903
12904 if PhactoriDbg(100):
12905 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcessInBlock returning\n")
12906
12907 def PhactoriFindCellWithMinMaxDataOnThisProcess(paraviewFilter, cellDataArrayName):
12908 if PhactoriDbg(100):
12909 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcess entered\n" + \
12910 "paraviewFilter: " + str(paraviewFilter) + "\n")
12911
12912 recursionParams = PhactoriFindCellWithMinMaxDataOnThisProcessRecursionParams()
12913 recursionParams.SetUpForRecursion(cellDataArrayName)
12914 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
12915 recursionObj.mParameters = recursionParams
12916 recursionObj.mOperationToDoPerBlock = PhactoriFindCellWithMinMaxDataOnThisProcessInBlock
12917
12918 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, paraviewFilter)
12919 if PhactoriDbg(100):
12920 myDebugPrint3("PhactoriFindCellWithMinMaxDataOnThisProcess returning\n")
12921
12922 return [recursionParams.minCell, recursionParams.maxCell]
12923
12924 def PhactoriFindCellWtihMinMaxDataUsingMPI(paraviewFilter, cellDataArrayName):
12925 if PhactoriDbg(100):
12926 myDebugPrint3("PhactoriFindCellWtihMinMaxDataUsingMPI entered\n" + \
12927 "paraviewFilter: " + str(paraviewFilter) + "\n")
12928
12929 thisPidMinMaxCells = PhactoriFindCellWithMinMaxDataOnThisProcess(paraviewFilter, cellDataArrayName)
12930 globalMinMaxCells = PhactoriLocalToGlobalCellsWithMinMaxDataUsingMPI(thisPidMinMaxCells, 1)
12931
12932 if PhactoriDbg(100):
12933 myDebugPrint3("PhactoriFindCellWtihMinMaxDataUsingMPI returning\n")
12934 return globalMinMaxCells
12935
12936 def PhactoriLocalToGlobalCellsWithMinMaxDataUsingMPI(localPidMinMaxCellPair, tupleSize):
12937
12938 if PhactoriDbg(100):
12939 myDebugPrint3("PhactoriLocalToGlobalCellsWithMinMaxDataUsingMPI entered\n")
12940 #find overall min/max
12941 minVal = localPidMinMaxCellPair[0].dataTuple[0]
12942 maxVal = localPidMinMaxCellPair[1].dataTuple[0]
12943 if PhactoriDbg(100):
12944 myDebugPrint3("local min/max, tupleSize: " + str([minVal, maxVal, tupleSize]) + "\n")
12945 localMinMax = [-minVal, maxVal]
12946 globalMinMax = UseReduceOnFloatList(localMinMax, 0)
12947 globalMinVal = -globalMinMax[0]
12948 globalMaxVal = globalMinMax[1]
12949 if PhactoriDbg(100):
12950 myDebugPrint3("global min/max, tupleSize: " + str([globalMinVal, globalMaxVal, tupleSize]) + "\n")
12951
12952 localPidMinMax = [-1,-1]
12953 myPid = SmartGetLocalProcessId()
12954 if globalMinVal == minVal:
12955 localPidMinMax[0] = myPid
12956 if globalMaxVal == maxVal:
12957 localPidMinMax[1] = myPid
12958
12959 if PhactoriDbg(100):
12960 myDebugPrint3("localPidMinMax: " + str(localPidMinMax) + "\n")
12961 globalPidMinMax = UseReduceOnIntegerList(localPidMinMax, 0)
12962 if PhactoriDbg(100):
12963 myDebugPrint3("globalPidMinMax: " + str(globalPidMinMax) + "\n")
12964
12965 localSerializedFloatArray = []
12966 localSerializedIntArray = []
12967 if globalPidMinMax[0] == myPid:
12968 localPidMinMaxCellPair[0].SerializeAppendToFloatAndIntArray(localSerializedFloatArray, localSerializedIntArray, tupleSize)
12969 else:
12970 localPidMinMaxCellPair[0].SerializeAppendToFloatAndIntArrayZeroVersion(localSerializedFloatArray, localSerializedIntArray, tupleSize)
12971 if globalPidMinMax[1] == myPid:
12972 localPidMinMaxCellPair[1].SerializeAppendToFloatAndIntArray(localSerializedFloatArray, localSerializedIntArray, tupleSize)
12973 else:
12974 localPidMinMaxCellPair[1].SerializeAppendToFloatAndIntArrayZeroVersion(localSerializedFloatArray, localSerializedIntArray, tupleSize)
12975
12976 globalSerializedFloatArray = UseReduceOnFloatList(localSerializedFloatArray, 2)
12977 globalSerializedIntArray = UseReduceOnIntegerList(localSerializedIntArray, 2)
12978
12979 globalMinCell = PhactoriSampledCellInfo()
12980 globalMaxCell = PhactoriSampledCellInfo()
12981 globalMinCell.SerializeSetFromFloatAndIntArray(globalSerializedFloatArray, globalSerializedIntArray, 0, tupleSize)
12982 globalMaxCell.SerializeSetFromFloatAndIntArray(globalSerializedFloatArray, globalSerializedIntArray, 1, tupleSize)
12983
12984 if PhactoriDbg(100):
12985 myDebugPrint3("PhactoriLocalToGlobalCellsWithMinMaxDataUsingMPI returning\n")
12986 return [globalMinCell, globalMaxCell]
12987
12988 #phactori_combine_to_single_python_file_subpiece_end_1
12989
12990 #phactori_combine_to_single_python_file_parent_1
12991 #from Operation.PhactoriPointSourceGeometrySampler1 import *
12992 #phactori_combine_to_single_python_file_subpiece_begin_1
12993
12994 class PhactoriPointSourceGeometrySampler1(PhactoriOperationSpecifics):
12995 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates and creates a new point source from that list. Resulting\n point source will have 1 element an N points. This source is intented\n to work correctly in parallel for Catalyst or pvbatch symmetric mode.\n The json file which is read in will only be read on one process and\n mpi broadcast is used to distribute the list, rather than having each\n process read the json file."
12996 def __init__(self):
12997 self.JsonListFileName = "PhactoriPointSourceGeometrySampler1.json"
12998 self.JsonList = None
12999 self.ParaviewPointSource = None
13000 self.SourceVtkPolyData = None
13001 self.myVtkPoints = vtk.vtkPoints()
13002 self.myVtkPolyVertex = vtk.vtkPolyVertex()
13003 self.myVtkCellArray = vtk.vtkCellArray()
13004 self.myVtkPolyData = vtk.vtkPolyData()
13005 self.NearestQuadList = None
13006 self.DistanceList = None
13007
13008 def ValidateJsonPointList(self):
13009 numPoints = len(self.JsonList)
13010 if numPoints < 1:
13011 myDebugPrint3AndException(
13012 "PhactoriPointSourceGeometrySampler1::ValidateJsonPointList\n"
13013 "list must have at least one element\n")
13014
13015 for ptNdx in range(0,numPoints):
13016 jsonPt = self.JsonList[ptNdx]
13017 if len(jsonPt) != 3:
13018 errStr = "PhactoriPointSourceGeometrySampler1::ValidateJsonPointList\n" \
13019 "point with index " + str(ptNdx) + "does not have three elements\n"
13020 myDebugPrint3AndException(errStr)
13021
13022
13023 def ParseParametersFromJson(self, inJson):
13024 if 'filename' in inJson:
13025 self.JsonListFileName = inJson['filename']
13026 else:
13027 myDebugPrint3AndException(
13028 "PhactoriPointSourceGeometrySampler1::ParseParametersFromJson\n"
13029 "Error: must have 'filename' key\n")
13030
13031 def GetPidWithLeastValueList(self, inLocalDistSqrdList):
13032 myPid = int(SmartGetLocalProcessId())
13033 globalDistSqrdList = UseReduceOnFloatList(inLocalDistSqrdList, 1)
13034 localPidList = []
13035 numItems = len(inLocalDistSqrdList)
13036 for ndx in range(0,numItems):
13037 if globalDistSqrdList[ndx] == inLocalDistSqrdList[ndx]:
13038 localPidList.append(myPid)
13039 else:
13040 localPidList.append(-1)
13041
13042 pidWithDataList = UseReduceOnIntegerList(localPidList, 0)
13043 return pidWithDataList, globalDistSqrdList
13044
13045 def UseMpiToGetGlobalQuadsClosest(self, inLocalQuadList, inLocalDistSqrdList):
13046 if PhactoriDbg(100):
13047 myDebugPrint3("PhactoriPointSourceGeometrySampler1.UseMpiToGetGlobalQuadsClosest entered\n", 100)
13048
13049 pidWithDataList, globalDistSqrdList = self.GetPidWithLeastValueList(inLocalDistSqrdList)
13050 if PhactoriDbg(100):
13051 myDebugPrint3("pidWithDataList:\n" + str(pidWithDataList) + "\nglobalDistSqrdList:\n" + str(globalDistSqrdList) + "\n")
13052
13053 #convert quad list to array of doubles and ints, use mpi reduce to share
13054 #the values, then convert back to quad list
13055
13056 #convert quad list to array of doubles and ints
13057 quadInfoDoubleArray = []
13058 quadInfoIntArray = []
13059 myPid = SmartGetLocalProcessId()
13060 for ii, oneQuad in enumerate(inLocalQuadList):
13061 if pidWithDataList[ii] == myPid:
13062 oneQuad.AddToInfoArrays(quadInfoDoubleArray, quadInfoIntArray)
13063 else:
13064 oneQuad.AddZeroQuadToInfoArrays(quadInfoDoubleArray, quadInfoIntArray)
13065
13066 #use mpi reduce to spread array correctly
13067 globalQuadInfoDoubleArray = UseReduceOnFloatList(quadInfoDoubleArray, 2)
13068 globalQuadInfoIntArray = UseReduceOnIntegerList(quadInfoIntArray, 2)
13069
13070 #now create return global quad list from arrays
13071 numQuads = len(inLocalQuadList)
13072 returnGlobalQuadList = []
13073 for ii in range(0,numQuads):
13074 newQuad = QuadInfoGQC()
13075 newQuad.PopulateFromInfoArrays(ii, globalQuadInfoDoubleArray, globalQuadInfoIntArray)
13076 returnGlobalQuadList.append(newQuad)
13077
13078 if PhactoriDbg(100):
13079 myDebugPrint3("PhactoriPointSourceGeometrySampler1.UseMpiToGetGlobalQuadsClosest returning\n", 100)
13080 return returnGlobalQuadList, globalDistSqrdList
13081
13082 def CreateSamplePoints(self, inInputFilter):
13083 if PhactoriDbg(100):
13084 myDebugPrint3("PhactoriPointSourceGeometrySampler1.CreateSamplePoints entered\n", 100)
13085
13086 thisProcessNearestQuadList, thisProcDistSqrdList = self.mPhactoriOperationBlockOwner.\
13087 GetQuadsClosestToPointsOnThisProcessFromParaViewFilter(inInputFilter, self.JsonList)
13088
13089 if PhactoriDbg(100):
13090 myDebugPrint3("quads before mpi\n", 100)
13091 for ii, oneQuad in enumerate(thisProcessNearestQuadList):
13092 myDebugPrint3(str(ii) + ": " + str(thisProcDistSqrdList[ii]) + "\n" + oneQuad.ToString(), 100)
13093
13094 self.NearestQuadList, self.DistanceList = self.UseMpiToGetGlobalQuadsClosest(
13095 thisProcessNearestQuadList, thisProcDistSqrdList)
13096
13097 if PhactoriDbg(100):
13098 myDebugPrint3("quads after mpi\n", 100)
13099 for ii, oneQuad in enumerate(self.NearestQuadList):
13100 myDebugPrint3(str(ii) + ": " + str(self.NearestQuadList[ii]) + "\n" + oneQuad.ToString(), 100)
13101
13102 if PhactoriDbg(100):
13103 myDebugPrint3("PhactoriPointSourceGeometrySampler1.CreateSamplePoints returning\n", 100)
13104
13105 def CreateParaViewFilter(self, inInputFilter):
13106 if PhactoriDbg(100):
13107 myDebugPrint3("PhactoriPointSourceGeometrySampler1.CreateParaViewFilter entered\n", 100)
13108
13109 savedActiveSource = GetActiveSource()
13110
13111 self.JsonList = ReadAndMpiBroadcastJsonFile(self.JsonListFileName)
13112
13113 self.ValidateJsonPointList()
13114
13115 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
13116 self.CreateSamplePoints(inInputFilter)
13117
13118 allSamplePoints = []
13119 for ii, oneQuad in enumerate(self.NearestQuadList):
13120 #oneQuadSamplePoints = oneQuad.MakePerpendicularSamplePoints()
13121 oneQuadSamplePoints = oneQuad.MakeLogSamplePointsAlongRayFromNearbyPoint(self.JsonList[ii], 0.0000001, 1.414, 0.05)
13122 allSamplePoints.extend(oneQuadSamplePoints)
13123
13124 numPoints = len(allSamplePoints)
13125 self.myVtkPoints.SetNumberOfPoints(numPoints)
13126 self.myVtkPolyVertex.GetPointIds().SetNumberOfIds(numPoints)
13127
13128 vtkPolyVertPtIds = self.myVtkPolyVertex.GetPointIds()
13129 usePoint = [0.0, 0.0, 0.0]
13130 for ptNdx in range(0,numPoints):
13131 #self.myVtkPoints.SetPoint(ptNdx, self.JsonList[ptNdx])
13132 quadPtAvg = allSamplePoints[ptNdx]
13133 usePoint[0] = quadPtAvg[0]
13134 usePoint[1] = quadPtAvg[1]
13135 usePoint[2] = quadPtAvg[2]
13136 self.myVtkPoints.SetPoint(ptNdx, usePoint)
13137 vtkPolyVertPtIds.SetId(ptNdx, ptNdx)
13138
13139 self.myVtkPolyData.SetPoints(self.myVtkPoints)
13140 self.myVtkCellArray.InsertNextCell(self.myVtkPolyVertex)
13141 self.myVtkPolyData.SetVerts(self.myVtkCellArray)
13142
13143 self.ParaviewPointSource = PVTrivialProducer()
13144 self.ParaviewPointSource.GetClientSideObject().SetOutput(self.myVtkPolyData)
13145
13146 SetActiveSource(self.ParaviewPointSource)
13147 SetActiveSource(savedActiveSource)
13148
13149 UpdatePipelineWithCurrentTimeArgument(self.ParaviewPointSource)
13150
13151 if PhactoriDbg(100):
13152 myDebugPrint3("PhactoriPointSourceGeometrySampler1.CreateParaViewFilter returning\n", 100)
13153 return self.ParaviewPointSource
13154
13155 #phactori_combine_to_single_python_file_subpiece_end_1
13156
13157 #phactori_combine_to_single_python_file_parent_1
13158 #from Operation.PhactoriSegmentCellSampler3 import *
13159 #phactori_combine_to_single_python_file_subpiece_begin_1
13160
13161 class GetCellsClosestToPointsInBlockRecursionParams:
13162 def __init__(self):
13163 self.testPointList = []
13164 self.distSqrdList = []
13165 self.closestList = []
13166
13167 def InitializeWithPointList(self, inTestPointList):
13168 self.testPointList = inTestPointList
13169 numTestPoints = len(inTestPointList)
13170 for ii in range(0, numTestPoints):
13171 self.distSqrdList.append(sys.float_info.max)
13172 self.closestList.append(None)
13173
13174 class SetMaskValueForCellsNearSegmentsRecursionParams:
13175 def __init__(self):
13176 self.segmentList = None
13177 self.maskCellVariableName = None
13178 self.globalCellIdName = None
13179 self.CellDataArrayName = "V"
13180 self.markedCellSet = None
13181 self.maskTestDistanceSquared = None
13182 self.projectionAxis = -1
13183 self.leafVisitCount = 0
13184
13185 def Initialize(self, segmentList, cellDataArrayName, maskCellVariableName, globalCellIdName, maskTestDistanceSquared, projectionAxis):
13186 self.CellDataArrayName = cellDataArrayName
13187 self.maskCellVariableName = maskCellVariableName
13188 self.globalCellIdName = globalCellIdName
13189 self.segmentList = segmentList
13190 self.maskTestDistanceSquared = maskTestDistanceSquared
13191 self.markedCellSet = []
13192 self.projectionAxis = projectionAxis
13193 self.leafVisitCount = 0
13194 if PhactoriDbg(100):
13195 myDebugPrint3("SetMaskValueForCellsNearSegmentsRecursionParams::Initialize\n" +\
13196 "self.segmentList:\n" + str(self.segmentList) + "\n")
13197
13198 for oneSegment in self.segmentList:
13199 cellInfoListForThisSegment = []
13200 self.markedCellSet.append(cellInfoListForThisSegment)
13201
13202 class CellsListClosestToPointsListInBlockStructuredRecursionParams:
13203 def __init__(self):
13204 self.testPointList = []
13205 self.distSqrdList = []
13206 self.closestCellList = []
13207 self.leafVisitCount = 0
13208
13209 def InitializeWithPointList(self, inTestPointList):
13210 self.testPointList = inTestPointList
13211 numTestPoints = len(inTestPointList)
13212 self.leafVisitCount = 0
13213 for ii in range(0, numTestPoints):
13214 self.distSqrdList.append(sys.float_info.max)
13215 newCellInfo = PhactoriSampledCellInfo()
13216 self.closestCellList.append(newCellInfo)
13217
13218 class GatherStructuredCellsFromSeedCellsRecursionParams:
13219 def __init__(self):
13220 self.leafVisitCount = 0
13221 self.dataArrayName = "noname"
13222 self.SeedCells = None
13223 self.CellsPerSeedCell = None
13224
13225 def SetUpForRecursion(self, creatingSamplerInstance):
13226 self.SeedCells = creatingSamplerInstance.StructuredNearbyCellPointList
13227 self.dataArrayName = creatingSamplerInstance.CellDataArrayName
13228 self.CellsPerSeedCell = []
13229 for ii in range(0, len(self.SeedCells)):
13230 self.CellsPerSeedCell.append([])
13231
13232 class PhactoriSegmentCellSampler3(PhactoriOperationSpecifics):
13233 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates pairs (representating segments, and then finds all cells\n in the input data that cross that segment and sets a masking value\n into a cell data array for those cells"
13234 def __init__(self):
13235 self.myCopyOfInputFilter = None
13236
13237 #[[[x1,y1],[x2.y2]],[[x3,y3],[x4.y4]],...]
13238 self.JsonSegmentListFileName = "PhactoriSegmentCellSampler3.json"
13239
13240 self.SegmentList = None
13241 #self.MaskTestDistanceSquared = 0.00001
13242 self.MaskTestDistanceSquared = 1.6e-07
13243
13244 self.SegmentDefinitionFormat = "two geometric points"
13245
13246 self.PerSegmentMarkedCellInfoList = []
13247
13248 #indicates whether we should conduct our segment-picking cell calculations
13249 #by projecting onto an ordinal plane. -1 is no projection, 0, 1, or 2 are
13250 #the x, y, or z axes. This is of particular use if you are doing a slice
13251 #before selecting elements. The slice does not need to be axis aligned,
13252 #just choose the axis plane closest to parallel to the slice plane.
13253 self.ProjectionAxis = -1
13254
13255 #as of 2019Aug13, we are having the programmable filter core dump with
13256 #structured data: this allows us to turn off the programmable filter to
13257 #do the other operations
13258 self.DoProgrammableFilterToAddMaskVariable = False
13259 self.mProgFilterMaskSetter = None
13260 self.mProgFilterString = None
13261 self.ProgrammableFilterOutputCellVariableName = "mask1"
13262
13263 self.StructuredNearbyCellPointList = None
13264 self.NearbyGeometryPointList = None
13265
13266 #"structured" or "unstructured"
13267 self.collectionMethod = "segments identify cells"
13268
13269 self.SampledCellsOutputFilename = "PhactoriSegmentCellSampler3_sampled_cells_"
13270 self.SampledCellsOutputDirectory = "PhactoriSegmentCellSampler3_Output"
13271 self.NumCounterDigits = 5
13272 self.SampledCellsOutputFilenameExtension = ".json"
13273
13274 self.CellDataArrayName = "V"
13275 self.CellDataArrayTupleSize = 8
13276
13277 #controls whether or not we output a single json file with a list of all
13278 #the selected cells (using MPI to combine to one process)
13279 self.WriteCellListToJsonFile = True
13280
13281 def ValidateJsonStructuredSeedCellList(self, inJson):
13282 numPoints = len(inJson)
13283 if numPoints < 1:
13284 myDebugPrint3AndException(
13285 "PhactoriSegmentCellSampler3::ValidateJsonStructuredSeedCellList\n"
13286 "list must have at least one seed cell\n")
13287
13288 for ptNdx, onePtJson in enumerate(inJson):
13289 key1 = "geometric seed point"
13290 if key1 not in onePtJson:
13291 myDebugPrint3AndException("point " + str(ptNdx) + " missing '" + key1 + "'\n" + str(inJson) + "\n")
13292 geompt = onePtJson[key1]
13293 if(len(geompt) != 3):
13294 myDebugPrint3AndException("point " + str(ptNdx) + " bad json format for xyz point:\n" + str(inJson) + "\n")
13295 key2 = "collection axis"
13296 if key2 in onePtJson:
13297 axisVal = onePtJson[key2]
13298 if (axisVal != "i") and (axisVal != "j") and (axisVal != "k") and \
13299 (axisVal != "ij") and (axisVal != "ik") and (axisVal != "jk"):
13300 myDebugPrint3AndException(
13301 "point " + str(ptNdx) + " bad json format (2):\n"\
13302 "needs 'i', 'j', 'k', 'ij', 'ik', or 'jk':\n" + str(inJson) + "\n")
13303
13304 return True
13305
13306
13307 def ValidateJsonSegmentList2(self, testlist):
13308 numSegments = len(testlist)
13309 if numSegments < 1:
13310 myDebugPrint3AndException(
13311 "PhactoriSegmentCellSampler3::ValidateJsonSegmentList2\n"
13312 "list must have at least one segment\n")
13313
13314 for segNdx in range(0,numSegments):
13315 oneSegment = testlist[segNdx]
13316 if len(oneSegment) != 2:
13317 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList2\n" \
13318 "segment with index " + str(segNdx) + " does not have a point and a length\n"
13319 myDebugPrint3AndException(errStr)
13320 pt1 = oneSegment[0]
13321 if len(pt1) != 3:
13322 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList2\n" \
13323 "segment with index " + str(segNdx) + " point does not have 3 components\n"
13324 myDebugPrint3AndException(errStr)
13325
13326 return True
13327
13328 def ValidateJsonSegmentList3(self, testlist):
13329 numSegments = len(testlist)
13330 if numSegments < 1:
13331 myDebugPrint3AndException(
13332 "PhactoriSegmentCellSampler3::ValidateJsonSegmentList3\n"
13333 "list must have at least one segment\n")
13334
13335 for segNdx in range(0,numSegments):
13336 oneSegment = testlist[segNdx]
13337 if len(oneSegment) != 3:
13338 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList3\n" \
13339 "segment with index " + str(segNdx) + " does not have a point, direction, and length\n"
13340 myDebugPrint3AndException(errStr)
13341 pt1 = oneSegment[0]
13342 dir1 = oneSegment[1]
13343 length1 = oneSegment[2]
13344 if len(pt1) != 3:
13345 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList3\n" \
13346 "segment with index " + str(segNdx) + " point does not have 3 components\n"
13347 myDebugPrint3AndException(errStr)
13348 if len(dir1) != 3:
13349 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList3\n" \
13350 "segment with index " + str(segNdx) + " direction does not have 3 components\n"
13351 myDebugPrint3AndException(errStr)
13352
13353 return True
13354
13355 def ValidateJsonSegmentList(self, testlist):
13356 numSegments = len(testlist)
13357 if numSegments < 1:
13358 myDebugPrint3AndException(
13359 "PhactoriSegmentCellSampler3::ValidateJsonSegmentList\n"
13360 "list must have at least one segment\n")
13361
13362 for segNdx in range(0,numSegments):
13363 oneSegment = testlist[segNdx]
13364 if len(oneSegment) != 2:
13365 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList\n" \
13366 "segment with index " + str(segNdx) + " does not have two points\n"
13367 myDebugPrint3AndException(errStr)
13368 pt1 = oneSegment[0]
13369 if len(pt1) != 3:
13370 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList\n" \
13371 "segment with index " + str(segNdx) + " point 1 does not have 3 components\n"
13372 myDebugPrint3AndException(errStr)
13373 pt2 = oneSegment[1]
13374 if len(pt1) != 3:
13375 errStr = "PhactoriSegmentCellSampler3:ValidateJsonSegmentList\n" \
13376 "segment with index " + str(segNdx) + " point 2 does not have 3 components\n"
13377 myDebugPrint3AndException(errStr)
13378
13379 return True
13380
13381 def ParseParametersFromJson(self, inJson):
13382 keyval6 = "collection method"
13383 if keyval6 in inJson:
13384 self.collectionMethod = inJson[keyval6]
13385 if (self.collectionMethod != "segments identify cells") and \
13386 (self.collectionMethod != "seed cell with structured grid"):
13387 myDebugPrint3AndException("'collection method' must be one of:\n" \
13388 "'segments identify cells' (default)\n" \
13389 "'seed cell with structured grid'\n")
13390
13391 if "filename" in inJson:
13392 self.JsonListFileName = inJson['filename']
13393 else:
13394 myDebugPrint3AndException(
13395 "PhactoriSegmentCellSampler3:ParseParametersFromJson\n"
13396 "Error: must have 'filename' key\n")
13397
13398 keyval2 = "cell center to segment test distance"
13399 if keyval2 not in inJson:
13400 myDebugPrint3AndException(
13401 "PhactoriSegmentCellSampler3:ParseParametersFromJson\n"
13402 "Error: must have '" + keyval2 + "' key\n")
13403 testDist = inJson[keyval2]
13404 self.MaskTestDistanceSquared = testDist * testDist
13405
13406 if self.collectionMethod == "seed cell with structured grid":
13407 keyval3 = "segment definition format"
13408 if keyval3 in inJson:
13409 myDebugPrint3AndException("with collection method '" + str(self.collectionMethod) + "'\n" \
13410 "you cannot have 'segment definition format' key\n")
13411 else:
13412 keyval3 = "segment definition format"
13413 if keyval3 in inJson:
13414 self.SegmentDefinitionFormat = inJson[keyval3]
13415 if (self.SegmentDefinitionFormat != "two geometric points") and \
13416 (self.SegmentDefinitionFormat != "geometric point and nearest cell") and \
13417 (self.SegmentDefinitionFormat != "structured cell geometric point and length") and \
13418 (self.SegmentDefinitionFormat != "geometric point and nearest cell and direction"):
13419 myDebugPrint3AndException("PhactoriSegmentCellSampler3::ParseParametersFromJson\n"
13420 "bad " + keyval3 + "\n")
13421
13422 keyval4 = "projection axis"
13423 if keyval4 in inJson:
13424 val4 = inJson[keyval4]
13425 if val4 == "none":
13426 self.ProjectionAxis = -1
13427 elif val4 == "x":
13428 self.ProjectionAxis = 0
13429 elif val4 == "y":
13430 self.ProjectionAxis = 1
13431 elif val4 == "z":
13432 self.ProjectionAxis = 2
13433 elif int(val4) == 1:
13434 self.ProjectionAxis = 0
13435 elif int(val4) == 2:
13436 self.ProjectionAxis = 1
13437 elif int(val4) == 3:
13438 self.ProjectionAxis = 2
13439
13440 keyval5 = "do programmable filter"
13441 if keyval5 in inJson:
13442 self.DoProgrammableFilterToAddMaskVariable = inJson[keyval5]
13443
13444 keyval7 = "sampled cells output filename"
13445 if keyval7 in inJson:
13446 self.SampledCellsOutputFilename = inJson[keyval7]
13447
13448 keyval7b = "sampled cells output directory"
13449 if keyval7b in inJson:
13450 self.SampledCellsOutputDirectory = inJson[keyval7b]
13451 if self.SampledCellsOutputDirectory != ".":
13452 CreateDirectoryFromProcessZero(self.SampledCellsOutputDirectory)
13453
13454 keyval7c = "sampled cells output filename digit count"
13455 if keyval7c in inJson:
13456 self.NumCounterDigits = inJson[keyval7c]
13457
13458 keyval7d = "sampled cells output filename extension"
13459 if keyval7d in inJson:
13460 self.SampledCellsOutputFilenameExtension = inJson[keyval7d]
13461
13462 keyval8 = "cell data array name"
13463 if keyval8 in inJson:
13464 self.CellDataArrayName = inJson[keyval8]
13465
13466 keyval9 = "cell data array tuple size"
13467 if keyval9 in inJson:
13468 self.CellDataArrayTupleSize = inJson[keyval9]
13469
13470 keyval10 = "programmable filter output cell variable name"
13471 if keyval10 in inJson:
13472 self.ProgrammableFilterOutputCellVariableName = inJson[keyval10]
13473
13474 keyval11 = "write cell list to json file"
13475 if keyval11 in inJson:
13476 self.WriteCellListToJsonFile = inJson[keyval11]
13477
13478 def SetStructuredNearbyCellPointList(self, nearbyGeometryPoints, structuredNearbyCellPointList):
13479 self.NearbyGeometryPointList = nearbyGeometryPoints
13480 self.StructuredNearbyCellPointList = structuredNearbyCellPointList
13481 #self.SegmentList = []
13482 if PhactoriDbg(100):
13483 myDebugPrint3("(structured) format: " + str(self.SegmentDefinitionFormat) + "\n")
13484 for ii in range(0,len(self.StructuredNearbyCellPointList)):
13485 seedPoint = nearbyGeometryPoints[ii]
13486 segmentPointA = self.StructuredNearbyCellPointList[ii].cellTestPoint
13487 SeedToCell = vecFromAToB(seedPoint, segmentPointA)
13488 #SeedToCellNorm = vecNormalize(SeedToCell)
13489 SeedToCellNorm = vecNormalizeWithSmallCheck(SeedToCell, 0.0, [0.0, 1.0, 0.0])
13490 #segmentPointB = vecMultiplyAdd(segmentPointA, SeedToCellNorm, segmentLengths[ii])
13491 segmentPointB = vecMultiplyAdd(segmentPointA, SeedToCellNorm, 1.0)
13492 if PhactoriDbg(100):
13493 myDebugPrint3("segment " + str(ii) + "\n", 100)
13494 myDebugPrint3("seedPoint: " + str(seedPoint) + "\n")
13495 myDebugPrint3("closest cell point: " + str(segmentPointA) + "\n")
13496 myDebugPrint3("SeedToCellNorm: " + str(SeedToCellNorm) + "\n")
13497 myDebugPrint3("segmentPointB: " + str(segmentPointB) + "\n")
13498 newSegment = PhactoriSegment()
13499 newSegment.SetPoints(segmentPointA, segmentPointB)
13500 #self.SegmentList.append(newSegment)
13501
13502 def CreateInternalStructuredSeedCellListFromJson(self, inJson):
13503 self.ValidateJsonStructuredSeedCellList(inJson)
13504 nearbyGeometryPoints = []
13505 collectionAxes = []
13506 for oneSeedCellJson in inJson:
13507 geometryPoint = oneSeedCellJson["geometric seed point"]
13508 nearbyGeometryPoints.append(list(geometryPoint))
13509 if "collection axis" in oneSeedCellJson:
13510 oneAxis = oneSeedCellJson["collection axis"]
13511 if oneAxis == "i":
13512 axisInt = 0
13513 elif oneAxis == "j":
13514 axisInt = 1
13515 elif oneAxis == "k":
13516 axisInt = 2
13517 elif oneAxis == "ij":
13518 axisInt = 3
13519 elif oneAxis == "ik":
13520 axisInt = 4
13521 elif oneAxis == "jk":
13522 axisInt = 5
13523 else:
13524 axisInt = 2
13525 collectionAxes.append(axisInt)
13526 structuredNearbyCellPointList = self.GetListOfCellTestPointsNearestListOfPointsStructured(nearbyGeometryPoints)
13527 for ii, oneCell in enumerate(structuredNearbyCellPointList):
13528 oneCell.SetCollectionAxis(collectionAxes[ii])
13529 self.SetStructuredNearbyCellPointList(nearbyGeometryPoints, structuredNearbyCellPointList)
13530
13531 def CreateInternalSegmentListFromJson(self, segmentListJson):
13532 if PhactoriDbg(100):
13533 myDebugPrint3("PhactoriSegmentCellSampler3.ExportOperationData entered\n", 100)
13534
13535 if self.SegmentDefinitionFormat == "two geometric points":
13536 self.ValidateJsonSegmentList(segmentListJson)
13537 self.SegmentList = []
13538 self.NearbyGeometryPointList = []
13539 if PhactoriDbg(100):
13540 myDebugPrint3("format: " + str(self.SegmentDefinitionFormat) + "\n")
13541 for item in segmentListJson:
13542 newSegment = PhactoriSegment()
13543 newSegment.SetPoints(item[0], item[1])
13544 self.SegmentList.append(newSegment)
13545 self.NearbyGeometryPointList.append(item[0])
13546 elif self.SegmentDefinitionFormat == "geometric point and nearest cell":
13547 self.ValidateJsonSegmentList2(segmentListJson)
13548 nearbyGeometryPoints = []
13549 segmentLengths = []
13550 for item in segmentListJson:
13551 nearbyGeometryPoints.append(item[0])
13552 segmentLengths.append(item[1])
13553 self.NearbyGeometryPointList = nearbyGeometryPoints
13554
13555 nearbyCellPoints = self.GetListOfCellTestPointsNearestListOfPoints(nearbyGeometryPoints)
13556 #use some vector math to construct the segments from the seed points
13557 #and the nearest cell to each seed point
13558 self.SegmentList = []
13559 if PhactoriDbg(100):
13560 myDebugPrint3("(unstructured) format: " + str(self.SegmentDefinitionFormat) + "\n")
13561 for ii in range(0,len(nearbyGeometryPoints)):
13562 seedPoint = nearbyGeometryPoints[ii]
13563 segmentPointA = nearbyCellPoints[ii]
13564 SeedToCell = vecFromAToB(seedPoint, segmentPointA)
13565 SeedToCellNorm = vecNormalize(SeedToCell)
13566 segmentPointB = vecMultiplyAdd(segmentPointA, SeedToCellNorm, segmentLengths[ii])
13567 if PhactoriDbg(100):
13568 myDebugPrint3("segment " + str(ii) + "\n", 100)
13569 myDebugPrint3("seedPoint: " + str(seedPoint) + "\n")
13570 myDebugPrint3("closest cell point: " + str(segmentPointA) + "\n")
13571 myDebugPrint3("SeedToCellNorm: " + str(SeedToCellNorm) + "\n")
13572 myDebugPrint3("segmentPointB: " + str(segmentPointB) + "\n")
13573 newSegment = PhactoriSegment()
13574 newSegment.SetPoints(segmentPointA, segmentPointB)
13575 self.SegmentList.append(newSegment)
13576 elif self.SegmentDefinitionFormat == "geometric point and nearest cell and direction":
13577 self.ValidateJsonSegmentList3(segmentListJson)
13578 nearbyGeometryPoints = []
13579 segmentLengths = []
13580 directionVecs = []
13581 for item in segmentListJson:
13582 nearbyGeometryPoints.append(item[0])
13583 directionVecs.append(item[1])
13584 segmentLengths.append(item[2])
13585 self.NearbyGeometryPointList = nearbyGeometryPoints
13586
13587 nearbyCellPoints = self.GetListOfCellTestPointsNearestListOfPoints(nearbyGeometryPoints)
13588 self.SegmentList = []
13589 if PhactoriDbg(100):
13590 myDebugPrint3("format: " + str(self.SegmentDefinitionFormat) + "\n")
13591 for ii in range(0,len(nearbyGeometryPoints)):
13592 segmentPointA = nearbyCellPoints[ii]
13593 directionVecNorm = vecNormalize(directionVecs[ii])
13594 segmentPointB = vecMultiplyAdd(segmentPointA, directionVecNorm, segmentLengths[ii])
13595 if PhactoriDbg(100):
13596 myDebugPrint3("seedPoint: " + str(nearbyGeometryPoints[ii]) + "\n")
13597 myDebugPrint3("segmentPointA (nearest cell point): " + str(seedPoint) + "\n")
13598 myDebugPrint3("directionVecNorm: " + str(directionVecNorm) + "\n")
13599 myDebugPrint3("segmentPointB: " + str(segmentPointB) + "\n")
13600 newSegment = PhactoriSegment()
13601 newSegment.SetPoints(segmentPointA, segmentPointB)
13602 self.SegmentList.append(newSegment)
13603 else:
13604 myDebugPrint3AndException("bad self.SegmentDefinitionFormat\n")
13605
13606 if PhactoriDbg(100):
13607 myDebugPrint3("PhactoriSegmentCellSampler3.ExportOperationData returning\n", 100)
13608
13609 def CreateParaViewFilter(self, inInputFilter):
13610 if PhactoriDbg(100):
13611 myDebugPrint3("PhactoriSegmentCellSampler3.CreateParaViewFilter entered\n", 100)
13612
13613 savedActiveSource = GetActiveSource()
13614
13615 segmentListJson = ReadAndMpiBroadcastJsonFile(self.JsonListFileName)
13616
13617 self.myCopyOfInputFilter = inInputFilter
13618
13619 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
13620
13621 if self.collectionMethod == "seed cell with structured grid":
13622 self.CreateInternalStructuredSeedCellListFromJson(segmentListJson)
13623 if PhactoriDbg(100):
13624 myDebugPrint3("self.StructuredNearbyCellPointList:\n", 100)
13625 for ii, oneCell in enumerate(self.StructuredNearbyCellPointList):
13626 outStr = oneCell.ToStr()
13627 myDebugPrint3("cell " + str(ii) + ":\n" + outStr + \
13628 "from geometry point: " + \
13629 str(self.NearbyGeometryPointList[ii]) + "\n")
13630 else:
13631 self.CreateInternalSegmentListFromJson(segmentListJson)
13632 if PhactoriDbg(100):
13633 myDebugPrint3("self.SegmentList:\n", 100)
13634 for oneSeg in self.SegmentList:
13635 myDebugPrint3(str(oneSeg.ptA) + ", " + str(oneSeg.ptB) + "\n")
13636
13637 if self.collectionMethod == "seed cell with structured grid":
13638 perSegmentStructuredCellList = self.GatherStructuredCellsFromSeedCells()
13639 self.PerSegmentMarkedCellInfoList = perSegmentStructuredCellList
13640 else:
13641 perSegmentCellList = self.SetMaskValueForCellsNearSegments(
13642 self.myCopyOfInputFilter, self.SegmentList, "blargmask1", "Ids",
13643 self.MaskTestDistanceSquared, self.ProjectionAxis)
13644 self.PerSegmentMarkedCellInfoList = perSegmentCellList
13645 #UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
13646 #end new work
13647
13648 if self.DoProgrammableFilterToAddMaskVariable:
13649 if PhactoriDbg(100):
13650 myDebugPrint3("cell and point data arrays before filter:\n")
13651 RecursivelyPrintPointAndCellArrayInformation(inInputFilter)
13652 self.mProgFilterMaskSetter = ProgrammableFilter(
13653 Input = self.myCopyOfInputFilter)
13654 self.mProgFilterMaskSetter.CopyArrays = 1
13655 self.CreateProgrammableFilterString()
13656 self.mProgFilterMaskSetter.Script = self.mProgFilterString
13657 self.mProgFilterMaskSetter.UpdatePipeline()
13658 if PhactoriDbg(100):
13659 myDebugPrint3("cell and point data arrays after filter:\n")
13660 RecursivelyPrintPointAndCellArrayInformation(self.mProgFilterMaskSetter)
13661 else:
13662 self.mProgFilterMaskSetter = self.myCopyOfInputFilter
13663
13664 SetActiveSource(savedActiveSource)
13665
13666 if PhactoriDbg(100):
13667 myDebugPrint3("PhactoriSegmentCellSampler3.CreateParaViewFilter returning\n", 100)
13668 return self.mProgFilterMaskSetter
13669
13670 def GetPidWithLeastValueList(self, inLocalDistSqrdList):
13671 myPid = int(SmartGetLocalProcessId())
13672 globalDistSqrdList = UseReduceOnFloatList(inLocalDistSqrdList, 1)
13673 localPidList = []
13674 numItems = len(inLocalDistSqrdList)
13675 for ndx in range(0,numItems):
13676 if globalDistSqrdList[ndx] == inLocalDistSqrdList[ndx]:
13677 localPidList.append(myPid)
13678 else:
13679 localPidList.append(-1)
13680
13681 pidWithDataList = UseReduceOnIntegerList(localPidList, 0)
13682 return pidWithDataList, globalDistSqrdList
13683
13684 def UseMpiToGetGlobalCellPointsClosestStructured(self, ioCellList, inLocalDistSqrdList):
13685 if PhactoriDbg(100):
13686 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosestStructured entered\n", 100)
13687
13688 pidWithDataList, globalDistSqrdList = self.GetPidWithLeastValueList(inLocalDistSqrdList)
13689 if PhactoriDbg(100):
13690 myDebugPrint3("pidWithDataList:\n" + str(pidWithDataList) + "\nglobalDistSqrdList:\n" + str(globalDistSqrdList) + "\n")
13691
13692 if PhactoriDbg(100):
13693 myDebugPrint3("local nearest cell list (ioCellList) before mpi:\n")
13694 for ii, oneCellInfo in enumerate(ioCellList):
13695 myDebugPrint3(str(ii) + ": " + \
13696 str(inLocalDistSqrdList[ii]) + "\n" + \
13697 str(oneCellInfo.cellTestPoint) + "\n" + \
13698 str(oneCellInfo.pid) + "\n" + \
13699 str(oneCellInfo.leafVisitCount) + "\n" + \
13700 str(oneCellInfo.ijk) + "\n")
13701
13702 #convert cell point list to array of doubles and ints, use mpi reduce to share
13703 #the values, then convert back to cell point list
13704 serializeFloatArray = []
13705 serializeIntArray = []
13706 myPid = int(SmartGetLocalProcessId())
13707 for ii, oneCell in enumerate(ioCellList):
13708 if pidWithDataList[ii] == myPid:
13709 oneCell.SerializeAppendToFloatAndIntArray(serializeFloatArray, serializeIntArray)
13710 else:
13711 oneCell.SerializeAppendToFloatAndIntArrayZeroVersion(serializeFloatArray, serializeIntArray)
13712
13713 #use mpi reduce to spread array correctly
13714 globalSerializeFloatArray = UseReduceOnFloatList(serializeFloatArray, 2)
13715 globalSerializeIntArray = UseReduceOnIntegerList(serializeIntArray, 2)
13716
13717 #now create return global cell point list from arrays
13718 for ii, oneCell in enumerate(ioCellList):
13719 oneCell.SerializeSetFromFloatAndIntArray(globalSerializeFloatArray, globalSerializeIntArray, ii)
13720
13721 if PhactoriDbg(100):
13722 myDebugPrint3("global nearest cell list (ioCellList) after mpi:\n")
13723 for ii, oneCellInfo in enumerate(ioCellList):
13724 myDebugPrint3(str(ii) + ": " + \
13725 str(globalDistSqrdList[ii]) + "\n" + \
13726 str(oneCellInfo.cellTestPoint) + "\n" + \
13727 str(oneCellInfo.pid) + "\n" + \
13728 str(oneCellInfo.leafVisitCount) + "\n" + \
13729 str(oneCellInfo.ijk) + "\n")
13730
13731 if PhactoriDbg(100):
13732 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosestStructured returning\n", 100)
13733
13734 return ioCellList, globalDistSqrdList
13735
13736 def UseMpiToGetGlobalCellPointsClosest(self, inLocalCellPointList, inLocalDistSqrdList):
13737 if PhactoriDbg(100):
13738 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest entered\n", 100)
13739
13740 pidWithDataList, globalDistSqrdList = self.GetPidWithLeastValueList(inLocalDistSqrdList)
13741 if PhactoriDbg(100):
13742 myDebugPrint3("pidWithDataList:\n" + str(pidWithDataList) + "\nglobalDistSqrdList:\n" + str(globalDistSqrdList) + "\n")
13743
13744 #convert cell point list to array of doubles and ints, use mpi reduce to share
13745 #the values, then convert back to cell point list
13746 serializeFloatArray = []
13747 serializeIntArray = []
13748
13749 #convert cell point list to array of doubles
13750 cellPointFloatArray = []
13751 myPid = SmartGetLocalProcessId()
13752 for ii, oneCellPoint in enumerate(inLocalCellPointList):
13753 if pidWithDataList[ii] == myPid:
13754 cellPointFloatArray.append(oneCellPoint[0])
13755 cellPointFloatArray.append(oneCellPoint[1])
13756 cellPointFloatArray.append(oneCellPoint[2])
13757 else:
13758 cellPointFloatArray.append(0.0)
13759 cellPointFloatArray.append(0.0)
13760 cellPointFloatArray.append(0.0)
13761
13762 #use mpi reduce to spread array correctly
13763 globalCellPointFloatArray = UseReduceOnFloatList(cellPointFloatArray, 2)
13764
13765 #now create return global cell point list from arrays
13766 numCells = len(inLocalCellPointList)
13767 returnGlobalCellPointList = []
13768 for ii in range(0,numCells):
13769 myndx = ii*3
13770 oneCellPoint = [globalCellPointFloatArray[myndx],
13771 globalCellPointFloatArray[myndx+1],
13772 globalCellPointFloatArray[myndx+2]]
13773 returnGlobalCellPointList.append(oneCellPoint)
13774
13775 if PhactoriDbg(100):
13776 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest returning\n", 100)
13777 return returnGlobalCellPointList, globalDistSqrdList
13778
13779 @staticmethod
13780 def DebugPrintCellPointsFaces(oneCell, cellIndex, inInputCsData):
13781 if not PhactoriDbg(100):
13782 return
13783 myDebugPrint3("cellIndex: " + str(cellIndex) + "\n");
13784 cellPointIds = oneCell.GetPointIds()
13785 numPoints = cellPointIds.GetNumberOfIds()
13786 numFaces = oneCell.GetNumberOfFaces()
13787 myDebugPrint3("numFaces: " + str(numFaces) + " numPoints: " + str(numPoints) + " pointIds: " + str(cellPointIds) + "\n")
13788 for ii in range(0, numFaces):
13789 oneFace = oneCell.GetFace(ii)
13790 facePoints = oneFace.GetPointIds()
13791 myDebugPrint3("face " + str(ii) + ": " + str(facePoints) + "\n")
13792 onePointXyz = [0.0, 0.0, 0.0]
13793 for jj in range(0, facePoints.GetNumberOfIds()):
13794 onePtId = facePoints.GetId(jj)
13795 inInputCsData.GetPoint(onePtId, onePointXyz)
13796 myDebugPrint3(" point " + str(jj) + ": id: " + str(onePtId) + " xyz: " + str(onePointXyz) + "\n")
13797
13798 @staticmethod
13799 def SetMaskValueForCellsNearSegmentsInBlock(recursionObject, inInputCsData, inParameters):
13800 if PhactoriDbg(100):
13801 myDebugPrint3("SetMaskValueForCellsNearSegmentsInBlock entered\n")
13802 inParameters.leafVisitCount += 1
13803 numCells = inInputCsData.GetNumberOfCells()
13804 numPoints = inInputCsData.GetNumberOfPoints()
13805 if (numCells != 0) and (numPoints == 0):
13806 if PhactoriDbg(100):
13807 myDebugPrint3("case where numCells is " + str(numCells) + " and numPoints is 0")
13808 myDebugPrint3("number of cell arrays: " + str(inInputCsData.GetCellData().GetNumberOfArrays()) + "\n")
13809 myDebugPrint3("number of point arrays: " + str(inInputCsData.GetPointData().GetNumberOfArrays()) + "\n")
13810
13811 if (numCells == 0) or (numPoints == 0):
13812 if PhactoriDbg(100):
13813 cellData = inInputCsData.GetCellData()
13814 if cellData != None:
13815 myDebugPrint3("cellData is None, numCells is 0\n")
13816 else:
13817 myDebugPrint3("cellData has " + str(cellData.GetNumberOfArrays()) + " arrays, numCells is 0\n")
13818 if PhactoriDbg(100):
13819 myDebugPrint3("SetMaskValueForCellsNearSegmentsInBlock returning (no cells or no points)\n")
13820 return
13821
13822 cellData = inInputCsData.GetCellData()
13823 maskCellData = cellData.GetArray(inParameters.maskCellVariableName)
13824 #if maskCellData == None:
13825 # maskCellData = cellData.GetArray(inParameters.maskCellVariableName)
13826
13827 globalCellIdData = cellData.GetArray(inParameters.globalCellIdName)
13828 outputCellArray = cellData.GetArray(inParameters.CellDataArrayName)
13829
13830 if PhactoriDbg(100):
13831 myDebugPrint3("numCells \n" + str(numCells) + "\n")
13832 myDebugPrint3("inParameters.segmentList:\n" + str(inParameters.segmentList) + "\n")
13833 myDebugPrint3("cellData: " + str(cellData) + "\n")
13834 myDebugPrint3("maskCellData: " + str(maskCellData) + "\n")
13835 myDebugPrint3("globalCellIdData: " + str(globalCellIdData) + "\n")
13836 #myDebugPrint3("inInputCsData \n" + str(inInputCsData) + "\n")
13837 myDebugPrint3("inInputCsData.GetClassName() \n" + str(inInputCsData.GetClassName()) + "\n")
13838 projectionAxis = inParameters.projectionAxis
13839 leafVisitCount = inParameters.leafVisitCount
13840 myPid = int(SmartGetLocalProcessId())
13841 cellBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
13842 for cellIndex in range(0,numCells):
13843 oneCell = inInputCsData.GetCell(cellIndex)
13844 cellTestPoint = GetCellTestPoint(oneCell)
13845 if maskCellData != None:
13846 maskCellData.SetValue(cellIndex, 0.0)
13847 for segIndex, oneSegment in enumerate(inParameters.segmentList):
13848 cellTestPointToSegmentDistanceSquared = oneSegment.FindDistanceSquaredToPointProjected(cellTestPoint, projectionAxis)
13849 #if PhactoriDbg(100):
13850 # if cellIndex%5000 == 0:
13851 # myDebugPrint3(str(cellIndex) + " " + str(cellTestPointToSegmentDistanceSquared) + " " + str(cellTestPoint) + "\n")
13852 floatSegIndex = float(segIndex) * 5.0
13853 if cellTestPointToSegmentDistanceSquared < inParameters.maskTestDistanceSquared:
13854 #nearestPointOnSegment = oneSegment.FindNearestPointOnSegmentToPointProjected(cellTestPoint, projectionAxis)
13855 #if IsPointInsideCellBoundingBoxProjected(oneCell, nearestPointOnSegment, projectionAxis):
13856 oneCell.GetBounds(cellBounds)
13857 if oneSegment.IntersectsBoundingBoxProjected(cellBounds, projectionAxis):
13858 PhactoriSegmentCellSampler3.DebugPrintCellPointsFaces(oneCell, cellIndex, inInputCsData)
13859 if maskCellData != None:
13860 #warning--if element is near two segments, both will be marked,
13861 #last will win
13862 maskCellData.SetValue(cellIndex, floatSegIndex)
13863 if globalCellIdData != None:
13864 thisCellId = globalCellIdData.GetValue(cellIndex)
13865 else:
13866 thisCellId = None
13867 if outputCellArray == None:
13868 thisCellDataTuple = None
13869 else:
13870 thisCellDataTuple = outputCellArray.GetTuple(cellIndex)
13871 newCellInfo = PhactoriSampledCellInfo()
13872 newCellInfo.SetFromList([cellTestPoint, [-1,-1,-1], thisCellDataTuple, myPid, leafVisitCount, cellIndex, segIndex, -1])
13873
13874 inParameters.markedCellSet[segIndex].append(newCellInfo)
13875 if PhactoriDbg(100):
13876 myDebugPrint3("new cell close to segment:\n")
13877 myDebugPrint3(newCellInfo.ToStr())
13878
13879
13880 if PhactoriDbg(100):
13881 for idx, cellsForThisSegment in enumerate(inParameters.markedCellSet):
13882 myDebugPrint3("after this block cells for segment (index, count): " + str(idx) + ", " + str(len(cellsForThisSegment)) + "\n")
13883 #myDebugPrint3(str(inParameters.markedCellSet[idx]) + "\n")
13884 myDebugPrint3("\n")
13885
13886 if PhactoriDbg(100):
13887 myDebugPrint3("SetMaskValueForCellsNearSegmentsInBlock returning\n")
13888
13889 def SetMaskValueForCellsNearSegments(self,
13890 inputFilter, segmentList, maskCellVariableName, globalCellIdName, maskTestDistanceSquared, projectionAxis):
13891 if PhactoriDbg(100):
13892 myDebugPrint3("SetMaskValueForCellsNearSegments entered\n")
13893 numCellArrays = inputFilter.CellData.GetNumberOfArrays()
13894 myDebugPrint3("numCellArrays: " + str(numCellArrays) + "\n")
13895 for ii in range(0,numCellArrays):
13896 myDebugPrint3(str(inputFilter.CellData.GetArray(ii)) + "\n")
13897 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
13898 recursionObj.mParameters = SetMaskValueForCellsNearSegmentsRecursionParams()
13899 recursionObj.mParameters.Initialize(segmentList, self.CellDataArrayName, maskCellVariableName, globalCellIdName, maskTestDistanceSquared, projectionAxis)
13900 recursionObj.mOperationToDoPerBlock = self.SetMaskValueForCellsNearSegmentsInBlock
13901 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, inputFilter)
13902
13903 #if PhactoriDbg(100):
13904 # myDebugPrint3("SetMaskValueForCellsNearSegments returning\n")
13905 # numCellArrays = inputFilter.CellData.GetNumberOfArrays()
13906 # myDebugPrint3("numCellArrays: " + str(numCellArrays) + "\n")
13907 # for ii in range(0,numCellArrays):
13908 # myDebugPrint3(str(inputFilter.CellData.GetArray(ii)) + "\n")
13909 # UpdatePipelineWithCurrentTimeArgument(inputFilter)
13910 # numCellArrays = inputFilter.CellData.GetNumberOfArrays()
13911 # myDebugPrint3("numCellArrays: " + str(numCellArrays) + "\n")
13912 # for ii in range(0,numCellArrays):
13913 # myDebugPrint3(str(inputFilter.CellData.GetArray(ii)) + "\n")
13914
13915 return recursionObj.mParameters.markedCellSet
13916
13917 @staticmethod
13918 def GetCellsClosestToPointsInBlock(recursionObject, inInputCsData, inParameters):
13919 if PhactoriDbg(100):
13920 myDebugPrint3("GetCellsClosestToPointsInBlock entered\n")
13921 numCells = inInputCsData.GetNumberOfCells()
13922 numPoints = inInputCsData.GetNumberOfPoints()
13923 if (numCells == 0) or (numPoints == 0):
13924 #no cells here
13925 if PhactoriDbg(100):
13926 myDebugPrint3("GetCellsClosestToPointsInBlock returning (no cells or no points)\n")
13927 return
13928
13929 if PhactoriDbg(100):
13930 myDebugPrint3(str(inParameters.testPointList) + "\n")
13931 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
13932
13933 for cellIndex in range(0,numCells):
13934 oneCell = inInputCsData.GetCell(cellIndex)
13935 cellTestPoint = GetCellTestPoint(oneCell)
13936 for ptndx, oneTestPt in enumerate(inParameters.testPointList):
13937 testDist = vecDistanceSquared(oneTestPt, cellTestPoint)
13938 if testDist < inParameters.distSqrdList[ptndx]:
13939 inParameters.closestList[ptndx] = cellTestPoint
13940 inParameters.distSqrdList[ptndx] = testDist
13941
13942 if PhactoriDbg(100):
13943 myDebugPrint3(str(inParameters.testPointList) + "\n")
13944 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
13945
13946 if PhactoriDbg(100):
13947 myDebugPrint3("after this block:\n")
13948 for ii, oneCellPoint in enumerate(inParameters.closestList):
13949 myDebugPrint3(str(ii) + ": " + \
13950 str(inParameters.distSqrdList[ii]) + "\n" + \
13951 str(inParameters.testPointList[ii]) + "\n" + str(oneCellPoint))
13952 myDebugPrint3("\n")
13953
13954 if PhactoriDbg(100):
13955 myDebugPrint3("GetCellsClosestToPointsInBlock returning\n")
13956
13957 def GetCellsClosestToPointsOnThisProcessFromParaViewFilter(self, inTestPointList):
13958 if PhactoriDbg(100):
13959 myDebugPrint3("GetCellsClosestToPointsOnThisProcessFromParaViewFilter entered\n")
13960 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
13961 recursionObj.mParameters = GetCellsClosestToPointsInBlockRecursionParams()
13962 recursionObj.mParameters.InitializeWithPointList(inTestPointList)
13963 recursionObj.mOperationToDoPerBlock = self.GetCellsClosestToPointsInBlock
13964 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.myCopyOfInputFilter)
13965 if PhactoriDbg(100):
13966 myDebugPrint3("GetCellsClosestToPointsOnThisProcessFromParaViewFilter returning\n")
13967 return recursionObj.mParameters.closestList, recursionObj.mParameters.distSqrdList
13968
13969 @staticmethod
13970 def GetCellsListClosestToPointsListInBlockStructured(recursionObject, inInputCsData, inParameters):
13971 if PhactoriDbg(100):
13972 myDebugPrint3("GetCellsListClosestToPointsListInBlockStructured entered\n")
13973 numCells = inInputCsData.GetNumberOfCells()
13974 numPoints = inInputCsData.GetNumberOfPoints()
13975 inParameters.leafVisitCount += 1
13976 if (numCells == 0) or (numPoints == 0):
13977 #no cells here
13978 if PhactoriDbg(100):
13979 myDebugPrint3("GetCellsListClosestToPointsListInBlockStructured returning (no cells or no points)\n")
13980 return
13981
13982 mypid = SmartGetLocalProcessId()
13983 #myExtent = [0,0,0,0,0,0]
13984 myExtent = inInputCsData.GetExtent()
13985 if PhactoriDbg(100):
13986 myDebugPrint3("myExtent: " + str(myExtent) + "\n")
13987 for ii in range(myExtent[0], myExtent[1]):
13988 for jj in range(myExtent[2], myExtent[3]):
13989 for kk in range(myExtent[4], myExtent[5]):
13990 #oneCell = inInputCsData.GetCell(cellIndex)
13991 #oneCell = inInputCsData.GetCell(ii, jj, kk)
13992 oneCell = localGetCellijk(ii, jj, kk, inInputCsData, myExtent)
13993 cellTestPoint = GetCellTestPoint(oneCell)
13994 if PhactoriDbg(100):
13995 if ((ii==myExtent[0]) and (jj == myExtent[2]) and (kk == myExtent[4])):
13996 myDebugPrint3("cellTestPoint " + str([ii,jj,kk]) + " " + str(cellTestPoint) + "\n")
13997 oneCellBounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
13998 oneCell.GetBounds(oneCellBounds)
13999 myDebugPrint3("oneCellBounds " + str([ii,jj,kk]) + " " + str(oneCellBounds) + "\n")
14000 for ptndx, oneTestPt in enumerate(inParameters.testPointList):
14001 testDist = vecDistanceSquared(oneTestPt, cellTestPoint)
14002 if testDist < inParameters.distSqrdList[ptndx]:
14003 inParameters.distSqrdList[ptndx] = testDist
14004 cellInfo = inParameters.closestCellList[ptndx]
14005 cellInfo.pid = mypid
14006 cellInfo.SetCellTestPoint(cellTestPoint)
14007 cellInfo.leafVisitCount = inParameters.leafVisitCount
14008 cellInfo.SetIjk(ii, jj, kk)
14009
14010 if PhactoriDbg(100):
14011 myDebugPrint3(str(inParameters.testPointList) + "\n")
14012 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
14013
14014 if PhactoriDbg(100):
14015 myDebugPrint3("after this block:\n")
14016 for ii, oneCellInfo in enumerate(inParameters.closestCellList):
14017 myDebugPrint3(str(ii) + ": " + \
14018 str(inParameters.distSqrdList[ii]) + "\n" + \
14019 str(inParameters.testPointList[ii]) + "\n" + \
14020 str(oneCellInfo.cellTestPoint) + "\n" + \
14021 str(oneCellInfo.pid) + "\n" + \
14022 str(oneCellInfo.leafVisitCount) + "\n" + \
14023 str(oneCellInfo.ijk) + "\n")
14024 myDebugPrint3("\n")
14025
14026 if PhactoriDbg(100):
14027 myDebugPrint3("GetCellsListClosestToPointsListInBlockStructured returning\n")
14028
14029 def GetListOfCellTestPointsNearestListOfPointsStructured(self, inTestPointList):
14030 if PhactoriDbg(100):
14031 myDebugPrint3("GetListOfCellTestPointsNearestListOfPointsStructured entered\n")
14032 #find the closest structured cells for this process, recursing into
14033 #multiblock dataset
14034 recursionParams = CellsListClosestToPointsListInBlockStructuredRecursionParams()
14035 recursionParams.InitializeWithPointList(inTestPointList)
14036 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
14037 recursionObj.mParameters = recursionParams
14038 recursionObj.mOperationToDoPerBlock = self.GetCellsListClosestToPointsListInBlockStructured
14039 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.myCopyOfInputFilter)
14040
14041 #use mpi to find closest structured cells across all processes
14042 nearestCellList, distanceList = self.UseMpiToGetGlobalCellPointsClosestStructured(
14043 recursionObj.mParameters.closestCellList, recursionObj.mParameters.distSqrdList)
14044
14045 if PhactoriDbg(100):
14046 myDebugPrint3("GetListOfCellTestPointsNearestListOfPointsStructured returning\n")
14047 return nearestCellList
14048
14049 @staticmethod
14050 def GatherStructuredCellsInBlockFromSeedCells(recursionObject, inInputCsData, inParameters):
14051 if PhactoriDbg(100):
14052 myDebugPrint3("GatherStructuredCellsInBlockFromSeedCells entered\n")
14053
14054 numCells = inInputCsData.GetNumberOfCells()
14055 numPoints = inInputCsData.GetNumberOfPoints()
14056 inParameters.leafVisitCount += 1
14057 if (numCells == 0) or (numPoints == 0):
14058 #no cells here
14059 return
14060
14061 cellData = inInputCsData.GetCellData()
14062 outputCellArray = None
14063 if cellData != None:
14064 outputCellArray = cellData.GetArray(inParameters.dataArrayName)
14065
14066 if outputCellArray != None:
14067 dataArrayNumCmpnts = outputCellArray.GetNumberOfComponents()
14068 defaultTuple = []
14069 for ii in range(0, dataArrayNumCmpnts):
14070 defaultTuple.append(-1.0)
14071 else:
14072 dataArrayNumCmpnts = -1
14073 defaultTuple = []
14074
14075 myPid = SmartGetLocalProcessId()
14076 myExtent = inInputCsData.GetExtent()
14077 myDims = inInputCsData.GetDimensions()
14078 if PhactoriDbg(100):
14079 myDebugPrint3("myExtent: " + str(myExtent) + \
14080 "\nmyDims: " + str(myDims) + \
14081 "\nnumCells: " + str(numCells) + "\n")
14082 seedCellList = inParameters.SeedCells
14083 for seedCellIndex, oneSeedCell in enumerate(seedCellList):
14084 if PhactoriDbg(100):
14085 myDebugPrint3("oneSeedCell: " + str(seedCellIndex) + " " + str(oneSeedCell.ijk) + " " + str([oneSeedCell.leafVisitCount, inParameters.leafVisitCount]) + " " + str(myExtent) + "\n")
14086 #is this seed cell in this block?
14087 if oneSeedCell.leafVisitCount != inParameters.leafVisitCount:
14088 if PhactoriDbg(100):
14089 myDebugPrint3("this block is not for this seed cell: " + \
14090 str(oneSeedCell.leafVisitCount) + " " + \
14091 str(inParameters.leafVisitCount) + "\n")
14092 continue
14093 if PhactoriDbg(100):
14094 myDebugPrint3("this block is for this seed cell: " + \
14095 str(oneSeedCell.leafVisitCount) + " " + \
14096 str(inParameters.leafVisitCount) + "\n")
14097 #does this process have any data for this seed cell?
14098 if oneSeedCell.AxisCrossesExtent(myExtent, oneSeedCell.collectionAxis) == False:
14099 if PhactoriDbg(100):
14100 myDebugPrint3("this seed cell not in myExtent: " + str(oneSeedCell.ijk) + "\n")
14101 continue
14102 ijkrange = oneSeedCell.GetIntersectingCollectionExtent(myExtent, oneSeedCell.collectionAxis)
14103 if PhactoriDbg(100):
14104 myDebugPrint3("this block has cells to collect: " + str(ijkrange) + "\n")
14105 #collect all the cells for this seed cell
14106 for ii in range(ijkrange[0], ijkrange[1]):
14107 for jj in range(ijkrange[2], ijkrange[3]):
14108 for kk in range(ijkrange[4], ijkrange[5]):
14109 newStructuredCell = PhactoriSampledCellInfo()
14110 newStructuredCell.Populate1(ii, jj, kk, myPid,
14111 inParameters.leafVisitCount, seedCellIndex, inInputCsData,
14112 myExtent, numCells,
14113 outputCellArray, dataArrayNumCmpnts, defaultTuple)
14114 inParameters.CellsPerSeedCell[seedCellIndex].append(newStructuredCell)
14115
14116 if PhactoriDbg(100):
14117 myDebugPrint3("GatherStructuredCellsInBlockFromSeedCells returning\n")
14118
14119 def GatherStructuredCellsFromSeedCells(self):
14120 "for each structured seed cell in self.StructuredNearbyCellPointList,\n gather cells along one u/v/w direction in the structured data (on this\n process), including the current data for the cells"
14121 if PhactoriDbg(100):
14122 myDebugPrint3("GatherStructuredCellsFromSeedCells entered\n")
14123
14124 #find the closest structured cells for this process, recursing into
14125 #multiblock dataset
14126 recursionParams = GatherStructuredCellsFromSeedCellsRecursionParams()
14127 recursionParams.SetUpForRecursion(self)
14128 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
14129 recursionObj.mParameters = recursionParams
14130 recursionObj.mOperationToDoPerBlock = self.GatherStructuredCellsInBlockFromSeedCells
14131 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.myCopyOfInputFilter)
14132
14133 if PhactoriDbg(100):
14134 myDebugPrint3("GatherStructuredCellsFromSeedCells returning\n")
14135 return recursionParams.CellsPerSeedCell
14136
14137
14138 def GetListOfCellTestPointsNearestListOfPoints(self, pointList):
14139 "for each point in the list, find the cell test point (e.g. center of\n cell bounding box) which is nearest the test point. Use MPI to work\n in parallel"
14140
14141 thisProcessNearestCellPointList, thisProcDistSqrdList = \
14142 self.GetCellsClosestToPointsOnThisProcessFromParaViewFilter(pointList)
14143
14144 nearestCellList, distanceList = self.UseMpiToGetGlobalCellPointsClosest(
14145 thisProcessNearestCellPointList, thisProcDistSqrdList)
14146
14147 return nearestCellList
14148
14149 def WritePerSegmentCellListToFile(self, filename, perSegmentCellList):
14150 ff = open(filename, "w")
14151 if self.collectionMethod == "seed cell with structured grid":
14152 ff.write("{\n")
14153 ff.write('"format for cells in lists": ' + PhactoriSampledCellInfo.TerseOneLineJsonFormatComment() + ",\n")
14154 ff.write('"list of collected cells for each seed cell": [\n')
14155 lastIdx = len(perSegmentCellList) - 1
14156 for idx, cellsForThisSegment in enumerate(perSegmentCellList):
14157 ff.write("{\n")
14158 ff.write('"cells for seed cell index": ' + str(idx) + ',\n')
14159 thisStructuredSeedCell = self.StructuredNearbyCellPointList[idx]
14160 nearbyGeometryPoint = self.NearbyGeometryPointList[idx]
14161 ff.write('"structured seed cell xyz": ' + str(thisStructuredSeedCell.cellTestPoint) + ',\n')
14162 ff.write('"structured seed cell ijk": ' + str(thisStructuredSeedCell.ijk) + ',\n')
14163 ff.write('"structured seed cell complete": ' + thisStructuredSeedCell.ToStrTerseOneLineList() + ',\n')
14164 ff.write('"geometry point used to find seed cell": ' + str(nearbyGeometryPoint) + ',\n')
14165 ff.write('"number of cells collected for this seed cell": ' + str(len(cellsForThisSegment)) + ',\n')
14166 ff.write('"cell list for this seed cell": [\n')
14167 for cellCntr, oneCellInfo in enumerate(cellsForThisSegment):
14168 if cellCntr != 0:
14169 ff.write(",\n")
14170 cellStr = oneCellInfo.ToStrTerseOneLineList()
14171 ff.write(cellStr)
14172 ff.write("\n]\n")
14173 if idx != lastIdx:
14174 ff.write("},\n")
14175 else:
14176 ff.write("}\n")
14177 ff.write("]\n")
14178 ff.write("}\n")
14179 else:
14180 ff.write("{\n")
14181 ff.write('"format for cells in lists": ' + PhactoriSampledCellInfo.TerseOneLineJsonFormatComment() + ",\n")
14182 ff.write('"list of collected cells for each segment": [\n')
14183 lastIdx = len(perSegmentCellList) - 1
14184 for idx, cellsForThisSegment in enumerate(perSegmentCellList):
14185 ff.write("{\n")
14186 ff.write('"cells for segment index": ' + str(idx) + ',\n')
14187 thisSegment = self.SegmentList[idx]
14188 nearbyGeometryPoint = self.NearbyGeometryPointList[idx]
14189 ff.write('"segment point A": ' + str(thisSegment.ptA) + ',\n')
14190 ff.write('"segment point B": ' + str(thisSegment.ptB) + ',\n')
14191 ff.write('"geometry point used to find point A": ' + str(nearbyGeometryPoint) + ',\n')
14192 ff.write('"number of cells collected for this segment": ' + str(len(cellsForThisSegment)) + ',\n')
14193 ff.write('"cell list for this segment": [\n')
14194 for cellCntr, oneCellInfo in enumerate(cellsForThisSegment):
14195 if cellCntr != 0:
14196 ff.write(",\n")
14197 cellStr = oneCellInfo.ToStrTerseOneLineList()
14198 ff.write(cellStr)
14199 ff.write("\n]\n")
14200 if idx != lastIdx:
14201 ff.write("},\n")
14202 else:
14203 ff.write("}\n")
14204 ff.write("]\n")
14205 ff.write("}\n")
14206 ff.close()
14207
14208 def WriteAllDataFromOneProcessUsingMPI(self, perSegmentCellList, basename = "PhactoriSegmentCellSampler3_", outputFilenameCounter = -1):
14209 if PhactoriDbg(100):
14210 myDebugPrint3("PhactoriSegmentCellSampler3.WriteAllDataFromOneProcessUsingMPI entered\n", 100)
14211 myPid = SmartGetLocalProcessId()
14212
14213 ##to start with, just have each process output it's data
14214 if PhactoriDbg(100):
14215 thisProcessHasData = False
14216 for idx, cellsForThisSegment in enumerate(perSegmentCellList):
14217 if len(cellsForThisSegment) != 0:
14218 thisProcessHasData = True
14219 break
14220 if self.collectionMethod == "seed cell with structured grid":
14221 structuredFlag = True
14222 else:
14223 structuredFlag = False
14224 if structuredFlag:
14225 basename = "PhactoriSegmentCellSampler3_structured_"
14226 else:
14227 basename = "PhactoriSegmentCellSampler3_"
14228 fname = basename + str(myPid) + self.SampledCellsOutputFilenameExtension
14229 if thisProcessHasData:
14230 self.WritePerSegmentCellListToFile(fname, perSegmentCellList)
14231
14232 if PhactoriDbg(100):
14233 myDebugPrint3("about to serialize cell infos\n", 100)
14234
14235 tupleSize = self.CellDataArrayTupleSize
14236 cellListSerializedFloatArray = []
14237 cellListSerializedIntArray = []
14238 for idx, cellsForThisSegment in enumerate(perSegmentCellList):
14239 for cellCntr, oneCellInfo in enumerate(cellsForThisSegment):
14240 oneCellInfo.SerializeAppendToFloatAndIntArray(cellListSerializedFloatArray, cellListSerializedIntArray, tupleSize)
14241
14242 if PhactoriDbg(100):
14243 myDebugPrint3("done serializing " + str(len(cellListSerializedFloatArray)) + " " + str(len(cellListSerializedIntArray)) + "\n", 100)
14244
14245 pidToDoOutput = SmartGetNumberOfProcesses() - 1
14246 globalSerializedFloatArray = UseMpiToSendAllProcessesFloatArrayToOneProcess(cellListSerializedFloatArray, pidToDoOutput)
14247 globalSerializedIntArray = UseMpiToSendAllProcessesIntArrayToOneProcess(cellListSerializedIntArray, pidToDoOutput)
14248
14249 if PhactoriDbg(100):
14250 myDebugPrint3("returned from getting globalSerializedFloatArray and globalSerializedIntArray\n")
14251
14252 if myPid == pidToDoOutput:
14253 if PhactoriDbg(100):
14254 myDebugPrint3("I'm the output pid, about to serialize in\n")
14255
14256 serialFloatSize, serialIntSize = PhactoriSampledCellInfo.GetSerializeFloatAndIntSize(tupleSize)
14257 globalNumCells = int(len(globalSerializedFloatArray) / serialFloatSize)
14258
14259 globalPerSegmentCellList = []
14260 if self.collectionMethod == "seed cell with structured grid":
14261 structuredFlag = True
14262 else:
14263 structuredFlag = False
14264 for ii in perSegmentCellList:
14265 globalPerSegmentCellList.append([])
14266 for ii in range(0, globalNumCells):
14267 newCell = PhactoriSampledCellInfo()
14268 newCell.SerializeSetFromFloatAndIntArray(globalSerializedFloatArray, globalSerializedIntArray, ii, tupleSize)
14269 whichSegList = globalPerSegmentCellList[newCell.segmentIndex]
14270 whichSegList.append(newCell)
14271
14272 if PhactoriDbg(100):
14273 myDebugPrint3("finished serialize, about to write to file\n")
14274 if PhactoriDbg(100):
14275 for ii, oneSegmentGlobalCellList in enumerate(globalPerSegmentCellList):
14276 myDebugPrint3(str(ii) + " " + str(len(oneSegmentGlobalCellList)) + "\n")
14277
14278 fname = self.CreateCurrentCallbackCellCollectionOutputFilePath(outputFilenameCounter)
14279 if PhactoriDbg(100):
14280 myDebugPrint3("output filename will be: " + str(fname) + "\n")
14281 self.WritePerSegmentCellListToFile(fname, globalPerSegmentCellList)
14282
14283 if PhactoriDbg(100):
14284 myDebugPrint3("PhactoriSegmentCellSampler3.WriteAllDataFromOneProcessUsingMPI returning\n", 100)
14285
14286 def CreateCurrentCallbackCellCollectionOutputFilePath(self, outputFilenameCounter):
14287 if outputFilenameCounter < 0:
14288 ftc = GetFrameTagCounter()
14289 else:
14290 ftc = outputFilenameCounter
14291
14292 outName = self.SampledCellsOutputDirectory + "/" + \
14293 self.SampledCellsOutputFilename + \
14294 str(ftc).zfill(self.NumCounterDigits) + \
14295 self.SampledCellsOutputFilenameExtension
14296
14297 return outName
14298
14299 def WriteAllDataFromOneProcessUsingMPIStructured(self, perSegmentCellList, outputFilenameCounter = -1):
14300 self.WriteAllDataFromOneProcessUsingMPI(perSegmentCellList, "PhactoriSegmentCellSampler3_structured_", outputFilenameCounter)
14301
14302 def ExportOperationData(self, datadescription):
14303 if PhactoriDbg(100):
14304 myDebugPrint3("PhactoriSegmentCellSampler3.ExportOperationData entered\n", 100)
14305
14306 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
14307
14308 if self.collectionMethod == "seed cell with structured grid":
14309 perSegmentStructuredCellList = self.GatherStructuredCellsFromSeedCells()
14310 if self.WriteCellListToJsonFile:
14311 self.WriteAllDataFromOneProcessUsingMPIStructured(perSegmentStructuredCellList)
14312 else:
14313 perSegmentCellList = self.SetMaskValueForCellsNearSegments(
14314 self.myCopyOfInputFilter, self.SegmentList, "blargmask1", "Ids",
14315 self.MaskTestDistanceSquared, self.ProjectionAxis)
14316
14317 if PhactoriDbg(100):
14318 for idx, cellsForThisSegment in enumerate(perSegmentCellList):
14319 myDebugPrint3("after recursion cells for segment (index, count): " + str(idx) + ", " + str(len(cellsForThisSegment)) + "\n")
14320 #myDebugPrint3(str(cellsForThisSegment) + "\n")
14321 myDebugPrint3("\n")
14322
14323 if self.WriteCellListToJsonFile:
14324 self.WriteAllDataFromOneProcessUsingMPI(perSegmentCellList)
14325
14326 if PhactoriDbg(100):
14327 myDebugPrint3("PhactoriSegmentCellSampler3.ExportOperationData returning\n", 100)
14328
14329 def CreateProgrammableFilterString(self):
14330
14331 scriptLines = []
14332
14333 scriptLines.append("#print('test2')\n")
14334
14335 scriptLines.append("#cellIndexesToSet = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n")
14336 scriptLines.append("#maskValuesToSet = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]\n")
14337 scriptLines.append("#leafVisitCount = [0,0,0,0,0,0,0,0,0,0,0]\n")
14338
14339 scriptLines.append("localLeafVisitCount = 0\n")
14340
14341 scriptLines.append("def flatten(input, output):\n")
14342 scriptLines.append(" # Copy the cells etc.\n")
14343 scriptLines.append(" output.ShallowCopy(input)\n")
14344 scriptLines.append(" celldata = output.GetCellData()\n")
14345 scriptLines.append(" #for now if there are no cell arrays here we don't want to add one\n")
14346 scriptLines.append(" #really we don't want to add one of there are actually no cells\n")
14347 scriptLines.append(" numCellArrays = celldata.GetNumberOfArrays()\n")
14348 scriptLines.append(" if numCellArrays == 0:\n")
14349 scriptLines.append(" return\n")
14350 scriptLines.append(" numCells = input.GetNumberOfCells()\n")
14351 scriptLines.append(" numPoints = input.GetNumberOfPoints()\n")
14352 scriptLines.append(" #print(str(numCells))\n")
14353 scriptLines.append(" ncda = vtk.vtkDoubleArray()\n")
14354 scriptLines.append(" ncda.SetNumberOfTuples(numCells)\n")
14355 scriptLines.append(" numTuples = ncda.GetNumberOfTuples()\n")
14356 scriptLines.append(" for ii in range(0, numTuples):\n")
14357 scriptLines.append(" ncda.SetValue(ii, 0.0)\n")
14358 scriptLines.append(" for ii, cellNdx in enumerate(cellIndexesToSet):\n")
14359 scriptLines.append(" if localLeafVisitCount == leafVisitCount[ii]:\n")
14360 scriptLines.append(" if cellNdx < numCells:\n")
14361 scriptLines.append(" ncda.SetValue(cellNdx, float(maskValuesToSet[ii]))\n")
14362 scriptLines.append(" ncda.SetName('" + self.ProgrammableFilterOutputCellVariableName + "')\n")
14363 scriptLines.append(" #print(ncda.GetName())\n")
14364 scriptLines.append(" celldata.AddArray(ncda)\n")
14365
14366 scriptLines.append("input = self.GetInputDataObject(0, 0)\n")
14367 scriptLines.append("output = self.GetOutputDataObject(0)\n")
14368
14369 scriptLines.append("if input.IsA('vtkMultiBlockDataSet'):\n")
14370 scriptLines.append(" output.CopyStructure(input)\n")
14371 scriptLines.append(" iter = input.NewIterator()\n")
14372 scriptLines.append(" iter.UnRegister(None)\n")
14373 scriptLines.append(" iter.InitTraversal()\n")
14374 scriptLines.append(" while not iter.IsDoneWithTraversal():\n")
14375 scriptLines.append(" localLeafVisitCount += 1\n")
14376 scriptLines.append(" curInput = iter.GetCurrentDataObject()\n")
14377 scriptLines.append(" curOutput = curInput.NewInstance()\n")
14378 scriptLines.append(" curOutput.UnRegister(None)\n")
14379 scriptLines.append(" output.SetDataSet(iter, curOutput)\n")
14380 scriptLines.append(" flatten(curInput, curOutput)\n")
14381 scriptLines.append(" iter.GoToNextItem();\n")
14382 scriptLines.append("else:\n")
14383 scriptLines.append(" flatten(input, output)\n")
14384
14385 mainScriptString = "".join(scriptLines)
14386
14387 myCellIndexesToSet = []
14388 myMaskValuesToSet = []
14389 myLeafVisitCount = []
14390 if self.PerSegmentMarkedCellInfoList != None:
14391 for idx, cellsForThisSegment in enumerate(self.PerSegmentMarkedCellInfoList):
14392 if cellsForThisSegment != None:
14393 maskValue = idx+1
14394 for cellIdx, oneCellInfo in enumerate(cellsForThisSegment):
14395 myCellIndexesToSet.append(oneCellInfo.index)
14396 myMaskValuesToSet.append(maskValue)
14397 myLeafVisitCount.append(oneCellInfo.leafVisitCount)
14398
14399 newstr1 = "cellIndexesToSet = " + str(myCellIndexesToSet) + "\n"
14400 newstr2 = "maskValuesToSet = " + str(myMaskValuesToSet) + "\n"
14401 newstr3 = "leafVisitCount = " + str(myLeafVisitCount) + "\n"
14402 self.mProgFilterString = newstr1 + newstr2 + newstr3 + mainScriptString
14403
14404 if PhactoriDbg(100):
14405 myDebugPrint3("PhactoriMarkCellSetsOperation constructed script:\n" + \
14406 self.mProgFilterString)
14407
14408 #phactori_combine_to_single_python_file_subpiece_end_1
14409
14410 #phactori_combine_to_single_python_file_parent_1
14411 #from Operation.PhactoriGeometricCellSampler1 import *
14412 #phactori_combine_to_single_python_file_subpiece_begin_1
14413
14414
14415 class GatherGeometricallySampledCellsRecursionParams:
14416 def __init__(self):
14417 self.leafVisitCount = 0
14418 self.dataArrayNames = ["noname"]
14419 self.boundingBox = [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]
14420 self.CellsMeetingGeometricCriteria = []
14421
14422 def CellTestPointMeetsGeometricCriteria(self, cellTestPoint):
14423 if cellTestPoint[0] < self.boundingBox[0]:
14424 return False
14425 if cellTestPoint[0] > self.boundingBox[1]:
14426 return False
14427 if cellTestPoint[1] < self.boundingBox[2]:
14428 return False
14429 if cellTestPoint[1] > self.boundingBox[3]:
14430 return False
14431 if cellTestPoint[2] < self.boundingBox[4]:
14432 return False
14433 if cellTestPoint[2] > self.boundingBox[5]:
14434 return False
14435 return True
14436
14437 def SetUpForRecursion(self, creatingSamplerInstance):
14438 self.dataArrayNames = creatingSamplerInstance.CellDataArrayNames
14439 self.boundingBox = creatingSamplerInstance.SamplingGeometryBoundingBox
14440
14441 class CollectDataOnSampledCellsRecursionParams:
14442 def __init__(self):
14443 self.leafVisitCount = 0
14444 self.dataArrayNames = ["noname"]
14445 self.GeometricallySampledCellsByRecursionLeaf = None
14446
14447 def SetUpForRecursion(self, creatingSamplerInstance):
14448 self.dataArrayNames = creatingSamplerInstance.CellDataArrayNames
14449 self.GeometricallySampledCellsByRecursionLeaf = creatingSamplerInstance.GeometricallySampledCellsByRecursionLeaf
14450
14451
14452 def localGetCellijk(ii, jj, kk, inInputCsData, myExtent):
14453 #returnCell = inInputCsData.GetCell(ii, jj, kk)
14454 computedIndex = vtk.vtkStructuredData.ComputeCellIdForExtent(myExtent, [ii,jj,kk])
14455 returnCell = inInputCsData.GetCell(computedIndex)
14456 return returnCell
14457
14458 class PhactoriGeometricCellSampler1(PhactoriOperationSpecifics):
14459 "Filter/operation which reads in a .json file which is a list of 3d\n coordinates pairs (representating segments, and then finds all cells\n in the input data that cross that segment and sets a masking value\n into a cell data array for those cells"
14460 def __init__(self):
14461 self.myCopyOfInputFilter = None
14462
14463 #indicates whether we should conduct our segment-picking cell calculations
14464 #by projecting onto an ordinal plane. -1 is no projection, 0, 1, or 2 are
14465 #the x, y, or z axes. This is of particular use if you are doing a slice
14466 #before selecting elements. The slice does not need to be axis aligned,
14467 #just choose the axis plane closest to parallel to the slice plane.
14468 self.ProjectionAxis = -1
14469
14470 #as of 2019Aug13, we are having the programmable filter core dump with
14471 #structured data: this allows us to turn off the programmable filter to
14472 #do the other operations
14473 self.DoProgrammableFilterToAddMaskVariable = False
14474 self.mProgFilterMaskSetter = None
14475 self.mProgFilterString = None
14476 self.ProgrammableFilterOutputCellVariableName = "mask1"
14477 self.mainScriptString = None
14478
14479 self.WriteOutGeometricallySampledCellData = True
14480 self.GeometricSampledCellOutputFilePathManager = PhactoriOutputFileNameAndDirectoryManager(
14481 "PhactoriGeometricCellSampler1_geometric_",
14482 "PhactoriGeometricCellSampler1_Output", 5, ".csv")
14483
14484 self.WriteOutDataControlledSampledCellData = True
14485 self.DataControlledSampledCellOutputFilePathManager = PhactoriOutputFileNameAndDirectoryManager(
14486 "PhactoriGeometricCellSampler1_data_controlled_",
14487 "PhactoriGeometricCellSampler1_Output", 5, ".csv")
14488
14489 self.CellDataArrayNames = ["V"]
14490 self.CellDataArrayTupleSize = 8
14491
14492 self.SamplingGeometryBoundingBox = [-0.5, 0.5, -0.5, 0.5, -0.5, 0.5]
14493 self.GeometricallySampledCellsForThisProcess = None
14494 self.GeometricallySampledCellsByRecursionLeaf = None
14495
14496 self.DoPerCallbackDataControlledSampling = True
14497 self.DataControlledSampledCellsForThisProcess = None
14498 self.DataControlledSamplingMethod = "cells with ratio of min/max data value"
14499 #self.DataControlledSamplingMethod = "cells within distance of min/max highest data value cell"
14500 #self.DataControlledSamplingMethod = "cells within bounding box around min/max highest data value cell"
14501 self.DataControlledRatioBasis = "ratio is from zero to data maximum"
14502 #self.DataControlledRatioBasis = "ratio is from data minimum to data maximum"
14503 self.DataControlledRatio = 0.75
14504 self.DataControlledRatioGreaterOrLess = "cells greater/equal"
14505 #self.DataControlledRatioGreaterOrLess = "cells less/equal"
14506 #self.RatioBasis = "data range based"
14507 self.DataControlledDistance = 0.1
14508 self.DataControlledUseMinOrMax = "max"
14509 self.DataControlledBoundingBox = [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]
14510
14511 def CheckBoundingBox(self, boundingBox, parsekey, infoString):
14512 goodFlag = True
14513 if len(boundingBox) != 6:
14514 myDebugPrint3AndException(infoString + "\n"
14515 "bounding box is invalid for key: " + parseKey + "\n"
14516 "must be six float list, like:\n"
14517 "[-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]\n")
14518 if (boundingBox[0] > boundingBox[1]) or \
14519 (boundingBox[2] > boundingBox[3]) or \
14520 (boundingBox[4] > boundingBox[5]):
14521 myDebugPrint3AndException(infoString + "\n"
14522 "bounding box is invalid for key: " + parseKey + "\n"
14523 "we need max >= min for each axis, like:\n"
14524 "[-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]\n")
14525
14526 def ParseParametersFromJson(self, inJson):
14527 #if "filename" in inJson:
14528 # self.JsonListFileName = inJson['filename']
14529 #else:
14530 # myDebugPrint3AndException(
14531 # "PhactoriGeometricCellSampler1:ParseParametersFromJson\n"
14532 # "Error: must have 'filename' key\n")
14533
14534 keyval1 = "sampling geometry bounding box"
14535 if keyval1 in inJson:
14536 newBB = inJson[keyval1]
14537 self.CheckBoundingBox(newBB, keyval1,
14538 "PhactoriGeometricCellSampler1:ParseParametersFromJson")
14539 self.SamplingGeometryBoundingBox = newBB
14540
14541 keyval4 = "projection axis"
14542 if keyval4 in inJson:
14543 val4 = inJson[keyval4]
14544 if val4 == "none":
14545 self.ProjectionAxis = -1
14546 elif val4 == "x":
14547 self.ProjectionAxis = 0
14548 elif val4 == "y":
14549 self.ProjectionAxis = 1
14550 elif val4 == "z":
14551 self.ProjectionAxis = 2
14552 elif int(val4) == 1:
14553 self.ProjectionAxis = 0
14554 elif int(val4) == 2:
14555 self.ProjectionAxis = 1
14556 elif int(val4) == 3:
14557 self.ProjectionAxis = 2
14558
14559 keyval5 = "do programmable filter"
14560 if keyval5 in inJson:
14561 self.DoProgrammableFilterToAddMaskVariable = inJson[keyval5]
14562
14563 self.GeometricSampledCellOutputFilePathManager.ParseOutputFileNameControl(
14564 inJson, "geometric sampled cell output file ")
14565
14566 self.DataControlledSampledCellOutputFilePathManager.ParseOutputFileNameControl(
14567 inJson, "data controlled sampled cell output file ")
14568
14569 keyval7e = "export geometric sampled cell data as json file"
14570 if keyval7e in inJson:
14571 self.WriteOutGeometricallySampledCellData = inJson[keyval7e]
14572
14573 keyval7f = "export data controlled sampled cell data as json file"
14574 if keyval7f in inJson:
14575 self.WriteOutDataControlledSampledCellData = inJson[keyval7f]
14576
14577 keyval8 = "cell data array names"
14578 if keyval8 in inJson:
14579 self.CellDataArrayNames = inJson[keyval8]
14580
14581 keyval9 = "cell data array tuple size"
14582 if keyval9 in inJson:
14583 self.CellDataArrayTupleSize = inJson[keyval9]
14584
14585 keyval10 = "programmable filter output cell variable name"
14586 if keyval10 in inJson:
14587 self.ProgrammableFilterOutputCellVariableName = inJson[keyval10]
14588
14589 keyval11 = "data controlled sampling method"
14590 if keyval11 in inJson:
14591 self.DataControlledSamplingMethod = inJson[keyval11]
14592 if self.DataControlledSamplingMethod == "cells within distance of min/max highest data value cell":
14593 keyval11b = "data controlled distance"
14594 if keyval11b not in inJson:
14595 myDebugPrint3AndException("must have 'data controlled distance'\n")
14596 self.DataControlledDistance = inJson[keyval11b]
14597 elif self.DataControlledSamplingMethod == "cells with ratio of min/max data value":
14598 keyval11b = "data controlled ratio of min/max"
14599 if keyval11b in inJson:
14600 self.DataControlledRatio = inJson[keyval11b]
14601 if (self.DataControlledRatio < 0.0) or (self.DataControlledRatio > 1.0):
14602 myDebugPrint3AndException("'data controlled ratio of min/max must be in range [0.0, 1.0]\n")
14603 if PhactoriDbg(100):
14604 myDebugPrint3("self.DataControlledRatio set to " + str(self.DataControlledRatio) + "\n", 100)
14605 keyval11c = "data controlled ratio basis"
14606 if keyval11c in inJson:
14607 self.DataControlledRatioBasis = inJson[keyval11c]
14608 if (self.DataControlledRatioBasis != "ratio is from zero to data maximum") and \
14609 (self.DataControlledRatioBasis != "ratio is from data minimum to data maximum"):
14610 myDebugPrint3("bad 'data controlled ratio basis'\n"
14611 "must be one of:\n"
14612 "'ratio is from zero to data maximum'\n"
14613 "'ratio is from data minimum to data maximum'\n")
14614 keyval11d = "collect cells relative to ratio"
14615 if keyval11d in inJson:
14616 self.DataControlledRatioGreaterOrLess = inJson[keyval11d]
14617 if (self.DataControlledRatioGreaterOrLess != "cells greater/equal") and \
14618 (self.DataControlledRatioGreaterOrLess != "cells less/equal"):
14619 myDebugPrint3("bad 'collect cells relative to ratio'\n"
14620 "must be one of:\n"
14621 "'cells greater/equal'\n"
14622 "'cells less/equal'\n")
14623 elif self.DataControlledSamplingMethod == "cells within bounding box around min/max highest data value cell":
14624 keyval11b = "data controlled bounding box"
14625 if keyval11b in inJson:
14626 self.DataControlledBoundingBox = inJson[keyval11b]
14627 self.CheckBoundingBox(self.DataControlledBoundingBox, keyval11b,
14628 "PhactoriGeometricCellSampler1:ParseParametersFromJson")
14629 else:
14630 myDebugPrint3AndException("bad 'data controlled sampling method'\n")
14631 if PhactoriDbg(100):
14632 myDebugPrint3("self.DataControlledSamplingMethod set to " + \
14633 str(self.DataControlledSamplingMethod) + "\n", 100)
14634
14635 keyval11c = "data controlled sampling use min or max"
14636 if keyval11c in inJson:
14637 if inJson[keyval11c] == "max":
14638 self.DataControlledUseMinOrMax = "max"
14639 else:
14640 self.DataControlledUseMinOrMax = "min"
14641
14642 def CreateParaViewFilter(self, inInputFilter):
14643 if PhactoriDbg(100):
14644 myDebugPrint3("PhactoriGeometricCellSampler1.CreateParaViewFilter entered\n", 100)
14645
14646 savedActiveSource = GetActiveSource()
14647
14648 self.myCopyOfInputFilter = inInputFilter
14649
14650 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
14651
14652 self.CreateInternalListOfGeometricallySampledCellsOnThisProcess()
14653 self.CreateInternalListOfDataControlledSampledCellsOnThisProcess()
14654
14655 if self.DoProgrammableFilterToAddMaskVariable:
14656 self.mProgFilterMaskSetter = ProgrammableFilter(
14657 Input = self.myCopyOfInputFilter)
14658 self.mProgFilterMaskSetter.CopyArrays = 1
14659 self.CreateProgrammableFilterString()
14660 self.mProgFilterMaskSetter.Script = self.mProgFilterString
14661 self.mProgFilterMaskSetter.UpdatePipeline()
14662 else:
14663 self.mProgFilterMaskSetter = self.myCopyOfInputFilter
14664
14665 SetActiveSource(savedActiveSource)
14666
14667 if PhactoriDbg(100):
14668 myDebugPrint3("PhactoriGeometricCellSampler1.CreateParaViewFilter returning\n", 100)
14669 return self.mProgFilterMaskSetter
14670
14671 @staticmethod
14672 def GatherGeometricallySampledCellsInBlock(recursionObject, inInputCsData, inParameters):
14673 if PhactoriDbg(100):
14674 myDebugPrint3("GatherGeometricallySampledCellsInBlock entered\n")
14675
14676 numCells = inInputCsData.GetNumberOfCells()
14677 numPoints = inInputCsData.GetNumberOfPoints()
14678 inParameters.leafVisitCount += 1
14679 if (numCells == 0) or (numPoints == 0):
14680 #no cells here
14681 return
14682
14683 cellData = inInputCsData.GetCellData()
14684 outputCellArrays = []
14685 dataArrayNumCmpnts = 0
14686 if cellData != None:
14687 for oneDataArrayName in inParameters.dataArrayNames:
14688 oneCellDataArray = cellData.GetArray(oneDataArrayName)
14689 outputCellArrays.append(oneCellDataArray)
14690 if oneCellDataArray != None:
14691 dataArrayNumCmpnts += oneCellDataArray.GetNumberOfComponents()
14692 if PhactoriDbg(100):
14693 myDebugPrint3("inParameters.dataArrayNames: " + str(inParameters.dataArrayNames) + "\n")
14694 for oneCellDataArray in outputCellArrays:
14695 if oneCellDataArray == None:
14696 myDebugPrint3("None\n")
14697 else:
14698 myDebugPrint3(str(oneCellDataArray.GetNumberOfTuples()) + "\n")
14699
14700 if dataArrayNumCmpnts != 0:
14701 defaultTuple = []
14702 for ii in range(0, dataArrayNumCmpnts):
14703 defaultTuple.append(-1.0)
14704 else:
14705 dataArrayNumCmpnts = -1
14706 defaultTuple = []
14707
14708 myPid = SmartGetLocalProcessId()
14709 for cellIndex in range(0,numCells):
14710 oneCell = inInputCsData.GetCell(cellIndex)
14711 cellTestPoint = GetCellTestPoint(oneCell)
14712 if inParameters.CellTestPointMeetsGeometricCriteria(cellTestPoint):
14713 if dataArrayNumCmpnts == 0:
14714 thisCellDataTuple = defaultTuple
14715 else:
14716 thisCellDataTuple = []
14717 for oneCellDataArray in outputCellArrays:
14718 if oneCellDataArray != None:
14719 dataTupleSub1 = oneCellDataArray.GetTuple(cellIndex)
14720 thisCellDataTuple.extend(dataTupleSub1)
14721 newCellInfo = PhactoriSampledCellInfo()
14722 newCellInfo.SetFromList([cellTestPoint, [-1,-1,-1], thisCellDataTuple, myPid, inParameters.leafVisitCount, cellIndex, -1, -1])
14723 inParameters.CellsMeetingGeometricCriteria.append(newCellInfo)
14724
14725
14726 if PhactoriDbg(100):
14727 myDebugPrint3("GatherGeometricallySampledCellsInBlock returning\n")
14728
14729 def CreateInternalListOfGeometricallySampledCellsOnThisProcess(self):
14730 if PhactoriDbg(100):
14731 myDebugPrint3("CreateInternalListOfGeometricallySampledCellsOnThisProcess entered\n")
14732
14733 recursionParams = GatherGeometricallySampledCellsRecursionParams()
14734 recursionParams.SetUpForRecursion(self)
14735 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
14736 recursionObj.mParameters = recursionParams
14737 recursionObj.mOperationToDoPerBlock = self.GatherGeometricallySampledCellsInBlock
14738
14739 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.myCopyOfInputFilter)
14740 if PhactoriDbg(100):
14741 myDebugPrint3("CreateInternalListOfGeometricallySampledCellsOnThisProcess returning\n")
14742
14743 self.GeometricallySampledCellsForThisProcess = recursionParams.CellsMeetingGeometricCriteria
14744 self.CreateLeafRecursionTrackingStructure()
14745
14746 def PointIsInsideBoundingBox(self, testPoint, testBoundingBox):
14747 if testPoint[0] < testBoundingBox[0]:
14748 return False
14749 if testPoint[0] > testBoundingBox[1]:
14750 return False
14751 if testPoint[1] < testBoundingBox[2]:
14752 return False
14753 if testPoint[1] > testBoundingBox[3]:
14754 return False
14755 if testPoint[2] < testBoundingBox[4]:
14756 return False
14757 if testPoint[2] > testBoundingBox[5]:
14758 return False
14759 return True
14760
14761 def CreateInternalListOfDataControlledSampledCellsOnThisProcess(self):
14762 if PhactoriDbg(100):
14763 myDebugPrint3("CreateInternalListOfDataControlledSampledCellsOnThisProcess entered\n")
14764
14765 if self.DoPerCallbackDataControlledSampling == False:
14766 self.DataControlledSampledCellsForThisProcess = self.GeometricallySampledCellsForThisProcess
14767 if PhactoriDbg(100):
14768 myDebugPrint3("CreateInternalListOfDataControlledSampledCellsOnThisProcess returning (no processing)\n")
14769 return
14770
14771 self.DataControlledSampledCellsForThisProcess = []
14772
14773 #find min/max cell this process
14774 currentMax = -sys.float_info.max
14775 currentMin = sys.float_info.max
14776 if len(self.GeometricallySampledCellsForThisProcess) >= 1:
14777 for ii, oneCell in enumerate(self.GeometricallySampledCellsForThisProcess):
14778 testVal = oneCell.dataTuple[0]
14779 if testVal > currentMax:
14780 localMaxCell = oneCell
14781 currentMax = testVal
14782 if testVal < currentMin:
14783 localMinCell = oneCell
14784 currentMin = testVal
14785 else:
14786 myPid = SmartGetLocalProcessId()
14787 defaultDataTuple = []
14788 for ii in range(0, self.CellDataArrayTupleSize):
14789 defaultDataTuple.append(0.0)
14790 localMinCell = PhactoriSampledCellInfo()
14791 defaultDataTuple[0] = currentMax
14792 localMinCell.SetFromList([[0.0,0.0,0.0], [-1,-1,-1], defaultDataTuple, myPid, -1, -1, -1, -1])
14793 localMaxCell = PhactoriSampledCellInfo()
14794 defaultDataTuple[0] = currentMin
14795 localMaxCell.SetFromList([[0.0,0.0,0.0], [-1,-1,-1], defaultDataTuple, myPid, -1, -1, -1, -1])
14796
14797 if PhactoriDbg(100):
14798 myDebugPrint3("localMinCell:\n" + localMinCell.ToStrTerseOneLineList() + "\n")
14799 myDebugPrint3("localMaxCell:\n" + localMaxCell.ToStrTerseOneLineList() + "\n")
14800 #find min/max cell all processes
14801 globalMinMaxCellPair = PhactoriLocalToGlobalCellsWithMinMaxDataUsingMPI([localMinCell, localMaxCell], self.CellDataArrayTupleSize)
14802 if PhactoriDbg(100):
14803 myDebugPrint3("globalMinCell:\n" + globalMinMaxCellPair[0].ToStrTerseOneLineList() + "\n")
14804 myDebugPrint3("globalMaxCell:\n" + globalMinMaxCellPair[1].ToStrTerseOneLineList() + "\n")
14805 myDebugPrint3("self.DataControlledSamplingMethod: " + self.DataControlledSamplingMethod + "\n")
14806
14807 if self.DataControlledSamplingMethod == "cells with ratio of min/max data value":
14808 if self.DataControlledRatioBasis == "ratio is from zero to data maximum":
14809 maxCell = globalMinMaxCellPair[1]
14810 thresholdValue = self.DataControlledRatio * maxCell.dataTuple[0]
14811 if PhactoriDbg(100):
14812 myDebugPrint3("ratio is from zero to data maximum: " + str(maxCell.dataTuple[0]) + \
14813 ", " + str(self.DataControlledRatio) + "\n")
14814 else:
14815 minCell = globalMinMaxCellPair[0]
14816 maxCell = globalMinMaxCellPair[1]
14817 minValue = minCell.dataTuple[0]
14818 maxValue = maxCell.dataTuple[0]
14819 minMaxRange = maxValue - minValue
14820 thresholdValue = minValue + self.DataControlledRatio * minMaxRange
14821 if PhactoriDbg(100):
14822 myDebugPrint3("ratio is from data minimum to data maximum: " + str(minValue) + ", " + \
14823 str(maxValue) + ", " + str(minMaxRange) + ", " + \
14824 str(self.DataControlledRatio) + "\n")
14825 if PhactoriDbg(100):
14826 myDebugPrint3("thresholdValue: " + str(thresholdValue) + "\n")
14827 if self.DataControlledRatioGreaterOrLess == "cells greater/equal":
14828 for ii, oneCell in enumerate(self.GeometricallySampledCellsForThisProcess):
14829 if oneCell.dataTuple[0] >= thresholdValue:
14830 self.DataControlledSampledCellsForThisProcess.append(oneCell)
14831 else:
14832 for ii, oneCell in enumerate(self.GeometricallySampledCellsForThisProcess):
14833 if oneCell.dataTuple[0] <= thresholdValue:
14834 self.DataControlledSampledCellsForThisProcess.append(oneCell)
14835 if PhactoriDbg(100):
14836 myDebugPrint3("number of cells out of how many got sampled: " + \
14837 str(len(self.DataControlledSampledCellsForThisProcess)) + ", " + \
14838 str(len(self.GeometricallySampledCellsForThisProcess)) + "\n")
14839 elif self.DataControlledSamplingMethod == "cells within distance of min/max highest data value cell":
14840 if PhactoriDbg(100):
14841 myDebugPrint3("doing distance test: " + \
14842 str(self.DataControlledUseMinOrMax) + ", " + \
14843 str(self.DataControlledDistance) + "\n")
14844 if self.DataControlledUseMinOrMax == "max":
14845 centerCellPoint = globalMinMaxCellPair[1].cellTestPoint
14846 else:
14847 centerCellPoint = globalMinMaxCellPair[0].cellTestPoint
14848 if PhactoriDbg(100):
14849 myDebugPrint3("centerCellPoint: " + str(centerCellPoint) + "\n")
14850 for ii, oneCell in enumerate(self.GeometricallySampledCellsForThisProcess):
14851 cellDistance = vecDistance(centerCellPoint, oneCell.cellTestPoint)
14852 if cellDistance <= self.DataControlledDistance:
14853 self.DataControlledSampledCellsForThisProcess.append(oneCell)
14854 elif self.DataControlledSamplingMethod == "cells within bounding box around min/max highest data value cell":
14855 if PhactoriDbg(100):
14856 myDebugPrint3("doing bounding box test: " + \
14857 str(self.DataControlledUseMinOrMax) + ", " + \
14858 str(self.DataControlledBoundingBox) + "\n")
14859 if self.DataControlledUseMinOrMax == "max":
14860 centerCellPoint = globalMinMaxCellPair[1].cellTestPoint
14861 else:
14862 centerCellPoint = globalMinMaxCellPair[0].cellTestPoint
14863 if PhactoriDbg(100):
14864 myDebugPrint3("centerCellPoint: " + str(centerCellPoint) + "\n")
14865 testBoundingBox = [
14866 centerCellPoint[0] + self.DataControlledBoundingBox[0],
14867 centerCellPoint[0] + self.DataControlledBoundingBox[1],
14868 centerCellPoint[1] + self.DataControlledBoundingBox[2],
14869 centerCellPoint[1] + self.DataControlledBoundingBox[3],
14870 centerCellPoint[2] + self.DataControlledBoundingBox[4],
14871 centerCellPoint[2] + self.DataControlledBoundingBox[5]
14872 ]
14873 for ii, oneCell in enumerate(self.GeometricallySampledCellsForThisProcess):
14874 if self.PointIsInsideBoundingBox(oneCell.cellTestPoint, testBoundingBox):
14875 self.DataControlledSampledCellsForThisProcess.append(oneCell)
14876 else:
14877 myDebugPrint3AndException("CreateInternalListOfDataControlledSampledCellsOnThisProcess:\n" +\
14878 "bad self.DataControlledSamplingMethod\n")
14879
14880
14881 if PhactoriDbg(100):
14882 myDebugPrint3("CreateInternalListOfDataControlledSampledCellsOnThisProcess returning\n")
14883
14884 #self.CreateLeafRecursionTrackingStructure()
14885
14886 @staticmethod
14887 def CollectDataOnSampledCellsInBlock(recursionObject, inInputCsData, inParameters):
14888 if PhactoriDbg(100):
14889 myDebugPrint3("CollectDataOnSampledCellsInBlock entered 1\n")
14890
14891 inParameters.leafVisitCount += 1
14892
14893 if inParameters.GeometricallySampledCellsByRecursionLeaf == None:
14894 #no cells collected for sampling on this process
14895 if PhactoriDbg(100):
14896 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 1\n")
14897 return
14898
14899 if inParameters.leafVisitCount not in inParameters.GeometricallySampledCellsByRecursionLeaf:
14900 #no cells collected for sampling on this block on this process
14901 if PhactoriDbg(100):
14902 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 2\n")
14903 return
14904
14905 numCells = inInputCsData.GetNumberOfCells()
14906 numPoints = inInputCsData.GetNumberOfPoints()
14907 if (numCells == 0) or (numPoints == 0):
14908 #no cells here
14909 if PhactoriDbg(100):
14910 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 3\n")
14911 return
14912
14913 cellData = inInputCsData.GetCellData()
14914 if cellData == None:
14915 if PhactoriDbg(100):
14916 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 4\n")
14917 return
14918
14919 testDataCellArray = None
14920 testDataCellArray = cellData.GetArray(inParameters.dataArrayNames[0])
14921
14922 if testDataCellArray == None:
14923 if PhactoriDbg(100):
14924 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 5\n")
14925 return
14926
14927 outputCellArrays = []
14928 dataArrayNumCmpnts = 0
14929 if cellData != None:
14930 for oneDataArrayName in inParameters.dataArrayNames:
14931 oneCellDataArray = cellData.GetArray(oneDataArrayName)
14932 outputCellArrays.append(oneCellDataArray)
14933 if oneCellDataArray != None:
14934 dataArrayNumCmpnts += oneCellDataArray.GetNumberOfComponents()
14935 if PhactoriDbg(100):
14936 myDebugPrint3("inParameters.dataArrayNames: " + str(inParameters.dataArrayNames) + "\n")
14937 for oneCellDataArray in outputCellArrays:
14938 if oneCellDataArray == None:
14939 myDebugPrint3("None\n")
14940 else:
14941 myDebugPrint3(str(oneCellDataArray.GetNumberOfTuples()) + "\n")
14942
14943 if dataArrayNumCmpnts != 0:
14944 defaultTuple = []
14945 for ii in range(0, dataArrayNumCmpnts):
14946 defaultTuple.append(-1.0)
14947 else:
14948 dataArrayNumCmpnts = -1
14949 defaultTuple = []
14950
14951 myPid = SmartGetLocalProcessId()
14952
14953 sampleCellList = inParameters.GeometricallySampledCellsByRecursionLeaf[inParameters.leafVisitCount]
14954 if PhactoriDbg(100):
14955 myDebugPrint3("num cells, leaf: " + str(len(sampleCellList)) + ", " + str(inParameters.leafVisitCount) + "\n")
14956 for oneSampleCell in sampleCellList:
14957 #thisCellDataTuple = outputCellArray.GetTuple(oneSampleCell.index)
14958 if dataArrayNumCmpnts == 0:
14959 thisCellDataTuple = defaultTuple
14960 else:
14961 thisCellDataTuple = []
14962 for oneCellDataArray in outputCellArrays:
14963 if oneCellDataArray != None:
14964 dataTupleSub1 = oneCellDataArray.GetTuple(oneSampleCell.index)
14965 thisCellDataTuple.extend(dataTupleSub1)
14966 tupleCount = min(len(thisCellDataTuple), len(oneSampleCell.dataTuple))
14967 if PhactoriDbg(100):
14968 myDebugPrint3(str(oneSampleCell.index) + ", " + str(thisCellDataTuple) + ", " + str(tupleCount) + "\n")
14969 for ii in range(0, tupleCount):
14970 oneSampleCell.dataTuple[ii] = thisCellDataTuple[ii]
14971
14972 if PhactoriDbg(100):
14973 myDebugPrint3("CollectDataOnSampledCellsInBlock returning 6\n")
14974
14975 def CollectDataOnSampledCellsOnThisProcess(self):
14976 "go through existing list of cells for this process, and get the data\n value for the current time into each cell sample instance"
14977 if PhactoriDbg(100):
14978 myDebugPrint3("CollectDataOnSampledCellsOnThisProcess entered\n")
14979
14980 recursionParams = CollectDataOnSampledCellsRecursionParams()
14981 recursionParams.SetUpForRecursion(self)
14982 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
14983 recursionObj.mParameters = recursionParams
14984 recursionObj.mOperationToDoPerBlock = self.CollectDataOnSampledCellsInBlock
14985
14986 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.myCopyOfInputFilter)
14987 if PhactoriDbg(100):
14988 myDebugPrint3("CollectDataOnSampledCellsOnThisProcess returning\n")
14989
14990 def CreateLeafRecursionTrackingStructure(self):
14991 if PhactoriDbg(100):
14992 myDebugPrint3("CreateLeafRecursionTrackingStructure entered\n")
14993
14994 if len(self.GeometricallySampledCellsForThisProcess) <= 0:
14995 self.GeometricallySampledCellsByRecursionLeaf = None
14996 if PhactoriDbg(100):
14997 myDebugPrint3("CreateLeafRecursionTrackingStructure returning (no cells)\n")
14998 return
14999
15000 self.GeometricallySampledCellsByRecursionLeaf = {}
15001 for oneCell in self.GeometricallySampledCellsForThisProcess:
15002 leafVal = oneCell.leafVisitCount
15003 if leafVal not in self.GeometricallySampledCellsByRecursionLeaf:
15004 self.GeometricallySampledCellsByRecursionLeaf[leafVal] = []
15005 listForLeaf = self.GeometricallySampledCellsByRecursionLeaf[leafVal]
15006 listForLeaf.append(oneCell)
15007
15008 if PhactoriDbg(100):
15009 for leafKey in self.GeometricallySampledCellsByRecursionLeaf:
15010 cellListForLeaf = self.GeometricallySampledCellsByRecursionLeaf[leafKey]
15011 myDebugPrint3(str(len(cellListForLeaf)) + " cells for leaf " + str(leafKey) + "\n")
15012
15013 if PhactoriDbg(100):
15014 myDebugPrint3("CreateLeafRecursionTrackingStructure returning\n")
15015
15016 def WriteCellListToFile(self, filename, cellList):
15017
15018 sumTuple = []
15019 for ii in range(0, self.CellDataArrayTupleSize):
15020 sumTuple.append(0.0)
15021 for oneCellInfo in cellList:
15022 dataTuple = oneCellInfo.dataTuple
15023 for ii in range(0, self.CellDataArrayTupleSize):
15024 sumTuple[ii] += dataTuple[ii]
15025 floatCellCount = float(len(cellList))
15026 averageTuple = []
15027 for oneItem in sumTuple:
15028 averageTuple.append(oneItem / floatCellCount)
15029
15030 ff = open(filename, "w")
15031 ff.write("{\n")
15032 ff.write('"format for cells in lists": ' + PhactoriSampledCellInfo.TerseOneLineJsonFormatComment() + ",\n")
15033 ff.write('"sampling geometry bounding box": ' + str(self.SamplingGeometryBoundingBox) + ",\n")
15034 ff.write('"number of cells": ' + str(len(cellList)) + ",\n")
15035 ff.write('"cell variable names": ')
15036 ff.write('[')
15037 lastIndex = len(self.CellDataArrayNames) - 1
15038 for ii, oneArrayName in enumerate(self.CellDataArrayNames):
15039 if ii != lastIndex:
15040 ff.write('"' + str(oneArrayName) + '", ')
15041 else:
15042 ff.write('"' + str(oneArrayName) + '"')
15043 ff.write('],\n')
15044 ff.write('"data tuple size": ' + str(self.CellDataArrayTupleSize) + ",\n")
15045 ff.write('"sum variable values": ' + str(sumTuple) + ",\n")
15046 ff.write('"average variable values": ' + str(averageTuple) + ",\n")
15047 ff.write('"list of sampled cells": [\n')
15048 for cellCntr, oneCellInfo in enumerate(cellList):
15049 if cellCntr != 0:
15050 ff.write(",\n")
15051 cellStr = oneCellInfo.ToStrTerseOneLineList()
15052 ff.write(cellStr)
15053 ff.write("]\n")
15054 ff.write("}\n")
15055
15056 ff.close()
15057
15058 def GatherSampledCellDataFromAllProcessesUsingMPI(self, thisProcessCellList):
15059 if PhactoriDbg(100):
15060 myDebugPrint3("PhactoriGeometricCellSampler1.GatherSampledCellDataFromAllProcessesUsingMPI entered\n", 100)
15061
15062 myPid = SmartGetLocalProcessId()
15063
15064 ##to start with, just have each process output it's data
15065 if PhactoriDbg(100):
15066 thisProcessHasData = False
15067 if thisProcessCellList != None:
15068 if len(thisProcessCellList) != 0:
15069 basename = "PhactoriGeometricCellSampler1_oneprocess_" + str(myPid) + ".json"
15070 self.WriteCellListToFile(pidfname, thisProcessCellList)
15071
15072 if PhactoriDbg(100):
15073 myDebugPrint3("about to serialize cell infos\n", 100)
15074
15075 tupleSize = self.CellDataArrayTupleSize
15076 cellListSerializedFloatArray = []
15077 cellListSerializedIntArray = []
15078 for idx, oneCellInfo in enumerate(thisProcessCellList):
15079 oneCellInfo.SerializeAppendToFloatAndIntArray(cellListSerializedFloatArray, cellListSerializedIntArray, tupleSize)
15080
15081 if PhactoriDbg(100):
15082 myDebugPrint3("done serializing " + str(len(cellListSerializedFloatArray)) + " " + str(len(cellListSerializedIntArray)) + "\n", 100)
15083
15084 pidToDoOutput = SmartGetNumberOfProcesses() - 1
15085 globalSerializedFloatArray = UseMpiToSendAllProcessesFloatArrayToOneProcess(cellListSerializedFloatArray, pidToDoOutput)
15086 globalSerializedIntArray = UseMpiToSendAllProcessesIntArrayToOneProcess(cellListSerializedIntArray, pidToDoOutput)
15087
15088 if PhactoriDbg(100):
15089 myDebugPrint3("returned from getting globalSerializedFloatArray and globalSerializedIntArray\n")
15090
15091 globalCellList = []
15092 if myPid == pidToDoOutput:
15093 if PhactoriDbg(100):
15094 myDebugPrint3("I'm the output pid, about to serialize in\n")
15095
15096 serialFloatSize, serialIntSize = PhactoriSampledCellInfo.GetSerializeFloatAndIntSize(tupleSize)
15097 globalNumCells = len(globalSerializedFloatArray) / serialFloatSize
15098
15099 for ii in range(0, globalNumCells):
15100 newCell = PhactoriSampledCellInfo()
15101 newCell.SerializeSetFromFloatAndIntArray(globalSerializedFloatArray, globalSerializedIntArray, ii, tupleSize)
15102 globalCellList.append(newCell)
15103
15104 if PhactoriDbg(100):
15105 myDebugPrint3("PhactoriGeometricCellSampler1.GatherSampledCellDataFromAllProcessesUsingMPI returning\n", 100)
15106
15107 return globalCellList
15108
15109
15110 def GatherSampledCellDataFromAllProcessesAndWriteFromOneProcessUsingMPI(self, outputFilenameCounter = -1):
15111 if PhactoriDbg(100):
15112 myDebugPrint3("PhactoriGeometricCellSampler1.GatherSampledCellDataFromAllProcessesAndWriteFromOneProcessUsingMPI entered\n", 100)
15113 myPid = SmartGetLocalProcessId()
15114
15115 if outputFilenameCounter < 0:
15116 ftc = GetFrameTagCounter()
15117 else:
15118 ftc = outputFilenameCounter
15119
15120
15121 pidToDoOutput = SmartGetNumberOfProcesses() - 1
15122 if self.WriteOutGeometricallySampledCellData == True:
15123 globalCellList = self.GatherSampledCellDataFromAllProcessesUsingMPI(self.GeometricallySampledCellsForThisProcess)
15124 if myPid == pidToDoOutput:
15125 if PhactoriDbg(100):
15126 myDebugPrint3("finished serialize, about to write to geometric sample cell file\n" +\
15127 "number of cells from all processes: " + str(len(globalCellList)) + "\n")
15128
15129 fname = self.GeometricSampledCellOutputFilePathManager.GetOutputFilePath(ftc, "")
15130 if PhactoriDbg(100):
15131 myDebugPrint3("output filename will be: " + str(fname) + "\n")
15132 self.WriteCellListToFile(fname, globalCellList)
15133
15134 if self.WriteOutDataControlledSampledCellData == True:
15135 globalCellList = self.GatherSampledCellDataFromAllProcessesUsingMPI(self.DataControlledSampledCellsForThisProcess)
15136 if myPid == pidToDoOutput:
15137 if PhactoriDbg(100):
15138 myDebugPrint3("finished serialize, about to write to data controlled sample cell file\n" +\
15139 "number of cells from all processes: " + str(len(globalCellList)) + "\n")
15140
15141 fname = self.DataControlledSampledCellOutputFilePathManager.GetOutputFilePath(ftc, "")
15142 if PhactoriDbg(100):
15143 myDebugPrint3("output filename will be: " + str(fname) + "\n")
15144 self.WriteCellListToFile(fname, globalCellList)
15145
15146 if PhactoriDbg(100):
15147 myDebugPrint3("PhactoriGeometricCellSampler1.GatherSampledCellDataFromAllProcessesAndWriteFromOneProcessUsingMPI returning\n", 100)
15148
15149 def ExportOperationData(self, datadescription):
15150 if PhactoriDbg(100):
15151 myDebugPrint3("PhactoriGeometricCellSampler1.ExportOperationData entered\n", 100)
15152
15153 UpdatePipelineWithCurrentTimeArgument(self.myCopyOfInputFilter)
15154
15155 #if we are supposed to resample data after first timestep, we call Create again
15156 #self.CreateInternalListOfGeometricallySampledCellsOnThisProcess
15157 #the idea here is that we already have our cell collection and we want to pull the data
15158 self.CollectDataOnSampledCellsOnThisProcess()
15159
15160 self.CreateInternalListOfDataControlledSampledCellsOnThisProcess()
15161
15162 self.GatherSampledCellDataFromAllProcessesAndWriteFromOneProcessUsingMPI()
15163
15164 if self.DoProgrammableFilterToAddMaskVariable:
15165 self.CreateProgrammableFilterString()
15166 self.mProgFilterMaskSetter.Script = self.mProgFilterString
15167 self.mProgFilterMaskSetter.UpdatePipeline()
15168
15169 #if PhactoriDbg(100):
15170 # minCellmaxCellPair = PhactoriFindCellWithMinMaxDataOnThisProcess(self.myCopyOfInputFilter, "eqps")
15171 # myDebugPrint3("min cell this process:\n" + minCellmaxCellPair[0].ToStr())
15172 # myDebugPrint3("max cell this process:\n" + minCellmaxCellPair[1].ToStr())
15173 # globalMinCellmaxCellPair = PhactoriFindCellWtihMinMaxDataUsingMPI(self.myCopyOfInputFilter, "eqps")
15174 # myDebugPrint3("min cell global:\n" + globalMinCellmaxCellPair[0].ToStr())
15175 # myDebugPrint3("max cell global:\n" + globalMinCellmaxCellPair[1].ToStr())
15176
15177 if PhactoriDbg(100):
15178 myDebugPrint3("PhactoriGeometricCellSampler1.ExportOperationData returning\n", 100)
15179
15180 def CreateProgrammableFilterString(self):
15181
15182 if self.mainScriptString == None:
15183 scriptLines = []
15184
15185 scriptLines.append("#print('test2')\n")
15186
15187 scriptLines.append("#cellIndexesToSet = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n")
15188 scriptLines.append("#maskValuesToSet = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]\n")
15189 scriptLines.append("#leafVisitCount = [0,0,0,0,0,0,0,0,0,0,0]\n")
15190
15191 scriptLines.append("localLeafVisitCount = 0\n")
15192
15193 scriptLines.append("def flatten(input, output):\n")
15194 scriptLines.append(" # Copy the cells etc.\n")
15195 scriptLines.append(" output.ShallowCopy(input)\n")
15196 scriptLines.append(" numPoints = input.GetNumberOfPoints()\n")
15197 scriptLines.append(" celldata = output.GetCellData()\n")
15198 scriptLines.append(" numCells = input.GetNumberOfCells()\n")
15199 scriptLines.append(" #print(str(numCells))\n")
15200 scriptLines.append(" ncda = vtk.vtkDoubleArray()\n")
15201 scriptLines.append(" ncda.SetNumberOfTuples(numCells)\n")
15202 scriptLines.append(" numTuples = ncda.GetNumberOfTuples()\n")
15203 scriptLines.append(" for ii in range(0, numTuples):\n")
15204 scriptLines.append(" ncda.SetValue(ii, 0.0)\n")
15205 scriptLines.append(" for ii, cellNdx in enumerate(cellIndexesToSet):\n")
15206 scriptLines.append(" if localLeafVisitCount == leafVisitCount[ii]:\n")
15207 scriptLines.append(" if cellNdx < numCells:\n")
15208 scriptLines.append(" ncda.SetValue(cellNdx, float(maskValuesToSet[ii]))\n")
15209 scriptLines.append(" ncda.SetName('" + self.ProgrammableFilterOutputCellVariableName + "')\n")
15210 scriptLines.append(" #print(ncda.GetName())\n")
15211 scriptLines.append(" celldata.AddArray(ncda)\n")
15212
15213 scriptLines.append("input = self.GetInputDataObject(0, 0)\n")
15214 scriptLines.append("output = self.GetOutputDataObject(0)\n")
15215
15216 scriptLines.append("if input.IsA('vtkMultiBlockDataSet'):\n")
15217 scriptLines.append(" output.CopyStructure(input)\n")
15218 scriptLines.append(" iter = input.NewIterator()\n")
15219 scriptLines.append(" iter.UnRegister(None)\n")
15220 scriptLines.append(" iter.InitTraversal()\n")
15221 scriptLines.append(" while not iter.IsDoneWithTraversal():\n")
15222 scriptLines.append(" localLeafVisitCount += 1\n")
15223 scriptLines.append(" curInput = iter.GetCurrentDataObject()\n")
15224 scriptLines.append(" curOutput = curInput.NewInstance()\n")
15225 scriptLines.append(" curOutput.UnRegister(None)\n")
15226 scriptLines.append(" output.SetDataSet(iter, curOutput)\n")
15227 scriptLines.append(" flatten(curInput, curOutput)\n")
15228 scriptLines.append(" iter.GoToNextItem();\n")
15229 scriptLines.append("else:\n")
15230 scriptLines.append(" flatten(input, output)\n")
15231
15232 self.mainScriptString = "".join(scriptLines)
15233
15234 myCellIndexesToSet = []
15235 myMaskValuesToSet = []
15236 myLeafVisitCount = []
15237 if self.GeometricallySampledCellsForThisProcess != None:
15238 for cellIdx, oneCellInfo in enumerate(self.GeometricallySampledCellsForThisProcess):
15239 maskValue = 1.0
15240 myCellIndexesToSet.append(oneCellInfo.index)
15241 myMaskValuesToSet.append(maskValue)
15242 myLeafVisitCount.append(oneCellInfo.leafVisitCount)
15243 if self.DataControlledSampledCellsForThisProcess != None:
15244 for cellIdx, oneCellInfo in enumerate(self.DataControlledSampledCellsForThisProcess):
15245 maskValue = 2.0
15246 myCellIndexesToSet.append(oneCellInfo.index)
15247 myMaskValuesToSet.append(maskValue)
15248 myLeafVisitCount.append(oneCellInfo.leafVisitCount)
15249
15250 newstr1 = "cellIndexesToSet = " + str(myCellIndexesToSet) + "\n"
15251 newstr2 = "maskValuesToSet = " + str(myMaskValuesToSet) + "\n"
15252 newstr3 = "leafVisitCount = " + str(myLeafVisitCount) + "\n"
15253 self.mProgFilterString = newstr1 + newstr2 + newstr3 + self.mainScriptString
15254
15255 if PhactoriDbg(100):
15256 myDebugPrint3("PhactoriMarkCellSetsOperation constructed script:\n" + \
15257 self.mProgFilterString)
15258
15259 #phactori_combine_to_single_python_file_subpiece_end_1
15260
15261 #phactori_combine_to_single_python_file_parent_1
15262 #from Operation.PhactoriParallelGeometryUtilities import *
15263 #phactori_combine_to_single_python_file_subpiece_begin_1
15264
15265 def GetGridPointsClosestToPointsInBlockV5(recursionObject, inInputCsData, inParameters):
15266 if PhactoriDbg(100):
15267 myDebugPrint3("GetGridPointsClosestToPointsInBlockV5 entered\n")
15268 numCells = inInputCsData.GetNumberOfCells()
15269 numPoints = inInputCsData.GetNumberOfPoints()
15270 if (numCells == 0) or (numPoints == 0):
15271 #no cells here
15272 if PhactoriDbg(100):
15273 myDebugPrint3("GetGridPointsClosestToPointsInBlockV5 returning (no cells or no points)\n")
15274 return
15275
15276 if PhactoriDbg(100):
15277 myDebugPrint3(str(inParameters.testPointList) + "\n")
15278 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
15279
15280 pointsArray = inInputCsData.GetPoints()
15281 gridPtXyz = [0.0, 0.0, 0.0]
15282 for gridPtNdx in range(0,numPoints):
15283 pointsArray.GetPoint(gridPtNdx, gridPtXyz)
15284 for ptndx, oneTestPt in enumerate(inParameters.testPointList):
15285 testDist = vecDistanceSquared(oneTestPt, gridPtXyz)
15286 if testDist < inParameters.distSqrdList[ptndx]:
15287 inParameters.closestList[ptndx] = list(gridPtXyz)
15288 inParameters.distSqrdList[ptndx] = testDist
15289
15290 if PhactoriDbg(100):
15291 myDebugPrint3(str(inParameters.testPointList) + "\n")
15292 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
15293
15294 if PhactoriDbg(100):
15295 myDebugPrint3("after this block:\n")
15296 for ii, oneGridPoint in enumerate(inParameters.closestList):
15297 myDebugPrint3(str(ii) + ": " + \
15298 str(inParameters.distSqrdList[ii]) + "\n" + \
15299 str(inParameters.testPointList[ii]) + "\n" + str(oneGridPoint))
15300 myDebugPrint3("\n")
15301
15302 if PhactoriDbg(100):
15303 myDebugPrint3("GetGridPointsClosestToPointsInBlockV5 returning\n")
15304
15305 def GetCellsClosestToPointsInBlockV5(recursionObject, inInputCsData, inParameters):
15306 if PhactoriDbg(100):
15307 myDebugPrint3("GetCellsClosestToPointsInBlock entered\n")
15308 numCells = inInputCsData.GetNumberOfCells()
15309 numPoints = inInputCsData.GetNumberOfPoints()
15310 if (numCells == 0) or (numPoints == 0):
15311 #no cells here
15312 if PhactoriDbg(100):
15313 myDebugPrint3("GetCellsClosestToPointsInBlock returning (no cells or no points)\n")
15314 return
15315
15316 if PhactoriDbg(100):
15317 myDebugPrint3(str(inParameters.testPointList) + "\n")
15318 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
15319
15320 for cellIndex in range(0,numCells):
15321 oneCell = inInputCsData.GetCell(cellIndex)
15322 cellTestPoint = GetCellTestPoint(oneCell)
15323 for ptndx, oneTestPt in enumerate(inParameters.testPointList):
15324 testDist = vecDistanceSquared(oneTestPt, cellTestPoint)
15325 if testDist < inParameters.distSqrdList[ptndx]:
15326 inParameters.closestList[ptndx] = cellTestPoint
15327 inParameters.distSqrdList[ptndx] = testDist
15328
15329 if PhactoriDbg(100):
15330 myDebugPrint3(str(inParameters.testPointList) + "\n")
15331 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
15332
15333 if PhactoriDbg(100):
15334 myDebugPrint3("after this block:\n")
15335 for ii, oneCellPoint in enumerate(inParameters.closestList):
15336 myDebugPrint3(str(ii) + ": " + \
15337 str(inParameters.distSqrdList[ii]) + "\n" + \
15338 str(inParameters.testPointList[ii]) + "\n" + str(oneCellPoint))
15339 myDebugPrint3("\n")
15340
15341 if PhactoriDbg(100):
15342 myDebugPrint3("GetCellsClosestToPointsInBlock returning\n")
15343
15344 class GetCellsClosestToPointsInBlockRecursionParamsV5:
15345 def __init__(self):
15346 self.testPointList = []
15347 self.distSqrdList = []
15348 self.closestList = []
15349
15350 def InitializeWithPointList(self, inTestPointList):
15351 self.testPointList = inTestPointList
15352 numTestPoints = len(inTestPointList)
15353 for ii in range(0, numTestPoints):
15354 self.distSqrdList.append(sys.float_info.max)
15355 self.closestList.append(None)
15356
15357 def GetCellsClosestToPointsOnThisProcessFromParaViewFilterV5(inInputFilter, inTestPointList):
15358 if PhactoriDbg(100):
15359 myDebugPrint3("GetCellsClosestToPointsOnThisProcessFromParaViewFilter entered\n")
15360 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
15361 recursionObj.mParameters = GetCellsClosestToPointsInBlockRecursionParamsV5()
15362 recursionObj.mParameters.InitializeWithPointList(inTestPointList)
15363 recursionObj.mOperationToDoPerBlock = GetCellsClosestToPointsInBlockV5
15364 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, inInputFilter)
15365 if PhactoriDbg(100):
15366 myDebugPrint3("GetCellsClosestToPointsOnThisProcessFromParaViewFilter returning\n")
15367 return recursionObj.mParameters.closestList, recursionObj.mParameters.distSqrdList
15368
15369 def GetGridPointsClosestToPointsOnThisProcessFromParaViewFilterV5(inInputFilter, inTestPointList):
15370 if PhactoriDbg(100):
15371 myDebugPrint3("GetGridPointsClosestToPointsOnThisProcessFromParaViewFilterV5 entered\n")
15372 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
15373 recursionObj.mParameters = GetCellsClosestToPointsInBlockRecursionParamsV5()
15374 recursionObj.mParameters.InitializeWithPointList(inTestPointList)
15375 recursionObj.mOperationToDoPerBlock = GetGridPointsClosestToPointsInBlockV5
15376 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, inInputFilter)
15377 if PhactoriDbg(100):
15378 myDebugPrint3("GetGridPointsClosestToPointsOnThisProcessFromParaViewFilterV5 returning\n")
15379 return recursionObj.mParameters.closestList, recursionObj.mParameters.distSqrdList
15380
15381 def GetPidWithLeastValueListV5(inLocalDistSqrdList):
15382 myPid = int(SmartGetLocalProcessId())
15383 globalDistSqrdList = UseReduceOnFloatList(inLocalDistSqrdList, 1)
15384 localPidList = []
15385 numItems = len(inLocalDistSqrdList)
15386 for ndx in range(0,numItems):
15387 if globalDistSqrdList[ndx] == inLocalDistSqrdList[ndx]:
15388 localPidList.append(myPid)
15389 else:
15390 localPidList.append(-1)
15391
15392 pidWithDataList = UseReduceOnIntegerList(localPidList, 0)
15393 return pidWithDataList, globalDistSqrdList
15394
15395
15396 def UseMpiToGetGlobalCellPointsClosestV5(inInputFilter, inLocalCellPointList, inLocalDistSqrdList):
15397 if PhactoriDbg(100):
15398 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest entered\n", 100)
15399
15400 if PhactoriDbg(100):
15401 myDebugPrint3("inLocalCellPointList:\n" + str(inLocalCellPointList) + "\ninLocalDistSqrdList:\n" + str(inLocalDistSqrdList) + "\n")
15402 pidWithDataList, globalDistSqrdList = GetPidWithLeastValueListV5(inLocalDistSqrdList)
15403 if PhactoriDbg(100):
15404 myDebugPrint3("pidWithDataList:\n" + str(pidWithDataList) + "\nglobalDistSqrdList:\n" + str(globalDistSqrdList) + "\n")
15405
15406 #convert cell point list to array of doubles and ints, use mpi reduce to share
15407 #the values, then convert back to cell point list
15408 serializeFloatArray = []
15409 serializeIntArray = []
15410
15411 #convert cell point list to array of doubles
15412 cellPointFloatArray = []
15413 myPid = SmartGetLocalProcessId()
15414 for ii, oneCellPoint in enumerate(inLocalCellPointList):
15415 if pidWithDataList[ii] == myPid:
15416 cellPointFloatArray.append(oneCellPoint[0])
15417 cellPointFloatArray.append(oneCellPoint[1])
15418 cellPointFloatArray.append(oneCellPoint[2])
15419 else:
15420 cellPointFloatArray.append(0.0)
15421 cellPointFloatArray.append(0.0)
15422 cellPointFloatArray.append(0.0)
15423
15424 #use mpi reduce to spread array correctly
15425 globalCellPointFloatArray = UseReduceOnFloatList(cellPointFloatArray, 2)
15426
15427 #now create return global cell point list from arrays
15428 numCells = len(inLocalCellPointList)
15429 returnGlobalCellPointList = []
15430 for ii in range(0,numCells):
15431 myndx = ii*3
15432 oneCellPoint = [globalCellPointFloatArray[myndx],
15433 globalCellPointFloatArray[myndx+1],
15434 globalCellPointFloatArray[myndx+2]]
15435 returnGlobalCellPointList.append(oneCellPoint)
15436
15437 if PhactoriDbg(100):
15438 myDebugPrint3("returnGlobalCellPointList:\n" + str(returnGlobalCellPointList) + "\n")
15439 if PhactoriDbg(100):
15440 myDebugPrint3("PhactoriSegmentCellSampler3.UseMpiToGetGlobalCellPointsClosest returning\n", 100)
15441 return returnGlobalCellPointList, globalDistSqrdList
15442
15443 def GetListOfCellTestPointsNearestListOfPointsV5(inInputFilter, pointList):
15444 "for each point in the list, find the cell test point (e.g. center of\n cell bounding box) which is nearest the test point. Use MPI to work\n in parallel"
15445
15446 thisProcessNearestCellPointList, thisProcDistSqrdList = \
15447 GetCellsClosestToPointsOnThisProcessFromParaViewFilterV5(inInputFilter, pointList)
15448
15449 nearestCellList, distanceList = UseMpiToGetGlobalCellPointsClosestV5(
15450 inInputFilter, thisProcessNearestCellPointList, thisProcDistSqrdList)
15451
15452 return nearestCellList
15453
15454 def GetListOfGridPointsNearestListOfPointsV5(inInputFilter, pointList):
15455 "for each point in the list, find the point in the data grid\n which is nearest the test point. Use MPI to work\n in parallel"
15456
15457 thisProcessNearestGridPointList, thisProcDistSqrdList = \
15458 GetGridPointsClosestToPointsOnThisProcessFromParaViewFilterV5(inInputFilter, pointList)
15459
15460 nearestCellList, distanceList = UseMpiToGetGlobalCellPointsClosestV5(
15461 inInputFilter, thisProcessNearestGridPointList, thisProcDistSqrdList)
15462
15463 return nearestCellList
15464
15465
15466
15467 #phactori_combine_to_single_python_file_subpiece_end_1
15468
15469 #phactori_combine_to_single_python_file_parent_1
15470 #from Operation.PhactoriExtractSubsetWithSeed import *
15471 #phactori_combine_to_single_python_file_subpiece_begin_1
15472
15473 class PhactoriExtractSubsetWithSeed(PhactoriOperationSpecifics):
15474 "manages extract block filter, including creating flat block\n indices list from list of block names"
15475 def __init__(self):
15476 PhactoriOperationSpecifics.__init__(self)
15477 self.Seed = [0.0, 0.0, 0.0]
15478 self.Direction = "I"
15479 self.FindSeedNearestTestPoint = False
15480 self.TestPointToFindSeed = [0.0, 0.0, 0.0]
15481 self.SeedOffset = [0.0, 0.0, 0.0]
15482 self.SeedWithOffset = [0.0, 0.0, 0.0]
15483
15484 def ParseParametersFromJson(self, inJson):
15485 key1 = "seed"
15486 key2 = "seed from cell nearest point"
15487 if "seed" in inJson:
15488 if key2 in inJson:
15489 myDebugPrint3AndException(
15490 "PhactoriExtractSubsetWithSeed.ParseParametersFromJson exception:\n"
15491 "block may have one of the following two tokens, but not both:\n"
15492 "'" + key1 + "'\n"
15493 "'" + key2 + "'\n")
15494 self.Seed = inJson["seed"]
15495 if len(self.Seed) != 3:
15496 myDebugPrint3AndException(
15497 "PhactoriExtractSubsetWithSeed.ParseParametersFromJson exception:\n"
15498 "'" + key1 + "' token must be [x,y,z] (list of 3 floats)\n")
15499
15500 if key2 in inJson:
15501 self.FindSeedNearestTestPoint = True
15502 self.TestPointToFindSeed = inJson[key2]
15503 if len(self.TestPointToFindSeed) != 3:
15504 myDebugPrint3AndException(
15505 "PhactoriExtractSubsetWithSeed.ParseParametersFromJson exception:\n"
15506 "'" + key2 + "' token must be [x,y,z] (list of 3 floats)\n")
15507
15508 key3 = "seed offset"
15509 if key3 in inJson:
15510 self.SeedOffset = inJson[key3]
15511 if len(self.SeedOffset) != 3:
15512 myDebugPrint3AndException(
15513 "PhactoriExtractSubsetWithSeed.ParseParametersFromJson exception:\n"
15514 "'" + key3 + "' token must be [x,y,z] (list of 3 floats)\n")
15515
15516 if "direction" in inJson:
15517 self.Direction = inJson["direction"]
15518 validDirectionStrings = ["I", "J", "K", "IJ", "JK", "KI"]
15519 if self.Direction not in validDirectionStrings:
15520 myDebugPrint3AndException(
15521 "PhactoriExtractSubsetWithSeed.ParseParametersFromJson exception:\n"
15522 "illegal 'direction' token: " + str(self.Direction) + "\n"
15523 "the direction must one of: " + str(validDirectionStrings) + "\n")
15524
15525 def CreateParaViewFilter(self, inInputFilter):
15526 "create the ExtractSubsetWithSeed filter for ParaView"
15527 if PhactoriDbg(100):
15528 myDebugPrint3("PhactoriExtractSubsetWithSeed.CreateParaViewFilter "
15529 "entered\n", 100)
15530
15531 savedActiveSource = GetActiveSource()
15532
15533 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
15534
15535 newParaViewFilter = ExtractSubsetWithSeed(inInputFilter)
15536
15537 if self.FindSeedNearestTestPoint:
15538 ##nearestCellTestPointList = GetListOfCellTestPointsNearestListOfPointsV5(inInputFilter, [self.TestPointToFindSeed])
15539 nearestCellTestPointList = GetListOfGridPointsNearestListOfPointsV5(inInputFilter, [self.TestPointToFindSeed])
15540 self.Seed = nearestCellTestPointList[0]
15541 if PhactoriDbg(100):
15542 myDebugPrint3("find grid point for seed nearest this point:\n" + str(self.TestPointToFindSeed) + "\n"
15543 "seed point found:\n" + str(self.Seed) + "\n")
15544
15545 self.SeedWithOffset[0] = self.Seed[0] + self.SeedOffset[0]
15546 self.SeedWithOffset[1] = self.Seed[1] + self.SeedOffset[1]
15547 self.SeedWithOffset[2] = self.Seed[2] + self.SeedOffset[2]
15548 if PhactoriDbg(100):
15549 myDebugPrint3("self.Seed: " + str(self.Seed) + "\n"
15550 "self.SeedWithOffset: " + str(self.SeedWithOffset) + "\n")
15551 newParaViewFilter.Seed = self.SeedWithOffset
15552 newParaViewFilter.Direction = self.Direction
15553
15554 SetActiveSource(newParaViewFilter)
15555
15556 UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
15557
15558 SetActiveSource(savedActiveSource)
15559
15560 if PhactoriDbg(100):
15561 myDebugPrint3("PhactoriExtractSubsetWithSeed.CreateParaViewFilter "
15562 "returning\n", 100)
15563
15564 return newParaViewFilter
15565 #phactori_combine_to_single_python_file_subpiece_end_1
15566
15567 #phactori_combine_to_single_python_file_parent_1
15568 #from Operation.PhactoriExtractStructuredMultiBlock import *
15569 #phactori_combine_to_single_python_file_subpiece_begin_1
15570
15571 global gStructuredGridFound
15572 gStructuredGridFound = None
15573 global gStructuredGridFoundExtent
15574 gStructuredGridFoundExtent = None
15575
15576 def FigureBlockIndicesFromBlockListOneBlock(includeIndexList, includeBlockList,
15577 inMetaData, ioFlatIndexCounter, inCsdata, inForceSetting):
15578 "determine if this one block should have it's flat index tripped on for\n the extract block filter (leaf item of recursion)"
15579 if PhactoriDbg(100):
15580 myDebugPrint3("FigureBlockIndicesFromBlockListOneBlock entered\n"
15581 "ioFlatIndexCounter " + str(ioFlatIndexCounter,) + " inForceSetting " + str(inForceSetting) + "\n"
15582 "2 inMetaData: " + str(inMetaData) + "\n")
15583
15584 if inMetaData == None:
15585 thisBlockName = None
15586 else:
15587 thisBlockName = inMetaData.Get(vtk.vtkCompositeDataSet.NAME())
15588
15589 if (thisBlockName == None) and (inForceSetting != 1):
15590 if PhactoriDbg(100):
15591 myDebugPrint3("block with no name " + \
15592 " not in include list, not + to mBlockIndices (flat index " + \
15593 str(ioFlatIndexCounter[0] - 1) + ")\n")
15594 elif (inForceSetting == 1) or (thisBlockName in includeBlockList):
15595 includeIndexList.append(int(ioFlatIndexCounter[0]) - 1)
15596 blockClassName = inCsdata.GetClassName()
15597 if blockClassName == "vtkStructuredGrid":
15598 global gStructuredGridFound
15599 gStructuredGridFound = inCsdata
15600 global gStructuredGridFoundExtent
15601 gStructuredGridFoundExtent = inMetaData.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT())
15602 if PhactoriDbg(100):
15603 myDebugPrint3("this leaf is structured grid: " + str(thisBlockName) + "\n"
15604 "vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT(): " + str(gStructuredGridFoundExtent) + "\n"
15605 "A inCsdata.GetExtent(): " + str(inCsdata.GetExtent()) + "\n")
15606 #global gDuplicateNameCounter
15607 #if thisBlockName in gDuplicateNameCounter:
15608 # oldCount = gDuplicateNameCounter[thisBlockName]
15609 # gDuplicateNameCounter[thisBlockName] = oldCount+1
15610 #else:
15611 # gDuplicateNameCounter[thisBlockName] = 1
15612 if PhactoriDbg(100):
15613 myDebugPrint3("block " + str(thisBlockName) + \
15614 " in include list, + to mBlockIndices (flat index " + \
15615 str(ioFlatIndexCounter[0] - 1) + ")\n")
15616 else:
15617 if PhactoriDbg(100):
15618 myDebugPrint3("block " + str(thisBlockName) + \
15619 " not in include list, not + to mBlockIndices (flat index " + \
15620 str(ioFlatIndexCounter[0] - 1) + ")\n")
15621
15622 if PhactoriDbg(100):
15623 myDebugPrint3("FigureBlockIndicesFromBlockListOneBlock returning\n")
15624
15625 def FigureBlockIndicesFromBlockListRecurse1(includeIndexList, includeBlockList,
15626 inCsdata, inMetaData, ioFlatIndexCounter, inForceSetting):
15627 "recursively go through multiblock dataset to determine flat indices\n of blocks to be included; we are assuming only leaf blocks are\n actually named"
15628
15629 icsdClassname = inCsdata.GetClassName()
15630
15631 if PhactoriDbg(100):
15632 if inMetaData == None:
15633 thisBlockName = None
15634 else:
15635 thisBlockName = inMetaData.Get(vtk.vtkCompositeDataSet.NAME())
15636 myDebugPrint3("FigureBlockIndicesFromBlockListRecurse1 " + \
15637 str(thisBlockName) + " index: " + str(int(ioFlatIndexCounter[0])) + \
15638 " inForceSetting: " + str(inForceSetting) + " classname: " + \
15639 str(icsdClassname) + "\n")
15640
15641 ioFlatIndexCounter[0] += 1
15642
15643 if icsdClassname == "vtkMultiBlockDataSet":
15644 thisIsLeaf = False
15645 nonLeafType = 0
15646 elif icsdClassname == "vtkExodusIIMultiBlockDataSet":
15647 thisIsLeaf = False
15648 nonLeafType = 1
15649 elif icsdClassname == "vtkMultiPieceDataSet":
15650 thisIsLeaf = False
15651 nonLeafType = 2
15652 elif icsdClassname == "vtkPartitionedDataSet":
15653 thisIsLeaf = False
15654 nonLeafType = 3
15655 else:
15656 thisIsLeaf = True
15657 nonLeafType = -1
15658
15659 if not thisIsLeaf:
15660 if inForceSetting == 1:
15661 includeIndexList.append(int(ioFlatIndexCounter[0]) - 1)
15662 includeOrExcludeAllSubBlocks = 1
15663 if PhactoriDbg(100):
15664 myDebugPrint3("this non-leaf block added inForceSetting == 1\n")
15665 elif inForceSetting == -1:
15666 includeOrExcludeAllSubBlocks = -1
15667 if PhactoriDbg(100):
15668 myDebugPrint3("this non-leaf block not added inForceSetting == -1\n")
15669 else:
15670 includeOrExcludeAllSubBlocks = 0
15671 #this is a non-leaf node, but we want to add it (or not) depending on
15672 #the filter settings
15673 if inMetaData == None:
15674 thisBlockName = None
15675 else:
15676 thisBlockName = inMetaData.Get(vtk.vtkCompositeDataSet.NAME())
15677
15678 if (thisBlockName != None) and (thisBlockName in includeBlockList):
15679 if PhactoriDbg(100):
15680 myDebugPrint3("include list, append nonleaf " + str(thisBlockName) + \
15681 " ndx " + str(int(ioFlatIndexCounter[0]) - 1) + "\n")
15682 includeIndexList.append(int(ioFlatIndexCounter[0]) - 1)
15683 includeOrExcludeAllSubBlocks = 1
15684 if PhactoriDbg(100):
15685 myDebugPrint3("includeOrExcludeAllSubBlocks set to 1\n")
15686 else:
15687 if PhactoriDbg(100):
15688 myDebugPrint3("include list, exclude nonleaf " + str(thisBlockName) + \
15689 " ndx " + str(int(ioFlatIndexCounter[0]) - 1) + "\n")
15690
15691 if nonLeafType == 2:
15692 numBlocks = inCsdata.GetNumberOfPieces()
15693 elif nonLeafType == 3:
15694 numBlocks = inCsdata.GetNumberOfPartitions()
15695 else:
15696 numBlocks = inCsdata.GetNumberOfBlocks()
15697
15698 if PhactoriDbg(100):
15699 myDebugPrint3("recursing, flat index: " + \
15700 str(ioFlatIndexCounter[0]) + \
15701 " num blocks: " + \
15702 str(numBlocks) + "\n")
15703 for ii in range(0, numBlocks):
15704 if nonLeafType == 2:
15705 oneBlock = inCsdata.GetPiece(ii)
15706 elif nonLeafType == 3:
15707 oneBlock = inCsdata.GetPartition(ii)
15708 else:
15709 oneBlock = inCsdata.GetBlock(ii)
15710 oneBlockMetaData = inCsdata.GetMetaData(ii)
15711 if PhactoriDbg(100):
15712 myDebugPrint3("oneBlockMetaData: " + str(oneBlockMetaData) + "\n")
15713 #myDebugPrint3("name: " + \
15714 # oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME()) + "\n")
15715 if oneBlock != None:
15716 if oneBlockMetaData != None:
15717 theBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME())
15718 if PhactoriDbg(100):
15719 myDebugPrint3("name for block " + str(ii) + ": " + \
15720 str(theBlockName) + "\n")
15721 else:
15722 if PhactoriDbg(100):
15723 myDebugPrint3("block " + str(ii) + " meta data was None\n")
15724 FigureBlockIndicesFromBlockListRecurse1(includeIndexList, includeBlockList,
15725 oneBlock, oneBlockMetaData, ioFlatIndexCounter,
15726 includeOrExcludeAllSubBlocks)
15727 else:
15728 #I think we need to count here to be okay with pruned stuff; maybe
15729 #we need to set extract block to no pruning (?)
15730 ioFlatIndexCounter[0] += 1
15731 if includeOrExcludeAllSubBlocks == 1:
15732 if PhactoriDbg(100):
15733 myDebugPrint3("leaf block None index " + \
15734 str(int(ioFlatIndexCounter[0]) - 1) + \
15735 " appended due to includeOrExcludeAllSubBlocks == 1\n\n")
15736 includeIndexList.append(int(ioFlatIndexCounter[0]) - 1)
15737 else:
15738 if PhactoriDbg(100):
15739 myDebugPrint3("force include is not on, so check include list\n")
15740 includeThisBlock = False
15741 if (includeBlockList != None) and (oneBlockMetaData != None):
15742 thisBlockName = oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME())
15743 if PhactoriDbg(100):
15744 myDebugPrint3("include list not None, thisBlockName " + str(thisBlockName) + "\n"
15745 "includeBlockList " + str(includeBlockList) + "\n")
15746 if (thisBlockName != None) and (thisBlockName in includeBlockList):
15747 includeThisBlock = True
15748 if PhactoriDbg(100):
15749 myDebugPrint3("leaf block None index " + \
15750 str(int(ioFlatIndexCounter[0]) - 1) + \
15751 " included due to name being in includeBlockList\n")
15752 includeIndexList.append(int(ioFlatIndexCounter[0]) - 1)
15753 if includeThisBlock == False:
15754 if PhactoriDbg(100):
15755 myDebugPrint3("leaf block None index " + \
15756 str(int(ioFlatIndexCounter[0]) - 1) + \
15757 " excluded due to includeOrExcludeAllSubBlocks != 1\n")
15758 else:
15759 if inForceSetting != -1:
15760 if inForceSetting == 1:
15761 if PhactoriDbg(100):
15762 myDebugPrint3("this leaf block will be added inForceSetting == 1\n")
15763 FigureBlockIndicesFromBlockListOneBlock(includeIndexList,
15764 includeBlockList, inMetaData, ioFlatIndexCounter, inCsdata, inForceSetting)
15765 else:
15766 if PhactoriDbg(100):
15767 myDebugPrint3("this leaf block not added inForceSetting == -1\n")
15768 #if icsdClassname == "vtkMultiPieceDataSet":
15769 # numpieces = inCsdata.GetNumberOfPieces()
15770 # # ioFlatIndexCounter[0] += numpieces - 1
15771 # ioFlatIndexCounter[0] += numpieces
15772
15773
15774 def FigureBlockIndicesFromBlockList(includeBlockList, inInputFilter):
15775 "from the includeBlockList create a indices list\n of blocks to put in filter"
15776 if PhactoriDbg(100):
15777 myDebugPrint3("FigureBlockIndicesFromBlockList entered"
15778 "\nincludeBlockList: " + str(includeBlockList) + "\n")
15779
15780 #global gDuplicateNameCounter
15781 #gDuplicateNameCounter = {}
15782 csdata = inInputFilter.GetClientSideObject().GetOutputDataObject(0)
15783 flatIndexCounter = [0]
15784 listOfBlockIndicesToInclude = []
15785 FigureBlockIndicesFromBlockListRecurse1(listOfBlockIndicesToInclude,
15786 includeBlockList, csdata, None, flatIndexCounter, 0)
15787
15788 #if PhactoriDbg(100):
15789 # myDebugPrint3("number of times existing block names found:\n")
15790 # for blknm, count in gDuplicateNameCounter.items():
15791 # myDebugPrint3(blknm + ": " + str(count) + "\n");
15792 if PhactoriDbg(100):
15793 myDebugPrint3("FigureBlockIndicesFromBlockList final indices list:\n" \
15794 + str(listOfBlockIndicesToInclude) + \
15795 "\nFigureBlockIndicesFromBlockList returning\n")
15796
15797 return listOfBlockIndicesToInclude
15798
15799 def PrintMultiBlockStatsOneBlock(inCsdata, inMetaData, ioFlatIndexCounter):
15800 icsdClassname = inCsdata.GetClassName()
15801 myDebugPrint3("leaf block " + str(icsdClassname) + " index " + str(ioFlatIndexCounter[0]) + "\n")
15802 if icsdClassname == "vtkStructuredGrid":
15803 wholeExtent = inMetaData.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT())
15804 myDebugPrint3("this leaf is structured grid: " + str(ioFlatIndexCounter[0]) + "\n"
15805 "vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT(): " + str(wholeExtent) + "\n"
15806 "B inCsdata.GetExtent(): " + str(inCsdata.GetExtent()) + "\n")
15807
15808 def PrintMultiBlockStatsRecurse1(inCsdata, inMetaData, recursionLevel, ioFlatIndexCounter):
15809 myDebugPrint3("PrintMultiBlockStatsRecurse1 entered recursionLevel " + str(recursionLevel) + "\n")
15810
15811 icsdClassname = inCsdata.GetClassName()
15812 myDebugPrint3("inCsdata.GetClassName() " + str(icsdClassname) + " ioFlatIndexCounter[0] " + str(ioFlatIndexCounter[0]) + "\n")
15813
15814 ioFlatIndexCounter[0] += 1
15815
15816 if icsdClassname == "vtkMultiBlockDataSet":
15817 thisIsLeaf = False
15818 nonLeafType = 0
15819 elif icsdClassname == "vtkExodusIIMultiBlockDataSet":
15820 thisIsLeaf = False
15821 nonLeafType = 1
15822 elif icsdClassname == "vtkMultiPieceDataSet":
15823 thisIsLeaf = False
15824 nonLeafType = 2
15825 elif icsdClassname == "vtkPartitionedDataSet":
15826 thisIsLeaf = False
15827 nonLeafType = 3
15828 else:
15829 thisIsLeaf = True
15830 nonLeafType = -1
15831
15832 myDebugPrint3("thisIsLeaf " + str(thisIsLeaf) + " nonLeafType " + str(nonLeafType) + "\n")
15833 if not thisIsLeaf:
15834 if nonLeafType == 2:
15835 numBlocks = inCsdata.GetNumberOfPieces()
15836 elif nonLeafType == 3:
15837 numBlocks = inCsdata.GetNumberOfPartitions()
15838 else:
15839 numBlocks = inCsdata.GetNumberOfBlocks()
15840
15841 myDebugPrint3("recursing, flat index: " + \
15842 str(ioFlatIndexCounter[0]) + \
15843 " num blocks: " + \
15844 str(numBlocks) + "\n")
15845 for ii in range(0, numBlocks):
15846 myDebugPrint3("doing sub block " + str(ii) + " of " + str(numBlocks) + "\n")
15847 if nonLeafType == 2:
15848 oneBlock = inCsdata.GetPiece(ii)
15849 elif nonLeafType == 3:
15850 oneBlock = inCsdata.GetPartition(ii)
15851 else:
15852 oneBlock = inCsdata.GetBlock(ii)
15853 oneBlockMetaData = inCsdata.GetMetaData(ii)
15854 myDebugPrint3("oneBlockMetaData: " + str(oneBlockMetaData) + "\n")
15855 #myDebugPrint3("name: " + \
15856 # oneBlockMetaData.Get(vtk.vtkCompositeDataSet.NAME()) + "\n")
15857 if oneBlock != None:
15858 PrintMultiBlockStatsRecurse1(oneBlock, oneBlockMetaData, recursionLevel + 1, ioFlatIndexCounter)
15859 else:
15860 myDebugPrint3("this sub block is None, index " + str(ioFlatIndexCounter[0]) + "\n")
15861 ioFlatIndexCounter[0] += 1
15862 else:
15863 PrintMultiBlockStatsOneBlock(inCsdata, inMetaData, ioFlatIndexCounter)
15864
15865 myDebugPrint3("PrintMultiBlockStatsRecurse1 returning recursionLevel " + str(recursionLevel) + "\n")
15866
15867 def RecursivelyPrintMultiBlockStats(inFilter):
15868 if PhactoriDbg(100) == False:
15869 return
15870
15871 myDebugPrint3("RecursivelyPrintMultiBlockStats entered\n")
15872 csdata = inFilter.GetClientSideObject().GetOutputDataObject(0)
15873 flatIndexCounter = [0]
15874 recursionLevel = 0
15875 PrintMultiBlockStatsRecurse1(csdata, None, recursionLevel, flatIndexCounter)
15876
15877 myDebugPrint3("RecursivelyPrintMultiBlockStats returning\n")
15878
15879 class PhactoriExtractStructuredMultiBlock(PhactoriOperationSpecifics):
15880 "manages PhactoriExtractStructuredMultiBlock filter"
15881 def __init__(self):
15882 PhactoriOperationSpecifics.__init__(self)
15883 self.ControlJson = None
15884 self.SavedIncludeBlockIndexList = None
15885 self.ExtractBlockFilters = []
15886 self.ExtractSubsetFilters = []
15887 self.FinalGroupFilter = None
15888 self.mStructuredGridsIncluded = []
15889 self.mStructuredGridsIncludedExtent = []
15890
15891 def ParseParametersFromJson(self, inJson):
15892 #["blk-4":{"ijkrange":[imin,imax,jmin,jmax,kmin,kmax]]
15893 #["blk-5":{"ijkrange":[imin,imax,jmin,jmax,kmin,kmax],"ijkrangefunction":[-1,0,0,1,0,1]}]
15894 #["blk-6":{"ijkrange":[imin,imax,jmin,jmax,kmin,kmax],"ijkrangefunction":[-1,0,-1,0,0,1]}]
15895 if "ExtractSubsetSettingsByBlock" not in inJson:
15896 myDebugPrint3AndException("PhactoriExtractStructuredMultiBlock.ParseParametersFromJson\n"
15897 "missing key 'ExtractSubsetSettingsByBlock'\n")
15898
15899 self.ControlJson = inJson["ExtractSubsetSettingsByBlock"]
15900 dummy = 0
15901
15902 def MakeExtractBlockFilter(self, inInputFilter, blockName):
15903 if PhactoriDbg(100):
15904 myDebugPrint3("MakeExtractBlockFilter entered: " + str(blockName) + "\n")
15905 newPvExtractBlockFilter = ExtractBlock(inInputFilter)
15906 #newParaViewFilter.PruneOutput = 1
15907 #newParaViewFilter.MaintainStructure = 0
15908 #newParaViewFilter.MaintainStructure = 1
15909 global gStructuredGridFound
15910 gStructuredGridFound = None
15911 self.SavedIncludeBlockIndexList = FigureBlockIndicesFromBlockList([blockName], inInputFilter)
15912 self.mStructuredGridsIncluded.append(gStructuredGridFound)
15913 self.mStructuredGridsIncludedExtent.append(gStructuredGridFoundExtent)
15914
15915 if PhactoriDbg(100):
15916 myDebugPrint3("self.SavedIncludeBlockIndexList:\n" + str(self.SavedIncludeBlockIndexList) + "\n")
15917 newPvExtractBlockFilter.BlockIndices = self.SavedIncludeBlockIndexList
15918 if PhactoriDbg(100):
15919 myDebugPrint3("MakeExtractBlockFilter returning: " + str(blockName) + "\n")
15920 return newPvExtractBlockFilter
15921
15922 def CreateIjkRangeFromSettingsForThisBlock(self, ijkJson, blockExtent):
15923
15924 rngFuncAllAbsolute = True
15925 if "ijkrangefunction" in ijkJson:
15926 rngFunc = ijkJson["ijkrangefunction"]
15927 for ijksetting in rngFunc:
15928 if ijksetting != 0:
15929 rngFuncAllAbsolute = False
15930 break
15931 else:
15932 #rngFuncAllAbsolute = True
15933 rngFunc = [0,0,0,0,0,0]
15934
15935 if rngFuncAllAbsolute:
15936 retIjkRange = ijkJson["ijkrange"]
15937 if PhactoriDbg(100):
15938 myDebugPrint3("rngFunc is [0,0,0,0,0,0], all absolute, "
15939 "so just return explicit ijkrange:\nretIjkRange: \n" + \
15940 str(retIjkRange) + "\n")
15941 return retIjkRange
15942
15943 #return ijkJson["ijkrange"]
15944 if blockExtent == None:
15945 if rngFuncAllAbsolute == False:
15946 return [0,-1,0,-1,0,-1]
15947
15948 if "ijkrange" in ijkJson:
15949 ijkRangeFromJson = ijkJson["ijkrange"]
15950 else:
15951 ijkRangeFromJson = [0,0,0,0,0,0]
15952
15953 if PhactoriDbg(100):
15954 myDebugPrint3("ijkrange: " + str(ijkRangeFromJson) + "\n" + \
15955 "ijkrangefunction: " + str(rngFunc) + "\n" + \
15956 "blockExtent: " + str(blockExtent) + "\n")
15957
15958 retIjkRange = [0,0,0,0,0,0]
15959 minIndex = [0,0,2,2,4,4]
15960 maxIndex = [1,1,3,3,5,5]
15961 for ii in range(0,6):
15962 if rngFunc[ii] == 0:
15963 retIjkRange[ii] = ijkRangeFromJson[ii]
15964 elif rngFunc[ii] < 0:
15965 retIjkRange[ii] = blockExtent[minIndex[ii]] + ijkRangeFromJson[ii]
15966 else:
15967 retIjkRange[ii] = blockExtent[maxIndex[ii]] - ijkRangeFromJson[ii]
15968
15969 #validate/fix (with warning) extraction extents
15970 hadToCorrect = False
15971 uncorrectedIjkRange = list(retIjkRange)
15972 for ii in range(0,6):
15973 extentMin = blockExtent[minIndex[ii]]
15974 extentMax = blockExtent[maxIndex[ii]]
15975 if retIjkRange[ii] < extentMin:
15976 hadToCorrect = True
15977 retIjkRange[ii] = extentMin
15978 if retIjkRange[ii] > extentMax:
15979 hadToCorrect = True
15980 retIjkRange[ii] = extentMax
15981 for ii in range(0,3):
15982 ndx1 = ii * 2
15983 ndx2 = ndx1 + 1
15984 if retIjkRange[ndx1] > retIjkRange[ndx2]:
15985 hadToCorrect = True
15986 retIjkRange[ndx1] = retIjkRange[ndx2]
15987 if hadToCorrect:
15988 if PhactoriDbg(100):
15989 myDebugPrint3("return ijkrange had to be corrected because it was outside block extent"
15990 "\nblockExtent: " + str(blockExtent) +
15991 "\nijkRangeFromJson: " + str(retIjkRange) +
15992 "\nrngFunc (from json): " + str(rngFunc) +
15993 "\nuncorrectedIjkRange: " + str(uncorrectedIjkRange) +
15994 "\nretIjkRange: " + str(retIjkRange) + "\n")
15995 else:
15996 if PhactoriDbg(100):
15997 myDebugPrint3("return ijkrange did not need correction"
15998 "\nblockExtent: " + str(blockExtent) +
15999 "\nijkRangeFromJson: " + str(retIjkRange) +
16000 "\nrngFunc (from json): " + str(rngFunc) +
16001 "\nretIjkRange: " + str(retIjkRange) + "\n")
16002
16003 return retIjkRange
16004
16005
16006 def MakeExtractSubsetFilter(self, extractBlockFilter, oneBlockExtractSubsetJson, oneBlockExtents):
16007 if PhactoriDbg(100):
16008 myDebugPrint3("MakeOneExtractBlockExtractSubsetFilter entered\n")
16009
16010 #ijkrange = oneBlockExtractSubsetJson["ijkrange"]
16011 ijkrange = self.CreateIjkRangeFromSettingsForThisBlock(oneBlockExtractSubsetJson, oneBlockExtents)
16012 UpdatePipelineWithCurrentTimeArgument(extractBlockFilter)
16013 extractSubset1 = ExtractSubset(Input=extractBlockFilter)
16014 extractSubset1.VOI = ijkrange
16015 UpdatePipelineWithCurrentTimeArgument(extractSubset1)
16016 if PhactoriDbg(100):
16017 myDebugPrint3("MakeOneExtractBlockExtractSubsetFilter returning\n")
16018 return extractSubset1
16019
16020 def MakeOneExtractBlockExtractSubsetFilterPair(self, inInputFilter, blockName, oneBlockExtractSubsetJson):
16021 if PhactoriDbg(100):
16022 myDebugPrint3("MakeOneExtractBlockExtractSubsetFilterPair entered: " + str(blockName) + "\n")
16023 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
16024 newExtractBlockPvFilter = self.MakeExtractBlockFilter(inInputFilter, blockName)
16025 UpdatePipelineWithCurrentTimeArgument(newExtractBlockPvFilter)
16026 self.ExtractBlockFilters.append(newExtractBlockPvFilter)
16027
16028 if PhactoriDbg(100):
16029 myDebugPrint3("pesmb one extract block structure begin: " + blockName + "\n")
16030 RecursivelyPrintMultiBlockStats(newExtractBlockPvFilter)
16031 myDebugPrint3("pesmb one extract block structure end: " + blockName + "\n")
16032
16033 oneBlockExtent = self.mStructuredGridsIncludedExtent[-1]
16034 newExtractSubsetPvFilter = self.MakeExtractSubsetFilter(newExtractBlockPvFilter, oneBlockExtractSubsetJson, oneBlockExtent)
16035 UpdatePipelineWithCurrentTimeArgument(newExtractSubsetPvFilter)
16036 self.ExtractSubsetFilters.append(newExtractSubsetPvFilter)
16037
16038 if PhactoriDbg(100):
16039 myDebugPrint3("pesmb one extract subset structure begin: " + blockName + "\n")
16040 RecursivelyPrintMultiBlockStats(newExtractSubsetPvFilter)
16041 myDebugPrint3("pesmb one extract subset structure end: " + blockName + "\n")
16042
16043 if PhactoriDbg(100):
16044 myDebugPrint3("MakeOneExtractBlockExtractSubsetFilterPair returning: " + str(blockName) + "\n")
16045
16046 def MakeGroupAllExtractSubsetsFilter(self):
16047 if PhactoriDbg(100):
16048 myDebugPrint3("MakeGroupAllExtractSubsetsFilter entered\n")
16049 self.FinalGroupFilter = GroupDatasets(Input = self.ExtractSubsetFilters)
16050
16051 UpdatePipelineWithCurrentTimeArgument(self.FinalGroupFilter)
16052
16053 if PhactoriDbg(100):
16054 myDebugPrint3("MakeGroupAllExtractSubsetsFilter returning\n")
16055
16056 def CreateParaViewFilter(self, inInputFilter):
16057 "create the PhactoriExtractStructuredMultiBlock filter for ParaView"
16058 if PhactoriDbg(100):
16059 myDebugPrint3("PhactoriExtractStructuredMultiBlock.CreateParaViewFilter "
16060 "entered\n", 100)
16061
16062 savedActiveSource = GetActiveSource()
16063
16064 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
16065
16066 if PhactoriDbg(100):
16067 myDebugPrint3("pesmb incoming multiblock structure begin\n")
16068 RecursivelyPrintMultiBlockStats(inInputFilter)
16069 myDebugPrint3("pesmb incoming multiblock structure end\n")
16070
16071 for blockName, oneBlockExtractSubsetJson in self.ControlJson.items():
16072 self.MakeOneExtractBlockExtractSubsetFilterPair(inInputFilter, blockName, oneBlockExtractSubsetJson)
16073
16074 self.MakeGroupAllExtractSubsetsFilter()
16075 #newParaViewFilter = PhactoriExtractStructuredMultiBlock(inInputFilter)
16076
16077 if PhactoriDbg(100):
16078 myDebugPrint3("pesmb outgoing group multiblock structure begin\n")
16079 RecursivelyPrintMultiBlockStats(self.FinalGroupFilter)
16080 myDebugPrint3("pesmb outgoing group multiblock structure end\n")
16081
16082
16083 SetActiveSource(self.FinalGroupFilter)
16084 UpdatePipelineWithCurrentTimeArgument(self.FinalGroupFilter)
16085 SetActiveSource(savedActiveSource)
16086
16087 if PhactoriDbg(100):
16088 myDebugPrint3("PhactoriExtractStructuredMultiBlock.CreateParaViewFilter "
16089 "returning\n", 100)
16090
16091 return self.FinalGroupFilter
16092
16093 def DoUpdateDueToChangeInData(self, inIncomingPvFilter, outOutgoingPvFilter):
16094 UpdatePipelineWithCurrentTimeArgument(self.FinalGroupFilter)
16095
16096 if PhactoriDbg(100):
16097 myDebugPrint3("PhactoriExtractStructuredMultiBlock printing out multiblock this callback:\n")
16098 myDebugPrint3("pesmb outgoing group multiblock structure begin (per frame callback)\n")
16099 RecursivelyPrintMultiBlockStats(self.FinalGroupFilter)
16100 myDebugPrint3("pesmb outgoing group multiblock structure end (per frame callback)\n")
16101
16102 #phactori_combine_to_single_python_file_subpiece_end_1
16103
16104 class ClosestNPointsFromEachProcess:
16105 "class to manage parallel operations where we obtain a set of N points on\n each process and then share those points from each process to all\n process. used for doing things like finding closest N points from one\n operation to another on each process and then sharing and sorting and\n finding closest overall"
16106
16107 def __init__(self):
16108 self.mPointsPerProcess = None
16109 self.mMyPid = -1
16110 self.mNumProcesses = -1
16111 self.mClosestNRefs = None
16112
16113 #closest N local points (local id and id from list and geometry xyzs
16114 #from local and from list and distance squared
16115 self.mThisProcIds = vtk.vtkIntArray()
16116 self.mTargetMatchIds = vtk.vtkIntArray()
16117 self.mThisProcXyzs = vtk.vtkDoubleArray()
16118 self.mTargetMatchXyzs = vtk.vtkDoubleArray()
16119 self.mDistSqrds = vtk.vtkDoubleArray()
16120
16121 def ParallelSetupFromFindClosestNPointsToList(self, inMyProcData):
16122 self.mPointsPerProcess = inMyProcData.mNumToFind
16123 mypid, numproc = UseMPIToFillInSharedListNPerProcess(
16124 inMyProcData.mThisProcIds, self.mPointsPerProcess, self.mThisProcIds, 0)
16125 UseMPIToFillInSharedListNPerProcess(
16126 inMyProcData.mTargetMatchIds, self.mPointsPerProcess, self.mTargetMatchIds, 0)
16127 UseMPIToFillInSharedListNPerProcess(
16128 inMyProcData.mDistSqrds, self.mPointsPerProcess, self.mDistSqrds, 1)
16129 UseMPIToFillInSharedListNPerProcess(
16130 inMyProcData.mThisProcXyzs, self.mPointsPerProcess * 3, self.mThisProcXyzs, 1)
16131 UseMPIToFillInSharedListNPerProcess(
16132 inMyProcData.mTargetMatchXyzs, self.mPointsPerProcess * 3, self.mTargetMatchXyzs, 1)
16133
16134 self.mMyPid = mypid
16135 self.mNumProcesses = numproc
16136
16137 def FindNClosestPointsNdxInList(self, inHowMany):
16138 import heapq
16139
16140 numPoints = self.mPointsPerProcess * self.mNumProcesses
16141 if PhactoriDbg():
16142 myDebugPrint3(str(inHowMany) + " " + str(numPoints) + "\n")
16143 if numPoints < inHowMany:
16144 exit(-1)
16145 topNHeap = []
16146 for ii in range(0, inHowMany):
16147 heapq.heappush(topNHeap, (-self.mDistSqrds.GetValue(ii), ii))
16148 for ii in range(inHowMany, numPoints):
16149 testval = -self.mDistSqrds.GetValue(ii)
16150 if testval > topNHeap[0][0]:
16151 heapq.heappushpop(topNHeap, (testval, ii))
16152
16153 self.mClosestNRefs = []
16154 for ii in range(0, inHowMany):
16155 item = heapq.heappop(topNHeap)
16156 self.mClosestNRefs.append((-item[0], item[1]))
16157
16158 self.mClosestNRefs.reverse()
16159
16160 if PhactoriDbg():
16161 myDebugPrint3("FindNClosestPointsNdxInList:\n" + str(self.mClosestNRefs) + "\n")
16162
16163 def MakeNClosestPointsNdxInListTableString(self, inMakeHeaderLine = True):
16164 if inMakeHeaderLine:
16165 retStr = "index, distance, distance squared, " \
16166 "source node id, source x, source y, source z, " \
16167 "target node id, target x, target y, target z\n"
16168 else:
16169 retStr = ""
16170 for ii in range(0, len(self.mClosestNRefs)):
16171 ndx = self.mClosestNRefs[ii][1]
16172 srcndid = self.mThisProcIds.GetValue(ndx)
16173 tgtndid = self.mTargetMatchIds.GetValue(ndx)
16174 distsqrd = self.mDistSqrds.GetValue(ndx)
16175 dist = math.sqrt(distsqrd)
16176 pndx = ndx*3
16177 srcx = self.mThisProcXyzs.GetValue(pndx)
16178 srcy = self.mThisProcXyzs.GetValue(pndx+1)
16179 srcz = self.mThisProcXyzs.GetValue(pndx+2)
16180 tgtx = self.mTargetMatchXyzs.GetValue(pndx)
16181 tgty = self.mTargetMatchXyzs.GetValue(pndx+1)
16182 tgtz = self.mTargetMatchXyzs.GetValue(pndx+2)
16183 retStr += str(ii) + ", " + \
16184 str(dist) + ", " + \
16185 str(distsqrd) + ", " + \
16186 str(srcndid) + ", " + \
16187 str(srcx) + ", " + \
16188 str(srcy) + ", " + \
16189 str(srcz) + ", " + \
16190 str(tgtndid) + ", " + \
16191 str(tgtx) + ", " + \
16192 str(tgty) + ", " + \
16193 str(tgtz) + "\n"
16194 return retStr
16195
16196 def ToStr(self):
16197 retStr = "parallel shared closest " + str(self.mPointsPerProcess) + " points:\n" + \
16198 "index:process:pndx source id, target id, dist sqrd: source xyz: target xyz\n"
16199 for ii in range(0, self.mPointsPerProcess * self.mNumProcesses):
16200 pp = ii*3
16201 adst = str(ii) + ":" + \
16202 str(ii/self.mPointsPerProcess) + ":" + \
16203 str(ii%self.mPointsPerProcess) + ": " + \
16204 str(self.mThisProcIds.GetValue(ii)) + ", " + \
16205 str(self.mTargetMatchIds.GetValue(ii)) + ", " + \
16206 str(self.mDistSqrds.GetValue(ii)) + ": " + \
16207 str(self.mThisProcXyzs.GetValue(pp)) + ", " + \
16208 str(self.mThisProcXyzs.GetValue(pp+1)) + ", " + \
16209 str(self.mThisProcXyzs.GetValue(pp+2)) + ": " + \
16210 str(self.mTargetMatchXyzs.GetValue(pp)) + ", " + \
16211 str(self.mTargetMatchXyzs.GetValue(pp+1)) + ", " + \
16212 str(self.mTargetMatchXyzs.GetValue(pp+2)) + "\n"
16213 retStr += adst
16214 return retStr
16215
16216 #phactori_combine_to_single_python_file_parent_1
16217 #from Operation.QuadInfoGQC import *
16218 #phactori_combine_to_single_python_file_subpiece_begin_1
16219 class QuadInfoGQC:
16220 def __init__(self):
16221 self.ptA = [0.0, 0.0, 0.0]
16222 self.ptB = [0.0, 0.0, 0.0]
16223 self.ptC = [0.0, 0.0, 0.0]
16224 self.ptD = [0.0, 0.0, 0.0]
16225 #using average of points instead of center
16226 self.ptAverage = [0.0, 0.0, 0.0]
16227 self.normal = None
16228 self.cellId = -1
16229 self.index = -1
16230
16231 def PopulateFromVtkData(self, inInputCsData, globalCellIdArray, quadIndex):
16232 self.index = quadIndex
16233 cellPointIds = vtk.vtkIdList()
16234 inInputCsData.GetCellPoints(quadIndex, cellPointIds)
16235 numids = cellPointIds.GetNumberOfIds()
16236 if numids != 4:
16237 myDebugPrint3AndException("GetQuadClosestToPointsInBlock2Params: not a quad")
16238 inInputCsData.GetPoint(cellPointIds.GetId(0), self.ptA)
16239 inInputCsData.GetPoint(cellPointIds.GetId(1), self.ptB)
16240 inInputCsData.GetPoint(cellPointIds.GetId(2), self.ptC)
16241 inInputCsData.GetPoint(cellPointIds.GetId(3), self.ptD)
16242 self.ptAverage[0] = (self.ptA[0] + self.ptB[0] + self.ptC[0] + self.ptD[0]) * 0.25
16243 self.ptAverage[1] = (self.ptA[1] + self.ptB[1] + self.ptC[1] + self.ptD[1]) * 0.25
16244 self.ptAverage[2] = (self.ptA[2] + self.ptB[2] + self.ptC[2] + self.ptD[2]) * 0.25
16245 if globalCellIdArray != None:
16246 self.cellId = globalCellIdArray.GetValue(quadIndex)
16247
16248 def PopulateFromInfoArrays(self, index, doubleArray, integerArray):
16249 "given arrays which were populated with the help of AddToInfoArrays(),\n set up this quad to match the one represented in the arrays at the\n given index"
16250 ptIndx = index*15
16251 idIndx = index
16252 self.ptA[0] = doubleArray[ptIndx]
16253 self.ptA[1] = doubleArray[ptIndx+1]
16254 self.ptA[2] = doubleArray[ptIndx+2]
16255 self.ptB[0] = doubleArray[ptIndx+3]
16256 self.ptB[1] = doubleArray[ptIndx+4]
16257 self.ptB[2] = doubleArray[ptIndx+5]
16258 self.ptC[0] = doubleArray[ptIndx+6]
16259 self.ptC[1] = doubleArray[ptIndx+7]
16260 self.ptC[2] = doubleArray[ptIndx+8]
16261 self.ptD[0] = doubleArray[ptIndx+9]
16262 self.ptD[1] = doubleArray[ptIndx+10]
16263 self.ptD[2] = doubleArray[ptIndx+11]
16264 self.ptAverage[0] = doubleArray[ptIndx+12]
16265 self.ptAverage[1] = doubleArray[ptIndx+13]
16266 self.ptAverage[2] = doubleArray[ptIndx+14]
16267 self.cellId = integerArray.append(self.cellId)
16268
16269 def AddToInfoArrays(self, outDoubleArray, outIntegerArray):
16270 "add the quad points, point average, and cellId to the argument arrays\n for purspose of doing mpi broadcast/reduce work"
16271 outDoubleArray.append(self.ptA[0])
16272 outDoubleArray.append(self.ptA[1])
16273 outDoubleArray.append(self.ptA[2])
16274 outDoubleArray.append(self.ptB[0])
16275 outDoubleArray.append(self.ptB[1])
16276 outDoubleArray.append(self.ptB[2])
16277 outDoubleArray.append(self.ptC[0])
16278 outDoubleArray.append(self.ptC[1])
16279 outDoubleArray.append(self.ptC[2])
16280 outDoubleArray.append(self.ptD[0])
16281 outDoubleArray.append(self.ptD[1])
16282 outDoubleArray.append(self.ptD[2])
16283 outDoubleArray.append(self.ptAverage[0])
16284 outDoubleArray.append(self.ptAverage[1])
16285 outDoubleArray.append(self.ptAverage[2])
16286 outIntegerArray.append(self.cellId)
16287
16288 def AddZeroQuadToInfoArrays(self, outDoubleArray, outIntegerArray):
16289 "add zeros to the argument arrays representing a blank quad\n for purspose of doing mpi broadcast/reduce work"
16290 for ii in range(0, 15):
16291 outDoubleArray.append(0.0)
16292 outIntegerArray.append(int(0))
16293
16294 def CalculateDistanceSquaredTo(self, onePt):
16295 return vecDistanceSquared(onePt, self.ptAverage)
16296
16297 def ToString(self):
16298 retStr = str(self.index) + " " + str(self.cellId) + "\n" + \
16299 str(self.ptA) + "\n" + \
16300 str(self.ptB) + "\n" + \
16301 str(self.ptC) + "\n" + \
16302 str(self.ptD) + "\n" + \
16303 str(self.ptAverage) + "\n"
16304 return retStr
16305
16306 def CalculateNormal(self):
16307 vec1 = vecFromAToB(self.ptA, self.ptC)
16308 vec2 = vecFromAToB(self.ptB, self.ptD)
16309 vecCrs = vecCrossProduct(vec1, vec2)
16310 self.normal = vecNormalize(vecCrs)
16311
16312 def MakeLogSamplePointsAlongRayStartingAtAveragePoint(self, rayDirection, startStep, multiplier, maxDistance):
16313 smplList = []
16314 newPt = vecMultiplyAdd(self.ptAverage, rayDirection, 0.0)
16315 smplList.append(newPt)
16316 thisDistance = startStep
16317 count = 1
16318 while thisDistance < maxDistance:
16319 newPt = vecMultiplyAdd(self.ptAverage, rayDirection, thisDistance)
16320 smplList.append(newPt)
16321 thisDistance *= multiplier
16322 count += 1
16323 if count > 200:
16324 break
16325 if PhactoriDbg(100):
16326 myDebugPrint3("MakeLogSamplePointsAlongRayStartingAtAveragePoint:\n" + \
16327 str(len(smplList)) + " " + \
16328 str(thisDistance) + " " + \
16329 str(count) + \
16330 "\n" + str(smplList[0]) + \
16331 "\n" + str(smplList[-1]) + \
16332 "\n", 100)
16333 return smplList
16334
16335 def MakeSamplePointsAlongRayStartingAtAveragePoint(self, rayDirection, numSamples, maxDistance):
16336 smplList = []
16337 #for ii in range(-50,51):
16338 sampleStep = maxDistance / (float(numSamples - 1))
16339 for ii in range(0, numSamples):
16340 rr = float(ii) * sampleStep
16341 newPt = vecMultiplyAdd(self.ptAverage, rayDirection, rr)
16342 smplList.append(newPt)
16343 return smplList
16344
16345 def MakeSamplePointsAlongRayFromNearbyPoint(self, rayDefiningPoint):
16346 "create a vector from rayDefiningPoint to the average point of this ray,\n VV. Create sample points along a ray starting at the average point of\n the quad (self.ptAverage) along the vector VV"
16347 vecVUN = vecFromAToB(rayDefiningPoint, self.ptAverage)
16348 vecVV= vecNormalize(vecVUN)
16349 return self.MakeSamplePointsAlongRayStartingAtAveragePoint(vecVV, 50, 0.05)
16350
16351 def MakeLogSamplePointsAlongRayFromNearbyPoint(self, rayDefiningPoint, startStep, multiplier, maxDistance):
16352 "create a vector from rayDefiningPoint to the average point of this ray,\n VV. Create sample points along a ray starting at the average point of\n the quad (self.ptAverage) along the vector VV. Space the sample points\n in a logarithmic manner controlled by startStep, multiplier, and\n maxDistance"
16353 vecVUN = vecFromAToB(rayDefiningPoint, self.ptAverage)
16354 vecVV= vecNormalize(vecVUN)
16355 return self.MakeLogSamplePointsAlongRayStartingAtAveragePoint(vecVV, startStep, multiplier, maxDistance)
16356
16357 def MakePerpendicularSamplePoints(self):
16358 "create a list of sample points based on the average quad point (later\n the center) and thr normal to the quad"
16359 self.CalculateNormal()
16360 return self.MakeSamplePointsAlongRayStartingAtAveragePoint(self.normal, 50, 0.05)
16361
16362 #phactori_combine_to_single_python_file_subpiece_end_1
16363
16364 #phactori_combine_to_single_python_file_parent_1
16365 #from Operation.PhactoriSegment import *
16366 #phactori_combine_to_single_python_file_subpiece_begin_1
16367 class PhactoriSegment:
16368 def __init__(self):
16369 self.ptA = None
16370 self.ptB = None
16371 self.AtoB = None
16372 self.lengthSquared = None
16373 self.oneOverLenSqrd = None
16374 self.boundingBox = None
16375
16376 def SetPoints(self, ptA, ptB):
16377 self.ptA = list(ptA)
16378 self.ptB = list(ptB)
16379 self.AtoB = vecFromAToB(self.ptA, self.ptB)
16380 self.lengthSquared = vecMagnitudeSquared(self.AtoB)
16381 if self.lengthSquared == 0.0:
16382 myDebugPrint3AndException("PhactoriSegment:SetPoints self.lengthSquared is 0.0\n")
16383 self.oneOverLenSqrd = 1.0 / self.lengthSquared
16384
16385 self.boundingBox = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
16386 if self.ptA[0] <= self.ptB[0]:
16387 self.boundingBox[0] = ptA[0]
16388 self.boundingBox[1] = ptB[0]
16389 else:
16390 self.boundingBox[0] = ptB[0]
16391 self.boundingBox[1] = ptA[0]
16392 if self.ptA[1] <= self.ptB[1]:
16393 self.boundingBox[2] = ptA[1]
16394 self.boundingBox[3] = ptB[1]
16395 else:
16396 self.boundingBox[2] = ptB[1]
16397 self.boundingBox[3] = ptA[1]
16398 if self.ptA[2] <= self.ptB[2]:
16399 self.boundingBox[4] = ptA[2]
16400 self.boundingBox[5] = ptB[2]
16401 else:
16402 self.boundingBox[4] = ptB[2]
16403 self.boundingBox[5] = ptA[2]
16404
16405 #if PhactoriDbg(100):
16406 # myDebugPrint3("PhactoriSegment:SetPoints\n" +\
16407 # str(self.ptA) + "\n" + \
16408 # str(self.ptB) + "\n" + \
16409 # str(self.AtoB) + "\n" + \
16410 # str(self.lengthSquared) + "\n" + \
16411 # str(self.oneOverLenSqrd) + "\n")
16412
16413 def FindDistanceToPoint(self, testPoint):
16414 return math.sqrt(self.FindDistanceSquaredToPoint(testPoint))
16415
16416 def FindDistanceToPointProjected(self, testPoint, projectionAxis):
16417 return math.sqrt(self.FindDistanceSquaredToPointProjected(testPoint, projectionAxis))
16418
16419 def FindNearestPointOnSegmentToPoint(self, testPoint):
16420 if self.lengthSquared == 0.0:
16421 return list(self.ptA)
16422 AtoTest = vecFromAToB(self.ptA, testPoint)
16423 tt = vecDotProduct(AtoTest, self.AtoB) * self.oneOverLenSqrd
16424 if tt <= 0.0:
16425 return list(self.ptA)
16426 elif tt >= 1.0:
16427 return list(self.ptB)
16428 else:
16429 testProjectedToSegment = vecMultiplyAdd(self.ptA, self.AtoB, tt)
16430 return testProjectedToSegment
16431
16432 def ProjectPointOntoPlane(self, pointToChange, projectionAxis):
16433 if projectionAxis == 0:
16434 pointToChange[0] = 0.0
16435 elif projectionAxis == 1:
16436 pointToChange[1] = 0.0
16437 elif projectionAxis == 2:
16438 pointToChange[2] = 0.0
16439
16440 def FindNearestPointOnSegmentToPointProjected(self, testPoint, projectionAxis):
16441 retPoint = self.FindNearestPointOnSegmentToPoint(testPoint)
16442 self.ProjectPointOntoPlane(retPoint, projectionAxis)
16443 return retPoint
16444
16445 def FindDistanceSquaredToPoint(self, testPoint):
16446 testPointProjectedOntoSegment = self.FindNearestPointOnSegmentToPoint(testPoint)
16447 return vecDistanceSquared(testPoint, testPointProjectedOntoSegment)
16448
16449 def FindDistanceSquaredToPointProjected(self, testPoint, projectionAxis):
16450 testPointProjectedOntoSegment = self.FindNearestPointOnSegmentToPointProjected(testPoint, projectionAxis)
16451 localTestPoint = list(testPoint)
16452 self.ProjectPointOntoPlane(localTestPoint, projectionAxis)
16453 return vecDistanceSquared(localTestPoint, testPointProjectedOntoSegment)
16454
16455 def MyBoundingBoxIntersectsTargetBoundingBox(self, testBoundingBox):
16456 if self.boundingBox[0] > testBoundingBox[1]:
16457 return False
16458 if self.boundingBox[1] < testBoundingBox[0]:
16459 return False
16460 if self.boundingBox[2] > testBoundingBox[3]:
16461 return False
16462 if self.boundingBox[3] < testBoundingBox[2]:
16463 return False
16464 if self.boundingBox[4] > testBoundingBox[5]:
16465 return False
16466 if self.boundingBox[5] < testBoundingBox[4]:
16467 return False
16468 return True
16469
16470 def EitherEndpointIsInBoundingBox(self, testBoundingBox):
16471 ptIsIn = True
16472 if (self.ptA[0] < testBoundingBox[0]):
16473 ptIsIn = False
16474 if (self.ptA[0] > testBoundingBox[1]):
16475 ptIsIn = False
16476 if (self.ptA[1] < testBoundingBox[2]):
16477 ptIsIn = False
16478 if (self.ptA[1] > testBoundingBox[3]):
16479 ptIsIn = False
16480 if (self.ptA[2] < testBoundingBox[4]):
16481 ptIsIn = False
16482 if (self.ptA[2] > testBoundingBox[5]):
16483 ptIsIn = False
16484 if ptIsIn == True:
16485 return True
16486 ptIsIn = True
16487 if (self.ptB[0] < testBoundingBox[0]):
16488 ptIsIn = False
16489 if (self.ptB[0] > testBoundingBox[1]):
16490 ptIsIn = False
16491 if (self.ptB[1] < testBoundingBox[2]):
16492 ptIsIn = False
16493 if (self.ptB[1] > testBoundingBox[3]):
16494 ptIsIn = False
16495 if (self.ptB[2] < testBoundingBox[4]):
16496 ptIsIn = False
16497 if (self.ptB[2] > testBoundingBox[5]):
16498 ptIsIn = False
16499 if ptIsIn == True:
16500 return True
16501 return False
16502
16503 def IntersectsXYRectangle(self, minU, maxU, minV, maxV, posW):
16504 #myDebugPrint3("IntersectsXYRectangle entered\n")
16505 #myDebugPrint3(str([minU, maxU, minV, maxV, posW]) + "\n")
16506 #myDebugPrint3(str(self.boundingBox) + "\n")
16507 if self.boundingBox[4] > posW:
16508 return False
16509 if self.boundingBox[5] < posW:
16510 return False
16511 tt = (posW - self.ptA[2])/(self.ptB[2] - self.ptA[2])
16512 #myDebugPrint3(str(tt) + "\n")
16513 uIntersect = self.ptA[0] + tt * (self.ptB[0] - self.ptA[0])
16514 #myDebugPrint3(str(uIntersect) + "\n")
16515 if uIntersect < minU:
16516 return False
16517 if uIntersect > maxU:
16518 return False
16519 vIntersect = self.ptA[1] + tt * (self.ptB[1] - self.ptA[1])
16520 #myDebugPrint3(str(vIntersect) + "\n")
16521 if vIntersect < minV:
16522 return False
16523 if vIntersect > maxV:
16524 return False
16525 return True
16526
16527 def IntersectsXZRectangle(self, minU, maxU, minV, maxV, posW):
16528 if self.boundingBox[2] > posW:
16529 return False
16530 if self.boundingBox[3] < posW:
16531 return False
16532 tt = (posW - self.ptA[1])/(self.ptB[1] - self.ptA[1])
16533 uIntersect = self.ptA[0] + tt * (self.ptB[0] - self.ptA[0])
16534 if uIntersect < minU:
16535 return False
16536 if uIntersect > maxU:
16537 return False
16538 vIntersect = self.ptA[2] + tt * (self.ptB[2] - self.ptA[2])
16539 if vIntersect < minV:
16540 return False
16541 if vIntersect > maxV:
16542 return False
16543 return True
16544
16545 def IntersectsYZRectangle(self, minU, maxU, minV, maxV, posW):
16546 if self.boundingBox[0] > posW:
16547 return False
16548 if self.boundingBox[1] < posW:
16549 return False
16550 tt = (posW - self.ptA[0])/(self.ptB[0] - self.ptA[0])
16551 uIntersect = self.ptA[1] + tt * (self.ptB[1] - self.ptA[1])
16552 if uIntersect < minU:
16553 return False
16554 if uIntersect > maxU:
16555 return False
16556 vIntersect = self.ptA[2] + tt * (self.ptB[2] - self.ptA[2])
16557 if vIntersect < minV:
16558 return False
16559 if vIntersect > maxV:
16560 return False
16561 return True
16562
16563 def IntersectsBoundingBox(self, testBoundingBox):
16564 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBox entered\n")
16565 #myDebugPrint3("ptA: " + str(self.ptA) + "\n")
16566 #myDebugPrint3("ptB: " + str(self.ptB) + "\n")
16567 #myDebugPrint3("box: " + str(testBoundingBox) + "\n")
16568
16569 if self.MyBoundingBoxIntersectsTargetBoundingBox(testBoundingBox) == False:
16570 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBox returning false due to bounding box test\n")
16571 return False
16572
16573 if self.EitherEndpointIsInBoundingBox(testBoundingBox) == True:
16574 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBox returning false due to endpoint in box test\n")
16575 return True
16576
16577 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBox testing against all six sides\n")
16578 if self.IntersectsXYRectangle(testBoundingBox[0], testBoundingBox[1], testBoundingBox[2], testBoundingBox[3], testBoundingBox[4]):
16579 return True
16580 if self.IntersectsXYRectangle(testBoundingBox[0], testBoundingBox[1], testBoundingBox[2], testBoundingBox[3], testBoundingBox[5]):
16581 return True
16582 if self.IntersectsXZRectangle(testBoundingBox[0], testBoundingBox[1], testBoundingBox[4], testBoundingBox[5], testBoundingBox[2]):
16583 return True
16584 if self.IntersectsXZRectangle(testBoundingBox[0], testBoundingBox[1], testBoundingBox[4], testBoundingBox[5], testBoundingBox[3]):
16585 return True
16586 if self.IntersectsYZRectangle(testBoundingBox[2], testBoundingBox[3], testBoundingBox[4], testBoundingBox[5], testBoundingBox[4]):
16587 return True
16588 if self.IntersectsYZRectangle(testBoundingBox[2], testBoundingBox[3], testBoundingBox[4], testBoundingBox[5], testBoundingBox[5]):
16589 return True
16590
16591 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBox returning false, no side intersection\n")
16592 return False
16593
16594 def IntersectsBoundingBoxProjected(self, boundingBox, projectionAxis):
16595 #myDebugPrint3("PhactoriSegment.IntersectsBoundingBoxProjected entered\n")
16596 if (projectionAxis < 0) or (projectionAxis > 2):
16597 return self.IntersectsBoundingBox(boundingBox)
16598
16599 #inefficient but simple method of handling projection: make projected
16600 #bounding box (rectangle) and projected segment and do 3d version
16601 localProjectedPointA = list(self.ptA)
16602 localProjectedPointB = list(self.ptB)
16603 localProjectedBoundingBox = list(boundingBox)
16604 localProjectedPointA[projectionAxis] = 0.0
16605 localProjectedPointB[projectionAxis] = 0.0
16606 localProjectedBoundingBox[2*projectionAxis] = 0.0
16607 localProjectedBoundingBox[2*projectionAxis+1] = 0.0
16608 localProjectedSegment = PhactoriSegment()
16609 localProjectedSegment.SetPoints(localProjectedPointA, localProjectedPointB)
16610 intersectionFlag = localProjectedSegment.IntersectsBoundingBox(localProjectedBoundingBox)
16611 return intersectionFlag
16612
16613 #phactori_combine_to_single_python_file_subpiece_end_1
16614
16615 #phactori_combine_to_single_python_file_parent_1
16616 #from Operation.PhactoriOperationBlock import *
16617 #phactori_combine_to_single_python_file_subpiece_begin_1
16618
16619 global FlagToTestOutgoingPvGeometryFilter
16620 FlagToTestOutgoingPvGeometryFilter = False
16621
16622 global WriteEachDeadCellElementToFiles
16623 WriteEachDeadCellElementToFiles = False
16624
16625 class BlockRecursionControlItem:
16626 "see DoMethodPerBlock(); mOperationPerBlock should be set to a method\n which takes 1 parameter, mParameters should be set to the parameter\n instance which will be passes to the mOperationPerBlock call"
16627 def __init__(self):
16628 self.mOperationPerBlock = None
16629 self.mParameters = None
16630
16631 class PhactoriOperationBlock:
16632 "manages one stage of the data pipeline, analagous to ParaView Filter\n\n An instance of this class represents and manages one stage of the data\n pipeline which has been set up for management by phatori. It creates and\n holds a reference to a ParaView/Catalyst/vtk Filter which is doing the\n real work--this class might be thought of as an adapter or interface from\n phactori to ParaView. As currently implemented, an operation is assumed to\n have only one input and one output. Multiple operations can have the same\n input, so a tree structure is allowed rather than just a linear pipe.\n Operations with multiple inputs and outputs are conceiveable, and may be\n added pending user requirements.\n The instance is presumed to contain a name unique amound the operation\n blocks and keeps a reference to the input operation (by name), the \n ParaView/Catalyst filter which is built, and some flags determining where\n we are in the construction process.\n "
16633 def __init__(self):
16634 self.mName = ""
16635 self.mInputOperationName = None
16636 self.mType = ""
16637 self.mHasBeenConstructed = None
16638 self.mParaViewFilter = None
16639 #for keeping track of data bounds for this operation and only updating
16640 #it when necessary
16641 self.mDataBoundsIsCurrent = False
16642 self.mDataBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]
16643 self.mOperationSpecifics = None
16644
16645 #If this is a purely internal pipeline filter, this will remain None.
16646 #If somebody uses the filter for rendering, it will be created and
16647 #handed off for rendering--only needs creation once.
16648 self.mOutgoingGeometryFilter = None
16649
16650 #stores annotation time source, if one gets created associated with this
16651 #operation
16652 self.mParaViewTimeAnnotationSource = None
16653
16654 self.mRecursionParameterStore = {}
16655
16656
16657 def GetPvFilter(self):
16658 return self.mParaViewFilter
16659
16660 def CreateOutgoingPvGeometryFilter(self):
16661 savedActiveSource = GetActiveSource()
16662 self.mOutgoingGeometryFilter = ExtractSurface(self.GetPvFilter())
16663 if PhactoriDbg():
16664 myDebugPrint3("PhactoriOperationBlock::CreateOutgoingPvGeometryFilter\n"
16665 "created self.mOutgoingGeometryFilter: " + \
16666 str(self.mOutgoingGeometryFilter) + "\n")
16667
16668 SetActiveSource(savedActiveSource)
16669
16670 def GetOutgoingPvGeometryFilter(self):
16671 global FlagToTestOutgoingPvGeometryFilter
16672 if FlagToTestOutgoingPvGeometryFilter == False:
16673 if PhactoriDbg():
16674 myDebugPrint3("PhactoriOperationBlock::GetOutgoingPvGeometryFilter\n"
16675 "not creating or using external geometry filter:\n")
16676 return self.GetPvFilter()
16677 if self.mOutgoingGeometryFilter == None:
16678 self.CreateOutgoingPvGeometryFilter()
16679 return self.mOutgoingGeometryFilter
16680
16681 def GetListOfInputOperationNames(self):
16682 retList = self.mOperationSpecifics.GetListOfInputOperationNamesForThisOperationType()
16683 if self.mInputOperationName != None:
16684 retList.append(self.mInputOperationName)
16685 return retList
16686
16687 def DoUpdateDueToChangeInData(self, ioPipeAndViewsState):
16688 outputPvFilter = self.mParaViewFilter
16689 if self.mInputOperationName == None:
16690 inputOperation = ioPipeAndViewsState.mIncomingDefaultOperation
16691 else:
16692 inputOperation = ioPipeAndViewsState.mOperationBlocks[
16693 self.mInputOperationName]
16694 if inputOperation == None:
16695 myDebugPrint3AndException(
16696 "PhactoriOperationBlock::DoUpdateDueToChangeInData:\n"
16697 "couldn't find input operation with name: " + \
16698 str(self.mInputOperationName) + "\n")
16699
16700 self.mOperationSpecifics.DoUpdateDueToChangeInData(
16701 inputOperation.mParaViewFilter, outputPvFilter)
16702
16703 def DoMethodPerBlockFromParaViewFilter(self, inRecursionControlItem, inPvFilter):
16704 pvClientSideData = inPvFilter.GetClientSideObject().GetOutputDataObject(0)
16705 if pvClientSideData == None:
16706 if PhactoriDbg(100):
16707 myDebugPrint3(
16708 'DoMethodPerBlock: pvClientSideData is None, returning',100)
16709
16710 self.DoMethodPerBlockRecurse1(pvClientSideData, inRecursionControlItem)
16711
16712 def DoMethodPerBlock(self, inRecursionControlItem):
16713 "DoMethodPerBlock is a generic method for doing recursion through the\n multiblock dataset and doing something (a callback) on a per leaf block\n basis. Gets the clientside data and calls DoMethodPerBlockRecurse1\n which calls itself on internal nodes and calls\n inRecursionControlItem.mOperationToDoPerBlock on leaf block nodes"
16714 pvFilter = self.GetPvFilter()
16715 self.DoMethodPerBlockFromParaViewFilter(inRecursionControlItem, pvFilter)
16716
16717 def DoMethodPerBlockRecurse1(self, inInputCsData, inRecursionControlItem):
16718 "DoMethodPerBlockRecurse1 is a generic method for doing recursion through\n the multiblock dataset and doing something (a callback) on a per leaf block\n basis. Called by DoMethodPerBlock which got clientside data and calls\n itself on internal nodes and calls\n inRecursionControlItem.mOperationToDoPerBlock on leaf block nodes"
16719 #if PhactoriDbg(100):
16720 # myDebugPrint3('DoMethodPerBlockRecurse1 entered\n', 100)
16721
16722 icsdClassname = inInputCsData.GetClassName()
16723 if icsdClassname == "vtkMultiBlockDataSet" or \
16724 icsdClassname == "vtkExodusIIMultiBlockDataSet":
16725 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
16726 numBlocks = inInputCsData.GetNumberOfBlocks()
16727 for ii in range(0, numBlocks):
16728 oneBlock = inInputCsData.GetBlock(ii)
16729 if(oneBlock != None):
16730 self.DoMethodPerBlockRecurse1(oneBlock, inRecursionControlItem)
16731 else:
16732 inRecursionControlItem.mOperationToDoPerBlock(inInputCsData,
16733 inRecursionControlItem.mParameters)
16734
16735 #if PhactoriDbg(100):
16736 # myDebugPrint3('DoMethodPerBlockRecurse1 returning\n', 100)
16737
16738 def OutputElementListFromOneBlockToFile(self, inInputCsData, inParameters):
16739 if PhactoriDbg(100):
16740 myDebugPrint3("OutputElementListFromOneBlockToFile entered\n")
16741 cellData = inInputCsData.GetCellData()
16742 numTuplesX = cellData.GetNumberOfTuples()
16743 numArrays = cellData.GetNumberOfArrays()
16744
16745 global WriteEachDeadCellElementToFiles
16746 #if inParameters.mBlockCount == 0:
16747 if (inParameters.mFlag1 == 0) and (numTuplesX > 0):
16748 inParameters.mFlag1 = 1
16749 if WriteEachDeadCellElementToFiles:
16750 inParameters.mOutFileff.write("element index")
16751 for arrayIndex in range(0, numArrays):
16752 inParameters.mOutFileff.write(
16753 ", " + str(cellData.GetArray(arrayIndex).GetName()))
16754 inParameters.mOutFileff.write("\n")
16755
16756 if WriteEachDeadCellElementToFiles:
16757 for cellIndex in range(0, numTuplesX):
16758 inParameters.mOutFileff.write(
16759 str(cellIndex + inParameters.mElementCount))
16760 for arrayIndex in range(0, numArrays):
16761 inParameters.mOutFileff.write(
16762 ", " + str(cellData.GetArray(arrayIndex).GetTuple1(cellIndex)))
16763 inParameters.mOutFileff.write("\n")
16764
16765 killed_criteria_array = cellData.GetArray("KILLED")
16766 for cellIndex in range(0, numTuplesX):
16767 kval = killed_criteria_array.GetTuple1(cellIndex)
16768 kvalindex = int(kval)
16769 if (kvalindex >= 0) and (kvalindex < 10):
16770 inParameters.mKilledByCriteriaCount[kvalindex] += 1
16771
16772
16773 inParameters.mElementCount += inInputCsData.GetNumberOfCells()
16774 inParameters.mNodeCount += inInputCsData.GetNumberOfPoints()
16775 inParameters.mBlockCount += 1
16776
16777 if PhactoriDbg(100):
16778 myDebugPrint3("OutputElementListFromOneBlockToFile returning\n")
16779
16780 class FindClosestNPointsToListParams:
16781 "recursion structure for FindClosestNPointsToList(). Also servers to \n store/track data for passing back answer"
16782 def __init__(self, inParentOperation, inNumToFind,
16783 inTargetGlobalNodeIdList, inTargetPointXyzList):
16784 self.mParentOperation = inParentOperation
16785 self.mNumToFind = inNumToFind
16786
16787 #list of points we need to find closest local points to
16788 #(global node ids and geometry xyzs)
16789 self.mTargetIds = inTargetGlobalNodeIdList
16790 self.mTargetXyzs = inTargetPointXyzList
16791
16792 self.mKdtree = None
16793
16794 #closest N local points (local id and id from list and geometry xyzs
16795 #from local and from list and distance squared
16796 self.mThisProcIds = vtk.vtkIntArray()
16797 self.mTargetMatchIds = vtk.vtkIntArray()
16798 self.mThisProcXyzs = vtk.vtkDoubleArray()
16799 self.mTargetMatchXyzs = vtk.vtkDoubleArray()
16800 self.mDistSqrds = vtk.vtkDoubleArray()
16801
16802 self.mThisProcIds.SetNumberOfValues(inNumToFind)
16803 self.mTargetMatchIds.SetNumberOfValues(inNumToFind)
16804 self.mThisProcXyzs.SetNumberOfValues(inNumToFind*3)
16805 self.mTargetMatchXyzs.SetNumberOfValues(inNumToFind*3)
16806 self.mDistSqrds.SetNumberOfValues(inNumToFind)
16807
16808 #set default values indicating nothing found in those entries
16809 for ii in range(0,inNumToFind):
16810 self.mThisProcIds.SetValue(ii, -1)
16811 self.mTargetMatchIds.SetValue(ii, -1)
16812 self.mDistSqrds.SetValue(ii, sys.float_info.max)
16813 self.mMinDistSqrd = sys.float_info.max
16814 #index of the item that currently has the biggest distance
16815 self.mcfndx = 0
16816
16817 def SetUpKdtree(self):
16818 "take the points in this instance (presumably the target object) and\n put them in a kdtree (using scipy) so we can find the closest point\n in log(n) time"
16819 from scipy import spatial
16820 kdtreepts = []
16821 numpts = self.mTargetIds.GetNumberOfValues()
16822 for ii in range(0,numpts):
16823 pndx = ii*3
16824 kdtreepts.append([
16825 self.mTargetXyzs.GetValue(pndx),
16826 self.mTargetXyzs.GetValue(pndx+1),
16827 self.mTargetXyzs.GetValue(pndx+2)])
16828 self.mKdtree = None
16829 self.mKdtree = spatial.KDTree(kdtreepts)
16830
16831 def TestPointWithKdtree(self, inSrcId, inSrcXyz):
16832 nrstdist, nrstndx = self.mKdtree.query(inSrcXyz)
16833 #print "nrstdist: ", str(nrstdist)
16834 #print "nrstndx: ", str(nrstndx)
16835 tgtId = self.mTargetIds.GetValue(nrstndx)
16836 tgtXyz = self.mKdtree.data[nrstndx]
16837 #self.TestPointSub1(inSrcId, inSrcXyz[0], inSrcXyz[1], inSrcXyz[2],
16838 # tgtId, tgtXyz[0], tgtXyz[1], tgtXyz[2])
16839 self.TestPointSub2(inSrcId, inSrcXyz, tgtId, tgtXyz, nrstdist)
16840
16841 def TestPoint(self, inId, inXyz):
16842 "given an xyz point in the local processor (and its global node id)\n see if it is closer to any of the target points than the current\n set of nearest points and, if so, put it in the set, dropping\n others out if necessary"
16843 if PhactoriDbg():
16844 myDebugPrint3("TestPoint id " + str(inId))
16845 tgtxyzs = self.mTargetXyzs
16846 numtgtpts = self.mTargetIds.GetNumberOfValues()
16847 for pp in range(0, numtgtpts):
16848 tgtid = self.mTargetIds.GetValue(pp)
16849 ndx = pp*3
16850 self.TestPointSub1(inId, inXyz[0], inXyz[1], inXyz[2],
16851 tgtid, tgtxyzs.GetValue(ndx), tgtxyzs.GetValue(ndx+1),
16852 tgtxyzs.GetValue(ndx+2))
16853
16854 def TestPointSub2(self, inSrcId, inSrcXyz, inTgtId, inTgtXyz, inNrstdist):
16855 dstsqd = inNrstdist*inNrstdist
16856 if dstsqd >= self.mMinDistSqrd:
16857 #we already have mNumToFind closer
16858 #if PhactoriDbg():
16859 # myDebugPrint3("inSrcId inTgtId " + str(inSrcId) + " " + \
16860 # str(inTgtId) + \
16861 # " too far: " + str(dstsqd) + " >= " + \
16862 # str(self.mMinDistSqrd) + "\n")
16863 return
16864
16865 #replace the previous point that was furthest
16866 self.mDistSqrds.SetValue(self.mcfndx, dstsqd)
16867 self.mThisProcIds.SetValue(self.mcfndx, inSrcId)
16868 self.mTargetMatchIds.SetValue(self.mcfndx, inTgtId)
16869 gndx = self.mcfndx * 3
16870 self.mThisProcXyzs.SetValue(gndx, inSrcXyz[0])
16871 self.mThisProcXyzs.SetValue(gndx+1, inSrcXyz[1])
16872 self.mThisProcXyzs.SetValue(gndx+2, inSrcXyz[2])
16873 self.mTargetMatchXyzs.SetValue(gndx, inTgtXyz[0])
16874 self.mTargetMatchXyzs.SetValue(gndx+1, inTgtXyz[1])
16875 self.mTargetMatchXyzs.SetValue(gndx+2, inTgtXyz[2])
16876 #if PhactoriDbg():
16877 # myDebugPrint3("closer point found put in index " + \
16878 # str(self.mcfndx) + \
16879 # " dstsqrd: " + str(self.mDistSqrds.GetValue(self.mcfndx)) + "\n" + \
16880 # "\nsource id xyz: " + \
16881 # str(self.mThisProcIds.GetValue(self.mcfndx)) + " " + \
16882 # str(self.mThisProcXyzs.GetValue(gndx)) + ", " + \
16883 # str(self.mThisProcXyzs.GetValue(gndx+1)) + ", " + \
16884 # str(self.mThisProcXyzs.GetValue(gndx+2)) + ", " + \
16885 # "\ntarget id xyz: " + \
16886 # str(self.mTargetMatchIds.GetValue(self.mcfndx)) + " " + \
16887 # str(self.mTargetMatchXyzs.GetValue(gndx)) + ", " + \
16888 # str(self.mTargetMatchXyzs.GetValue(gndx+1)) + ", " + \
16889 # str(self.mTargetMatchXyzs.GetValue(gndx+2)) + "\n")
16890
16891 #now find which in the current list has the biggest distance, as it is
16892 #next in line for replacement (we do this to avoid having to shift
16893 #elements every time
16894 self.mcfndx = 0
16895 self.mMinDistSqrd = self.mDistSqrds.GetValue(0)
16896 #if PhactoriDbg():
16897 # myDebugPrint3("find next index to be replaced try 0 \n" + \
16898 # str(self.mMinDistSqrd) + "\n")
16899 for kk in range(1, self.mNumToFind):
16900 #if PhactoriDbg():
16901 # myDebugPrint3("try " + str(kk) + " " + \
16902 # str(self.mDistSqrds.GetValue(kk)) + " >? " + \
16903 # str(self.mMinDistSqrd)+ "\n")
16904 if self.mDistSqrds.GetValue(kk) > self.mMinDistSqrd:
16905 self.mcfndx = kk
16906 self.mMinDistSqrd = self.mDistSqrds.GetValue(kk)
16907 #if PhactoriDbg():
16908 # myDebugPrint3("yes, now " + str(self.mcfndx) + " " + \
16909 # str(self.mMinDistSqrd) + "\n")
16910 #if PhactoriDbg():
16911 # myDebugPrint3("next to be replaced ndx: " + str(self.mcfndx) + \
16912 # " sid: " + \
16913 # str(self.mThisProcIds.GetValue(self.mcfndx)) + \
16914 # " tid: " + \
16915 # str(self.mTargetMatchIds.GetValue(self.mcfndx)) + \
16916 # " dsqrd: " + \
16917 # str(self.mDistSqrds.GetValue(self.mcfndx)) + "\n")
16918
16919 def TestPointSub1(self, inId, inX, inY, inZ, tId, tX, tY, tZ):
16920 "given an xyz point in the local processor (and its global node id)\n see if it is closer to one of the target points than the current\n set of nearest points and, if so, put it in the set, dropping\n others out if necessary"
16921 ddx = inX - tX
16922 ddy = inY - tY
16923 ddz = inZ - tZ
16924 dstsqd = ddx*ddx + ddy*ddy + ddz*ddz
16925 if dstsqd >= self.mMinDistSqrd:
16926 #we already have mNumToFind closer
16927 #if PhactoriDbg():
16928 # myDebugPrint3("inId tId " + str(inId) + " " + str(tId) + \
16929 # " too far: " + str(dstsqd) + " >= " + \
16930 # str(self.mMinDistSqrd) + "\n")
16931 return
16932
16933 #replace the previous point that was furthest
16934 self.mDistSqrds.SetValue(self.mcfndx, dstsqd)
16935 self.mThisProcIds.SetValue(self.mcfndx, inId)
16936 self.mTargetMatchIds.SetValue(self.mcfndx, tId)
16937 gndx = self.mcfndx * 3
16938 self.mThisProcXyzs.SetValue(gndx, inX)
16939 self.mThisProcXyzs.SetValue(gndx+1, inY)
16940 self.mThisProcXyzs.SetValue(gndx+2, inZ)
16941 self.mTargetMatchXyzs.SetValue(gndx, tX)
16942 self.mTargetMatchXyzs.SetValue(gndx+1, tY)
16943 self.mTargetMatchXyzs.SetValue(gndx+2, tZ)
16944 if PhactoriDbg():
16945 myDebugPrint3("closer point found put in index " + \
16946 str(self.mcfndx) + \
16947 " dstsqrd: " + str(self.mDistSqrds.GetValue(self.mcfndx)) + "\n" + \
16948 "\nsource id xyz: " + \
16949 str(self.mThisProcIds.GetValue(self.mcfndx)) + " " + \
16950 str(self.mThisProcXyzs.GetValue(gndx)) + ", " + \
16951 str(self.mThisProcXyzs.GetValue(gndx+1)) + ", " + \
16952 str(self.mThisProcXyzs.GetValue(gndx+2)) + ", " + \
16953 "\ntarget id xyz: " + \
16954 str(self.mTargetMatchIds.GetValue(self.mcfndx)) + " " + \
16955 str(self.mTargetMatchXyzs.GetValue(gndx)) + ", " + \
16956 str(self.mTargetMatchXyzs.GetValue(gndx+1)) + ", " + \
16957 str(self.mTargetMatchXyzs.GetValue(gndx+2)) + "\n")
16958
16959 #now find which in the current list has the biggest distance, as it is
16960 #next in line for replacement (we do this to avoid having to shift
16961 #elements every time
16962 self.mcfndx = 0
16963 self.mMinDistSqrd = self.mDistSqrds.GetValue(0)
16964 if PhactoriDbg():
16965 myDebugPrint3("find next index to be replaced try 0 \n" + \
16966 str(self.mMinDistSqrd) + "\n")
16967 for kk in range(1, self.mNumToFind):
16968 if PhactoriDbg():
16969 myDebugPrint3("try " + str(kk) + " " + \
16970 str(self.mDistSqrds.GetValue(kk)) + " >? " + \
16971 str(self.mMinDistSqrd)+ "\n")
16972 if self.mDistSqrds.GetValue(kk) > self.mMinDistSqrd:
16973 self.mcfndx = kk
16974 self.mMinDistSqrd = self.mDistSqrds.GetValue(kk)
16975 if PhactoriDbg():
16976 myDebugPrint3("yes, now " + str(self.mcfndx) + " " + \
16977 str(self.mMinDistSqrd) + "\n")
16978 if PhactoriDbg():
16979 myDebugPrint3("next to be replaced ndx: " + str(self.mcfndx) + \
16980 " sid: " + \
16981 str(self.mThisProcIds.GetValue(self.mcfndx)) + \
16982 " tid: " + \
16983 str(self.mTargetMatchIds.GetValue(self.mcfndx)) + \
16984 " dsqrd: " + \
16985 str(self.mDistSqrds.GetValue(self.mcfndx)) + "\n")
16986
16987 def ToStr(self):
16988 retStr = "closest " + str(self.mNumToFind) + " points:\n" + \
16989 "index: source id, target id, dist sqrd: source xyz: target xyz\n"
16990 for ii in range(0, self.mNumToFind):
16991 pp = ii*3
16992 adst = str(ii) + ": " + \
16993 str(self.mThisProcIds.GetValue(ii)) + ", " + \
16994 str(self.mTargetMatchIds.GetValue(ii)) + ", " + \
16995 str(self.mDistSqrds.GetValue(ii)) + ": " + \
16996 str(self.mThisProcXyzs.GetValue(pp)) + ", " + \
16997 str(self.mThisProcXyzs.GetValue(pp+1)) + ", " + \
16998 str(self.mThisProcXyzs.GetValue(pp+2)) + ": " + \
16999 str(self.mTargetMatchXyzs.GetValue(pp)) + ", " + \
17000 str(self.mTargetMatchXyzs.GetValue(pp+1)) + ", " + \
17001 str(self.mTargetMatchXyzs.GetValue(pp+2)) + "\n"
17002 retStr += adst
17003 return retStr
17004
17005
17006 def FindClosestNPointsToList(self, inGlobalNodeIdList, inPointXyzList,
17007 inNumToFind):
17008 "given a list of node ids and xyz points, recursively find the nearest\n (geometrically) inNumToFind points in the local processor to the xyz\n points in inPointXyzList. Returns a list of inNumToFind global node\n ids and inNumToFind xyz points\n inGlobalNodeIds is vtkIntArray\n inPointXyzs is vtkDoubleArray\n returns a FindClosestNPointsToListParams instance which has list of\n length inNumToFind which contain the node id of the closest local\n process point, the node id of the corresponding point from the\n inGlobalNodeIdList, the xyzs of each of those, and this distance\n between (squared to save computation)"
17009 recursionItem = BlockRecursionControlItem()
17010 recursionItem.mParameters = \
17011 PhactoriOperationBlock.FindClosestNPointsToListParams(
17012 self, inNumToFind, inGlobalNodeIdList, inPointXyzList)
17013 recursionItem.mOperationToDoPerBlock = \
17014 self.FindClosestNPointsToListInBlock
17015 self.DoMethodPerBlock(recursionItem)
17016 return recursionItem.mParameters
17017
17018 def FindClosestNPointsToListInBlock(self, inInputCsData, inParameters):
17019 if PhactoriDbg(100):
17020 myDebugPrint3("FindClosestNPointsToListInBlock entered\n")
17021 pointsArray = inInputCsData.GetPoints()
17022 if pointsArray == None:
17023 #no points here
17024 return
17025 pointsData = inInputCsData.GetPointData()
17026 globalNodeIdArray = pointsData.GetArray('GlobalNodeId')
17027 numPoints = pointsArray.GetNumberOfPoints()
17028 ptXyz = [0.0, 0.0, 0.0]
17029
17030 #get target to set up Kdtree for quickly finding nearest point
17031 inParameters.SetUpKdtree()
17032
17033 for ndx in range(0,numPoints):
17034 #thePoint = pointsArray.GetPoint(ndx, ptXyz)
17035 if ndx % 100 == 0:
17036 if PhactoriDbg():
17037 myDebugPrint3("test " + str(ndx) + " of " + str(numPoints) + "\n")
17038 pointsArray.GetPoint(ndx, ptXyz)
17039 if(globalNodeIdArray == None):
17040 theGlobalNodeId = ndx + 1
17041 else:
17042 theGlobalNodeId = globalNodeIdArray.GetValue(ndx)
17043
17044 inParameters.TestPointWithKdtree(theGlobalNodeId, ptXyz)
17045 #inParameters.TestPoint(theGlobalNodeId, ptXyz)
17046 if PhactoriDbg(100):
17047 myDebugPrint3("FindClosestNPointsToListInBlock returning\n")
17048
17049 class MakeListOfAllPoints1Params:
17050 def __init__(self):
17051 self.mGlobalNodeIdList = vtk.vtkIntArray()
17052 self.mPointXYZList = vtk.vtkDoubleArray()
17053
17054 def MakeListOfAllPoints1(self):
17055 "recursively going through multiblock setup, make a list of all the\n points in this operation output in this process. We get a list\n of global node ids and a list of xyz geometry points"
17056 recursionItem = BlockRecursionControlItem()
17057 recursionItem.mParameters = \
17058 PhactoriOperationBlock.MakeListOfAllPoints1Params()
17059 recursionItem.mOperationToDoPerBlock = \
17060 self.MakeListOfAllPointsInBlock1
17061 self.DoMethodPerBlock(recursionItem)
17062 return recursionItem.mParameters.mGlobalNodeIdList, \
17063 recursionItem.mParameters.mPointXYZList
17064
17065 def MakeListOfAllPointsInBlock1(self, inInputCsData, inParameters):
17066 #if PhactoriDbg(100):
17067 # myDebugPrint3("MakeListOfAllPointsInBlock1 entered\n")
17068 pointsArray = inInputCsData.GetPoints()
17069 if pointsArray == None:
17070 #no points here
17071 return
17072 pointsData = inInputCsData.GetPointData()
17073 globalNodeIdArray = pointsData.GetArray('GlobalNodeId')
17074 numPoints = pointsArray.GetNumberOfPoints()
17075 ptXyz = [0.0, 0.0, 0.0]
17076 for ndx in range(0,pointsArray.GetNumberOfPoints()):
17077 #thePoint = pointsArray.GetPoint(ndx, ptXyz)
17078 pointsArray.GetPoint(ndx, ptXyz)
17079 if globalNodeIdArray == None:
17080 inParameters.mGlobalNodeIdList.InsertNextValue(ndx+1)
17081 else:
17082 inParameters.mGlobalNodeIdList.InsertNextValue(globalNodeIdArray.GetValue(ndx))
17083 inParameters.mPointXYZList.InsertNextValue(ptXyz[0])
17084 inParameters.mPointXYZList.InsertNextValue(ptXyz[1])
17085 inParameters.mPointXYZList.InsertNextValue(ptXyz[2])
17086 #if PhactoriDbg(100):
17087 # myDebugPrint3("MakeListOfAllPointsInBlock1 returning\n")
17088
17089 class MakeListOfAllPointsAndNodeIdsInBlock2Params:
17090 def __init__(self):
17091 self.mPointXYZAndNodeIdList = []
17092
17093 def MakeListOfAllPointsAndNodeIdsInBlock2(self, inInputCsData, inParameters):
17094 if PhactoriDbg(100):
17095 myDebugPrint3("MakeListOfAllPointsAndNodeIdsInBlock2 entered\n")
17096 pointsArray = inInputCsData.GetPoints()
17097 if pointsArray == None:
17098 #no points here
17099 return
17100 pointsData = inInputCsData.GetPointData()
17101 globalNodeIdArray = pointsData.GetArray('GlobalNodeId')
17102 numPoints = pointsArray.GetNumberOfPoints()
17103 ptXyz = [0.0, 0.0, 0.0]
17104 for ndx in range(0,pointsArray.GetNumberOfPoints()):
17105 #thePoint = pointsArray.GetPoint(ndx, ptXyz)
17106 pointsArray.GetPoint(ndx, ptXyz)
17107 if globalNodeIdArray == None:
17108 thisNodeId = -1
17109 else:
17110 thisNodeId = int(globalNodeIdArray.GetValue(ndx))
17111 inParameters.mPointXYZAndNodeIdList.append([ptXyz[0], ptXyz[1], ptXyz[2], thisNodeId])
17112 if PhactoriDbg(100):
17113 numPtsThisBlock = len(inParameters.mPointXYZAndNodeIdList)
17114 myDebugPrint3("num points after this block: " + str(numPtsThisBlock) + "\n")
17115 if numPtsThisBlock > 0:
17116 myDebugPrint3("last point: " + str(inParameters.mPointXYZAndNodeIdList[-1]) + "\n")
17117 if PhactoriDbg(100):
17118 myDebugPrint3("MakeListOfAllPointsAndNodeIdsInBlock2 returning\n")
17119
17120 def MakeListOfAllPointsAndNodeIdsOnThisProcessFromParaViewFilter(self, inInputFilter):
17121 if PhactoriDbg(100):
17122 myDebugPrint3("MakeListOfAllPointsAndNodeIdsOnThisProcessFromParaViewFilter entered\n")
17123 recursionItem = BlockRecursionControlItem()
17124 recursionItem.mParameters = PhactoriOperationBlock.MakeListOfAllPointsAndNodeIdsInBlock2Params()
17125 recursionItem.mOperationToDoPerBlock = self.MakeListOfAllPointsAndNodeIdsInBlock2
17126 self.DoMethodPerBlockFromParaViewFilter(recursionItem, inInputFilter)
17127 if PhactoriDbg(100):
17128 numPtsThisProcess = len(recursionItem.mParameters.mPointXYZAndNodeIdList)
17129 myDebugPrint3("num points in this process: " + str(numPtsThisProcess) + "\n")
17130 if numPtsThisProcess > 0:
17131 myDebugPrint3("last point: " + str(recursionItem.mParameters.mPointXYZAndNodeIdList[-1]) + "\n")
17132 if PhactoriDbg(100):
17133 myDebugPrint3("MakeListOfAllPointsAndNodeIdsOnThisProcessFromParaViewFilter returning\n")
17134 return recursionItem.mParameters.mPointXYZAndNodeIdList
17135
17136 class GetQuadClosestToPointsInBlock2Params:
17137 def __init__(self):
17138 self.testPointList = []
17139 self.distSqrdList = []
17140 self.closestList = []
17141
17142 def InitializeWithPointList(self, inTestPointList):
17143 self.testPointList = inTestPointList
17144 numTestPoints = len(inTestPointList)
17145 for ii in range(0, numTestPoints):
17146 self.distSqrdList.append(sys.float_info.max)
17147 self.closestList.append(None)
17148 if PhactoriDbg(100):
17149 myDebugPrint3("InitializeWithPointList: " + str(numTestPoints) + " " +\
17150 str(len(self.distSqrdList)) + " " + str(len(self.closestList)) +\
17151 "\n" + str(self.testPointList) + "\n" +\
17152 "\n" + str(self.distSqrdList) + "\n" +\
17153 "\n" + str(self.closestList) + "\n")
17154
17155 def GetQuadsClosestToPointsInBlock2(self, inInputCsData, inParameters):
17156 if PhactoriDbg(100):
17157 myDebugPrint3("GetCloseQuadsInBlock2 entered\n")
17158 numQuads = inInputCsData.GetNumberOfCells()
17159 if numQuads == 0:
17160 #no quads here
17161 return
17162
17163 if PhactoriDbg(100):
17164 myDebugPrint3(str(inParameters.testPointList) + "\n")
17165 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
17166
17167 cellsData = inInputCsData.GetCellData()
17168 globalCellIdArray = cellsData.GetArray('GlobalCellId')
17169 for quadIndex in range(0,numQuads):
17170 thisQuad = QuadInfoGQC()
17171 thisQuad.PopulateFromVtkData(inInputCsData, globalCellIdArray, quadIndex)
17172 for ptndx, oneTestPt in enumerate(inParameters.testPointList):
17173 testDist = thisQuad.CalculateDistanceSquaredTo(oneTestPt)
17174 if testDist < inParameters.distSqrdList[ptndx]:
17175 inParameters.closestList[ptndx] = thisQuad
17176 inParameters.distSqrdList[ptndx] = testDist
17177
17178 if PhactoriDbg(100):
17179 myDebugPrint3(str(inParameters.testPointList) + "\n")
17180 myDebugPrint3(str(inParameters.distSqrdList) + "\n")
17181
17182 if PhactoriDbg(100):
17183 myDebugPrint3("after this block:\n")
17184 for ii, oneQuad in enumerate(inParameters.closestList):
17185 myDebugPrint3(str(ii) + ": " + \
17186 str(inParameters.distSqrdList[ii]) + "\n" + \
17187 str(inParameters.testPointList[ii]) + "\n" + oneQuad.ToString())
17188 myDebugPrint3("\n")
17189
17190 if PhactoriDbg(100):
17191 myDebugPrint3("GetCloseQuadsInBlock2 returning\n")
17192
17193 def GetQuadsClosestToPointsOnThisProcessFromParaViewFilter(self, inInputFilter, inTestPointList):
17194 if PhactoriDbg(100):
17195 myDebugPrint3("GetQuadsClosestToPointsOnThisProcessFromParaViewFilter entered\n")
17196 recursionItem = BlockRecursionControlItem()
17197 recursionItem.mParameters = PhactoriOperationBlock.GetQuadClosestToPointsInBlock2Params()
17198 recursionItem.mParameters.InitializeWithPointList(inTestPointList)
17199 recursionItem.mOperationToDoPerBlock = self.GetQuadsClosestToPointsInBlock2
17200 self.DoMethodPerBlockFromParaViewFilter(recursionItem, inInputFilter)
17201 if PhactoriDbg(100):
17202 myDebugPrint3("GetQuadsClosestToPointsOnThisProcessFromParaViewFilter returning\n")
17203 return recursionItem.mParameters.closestList, recursionItem.mParameters.distSqrdList
17204
17205 class OutputElementListToFileParams:
17206 def __init__(self):
17207 self.mOutFileff = None
17208 self.mBlockCount = 0
17209 self.mElementCount = 0
17210 self.mNodeCount = 0
17211 self.mFlag1 = 0
17212 self.mKilledByCriteriaCount = [0,0,0,0,0,0,0,0,0,0]
17213
17214 def OutputElementListToFile(self, inFileNameToWrite):
17215 recursionItem = BlockRecursionControlItem()
17216
17217 recursionItem.mParameters = \
17218 PhactoriOperationBlock.OutputElementListToFileParams()
17219
17220 if WriteEachDeadCellElementToFiles:
17221 recursionItem.mParameters.mOutFileff = open(inFileNameToWrite, "w+b")
17222 recursionItem.mOperationToDoPerBlock = \
17223 self.OutputElementListFromOneBlockToFile
17224 self.DoMethodPerBlock(recursionItem)
17225 if WriteEachDeadCellElementToFiles:
17226 recursionItem.mParameters.mOutFileff.close()
17227 return recursionItem.mParameters
17228
17229 def OutputSingleElementFromBlockToTimeHistoryFile(
17230 self, inInputCsData, inParameters):
17231 if PhactoriDbg(100):
17232 myDebugPrint3("OutputSingleElementFromBlockToTimeHistoryFile entered\n")
17233 cellData = inInputCsData.GetCellData()
17234 numCellTuplesX = cellData.GetNumberOfTuples()
17235 numCellArrays = cellData.GetNumberOfArrays()
17236 pointData = inInputCsData.GetPointData()
17237 numPointTuplesX = cellData.GetNumberOfTuples()
17238 numPointArrays = pointData.GetNumberOfArrays()
17239
17240 #if inParameters.mBlockCount == 0:
17241 if (inParameters.mFlag1 == 0) and (numCellTuplesX > 0):
17242 inParameters.mFlag1 = 1
17243 #as constructed, we should only open once, so we can do 'w' not 'a+'
17244 inParameters.mOutElementFileff = open(inParameters.mOutElementFileName, "w")
17245 inParameters.mOutElementFileff.write("step, simtime")
17246 #inParameters.mOutElementFileff.write(", element index")
17247 for arrayIndex in range(0, numCellArrays):
17248 inParameters.mOutElementFileff.write(
17249 ", " + str(cellData.GetArray(arrayIndex).GetName()))
17250 inParameters.mOutElementFileff.write("\n")
17251
17252 inParameters.mOutNodeFileff = open(inParameters.mOutNodeFileName, "w")
17253 inParameters.mOutNodeFileff.write("step, simtime")
17254 for arrayIndex in range(0, numPointArrays):
17255 oneArray = pointData.GetArray(arrayIndex)
17256 numComp = oneArray.GetNumberOfComponents()
17257 oneArrayName = str(oneArray.GetName())
17258 if numComp == 1:
17259 inParameters.mOutNodeFileff.write(", " + oneArrayName)
17260 elif(numComp == 3):
17261 inParameters.mOutNodeFileff.write(
17262 ", " + oneArrayName + "x" + \
17263 ", " + oneArrayName + "y" + \
17264 ", " + oneArrayName + "z")
17265 else:
17266 myDebugPrint3AndException(
17267 "OutputSingleElementFromBlockToTimeHistoryFile:\n" \
17268 "expecting 1 or 3 components (A)\n")
17269 inParameters.mOutNodeFileff.write("\n")
17270
17271 #for now, only dump 1 element
17272 if numCellTuplesX > 0:
17273 numCellsToDo = 1
17274 else:
17275 numCellsToDo = 0
17276 for cellIndex in range(0, numCellsToDo):
17277 inParameters.mOutElementFileff.write(str(inParameters.mTimeStep) + ", " + \
17278 str(inParameters.mSimulationTime))
17279 #inParameters.mOutElementFileff.write(", " + \
17280 # str(cellIndex + inParameters.mElementCount))
17281 for arrayIndex in range(0, numCellArrays):
17282 inParameters.mOutElementFileff.write(
17283 ", " + str(cellData.GetArray(arrayIndex).GetTuple1(cellIndex)))
17284 inParameters.mOutElementFileff.write("\n")
17285
17286 #for now, only dump 1 node
17287 if numPointTuplesX > 0:
17288 numPointsToDo = 1
17289 else:
17290 numPointsToDo = 0
17291 for pointIndex in range(0, numPointsToDo):
17292 inParameters.mOutNodeFileff.write(str(inParameters.mTimeStep) + ", " + \
17293 str(inParameters.mSimulationTime))
17294 #inParameters.mOutNodeFileff.write(", " + \
17295 # str(pointIndex + inParameters.mCellCount))
17296 for arrayIndex in range(0, numPointArrays):
17297 #inParameters.mOutNodeFileff.write(
17298 # ", " + str(pointData.GetArray(arrayIndex).GetTuple1(0)))
17299 oneArray = pointData.GetArray(arrayIndex)
17300 numComp = oneArray.GetNumberOfComponents()
17301 if(numComp == 1):
17302 inParameters.mOutNodeFileff.write(
17303 ", " + str(pointData.GetArray(arrayIndex).GetTuple1(pointIndex)))
17304 elif(numComp == 3):
17305 theTuple = pointData.GetArray(arrayIndex).GetTuple3(0)
17306 inParameters.mOutNodeFileff.write( \
17307 ", " + str(theTuple[0]) + \
17308 ", " + str(theTuple[1]) + \
17309 ", " + str(theTuple[2]))
17310 else:
17311 myDebugPrint3AndException(
17312 "OutputSingleElementFromBlockToTimeHistoryFile:\n" \
17313 "expecting 1 or 3 components (B)\n")
17314 inParameters.mOutNodeFileff.write("\n")
17315
17316 inParameters.mNodeCount += inInputCsData.GetNumberOfPoints()
17317 inParameters.mElementCount += inInputCsData.GetNumberOfCells()
17318 inParameters.mBlockCount += 1
17319
17320 if PhactoriDbg(100):
17321 numCells = inInputCsData.GetNumberOfCells()
17322 if numCells > 0:
17323 numPoints = inInputCsData.GetNumberOfPoints()
17324 myDebugPrint3(
17325 "numCells: " + str(numCells) + "\n" \
17326 "numCellTuplesX: " + str(numCellTuplesX) + "\n" \
17327 "numPoints: " + str(numPoints) + "\n" \
17328 "numPointTuplesX: " + str(numPointTuplesX) + "\n")
17329
17330 if(inParameters.mOutElementFileff != None):
17331 inParameters.mOutElementFileff.flush()
17332 inParameters.mOutNodeFileff.flush()
17333
17334 #dump 1 node
17335
17336 if PhactoriDbg(100):
17337 myDebugPrint3("OutputSingleElementFromBlockToTimeHistoryFile returning\n")
17338
17339 class OutputSingleElementToTimeHistoryFileParams:
17340 def __init__(self):
17341 self.mOutElementFileff = None
17342 self.mOutElementFileName = None
17343 self.mOutNodeFileff = None
17344 self.mOutNodeFileName = None
17345 self.mTimeStep = 0
17346 self.mSimulationTime = 0.0
17347 self.mBlockCount = 0
17348 self.mElementCount = 0
17349 self.mNodeCount = 0
17350 self.mFlag1 = 0
17351
17352 def ResetBlockNodeElementCount(self):
17353 self.mBlockCount = 0
17354 self.mElementCount = 0
17355 self.mNodeCount = 0
17356
17357 def OutputSingleElementToTimeHistoryFile(self,
17358 inElementFileNameToWrite, inNodeFileNameToWrite,
17359 inTimeStep, inSimulationTime):
17360 recursionItem = BlockRecursionControlItem()
17361
17362 if inElementFileNameToWrite in self.mRecursionParameterStore:
17363 recursionItem.mParameters = \
17364 self.mRecursionParameterStore[inElementFileNameToWrite]
17365 recursionItem.mParameters.ResetBlockNodeElementCount()
17366 else:
17367 recursionItem.mParameters = \
17368 PhactoriOperationBlock.OutputSingleElementToTimeHistoryFileParams()
17369 self.mRecursionParameterStore[inElementFileNameToWrite] = \
17370 recursionItem.mParameters
17371
17372 #recursionItem.mParameters.mOutFileff = open(inFileNameToWrite, "w+b")
17373 recursionItem.mParameters.mOutElementFileName = inElementFileNameToWrite
17374 recursionItem.mParameters.mOutNodeFileName = inNodeFileNameToWrite
17375 recursionItem.mParameters.mTimeStep = inTimeStep
17376 recursionItem.mParameters.mSimulationTime = inSimulationTime
17377 recursionItem.mOperationToDoPerBlock = \
17378 self.OutputSingleElementFromBlockToTimeHistoryFile
17379 self.DoMethodPerBlock(recursionItem)
17380 #recursionItem.mParameters.mOutFileff.close()
17381
17382 def ExportOperationData(self, datadescription):
17383 "this will be called once per callback (before WriteImages) to allow the\n operation to export any desired data which is not an image. We call\n the operation specifics version of this method."
17384 self.mOperationSpecifics.ExportOperationData(datadescription)
17385
17386 #phactori_combine_to_single_python_file_subpiece_end_1
17387
17388 #phactori_combine_to_single_python_file_parent_1
17389 #from Operation.PhactoriFindCellEdgeLengths import *
17390 #phactori_combine_to_single_python_file_subpiece_begin_1
17391
17392 class CellEdgeLengthCalculationParameters():
17393 def __init__(self):
17394 self.numPointsPerBlock = None
17395 self.numCellsPerBlock = None
17396 self.OutputingFromShortest = True
17397 self.OutputShortestLongestIndex = 0
17398
17399 def Initialize(self, inOutputingFromShortest, inOutputShortestLongestIndex):
17400 self.numPointsPerBlock = []
17401 self.numCellsPerBlock = []
17402 self.OutputingFromShortest = inOutputingFromShortest
17403 self.OutputShortestLongestIndex = inOutputShortestLongestIndex
17404
17405 class PhactoriFindCellEdgeLengths(PhactoriOperationSpecifics):
17406 "experimental filter to find the lengths of the edges of cells in the mesh"
17407 def __init__(self):
17408 PhactoriOperationSpecifics.__init__(self)
17409 self.inPvFilter = None
17410 self.pfcelProgrammableFilter = None
17411 self.mProgFilterString = None
17412 self.ProgrammableFilterOutputCellVariableName = "mincelledgelength"
17413 self.OutputingFromShortest = True
17414 self.OutputShortestLongestIndex = 0
17415
17416 def ParseParametersFromJson(self, inJson):
17417
17418 keyval3 = "output nth shortest edge"
17419 keyval4 = "output nth longest edge"
17420 if keyval3 in inJson:
17421 self.OutputingFromShortest = True
17422 self.OutputShortestLongestIndex = inJson[keyval3]
17423 elif keyval4 in inJson:
17424 self.OutputingFromShortest = False
17425 self.OutputShortestLongestIndex = inJson[keyval3]
17426 else:
17427 self.OutputingFromShortest = True
17428 self.OutputShortestLongestIndex = 0
17429
17430 keyval10 = "output cell variable name"
17431 if keyval10 in inJson:
17432 self.ProgrammableFilterOutputCellVariableName = inJson[keyval10]
17433
17434 def CreateParaViewFilter(self, inInputFilter):
17435 "create the MergeBlocks filter for ParaView"
17436 if PhactoriDbg(100):
17437 myDebugPrint3("PhactoriFindCellEdgeLengths.CreateParaViewFilter "
17438 "entered\n", 100)
17439 self.inPvFilter = inInputFilter
17440
17441 savedActiveSource = GetActiveSource()
17442
17443 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
17444
17445 #SetActiveSource(newParaViewFilter)
17446 #UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
17447 #SetActiveSource(savedActiveSource)
17448
17449 self.pfcelProgrammableFilter = ProgrammableFilter(Input = self.inPvFilter)
17450 self.pfcelProgrammableFilter.CopyArrays = 1
17451 self.CreateProgrammableFilterString()
17452 self.pfcelProgrammableFilter.Script = self.mProgFilterString
17453 self.pfcelProgrammableFilter.UpdatePipeline()
17454
17455 SetActiveSource(self.pfcelProgrammableFilter)
17456 SetActiveSource(savedActiveSource)
17457
17458 if PhactoriDbg(100):
17459 myDebugPrint3("PhactoriFindCellEdgeLengths.CreateParaViewFilter "
17460 "returning\n", 100)
17461
17462 return self.pfcelProgrammableFilter
17463
17464 @staticmethod
17465 def FindCellEdgeLengthsForOneCell(inInputCsData, inParameters, inCellIndex,
17466 paramOutputingFromShortest, paramOutputShortestLongestIndex):
17467 oneCell = inInputCsData.GetCell(inCellIndex)
17468 #if PhactoriDbg(100):
17469 # myDebugPrint3("oneCell: " + str(oneCell) + "\n")
17470 numEdges = oneCell.GetNumberOfEdges()
17471 ptA = [0.0, 0.0, 0.0]
17472 ptB = [0.0, 0.0, 0.0]
17473 edgeLengthList = []
17474 for ii in range(0, numEdges):
17475 oneEdge = oneCell.GetEdge(ii)
17476 edgePoints = oneEdge.GetPointIds()
17477 ptAId = edgePoints.GetId(0)
17478 ptBId = edgePoints.GetId(1)
17479 inInputCsData.GetPoint(ptAId, ptA)
17480 inInputCsData.GetPoint(ptBId, ptB)
17481 edgeLength = vecDistance(ptA, ptB)
17482 edgeLengthList.append(edgeLength)
17483 sortedEdgeLengths = sorted(edgeLengthList)
17484
17485 if paramOutputingFromShortest:
17486 outputIndex = min(paramOutputShortestLongestIndex, len(sortedEdgeLengths) - 1)
17487 else:
17488 outputIndex = max(0, len(sortedEdgeLengths) - 1 - paramOutputShortestLongestIndex)
17489
17490 if PhactoriDbg(100):
17491 myDebugPrint3(
17492 "shortest edge length: " + str(sortedEdgeLengths[0]) + "\n"
17493 " longest edge length: " + str(sortedEdgeLengths[-1]) + "\n"
17494 " output edge length: " + str(sortedEdgeLengths[outputIndex]) + "\n"
17495 " shortest/longest flag: " + str(paramOutputingFromShortest) + "\n"
17496 "shortest/longest index: " + str(paramOutputShortestLongestIndex) + "\n"
17497 " outputIndex: " + str(outputIndex) + "\n")
17498
17499 @staticmethod
17500 def FindCellEdgeLengthsForCellsInBlock(recursionObject, inInputCsData, inParameters):
17501 if PhactoriDbg(100):
17502 myDebugPrint3("FindCellEdgeLengthsForCellsInBlock entered\n")
17503
17504 numCells = inInputCsData.GetNumberOfCells()
17505 numPoints = inInputCsData.GetNumberOfPoints()
17506 if PhactoriDbg(100):
17507 myDebugPrint3("numCells: " + str(numCells) + \
17508 " numPoints: " + str(numPoints) + "\n")
17509 inParameters.numCellsPerBlock.append(numCells)
17510 inParameters.numPointsPerBlock.append(numPoints)
17511
17512 for ii in range(0, numCells):
17513 if PhactoriDbg(100):
17514 myDebugPrint3("cell index " + str(ii) + " of " + str(numCells) + "\n")
17515 PhactoriFindCellEdgeLengths.FindCellEdgeLengthsForOneCell(
17516 inInputCsData, inParameters, ii,
17517 inParameters.OutputingFromShortest,
17518 inParameters.OutputShortestLongestIndex)
17519
17520 if PhactoriDbg(100):
17521 myDebugPrint3("FindCellEdgeLengthsForCellsInBlock returning\n")
17522
17523 def ExportOperationData(self, datadescription):
17524 if PhactoriDbg(100):
17525 myDebugPrint3("PhactoriFindCellEdgeLengths.ExportOperationData entered\n",
17526 100)
17527
17528 UpdatePipelineWithCurrentTimeArgument(self.inPvFilter)
17529
17530 #recursionObj = PhactoriParaviewMultiBlockRecursionControl()
17531 #recursionObj.mParameters = CellEdgeLengthCalculationParameters()
17532 #recursionObj.mParameters.Initialize(self.OutputingFromShortest,
17533 # self.OutputShortestLongestIndex)
17534 #recursionObj.mOperationToDoPerBlock = self.FindCellEdgeLengthsForCellsInBlock
17535 #PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.inPvFilter)
17536
17537 if PhactoriDbg(100):
17538 myDebugPrint3("PhactoriFindCellEdgeLengths.ExportOperationData returning\n",
17539 100)
17540
17541 def CreateProgrammableFilterString(self):
17542
17543 if self.mProgFilterString != None:
17544 return
17545
17546 scriptLines = []
17547
17548 scriptLines.append("#print('test2')\n")
17549
17550 scriptLines.append("localLeafVisitCount = 0\n")
17551
17552 scriptLines.append("import math\n")
17553 scriptLines.append("def FindEdgeLengthsForOneCell(inInputCsData, inCellIndex):\n")
17554 scriptLines.append(" oneCell = inInputCsData.GetCell(inCellIndex)\n")
17555 scriptLines.append(" numEdges = oneCell.GetNumberOfEdges()\n")
17556 scriptLines.append(" ptA = [0.0, 0.0, 0.0]\n")
17557 scriptLines.append(" ptB = [0.0, 0.0, 0.0]\n")
17558 scriptLines.append(" edgeLengthList = []\n")
17559 scriptLines.append(" for ii in range(0, numEdges):\n")
17560 scriptLines.append(" oneEdge = oneCell.GetEdge(ii)\n")
17561 scriptLines.append(" edgePoints = oneEdge.GetPointIds()\n")
17562 scriptLines.append(" ptAId = edgePoints.GetId(0)\n")
17563 scriptLines.append(" ptBId = edgePoints.GetId(1)\n")
17564 scriptLines.append(" inInputCsData.GetPoint(ptAId, ptA)\n")
17565 scriptLines.append(" inInputCsData.GetPoint(ptBId, ptB)\n")
17566 scriptLines.append(" dx = ptB[0] - ptA[0]\n")
17567 scriptLines.append(" dy = ptB[1] - ptA[1]\n")
17568 scriptLines.append(" dz = ptB[2] - ptA[2]\n")
17569 scriptLines.append(" edgeLength = dx*dx + dy*dy + dz*dz\n")
17570 scriptLines.append(" edgeLengthList.append(edgeLength)\n")
17571 scriptLines.append(" sortedEdgeLengths = sorted(edgeLengthList)\n")
17572 pickIndexStr = str(self.OutputShortestLongestIndex)
17573 if self.OutputingFromShortest:
17574 scriptLines.append(" outputIndex = min("+pickIndexStr+", len(sortedEdgeLengths) - 1)\n")
17575 else:
17576 scriptLines.append(" outputIndex = max(0, len(sortedEdgeLengths) - 1 - "+pickIndexStr+")\n")
17577
17578 scriptLines.append(" returnEdgeLength = math.sqrt(sortedEdgeLengths[outputIndex])\n")
17579 scriptLines.append(" return returnEdgeLength\n")
17580
17581 scriptLines.append("def flatten(input, output):\n")
17582 scriptLines.append(" # Copy the cells etc.\n")
17583 scriptLines.append(" output.ShallowCopy(input)\n")
17584 scriptLines.append(" numPoints = input.GetNumberOfPoints()\n")
17585 scriptLines.append(" celldata = output.GetCellData()\n")
17586 scriptLines.append(" numCells = input.GetNumberOfCells()\n")
17587 scriptLines.append(" #print(str(numCells))\n")
17588 scriptLines.append(" ncda = vtk.vtkDoubleArray()\n")
17589 scriptLines.append(" ncda.SetNumberOfTuples(numCells)\n")
17590 scriptLines.append(" numTuples = ncda.GetNumberOfTuples()\n")
17591 scriptLines.append(" for ii in range(0, numTuples):\n")
17592 scriptLines.append(" ncda.SetValue(ii, -1.0)\n")
17593 scriptLines.append(" for ii in range(0, numCells):\n")
17594 scriptLines.append(" minEdgeLengthForCell = FindEdgeLengthsForOneCell(input, ii)\n")
17595 scriptLines.append(" ncda.SetValue(ii, minEdgeLengthForCell)\n")
17596 scriptLines.append(" ncda.SetName('" + self.ProgrammableFilterOutputCellVariableName + "')\n")
17597 scriptLines.append(" #print(ncda.GetName())\n")
17598 scriptLines.append(" celldata.AddArray(ncda)\n")
17599
17600 scriptLines.append("input = self.GetInputDataObject(0, 0)\n")
17601 scriptLines.append("output = self.GetOutputDataObject(0)\n")
17602
17603 scriptLines.append("if input.IsA('vtkMultiBlockDataSet'):\n")
17604 scriptLines.append(" output.CopyStructure(input)\n")
17605 scriptLines.append(" iter = input.NewIterator()\n")
17606 scriptLines.append(" iter.UnRegister(None)\n")
17607 scriptLines.append(" iter.InitTraversal()\n")
17608 scriptLines.append(" while not iter.IsDoneWithTraversal():\n")
17609 scriptLines.append(" localLeafVisitCount += 1\n")
17610 scriptLines.append(" curInput = iter.GetCurrentDataObject()\n")
17611 scriptLines.append(" curOutput = curInput.NewInstance()\n")
17612 scriptLines.append(" curOutput.UnRegister(None)\n")
17613 scriptLines.append(" output.SetDataSet(iter, curOutput)\n")
17614 scriptLines.append(" flatten(curInput, curOutput)\n")
17615 scriptLines.append(" iter.GoToNextItem();\n")
17616 scriptLines.append("else:\n")
17617 scriptLines.append(" flatten(input, output)\n")
17618
17619 self.mProgFilterString = "".join(scriptLines)
17620
17621 if PhactoriDbg(100):
17622 myDebugPrint3("PhactoriFindCellEdgeLengths constructed script:\n" + \
17623 self.mProgFilterString)
17624
17625 #phactori_combine_to_single_python_file_subpiece_end_1
17626
17627 #phactori_combine_to_single_python_file_parent_1
17628 #from Operation.PhactoriCellEdgeAngleMetrics import *
17629 #phactori_combine_to_single_python_file_subpiece_begin_1
17630
17631 class CellEdgeAngleMetricParameters():
17632 def __init__(self):
17633 self.numPointsPerBlock = None
17634 self.numCellsPerBlock = None
17635 self.UseSmallestAngle = True
17636 self.OffsetIndex = 0
17637 self.AngleCellVariableName = "minedgenormalangle"
17638 self.HeightCellVariableName = "cellheight"
17639
17640 def Initialize(self, inUseSmallestAngle, inOffsetIndex,
17641 inAngleCellVariableName, inHeightCellVariableName):
17642 self.numPointsPerBlock = []
17643 self.numCellsPerBlock = []
17644 self.UseSmallestAngle = inUseSmallestAngle
17645 self.OffsetIndex = inOffsetIndex
17646 self.AngleCellVariableName = inAngleCellVariableName
17647 self.HeightCellVariableName = inHeightCellVariableName
17648
17649 class PhactoriCellEdgeAngleMetrics(PhactoriOperationSpecifics):
17650 "experimental filter to find the lengths of the edges of cells in the mesh"
17651 def __init__(self):
17652 PhactoriOperationSpecifics.__init__(self)
17653 self.inPvFilter = None
17654 self.pfcelProgrammableFilter = None
17655 self.mProgFilterString = None
17656 self.OutputAngleCellVariableName = "minedgenormalangle"
17657 self.OutputHeightCellVariableName = "cellheight"
17658 self.UseSmallestAngle = True
17659 self.OffsetIndex = 0
17660 self.DoOperationInCreateParaViewMethod = True
17661 self.CreateProgrammableFilter = False
17662
17663 def ParseParametersFromJson(self, inJson):
17664
17665 keyval3 = "output nth smallest angle"
17666 keyval4 = "output nth largest angle"
17667 if keyval3 in inJson:
17668 self.UseSmallestAngle = True
17669 self.OffsetIndex = inJson[keyval3]
17670 elif keyval4 in inJson:
17671 self.UseSmallestAngle = False
17672 self.OffsetIndex = inJson[keyval3]
17673 else:
17674 self.UseSmallestAngle = True
17675 self.OffsetIndex = 0
17676
17677 keyval10 = "output angle cell variable name"
17678 if keyval10 in inJson:
17679 self.OutputAngleCellVariableName = inJson[keyval10]
17680 keyval10 = "output height cell variable name"
17681 if keyval10 in inJson:
17682 self.OutputHeightCellVariableName = inJson[keyval10]
17683
17684 keyval11 = "do operation in createparaview method"
17685 if keyval11 in inJson:
17686 self.DoOperationInCreateParaViewMethod = inJson[keyval11]
17687
17688 keyval12 = "create programmable filter"
17689 if keyval12 in inJson:
17690 self.CreateProgrammableFilter = inJson[keyval12]
17691
17692 def CreateParaViewFilter(self, inInputFilter):
17693 "create the MergeBlocks filter for ParaView"
17694 if PhactoriDbg(100):
17695 myDebugPrint3("PhactoriCellEdgeAngleMetrics.CreateParaViewFilter "
17696 "entered\n", 100)
17697 self.inPvFilter = inInputFilter
17698
17699 savedActiveSource = GetActiveSource()
17700
17701 UpdatePipelineWithCurrentTimeArgument(self.inPvFilter)
17702
17703 if self.DoOperationInCreateParaViewMethod:
17704 if PhactoriDbg(100):
17705 myDebugPrint3("point and cell array info before calculating metrics:")
17706 RecursivelyPrintPointAndCellArrayInformation(self.inPvFilter)
17707
17708 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
17709 recursionObj.mParameters = CellEdgeAngleMetricParameters()
17710 recursionObj.mParameters.Initialize(self.UseSmallestAngle,
17711 self.OffsetIndex,
17712 self.OutputAngleCellVariableName,
17713 self.OutputHeightCellVariableName)
17714 recursionObj.mOperationToDoPerBlock = self.FindCellEdgeAngleMetricsInBlock
17715 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.inPvFilter)
17716
17717 UpdatePipelineWithCurrentTimeArgument(self.inPvFilter)
17718
17719 if PhactoriDbg(100):
17720 myDebugPrint3("point and cell array info after calculating metrics:")
17721 RecursivelyPrintPointAndCellArrayInformation(self.inPvFilter)
17722
17723 #SetActiveSource(newParaViewFilter)
17724 #UpdatePipelineWithCurrentTimeArgument(newParaViewFilter)
17725
17726 if self.CreateProgrammableFilter:
17727 self.pfcelProgrammableFilter = ProgrammableFilter(Input = self.inPvFilter)
17728 self.pfcelProgrammableFilter.CopyArrays = 1
17729 self.CreateProgrammableFilterString()
17730 self.pfcelProgrammableFilter.Script = self.mProgFilterString
17731 self.pfcelProgrammableFilter.UpdatePipeline()
17732
17733 SetActiveSource(savedActiveSource)
17734
17735 if self.CreateProgrammableFilter:
17736 if PhactoriDbg(100):
17737 myDebugPrint3("PhactoriCellEdgeAngleMetrics.CreateParaViewFilter "
17738 "returning programmable filter\n", 100)
17739 return self.pfcelProgrammableFilter
17740 else:
17741 if PhactoriDbg(100):
17742 myDebugPrint3("PhactoriCellEdgeAngleMetrics.CreateParaViewFilter "
17743 "returning passthrough filter\n", 100)
17744 return self.inPvFilter
17745
17746 @staticmethod
17747 def FindCellEdgeAngleMetricsInBlock(recursionObject, inInputCsData, inParameters):
17748 if PhactoriDbg(100):
17749 myDebugPrint3("FindCellEdgeAngleMetricsInBlock entered\n")
17750
17751 numCells = inInputCsData.GetNumberOfCells()
17752 numPoints = inInputCsData.GetNumberOfPoints()
17753 if PhactoriDbg(100):
17754 myDebugPrint3("numCells: " + str(numCells) + \
17755 " numPoints: " + str(numPoints) + "\n")
17756 inParameters.numCellsPerBlock.append(numCells)
17757 inParameters.numPointsPerBlock.append(numPoints)
17758
17759 ncda = vtk.vtkDoubleArray()
17760 ncda.SetNumberOfTuples(numCells)
17761 ncda2 = vtk.vtkDoubleArray()
17762 ncda2.SetNumberOfTuples(numCells)
17763
17764 outputAngles = []
17765 outputHeights = []
17766 for ii in range(0, numCells):
17767 #if PhactoriDbg(100):
17768 # myDebugPrint3("cell index " + str(ii) + " of " + str(numCells) + "\n")
17769 edgeAngle, cellHeight = PhactoriFindCellEdgeAngleMetricsForOneCell(inInputCsData, ii,
17770 inParameters.UseSmallestAngle, inParameters.OffsetIndex)
17771 outputAngles.append(edgeAngle)
17772 outputHeights.append(cellHeight)
17773 ncda.SetValue(ii, edgeAngle)
17774 ncda2.SetValue(ii, cellHeight)
17775
17776 celldata = inInputCsData.GetCellData()
17777 ncda.SetName(inParameters.AngleCellVariableName)
17778 celldata.AddArray(ncda)
17779 ncda2.SetName(inParameters.HeightCellVariableName)
17780 celldata.AddArray(ncda2)
17781 if PhactoriDbg(100):
17782 myDebugPrint3("numCells: " + str(numCells) + "\n"
17783 "inParameters.AngleCellVariableName: " + inParameters.AngleCellVariableName + "\n"
17784 "inParameters.HeightCellVariableName: " + inParameters.HeightCellVariableName + "\n")
17785 if numCells > 0:
17786 myDebugPrint3("edgeAngle 0: " + str(ncda.GetValue(0)) + "\n")
17787
17788 if PhactoriDbg(100):
17789 minOutputAngle = 91.0
17790 minOutputAngleIndex = -1
17791 maxOutputAngle = -1.0
17792 maxOutputAngleIndex = -1
17793 minHeight = 1e15
17794 minHeightIndex = -1
17795 maxHeight = -1.0
17796 maxHeightIndex = -1
17797 for ii in range(0, numCells):
17798 edgeAngle = outputAngles[ii]
17799 cellHeight = outputAngles[ii]
17800 if edgeAngle < minOutputAngle:
17801 minOutputAngle = edgeAngle
17802 minOutputAngleIndex = ii
17803 if edgeAngle > maxOutputAngle:
17804 maxOutputAngle = edgeAngle
17805 maxOutputAngleIndex = ii
17806 if cellHeight < minHeight:
17807 minHeight = cellHeight
17808 minHeightIndex = ii
17809 if cellHeight > maxHeight:
17810 maxHeight = cellHeight
17811 maxHeightIndex = ii
17812 myDebugPrint3(
17813 "minOutputAngle, index: " + str(minOutputAngle) + ", " + str(minOutputAngleIndex) + "\n" + \
17814 "maxOutputAngle, index: " + str(maxOutputAngle) + ", " + str(maxOutputAngleIndex) + "\n" + \
17815 "minHeight, index: " + str(minHeight) + ", " + str(minHeightIndex) + "\n" + \
17816 "maxHeight, index: " + str(maxHeight) + ", " + str(maxHeightIndex) + "\n" + \
17817 "FindCellEdgeAngleMetricsInBlock returning\n")
17818 return outputAngles, outputHeights
17819
17820 def CreateProgrammableFilterString(self):
17821
17822 if self.mProgFilterString != None:
17823 return
17824
17825 scriptLines = []
17826
17827 scriptLines.append("import math\n")
17828 GetPhactoriVectorLibraryProgrammableFilterLines(scriptLines)
17829 GetPhactoriVtkCellOperationsProgrammableFilterLines(scriptLines)
17830
17831 scriptLines.append("localLeafVisitCount = 0\n")
17832 scriptLines.append("def flatten(input, output):\n")
17833 scriptLines.append(" # Copy the cells etc.\n")
17834 scriptLines.append(" output.ShallowCopy(input)\n")
17835 scriptLines.append(" numPoints = input.GetNumberOfPoints()\n")
17836 scriptLines.append(" celldata = output.GetCellData()\n")
17837 scriptLines.append(" numCells = input.GetNumberOfCells()\n")
17838 scriptLines.append(" #print(str(numCells))\n")
17839 scriptLines.append(" ncda = vtk.vtkDoubleArray()\n")
17840 scriptLines.append(" ncda.SetNumberOfTuples(numCells)\n")
17841 scriptLines.append(" ncda2 = vtk.vtkDoubleArray()\n")
17842 scriptLines.append(" ncda2.SetNumberOfTuples(numCells)\n")
17843 scriptLines.append(" numTuples = ncda.GetNumberOfTuples()\n")
17844 scriptLines.append(" for ii in range(0, numTuples):\n")
17845 scriptLines.append(" ncda.SetValue(ii, -1.0)\n")
17846 scriptLines.append(" ncda2.SetValue(ii, -1.0)\n")
17847 scriptLines.append(" for ii in range(0, numCells):\n")
17848 scriptLines.append(" cellAngle, cellHeight = PhactoriFindCellEdgeAngleMetricsForOneCell(input, ii, " + \
17849 str(self.UseSmallestAngle) + ", " + str(self.OffsetIndex) + ")\n")
17850 scriptLines.append(" ncda.SetValue(ii, cellAngle)\n")
17851 scriptLines.append(" ncda2.SetValue(ii, cellHeight)\n")
17852 scriptLines.append(" ncda.SetName('" + self.OutputAngleCellVariableName + "')\n")
17853 scriptLines.append(" celldata.AddArray(ncda)\n")
17854 scriptLines.append(" ncda2.SetName('" + self.OutputHeightCellVariableName + "')\n")
17855 scriptLines.append(" celldata.AddArray(ncda2)\n")
17856
17857 scriptLines.append("input = self.GetInputDataObject(0, 0)\n")
17858 scriptLines.append("output = self.GetOutputDataObject(0)\n")
17859
17860 scriptLines.append("if input.IsA('vtkMultiBlockDataSet'):\n")
17861 scriptLines.append(" output.CopyStructure(input)\n")
17862 scriptLines.append(" iter = input.NewIterator()\n")
17863 scriptLines.append(" iter.UnRegister(None)\n")
17864 scriptLines.append(" iter.InitTraversal()\n")
17865 scriptLines.append(" while not iter.IsDoneWithTraversal():\n")
17866 scriptLines.append(" localLeafVisitCount += 1\n")
17867 scriptLines.append(" curInput = iter.GetCurrentDataObject()\n")
17868 scriptLines.append(" curOutput = curInput.NewInstance()\n")
17869 scriptLines.append(" curOutput.UnRegister(None)\n")
17870 scriptLines.append(" output.SetDataSet(iter, curOutput)\n")
17871 scriptLines.append(" flatten(curInput, curOutput)\n")
17872 scriptLines.append(" iter.GoToNextItem();\n")
17873 scriptLines.append("else:\n")
17874 scriptLines.append(" flatten(input, output)\n")
17875
17876 self.mProgFilterString = "".join(scriptLines)
17877
17878 if PhactoriDbg(100):
17879 myDebugPrint3("PhactoriCellEdgeAngleMetrics constructed script:\n" + \
17880 self.mProgFilterString)
17881
17882 #phactori_combine_to_single_python_file_subpiece_end_1
17883
17884 #phactori_combine_to_single_python_file_parent_1
17885 #from Operation.PhactoriMarkCellSurfaceStatus2 import *
17886 #phactori_combine_to_single_python_file_subpiece_begin_1
17887
17888 class CellEdgeAngleMetricParameters():
17889 def __init__(self):
17890 self.numPointsPerBlock = None
17891 self.numCellsPerBlock = None
17892 self.UseSmallestAngle = True
17893 self.OffsetIndex = 0
17894 self.OutputCellVariableName = None
17895
17896 def Initialize(self, inUseSmallestAngle, inOffsetIndex, inCellVariableName):
17897 self.numPointsPerBlock = []
17898 self.numCellsPerBlock = []
17899 self.UseSmallestAngle = inUseSmallestAngle
17900 self.OffsetIndex = inOffsetIndex
17901 self.OutputCellVariableName = inCellVariableName
17902
17903 class PhactoriMarkCellSurfaceStatus2(PhactoriOperationSpecifics):
17904 "experimental filter to find the lengths of the edges of cells in the mesh"
17905 def __init__(self):
17906 PhactoriOperationSpecifics.__init__(self)
17907 self.inPvFilter = None
17908 self.pfcelProgrammableFilter = None
17909 self.mProgFilterString = None
17910 self.OutputCellVariableName = "surfacestatus"
17911 self.UseSmallestAngle = True
17912 self.OffsetIndex = 0
17913 self.DoOperationInCreateParaViewMethod = True
17914 self.CreateProgrammableFilter = False
17915
17916 def ParseParametersFromJson(self, inJson):
17917
17918 keyval3 = "output nth smallest angle"
17919 keyval4 = "output nth largest angle"
17920 if keyval3 in inJson:
17921 self.UseSmallestAngle = True
17922 self.OffsetIndex = inJson[keyval3]
17923 elif keyval4 in inJson:
17924 self.UseSmallestAngle = False
17925 self.OffsetIndex = inJson[keyval3]
17926 else:
17927 self.UseSmallestAngle = True
17928 self.OffsetIndex = 0
17929
17930 keyval10 = "output cell variable name"
17931 if keyval10 in inJson:
17932 self.OutputCellVariableName = inJson[keyval10]
17933
17934 keyval11 = "do operation in createparaview method"
17935 if keyval11 in inJson:
17936 self.DoOperationInCreateParaViewMethod = inJson[keyval11]
17937
17938 keyval12 = "create programmable filter"
17939 if keyval12 in inJson:
17940 self.ProgrammableFilterOutputCellVariableName = inJson[keyval10]
17941
17942 def CreateParaViewFilter(self, inInputFilter):
17943 "create the MergeBlocks filter for ParaView"
17944 if PhactoriDbg(100):
17945 myDebugPrint3("PhactoriMarkCellSurfaceStatus2.CreateParaViewFilter "
17946 "entered\n", 100)
17947 self.inPvFilter = inInputFilter
17948
17949 savedActiveSource = GetActiveSource()
17950
17951 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
17952
17953 if self.DoOperationInCreateParaViewMethod:
17954 if PhactoriDbg(100):
17955 myDebugPrint3("make variable during CreateParaViewFilter\n", 100)
17956 recursionObj = PhactoriParaviewMultiBlockRecursionControl()
17957 recursionObj.mParameters = CellEdgeAngleMetricParameters()
17958 recursionObj.mParameters.Initialize(self.UseSmallestAngle,
17959 self.OffsetIndex, self.OutputCellVariableName)
17960 recursionObj.mOperationToDoPerBlock = self.MarkCellStatusInBlock
17961 PhactoriRecusivelyDoMethodPerBlockFromParaViewFilter(recursionObj, self.inPvFilter)
17962
17963 UpdatePipelineWithCurrentTimeArgument(inInputFilter)
17964 if PhactoriDbg(100):
17965 myDebugPrint3("done make variable during CreateParaViewFilter\n", 100)
17966
17967 if self.CreateProgrammableFilter:
17968 self.pfcelProgrammableFilter = ProgrammableFilter(Input = self.inPvFilter)
17969 self.pfcelProgrammableFilter.CopyArrays = 1
17970 self.CreateProgrammableFilterString()
17971 self.pfcelProgrammableFilter.Script = self.mProgFilterString
17972 self.pfcelProgrammableFilter.UpdatePipeline()
17973 UpdatePipelineWithCurrentTimeArgument(self.pfcelProgrammableFilter)
17974 if PhactoriDbg(100):
17975 myDebugPrint3("self.CreateProgrammableFilter true, created programmable filter\n", 100)
17976
17977 SetActiveSource(savedActiveSource)
17978
17979 if self.CreateProgrammableFilter:
17980 if PhactoriDbg(100):
17981 myDebugPrint3("PhactoriMarkCellSurfaceStatus2.CreateParaViewFilter "
17982 "returning programmable filter\n", 100)
17983 return self.pfcelProgrammableFilter
17984 else:
17985 if PhactoriDbg(100):
17986 myDebugPrint3("PhactoriMarkCellSurfaceStatus2.CreateParaViewFilter "
17987 "returning passthrough filter\n", 100)
17988 return self.inPvFilter
17989
17990 @staticmethod
17991 def MarkCellStatusInBlock(recursionObject, inInputCsData, inParameters):
17992 if PhactoriDbg(100):
17993 myDebugPrint3("MarkCellStatusInBlock entered\n")
17994
17995 numCells = inInputCsData.GetNumberOfCells()
17996
17997 celldata = inInputCsData.GetCellData()
17998
17999 newCellArrayName = inParameters.OutputCellVariableName
18000
18001 inParameters.numCellsPerBlock.append(numCells)
18002 ncda = vtk.vtkIntArray()
18003 ncda.SetNumberOfTuples(numCells)
18004
18005 if numCells <= 0:
18006 ncda.SetName(newCellArrayName)
18007 celldata.AddArray(ncda)
18008
18009 if PhactoriDbg(100):
18010 myDebugPrint3("numCells 0, MarkCellStatusInBlock returning 2\n")
18011
18012 #see how many cells are touching each point
18013 cellsTouchingPointCount = PhactoriCountCellTouchingEachPoint(inInputCsData)
18014
18015 #see which cells have how many points with 8 or other cells
18016 for ii in range(0, numCells):
18017 #if PhactoriDbg(100):
18018 # myDebugPrint3("(b) cell index " + str(ii) + " of " + str(numCells) + "\n")
18019 oneCellSurfaceStatus = PhactoriFindSurfaceStatusForOneCell(inInputCsData, ii,
18020 cellsTouchingPointCount)
18021 ncda.SetValue(ii, oneCellSurfaceStatus)
18022
18023 ncda.SetName(newCellArrayName)
18024 celldata.AddArray(ncda)
18025
18026 if PhactoriDbg(100):
18027 myDebugPrint3("MarkCellStatusInBlock returning\n")
18028
18029 def CreateProgrammableFilterString(self):
18030
18031 if self.mProgFilterString != None:
18032 return
18033
18034 scriptLines = []
18035
18036 scriptLines.append("import math\n")
18037 GetPhactoriVectorLibraryProgrammableFilterLines(scriptLines)
18038 GetPhactoriVtkCellOperationsProgrammableFilterLines(scriptLines)
18039
18040 scriptLines.append("localLeafVisitCount = 0\n")
18041 scriptLines.append("def flatten(input, output):\n")
18042 scriptLines.append(" # Copy the cells etc.\n")
18043 scriptLines.append(" output.ShallowCopy(input)\n")
18044 scriptLines.append(" celldata = output.GetCellData()\n")
18045 scriptLines.append(" numCells = input.GetNumberOfCells()\n")
18046 scriptLines.append(" ncda = vtk.vtkIntArray()\n")
18047 scriptLines.append(" ncda.SetNumberOfTuples(numCells)\n")
18048
18049 #the first three of the next lines use face connections to find
18050 #interior/surface/edge/corner cells, and the next three use point
18051 #connections. Point connections create 1/3 the size intermediate data as
18052 #face connectinos, but face connections should work with wedge cells too
18053 #scriptLines.append(" cellsTouchingPointCount = PhactoriCountCellTouchingEachPoint(input)\n")
18054 #scriptLines.append(" for ii in range(0, numCells):\n")
18055 #scriptLines.append(" oneCellSurfaceStatus = PhactoriFindSurfaceStatusForOneCell(input, ii, cellsTouchingPointCount)\n")
18056 scriptLines.append(" cellsTouchingEachFace = PhactoriCountCellTouchingEachFace(input)\n")
18057 scriptLines.append(" for ii in range(0, numCells):\n")
18058 scriptLines.append(" oneCellSurfaceStatus = PhactoriFindSurfaceStatusForOneCellUsingFaceInfo(input, ii, cellsTouchingEachFace)\n")
18059
18060 scriptLines.append(" ncda.SetValue(ii, oneCellSurfaceStatus)\n")
18061 scriptLines.append(" ncda.SetName('" + self.OutputCellVariableName + "')\n")
18062 scriptLines.append(" celldata.AddArray(ncda)\n")
18063
18064 scriptLines.append("input = self.GetInputDataObject(0, 0)\n")
18065 scriptLines.append("output = self.GetOutputDataObject(0)\n")
18066
18067 scriptLines.append("if input.IsA('vtkMultiBlockDataSet'):\n")
18068 scriptLines.append(" output.CopyStructure(input)\n")
18069 scriptLines.append(" iter = input.NewIterator()\n")
18070 scriptLines.append(" iter.UnRegister(None)\n")
18071 scriptLines.append(" iter.InitTraversal()\n")
18072 scriptLines.append(" while not iter.IsDoneWithTraversal():\n")
18073 scriptLines.append(" localLeafVisitCount += 1\n")
18074 scriptLines.append(" curInput = iter.GetCurrentDataObject()\n")
18075 scriptLines.append(" curOutput = curInput.NewInstance()\n")
18076 scriptLines.append(" curOutput.UnRegister(None)\n")
18077 scriptLines.append(" output.SetDataSet(iter, curOutput)\n")
18078 scriptLines.append(" flatten(curInput, curOutput)\n")
18079 scriptLines.append(" iter.GoToNextItem();\n")
18080 scriptLines.append("else:\n")
18081 scriptLines.append(" flatten(input, output)\n")
18082
18083 self.mProgFilterString = "".join(scriptLines)
18084
18085 if PhactoriDbg(100):
18086 myDebugPrint3("PhactoriMarkCellSurfaceStatus2 constructed script:\n" + \
18087 self.mProgFilterString)
18088
18089 #phactori_combine_to_single_python_file_subpiece_end_1
18090
18091 class PhactoriTextAnnotationBlock(PhactoriOperationSpecifics):
18092 "represents manages one text annotation item (paraview Text source).\n The idea is that we print a 2d text item on the window front to give\n information to the user. Notionally the text can change depending on\n data (e.g. min/max/average values from an operation), but this is not\n yet implemented. Imagesets can selectively turn on any desired subset\n of existing text annotations. The position of the text annotation\n on the window, the color can be set, the font size and family can be\n chosen, and the bold/italic/shadow flags can be set"
18093 def __init__(self):
18094 self.mName = ""
18095 self.mTextString = ""
18096 #not implemented yet self.minputOperationName = ""
18097 #not implemented yet self.minputOperationBlock = None
18098 self.mParaViewSource = None
18099 self.mParaViewRepresentation = None
18100 self.mWindowLocation = None
18101 self.mPosition = None
18102 self.mColor = None
18103 self.mOpacity = None
18104 self.mBoldFlag = None
18105 self.mShadowFlag = None
18106 self.mItalicFlag = None
18107 self.mFontSize = None
18108 self.mFontFamily = None
18109
18110 def UpdateAndMakeVisible(self):
18111 if PhactoriDbg(100):
18112 myDebugPrint3(
18113 "PhactoriTextAnnotationBlock::UpdateAndMakeVisible entered:\n" + \
18114 self.mName + "\n", 100)
18115
18116 if self.mParaViewSource == None:
18117 #this text annotation needs to have its paraview components created
18118 if PhactoriDbg(100):
18119 myDebugPrint3("(paraview items will now be created)\n")
18120 self.CreateParaViewItems()
18121
18122 #here is where we'd get input operation and update text if it
18123 #was data dependent; see PhactoriMarkerBlock:UpdateAndMakeVisible()
18124
18125 #make it visible
18126 self.mParaViewRepresentation.Visibility = 1
18127
18128 if PhactoriDbg(100):
18129 myDebugPrint3(
18130 "PhactoriTextAnnotationBlock::UpdateAndMakeVisible returning:\n" + \
18131 self.mName + "\n", 100)
18132
18133 def MakeInvisible(self):
18134 if PhactoriDbg(100):
18135 myDebugPrint3("making text annotation invisible: " + \
18136 self.mName + "\n", 100)
18137 if self.mParaViewRepresentation != None:
18138 self.mParaViewRepresentation.Visibility = 0
18139 else:
18140 myDebugPrint3("(paraview items not yet created)\n")
18141
18142 def CreateParaViewItems(self):
18143 "creates the paraview text source and representation for this\n PhactoriTextAnnotationBlock instance"
18144 if PhactoriDbg(100):
18145 myDebugPrint3(
18146 "PhactoriTextAnnotationBlock::CreateParaViewItems entered:\n" + \
18147 self.mName + "\n", 100)
18148
18149
18150 savedActiveSource = GetActiveSource()
18151
18152 #UpdatePipelineWithCurrentTimeArgument(inInputFilter)
18153 self.mParaViewSource = Text()
18154 self.mParaViewSource.Text = self.mTextString
18155
18156 self.mParaViewRepresentation = Show()
18157
18158 if self.mWindowLocation != None:
18159 self.mParaViewRepresentation.WindowLocation = self.mWindowLocation
18160 if self.mPosition != None:
18161 self.mParaViewRepresentation.Position = self.mPosition
18162 if self.mFontSize != None:
18163 self.mParaViewRepresentation.FontSize = self.mFontSize
18164 if self.mFontFamily != None:
18165 self.mParaViewRepresentation.FontFamily = self.mFontFamily
18166 if self.mColor != None:
18167 self.mParaViewRepresentation.Color = self.mColor
18168 if self.mOpacity != None:
18169 self.mParaViewRepresentation.Opacity = self.mOpacity
18170 if self.mBoldFlag != None:
18171 self.mParaViewRepresentation.Bold = self.mBoldFlag
18172 if self.mItalicFlag != None:
18173 self.mParaViewRepresentation.Italic = self.mItalicFlag
18174 if self.mShadowFlag != None:
18175 self.mParaViewRepresentation.Shadow = self.mShadowFlag
18176
18177
18178 #SetActiveSource(self.mParaViewSource)
18179 SetActiveSource(savedActiveSource)
18180
18181 if PhactoriDbg(100):
18182 myDebugPrint3(
18183 "PhactoriTextAnnotationBlock::CreateParaViewItems returning:\n" + \
18184 self.mName + "\n", 100)
18185
18186 def SelfToStr(self):
18187 return "PhactoriTextAnnotationBlock:\n" \
18188 "mName: " + self.mName + "\n" \
18189 "mTextString: " + self.mTextString + "\n" \
18190 "self.mWindowLocation: " + str(self.mWindowLocation) + "\n" \
18191 "self.mPosition: " + str(self.mPosition) + "\n" \
18192 "self.mColor: " + str(self.mColor) + "\n" \
18193 "self.mOpacity: " + str(self.mOpacity) + "\n" \
18194 "self.mBoldFlag: " + str(self.mBoldFlag) + "\n" \
18195 "self.mShadowFlag: " + str(self.mShadowFlag) + "\n" \
18196 "self.mItalicFlag: " + str(self.mItalicFlag) + "\n" \
18197 "self.mFontSize: " + str(self.mFontSize) + "\n" \
18198 "self.mFontFamily: " + str(self.mFontFamily) + "\n"
18199 #"mInputOperationName: " + str(self.mInputOperationName) + "\n" \
18200
18201 def ParseTextAnnotationSettingsFromJson(self, inJson):
18202 if PhactoriDbg(100):
18203 myDebugPrint3(
18204 "PhactoriTextAnnotationBlock::ParseTextAnnotationSettingsFromJson " \
18205 "entered\n", 100)
18206
18207 if "line1" in inJson:
18208 self.mTextString = inJson["line1"]
18209 else:
18210 myDebugPrint3AndException(
18211 "PhactoriTextAnnotationBlock::ParseParametersFromJson\n"
18212 "Error: must have 'line1' command\n")
18213
18214 for lineIndex in range(2, 10):
18215 linetoken = "line" + str(lineIndex)
18216 if linetoken not in inJson:
18217 break
18218 self.mTextString += "\n" + inJson[linetoken]
18219
18220 if PhactoriDbg(100):
18221 myDebugPrint3("final text string:\n" + self.mTextString + "\n", 100)
18222
18223 if "windowlocation" in inJson:
18224 self.mWindowLocation = inJson["windowlocation"]
18225
18226 if "position" in inJson:
18227 self.mWindowLocation = "AnyLocation"
18228 self.mPosition = inJson["position"]
18229
18230 if "fontsize" in inJson:
18231 self.mFontSize = int(inJson["fontsize"])
18232
18233 if "fontfamily" in inJson:
18234 self.mFontFamily = inJson["fontfamily"]
18235
18236 if "color" in inJson:
18237 self.mColor = inJson["color"]
18238
18239 if "opacity" in inJson:
18240 self.mOpacity = float(inJson["opacity"])
18241
18242 if "boldflag" in inJson:
18243 self.mBoldFlag = inJson["boldflag"]
18244
18245 if "italicflag" in inJson:
18246 self.mItalicFlag = inJson["italicflag"]
18247
18248 if "shadowflag" in inJson:
18249 self.mShadowFlag = inJson["shadowflag"]
18250
18251 if PhactoriDbg(100):
18252 myDebugPrint3("after parsing:\n" + self.SelfToStr())
18253 myDebugPrint3(
18254 "PhactoriTextAnnotationBlock::ParseTextAnnotationSettingsFromJson " \
18255 "returning\n", 100)
18256
18257
18258 class PhactoriMarkerBlock:
18259 "represents and manages one 'marker' item. The idea of a phactori marker\n is that we can place a sphere (or maybe cube or other geometric object)\n at a specific point in the scene to provide some kind of information to\n the user. Markers can be placed at absolute or relative geometric\n points, at an element or node, or (perhaps most valuably) at a min or\n max of a particular variable (with the min or max determined at the\n pipeline point of any selected operation, e.g. filter out block X\n and place a marker at the max of Temperature on block X). Imagesets\n can selectively turn on any desired subset of existing markers. In\n Paraview the markers are simply sphere (or maybe cube) sources.\n Additionally, the color of the marker can be set as well as the size\n (relative or absolute)"
18260
18261 def __init__(self):
18262 self.mName = ""
18263 self.mInputOperationName = None
18264 self.mInputOperationBlock = None
18265 self.mShape = "sphere" #we will add others
18266 self.mParaViewSource = None
18267 self.mParaViewRepresentation = None
18268 self.mLocationPoint = PhactoriUserPointInfo()
18269 self.mSizeType = "absolute" #"or datasize relative", not handled yet
18270 self.mSize = [0.5, 0.5, 0.5]
18271 self.mOrientation = [0.0, 0.0, 0.0]
18272 self.mColor = [0.0, 1.0, 0.0]
18273 self.mResolution = 16
18274
18275 def UpdateAndMakeVisible(self):
18276 if PhactoriDbg(100):
18277 myDebugPrint3("PhactoriMarkerBlock::UpdateAndMakeVisible entered: " + \
18278 self.mName + "\n", 100)
18279
18280 if self.mParaViewSource == None:
18281 #this marker needs to have its paraview components created
18282 if PhactoriDbg(100):
18283 myDebugPrint3("(paraview items will now be created)\n")
18284 self.CreateParaViewItems()
18285
18286 #get the current location of the point (which may change for a point
18287 #at a variable min/max or a relative point)
18288 global gPipeAndViewsState
18289 myViewBounds = None
18290 viewBoundsIo = [myViewBounds]
18291
18292 if self.mInputOperationBlock == None:
18293 if self.mInputOperationName == None:
18294 self.mInputOperationBlock = \
18295 gPipeAndViewsState.mIncomingDefaultOperation
18296 if PhactoriDbg(100):
18297 myDebugPrint3("first calc, using default incoming operation\n")
18298 else:
18299 self.mInputOperationBlock = gPipeAndViewsState.mOperationBlocks[
18300 self.mInputOperationName]
18301 if self.mInputOperationBlock == None:
18302 myDebugPrint3AndException(
18303 "PhactoriMarkerBlock::UpdateAndMakeVisible:\n"
18304 "couldn't find input operation with name: " + \
18305 str(self.mInputOperationName) + "\n")
18306 if PhactoriDbg(100):
18307 myDebugPrint3("first calc, using operation named: " + \
18308 self.mInputOperationName + "\n")
18309
18310 checkPvFilter = self.mInputOperationBlock.GetPvFilter()
18311
18312 updatedMarkerLocation = self.mLocationPoint.\
18313 GetCurrentGeometricPointWithDisplacement(checkPvFilter,
18314 viewBoundsIo, True)
18315
18316 #update the paraview component to reflect the current marker location
18317 #self.mParaViewSource.Center = updatedMarkerLocation
18318 self.mParaViewRepresentation.Position = updatedMarkerLocation
18319 if PhactoriDbg(100):
18320 #myDebugPrint3("updatedMarkerLocation: " + \
18321 # str(self.mParaViewSource.Center)+ "\n", 100)
18322 myDebugPrint3("updatedMarkerLocation: " + \
18323 str(self.mParaViewRepresentation.Position)+ "\n", 100)
18324
18325 #make it visible
18326 self.mParaViewRepresentation.Visibility = 1
18327
18328 if PhactoriDbg(100):
18329 myDebugPrint3("PhactoriMarkerBlock::UpdateAndMakeVisible returning: " + \
18330 self.mName + "\n", 100)
18331
18332 def MakeInvisible(self):
18333 if PhactoriDbg(100):
18334 myDebugPrint3("making marker invisible: " + self.mName + "\n", 100)
18335 if self.mParaViewRepresentation != None:
18336 self.mParaViewRepresentation.Visibility = 0
18337 else:
18338 if PhactoriDbg(100):
18339 myDebugPrint3("(paraview items not yet created\n")
18340
18341 def CreateParaViewItems(self):
18342 "creates the paraview source (e.g box, sphere, cone, arrow) and representation\n for the marker"
18343 if PhactoriDbg(100):
18344 myDebugPrint3("PhactoriMarkerBlock::CreateParaViewItems entered\n", 100)
18345 savedActiveSource = GetActiveSource()
18346 if self.mShape == "sphere":
18347 self.mParaViewSource = Sphere()
18348 #self.mParaViewRepresentation.SelectionPointFieldDataArrayName = 'Normals'
18349 self.mParaViewSource.Radius = 0.5
18350 self.mParaViewSource.ThetaResolution = self.mResolution
18351 self.mParaViewSource.PhiResolution = self.mResolution
18352 elif self.mShape == "box":
18353 self.mParaViewSource = Box()
18354 self.mParaViewRepresentation = Show()
18355 #self.mParaViewSource.ZLength = self.mSize[0]
18356 #self.mParaViewSource.XLength = self.mSize[1]
18357 #self.mParaViewSource.YLength = self.mSize[2]
18358 elif self.mShape == "arrow":
18359 self.mParaViewSource = Arrow()
18360 self.mParaViewSource.Invert = 1
18361 self.mParaViewSource.ShaftResolution = self.mResolution
18362 self.mParaViewSource.TipResolution = self.mResolution
18363 elif self.mShape == "cone":
18364 self.mParaViewSource = Cone()
18365 self.mParaViewSource.Direction = [-1.0, 0.0, 0.0]
18366 self.mParaViewSource.Center = [0.5, 0.0, 0.0]
18367 self.mParaViewSource.Resolution = self.mResolution
18368 self.mParaViewSource.Capping = 1
18369
18370 self.mParaViewRepresentation = Show()
18371
18372 self.mParaViewRepresentation.Position = [0.0, 0.0, 0.0]
18373 self.mParaViewRepresentation.Scale = self.mSize
18374 self.mParaViewRepresentation.Orientation = self.mOrientation
18375
18376 if gParaViewCatalystVersionFlag <= 40100:
18377 self.mParaViewRepresentation.\
18378 AllowSpecularHighlightingWithScalarColoring = 1
18379 self.mParaViewRepresentation.ScaleFactor = 0.1
18380 self.mParaViewRepresentation.EdgeColor = [0.0, 0.0, 0.5000076295109483]
18381 self.mParaViewRepresentation.DiffuseColor = self.mColor
18382
18383 SetActiveSource(savedActiveSource)
18384
18385 if PhactoriDbg(100):
18386 myDebugPrint3("PhactoriMarkerBlock::CreateParaViewItems returning\n", 100)
18387
18388
18389 def SelfToStr(self):
18390 return "marker:\n" \
18391 "mName: " + self.mName + "\n" \
18392 "mInputOperationName: " + str(self.mInputOperationName) + "\n" \
18393 "mShape: " + self.mShape + "\n" \
18394 "mSizeType: " + self.mSizeType + "\n" \
18395 "mSize: " + str(self.mSize) + "\n" \
18396 "mOrientation: " + str(self.mOrientation) + "\n" \
18397 "mColor: " + str(self.mColor) + "\n" \
18398 "mResolution: " + str(self.mResolution) + "\n" \
18399 "mLocationPoint:\n" + self.mLocationPoint.SelfToStr()
18400
18401 def ParseMarkerSettingsFromJson(self, inJsn):
18402 if PhactoriDbg(100):
18403 myDebugPrint3(
18404 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson entered\n", 100)
18405
18406 if 'input' in inJsn:
18407 self.mInputOperationName = inJsn['input']
18408 else:
18409 noticeStr = \
18410 'notice! inJsn has no input key, using default pipeline input\n'
18411 self.mInputOperationName = None
18412 if PhactoriDbg():
18413 myDebugPrint3(noticeStr)
18414
18415 if "color" in inJsn:
18416 self.mColor = inJsn["color"]
18417 if len(self.mColor) != 3:
18418 myDebugPrint3AndException(
18419 "'color' item was not three element list")
18420 if "relative size" in inJsn:
18421 myDebugPrint3AndException(
18422 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
18423 "'relative size' not yet implemented")
18424 if "absolute size" in inJsn:
18425 self.mSize = inJsn["absolute size"]
18426 if "orientation" in inJsn:
18427 self.mOrientation= inJsn["orientation"]
18428 if "resolution" in inJsn:
18429 self.mResolution = inJsn["resolution"]
18430 if "shape" in inJsn:
18431 self.mShape = inJsn["shape"]
18432 if self.mShape == "sphere":
18433 if PhactoriDbg(100):
18434 myDebugPrint3("shape is sphere\n", 100)
18435 elif self.mShape == "box":
18436 if PhactoriDbg(100):
18437 myDebugPrint3("shape is box\n", 100)
18438 elif self.mShape == "cone":
18439 if PhactoriDbg(100):
18440 myDebugPrint3("shape is cone\n", 100)
18441 elif self.mShape == "arrow":
18442 if PhactoriDbg(100):
18443 myDebugPrint3("shape is arrow\n", 100)
18444 else:
18445 myDebugPrint3AndException(
18446 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
18447 "'shape' must be 'sphere' or 'box' or 'cone' or 'arrow'\n"
18448 "got: " + str(self.mShape) + "\n")
18449
18450 #get point location for marker settings, e.g. marker at max variable point
18451 self.mLocationPoint.UserPointInfoParseParametersFromJson(inJsn,
18452 "marker at ", "")
18453
18454 if self.mLocationPoint.mParsingDetectedAtLeastOneSetting == False:
18455 myDebugPrint3AndException(
18456 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson:\n"
18457 "must have 'marker at ... point' parameters")
18458
18459 if PhactoriDbg(100):
18460 myDebugPrint3(self.SelfToStr())
18461 myDebugPrint3(
18462 "PhactoriMarkerBlock::ParseMarkerSettingsFromJson returning\n", 100)
18463
18464
18465
18466 #class ParaViewRenderInfoC:
18467 # def __init__(self):
18468 # self.mParaViewInfo = None
18469 # self.mLookDirection = None
18470
18471 class PhactoriAnnotationPv:
18472 '''class manages the ParaView stuff for annotation. The settings are
18473 managed in PhactoriAnnotationViewSettings, and instances of this
18474 class are used in PhactoriImageset to manage the actual paraview
18475 objects, which might be different from image set to image set,
18476 while still using the same PhactoriAnnotationViewSettings'''
18477 def __init__(self, inSettings):
18478 #paraview stuff not created yet
18479 self.mParaViewTextAnnotationSource = None
18480 self.mParaViewRepresentation = None
18481 self.mInputOperation = None
18482 self.mSettings = inSettings
18483
18484 def CreateParaViewStuff(self, inColor, inImageset = None):
18485 '''assumes inImageset is valid; creates ParaView source and
18486 representation based on internal parameters'''
18487 if PhactoriDbg():
18488 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff entered\n")
18489 if self.mSettings.mType == 'time':
18490 if inImageset == None:
18491 if PhactoriDbg():
18492 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff\n" + \
18493 "this is a time annotation, and it needs a valid imageset\n" + \
18494 "to work off, and None was supplied\n")
18495 return
18496 self.mInputOperation = inImageset.mOperation
18497
18498 savedActiveSource = GetActiveSource()
18499 inOprtn = self.mInputOperation
18500 if(inOprtn.mParaViewTimeAnnotationSource == None):
18501 SetActiveSource(inOprtn.GetPvFilter())
18502 inOprtn.mParaViewTimeAnnotationSource = AnnotateTime()
18503 #inOprtn.mParaViewTimeAnnotationSource.Format = 'Time: %.20e'
18504 inOprtn.mParaViewTimeAnnotationSource.Format = self.mSettings.mTimeFormatString
18505 else:
18506 SetActiveSource(inOprtn.mParaViewTimeAnnotationSource)
18507 #self.mParaViewAnnotationSource = Text()
18508 self.mParaViewRepresentation = Show()
18509 self.mParaViewRepresentation.Color = inColor
18510 SetActiveSource(savedActiveSource)
18511 else:
18512 self.mParaViewTextAnnotationSource = Text()
18513 self.mParaViewTextAnnotationSource.Text = self.mText
18514 self.mParaViewRepresentation = Show()
18515 self.mParaViewRepresentation.Color = inColor
18516 self.mParaViewRepresentation.FontSize = self.mSettings.mFontSize
18517 self.mParaViewRepresentation.WindowLocation = self.mSettings.mWindowLocation
18518 if PhactoriDbg():
18519 myDebugPrint3("window location: " + str(self.mParaViewRepresentation.WindowLocation) + "\n")
18520 if PhactoriDbg():
18521 myDebugPrint3("PhactoriAnnotationPv::CreateParaViewStuff returning\n")
18522
18523 #global gTestTimeNotation
18524 #gTestTimeNotation = 1
18525
18526 class PhactoriAnnotationViewSettings:
18527 '''class manages settings for how a text or time annotation is to be
18528 show in the window--size, position, alignment, visible/invisible,
18529 etc. An instance is a member of a PhactoriRepresentation. ParaView
18530 stuff which uses these settings is in a different class, which is
18531 associated with ImageSet. Gives access to control annotation
18532 position, size, text, and could be extended to control all the items
18533 controllable in paraview (x,y position, alignment, bold/italic/shadow'''
18534
18535 def __init__(self, inName, inAnnotationType):
18536 if PhactoriDbg():
18537 myDebugPrint3("ViewSettingsPhactoriAnnotation::__init__ entered\n")
18538 self.mName = inName
18539 self.mVisible = False
18540 if inAnnotationType == 'time':
18541 self.mType = 'time'
18542 self.mText = None
18543 self.mTimeFormatString = gDefaultTimeFormatString
18544 else:
18545 self.mType = 'text'
18546 self.mText = 'Text'
18547 self.mSizeScale = 1.0
18548 #self.mFontSize = 18
18549 self.mFontSize = 36
18550 self.mFont = 'Arial'
18551 self.mBold = False
18552 self.mItalic = False
18553 self.mShadow = False
18554 self.mOpacity = 1.0
18555 self.mAlign = 'Center'
18556 global gParaViewCatalystVersionFlag
18557 if gParaViewCatalystVersionFlag < 51000:
18558 self.mWindowLocation = 'UpperLeftCorner'
18559 else:
18560 self.mWindowLocation = 'Upper Left Corner'
18561 if PhactoriDbg():
18562 myDebugPrint3("ViewSettingsPhactoriAnnotation::__init__ returning\n")
18563
18564 def ParseAvsFromJson(self, inJsn):
18565 self.mVisible = getParameterFromBlock(inJsn, 'show time annotation',
18566 self.mVisible)
18567
18568 #global gTestTimeNotation
18569 #if gTestTimeNotation == 0:
18570 # self.mVisible = True
18571 # gTestTimeNotation = 1
18572 #else:
18573 # self.mVisible = False
18574 # gTestTimeNotation = 0
18575
18576 if 'time annotation position' in inJsn:
18577 windowPosSize = inJsn['time annotation position']
18578 winPos = windowPosSize[0]
18579 winSize = windowPosSize[1]
18580 self.SetSizeScale(winSize)
18581 global gParaViewCatalystVersionFlag
18582 if gParaViewCatalystVersionFlag < 51000:
18583 if winPos == 'top left':
18584 self.SetWindowLocation('UpperLeftCorner')
18585 elif winPos == 'top right':
18586 self.SetWindowLocation('UpperRightCorner')
18587 elif winPos == 'top':
18588 self.SetWindowLocation('UpperCenter')
18589 elif winPos == 'bottom left':
18590 self.SetWindowLocation('LowerLeftCorner')
18591 elif winPos == 'bottom right':
18592 self.SetWindowLocation('LowerRightCorner')
18593 elif winPos == 'bottom':
18594 self.SetWindowLocation('LowerCenter')
18595 else:
18596 if PhactoriDbg():
18597 myDebugPrint3("bad time annotation position, using upper left\n")
18598 self.SetWindowLocation('UpperLeftCorner')
18599 else: #gParaViewCatalystVersionFlag >= 51000
18600 if winPos == 'top left':
18601 self.SetWindowLocation('Upper Left Corner')
18602 elif winPos == 'top right':
18603 self.SetWindowLocation('Upper Right Corner')
18604 elif winPos == 'top':
18605 self.SetWindowLocation('Upper Center')
18606 elif winPos == 'bottom left':
18607 self.SetWindowLocation('Lower Left Corner')
18608 elif winPos == 'bottom right':
18609 self.SetWindowLocation('Lower Right Corner')
18610 elif winPos == 'bottom':
18611 self.SetWindowLocation('Lower Center')
18612 else:
18613 if PhactoriDbg():
18614 myDebugPrint3("bad time annotation position, using upper left\n")
18615 self.SetWindowLocation('UpperLeftCorner')
18616
18617 if 'time format string' in inJsn:
18618 self.mTimeFormatString = inJsn['time format string']
18619
18620 def SetText(self, newText):
18621 if self.mType != 'text':
18622 if PhactoriDbg():
18623 myDebugPrint3("ViewSettingsPhactoriAnnotationSource::SetText not text annotation\n")
18624 return
18625 self.mText = newText
18626 self.mParaViewTextAnnotationSource.Text = newText
18627
18628 def SetSizeScale(self, inNewSizeScale):
18629 if inNewSizeScale < 0.001:
18630 if PhactoriDbg():
18631 myDebugPrint3(
18632 "ViewSettingsPhactoriAnnotationSource::SetSizeScale not in [0.001,1000]\n")
18633 if inNewSizeScale > 1000.0:
18634 if PhactoriDbg():
18635 myDebugPrint3(
18636 "ViewSettingsPhactoriAnnotationSource::SetSizeScale not in [0.001,1000]\n")
18637 self.mSizeScale = inNewSizeScale
18638 fontSizeFloat = float(self.mFontSize)
18639 fontSizeFloat *= self.mSizeScale
18640 intSizeFloat = math.floor(fontSizeFloat)
18641 self.mFontSize = int(intSizeFloat)
18642 #self.mParaViewRepresentation.FontSize = self.mFontSize
18643
18644 def SetWindowLocation(self, inNewPosition):
18645 global gParaViewCatalystVersionFlag
18646 if gParaViewCatalystVersionFlag < 51000:
18647 validPositions = ['UpperLeftCorner', 'UpperRightCorner',
18648 'LowerLeftCorner', 'LowerRightCorner',
18649 'UpperCenter', 'LowerCenter']
18650 else:
18651 validPositions = ['Upper Left Corner', 'Upper Right Corner',
18652 'Lower Left Corner', 'Lower Right Corner',
18653 'Upper Center', 'Lower Center']
18654 if inNewPosition in validPositions:
18655 #self.mParaViewRepresentation.WindowLocation = inNewPosition
18656 self.mWindowLocation = inNewPosition
18657 else:
18658 if PhactoriDbg():
18659 myDebugPrint3("ViewSettingsPhactoriAnnotationSource::SetWindowLocation invalid " + \
18660 "position\n")
18661
18662 class PhactoriPolyDataForPlotLine:
18663 "contains time over plot data values and vtk geometry, as well as the\n routines to construct and maintain the vtk geometry\n "
18664 def __init__(self, inName):
18665 self.m_TableColumn = vtk.vtkDoubleArray()
18666 self.m_TableColumn.SetName(inName)
18667
18668 def GetRestartInfo(self):
18669 "construct, in python map/json format, the information from this\n PhactoriPolyDataForPlotLine instance which contains the information\n which would be needed to restore the instance to the proper\n state after a simulation restart, particularly prior data values.\n Return the restart info map/json"
18670 newJsonItem = {}
18671 numValues = self.m_TableColumn.GetNumberOfValues()
18672 if numValues > 0:
18673 newJsonItem["m_HasAtLeastOnePoint"] = True
18674 else:
18675 newJsonItem["m_HasAtLeastOnePoint"] = False
18676 if self.m_HasAtLeastOnePoint:
18677 #should we not make copy and just return reference?
18678 #we don't need deepcopy because all items are floats/non-objects
18679 valueList = []
18680 for ii in range(0, self.m_TableColumn.GetNumberOfValues()):
18681 valueList.append(self.m_TableColumn.GetValue(ii))
18682 newJsonItem["m_ColumnValues"] = valueList
18683 return newJsonItem
18684
18685 def SetFromRestartInfo(self, inJson):
18686 "given a map (json format), use the info in the map to set this\n PhactoriPolyDataForPlotLine instance state--this reads the info\n created by out in GetRestartInfo. It should only occur on a restart,\n and it fills in the data that had been generated during the\n earlier run of the system"
18687 if "m_HasAtLeastOnePoint"not in inJson:
18688 if PhactoriDbg():
18689 myDebugPrint3("PhactoriPolyDataForPlotLine::SetFromRestartInfo " + \
18690 "m_HasAtLeastOnePoint not in inJson\n")
18691 return
18692
18693 hasAtLeastOnePoint = inJson["m_HasAtLeastOnePoint"]
18694 if hasAtLeastOnePoint == False:
18695 return
18696
18697 inJsonIsGood = True
18698 if "m_ColumnValues" not in inJson:
18699 myDebugPrint("PhactoriPolyDataForPlotLine::SetFromRestartInfo " + \
18700 "m_ColumnValues not in inJson\n")
18701 inJsonIsGood = False
18702 if inJsonIsGood == False:
18703 return
18704
18705 valueList = inJson["m_ColumnValues"]
18706 self.m_ColumnValues = valueList[:]
18707 for vv in valueList:
18708 self.m_TableColumn.InsertNextValue(vv)
18709
18710 def AppendPlotValue(self, inNewValue):
18711 self.m_TableColumn.InsertNextValue(inNewValue)
18712
18713
18714 class PhactoriPlotOverTimeIdLine:
18715 "useful info for tracking a single element over time in a plot line"
18716 def __init__(self, inIdToPlot):
18717 self.m_Id = inIdToPlot
18718 linename = "Id " + str(inIdToPlot)
18719 self.m_PlotColumn = PhactoriPolyDataForPlotLine(linename)
18720 self.m_FoundOnThisProcessorLastTime = False
18721 self.m_FoundBlockRef = None
18722 self.m_FoundIndex = None
18723
18724 class ImageFileNameCountSettings:
18725 "used to control par of how the image filenames are generated. The default\n is to increment a counter each time the results output block is triggered\n to call the catalyst stuff and make the count value part of the filename.\n We can optionally have a filename section that is based on the date/time,\n we can optionally include microseconds, and we can optionally convert the\n date/time to an integer which will be monotonically increasing"
18726 def __init__(self):
18727 self.mUseDateTime = False
18728 self.mUseMicrosecondsWithDateTime = False
18729 self.mConvertDateTimeToInteger = True
18730 self.mUseSimulationTime = False
18731 #self.mSimulationTimeFormat = "simtime_%e"
18732 self.mSimulationTimeFormat = "simtime_%.6e"
18733 self.mUseCallbackCount = True
18734 self.mUseRemeshRestartTag = True
18735
18736 def ParseImageFileNameCountSettings(self, inJson):
18737 self.mUseDateTime = getParameterFromBlock(inJson,
18738 "filename use datetime", self.mUseDateTime)
18739 self.mUseMicrosecondsWithDateTime = getParameterFromBlock(inJson,
18740 "filename datetime microseconds", self.mUseMicrosecondsWithDateTime)
18741 self.mConvertDateTimeToInteger = getParameterFromBlock(inJson,
18742 "filename datetime convert to integer", self.mConvertDateTimeToInteger)
18743 self.mUseSimulationTime = getParameterFromBlock(inJson,
18744 "filename use simulation time", self.mUseSimulationTime)
18745 self.mSimulationTimeFormat = getParameterFromBlock(inJson,
18746 "filename simulation time format", self.mSimulationTimeFormat)
18747 self.mUseCallbackCount = getParameterFromBlock(inJson,
18748 "filename use call count", self.mUseCallbackCount)
18749 self.mUseRemeshRestartTag = getParameterFromBlock(inJson,
18750 "filename use restart or remesh tag", self.mUseRemeshRestartTag)
18751
18752 def GetImageFilename(self, datadescription, inImageSettings,
18753 inOneLookDirectionFilenameAddon, inRepresentationFilenameAddon,
18754 inCameraFilenameAddon):
18755 "given the imageset and the look direction filename addon, figure out the\n filename for the image. Due to prior implementation, we return two\n values, a temporary name based only on the callback count, and the\n entire name we intend to have so that all processes can agree on the\n file name when it is generated and then process zero can move the image\n filename to it's final correct value. If we return a None as the\n second value, this indicates the callback count temporary name is also\n the final name so no operating system move needs to happen"
18756
18757 inImageBasename = inImageSettings.mImageBasename
18758 inImageBasedirectory = inImageSettings.mImageBasedirectory
18759 inNumCounterDigits = inImageSettings.mNumCounterDigits
18760 inImageFormat = inImageSettings.mImageFormat
18761
18762 timestep = datadescription.GetTimeStep()
18763
18764 lastImagesetName = ""
18765
18766 unusedFilenameFound = False
18767 extraCount = 0
18768 import os
18769
18770 while unusedFilenameFound == False:
18771 imageBasename = inImageBasename
18772 imageBasedirectory = inImageBasedirectory
18773 nameSuffix = inRepresentationFilenameAddon + \
18774 inCameraFilenameAddon + inOneLookDirectionFilenameAddon
18775
18776 if imageBasedirectory == None:
18777 fileBaseName = imageBasename + nameSuffix
18778 elif imageBasedirectory == "":
18779 fileBaseName = imageBasename + nameSuffix
18780 else:
18781 import os
18782 fileBaseName = imageBasedirectory + os.sep + imageBasename + \
18783 nameSuffix
18784
18785 fname = fileBaseName
18786
18787 fname += "%t." + inImageFormat
18788
18789 extraString = GetExtraFileString()
18790 if extraString != '':
18791 fname = fname.replace("%t", extraString + "-%t")
18792 timestepString = str(timestep + extraCount)
18793 while len(timestepString) < inNumCounterDigits:
18794 timestepString = "0" + timestepString
18795 myDebugPrint2("image fname: " + fname + "\ndigit count: " + str(inNumCounterDigits) + "\ntimestepString: " + timestepString + "\n")
18796
18797 rplstr1 = None
18798 if self.mUseDateTime:
18799 ttnow = gPipeAndViewsState.mCallbackDateTime
18800 if self.mUseMicrosecondsWithDateTime == False:
18801 ttnow = ttnow.replace(microsecond=0)
18802 rplstr1 = str(ttnow.isoformat('-'))
18803 if self.mConvertDateTimeToInteger:
18804 import re
18805 rplstr1 = re.sub('[-:.]', '', rplstr1)
18806
18807 if self.mUseSimulationTime:
18808 global gSharedRenderView
18809 simtm = gSharedRenderView.ViewTime
18810 simtmstr = self.mSimulationTimeFormat % simtm
18811 if rplstr1 == None:
18812 rplstr1 = simtmstr
18813 else:
18814 rplstr1 = rplstr1 + "_" + simtmstr
18815
18816 if self.mUseCallbackCount:
18817 #if rplstr1 is None, we just fall through and use the default
18818 #behavior; otherwise we need to add to the string
18819 if rplstr1 != None:
18820 rplstr1 = timestepString + "_" + rplstr1
18821
18822 if rplstr1 != None:
18823 fnameRR = fname.replace("%t", rplstr1)
18824 else:
18825 fnameRR = None
18826
18827 fname = fname.replace("%t", timestepString)
18828
18829 myDebugPrint2("fname after replace: ->" + fname + "<-\n")
18830 #if os.path.exists(fname):
18831 if False: #don't do os.path.exists; it's maybe slow
18832 #myDebugPrint2(" filename in use, try to find another\n")
18833 #unusedFilenameFound = False
18834 unusedFilenameFound = True
18835 extraCount += 1
18836 else:
18837 #myDebugPrint2(" filename is not in use, use it\n")
18838 unusedFilenameFound = True
18839
18840 if self.mUseRemeshRestartTag == False:
18841 if fnameRR != None:
18842 import re
18843 #print "removing, e.g. -s0004-"
18844 #print "before:", fnameRR
18845 fnameRR = re.sub('-s[0123456789]*-', '', fnameRR)
18846 #print "after:", fnameRR
18847
18848 return fname, fnameRR
18849
18850
18851 class PhactoriPlot1Base:
18852 def __init__(self):
18853 self.mName = ""
18854 self.m_DataCubeAxesInfo = PhactoriDataCubeAxesInfo()
18855
18856 self.m_PlotType = "PhactoriPlot1Base"
18857 self.mImageSettings = PhactoriImageSettings()
18858 self.mImageSettings.mPixelBorderRatioXY = [0.175 / self.mImageSettings.GetAspectRatio(), 0.175]
18859 self.mInputOperation = None
18860 #self.m_plotColorInfo = PlotColorInfo()
18861 self.mColorSettings = PhactoriColorSettings(inUsePlotDefaultColors = True)
18862
18863 #used to help generate paraview View and Representation
18864 self.mCamera = PhactoriCameraBlock()
18865
18866 #paraview filter created to hold geometric data
18867 self.m_producer = None
18868 self.m_PhactoriRenderViewInfo = None
18869
18870 #reference for paraview RenderView instance which is shared among all
18871 #renderings
18872 self.mSharedPvRenderView2 = None
18873
18874 #reference for paraview DataRepresentation instance for this imageset.
18875 #if the imageset has multiple view directions, they can share the same
18876 #representation
18877 self.mPvDataRepresentation2 = None
18878
18879 #for compatibility with PhactoriImagesetBlock
18880 self.mLookDirectionList = []
18881 self.mLookDirectionFilenameAddon = []
18882 self.mVisibleOps = [None]
18883 self.mVisibleReps = [None]
18884 self.mVisiblePvDataReps = [None]
18885 self.mColorLegendRepRefs = [None]
18886
18887 #used to control if we want to have image names sequentially count by
18888 #callback index, or if we want to use a date/time based count
18889 #(which can use microseconds or not, and can be converted to an integer
18890 #or not)
18891 self.mImageFileNameCountSettings = ImageFileNameCountSettings()
18892
18893 self.mBackground = [0.0, 0.0, 0.0]
18894
18895 def GetInputPhactoriOperation(self):
18896 #mainly for compatibility between plot blocks and imageset blocks, give
18897 #same access to phactori operation coming being visualized
18898 return self.mInputOperation
18899
18900 def WriteImages(self, datadescription):
18901 "write out the .png/.jpg/whatever images associated with this plot\n block for the current timestep/state. Must loop through camera angles\n and do a write for each one if necessary"
18902 if PhactoriDbg():
18903 myDebugPrint3("PhactoriPlotBase1::WriteImages entered\n")
18904
18905 if self.mImageSettings.mUsingDefaultGeneratedImageBasename:
18906 if self.m_PlotType == "PhactoriScatterPlotBlock":
18907 oneLookDirectionFilenameAddon = "sctr."
18908 elif self.m_PlotType == "PhactoriPlotOverTimeBlock":
18909 oneLookDirectionFilenameAddon = "plot."
18910 else:
18911 oneLookDirectionFilenameAddon = ""
18912 else:
18913 oneLookDirectionFilenameAddon = ""
18914
18915 fname, fnameRR = self.mImageFileNameCountSettings.GetImageFilename(
18916 datadescription, self.mImageSettings,
18917 oneLookDirectionFilenameAddon,
18918 "", #no representation string for plot
18919 self.mCamera.mFilenameAddon)
18920
18921 #used to do this:
18922 #view.ViewTime = datadescription.GetTime()
18923 #maybe need to do this?
18924 #UpdatePipelineWithCurrentTimeArgument()
18925
18926 #SetUpViewAndRepresentationBeforeWriteImage(oneViewInfo)
18927 self.SetUpViewAndRepresentationBeforeWriteImage()
18928
18929 colorPalette = GetSettingsProxy('ColorPalette')
18930 colorPalette.Background = self.mBackground
18931
18932 #only need to update color range for first look direction, rest
18933 #are same
18934 #if self.mRepresentation.mUseFixedColorRange == False:
18935 # UseDataRangeForColorValues(self.mPvDataRepresentation2,
18936 # self.mRepresentation, self.mOperation)
18937 if PhactoriDbg(150):
18938 myDebugPrint3("writing plot image: " + fname + "\n" +
18939 str(self.mSharedPvRenderView2) + "\n")
18940
18941 self.mSharedPvRenderView2.LeftAxisUseCustomRange = 0
18942 self.mSharedPvRenderView2.BottomAxisUseCustomRange = 0
18943
18944 if self.m_PlotType == "PhactoriPlotOverTimeBlock":
18945 self.mPvDataRepresentation2.AttributeType = "Row Data"
18946 self.mSharedPvRenderView2.LeftAxisTitle = self.m_YAxisVariableInfo.GetXYPlotAxisTitle()
18947 self.mSharedPvRenderView2.BottomAxisTitle = "Time"
18948 self.mSharedPvRenderView2.ChartTitle = ""
18949 self.mSharedPvRenderView2.ShowLegend = 1
18950 else:
18951 self.m_producer.UpdatePipeline()
18952 DataRepresentation1 = self.mPvDataRepresentation2
18953 atrtype = "Point Data"
18954 if self.m_YAxisVariableInfo.mVariableType == 'element':
18955 atrtype = "Cell Data"
18956 DataRepresentation1.AttributeType = "Row Data"
18957 DataRepresentation1.AttributeType = atrtype
18958 self.mSharedPvRenderView2.LeftAxisTitle = self.m_YAxisVariableInfo.GetXYPlotAxisTitle()
18959 self.mSharedPvRenderView2.BottomAxisTitle = self.m_XAxisVariableInfo.GetXYPlotAxisTitle()
18960 #self.mSharedPvRenderView2.ChartTitle = "Scatter Plot at Time ${TIME}"
18961 self.mSharedPvRenderView2.ChartTitle = ""
18962 self.mSharedPvRenderView2.ShowLegend = 0
18963 if PhactoriDbg(150):
18964 myDebugPrint3("B representation made for scatter plot:\n" + str(DataRepresentation1) + "\n")
18965 myDebugPrint3("m_producer for scatter plot:\n" + str(self.m_producer) + "\n")
18966 myDebugPrint3("rep input num points " + str(DataRepresentation1.Input.GetDataInformation().DataInformation.GetNumberOfPoints()) + "\n")
18967 myDebugPrint3("DataRepresentation1.ListProperties() " + str(DataRepresentation1.ListProperties()) + "\n")
18968 myDebugPrint3("DataRepresentation1.Input " + str(DataRepresentation1.Input) + "\n")
18969 myDebugPrint3("DataRepresentation1.AttributeType " + str(DataRepresentation1.AttributeType) + "\n")
18970 myDebugPrint3("DataRepresentation1.UseIndexForXAxis " + str(DataRepresentation1.UseIndexForXAxis) + "\n")
18971 myDebugPrint3("DataRepresentation1.Visibility " + str(DataRepresentation1.Visibility) + "\n")
18972 myDebugPrint3("DataRepresentation1.XArrayName " + str(DataRepresentation1.XArrayName) + "\n")
18973 myDebugPrint3("DataRepresentation1.SeriesVisibility " + str(DataRepresentation1.SeriesVisibility) + "\n")
18974 myDebugPrint3("DataRepresentation1.SeriesLabel " + str(DataRepresentation1.SeriesLabel) + "\n")
18975 myDebugPrint3("DataRepresentation1.SeriesColor " + str(DataRepresentation1.SeriesColor) + "\n")
18976 myDebugPrint3("DataRepresentation1.SeriesPlotCorner " + str(DataRepresentation1.SeriesPlotCorner) + "\n")
18977 myDebugPrint3("DataRepresentation1.SeriesLabelPrefix " + str(DataRepresentation1.SeriesLabelPrefix) + "\n")
18978 myDebugPrint3("DataRepresentation1.SeriesLineStyle " + str(DataRepresentation1.SeriesLineStyle) + "\n")
18979 myDebugPrint3("DataRepresentation1.SeriesLineThickness " + str(DataRepresentation1.SeriesLineThickness) + "\n")
18980 myDebugPrint3("DataRepresentation1.SeriesMarkerStyle " + str(DataRepresentation1.SeriesMarkerStyle) + "\n")
18981
18982 yaxisstng = self.m_xyzMinMaxTrkC.mXyzTrk[1]
18983 if yaxisstng.mUseLowestBot and yaxisstng.mUseHighestBot and yaxisstng.mUseLowestTop and yaxisstng.mUseHighestTop:
18984 self.mSharedPvRenderView2.LeftAxisUseCustomRange = 1
18985 self.mSharedPvRenderView2.LeftAxisRangeMinimum = yaxisstng.mLowestBot
18986 self.mSharedPvRenderView2.LeftAxisRangeMaximum = yaxisstng.mHighestTop
18987 xaxisstng = self.m_xyzMinMaxTrkC.mXyzTrk[0]
18988 if xaxisstng.mUseLowestBot and xaxisstng.mUseHighestBot and xaxisstng.mUseLowestTop and xaxisstng.mUseHighestTop:
18989 self.mSharedPvRenderView2.BottomAxisUseCustomRange = 1
18990 self.mSharedPvRenderView2.BottomAxisRangeMinimum = xaxisstng.mLowestBot
18991 self.mSharedPvRenderView2.BottomAxisRangeMaximum = xaxisstng.mHighestTop
18992
18993 WriteImage(fname, self.mSharedPvRenderView2,
18994 Magnification=1)
18995 GetGlobalDataArtifactTracker().AddImageToDataArtifactOutputList(fname)
18996 #handle datetime naming extra work to avoid race condition
18997 if fnameRR != None:
18998 if SmartGetLocalProcessId() == 0:
18999 import os
19000 os.rename(fname, fnameRR)
19001
19002 #ClearPvViewAndPvRepAfterWriteImage(oneViewInfo)
19003 self.ClearPvViewAndPvRepAfterWriteImage()
19004
19005 def SetUpViewAndRepresentationBeforeWriteImage(self):
19006 "Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n from PhactoriDriver immediately before WriteImage in order to set the\n camera, background color, image size, etc. up appropriately for the\n WriteImage call"
19007 if PhactoriDbg(150):
19008 myDebugPrint3("PhactoriPlot1Base:" \
19009 "SetUpViewAndRepresentationBeforeWriteImage entered " + \
19010 str(self.mName) + "\n", 150)
19011 self.mPvDataRepresentation2.Visibility = 1
19012
19013 pvRenderView = self.mSharedPvRenderView2
19014 pvDataRep = self.mPvDataRepresentation2
19015
19016 #image size
19017 #pvRenderView.ViewSize = self.mImageSettings.mImageSize
19018 pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),
19019 int(self.mImageSettings.mImageSize[1])]
19020
19021 UpdatePlotViewLook(self)
19022
19023 def ClearPvViewAndPvRepAfterWriteImage(self):
19024 "Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n immediately after WriteImage in order to make stuff invisible again\n before the next item gets a chance to do WriteImage"
19025 #if PhactoriDbg(150):
19026 # myDebugPrint3("ClearPvViewAndPvRepAfterWriteImage entered\n", 150)
19027
19028 #3d/pointset dataset invisible (plot or 3d viewing)
19029 self.mPvDataRepresentation2.Visibility = 0
19030
19031
19032 class PhactoriPlotOverTimeBlock(PhactoriPlot1Base):
19033 "container for one time plot of variable\n "
19034 def __init__(self):
19035 PhactoriPlot1Base.__init__(self)
19036 self.m_PlotType = "PhactoriPlotOverTimeBlock"
19037 self.m_xyzMinMaxTrkC = PlotXYZMinMaxTrkC()
19038
19039 self.m_XAxisVariableInfo = PhactoriVariableInfo()
19040 self.m_XAxisVariableInfo.mVariableName = "Time Step"
19041
19042 self.m_YAxisVariableInfo = PhactoriVariableInfo()
19043 self.m_YAxisVariableInfo.mVariableName = None
19044
19045 self.m_NumberOfEntries = 0
19046 self.m_vtkTable = None
19047 self.m_TimeColumn = PhactoriPolyDataForPlotLine("Time")
19048 self.m_MaxPlotLine = PhactoriPolyDataForPlotLine("Max")
19049 self.m_MinPlotLine = PhactoriPolyDataForPlotLine("Min")
19050 self.m_MeanPlotLine = PhactoriPolyDataForPlotLine("Mean")
19051 self.m_IdPlotLineList = []
19052
19053 self.mPlotMaximumFlag = None
19054 self.mPlotMinimumFlag = None
19055 self.mPlotMeanFlag = None
19056
19057 def SetFromRestartInfo(self, inJson):
19058 "given a map (json format), use the info in the map to set the\n plot state--this reads the info created by out in \n GetRestartInfo. It should only occur on a restart, and\n it fills in the data that had been generated during the\n earlier run of the system"
19059 if 'm_xyzMinMaxTrkC' not in inJson:
19060 if PhactoriDbg():
19061 myDebugPrint3("PhactoriPlotOverTimeBlock::SetFromRestartInfo " + \
19062 "m_xyzMinMaxTrkC not in inJson\n")
19063 return
19064
19065 self.m_xyzMinMaxTrkC.SetFromRestartInfo(inJson["m_xyzMinMaxTrkC"])
19066 self.m_TimeColumn.SetFromRestartInfo(inJson["m_TimeColumn"])
19067 self.m_MaxPlotLine.SetFromRestartInfo(inJson["m_MaxPlotLine"])
19068 self.m_MinPlotLine.SetFromRestartInfo(inJson["m_MinPlotLine"])
19069 self.m_MeanPlotLine.SetFromRestartInfo(inJson["m_MeanPlotLine"])
19070
19071
19072 def GetRestartInfo(self):
19073 "construct, in python map/json format, the information from this\n plot over time instance which contains the information\n which would be needed to restore the plot over time to the proper\n state after a simulation restart, particularly prior plot points.\n Return the restart info map/json"
19074 newJsonItem = {}
19075 newJsonItem["m_xyzMinMaxTrkC"] = self.m_xyzMinMaxTrkC.GetRestartInfo()
19076 newJsonItem["m_TimeColumn"] = self.m_TimeColumn.GetRestartInfo()
19077 newJsonItem["m_MaxPlotLine"] = self.m_MaxPlotLine.GetRestartInfo()
19078 newJsonItem["m_MinPlotLine"] = self.m_MinPlotLine.GetRestartInfo()
19079 newJsonItem["m_MeanPlotLine"] = self.m_MeanPlotLine.GetRestartInfo()
19080 return newJsonItem
19081
19082 #self.m_TimeColumn = PhactoriPolyDataForPlotLine()
19083 #self.m_MaxPlotLine = PhactoriPolyDataForPlotLine()
19084 #self.m_MinPlotLine = PhactoriPolyDataForPlotLine()
19085 #self.m_MeanPlotLine = PhactoriPolyDataForPlotLine()
19086
19087 class PhactoriScatterPlotBlock(PhactoriPlot1Base):
19088 "container for one parallel scatterplot of one variable\n "
19089 def __init__(self):
19090 PhactoriPlot1Base.__init__(self)
19091 self.m_PlotType = "PhactoriScatterPlotBlock"
19092
19093 self.m_YAxisVariableInfo = PhactoriVariableInfo()
19094 self.m_YAxisVariableInfo.mVariableName = None
19095 self.m_XAxisVariableInfo = PhactoriVariableInfo()
19096 self.m_XAxisVariableInfo.mVariableName = None
19097
19098 self.m_xyzMinMaxTrkC = PlotXYZMinMaxTrkC()
19099 #self.m_PersistentPoints = None
19100 self.m_LimitNumberOfPointsFlag = False
19101 self.m_MaximumNumberOfPoints = 1000
19102 self.m_GrabMinsAndMaxesWhenLimitedFlag = True
19103 #self.m_Name = ""
19104 self.m_PolyData = None
19105 self.m_Points = None
19106 self.m_Vertex = None
19107
19108 #used to keep track paraview mergeblocks filter which is automatically
19109 #applied to the data before doing the ScatterPlot()
19110 self.m_MergeBlocks = None
19111
19112 #self.m_DataCubeAxesInfo = PhactoriDataCubeAxesInfo()
19113
19114 def SetVarABasedOnVarB(self, ioVarInfoA, ioVarInfoB):
19115 if PhactoriDbg():
19116 myDebugPrint3("SetVarABasedOnVarB entered\n")
19117 #see if x axis variable type needs detecting, and if so, detect it
19118 detectResult = ioVarInfoB.DetectVariableType(
19119 self.mInputOperation.GetPvFilter(), True)
19120 #if detectResult == False:
19121 #PutPlotOnListToDetectVariableTypeInFutureSteps() ?
19122 if detectResult == False:
19123 if PhactoriDbg(10000):
19124 myDebugPrint3("PhactoriScatterPlotBlock." + \
19125 "SetVarABasedOnVarB:\n" + \
19126 " error! detect variable type failed.\n",
19127 10000)
19128
19129 #set variable name and type for A based on B
19130 if ioVarInfoB.mVariableType == 'element':
19131 if PhactoriDbg():
19132 myDebugPrint3("variable B is element, setting A\n")
19133 ioVarInfoA.mVariableName = 'GlobalElementId'
19134 ioVarInfoA.mVariableType = 'element'
19135 else:
19136 if PhactoriDbg():
19137 myDebugPrint3("variable B is node, setting A\n")
19138 ioVarInfoA.mVariableName = 'GlobalNodeId'
19139 ioVarInfoA.mVariableType = 'node'
19140 if PhactoriDbg():
19141 myDebugPrint3("SetVarABasedOnVarB returning\n")
19142
19143 def ChooseDefaultVariableIfNecessary(self):
19144 if PhactoriDbg():
19145 myDebugPrint3("ChooseDefaultVariableIfNecessary entered\n")
19146 if PhactoriDbg():
19147 myDebugPrint3(" x axis var:\n" + self.m_XAxisVariableInfo.SelfToStr())
19148 if PhactoriDbg():
19149 myDebugPrint3(" y axis var:\n" + self.m_YAxisVariableInfo.SelfToStr())
19150
19151 if self.m_XAxisVariableInfo.mVariableType == None:
19152 if PhactoriDbg():
19153 myDebugPrint3(" x axis variable needs default from y axis\n")
19154 if self.m_YAxisVariableInfo.mVariableType == None:
19155 if PhactoriDbg(
19156 10000):
19157 myDebugPrint3("PhactoriScatterPlotBlock." + \
19158 "ChooseDefaultVariableIfNecessary:\n" + \
19159 " neither x axis variable or y axis variable is specified\n",
19160 10000)
19161 self.SetVarABasedOnVarB(self.m_XAxisVariableInfo,
19162 self.m_YAxisVariableInfo)
19163 SetUpPlotAxisNameDetails(self.m_XAxisVariableInfo,
19164 self.m_DataCubeAxesInfo.mXAxisInfo)
19165 elif self.m_YAxisVariableInfo.mVariableType == None:
19166 if PhactoriDbg():
19167 myDebugPrint3(" y axis variable needs default from x axis\n")
19168 self.SetVarABasedOnVarB(self.m_YAxisVariableInfo,
19169 self.m_XAxisVariableInfo)
19170 SetUpPlotAxisNameDetails(self.m_YAxisVariableInfo,
19171 self.m_DataCubeAxesInfo.mYAxisInfo)
19172 if PhactoriDbg():
19173 myDebugPrint3("ChooseDefaultVariableIfNecessary returning\n")
19174
19175 def ParseParametersFromJson(self, inJsn, inPipeAndViewsState):
19176 if PhactoriDbg():
19177 myDebugPrint3("PhactoriScatterPlotBlock.ParseParametersFromJson entered\n")
19178 self.mImageSettings.ParseImageSettingsInfo(inJsn,
19179 'plot basename', 'plot basedirectory')
19180 self.mImageFileNameCountSettings.ParseImageFileNameCountSettings(inJsn)
19181
19182 self.mBackground = getParameterFromBlock(inJsn,
19183 'background color', self.mBackground)
19184
19185 #parse x axis variable
19186 self.m_XAxisVariableInfo.ParseVariableNameAndVectorOrTensorComponent(inJsn,
19187 'x axis variable ')
19188
19189 #parse y axis variable
19190 self.m_YAxisVariableInfo.ParseVariableNameAndVectorOrTensorComponent(inJsn,
19191 'y axis variable ')
19192
19193 if self.m_YAxisVariableInfo.mVariableType == None and \
19194 self.m_XAxisVariableInfo.mVariableType:
19195 if PhactoriDbg(
19196 10000):
19197 myDebugPrint3("PhactoriScatterPlotBlock.ParseParametersFromJson " + \
19198 ":\n neither x axis variable or y axis variable is specified\n",
19199 10000)
19200
19201 #handle name of each axis, particularly in vector component/magnitude case
19202 SetUpPlotAxisNameDetails(self.m_XAxisVariableInfo,
19203 self.m_DataCubeAxesInfo.mXAxisInfo)
19204 SetUpPlotAxisNameDetails(self.m_YAxisVariableInfo,
19205 self.m_DataCubeAxesInfo.mYAxisInfo)
19206
19207 #hack to test missing data situations
19208 #if self.mName == "fooScatter":
19209 # myDebugPrint3("hack to test missing data, found fooScatter, using stressthresh\n")
19210 # self.mInputOperation = inPipeAndViewsState.mOperationBlocks["stressthresh"]
19211 #else:
19212 # myDebugPrint3("hack to test missing data, did not find fooScatter\n")
19213 # self.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson(
19214 # 'operation', inJsn)
19215
19216 self.mInputOperation = inPipeAndViewsState.GetOperationReferredByJson(
19217 'operation', inJsn)
19218
19219 self.m_xyzMinMaxTrkC.PlotXYZMinMaxTrkCParseJson(inJsn, 'axis ')
19220
19221 self.mColorSettings.ParsePlotColorSettingsFromJson(inJsn)
19222
19223 if PhactoriDbg():
19224 myDebugPrint3(\
19225 "PhactoriScatterPlotBlock.ParseParametersFromJson returning\n")
19226
19227 global HandleShowAxesWithEmptyDataParaViewIssueFlag
19228 #HandleShowAxesWithEmptyDataParaViewIssueFlag = True
19229 HandleShowAxesWithEmptyDataParaViewIssueFlag = False
19230
19231 #for now, we are trying to have one paraview RenderView which is shared and
19232 #reused for all images everywhere; we may need to change that for plots and
19233 #multiple simulation codes in same input deck
19234 global gSharedRenderView
19235 gSharedRenderView = None
19236
19237 #shared render view to be used by all plots
19238 global gSharedLineChartView
19239 gSharedLineChartView = None
19240
19241 class PhactoriImagesetBlock:
19242 "contains information corresponding to an imageset block\n "
19243 def __init__(self):
19244 self.mName = ""
19245
19246 #weirdness on first image for an imageset; partial fix is to render twice
19247 #the first time
19248 #self.mWriteFirstImageTwiceFlag = 0
19249 #1 is don't render twice first time
19250 self.mWriteFirstImageTwiceFlag = 1
19251
19252 #(for now) mOperation and mRepresentation are the 'primary' data sources
19253 #for this imageset, which includes directing camera positioning if
19254 #necessary. Later we may update this to only have a list, not a
19255 #distinction between primary and other.
19256 self.mOperation = None
19257 self.mRepresentation = None
19258
19259 #(for now) allowing imageset to have additional operations visible.
19260 #later this may become the only recording of which operations are visible
19261 #and mOperation and mRepresentation will be eliminated. Also for
19262 #now, mVisibleOps[0] should be the same as mOperation and
19263 #mVisibleReps[0] should be the same as mRepresentation
19264 self.mVisibleOps = []
19265 self.mVisibleReps = []
19266 self.mVisiblePvDataReps = []
19267 self.mColorLegendRepRefs = []
19268
19269 self.mVisibleMarkerNames = []
19270 self.mVisibleMarkers = []
19271
19272 self.mTextAnnotationNames = []
19273 self.mTextAnnotations = []
19274
19275 self.mCamera = None
19276 self.mImageSettings = PhactoriImageSettings()
19277 self.mLookDirectionList = []
19278 self.mLookDirectionFilenameAddon = []
19279
19280 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 0
19281
19282 #reference for paraview RenderView instance which is shared among all
19283 #renderings
19284 self.mSharedPvRenderView2 = None
19285
19286 #reference for paraview DataRepresentation instance for this imageset.
19287 #if the imageset has multiple view directions, they can share the same
19288 #representation
19289 self.mPvDataRepresentation2 = None
19290
19291 #self.mOnOffCriteriaName = None
19292 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
19293
19294 self.DeadCellIoFf = None
19295
19296 #used to control if we want to have image names sequentially count by
19297 #callback index, or if we want to use a date/time based count
19298 #(which can use microseconds or not, and can be converted to an integer
19299 #or not)
19300 self.mImageFileNameCountSettings = ImageFileNameCountSettings()
19301
19302 self.mBackground = [0.31999694819562063, 0.3400015259021897,
19303 0.4299992370489052]
19304
19305 def GetInputPhactoriOperation(self):
19306 #mainly for compatibility between plot blocks and imageset blocks, give
19307 #same access to phactori operation coming being visualized
19308 return self.mOperation
19309
19310 def HandleShowAxesWithEmptyDataParaViewIssue(self):
19311 "we are having a paraview related issue wherein if an empty dataset\n (due to threshold or clip) has a show axes setting of true, VTK\n complains. For now, we are turning off the cube axes if the data is\n empty and back on if data is nonempty (assuming user has cube axes\n set to on"
19312
19313 if self.mRepresentation.mDataCubeAxesFlag == False:
19314 #nothing to be done--it's off so we just return
19315 return
19316
19317 #allow this functionality to be eliminated to avoid mpi communication
19318 global HandleShowAxesWithEmptyDataParaViewIssueFlag
19319 if HandleShowAxesWithEmptyDataParaViewIssueFlag != True:
19320 return
19321
19322 if self.mHandleShowAxesWithEmptyDataParaViewIssueStatus == 2:
19323 #if PhactoriDbg():
19324 # myDebugPrint3("HandleShowAxesWithEmptyDataParaViewIssue at status 2\n")
19325 return
19326
19327 paraviewSource = self.mOperation.GetPvFilter()
19328 UpdatePipelineWithCurrentTimeArgument(paraviewSource)
19329
19330 pvsDi = paraviewSource.GetDataInformation()
19331
19332 #we find num cells and num points on this processor and share with others;
19333 #note that we use UseReduceToSpreadValues which doesn't sum values--we're
19334 #just trying to ascertain if there are ANY cells or points
19335
19336 numCells = pvsDi.GetNumberOfCells()
19337 numPoints = pvsDi.GetNumberOfPoints()
19338 cellAndPointCount = [numCells, numPoints]
19339 UseReduceToSpreadValues(cellAndPointCount)
19340
19341 #see if data is empty or nonempty
19342 if cellAndPointCount[0] + cellAndPointCount[1] != 0:
19343 datasetIsEmpty = False
19344 else:
19345 datasetIsEmpty = True
19346
19347 #if PhactoriDbg():
19348 # myDebugPrint3("HandleShowAxesWithEmptyDataParaViewIssue executing:\n")
19349 # myDebugPrint3(" num cells: " + str(pvsDi.GetNumberOfCells()) + \
19350 # "\n num points: " + str(pvsDi.GetNumberOfPoints()) + "\n")
19351 # myDebugPrint3("datasetIsEmpty is " + str(datasetIsEmpty) + "\n")
19352
19353 #thePvDataRep = self.mParaViewRenderInfoCs[0].mParaViewInfo.DataRepresentation1
19354
19355 if datasetIsEmpty:
19356 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 1
19357 ShowCubeAxesXX(self.mSharedPvRenderView2, 'off')
19358 else:
19359 self.mHandleShowAxesWithEmptyDataParaViewIssueStatus = 2
19360 ShowCubeAxesXX(self.mSharedPvRenderView2, 'on')
19361
19362 def WriteImages(self, datadescription):
19363 "write out the .png/.jpg/whatever images associated with this imageset\n block for the current timestep/state. Must loop through camera angles\n and do a write for each one if necessary"
19364 if PhactoriDbg(100):
19365 myDebugPrint3("PhactoriImagesetBlock::WriteImages entered: " + \
19366 self.mName + "\n")
19367
19368 global gPipeAndViewsState
19369 if self.mImagesetOnOffFilter.TestDrawImagesThisCallback(
19370 gPipeAndViewsState) == False:
19371 if PhactoriDbg(100):
19372 myDebugPrint3("WriteImages returning with no write due to filter\n")
19373 return
19374
19375 self.WriteImagesPassedOnOffFilter(datadescription)
19376
19377 if PhactoriDbg(100):
19378 myDebugPrint3("PhactoriImagesetBlock::WriteImages returning: " + \
19379 self.mName + "\n")
19380
19381 def WriteOutCameraInformationForTesting(self, fname):
19382 if SmartGetLocalProcessId() != 0:
19383 return
19384 camfname = fname + ".test.camera.txt"
19385 ff = open(camfname, "w")
19386 if ff == None:
19387 return
19388 pvRv = self.mSharedPvRenderView2;
19389 ff.write("{\n")
19390 ff.write("'CameraPosition':" + str(pvRv.CameraPosition) + ",\n")
19391 ff.write("'CameraFocalPoint': " + str(pvRv.CameraFocalPoint) + ",\n")
19392 ff.write("'CameraParallelProjection': " + str(pvRv.CameraParallelProjection) + ",\n")
19393 if pvRv.CameraParallelProjection == 0:
19394 ff.write("'CameraParallelScale': -1.0,\n")
19395 else:
19396 ff.write("'CameraParallelScale': " + str(pvRv.CameraParallelScale) + ",\n")
19397 ff.write("'CameraViewUp': " + str(pvRv.CameraViewUp) + ",\n")
19398 ff.write("'CameraViewAngle': " + str(pvRv.CameraViewAngle) + "\n")
19399 ff.write("}\n")
19400 ff.close()
19401
19402 def WriteImagesPassedOnOffFilter(self, datadescription):
19403 "write out the .png/.jpg/whatever images associated with this imageset\n block for the current timestep/state. Must loop through camera angles\n and do a write for each one if necessary"
19404
19405 global gPipeAndViewsState
19406
19407 if PhactoriDbg(100):
19408 myDebugPrint3(
19409 "PhactoriImagesetBlock::WriteImagesPassedOnOffFilter entered\n")
19410
19411 for ii in range(len(self.mLookDirectionList)):
19412 oneLookDirection = self.mLookDirectionList[ii]
19413 oneLookDirectionFilenameAddon = self.mLookDirectionFilenameAddon[ii]
19414
19415 fname, fnameRR = self.mImageFileNameCountSettings.GetImageFilename(
19416 datadescription, self.mImageSettings,
19417 oneLookDirectionFilenameAddon,
19418 self.mRepresentation.mFilenameAddon,
19419 self.mCamera.mFilenameAddon)
19420
19421 #used to do this:
19422 #view.ViewTime = datadescription.GetTime()
19423 #maybe need to do this?
19424 #UpdatePipelineWithCurrentTimeArgument()
19425
19426 #SetUpViewAndRepresentationBeforeWriteImage(oneViewInfo)
19427 self.SetUpViewAndRepresentationBeforeWriteImage(oneLookDirection, ii)
19428
19429 colorPalette = GetSettingsProxy('ColorPalette')
19430 colorPalette.Background = self.mBackground
19431
19432 #only need to update color range for first look direction, rest
19433 #are same
19434 if ii == 0:
19435 #UpdateColorRangeImmediatelyBeforeWrite(phactoriImagesetName)
19436 if self.mRepresentation.mUseFixedColorRange == False:
19437 UseDataRangeForColorValues(self.mPvDataRepresentation2,
19438 self.mRepresentation, self.mOperation)
19439 for ii in range(1, len(self.mVisibleReps)):
19440 oneVisOp = self.mVisibleOps[ii]
19441 oneVisRep = self.mVisibleReps[ii]
19442 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
19443 UseDataRangeForColorValues(oneVisPvDataRep,
19444 oneVisRep, oneVisOp)
19445
19446 if self.mName.startswith("is_element_select") == False:
19447
19448 for onevisop in self.mVisibleOps:
19449 if onevisop.mType == "nearestpoints":
19450 onevisop.mOperationSpecifics.\
19451 RunCalculationToFindNearestPoints(gPipeAndViewsState)
19452 if onevisop.mType == "castnormalrays":
19453 onevisop.mOperationSpecifics.\
19454 RunCalculationToCastRays(gPipeAndViewsState)
19455 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
19456 if onevisop.mName == "surfaceofinterest1":
19457 global gParaViewCatalystVersionFlag
19458 if gParaViewCatalystVersionFlag < 51000:
19459 svrng = onevisop.mParaViewFilter.ThresholdRange
19460 #onevisop.mParaViewFilter.ThresholdRange = [svrng[0]*0.5, svrng[1]*0.5]
19461 onevisop.mParaViewFilter.ThresholdRange = [1.0, 10.0]
19462 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
19463 onevisop.mParaViewFilter.ThresholdRange = svrng
19464 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
19465 else:
19466 svrngLower = onevisop.mParaViewFilter.LowerThreshold
19467 svrngUpper = onevisop.mParaViewFilter.UpperThreshold
19468 onevisop.mParaViewFilter.LowerThreshold = 1.0
19469 onevisop.mParaViewFilter.UpperThreshold = 10.0
19470 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
19471 onevisop.mParaViewFilter.LowerThreshold = svrngLower
19472 onevisop.mParaViewFilter.UpperThreshold = svrngUpper
19473 UpdatePipelineWithCurrentTimeArgument(onevisop.mParaViewFilter)
19474
19475 if PhactoriDbg():
19476 firstop = self.mVisibleOps[0]
19477 firstPvFilter = firstop.GetPvFilter()
19478 label1 = "before WriteImage() " + fname + "\n"
19479 DebugPrintCellAndPointArrayInfo(label1, firstPvFilter, 100)
19480 myDebugPrint3("self.mPvDataRepresentation2.Representation:\n" + \
19481 str(self.mPvDataRepresentation2.Representation) + "\n")
19482
19483 if PhactoriDbg():
19484 myDebugPrint3("calling WriteImage() " + fname + "\n")
19485
19486 global gCameraTestMode
19487 if gCameraTestMode == 1:
19488 self.WriteOutCameraInformationForTesting(fname)
19489
19490 global gSkipWriteImageForTests
19491 if gSkipWriteImageForTests == False:
19492 WriteImage(fname, self.mSharedPvRenderView2,
19493 Magnification=1)
19494 GetGlobalDataArtifactTracker().AddImageToDataArtifactOutputList(fname)
19495 if PhactoriDbg():
19496 myDebugPrint3("returned from WriteImage()\n")
19497 #handle datetime naming extra work to avoid race condition
19498 if fnameRR != None:
19499 if SmartGetLocalProcessId() == 0:
19500 import os
19501 os.rename(fname, fnameRR)
19502 #hack, double write
19503 #WriteImage(fname, self.mSharedPvRenderView2,
19504 # Magnification=1)
19505
19506 #ClearPvViewAndPvRepAfterWriteImage(oneViewInfo)
19507 self.ClearPvViewAndPvRepAfterWriteImage()
19508
19509 if self.mWriteFirstImageTwiceFlag == 0:
19510 self.mWriteFirstImageTwiceFlag = 1
19511 if PhactoriDbg(100):
19512 myDebugPrint3(
19513 "mWriteFirstImageTwiceFlag triggers (3) re-render of first image\n")
19514 self.WriteImagesPassedOnOffFilter(datadescription)
19515
19516 if self.mName.startswith("is_dead_cells"):
19517 timestep = datadescription.GetTimeStep()
19518
19519 imageBasename = self.mImageSettings.mImageBasename
19520 imageBasedirectory = self.mImageSettings.mImageBasedirectory
19521 import os
19522 #dcfname = + str(timestep) + "_.csv"
19523 lpid = SmartGetLocalProcessId()
19524 #dcfname = imageBasedirectory + os.sep + imageBasename + \
19525 # str(timestep) + "." + str(lpid) + "._.csv"
19526 dcfname = imageBasedirectory + os.sep + imageBasename + \
19527 str(timestep) + "." + str(lpid) + ".csv"
19528 if PhactoriDbg(100):
19529 myDebugPrint3("is_dead_cells: writing:\n" + dcfname + "\n")
19530 rcrsnParams = self.mOperation.OutputElementListToFile(dcfname)
19531 if PhactoriDbg(100):
19532 myDebugPrint3("is_dead_cells: done writing:\n" + dcfname + "\n")
19533
19534 #write out dead cell count
19535 global WriteDeadCellSummaryFile
19536
19537 if WriteDeadCellSummaryFile:
19538 myVals = [rcrsnParams.mElementCount,
19539 rcrsnParams.mKilledByCriteriaCount[2],
19540 rcrsnParams.mKilledByCriteriaCount[3],
19541 rcrsnParams.mKilledByCriteriaCount[5]]
19542 UseReduceToSumArrayOfInts(myVals)
19543
19544 if lpid == 0:
19545 if self.DeadCellIoFf == None:
19546 dcsummaryname = imageBasedirectory + os.sep + imageBasename + \
19547 "dead_cell_info.csv"
19548 self.DeadCellIoFf = open(dcsummaryname, "w")
19549 self.DeadCellIoFf.write("step, simtime, number of dead cells, " \
19550 "killed 2, killed 3, killed 5\n")
19551 timestep = datadescription.GetTimeStep()
19552 simTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
19553 self.DeadCellIoFf.write(
19554 str(timestep) + ", " + \
19555 str(simTime) + "," + \
19556 str(myVals[0]) + ", " + \
19557 str(myVals[1]) + ", " + \
19558 str(myVals[2]) + ", " + \
19559 str(myVals[3]) + "\n")
19560 self.DeadCellIoFf.flush()
19561
19562 if self.mName.startswith("is_element_select"):
19563 timestep = datadescription.GetTimeStep()
19564 #global gPipeAndViewsState
19565 simTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
19566 imageBasename = self.mImageSettings.mImageBasename
19567 imageBasedirectory = self.mImageSettings.mImageBasedirectory
19568 import os
19569 #dcfname = imageBasedirectory + os.sep + imageBasename + ".csv"
19570 dcfname1 = imageBasedirectory + os.sep + imageBasename + "element.csv"
19571 dcfname2 = imageBasedirectory + os.sep + imageBasename + "node.csv"
19572 self.mOperation.OutputSingleElementToTimeHistoryFile(
19573 dcfname1, dcfname2, timestep, simTime)
19574
19575 if PhactoriDbg(100):
19576 myDebugPrint3(
19577 "PhactoriImagesetBlock::WriteImagesPassedOnOffFilter returning\n")
19578
19579 def SetUpViewAndRepresentationBeforeWriteImage(self, inLookDirection,
19580 inLookDirectionIndex):
19581 "Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n immediately before WriteImage in order to set the\n camera, background color, image size, etc. up appropriately for the\n WriteImage call"
19582 if PhactoriDbg(100):
19583 myDebugPrint3("PhactoriImagesetBlock:" \
19584 "SetUpViewAndRepresentationBeforeWriteImage entered " + \
19585 str(self.mName) + "\n", 100)
19586 self.mPvDataRepresentation2.Visibility = 1
19587
19588 pvRenderView = self.mSharedPvRenderView2
19589 pvDataRep = self.mPvDataRepresentation2
19590
19591 #image size
19592 #pvRenderView.ViewSize = self.mImageSettings.mImageSize
19593 pvRenderView.ViewSize = [int(self.mImageSettings.mImageSize[0]),
19594 int(self.mImageSettings.mImageSize[1])]
19595
19596 #background color, text color, etc.
19597
19598 theColorSettings = self.mRepresentation.mColorSettings
19599
19600 theColorSettings.SetParaviewRvRepColors(pvRenderView, pvDataRep)
19601
19602 phactoriRep = self.mRepresentation
19603 #orientation axis on or off for this 3d mesh
19604 if phactoriRep.mOrientationAxesFlag:
19605 pvRenderView.OrientationAxesVisibility = 1
19606 else:
19607 pvRenderView.OrientationAxesVisibility = 0
19608
19609 #time annotation invisible (for 3d plot)
19610 timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings
19611 if timeAnnStngs.mVisible:
19612 global gPipeAndViewsState
19613 if gPipeAndViewsState.mTimeAnnotationPv != None:
19614 gPipeAndViewsState.mTimeAnnotationPv.\
19615 mParaViewRepresentation.Visibility = 1
19616
19617 #cube axes
19618 if phactoriRep.mDataCubeAxesFlag:
19619 ShowCubeAxesXX(pvRenderView, 'on', phactoriRep.mDataCubeAxesInfo)
19620
19621 #edges/surface/wireframe
19622 #self.mPvDataRepresentation2.Representation = \
19623 # phactoriRep.mMeshRenderControl
19624 self.mPvDataRepresentation2.SetRepresentationType(
19625 phactoriRep.mMeshRenderControl)
19626
19627 if phactoriRep.mDoingVolumeRendering:
19628 if phactoriRep.mScalarOpacityUnitDistance < 0.0:
19629 phactoriRep.CalculateDefaultScalarOpacityUnitDistance(self.mOperation)
19630 if phactoriRep.mScalarOpacityUnitDistance != \
19631 self.mPvDataRepresentation2.ScalarOpacityUnitDistance:
19632 self.mPvDataRepresentation2.ScalarOpacityUnitDistance = \
19633 phactoriRep.mScalarOpacityUnitDistance
19634
19635 #size of points
19636 self.mPvDataRepresentation2.PointSize = phactoriRep.mPointSize
19637
19638 #color legend
19639 for oneColorLegendRepRef in self.mColorLegendRepRefs:
19640 if oneColorLegendRepRef != None:
19641 oneColorLegendRepRef.Visibility = 1
19642
19643 #color by variable or solid color or color by block
19644 if inLookDirectionIndex == 0:
19645 #on multicamera 8 setups, we only do this on first (index 0)
19646 SetForCorrectColorBy(self, self.mOperation,
19647 self.mPvDataRepresentation2, phactoriRep, False)
19648 else:
19649 #for some reason, solid color doesn't stick between camera angles;
19650 #redo if it is solid color
19651 if phactoriRep.mColorBySolidColorFlag == True:
19652 SetForCorrectColorBy(self, self.mOperation,
19653 self.mPvDataRepresentation2, phactoriRep, False)
19654
19655 #markers for this imageset made visible
19656 for oneMarker in self.mVisibleMarkers:
19657 oneMarker.UpdateAndMakeVisible()
19658
19659 for oneTextAnnotation in self.mTextAnnotations:
19660 oneTextAnnotation.UpdateAndMakeVisible()
19661
19662 #do extra visible operations/representations
19663 ii = 1
19664 while ii < len(self.mVisibleReps):
19665 oneVisOp = self.mVisibleOps[ii]
19666 oneVisRep = self.mVisibleReps[ii]
19667 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
19668 if PhactoriDbg(100):
19669 myDebugPrint3("add extra visiblity " + str(ii) + " rep:\n" + \
19670 str(oneVisPvDataRep))
19671 ii += 1
19672
19673 oneVisPvDataRep.Visibility = 1
19674 #theColorSettings = self.mRepresentation.mColorSettings
19675 #theColorSettings.SetParaviewRvRepColors(pvRenderView, oneVisPvDataRep)
19676
19677 #edges/surface/wireframe
19678 oneVisPvDataRep.SetRepresentationType(oneVisRep.mMeshRenderControl)
19679
19680 if oneVisRep.mDoingVolumeRendering:
19681 if oneVisRep.mScalarOpacityUnitDistance < 0.0:
19682 oneVisRep.CalculateDefaultScalarOpacityUnitDistance(oneVisOp)
19683 if oneVisRep.mScalarOpacityUnitDistance != \
19684 oneVisPvDataRep.ScalarOpacityUnitDistance:
19685 oneVisPvDataRep.ScalarOpacityUnitDistance = \
19686 oneVisRep.mScalarOpacityUnitDistance
19687
19688
19689 #color legend
19690 #if self.mColorLegendRepRef != None:
19691 # self.mColorLegendRepRef.Visibility = 1
19692
19693 #color by variable or solid color or color by block
19694 if inLookDirectionIndex == 0:
19695 #on multicamera 8 setups, we only do this on first (index 0)
19696 SetForCorrectColorBy(self, oneVisOp,
19697 oneVisPvDataRep, oneVisRep, False)
19698 else:
19699 #for some reason, solid color doesn't stick between camera angles;
19700 #redo if it is solid color
19701 if phactoriRep.mColorBySolidColorFlag == True:
19702 #SetForCorrectColorBy(self, self.mPvDataRepresentation2,
19703 # phactoriRep, False)
19704 SetForCorrectColorBy(self, oneVisOp,
19705 oneVisPvDataRep, oneVisRep, False)
19706
19707 if PhactoriDbg(100):
19708 myDebugPrint3("start setting camera parameters for imageset: " + \
19709 self.mName + "\n", 100)
19710 SetParaViewRepresentationCameraParams(
19711 pvRenderView,
19712 self.mCamera,
19713 inLookDirection,
19714 self.mImageSettings,
19715 self.mOperation.GetPvFilter())
19716 if PhactoriDbg(100):
19717 myDebugPrint3("done setting camera parameters for imageset: " + \
19718 self.mName + "\n", 100)
19719
19720 if PhactoriDbg(100):
19721 myDebugPrint3("SetUpViewAndRepresentationBeforeWriteImage returning\n",
19722 100)
19723
19724 def ClearPvViewAndPvRepAfterWriteImage(self):
19725 "Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n immediately after WriteImage in order to make stuff invisible again\n before the next item gets a chance to do WriteImage"
19726 #if PhactoriDbg(150):
19727 # myDebugPrint3("ClearPvViewAndPvRepAfterWriteImage entered\n", 150)
19728
19729 #cube axes invisible
19730 ShowCubeAxesXX(self.mSharedPvRenderView2, 'off')
19731
19732 #3d/pointset dataset invisible (plot or 3d viewing)
19733 self.mPvDataRepresentation2.Visibility = 0
19734
19735 #color legend invisible, if 3d viewing
19736 for oneColorLegendRepRef in self.mColorLegendRepRefs:
19737 if oneColorLegendRepRef != None:
19738 if PhactoriDbg(100):
19739 myDebugPrint3("C inColorLegendRepRef was " + \
19740 str(oneColorLegendRepRef.Visibility) + \
19741 " now 0: " + str(oneColorLegendRepRef) + "\n")
19742 oneColorLegendRepRef.Visibility = 0
19743
19744 #time annotation invisible (for 3d plot)
19745 timeAnnStngs = self.mRepresentation.mTimeAnnotationSettings
19746 if timeAnnStngs.mVisible:
19747 global gPipeAndViewsState
19748 if gPipeAndViewsState.mTimeAnnotationPv != None:
19749 gPipeAndViewsState.mTimeAnnotationPv.\
19750 mParaViewRepresentation.Visibility = 0
19751
19752 #markers for this imageset made invisible
19753 for oneMarker in self.mVisibleMarkers:
19754 oneMarker.MakeInvisible()
19755
19756 for oneTextAnnotation in self.mTextAnnotations:
19757 oneTextAnnotation.MakeInvisible()
19758
19759 #do extra visible operations/representations
19760 ii = 1
19761 while ii < len(self.mVisibleReps):
19762 oneVisPvDataRep = self.mVisiblePvDataReps[ii]
19763 if(oneVisPvDataRep != None):
19764 oneVisPvDataRep.Visibility = 0
19765 #this is already done above
19766 #oneColorLegendRepRef = self.mColorLegendRepRefs[ii]
19767 #if(oneColorLegendRepRef != None):
19768 # oneColorLegendRepRef.Visbility = 0
19769 ii += 1
19770
19771
19772 def ParseOperationAndRepresentationPair(self, ioPipeAndViewsState, ioJson,
19773 inOperationKey, inSkipIfOperationKeyNotPresent,
19774 inRepresentationKey, inRepresentationKeyRequired,
19775 inAllowPairFromAnotherSource):
19776 "parse out the operation and associated representation from the\n given json; also optionally throw exception if representation\n is not given. Used to get multiple visible operation/representation\n pairs"
19777 if PhactoriDbg():
19778 myDebugPrint3("PhactoriImagesetBlock::"
19779 "ParseOperationAndRepresentationPair entered\n")
19780 myDebugPrint3(
19781 "inOperationKey: " + str(inOperationKey) + "\n"
19782 "inRepresentationKey: " + str(inRepresentationKey) + "\n"
19783 "incoming json:\n" + str(ioJson) + "\n")
19784
19785
19786 if inOperationKey not in ioJson:
19787 if inSkipIfOperationKeyNotPresent:
19788 return
19789
19790 if inRepresentationKeyRequired == False and \
19791 inRepresentationKey not in ioJson:
19792 #we have to construct and use a default representation, including parsing
19793 #commands in the imageset for the representation
19794 if PhactoriDbg():
19795 myDebugPrint3(" ParseOperationAndRepresentationPair: for imageset " + \
19796 self.mName + \
19797 " there is no representation, " +
19798 "so we must add and reference default\n")
19799 defaultRepName = self.mName + '_default_representation'
19800 defaultRepBlockAndWrapper = {defaultRepName: ioJson}
19801 ParseBlocksC(ioPipeAndViewsState.mRepresentationBlocks,
19802 defaultRepBlockAndWrapper,
19803 PhactoriRepresentationBlock,
19804 ParseOneRepresentationBlockC,
19805 ioPipeAndViewsState)
19806 ioJson[inRepresentationKey] = defaultRepName
19807
19808 pipeForPair = None
19809 if inAllowPairFromAnotherSource:
19810 anotherVisOperation, pipeForPair = ioPipeAndViewsState. \
19811 GetOperationReferredByJsonCrossPipe(inOperationKey, ioJson)
19812 else:
19813 anotherVisOperation = ioPipeAndViewsState.GetOperationReferredByJson(
19814 inOperationKey, ioJson)
19815
19816 self.mVisibleOps.append(anotherVisOperation)
19817
19818 anotherVisRepresentation = None
19819 if inRepresentationKey in ioJson:
19820 pipeForRepresentation = ioPipeAndViewsState
19821 if pipeForPair != None:
19822 pipeForRepresentation = pipeForPair
19823 representationName = ioJson[inRepresentationKey]
19824 if representationName not in pipeForRepresentation.mRepresentationBlocks:
19825 errStr = "ParseOperationAndRepresentationPair::exeception/error\n" + \
19826 " imageset (" + str(self.mName) + \
19827 ") calls for representation (" + \
19828 str(representationName) + ") which does not exist\n"
19829 myDebugPrint3AndException(errStr)
19830 else:
19831 anotherVisRepresentation = \
19832 pipeForRepresentation.mRepresentationBlocks[representationName]
19833
19834 if anotherVisRepresentation == None:
19835 #at this point we should have a representation--if we don't it
19836 #was required to be set but not set
19837 myDebugPrint3AndException(\
19838 "PhactoriImagesetBlock::ParseOperationAndRepresentationPair\n"
19839 "Exception/Error: operation missing required corresponding\n"
19840 "repesentation.\noperation key: " + inOperationKey + "\n"
19841 "missing representation key: " + inRepresentationKey + "\n")
19842
19843 self.mVisibleReps.append(anotherVisRepresentation)
19844 self.mVisiblePvDataReps.append(None)
19845 self.mColorLegendRepRefs.append(None)
19846
19847 class PhactoriPipeAndViewsState:
19848 "Top State Container--Pipeline, Cameras, Representations, Imagesets, Plots\n\n This is essentially the top-level class for wrapping up everything about the\n phactori-controlled viewing situation. It keeps a reference to the original\n json (assuming that was how the state was described originally), and stores\n and organizes all the other information. Presently that means that there\n six sets, each of which stores the class instances corresponding to one\n block type from the json input format. The block types stored are the\n camera blocks, the representation blocks, the operation blocks, the\n imageset blocks, the scatter plot blocks, and the plot over time blocks.\n A set for each type of block is kept, with the block name (assigned by the\n json author) as a key for that block. The Operation blocks are basically\n analagous to the ParaView/Catalyst Filters, the imagesets are roughly\n analagous to the ParaView Views (but with image endpoints rather than\n interactive rendering endpoints), the Representation blocks plus the\n camera blocks are analagous to the ParaView Representations. The\n scatter plot and plot over time blocks are simply specialized descriptions\n of requested plots, which are converted into ParaView filters and views\n to create plots which can be calculated and/or rendered in parallel at\n runtime, as opposed to bringing data to the client. An imageset block will\n reference a camera block, a representation block, and an operation block and\n contains some additional parameters (e.g. image size and file basename)\n which will describe a view to be rendered--repeatedly at different times\n when using insitu. The camera blocks describe 3-D viewpoints, sometimes in\n absoulte 3D terms, sometimes dependent on the data. The representation\n blocks control how the view looks, e.g. if element surface and edges are\n rendered or just surfaces and if we show axes and color legends. The\n operation blocks can describe a potentially complex data pipeline which can\n allow rendering at various points along the pipeline. The pipeline is\n currently assumed to have operations that only have one input and one\n output. Multiple operations can have the same input, so a 'tree' is\n possible, not just a single linear pipe. Operations with multiple inputs\n and outputs are conceivable but not currently implemented. One obvious\n possible upgrade would be to allow 'geometryoutput' blocks which would\n output geometry rather than images, presumably geometry which is at the\n back end of a pipeline (e.g. to extract isosurface and the decimate).\n "
19849 def __init__(self):
19850 self.mJsonDescription = {}
19851 self.mCameraBlocks = {}
19852 self.mRepresentationBlocks = {}
19853 #default operation for incoming input
19854 self.mIncomingDefaultOperation = PhactoriOperationBlock()
19855 self.mIncomingDefaultOperation.mName = "default incoming input"
19856 #self.mIncomingOperationList = []
19857 self.mOperationBlocks = {}
19858 self.mImagesetBlocks = {}
19859 self.mScatterPlotBlocks = {}
19860 self.mPlotOverTimeBlocks = {}
19861 self.mImagesetOnOffCriteriaBlocks = {}
19862 self.mMarkerBlocks = {}
19863 self.mTextAnnotationBlocks = {}
19864 self.mCallbackDateTime = datetime.datetime.now()
19865
19866 #used to essentially keep track of the number of times catalyst is
19867 #called back, for keying when we do or do not need to recalculate
19868 #things such as variable mins/maxes
19869 self.mFrameTagCounter = 0
19870
19871 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
19872
19873 #the following items help id this instance to one results output block
19874 #in the input deck, and to a given restart or remesh instance
19875 self.mOutputResultsBlockId = None
19876 self.mCurrentDatabaseDummyFileName = None
19877 self.mProducer = None
19878 #self.mIncomingGridProducerList = []
19879 self.mPipeAndViewsState = None
19880 self.mRemeshRestartTag = None
19881 self.mSeparatorString = '_'
19882 self.mRemeshCount = 0
19883 self.mOutputResultsBlockCountId = -1
19884 self.mImageSetCounter = 0
19885
19886 self.CurrentDatadescription = None
19887 self.mDefaultBasedirectory = ''
19888
19889 self.mBlockIdForRestart = ''
19890
19891 #self.mInteractionEnabled = True
19892 self.mInteractionEnabled = False
19893 self.mInteractionTriggerCounter = 0
19894 self.mInteractionTriggerTries = 7
19895 self.mInteractionTriggerSleep = 1
19896 self.mInteractionRepeatPauseSim = False
19897
19898 #class instance to filter rendering of images on/off based on simulation
19899 #data
19900 self.mImagesetOnOffFilter = PhactoriImagesetOnOffFilter()
19901
19902 #this item manges the paraview representation and color stuff for the
19903 #time annotation source.
19904 #since we are now using one RenderView, we can share a single time
19905 #annotation source representation. However, it is conceivable that
19906 #we may eventually want to show different times for some reason, and
19907 #in that case we will need to have each imageset have its own time
19908 #annotation paraview stuff
19909 self.mTimeAnnotationPv = None
19910
19911 def ExportOperationsData(self, datadescription):
19912 "go through all the operation blocks and call the ExportOperationData()\n method on each to allow each operation to export non-image data if\n they need to do so"
19913 for operationName, operationInstance in self.mOperationBlocks.items():
19914 operationInstance.ExportOperationData(datadescription)
19915
19916 def WriteImages(self, datadescription):
19917 "go through all imageset blocks and plot blocks and have each of them\n write out their images"
19918
19919 global gRenderingEnabled
19920 if gRenderingEnabled == False:
19921 if PhactoriDbg():
19922 myDebugPrint3("PhactoriPipeAndViewsState:WriteImages returning with noop because rendering is disabled\n")
19923 return
19924
19925 #since we are sharing a paraview RenderView instance, we need to go
19926 #through all the plots and imagesets and turn them all to invisible
19927 #so they can be made visible one at a time during the write image loop
19928
19929 #NOTE: when we change this it needs to work across multiple pipes
19930 #i.e. all pipes need to make selves invisible
19931 self.SetUpForWriteImageLoop()
19932
19933 for imagesetName, imagesetInstance in self.mImagesetBlocks.items():
19934 imagesetInstance.WriteImages(datadescription)
19935 for splotName, splotInstance in self.mScatterPlotBlocks.items():
19936 splotInstance.WriteImages(datadescription)
19937 for tplotName, tplotInstance in self.mPlotOverTimeBlocks.items():
19938 tplotInstance.WriteImages(datadescription)
19939
19940
19941 def SetUpForWriteImageLoop(self):
19942 "Since it turns out to be much more memory efficient to reuse a single\n render view rather than having one per image, this routine is called\n from WriteImages immediately before we start looping through the\n imagesets and plots to render images in order to basically set all\n paraview Representations to Visibility=0 so that we can turn them\n visible approriately as we do a WriteImage for each one."
19943
19944 for imagesetName, imagesetInstance in self.mImagesetBlocks.items():
19945 imagesetInstance.ClearPvViewAndPvRepAfterWriteImage()
19946 for splotName, splotInstance in self.mScatterPlotBlocks.items():
19947 splotInstance.ClearPvViewAndPvRepAfterWriteImage()
19948 for tplotName, tplotInstance in self.mPlotOverTimeBlocks.items():
19949 tplotInstance.ClearPvViewAndPvRepAfterWriteImage()
19950
19951 def GetOperationReferredByJson(self, inOperationNameKey, inJsonDict):
19952 "utility function to get a reference to an operation instance given a\n dict (inJsonDict) which may (or may not) contain the key\n (inOperationNameKey) which tags the name of the operation to be\n found. If the key isn't there, we return mIncomingDefaultOperation,\n if the key grabs a name which isn't in mOperationBlocks, that is an\n exception"
19953 if inOperationNameKey in inJsonDict:
19954 nameOfOperationToUse = inJsonDict[inOperationNameKey]
19955 if nameOfOperationToUse not in self.mOperationBlocks:
19956 errStr = ' in GetOperationReferredByJson operation with name ' +\
19957 str(nameOfOperationToUse) + ' does not exist\n'
19958 if PhactoriDbg():
19959 myDebugPrint3(errStr)
19960 raise Exception(errStr)
19961 returnOperation = self.mOperationBlocks[nameOfOperationToUse]
19962 else:
19963 returnOperation = self.mIncomingDefaultOperation
19964
19965 return returnOperation
19966
19967 def GetOperationReferredByJsonCrossPipe(self, inOperationNameKey, inJsonDict):
19968 "same as GetOperationReferredByJson(); however, if the operation is not\n in our self.mOperationBlocks, then we will also search all the other\n pipe and views state instances for the operation. If we find it, we\n will return it along with the pipe we found it in"
19969 if inOperationNameKey in inJsonDict:
19970 nameOfOperationToUse = inJsonDict[inOperationNameKey]
19971 if nameOfOperationToUse in self.mOperationBlocks:
19972 #this operation is in our own operation blocks; return it and None
19973 #to follow the normal course of (non cross-pipe) operation
19974 returnOperation = self.mOperationBlocks[nameOfOperationToUse]
19975 returnPipe = None
19976 else:
19977 returnOperation = None
19978 returnPipe = None
19979 for onePipeKey, onePipe in gPhactoriPipeRootMap.items():
19980 if nameOfOperationToUse in onePipe.mOperationBlocks:
19981 #we found the operation in another pipe; return that and the other
19982 #pipe
19983 returnOperation = onePipe.mOperationBlocks[nameOfOperationToUse]
19984 returnPipe = onePipe
19985 break
19986 if returnOperation == None:
19987 #operation not found anywhere: this is fatal
19988 errStr = " in GetOperationReferredByJsonCrossPipe " +\
19989 "operation with name " +\
19990 str(nameOfOperationToUse) + " does not exist in any pipe\n"
19991 if PhactoriDbg():
19992 myDebugPrint3(errStr)
19993 raise Exception(errStr)
19994 else:
19995 #this code path requires an operation name, no implied default allowed
19996 errStr = " in GetOperationReferredByJsonCrossPipe " +\
19997 "requires specific operation name; no implied default allowed\n"
19998 if PhactoriDbg():
19999 myDebugPrint3(errStr)
20000 raise Exception(errStr)
20001
20002 return returnOperation, returnPipe
20003
20004 def GetOperationBlockByName(self, inName):
20005 if inName not in self.mOperationBlocks:
20006 myDebugPrint3AndException("PhactoriPipeAndViewsState:GetOperationBlockByName\n"
20007 "requesting paraview operation from nonexistent operation block: " + inName)
20008 return self.mOperationBlocks[inName]
20009
20010 def GetParaViewSourceByOperationName(self, inName):
20011 opBlock = self.GetOperationBlockByName(inName)
20012 pvSource = opBlock.GetPvFilter()
20013 if pvSource == None:
20014 myDebugPrint3AndException("PhactoriPipeAndViewsState:GetParaViewSourceByOperationName\n"
20015 "ParaView source is None for operation block: " + inName)
20016 return pvSource
20017
20018
20019 def PerRendersetInitialization(datadescription):
20020 "do setup necessary on a once-per insitu callback basis\n\n There are some things that should be done once each time everything is\n rendered, particularly incrementing a callback counter so that we can keep\n track and do some things, such as getting data bounds, as few times as\n possible (i.e. don't get data bounds for an operation stage multiple times\n when once is sufficient)\n "
20021 global gPipeAndViewsState
20022 gPipeAndViewsState.mFrameTagCounter = gPipeAndViewsState.mFrameTagCounter + 1
20023 if PhactoriDbg(100):
20024 myDebugPrint3("-X-X-X-X- mFrameTagCounter now " + \
20025 str(gPipeAndViewsState.mFrameTagCounter) + " -X-X-X-X-\n", 100)
20026
20027 if PhactoriDbg():
20028 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
20029 pvsDi = paraviewSource.GetDataInformation()
20030 #pointDataInfo = paraviewSource.GetPointDataInformation()
20031 #cellDataInfo = paraviewSource.GetCellDataInformation()
20032 myDebugPrint3(" PerRendersetInitialization:\n num cells: " + str(pvsDi.GetNumberOfCells()) + "\n num points: " + str(pvsDi.GetNumberOfPoints()) + "\n")
20033
20034 #we assume to begin with that all global data bounds in operations are
20035 #invalid as data may have changed
20036 for oneOperationName, oneOperation in \
20037 gPipeAndViewsState.mOperationBlocks.items():
20038 oneOperation.mDataBoundsIsCurrent = False
20039
20040 #update the time tag in all views
20041 global gRenderingEnabled
20042 if gRenderingEnabled:
20043 global gSharedRenderView
20044 gSharedRenderView.ViewTime = datadescription.GetTime()
20045 else:
20046 if PhactoriDbg():
20047 myDebugPrint3("gSharedRenderView.ViewTime not set due to no rendering\n")
20048
20049 def UpdateRepresentationColorBy(ioPhactoriImagesetBlock):
20050 "given a para view representation and source and a phactori representation,\n set the color by variable in the paraview representation based on the\n phactori representation. Used to interactively change what the\n 'color by' variable is between insitu callbacks"
20051 if PhactoriDbg():
20052 myDebugPrint3("UpdateRepresentationColorBy entered\n")
20053
20054 for ii in range(0, len(ioPhactoriImagesetBlock.mVisibleReps)):
20055 oneVisOp = ioPhactoriImagesetBlock.mVisibleOps[ii]
20056 oneVisRep = ioPhactoriImagesetBlock.mVisibleReps[ii]
20057 oneVisPvDataRep = ioPhactoriImagesetBlock.mVisiblePvDataReps[ii]
20058 oneColorLegendRepRef = ioPhactoriImagesetBlock.mColorLegendRepRefs[ii]
20059 if oneVisRep != None:
20060 retVal = UpdateRepresentationColorBySub1(
20061 ioPhactoriImagesetBlock.mSharedPvRenderView2, oneVisPvDataRep,
20062 oneVisRep, oneVisOp, oneColorLegendRepRef)
20063 if oneColorLegendRepRef == None and retVal != None:
20064 if PhactoriDbg(100):
20065 myDebugPrint3("in PhactoriImagsetBlock named: " + \
20066 ioPhactoriImagesetBlock.mName + "\n" + \
20067 "mColorLegendRepRefs " + str(ii) +
20068 "is set to " + str(retVal) + "\n")
20069 ioPhactoriImagesetBlock.mColorLegendRepRefs[ii] = retVal
20070
20071 if PhactoriDbg():
20072 myDebugPrint3("UpdateRepresentationColorBy returning\n")
20073
20074 def UpdateRepresentationColorBySub1(inPvView, inPvRep,
20075 inPhactoriRep, inPhactoriOp, inColorLegendRepRef):
20076 if PhactoriDbg():
20077 myDebugPrint3("UpdateRepresentationColorBySub1 entered\n")
20078
20079 colorVarInfo = inPhactoriRep.mColorVariableInfo
20080
20081 if PhactoriDbg():
20082 myDebugPrint3("setting color by to:\n" + colorVarInfo.SelfToStr() + "\n")
20083
20084 colorVarName = colorVarInfo.mVariableName
20085 detectResult = colorVarInfo.DetectVariableType(
20086 inPhactoriOp.GetPvFilter(), True)
20087 if detectResult == False:
20088 if PhactoriDbg(100):
20089 myDebugPrint3('no detection: returning\n', 100)
20090 return None
20091
20092 if colorVarInfo.mVariableType == 'element':
20093 thePvVarType = gCellsString
20094 elif colorVarInfo.mVariableType == 'node':
20095 thePvVarType = gPointsString
20096 else:
20097 if PhactoriDbg(100):
20098 myDebugPrint3('bad element type: returning\n', 100)
20099 return None
20100
20101 if colorVarName != '':
20102 if inPhactoriRep.mColorVariableInfo.mVariableIsVectorComponent:
20103 ColorByVariableComponentOrMagnitudeXX(inPvRep, inPhactoriRep,
20104 colorVarName, 'Component', colorVarInfo.mVariableComponent,
20105 thePvVarType, inPhactoriRep.mColorMapSettings)
20106 if colorVarInfo.mVariableComponent == 0:
20107 componentString = "X"
20108 elif colorVarInfo.mVariableComponent == 1:
20109 componentString = "Y"
20110 elif colorVarInfo.mVariableComponent == 2:
20111 componentString = "Z"
20112 else:
20113 componentString = str(colorVarInfo.mVariableComponent)
20114 elif inPhactoriRep.mColorVariableInfo.mVariableIsVectorMagnitude:
20115 ColorByVariableComponentOrMagnitudeXX(inPvRep, inPhactoriRep,
20116 colorVarName, 'Magnitude', colorVarInfo.mVariableComponent,
20117 thePvVarType, inPhactoriRep.mColorMapSettings)
20118 componentString = "Magnitude"
20119 else:
20120 ColorByVariableScalarXX(inPvRep, inPhactoriRep, colorVarName,
20121 thePvVarType, inPhactoriRep.mColorMapSettings)
20122 componentString = ""
20123
20124 #update the color legend widget
20125 if inPhactoriRep.mColorLegendFlag:
20126 onoffFlagString = 'on'
20127 else:
20128 onoffFlagString = 'off'
20129 retVal = ShowDataColorLegendXX(inPvView, onoffFlagString,
20130 inPhactoriRep.mColorLegendPositionAndSize, inPhactoriRep.mColorSettings,
20131 inColorLegendRepRef, inPvRep, componentString)
20132
20133 if PhactoriDbg():
20134 myDebugPrint3("UpdateRepresentationColorBySub1 returning\n")
20135
20136 return retVal
20137
20138 def DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState):
20139 "used by process zero (broadcast send process) as well as other processes\n (broadcast recieve processes) to actually take the info in json format\n and set the system up for proper behavior after restart, particularly\n data ranges and plots over time"
20140 #go through representations and have each add it's state info to jsonOut
20141 if "RepresentationsRestartInfo" not in jsonIn:
20142 if PhactoriDbg():
20143 myDebugPrint3("StartOfVisualizationCallback returning, no rep info\n")
20144 return
20145
20146 representationsJsonIn = jsonIn["RepresentationsRestartInfo"]
20147 for oneRepName, oneRep in \
20148 ioPipeAndViewsState.mRepresentationBlocks.items():
20149 if oneRepName in representationsJsonIn:
20150 if PhactoriDbg():
20151 myDebugPrint3("restart setup callback json for rep: " + oneRepName + "\n")
20152 oneRep.SetFromRestartInfo(representationsJsonIn[oneRepName])
20153 else:
20154 if PhactoriDbg():
20155 myDebugPrint3("warning: Representation named " + oneRepName +
20156 " not in restart info")
20157
20158 plotsOverTimeJsonIn = jsonIn["PlotsOverTimeRestartInfo"]
20159 for onePlotOtName, onePlotOt in \
20160 ioPipeAndViewsState.mPlotOverTimeBlocks.items():
20161 if onePlotOtName in plotsOverTimeJsonIn:
20162 if PhactoriDbg():
20163 myDebugPrint3("plot over time setup callback json for rep: " + \
20164 onePlotOtName + "\n")
20165 onePlotOt.SetFromRestartInfo(plotsOverTimeJsonIn[onePlotOtName])
20166 else:
20167 if PhactoriDbg():
20168 myDebugPrint3("warning: plot over time named " + onePlotOtName +
20169 " not in restart info")
20170
20171
20172 def HandleRestartUpdateProcessZero(ioPipeAndViewsState):
20173 if PhactoriDbg():
20174 myDebugPrint3("HandleRestartUpdateProcessZero entered\n")
20175 #import pdb
20176 #pdb.set_trace()
20177
20178 #broadcast for full multiprocess functionality
20179 #color range needs no broadcast, as that will be managed when color range
20180 #calculated for the next frame (process 1 will share the maxes and mins
20181 #it has)
20182 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
20183 globalController = pm.GetGlobalController()
20184
20185 #try to read file written (presumably last restart place)
20186 #and convert to json with expected string type
20187 validDataIsAvailableToBroadcast = True
20188 try:
20189 #read map/json from file
20190 import os
20191
20192 restartInfoFilename = ioPipeAndViewsState.mDefaultBasedirectory + \
20193 os.sep + ioPipeAndViewsState.mBlockIdForRestart + ".phrs"
20194
20195 inFile = open(restartInfoFilename, "rb")
20196 jsonIn = json.load(inFile)
20197 inFile.close()
20198 jsonIn = convertJsonUnicodeToStrings(jsonIn)
20199
20200 except:
20201 if PhactoriDbg():
20202 myDebugPrint3("no info file to read or json failed\n")
20203 #need to broadcast to non-zero processes that there is no info--we
20204 #do this by indicating a length of zero
20205 validDataIsAvailableToBroadcast = False
20206
20207 if validDataIsAvailableToBroadcast:
20208 try:
20209 DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState)
20210 except:
20211 if PhactoriDbg():
20212 myDebugPrint3("exception trying to use info for setting\n")
20213 validDataIsAvailableToBroadcast = False
20214
20215 #if no valid data is available (either no file read or bad data), send
20216 #indicator to other processes by sending 0 data size
20217 if validDataIsAvailableToBroadcast == False:
20218 if PhactoriDbg():
20219 myDebugPrint3("no valid restart data to send, send signal of no data\n")
20220 vtkInfoBufferSizeArray = vtk.vtkIntArray()
20221 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
20222 vtkInfoBufferSizeArray.SetValue(0, 0)
20223 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
20224 if PhactoriDbg():
20225 myDebugPrint3("HandleRestartUpdateProcessZero returning 2\n")
20226 return
20227
20228 try:
20229
20230 outStr = json.dumps(jsonIn)
20231
20232 numberOfValues = len(outStr)
20233
20234 if PhactoriDbg():
20235 myDebugPrint3("valid restart data to send. Sending size: " + \
20236 str(numberOfValues) + "\n")
20237 #send size of data buffer first
20238 vtkInfoBufferSizeArray = vtk.vtkIntArray()
20239 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
20240 vtkInfoBufferSizeArray.SetValue(0, numberOfValues)
20241 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
20242
20243 if PhactoriDbg():
20244 myDebugPrint3("now sending data\n")
20245 #now fill out data and send it
20246 vtkOutArray = vtk.vtkCharArray()
20247 vtkOutArray.SetNumberOfTuples(numberOfValues)
20248 for jj in range(0, numberOfValues):
20249 vtkOutArray.SetValue(jj, outStr[jj])
20250
20251 globalController.Broadcast(vtkOutArray, 0)
20252
20253 if PhactoriDbg():
20254 myDebugPrint3("done sending data\n")
20255 except:
20256 #broadcast error; not really recoverable;
20257 if PhactoriDbg():
20258 myDebugPrint3("exception trying to broadcast\n")
20259 if PhactoriDbg():
20260 myDebugPrint3("HandleRestartUpdateProcessZero returning 4\n")
20261 return
20262
20263 if PhactoriDbg():
20264 myDebugPrint3("HandleRestartUpdateProcessZero returning\n")
20265
20266
20267 def HandleRestartUpdateProcessNotZero(ioPipeAndViewsState):
20268
20269 if PhactoriDbg():
20270 myDebugPrint3("HandleRestartUpdateProcessNotZero entered\n")
20271
20272 try:
20273 #do broadcast (receive from process 0) to receive update data
20274 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
20275 globalController = pm.GetGlobalController()
20276
20277 if PhactoriDbg():
20278 myDebugPrint3("trying to receive data buffer length")
20279
20280 #first, get size of data. If it is zero, we are done and there won't be
20281 #another broadcast
20282 vtkInfoBufferSizeArray = vtk.vtkIntArray()
20283 vtkInfoBufferSizeArray.SetNumberOfTuples(1)
20284 #vtkInfoBufferSizeArray.SetValue(0, 0)
20285 globalController.Broadcast(vtkInfoBufferSizeArray, 0)
20286 bufferLen = vtkInfoBufferSizeArray.GetTuple1(0)
20287 if bufferLen == 0:
20288 if PhactoriDbg():
20289 myDebugPrint3("broadcast indicated 0 data, so we are done\n")
20290 if PhactoriDbg():
20291 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 2\n")
20292 return;
20293
20294 if PhactoriDbg():
20295 myDebugPrint3("buffer length: " + str(bufferLen) + \
20296 ", now trying to receive data\n")
20297 #first go round, fixed buffer length, next expandable if necessary
20298 vtkOutArray = vtk.vtkCharArray()
20299 vtkOutArray.SetNumberOfTuples(bufferLen)
20300 #for jj in range(0, bufferLen):
20301 # vtkOutArray.SetValue(jj, 0)
20302
20303 #receive broadcast of info from process 0
20304 globalController.Broadcast(vtkOutArray, 0)
20305 if PhactoriDbg():
20306 myDebugPrint3("data received successfully\n")
20307 except:
20308 #broadcast error; not really recoverable;
20309 if PhactoriDbg():
20310 myDebugPrint3("exception trying to receive broadcast\n")
20311 if PhactoriDbg():
20312 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 2\n")
20313 return
20314
20315 try:
20316 if PhactoriDbg():
20317 myDebugPrint3("converting data to json format string\n")
20318 #convert to json-format string
20319 jsonCharList = []
20320 for ii in range(0, bufferLen):
20321 oneChar = vtkOutArray.GetTuple1(ii)
20322 jsonCharList.append(oneChar)
20323
20324 jsonInString = "".join(jsonCharList)
20325
20326 if PhactoriDbg():
20327 myDebugPrint3("json received from broadcast (converted to string):\n" +
20328 jsonInString)
20329
20330 #convert json format string to python dict
20331 jsonIn = json.loads(jsonInString)
20332
20333 if PhactoriDbg():
20334 myDebugPrint3("json received from broadcast (converted to dict):\n" +
20335 str(jsonIn))
20336
20337 #use info to set up for post-restart (color ranges, time plots, etc.)
20338 DuringRestartUseJsonToSetUp(jsonIn, ioPipeAndViewsState)
20339
20340 except:
20341 #broadcast error; not really recoverable;
20342 if PhactoriDbg():
20343 myDebugPrint3("exception trying to use broadcast info as json set info\n")
20344 if PhactoriDbg():
20345 myDebugPrint3("HandleRestartUpdateProcessNotZero returning 3\n")
20346 return
20347
20348 if PhactoriDbg():
20349 myDebugPrint3("HandleRestartUpdateProcessNotZero returning\n")
20350
20351
20352 def HandleRestartUpdateForOutputResultsBlock(ioPipeAndViewsState):
20353 "this method is a companion to SaveRestartInfoCallback. It is called\n after the pipeline is first initialized for the given output block, and\n it will read the data stored by SaveRestartInfoCallback in a file.\n The presumption is that the pipeline will be initialized for the \n given output block only once when the system starts or only once\n when the system restarts.\n The intent is to deal with restart by allowing persistent\n information across restarts. See SaveRestartInfoCallback."
20354 if PhactoriDbg():
20355 myDebugPrint3("HandleRestartUpdateForOutputResultsBlock entered\n")
20356
20357 #we need to behave differently for process 0 and other processes; process 0
20358 #needs to read the file and, if necessary, broadcast info to other
20359 #processes, while other processes need to receive info broadcast from 0, if
20360 #necessary
20361 if SmartGetLocalProcessId() == 0:
20362 HandleRestartUpdateProcessZero(ioPipeAndViewsState)
20363 else:
20364 HandleRestartUpdateProcessNotZero(ioPipeAndViewsState)
20365
20366
20367 if PhactoriDbg():
20368 myDebugPrint3("HandleRestartUpdateForOutputResultsBlock returning\n")
20369
20370
20371 def SaveRestartInfoCallback():
20372 "this method is called back at the tail end of the visualization\n from the simulation. The purpose of this function is to collect and\n save out information which is necessary for a restart to have the\n restart begin in the same state as if the simulation had run to this\n point. Items include things such as\n recording color range mins and maxes and data values in plots over time\n so that they can be correctly restarted in the case of a simulation\n restart"
20373
20374 if PhactoriDbg():
20375 myDebugPrint3("SaveRestartInfoCallback entered\n")
20376 #only process zero gets to write anything out: info should have already
20377 #been shared appropriately to process zero and we don't want every process
20378 #hitting the disk
20379 if SmartGetLocalProcessId() != 0:
20380 if PhactoriDbg():
20381 myDebugPrint3("SaveRestartInfoCallback returning, not process zero\n")
20382 return
20383
20384 #we construct a json-format/python map style data item which we will save
20385 #out to a file. We start with a blank map and allow each image set and
20386 #plot over time to add stuff to it. Then we write it out to a file.
20387
20388 jsonOut = {}
20389 global gPipeAndViewsState
20390
20391 #go through representations and have each add it's state info to jsonOut
20392 representationsJsonOut = {}
20393 for oneRepName, oneRep in \
20394 gPipeAndViewsState.mRepresentationBlocks.items():
20395 if PhactoriDbg():
20396 myDebugPrint3("making end vis callback json for rep: " + oneRepName + "\n")
20397 representationsJsonOut[oneRepName] = oneRep.GetRestartInfo()
20398
20399 jsonOut['RepresentationsRestartInfo'] = \
20400 representationsJsonOut
20401
20402 #go through plots over time and have each add it's state info to jsonOut
20403 plotsOverTimeJsonOut = {}
20404 for onePlotOtName, onePlotOt in \
20405 gPipeAndViewsState.mPlotOverTimeBlocks.items():
20406 if PhactoriDbg():
20407 myDebugPrint3("making end vis callback json for plot over time: " +
20408 onePlotOtName + "\n")
20409 plotsOverTimeJsonOut[onePlotOtName] = onePlotOt.GetRestartInfo()
20410
20411 jsonOut['PlotsOverTimeRestartInfo'] = plotsOverTimeJsonOut
20412
20413 #write info to file
20414
20415 import os
20416 restartInfoFilename = gPipeAndViewsState.mDefaultBasedirectory + \
20417 os.sep + gPipeAndViewsState.mBlockIdForRestart + ".phrs"
20418
20419 outStr = json.dumps(jsonOut, sort_keys=True,
20420 indent = 2, separators=(',', ': '))
20421 outFile = open(restartInfoFilename, 'w+b')
20422 outFile.write(outStr)
20423 outFile.close()
20424
20425 if PhactoriDbg():
20426 myDebugPrint3("SaveRestartInfoCallback returning\n")
20427
20428 def UpdateOneImagesetViewsWhichMayChangeWithData(ioImageset):
20429 if PhactoriDbg(100):
20430 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData entered\n", 100)
20431
20432 global gRenderingEnabled
20433 if gRenderingEnabled == False:
20434 if PhactoriDbg():
20435 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData returning with noop because rendering is disabled\n")
20436 return
20437
20438 theCamera = ioImageset.mCamera
20439
20440 #this is a bit hacky--we should probably update the para view sources when
20441 #we update operations, which we aren't doing separately yet
20442 #theParaViewSource = ioImageset.mOperation.GetPvFilter()
20443 theParaViewSource = ioImageset.mOperation.GetOutgoingPvGeometryFilter()
20444
20445 UpdatePipelineWithCurrentTimeArgument(theParaViewSource)
20446
20447 UpdateRepresentationColorBy(ioImageset)
20448
20449 if theCamera.MayChangeWithData() == False:
20450 if PhactoriDbg():
20451 myDebugPrint3(" camera: " + theCamera.mName + " imageset: " + ioImageset.mName + " is set to not change with data \n")
20452 return
20453
20454 #it no longer makes sense to loop through and set stuff up here, as
20455 #we will do it right before we call WriteImage
20456 #for xx in ioImageset.mParaViewRenderInfoCs:
20457 # if PhactoriDbg():
20458 # myDebugPrint3(" renderview.CameraPosition before: " + str(xx.mParaViewInfo.RenderView1.CameraPosition) + "\n")
20459 # lookDirectionToUse = xx.mLookDirection
20460 # if theCamera.mType == 'camera':
20461 # lookDirectionToUse = theCamera.mLookDirection
20462 # if PhactoriDbg():
20463 # myDebugPrint3(" camera: " + theCamera.mName + " imageset: " + ioImageset.mName + " look dir: " + str(lookDirectionToUse) + "\n")
20464 # SetParaViewRepresentationCameraParams(xx.mParaViewInfo.RenderView1, theCamera, lookDirectionToUse, ioImageset.mImageSettings, theParaViewSource)
20465 # if PhactoriDbg():
20466 # myDebugPrint3(" renderview.CameraPosition after : " + str(xx.mParaViewInfo.RenderView1.CameraPosition) + "\n")
20467
20468 if PhactoriDbg(100):
20469 myDebugPrint3("UpdateOneImagesetViewsWhichMayChangeWithData returning\n", 100)
20470 #SetActiveSource(savedActiveSource)
20471
20472 def UpdateAllOperationsWhichMayChangeWithData():
20473 if PhactoriDbg(100):
20474 myDebugPrint3("UpdateAllOperationsWhichMayChangeWithData entered\n", 100)
20475 global gPipeAndViewsState
20476 for oneOperationName, oneOperation in gPipeAndViewsState.mOperationBlocks.items():
20477 oneOperation.DoUpdateDueToChangeInData(gPipeAndViewsState)
20478 if PhactoriDbg(100):
20479 myDebugPrint3("UpdateAllOperationsWhichMayChangeWithData returning\n", 100)
20480
20481 def UpdateAllImagesetViewsWhichMayChangeWithData():
20482 if PhactoriDbg(100):
20483 myDebugPrint3("UpdateAllImagesetViewsWhichMayChangeWithData entered\n", 100)
20484 global gPipeAndViewsState
20485 for oneImagesetName, oneImageset in gPipeAndViewsState.mImagesetBlocks.items():
20486 if PhactoriDbg(100):
20487 myDebugPrint3("doing UpdateOneImagesetViewsWhichMayChangeWithData for imageset named:" + oneImagesetName + "\n", 100)
20488 if PhactoriDbg(100):
20489 myDebugPrint3(" doing oneImageset.HandleShowAxesWithEmptyDataParaViewIssue\n", 100)
20490 oneImageset.HandleShowAxesWithEmptyDataParaViewIssue()
20491 if PhactoriDbg(100):
20492 myDebugPrint3(" returned from oneImageset.HandleShowAxesWithEmptyDataParaViewIssue\n", 100)
20493 UpdateOneImagesetViewsWhichMayChangeWithData(oneImageset)
20494 if PhactoriDbg(100):
20495 myDebugPrint3("did UpdateOneImagesetViewsWhichMayChangeWithData for imageset named:" + oneImagesetName + "\n", 100)
20496 if PhactoriDbg(100):
20497 myDebugPrint3("UpdateAllImagesetViewsWhichMayChangeWithData returning\n", 100)
20498
20499 def HandleOperationShortcuts2(inBlockName, inJson, ioOperationBlocks, inCount):
20500 if PhactoriDbg(100):
20501 myDebugPrint3('HandleOperationShortcuts entered2\n', 100)
20502
20503 lastShortcutOperationName = None
20504
20505 opSuffix = str(inCount)
20506
20507 if "threshold" in inJson:
20508 stuff = inJson["threshold"]
20509 if len(stuff) != 4:
20510 errStr = 'HandleOperationShortcuts2 threshold shortcut bad stuff, not 4 items\n'
20511 if PhactoriDbg():
20512 myDebugPrint3(errStr)
20513 raise Exception(errStr)
20514 #stuff should have 4 items
20515 #[scalar|vector magnitude|vector component|tensor
20516 #component, component<variable name>, namekeep between|keep above|keep
20517 #below, [<val1>, <val2>]]
20518 newOperationJson = {}
20519 newOperationJson["type"] = "threshold"
20520 varkey = "variable " + stuff[0]
20521 newOperationJson[varkey] = stuff[1]
20522 thresholdValues = stuff[3]
20523 if stuff[2] == "keep between":
20524 newOperationJson["keep between"] = thresholdValues
20525 elif stuff[2] == "keep below":
20526 newOperationJson["keep below"] = thresholdValues[0]
20527 elif stuff[2] == "keep above":
20528 newOperationJson["keep above"] = thresholdValues[0]
20529 else:
20530 errStr = 'HandleOperationShortcuts2 bad stuff[2], not keep above|below|between\n'
20531 if PhactoriDbg():
20532 myDebugPrint3(errStr)
20533 raise Exception(errStr)
20534
20535 if PhactoriDbg():
20536 myDebugPrint3('got threshold operation shortcut ' + str(newOperationJson) + '\n')
20537 if lastShortcutOperationName != None:
20538 newOperationJson["input"] = lastShortcutOperationName
20539 lastShortcutOperationName = "thresholdshortcutoperation" + opSuffix
20540 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
20541
20542
20543 if "boxclip" in inJson:
20544 stuff = inJson["boxclip"]
20545 if len(stuff) != 3:
20546 errStr = 'HandleOperationShortcuts2 boxclip shortcut bad stuff, not 3 items\n'
20547 if PhactoriDbg():
20548 myDebugPrint3(errStr)
20549 raise Exception(errStr)
20550 center = stuff[0]
20551 extents = stuff[1]
20552 insideOrOutside = stuff[2]
20553
20554 newOperationJson = {}
20555 newOperationJson["type"] = "boxclip"
20556 newOperationJson["center at absolute point"] = center
20557 newOperationJson["absolute extents"] = extents
20558 if insideOrOutside == "keep inside box":
20559 newOperationJson["keep inside box"] = True
20560 elif insideOrOutside == "keep outside box":
20561 newOperationJson["keep inside box"] = False
20562 else:
20563 newOperationJson["keep inside box"] = True
20564
20565 if PhactoriDbg():
20566 myDebugPrint3('got boxclip operation shortcut ' + str(newOperationJson) + '\n')
20567 if lastShortcutOperationName != None:
20568 newOperationJson["input"] = lastShortcutOperationName
20569 lastShortcutOperationName = "boxclipshortcutoperation" + opSuffix
20570 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
20571
20572 if "clip" in inJson:
20573 stuff = inJson["clip"]
20574 if len(stuff) != 2:
20575 errStr = 'HandleOperationShortcuts2 clip shortcut bad stuff, not 2 items\n'
20576 if PhactoriDbg():
20577 myDebugPrint3(errStr)
20578 raise Exception(errStr)
20579 pointOnPlane = stuff[0]
20580 planeNormal = stuff[1]
20581 if PhactoriDbg():
20582 myDebugPrint3('got clip operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\n')
20583 newOperationJson = {"type":"clip", "absolute point on plane":pointOnPlane, "plane normal":planeNormal}
20584 if lastShortcutOperationName != None:
20585 newOperationJson["input"] = lastShortcutOperationName
20586 lastShortcutOperationName = "clipshortcutoperation" + opSuffix
20587 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
20588
20589 if "contour" in inJson:
20590 stuff = inJson["contour"]
20591 if len(stuff) != 4:
20592 errStr = 'HandleOperationShortcuts2 contour shortcut bad stuff, not 4 items\n'
20593 if PhactoriDbg():
20594 myDebugPrint3(errStr)
20595 raise Exception(errStr)
20596 variableInfo = stuff[0]
20597 variableName = stuff[1]
20598 valueListOrSequence = stuff[2]
20599 contourValues = stuff[3]
20600 newOperationJson = {}
20601 newOperationJson["type"] = "contour"
20602 varkey = "variable " + variableInfo
20603 newOperationJson[varkey] = variableName
20604 if (valueListOrSequence.lower()=="value list"):
20605 newOperationJson["contour value"] = contourValues
20606 elif (valueListOrSequence.lower()=="value sequence"):
20607 newOperationJson["contour value sequence"]=contourValues
20608 else:
20609 errStr = "error! contour shortcut did not contain 'value list' or 'value sequence' in\n HandleOperationShortcuts2\n"
20610 if PhactoriDbg():
20611 myDebugPrint3(errStr)
20612 raise Exception(errStr)
20613 if lastShortcutOperationName != None:
20614 newOperationJson["input"] = lastShortcutOperationName
20615 lastShortcutOperationName = "contourshortcutoperation" + opSuffix
20616 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
20617
20618 if "slice" in inJson:
20619 stuff = inJson["slice"]
20620 if len(stuff) != 2:
20621 errStr = 'HandleOperationShortcuts2 slice shortcut bad stuff, not 2 items\n'
20622 if PhactoriDbg():
20623 myDebugPrint3(errStr)
20624 raise Exception(errStr)
20625 pointOnPlane = stuff[0]
20626 planeNormal = stuff[1]
20627 if PhactoriDbg():
20628 myDebugPrint3('got slice operation shortcut ' + str(pointOnPlane) + str(planeNormal) + '\n')
20629 newOperationJson = {"type":"slice", "absolute point on plane":pointOnPlane, "plane normal":planeNormal}
20630 if lastShortcutOperationName != None:
20631 newOperationJson["input"] = lastShortcutOperationName
20632 lastShortcutOperationName = "sliceshortcutoperation" + opSuffix
20633 ioOperationBlocks[lastShortcutOperationName] = newOperationJson
20634
20635 if lastShortcutOperationName != None:
20636 inJson["operation"] = lastShortcutOperationName
20637 if PhactoriDbg(100):
20638 myDebugPrint3('HandleOperationShortcuts returning\n', 100)
20639
20640 #go through imageset json, and locate operation shortcuts. If found, create
20641 #json defintion of operations and add them to the structure for later
20642 #creation, and add reference to the new operations in the imageblock json
20643 def HandleOperationShortcuts(ioImagesetBlocks, ioOperationBlocks):
20644 if PhactoriDbg(100):
20645 myDebugPrint3('HandleOperationShortcuts entered\n', 100)
20646 count = 0
20647 for blockName, blockParamsJson in ioImagesetBlocks.items():
20648 count = count + 1
20649 HandleOperationShortcuts2(blockName, blockParamsJson, ioOperationBlocks, count)
20650 if PhactoriDbg(100):
20651 myDebugPrint3('HandleOperationShortcuts returning\n', 100)
20652 return count
20653
20654 def ConstructAndAddPlotsOverTimeJson(outPlotOverTimeJsonBlocks, inJsonToCopy,
20655 inYAxisVariableName, inNumComponents):
20656 "helper function for TestForAndConstructAllPlotsOverTime, creates a\n PlotOverTime json block, not for external use"
20657
20658 global gPipeAndViewsState
20659 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
20660 imageSetCount = gPipeAndViewsState.mImageSetCounter
20661
20662 if 'plot basename' in inJsonToCopy:
20663 extraNameString = inJsonToCopy['plot basename']
20664 else:
20665 extraNameString = ''
20666 if inNumComponents != 3:
20667 newPlotOverTimeJson = inJsonToCopy.copy()
20668 newPlotOverTimeJson['all variables'] = False
20669 plotName = extraNameString + inYAxisVariableName + ".b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
20670 newPlotOverTimeJson['plot basename'] = plotName
20671 newPlotOverTimeJson['variable scalar'] = inYAxisVariableName
20672 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
20673 if PhactoriDbg():
20674 myDebugPrint3('added block named ' + plotName + ': ' + \
20675 str(newPlotOverTimeJson) + '\n')
20676 else:
20677 newPlotOverTimeJson = inJsonToCopy.copy()
20678 newPlotOverTimeJson['all variables'] = False
20679 plotName = extraNameString + inYAxisVariableName + "x.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
20680 newPlotOverTimeJson['plot basename'] = plotName
20681 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'x'
20682 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
20683 if PhactoriDbg():
20684 myDebugPrint3('added block named ' + plotName + ': ' + \
20685 str(newPlotOverTimeJson) + '\n')
20686 newPlotOverTimeJson = inJsonToCopy.copy()
20687 newPlotOverTimeJson['all variables'] = False
20688 plotName = extraNameString + inYAxisVariableName + "y.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
20689 newPlotOverTimeJson['plot basename'] = plotName
20690 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'y'
20691 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
20692 if PhactoriDbg():
20693 myDebugPrint3('added block named ' + plotName + ': ' + \
20694 str(newPlotOverTimeJson) + '\n')
20695 newPlotOverTimeJson = inJsonToCopy.copy()
20696 newPlotOverTimeJson['all variables'] = False
20697 plotName = extraNameString + inYAxisVariableName + "z.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
20698 newPlotOverTimeJson['plot basename'] = plotName
20699 newPlotOverTimeJson['variable vector component'] = inYAxisVariableName + 'z'
20700 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
20701 if PhactoriDbg():
20702 myDebugPrint3('added block named ' + plotName + ': ' + \
20703 str(newPlotOverTimeJson) + '\n')
20704 newPlotOverTimeJson = inJsonToCopy.copy()
20705 newPlotOverTimeJson['all variables'] = False
20706 plotName = extraNameString + inYAxisVariableName + "mag.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".plot."
20707 newPlotOverTimeJson['plot basename'] = plotName
20708 lenToGrab = len(inYAxisVariableName) - len(GetSeparatorString())
20709 magVarName = inYAxisVariableName[0:lenToGrab]
20710 newPlotOverTimeJson['variable vector magnitude'] = magVarName
20711 outPlotOverTimeJsonBlocks[plotName] = newPlotOverTimeJson
20712 if PhactoriDbg():
20713 myDebugPrint3('added block named ' + plotName + ': ' + \
20714 str(newPlotOverTimeJson) + '\n')
20715
20716
20717 def ConstructAndAddScatterPlotsJson(outScatterPlotJsonBlocks, inJsonToCopy,
20718 inYAxisVariableName, inNumComponents, inXAxisVariableName):
20719 "helper function for TestForAndConstructAllScatterPlots, creates a\n scatterplot json block, not for external use"
20720
20721 global gPipeAndViewsState
20722 blockCountIdStr = GetCurrentOutputResultsBlockCountId()
20723 imageSetCount = gPipeAndViewsState.mImageSetCounter
20724
20725 if 'plot basename' in inJsonToCopy:
20726 extraNameString = inJsonToCopy['plot basename']
20727 else:
20728 extraNameString = ''
20729 if inNumComponents != 3:
20730 newScatterPlotJson = inJsonToCopy.copy()
20731 newScatterPlotJson['all variables'] = False
20732 plotName = extraNameString + inYAxisVariableName + ".b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
20733 newScatterPlotJson['plot basename'] = plotName
20734 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
20735 newScatterPlotJson['y axis variable scalar'] = inYAxisVariableName
20736 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
20737 if PhactoriDbg():
20738 myDebugPrint3('added block named ' + plotName + ': ' + \
20739 str(newScatterPlotJson) + '\n')
20740 else:
20741 newScatterPlotJson = inJsonToCopy.copy()
20742 newScatterPlotJson['all variables'] = False
20743 plotName = extraNameString + inYAxisVariableName + "x.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
20744 newScatterPlotJson['plot basename'] = plotName
20745 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
20746 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'x'
20747 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
20748 if PhactoriDbg():
20749 myDebugPrint3('added block named ' + plotName + ': ' + \
20750 str(newScatterPlotJson) + '\n')
20751 newScatterPlotJson = inJsonToCopy.copy()
20752 newScatterPlotJson['all variables'] = False
20753 plotName = extraNameString + inYAxisVariableName + "y.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
20754 newScatterPlotJson['plot basename'] = plotName
20755 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
20756 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'y'
20757 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
20758 if PhactoriDbg():
20759 myDebugPrint3('added block named ' + plotName + ': ' + \
20760 str(newScatterPlotJson) + '\n')
20761 newScatterPlotJson = inJsonToCopy.copy()
20762 newScatterPlotJson['all variables'] = False
20763 plotName = extraNameString + inYAxisVariableName + "z.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
20764 newScatterPlotJson['plot basename'] = plotName
20765 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
20766 newScatterPlotJson['y axis variable vector component'] = inYAxisVariableName + 'z'
20767 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
20768 if PhactoriDbg():
20769 myDebugPrint3('added block named ' + plotName + ': ' + \
20770 str(newScatterPlotJson) + '\n')
20771 newScatterPlotJson = inJsonToCopy.copy()
20772 newScatterPlotJson['all variables'] = False
20773 plotName = extraNameString + inYAxisVariableName + "mag.b-" + blockCountIdStr + ".is-" + str(imageSetCount) + ".sctr."
20774 newScatterPlotJson['plot basename'] = plotName
20775 newScatterPlotJson['x axis variable scalar'] = inXAxisVariableName
20776 lenToGrab = len(inYAxisVariableName) - len(GetSeparatorString())
20777 magVarName = inYAxisVariableName[0:lenToGrab]
20778 newScatterPlotJson['y axis variable vector magnitude'] = magVarName
20779 outScatterPlotJsonBlocks[plotName] = newScatterPlotJson
20780 if PhactoriDbg():
20781 myDebugPrint3('added block named ' + plotName + ': ' + \
20782 str(newScatterPlotJson) + '\n')
20783
20784 def TestForAndConstructAllPlotsOverTime(ioPlotOverTimeBlocksJson):
20785 "tests to see if a scatterplot block contains 'all variables': true and,\n if so, construct a scatterplot block for each variable"
20786 if PhactoriDbg(100):
20787 myDebugPrint3('TestForAndConstructAllPlotsOverTime entered\n', 100)
20788 potBlocks = ioPlotOverTimeBlocksJson
20789 blocksToPop = []
20790 constructAllVariablesFlag = False
20791 for blockName, blockParamsJson in potBlocks.items():
20792 if PhactoriDbg():
20793 myDebugPrint3("testing block named " + blockName + " for all variables\n")
20794 if PhactoriDbg():
20795 myDebugPrint3(" json is: " + str(blockParamsJson) + "\n")
20796 testVal = getParameterFromBlock(blockParamsJson, "all variables", False)
20797 if testVal == True:
20798 constructAllVariablesFlag = True
20799 blockToPop = blockName
20800 blockToCopy = blockParamsJson
20801 #there should be only one like this
20802 break
20803
20804 if constructAllVariablesFlag == False:
20805 #don't construct all variables
20806 if PhactoriDbg(100):
20807 myDebugPrint3('TestForAndConstructAllPlotsOverTime returning, no all variables\n', 100)
20808 return
20809
20810 global gPipeAndViewsState
20811 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
20812 pointDataInfo = paraviewSource.GetPointDataInformation()
20813 cellDataInfo = paraviewSource.GetCellDataInformation()
20814 fieldDataInfo = paraviewSource.GetFieldDataInformation()
20815
20816 numPointArrays = pointDataInfo.GetNumberOfArrays()
20817 for ii in range(numPointArrays):
20818 pointArray = pointDataInfo.GetArray(ii)
20819 pointArrayName = pointArray.GetName()
20820 if pointArrayName != "GlobalNodeId":
20821 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
20822 pointArrayName, pointArray.GetNumberOfComponents())
20823 numCellArrays = cellDataInfo.GetNumberOfArrays()
20824 for ii in range(numCellArrays):
20825 cellArray = cellDataInfo.GetArray(ii)
20826 cellArrayName = cellArray.GetName()
20827 if cellArrayName != "GlobalElementId":
20828 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
20829 cellArray.GetName(), cellArray.GetNumberOfComponents())
20830 numFieldArrays = fieldDataInfo.GetNumberOfArrays()
20831 for ii in range(numFieldArrays):
20832 fieldArray = fieldDataInfo.GetArray(ii)
20833 fieldArrayName = fieldArray.GetName()
20834 ConstructAndAddPlotsOverTimeJson(potBlocks, blockToCopy,
20835 fieldArray.GetName(), fieldArray.GetNumberOfComponents())
20836
20837 gPipeAndViewsState.mImageSetCounter += 1
20838
20839 potBlocks.pop(blockToPop, None)
20840
20841 if PhactoriDbg(100):
20842 myDebugPrint3('TestForAndConstructAllPlotsOverTime returning\n', 100)
20843
20844
20845 def TestForAndConstructAllScatterPlots(ioScatterPlotBlocksJson):
20846 "tests to see if a scatterplot block contains 'all variables': true and,\n if so, construct a scatterplot block for each variable"
20847 if PhactoriDbg(100):
20848 myDebugPrint3('TestForAndConstructAllScatterPlots entered\n', 100)
20849 spBlocks = ioScatterPlotBlocksJson
20850 blocksToPop = []
20851 constructAllVariablesFlag = False
20852 for blockName, blockParamsJson in spBlocks.items():
20853 if PhactoriDbg():
20854 myDebugPrint3("testing block named " + blockName + " for all variables\n")
20855 if PhactoriDbg():
20856 myDebugPrint3(" json is: " + str(blockParamsJson) + "\n")
20857 testVal = getParameterFromBlock(blockParamsJson, "all variables", False)
20858 if testVal == True:
20859 constructAllVariablesFlag = True
20860 blockToPop = blockName
20861 blockToCopy = blockParamsJson
20862 #there should be only one like this
20863 break
20864
20865 if constructAllVariablesFlag == False:
20866 #don't construct all variables
20867 if PhactoriDbg(100):
20868 myDebugPrint3('TestForAndConstructAllScatterPlots returning, no all variables\n', 100)
20869 return
20870
20871 global gPipeAndViewsState
20872 paraviewSource = gPipeAndViewsState.mIncomingDefaultOperation.GetPvFilter()
20873 pointDataInfo = paraviewSource.GetPointDataInformation()
20874 cellDataInfo = paraviewSource.GetCellDataInformation()
20875
20876 numPointArrays = pointDataInfo.GetNumberOfArrays()
20877 for ii in range(numPointArrays):
20878 pointArray = pointDataInfo.GetArray(ii)
20879 pointArrayName = pointArray.GetName()
20880 if pointArrayName != "GlobalNodeId":
20881 ConstructAndAddScatterPlotsJson(spBlocks, blockToCopy,
20882 pointArrayName, pointArray.GetNumberOfComponents(),
20883 "GlobalNodeId")
20884 numCellArrays = cellDataInfo.GetNumberOfArrays()
20885 for ii in range(numCellArrays):
20886 cellArray = cellDataInfo.GetArray(ii)
20887 cellArrayName = cellArray.GetName()
20888 if cellArrayName != "GlobalElementId":
20889 ConstructAndAddScatterPlotsJson(spBlocks, blockToCopy,
20890 cellArray.GetName(), pointArray.GetNumberOfComponents(),
20891 "GlobalElementId")
20892
20893 gPipeAndViewsState.mImageSetCounter += 1
20894
20895 spBlocks.pop(blockToPop, None)
20896
20897 if PhactoriDbg(100):
20898 myDebugPrint3('TestForAndConstructAllScatterPlots returning\n', 100)
20899
20900 def UpdatePipeAndViewsStateFromUserA(inPipeAndViewsState, inFileName):
20901 "given a PhactoriPipeAndViewsState instance which has been previously\n parsed, paraview items created, etc. (and presumably used to create\n rendered images at least once), read in the json state from the\n specified file, and update the inPipeAndViewsState accordingly.\n Only do the update if the PhactoriUpdateTrigger.txt file has a new\n value since the last check. Only read the file on processor zero,\n and use mpi to share the update with all other processors."
20902 if PhactoriDbg():
20903 myDebugPrint3("UpdatePipeAndViewsStateFromUserA entered\n")
20904 if SmartGetLocalProcessId() != 0:
20905 if PhactoriDbg():
20906 myDebugPrint3("UpdatePipeAndViewsStateFromUserA returning, not process 0\n")
20907 return
20908 try:
20909 inFile = open(inFileName, 'rb')
20910 userUpdateJson = json.load(inFile)
20911 inFile.close()
20912 userUpdateJson = convertJsonUnicodeToStrings(userUpdateJson)
20913
20914 if 'representation blocks' in userUpdateJson:
20915 representationBlocks = userUpdateJson['representation blocks']
20916 #could add logic to detect no change
20917 for repName, repJson in representationBlocks.items():
20918 onePhactoriRep = inPipeAndViewsState.mRepresentationBlocks[repName]
20919 if PhactoriDbg():
20920 myDebugPrint3("representation name: " + str(repName) + \
20921 "\nrepresentation json: " + str(repJson) + "\n")
20922 if onePhactoriRep != None:
20923 ParseOneRepresentationBlockC(onePhactoriRep, repJson,
20924 inPipeAndViewsState)
20925 if PhactoriDbg():
20926 myDebugPrint3("new color by variable: " +
20927 onePhactoriRep.mColorVariableInfo.SelfToStr() + "\n")
20928
20929 if 'camera blocks' in userUpdateJson:
20930 cameraBlocks = userUpdateJson['camera blocks']
20931 for cameraName, cameraJson in cameraBlocks.items():
20932 onePhactoriCamera = inPipeAndViewsState.mCameraBlocks[cameraName]
20933 if PhactoriDbg():
20934 myDebugPrint3("camera name: " + str(cameraName) + \
20935 "\ncamera json: " + str(cameraJson) + "\n")
20936 if onePhactoriCamera != None:
20937 if PhactoriDbg():
20938 myDebugPrint3("updating camera named: " + str(cameraName) + "\n")
20939 ParseOneCameraBlockC(onePhactoriCamera, cameraJson,
20940 inPipeAndViewsState)
20941 if PhactoriDbg():
20942 myDebugPrint3("new look direction: " + \
20943 str(onePhactoriCamera.mLookDirection) + "\n")
20944
20945 except:
20946 if PhactoriDbg():
20947 myDebugPrint3("error trying to get and use json from file\n")
20948 if PhactoriDbg():
20949 myDebugPrint3("UpdatePipeAndViewsStateFromUserA returning\n")
20950
20951 def SaveJsonSettingsToFile(inPipeAndViewsState, inFileName):
20952 "given a PhactoriPipeAndViewsState instance, dump the json that was\n used to construct it (usually called after default items have been\n added)"
20953 if PhactoriDbg():
20954 myDebugPrint3("SaveJsonSettingsToFile entered\n")
20955 if SmartGetLocalProcessId() != 0:
20956 if PhactoriDbg():
20957 myDebugPrint3("SaveJsonSettingsToFile returning, not process 0\n")
20958 return
20959 try:
20960 outStr = json.dumps(inPipeAndViewsState.mJsonDescription, sort_keys=True,
20961 indent = 2, separators=(',', ': '))
20962 outFile = open(inFileName, 'w+b')
20963 outFile.write(outStr)
20964 outFile.close()
20965 outFile = open('PhactoriInteractionTrigger.txt', 'w+b')
20966 outStr = json.dumps({'InteractionTriggerCounter': 0,
20967 'InteractionState':'OncePerCallbackFromSimulation'})
20968 outFile.write(outStr)
20969 outFile.close()
20970 except:
20971 if PhactoriDbg():
20972 myDebugPrint3("error trying to create or write file or make json string\n")
20973
20974 if PhactoriDbg():
20975 myDebugPrint3("SaveJsonSettingsToFile returning\n")
20976
20977 def PreprocessExperimentalTextAnnotationBlock(
20978 inViewMapC, inExpBlkname, inExpBlk):
20979
20980 substringToSubstituteForSpace = None
20981 if 'substringtosubstituteforspace' in inExpBlk:
20982 substringToSubstituteForSpace = \
20983 str(inExpBlk['substringtosubstituteforspace'])
20984 if PhactoriDbg():
20985 myDebugPrint3("substringtosubstituteforspace: ->" + \
20986 substringToSubstituteForSpace + "<-\n")
20987
20988 if 'line1' not in inExpBlk:
20989 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
20990 "textannotation type block must have 'line1' entry")
20991
20992 myNewTxtAntnBlk = {}
20993
20994 for lineIndex in range(1, 10):
20995 oneLineString = ""
20996 lineKey = "line" + str(lineIndex)
20997 if lineKey not in inExpBlk:
20998 break
20999 oneLineString = str(inExpBlk[lineKey])
21000 if substringToSubstituteForSpace != None:
21001 oneLineString = oneLineString.replace(
21002 substringToSubstituteForSpace, " ")
21003 if PhactoriDbg():
21004 myDebugPrint3("line after sub: ->" + oneLineString + "\n")
21005 myNewTxtAntnBlk[lineKey] = oneLineString
21006
21007 if 'windowlocation' in inExpBlk:
21008 myNewTxtAntnBlk['windowlocation'] = inExpBlk['windowlocation']
21009
21010 if ('positionx' in inExpBlk) or ('positiony' in inExpBlk):
21011 if 'positiony' not in inExpBlk:
21012 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
21013 "if you have 'positionx' you need 'positiony'\n")
21014 if 'positionx' not in inExpBlk:
21015 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
21016 "if you have 'positiony' you need 'positionx'\n")
21017 posx = float(inExpBlk['positionx'])
21018 posy = float(inExpBlk['positiony'])
21019 myNewTxtAntnBlk['windowlocation'] = 'AnyLocation'
21020 myNewTxtAntnBlk['position'] = [posx, posy]
21021
21022 if 'color' in inExpBlk:
21023 colorRgb = inExpBlk['color']
21024 myNewTxtAntnBlk['color'] = \
21025 [float(colorRgb[0]), float(colorRgb[1]), float(colorRgb[2])]
21026
21027 if 'opacity' in inExpBlk:
21028 myNewTxtAntnBlk['opacity'] = float(inExpBlk['opacity'])
21029
21030 if 'boldflag' in inExpBlk:
21031 myNewTxtAntnBlk['boldflag'] = int(inExpBlk['boldflag'])
21032 if 'italicflag' in inExpBlk:
21033 myNewTxtAntnBlk['italicflag'] = int(inExpBlk['italicflag'])
21034 if 'shadowflag' in inExpBlk:
21035 myNewTxtAntnBlk['shadowflag'] = int(inExpBlk['shadowflag'])
21036
21037 if 'fontsize' in inExpBlk:
21038 myNewTxtAntnBlk['fontsize'] = int(inExpBlk['fontsize'])
21039 if 'fontfamily' in inExpBlk:
21040 myNewTxtAntnBlk['fontfamily'] = inExpBlk['fontfamily']
21041
21042 if 'text annotation blocks' not in inViewMapC:
21043 inViewMapC['text annotation blocks'] = {}
21044 inViewMapC['text annotation blocks'][inExpBlkname] = myNewTxtAntnBlk
21045
21046 if 'show_in_imageset' in inExpBlk:
21047 targetImageset = inExpBlk['show_in_imageset']
21048 imagesets = inViewMapC['imageset blocks']
21049 if targetImageset in imagesets:
21050 theImageset = imagesets[targetImageset]
21051 if 'text annotations' not in theImageset:
21052 theImageset['text annotations'] = []
21053 textAnnotationList = theImageset['text annotations']
21054 textAnnotationList.append(inExpBlkname)
21055 else:
21056 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
21057 "textannotation target imageset is not in imageset blocks")
21058 else:
21059 myDebugPrint3AndException("PreprocessOneExperimentalBlock:\n" \
21060 "textannotation type block must have 'show_in_imageset' entry")
21061
21062
21063 def PreprocessExperimentalAddOpacityToRepBlock(
21064 inViewMapC, inExpBlkname, inExpBlk):
21065
21066 if 'representation blocks' not in inViewMapC:
21067 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
21068 "no 'representation blocks'\n")
21069
21070 repNameToAddTo = inExpBlk["target_representation"]
21071 if repNameToAddTo == None:
21072 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
21073 + str(inExpBlkname) + " missing 'target_representation'\n")
21074
21075 representationBlocks = inViewMapC["representation blocks"]
21076 targetRep = representationBlocks[repNameToAddTo]
21077 if targetRep == None:
21078 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
21079 "no representation with name: " + str(repNameToAddTo) + "\n");
21080
21081 opacitySetting = inExpBlk["opacity"]
21082 if opacitySetting == None:
21083 myDebugPrint3AndException("PreprocessExperimentalAddOpacityToRepBlock:\n" \
21084 + str(inExpBlkname) + " missing 'opacity'\n")
21085
21086 targetRep["opacity"] = float(opacitySetting)
21087 if PhactoriDbg():
21088 myDebugPrint3("PreprocessExperimentalAddOpacityToRepBlock:\n" \
21089 "to representation: " + repNameToAddTo + "\n" \
21090 "added opacity: " + str(opacitySetting) + "\n")
21091
21092
21093 def PreprocessOneExperimentalBlock(inViewMapC, inExpBlkname, inExpBlk):
21094 "gives us entry point to take one experimental blocks and manipulate it\n to produce other kinds of blocks to enter into inViewMapC"
21095 expBlkType = inExpBlk["type"]
21096
21097 if expBlkType == "textannotation":
21098 PreprocessExperimentalTextAnnotationBlock(
21099 inViewMapC, inExpBlkname, inExpBlk)
21100
21101 if expBlkType == "addopacitysettingtorepresentation":
21102 PreprocessExperimentalAddOpacityToRepBlock(inViewMapC, inExpBlkname, inExpBlk)
21103
21104
21105 def PreprocessExperimentalBlocks(inViewMapC):
21106 "gives us entry point to take experimental blocks and manipulate them\n to produce other kinds of blocks to enter into inViewMapC"
21107
21108 if 'experimental blocks' not in inViewMapC:
21109 #no experimental blocks
21110 return
21111
21112 expBlkMap = inViewMapC['experimental blocks']
21113 for expBlkName, expBlk in expBlkMap.items():
21114 PreprocessOneExperimentalBlock(inViewMapC, expBlkName, expBlk)
21115
21116 if len(expBlkMap) > 0:
21117 if PhactoriDbg():
21118 myDebugPrint3(
21119 "altered inViewMapC after experimental block handling:\n" + \
21120 str(inViewMapC) + "\n")
21121
21122 #construct a set of views from the json-structure view/pipeline description
21123 #specified in the sierra catalyst wiki/documentation
21124 def CreateViewSetFromPhactoriViewMapC(inViewMapC):
21125 "Create data pipeline, cameras, representations, and views from data struct\n\n Given a dict which is a json format structure with syntax as discussed in\n the sierra catalyst paraview insitu wiki, create the corresponding data\n pipeline, representations, views, etc. The basic idea is that from the\n incoming datastructure, we will parse out 6 (currently) sets of blocks:\n operations, cameras, representations, imagesets, scatter plots, and plots\n over time. From these, we will construct ParaView/Catalyst data structures\n to do the data management and rendering. See the class\n PhactoriPipeAndViewsState and the lower level related classes for more\n explaination.\n "
21126
21127 if PhactoriDbg(100):
21128 myDebugPrint3('CreateViewSetFromPhactoriViewMapC entered\n', 100)
21129 if PhactoriDbg():
21130 myDebugPrint3(str(inViewMapC) + "\n")
21131 global gPipeAndViewsState
21132 gPipeAndViewsState.mJsonDescription = inViewMapC
21133
21134 #get pointers to the various block types (currently 6, camera,
21135 #representation, operation, imageset, plot over time, and scatter plot)
21136
21137 #check for 'experimental blocks' and handle them appropriately if they
21138 #are there (e.g. use them to create other blocks)
21139 PreprocessExperimentalBlocks(inViewMapC)
21140
21141 cameraBlocks = {}
21142 representationBlocks = {}
21143 imagesetBlocks = {}
21144 operationBlocks = {}
21145 scatterplotBlocks = {}
21146 timeplotBlocks = {}
21147 criteriaBlocks = {}
21148 markerBlocks = {}
21149 textannotationBlocks = {}
21150 if 'camera blocks' in inViewMapC:
21151 cameraBlocks = inViewMapC['camera blocks']
21152 if 'representation blocks' in inViewMapC:
21153 representationBlocks = inViewMapC['representation blocks']
21154 if 'imageset blocks' in inViewMapC:
21155 imagesetBlocks = inViewMapC['imageset blocks']
21156 if 'operation blocks' in inViewMapC:
21157 operationBlocks = inViewMapC['operation blocks']
21158 if 'scatter plot blocks' in inViewMapC:
21159 scatterplotBlocks = inViewMapC['scatter plot blocks']
21160 if 'plot over time blocks' in inViewMapC:
21161 timeplotBlocks = inViewMapC['plot over time blocks']
21162 if 'onoff criteria blocks' in inViewMapC:
21163 criteriaBlocks = inViewMapC['onoff criteria blocks']
21164 if 'visual marker blocks' in inViewMapC:
21165 markerBlocks = inViewMapC['visual marker blocks']
21166 if 'text annotation blocks' in inViewMapC:
21167 textannotationBlocks = inViewMapC['text annotation blocks']
21168 if PhactoriDbg():
21169 myDebugPrint3(" cameraBlocks:\n")
21170 myDebugPrint3(" " + str(cameraBlocks) + "\n")
21171 myDebugPrint3(" representationBlocks:\n")
21172 myDebugPrint3(" " + str(representationBlocks) + "\n")
21173 myDebugPrint3(" imagesetBlocks:\n")
21174 myDebugPrint3(" " + str(imagesetBlocks) + "\n")
21175 myDebugPrint3(" operationBlocks:\n")
21176 myDebugPrint3(" " + str(operationBlocks) + "\n")
21177 myDebugPrint3(" scatterplotBlocks:\n")
21178 myDebugPrint3(" " + str(scatterplotBlocks) + "\n")
21179 myDebugPrint3(" timeplotBlocks:\n")
21180 myDebugPrint3(" " + str(timeplotBlocks) + "\n")
21181 myDebugPrint3(" onoff criteria blocks:\n")
21182 myDebugPrint3(" " + str(criteriaBlocks) + "\n")
21183 myDebugPrint3(" visual marker blocks:\n")
21184 myDebugPrint3(" " + str(markerBlocks) + "\n")
21185 myDebugPrint3(" text annotation blocks:\n")
21186 myDebugPrint3(" " + str(textannotationBlocks) + "\n")
21187
21188 #go through imageset json, and locate operation shortcuts. If found, create
21189 #json defintion of operations and add them to the structure for later
21190 #creation, and add reference to the new operations in the imageblock json
21191 HandleOperationShortcuts(imagesetBlocks, operationBlocks)
21192
21193 #do pipeline stuff
21194 gPipeAndViewsState.mIncomingDefaultOperation.mParaViewFilter = GetActiveSource()
21195
21196 global gEnableTemporaryExtractBlockTest
21197 if gEnableTemporaryExtractBlockTest:
21198 #hack to test extract block filter
21199 if gExtractBlockAOperationName in operationBlocks:
21200 global gExtractBlockAList
21201 theBlock = operationBlocks[gExtractBlockAOperationName]
21202 theBlock['type'] = 'extractblock'
21203 theBlock['include blocks'] = gExtractBlockAList
21204 if gExtractBlockBOperationName in operationBlocks:
21205 global gExtractBlockBList
21206 theBlock = operationBlocks[gExtractBlockBOperationName]
21207 theBlock['type'] = 'extractblock'
21208 theBlock['include blocks'] = gExtractBlockBList
21209
21210 #to test imagesets with multiple operations visible
21211 if gEnableTemporaryMultiOpViewTest:
21212 if gMultiOpViewTestImagesetName in imagesetBlocks:
21213 theBlock = imagesetBlocks["multioptestimageset"]
21214 theBlock["operation2"] = gMultiOpViewTestOp2Name
21215 theBlock["representation2"] = gMultiOpViewTestRep2Name
21216
21217 global gEnableTemporaryOffAxisProjectionTest
21218 if gEnableTemporaryOffAxisProjectionTest:
21219 global gOaptCameraNameList
21220
21221 #go through cameras and set up stereo ones
21222 for oneOaptCameraName in gOaptCameraNameList:
21223 if oneOaptCameraName in cameraBlocks:
21224 global gOaptPhysicalSettingsForCamera
21225 physicalSettingsForCamera = \
21226 gOaptPhysicalSettingsForCamera[oneOaptCameraName]
21227 theBlock = cameraBlocks[oneOaptCameraName]
21228 theBlock['use off axis projection'] = True
21229 for key, value in physicalSettingsForCamera.items():
21230 theBlock[key] = value
21231 theBlock['which eye'] = 'left'
21232 #copy this camera to another to use for right eye
21233 rightCameraName = oneOaptCameraName + "Right"
21234 rightCameraBlock = {}
21235 for key, value in theBlock.items():
21236 rightCameraBlock[key] = value
21237 rightCameraBlock['which eye'] = 'right'
21238 cameraBlocks[rightCameraName] = rightCameraBlock
21239 if PhactoriDbg():
21240 myDebugPrint3("new camera block for right eye:\n"
21241 + str(rightCameraBlock) + "\n")
21242
21243 #go through imageset blocks and add extras for stereo
21244 blocksToReplicateForRightEye = []
21245 for imagesetName, oneImagesetBlock in imagesetBlocks.items():
21246 if 'camera' in oneImagesetBlock:
21247 if oneImagesetBlock['camera'] in gOaptCameraNameList:
21248 blocksToReplicateForRightEye.append(
21249 [imagesetName, oneImagesetBlock])
21250 if PhactoriDbg():
21251 myDebugPrint3("blocksToReplicateForRightEye:\n"
21252 + str(blocksToReplicateForRightEye) + "\n")
21253 for iterItem in blocksToReplicateForRightEye:
21254 oneImagesetName = iterItem[0]
21255 oneImagesetBlock = iterItem[1]
21256 newImagesetBlock = {}
21257 for key, value in oneImagesetBlock.items():
21258 newImagesetBlock[key] = value
21259 rightCameraName = oneImagesetBlock['camera'] + "Right"
21260 newImagesetBlock['camera'] = rightCameraName
21261 imagesetBaseName = str(oneImagesetBlock['image basename'])
21262 oneImagesetBlock['image basename'] = imagesetBaseName + "left."
21263 newImagesetBlock['image basename'] = imagesetBaseName + "right."
21264 if PhactoriDbg():
21265 myDebugPrint3("new imageset block for right eye:\n"
21266 + str(newImagesetBlock) + "\n")
21267 imagesetBlocks[oneImagesetName + "Right"] = newImagesetBlock
21268
21269 #swap out operations from input deck for testing operations which aren't
21270 #available through the input deck syntax yet
21271 global gEnableSubstituteOperationTesting
21272 if gEnableSubstituteOperationTesting:
21273 global gSubstituteOperationTestingList
21274 global gSubstituteOperationTestingMap
21275 for oneOpName in gSubstituteOperationTestingList:
21276 if oneOpName in operationBlocks:
21277 if PhactoriDbg():
21278 myDebugPrint3("substituting operation named: " + oneOpName + "\n")
21279 oneOpBlock = operationBlocks[oneOpName]
21280 subOpBlock = gSubstituteOperationTestingMap[oneOpName]
21281 if 'input' in oneOpBlock:
21282 subOpBlock['input'] = oneOpBlock['input']
21283 operationBlocks[oneOpName] = subOpBlock
21284
21285 #swap out imagesets from input deck for testing imagesets which aren't
21286 #available through the input deck syntax yet
21287 global gEnableSubstituteImagesetTesting
21288 if gEnableSubstituteImagesetTesting:
21289 global gSubstituteImagesetTestingList
21290 global gSubstituteImagesetTestingMap
21291 for oneIsName in gSubstituteImagesetTestingList:
21292 if oneIsName in imagesetBlocks:
21293 oneIsBlock = imagesetBlocks[oneIsName]
21294 subIsBlock = gSubstituteImagesetTestingMap[oneIsName]
21295 for key, value in subIsBlock.items():
21296 oneIsBlock[key] = value
21297
21298 MakeFiltersFromViewMapOperationsC(gPipeAndViewsState, operationBlocks)
21299 if PhactoriDbg():
21300 myDebugPrint3(' gPipeAndViewsState.mOperationBlocks: ' + \
21301 str(gPipeAndViewsState.mOperationBlocks) + '\n')
21302
21303 #parse scatter plot blocks
21304
21305 #special case; check for 'all variables' in a scatter plot and contruct all
21306 #plot json blocks if necessary
21307 TestForAndConstructAllScatterPlots(scatterplotBlocks)
21308
21309 #ParseScatterPlotBlocksC(gPipeAndViewsState, scatterplotBlocks)
21310 #ParseBlocksC(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,
21311 # PhactoriScatterPlotBlock, ParseOneScatterPlotBlockC,
21312 # gPipeAndViewsState)
21313 ParseBlocksC2(gPipeAndViewsState.mScatterPlotBlocks, scatterplotBlocks,
21314 PhactoriScatterPlotBlock, gPipeAndViewsState)
21315
21316 #special case; check for 'all variables' in a plot over time and contruct all
21317 #plot json blocks if necessary
21318 TestForAndConstructAllPlotsOverTime(timeplotBlocks)
21319
21320 #parse time plot blocks
21321 ParseBlocksC(gPipeAndViewsState.mPlotOverTimeBlocks, timeplotBlocks,
21322 PhactoriPlotOverTimeBlock, ParseOnePlotOverTimeBlockC,
21323 gPipeAndViewsState)
21324
21325 #create producers for plots
21326 CreateScatterPlotProducersC(gPipeAndViewsState)
21327 CreatePlotOverTimeProducersC(gPipeAndViewsState)
21328
21329 #parse camera blocks
21330 #ParseCameraBlocksC(gPipeAndViewsState, cameraBlocks)
21331 ParseBlocksC(gPipeAndViewsState.mCameraBlocks, cameraBlocks,
21332 PhactoriCameraBlock, ParseOneCameraBlockC,
21333 gPipeAndViewsState)
21334
21335 #parse representation blocks
21336 #ParseRepresentationBlocksC(gPipeAndViewsState, representationBlocks)
21337 ParseBlocksC(gPipeAndViewsState.mRepresentationBlocks, representationBlocks,
21338 PhactoriRepresentationBlock, ParseOneRepresentationBlockC,
21339 gPipeAndViewsState)
21340
21341 #parse imageset onoff criteria blocks
21342 ParseBlocksC(gPipeAndViewsState.mImagesetOnOffCriteriaBlocks, criteriaBlocks,
21343 PhactoriImagesetOnOffFilterCriteria, ParseOneCriteriaBlockC,
21344 gPipeAndViewsState)
21345
21346 #parse visual marker blocks
21347 numMarkerBlocks = ParseBlocksC(
21348 gPipeAndViewsState.mMarkerBlocks,
21349 markerBlocks, PhactoriMarkerBlock,
21350 ParseOneMarkerBlockC, gPipeAndViewsState)
21351
21352 #parse text annotation blocks
21353 numTextAnnotationBlocks = ParseBlocksC(
21354 gPipeAndViewsState.mTextAnnotationBlocks,
21355 textannotationBlocks, PhactoriTextAnnotationBlock,
21356 ParseOneTextAnnotationBlockC, gPipeAndViewsState)
21357
21358 #construct marker paraview items (e.g. sphere or box source and the
21359 #corresponding representation
21360 #this is now done the first time the marker is made visible
21361 #for oneMarkerName, oneMarkerBlock in \
21362 # gPipeAndViewsState.mMarkerBlocks.iteritems():
21363 # oneMarkerBlock.CreateParaViewItems()
21364
21365 #parse imageset blocks
21366 #ParseImagesetBlocksC(gPipeAndViewsState, imagesetBlocks)
21367 numImagesetBlocks = ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,
21368 PhactoriImagesetBlock, ParseOneImagesetBlockC,
21369 gPipeAndViewsState)
21370
21371 #if there are no imageset blocks, create default and parse parameters in
21372 #wrappint imagesetBlock json as if they were from an imageset block
21373 if numImagesetBlocks == 0:
21374 if PhactoriDbg():
21375 myDebugPrint3(" no imagesets, creating a default imageset\n")
21376 imagesetBlocks['defaultimageset'] = {}
21377 ParseBlocksC(gPipeAndViewsState.mImagesetBlocks, imagesetBlocks,
21378 PhactoriImagesetBlock, ParseOneImagesetBlockC,
21379 gPipeAndViewsState)
21380
21381
21382 # if 'camera' not in ioImagesetBlockJson:
21383 # #we have to construct and use a default camera, including parsing
21384 # #commands in the imageset for the camera
21385 # myDebugPrint3(" ParseOneImagesetBlockC: for imageset " + \
21386 # ioImagesetBlock.mName + \
21387 # " there is no camera, so we must add and reference default\n")
21388 # if 'camera type' not in ioImagesetBlockJson:
21389 # ioImagesetBlockJson['camera type'] = 'multicamera8'
21390 # defaultCameraName = ioImagesetBlock.mName + '_default_camera'
21391 # defaultCameraBlockAndWrapper = {defaultCameraName: ioImagesetBlockJson}
21392 # ParseBlocksC(ioPipeAndViewsState.mCameraBlocks,
21393 # defaultCameraBlockAndWrapper,
21394 # PhactoriCameraBlock,
21395 # ParseOneCameraBlockC,
21396 # ioPipeAndViewsState)
21397 # ioImagesetBlockJson['camera'] = defaultCameraName
21398 # #myDebugPrint3( "done adding camera, here it is:\n")
21399 # #ioPipeAndViewsState.mCameraBlocks[defaultCameraName].PrintSelf()
21400
21401
21402 #loop through imageset blocks and create a viz for each--i.e. create a
21403 #ParaView/Catalyst Representation and View for each imageset block, and
21404 #have it render info from some stage of the above pipeline
21405
21406 for imagesetName, imagesetInstance in gPipeAndViewsState.mImagesetBlocks.items():
21407 CreateParaviewItemsForImagesetC(imagesetInstance)
21408
21409 CreateScatterPlotViewsC(gPipeAndViewsState)
21410 CreatePlotOverTimeViewsC(gPipeAndViewsState)
21411
21412 if gPipeAndViewsState.mInteractionEnabled == True:
21413 SaveJsonSettingsToFile(gPipeAndViewsState, "PhactoriJsonSettings.txt")
21414
21415 def CreateScatterPlotProducersC(inPipeAndViewsState):
21416 if PhactoriDbg(100):
21417 myDebugPrint3('CreateScatterPlotProducersC entered\n', 100)
21418 for oneScatterPlotName, oneScatterPlot in inPipeAndViewsState.mScatterPlotBlocks.items():
21419 #myDebugPrint3(' creating scatter plot producer nameed ' + oneScatterPlot.mName + '\n')
21420 CreateOneScatterPlotProducerC(oneScatterPlot)
21421 if PhactoriDbg(100):
21422 myDebugPrint3('CreateScatterPlotProducersC returning\n', 100)
21423
21424 def CreatePlotOverTimeProducersC(inPipeAndViewsState):
21425 if PhactoriDbg(100):
21426 myDebugPrint3('CreatePlotOverTimeProducersC entered\n', 100)
21427 for onePlotOverTimeName, onePlotOverTime in inPipeAndViewsState.mPlotOverTimeBlocks.items():
21428 #myDebugPrint3(' creating plot over time producer nameed ' + onePlotOverTime.mName + '\n')
21429 CreateOnePlotOverTimeProducerC(onePlotOverTime)
21430 if PhactoriDbg(100):
21431 myDebugPrint3('CreatePlotOverTimeProducersC returning\n', 100)
21432
21433 def CreateScatterPlotViewsC(inPipeAndViewsState):
21434
21435 if PhactoriDbg(100):
21436 myDebugPrint3('CreateScatterPlotViewsC entered\n', 100)
21437 #SetPlotView2StartColors(
21438 # inBackgroundColor = [1.0, 1.0, 1.0],
21439 # inEdgeColor = [0.0, 0.0, 0.5],
21440 # inCubeAxesColor = [0.2, 0.2, 0.2],
21441 # inDiffuseColor = [0.2, 0.2, 0.2],
21442 # inAmbientColor = [0.2, 0.2, 0.2],
21443 # inSelectionColor = [0.2, 0.2, 0.2],
21444 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
21445
21446 for oneScatterPlotName, oneScatterPlot in inPipeAndViewsState.mScatterPlotBlocks.items():
21447 #myDebugPrint3(' creating scatter plot view nameed ' + oneScatterPlot.mName + '\n')
21448 CreateOneScatterPlotViewC(oneScatterPlot)
21449 if PhactoriDbg(100):
21450 myDebugPrint3('CreateScatterPlotViewsC returning\n', 100)
21451
21452
21453 def CreatePlotOverTimeViewsC(inPipeAndViewsState):
21454
21455 if PhactoriDbg(100):
21456 myDebugPrint3('CreatePlotOverTimeViewsC entered\n', 100)
21457 #SetPlotView2StartColors(
21458 # inBackgroundColor = [1.0, 1.0, 1.0],
21459 # inEdgeColor = [0.0, 0.0, 0.5],
21460 # inCubeAxesColor = [0.2, 0.2, 0.2],
21461 # inDiffuseColor = [0.2, 0.2, 0.2],
21462 # inAmbientColor = [0.2, 0.2, 0.2],
21463 # inSelectionColor = [0.2, 0.2, 0.2],
21464 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
21465
21466 for onePlotOverTimeName, onePlotOverTime in inPipeAndViewsState.mPlotOverTimeBlocks.items():
21467 #myDebugPrint3(' creating scatter plot view nameed ' + onePlotOverTime.mName + '\n')
21468 CreateOnePlotOverTimeViewC(onePlotOverTime)
21469 if PhactoriDbg(100):
21470 myDebugPrint3('CreatePlotOverTimeViewsC returning\n', 100)
21471
21472
21473 def ColorByVariableComponentOrMagnitudeXX(inParaViewDataRepresentation,
21474 inPhactoriRepresentation,
21475 inVariableName, inComponentOrMagnitude, inWhichComponent,
21476 inVariableArrayType, inColorMapSettings):
21477 #myDebugPrint3("ColorByVariableComponentOrMagnitudeXX entered\n", 100)
21478 #myDebugPrint3(" inVariableName: " + inVariableName + "\n")
21479 #myDebugPrint3(" inComponentOrMagnitude: " + inComponentOrMagnitude + "\n")
21480 #myDebugPrint3(" inWhichComponent: " + str(inWhichComponent) + "\n")
21481 #myDebugPrint3(" inVariableArrayType: " + str(inVariableArrayType) + "\n")
21482
21483 if gParaViewCatalystVersionFlag >= 40300:
21484 #for paraview 4.3
21485 if inVariableArrayType == None:
21486 myDebugPrint3AndException(\
21487 "ColorByVariableComponentOrMagnitudeXX "
21488 "expecting inVariableArrayType\n")
21489 if PhactoriDbg():
21490 myDebugPrint3("using ColorBy() to set color var " + \
21491 inVariableName + " " + inVariableArrayType + " 1\n")
21492 myDebugPrint3("inComponentOrMagnitude: " + str(inComponentOrMagnitude) \
21493 + "\ninWhichComponent: " + str(inWhichComponent) + "\n")
21494 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
21495 SafeColorBy(inParaViewDataRepresentation,
21496 (inVariableArrayType, inVariableName))
21497 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
21498 #deal with vector mode, component index
21499 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
21500 if inComponentOrMagnitude == 'Magnitude':
21501 pv_4_3_LUT.VectorMode = 'Magnitude'
21502 else:
21503 pv_4_3_LUT.VectorMode = 'Component'
21504 pv_4_3_LUT.VectorComponent = inWhichComponent
21505 #need to deal with color table
21506 myRGBPoints, myColorSpace, myNanColor = \
21507 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
21508 -1.0, 1.0)
21509 pv_4_3_LUT.RGBPoints = myRGBPoints
21510 pv_4_3_LUT.ColorSpace = myColorSpace
21511 pv_4_3_LUT.NanColor = myNanColor
21512 return;
21513
21514 #after this the function is for paraview 4.1
21515
21516 if inVariableArrayType != None:
21517 inParaViewDataRepresentation.ColorAttributeType = inVariableArrayType
21518
21519 myRGBPoints, myColorSpace, myNanColor = \
21520 GetColorMapInfoFromColorLegendCollection(inColorMapSettings, -1.0, 1.0)
21521
21522 newLookupTable = None
21523 if inComponentOrMagnitude == 'Magnitude':
21524 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 )
21525 elif inComponentOrMagnitude == 'Component':
21526 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 )
21527 else:
21528 #bad name, should be 'Component' or 'Magnitude'
21529 return
21530
21531 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
21532 inParaViewDataRepresentation.LookupTable = newLookupTable
21533 try:
21534 inParaViewDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
21535 except:
21536 if PhactoriDbg():
21537 myDebugPrint3('no inParaViewDataRepresentation.ScalarOpacityFunction\n');
21538
21539 inParaViewDataRepresentation.ColorArrayName = inVariableName
21540
21541
21542 def ColorByVariableScalarXX(inParaViewDataRepresentation, inPhactoriRepresentation, inVariableName, inVariableArrayType, inColorMapSettings):
21543 "Set the scalar variable (by name) which will be used to color the data\n presentation."
21544 if gParaViewCatalystVersionFlag >= 40300:
21545 #for paraview 4.3
21546 if inVariableArrayType == None:
21547 myDebugPrint3AndException(\
21548 "ColorByVariableComponentOrMagnitudeXX "
21549 "expecting inVariableArrayType\n")
21550 if PhactoriDbg():
21551 myDebugPrint3("using ColorBy() to set color var " + \
21552 inVariableName + " " + inVariableArrayType + " 3\n")
21553 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
21554 SafeColorBy(inParaViewDataRepresentation,
21555 (inVariableArrayType, inVariableName))
21556 inParaViewDataRepresentation.RescaleTransferFunctionToDataRange(False)
21557 #need to deal with color table
21558 myRGBPoints, myColorSpace, myNanColor = \
21559 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
21560 -1.0, 1.0)
21561 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
21562 pv_4_3_LUT.RGBPoints = myRGBPoints
21563 pv_4_3_LUT.ColorSpace = myColorSpace
21564 pv_4_3_LUT.NanColor = myNanColor
21565 if inPhactoriRepresentation.InterpretValuesAsCategories:
21566 if PhactoriDbg():
21567 myDebugPrint3("variable name is ObjectId, trying to do categories\n")
21568 inPhactoriRepresentation.SetUpForInterpretValuesAsCateories(pv_4_3_LUT)
21569 pv_4_3_LUT.InterpretValuesAsCategories = 1
21570 pv_4_3_LUT.AnnotationsInitialized = 1
21571 pv_4_3_LUT.Annotations = inPhactoriRepresentation.Annotations
21572 pv_4_3_LUT.IndexedColors = inPhactoriRepresentation.IndexedColors
21573 pv_4_3_LUT.IndexedOpacities = inPhactoriRepresentation.IndexedOpacities
21574 else:
21575 pv_4_3_LUT.InterpretValuesAsCategories = 0
21576 return
21577
21578 #rest of function for paraview 4.1
21579
21580 inParaViewDataRepresentation.ColorArrayName = inVariableName
21581 if inVariableArrayType != None:
21582 inParaViewDataRepresentation.ColorAttributeType = inVariableArrayType
21583
21584 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
21585
21586 myRGBPoints, myColorSpace, myNanColor = \
21587 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
21588 0.0, 1647.1430997030882)
21589
21590 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 )
21591 if PhactoriDbg():
21592 myDebugPrint3("new lookup table (1):\n");
21593 if PhactoriDbg():
21594 myDebugPrint3(str(new_var_PVLookupTable) + "\n")
21595 if PhactoriDbg():
21596 myDebugPrint3("RGBPoints:\n");
21597 if PhactoriDbg():
21598 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints) + "\n")
21599
21600 if PhactoriDbg():
21601 myDebugPrint3(str(inParaViewDataRepresentation) + '\n')
21602 try:
21603 inParaViewDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
21604 except:
21605 if PhactoriDbg():
21606 myDebugPrint3('no inParaViewDataRepresentation.ScalarOpacityFunction\n');
21607 if PhactoriDbg():
21608 myDebugPrint3('new or reused lookup table: ' + str(new_var_PVLookupTable) + '\n')
21609 if PhactoriDbg():
21610 myDebugPrint3('prior inParaViewDataRepresentation.DataRepresentation.LookupTable: ' + str(inParaViewDataRepresentation.LookupTable) + '\n')
21611 inParaViewDataRepresentation.LookupTable = new_var_PVLookupTable
21612 if PhactoriDbg():
21613 myDebugPrint3(str(new_var_PVLookupTable))
21614 if PhactoriDbg():
21615 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints))
21616 if PhactoriDbg():
21617 myDebugPrint3(str(inParaViewDataRepresentation) + '\n')
21618
21619 global gNumCycleBlockColors
21620 global gCycleBlockColors
21621
21622 gNumCycleBlockColors = 12
21623 gCycleBlockColors = [[1.00, 0.00, 0.00],
21624 [1.00, 1.00, 0.00],
21625 [0.00, 1.00, 0.00],
21626 [0.00, 1.00, 1.00],
21627 [0.00, 0.00, 1.00],
21628 [1.00, 0.00, 1.00],
21629 [1.00, 0.50, 0.00],
21630 [0.50, 1.00, 0.00],
21631 [0.00, 1.00, 0.50],
21632 [0.00, 0.50, 1.00],
21633 [0.50, 0.00, 1.00],
21634 [1.00, 0.00, 0.50]]
21635
21636 def ColorByBlockOneBlock(inInputCsData, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag):
21637 #myDebugPrint3('ColorByBlockOneBlock entered\n', 100)
21638 ioBlockAndLeafBlockCounter[1] += 1
21639 #myDebugPrint3(' ioBlockAndLeafBlockCounter: ' + str(ioBlockAndLeafBlockCounter) + '\n')
21640 if inCountOnlyFlag == False:
21641 global gNumCycleBlockColors
21642 global gCycleBlockColors
21643 colorIndex = (ioBlockAndLeafBlockCounter[1] - 1) % gNumCycleBlockColors
21644 #myDebugPrint3(' colorIndex: ' + str(colorIndex) + ' color: ' + str(gCycleBlockColors[colorIndex]) + '\n')
21645 blockIndex = ioBlockAndLeafBlockCounter[0] - 1
21646 ioBlockColorData[blockIndex] = gCycleBlockColors[colorIndex]
21647
21648 #myDebugPrint3('ColorByBlockOneBlock returning\n', 100)
21649
21650 def ColorByBlockRecurse1(inInputCsData,
21651 ioBlockAndLeafBlockCounter,
21652 ioBlockColorData,
21653 inCountOnlyFlag = False,
21654 inMaximumCountFlag = False,
21655 inMaximumCount = 10000):
21656 #myDebugPrint3('ColorByBlockRecurse1 entered\n', 100)
21657
21658 ioBlockAndLeafBlockCounter[0] += 1
21659
21660 if inMaximumCountFlag:
21661 #myDebugPrint3(" inMaximumCountFlag true, inMaximumCount: " + str(inMaximumCount) + " block count: " + str(ioBlockAndLeafBlockCounter[0]) + "\n")
21662 if ioBlockAndLeafBlockCounter[0] >= inMaximumCount:
21663 #myDebugPrint3(" inMaximumCount hit, returning early\n", 100)
21664 return
21665
21666 icsdClassname = inInputCsData.GetClassName()
21667 #if PhactoriDbg(100):
21668 # myDebugPrint3("icsdClassname 2: " + str(icsdClassname) + "\n")
21669 if icsdClassname == "vtkMultiBlockDataSet" or \
21670 icsdClassname == "vtkExodusIIMultiBlockDataSet":
21671 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
21672 numBlocks = inInputCsData.GetNumberOfBlocks()
21673 for ii in range(0, numBlocks):
21674 oneBlock = inInputCsData.GetBlock(ii)
21675 if(oneBlock != None):
21676 ColorByBlockRecurse1(oneBlock, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag, inMaximumCountFlag, inMaximumCount)
21677 else:
21678 ioBlockAndLeafBlockCounter[0] += 1
21679 if inMaximumCountFlag:
21680 #myDebugPrint3(" inMaximumCountFlag (2) true, inMaximumCount: " + str(inMaximumCount) + " block count: " + str(ioBlockAndLeafBlockCounter[0]) + "\n")
21681 if ioBlockAndLeafBlockCounter[0] >= inMaximumCount:
21682 #myDebugPrint3(" inMaximumCount hit (2), returning early\n", 100)
21683 return
21684 else:
21685 ColorByBlockOneBlock(inInputCsData, ioBlockAndLeafBlockCounter, ioBlockColorData, inCountOnlyFlag)
21686
21687 #myDebugPrint3(' ioBlockAndLeafBlockCounter after this recursion: ' + str(ioBlockAndLeafBlockCounter) + '\n')
21688
21689 #myDebugPrint3('ColorByBlockRecurse1 returning\n', 100)
21690
21691 def ColorByBlock(inParaViewDataSource, inParaViewDataRepresentation,
21692 inBlockCountLimitOverride = False):
21693 if PhactoriDbg(100):
21694 myDebugPrint3('ColorByBlock entered\n', 100)
21695
21696 csdata = inParaViewDataSource.GetClientSideObject().GetOutputDataObject(0)
21697 blockAndLeafBlockCounter = [0,0]
21698
21699 #test for extreme case when there are too many blocks
21700 #tooManyBlocksToColor = 8
21701 tooManyBlocksToColor = 10000
21702 ColorByBlockRecurse1(csdata, blockAndLeafBlockCounter, None, True, True, tooManyBlocksToColor)
21703 if blockAndLeafBlockCounter[0] >= tooManyBlocksToColor:
21704 if inBlockCountLimitOverride:
21705 if PhactoriDbg():
21706 myDebugPrint3(' warning: color by blocks is being used with large number of blocks\n')
21707 else:
21708 if PhactoriDbg():
21709 myDebugPrint3(' too many blocks (>10000) for coloring: color data could cause issues\n')
21710 return
21711
21712 blockAndLeafBlockCounter = [0,0]
21713
21714 global gParaViewCatalystVersionFlag
21715 if gParaViewCatalystVersionFlag < 51000:
21716
21717 blockColorData = inParaViewDataRepresentation.BlockColor
21718 if PhactoriDbg(100):
21719 myDebugPrint3(' blockColorData is ' + str(blockColorData) + '\n', 100)
21720 if PhactoriDbg(100):
21721 myDebugPrint3(' blockColorData type is ' + str(type(blockColorData)) + '\n', 100)
21722
21723 ColorByBlockRecurse1(csdata, blockAndLeafBlockCounter, inParaViewDataRepresentation.BlockColor, False)
21724
21725 #inParaViewDataRepresentation.BlockColor = blockColorData
21726
21727 if PhactoriDbg(100):
21728 myDebugPrint3(' block color data: ' + str(inParaViewDataRepresentation.BlockColor) + '\n', 100)
21729 if PhactoriDbg(100):
21730 myDebugPrint3(' final count: ' + str(blockAndLeafBlockCounter) + '\n', 100)
21731
21732 if PhactoriDbg(100):
21733 myDebugPrint3('ColorByBlock returning\n', 100)
21734
21735
21736 def UseDataRangeForColorValues(inPvDataRepresentation, inRepresentation,
21737 inOperation):
21738
21739 if inRepresentation.mColorVariableInfo.mVariableIntendedForUseFlag == False:
21740 #the color by variable is not set, we do nothing
21741 return
21742
21743 if PhactoriDbg(100):
21744 myDebugPrint3("UseDataRangeForColorValues entered\n", 100)
21745
21746 rep = inPvDataRepresentation
21747
21748 localColorArrayName = inRepresentation.mColorVariableInfo.mVariableName
21749 if inRepresentation.mColorVariableInfo.mVariableType == 'node':
21750 pointsOrCellsType = gPointsString
21751 else:
21752 pointsOrCellsType = gCellsString
21753
21754 #if gParaViewCatalystVersionFlag <= 40100:
21755 # localColorArrayName = rep.ColorArrayName
21756 # pointsOrCellsType = rep.ColorAttributeType
21757 #else:
21758 # localColorArrayName = rep.ColorArrayName[1]
21759 # pointsOrCellsType = rep.ColorArrayName[0]
21760
21761 if PhactoriDbg():
21762 myDebugPrint3(' color variable is ' + localColorArrayName + '\n')
21763 myDebugPrint3(' color attribute type is ' + \
21764 pointsOrCellsType + '\n')
21765
21766 if PhactoriDbg():
21767 myDebugPrint3(" rep:" + str(rep) + "\n")
21768
21769 #if rep.ColorArrayName == '':
21770 # return
21771
21772 input = rep.Input
21773
21774 if PhactoriDbg():
21775 myDebugPrint3(" input:" + str(input) + "\n")
21776 UpdatePipelineWithCurrentTimeArgument(input)
21777
21778 #assume point info
21779 #datainformation = rep.Input.GetPointDataInformation()
21780
21781 if pointsOrCellsType == gPointsString:
21782 datainformation = input.GetPointDataInformation()
21783 elif pointsOrCellsType == gCellsString:
21784 datainformation = input.GetCellDataInformation()
21785 else:
21786 if PhactoriDbg():
21787 myDebugPrint3("something strange with color attribute type :" + \
21788 str(pointsOrCellsType) + "\n")
21789 return;
21790
21791 datarange = [sys.float_info.max, -sys.float_info.max]
21792 if gParaViewCatalystVersionFlag <= 40100:
21793 lut = rep.LookupTable
21794 else:
21795 lut = GetColorTransferFunction(rep.ColorArrayName[1])
21796
21797 if lut == None:
21798 #at this point in time, all processes should have a look up table, even
21799 #if they don't have associated data
21800 myDebugPrint3AndException(\
21801 "UseDataRangeForColorValues expecting LookupTable\n")
21802
21803 if inRepresentation.mColorVariableInfo.mVariableIsVectorComponent == True:
21804 lut.VectorMode = 'Component'
21805 index = inRepresentation.mColorVariableInfo.mVariableComponent
21806 lut.VectorComponent = index
21807 dataarray = datainformation.GetArray(localColorArrayName)
21808 if dataarray == None:
21809 #no data array, nothing to be done---screws up mpi?
21810 #return
21811 datarange = [sys.float_info.max, -sys.float_info.max]
21812 else:
21813 datarange = datainformation.GetArray(localColorArrayName).\
21814 GetRange(index)
21815 elif inRepresentation.mColorVariableInfo.\
21816 mVariableIsVectorMagnitude == True:
21817 lut.VectorMode = 'Magnitude'
21818 lut.VectorComponent = 0
21819 dataarray = datainformation.GetArray(localColorArrayName)
21820 if dataarray == None:
21821 #no data array, nothing to be done---screws up mpi?
21822 #return
21823 datarange = [sys.float_info.max, -sys.float_info.max]
21824 else:
21825 numComponents = dataarray.GetNumberOfComponents()
21826 if numComponents != 3:
21827 myDebugPrint3AndException(\
21828 "UseDataRangeForColorValues expecting 3 component item here\n")
21829 localMinMaxInfo = FindThisProcessorMinMaxForVar(inOperation,
21830 inRepresentation.mColorVariableInfo)
21831 if localMinMaxInfo[2] == False:
21832 datarange = [sys.float_info.max, -sys.float_info.max]
21833 else:
21834 datarange = [localMinMaxInfo[0], localMinMaxInfo[1]]
21835 else:
21836 #assume one component, scalar, assume one vector component and it's 0
21837 dataarray = datainformation.GetArray(localColorArrayName)
21838 if dataarray == None:
21839 #no data array, nothing to be done---screws up mpi?
21840 #return
21841 if PhactoriDbg():
21842 myDebugPrint3(\
21843 " no data array, using range "
21844 "[sys.float_info.max, -sys.float_info.max]\n")
21845 datarange = [sys.float_info.max, -sys.float_info.max]
21846 else:
21847 datarange = datainformation.GetArray(localColorArrayName).GetRange(0)
21848 if PhactoriDbg():
21849 myDebugPrint3("finding color legend datarange for " + str(localColorArrayName) + "\n")
21850 myDebugPrint3(' datarange: ' + str(datarange) + '\n')
21851
21852 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
21853 globalController = pm.GetGlobalController()
21854
21855 localarray = vtk.vtkDoubleArray()
21856 localarray.SetNumberOfTuples(2)
21857 # negate so that MPI_MAX gets min instead of doing a MPI_MIN and MPI_MAX
21858 localarray.SetValue(0, -datarange[0])
21859 localarray.SetValue(1, datarange[1])
21860
21861 globalarray = vtk.vtkDoubleArray()
21862 globalarray.SetNumberOfTuples(2)
21863 globalController.AllReduce(localarray, globalarray, 0)
21864 globalDatarange = [ \
21865 -globalarray.GetTuple1(0), globalarray.GetTuple1(1), \
21866 ]
21867 if PhactoriDbg():
21868 myDebugPrint3("local datarange: " + str(datarange) + \
21869 "\nglobal datarange: " + str(globalDatarange) + "\n")
21870
21871 minmaxTrk = inRepresentation.mColorRangeMinMaxTracker
21872 minmaxTrk.ResetThisCb()
21873
21874 if globalDatarange[0] >= globalDatarange[1]:
21875 #min was >= max, so we can't do a good color mapping; take steps
21876 #this means we really had no data; therefore set min and max to 0.0
21877 #and let this system handle the color mapping as if all data values
21878 #were 0.0
21879 globalDatarange[0] = 0.0
21880 globalDatarange[1] = 0.0
21881 if PhactoriDbg():
21882 myDebugPrint3("no valid data for variable; setting min/max to 0.0\n")
21883
21884 minmaxTrk.MinMaxTestAndSet(globalDatarange[0])
21885 minmaxTrk.MinMaxTestAndSet(globalDatarange[1])
21886 minmaxTrk.UpdateMinMaxToUse()
21887 #myDebugPrint3("representation color range tracking:\n")
21888 #myDebugPrint3(minmaxTrk.SelfToStr())
21889
21890 minToUse = minmaxTrk.GetMinToUse()
21891 maxToUse = minmaxTrk.GetMaxToUse()
21892
21893 if PhactoriDbg():
21894 myDebugPrint3("minmaxTrk min: " + str(minToUse) + " max: " + str(maxToUse) + "\n")
21895
21896 hadToAlterMinMaxDueToSmallRange = False
21897 if (maxToUse - minToUse) < 1.0e-20:
21898 hadToAlterMinMaxDueToSmallRange = True
21899 middle1 = 0.5 * (minToUse + maxToUse)
21900 minToUse = middle1 - 5.0e-21
21901 maxToUse = middle1 + 5.0e-21
21902 if PhactoriDbg(100):
21903 myDebugPrint3("had to change minToUse and maxToUse due to (maxToUse - minToUse) < 1.0e-20\n"
21904 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
21905 else:
21906 testMag1 = max(abs(maxToUse), abs(minToUse))
21907 if (maxToUse - minToUse) < testMag1*1.0e-6:
21908 hadToAlterMinMaxDueToSmallRange = True
21909 middle1 = 0.5 * (minToUse + maxToUse)
21910 delta2 = testMag1*5.0e-7
21911 minToUse = middle1 - delta2
21912 maxToUse = middle1 + delta2
21913 myDebugPrint3("had to change minToUse and maxToUse due to (maxToUse - minToUse) < testMag1\n"
21914 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
21915
21916 #if required, restrict color range to subset of otherwise calculated range
21917 if inRepresentation.mUseColorSubrange and (hadToAlterMinMaxDueToSmallRange == False):
21918 clrDelta = maxToUse - minToUse
21919 maxToUse = minToUse + inRepresentation.mColorSubrange[1] * clrDelta
21920 minToUse = minToUse + inRepresentation.mColorSubrange[0] * clrDelta
21921 myDebugPrint3("changed minToUse and maxToUse due to inRepresentation.mUseColorSubrange == True\n"
21922 "new minToUse: " + str(minToUse) + " new maxToUse: " + str(maxToUse) + "\n")
21923
21924 SetMinimumMaximumColorValues(inPvDataRepresentation,
21925 minToUse, maxToUse,
21926 inOperation, inRepresentation,
21927 localColorArrayName, pointsOrCellsType)
21928
21929 if PhactoriDbg(100):
21930 myDebugPrint3("UseDataRangeForColorValues returning\n", 100)
21931
21932 #def UpdateDataRangesForColorValues():
21933 # myDebugPrint3("UpdateDataRangesForColorValues entered\n", 100)
21934 # global PhactoriRenderViewInfoList
21935 # for ii in PhactoriRenderViewInfoList:
21936 # UseDataRangeForColorValues(ii)
21937 # myDebugPrint3("UpdateDataRangesForColorValues returning\n", 100)
21938
21939 def helpFindNewRgbPoint(inBaseRgbPts, inRatio):
21940 #print "inRatio: ", inRatio
21941 positionIndex = -2
21942
21943 if inBaseRgbPts[0] >= inRatio:
21944 positionIndex = 0
21945 else:
21946 positionIndex = -1
21947 for rIndex in range(4, len(inBaseRgbPts), 4):
21948 #print "rIndex: ", rIndex
21949 #print "positionIndex: ", positionIndex
21950 #print "val: ", inBaseRgbPts[rIndex]
21951 if inRatio <= inBaseRgbPts[rIndex]:
21952 positionIndex = rIndex - 4
21953 #print "stopping"
21954 break
21955 #bad case, ratio is off end
21956 if positionIndex == -1:
21957 #print "bad case"
21958 positionIndex = len(inBaseRgbPts) - 4
21959
21960 if PhactoriDbg(100):
21961 myDebugPrint3("position index: " + str(positionIndex) + "\n", 100)
21962
21963 if positionIndex >= len(inBaseRgbPts):
21964 myDebugPrint3AndException("helpFindNewRgbPoint: ran off end\n")
21965
21966 zz1 = inBaseRgbPts[positionIndex + 0]
21967 rr1 = inBaseRgbPts[positionIndex + 1]
21968 gg1 = inBaseRgbPts[positionIndex + 2]
21969 bb1 = inBaseRgbPts[positionIndex + 3]
21970 zz2 = inBaseRgbPts[positionIndex + 4]
21971 rr2 = inBaseRgbPts[positionIndex + 5]
21972 gg2 = inBaseRgbPts[positionIndex + 6]
21973 bb2 = inBaseRgbPts[positionIndex + 7]
21974 deltaPt = zz2 - zz1
21975 ratioPt = (inRatio - zz1)/deltaPt
21976 #print "before Pt: ", zz1, rr1, gg1, bb1
21977 #print "after Pt : ", zz2, rr2, gg2, bb2
21978 #print "inRatio: ", inRatio
21979 #print "deltaPt: ", deltaPt
21980 #print "ratioPt: ", ratioPt
21981
21982 subrangePt1 = [inRatio,
21983 rr1 + ratioPt * (rr2 - rr1),
21984 gg1 + ratioPt * (gg2 - gg1),
21985 bb1 + ratioPt * (bb2 - bb1)]
21986 if PhactoriDbg(100):
21987 myDebugPrint3("subrangePt1: " + str(subrangePt1) + "\n")
21988 return subrangePt1
21989
21990
21991 def CalculateColorMapRGBPointsWithSubranges(inBaseRgbPoints,
21992 inMinimum, inMaximum, inSubrangeMin, inSubrangeMax, inSubrangeColor):
21993 "creates the rgb values for color map with highlighed subranges"
21994
21995 if PhactoriDbg(100):
21996 myDebugPrint3("CalculateColorMapRGBPointsWithSubranges entered \n"
21997 " min, max: " + str(inMinimum) + ", " + str(inMaximum) + "\n"
21998 "subrange min, max: " + str(inSubrangeMin) + ", " + \
21999 str(inSubrangeMax) + "\n"
22000 "subrange color: " + str(inSubrangeColor) + "\n", 100)
22001
22002 #find where subrange fits in overallrange
22003 allRange = inMaximum - inMinimum
22004 minHlRatio = (inSubrangeMin - inMinimum)/allRange
22005 maxHlRatio = (inSubrangeMax - inMinimum)/allRange
22006
22007 #test for case where whole subrange is above or below overall range
22008 if minHlRatio >= 1.0 or maxHlRatio <= 0.0:
22009 if PhactoriDbg(100):
22010 myDebugPrint3("subrange is above or below overall range, returning\n"
22011 "CalculateColorMapRGBPointsWithSubranges returing \n", 100)
22012 return inBaseRgbPoints
22013
22014 if minHlRatio < 0.0:
22015 minHlRatio = 0.0
22016 if maxHlRatio > 1.0:
22017 maxHlRatio = 1.0
22018 if maxHlRatio - minHlRatio < 0.004:
22019 #very narrow subrange; use narrow bands but might color odd
22020 #issue warning?
22021 ratDelta = maxHlRatio - minHlRatio
22022 bandStep = ratDelta * 0.25
22023 else:
22024 bandStep = 0.001
22025
22026 #construct the no-subrange color map, with extra items to track the
22027 #outer range colors while changing the inner subrange colors
22028 xrgbPoints = inBaseRgbPoints
22029 #xrgbPoints = [0.0, 0.23137254902, 0.298039215686, 0.752941176471,
22030 # 0.5, 0.865, 0.865, 0.865,
22031 # 1.0, 0.705882352941, 0.0156862745098, 0.149019607843]
22032 if PhactoriDbg(100):
22033 myDebugPrint3("inBaseRgbPoints:\n" + str(inBaseRgbPoints) + "\n", 100)
22034
22035 #find the 4 points for the subrange
22036 subrangePt1 = helpFindNewRgbPoint(xrgbPoints, minHlRatio)
22037 subrangePt2 = [minHlRatio + bandStep,
22038 inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]
22039 subrangePt3 = [maxHlRatio - bandStep,
22040 inSubrangeColor[0], inSubrangeColor[1], inSubrangeColor[2]]
22041 subrangePt4 = helpFindNewRgbPoint(xrgbPoints, maxHlRatio)
22042
22043 #construct the map with the subrange
22044 xrgbIndex = 0
22045 myRgbPoints = []
22046
22047 #first do points from original color map which are below subrange
22048 while (xrgbIndex < len(xrgbPoints)) and xrgbPoints[xrgbIndex] < subrangePt1[0]:
22049 myRgbPoints.append(xrgbPoints[xrgbIndex+0])
22050 myRgbPoints.append(xrgbPoints[xrgbIndex+1])
22051 myRgbPoints.append(xrgbPoints[xrgbIndex+2])
22052 myRgbPoints.append(xrgbPoints[xrgbIndex+3])
22053 xrgbIndex += 4
22054
22055 #add in subrange points, accounting for bottom/top cases
22056 if subrangePt1[0] > xrgbPoints[0]:
22057 for nn in subrangePt1:
22058 myRgbPoints.append(nn)
22059 for nn in subrangePt2:
22060 myRgbPoints.append(nn)
22061 else:
22062 #special case, bottom of subrange is bottom of whole range
22063 subrangePt2[0] = subrangePt1[0]
22064 for nn in subrangePt2:
22065 myRgbPoints.append(nn)
22066
22067 numXrgbPoints = int(len(xrgbPoints) / 4)
22068 if subrangePt4[0] < xrgbPoints[(numXrgbPoints-1) * 4]:
22069 for nn in subrangePt3:
22070 myRgbPoints.append(nn)
22071 for nn in subrangePt4:
22072 myRgbPoints.append(nn)
22073 else:
22074 #special case, top of subrange is top of whole range
22075 subrangePt3[0] = subrangePt4[0]
22076 for nn in subrangePt3:
22077 myRgbPoints.append(nn)
22078
22079 #add in points from original color map after subrange, skipping any points
22080 #which were subsumed in subrange
22081 while subrangePt4[0] >= xrgbPoints[xrgbIndex]:
22082 xrgbIndex += 4
22083 if xrgbIndex >= len(xrgbPoints):
22084 break
22085
22086 while xrgbIndex < len(xrgbPoints):
22087 myRgbPoints.append(xrgbPoints[xrgbIndex+0])
22088 myRgbPoints.append(xrgbPoints[xrgbIndex+1])
22089 myRgbPoints.append(xrgbPoints[xrgbIndex+2])
22090 myRgbPoints.append(xrgbPoints[xrgbIndex+3])
22091 xrgbIndex += 4
22092
22093 if PhactoriDbg(100):
22094 myDebugPrint3('subrange: [' + \
22095 str(inSubrangeMin) + ', ' + \
22096 str(inSubrangeMax) + ']\n' + \
22097 'subrange ratio: [' + \
22098 str(minHlRatio) + ', ' + \
22099 str(maxHlRatio) + ']\n' + \
22100 'myRGBPoints: \n' + str(myRgbPoints) + '\n')
22101
22102 if PhactoriDbg(100):
22103 myDebugPrint3("CalculateColorMapRGBPointsWithSubranges returing \n", 100)
22104
22105 return myRgbPoints
22106
22107
22108 global gDefault_LUT_Num_RGBPoints
22109 global gDefault_LUT_RGBPoints
22110 global gDefault_PWF_Num_Points
22111 global gDefault_PWF_Points
22112 gDefault_LUT_Num_RGBPoints = -1
22113 gDefault_LUT_RGBPoints = []
22114 gDefault_PWF_Num_Points = -1
22115 gDefault_PWF_Points = []
22116
22117 def SetMinimumMaximumColorValues(inPvDataRepresentation,
22118 inMinimum, inMaximum,
22119 inPhactoriOperation, inPhactoriRepresentation,
22120 inVariableName, inPointsOrCells):
22121 "This sets the data values which will correspond to the colors at the " \
22122 "bottom and top of the color table. Data values above or below this " \
22123 "range will be clamped to the color table bottom or top."
22124 inColorMapSettings = inPhactoriRepresentation.mColorMapSettings
22125 if PhactoriDbg(100):
22126 myDebugPrint3('phactori.SetMinimumMaximumColorValues entered, min: ' + \
22127 str(inMinimum) + ' max: ' + str(inMaximum) + '\n' + \
22128 'inVariableName: ' + inVariableName + \
22129 ' inPointsOrCells: ' + inPointsOrCells + '\n', 100)
22130
22131 if inPhactoriRepresentation.mColorVariableInfo.mVariableTypeNeedsDetection:
22132 if PhactoriDbg(100):
22133 myDebugPrint3(" variable type was undetected, returning (1)\n")
22134 return
22135 if gParaViewCatalystVersionFlag >= 40300:
22136 savedActiveSourceZ = GetActiveSource()
22137 SetActiveSource(inPhactoriOperation.GetPvFilter())
22138 if PhactoriDbg():
22139 myDebugPrint3("using ColorBy() to set color var " + \
22140 inVariableName + " " + inPointsOrCells + " 4\n")
22141 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
22142 SafeColorBy(inPvDataRepresentation, (inPointsOrCells, inVariableName))
22143 inPvDataRepresentation.RescaleTransferFunctionToDataRange(False)
22144
22145 if inPhactoriRepresentation.mNameOfPresetToUse != None:
22146 if PhactoriDbg():
22147 myDebugPrint3("using preset with name: " + \
22148 inPhactoriRepresentation.mNameOfPresetToUse + "\n")
22149 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
22150 pv_4_3_PWF = GetOpacityTransferFunction(inVariableName)
22151 #second argument is rescale to data range; need to handle correctly
22152 pv_4_3_LUT.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, False)
22153 pv_4_3_PWF.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, False)
22154 #pv_4_3_LUT.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, True)
22155 #pv_4_3_PWF.ApplyPreset(inPhactoriRepresentation.mNameOfPresetToUse, True)
22156 allRange = inMaximum - inMinimum
22157 for ii in range(0, len(pv_4_3_LUT.RGBPoints), 4):
22158 pv_4_3_LUT.RGBPoints[ii] = inMinimum + pv_4_3_LUT.RGBPoints[ii] * allRange
22159 else:
22160 pv_4_3_LUT = GetColorTransferFunction(inVariableName)
22161 if pv_4_3_LUT.Discretize != 1:
22162 pv_4_3_LUT.Discretize = 1
22163 if pv_4_3_LUT.NumberOfTableValues != 1024:
22164 pv_4_3_LUT.NumberOfTableValues = 1024
22165
22166 pv_4_3_PWF = GetOpacityTransferFunction(inVariableName)
22167
22168 global gDefault_LUT_Num_RGBPoints
22169 global gDefault_LUT_RGBPoints
22170 global gDefault_PWF_Num_Points
22171 global gDefault_PWF_Points
22172 if gDefault_LUT_Num_RGBPoints < 0:
22173 for ii in pv_4_3_LUT.RGBPoints:
22174 gDefault_LUT_RGBPoints.append(ii)
22175 gDefault_LUT_Num_RGBPoints = len(gDefault_LUT_RGBPoints)
22176 for ii in pv_4_3_PWF.Points:
22177 gDefault_PWF_Points.append(ii)
22178 gDefault_PWF_Num_Points = len(gDefault_PWF_Points)
22179
22180 if len(pv_4_3_LUT.RGBPoints) != gDefault_LUT_Num_RGBPoints:
22181 #revert back to default rgb points starting setup
22182 pv_4_3_LUT.RGBPoints = gDefault_LUT_RGBPoints
22183
22184 if len(pv_4_3_PWF.Points) != gDefault_PWF_Num_Points:
22185 #revert back to default points starting setup
22186 pv_4_3_PWF.Points = gDefault_PWF_Points
22187
22188 pv_4_3_LUT.ScalarRangeInitialized = 1.0
22189 pv_4_3_PWF.ScalarRangeInitialized = 1
22190
22191 pv_4_3_LUT.RescaleTransferFunction(inMinimum, inMaximum)
22192 pv_4_3_PWF.RescaleTransferFunction(inMinimum, inMaximum)
22193 #pv_4_3_LUT.LockScalarRange = 1
22194 if PhactoriDbg(100):
22195 myDebugPrint3("rgb points: " + str(pv_4_3_LUT.RGBPoints) + "\n" + \
22196 "opacity points: " + str(pv_4_3_PWF.Points) + "\n")
22197 if inPhactoriRepresentation.mUseHighlightSubranges:
22198 baseRgbPoints, myColorSpace, myNanColor = \
22199 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
22200 0.0, 1.0)
22201 if PhactoriDbg(100):
22202 myDebugPrint3(
22203 "default base rgb points: " + str( baseRgbPoints) + "\n", 100)
22204 #add each subrange into the base color map one at a time
22205 for oneSubrange in inPhactoriRepresentation.mHighlightSubranges:
22206 myRGBPoints = CalculateColorMapRGBPointsWithSubranges(baseRgbPoints,
22207 inMinimum, inMaximum, oneSubrange[0], oneSubrange[1], oneSubrange[2])
22208 baseRgbPoints = myRGBPoints
22209
22210 #adjust the color range from 0 to 1 to the overall min to max
22211 for ii in range(0, len(myRGBPoints), 4):
22212 allRange = inMaximum - inMinimum
22213 myRGBPoints[ii] = inMinimum + myRGBPoints[ii] * allRange
22214 else:
22215 myRGBPoints, myColorSpace, myNanColor = \
22216 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
22217 inMinimum, inMaximum)
22218 pv_4_3_LUT.RGBPoints = myRGBPoints
22219 pv_4_3_LUT.ColorSpace = myColorSpace
22220 pv_4_3_LUT.NanColor = myNanColor
22221 if PhactoriDbg(100):
22222 myDebugPrint3('phactori.SetMinimumMaximumColorValues returning\n')
22223
22224 SetActiveSource(savedActiveSourceZ)
22225
22226 return
22227
22228 savedActiveSourceZ = GetActiveSource()
22229 SetActiveSource(inPhactoriOperation.GetPvFilter())
22230
22231 new_var_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 1.0, 1.0] )
22232
22233 new_var_PVLookupTable = inPvDataRepresentation.LookupTable
22234 myRGBPoints, myColorSpace, myNanColor = \
22235 GetColorMapInfoFromColorLegendCollection(inColorMapSettings,
22236 inMinimum, inMaximum)
22237 new_var_PVLookupTable.RGBPoints = myRGBPoints
22238 new_var_PVLookupTable.ColorSpace = myColorSpace
22239 if PhactoriDbg():
22240 myDebugPrint3("nan color: " + str(myNanColor) + " len: " + str(len(myNanColor)) + "\n")
22241 new_var_PVLookupTable.NanColor = myNanColor
22242
22243 if PhactoriDbg():
22244 myDebugPrint3("new lookup table (2):\n");
22245 myDebugPrint3(str(new_var_PVLookupTable) + "\n")
22246 myDebugPrint3("RGBPoints:\n");
22247 myDebugPrint3(str(new_var_PVLookupTable.RGBPoints) + "\n")
22248
22249 try:
22250 inPvDataRepresentation.ScalarOpacityFunction = new_var_PiecewiseFunction
22251 except:
22252 if PhactoriDbg():
22253 myDebugPrint3('no inPvDataRepresentation.ScalarOpacityFunction\n');
22254
22255 SetActiveSource(savedActiveSourceZ)
22256
22257 myDebugPrint3('phactori.SetMinimumMaximumColorValues returning (2)\n')
22258
22259 #'Closest Triad'
22260 #'Furthest Triad'
22261 #'Static Triad'
22262 #'Static Edges'
22263 #'Outer Edges'
22264 #def SetCubeAxesMode(inNewMode):
22265 # global currentPhactoriRenderViewInfo
22266 # currentPhactoriRenderViewInfo.DataRepresentation1.CubeAxesFlyMode = inNewMode
22267
22268 def ShowCubeAxesXX(inPvRenderView, inOnOrOff, inShowDataCubeAxesInfo = None):
22269 if PhactoriDbg(100):
22270 myDebugPrint3("ShowCubeAxesXX entered\n", 100)
22271 if(inOnOrOff == 'on'):
22272 if PhactoriDbg():
22273 myDebugPrint3(" ShowCubeAxesXX: turning on\n")
22274 #inPvDataRepresentation.CubeAxesVisibility = 1
22275 SetAxesGridVisibility(inPvRenderView, 1)
22276 if inShowDataCubeAxesInfo != None:
22277 inPvRenderView.AxesGrid.ShowEdges = inShowDataCubeAxesInfo.mShowEdges
22278 inPvRenderView.AxesGrid.ShowTicks = inShowDataCubeAxesInfo.mShowTicks
22279 axisXInfo = inShowDataCubeAxesInfo.mXAxisInfo
22280 axisYInfo = inShowDataCubeAxesInfo.mYAxisInfo
22281 axisZInfo = inShowDataCubeAxesInfo.mZAxisInfo
22282
22283 ##axis labels as specified
22284 if axisXInfo.mUseLabelFlag:
22285 inPvRenderView.AxesGrid.XTitle = axisXInfo.mAxisLabel
22286 if PhactoriDbg():
22287 myDebugPrint3(" x axis label set to: " + inPvRenderView.AxesGrid.XTitle + "\n")
22288 else:
22289 inPvRenderView.AxesGrid.XTitle = "X Axis"
22290 if axisYInfo.mUseLabelFlag:
22291 inPvRenderView.AxesGrid.YTitle = axisYInfo.mAxisLabel
22292 if PhactoriDbg():
22293 myDebugPrint3(" y axis label set to: " + inPvRenderView.AxesGrid.YTitle + "\n")
22294 else:
22295 inPvRenderView.AxesGrid.YTitle = "Y Axis"
22296 if axisZInfo.mUseLabelFlag:
22297 inPvRenderView.AxesGrid.ZTitle = axisZInfo.mAxisLabel
22298 if PhactoriDbg():
22299 myDebugPrint3(" z axis label set to: " + inPvRenderView.AxesGrid.ZTitle + "\n")
22300 else:
22301 inPvRenderView.AxesGrid.ZTitle = "Z Axis"
22302 else:
22303 if PhactoriDbg():
22304 myDebugPrint3(" ShowCubeAxesXX: turning off\n")
22305 #inPvDataRepresentation.CubeAxesVisibility = 0
22306 SetAxesGridVisibility(inPvRenderView, 0)
22307 if PhactoriDbg(100):
22308 myDebugPrint3("ShowCubeAxesXX returning\n", 100)
22309
22310
22311 def ShowDataColorLegendXX(inPvView,
22312 inOnOffSetting, inColorLegendPositionAndSize, inColorSettings,
22313 inColorLegendRepRef, inPvDataRep, inComponentString):
22314 "Turns on or off the display of the color bar legend showing the mapping\n between the color and the data value (and the name of the data value.\n (note this is primarily to do the paraview-side work to turn bar on or\n off, on to set up for rendering in the shared view, off to turn off\n rendering in shared view. On or off state for rendering is stored\n as a flag in the ioPhactoriImagesetBlock instance"
22315
22316 global gParaViewCatalystVersionFlag
22317
22318 if PhactoriDbg(100):
22319 myDebugPrint3('phactori.ShowDataColorLegendXX entered, setting:' + \
22320 inOnOffSetting + '\n', 100)
22321 if(inOnOffSetting == 'on'):
22322 myVisibility = 1
22323 else:
22324 myVisibility = 0
22325 if inColorLegendRepRef != None:
22326 if PhactoriDbg(100):
22327 myDebugPrint3("A inColorLegendRepRef was " + \
22328 str(inColorLegendRepRef.Visibility) + \
22329 " now 0: " + str(inColorLegendRepRef) + "\n")
22330 inColorLegendRepRef.Visibility = 0
22331 myDebugPrint3(
22332 'phactori.ShowDataColorLegendXX returing with none rep: ' + \
22333 inOnOffSetting + '\n', 100)
22334 return None
22335
22336 if gParaViewCatalystVersionFlag <= 40100:
22337 localColorArrayName = \
22338 inPvDataRep.ColorArrayName
22339 else:
22340 localColorArrayName = \
22341 inPvDataRep.ColorArrayName[1]
22342
22343 if inColorLegendRepRef != None:
22344 #myDebugPrint3(' phactori.ShowDataColorLegend using rep reference\n', 100)
22345 #if inColorLegendRepRef.ColorArrayName == '':
22346 # return
22347 inPvView.OrientationAxesLabelColor = inColorSettings.mTextColor
22348 if PhactoriDbg(100):
22349 myDebugPrint3("B inColorLegendRepRef was " + \
22350 str(inColorLegendRepRef.Visibility) + \
22351 " now " + str(myVisibility) + ": " + str(inColorLegendRepRef) + "\n")
22352 inColorLegendRepRef.Visibility = myVisibility
22353 inColorLegendRepRef.LookupTable = inPvDataRep.LookupTable
22354 inColorLegendRepRef.Title = localColorArrayName
22355 inColorLegendRepRef.ComponentTitle = inComponentString
22356 #ioPhactoriImagesetBlock.mColorLegendRepRef.Color = \
22357 # inColorSettings.mTextColor
22358 if PhactoriDbg(100):
22359 myDebugPrint3(
22360 'phactori.ShowDataColorLegendXX returing with old rep: ' + \
22361 inOnOffSetting + '\n', 100)
22362 return inColorLegendRepRef
22363 #else:
22364 #myDebugPrint3(' phactori.ShowDataColorLegend have to create rep reference\n', 100)
22365
22366 if inColorLegendPositionAndSize[0] == 'parameters':
22367 legendSizeMultiplier = None
22368 legendSize = inColorLegendPositionAndSize[3]
22369 legendFontSize = inColorLegendPositionAndSize[4]
22370 else:
22371 legendSizeMultiplier = inColorLegendPositionAndSize[1]
22372 if gParaViewCatalystVersionFlag <= 40100:
22373 #our own factor to make legends smaller generally
22374 legendSizeMultiplier *= 0.6
22375 else:
22376 #legendSizeMultiplier *= 1.0
22377 legendSizeMultiplier *= 0.7
22378 #legendFontSize = int(12.0 * legendSizeMultiplier)
22379 legendFontSize = int(9.0 * legendSizeMultiplier)
22380
22381 if gParaViewCatalystVersionFlag <= 40100:
22382 colorLegendDefaultLongSize = 0.5
22383 colorLegendDefaultShortSize = 0.13
22384 else:
22385 #[0.12, 0.43]
22386 #[0.85, 0.05]
22387 colorLegendDefaultLongSize = 0.43
22388 colorLegendDefaultShortSize = 0.12
22389
22390 colorLegendAdjustedLongSize = colorLegendDefaultLongSize * legendSizeMultiplier
22391 colorLegendAdjustedShortSize = colorLegendDefaultShortSize * legendSizeMultiplier
22392 horizontalLegendSize = [colorLegendAdjustedLongSize, colorLegendAdjustedShortSize]
22393 verticalLegendSize = [colorLegendAdjustedShortSize, colorLegendAdjustedLongSize]
22394
22395 xPosForBottomTop = 0.5 - 0.5 * colorLegendAdjustedLongSize
22396 yPosForLeftRight = 0.5 - 0.5 * colorLegendAdjustedShortSize
22397
22398 if gParaViewCatalystVersionFlag < 50400:
22399 if inColorLegendPositionAndSize[0] == 'top':
22400 legendOrientation = 'Horizontal'
22401 legendSize = horizontalLegendSize
22402 legendPosition=[xPosForBottomTop, 0.85]
22403 elif inColorLegendPositionAndSize[0] == 'bottom':
22404 legendOrientation = 'Horizontal'
22405 legendSize = horizontalLegendSize
22406 legendPosition=[xPosForBottomTop, 0.02]
22407 elif inColorLegendPositionAndSize[0] == 'left':
22408 legendOrientation = 'Vertical'
22409 legendSize = verticalLegendSize
22410 legendPosition=[0.065, yPosForLeftRight]
22411 elif inColorLegendPositionAndSize[0] == 'right':
22412 legendOrientation = 'Vertical'
22413 legendSize = verticalLegendSize
22414 legendPosition=[0.9, yPosForLeftRight]
22415 elif inColorLegendPositionAndSize[0] == 'top left':
22416 legendOrientation = 'Horizontal'
22417 legendSize = horizontalLegendSize
22418 legendPosition=[0.065, 0.85]
22419 elif inColorLegendPositionAndSize[0] == 'top right':
22420 legendOrientation = 'Horizontal'
22421 legendSize = horizontalLegendSize
22422 legendPosition=[0.7, 0.85]
22423 elif inColorLegendPositionAndSize[0] == 'bottom left':
22424 legendOrientation = 'Horizontal'
22425 legendSize = horizontalLegendSize
22426 #legendPosition=[0.065, 0.85]
22427 legendPosition=[0.065, 0.01]
22428 elif inColorLegendPositionAndSize[0] == 'bottom right':
22429 legendOrientation = 'Horizontal'
22430 legendSize = horizontalLegendSize
22431 #legendPosition=[0.7, 0.05]
22432 legendPosition=[0.7, 0.01]
22433 elif inColorLegendPositionAndSize[0] == 'parameters':
22434 legendOrientation = inColorLegendPositionAndSize[1]
22435 legendSize = horizontalLegendSize
22436 legendPosition = inColorLegendPositionAndSize[2]
22437 else:
22438 legendOrientation = 'Horizontal'
22439 legendSize = horizontalLegendSize
22440 #legendPosition=[xPosForBottomTop, 0.05]
22441 legendPosition=[xPosForBottomTop, 0.01]
22442
22443 if PhactoriDbg():
22444 myDebugPrint3("legend info:\n legendSizeMultiplier: " + str(legendSizeMultiplier) + "\n" \
22445 " legendSize: " + str(legendSize) + "\n" \
22446 " legendPos: " + str(legendPosition) + "\n"\
22447 " legendOrientation: " + str(legendOrientation) + "\n"\
22448 " legendFontSize: " + str(legendFontSize) + "\n")
22449
22450 elif gParaViewCatalystVersionFlag < 51000:
22451 defaultLegendLength = 0.33
22452 defaultMidPos = 0.5 - 0.5*defaultLegendLength
22453 #legendFontSize = 16
22454 #legendSize = 1.0
22455 #validPositions = ['UpperLeftCorner', 'UpperRightCorner',
22456 # 'LowerLeftCorner', 'LowerRightCorner',
22457 # 'UpperCenter', 'LowerCenter']
22458 legendPosition=[0.0, 0.0]
22459 if inColorLegendPositionAndSize[0] == 'top':
22460 legendOrientation = 'Horizontal'
22461 legendWindowLocation = 'UpperCenter'
22462 elif inColorLegendPositionAndSize[0] == 'bottom':
22463 legendOrientation = 'Horizontal'
22464 legendWindowLocation = 'LowerCenter'
22465 elif inColorLegendPositionAndSize[0] == 'left':
22466 legendOrientation = 'Vertical'
22467 legendPosition=[0.02, defaultMidPos]
22468 legendWindowLocation = 'AnyLocation'
22469 elif inColorLegendPositionAndSize[0] == 'right':
22470 legendOrientation = 'Vertical'
22471 legendPosition=[0.89, defaultMidPos]
22472 legendWindowLocation = 'AnyLocation'
22473 elif inColorLegendPositionAndSize[0] == 'top left':
22474 legendOrientation = 'Vertical'
22475 legendWindowLocation = 'UpperLeftCorner'
22476 elif inColorLegendPositionAndSize[0] == 'top right':
22477 legendOrientation = 'Vertical'
22478 legendWindowLocation = 'UpperRightCorner'
22479 elif inColorLegendPositionAndSize[0] == 'bottom left':
22480 legendOrientation = 'Vertical'
22481 legendWindowLocation = 'LowerLeftCorner'
22482 elif inColorLegendPositionAndSize[0] == 'bottom right':
22483 legendOrientation = 'Vertical'
22484 legendWindowLocation = 'LowerRightCorner'
22485 elif inColorLegendPositionAndSize[0] == 'parameters':
22486 legendOrientation = inColorLegendPositionAndSize[1]
22487 legendPosition = inColorLegendPositionAndSize[2]
22488 legendWindowLocation = 'AnyLocation'
22489 else:
22490 legendOrientation = 'Vertical'
22491 legendWindowLocation = 'LowerRightCorner'
22492 else:
22493 defaultLegendLength = 0.33
22494 defaultMidPos = 0.5 - 0.5*defaultLegendLength
22495 #legendFontSize = 16
22496 #legendSize = 1.0
22497 #validPositions = ['UpperLeftCorner', 'UpperRightCorner',
22498 # 'LowerLeftCorner', 'LowerRightCorner',
22499 # 'UpperCenter', 'LowerCenter']
22500 legendPosition=[0.0, 0.0]
22501 if inColorLegendPositionAndSize[0] == 'top':
22502 legendOrientation = 'Horizontal'
22503 legendWindowLocation = 'Upper Center'
22504 elif inColorLegendPositionAndSize[0] == 'bottom':
22505 legendOrientation = 'Horizontal'
22506 legendWindowLocation = 'Lower Center'
22507 elif inColorLegendPositionAndSize[0] == 'left':
22508 legendOrientation = 'Vertical'
22509 legendPosition=[0.02, defaultMidPos]
22510 legendWindowLocation = 'Any Location'
22511 elif inColorLegendPositionAndSize[0] == 'right':
22512 legendOrientation = 'Vertical'
22513 legendPosition=[0.89, defaultMidPos]
22514 legendWindowLocation = 'Any Location'
22515 elif inColorLegendPositionAndSize[0] == 'top left':
22516 legendOrientation = 'Vertical'
22517 legendWindowLocation = 'Upper Left Corner'
22518 elif inColorLegendPositionAndSize[0] == 'top right':
22519 legendOrientation = 'Vertical'
22520 legendWindowLocation = 'Upper Right Corner'
22521 elif inColorLegendPositionAndSize[0] == 'bottom left':
22522 legendOrientation = 'Vertical'
22523 legendWindowLocation = 'Lower Left Corner'
22524 elif inColorLegendPositionAndSize[0] == 'bottom right':
22525 legendOrientation = 'Vertical'
22526 legendWindowLocation = 'Lower Right Corner'
22527 elif inColorLegendPositionAndSize[0] == 'parameters':
22528 legendOrientation = inColorLegendPositionAndSize[1]
22529 legendPosition = inColorLegendPositionAndSize[2]
22530 legendWindowLocation = 'Any Location'
22531 else:
22532 legendOrientation = 'Vertical'
22533 legendWindowLocation = 'Lower Right Corner'
22534
22535 #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 )
22536 if gParaViewCatalystVersionFlag <= 40100:
22537 newScalarBarWidgetRepresentation = CreateScalarBar(Title=localColorArrayName,
22538 Orientation=legendOrientation,
22539 Position=legendPosition,
22540 Position2 = legendSize,
22541 Visibility=myVisibility,
22542 LookupTable=inPvDataRep.LookupTable,
22543 LabelFontSize=legendFontSize,
22544 TitleOpacity=1.0,
22545 TitleShadow=0,
22546 AutomaticLabelFormat=1,
22547 TitleFontSize=legendFontSize,
22548 TitleColor=inColorSettings.mTextColor,
22549 AspectRatio=20.0,
22550 NumberOfLabels=5,
22551 ComponentTitle='',
22552 Resizable=1,
22553 TitleFontFamily='Arial',
22554 LabelFontFamily='Arial',
22555 TitleItalic=0,
22556 Selectable=0,
22557 LabelItalic=0,
22558 Enabled=0,
22559 LabelColor=inColorSettings.mTextColor,
22560 LabelBold=0,
22561 UseNonCompositedRenderer=1,
22562 LabelOpacity=1.0,
22563 TitleBold=0,
22564 LabelFormat='%-#6.3g',
22565 LabelShadow=0,
22566 Repositionable=1)
22567 elif gParaViewCatalystVersionFlag < 50400:
22568 newScalarBarWidgetRepresentation = CreateScalarBar(Title=localColorArrayName,
22569 Orientation=legendOrientation,
22570 Position=legendPosition,
22571 Position2 = legendSize,
22572 Visibility=myVisibility,
22573 LookupTable=inPvDataRep.LookupTable,
22574 LabelFontSize=legendFontSize,
22575 #TitleOpacity=1.0,
22576 #TitleShadow=0,
22577 #AutomaticLabelFormat=1,
22578 TitleFontSize=legendFontSize,
22579 TitleColor=inColorSettings.mTextColor,
22580 AspectRatio=20.0,
22581 #NumberOfLabels=5,
22582 ComponentTitle='',
22583 #Resizable=1,
22584 #TitleFontFamily='Arial',
22585 #LabelFontFamily='Arial',
22586 #TitleItalic=0,
22587 #Selectable=0,
22588 #LabelItalic=0,
22589 #Enabled=0,
22590 LabelColor=inColorSettings.mTextColor,
22591 #LabelBold=0,
22592 #UseNonCompositedRenderer=1,
22593 #LabelOpacity=1.0,
22594 #TitleBold=0,
22595 #LabelFormat='%-#6.3g',
22596 #LabelShadow=0,
22597 #Repositionable=1
22598 )
22599 elif gParaViewCatalystVersionFlag < 51000:
22600 newScalarBarWidgetRepresentation = CreateScalarBar(
22601 Title=localColorArrayName, ComponentTitle='')
22602 newScalarBarWidgetRepresentation.Orientation = legendOrientation
22603 newScalarBarWidgetRepresentation.WindowLocation = legendWindowLocation
22604 if legendWindowLocation == 'AnyLocation':
22605 newScalarBarWidgetRepresentation.Position = legendPosition
22606 if PhactoriDbg():
22607 nbwr = newScalarBarWidgetRepresentation
22608 myDebugPrint3("newScalarBarWidgetRepresentation:\n" +\
22609 str(nbwr) + "\n" +\
22610 " Title: " + str(nbwr.Title) + "\n" +\
22611 " ComponentTitle: " + str(nbwr.ComponentTitle) + "\n" +\
22612 " WindowLocation: " + str(nbwr.WindowLocation) + "\n" +\
22613 " Position: " + str(nbwr.Position) + "\n" +\
22614 " ScalarBarLength: " + str(nbwr.ScalarBarLength) + "\n" +\
22615 " ScalarBarThickness: " + str(nbwr.ScalarBarThickness) + "\n" +\
22616 " Orientation: " + str(nbwr.Orientation) + "\n" +\
22617 " LabelFontSize: " + str(nbwr.LabelFontSize) + "\n" +\
22618 " TitleFontSize: " + str(nbwr.TitleFontSize) + "\n" +\
22619 " LabelFontFamily: " + str(nbwr.LabelFontFamily) + "\n" +\
22620 " TitleFontFamily: " + str(nbwr.TitleFontSize) + "\n")
22621 #" LockPosition: " + str(nbwr.LockPosition) + "\n" +\
22622 #" Repositionable: " + str(nbwr.Repositionable) + "\n" +\
22623 #" AutoOrient: " + str(nbwr.AutoOrient) + "\n" +\
22624 else:
22625 pv_4_3_LUT = GetColorTransferFunction(inPvDataRep.ColorArrayName[1])
22626 newScalarBarWidgetRepresentation = GetScalarBar(pv_4_3_LUT, inPvView)
22627 newScalarBarWidgetRepresentation.Orientation = legendOrientation
22628 global gTemporaryGlobalImageTextColor
22629 newScalarBarWidgetRepresentation.TitleColor = gTemporaryGlobalImageTextColor
22630 newScalarBarWidgetRepresentation.LabelColor = gTemporaryGlobalImageTextColor
22631 newScalarBarWidgetRepresentation.WindowLocation = legendWindowLocation
22632 if legendWindowLocation == 'AnyLocation':
22633 newScalarBarWidgetRepresentation.Position = legendPosition
22634 if PhactoriDbg():
22635 nbwr = newScalarBarWidgetRepresentation
22636 nbwr.ComponentTitle = ""
22637 myDebugPrint3("newScalarBarWidgetRepresentation:\n" +\
22638 str(nbwr) + "\n" +\
22639 " Title: " + str(nbwr.Title) + "\n" +\
22640 " ComponentTitle: " + str(nbwr.ComponentTitle) + "\n" +\
22641 " WindowLocation: " + str(nbwr.WindowLocation) + "\n" +\
22642 " Position: " + str(nbwr.Position) + "\n" +\
22643 " ScalarBarLength: " + str(nbwr.ScalarBarLength) + "\n" +\
22644 " ScalarBarThickness: " + str(nbwr.ScalarBarThickness) + "\n" +\
22645 " Orientation: " + str(nbwr.Orientation) + "\n" +\
22646 " LabelFontSize: " + str(nbwr.LabelFontSize) + "\n" +\
22647 " TitleFontSize: " + str(nbwr.TitleFontSize) + "\n" +\
22648 " LabelFontFamily: " + str(nbwr.LabelFontFamily) + "\n" +\
22649 " TitleFontFamily: " + str(nbwr.TitleFontSize) + "\n")
22650 #" LockPosition: " + str(nbwr.LockPosition) + "\n" +\
22651 #" Repositionable: " + str(nbwr.Repositionable) + "\n" +\
22652 #" AutoOrient: " + str(nbwr.AutoOrient) + "\n" +\
22653
22654 inPvView.OrientationAxesLabelColor = inColorSettings.mTextColor
22655 inPvView.Representations.append(newScalarBarWidgetRepresentation)
22656 #ioPhactoriImagesetBlock.mColorLegendRepRef = \
22657 # newScalarBarWidgetRepresentation
22658 if PhactoriDbg():
22659 myDebugPrint3("current lookup table:\n");
22660 if PhactoriDbg():
22661 myDebugPrint3(str(inPvDataRep.LookupTable) + '\n')
22662 if PhactoriDbg():
22663 myDebugPrint3("RGBPoints:\n");
22664 if PhactoriDbg():
22665 if gParaViewCatalystVersionFlag <= 40100:
22666 myLocalRGBPoints = inPvDataRep.LookupTable.RGBPoints
22667 else:
22668 pv_4_3_LUT = GetColorTransferFunction(
22669 inPvDataRep.ColorArrayName[1])
22670 myLocalRGBPoints = pv_4_3_LUT.RGBPoints
22671 myDebugPrint3(str(myLocalRGBPoints) + '\n')
22672 if PhactoriDbg():
22673 myDebugPrint3("widget:\n");
22674 if PhactoriDbg():
22675 myDebugPrint3(str(newScalarBarWidgetRepresentation) + '\n')
22676
22677 if PhactoriDbg(100):
22678 myDebugPrint3('phactori.ShowDataColorLegendXX returing with new rep: ' + \
22679 inOnOffSetting + '\n', 100)
22680
22681 return newScalarBarWidgetRepresentation
22682
22683 def ApplyClipPlane(inNormal, inOrigin, inClipPlaneFilterName):
22684 newClip = Clip(ClipType = "Plane")
22685 newClip.ClipType.Normal = inNormal
22686 newClip.ClipType.Origin = inOrigin
22687 SetActiveSource(newClip);
22688 AddFilterToFilterMap(inClipPlaneFilterName, newClip)
22689
22690 def TempAddTestFiltersAfterDispl():
22691 "create the clip plane filter for ParaView"
22692 if PhactoriDbg(100):
22693 myDebugPrint3('TempAddTestFiltersAfterDispl entered\n', 100)
22694 #info in block class should already be parsed and checked
22695
22696 #savedActiveSource = GetActiveSource()
22697 #newCellToPointFilter = CellDatatoPointData()
22698
22699 ##SetActiveSource(newCellToPointFilter)
22700 ##SetActiveSource(savedActiveSource)
22701
22702 #SetActiveSource(newCellToPointFilter)
22703 #newCellToPointFilter.UpdatePipeline()
22704 #AddFilterToFilterMap('initialCellToPointFilter', newCellToPointFilter)
22705
22706 #newContourFilter = Contour(PointMergeMethod="Uniform Binning")
22707 #myDebugPrint3(" contour filter is: " + str(newContourFilter) + "\n")
22708 #newContourFilter.PointMergeMethod = "Uniform Binning"
22709 #newContourFilter.Isosurfaces = [9687]
22710 #myDebugPrint3(" variable is: " + str('VON_MISES') + "\n")
22711 #newContourFilter.ContourBy = ['POINTS', 'Global Node Id']
22712
22713 #myDebugPrint3(" still okay\n")
22714 #SetActiveSource(newContourFilter)
22715 #AddFilterToFilterMap('initialContourFilter', newContourFilter)
22716
22717 #Contour2 = Contour( guiName="Contour2", Isosurfaces=[9882.0], ComputeNormals=1, GenerateTriangles=1, ComputeGradients=0, ComputeScalars=0, ContourBy=['POINTS', 'GlobalNodeId'], PointMergeMethod="Uniform Binning" )
22718 #Contour2.PointMergeMethod.Numberofpointsperbucket = 8
22719 #Contour2.PointMergeMethod.Divisions = [50, 50, 50]
22720
22721 if PhactoriDbg(100):
22722 myDebugPrint3('TempAddTestFiltersAfterDispl returning\n', 100)
22723
22724
22725 #makes a filter which pulls a component out of a vector so it can be treated
22726 #separately
22727 def ExtractComponentFromVectorVariable(inVariableName, inWhichComponent, inResultName = 'Result', inFilterName = None):
22728
22729 if inFilterName == None:
22730 inFilterName = "ExtractComponent_" + str(inWhichComponent) + GetSeparatorString() + inVariableName
22731 if PhactoriDbg(100):
22732 myDebugPrint3('phactori.ExtractComponentFromVectorVariable entered, variable name:' + \
22733 inVariableName + ', ' + inResultName + ', ' + \
22734 str(inWhichComponent) + '\n', 100)
22735
22736 #theActiveSource = GetActiveSource()
22737 #if(theActiveSource == None):
22738 # myDebugPrint3('phactori.ColorByVectorVariable no active source, returning:\n', 100)
22739 # return
22740
22741 #debugPrintRepresentationsAndVisibility(currentRvi)
22742 newFunctionString = ""
22743 if(inWhichComponent == 0):
22744 newFunctionString = inVariableName + '_X'
22745 elif(inWhichComponent == 1):
22746 newFunctionString = inVariableName + '_Y'
22747 elif(inWhichComponent == 2):
22748 newFunctionString = inVariableName + '_Z'
22749 else:
22750 if PhactoriDbg():
22751 myDebugPrint3('phactori.ColorByVectorVariable unexpected component (needs 0, 1, or 2)\n')
22752 exit()
22753
22754 #DisplacementWarpCalculator = Calculator( guiName="Calculator1", Function=FunctionString, ReplacementValue=0.0, ResultArrayName='Result', ReplaceInvalidResults=1, AttributeMode='point_data', CoordinateResults=1 )
22755
22756 calc2Source = Calculator( guiName=inFilterName, Function=newFunctionString, ReplacementValue=0.0, ResultArrayName=inResultName, ReplaceInvalidResults=1)
22757
22758 if PhactoriDbg():
22759 myDebugPrint3('Calulator2 has ' + str(calc2Source.PointData.GetNumberOfArrays()) + ' point data items\n');
22760 PointDataList = []
22761 for ii in range(calc2Source.PointData.GetNumberOfArrays()):
22762 PointDataList.append(calc2Source.PointData.GetArray(ii).Name)
22763 if PhactoriDbg():
22764 myDebugPrint3('calc2Source point data items: ' + str(PointDataList) + '\n');
22765 #SetActiveSource(currentSi.ActiveSource);
22766
22767 #tempDataRepresentation = GetDisplayProperties(currentSi.ActiveSource)
22768 #tempDataRepresentation.Visibility = 0
22769 SetActiveSource(calc2Source);
22770 #currentSi.ActiveSource.ResultArrayName = currentSi.ActiveSource.Function
22771 #currentSi.ActiveSource = calc2Source;
22772 AddFilterToFilterMap(inFilterName, calc2Source)
22773 #myDebugPrint3('calculator function: ' + currentSi.ActiveSource.Function + '\n');
22774 #originalSi = currentSi
22775
22776 global collectFrameCount
22777 collectFrameCount = 0
22778
22779 def CollectCells2(inClientSideData, inBlockIndex, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir):
22780 if PhactoriDbg():
22781 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' Entering CollectCells2: ' + inClientSideData.GetClassName() + '\n')
22782 if inClientSideData.GetClassName() == "vtkMultiBlockDataSet":
22783 numBlocks = inClientSideData.GetNumberOfBlocks()
22784 if PhactoriDbg():
22785 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is vtkMultiBlockDataSet, recursing, numblocks: ' + str(numBlocks) + '\n')
22786 for ii in range(0, numBlocks):
22787 oneBlock = inClientSideData.GetBlock(ii)
22788 if(oneBlock != None):
22789 CollectCells2(oneBlock, ii, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir)
22790 #if oneBlock.GetClassName() == "vtkExodusIIMultiBlockDataSet":
22791 # myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' vtkExodusIIMultiBlockDataSet breaks loop\n')
22792 # break
22793 elif inClientSideData.GetClassName() == "vtkExodusIIMultiBlockDataSet":
22794 numBlocks = inClientSideData.GetNumberOfBlocks()
22795 if PhactoriDbg():
22796 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is vtkExodusIIMultiBlockDataSet, not recursing, numblocks: ' + str(numBlocks) + '\n')
22797 for ii in range(0, numBlocks):
22798 oneBlock = inClientSideData.GetBlock(ii)
22799 if(oneBlock != None):
22800 CollectCells2(oneBlock, ii, ioCollectList, ioTotalCellCount, cellVariableName, thresholdValue, thresholdDir)
22801 else:
22802 cellData = inClientSideData.GetCellData()
22803 tearArray = cellData.GetArray(cellVariableName)
22804 #idArray = cellData.GetArray('GlobalElementId')
22805 numTuples = tearArray.GetNumberOfTuples()
22806 if PhactoriDbg():
22807 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' data is not vtkMultiBlockDataSet, collecting ' + str(numTuples) + '\n')
22808 global collectFrameCount
22809 appendCount = 0
22810 for jj in range(0, numTuples):
22811 ioTotalCellCount[0] = ioTotalCellCount[0] + 1
22812 tearVal = tearArray.GetTuple1(jj)
22813 testResult = False
22814 if thresholdDir == 1:
22815 if tearVal > thresholdValue:
22816 testResult = True
22817 else:
22818 if tearVal < thresholdValue:
22819 testResult = True
22820 if testResult:
22821 #elemId = idArray.GetTuple1(jj)
22822 listItem = [SmartGetLocalProcessId(), inBlockIndex, jj, tearVal, collectFrameCount]
22823 ioCollectList.append(listItem)
22824 if(appendCount == 0):
22825 if PhactoriDbg():
22826 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + 'listing first few appended (up to 20)\n')
22827 if(appendCount < 20):
22828 if PhactoriDbg():
22829 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' appending item: ' + str(listItem) + '\n')
22830 appendCount += 1
22831 if PhactoriDbg():
22832 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' Leaving CollectCells2\n')
22833
22834
22835 def CollectCells1(cellVariableName, thresholdValue, thresholdDir):
22836 if PhactoriDbg():
22837 myDebugPrint3('Entering CollectCells1 var ' + cellVariableName + '\n')
22838 global collectFrameCount
22839 collectFrameCount = collectFrameCount + 1
22840 xx = GetActiveSource()
22841 collectedCells = []
22842 xxdata = xx.GetClientSideObject().GetOutputDataObject(0)
22843 totalCellCount = [0]
22844 CollectCells2(xxdata, 0, collectedCells, totalCellCount, cellVariableName, thresholdValue, thresholdDir)
22845 #myDebugPrint3(' collection result:\n' + str(collectedCells) + '\n')
22846 if PhactoriDbg():
22847 myDebugPrint3(' proc ' + str(SmartGetLocalProcessId()) + ' total cells: ' + str(totalCellCount) + ' number of collected cells: ' + str(len(collectedCells)) + '\n')
22848 if PhactoriDbg():
22849 myDebugPrint3(' last 20: \n')
22850 for ii in range(0,20):
22851 index = len(collectedCells) - 1 - ii
22852 if index >= 0:
22853 if PhactoriDbg():
22854 myDebugPrint3(' ' + str(collectedCells[index]) + ' ')
22855 if PhactoriDbg():
22856 myDebugPrint3('\n')
22857 if PhactoriDbg():
22858 myDebugPrint3('Leaving CollectCells1\n')
22859 return collectedCells
22860
22861 def UseReduceToSumArrayOfInts(ioListOfValues):
22862 if PhactoriDbg(100):
22863 myDebugPrint3('UseReduceToSumArrayOfInts entered\n', 100)
22864 if PhactoriDbg():
22865 myDebugPrint3(' before reduced: ' + str(ioListOfValues) + '\n');
22866 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
22867 globalController = pm.GetGlobalController()
22868 localarray = vtk.vtkIntArray()
22869 numberOfValues = len(ioListOfValues)
22870 localarray.SetNumberOfTuples(numberOfValues)
22871 for jj in range(0, numberOfValues):
22872 localarray.SetValue(jj, ioListOfValues[jj])
22873 globalarray = vtk.vtkIntArray()
22874 globalarray.SetNumberOfTuples(numberOfValues)
22875 globalController.AllReduce(localarray, globalarray, 2)
22876 for jj in range(0, numberOfValues):
22877 ioListOfValues[jj] = globalarray.GetTuple1(jj)
22878 if PhactoriDbg():
22879 myDebugPrint3(' reduced: ' + str(ioListOfValues) + '\n');
22880 if PhactoriDbg(100):
22881 myDebugPrint3('UseReduceToSumArrayOfInts returning\n', 100)
22882
22883 #called by UseReduceToSpreadValues to actually do Reduce
22884 def UseReduceToSpreadPositiveValues(ioListOfValues):
22885 if PhactoriDbg(100):
22886 myDebugPrint3('UseReduceToSpreadPositiveValues entered\n', 100)
22887 if PhactoriDbg():
22888 myDebugPrint3(' before reduced: ' + str(ioListOfValues) + '\n');
22889 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
22890 globalController = pm.GetGlobalController()
22891 localarray = vtk.vtkDoubleArray()
22892 numberOfValues = len(ioListOfValues)
22893 localarray.SetNumberOfTuples(numberOfValues)
22894 for jj in range(0, numberOfValues):
22895 localarray.SetValue(jj, ioListOfValues[jj])
22896 globalarray = vtk.vtkDoubleArray()
22897 globalarray.SetNumberOfTuples(numberOfValues)
22898 globalController.AllReduce(localarray, globalarray, 0)
22899 for jj in range(0, numberOfValues):
22900 ioListOfValues[jj] = globalarray.GetTuple1(jj)
22901 if PhactoriDbg():
22902 myDebugPrint3(' reduced: ' + str(ioListOfValues) + '\n');
22903 if PhactoriDbg(100):
22904 myDebugPrint3('UseReduceToSpreadPositiveValues returning\n', 100)
22905
22906
22907 #used by GetAndReduceViewControl to read view control values from a file on
22908 #one process, then use Reduce to spread the values to all processes
22909 def UseReduceToSpreadValues(ioListOfValues):
22910 #assumes values for all processes are 0.0 except one, uses trick to only do max
22911
22912 if PhactoriDbg(100):
22913 myDebugPrint3('UseReduceToSpreadValues entered\n', 100)
22914 if PhactoriDbg():
22915 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' start values: ' + str(ioListOfValues) + '\n')
22916 listOfValuePairs = []
22917 numberOfValues = len(ioListOfValues)
22918 for ii in range(0, numberOfValues):
22919 if ioListOfValues[ii] >= 0.0:
22920 listOfValuePairs.append(ioListOfValues[ii])
22921 listOfValuePairs.append(0.0)
22922 else:
22923 listOfValuePairs.append(0.0)
22924 listOfValuePairs.append(-ioListOfValues[ii])
22925 if PhactoriDbg():
22926 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' paired values: ' + str(listOfValuePairs) + '\n')
22927 UseReduceToSpreadPositiveValues(listOfValuePairs)
22928 for ii in range(0, numberOfValues):
22929 value = listOfValuePairs[ii*2]
22930 if value == 0.0:
22931 value = listOfValuePairs[ii*2+1]
22932 if value != 0.0:
22933 value = -value
22934 ioListOfValues[ii] = value
22935
22936 if PhactoriDbg():
22937 myDebugPrint3(' ' + 'proc ' + str(SmartGetLocalProcessId()) + ' final values: ' + str(ioListOfValues) + '\n')
22938 if PhactoriDbg(100):
22939 myDebugPrint3('UseReduceToSpreadValues returning\n', 100)
22940
22941 def GetCurrentSource():
22942 return GetActiveSource()
22943
22944 def dummyTest1():
22945 print('####in dummyTest1')
22946
22947 global gPlotView1Pts
22948 gPlotView1Pts = None
22949
22950 global ProgrammableSourceInput
22951 ProgrammableSourceInput = None
22952 global ProgrammableSource2
22953 ProgrammableSource2 = None
22954
22955 class PlotValMinMaxTrkC:
22956 def __init__(self):
22957 self.mThisCbMin = 0.0
22958 self.mThisCbMax = 0.0
22959 self.mThisCbInitialized = False
22960 self.mAllMin = 0.0
22961 self.mAllMax = 0.0
22962 self.mAllInitialized = False
22963
22964 #sets minimum and maximum plot ranges, and allows there to not be
22965 #a minimmum and/or maximum as well
22966 self.mLowestTop = 0.0
22967 self.mUseLowestTop = False
22968 self.mLowestBot = 0.0
22969 self.mUseLowestBot = False
22970 self.mHighestTop = 0.0
22971 self.mUseHighestTop = False
22972 self.mHighestBot = 0.0
22973 self.mUseHighestBot = False
22974
22975 self.mMinToUse = 0.0
22976 self.mMaxToUse = 0.0
22977
22978 self.mUseCumulativeRange = False
22979
22980 def SetFromRestartInfo(self, inJson):
22981 "given a map (json format), use the info in the map to set the\n tracker state--this reads the info created out in GetRestartInfo"
22982
22983 inJsonIsGood = True
22984 if 'mAll' not in inJson:
22985 if PhactoriDbg():
22986 myDebugPrint3(
22987 'PlotValMinMaxTrkC::SetFromRestartInfo mAll not in inJson\n')
22988 inJsonIsGood = False
22989 if 'mLowestTop' not in inJson:
22990 if PhactoriDbg():
22991 myDebugPrint3(
22992 'PlotValMinMaxTrkC::SetFromRestartInfo mLowestTop not in inJson\n')
22993 inJsonIsGood = False
22994 if 'mLowestBot' not in inJson:
22995 if PhactoriDbg():
22996 myDebugPrint3(
22997 'PlotValMinMaxTrkC::SetFromRestartInfo mLowestBot not in inJson\n')
22998 inJsonIsGood = False
22999 if 'mHighestTop' not in inJson:
23000 if PhactoriDbg():
23001 myDebugPrint3(
23002 'PlotValMinMaxTrkC::SetFromRestartInfo mHighestTop not in inJson\n')
23003 inJsonIsGood = False
23004 if 'mHighestBot' not in inJson:
23005 if PhactoriDbg():
23006 myDebugPrint3(
23007 'PlotValMinMaxTrkC::SetFromRestartInfo mHighestBot not in inJson\n')
23008 inJsonIsGood = False
23009 if 'mMinMaxToUse' not in inJson:
23010 if PhactoriDbg():
23011 myDebugPrint3(
23012 'PlotValMinMaxTrkC::SetFromRestartInfo mMinMaxToUse not in inJson\n')
23013 inJsonIsGood = False
23014 if 'mUseCumulativeRange' not in inJson:
23015 if PhactoriDbg():
23016 myDebugPrint3('PlotValMinMaxTrkC::SetFromRestartInfo " + \
23017 "mUseCumulativeRange not in inJson\n')
23018 inJsonIsGood = False
23019 if inJsonIsGood == False:
23020 return
23021
23022 #thisCbItem = inJson['mThisCb']
23023 #self.mThisCbInitialized = thisCbItem[0]
23024 #self.mThisCbMin = thisCbItem[1]
23025 #self.mThisCbMax = thisCbItem[2]
23026
23027 allItem = inJson['mAll']
23028 self.mAllInitialized = allItem[0]
23029 self.mAllMin = allItem[1]
23030 self.mAllMax = allItem[2]
23031
23032 lowestTopItem = inJson['mLowestTop']
23033 self.mUseLowestTop = lowestTopItem[0]
23034 self.mLowestTop = lowestTopItem[1]
23035
23036 lowestBotItem = inJson['mLowestBot']
23037 self.mUseLowestBot = lowestBotItem[0]
23038 self.mLowestBot = lowestBotItem[1]
23039
23040 highestTopItem = inJson['mHighestTop']
23041 self.mUseHighestTop = highestTopItem[0]
23042 self.mHighestTop = highestTopItem[1]
23043
23044 highestBotItem = inJson['mHighestBot']
23045 self.mUseHighestBot = highestBotItem[0]
23046 self.mHighestBot = highestBotItem[1]
23047
23048 minMaxToUseItem = inJson['mMinMaxToUse']
23049 self.mMinToUse = minMaxToUseItem[0]
23050 self.mMaxToUse = minMaxToUseItem[1]
23051
23052 self.mUseCumulativeRange = inJson["mUseCumulativeRange"]
23053 if PhactoriDbg():
23054 myDebugPrint3("PlotValMinMaxTrkC::SetFromRestartInfo state loaded:\n"
23055 + self.SelfToStr())
23056
23057 def GetRestartInfo(self):
23058 "construct, in python map/json info from this PlotValMinMaxTrkC instance\n which contains the information which would be needed to restore the\n instance to the proper state after a simulation restart.\n Return the restart info map/json"
23059 newJsonItem = {}
23060 #newJsonItem["mThisCb"] = [self.mThisCbInitialized,
23061 # self.mThisCbMin, self.mThisCbMax]
23062 newJsonItem["mAll"] = [self.mAllInitialized,
23063 self.mAllMin, self.mAllMax]
23064 newJsonItem["mLowestTop"] = [self.mUseLowestTop, self.mLowestTop]
23065 newJsonItem["mLowestBot"] = [self.mUseLowestBot, self.mLowestBot]
23066 newJsonItem["mHighestTop"] = [self.mUseHighestTop, self.mHighestTop]
23067 newJsonItem["mHighestBot"] = [self.mUseHighestBot, self.mHighestBot]
23068 newJsonItem["mMinMaxToUse"] = [self.mMinToUse, self.mMaxToUse]
23069 newJsonItem["mUseCumulativeRange"] = self.mUseCumulativeRange
23070 if PhactoriDbg():
23071 myDebugPrint3("PlotValMinMaxTrkC::GetRestartInfo state saved:\n"
23072 + self.SelfToStr())
23073 return newJsonItem
23074
23075 def SelfToStr(self):
23076 retStr = "PlotValMinMaxTrkC info:" +\
23077 "\n mUseCumulativeRange: " + str(self.mUseCumulativeRange) +\
23078 "\n mThisCbInitialized: " + str(self.mThisCbInitialized) +\
23079 "\n mThisCbMin: " + repr(self.mThisCbMin) +\
23080 "\n mThisCbMax: " + repr(self.mThisCbMax) +\
23081 "\n mAllInitialized: " + str(self.mAllInitialized) +\
23082 "\n mAllMin: " + repr(self.mAllMin) +\
23083 "\n mAllMax: " + repr(self.mAllMax) +\
23084 "\n mLowestBot: " + repr(self.mLowestBot) +\
23085 "\n mHighestBot: " + repr(self.mHighestBot) +\
23086 "\n mLowestTop: " + repr(self.mLowestTop) +\
23087 "\n mHighestTop: " + str(self.mHighestTop) +\
23088 "\n mUseLowestBot: " + str(self.mUseLowestBot) +\
23089 "\n mUseHighestBot: " + str(self.mUseHighestBot) +\
23090 "\n mUseLowestTop: " + str(self.mUseLowestTop) +\
23091 "\n mUseHighestTop: " + str(self.mUseHighestTop) +\
23092 "\n ---in hex--- " +\
23093 "\n mThisCbMin: " + self.mThisCbMin.hex() +\
23094 "\n mThisCbMax: " + self.mThisCbMax.hex() +\
23095 "\n mAllMin: " + self.mAllMin.hex() +\
23096 "\n mAllMax: " + self.mAllMax.hex() +\
23097 "\n mLowestBot: " + self.mLowestBot.hex() +\
23098 "\n mHighestBot: " + self.mHighestBot.hex() +\
23099 "\n mLowestTop: " + self.mLowestTop.hex() +\
23100 "\n mHighestTop: " + self.mHighestTop.hex() +\
23101 "\n"
23102 return retStr
23103
23104 def PlotValMinMaxTrkCParseJson(self, inJson, inKeyPrefix):
23105 if PhactoriDbg(100):
23106 myDebugPrint3("PlotValMinMaxTrkCParseJson entered, key prefix is ->" + inKeyPrefix + "<-\n", 100)
23107 #self.mParseHadKeys = False
23108 keyCurrentDataRange = inKeyPrefix + 'use current data range'
23109 keyCumulativeDataRange = inKeyPrefix + 'use cumulative data range'
23110 keyRange = inKeyPrefix + 'range'
23111 keyMinimumRange = inKeyPrefix + 'minimum range'
23112 keyMaximumRange = inKeyPrefix + 'maximum range'
23113
23114 if keyCurrentDataRange in inJson:
23115 self.mUseCumulativeRange = False
23116 elif keyCumulativeDataRange in inJson:
23117 self.mUseCumulativeRange = True
23118
23119 if keyRange in inJson:
23120 range = inJson[keyRange]
23121 ff0 = float(range[0])
23122 ff1 = float(range[1])
23123 range = [ff0, ff1]
23124 if PhactoriDbg():
23125 myDebugPrint3("PlotValMinMaxTrkCParseJson got range " + str(range) + "\n")
23126 self.mLowestBot = range[0]
23127 self.mUseLowestBot = True
23128 self.mHighestBot = range[0]
23129 self.mUseHighestBot = True
23130 self.mLowestTop = range[1]
23131 self.mUseLowestTop = True
23132 self.mHighestTop = range[1]
23133 self.mUseHighestTop = True
23134 else:
23135 if keyMinimumRange in inJson:
23136 range = inJson[keyMinimumRange]
23137 ff0 = float(range[0])
23138 ff1 = float(range[1])
23139 range = [ff0, ff1]
23140 if PhactoriDbg():
23141 myDebugPrint3("PlotValMinMaxTrkCParseJson got minimum range " + str(range) + "\n")
23142 self.mHighestBot = range[0]
23143 self.mUseHighestBot = True
23144 self.mLowestTop = range[1]
23145 self.mUseLowestTop = True
23146 if keyMaximumRange in inJson:
23147 range = inJson[keyMaximumRange]
23148 ff0 = float(range[0])
23149 ff1 = float(range[1])
23150 range = [ff0, ff1]
23151 if PhactoriDbg():
23152 myDebugPrint3("PlotValMinMaxTrkCParseJson got maximum range " + str(range) + "\n")
23153 self.mLowestBot = range[0]
23154 self.mUseLowestBot = True
23155 self.mHighestTop = range[1]
23156 self.mUseHighestTop = True
23157
23158 if PhactoriDbg():
23159 myDebugPrint3(self.SelfToStr())
23160
23161 def GetMinToUse(self):
23162 return self.mMinToUse
23163
23164 def GetMaxToUse(self):
23165 return self.mMaxToUse
23166
23167 def ResetThisCb(self):
23168 "indicate we are starting a new callback search for min and max, so we\n can use the first test value as the initial min and max"
23169 self.mThisCbInitialized = False
23170 self.mThisCbMin = 0.0
23171 self.mThisCbMax = 0.0
23172
23173 def MinMaxTestAndSet(self, inTestXyz):
23174 if self.mAllInitialized:
23175 if inTestXyz < self.mAllMin:
23176 self.mAllMin = inTestXyz
23177 else:
23178 if inTestXyz > self.mAllMax:
23179 self.mAllMax = inTestXyz
23180 else:
23181 self.mAllMin = inTestXyz
23182 self.mAllMax = inTestXyz
23183 self.mAllInitialized = True
23184 if self.mThisCbInitialized:
23185 if inTestXyz < self.mThisCbMin:
23186 self.mThisCbMin = inTestXyz
23187 else:
23188 if inTestXyz > self.mThisCbMax:
23189 self.mThisCbMax = inTestXyz
23190 else:
23191 self.mThisCbMin = inTestXyz
23192 self.mThisCbMax = inTestXyz
23193 self.mThisCbInitialized = True
23194
23195 def UpdateMinMaxToUse(self):
23196 "assumes we have obtained this callback (ThisCb) mins and maxes; uses\n Initial settings and locks to determine what mins and maxes are\n now in force"
23197 if self.mUseCumulativeRange:
23198 localMin = self.mAllMin
23199 else:
23200 localMin = self.mThisCbMin
23201 if self.mUseHighestBot:
23202 if localMin > self.mHighestBot:
23203 localMin = self.mHighestBot
23204 if self.mUseLowestBot:
23205 if localMin < self.mLowestBot:
23206 localMin = self.mLowestBot
23207
23208 if self.mUseCumulativeRange:
23209 localMax = self.mAllMax
23210 else:
23211 localMax = self.mThisCbMax
23212 if self.mUseHighestTop:
23213 if localMax > self.mHighestTop:
23214 localMax = self.mHighestTop
23215 if self.mUseLowestTop:
23216 if localMax < self.mLowestTop:
23217 localMax = self.mLowestTop
23218
23219 if localMin > localMax:
23220 if self.mUseLowestBot:
23221 localMax = localMin
23222 if self.mUseHighestTop:
23223 localMin = localMax
23224 if localMin > localMax:
23225 if PhactoriDbg():
23226 myDebugPrint3("UpdateMinMaxToUse: weird case with min/max\n")
23227 localMin = localMax
23228
23229 self.mMinToUse = localMin
23230 self.mMaxToUse = localMax
23231
23232 class PlotXYZMinMaxTrkC:
23233 def __init__(self):
23234 self.mXyzTrk = []
23235 self.mXyzTrk.append(PlotValMinMaxTrkC())
23236 self.mXyzTrk.append(PlotValMinMaxTrkC())
23237 self.mXyzTrk.append(PlotValMinMaxTrkC())
23238
23239 self.currentYScaleFactor = 1.0
23240
23241 #for scaling axes, use either cumulative data range or current
23242
23243 def PlotXYZMinMaxTrkCParseJson(self, inJson, inKeyPrefix):
23244 if PhactoriDbg(100):
23245 myDebugPrint3("PlotXYZMinMaxTrkCParseJson entered, key prefix is ->" + inKeyPrefix + "<-\n", 100)
23246 xPrefix = 'x ' + inKeyPrefix
23247 yPrefix = 'y ' + inKeyPrefix
23248 zPrefix = 'z ' + inKeyPrefix
23249 self.mXyzTrk[0].PlotValMinMaxTrkCParseJson(inJson, xPrefix)
23250 self.mXyzTrk[1].PlotValMinMaxTrkCParseJson(inJson, yPrefix)
23251 self.mXyzTrk[2].PlotValMinMaxTrkCParseJson(inJson, zPrefix)
23252
23253 def GetMinToUse(self):
23254 retVal = [self.mXyzTrk[0].GetMinToUse(), self.mXyzTrk[1].GetMinToUse(), self.mXyzTrk[2].GetMinToUse()]
23255 return retVal
23256
23257 def GetMaxToUse(self):
23258 retVal = [self.mXyzTrk[0].GetMaxToUse(), self.mXyzTrk[1].GetMaxToUse(), self.mXyzTrk[2].GetMaxToUse()]
23259 return retVal
23260
23261 def ResetThisCb(self):
23262 "indicate we are starting a new callback search for min and max, so we\n can use the first test value as the initial min and max"
23263 self.mXyzTrk[0].ResetThisCb()
23264 self.mXyzTrk[1].ResetThisCb()
23265 self.mXyzTrk[2].ResetThisCb()
23266
23267 def MinMaxTestAndSet(self, inTestXyz):
23268 "test a data value and adjust recorded mins and maxes. Adjust overall\n min/max if necessary, adjust ThisCb min max if necessary, also see\n if this is first call since last ResetThisCb"
23269 self.mXyzTrk[0].MinMaxTestAndSet(inTestXyz[0])
23270 self.mXyzTrk[1].MinMaxTestAndSet(inTestXyz[1])
23271 self.mXyzTrk[2].MinMaxTestAndSet(inTestXyz[2])
23272
23273 def UpdateMinMaxToUse(self):
23274 "assumes we have obtained this callback (ThisCb) mins and maxes; uses\n Initial settings and locks to determine what mins and maxes are\n now in force"
23275 self.mXyzTrk[0].UpdateMinMaxToUse()
23276 self.mXyzTrk[1].UpdateMinMaxToUse()
23277 self.mXyzTrk[2].UpdateMinMaxToUse()
23278
23279 def SetFromRestartInfo(self, inJson):
23280 "given a map (json format), use the info in the map to set the\n state--this reads the info created out in GetRestartInfo"
23281 if len(inJson) != 3:
23282 if PhactoriDbg():
23283 myDebugPrint3("PlotXYZMinMaxTrkC::SetFromRestartInfo bad inJson\n")
23284 return
23285 self.mXyzTrk[0].SetFromRestartInfo(inJson[0])
23286 self.mXyzTrk[1].SetFromRestartInfo(inJson[1])
23287 self.mXyzTrk[2].SetFromRestartInfo(inJson[2])
23288
23289 def GetRestartInfo(self):
23290 "construct, in python map/json info from this PlotXYZMinMaxTrkC instance\n which contains the information which would be needed to restore the\n instance to the proper state after a simulation restart.\n Basically just calls the GetRestartInfo() for each underlying axis\n Return the restart info map/json"
23291 #this is a list of three items, which is an acceptable json type
23292 newJsonInfo = []
23293 newJsonInfo.append(self.mXyzTrk[0].GetRestartInfo())
23294 newJsonInfo.append(self.mXyzTrk[1].GetRestartInfo())
23295 newJsonInfo.append(self.mXyzTrk[2].GetRestartInfo())
23296 return newJsonInfo
23297
23298
23299 #class PlotColorInfo:
23300 # m_BackgroundColor = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052]
23301 # m_EdgeColor = [0.0, 0.0, 0.5000076295109483]
23302 # m_DiffuseColor = [1.0, 1.0, 1.0]
23303 # m_AmbientColor = [1.0, 1.0, 1.0]
23304 # m_SelectionColor = [1.0, 0.0, 1.0]
23305 # m_BackfaceDiffuseColor = [1.0, 1.0, 1.0]
23306 # m_CubeAxesColor = [1.0, 1.0, 1.0]
23307 # def CopyTo(self, outTarget):
23308 # outTarget.m_BackgroundColor = self.m_BackgroundColor
23309 # outTarget.m_EdgeColor = self.m_EdgeColor
23310 # outTarget.m_DiffuseColor = self.m_DiffuseColor
23311 # outTarget.m_AmbientColor = self.m_AmbientColor
23312 # outTarget.m_SelectionColor = self.m_SelectionColor
23313 # outTarget.m_BackfaceDiffuseColor = self.m_BackfaceDiffuseColor
23314 # outTarget.m_CubeAxesColor = self.m_CubeAxesColor
23315 # def SetRepresentationAndViewColors(self, ioRenderViewInfo):
23316 # myDebugPrint3('PlotColorInfo.SetRepresentationColors entered\n', 100)
23317 # rep1 = ioRenderViewInfo.DataRepresentation1
23318 # view1 = ioRenderViewInfo.RenderView1
23319 # view1.Background = self.m_BackgroundColor
23320 # rep1.EdgeColor = self.m_EdgeColor
23321 # rep1.DiffuseColor = self.m_DiffuseColor
23322 # rep1.AmbientColor = self.m_AmbientColor
23323 # rep1.SelectionColor = self.m_SelectionColor
23324 # rep1.BackfaceDiffuseColor = self.m_BackfaceDiffuseColor
23325 # rep1.CubeAxesColor = self.m_CubeAxesColor
23326 # myDebugPrint3('PlotColorInfo.SetRepresentationColors returning\n', 100)
23327
23328 #global gPlotColorInfoPreset
23329 #gPlotColorInfoPreset = PlotColorInfo()
23330
23331 global gPlotOverTimeMap
23332 gPlotOverTimeMap = {}
23333
23334 global gScatterPlotMap
23335 gScatterPlotMap = {}
23336
23337 #def SetPlotView2StartColors(
23338 # inBackgroundColor = [0.31999694819562063, 0.3400015259021897, 0.4299992370489052],
23339 # inEdgeColor = [0.0, 0.0, 0.5000076295109483],
23340 # inDiffuseColor = [1.0, 1.0, 1.0],
23341 # inAmbientColor = [1.0, 1.0, 1.0],
23342 # inSelectionColor = [1.0, 0.0, 1.0,],
23343 # inBackfaceDiffuseColor = [1.0, 1.0, 1.0],
23344 # inCubeAxesColor = [1.0, 1.0, 1.0]):
23345 # global gPlotColorInfoPreset
23346 # gPlotColorInfoPreset.m_BackgroundColor = inBackgroundColor
23347 # gPlotColorInfoPreset.m_EdgeColor = inEdgeColor
23348 # gPlotColorInfoPreset.m_DiffuseColor = inDiffuseColor
23349 # gPlotColorInfoPreset.m_AmbientColor = inAmbientColor
23350 # gPlotColorInfoPreset.m_SelectionColor = inSelectionColor
23351 # gPlotColorInfoPreset.m_BackfaceDiffuseColor = inBackfaceDiffuseColor
23352 # gPlotColorInfoPreset.m_CubeAxesColor = inBackfaceDiffuseColor
23353
23354 def UpdatePlotView2(inPlotInfo):
23355 if PhactoriDbg(100):
23356 myDebugPrint3('UpdatePlotView2 entered (' + inPlotInfo.mName + ')\n', 100)
23357 if PhactoriDbg():
23358 myDebugPrint3(' render info(' + str(inPlotInfo.m_PhactoriRenderViewInfo) + ')\n')
23359 if PhactoriDbg():
23360 myDebugPrint3(' minmax info: ' + str(inPlotInfo.m_PhactoriRenderViewInfo) + '\n')
23361 #DataXYMinMax = [0.0, 0.0, 0.0, 0.0]
23362 UpdatePipelineWithCurrentTimeArgument(
23363 inPlotInfo.mInputOperation.GetPvFilter())
23364 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
23365 SetPlotPointsFromData(inPlotInfo)
23366 UpdatePlotViewLook(inPlotInfo)
23367 if PhactoriDbg(100):
23368 myDebugPrint3('UpdatePlotView2 returning\n', 100)
23369
23370 def UpdateAllScatterPlots():
23371 if PhactoriDbg(100):
23372 myDebugPrint3('UpdateAllScatterPlots entered\n', 100)
23373 global gScatterPlotMap
23374 for ii in list(gScatterPlotMap.values()):
23375 UpdatePlotView2(ii)
23376 if PhactoriDbg(100):
23377 myDebugPrint3('UpdateAllScatterPlots returning\n', 100)
23378
23379 def UpdateOnePlotOverTime(inPlotInfo):
23380 if PhactoriDbg(100):
23381 myDebugPrint3('UpdateOnePlotOverTime entered (' + inPlotInfo.mName + ')\n', 100)
23382 if PhactoriDbg():
23383 myDebugPrint3(' render info(' + str(inPlotInfo.m_PhactoriRenderViewInfo) + ')\n')
23384 if PhactoriDbg():
23385 myDebugPrint3(' minmax info: ' + str(inPlotInfo.m_xyzMinMaxTrkC) + '\n')
23386 #DataXYMinMax = [0.0, 0.0, 0.0, 0.0]
23387 UpdatePipelineWithCurrentTimeArgument(
23388 inPlotInfo.mInputOperation.GetPvFilter())
23389 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
23390 SetPlotOverTimePointsFromData(inPlotInfo)
23391 UpdatePipelineWithCurrentTimeArgument(
23392 inPlotInfo.mInputOperation.GetPvFilter())
23393 UpdatePipelineWithCurrentTimeArgument(inPlotInfo.m_producer)
23394 UpdatePlotViewLook(inPlotInfo)
23395 if PhactoriDbg(100):
23396 myDebugPrint3('UpdateOnePlotOverTime returning\n', 100)
23397
23398 def UpdateAllPlotsOverTime():
23399 if PhactoriDbg(100):
23400 myDebugPrint3('UpdateAllPlotsOverTime entered\n', 100)
23401 global gPlotOverTimeMap
23402 for ii in list(gPlotOverTimeMap.values()):
23403 UpdateOnePlotOverTime(ii)
23404 if PhactoriDbg(100):
23405 myDebugPrint3('UpdateAllPlotsOverTime returning\n', 100)
23406
23407 def PrintAllPointsA(inPlotInfo):
23408 ppdata = inPlotInfo.m_producer.GetClientSideObject().GetOutputDataObject(0)
23409 programmableFilterPoints = ppdata.GetPoints()
23410 if PhactoriDbg():
23411 myDebugPrint3('programmableFilterPoints: ' + str(programmableFilterPoints))
23412 for ii in range(0, programmableFilterPoints.GetNumberOfPoints()):
23413 onePoint = programmableFilterPoints.GetPoint(ii)
23414 if PhactoriDbg():
23415 myDebugPrint3(str(ii) + ': ' + str(onePoint))
23416
23417 #def TryToDetectVariableCellOrElementType(inInputCsData, inVariableName, inInputIsProxy = False, inAllowGlobalVariableDetection = False):
23418 # if PhactoriDbg():
23419 # myDebugPrint3(' trying to detect variable type (node/element)\n')
23420 #
23421 # if inInputIsProxy:
23422 # pointData = inInputCsData.PointData
23423 # else:
23424 # pointData = inInputCsData.GetPointData()
23425 # if pointData != None:
23426 # testPointArray = pointData.GetArray(inVariableName)
23427 # if testPointArray != None:
23428 # if PhactoriDbg():
23429 # myDebugPrint3(' type node detected!\n')
23430 # return [True, 'node']
23431 #
23432 # if inInputIsProxy:
23433 # cellData = inInputCsData.CellData
23434 # else:
23435 # cellData = inInputCsData.GetCellData()
23436 # if cellData != None:
23437 # testCellArray = cellData.GetArray(inVariableName)
23438 # if testCellArray != None:
23439 # if PhactoriDbg():
23440 # myDebugPrint3(' type element detected!\n')
23441 # return [True, 'element']
23442 #
23443 # if inAllowGlobalVariableDetection:
23444 # if inInputIsProxy:
23445 # fieldData = inInputCsData.FieldData
23446 # else:
23447 # fieldData = inInputCsData.GetFieldData()
23448 # if fieldData != None:
23449 # testFieldArray = fieldData.GetArray(inVariableName)
23450 # if testFieldArray != None:
23451 # if PhactoriDbg():
23452 # myDebugPrint3(' type global detected!\n')
23453 # return [True, 'global']
23454 #
23455 # return [False, '']
23456
23457 def FindThisProcessorMinMaxForVarForOneBlock(inInputCsData, inVariableInfo,
23458 ioMinMaxInfo):
23459 if PhactoriDbg(100):
23460 myDebugPrint3('FindThisProcessorMinMaxForVarForOneBlock entered\n', 100)
23461 if PhactoriDbg():
23462 myDebugPrint3(' variable is ' + inVariableInfo.mVariableName + '\n')
23463
23464 #detect variable type (node/element) if necessary, and save info if detected
23465 detectResult = inVariableInfo.DetectVariableType(inInputCsData,
23466 False, False)
23467 if detectResult == False:
23468 if PhactoriDbg(100):
23469 myDebugPrint3('no detection: returning\n', 100)
23470 return
23471
23472 if(inVariableInfo.mVariableType == 'node'):
23473 cellOrPointData = inInputCsData.GetPointData()
23474 if cellOrPointData == None:
23475 if PhactoriDbg(100):
23476 myDebugPrint3('no point data: returning\n', 100)
23477 return
23478 else:
23479 cellOrPointData = inInputCsData.GetCellData()
23480 if cellOrPointData == None:
23481 if PhactoriDbg(100):
23482 myDebugPrint3('no cell data: returning\n', 100)
23483 return
23484
23485 theData = cellOrPointData.GetArray(inVariableInfo.mVariableName)
23486 if theData == None:
23487 if PhactoriDbg(100):
23488 myDebugPrint3('no theData: returning\n', 100)
23489 return
23490 if PhactoriDbg():
23491 myDebugPrint3(' theData: ' + str(theData) + '\n')
23492 if PhactoriDbg():
23493 myDebugPrint3(' theData name: ' + theData.GetName() + '\n')
23494 numTuplesX = theData.GetNumberOfTuples()
23495
23496 if numTuplesX <= 0:
23497 return
23498
23499 if ioMinMaxInfo[2] == False:
23500 if inVariableInfo.mVariableIsVectorComponent:
23501 vecVal = theData.GetTuple3(0)
23502 vv = vecVal[inVariableInfo.mVariableComponent]
23503 elif inVariableInfo.mVariableIsVectorMagnitude:
23504 vecVal = theData.GetTuple3(0)
23505 aa = vecVal[0]
23506 bb = vecVal[1]
23507 cc = vecVal[2]
23508 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23509 else:
23510 vv = theData.GetTuple1(0)
23511
23512 ioMinMaxInfo[0] = vv
23513 ioMinMaxInfo[1] = vv
23514 ioMinMaxInfo[2] = True
23515
23516 for ii in range(0, numTuplesX):
23517 if inVariableInfo.mVariableIsVectorComponent:
23518 vecVal = theData.GetTuple3(ii)
23519 vv = vecVal[inVariableInfo.mVariableComponent]
23520 elif inVariableInfo.mVariableIsVectorMagnitude:
23521 vecVal = theData.GetTuple3(ii)
23522 aa = vecVal[0]
23523 bb = vecVal[1]
23524 cc = vecVal[2]
23525 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23526 else:
23527 vv = theData.GetTuple1(ii)
23528
23529 if(vv < ioMinMaxInfo[0]):
23530 ioMinMaxInfo[0] = vv
23531 if(vv > ioMinMaxInfo[1]):
23532 ioMinMaxInfo[1] = vv
23533
23534 if PhactoriDbg():
23535 myDebugPrint3(' min max after this block: ' + str(ioMinMaxInfo) + '\n')
23536 if PhactoriDbg(100):
23537 myDebugPrint3('FindThisProcessorMinMaxForVarForOneBlock returning\n', 100)
23538
23539 def FindNodeOrElementIdForMinMaxOneBlock(inInputCsData, ioVariableInfo):
23540 if PhactoriDbg(100):
23541 myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock entered\n'
23542 ' variable is ' + ioVariableInfo.mVariableName + '\n'
23543 ' min: ' + str(ioVariableInfo.mStats.mMin) + '\n'
23544 ' max: ' + str(ioVariableInfo.mStats.mMax) + '\n', 100)
23545
23546 #detect variable type (node/element) if necessary, and save info if detected
23547 detectResult = ioVariableInfo.DetectVariableType(inInputCsData,
23548 False, True)
23549 if detectResult == False:
23550 if PhactoriDbg(100):
23551 myDebugPrint3('no detection: returning\n', 100)
23552 return
23553
23554 if(ioVariableInfo.mVariableType == 'node'):
23555 cellOrPointData = inInputCsData.GetPointData()
23556 if cellOrPointData == None:
23557 if PhactoriDbg(100):
23558 myDebugPrint3('no point data: returning\n', 100)
23559 return
23560 elif(ioVariableInfo.mVariableType == 'element'):
23561 cellOrPointData = inInputCsData.GetCellData()
23562 if cellOrPointData == None:
23563 if PhactoriDbg(100):
23564 myDebugPrint3('no cell data: returning\n', 100)
23565 return
23566 elif(ioVariableInfo.mVariableType == 'global'):
23567 cellOrPointData = inInputCsData.GetFieldData()
23568 if cellOrPointData == None:
23569 if PhactoriDbg(100):
23570 myDebugPrint3('no field data: returning\n', 100)
23571 return
23572 else:
23573 if PhactoriDbg(100):
23574 myDebugPrint3('no data type, should not be here,: returning\n', 100)
23575 return
23576
23577 varData = cellOrPointData.GetArray(ioVariableInfo.mVariableName)
23578 if varData == None:
23579 if PhactoriDbg(100):
23580 myDebugPrint3('no varData: returning\n', 100)
23581 return
23582 if PhactoriDbg():
23583 myDebugPrint3(' y data: ' + str(varData) + '\n')
23584 if PhactoriDbg():
23585 myDebugPrint3(' y data name: ' + varData.GetName() + '\n')
23586 numTuplesX = varData.GetNumberOfTuples()
23587
23588 if numTuplesX <= 0:
23589 return
23590
23591 globalIdArray = None
23592 if(ioVariableInfo.mVariableType == 'node'):
23593 globalIdArray = cellOrPointData.GetArray('GlobalNodeId')
23594 if globalIdArray == None:
23595 if PhactoriDbg():
23596 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
23597 else:
23598 globalIdArray = cellOrPointData.GetArray('GlobalElementId')
23599 if globalIdArray == None:
23600 if PhactoriDbg():
23601 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
23602
23603 for ii in range(0, numTuplesX):
23604 #vv = varData.GetTuple1(ii)
23605 if ioVariableInfo.mVariableIsVectorComponent:
23606 vecVal = varData.GetTuple3(ii)
23607 vv = vecVal[ioVariableInfo.mVariableComponent]
23608 elif ioVariableInfo.mVariableIsVectorMagnitude:
23609 vecVal = varData.GetTuple3(ii)
23610 aa = vecVal[0]
23611 bb = vecVal[1]
23612 cc = vecVal[2]
23613 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23614 else:
23615 vv = varData.GetTuple1(ii)
23616
23617 if vv == ioVariableInfo.mStats.mMin:
23618 #if ioVariableInfo.mStats.mLocalFoundMinId == False:
23619 # ioVariableInfo.mStats.mMinId = globalIdArray.GetTuple1(ii)
23620 # ioVariableInfo.mStats.mLocalFoundMinId = True
23621 # if PhactoriDbg(100):
23622 # myDebugPrint3(" found min node/element id: " + \
23623 # str(ioVariableInfo.mStats.mMinId) + "\n", 100)
23624 ioVariableInfo.mStats.mLocalMinIdCount += 1
23625 newGId = globalIdArray.GetTuple1(ii)
23626 if ioVariableInfo.mStats.mLocalMinIdCount <= 5:
23627 if PhactoriDbg(100):
23628 myDebugPrint3(" found min node/element id: " + \
23629 str(newGId) + "\n"
23630 " count: " + str(ioVariableInfo.mStats.mLocalMinIdCount) + "\n",
23631 100)
23632 if ioVariableInfo.mStats.mLocalFoundMinId == False:
23633 ioVariableInfo.mStats.mMinId = newGId
23634 ioVariableInfo.mStats.mLocalFoundMinId = True
23635 else:
23636 if newGId > ioVariableInfo.mStats.mMinId:
23637 ioVariableInfo.mStats.mMinId = newGId
23638
23639 if vv == ioVariableInfo.mStats.mMax:
23640 #if ioVariableInfo.mStats.mLocalFoundMaxId == False:
23641 # ioVariableInfo.mStats.mMaxId = globalIdArray.GetTuple1(ii)
23642 # ioVariableInfo.mStats.mLocalFoundMaxId = True
23643 # if PhactoriDbg(100):
23644 # myDebugPrint3(" found max node/element id: " + \
23645 # str(ioVariableInfo.mStats.mMaxId) + "\n", 100)
23646 ioVariableInfo.mStats.mLocalMaxIdCount += 1
23647 newGId = globalIdArray.GetTuple1(ii)
23648 if ioVariableInfo.mStats.mLocalMaxIdCount <= 5:
23649 if PhactoriDbg(100):
23650 myDebugPrint3(" found max node/element id: " + \
23651 str(newGId) + "\n"
23652 " count: " + str(ioVariableInfo.mStats.mLocalMaxIdCount) + "\n",
23653 100)
23654 if ioVariableInfo.mStats.mLocalFoundMaxId == False:
23655 ioVariableInfo.mStats.mMaxId = newGId
23656 ioVariableInfo.mStats.mLocalFoundMaxId = True
23657 else:
23658 if newGId > ioVariableInfo.mStats.mMaxId:
23659 ioVariableInfo.mStats.mMaxId = newGId
23660
23661 if PhactoriDbg(100):
23662 myDebugPrint3('FindNodeOrElementIdForMinMaxOneBlock returning\n', 100)
23663
23664 def FindNodeOrElementIdForMinMaxRecurse1(inInputCsData, ioVariableInfo):
23665 #myDebugPrint3('FindNodeOrElementIdForMinMaxRecurse1 entered\n', 100)
23666
23667 icsdClassname = inInputCsData.GetClassName()
23668 #if PhactoriDbg(100):
23669 # myDebugPrint3("icsdClassname 3: " + str(icsdClassname) + "\n")
23670 if icsdClassname == "vtkMultiBlockDataSet" or \
23671 icsdClassname == "vtkExodusIIMultiBlockDataSet":
23672 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
23673 numBlocks = inInputCsData.GetNumberOfBlocks()
23674 for ii in range(0, numBlocks):
23675 oneBlock = inInputCsData.GetBlock(ii)
23676 if(oneBlock != None):
23677 FindNodeOrElementIdForMinMaxRecurse1(oneBlock, ioVariableInfo)
23678 else:
23679 #myDebugPrint3('finding min/max: ' + icsdClassname + '\n')
23680 FindNodeOrElementIdForMinMaxOneBlock(inInputCsData, ioVariableInfo)
23681
23682 #myDebugPrint3('FindNodeOrElementIdForMinMaxRecurse1 returning\n', 100)
23683
23684 def FindNodeOrElementIdForMinMax(inputcsData, inVariableInfo):
23685 "fairly complex high level mpi-operation routine. Takes a variable,\n finds the min/max (global) and finds a node id or element id corresponding\n to the node or element for both the min and the max value. Has some\n intelligence to avoid recaculating and doing mpi communication if the\n information had already been found for this catalyst callback"
23686
23687 if PhactoriDbg(100):
23688 myDebugPrint3("FindNodeOrElementIdForMinMax entered: " + \
23689 str(inVariableInfo.mVariableName) + "\n", 100)
23690
23691 #if already been done for this catalyst callback, just return
23692 if inVariableInfo.mStats.mIdsTestCounter == \
23693 gPipeAndViewsState.mFrameTagCounter:
23694 if PhactoriDbg(100):
23695 myDebugPrint3("already calculated for this callback, returning\n", 100)
23696 return
23697
23698 #if variable is global, this shouldn't be called
23699 if inVariableInfo.mVariableType == "global":
23700 myDebugPrint3AndException("FindNodeOrElementIdForMinMax:\n"
23701 "this should not be called with global variable " + \
23702 inVariableInfo.mVariableName + "\n")
23703
23704 #first get the min/max for the variable if necessary
23705 if inVariableInfo.mStats.mStatsTestCounter != \
23706 gPipeAndViewsState.mFrameTagCounter:
23707 if PhactoriDbg(100):
23708 myDebugPrint3("min/max not available, calculating\n", 100)
23709 DataMinMax = [0.0, 0.0, False]
23710 DataSumCnt = [0.0, 0]
23711 FindMinMaxSumCntFromData(inputcsData, inVariableInfo,
23712 None, DataMinMax, DataSumCnt,
23713 None, None)
23714 else:
23715 if PhactoriDbg(100):
23716 myDebugPrint3("min/max previously calculated\n", 100)
23717
23718 #next, get the local node/element id, if any, which contain min and max
23719 #values
23720 inVariableInfo.mStats.mLocalFoundMinId = False
23721 inVariableInfo.mStats.mLocalMinIdCount = 0
23722 inVariableInfo.mStats.mMinId = -1
23723 inVariableInfo.mStats.mLocalFoundMaxId = False
23724 inVariableInfo.mStats.mLocalMaxIdCount = 0
23725 inVariableInfo.mStats.mMaxId = -1
23726 FindNodeOrElementIdForMinMaxRecurse1(inputcsData, inVariableInfo)
23727
23728 #now get every process to agree on which node or element id contains the
23729 #max and min value; for multiple instances we choose the id with the highest
23730 #integer value
23731 idForMinAndidForMax = [inVariableInfo.mStats.mMinId,
23732 inVariableInfo.mStats.mMaxId]
23733 UseReduceToGetMaximumIntegers(idForMinAndidForMax)
23734 inVariableInfo.mStats.mMinId = idForMinAndidForMax[0]
23735 inVariableInfo.mStats.mMaxId = idForMinAndidForMax[1]
23736
23737 #mark done for this catalyst callback, so we won't do extra mpi
23738 #communication if we call this routine again
23739 inVariableInfo.mStats.mIdsTestCounter = gPipeAndViewsState.mFrameTagCounter
23740
23741 if PhactoriDbg(100):
23742 myDebugPrint3(
23743 "counter: " + str(inVariableInfo.mStats.mIdsTestCounter) + "\n"
23744 "min: " + str(inVariableInfo.mStats.mMin) + "\n"
23745 "at id: " + str(inVariableInfo.mStats.mMinId) + "\n"
23746 "max: " + str(inVariableInfo.mStats.mMax) + "\n"
23747 "at id: " + str(inVariableInfo.mStats.mMaxId) + "\n"
23748 "FindNodeOrElementIdForMinMax returning\n")
23749
23750 def FindMinMaxSumCntFromDataOneBlock(inInputCsData, ioVariableInfo,
23751 ioSecondaryVariableInfo, ioDataMinMax, ioDataSumCnt,
23752 ioDataForIds, inPlotLineList):
23753 if PhactoriDbg(100):
23754 myDebugPrint3('FindMinMaxSumCntFromDataOneBlock entered\n', 100)
23755
23756 if PhactoriDbg():
23757 myDebugPrint3(' y axis variable is ' + ioVariableInfo.mVariableName + '\n')
23758
23759 #detect variable type (node/element) if necessary, and save info if detected
23760 detectResult = ioVariableInfo.DetectVariableType(inInputCsData,
23761 False, True)
23762 if detectResult == False:
23763 if PhactoriDbg(100):
23764 myDebugPrint3('no detection: returning\n', 100)
23765 return
23766
23767 if ioSecondaryVariableInfo != None:
23768 ioSecondaryVariableInfo.CopyVariableTypeFrom(ioVariableInfo)
23769
23770 if(ioVariableInfo.mVariableType == 'node'):
23771 cellOrPointData = inInputCsData.GetPointData()
23772 if cellOrPointData == None:
23773 if PhactoriDbg(100):
23774 myDebugPrint3('no point data: returning\n', 100)
23775 return
23776 elif(ioVariableInfo.mVariableType == 'element'):
23777 cellOrPointData = inInputCsData.GetCellData()
23778 if cellOrPointData == None:
23779 if PhactoriDbg(100):
23780 myDebugPrint3('no cell data: returning\n', 100)
23781 return
23782 elif(ioVariableInfo.mVariableType == 'global'):
23783 cellOrPointData = inInputCsData.GetFieldData()
23784 if cellOrPointData == None:
23785 if PhactoriDbg(100):
23786 myDebugPrint3('no field data: returning\n', 100)
23787 return
23788 else:
23789 if PhactoriDbg(100):
23790 myDebugPrint3('no data type, should not be here,: returning\n', 100)
23791 return
23792
23793 #print all element names
23794 #myDebugPrint3('printing array names:\n')
23795 #numCellArrays = cellOrPointData.GetNumberOfArrays()
23796 #for ii in range(0, numCellArrays):
23797 # myDebugPrint3(str(ii) + ": " + cellOrPointData.GetArray(ii).GetName() + "\n")
23798
23799 yData = cellOrPointData.GetArray(ioVariableInfo.mVariableName)
23800 if yData == None:
23801 if PhactoriDbg(100):
23802 myDebugPrint3('no yData: returning\n', 100)
23803 return
23804 if PhactoriDbg():
23805 myDebugPrint3(' y data: ' + str(yData) + '\n')
23806 if PhactoriDbg():
23807 myDebugPrint3(' y data name: ' + yData.GetName() + '\n')
23808 numTuplesX = yData.GetNumberOfTuples()
23809
23810 if numTuplesX <= 0:
23811 return
23812
23813 if ioDataMinMax[2] == False:
23814 #vv = yData.GetTuple1(0)
23815 if ioVariableInfo.mVariableIsVectorComponent:
23816 vecVal = yData.GetTuple3(0)
23817 vv = vecVal[ioVariableInfo.mVariableComponent]
23818 elif ioVariableInfo.mVariableIsVectorMagnitude:
23819 vecVal = yData.GetTuple3(0)
23820 aa = vecVal[0]
23821 bb = vecVal[1]
23822 cc = vecVal[2]
23823 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23824 else:
23825 vv = yData.GetTuple1(0)
23826
23827 ioDataMinMax[0] = vv
23828 ioDataMinMax[1] = vv
23829 ioDataMinMax[2] = True
23830
23831 for ii in range(0, numTuplesX):
23832 #vv = yData.GetTuple1(ii)
23833 if ioVariableInfo.mVariableIsVectorComponent:
23834 vecVal = yData.GetTuple3(ii)
23835 vv = vecVal[ioVariableInfo.mVariableComponent]
23836 elif ioVariableInfo.mVariableIsVectorMagnitude:
23837 vecVal = yData.GetTuple3(ii)
23838 aa = vecVal[0]
23839 bb = vecVal[1]
23840 cc = vecVal[2]
23841 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23842 else:
23843 vv = yData.GetTuple1(ii)
23844
23845 if(vv < ioDataMinMax[0]):
23846 ioDataMinMax[0] = vv
23847 if(vv > ioDataMinMax[1]):
23848 ioDataMinMax[1] = vv
23849 ioDataSumCnt[0] += vv
23850 ioDataSumCnt[1] += 1
23851
23852 if ioDataForIds != None:
23853 numIds = len(inPlotLineList)
23854 globalIdArray = None
23855 if(ioVariableInfo.mVariableType == 'node'):
23856 globalIdArray = cellOrPointData.GetArray('GlobalNodeId')
23857 if globalIdArray == None:
23858 if PhactoriDbg():
23859 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
23860 else:
23861 globalIdArray = cellOrPointData.GetArray('GlobalElementId')
23862 if globalIdArray == None:
23863 if PhactoriDbg():
23864 myDebugPrint3(' no GlobalNodeId to find ids in list\n')
23865 if globalIdArray != None:
23866 for ii in range(0, numIds):
23867 thisIdPlotLine = inPlotLineList[ii]
23868 idToFind = thisIdPlotLine.m_Id
23869 if PhactoriDbg():
23870 myDebugPrint3(' trying to find id: ' + str(idToFind) + '\n')
23871 if thisIdPlotLine.m_FoundOnThisProcessorLastTime == True:
23872 if inInputCsData == thisIdPlotLine.m_FoundBlockRef:
23873 idFromMesh = globalIdArray.GetTuple1(thisIdPlotLine.m_FoundIndex)
23874 if idFromMesh == idToFind:
23875 if PhactoriDbg():
23876 myDebugPrint3(' found id ' + str(idToFind) + ' on this processor again no search\n')
23877 #vv = yData.GetTuple1(thisIdPlotLine.m_FoundIndex)
23878 if ioVariableInfo.mVariableIsVectorComponent:
23879 vecVal = yData.GetTuple3(thisIdPlotLine.m_FoundIndex)
23880 vv = vecVal[ioVariableInfo.mVariableComponent]
23881 elif ioVariableInfo.mVariableIsVectorMagnitude:
23882 vecVal = yData.GetTuple3(thisIdPlotLine.m_FoundIndex)
23883 aa = vecVal[0]
23884 bb = vecVal[1]
23885 cc = vecVal[2]
23886 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23887 else:
23888 vv = yData.GetTuple1(thisIdPlotLine.m_FoundIndex)
23889 ioDataForIds[ii] = vv
23890 #go on to next id
23891 continue
23892 else:
23893 thisIdPlotLine.m_FoundOnThisProcessorLastTime = False
23894 for jj in range(0, numTuplesX):
23895 idFromMesh = globalIdArray.GetTuple1(jj)
23896 if idFromMesh == idToFind:
23897 if PhactoriDbg():
23898 myDebugPrint3(' found id ' + str(idToFind) + ' on this processor\n')
23899 #vv = yData.GetTuple1(jj)
23900 if ioVariableInfo.mVariableIsVectorComponent:
23901 vecVal = yData.GetTuple3(jj)
23902 vv = vecVal[ioVariableInfo.mVariableComponent]
23903 elif ioVariableInfo.mVariableIsVectorMagnitude:
23904 vecVal = yData.GetTuple3(jj)
23905 aa = vecVal[0]
23906 bb = vecVal[1]
23907 cc = vecVal[2]
23908 vv = math.sqrt(aa*aa + bb*bb + cc*cc)
23909 else:
23910 vv = yData.GetTuple1(jj)
23911 ioDataForIds[ii] = vv
23912 thisIdPlotLine.m_FoundOnThisProcessorLastTime = True
23913 thisIdPlotLine.m_FoundBlockRef = inInputCsData
23914 thisIdPlotLine.m_FoundIndex = jj
23915
23916 if PhactoriDbg():
23917 myDebugPrint3(' min max after this block: ' + str(ioDataMinMax) + '\n')
23918
23919 if PhactoriDbg(100):
23920 myDebugPrint3('FindMinMaxSumCntFromDataOneBlock returning\n', 100)
23921
23922
23923 def SetPlotPointsFromOneBlock(inInputCsData, ioPlotInfo, ioIndex):
23924 if PhactoriDbg(100):
23925 myDebugPrint3('SetPlotPointsFromOneBlock entered\n', 100)
23926 if PhactoriDbg():
23927 myDebugPrint3(' x axis variable: ' + ioPlotInfo.m_XAxisVariableInfo.mVariableName + \
23928 '\n y axis varaible: ' + ioPlotInfo.m_YAxisVariableInfo.mVariableName + '\n')
23929
23930 #detect variable type (node/element) if necessary, and save info if detected
23931 detectResult = ioPlotInfo.m_YAxisVariableInfo.DetectVariableType(
23932 inInputCsData, False, False)
23933 if detectResult == False:
23934 if PhactoriDbg(100):
23935 myDebugPrint3('no detection: returning\n', 100)
23936 return
23937
23938 ioPlotInfo.m_XAxisVariableInfo.CopyVariableTypeFrom(
23939 ioPlotInfo.m_YAxisVariableInfo)
23940
23941 if(ioPlotInfo.m_YAxisVariableInfo.mVariableType == 'node'):
23942 cellOrPointData = inInputCsData.GetPointData()
23943 if cellOrPointData == None:
23944 if PhactoriDbg(100):
23945 myDebugPrint3('no point data: returning\n', 100)
23946 return
23947 else:
23948 cellOrPointData = inInputCsData.GetCellData()
23949 if cellOrPointData == None:
23950 if PhactoriDbg(100):
23951 myDebugPrint3('no cell data: returning\n', 100)
23952 return
23953 #nodeData = inClientSideData.GetNodeData()
23954
23955
23956 #print all element names
23957 #myDebugPrint3('printing array names:\n')
23958 #numCellArrays = cellOrPointData.GetNumberOfArrays()
23959 #for ii in range(0, numCellArrays):
23960 # myDebugPrint3(str(ii) + ": " + cellOrPointData.GetArray(ii).GetName() + "\n")
23961
23962
23963 xData = cellOrPointData.GetArray(ioPlotInfo.m_XAxisVariableInfo.mVariableName)
23964 yData = cellOrPointData.GetArray(ioPlotInfo.m_YAxisVariableInfo.mVariableName)
23965 if xData == None:
23966 if PhactoriDbg(100):
23967 myDebugPrint3('no xData: returning\n', 100)
23968 return
23969 if yData == None:
23970 if PhactoriDbg(100):
23971 myDebugPrint3('no yData: returning\n', 100)
23972 return
23973 if PhactoriDbg():
23974 myDebugPrint3(' x data: ' + str(xData) + ' y data: ' + str(yData) + '\n')
23975 if PhactoriDbg():
23976 myDebugPrint3(' x data name: ' + xData.GetName() + ' y data name : ' + yData.GetName() + '\n')
23977 numTuplesX = xData.GetNumberOfTuples()
23978 numTuplesY = yData.GetNumberOfTuples()
23979
23980 if numTuplesX != numTuplesY:
23981 if PhactoriDbg():
23982 myDebugPrint3('number of tuples do not match in SetPlotPointsFromOneBlock')
23983 return
23984
23985 if 1:
23986 ptListCount = numTuplesX
23987 if ptListCount > 100:
23988 ptListCount = 100
23989 for jj in range(0, ptListCount):
23990 if PhactoriDbg():
23991 myDebugPrint3(' cell ' + str(jj) + ': ' + str(xData.GetTuple1(jj)) + ' data: ' + str(yData.GetTuple1(jj)) + '\n')
23992
23993 outOutputPoints = ioPlotInfo.m_Points
23994
23995 #myDebugPrint3('ioIndex is ' + str(ioIndex))
23996 #myDebugPrint3('outOutputPoints is ' + str(outOutputPoints))
23997 #myDebugPrint3('outOutputPoints number of points is ' + str(outOutputPoints.GetNumberOfPoints()))
23998
23999 localIndex = ioIndex[0]
24000 for ii in range(0, numTuplesX):
24001
24002 if ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorComponent:
24003 vecVal = xData.GetTuple3(ii)
24004 xx = vecVal[ioPlotInfo.m_XAxisVariableInfo.mVariableComponent]
24005 elif ioPlotInfo.m_XAxisVariableInfo.mVariableIsVectorMagnitude:
24006 vecVal = xData.GetTuple3(ii)
24007 aa = vecVal[0]
24008 bb = vecVal[1]
24009 cc = vecVal[2]
24010 xx = math.sqrt(aa*aa + bb*bb + cc*cc)
24011 else:
24012 xx = xData.GetTuple1(ii)
24013
24014 if ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorComponent:
24015 vecVal = yData.GetTuple3(ii)
24016 yy = vecVal[ioPlotInfo.m_YAxisVariableInfo.mVariableComponent]
24017 elif ioPlotInfo.m_YAxisVariableInfo.mVariableIsVectorMagnitude:
24018 vecVal = yData.GetTuple3(ii)
24019 aa = vecVal[0]
24020 bb = vecVal[1]
24021 cc = vecVal[2]
24022 yy = math.sqrt(aa*aa + bb*bb + cc*cc)
24023 else:
24024 yy = yData.GetTuple1(ii)
24025
24026 zz = 0.0
24027 if localIndex < outOutputPoints.GetNumberOfPoints():
24028 if PhactoriDbg():
24029 myDebugPrint3(' sppfob changing existing point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\n')
24030 outOutputPoints.SetPoint(localIndex, xx, yy, zz)
24031 else:
24032 if PhactoriDbg():
24033 myDebugPrint3(' sppfob inserting new point ' + str(localIndex) +': ' + str(xx) + ', ' + str(yy) + ', ' + str(zz) + '\n')
24034 outOutputPoints.InsertPoint(localIndex, xx, yy, zz)
24035 localIndex += 1
24036 ioIndex[0] = localIndex
24037 #PrintAllPointsA()
24038 if PhactoriDbg(100):
24039 myDebugPrint3('SetPlotPointsFromOneBlock returning\n', 100)
24040
24041 def FindMinMaxSumCntFromDataRecurse1(inInputCsData, ioVariableInfo,
24042 ioSecondaryVariableInfo, ioDataMinMax, ioDataSumCnt,
24043 ioDataForIds, inPlotIdLineList):
24044 #myDebugPrint3('FindMinMaxSumCntFromDataRecurse1 entered\n', 100)
24045
24046 icsdClassname = inInputCsData.GetClassName()
24047 #if PhactoriDbg(100):
24048 # myDebugPrint3("icsdClassname 4: " + str(icsdClassname) + "\n")
24049 if icsdClassname == "vtkMultiBlockDataSet" or \
24050 icsdClassname == "vtkExodusIIMultiBlockDataSet":
24051 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
24052 numBlocks = inInputCsData.GetNumberOfBlocks()
24053 for ii in range(0, numBlocks):
24054 oneBlock = inInputCsData.GetBlock(ii)
24055 if(oneBlock != None):
24056 FindMinMaxSumCntFromDataRecurse1(oneBlock,
24057 ioVariableInfo, ioSecondaryVariableInfo,
24058 ioDataMinMax, ioDataSumCnt, ioDataForIds, inPlotIdLineList)
24059 else:
24060 #myDebugPrint3('finding min/max: ' + icsdClassname + '\n')
24061 FindMinMaxSumCntFromDataOneBlock(inInputCsData,
24062 ioVariableInfo, ioSecondaryVariableInfo,
24063 ioDataMinMax, ioDataSumCnt, ioDataForIds, inPlotIdLineList)
24064
24065 #myDebugPrint3(' min max after this recursion: ' + str(ioDataMinMax) + '\n')
24066
24067 #myDebugPrint3('FindMinMaxFromDataSumCntRecurse1 returning\n', 100)
24068
24069
24070 def FindThisProcessorMinMaxForVarRecurse1(inInputCsData, inVariableInfo, ioMinMaxInfo):
24071 #myDebugPrint3('FindThisProcessorMinMaxForVarRecurse1 entered\n', 100)
24072
24073 icsdClassname = inInputCsData.GetClassName()
24074 #if PhactoriDbg(100):
24075 # myDebugPrint3("icsdClassname 5: " + str(icsdClassname) + "\n")
24076 if icsdClassname == "vtkMultiBlockDataSet" or \
24077 icsdClassname == "vtkExodusIIMultiBlockDataSet":
24078 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
24079 numBlocks = inInputCsData.GetNumberOfBlocks()
24080 for ii in range(0, numBlocks):
24081 oneBlock = inInputCsData.GetBlock(ii)
24082 if(oneBlock != None):
24083 FindThisProcessorMinMaxForVarRecurse1(oneBlock, inVariableInfo, ioMinMaxInfo)
24084 elif icsdClassname == "vtkPartitionedDataSet":
24085 numPartitions = inInputCsData.GetNumberOfPartitions()
24086 for ii in range(0, numPartitions):
24087 onePartition = inInputCsData.GetPartition(ii)
24088 if(onePartition != None):
24089 FindThisProcessorMinMaxForVarRecurse1(onePartition, inVariableInfo, ioMinMaxInfo)
24090 elif icsdClassname == "vtkMultiPieceDataSet":
24091 numPieces = inInputCsData.GetNumberOfPieces()
24092 for ii in range(0, numPieces):
24093 onePiece = inInputCsData.GetPiece(ii)
24094 if(onePiece != None):
24095 FindThisProcessorMinMaxForVarRecurse1(onePiece, inVariableInfo, ioMinMaxInfo)
24096 else:
24097 FindThisProcessorMinMaxForVarForOneBlock(inInputCsData, inVariableInfo, ioMinMaxInfo)
24098 #myDebugPrint3('FindThisProcessorMinMaxForVarRecurse1 returning\n', 100)
24099
24100 def SetPlotPointsFromDataRecurse1(inInputCsData, ioPlotInfo, ioIndex):
24101 #myDebugPrint3('SetPlotPointsFromDataRecurse1 entered\n', 100)
24102
24103 icsdClassname = inInputCsData.GetClassName()
24104 #if PhactoriDbg(100):
24105 # myDebugPrint3("icsdClassname 6: " + str(icsdClassname) + "\n")
24106 if icsdClassname == "vtkMultiBlockDataSet" or \
24107 icsdClassname == "vtkExodusIIMultiBlockDataSet":
24108 #myDebugPrint3('recursing: ' + icsdClassname + '\n')
24109 numBlocks = inInputCsData.GetNumberOfBlocks()
24110 for ii in range(0, numBlocks):
24111 oneBlock = inInputCsData.GetBlock(ii)
24112 if(oneBlock != None):
24113 SetPlotPointsFromDataRecurse1(oneBlock, ioPlotInfo, ioIndex)
24114 else:
24115 #myDebugPrint3('making points: ' + icsdClassname + '\n')
24116 SetPlotPointsFromOneBlock(inInputCsData, ioPlotInfo, ioIndex)
24117 #myDebugPrint3('SetPlotPointsFromDataRecurse1 returning\n', 100)
24118
24119 def FindPlotXyzMinMaxPtLst(inPlotPointsList, ioPlotXYZMinMaxTrkC):
24120 if len(inPlotPointsList) < 1:
24121 errStr = 'FindPlotXyzMinMaxPtLst needs to have at least one item in list'
24122 if PhactoriDbg():
24123 myDebugPrint3(errStr)
24124 raise Exception(errStr)
24125
24126 #if ioPlotXYZMinMaxTrkC.mThisDbInitized == False)
24127 # myDebugPrint3('no points, returning\n', 100)
24128 # return
24129
24130 firstPointForInitialization = None
24131 for onePointGroup in inPlotPointsList:
24132 if onePointGroup.GetNumberOfPoints() > 0:
24133 firstPointForInitialization = onePointGroup.GetPoint(0)
24134 break
24135
24136 if firstPointForInitialization == None:
24137 if PhactoriDbg(100):
24138 myDebugPrint3('no points, returning\n', 100)
24139 return
24140
24141 ioPlotXYZMinMaxTrkC.ResetThisCb()
24142
24143 if PhactoriDbg():
24144 myDebugPrint3(' xyzminmax C incoming: \n' \
24145 ' x: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax) + '\n' \
24146 ' y: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax) + '\n' \
24147 ' z: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax) + '\n' \
24148 ' xot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMax) + '\n' \
24149 ' yot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMax) + '\n' \
24150 ' zot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMax) + '\n' \
24151 )
24152 if PhactoriDbg():
24153 myDebugPrint3(str(ioPlotXYZMinMaxTrkC))
24154
24155 for onePointGroup in inPlotPointsList:
24156 numPoints = onePointGroup.GetNumberOfPoints()
24157 for ii in range(0, numPoints):
24158 onePoint = onePointGroup.GetPoint(ii)
24159 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet(onePoint)
24160
24161 xmin = ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin
24162 ymin = ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin
24163 zmin = ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin
24164 xmax = ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax
24165 ymax = ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax
24166 zmax = ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax
24167 minmaxlist = [xmin, xmax, ymin, ymax, zmin, zmax]
24168 UseReduceToGetMinMaxPairs(minmaxlist)
24169 xmin = minmaxlist[0]
24170 xmax = minmaxlist[1]
24171 ymin = minmaxlist[2]
24172 ymax = minmaxlist[3]
24173 zmin = minmaxlist[4]
24174 zmax = minmaxlist[5]
24175
24176 UseReduceToGetMinMaxPairs(minmaxlist)
24177 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet([xmin, ymin, zmin])
24178 ioPlotXYZMinMaxTrkC.MinMaxTestAndSet([xmax, ymax, zmax])
24179
24180 ioPlotXYZMinMaxTrkC.UpdateMinMaxToUse()
24181
24182 if PhactoriDbg():
24183 myDebugPrint3(' xyzminmax C outgoing: \n' \
24184 ' x: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mThisCbMax) + '\n' \
24185 ' y: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mThisCbMax) + '\n' \
24186 ' z: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mThisCbMax) + '\n' \
24187 ' xot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[0].mAllMax) + '\n' \
24188 ' yot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[1].mAllMax) + '\n' \
24189 ' zot: ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMin) + ', ' + str(ioPlotXYZMinMaxTrkC.mXyzTrk[2].mAllMax) + '\n' \
24190 )
24191 if PhactoriDbg():
24192 myDebugPrint3(str(ioPlotXYZMinMaxTrkC))
24193
24194
24195 def FindPlotXYZMinMax(inPlotPoints, ioPlotXYZMinMaxTrkC):
24196 FindPlotXyzMinMaxPtLst([inPlotPoints], ioPlotXYZMinMaxTrkC)
24197
24198 def ScalePlotYForFit(ioPlotPts, ioPlotXYZMinMaxTrkC, inAspectRatio):
24199
24200 xyzmin = ioPlotXYZMinMaxTrkC.GetMinToUse()
24201 xmin = xyzmin[0]
24202 ymin = xyzmin[1]
24203 zmin = xyzmin[2]
24204 xyzmax = ioPlotXYZMinMaxTrkC.GetMaxToUse()
24205 xmax = xyzmax[0]
24206 ymax = xyzmax[1]
24207 zmax = xyzmax[2]
24208
24209 xSpan = xmax - xmin
24210 ySpan = ymax - ymin
24211 if PhactoriDbg():
24212 myDebugPrint3('xSpan: ' + str(xSpan) + ' ySpan: ' + str(ySpan))
24213 yScaleFactor = 1.0
24214 if PhactoriDbg():
24215 myDebugPrint3('inAspectRatio: ' + str(inAspectRatio) + '\n')
24216
24217 if xSpan > 0.0:
24218 if ySpan > 0.0:
24219 yScaleFactor = xSpan / ySpan
24220 yScaleFactor /= inAspectRatio
24221
24222 ioPlotXYZMinMaxTrkC.currentYScaleFactor = yScaleFactor
24223 if PhactoriDbg():
24224 myDebugPrint3('yScaleFactor: ' + str(yScaleFactor))
24225
24226 numPoints = ioPlotPts.GetNumberOfPoints()
24227 for ii in range(0, numPoints):
24228 onePoint = ioPlotPts.GetPoint(ii)
24229 xx = onePoint[0]
24230 yy = onePoint[1]
24231 zz = onePoint[2]
24232 ioPlotPts.SetPoint(ii, xx, yy*yScaleFactor, zz)
24233
24234 def FindThisProcessorMinMaxForVar(inOperation, inVariableInfo):
24235
24236 myDataMinMax = [0.0, 0.0, False]
24237 pvClientSideData = inOperation.GetPvFilter().GetClientSideObject().GetOutputDataObject(0)
24238 if pvClientSideData == None:
24239 if PhactoriDbg(100):
24240 myDebugPrint3('pvClientSideData is None, returning', 100)
24241 return myDataMinMax
24242
24243 FindThisProcessorMinMaxForVarRecurse1(pvClientSideData, inVariableInfo, myDataMinMax)
24244
24245 return myDataMinMax
24246
24247
24248 def FindMinMaxSumCntFromData(inputcsData, inVariableInfo,
24249 inSecondaryVariableInfo, DataMinMax, DataSumCnt,
24250 DataForIds, inPlotIdLineList):
24251 "fairly complex high level mpi-operation routine. This takes a paraview\n filter client side object, gets the client side data\n (which is presumably a multiblock\n dataset) and finds the min, max, sum, and count of items for a variable.\n It uses MPI (if the item is not global) to share values and get them\n across all processors. Used for plotting min/max/mean and for evaluating\n boolean criteria (such as whether or not to produce images) for min/max\n /mean/count. Data return is a bit messy and should be updated--it fills\n in DataMinMax, DataSumCnt, and DataForIds if it is not None"
24252
24253 if PhactoriDbg():
24254 myDebugPrint3("FindMinMaxSumCntFromData entered\n")
24255
24256 FindMinMaxSumCntFromDataRecurse1(inputcsData, inVariableInfo,
24257 inSecondaryVariableInfo, DataMinMax, DataSumCnt,
24258 DataForIds, inPlotIdLineList)
24259
24260 #if variable is global, it is same on all processors so we don't need to do
24261 #any mpi communication
24262 if inVariableInfo.mVariableType != 'global':
24263 #do mpi to share values around
24264 UseReduceToSumDoubleAndIntPair(DataSumCnt)
24265 if DataSumCnt[1] == 0:
24266 #no data; we shouldn't add anything to plot lines
24267 if PhactoriDbg(100):
24268 myDebugPrint3('no data for variable; returning\n', 100)
24269 return
24270
24271 #bad situation; if we have no data on this processor we don't want
24272 #it to mess up other processors min/max
24273 if DataMinMax[2] == False:
24274 DataMinMax[0] = sys.float_info.max
24275 DataMinMax[1] = -sys.float_info.max
24276
24277 UseReduceToGetMinMaxPairs(DataMinMax)
24278 if DataForIds != None:
24279 UseReduceToSpreadValues(DataForIds)
24280
24281 if PhactoriDbg():
24282 myDebugPrint3('min/max result: ' + str(DataMinMax) + '\n')
24283 if PhactoriDbg():
24284 myDebugPrint3(' sum result: ' + str(DataSumCnt[0]) + ' count result: ' + str(DataSumCnt[1]) + '\n')
24285 #myDebugPrint3(' average result: ' + str(DataSumCnt[0]/DataSumCnt[1]) + '\n')
24286 if PhactoriDbg():
24287 myDebugPrint3(' average result: ' + \
24288 str(DataSumCnt[0]/float(DataSumCnt[1])) + '\n')
24289 if PhactoriDbg():
24290 myDebugPrint3('DataForIds result: ' + str(DataForIds) + '\n')
24291
24292 inVariableInfo.mStats.mMin = DataMinMax[0]
24293 inVariableInfo.mStats.mMax = DataMinMax[1]
24294 inVariableInfo.mStats.mSum = DataSumCnt[0]
24295 inVariableInfo.mStats.mCount = DataSumCnt[1]
24296 inVariableInfo.mStats.mStatsTestCounter = \
24297 gPipeAndViewsState.mFrameTagCounter
24298
24299 if PhactoriDbg():
24300 myDebugPrint3("FindMinMaxSumCntFromData returning\n")
24301
24302
24303 def SetPlotOverTimePointsFromData(ioPlotInfo):
24304 if PhactoriDbg(100):
24305 myDebugPrint3("SetPlotOverTimePointsFromData entered\n", 100)
24306 if PhactoriDbg(100):
24307 myDebugPrint3("variable is: " + str(ioPlotInfo.m_YAxisVariableInfo.mVariableName) + "\n", 100)
24308
24309 inputcsData = ioPlotInfo.mInputOperation.GetPvFilter().GetClientSideObject().GetOutputDataObject(0)
24310 if inputcsData == None:
24311 if PhactoriDbg(100):
24312 myDebugPrint3('inputcsData is None, returning', 100)
24313 return
24314
24315 if PhactoriDbg():
24316 myDebugPrint3('finding min/max for data for this processor at this timestep\n')
24317 DataMinMax = [0.0, 0.0, False]
24318 DataSumCnt = [0.0, 0]
24319
24320 numIds = len(ioPlotInfo.m_IdPlotLineList)
24321 if numIds > 0:
24322 DataForIds = []
24323 for ii in range(0, numIds):
24324 DataForIds.append(0.0)
24325 else:
24326 DataForIds = None
24327
24328 FindMinMaxSumCntFromData(inputcsData,
24329 ioPlotInfo.m_YAxisVariableInfo, ioPlotInfo.m_XAxisVariableInfo,
24330 DataMinMax, DataSumCnt, DataForIds, ioPlotInfo.m_IdPlotLineList)
24331
24332 if DataSumCnt[1] == 0:
24333 if PhactoriDbg(100):
24334 myDebugPrint3('num elements in data is 0, returning', 100)
24335 return
24336
24337 global gPipeAndViewsState
24338 plotPointTime = gPipeAndViewsState.CurrentDatadescription.GetTime()
24339
24340 #append time to time column
24341 ioPlotInfo.m_TimeColumn.AppendPlotValue(plotPointTime)
24342
24343 #append max value to plot
24344 plotDataVal = DataMinMax[1]
24345 ioPlotInfo.m_MaxPlotLine.AppendPlotValue(plotDataVal)
24346
24347 #append min value to plot
24348 #plotDataVal = -0.1*(DataMinMax[0] + DataMinMax[1])
24349 plotDataVal = DataMinMax[0]
24350 ioPlotInfo.m_MinPlotLine.AppendPlotValue(plotDataVal)
24351
24352 #append mean value to plot
24353 #ioPlotInfo.m_MeanPlotLine.AppendPlotValue(plotPointTime,
24354 # DataSumCnt[0]/DataSumCnt[1])
24355 plotDataVal = DataSumCnt[0]/float(DataSumCnt[1])
24356 ioPlotInfo.m_MeanPlotLine.AppendPlotValue(DataSumCnt[0]/float(DataSumCnt[1]))
24357
24358 if PhactoriDbg():
24359 myDebugPrint3("ioPlotInfo.m_vtkTable numcols B:" + str(ioPlotInfo.m_vtkTable.GetNumberOfColumns()) + "\n")
24360 myDebugPrint3("ioPlotInfo.m_vtkTable numrows B:" + str(ioPlotInfo.m_vtkTable.GetNumberOfRows()) + "\n")
24361
24362 #append node or element values (by id) to plot lines for each id
24363 numIdValues = len(ioPlotInfo.m_IdPlotLineList)
24364 for ii in range(0,numIdValues):
24365 ioPlotInfo.m_IdPlotLineList[ii].m_PlotColumn.AppendPlotValue(DataForIds[ii])
24366
24367 if PhactoriDbg():
24368 myDebugPrint3(' done updating ids\n')
24369
24370
24371 def SetPlotPointsFromData(ioPlotInfo):
24372 if PhactoriDbg(100):
24373 myDebugPrint3("SetPlotPointsFromData entered\n", 100)
24374
24375 inputcsData = ioPlotInfo.mInputOperation.GetPvFilter().\
24376 GetClientSideObject().GetOutputDataObject(0)
24377 if inputcsData == None:
24378 if PhactoriDbg(100):
24379 myDebugPrint3('inputcsData is None, returning', 100)
24380 return
24381
24382 plotPointIndex = [0]
24383 #myDebugPrint3(' inputcsData: ' + str(inputcsData) + '\n')
24384 #if ioPlotInfo.mVariableType == 'element':
24385 # cellOrPointFlag = 0
24386 #elif ioPlotInfo.mVariableType == 'node':
24387 # cellOrPointFlag = 1
24388 #else:
24389 # errStr = 'SetPlotPointsFromData error! can only handle element or node variable types for now'
24390 # myDebugPrint3(errStr)
24391 # raise Exception(errStr)
24392 #SetPlotPointsFromDataRecurse1(inputcsData, ioPlotInfo,
24393 # cellOrPointFlag, plotPointIndex)
24394 SetPlotPointsFromDataRecurse1(inputcsData, ioPlotInfo, plotPointIndex)
24395
24396 plotPts = ioPlotInfo.m_Points
24397 numPts = plotPts.GetNumberOfPoints()
24398 #myDebugPrint3(' need to update ids, get number of points: ' + str(numPts) + '\n')
24399
24400 ioPlotInfo.m_Vertex.GetPointIds().SetNumberOfIds(numPts)
24401
24402 for i in range(0,numPts):
24403 #Add the points to the line. The first value indicates
24404 #the order of the point on the line. The second value
24405 #is a reference to a point in a vtkPoints object. Depends
24406 #on the order that Points were added to vtkPoints object.
24407 #Note that this will not be associated with actual points
24408 #until it is added to a vtkPolyData object which holds a
24409 #vtkPoints object.
24410 #print str(i)
24411 ioPlotInfo.m_Vertex.GetPointIds().SetId(i, i)
24412
24413 ioPlotInfo.m_PolyData.Reset()
24414 ioPlotInfo.m_PolyData.SetPoints(plotPts)
24415 ioPlotInfo.m_PolyData.InsertNextCell(ioPlotInfo.m_Vertex.GetCellType(), ioPlotInfo.m_Vertex.GetPointIds())
24416
24417 #ioPlotInfo.m_PolyData.Modified()
24418
24419 #using ScatterPlot() now
24420 #ioPlotInfo.m_producer.GetClientSideObject().SetOutput(None)
24421 #ioPlotInfo.m_producer.GetClientSideObject().SetOutput(ioPlotInfo.m_PolyData)
24422
24423 #myDebugPrint3(' done updating ids\n')
24424
24425
24426
24427 FindPlotXYZMinMax(plotPts, ioPlotInfo.m_xyzMinMaxTrkC)
24428 ScalePlotYForFit(plotPts, ioPlotInfo.m_xyzMinMaxTrkC,
24429 ioPlotInfo.mImageSettings.GetAspectRatioInsidePixelBorder())
24430
24431 #find x and y min and max for data (current and over time)
24432
24433 #myDebugPrint3('before--->')
24434 #PrintAllPointsA()
24435
24436 #for ii in range(0,130):
24437 # onePoint = plotPts.GetPoint(ii)
24438 # xx = onePoint[0]
24439 # yy = onePoint[1]
24440 # #yy -= 10.0
24441 # yy = 50.0
24442 # zz = onePoint[2]
24443 # plotPts.SetPoint(ii, xx, yy, zz)
24444 #myDebugPrint3('after--->')
24445 if PhactoriDbg():
24446 myDebugPrint3("points in plot after updating\n")
24447 #PrintAllPointsA(ioPlotInfo)
24448 if PhactoriDbg(100):
24449 myDebugPrint3("SetPlotPointsFromData returning\n", 100)
24450
24451 def CreateOnePlotOverTimeProducerC(ioPlotOverTime):
24452 if PhactoriDbg(100):
24453 myDebugPrint3('CreateOnePlotOverTimeProducerC entered (' + ioPlotOverTime.mName + ')\n', 100)
24454
24455 global gPlotOverTimeMap
24456
24457 #ioPlotOverTime.m_YAxisVariableName = ioinYAxisVariableName
24458 #ioPlotOverTime.m_CellOrPointOrGlobalFlag = inCellOrPointOrGlobalFlag
24459
24460 UpdatePipelineWithCurrentTimeArgument(
24461 ioPlotOverTime.mInputOperation.GetPvFilter())
24462
24463 savedActiveSource = GetActiveSource()
24464
24465 if PhactoriDbg():
24466 myDebugPrint3('before active source: ' + str(savedActiveSource) + "\n")
24467
24468 SetActiveSource(ioPlotOverTime.mInputOperation.GetPvFilter())
24469
24470 ioPlotOverTime.m_vtkTable = vtk.vtkTable()
24471
24472 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_TimeColumn.m_TableColumn)
24473
24474 if ioPlotOverTime.mPlotMaximumFlag:
24475 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MaxPlotLine.m_TableColumn)
24476 if ioPlotOverTime.mPlotMinimumFlag:
24477 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MinPlotLine.m_TableColumn)
24478 if ioPlotOverTime.mPlotMeanFlag:
24479 ioPlotOverTime.m_vtkTable.AddColumn(ioPlotOverTime.m_MeanPlotLine.m_TableColumn)
24480
24481 if PhactoriDbg():
24482 myDebugPrint3("ioPlotOverTime.m_vtkTable numcols A:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfColumns()) + "\n")
24483 myDebugPrint3("ioPlotOverTime.m_vtkTable numrows A:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfRows()) + "\n")
24484
24485 if PhactoriDbg():
24486 myDebugPrint3("initializing id plot lines (" + str(len(ioPlotOverTime.m_IdPlotLineList)) + ")\n")
24487 for oneIdPlotLine in ioPlotOverTime.m_IdPlotLineList:
24488 if PhactoriDbg():
24489 myDebugPrint3(" doing line for id " + str(oneIdPlotLine.m_Id) + "\n")
24490 ioPlotOverTime.m_vtkTable.AddColumn(oneIdPlotLine.m_PlotColumn.m_TableColumn)
24491
24492 producer = PVTrivialProducer()
24493 #producer.GetClientSideObject().SetOutput(ioPlotOverTime.m_PolyData)
24494
24495 myDebugPrint3("ioPlotOverTime.m_vtkTable numcols C:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfColumns()) + "\n")
24496 myDebugPrint3("ioPlotOverTime.m_vtkTable numrows C:" + str(ioPlotOverTime.m_vtkTable.GetNumberOfRows()) + "\n")
24497 producer.GetClientSideObject().SetOutput(ioPlotOverTime.m_vtkTable)
24498
24499 ioPlotOverTime.m_producer = producer
24500
24501 UpdatePipelineWithCurrentTimeArgument(
24502 ioPlotOverTime.mInputOperation.GetPvFilter())
24503 UpdatePipelineWithCurrentTimeArgument(ioPlotOverTime.m_producer)
24504 SetPlotOverTimePointsFromData(ioPlotOverTime)
24505 UpdatePipelineWithCurrentTimeArgument(ioPlotOverTime.m_producer)
24506 if PhactoriDbg():
24507 myDebugPrint3('done filter output 2nd time:')
24508 if PhactoriDbg():
24509 myDebugPrint3('After 2nd update pipeline in CreatePlotOverTimeProducer:')
24510 #PrintAllPointsA(ioPlotOverTime)
24511
24512 #print ' active source after filter before reset: ' + str(GetActiveSource())
24513 SetActiveSource(savedActiveSource)
24514 if PhactoriDbg():
24515 myDebugPrint3('ioPlotOverTime.m_producer.GetDataInformation().GetBounds():\n' + str(ioPlotOverTime.m_producer.GetDataInformation().GetBounds()) + '\n')
24516
24517 gPlotOverTimeMap[ioPlotOverTime.mName] = ioPlotOverTime
24518 if PhactoriDbg():
24519 myDebugPrint3('gPlotOverTimeMap has ' + str(len(gPlotOverTimeMap)) + ' items\n')
24520 count = 0
24521 for ii in list(gPlotOverTimeMap.values()):
24522 if PhactoriDbg():
24523 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
24524 if PhactoriDbg():
24525 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
24526 count += 1
24527
24528 AddFilterToFilterMap(ioPlotOverTime.mName, ioPlotOverTime.m_producer)
24529
24530 if PhactoriDbg(100):
24531 myDebugPrint3('CreateOnePlotOverTimeProducerC returning\n', 100)
24532
24533
24534 def CreateOneScatterPlotProducerC(ioScatterPlot):
24535 if PhactoriDbg(100):
24536 myDebugPrint3('CreateOneScatterPlotProducerC entered (' + ioScatterPlot.mName + ')\n', 100)
24537
24538 global gScatterPlotMap
24539
24540 #needs to change to source specified
24541
24542 UpdatePipelineWithCurrentTimeArgument(
24543 ioScatterPlot.mInputOperation.GetPvFilter())
24544
24545 savedActiveSource = GetActiveSource()
24546 if PhactoriDbg():
24547 myDebugPrint3('before active source: ' + str(savedActiveSource) + "\n")
24548
24549 SetActiveSource(ioScatterPlot.mInputOperation.GetPvFilter())
24550
24551 #create poly data to use
24552 ioScatterPlot.m_PolyData = vtk.vtkPolyData()
24553 #ioScatterPlot.m_PolyLine = vtk.vtkPolyLine()
24554 ioScatterPlot.m_Points = vtk.vtkPoints()
24555 ioScatterPlot.m_Vertex = vtk.vtkVertex()
24556
24557 #numPts = 100
24558 #numPts = 1
24559 numPts = 0
24560 if PhactoriDbg():
24561 myDebugPrint3('numPts: ' + str(numPts) + "\n")
24562
24563 for ii in range(0, numPts):
24564 xx = float(ii) / float(numPts)
24565 yy = (float(ii) * float(ii)) / (float(numPts) * float(numPts))
24566 zz = 0.0
24567 ioScatterPlot.m_Points.InsertPoint(ii, xx,yy,zz)
24568 ioScatterPlot.m_PolyData.SetPoints(ioScatterPlot.m_Points)
24569
24570 #ioScatterPlot.m_PolyLine.GetPointIds().SetNumberOfIds(numPts)
24571 ioScatterPlot.m_Vertex.GetPointIds().SetNumberOfIds(numPts)
24572
24573 for i in range(0,numPts):
24574 #Add the points to the line. The first value indicates
24575 #the order of the point on the line. The second value
24576 #is a reference to a point in a vtkPoints object. Depends
24577 #on the order that Points were added to vtkPoints object.
24578 #Note that this will not be associated with actual points
24579 #until it is added to a vtkPolyData object which holds a
24580 #vtkPoints object.
24581 #print str(i)
24582 #ioScatterPlot.m_PolyLine.GetPointIds().SetId(i, i)
24583 ioScatterPlot.m_Vertex.GetPointIds().SetId(i, i)
24584
24585 ioScatterPlot.m_PolyData.Allocate(1, 1)
24586 ioScatterPlot.m_PolyData.InsertNextCell(ioScatterPlot.m_Vertex.GetCellType(),
24587 ioScatterPlot.m_Vertex.GetPointIds())
24588
24589 #producer = PVTrivialProducer()
24590 #producer.GetClientSideObject().SetOutput(ioScatterPlot.m_PolyData)
24591 ioScatterPlot.m_MergeBlocks = MergeBlocks(Input=ioScatterPlot.mInputOperation.GetPvFilter())
24592 producer = ScatterPlot(Input=ioScatterPlot.m_MergeBlocks)
24593
24594 if PhactoriDbg():
24595 csdoobj = producer.GetClientSideObject().GetOutputDataObject(0)
24596 myDebugPrint3("csdoobj: " + str(csdoobj) + "\n")
24597 myDebugPrint3("csdoobj.GetNumberOfPoints(): " + str(csdoobj.GetNumberOfPoints()) + "\n")
24598 myDebugPrint3("csdoobj.GetNumberOfCells(): " + str(csdoobj.GetNumberOfCells()) + "\n")
24599
24600 ioScatterPlot.m_producer = producer
24601
24602 UpdatePipelineWithCurrentTimeArgument(
24603 ioScatterPlot.mInputOperation.GetPvFilter())
24604 ioScatterPlot.ChooseDefaultVariableIfNecessary()
24605 UpdatePipelineWithCurrentTimeArgument(ioScatterPlot.m_producer)
24606 SetPlotPointsFromData(ioScatterPlot)
24607 UpdatePipelineWithCurrentTimeArgument(ioScatterPlot.m_producer)
24608 if PhactoriDbg():
24609 myDebugPrint3('done filter output 2nd time:')
24610 if PhactoriDbg():
24611 myDebugPrint3('After 2nd update pipeline in CreateScatterPlotProducer:')
24612 #PrintAllPointsA(ioScatterPlot)
24613
24614 #print ' active source after filter before reset: ' + str(GetActiveSource())
24615 SetActiveSource(savedActiveSource)
24616 if PhactoriDbg():
24617 myDebugPrint3('ioScatterPlot.m_producer.GetDataInformation().GetBounds():\n' + str(ioScatterPlot.m_producer.GetDataInformation().GetBounds()) + '\n')
24618
24619 gScatterPlotMap[ioScatterPlot.mName] = ioScatterPlot
24620 if PhactoriDbg():
24621 myDebugPrint3('gScatterPlotMap has ' + str(len(gScatterPlotMap)) + ' items\n')
24622 count = 0
24623 for ii in list(gScatterPlotMap.values()):
24624 if PhactoriDbg():
24625 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
24626 if PhactoriDbg():
24627 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
24628 count += 1
24629
24630 AddFilterToFilterMap(ioScatterPlot.mName, ioScatterPlot.m_producer)
24631
24632 if PhactoriDbg(100):
24633 myDebugPrint3('CreateOneScatterPlotProducerC returning\n', 100)
24634
24635
24636 def CreateOneScatterPlotViewC(ioScatterPlot):
24637 if PhactoriDbg(100):
24638 myDebugPrint3('CreateOneScatterPlotViewC entered (' + ioScatterPlot.mName + ')\n', 100)
24639 saveActiveSource = GetActiveSource()
24640 saveActiveView = GetActiveView()
24641 global currentPhactoriRenderViewInfo
24642 saveCurrentInfo = currentPhactoriRenderViewInfo
24643
24644 SetActiveSource(ioScatterPlot.m_producer)
24645
24646 #global gDefaultImageSizeX
24647 #global gDefaultImageSizeY
24648 #plot_view_setup_1 = { \
24649 # 'camera_setup': {'look_direction': [0.0, 0.0, -1.0] }, \
24650 # 'show_color_legend': False, \
24651 # 'show_data_cube_axes': True, \
24652 # 'show_orientation_axes': True, \
24653 # 'image_settings' : { \
24654 # 'basename': ioScatterPlot.mName, \
24655 # 'size': [gDefaultImageSizeX, gDefaultImageSizeY] \
24656 # }, \
24657 # }
24658 #
24659 #CreateViewSetFromPhactoriViewMapB(plot_view_setup_1)
24660
24661 ioScatterPlot.mCamera.mName = 'dummyscatterplotcamera'
24662 ioScatterPlot.mCamera.mType = 'camera'
24663 ioScatterPlot.mCamera.mLookAtDistanceType = 'datasize relative'
24664 ioScatterPlot.mCamera.mLookDirection = [0.0, 0.0, -1.0]
24665 ioScatterPlot.mCamera.mLookAtDistance = 1.0
24666
24667 if ioScatterPlot.mImageSettings.mUsingDefaultGeneratedImageBasename:
24668 imageBasename = ioScatterPlot.mName
24669 extraImagenameItem = "sctr."
24670 else:
24671 imageBasename = ioScatterPlot.mImageSettings.mImageBasename
24672 extraImagenameItem = ""
24673
24674 SetUpOneParaViewRepresentationAndViewC(ioScatterPlot.mCamera,
24675 [0.0, 0.0, -1.0],
24676 inImagesetInfo = ioScatterPlot,
24677 inColorSettingsX = ioScatterPlot.mColorSettings,
24678 inMeshRenderControl = 'Surface With Edges',
24679 inShowDataCubeAxes = True,
24680 inShowDataCubeAxesInfo = ioScatterPlot.m_DataCubeAxesInfo,
24681 inShowOrientationAxes = False,
24682 inFixedColorRange = None,
24683 inIsPlotFlag = True,
24684 inRepresentationFilenameAddon = "",
24685 inLookDirectionFilenameAddon = extraImagenameItem,
24686 inPhactoriRepresentation = None)
24687
24688 global gScatterPlotMap
24689 #myDebugPrint3('qqxxqq gScatterPlotMap has ' + str(len(gScatterPlotMap)) + ' items\n')
24690 count = 0
24691 for ii in list(gScatterPlotMap.values()):
24692 if PhactoriDbg():
24693 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
24694 if PhactoriDbg():
24695 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
24696 count += 1
24697
24698 if ioScatterPlot.mName in gScatterPlotMap:
24699 thePlot = gScatterPlotMap[ioScatterPlot.mName]
24700 thePlot.m_PhactoriRenderViewInfo = currentPhactoriRenderViewInfo
24701
24702 #set up colors based .on preset and then set DataRepresentation colors
24703 #global gPlotColorInfoPreset
24704 #gPlotColorInfoPreset.CopyTo(thePlot.m_plotColorInfo)
24705 #thePlot.m_plotColorInfo.SetRepresentationAndViewColors(
24706 # thePlot.m_PhactoriRenderViewInfo)
24707 #thePlot.mColorSettings.SetParaviewRvRepColors(
24708 # thePlot.m_PhactoriRenderViewInfo.RenderView1,
24709 # thePlot.m_PhactoriRenderViewInfo.DataRepresentation1)
24710
24711 UpdatePlotViewLook(thePlot)
24712 else:
24713 if PhactoriDbg():
24714 myDebugPrint3('error 3 making scatter plot')
24715
24716 SetActiveSource(saveActiveSource)
24717 SetActiveView(saveActiveView)
24718 currentPhactoriRenderViewInfo = saveCurrentInfo
24719 if PhactoriDbg(100):
24720 myDebugPrint3('CreateOneScatterPlotViewC returning\n', 100)
24721
24722 #phactori_combine_to_single_python_file_parent_1
24723 #from Operation.PhactoriMpiUtilities import *
24724 #phactori_combine_to_single_python_file_subpiece_begin_1
24725
24726 global BarrierLockCount
24727 BarrierLockCount = 0
24728 def BarrierLock(tagString = ""):
24729 "called to sync up all processes"
24730 global BarrierLockCount
24731 BarrierLockCount += 1
24732 numProcs = SmartGetNumberOfProcesses()
24733 myPid = SmartGetLocalProcessId()
24734 localIntList = [myPid]
24735 if PhactoriDbg(100):
24736 myDebugPrint3("BarrierLock A " + str(BarrierLockCount) + " " + tagString + "\n")
24737 globalPidSumList = UseReduceOnIntegerList(localIntList, 2)
24738 if PhactoriDbg(100):
24739 myDebugPrint3("BarrierLock B " + str(BarrierLockCount) + " " + tagString + "\n")
24740
24741 def UseReduceOnFloatList(inFloatList, inAllReduceType):
24742 "inAllReduceType 0-max 1-min 2-sum"
24743 #if PhactoriDbg(100):
24744 # myDebugPrint3("UseReduceOnFloatList entered " + str(inAllReduceType) + "\n", 100)
24745
24746 #if PhactoriDbg(100):
24747 # myDebugPrint3("num values: " + str(len(inFloatList)) + "\n")
24748 # if len(inFloatList) > 0:
24749 # myDebugPrint3("local first: " + str(inFloatList[0]) + " last: " + str(inFloatList[-1]) + "\n")
24750
24751 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
24752 globalController = pm.GetGlobalController()
24753
24754 numVals = len(inFloatList)
24755 localarray = vtk.vtkDoubleArray()
24756 localarray.SetNumberOfTuples(numVals)
24757 globalarray = vtk.vtkDoubleArray()
24758 globalarray.SetNumberOfTuples(numVals)
24759
24760 for idx, oneVal in enumerate(inFloatList):
24761 localarray.SetValue(idx, oneVal)
24762
24763 globalController.AllReduce(localarray, globalarray, inAllReduceType)
24764
24765 returnArray = []
24766 for idx in range(0, numVals):
24767 returnArray.append(globalarray.GetTuple1(idx))
24768
24769 #if PhactoriDbg(100):
24770 # if len(returnArray) > 0:
24771 # myDebugPrint3("global first: " + str(returnArray[0]) + " last: " + str(returnArray[-1]) + "\n")
24772
24773 #if PhactoriDbg(100):
24774 # myDebugPrint3("UseReduceOnFloatList returning\n", 100)
24775 return returnArray
24776
24777 def UseReduceOnIntegerList(inIntegerList, inAllReduceType):
24778 #if PhactoriDbg(100):
24779 # myDebugPrint3("UseReduceOnIntegerList entered\n", 100)
24780
24781 #if PhactoriDbg(100):
24782 # myDebugPrint3("num values: " + str(len(inIntegerList)) + "\n")
24783 # if len(inIntegerList) > 0:
24784 # myDebugPrint3("local first: " + str(inIntegerList[0]) + " last: " + str(inIntegerList[-1]) + "\n")
24785
24786 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
24787 globalController = pm.GetGlobalController()
24788
24789 numVals = len(inIntegerList)
24790 localarray = vtk.vtkIntArray()
24791 localarray.SetNumberOfTuples(numVals)
24792 globalarray = vtk.vtkIntArray()
24793 globalarray.SetNumberOfTuples(numVals)
24794
24795 for idx, oneVal in enumerate(inIntegerList):
24796 localarray.SetValue(idx, oneVal)
24797
24798 globalController.AllReduce(localarray, globalarray, inAllReduceType)
24799
24800 returnArray = []
24801 for idx in range(0, numVals):
24802 returnArray.append(int(globalarray.GetTuple1(idx)))
24803
24804 #if PhactoriDbg(100):
24805 # if len(returnArray) > 0:
24806 # myDebugPrint3("global first: " + str(returnArray[0]) + " last: " + str(returnArray[-1]) + "\n")
24807
24808 #if PhactoriDbg(100):
24809 # myDebugPrint3("UseReduceOnIntegerList returning\n", 100)
24810 return returnArray
24811
24812 def UseMpiToShareAllProcessArraySizes(inArray):
24813 if PhactoriDbg(100):
24814 myDebugPrint3("UseMpiToShareAllProcessArraySizes entered\n", 100)
24815 numProcs = SmartGetNumberOfProcesses()
24816 myPid = SmartGetLocalProcessId()
24817
24818 localArraySize = []
24819 for ii in range(0, numProcs):
24820 localArraySize.append(int(0))
24821
24822 localArraySize[myPid] = int(len(inArray))
24823 globalArraySize = UseReduceOnIntegerList(localArraySize, 0)
24824 if PhactoriDbg(100):
24825 myDebugPrint3(str(localArraySize) + "\n")
24826 myDebugPrint3(str(globalArraySize) + "\n")
24827 myDebugPrint3("UseMpiToShareAllProcessArraySizes returning\n", 100)
24828 return globalArraySize
24829
24830 def UseMpiToSendAllProcessesFloatArrayToOneProcess(thisProcessFloatArray, pidToCollectArray):
24831 "given a float array on this process, send the float arrays from all\n processes to the process pidToCollectArray. Gets sizes from all\n processes first and then uses reduce to send it all"
24832
24833 if PhactoriDbg(100):
24834 myDebugPrint3("UseMpiToSendAllProcessesFloatArrayToOneProcess entered\n", 100)
24835
24836 numProcs = SmartGetNumberOfProcesses()
24837 myPid = SmartGetLocalProcessId()
24838
24839 globalArraySize = UseMpiToShareAllProcessArraySizes(thisProcessFloatArray)
24840
24841 localFloatArray = []
24842 for pidIndex, oneSize in enumerate(globalArraySize):
24843 if pidIndex == myPid:
24844 for vv in thisProcessFloatArray:
24845 localFloatArray.append(vv)
24846 else:
24847 for cnt1 in range(0, oneSize):
24848 localFloatArray.append(0.0)
24849
24850 #we really don't need to use AllReduce here, just Reduce to one process
24851 #fix later
24852 globalFloatArray = UseReduceOnFloatList(localFloatArray, 2)
24853
24854 #we really should only have value for pidToCollectArray
24855 if myPid == pidToCollectArray:
24856 retVal = globalFloatArray
24857 else:
24858 retVal = []
24859
24860 if PhactoriDbg(100):
24861 if len(globalFloatArray) == 0:
24862 myDebugPrint3(str(len(globalFloatArray)) + "\n")
24863 else:
24864 myDebugPrint3(str(len(globalFloatArray)) + " " + str(globalFloatArray[0]) + " " + str(globalFloatArray[-1]) + "\n")
24865 myDebugPrint3("UseMpiToSendAllProcessesFloatArrayToOneProcess returning\n", 100)
24866 return retVal
24867
24868 def UseMpiToSendAllProcessesIntArrayToOneProcess(thisProcessIntArray, pidToCollectArray):
24869 "given a int array on this process, send the int arrays from all\n processes to the process pidToCollectArray. Gets sizes from all\n processes first and then uses reduce to send it all"
24870 if PhactoriDbg(100):
24871 myDebugPrint3("UseMpiToSendAllProcessesintArrayToOneProcess entered\n", 100)
24872 numProcs = SmartGetNumberOfProcesses()
24873 myPid = SmartGetLocalProcessId()
24874
24875 globalArraySize = UseMpiToShareAllProcessArraySizes(thisProcessIntArray)
24876
24877 localIntArray = []
24878 for pidIndex, oneSize in enumerate(globalArraySize):
24879 if pidIndex == myPid:
24880 for vv in thisProcessIntArray:
24881 localIntArray.append(vv)
24882 else:
24883 for cnt1 in range(0, oneSize):
24884 localIntArray.append(int(0))
24885
24886 #we really don't need to use AllReduce here, just Reduce to one process
24887 #fix later
24888 globalIntArray = UseReduceOnIntegerList(localIntArray, 2)
24889
24890 #we really should only have value for pidToCollectArray
24891 if myPid == pidToCollectArray:
24892 retVal = globalIntArray
24893 else:
24894 retVal = []
24895
24896 if PhactoriDbg(100):
24897 if len(globalIntArray) == 0:
24898 myDebugPrint3(str(len(globalIntArray)) + "\n")
24899 else:
24900 myDebugPrint3(str(len(globalIntArray)) + " " + str(globalIntArray[0]) + " " + str(globalIntArray[-1]) + "\n")
24901 myDebugPrint3("UseMpiToSendAllProcessesintArrayToOneProcess returning\n", 100)
24902 return retVal
24903
24904 def ReadAndMpiBroadcastJsonFile(inJsonFileName):
24905 "given a json format file, read in the contents using the python json\n library on process zero, use MPI to broadcast the contents to all\n processes (via converting to a long char string)"
24906 if SmartGetLocalProcessId() == 0:
24907 #process zero loads json script and broadcasts
24908 returnJson = HandleJsonScriptLoadProcessZero(inJsonFileName)
24909 else:
24910 #other processes receive json script
24911 returnJson = HandleJsonScriptLoadProcessNotZero()
24912 return returnJson
24913
24914 #phactori_combine_to_single_python_file_subpiece_end_1
24915
24916 def UseReduceToSumDoubleAndIntPair(ioDoubleAndIntPair):
24917 if PhactoriDbg(100):
24918 myDebugPrint3("UseReduceToSumDoubleAndIntPair entered\n", 100)
24919 if PhactoriDbg():
24920 myDebugPrint3(" local double: " + str(ioDoubleAndIntPair[0]) + " local int: " + str(ioDoubleAndIntPair[1]) + "\n")
24921 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
24922 globalController = pm.GetGlobalController()
24923
24924 localarray = vtk.vtkDoubleArray()
24925 localarray.SetNumberOfTuples(1)
24926 globalarray = vtk.vtkDoubleArray()
24927 globalarray.SetNumberOfTuples(1)
24928 localarray.SetValue(0, ioDoubleAndIntPair[0])
24929
24930 #fixed bug here; 0 argument is mpi find max, while 2 argument is mpi sum
24931 #which is what we want here
24932 #globalController.AllReduce(localarray, globalarray, 0)
24933 globalController.AllReduce(localarray, globalarray, 2)
24934 ioDoubleAndIntPair[0] = globalarray.GetTuple1(0)
24935
24936 localarray = vtk.vtkIntArray()
24937 localarray.SetNumberOfTuples(1)
24938 globalarray = vtk.vtkIntArray()
24939 globalarray.SetNumberOfTuples(1)
24940 localarray.SetValue(0, ioDoubleAndIntPair[1])
24941 globalController.AllReduce(localarray, globalarray, 2)
24942 ioDoubleAndIntPair[1] = globalarray.GetTuple1(0)
24943
24944 if PhactoriDbg():
24945 myDebugPrint3(" reduced double: " + str(ioDoubleAndIntPair[0]) + " reduced int: " + str(ioDoubleAndIntPair[1]) + "\n")
24946
24947 def UseReduceToGetMaximumIntegers(ioListOfMaximumIntegers):
24948 if PhactoriDbg(100):
24949 myDebugPrint3("UseReduceToGetMaximums entered\n", 100)
24950 myDebugPrint3(" local ioListOfMaximumIntegers: " +
24951 str(ioListOfMaximumIntegers) + "\n")
24952 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
24953 globalController = pm.GetGlobalController()
24954 numMaxes = len(ioListOfMaximumIntegers)
24955 localarray = vtk.vtkIntArray()
24956 localarray.SetNumberOfTuples(numMaxes)
24957 for ii in range(0, numMaxes):
24958 localarray.SetValue(ii, int(ioListOfMaximumIntegers[ii]))
24959 globalarray = vtk.vtkIntArray()
24960 globalarray.SetNumberOfTuples(numMaxes)
24961 globalController.AllReduce(localarray, globalarray, 0)
24962 for ii in range(0, numMaxes):
24963 ioListOfMaximumIntegers[ii] = globalarray.GetTuple1(ii)
24964
24965 if PhactoriDbg():
24966 myDebugPrint3(" global ioListOfMaximumIntegers: " +
24967 str(ioListOfMaximumIntegers) + "\n")
24968
24969 def UseReduceToGetMinMaxPairs(ioListOfMinMaxPairs):
24970 if PhactoriDbg(100):
24971 myDebugPrint3("UseReduceToGetMinMaxPairs entered\n", 100)
24972 pm = paraview.servermanager.vtkProcessModule.GetProcessModule()
24973 globalController = pm.GetGlobalController()
24974 numPairs = len(ioListOfMinMaxPairs) // 2
24975 localarray = vtk.vtkDoubleArray()
24976 localarray.SetNumberOfTuples(numPairs*2)
24977 # we negate mins so we can do a single MPI_MAX reduce
24978 for ii in range(0, numPairs):
24979 ndx1 = ii*2
24980 localarray.SetValue(ndx1, -ioListOfMinMaxPairs[ndx1])
24981 ndx1 += 1
24982 localarray.SetValue(ndx1, ioListOfMinMaxPairs[ndx1])
24983 globalarray = vtk.vtkDoubleArray()
24984 globalarray.SetNumberOfTuples(numPairs*2)
24985 globalController.AllReduce(localarray, globalarray, 0)
24986 if PhactoriDbg():
24987 myDebugPrint3(" local minmax pairs: " + str(ioListOfMinMaxPairs) + "\n")
24988 for ii in range(0, numPairs):
24989 ndx1 = ii*2
24990 ioListOfMinMaxPairs[ndx1] = -globalarray.GetTuple1(ndx1)
24991 ndx1 += 1
24992 ioListOfMinMaxPairs[ndx1] = globalarray.GetTuple1(ndx1)
24993 if PhactoriDbg():
24994 myDebugPrint3(" global minmax pairs: " + str(ioListOfMinMaxPairs) + "\n")
24995 if PhactoriDbg(100):
24996 myDebugPrint3("UseReduceToGetMinMaxPairs returning\n", 100)
24997
24998 #set the 3d viewpoint to look at the xy scatter plot
24999 def UpdatePlotViewLook(inPlotInfo):
25000 return
25001
25002 def CreateOnePlotOverTimeViewC(ioPlotOverTime):
25003 if PhactoriDbg(100):
25004 myDebugPrint3('CreateOnePlotOverTimeViewC entered (' + ioPlotOverTime.mName + ')\n', 100)
25005 saveActiveSource = GetActiveSource()
25006 saveActiveView = GetActiveView()
25007 global currentPhactoriRenderViewInfo
25008 saveCurrentInfo = currentPhactoriRenderViewInfo
25009
25010 SetActiveSource(ioPlotOverTime.m_producer)
25011
25012 #global gDefaultImageSizeX
25013 #global gDefaultImageSizeY
25014 #plot_view_setup_1 = { \
25015 # 'camera_setup': {'look_direction': [0.0, 0.0, -1.0] }, \
25016 # 'show_color_legend': False, \
25017 # 'show_data_cube_axes': True, \
25018 # 'show_orientation_axes': True, \
25019 # 'image_settings' : { \
25020 # 'basename': ioPlotOverTime.mName, \
25021 # 'size': [gDefaultImageSizeX, gDefaultImageSizeY], \
25022 # }, \
25023 # }
25024
25025 #CreateViewSetFromPhactoriViewMapB(plot_view_setup_1)
25026
25027 ioPlotOverTime.mCamera.mName = 'dummyscatterplotcamera'
25028 ioPlotOverTime.mCamera.mType = 'camera'
25029 ioPlotOverTime.mCamera.mLookAtDistanceType = 'datasize relative'
25030 ioPlotOverTime.mCamera.mLookDirection = [0.0, 0.0, -1.0]
25031 ioPlotOverTime.mCamera.mLookAtDistance = 1.0
25032
25033 if ioPlotOverTime.mImageSettings.mUsingDefaultGeneratedImageBasename:
25034 imageBasename = ioPlotOverTime.mName
25035 extraImagenameItem = "plot."
25036 else:
25037 imageBasename = ioPlotOverTime.mImageSettings.mImageBasename
25038 extraImagenameItem = ""
25039
25040 if PhactoriDbg():
25041 myDebugPrint3(" use specific y axis label: " + str(ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mUseLabelFlag) + "\n")
25042 if ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mUseLabelFlag:
25043 if PhactoriDbg():
25044 myDebugPrint3(" specific y axis label: " + str(ioPlotOverTime.m_DataCubeAxesInfo.mYAxisInfo.mAxisLabel) + "\n")
25045
25046 SetUpOneParaViewRepresentationAndViewC(ioPlotOverTime.mCamera,
25047 [0.0, 0.0, -1.0],
25048 inImagesetInfo = ioPlotOverTime,
25049 inColorSettingsX = ioPlotOverTime.mColorSettings,
25050 inMeshRenderControl = 'Surface With Edges',
25051 inShowDataCubeAxes = True,
25052 inShowDataCubeAxesInfo = ioPlotOverTime.m_DataCubeAxesInfo,
25053 inShowOrientationAxes = False,
25054 inFixedColorRange = None,
25055 inIsPlotFlag = True,
25056 inRepresentationFilenameAddon = "",
25057 inLookDirectionFilenameAddon = extraImagenameItem,
25058 inPhactoriRepresentation = None)
25059
25060
25061 global gPlotOverTimeMap
25062 if PhactoriDbg():
25063 myDebugPrint3('qqxxqq gPlotOverTimeMap has ' + str(len(gPlotOverTimeMap)) + ' items\n')
25064 count = 0
25065 for ii in list(gPlotOverTimeMap.values()):
25066 if PhactoriDbg():
25067 myDebugPrint3(str(count) + ': ' + str(ii) + '\n')
25068 if PhactoriDbg():
25069 myDebugPrint3(str(count) + ': ' + ii.mName + '\n')
25070 count += 1
25071
25072 if ioPlotOverTime.mName in gPlotOverTimeMap:
25073 thePlot = gPlotOverTimeMap[ioPlotOverTime.mName]
25074
25075 UpdatePlotViewLook(thePlot)
25076 else:
25077 if PhactoriDbg():
25078 myDebugPrint3('error 3 making plot over time')
25079
25080 SetActiveSource(saveActiveSource)
25081 SetActiveView(saveActiveView)
25082 currentPhactoriRenderViewInfo = saveCurrentInfo
25083 if PhactoriDbg(100):
25084 myDebugPrint3('CreateOnePlotOverTimeViewC returning\n', 100)
25085
25086 global gPhactoriPipeRootMap
25087 gPhactoriPipeRootMap = {}
25088
25089 def convertJsonUnicodeToStrings(inJson):
25090 "go through a dict/list/item which was loaded via json.load, and convert\n unicode strings to python strings"
25091 #for python 2.6 or earlier, replace
25092 # return {convertJsonUnicodeToStrings(key): convertJsonUnicodeToStrings(value) for key, value in inJson.iteritems()}
25093 #with
25094 # return dict([(convert(key), convert(value)) for key, value in input.iteritems()])
25095 #(not tested, this routine was copied from web answer to question)
25096 if isinstance(inJson, dict):
25097 return {convertJsonUnicodeToStrings(key): convertJsonUnicodeToStrings(value) for key, value in inJson.items()}
25098 elif isinstance(inJson, list):
25099 return [convertJsonUnicodeToStrings(element) for element in inJson]
25100 elif isinstance(inJson, str):
25101 #return inJson.encode('utf-8')
25102 return str(inJson)
25103 else:
25104 return inJson
25105
25106
25107 def IssueErrorOrWarningThroughSierraIO(datadescription, outString, isErrorFlag):
25108 if PhactoriDbg():
25109 myDebugPrint3("IssueErrorOrWarningThroughSierraIO entered")
25110
25111 if datadescription == None:
25112 errStr = "IssueErrorOrWarningThroughSierraIO no datadescription\n" + \
25113 outString
25114 raise Exception(errStr)
25115 return
25116
25117 fd = datadescription.GetUserData()
25118
25119 if fd == None:
25120 errStr = "IssueErrorOrWarningThroughSierraIO, no user data\n" + \
25121 outString
25122 if PhactoriDbg():
25123 myDebugPrint3(errStr)
25124 raise Exception(errStr)
25125 return
25126
25127 #numArrays = fd.GetNumberOfArrays()
25128 #myDebugPrint3("abstract arrays: number of arrays: " + str(numArrays) + "\n")
25129 #for ii in range(numArrays):
25130 # myDebugPrint3("array " + str(ii) + ":\n")
25131 # oneArray = fd.GetAbstractArray(ii)
25132 # myDebugPrint3("name: " + oneArray.GetName() + "\n")
25133
25134 errorCodeArray = fd.GetAbstractArray("catalyst_sierra_error_codes")
25135 errorMessageArray = fd.GetAbstractArray("catalyst_sierra_error_messages")
25136
25137 if errorCodeArray == None or errorMessageArray == None:
25138 if PhactoriDbg(999):
25139 myDebugPrint3("IssueErrorOrWarningThroughSierraIO::\n"
25140 "catalyst_sierra_error_codes and/or catalyst_sierra_error_messages\n"
25141 "were missing from UserData. Item follows:\n" + outString, 999)
25142 else:
25143 if isErrorFlag:
25144 errorCode = 0
25145 else:
25146 errorCode = 1
25147 errorCodeArray.InsertNextValue(errorCode)
25148 errorMessageArray.InsertNextValue(outString)
25149
25150 if PhactoriDbg():
25151 myDebugPrint3("IssueErrorOrWarningThroughSierraIO reached end")
25152
25153 def GetUserDataStringArrayAccountingForBypass(datadescription):
25154 if datadescription == None:
25155 if gBypassUserData:
25156 if PhactoriDbg():
25157 myDebugPrint3(
25158 "GetUserDataStringArrayAccountingForBypass returning " \
25159 "bypass strings 1\n")
25160 return gUserDataBypassStrings
25161 else:
25162 if PhactoriDbg():
25163 myDebugPrint3(
25164 "GetUserDataStringArrayAccountingForBypass returning None 1\n")
25165 return None
25166
25167 fd = datadescription.GetUserData()
25168 if fd == None:
25169 if gBypassUserData:
25170 if PhactoriDbg():
25171 myDebugPrint3(
25172 "GetUserDataStringArrayAccountingForBypass returning " \
25173 "bypass strings 2\n")
25174 return gUserDataBypassStrings
25175 else:
25176 if PhactoriDbg():
25177 myDebugPrint3(
25178 "GetUserDataStringArrayAccountingForBypass returning None 2\n")
25179 return None
25180
25181 sa = fd.GetAbstractArray(0)
25182 if sa == None or sa.GetNumberOfValues() < 1:
25183 if gBypassUserData:
25184 if PhactoriDbg():
25185 myDebugPrint3(
25186 "GetUserDataStringArrayAccountingForBypass returning " \
25187 "bypass strings 3\n")
25188 return gUserDataBypassStrings
25189 else:
25190 if PhactoriDbg():
25191 myDebugPrint3(
25192 "GetUserDataStringArrayAccountingForBypass returning None 3\n")
25193 return None
25194
25195 returnStringArray = ["","","","","","","","",""]
25196
25197 for ii in range(0, sa.GetNumberOfValues()):
25198 returnStringArray[ii] = sa.GetValue(ii)
25199
25200 if gBypassUserData:
25201 #sub in json string
25202 if PhactoriDbg():
25203 myDebugPrint3("gBypassUserData is true, user data is valid, subbing\n")
25204 returnStringArray[0] = gUserDataBypassStrings[0]
25205 #also add in missing user values if sa was short
25206 for jj in range(sa.GetNumberOfValues(), len(gUserDataBypassStrings)):
25207 returnStringArray[jj] = gUserDataBypassStrings[0]
25208
25209 return returnStringArray
25210
25211
25212 def GetViewMapCFromUserData(datadescription):
25213 "given a datadescription, get the json string view map from the user data\n and convert it into a python dict using the json library, and return\n that item. Also determine the separator character and input deck\n filename"
25214
25215 #the following code forces a UserData item for internal testing
25216 #myDebugPrint3("GetViewMapCFromUserData entered\n")
25217 #newFd = vtk.vtkFieldData()
25218 #newStringArray = vtk.vtkStringArray()
25219 #xxViewMapCStr = '{ "camera blocks": { }, "representation blocks": { }, \
25220 # "operation blocks": { }, "imageset blocks": {}, \
25221 # "scatter plot blocks": { }, "plot over time blocks": { } }'
25222 #newStringArray.InsertNextValue(xxViewMapCStr)
25223 #x2str = '_'
25224 #x3str = 'cool_input_deck'
25225 #newStringArray.InsertNextValue(x2str)
25226 #newStringArray.InsertNextValue(x3str)
25227 #newFd.AddArray(newStringArray)
25228
25229 #datadescription.SetUserData(newFd)
25230
25231 global gBypassUserData
25232
25233 sa = GetUserDataStringArrayAccountingForBypass(datadescription)
25234
25235 testJsonString = sa[0]
25236 separatorCharacterString = sa[1]
25237 inputDeckFilename = sa[2]
25238
25239 if PhactoriDbg():
25240 myDebugPrint3("gGetJsonViewMapCFromUserData string:\n" + \
25241 str(testJsonString) + "\n")
25242 if PhactoriDbg():
25243 myDebugPrint3("separator string: " + separatorCharacterString + \
25244 "\ninputDeckFilename: " + inputDeckFilename + "\n")
25245 #if PhactoriDbg():
25246 #myDebugPrint3("num strings2: " + str(sa.GetNumberOfValues()))
25247 if PhactoriDbg():
25248 myDebugPrint3("json.loads begin ---------------\n");
25249 myDebugPrint3(testJsonString);
25250 myDebugPrint3("\njson.loads end ---------------\n");
25251
25252 if gBypassUserData == True:
25253 global gBypassUserDataJson
25254 returnViewMapC = gBypassUserDataJson
25255 #returnViewMapC = bccolli_controls.catalystSierraInputInJsonFormat
25256 else:
25257 returnViewMapC = json.loads(testJsonString)
25258 returnViewMapC = convertJsonUnicodeToStrings(returnViewMapC)
25259
25260 SetDefaultImageBasename(inputDeckFilename)
25261
25262 if PhactoriDbg():
25263 myDebugPrint3("GetViewMapCFromUserData returning\n")
25264
25265 return returnViewMapC
25266
25267
25268 def CreatePipelineFromDataDescription(datadescription):
25269 theSource = GetCurrentSource()
25270
25271 theCellArrays = None
25272 theCellArrays = theSource.CellData
25273 thePointArrays = None
25274 thePointArrays = theSource.PointData
25275
25276 theViewMapC = GetViewMapCFromUserData(datadescription)
25277
25278 CreateViewSetFromPhactoriViewMapC(theViewMapC)
25279
25280 #SetPlotView2StartColors(
25281 # inBackgroundColor = [1.0, 1.0, 1.0],
25282 # inEdgeColor = [0.0, 0.0, 0.5],
25283 # inCubeAxesColor = [0.2, 0.2, 0.2],
25284 # inDiffuseColor = [0.2, 0.2, 0.2],
25285 # inAmbientColor = [0.2, 0.2, 0.2],
25286 # inSelectionColor = [0.2, 0.2, 0.2],
25287 # inBackfaceDiffuseColor = [0.2, 0.2, 0.2])
25288
25289 def parseDbDummyFname(dbDummyFname):
25290 "given user data item which is dummy database name used for remesh and\n restart purposes, pull out the base name (minus -s0002, -sXXXX, etc.)\n and return the base name and extension (extension in an empty string\n if appropriate)"
25291 remeshRestartTagIndex = dbDummyFname.rfind("-s")
25292 if remeshRestartTagIndex == -1:
25293 baseId = dbDummyFname
25294 remeshRestartTag = ''
25295 else:
25296 baseId = dbDummyFname[0:remeshRestartTagIndex]
25297 remeshRestartTag = dbDummyFname[remeshRestartTagIndex:]
25298 return baseId, remeshRestartTag
25299
25300 def DoUserInteractionWithSimulationPausedIfEnabled():
25301 if PhactoriDbg():
25302 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled entered\n")
25303 global gPipeAndViewsState
25304
25305 if gPipeAndViewsState.mInteractionRepeatPauseSim == False:
25306 if PhactoriDbg():
25307 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled returning 0\n")
25308 return 0
25309
25310 updateWasDone = HandleUserInteractionIfEnabled(gPipeAndViewsState)
25311 if updateWasDone:
25312 returnVal = 2
25313 else:
25314 returnVal = 1
25315 if PhactoriDbg():
25316 myDebugPrint3("DoUserInteractionWithSimulationPausedIfEnabled returning " + \
25317 str(returnVal) + "\n")
25318 return returnVal
25319
25320 def HandleUserInteractionIfEnabled(ioPipeAndViewsState):
25321 "if the pipe (or imageset maybe) is in interactive mode, check for the\n trigger which will cause a read-and-update of the state. Provides\n control to skip interaction when it is not enabled, the default case.\n Allows for a wait for an interaction trigger of N tries at M seconds\n per try, mainly to deal with situations where images are being \n rendered quickly. Eventually may be altered to help deal with cases\n where we want to keep re-rendering with changed pipeline states\n until we are happy and then let the simulation return to operation"
25322 if PhactoriDbg():
25323 myDebugPrint3("HandleUserInteractionIfEnabled entered\n")
25324 if ioPipeAndViewsState.mInteractionEnabled == False:
25325 return False
25326
25327 if SmartGetLocalProcessId() != 0:
25328 return False
25329 #else:
25330 #do parallel stuff to receive info
25331
25332
25333 #check for trigger. Only update if trigger file is incremented
25334 doUpdate = False
25335 triggerTestCount = 0
25336
25337 while doUpdate == False and \
25338 triggerTestCount < ioPipeAndViewsState.mInteractionTriggerTries:
25339 if PhactoriDbg():
25340 myDebugPrint3("testing for trigger: " + str(triggerTestCount) + \
25341 " of " + str(ioPipeAndViewsState.mInteractionTriggerTries) + "\n")
25342 triggerTestCount += 1
25343 try:
25344 inFile = open('PhactoriInteractionTrigger.txt', 'rb')
25345 userTrigger = json.load(inFile)
25346 inFile.close()
25347 userTrigger = convertJsonUnicodeToStrings(userTrigger)
25348 except:
25349 if PhactoriDbg():
25350 myDebugPrint3("error dealing with PhactoriInteractionTrigger.txt\n")
25351 return
25352
25353 if 'InteractionTriggerCounter' not in userTrigger:
25354 if PhactoriDbg():
25355 myDebugPrint3("no InteractionTriggerCounter in \
25356 PhactoriInteractionTrigger.txt\n")
25357 else:
25358 testTriggerCount = userTrigger['InteractionTriggerCounter']
25359 if testTriggerCount != ioPipeAndViewsState.mInteractionTriggerCounter:
25360 ioPipeAndViewsState.mInteractionTriggerCounter = testTriggerCount
25361 doUpdate = True
25362
25363 if doUpdate == False:
25364 import time
25365 time.sleep(ioPipeAndViewsState.mInteractionTriggerSleep)
25366
25367 if doUpdate:
25368 if PhactoriDbg():
25369 myDebugPrint3("update triggered, doing update\n")
25370 UpdatePipeAndViewsStateFromUserA(ioPipeAndViewsState,
25371 "PhactoriJsonSettings.txt")
25372 if 'InteractionState' in userTrigger:
25373 if userTrigger['InteractionState'] == 'RepeatWithPausedSimulation':
25374 ioPipeAndViewsState.mInteractionRepeatPauseSim = True
25375 else:
25376 ioPipeAndViewsState.mInteractionRepeatPauseSim = False
25377 else:
25378 ioPipeAndViewsState.mInteractionRepeatPauseSim = False
25379
25380 if PhactoriDbg():
25381 myDebugPrint3("HandleUserInteractionIfEnabled returning\n")
25382 return doUpdate
25383
25384 #phactori_combine_to_single_python_file_parent_1
25385 #from Operation.PhactoriRepresentationBlock import *
25386 #phactori_combine_to_single_python_file_subpiece_begin_1
25387 class PhactoriRepresentationBlock:
25388 def __init__(self):
25389 self.mName = ""
25390 self.mColorVariableInfo = PhactoriVariableInfo()
25391 self.mColorLegendFlag = True
25392 #self.mColorLegendPositionAndSize = ['bottom', 1.0]
25393 #self.mColorLegendPositionAndSize = ['right', 1.0]
25394 self.mColorLegendPositionAndSize = ['bottom right', 1.0]
25395 self.mTimeAnnotationSettings = PhactoriAnnotationViewSettings(
25396 'time', 'time')
25397 self.mDataCubeAxesFlag = False
25398 self.mDataCubeAxesInfo = PhactoriDataCubeAxesInfo()
25399 #self.mColorByBlockFlag = True
25400 self.mColorByBlockFlag = True
25401 self.mColorByBlockExplicitlySet = False
25402 self.mColorBySolidColorFlag = False
25403 self.mSolidColor = None
25404 self.mOpacitySetting = 1.0
25405 self.mOrientationAxesFlag = True
25406 self.mFixedColorRange = None
25407 self.mUseFixedColorRange = False
25408 self.mColorRangeMinMaxTracker = PlotValMinMaxTrkC()
25409 self.mUseHighlightSubranges = False
25410 self.mHighlightSubranges = []
25411 self.mUseColorSubrange = False
25412 self.mColorSubrange = [0.0, 1.0]
25413 self.mFilenameAddon = ""
25414 self.mColorSettings = PhactoriColorSettings()
25415 self.mColorMapSettings = PhactoriColorMapSettings()
25416 self.mPointSize = 2.0
25417 self.InterpretValuesAsCategories = False
25418 self.CategoryAndColorJsonFile = None
25419 self.Annotations = None
25420 self.IndexedColors = None
25421 self.IndexedOpacities = None
25422
25423 def ParseSettingsFromJson(self, inRepresentationBlockJson):
25424 "given a python dict (presumably from json) description of a\n representation block, parse all the representation parameters out of\n the block"
25425
25426 if PhactoriDbg(100):
25427 myDebugPrint3('ParseSettingsFromJson entered\n', 100)
25428
25429 inJsn = inRepresentationBlockJson
25430
25431 #hack test for colors start
25432 #inJsn['surface color'] = [1.0, 0.0, 0.0]
25433 #inJsn['background color'] = [0.0, 0.0, 0.0]
25434 #inJsn['edge color'] = [0.0, 1.0, 0.0]
25435 ##inJsn['axes color'] = [0.0, 1.0, 1.0]
25436 #inJsn['text color'] = [1.0, 1.0, 0.0]
25437 #hack test for colors end
25438
25439 #myDebugPrint3(' json: ' + str(inJsn) + '\n')
25440
25441 if 'point size' in inJsn:
25442 self.mPointSize = inJsn['point size']
25443
25444 #color by variable scalar/vector magnitude/vector component/tensor component
25445 self.mColorVariableInfo.\
25446 ParseVariableNameAndVectorOrTensorComponent(inJsn, 'color by ')
25447
25448 if self.mColorVariableInfo.mVariableName != '':
25449 self.mColorByBlockFlag = False
25450 self.mColorBySolidColorFlag = False
25451 elif 'color by blockid' in inJsn:
25452 self.mColorByBlockFlag = True
25453 self.mColorByBlockExplicitlySet = True
25454 self.mColorBySolidColorFlag = False
25455 elif 'color by solid color' in inJsn:
25456 self.mColorBySolidColorFlag = True
25457 self.mColorByBlockFlag = False
25458 self.mSolidColor = inJsn['color by solid color']
25459
25460 #color map range control
25461 if 'color legend range' in inJsn:
25462 self.mFixedColorRange = inJsn['color legend range']
25463 self.mUseFixedColorRange = True
25464 else:
25465 self.mUseFixedColorRange = False
25466
25467 #highlight subranges with solid colors
25468 if 'highlight subrange 1' in inJsn:
25469 highlightSubrangeIndex = 1
25470 while True:
25471 oneSubrangeKey = 'highlight subrange ' + str(highlightSubrangeIndex)
25472 if oneSubrangeKey in inJsn:
25473 subrangeArgs = inJsn[oneSubrangeKey]
25474 highlightSubrangeIndex += 1
25475 if len(subrangeArgs) != 5:
25476 if PhactoriDbg():
25477 myDebugPrint3("highlight subrange needs 5 values\n");
25478 PrintOnProcessZero("highlight subrange needs 5 values, skipping " + \
25479 oneSubrangeKey + "\n");
25480 continue
25481 srmin = float(subrangeArgs[0])
25482 srmax = float(subrangeArgs[1])
25483 if srmin > srmax:
25484 if PhactoriDbg():
25485 myDebugPrint3("subrange highlight min >= max: " + \
25486 str(srmin) + ", " + str(srmax) + "\nskipping " + \
25487 oneSubrangeKey + "\n", 100)
25488 PrintOnProcessZero("subrange highlight min >= max: " + \
25489 str(srmin) + ", " + str(srmax) + "\nskipping " + \
25490 oneSubrangeKey + "\n")
25491 continue
25492 srColor = [float(subrangeArgs[2]), float(subrangeArgs[3]),
25493 float(subrangeArgs[4])]
25494 if (srColor[0] < 0.0) or (srColor[0] > 1.0) or \
25495 (srColor[1] < 0.0) or (srColor[1] > 1.0) or \
25496 (srColor[2] < 0.0) or (srColor[2] > 1.0):
25497 srColor = [1.0, 1.0, 0.0]
25498 if PhactoriDbg():
25499 myDebugPrint3(oneSubrangeKey + ": bad color "
25500 "(component not 0.0-1.0), using rgb 1.0, 1.0, 0.0\n", 100)
25501 PrintOnProcessZero(oneSubrangeKey + ": bad color "
25502 "(component not 0.0-1.0), using rgb 1.0, 1.0, 0.0\n")
25503 self.mHighlightSubranges.append(
25504 [srmin, srmax, srColor])
25505 self.mUseHighlightSubranges = True
25506 else:
25507 break
25508 if PhactoriDbg():
25509 myDebugPrint3("parsed highlight subranges:\n" + \
25510 str(self.mHighlightSubranges) + "\n", 100)
25511
25512 #if 'highlight subranges' in inJsn:
25513 # self.mUseHighlightSubranges = True
25514 # sbrngsJsn = inJsn['highlight subranges']
25515 # for oneSubrange in sbrngsJsn:
25516 # if 'range' in oneSubrange:
25517 # srmin = oneSubrange['range'][0]
25518 # srmax = oneSubrange['range'][1]
25519 # if srmin < srmax:
25520 # if 'color' in oneSubrange:
25521 # srColor = oneSubrange['color']
25522 # else:
25523 # srColor = [1.0, 1.0, 0.0]
25524 # self.mHighlightSubranges.append(
25525 # [srmin, srmax, srColor])
25526 # else:
25527 # if PhactoriDbg():
25528 # myDebugPrint3("highlight min >= max: " + \
25529 # str(srmin) + ", " + str(srmax) + "\nskipping subrange\n", 100)
25530 # PrintOnProcessZero("highlight min >= max: " + \
25531 # str(srmin) + ", " + str(srmax) + "\nskipping subrange\n")
25532 # else:
25533 # if PhactoriDbg():
25534 # myDebugPrint3("subrange is missing 'range' key; skipping\n")
25535 # PrintOnProcessZero("subrange is missing 'range' key; skipping\n")
25536 # if PhactoriDbg():
25537 # myDebugPrint3("parsed highlight subranges:\n" + \
25538 # str(self.mHighlightSubranges) + "\n", 100)
25539
25540 #additional capability: use ratio-expressed subrange of
25541 #range that would otherwise be used to increase concentration of
25542 #dynamic range of color map in range of interest
25543 if 'color legend subrange' in inJsn:
25544 self.mUseColorSubrange = True
25545 self.mColorSubrange = inJsn['color legend subrange']
25546 goodSubrange = True
25547 if self.mColorSubrange[0] < 0.0:
25548 goodSubrange = False
25549 if self.mColorSubrange[1] > 1.0:
25550 goodSubrange = False
25551 if self.mColorSubrange[0] > \
25552 self.mColorSubrange[1]:
25553 goodSubrange = False
25554 if goodSubrange == False:
25555 myDebugPrint3AndException(
25556 "ParseOneRepresentationBlockC:\n"
25557 "bad color legend subrange, must be 0.0 <= bottom <= top <= 1.0\n")
25558
25559 #choose color map by name
25560 self.mColorMapSettings.ParseColorMapSettings(inJsn)
25561
25562 self.InterpretValuesAsCategories = \
25563 getParameterFromBlock(inJsn, "interpret values as categories", False)
25564 if self.InterpretValuesAsCategories:
25565 key1 = "category and color json file"
25566 if key1 not in inJsn:
25567 myDebugPrint3AndException(
25568 "interpret values as categories is true but '" + key1 + \
25569 "' is missing\n")
25570 self.CategoryAndColorJsonFile = \
25571 getParameterFromBlock(inJsn, key1, "dummy1.json")
25572 elif 'color by scalar' in inJsn:
25573 if inJsn['color by scalar'] == "ObjectId":
25574 if PhactoriDbg():
25575 myDebugPrint3("variable is ObjectId, using categories\n")
25576 self.InterpretValuesAsCategories = True
25577 self.CategoryAndColorJsonFile = "ObjectIdBlockColors.json"
25578
25579 showSurfacesFlag = getParameterFromBlock(inJsn, 'show surfaces', True)
25580 showEdgesFlag = getParameterFromBlock(inJsn, 'show edges', False)
25581 showPointsFlag = getParameterFromBlock(inJsn, 'show points', False)
25582
25583 self.mOpacitySetting = getParameterFromBlock(inJsn, 'opacity',
25584 self.mOpacitySetting)
25585
25586 #doVolumeRenderingFlag = getParameterFromBlock(inJsn, 'volume rendering', True)
25587 doVolumeRenderingFlag = getParameterFromBlock(inJsn, 'volume rendering', False)
25588 self.mScalarOpacityUnitDistance = getParameterFromBlock(
25589 inJsn, 'scalar opacity unit distance', -1.0)
25590
25591 #self.mScalarOpacityUnitDistance = 0.01
25592 if PhactoriDbg():
25593 myDebugPrint3("doVolumeRenderingFlag: " + \
25594 str(doVolumeRenderingFlag) + "\n" + \
25595 "self.mScalarOpacityUnitDistance: " + \
25596 str(self.mScalarOpacityUnitDistance) + "\n")
25597
25598 self.mPresetsImportFileName = getParameterFromBlock(inJsn,
25599 'color and opacity presets import file', None)
25600 if self.mPresetsImportFileName != None:
25601 retval = ImportPresets(self.mPresetsImportFileName)
25602 if retval != True:
25603 myDebugPrint3AndException(
25604 "paraview.simple.ImportPresets failed with the file:\n" + \
25605 str(self.mPresetsImportFileName) + "\n")
25606 self.mNameOfPresetToUse = getParameterFromBlock(inJsn,
25607 'color and opacity preset', None)
25608
25609 showBoundingBoxFlag = getParameterFromBlock(inJsn, 'show bounding box', False)
25610
25611 self.mMeshRenderControl = 'Surface'
25612 if showBoundingBoxFlag:
25613 self.mMeshRenderControl = 'Outline'
25614 if showSurfacesFlag | showEdgesFlag | showPointsFlag:
25615 if PhactoriDbg():
25616 myDebugPrint3(" warning: when show bounding box is true, \n" + \
25617 " show surfaces, show edges, and show points should be false\n")
25618 elif showPointsFlag:
25619 self.mMeshRenderControl = 'Points'
25620 else:
25621 if showSurfacesFlag:
25622 if showEdgesFlag:
25623 self.mMeshRenderControl = 'Surface With Edges'
25624 else:
25625 self.mMeshRenderControl = 'Surface'
25626 else:
25627 if showEdgesFlag:
25628 self.mMeshRenderControl = 'Wireframe'
25629 #self.mMeshRenderControl = 'Points'
25630 else:
25631 self.mMeshRenderControl = 'Outline'
25632
25633 if doVolumeRenderingFlag:
25634 if PhactoriDbg(100):
25635 myDebugPrint3('doing volume rendering\n', 100)
25636 self.mMeshRenderControl = 'Volume'
25637 self.mDoingVolumeRendering = True
25638 else:
25639 self.mDoingVolumeRendering = False
25640
25641 #color legend on/off
25642 self.mColorLegendFlag = getParameterFromBlock(inJsn,
25643 'show color legend', self.mColorLegendFlag)
25644
25645 self.mColorLegendPositionAndSize = \
25646 getParameterFromBlock(inJsn, 'color legend position',
25647 self.mColorLegendPositionAndSize)
25648
25649 if self.mColorLegendFlag == True:
25650 if self.mColorVariableInfo.mVariableName == '':
25651 self.mColorLegendFlag = False
25652
25653 self.mColorRangeMinMaxTracker.PlotValMinMaxTrkCParseJson(
25654 inJsn, "color legend ")
25655
25656 self.mTimeAnnotationSettings.ParseAvsFromJson(inJsn)
25657
25658 self.mDataCubeAxesFlag = getParameterFromBlock(inJsn,
25659 'show axes', self.mDataCubeAxesFlag)
25660
25661 self.mDataCubeAxesInfo.DcaiParseParametersFromJson(inJsn)
25662
25663 self.mOrientationAxesFlag = getParameterFromBlock(inJsn,
25664 'show orientation axes', self.mOrientationAxesFlag)
25665
25666 if "image name addon" in inJsn:
25667 self.mFilenameAddon = inJsn["image name addon"]
25668
25669 self.mColorSettings.ParseColorSettingsFromJson(inJsn)
25670
25671 if PhactoriDbg(100):
25672 myDebugPrint3('ParseOneRepresentationBlockC returning\n', 100)
25673
25674 def SetFromRestartInfo(self, inJson):
25675 "given a map (json format), use the info in the map to set the\n representation state--this reads the info created in \n GetRestartInfo"
25676
25677 if 'mColorRangeMinMaxTracker' not in inJson:
25678 if PhactoriDbg():
25679 myDebugPrint3("PhactoriRepresentationBlock::" + \
25680 "SetFromRestartInfo: no mColorRangeMinMaxTracker, return\n")
25681 return
25682
25683 if PhactoriDbg():
25684 myDebugPrint3("Representation::SetFromRestartInfo\n" +
25685 "currently set to do something\n" +
25686 "before tracker:\n" + self.mColorRangeMinMaxTracker.SelfToStr())
25687
25688 jsonItem = inJson['mColorRangeMinMaxTracker']
25689 self.mColorRangeMinMaxTracker.SetFromRestartInfo(jsonItem)
25690
25691 if PhactoriDbg():
25692 myDebugPrint3("after tracker:\n" +
25693 self.mColorRangeMinMaxTracker.SelfToStr())
25694
25695 def GetRestartInfo(self):
25696 "construct, in python map/json format, the information from this\n representation instance which contains the information\n which would be needed to restore the representation to the proper\n state after a simulation restart, particularly color range tracking\n information. Return the restart info map/json"
25697 newRestartInfoJson = {}
25698 newRestartInfoJson['mColorRangeMinMaxTracker'] = \
25699 self.mColorRangeMinMaxTracker.GetRestartInfo()
25700 return newRestartInfoJson
25701
25702 def CalculateDefaultScalarOpacityUnitDistance(self, inPhactoriOperation):
25703 "given a phactori operation assumed to have an updated pipeline,\n calculate a default scalar opacity unit distance the same as paraview,\n with 0.05 * diagonal length of data bounding box"
25704 bnds = GetGlobalDataBoundsParallel(inPhactoriOperation.mParaViewFilter)
25705 xxlen = bnds[1] - bnds[0]
25706 yylen = bnds[3] - bnds[2]
25707 zzlen = bnds[5] - bnds[4]
25708 self.mScalarOpacityUnitDistance = \
25709 0.05 * math.sqrt(xxlen*xxlen + yylen*yylen + zzlen*zzlen)
25710
25711 def SetUpForInterpretValuesAsCateories(self, variableLookUpTable):
25712 if PhactoriDbg():
25713 myDebugPrint3("SetUpForInterpretValuesAsCateories entered\n")
25714 if(self.Annotations == None):
25715 jsonCategories = ReadAndMpiBroadcastJsonFile(self.CategoryAndColorJsonFile)
25716 jsonCategories = convertJsonUnicodeToStrings(jsonCategories)
25717 self.Annotations = jsonCategories[0]["Annotations"]
25718 self.IndexedColors = jsonCategories[0]["IndexedColors"]
25719 self.IndexedOpacities = []
25720 numCategories = len(self.Annotations) // 2
25721 for ii in range(0, numCategories):
25722 self.IndexedOpacities.append(1.0)
25723 if PhactoriDbg():
25724 myDebugPrint3("self.Annotations:\n" + str(self.Annotations) + "\n")
25725 myDebugPrint3("self.IndexedColors:\n" + str(self.IndexedColors) + "\n")
25726 myDebugPrint3("self.IndexedOpacities:\n" + str(self.IndexedOpacities) + "\n")
25727 variableLookUpTable.InterpretValuesAsCategories = 1
25728 variableLookUpTable.AnnotationsInitialized = 1
25729 variableLookUpTable.Annotations = self.Annotations
25730 variableLookUpTable.IndexedColors = self.IndexedColors
25731 variableLookUpTable.IndexedOpacities = self.IndexedOpacities
25732 if PhactoriDbg():
25733 myDebugPrint3("SetUpForInterpretValuesAsCateories returning\n")
25734 #phactori_combine_to_single_python_file_subpiece_end_1
25735
25736 class PhactoriCriteriaThreshold:
25737 "\n maintains a threshold value TT, and tracks when a min/max/mean/sum/count\n of a variable crosses the threshold; also keeps track of how many frames\n it has been since the crossing and if this is within a frame count setting\n and also tracks how many times it has been triggered and no longer triggers\n after a max has been reached\n "
25738
25739 def __init__(self, inThresholdValue, inFramesAfterTrigger, inMaxTriggers):
25740 self.mThresholdValue = inThresholdValue
25741 self.mFramesAfterTrigger = inFramesAfterTrigger
25742 self.mMaxTriggers = inMaxTriggers
25743 self.mCrossingsSoFar = 0
25744 self.mLastTestValue = 0.0
25745 self.mObserveCallCount = 0
25746 self.mCountAtLastCrossing = 0
25747 self.mCountAtLastTrigger = 0
25748 self.mFramesSinceLastTrigger = 0
25749 self.mCurrentlyTriggered = False
25750 if PhactoriDbg(100):
25751 myDebugPrint3(
25752 "PhactoriCriteriaThreshold::__init__:\n"
25753 "self.mThresholdValue: " + str(self.mThresholdValue) + "\n"
25754 "self.mFramesAfterTrigger: " + str(self.mFramesAfterTrigger) + "\n"
25755 "self.mMaxTriggers: " + str(self.mMaxTriggers) + "\n", 100)
25756
25757
25758 def ObservePotentialCrossingValue(self, mTestValue):
25759 if PhactoriDbg(100):
25760 if self.mObserveCallCount != 0:
25761 if PhactoriDbg(100):
25762 myDebugPrint3("ObservePotentialCrossingValue:\n" +
25763 str(mTestValue) + " <> " + str(self.mThresholdValue) + " <> " + \
25764 str(self.mLastTestValue) + "\n", 100)
25765 else:
25766 if PhactoriDbg(100):
25767 myDebugPrint3("ObservePotentialCrossingValue:\n" +
25768 str(mTestValue) + " <> " + str(self.mThresholdValue) + " <> " + \
25769 str("first call") + "\n", 100)
25770
25771 if self.mObserveCallCount != 0:
25772 if((self.mLastTestValue <= self.mThresholdValue) and \
25773 (mTestValue >= self.mThresholdValue)) or \
25774 ((self.mLastTestValue >= self.mThresholdValue) and \
25775 (mTestValue <= self.mThresholdValue)):
25776 #the test value crosses the threshold from the last test value
25777 self.mCrossingsSoFar += 1
25778 self.mCountAtLastCrossing = self.mObserveCallCount
25779 if PhactoriDbg(100):
25780 myDebugPrint3("crossing occurred: " + str(self.mCrossingsSoFar) + \
25781 ", " + str(self.mCountAtLastCrossing) + "\n")
25782 if(self.mCrossingsSoFar <= self.mMaxTriggers):
25783 self.mCountAtLastTrigger = self.mObserveCallCount
25784 if PhactoriDbg(100):
25785 myDebugPrint3("self.mCountAtLastTrigger changed to " +
25786 str(self.mCountAtLastTrigger) + "\n")
25787 else:
25788 if PhactoriDbg(100):
25789 myDebugPrint3("no trigger due to self.mMaxTriggers")
25790
25791 self.mCurrentlyTriggered = False
25792 if self.mCrossingsSoFar != 0:
25793 if (self.mFramesAfterTrigger <= 0) or \
25794 (self.mObserveCallCount - self.mCountAtLastTrigger) < \
25795 self.mFramesAfterTrigger:
25796 self.mCurrentlyTriggered = True
25797
25798 if PhactoriDbg(100):
25799 myDebugPrint3("self.mCurrentlyTriggered now " + \
25800 str(self.mCurrentlyTriggered) + "\n")
25801
25802 self.mLastTestValue = mTestValue
25803 self.mObserveCallCount += 1
25804 return
25805
25806 def CurrentlyTriggered(self):
25807 return self.mCurrentlyTriggered
25808
25809 class PhactoriImagesetOnOffFilterCriteria:
25810 "\n this class represents one test used to determine if images are or are\n not shown. The general idea is that the test is whether a variable\n minimum/maximum/mean is above/below/between a certain value or values.\n The variable can be scalar, vector magnitude, vector component, or\n tensor component, or global, and can be cell/element or point/node\n "
25811
25812 def __init__(self):
25813 self.mName = ""
25814 self.mVariableInfo = PhactoriVariableInfo()
25815 self.mRange = [0.0, 1.0]
25816 #min/mean/max
25817 self.mFunctionType = "maximum"
25818 self.mInputOperationName = None
25819 self.mInputOperation = None
25820 #default number of frames after trigger is 5
25821 self.mNumberOfFramesAfterTrigger = 5
25822 self.mHasBeenTriggered = False
25823 self.mCallbackTagAtFirstTrigger = -1
25824 self.mThresholdList = []
25825 self.mMaxTriggersPerThreshold = 1
25826 self.mFrameTagCounter = -1
25827 self.mReturnValAtCurrentFrameTagCounter = False
25828
25829 def TestForTruth(self, ioPipeAndViewsState):
25830 "returns true if this criteria indicates we should render a frame, false\n otherwise"
25831
25832 if PhactoriDbg(100):
25833 myDebugPrint3(
25834 "PhactoriImagesetOnOffFilterCriteria::TestForTruth entered", 100)
25835
25836 if self.mFrameTagCounter == ioPipeAndViewsState.mFrameTagCounter:
25837 if PhactoriDbg(100):
25838 myDebugPrint3(
25839 "additional call, same mFrameTagCounter, just return value", 100)
25840 return self.mReturnValAtCurrentFrameTagCounter
25841 self.mFrameTagCounter = ioPipeAndViewsState.mFrameTagCounter
25842
25843 #if this has been triggered, it remains true no matter what variables do.
25844 #if there is a limit to the number of frames this trigger is true, it
25845 #will be false after that many frames no matter what
25846 #if self.mHasBeenTriggered:
25847 # if self.mNumberOfFramesAfterTrigger < 0:
25848 # #no frame limit; always true now
25849 # return True
25850 # else:
25851 # countSoFar = ioPipeAndViewsState.mFrameTagCounter - \
25852 # self.mCallbackTagAtFirstTrigger
25853 # if PhactoriDbg(100):
25854 # myDebugPrint3(
25855 # "mFrameTagCounter: " + \
25856 # str(ioPipeAndViewsState.mFrameTagCounter) + "\n"
25857 # "mCallbackTagAtFirstTrigger: " + \
25858 # str(self.mCallbackTagAtFirstTrigger) + "\n"
25859 # "countSoFar: " + str(countSoFar) + "\n"
25860 # "mNumberOfFramesAfterTrigger: " + \
25861 # str(self.mNumberOfFramesAfterTrigger) + "\n",
25862 # 100)
25863 # if countSoFar >= self.mNumberOfFramesAfterTrigger:
25864 # #reached frame limit
25865 # return False
25866 # else:
25867 # #haven't reached frame limit, still true
25868 # return True
25869
25870 if self.mInputOperation == None:
25871 if self.mInputOperationName == None:
25872 self.mInputOperation = ioPipeAndViewsState.mIncomingDefaultOperation
25873 else:
25874 if self.mInputOperationName not in ioPipeAndViewsState.mOperationBlocks:
25875 errStr = 'error! in PhactoriImagesetOnOffFilterCriteria::TestForTruth calls for nonexistent input operation with name ' + str(self.mInputOperationName) + '\n'
25876 if PhactoriDbg():
25877 myDebugPrint3(errStr)
25878 raise Exception(errStr)
25879 else:
25880 self.mInputOperation = \
25881 ioPipeAndViewsState.mOperationBlocks[self.mInputOperationName]
25882
25883 theParaViewFilter = self.mInputOperation.GetPvFilter()
25884 UpdatePipelineWithCurrentTimeArgument(theParaViewFilter)
25885
25886 ###find min/max/avg/sum/count
25887 inputcsData = theParaViewFilter.GetClientSideObject().\
25888 GetOutputDataObject(0)
25889 if inputcsData == None:
25890 if PhactoriDbg(100):
25891 myDebugPrint3('inputcsData is None, returning false', 100)
25892 self.mReturnValAtCurrentFrameTagCounter = False
25893 return False
25894
25895 if PhactoriDbg():
25896 myDebugPrint3('finding min/max data for this processor at this timestep\n')
25897 DataMinMax = [0.0, 0.0, False]
25898 DataSumCnt = [0.0, 0]
25899
25900 FindMinMaxSumCntFromData(inputcsData, self.mVariableInfo, None,
25901 DataMinMax, DataSumCnt, None, None)
25902
25903 #just return false if there is no min/max found
25904 #if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
25905 if (DataSumCnt[1] == 0):
25906 if PhactoriDbg(100):
25907 myDebugPrint3('no data value for min/max found, returning', 100)
25908 if PhactoriDbg(100):
25909 myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
25910 100)
25911 self.mReturnValAtCurrentFrameTagCounter = False
25912 return False
25913
25914 if self.mFunctionType == "maximum":
25915 mTestValue = DataMinMax[1]
25916 if PhactoriDbg():
25917 myDebugPrint3("test is against max, " + str(mTestValue) + "\n")
25918 elif self.mFunctionType == "minimum":
25919 mTestValue = DataMinMax[0]
25920 if PhactoriDbg():
25921 myDebugPrint3("test is against min, " + str(mTestValue) + "\n")
25922 elif self.mFunctionType == "mean":
25923 mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])
25924 if PhactoriDbg():
25925 myDebugPrint3("test is against mean, " + str(mTestValue) + "\n")
25926 elif self.mFunctionType == "sum":
25927 mTestValue = DataSumCnt[0]
25928 if PhactoriDbg():
25929 myDebugPrint3("test is against sum, " + str(mTestValue) + "\n")
25930 elif self.mFunctionType == "count":
25931 mTestValue = DataSumCnt[1]
25932 if PhactoriDbg():
25933 myDebugPrint3("test is against count, " + str(mTestValue) + "\n")
25934 else:
25935 myDebugPrint3AndException("PhactoriOnOffCriteria::TestForTruth"
25936 "bad mFunctionType: " + str(self.mFunctionType) + "\n")
25937
25938 #let each threshold see if this value crossed from the previous value,
25939 #and update its internal frame count as appropriate
25940 for oneThrsld in self.mThresholdList:
25941 oneThrsld.ObservePotentialCrossingValue(mTestValue)
25942
25943 #if any threshold was just triggered or was triggered and is within
25944 #the frame count limit, issue a 'True'
25945 for oneThrsld in self.mThresholdList:
25946 if oneThrsld.CurrentlyTriggered():
25947 self.mReturnValAtCurrentFrameTagCounter = True
25948 return True
25949
25950 self.mReturnValAtCurrentFrameTagCounter = False
25951 return False
25952
25953 #if self.mFunctionType == "maximum":
25954 # #possible issue, but probably not; if min/max is 0.0 we assume no
25955 # #data existed
25956 # #DataMinMax[2] == False: don't use this, it's not mpi shared
25957 # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
25958 # if PhactoriDbg(100):
25959 # myDebugPrint3('no data value for max found, returning', 100)
25960 # if PhactoriDbg(
25961 # 100):
25962 # myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
25963 # 100)
25964 # return False
25965 # else:
25966 # mTestValue = DataMinMax[1]
25967 # if PhactoriDbg():
25968 # myDebugPrint3("test is against max, " + str(mTestValue) + "\n")
25969 #elif self.mFunctionType == "minimum":
25970 # #possible issue, but probably not; if min/max is 0.0 we assume no
25971 # #data existed
25972 # #DataMinMax[2] == False: don't use this, it's not mpi shared
25973 # if (DataMinMax[0] == 0.0) and (DataMinMax[1] == 0.0):
25974 # if PhactoriDbg(100):
25975 # myDebugPrint3('no data value for min found, returning', 100)
25976 # if PhactoriDbg(
25977 # 100):
25978 # myDebugPrint3("PhactoriImagesetOnOffFilterCriteria returning false",
25979 # 100)
25980 # return False
25981 # else:
25982 # mTestValue = DataMinMax[0]
25983 # if PhactoriDbg():
25984 # myDebugPrint3("test is against min, " + str(mTestValue) + "\n")
25985 #elif self.mFunctionType == "mean":
25986 # if DataSumCnt[1] == 0:
25987 # if PhactoriDbg(100):
25988 # myDebugPrint3('no data values for mean found, returning false', 100)
25989 # return False
25990 # else:
25991 # mTestValue = float(DataSumCnt[1])/float(DataSumCnt[0])
25992 # if PhactoriDbg():
25993 # myDebugPrint3("test is against mean, " + str(mTestValue) + "\n")
25994 #elif self.mFunctionType == "sum":
25995 # mTestValue = DataSumCnt[0]
25996 # if PhactoriDbg():
25997 # myDebugPrint3("test is against sum, " + str(mTestValue) + "\n")
25998 #elif self.mFunctionType == "count":
25999 # mTestValue = DataSumCnt[1]
26000 # if PhactoriDbg():
26001 # myDebugPrint3("test is against count, " + str(mTestValue) + "\n")
26002
26003 #if PhactoriDbg():
26004 # myDebugPrint3("test range: " + str(self.mRange) + "\n")
26005 #if mTestValue < self.mRange[0]:
26006 # if PhactoriDbg(100):
26007 # myDebugPrint3('below range, returning false', 100)
26008 # return False
26009 #if mTestValue > self.mRange[1]:
26010 # if PhactoriDbg(100):
26011 # myDebugPrint3('above range, returning false', 100)
26012 # return False
26013
26014 #if PhactoriDbg(100):
26015 # myDebugPrint3('in range, returning true', 100)
26016
26017 #if PhactoriDbg(100):
26018 # myDebugPrint3("cp 6000")
26019
26020
26021 #self.mHasBeenTriggered = True
26022 #self.mCallbackTagAtFirstTrigger = ioPipeAndViewsState.mFrameTagCounter
26023 #return True
26024
26025 def ParseParametersFromJson(self, inJson):
26026 if PhactoriDbg(100):
26027 myDebugPrint3('PhactoriImagesetOnOffFilterCriteria::'
26028 'ParseParametersFromJson entered\n', 100)
26029
26030 foundVariableFlag = self.mVariableInfo.\
26031 ParseVariableNameAndVectorOrTensorComponent(
26032 inJson, 'variable ')
26033
26034 if foundVariableFlag == False:
26035 errStr = "error! inJson has no variable info in\n PhactoriImagesetOnOffFilterCriteria.ParseParametersFromJson\n"
26036 if PhactoriDbg():
26037 myDebugPrint3(errStr)
26038 raise Exception(errStr)
26039
26040 if 'input' in inJson:
26041 self.mInputOperationName = inJson['input']
26042 else:
26043 noticeStr = \
26044 'notice! inJson has no input key, using default pipeline input\n'
26045 self.mInputOperationName = None
26046 if PhactoriDbg():
26047 myDebugPrint3(noticeStr)
26048
26049 if PhactoriDbg():
26050 myDebugPrint3("variable name: " + \
26051 str(self.mVariableInfo.mVariableName) + "\n")
26052
26053 if 'type' in inJson:
26054 theType = inJson['type']
26055 #bug in parsing right now requires different if test
26056 #if theType == 'triggerthresholds':
26057 if theType == 'triggerthresholds' or theType == 'onoffcriteriablock':
26058 if 'threshold variable function' in inJson:
26059 self.mFunctionType = inJson['threshold variable function']
26060 if 'frames after trigger' in inJson:
26061 self.mNumberOfFramesAfterTrigger = \
26062 inJson['frames after trigger']
26063 if 'maximum triggers per threshold' in inJson:
26064 self.mMaxTriggersPerThreshold = \
26065 inJson['maximum triggers per threshold']
26066 for oneThreshold in inJson['threshold values']:
26067 newThrshld = PhactoriCriteriaThreshold(oneThreshold,
26068 self.mNumberOfFramesAfterTrigger,
26069 self.mMaxTriggersPerThreshold)
26070 self.mThresholdList.append(newThrshld)
26071
26072 if PhactoriDbg():
26073 myDebugPrint3("parsed min/max triggerthresholds\n")
26074 return
26075
26076 if 'keep between' in inJson:
26077 self.mRange = inJson['keep between']
26078 self.mFunctionType = "maximum"
26079 elif 'keep below' in inJson:
26080 rangeMin = -sys.float_info.max
26081 rangeMax = inJson['keep below']
26082 self.mRange = [rangeMin, rangeMax]
26083 self.mFunctionType = "minimum"
26084 elif 'keep above' in inJson:
26085 self.mFunctionType = "maximum"
26086 rangeMin = inJson['keep above']
26087 rangeMax = sys.float_info.max
26088 self.mRange = [rangeMin, rangeMax]
26089 elif 'trigger when maximum value is at or above' in inJson:
26090 self.mFunctionType = "maximum"
26091 rangeMin = inJson['trigger when maximum value is at or above']
26092 rangeMax = sys.float_info.max
26093 self.mRange = [rangeMin, rangeMax]
26094 elif 'trigger on maximum value' in inJson:
26095 self.mFunctionType = "maximum"
26096 rangeMin = inJson['trigger on maximum value']
26097 rangeMax = sys.float_info.max
26098 self.mRange = [rangeMin, rangeMax]
26099 elif 'trigger on minimum value' in inJson:
26100 self.mFunctionType = "minimum"
26101 rangeMin = -sys.float_info.max
26102 rangeMax = inJson['trigger on minimum value']
26103 self.mRange = [rangeMin, rangeMax]
26104 else:
26105 if PhactoriDbg():
26106 myDebugPrint3(" no keep between/above/below, using keep above 0.0\n")
26107 self.mFunctionType = "maximum"
26108 rangeMin = 0.0
26109 rangeMax = sys.float_info.max
26110 self.mRange = [rangeMin, rangeMax]
26111
26112 if 'number of frames after trigger' in inJson:
26113 self.mNumberOfFramesAfterTrigger = \
26114 inJson['number of frames after trigger']
26115
26116 if 'frames after trigger' in inJson:
26117 self.mNumberOfFramesAfterTrigger = \
26118 inJson['frames after trigger']
26119
26120 if PhactoriDbg():
26121 myDebugPrint3("range: " + str(self.mRange) + "\n")
26122
26123
26124 class PhactoriImagesetOnOffFilter:
26125 "\n this class manages the system whereby users can selectively\n choose to render or not render images based on simulation data. The first\n simple capability allows users to begin rendering after some simulation\n data criteria is met (e.g. maximum of element variable X is above Y), and\n stop rendering after some criteria is met"
26126
26127 def __init__(self):
26128 self.mEnabled = False
26129 self.mLastStartImagesFlag = False
26130 self.mStartCriteriaList = []
26131 #self.mStopCriteriaList = []
26132
26133 def AddStartCriteria(self, inNewCriteria):
26134 self.mEnabled = True
26135 self.mStartCriteriaList.append(inNewCriteria)
26136
26137 #def AddStopCriteria(self, inNewCriteria):
26138 # self.mEnabled = True
26139 # self.mStopCriteriaList.append(inNewCriteria)
26140
26141 def TestDrawImagesThisCallback(self, ioPipeAndViewsState):
26142 "returns True if images should be rendered, False if they should not"
26143
26144 if PhactoriDbg(
26145 100):
26146 myDebugPrint3(
26147 'PhactoriImagesetOnOffFilter::TestDrawImagesThisCallback entered\n',
26148 100)
26149
26150 #criteriaIndex = 0
26151 #for oneCriteria in self.mStartCriteriaList:
26152 # criteriaIndex += 1
26153 # myDebugPrint3("trying critera: " + str(criteriaIndex))
26154 # if oneCriteria.TestForTruth(ioPipeAndViewsState):
26155 # myDebugPrint3("criteria returned true")
26156 # else:
26157 # myDebugPrint3("criteria returned true")
26158 #return True
26159
26160 if self.mEnabled == False:
26161 if PhactoriDbg():
26162 myDebugPrint3("not enabled, return True\n")
26163 return True
26164
26165 #if images had already been started, keep doing them until a stop
26166 #criteria is hit
26167 #if self.mLastStartImagesFlag == True:
26168 # if PhactoriDbg():
26169 # myDebugPrint3(" returned true last time\n")
26170 # startImages = True
26171 #else:
26172 if True:
26173 #if no startup criteria are present, startup is assumed to be true
26174 if len(self.mStartCriteriaList) == 0:
26175 if PhactoriDbg():
26176 myDebugPrint3(" no criteria, default true\n")
26177 startImages = True
26178 else:
26179 if PhactoriDbg():
26180 myDebugPrint3(" criteria exists, default false\n")
26181 startImages = False
26182 for oneCriteria in self.mStartCriteriaList:
26183 if oneCriteria.TestForTruth(ioPipeAndViewsState):
26184 if PhactoriDbg():
26185 myDebugPrint3(" criteria returned true\n")
26186 startImages = True
26187 #at least one startup criteria is true
26188 break
26189
26190 #if images are going (even if they just started), check the stop criteria
26191 #to see if they need stopping
26192 #if startImages:
26193 # if len(self.mStopCriteriaList) != 0:
26194 # for oneCriteria in self.mStopCriteriaList:
26195 # if oneCriteria.TestForTruth(ioPipeAndViewsState):
26196 # startImages = False
26197 # #at least one stop criteria is true
26198 # break
26199
26200 self.mLastStartImagesFlag = startImages
26201 if PhactoriDbg(100):
26202 myDebugPrint3('returning with value: ' + str(startImages) + '\n', 100)
26203 return startImages
26204
26205 def ParseOneImageStartStopFilterFromViewMap(inOperationParamsJson):
26206 newFilterCriteria = PhactoriImagesetOnOffFilterCriteria()
26207 newFilterCriteria.ParseParametersFromJson(inOperationParamsJson)
26208 global gPipeAndViewsState
26209 gPipeAndViewsState.mImagesetOnOffFilter.AddStartCriteria(newFilterCriteria)
26210
26211
26212 def WriteOutImagesTest(datadescription, coprocessor):
26213 global gPipeAndViewsState
26214 return gPipeAndViewsState.mImagesetOnOffFilter.TestDrawImagesThisCallback(gPipeAndViewsState)
26215
26216 def CreateAllProducersFromAllInputDescriptions(datadescription, inCoprocessor, newRoot):
26217 global gPipeAndViewsState
26218 inputGrid0Name = datadescription.GetInputDescriptionName(0)
26219 #newRoot.mProducer = inCoprocessor.CreateProducer( datadescription, "input" )
26220 newRoot.mProducer = inCoprocessor.CreateProducer( datadescription, inputGrid0Name)
26221 newRoot.mIncomingDefaultOperation.mHasBeenConstructed = True
26222 newRoot.mIncomingDefaultOperation.mName = inputGrid0Name
26223 newRoot.mIncomingDefaultOperation.mOperationSpecifics = PhactoriOperationSpecifics()
26224 newRoot.mOperationBlocks[inputGrid0Name] = newRoot.mIncomingDefaultOperation
26225 numInputGrids = datadescription.GetNumberOfInputDescriptions()
26226 if PhactoriDbg():
26227 myDebugPrint3("numInputGrids: " + str(numInputGrids) + "\n");
26228 for ii in range(0,numInputGrids):
26229 myDebugPrint3(str(ii) + ": " + str(datadescription.GetInputDescriptionName(ii)) + "\n")
26230 defSrc = GetActiveSource();
26231 for ii in range(1,numInputGrids):
26232 incomingInputName = datadescription.GetInputDescriptionName(ii)
26233 newTrivialProducerForGrid = inCoprocessor.CreateProducer( datadescription, incomingInputName)
26234 theGrid = datadescription.GetInputDescription(ii).GetGrid()
26235 newIncomingOperationBlock = PhactoriOperationBlock()
26236 newIncomingOperationBlock.mName = incomingInputName
26237 newIncomingOperationBlock.mParaViewFilter = newTrivialProducerForGrid
26238 newIncomingOperationBlock.mHasBeenConstructed = True
26239 newIncomingOperationBlock.mOperationSpecifics = PhactoriOperationSpecifics()
26240 #newRoot.mIncomingOperationList.append(newIncomingOperationBlock)
26241 #newRoot.mIncomingGridProducerList.append(newTrivialProducerForGrid)
26242 newRoot.mOperationBlocks[newIncomingOperationBlock.mName] = newIncomingOperationBlock
26243 SetActiveSource(defSrc);
26244
26245 def InitializePerPipeRoot(datadescription, inCoprocessor):
26246 if PhactoriDbg():
26247 myDebugPrint3("InitializePerPipeRoot entered\n")
26248
26249 sa = GetUserDataStringArrayAccountingForBypass(datadescription)
26250
26251 testJsonString = sa[0]
26252 separatorCharacterString = sa[1]
26253 inputDeckFilename = sa[2]
26254 extraFileString = sa[3]
26255 sa4 = sa[4]
26256 sa5 = sa[5]
26257 dbDummyFname = sa[6]
26258 if(len(sa) > 7):
26259 defaultDirectory = sa[7]
26260 else:
26261 defaultDirectory = ""
26262 if(len(sa) > 8):
26263 catalyst_script_extra_file = sa[8]
26264 else:
26265 catalyst_script_extra_file = ""
26266
26267 outputResultBaseId, remeshRestartTag = parseDbDummyFname(dbDummyFname)
26268 if PhactoriDbg():
26269 myDebugPrint3(" extra data list:\n")
26270 if PhactoriDbg():
26271 myDebugPrint3(" separatorCharacterString: ->" + separatorCharacterString + "<-\n")
26272 if PhactoriDbg():
26273 myDebugPrint3(" inputDeckFilename: ->" + inputDeckFilename + "<-\n")
26274 if PhactoriDbg():
26275 myDebugPrint3(" extraFileString: ->" + extraFileString + "<-\n")
26276 if PhactoriDbg():
26277 myDebugPrint3(" sa4: ->" + sa4 + "<-\n")
26278 if PhactoriDbg():
26279 myDebugPrint3(" sa5: ->" + sa5 + "<-\n")
26280 if PhactoriDbg():
26281 myDebugPrint3(" dbDummyFname: ->" + dbDummyFname + "<-\n")
26282 if PhactoriDbg():
26283 myDebugPrint3(" outputResultBaseId: ->" + outputResultBaseId + "<-\n")
26284 if PhactoriDbg():
26285 myDebugPrint3(" remeshRestartTag: ->" + remeshRestartTag + "<-\n")
26286 if PhactoriDbg():
26287 myDebugPrint3(" defaultDirectory: ->" + defaultDirectory + "<-\n")
26288 if PhactoriDbg():
26289 myDebugPrint3(" catalyst_script_extra_file: ->" + catalyst_script_extra_file + "<-\n")
26290
26291 global gPipeAndViewsState
26292
26293 if outputResultBaseId in gPhactoriPipeRootMap:
26294 if PhactoriDbg():
26295 myDebugPrint3(" I've seen this outputResults block id\n")
26296 oneRoot = gPhactoriPipeRootMap[outputResultBaseId]
26297 oneRoot.CurrentDatadescription = datadescription
26298 gPipeAndViewsState = oneRoot
26299 if remeshRestartTag != oneRoot.mRemeshRestartTag:
26300 oneRoot.mRemeshRestartTag = remeshRestartTag
26301 oneRoot.mRemeshCount += 1
26302 HandleUserInteractionIfEnabled(oneRoot)
26303 else:
26304 if PhactoriDbg():
26305 myDebugPrint3(" first time for this outputResults block id\n")
26306 SetUpCoProcessor(inCoprocessor)
26307 newRoot = PhactoriPipeAndViewsState()
26308 newRoot.mDefaultBasedirectory = defaultDirectory
26309 newRoot.CurrentDatadescription = datadescription
26310 newRoot.mOutputResultsBlockId = outputResultBaseId
26311 newRoot.mCurrentDatabaseDummyFileName = dbDummyFname
26312 newRoot.mRemeshRestartTag = remeshRestartTag
26313 newRoot.mSeparatorString = separatorCharacterString
26314 newRoot.mOutputResultsBlockCountId = len(gPhactoriPipeRootMap)
26315 newRoot.mBlockIdForRestart = "restart." + str(len(gPhactoriPipeRootMap))
26316 gPhactoriPipeRootMap[outputResultBaseId] = newRoot
26317 gPipeAndViewsState = newRoot
26318 CreateAllProducersFromAllInputDescriptions(datadescription, inCoprocessor, newRoot)
26319
26320 CreatePipelineFromDataDescription(datadescription)
26321 HandleRestartUpdateForOutputResultsBlock(newRoot)
26322
26323 gPipeAndViewsState.mCallbackDateTime = datetime.datetime.now()
26324
26325 if PhactoriDbg():
26326 myDebugPrint3("InitializePerPipeRoot returning\n")
26327
26328
26329 global gColorLegendCollection
26330 gColorLegendCollection = {
26331 "Default":{
26332 "ColorSpace":"Diverging",
26333 "NanColor":[0.25, 0.0, 0.0],
26334 "RGBPoints":[
26335 0.0, 0.23000000000000001, 0.29899999999999999, 0.754,
26336 1.0, 0.70599999999999996, 0.016, 0.14999999999999999
26337 ]
26338 },
26339 "Cool to Warm":{
26340 "ColorSpace":"Diverging",
26341 "NanColor":[0.247058823529, 0.0, 0.0],
26342 "RGBPoints":[
26343 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
26344 0.5, 0.865, 0.865, 0.865,
26345 1.0, 0.705882352941, 0.0156862745098, 0.149019607843
26346 ]
26347 },
26348 "Blue to Red Rainbow":{
26349 "ColorSpace":"HSV",
26350 "NanColor":[0.498039215686, 0.498039215686, 0.498039215686],
26351 "RGBPoints":[
26352 0.0, 0.0, 0.0, 1.0,
26353 1.0, 1.0, 0.0, 0.0
26354 ]
26355 },
26356 "Red to Blue Rainbow":{
26357 "ColorSpace":"HSV",
26358 "NanColor":[0.498039215686, 0.498039215686, 0.498039215686],
26359 "RGBPoints":[
26360 0.0, 1.0, 0.0, 0.0,
26361 1.0, 0.0, 0.0, 1.0
26362 ]
26363 },
26364 "Grayscale":{
26365 "ColorSpace":"RGB",
26366 "NanColor":[1.0, 0.0, 0.0],
26367 "RGBPoints":[
26368 0.0, 0.0, 0.0, 0.0,
26369 1.0, 1.0, 1.0, 1.0
26370 ]
26371 },
26372 "X Ray":{
26373 "ColorSpace":"RGB",
26374 "NanColor":[1.0, 0.0, 0.0],
26375 "RGBPoints":[
26376 0.0, 1.0, 1.0, 1.0,
26377 1.0, 0.0, 0.0, 0.0
26378 ]
26379 },
26380 "Blue to Yellow":{
26381 "ColorSpace":"RGB",
26382 "NanColor":[1.0, 0.0, 0.0],
26383 "RGBPoints":[
26384 0.0, 0.0392156862745, 0.0392156862745, 0.949019607843,
26385 1.0, 0.949019607843, 0.949019607843, 0.0392156862745
26386 ]
26387 },
26388 #"Black-Body Radiation":{}
26389 "Black Body Radiation":{
26390 "ColorSpace":"RGB",
26391 "NanColor":[0.0, 0.498039215686, 1.0],
26392 "RGBPoints":[
26393 0.0, 0.0, 0.0, 0.0,
26394 0.4, 0.901960784314, 0.0, 0.0,
26395 0.8, 0.901960784314, 0.901960784314, 0.0,
26396 1.0, 1.0, 1.0, 1.0
26397 ]
26398 },
26399 "CIELab Blue to Red":{
26400 "ColorSpace":"Lab",
26401 "NanColor":[1.0, 1.0, 0.0],
26402 "RGBPoints":[
26403 0.0, 0.0, 0.6, 0.749019607843,
26404 1.0, 0.76862745098, 0.466666666667, 0.341176470588
26405 ]
26406 },
26407 "Black, Blue and White":{
26408 "ColorSpace":"RGB",
26409 "NanColor":[1.0, 1.0, 0.0],
26410 "RGBPoints":[
26411 0.0, 0.0, 0.0, 0.0,
26412 0.333, 0.0, 0.0, 0.501960784314,
26413 0.666, 0.0, 0.501960784314, 1.0,
26414 1.0, 1.0, 1.0, 1.0
26415 ]
26416 },
26417 "Black, Orange and White":{
26418 "ColorSpace":"RGB",
26419 "NanColor":[1.0, 1.0, 0.0],
26420 "RGBPoints":[
26421 0.0, 0.0, 0.0, 0.0,
26422 0.333, 0.501960784314, 0.0, 0.0,
26423 0.666, 1.0, 0.501960784314, 0.0,
26424 1.0, 1.0, 1.0, 1.0
26425 ]
26426 },
26427 "Cold and Hot":{
26428 "ColorSpace":"RGB",
26429 "NanColor":[1.0, 1.0, 0.0],
26430 "RGBPoints":[
26431 0.0, 0.0, 1.0, 1.0,
26432 0.45, 0.0, 0.0, 1.0,
26433 0.5, 0.0, 0.0, 0.501960784314,
26434 0.55, 1.0, 0.0, 0.0,
26435 1.0, 1.0, 1.0, 0.0
26436 ]
26437 },
26438 "Rainbow Desaturated":{
26439 "ColorSpace":"RGB",
26440 "NanColor":[1.0, 1.0, 0.0],
26441 "RGBPoints":[
26442 0.0, 0.278431372549, 0.278431372549, 0.858823529412,
26443 0.143, 0.0, 0.0, 0.360784313725,
26444 0.285, 0.0, 1.0, 1.0,
26445 0.429, 0.0, 0.501960784314, 0.0,
26446 0.571, 1.0, 1.0, 0.0,
26447 0.714, 1.0, 0.380392156863, 0.0,
26448 0.857, 0.419607843137, 0.0, 0.0,
26449 1.0, 0.878431372549, 0.301960784314, 0.301960784314
26450 ]
26451 },
26452 "Rainbow Blended White":{
26453 "ColorSpace":"RGB",
26454 "NanColor":[1.0, 1.0, 0.0],
26455 "RGBPoints":[
26456 0.0, 1.0, 1.0, 1.0,
26457 0.17, 0.0, 0.0, 1.0,
26458 0.34, 0.0, 1.0, 1.0,
26459 0.5, 0.0, 1.0, 0.0,
26460 0.67, 1.0, 1.0, 0.0,
26461 0.84, 1.0, 0.0, 0.0,
26462 1.0, 0.878431372549, 0.0, 1.0
26463 ]
26464 },
26465 "Rainbow Blended Grey":{
26466 "ColorSpace":"RGB",
26467 "NanColor":[1.0, 1.0, 0.0],
26468 "RGBPoints":[
26469 0.0, 0.317647058824, 0.341176470588, 0.43137254902,
26470 0.17, 0.0, 0.0, 1.0,
26471 0.34, 0.0, 1.0, 1.0,
26472 0.5, 0.0, 1.0, 0.0,
26473 0.67, 1.0, 1.0, 0.0,
26474 0.84, 1.0, 0.0, 0.0,
26475 1.0, 0.878431372549, 0.0, 1.0
26476 ]
26477 },
26478 #"Cool to Warm with Top":{
26479 # "ColorSpace":"Diverging",
26480 # "NanColor":[0.247058823529, 0.0, 0.0],
26481 # "RGBPoints":[
26482 # 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
26483 # 0.5, 0.865, 0.865, 0.865,
26484 # 0.98, 0.705882352941, 0.0156862745098, 0.149019607843,
26485 # 1.0, 0.0, 1.0, 1.0,
26486 # ]
26487 #},
26488 "Cool to Warm with Top":{
26489 "ColorSpace":"Diverging",
26490 #"ColorSpace":"RGB",
26491 "NanColor":[0.247058823529, 0.0, 0.0],
26492 "RGBPoints":[
26493 0.0, 0.23137254902, 0.298039215686, 0.752941176471,
26494 0.5, 0.865, 0.865, 0.865,
26495 0.799, 0.769528, 0.355412, 0.435412,
26496 0.800, 0.0, 1.0, 1.0,
26497 0.814, 0.0, 1.0, 1.0,
26498 0.815, 0.769528, 0.355412, 0.435412,
26499 1.0, 0.705882352941, 0.0156862745098, 0.149019607843,
26500 ]
26501 },
26502 }
26503
26504 def GetColorMapInfoFromColorLegendCollection(inColorMapSettings, inMin, inMax):
26505 global gColorLegendCollection
26506
26507 inStrId = inColorMapSettings.mColorMapNameId
26508
26509 #convert underscores (if any) to spaces in key
26510 inStrId = inStrId.replace('_', ' ')
26511
26512 if inStrId not in gColorLegendCollection:
26513 if PhactoriDbg(600):
26514 myDebugPrint3("GetColorMapInfoFromColorLegendCollection: bad map name:" +\
26515 str(inStrId) + " using Default\n", 600)
26516 inStrId = "Default"
26517 colorLegendItem = gColorLegendCollection[inStrId]
26518 outRGBPoints = list(colorLegendItem["RGBPoints"])
26519 outNanColor = list(colorLegendItem["NanColor"])
26520 outColorSpace = str(colorLegendItem["ColorSpace"])
26521
26522 #invert color map if requested
26523 if inColorMapSettings.mInvertColorMap:
26524 newOutRGBPoints = list()
26525 #step through the points (4 doubles) backwards and put them on a new
26526 #list in reverse order, also reversing the position value
26527 for ii in range(len(outRGBPoints) - 4, -1, -4):
26528 newOutRGBPoints.append(1.0 - outRGBPoints[ii])
26529 newOutRGBPoints.append(outRGBPoints[ii+1])
26530 newOutRGBPoints.append(outRGBPoints[ii+2])
26531 newOutRGBPoints.append(outRGBPoints[ii+3])
26532 #myDebugPrint3("uninverted list:")
26533 #for ii in range(0, len(outRGBPoints), 4):
26534 # myDebugPrint3(" " + \
26535 # str(outRGBPoints[ii]) + ", " + \
26536 # str(outRGBPoints[ii+1]) + ", " + \
26537 # str(outRGBPoints[ii+2]) + ", " + \
26538 # str(outRGBPoints[ii+3]) + "\n")
26539 #myDebugPrint3("inverted list:")
26540 #for ii in range(0, len(newOutRGBPoints), 4):
26541 # myDebugPrint3(" " + \
26542 # str(newOutRGBPoints[ii]) + ", " + \
26543 # str(newOutRGBPoints[ii+1]) + ", " + \
26544 # str(newOutRGBPoints[ii+2]) + ", " + \
26545 # str(newOutRGBPoints[ii+3]) + "\n")
26546 outRGBPoints = newOutRGBPoints
26547
26548 numVals = len(outRGBPoints)
26549 delta = inMax - inMin
26550 for ii in range(0, numVals, 4):
26551 ratio = outRGBPoints[ii]
26552 outRGBPoints[ii] = inMin + ratio * delta
26553 return (outRGBPoints, outColorSpace, outNanColor)
26554
26555
26556
26557 myDebugPrint3("gParaViewCatalystVersionFlag is: " + str(gParaViewCatalystVersionFlag) +"\n")
26558
26559
26560
26561 #do sierra/catalyst logging (from process id 0 only)
26562 #note: logging should be disabled for testing, but enabled for production
26563 if SmartGetLocalProcessId() == 0:
26564 import os
26565 import datetime
26566
26567 loggingIsEnabled = True
26568 if "SNL_CATALYST_SIERRA_USAGE_LOG_FLAG" in os.environ:
26569 #print "SNL_CATALYST_SIERRA_USAGE_LOG_FLAG environment variable: " + \
26570 #os.environ["SNL_CATALYST_SIERRA_USAGE_LOG_FLAG"]
26571 if os.environ["SNL_CATALYST_SIERRA_USAGE_LOG_FLAG"] == "disable":
26572 loggingIsEnabled = False
26573
26574 if loggingIsEnabled:
26575 #print "I am process 0 doing logging!"
26576 if "HOSTNAME" in os.environ:
26577 os.environ["LOG_PLATFORM"] = os.environ["HOSTNAME"]
26578 else:
26579 os.environ["LOG_PLATFORM"] = "HOSTNAMEnotset"
26580 os.environ["LOG_PRODUCT"] = "sierra-catalyst"
26581 os.environ["CATALYST_VERSION"] = "p4.1.0-s4.31.6-p"
26582 nowdate = datetime.datetime.now()
26583 #os.environ["DATE"] = str(nowdate.month) + "/" + str(nowdate.day) + "/" + str(nowdate.year)
26584 #currently, DATE environment variable is overwritten in logParserScr script
26585 #print "date is : " + os.environ["DATE"]
26586 import subprocess
26587 try:
26588 subprocess.call("/projects/viz/catalyst/utilities/logParserScr")
26589 except:
26590 print("usage logging warning: logParserScr call failed\n")
26591
26592 #print "platform: " + os.environ["LOG_PLATFORM"]
26593 #print "product: " + os.environ["LOG_PRODUCT"]
26594 #print "version: " + os.environ["CATALYST_VERSION"]
26595 #print "date: ->" + os.environ["DATE"] + "<-"
26596 #print "I am process 0 done logging!"
26597 #else:
26598 #print "I am process 0, logging disabled in environment variable"
26599
26600 #def UseViewMapB(inViewMapB):
26601 # PhactoriScript.UseViewMapB_ps(inViewMapB)
26602
26603 #def UseDataSetupMapB(inDataSetupMapB):
26604 # PhactoriScript.UseDataSetupMapB_ps(inDataSetupMapB)
26605
26606 global gMyInitialUpdateFrequencies
26607 gMyInitialUpdateFrequencies = {}
26608
26609 def CreateCoProcessor():
26610 def _CreatePipeline(coprocessor, datadescription):
26611 class Pipeline:
26612 dummyItem = "blah"
26613 #global cp_views, cp_writers
26614
26615 #print "CreatePipeline startup"
26616 #print "cp_views len is " + str(len(cp_views))
26617
26618 #rigid_body_impact_6_ff_e = coprocessor.CreateProducer( datadescription, "input" )
26619
26620 #SetUpCoProcessor(coprocessor)
26621 #SetCpViewsAndCpWriters(cp_views, cp_writers)
26622
26623 #QQQQQ->we want to do this and CreateProducer once for each output results block,
26624 #reuse same coprocesor instance (?), then have LocalWriteImages3 only do the images for a given output results bloxk:q
26625
26626 #PhactoriScript.CreatePipeline(datadescription)
26627
26628 return Pipeline()
26629
26630 class CoProcessor(coprocessing.CoProcessor):
26631 def CreatePipeline(self, datadescription):
26632 self.Pipeline = _CreatePipeline(self, datadescription)
26633
26634 def LocalWriteImages3(self, datadescription, rescale_lookuptable=False):
26635 WriteImagesForCurrentPipeAndViewsState(datadescription)
26636
26637 def LocalExportOperationsData3(self, datadescription, rescale_lookuptable=False):
26638 ExportOperationsDataForCurrentPipeAndViewsState(datadescription)
26639
26640 def SetInitialUpdateFrequences(self, datadescription):
26641 global gMyInitialUpdateFrequencies
26642 freqsChanged = False
26643 numInputGrids = datadescription.GetNumberOfInputDescriptions()
26644 for ii in range(0,numInputGrids):
26645 oneGridName = datadescription.GetInputDescriptionName(ii)
26646 if PhactoriDbg():
26647 myDebugPrint3("SetInitialUpdateFrequences " + str(ii) + " " + str(oneGridName) + "\n")
26648 if oneGridName not in gMyInitialUpdateFrequencies:
26649 gMyInitialUpdateFrequencies[oneGridName] = [1]
26650 freqsChanged = True
26651 if PhactoriDbg():
26652 if freqsChanged:
26653 myDebugPrint3("gMyInitialUpdateFrequencies changed:\n")
26654 else:
26655 myDebugPrint3("gMyInitialUpdateFrequencies not changed:\n")
26656 myDebugPrint3(str(gMyInitialUpdateFrequencies) + "\n")
26657 if freqsChanged:
26658 self.SetUpdateFrequencies(gMyInitialUpdateFrequencies)
26659
26660 coprocessor = CoProcessor()
26661 #freqs = {'input': [1]}
26662 #coprocessor.SetUpdateFrequencies(freqs)
26663 return coprocessor
26664
26665
26666 #--------------------------------------------------------------
26667 # Global variables that will hold the pipeline for each timestep
26668 # Creating the CoProcessor object, doesn't actually create the ParaView pipeline.
26669 # It will be automatically setup when coprocessor.UpdateProducers() is called the
26670 # first time.
26671 #coprocessor = CreateCoProcessor()
26672 coprocessor = None
26673
26674 #--------------------------------------------------------------
26675 # Enable Live-Visualizaton with ParaView
26676 #coprocessor.EnableLiveVisualization(False)
26677
26678 global gDoNewScatterPlotsC
26679 gDoNewScatterPlotsC = True
26680 #gDoNewScatterPlotsC = False
26681
26682 def PerFrameUpdate(datadescription):
26683 PerRendersetInitialization(datadescription)
26684 UpdateAllOperationsWhichMayChangeWithData()
26685 UpdateAllImagesetViewsWhichMayChangeWithData()
26686
26687 #we are now updating color range stuff right before WriteImage
26688 #UpdateDataRangesForColorValues()
26689
26690 myDebugPrint3('PerFrameUpdate entered\n')
26691 #GetAndReduceViewControl()
26692 global tearListPersistent
26693 global deathListPersistent
26694
26695 global gDoNewScatterPlotsC
26696 if gDoNewScatterPlotsC:
26697 myDebugPrint3('doing UpdateAllScatterPlots (C)\n')
26698 UpdateAllScatterPlots()
26699 myDebugPrint3('doing UpdateAllPlotsOverTime\n')
26700 UpdateAllPlotsOverTime()
26701 myDebugPrint3('did plot updates\n')
26702
26703 #currentFrameTearList = CollectCells1('TEAR_DOUBLE', 0.01, 1)
26704 #tearListPersistent = mergeCurrentIntoPersistent(tearListPersistent,
26705 # currentFrameTearList)
26706 #currentFrameDeathList = CollectCells1('STATUS', 0.8, -1)
26707 #deathListPersistent = mergeCurrentIntoPersistent(deathListPersistent,
26708 # currentFrameDeathList)
26709 #compareTearDeath(tearListPersistent, deathListPersistent)
26710
26711 myDebugPrint3('PerFrameUpdate exiting\n')
26712
26713
26714 #begin tear/death persistence; not used now but may be useful later
26715 global tearListPersistent
26716 tearListPersistent = []
26717 global deathListPersistent
26718 deathListPersistent = []
26719
26720 def mergeCipCompare(item1, item2):
26721 if item1[1] > item2[1]:
26722 return 1
26723 if item1[1] < item2[1]:
26724 return -1
26725 if item1[2] > item2[2]:
26726 return 1
26727 if item1[2] < item2[2]:
26728 return -1
26729 return 0
26730
26731 def mergeCurrentIntoPersistent(pList, cList):
26732 myDebugPrint2('mergeCurrentIntoPersistent entered\n')
26733 pListLen = len(pList)
26734 cListLen = len(cList)
26735 myDebugPrint2(' pList has ' + str(pListLen) + ' elements, cList has ' + str(cListLen) + ' elements\n')
26736 pIndex = 0
26737 cIndex = 0
26738 mergeList = []
26739 while (pIndex < pListLen) or (cIndex < cListLen):
26740 if(pIndex >= pListLen):
26741 mergeList.append(cList[cIndex])
26742 #myDebugPrint2(' pIndex ' + str(pIndex) + ' cIndex ' + str(cIndex) + '\n')
26743 #myDebugPrint2(' (p ended) [cIndex] ' + str(cList[cIndex]) + '\n')
26744 cIndex += 1
26745 continue
26746 if(cIndex >= cListLen):
26747 mergeList.append(pList[pIndex])
26748 #myDebugPrint2(' pIndex ' + str(pIndex) + ' cIndex ' + str(cIndex) + '\n')
26749 #myDebugPrint2(' (c ended) [pIndex] ' + str(cList[pIndex]) + '\n')
26750 pIndex += 1
26751 continue
26752 compareResult = mergeCipCompare(cList[cIndex], pList[pIndex])
26753 #myDebugPrint2(' pIndex ' + str(pIndex) + ' cIndex ' + str(cIndex) + '\n')
26754 #myDebugPrint2(' [pIndex] ' + str(pList[pIndex]) + ' [cIndex] ' + str(cList[cIndex]) + '\n')
26755 if compareResult == 1:
26756 #myDebugPrint2(' item from pList is less\n')
26757 mergeList.append(pList[pIndex])
26758 pIndex += 1
26759 if compareResult == -1:
26760 #myDebugPrint2(' item from cList is less\n')
26761 mergeList.append(cList[cIndex])
26762 cIndex += 1
26763 if compareResult == 0:
26764 #myDebugPrint2(' items from cList and pList are same element\n')
26765 mergeList.append(pList[pIndex])
26766 pIndex += 1
26767 cIndex += 1
26768 myDebugPrint2(' merged list has ' + str(len(mergeList)) + ' elements\n')
26769 myDebugPrint2('mergeCurrentIntoPersistent returning\n')
26770 return mergeList
26771
26772 def compareTearDeath(tList, dList):
26773 myDebugPrint2('compareTearDeath entered\n')
26774 myDebugPrint2('compareTearDeath returning\n')
26775 #end tear/death persistence; not used now but may be useful later
26776
26777
26778 # ---------------------- Data Selection method ----------------------
26779
26780 global gFirstTimeInDoCoProcessing
26781 gFirstTimeInDoCoProcessing = True
26782 global gSkipCountdown
26783 #gSkipCountdown = 3
26784 gSkipCountdown = 0
26785
26786 global gCatchAllExceptionsAndPassUpFlag
26787 gCatchAllExceptionsAndPassUpFlag = True
26788 #gCatchAllExceptionsAndPassUpFlag = False
26789
26790 def RequestDataDescription(datadescription):
26791 myDebugPrint3("PhactoriDriver.RequestDataDescription entered: " + str(gDoCoProcessingCount)+ "\n");
26792 if PhactoriDbg():
26793 numInputGrids = datadescription.GetNumberOfInputDescriptions()
26794 for ii in range(0,numInputGrids):
26795 oneGridName = datadescription.GetInputDescriptionName(ii)
26796 myDebugPrint3("RequestDataDescription " + str(ii) + " " + str(oneGridName) + "\n")
26797
26798 TestUserDataForBypassScript(datadescription)
26799
26800 if GetBypassUserDataFlag() == False:
26801 fd = datadescription.GetUserData()
26802
26803 if fd == None:
26804 myDebugPrint2("no user data, returning {}\n")
26805 returnViewMapC = {}
26806 return returnViewMapC
26807
26808 global gCatchAllExceptionsAndPassUpFlag
26809 if gCatchAllExceptionsAndPassUpFlag:
26810 try:
26811 return RequestDataDescriptionSub(datadescription)
26812 except:
26813 import traceback
26814 tb = traceback.format_exc()
26815 IssueErrorOrWarningThroughSierraIO(datadescription, tb, True)
26816 else:
26817 return RequestDataDescriptionSub(datadescription)
26818
26819 def RequestDataDescriptionSub(datadescription):
26820 myDebugPrint("PhactoriDriver.RequestDataDescriptionSub entered\n");
26821 "Callback to populate the request for current timestep"
26822
26823 TestUserDataForBypassScript(datadescription)
26824
26825 if GetBypassUserDataFlag() == False:
26826 fd = datadescription.GetUserData()
26827
26828 if fd == None:
26829 myDebugPrint2("no user data, returning {}\n")
26830 returnViewMapC = {}
26831 return returnViewMapC
26832
26833 global coprocessor
26834
26835 global gFirstTimeInDoCoProcessing
26836 global gSkipCountdown
26837
26838 if gFirstTimeInDoCoProcessing == True:
26839 myDebugPrint2("RequestDataDescription doing gFirstTimeInDoCoProcessing\n")
26840 myDebugPrint2(" skip countdown is " + str(gSkipCountdown) + "\n")
26841 if gSkipCountdown > 0:
26842 gSkipCountdown = gSkipCountdown - 1
26843 return 0
26844 coprocessor = CreateCoProcessor()
26845 coprocessor.SetInitialUpdateFrequences(datadescription)
26846 coprocessor.EnableLiveVisualization(False)
26847 gFirstTimeInDoCoProcessing = False
26848 else:
26849 coprocessor.SetInitialUpdateFrequences(datadescription)
26850
26851 #import pdb
26852 #pdb.set_trace()
26853
26854 InitializePerPipeRoot(datadescription, coprocessor)
26855
26856 if datadescription.GetForceOutput() == True:
26857 # We are just going to request all fields and meshes from the simulation
26858 # code/adaptor.
26859 for i in range(datadescription.GetNumberOfInputDescriptions()):
26860 datadescription.GetInputDescription(i).AllFieldsOn()
26861 datadescription.GetInputDescription(i).GenerateMeshOn()
26862 return 1
26863
26864 # setup requests for all inputs based on the requirements of the
26865 # pipeline.
26866 coprocessor.LoadRequestedData(datadescription)
26867 return 1
26868
26869
26870
26871
26872 # ------------------------ Processing method ------------------------
26873
26874 global tripleBufferCount
26875 tripleBufferCount = 0
26876
26877 global gDoCoProcessingCount
26878 gDoCoProcessingCount = 0
26879
26880 def DoCoProcessing(datadescription):
26881 myDebugPrint3("PhactoriDriver.DoCoProcessing entered: " + str(gDoCoProcessingCount)+ "\n");
26882 if PhactoriDbg():
26883 numInputGrids = datadescription.GetNumberOfInputDescriptions()
26884 for ii in range(0,numInputGrids):
26885 oneGridName = datadescription.GetInputDescriptionName(ii)
26886 myDebugPrint3("DoCoProcessing " + str(ii) + " " + str(oneGridName) + "\n")
26887
26888
26889 fd = datadescription.GetUserData()
26890
26891 if GetBypassUserDataFlag() == False:
26892 if fd == None:
26893 myDebugPrint2("no user data, returning {}\n")
26894 returnViewMapC = {}
26895 return returnViewMapC
26896
26897 global gCatchAllExceptionsAndPassUpFlag
26898 if gCatchAllExceptionsAndPassUpFlag:
26899 try:
26900 DoCoProcessingSub(datadescription)
26901 except:
26902 import traceback
26903 tb = traceback.format_exc()
26904 IssueErrorOrWarningThroughSierraIO(datadescription, tb, True)
26905 else:
26906 DoCoProcessingSub(datadescription)
26907
26908 def DoCoProcessingSub(datadescription):
26909 "Callback to do co-processing for current timestep"
26910
26911 global gDoCoProcessingCount
26912 myDebugPrint3("PhactoriDriver.DoCoProcessingSub entered: " + str(gDoCoProcessingCount)+ "\n");
26913
26914 gDoCoProcessingCount += 1
26915
26916
26917 fd = datadescription.GetUserData()
26918
26919 if GetBypassUserDataFlag() == False:
26920 if fd == None:
26921 myDebugPrint2("no user data, returning {}\n")
26922 returnViewMapC = {}
26923 return returnViewMapC
26924
26925 global coprocessor
26926 global gFirstTimeInDoCoProcessing
26927 global gSkipCountdown
26928
26929 if gFirstTimeInDoCoProcessing == True:
26930 myDebugPrint2("DoCoProcessing doing gFirstTimeInDoCoProcessing\n")
26931 myDebugPrint2(" skip countdown is " + str(gSkipCountdown) + "\n")
26932 if gSkipCountdown > 0:
26933 return
26934 coprocessor = CreateCoProcessor()
26935 coprocessor.SetInitialUpdateFrequences(datadescription)
26936 coprocessor.EnableLiveVisualization(False)
26937 gFirstTimeInDoCoProcessing = False
26938 else:
26939 coprocessor.SetInitialUpdateFrequences(datadescription)
26940
26941 #import pdb
26942 #pdb.set_trace()
26943
26944 InitializePerPipeRoot(datadescription, coprocessor)
26945
26946 "Callback to do co-processing for current timestep"
26947 timestep = datadescription.GetTimeStep()
26948
26949 myDebugPrint("timestep is: " + str(timestep) + "\n");
26950
26951 SmartGetLocalProcessId()
26952
26953 # Load the Pipeline if not created yet
26954 #if not pipeline:
26955 # myDebugPrint("PhactoriDriver.DoCoProcessing creating pipeline\n");
26956 # pipeline = CreatePipeline(datadescription)
26957 #else:
26958 # myDebugPrint("PhactoriDriver.DoCoProcessing updating pipeline\n");
26959 # # update to the new input and time
26960 # UpdateProducers(datadescription)
26961 # PerFrameUpdate(datadescription)
26962
26963
26964 # Update the coprocessor by providing it the newly generated simulation data.
26965 # If the pipeline hasn't been setup yet, this will setup the pipeline.
26966 coprocessor.UpdateProducers(datadescription)
26967
26968 PerFrameUpdate(datadescription)
26969
26970 # check for simulation-data-based i/o filtering--skip image creation
26971 # and writing if criteria has been set up to determine whether to
26972 # create images, such as 'maximum of variable X above 80.0'
26973 result = WriteOutImagesTest(datadescription, coprocessor)
26974 if result == False:
26975 #don't write images
26976 return
26977
26978 # Write output data, if appropriate.
26979 #coprocessor.WriteData(datadescription);
26980
26981 # Write output data
26982 #WriteAllData(datadescription, cp_writers, timestep);
26983
26984 # Write image capture (Last arg: rescale lookup table)
26985 #myDebugPrint("PhactoriDriver.DoCoProcessing writing images\n");
26986 #LocalWriteAllImages(datadescription, cp_views, timestep, False)
26987 #WriteAllImages(datadescription, cp_views, timestep, False)
26988
26989 # Live Visualization
26990 #if (len(cp_views) == 0) and live_visu_active:
26991 # DoLiveInsitu(timestep, pv_host, pv_port)
26992
26993 # Write output data, if appropriate.
26994 coprocessor.WriteData(datadescription)
26995
26996 coprocessor.LocalExportOperationsData3(datadescription)
26997
26998 # Write image capture (Last arg: rescale lookup table), if appropriate.
26999 coprocessor.LocalWriteImages3(datadescription,
27000 rescale_lookuptable=False)
27001
27002 #test and allow for looping when doing user vis interaction while
27003 #pausing simulation
27004 continueWriteAndInteractionCheckLoop = True
27005 while continueWriteAndInteractionCheckLoop:
27006 interactionTestResult = \
27007 DoUserInteractionWithSimulationPausedIfEnabled()
27008 if interactionTestResult == 0:
27009 #looping interaction is not or is no longer on; allow simulation to
27010 #continue
27011 continueWriteAndInteractionCheckLoop = False
27012 elif interactionTestResult == 1:
27013 #looping interaction is on, but there were no changes to the vis
27014 #(i.e. no trigger was given to update vis). Therefore do not write
27015 #images, but continue looping and waiting for vis change trigger
27016 continueWriteAndInteractionCheckLoop = True
27017 elif interactionTestResult == 2:
27018 #there was a vis change triggered; update the images for the new
27019 #vis, write out the images, and continue looping
27020 continueWriteAndInteractionCheckLoop = True
27021 imagesNeedWriting = True
27022 if imagesNeedWriting:
27023 UpdateAllImagesetViewsWhichMayChangeWithData()
27024 coprocessor.LocalExportOperationsData3(datadescription)
27025 coprocessor.LocalWriteImages3(datadescription,
27026 rescale_lookuptable=False)
27027
27028 #coprocessor.WriteImages(datadescription, rescale_lookuptable=True)
27029
27030 # Live Visualization, if enabled.
27031 coprocessor.DoLiveVisualization(datadescription, "localhost", 22222)
27032