1 # Copyright (C) 2010-2016 CEA/DEN, EDF R&D
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 This module is intended to provide Python API for building presentations
22 typical for Post-Pro module (Scalar Map, Deformed Shape, Vectors, etc.)
26 from __future__ import division
27 ##from __future__ import print_function
32 from math import sqrt, sin, cos, radians
33 from string import upper
35 # Do not use pv as a short name.
36 # It is a name of function from numpy and may be redefined implicitly by 'from numpy import *' call.
37 # import pvsimple as pv
38 import pvsimple as pvs
40 # # TODO(MZN): to be removed (issue with Point Sprite texture)
41 # #import paravisSM as sm
43 # import paraview.simple as pvs
44 # import paraview.servermanager as sm
50 VTK_LARGE_FLOAT = 1E+38
51 GAP_COEFFICIENT = 0.0001
56 _med_field_sep = '@@][@@'
62 Post-Pro presentation types.
70 DEFORMEDSHAPESCALARMAP = 6
76 _type2name = {MESH: 'Mesh',
77 SCALARMAP: 'Scalar Map',
78 ISOSURFACES: 'Iso Surfaces',
79 CUTPLANES: 'Cut Planes',
80 CUTLINES: 'Cut Lines',
81 DEFORMEDSHAPE: 'Deformed Shape',
82 DEFORMEDSHAPESCALARMAP: 'Deformed Shape And Scalar Map',
85 STREAMLINES: 'Stream Lines',
86 GAUSSPOINTS: 'Gauss Points'}
89 def get_name(cls, type):
90 """Return presentaion name by its type."""
91 return cls._type2name[type]
101 _type2name = {NODE: 'P1',
104 _name2type = {'P1': NODE,
107 _type2pvtype = {NODE: 'POINT_DATA',
111 def get_name(cls, type):
112 """Return entity name (used in full group names) by its type."""
113 return cls._type2name[type]
116 def get_type(cls, name):
117 """Return entity type by its name (used in full group names)."""
118 return cls._name2type[name]
121 def get_pvtype(cls, type):
122 """Return entity type from ['CELL_DATA', 'POINT_DATA']"""
123 return cls._type2pvtype[type]
127 """Orientation types.
129 Defines a set of plane orientation possibilities:
130 AUTO: plane orientation should be calculated.
131 XY: plane formed by X and Y axis.
132 YZ: plane formed by Y and Z axis.
133 ZX: plane formed by Z and X axis
145 Set of elements defining the position of the vector head:
146 CENTER: in the center of the vector
147 TAIL: in the tail of the vector
148 HEAD: in the head of the vector
158 Gauss Points primitive types.
164 _type2mode = {SPRITE: 'Texture',
165 POINT: 'SimplePoint',
166 SPHERE: 'Sphere (Texture)'}
169 def get_mode(cls, type):
170 """Return paraview point sprite mode by the primitive type."""
171 return cls._type2mode[type]
174 # Auxiliary functions
176 def get_field_mesh_name(full_field_name):
177 """Return mesh name of the field by its full name."""
178 aList = full_field_name.split('/')
180 field_name = full_field_name.split('/')[1]
184 def get_field_entity(full_field_name):
185 """Return entity type of the field by its full name."""
186 aList = full_field_name.split(_med_field_sep)
188 entity_name = full_field_name.split(_med_field_sep)[-1]
189 entity = EntityType.get_type(entity_name)
193 def get_field_short_name(full_field_name):
194 """Return short name of the field by its full name."""
195 aList = full_field_name.split('/')
197 short_name_with_type = full_field_name.split('/')[-1]
198 short_name = short_name_with_type.split(_med_field_sep)[0]
202 def find_mesh_full_name(proxy, short_mesh_name):
203 """Return full mesh path by short mesh name, if found"""
204 proxy.UpdatePipeline()
205 all_mesh_names = get_mesh_full_names(proxy)
206 for name in all_mesh_names:
207 if short_mesh_name == get_field_short_name(name):
211 def process_prs_for_test(prs, view, picture_name, show_bar=True):
212 """Show presentation and record snapshot image.
215 prs: the presentation to show
216 view: the render view
217 picture_name: the full name of the graphics file to save
218 show_bar: to show scalar bar or not
221 # Show the presentation only
222 display_only(prs, view)
226 if show_bar and _current_bar:
227 _current_bar.Visibility = 1
232 # Create a directory for screenshot if necessary
233 file_name = re.sub("\s+", "_", picture_name)
234 pic_dir = os.path.dirname(picture_name)
235 if not os.path.exists(pic_dir):
239 print "Write image:", file_name
240 pvs.WriteImage(file_name, view=view, Magnification=1)
243 def reset_view(view=None):
246 Set predefined (taken from Post-Pro) camera settings.
247 If the view is not passed, the active view is used.
251 view = pvs.GetRenderView()
254 view.CameraFocalPoint = [0.0, 0.0, 0.0]
255 view.CameraViewUp = [0.0, 0.0, 1.0]
256 view.CameraPosition = [738.946, -738.946, 738.946]
258 # Turn on the headligth
260 view.LightIntensity = 0.5
262 # Use parallel projection
263 view.CameraParallelProjection = 1
266 pvs.Render(view=view)
269 def hide_all(view, to_remove=False):
270 """Hide all representations in the view."""
272 view = pvs.GetRenderView()
274 rep_list = view.Representations
276 if hasattr(rep, 'Visibility') and rep.Visibility != 0:
279 view.Representations.remove(rep)
280 pvs.Render(view=view)
283 def display_only(prs, view=None):
284 """Display only the given presentation in the view."""
286 view = pvs.GetRenderView()
288 rep_list = view.Representations
290 if hasattr(rep, 'Visibility'):
291 rep.Visibility = (rep == prs)
292 pvs.Render(view=view)
295 def set_visible_lines(xy_prs, lines):
296 """Set visible only the given lines for XYChartRepresentation."""
297 sv = xy_prs.GetProperty("SeriesVisibility").GetData()
300 for i in xrange(0, len(sv)):
303 if line_name in lines:
310 xy_prs.SeriesVisibility = sv
313 def check_vector_mode(vector_mode, nb_components):
314 """Check vector mode.
316 Check if vector mode is correct for the data array with the
317 given number of components.
320 vector_mode: 'Magnitude', 'X', 'Y' or 'Z'
321 nb_components: number of component in the data array
324 ValueError: in case of the vector mode is unexistent
328 if vector_mode not in ('Magnitude', 'X', 'Y', 'Z'):
329 raise ValueError("Unexistent vector mode: " + vector_mode)
331 if ((nb_components == 1 and (vector_mode == 'Y' or vector_mode == 'Z')) or
332 (nb_components == 2 and vector_mode == 'Z')):
333 raise ValueError("Incorrect vector mode " + vector_mode + " for " +
334 nb_components + "-component field")
337 def get_vector_component(vector_mode):
338 """Get vector component as ineger.
340 Translate vector component notation from string
350 if vector_mode == 'X':
352 elif vector_mode == 'Y':
354 elif vector_mode == 'Z':
360 def get_data_range(proxy, entity, field_name, vector_mode='Magnitude',
362 """Get data range for the field.
365 proxy: the pipeline object, containig data array for the field
366 entity: the field entity
367 field_name: the field name
368 vector_mode: the vector mode ('Magnitude', 'X', 'Y' or 'Z')
371 Data range as [min, max]
374 proxy.UpdatePipeline()
375 entity_data_info = None
376 field_data = proxy.GetFieldDataInformation()
378 if field_name in field_data.keys():
379 entity_data_info = field_data
380 elif entity == EntityType.CELL:
381 entity_data_info = proxy.GetCellDataInformation()
382 elif entity == EntityType.NODE:
383 entity_data_info = proxy.GetPointDataInformation()
387 if field_name in entity_data_info.keys():
388 vcomp = get_vector_component(vector_mode)
389 data_range = entity_data_info[field_name].GetComponentRange(vcomp)
391 pv_entity = EntityType.get_pvtype(entity)
392 warnings.warn("Field " + field_name +
393 " is unknown for " + pv_entity + "!")
396 if cut_off and (data_range[0] <= data_range[1]):
397 data_range = list(data_range)
398 delta = abs(data_range[1] - data_range[0]) * GAP_COEFFICIENT
399 data_range[0] += delta
400 data_range[1] -= delta
405 def get_bounds(proxy):
406 """Get bounds of the proxy in 3D."""
407 proxy.UpdatePipeline()
408 dataInfo = proxy.GetDataInformation()
409 bounds_info = dataInfo.GetBounds()
413 def get_x_range(proxy):
414 """Get X range of the proxy bounds in 3D."""
415 proxy.UpdatePipeline()
416 bounds_info = get_bounds(proxy)
417 return bounds_info[0:2]
420 def get_y_range(proxy):
421 """Get Y range of the proxy bounds in 3D."""
422 proxy.UpdatePipeline()
423 bounds_info = get_bounds(proxy)
424 return bounds_info[2:4]
427 def get_z_range(proxy):
428 """Get Z range of the proxy bounds in 3D."""
429 proxy.UpdatePipeline()
430 bounds_info = get_bounds(proxy)
431 return bounds_info[4:6]
434 def is_planar_input(proxy):
435 """Check if the given input is planar."""
436 proxy.UpdatePipeline()
437 bounds_info = get_bounds(proxy)
439 if (abs(bounds_info[0] - bounds_info[1]) <= FLT_MIN or
440 abs(bounds_info[2] - bounds_info[3]) <= FLT_MIN or
441 abs(bounds_info[4] - bounds_info[5]) <= FLT_MIN):
447 def is_data_on_cells(proxy, field_name):
448 """Check the existence of a field on cells with the given name."""
449 proxy.UpdatePipeline()
450 cell_data_info = proxy.GetCellDataInformation()
451 return (field_name in cell_data_info.keys())
455 """Check if the object contains any points or cells.
458 True: if the given proxy doesn't contain any points or cells
462 proxy.UpdatePipeline()
463 data_info = proxy.GetDataInformation()
465 nb_cells = data_info.GetNumberOfCells()
466 nb_points = data_info.GetNumberOfPoints()
468 return not(nb_cells + nb_points)
471 def get_orientation(proxy):
472 """Get the optimum cutting plane orientation for Plot 3D."""
473 proxy.UpdatePipeline()
474 orientation = Orientation.XY
476 bounds = get_bounds(proxy)
477 delta = [bounds[1] - bounds[0],
478 bounds[3] - bounds[2],
479 bounds[5] - bounds[4]]
481 if (delta[0] >= delta[1] and delta[0] >= delta[2]):
482 if (delta[1] >= delta[2]):
483 orientation = Orientation.XY
485 orientation = Orientation.ZX
486 elif (delta[1] >= delta[0] and delta[1] >= delta[2]):
487 if (delta[0] >= delta[2]):
488 orientation = Orientation.XY
490 orientation = Orientation.YZ
491 elif (delta[2] >= delta[0] and delta[2] >= delta[1]):
492 if (delta[0] >= delta[1]):
493 orientation = Orientation.ZX
495 orientation = Orientation.YZ
500 def dot_product(a, b):
501 """Dot product of two 3-vectors."""
502 dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
506 def multiply3x3(a, b):
507 """Mutltiply one 3x3 matrix by another."""
513 c[0][i] = a[0][0] * b[0][i] + a[0][1] * b[1][i] + a[0][2] * b[2][i]
514 c[1][i] = a[1][0] * b[0][i] + a[1][1] * b[1][i] + a[1][2] * b[2][i]
515 c[2][i] = a[2][0] * b[0][i] + a[2][1] * b[1][i] + a[2][2] * b[2][i]
521 """Get X rotation matrix by angle."""
522 rx = [[1.0, 0.0, 0.0],
523 [0.0, cos(ang), -sin(ang)],
524 [0.0, sin(ang), cos(ang)]]
530 """Get Y rotation matrix by angle."""
531 ry = [[cos(ang), 0.0, sin(ang)],
533 [-sin(ang), 0.0, cos(ang)]]
539 """Get Z rotation matrix by angle."""
540 rz = [[cos(ang), -sin(ang), 0.0],
541 [sin(ang), cos(ang), 0.0],
547 def get_normal_by_orientation(orientation, ang1=0, ang2=0):
548 """Get normal for the plane by its orientation."""
550 rotation = [[], [], []]
551 rx = ry = rz = [[1.0, 0.0, 0.0],
555 normal = [0.0, 0.0, 0.0]
556 if orientation == Orientation.XY:
561 rotation = multiply3x3(rx, ry)
563 elif orientation == Orientation.ZX:
568 rotation = multiply3x3(rz, rx)
570 elif orientation == Orientation.YZ:
575 rotation = multiply3x3(ry, rz)
578 for i in xrange(0, 3):
579 normal[i] = rotation[i][i_plane]
584 def get_bound_project(bound_box, dir):
585 """Get bounds projection"""
586 bound_points = [[bound_box[0], bound_box[2], bound_box[4]],
587 [bound_box[1], bound_box[2], bound_box[4]],
588 [bound_box[0], bound_box[3], bound_box[4]],
589 [bound_box[1], bound_box[3], bound_box[4]],
590 [bound_box[0], bound_box[2], bound_box[5]],
591 [bound_box[1], bound_box[2], bound_box[5]],
592 [bound_box[0], bound_box[3], bound_box[5]],
593 [bound_box[1], bound_box[3], bound_box[5]]]
595 bound_prj = [0, 0, 0]
596 bound_prj[0] = dot_product(dir, bound_points[0])
597 bound_prj[1] = bound_prj[0]
599 for i in xrange(1, 8):
600 tmp = dot_product(dir, bound_points[i])
601 if bound_prj[1] < tmp:
603 if bound_prj[0] > tmp:
606 bound_prj[2] = bound_prj[1] - bound_prj[0]
607 bound_prj[1] = bound_prj[0] + (1.0 - EPS) * bound_prj[2]
608 bound_prj[0] = bound_prj[0] + EPS * bound_prj[2]
609 bound_prj[2] = bound_prj[1] - bound_prj[0]
614 def get_positions(nb_planes, dir, bounds, displacement):
615 """Compute plane positions."""
617 bound_prj = get_bound_project(bounds, dir)
619 step = bound_prj[2] / (nb_planes - 1)
620 abs_displacement = step * displacement
621 start_pos = bound_prj[0] - 0.5 * step + abs_displacement
622 for i in xrange(nb_planes):
623 pos = start_pos + i * step
624 positions.append(pos)
626 pos = bound_prj[0] + bound_prj[2] * displacement
627 positions.append(pos)
632 def get_contours(scalar_range, nb_contours):
633 """Generate contour values."""
635 for i in xrange(nb_contours):
636 pos = scalar_range[0] + i * (
637 scalar_range[1] - scalar_range[0]) / (nb_contours - 1)
643 def get_nb_components(proxy, entity, field_name):
644 """Return number of components for the field."""
645 proxy.UpdatePipeline()
646 entity_data_info = None
647 field_data = proxy.GetFieldDataInformation()
649 if field_name in field_data.keys():
650 entity_data_info = field_data
651 elif entity == EntityType.CELL:
652 select_cells_with_data(proxy, on_cells=[field_name])
653 entity_data_info = proxy.GetCellDataInformation()
654 elif entity == EntityType.NODE:
655 select_cells_with_data(proxy, on_points=[field_name])
656 entity_data_info = proxy.GetPointDataInformation()
659 if field_name in entity_data_info.keys():
660 nb_comp = entity_data_info[field_name].GetNumberOfComponents()
662 pv_entity = EntityType.get_pvtype(entity)
663 raise ValueError("Field " + field_name +
664 " is unknown for " + pv_entity + "!")
669 def get_scale_factor(proxy):
670 """Compute scale factor."""
674 proxy.UpdatePipeline()
675 data_info = proxy.GetDataInformation()
677 nb_cells = data_info.GetNumberOfCells()
678 nb_points = data_info.GetNumberOfPoints()
679 nb_elements = nb_cells if nb_cells > 0 else nb_points
680 bounds = get_bounds(proxy)
685 for i in xrange(0, 6, 2):
686 vol = abs(bounds[i + 1] - bounds[i])
691 if nb_elements == 0 or dim < 1 / VTK_LARGE_FLOAT:
694 volume /= nb_elements
696 return pow(volume, 1 / dim)
699 def get_default_scale(prs_type, proxy, entity, field_name):
700 """Get default scale factor."""
701 proxy.UpdatePipeline()
702 data_range = get_data_range(proxy, entity, field_name)
704 if prs_type == PrsTypeEnum.DEFORMEDSHAPE:
705 EPS = 1.0 / VTK_LARGE_FLOAT
706 if abs(data_range[1]) > EPS:
707 scale_factor = get_scale_factor(proxy)
708 return scale_factor / data_range[1]
709 elif prs_type == PrsTypeEnum.PLOT3D:
710 bounds = get_bounds(proxy)
711 length = sqrt((bounds[1] - bounds[0]) ** 2 +
712 (bounds[3] - bounds[2]) ** 2 +
713 (bounds[5] - bounds[4]) ** 2)
716 if data_range[1] > 0:
717 return length / data_range[1] * EPS
722 def get_calc_magnitude(proxy, array_entity, array_name):
723 """Compute magnitude for the given vector array via Calculator.
726 the calculator object.
729 proxy.UpdatePipeline()
732 # Transform vector array to scalar array if possible
733 nb_components = get_nb_components(proxy, array_entity, array_name)
734 if (nb_components > 1):
735 calculator = pvs.Calculator(proxy)
736 attribute_mode = "Point Data"
737 if array_entity != EntityType.NODE:
738 attribute_mode = "Cell Data"
739 calculator.AttributeMode = attribute_mode
740 if (nb_components == 2):
741 # Workaroud: calculator unable to compute magnitude
742 # if number of components equal to 2
743 func = "sqrt(" + array_name + "_X^2+" + array_name + "_Y^2)"
744 calculator.Function = func
746 calculator.Function = "mag(" + array_name + ")"
747 calculator.ResultArrayName = array_name + "_magnitude"
748 calculator.UpdatePipeline()
753 def get_add_component_calc(proxy, array_entity, array_name):
754 """Creates 3-component array from 2-component.
756 The first two components is from the original array. The 3rd component
758 If the number of components is not equal to 2 - return original array name.
761 the calculator object.
764 proxy.UpdatePipeline()
767 nb_components = get_nb_components(proxy, array_entity, array_name)
768 if nb_components == 2:
769 calculator = pvs.Calculator(proxy)
770 attribute_mode = "Point Data"
771 if array_entity != EntityType.NODE:
772 attribute_mode = "Cell Data"
773 calculator.AttributeMode = attribute_mode
774 expression = "iHat * " + array_name + "_X + jHat * " + array_name + "_Y + kHat * 0"
775 calculator.Function = expression
776 calculator.ResultArrayName = array_name + "_3c"
777 calculator.UpdatePipeline()
782 def select_all_cells(proxy):
783 """Select all cell types.
785 Used in creation of mesh/submesh presentation.
788 proxy.UpdatePipeline()
789 extractCT = pvs.ExtractCellType()
790 extractCT.AllGeoTypes = extractCT.GetProperty("GeoTypesInfo")[::2]
791 extractCT.UpdatePipelineInformation()
794 def select_cells_with_data(proxy, on_points=[], on_cells=[], on_gauss=[]):
795 """Select cell types with data.
797 Only cell types with data for the given fields will be selected.
798 If no fields defined (neither on points nor on cells) only cell
799 types with data for even one field (from available) will be selected.
802 if not proxy.GetProperty("FieldsTreeInfo"):
805 proxy.UpdatePipeline()
806 if not hasattr(proxy, 'Entity'):
807 fields_info = proxy.GetProperty("FieldsTreeInfo")[::2]
808 arr_name_with_dis=[elt.split("/")[-1] for elt in fields_info]
811 for name in on_gauss:
812 fields.append(name+_med_field_sep+'GAUSS')
813 for name in on_cells:
814 fields.append(name+_med_field_sep+'P0')
815 for name in on_points:
816 fields.append(name+_med_field_sep+'P1')
820 if arr_name_with_dis.count(name) > 0:
821 index = arr_name_with_dis.index(name)
822 field_list.append(fields_info[index])
825 proxy.AllArrays = field_list
826 proxy.UpdatePipeline()
827 return len(field_list) != 0
829 # TODO: VTN. Looks like this code is out of date.
831 #all_cell_types = proxy.CellTypes.Available
832 all_cell_types = proxy.Entity.Available
833 all_arrays = list(proxy.CellArrays.GetData())
834 all_arrays.extend(proxy.PointArrays.GetData())
837 file_name = proxy.FileName.split(os.sep)[-1]
838 print "Warning: " + file_name + " doesn't contain any data array."
840 # List of cell types to be selected
843 for cell_type in all_cell_types:
844 #proxy.CellTypes = [cell_type]
845 proxy.Entity = [cell_type]
846 proxy.UpdatePipeline()
848 cell_arrays = proxy.GetCellDataInformation().keys()
849 point_arrays = proxy.GetPointDataInformation().keys()
851 if on_points or on_cells:
852 if on_points is None:
857 if (all(array in cell_arrays for array in on_cells) and
858 all(array in point_arrays for array in on_points)):
859 # Add cell type to the list
860 cell_types_on.append(cell_type)
862 in_arrays = lambda array: ((array in cell_arrays) or
863 (array in point_arrays))
864 if any(in_arrays(array) for array in all_arrays):
865 cell_types_on.append(cell_type)
868 #proxy.CellTypes = cell_types_on
869 proxy.Entity = cell_types_on
870 proxy.UpdatePipeline()
872 def if_possible(proxy, field_name, entity, prs_type, extrGrps=None):
873 """Check if the presentation creation is possible on the given field."""
874 proxy.UpdatePipeline()
876 if (prs_type == PrsTypeEnum.DEFORMEDSHAPE or
877 prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP or
878 prs_type == PrsTypeEnum.VECTORS or
879 prs_type == PrsTypeEnum.STREAMLINES):
880 nb_comp = get_nb_components(proxy, entity, field_name)
881 result = (nb_comp > 1)
882 elif (prs_type == PrsTypeEnum.GAUSSPOINTS):
883 result = (entity == EntityType.CELL or
884 field_name in proxy.QuadraturePointArrays.Available)
885 elif (prs_type == PrsTypeEnum.MESH):
886 result = len(get_group_names(extrGrps)) > 0
891 def add_scalar_bar(field_name, nb_components,
892 vector_mode, lookup_table, time_value):
893 """Add scalar bar with predefined properties."""
896 # Construct bar title
897 title = "\n".join([field_name, str(time_value)])
898 if nb_components > 1:
899 title = "\n".join([title, vector_mode])
902 scalar_bar = pvs.CreateScalarBar(Enabled=1)
903 scalar_bar.Orientation = 'Vertical'
904 scalar_bar.Title = title
905 scalar_bar.LookupTable = lookup_table
907 # Set default properties same as in Post-Pro
908 scalar_bar.NumberOfLabels = 5
909 scalar_bar.AutomaticLabelFormat = 0
910 scalar_bar.LabelFormat = '%-#6.6g'
912 scalar_bar.TitleFontFamily = 'Arial'
913 scalar_bar.TitleFontSize = 8
914 scalar_bar.TitleBold = 1
915 scalar_bar.TitleItalic = 1
916 scalar_bar.TitleShadow = 1
918 scalar_bar.LabelFontFamily = 'Arial'
919 scalar_bar.LabelFontSize = 8
920 scalar_bar.LabelBold = 1
921 scalar_bar.LabelItalic = 1
922 scalar_bar.LabelShadow = 1
924 # Add the scalar bar to the view
925 pvs.GetRenderView().Representations.append(scalar_bar)
927 # Reassign the current bar
928 _current_bar = scalar_bar
934 """Get current scalar bar."""
938 def get_lookup_table(field_name, nb_components, vector_mode='Magnitude'):
939 """Get lookup table for the given field."""
940 lookup_table = pvs.GetLookupTableForArray(field_name, nb_components)
942 if vector_mode == 'Magnitude':
943 lookup_table.VectorMode = vector_mode
944 elif vector_mode == 'X':
945 lookup_table.VectorMode = 'Component'
946 lookup_table.VectorComponent = 0
947 elif vector_mode == 'Y':
948 lookup_table.VectorMode = 'Component'
949 lookup_table.VectorComponent = 1
950 elif vector_mode == 'Z':
951 lookup_table.VectorMode = 'Component'
952 lookup_table.VectorComponent = 2
954 raise ValueError("Incorrect vector mode: " + vector_mode)
956 lookup_table.Discretize = 0
957 lookup_table.ColorSpace = 'HSV'
958 if hasattr(lookup_table,"LockDataRange"):
959 lookup_table.LockDataRange = 0
960 elif hasattr(lookup_table,"LockScalarRange"):
961 lookup_table.LockScalarRange = 0
963 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
968 def get_group_mesh_name(full_group_name):
969 """Return mesh name of the group by its full name."""
970 aList = full_group_name.split('/')
972 group_name = full_group_name.split('/')[1]
975 def get_group_entity(full_group_name):
976 """Return entity type of the group by its full name."""
977 aList = full_group_name.split('/')
979 entity_name = full_group_name.split('/')[2]
980 entity = EntityType.get_type(entity_name)
984 def get_group_short_name(full_group_name):
985 """Return short name of the group by its full name."""
986 short_name = re.sub('^GRP_', '', full_group_name)
990 def get_mesh_full_names(proxy):
991 """Return all mesh names in the given proxy as a set."""
992 proxy.UpdatePipeline()
993 fields = proxy.GetProperty("FieldsTreeInfo")[::2]
994 mesh_full_names = set([item for item in fields if get_field_mesh_name(item) == get_field_short_name(item)])
995 return mesh_full_names
998 def get_group_names(extrGrps):
999 """Return full names of all groups of the given 'ExtractGroup' filter object.
1001 group_names = filter(lambda x:x[:4]=="GRP_",list(extrGrps.GetProperty("GroupsFlagsInfo")[::2]))
1005 def get_time(proxy, timestamp_nb):
1006 """Get time value by timestamp number."""
1007 #proxy.UpdatePipeline()
1008 # Check timestamp number
1011 if (hasattr(proxy, 'TimestepValues')):
1012 timestamps = proxy.TimestepValues.GetData()
1013 elif (hasattr(proxy.Input, 'TimestepValues')):
1014 timestamps = proxy.Input.TimestepValues.GetData()
1016 length = len(timestamps)
1017 if (timestamp_nb > 0 and (timestamp_nb - 1) not in xrange(length) ) or (timestamp_nb < 0 and -timestamp_nb > length):
1018 raise ValueError("Timestamp number is out of range: " + str(timestamp_nb))
1024 if timestamp_nb > 0:
1025 return timestamps[timestamp_nb - 1]
1027 return timestamps[timestamp_nb]
1029 def create_prs(prs_type, proxy, field_entity, field_name, timestamp_nb):
1030 """Auxiliary function.
1032 Build presentation of the given type on the given field and
1034 Set the presentation properties like visu.CreatePrsForResult() do.
1037 proxy.UpdatePipeline()
1040 if prs_type == PrsTypeEnum.SCALARMAP:
1041 prs = ScalarMapOnField(proxy, field_entity, field_name, timestamp_nb)
1042 elif prs_type == PrsTypeEnum.CUTPLANES:
1043 prs = CutPlanesOnField(proxy, field_entity, field_name, timestamp_nb,
1044 orientation=Orientation.ZX)
1045 elif prs_type == PrsTypeEnum.CUTLINES:
1046 prs = CutLinesOnField(proxy, field_entity, field_name, timestamp_nb,
1047 orientation1=Orientation.XY,
1048 orientation2=Orientation.ZX)
1049 elif prs_type == PrsTypeEnum.DEFORMEDSHAPE:
1050 prs = DeformedShapeOnField(proxy, field_entity,
1051 field_name, timestamp_nb)
1052 elif prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP:
1053 prs = DeformedShapeAndScalarMapOnField(proxy, field_entity,
1054 field_name, timestamp_nb)
1055 elif prs_type == PrsTypeEnum.VECTORS:
1056 prs = VectorsOnField(proxy, field_entity, field_name, timestamp_nb)
1057 elif prs_type == PrsTypeEnum.PLOT3D:
1058 prs = Plot3DOnField(proxy, field_entity, field_name, timestamp_nb)
1059 elif prs_type == PrsTypeEnum.ISOSURFACES:
1060 prs = IsoSurfacesOnField(proxy, field_entity, field_name, timestamp_nb)
1061 elif prs_type == PrsTypeEnum.GAUSSPOINTS:
1062 prs = GaussPointsOnField(proxy, field_entity, field_name, timestamp_nb)
1063 elif prs_type == PrsTypeEnum.STREAMLINES:
1064 prs = StreamLinesOnField(proxy, field_entity, field_name, timestamp_nb)
1066 raise ValueError("Unexistent presentation type.")
1071 # Functions for building Post-Pro presentations
1072 def ScalarMapOnField(proxy, entity, field_name, timestamp_nb,
1073 vector_mode='Magnitude'):
1074 """Creates Scalar Map presentation on the given field.
1077 proxy: the pipeline object, containig data
1078 entity: the entity type from PrsTypeEnum
1079 field_name: the field name
1080 timestamp_nb: the number of time step (1, 2, ...)
1081 vector_mode: the mode of transformation of vector values
1082 into scalar values, applicable only if the field contains vector values.
1083 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1086 Scalar Map as representation object.
1089 proxy.UpdatePipeline()
1090 # We don't need mesh parts with no data on them
1091 if entity == EntityType.NODE:
1092 select_cells_with_data(proxy, on_points=[field_name])
1094 select_cells_with_data(proxy, on_cells=[field_name])
1097 nb_components = get_nb_components(proxy, entity, field_name)
1098 check_vector_mode(vector_mode, nb_components)
1101 time_value = get_time(proxy, timestamp_nb)
1104 pvs.GetRenderView().ViewTime = time_value
1105 pvs.UpdatePipeline(time_value, proxy)
1107 # Get Scalar Map representation object
1108 scalarmap = pvs.GetRepresentation(proxy)
1111 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1113 # Set field range if necessary
1114 data_range = get_data_range(proxy, entity,
1115 field_name, vector_mode)
1116 if hasattr(lookup_table,"LockDataRange"):
1117 lookup_table.LockDataRange = 1
1118 elif hasattr(lookup_table,"LockScalarRange"):
1119 lookup_table.LockScalarRange = 1
1121 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1123 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1125 pvs.ColorBy(scalarmap, (EntityType.get_pvtype(entity), field_name))
1126 scalarmap.LookupTable = lookup_table
1129 bar_title = field_name + ", " + str(time_value)
1130 if (nb_components > 1):
1131 bar_title += "\n" + vector_mode
1132 add_scalar_bar(field_name, nb_components, vector_mode,
1133 lookup_table, time_value)
1138 def CutPlanesOnField(proxy, entity, field_name, timestamp_nb,
1139 nb_planes=10, orientation=Orientation.YZ,
1141 displacement=0.5, vector_mode='Magnitude'):
1142 """Creates Cut Planes presentation on the given field.
1145 proxy: the pipeline object, containig data
1146 entity: the entity type from PrsTypeEnum
1147 field_name: the field name
1148 timestamp_nb: the number of time step (1, 2, ...)
1149 nb_planes: number of cutting planes
1150 orientation: cutting planes orientation in 3D space
1151 angle1: rotation of the planes in 3d space around the first axis of the
1152 selected orientation (X axis for XY, Y axis for YZ, Z axis for ZX).
1153 The angle of rotation is set in degrees. Acceptable range: [-45, 45].
1154 angle2: rotation of the planes in 3d space around the second axis of the
1155 selected orientation. Acceptable range: [-45, 45].
1156 displacement: the displacement of the planes into one or another side
1157 vector_mode: the mode of transformation of vector values
1158 into scalar values, applicable only if the field contains vector values.
1159 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1162 Cut Planes as representation object.
1165 proxy.UpdatePipeline()
1166 if entity == EntityType.NODE:
1167 select_cells_with_data(proxy, on_points=[field_name])
1169 select_cells_with_data(proxy, on_cells=[field_name])
1172 nb_components = get_nb_components(proxy, entity, field_name)
1173 check_vector_mode(vector_mode, nb_components)
1176 time_value = get_time(proxy, timestamp_nb)
1179 pvs.GetRenderView().ViewTime = time_value
1180 pvs.UpdatePipeline(time_value, proxy)
1182 # Create slice filter
1183 slice_filter = pvs.Slice(proxy)
1184 slice_filter.SliceType = "Plane"
1186 # Set cut planes normal
1187 normal = get_normal_by_orientation(orientation,
1188 radians(angle1), radians(angle2))
1189 slice_filter.SliceType.Normal = normal
1191 # Set cut planes positions
1192 positions = get_positions(nb_planes, normal,
1193 get_bounds(proxy), displacement)
1194 slice_filter.SliceOffsetValues = positions
1196 # Get Cut Planes representation object
1197 cut_planes = pvs.GetRepresentation(slice_filter)
1200 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1202 # Set field range if necessary
1203 data_range = get_data_range(proxy, entity,
1204 field_name, vector_mode)
1206 if hasattr(lookup_table,"LockDataRange"):
1207 lookup_table.LockDataRange = 1
1208 elif hasattr(lookup_table,"LockScalarRange"):
1209 lookup_table.LockScalarRange = 1
1211 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1213 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1216 pvs.ColorBy(cut_planes, (EntityType.get_pvtype(entity), field_name))
1217 cut_planes.LookupTable = lookup_table
1220 add_scalar_bar(field_name, nb_components,
1221 vector_mode, lookup_table, time_value)
1226 def CutLinesOnField(proxy, entity, field_name, timestamp_nb,
1228 orientation1=Orientation.XY,
1229 base_angle1=0, base_angle2=0,
1230 orientation2=Orientation.YZ,
1231 cut_angle1=0, cut_angle2=0,
1232 displacement1=0.5, displacement2=0.5,
1233 generate_curves=False,
1234 vector_mode='Magnitude'):
1235 """Creates Cut Lines presentation on the given field.
1238 proxy: the pipeline object, containig data
1239 entity: the entity type from PrsTypeEnum
1240 field_name: the field name
1241 timestamp_nb: the number of time step (1, 2, ...)
1242 nb_lines: number of lines
1243 orientation1: base plane orientation in 3D space
1244 base_angle1: rotation of the base plane in 3d space around the first
1245 axis of the orientation1 (X axis for XY, Y axis for YZ, Z axis for ZX).
1246 The angle of rotation is set in degrees. Acceptable range: [-45, 45].
1247 base_angle2: rotation of the base plane in 3d space around the second
1248 axis of the orientation1. Acceptable range: [-45, 45].
1249 orientation2: cutting planes orientation in 3D space
1250 cut_angle1: rotation of the cut planes in 3d space around the first
1251 axis of the orientation2. Acceptable range: [-45, 45].
1252 cut_angle2: rotation of the cuting planes in 3d space around the second
1253 axis of the orientation2. Acceptable range: [-45, 45].
1254 displacement1: base plane displacement
1255 displacement2: cutting planes displacement
1256 generate_curves: if true, 'PlotOverLine' filter will be created
1258 vector_mode: the mode of transformation of vector values
1259 into scalar values, applicable only if the field contains vector values.
1260 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1263 Cut Lines as representation object if generate_curves == False,
1264 (Cut Lines as representation object, list of 'PlotOverLine') otherwise
1267 proxy.UpdatePipeline()
1268 if entity == EntityType.NODE:
1269 select_cells_with_data(proxy, on_points=[field_name])
1271 select_cells_with_data(proxy, on_cells=[field_name])
1274 nb_components = get_nb_components(proxy, entity, field_name)
1275 check_vector_mode(vector_mode, nb_components)
1278 time_value = get_time(proxy, timestamp_nb)
1281 pvs.GetRenderView().ViewTime = time_value
1282 pvs.UpdatePipeline(time_value, proxy)
1285 base_plane = pvs.Slice(proxy)
1286 base_plane.SliceType = "Plane"
1288 # Set base plane normal
1289 base_normal = get_normal_by_orientation(orientation1,
1290 radians(base_angle1),
1291 radians(base_angle2))
1292 base_plane.SliceType.Normal = base_normal
1294 # Set base plane position
1295 base_position = get_positions(1, base_normal,
1296 get_bounds(proxy), displacement1)
1297 base_plane.SliceOffsetValues = base_position
1300 base_plane.UpdatePipeline()
1301 if (base_plane.GetDataInformation().GetNumberOfCells() == 0):
1304 # Create cutting planes
1305 cut_planes = pvs.Slice(base_plane)
1306 cut_planes.SliceType = "Plane"
1308 # Set cutting planes normal and get positions
1309 cut_normal = get_normal_by_orientation(orientation2,
1310 radians(cut_angle1),
1311 radians(cut_angle2))
1312 cut_planes.SliceType.Normal = cut_normal
1314 # Set cutting planes position
1315 cut_positions = get_positions(nb_lines, cut_normal,
1316 get_bounds(base_plane), displacement2)
1322 for pos in cut_positions:
1323 # Get points for plot over line objects
1324 cut_planes.SliceOffsetValues = pos
1325 cut_planes.UpdatePipeline()
1326 bounds = get_bounds(cut_planes)
1327 point1 = [bounds[0], bounds[2], bounds[4]]
1328 point2 = [bounds[1], bounds[3], bounds[5]]
1330 # Create plot over line filter
1331 pol = pvs.PlotOverLine(cut_planes,
1332 Source="High Resolution Line Source")
1333 pvs.RenameSource('Y' + str(index), pol)
1334 pol.Source.Point1 = point1
1335 pol.Source.Point2 = point2
1336 pol.UpdatePipeline()
1341 cut_planes.SliceOffsetValues = cut_positions
1342 cut_planes.UpdatePipeline()
1344 # Get Cut Lines representation object
1345 cut_lines = pvs.GetRepresentation(cut_planes)
1348 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1350 # Set field range if necessary
1351 data_range = get_data_range(proxy, entity,
1352 field_name, vector_mode)
1353 if hasattr(lookup_table,"LockDataRange"):
1354 lookup_table.LockDataRange = 1
1355 elif hasattr(lookup_table,"LockScalarRange"):
1356 lookup_table.LockScalarRange = 1
1358 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1360 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1363 pvs.ColorBy(cut_lines, (EntityType.get_pvtype(entity), field_name))
1364 cut_lines.LookupTable = lookup_table
1366 # Set wireframe represenatation mode
1367 cut_lines.Representation = 'Wireframe'
1370 add_scalar_bar(field_name, nb_components,
1371 vector_mode, lookup_table, time_value)
1374 # If curves were generated return tuple (cut lines, list of curves)
1376 result = cut_lines, curves
1381 def CutSegmentOnField(proxy, entity, field_name, timestamp_nb,
1382 point1, point2, vector_mode='Magnitude'):
1383 """Creates Cut Segment presentation on the given field.
1386 proxy: the pipeline object, containig data
1387 entity: the entity type from PrsTypeEnum
1388 field_name: the field name
1389 timestamp_nb: the number of time step (1, 2, ...)
1390 point1: set the first point of the segment (as [x, y, z])
1391 point1: set the second point of the segment (as [x, y, z])
1392 vector_mode: the mode of transformation of vector values
1393 into scalar values, applicable only if the field contains vector values.
1394 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1397 Cut Segment as 3D representation object.
1400 proxy.UpdatePipeline()
1401 if entity == EntityType.NODE:
1402 select_cells_with_data(proxy, on_points=[field_name])
1404 select_cells_with_data(proxy, on_cells=[field_name])
1407 nb_components = get_nb_components(proxy, entity, field_name)
1408 check_vector_mode(vector_mode, nb_components)
1411 time_value = get_time(proxy, timestamp_nb)
1414 pvs.GetRenderView().ViewTime = time_value
1415 pvs.UpdatePipeline(time_value, proxy)
1417 # Create plot over line filter
1418 pol = pvs.PlotOverLine(proxy, Source="High Resolution Line Source")
1419 pol.Source.Point1 = point1
1420 pol.Source.Point2 = point2
1421 pol.UpdatePipeline()
1423 # Get Cut Segment representation object
1424 cut_segment = pvs.GetRepresentation(pol)
1427 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1429 # Set field range if necessary
1430 data_range = get_data_range(proxy, entity,
1431 field_name, vector_mode)
1432 if hasattr(lookup_table,"LockDataRange"):
1433 lookup_table.LockDataRange = 1
1434 elif hasattr(lookup_table,"LockScalarRange"):
1435 lookup_table.LockScalarRange = 1
1437 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1439 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1442 pvs.ColorBy(cut_segment, (EntityType.get_pvtype(entity), field_name))
1443 cut_segment.LookupTable = lookup_table
1445 # Set wireframe represenatation mode
1446 cut_segment.Representation = 'Wireframe'
1449 add_scalar_bar(field_name, nb_components,
1450 vector_mode, lookup_table, time_value)
1455 def VectorsOnField(proxy, entity, field_name, timestamp_nb,
1457 glyph_pos=GlyphPos.TAIL, glyph_type='2D Glyph',
1458 is_colored=False, vector_mode='Magnitude'):
1459 """Creates Vectors presentation on the given field.
1462 proxy: the pipeline object, containig data
1463 entity: the entity type from PrsTypeEnum
1464 field_name: the field name
1465 timestamp_nb: the number of time step (1, 2, ...)
1466 scale_factor: scale factor
1467 glyph_pos: the position of glyphs
1468 glyph_type: the type of glyphs
1469 is_colored: this option allows to color the presentation according to
1470 the corresponding data array values
1471 vector_mode: the mode of transformation of vector values
1472 into scalar values, applicable only if the field contains vector values.
1473 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1476 Vectors as representation object.
1479 proxy.UpdatePipeline()
1480 if entity == EntityType.NODE:
1481 select_cells_with_data(proxy, on_points=[field_name])
1483 select_cells_with_data(proxy, on_cells=[field_name])
1486 nb_components = get_nb_components(proxy, entity, field_name)
1487 check_vector_mode(vector_mode, nb_components)
1490 time_value = get_time(proxy, timestamp_nb)
1493 pvs.GetRenderView().ViewTime = time_value
1494 pvs.UpdatePipeline(time_value, proxy)
1496 # Extract only groups with data for the field
1500 if is_data_on_cells(proxy, field_name):
1501 cell_centers = pvs.CellCenters(source)
1502 cell_centers.VertexCells = 1
1503 source = cell_centers
1505 vector_array = field_name
1506 # If the given vector array has only 2 components, add the third one
1507 if nb_components == 2:
1508 calc = get_add_component_calc(source, EntityType.NODE, field_name)
1509 vector_array = calc.ResultArrayName
1513 glyph = pvs.Glyph(source)
1514 glyph.Vectors = vector_array
1515 glyph.ScaleMode = 'vector'
1516 #glyph.MaskPoints = 0
1519 glyph.GlyphType = glyph_type
1520 if glyph_type == '2D Glyph':
1521 glyph.GlyphType.GlyphType = 'Arrow'
1522 elif glyph_type == 'Cone':
1523 glyph.GlyphType.Resolution = 7
1524 glyph.GlyphType.Height = 2
1525 glyph.GlyphType.Radius = 0.2
1527 # Set glyph position if possible
1528 if glyph.GlyphType.GetProperty("Center"):
1529 if (glyph_pos == GlyphPos.TAIL):
1530 glyph.GlyphType.Center = [0.5, 0.0, 0.0]
1531 elif (glyph_pos == GlyphPos.HEAD):
1532 glyph.GlyphType.Center = [-0.5, 0.0, 0.0]
1533 elif (glyph_pos == GlyphPos.CENTER):
1534 glyph.GlyphType.Center = [0.0, 0.0, 0.0]
1536 if scale_factor is not None:
1537 glyph.ScaleFactor = scale_factor
1539 def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
1540 proxy, entity, field_name)
1541 glyph.ScaleFactor = def_scale
1543 glyph.UpdatePipeline()
1545 # Get Vectors representation object
1546 vectors = pvs.GetRepresentation(glyph)
1549 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1551 # Set field range if necessary
1552 data_range = get_data_range(proxy, entity,
1553 field_name, vector_mode)
1554 if hasattr(lookup_table,"LockDataRange"):
1555 lookup_table.LockDataRange = 1
1556 elif hasattr(lookup_table,"LockScalarRange"):
1557 lookup_table.LockScalarRange = 1
1559 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1561 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1565 pvs.ColorBy(vectors, (EntityType.get_pvtype(entity), 'GlyphVector'))
1567 pvs.ColorBy(vectors, (EntityType.get_pvtype(entity), None))
1568 vectors.LookupTable = lookup_table
1570 vectors.LineWidth = 1.0
1572 # Set wireframe represenatation mode
1573 vectors.Representation = 'Wireframe'
1576 add_scalar_bar(field_name, nb_components,
1577 vector_mode, lookup_table, time_value)
1582 def DeformedShapeOnField(proxy, entity, field_name,
1584 scale_factor=None, is_colored=False,
1585 vector_mode='Magnitude'):
1586 """Creates Defromed Shape presentation on the given field.
1589 proxy: the pipeline object, containig data
1590 entity: the entity type from PrsTypeEnum
1591 field_name: the field name
1592 timestamp_nb: the number of time step (1, 2, ...)
1593 scale_factor: scale factor of the deformation
1594 is_colored: this option allows to color the presentation according to
1595 the corresponding data array values
1596 vector_mode: the mode of transformation of vector values
1597 into scalar values, applicable only if the field contains vector values.
1598 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1601 Defromed Shape as representation object.
1604 proxy.UpdatePipeline()
1605 # We don't need mesh parts with no data on them
1606 if entity == EntityType.NODE:
1607 select_cells_with_data(proxy, on_points=[field_name])
1609 select_cells_with_data(proxy, on_cells=[field_name])
1612 nb_components = get_nb_components(proxy, entity, field_name)
1613 check_vector_mode(vector_mode, nb_components)
1616 time_value = get_time(proxy, timestamp_nb)
1619 pvs.GetRenderView().ViewTime = time_value
1620 pvs.UpdatePipeline(time_value, proxy)
1623 source = pvs.MergeBlocks(proxy)
1624 pvs.UpdatePipeline()
1626 # Cell data to point data
1627 if is_data_on_cells(proxy, field_name):
1628 cell_to_point = pvs.CellDatatoPointData()
1629 cell_to_point.PassCellData = 1
1630 source = cell_to_point
1632 vector_array = field_name
1633 # If the given vector array has only 2 components, add the third one
1634 if nb_components == 2:
1635 calc = get_add_component_calc(source, EntityType.NODE, field_name)
1636 vector_array = calc.ResultArrayName
1640 warp_vector = pvs.WarpByVector(source)
1641 warp_vector.Vectors = [vector_array]
1642 if scale_factor is not None:
1643 warp_vector.ScaleFactor = scale_factor
1645 def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
1646 proxy, entity, field_name)
1647 warp_vector.ScaleFactor = def_scale
1649 # Get Deformed Shape representation object
1650 defshape = pvs.GetRepresentation(warp_vector)
1653 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1655 # Set field range if necessary
1656 data_range = get_data_range(proxy, entity,
1657 field_name, vector_mode)
1658 if hasattr(lookup_table,"LockDataRange"):
1659 lookup_table.LockDataRange = 1
1660 elif hasattr(lookup_table,"LockScalarRange"):
1661 lookup_table.LockScalarRange = 1
1663 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1665 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1669 pvs.ColorBy(defshape, (EntityType.get_pvtype(entity), field_name))
1671 pvs.ColorBy(defshape, (EntityType.get_pvtype(entity), None))
1672 defshape.LookupTable = lookup_table
1674 # Set wireframe represenatation mode
1675 defshape.Representation = 'Wireframe'
1678 add_scalar_bar(field_name, nb_components,
1679 vector_mode, lookup_table, time_value)
1684 def DeformedShapeAndScalarMapOnField(proxy, entity, field_name,
1688 scalar_field_name=None,
1689 vector_mode='Magnitude'):
1690 """Creates Defromed Shape And Scalar Map presentation on the given field.
1693 proxy: the pipeline object, containig data
1694 entity: the entity type from PrsTypeEnum
1695 field_name: the field name
1696 timestamp_nb: the number of time step (1, 2, ...)
1697 scale_factor: scale factor of the deformation
1698 scalar_entity: scalar field entity
1699 scalar_field_name: scalar field, i.e. the field for coloring
1700 vector_mode: the mode of transformation of vector values
1701 into scalar values, applicable only if the field contains vector values.
1702 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1705 Defromed Shape And Scalar Map as representation object.
1708 proxy.UpdatePipeline()
1709 # We don't need mesh parts with no data on them
1713 if entity == EntityType.NODE:
1714 on_points.append(field_name)
1716 on_cells.append(field_name)
1718 if scalar_entity and scalar_field_name:
1719 if scalar_entity == EntityType.NODE:
1720 on_points.append(scalar_field_name)
1722 on_cells.append(scalar_field_name)
1724 nb_components = get_nb_components(proxy, entity, field_name)
1727 select_cells_with_data(proxy, on_points, on_cells)
1730 check_vector_mode(vector_mode, nb_components)
1733 time_value = get_time(proxy, timestamp_nb)
1736 pvs.GetRenderView().ViewTime = time_value
1737 pvs.UpdatePipeline(time_value, proxy)
1739 # Set scalar field by default
1740 scalar_field_entity = scalar_entity
1741 scalar_field = scalar_field_name
1742 if (scalar_field_entity is None) or (scalar_field is None):
1743 scalar_field_entity = entity
1744 scalar_field = field_name
1747 source = pvs.MergeBlocks(proxy)
1748 pvs.UpdatePipeline()
1750 # Cell data to point data
1751 if is_data_on_cells(proxy, field_name):
1752 cell_to_point = pvs.CellDatatoPointData(source)
1753 cell_to_point.PassCellData = 1
1754 source = cell_to_point
1756 vector_array = field_name
1757 # If the given vector array has only 2 components, add the third one
1758 if nb_components == 2:
1759 calc = get_add_component_calc(source, EntityType.NODE, field_name)
1760 vector_array = calc.ResultArrayName
1764 warp_vector = pvs.WarpByVector(source)
1765 warp_vector.Vectors = [vector_array]
1766 if scale_factor is not None:
1767 warp_vector.ScaleFactor = scale_factor
1769 def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE,
1770 proxy, entity, field_name)
1771 warp_vector.ScaleFactor = def_scale
1773 # Get Defromed Shape And Scalar Map representation object
1774 defshapemap = pvs.GetRepresentation(warp_vector)
1777 lookup_table = get_lookup_table(scalar_field, nb_components, vector_mode)
1779 # Set field range if necessary
1780 data_range = get_data_range(proxy, scalar_field_entity,
1781 scalar_field, vector_mode)
1782 if hasattr(lookup_table,"LockDataRange"):
1783 lookup_table.LockDataRange = 1
1784 elif hasattr(lookup_table,"LockScalarRange"):
1785 lookup_table.LockScalarRange = 1
1787 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1789 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1792 pvs.ColorBy(defshapemap, (EntityType.get_pvtype(scalar_field_entity), scalar_field))
1793 defshapemap.LookupTable = lookup_table
1796 add_scalar_bar(field_name, nb_components,
1797 vector_mode, lookup_table, time_value)
1802 def Plot3DOnField(proxy, entity, field_name, timestamp_nb,
1803 orientation=Orientation.AUTO,
1805 position=0.5, is_relative=True,
1807 is_contour=False, nb_contours=32,
1808 vector_mode='Magnitude'):
1809 """Creates Plot 3D presentation on the given field.
1812 proxy: the pipeline object, containig data
1813 entity: the entity type from PrsTypeEnum
1814 field_name: the field name
1815 timestamp_nb: the number of time step (1, 2, ...)
1816 orientation: the cut plane plane orientation in 3D space, if
1817 the input is planar - will not be taken into account
1818 angle1: rotation of the cut plane in 3d space around the first axis
1819 of the selected orientation (X axis for XY, Y axis for YZ,
1821 The angle of rotation is set in degrees. Acceptable range: [-45, 45].
1822 angle2: rotation of the cut plane in 3d space around the second axis
1823 of the selected orientation. Acceptable range: [-45, 45].
1824 position: position of the cut plane in the object (ranging from 0 to 1).
1825 The value 0.5 corresponds to cutting by halves.
1826 is_relative: defines if the cut plane position is relative or absolute
1827 scale_factor: deformation scale factor
1828 is_contour: if True - Plot 3D will be represented with a set of contours,
1829 otherwise - Plot 3D will be represented with a smooth surface
1830 nb_contours: number of contours, applied if is_contour is True
1831 vector_mode: the mode of transformation of vector values
1832 into scalar values, applicable only if the field contains vector values.
1833 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1836 Plot 3D as representation object.
1839 proxy.UpdatePipeline()
1840 # We don't need mesh parts with no data on them
1841 if entity == EntityType.NODE:
1842 select_cells_with_data(proxy, on_points=[field_name])
1844 select_cells_with_data(proxy, on_cells=[field_name])
1847 nb_components = get_nb_components(proxy, entity, field_name)
1848 check_vector_mode(vector_mode, nb_components)
1851 time_value = get_time(proxy, timestamp_nb)
1854 pvs.GetRenderView().ViewTime = time_value
1855 pvs.UpdatePipeline(time_value, proxy)
1858 merge_blocks = pvs.MergeBlocks(proxy)
1859 merge_blocks.UpdatePipeline()
1865 # Define orientation if necessary (auto mode)
1866 plane_orientation = orientation
1867 if (orientation == Orientation.AUTO):
1868 plane_orientation = get_orientation(proxy)
1870 # Get cutting plane normal
1873 if (not is_planar_input(proxy)):
1874 normal = get_normal_by_orientation(plane_orientation,
1875 radians(angle1), radians(angle2))
1877 # Create slice filter
1878 slice_filter = pvs.Slice(merge_blocks)
1879 slice_filter.SliceType = "Plane"
1881 # Set cutting plane normal
1882 slice_filter.SliceType.Normal = normal
1884 # Set cutting plane position
1886 base_position = get_positions(1, normal,
1887 get_bounds(proxy), position)
1888 slice_filter.SliceOffsetValues = base_position
1890 slice_filter.SliceOffsetValues = position
1892 slice_filter.UpdatePipeline()
1893 poly_data = slice_filter
1895 normal = get_normal_by_orientation(plane_orientation, 0, 0)
1899 if not poly_data or poly_data.GetDataInformation().GetNumberOfCells() == 0:
1900 geometry_filter = pvs.GeometryFilter(merge_blocks)
1901 poly_data = geometry_filter
1902 use_normal = 1 # TODO(MZN): workaround
1908 if is_data_on_cells(poly_data, field_name):
1909 # Cell data to point data
1910 cell_to_point = pvs.CellDatatoPointData(poly_data)
1911 cell_to_point.PassCellData = 1
1912 source = cell_to_point
1914 scalars = ['POINTS', field_name]
1916 # Transform vector array to scalar array if necessary
1917 if (nb_components > 1):
1918 calc = get_calc_magnitude(source, EntityType.NODE, field_name)
1919 scalars = ['POINTS', calc.ResultArrayName]
1923 warp_scalar = pvs.WarpByScalar(source)
1924 warp_scalar.Scalars = scalars
1925 warp_scalar.Normal = normal
1926 warp_scalar.UseNormal = use_normal
1927 if scale_factor is not None:
1928 warp_scalar.ScaleFactor = scale_factor
1930 def_scale = get_default_scale(PrsTypeEnum.PLOT3D,
1931 proxy, entity, field_name)
1932 warp_scalar.ScaleFactor = def_scale
1934 warp_scalar.UpdatePipeline()
1935 source = warp_scalar
1939 contour = pvs.Contour(warp_scalar)
1940 contour.PointMergeMethod = "Uniform Binning"
1941 contour.ContourBy = ['POINTS', field_name]
1942 scalar_range = get_data_range(proxy, entity,
1943 field_name, vector_mode)
1944 contour.Isosurfaces = get_contours(scalar_range, nb_contours)
1945 contour.UpdatePipeline()
1948 # Get Plot 3D representation object
1949 plot3d = pvs.GetRepresentation(source)
1952 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
1954 # Set field range if necessary
1955 data_range = get_data_range(proxy, entity,
1956 field_name, vector_mode)
1957 if hasattr(lookup_table,"LockDataRange"):
1958 lookup_table.LockDataRange = 1
1959 elif hasattr(lookup_table,"LockScalarRange"):
1960 lookup_table.LockScalarRange = 1
1962 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
1964 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
1967 pvs.ColorBy(plot3d, (EntityType.get_pvtype(entity), field_name))
1968 plot3d.LookupTable = lookup_table
1971 add_scalar_bar(field_name, nb_components,
1972 vector_mode, lookup_table, time_value)
1977 def IsoSurfacesOnField(proxy, entity, field_name, timestamp_nb,
1978 custom_range=None, nb_surfaces=10,
1979 is_colored=True, color=None, vector_mode='Magnitude'):
1980 """Creates Iso Surfaces presentation on the given field.
1983 proxy: the pipeline object, containig data
1984 entity: the entity type from PrsTypeEnum
1985 field_name: the field name
1986 timestamp_nb: the number of time step (1, 2, ...)
1987 custom_range: scalar range, if undefined the source range will be applied
1988 nb_surfaces: number of surfaces, which will be generated
1989 is_colored: this option allows to color the presentation according to
1990 the corresponding data array values. If False - the presentation will
1992 color: defines the presentation color as [R, G, B] triple. Taken into
1993 account only if is_colored is False.
1994 vector_mode: the mode of transformation of vector values
1995 into scalar values, applicable only if the field contains vector values.
1996 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
1999 Iso Surfaces as representation object.
2002 proxy.UpdatePipeline()
2003 # We don't need mesh parts with no data on them
2004 if entity == EntityType.NODE:
2005 select_cells_with_data(proxy, on_points=[field_name])
2007 select_cells_with_data(proxy, on_cells=[field_name])
2010 nb_components = get_nb_components(proxy, entity, field_name)
2011 check_vector_mode(vector_mode, nb_components)
2014 time_value = get_time(proxy, timestamp_nb)
2017 pvs.GetRenderView().ViewTime = time_value
2018 pvs.UpdatePipeline(time_value, proxy)
2021 source = pvs.MergeBlocks(proxy)
2022 pvs.UpdatePipeline()
2024 # Transform cell data into point data if necessary
2025 if is_data_on_cells(proxy, field_name):
2026 cell_to_point = pvs.CellDatatoPointData(source)
2027 cell_to_point.PassCellData = 1
2028 source = cell_to_point
2030 contour_by = ['POINTS', field_name]
2032 # Transform vector array to scalar array if necessary
2033 if (nb_components > 1):
2034 calc = get_calc_magnitude(source, EntityType.NODE, field_name)
2035 contour_by = ['POINTS', calc.ResultArrayName]
2038 # Contour filter settings
2039 contour = pvs.Contour(source)
2040 contour.ComputeScalars = 1
2041 contour.ContourBy = contour_by
2044 scalar_range = custom_range
2045 if (scalar_range is None):
2046 scalar_range = get_data_range(proxy, entity,
2047 field_name, cut_off=True)
2049 # Get contour values for the range
2050 surfaces = get_contours(scalar_range, nb_surfaces)
2052 # Set contour values
2053 contour.Isosurfaces = surfaces
2055 # Get Iso Surfaces representation object
2056 isosurfaces = pvs.GetRepresentation(contour)
2059 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
2061 # Set field range if necessary
2062 data_range = get_data_range(proxy, entity,
2063 field_name, vector_mode)
2064 if hasattr(lookup_table,"LockDataRange"):
2065 lookup_table.LockDataRange = 1
2066 elif hasattr(lookup_table,"LockScalarRange"):
2067 lookup_table.LockScalarRange = 1
2069 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
2071 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
2073 # Set display properties
2075 pvs.ColorBy(isosurfaces, (EntityType.get_pvtype(entity), field_name))
2077 pvs.ColorBy(isosurfaces, (EntityType.get_pvtype(entity), None))
2079 isosurfaces.DiffuseColor = color
2080 isosurfaces.LookupTable = lookup_table
2083 add_scalar_bar(field_name, nb_components,
2084 vector_mode, lookup_table, time_value)
2089 def GaussPointsOnField(proxy, entity, field_name,
2091 is_deformed=True, scale_factor=None,
2092 is_colored=True, color=None,
2093 primitive=GaussType.SPRITE,
2094 is_proportional=True,
2096 multiplier=None, vector_mode='Magnitude'):
2097 """Creates Gauss Points on the given field.
2101 proxy: the pipeline object, containig data
2102 entity: the field entity type from PrsTypeEnum
2103 field_name: the field name
2104 timestamp_nb: the number of time step (1, 2, ...)
2105 is_deformed: defines whether the Gauss Points will be deformed or not
2106 scale_factor -- the scale factor for deformation. Will be taken into
2107 account only if is_deformed is True.
2108 If not passed by user, default scale will be computed.
2109 is_colored -- defines whether the Gauss Points will be multicolored,
2110 using the corresponding data values
2111 color: defines the presentation color as [R, G, B] triple. Taken into
2112 account only if is_colored is False.
2113 primitive: primitive type from GaussType
2114 is_proportional: if True, the size of primitives will depends on
2115 the gauss point value
2116 max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels
2117 multiplier: coefficient between data values and the size of primitives
2118 If not passed by user, default scale will be computed.
2119 vector_mode: the mode of transformation of vector values into
2120 scalar values, applicable only if the field contains vector values.
2121 Possible modes: 'Magnitude' - vector module;
2122 'X', 'Y', 'Z' - vector components.
2125 Gauss Points as representation object.
2128 proxy.UpdatePipeline()
2129 # We don't need mesh parts with no data on them
2130 on_gauss = select_cells_with_data(proxy, on_gauss=[field_name])
2132 if entity == EntityType.NODE:
2133 select_cells_with_data(proxy, on_points=[field_name])
2135 select_cells_with_data(proxy, on_cells=[field_name])
2138 nb_components = get_nb_components(proxy, entity, field_name)
2139 check_vector_mode(vector_mode, nb_components)
2142 time_value = get_time(proxy, timestamp_nb)
2145 pvs.GetRenderView().ViewTime = time_value
2146 pvs.UpdatePipeline(time_value, proxy)
2150 # If no quadrature point array is passed, use cell centers
2152 generate_qp = pvs.GenerateQuadraturePoints(source)
2153 generate_qp.QuadratureSchemeDef = ['CELLS', 'ELGA@0']
2154 source = generate_qp
2157 cell_centers = pvs.CellCenters(source)
2158 cell_centers.VertexCells = 1
2159 source = cell_centers
2161 source.UpdatePipeline()
2163 # Check if deformation enabled
2164 if is_deformed and nb_components > 1:
2165 vector_array = field_name
2166 # If the given vector array has only 2 components, add the third one
2167 if nb_components == 2:
2168 calc = get_add_component_calc(source, EntityType.NODE, field_name)
2169 vector_array = calc.ResultArrayName
2173 warp_vector = pvs.WarpByVector(source)
2174 warp_vector.Vectors = [vector_array]
2175 if scale_factor is not None:
2176 warp_vector.ScaleFactor = scale_factor
2178 def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, proxy,
2180 warp_vector.ScaleFactor = def_scale
2181 warp_vector.UpdatePipeline()
2182 source = warp_vector
2184 # Get Gauss Points representation object
2185 gausspnt = pvs.GetRepresentation(source)
2188 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
2190 # Set field range if necessary
2191 data_range = get_data_range(proxy, entity,
2192 field_name, vector_mode)
2193 if hasattr(lookup_table,"LockDataRange"):
2194 lookup_table.LockDataRange = 1
2195 elif hasattr(lookup_table,"LockScalarRange"):
2196 lookup_table.LockScalarRange = 1
2198 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
2200 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
2202 # Set display properties
2204 pvs.ColorBy(gausspnt, (EntityType.get_pvtype(entity), field_name))
2206 pvs.ColorBy(gausspnt, (EntityType.get_pvtype(entity), None))
2208 gausspnt.DiffuseColor = color
2210 gausspnt.LookupTable = lookup_table
2213 add_scalar_bar(field_name, nb_components,
2214 vector_mode, lookup_table, time_value)
2216 # Set point sprite representation
2217 gausspnt.Representation = 'Point Sprite'
2219 # Point sprite settings
2220 gausspnt.InterpolateScalarsBeforeMapping = 0
2221 gausspnt.MaxPixelSize = max_pixel_size
2224 gausspnt.RenderMode = GaussType.get_mode(primitive)
2226 #if primitive == GaussType.SPRITE:
2228 # TODO(MZN): replace with pvsimple high-level interface
2229 # texture = sm.CreateProxy("textures", "SpriteTexture")
2230 # alphamprop = texture.GetProperty("AlphaMethod")
2231 # alphamprop.SetElement(0, 2) # Clamp
2232 # alphatprop = texture.GetProperty("AlphaThreshold")
2233 # alphatprop.SetElement(0, 63)
2234 # maxprop = texture.GetProperty("Maximum")
2235 # maxprop.SetElement(0, 255)
2236 # texture.UpdateVTKObjects()
2238 # gausspnt.Texture = texture
2239 #gausspnt.Texture.AlphaMethod = 'Clamp'
2240 #gausspnt.Texture.AlphaThreshold = 63
2241 #gausspnt.Texture.Maximum= 255
2243 # Proportional radius
2244 gausspnt.RadiusUseScalarRange = 0
2245 gausspnt.RadiusIsProportional = 0
2249 if mult is None and data_range[1] != 0:
2250 mult = abs(0.1 / data_range[1])
2252 gausspnt.RadiusScalarRange = data_range
2253 gausspnt.RadiusTransferFunctionEnabled = 1
2254 gausspnt.RadiusMode = 'Scalar'
2255 gausspnt.RadiusArray = ['POINTS', field_name]
2256 if nb_components > 1:
2257 v_comp = get_vector_component(vector_mode)
2258 gausspnt.RadiusVectorComponent = v_comp
2259 gausspnt.RadiusTransferFunctionMode = 'Table'
2260 gausspnt.RadiusScalarRange = data_range
2261 gausspnt.RadiusUseScalarRange = 1
2262 if mult is not None:
2263 gausspnt.RadiusIsProportional = 1
2264 gausspnt.RadiusProportionalFactor = mult
2266 gausspnt.RadiusTransferFunctionEnabled = 0
2267 gausspnt.RadiusMode = 'Constant'
2268 gausspnt.RadiusArray = ['POINTS', 'Constant Radius']
2272 def GaussPointsOnField1(proxy, entity, field_name,
2274 is_colored=True, color=None,
2275 primitive=GaussType.SPHERE,
2276 is_proportional=True,
2279 vector_mode='Magnitude'):
2280 """Creates Gauss Points on the given field. Use GaussPoints() Paraview interface.
2283 proxy: the pipeline object, containig data
2284 entity: the field entity type from PrsTypeEnum
2285 field_name: the field name
2286 timestamp_nb: the number of time step (1, 2, ...)
2287 is_colored -- defines whether the Gauss Points will be multicolored,
2288 using the corresponding data values
2289 color: defines the presentation color as [R, G, B] triple. Taken into
2290 account only if is_colored is False.
2291 primitive: primitive type from GaussType
2292 is_proportional: if True, the size of primitives will depends on
2293 the gauss point value
2294 max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels
2295 multiplier: coefficient between data values and the size of primitives
2296 If not passed by user, default scale will be computed.
2297 vector_mode: the mode of transformation of vector values into
2298 scalar values, applicable only if the field contains vector values.
2299 Possible modes: 'Magnitude' - vector module;
2300 'X', 'Y', 'Z' - vector components.
2303 Gauss Points as representation object.
2306 proxy.UpdatePipeline()
2307 select_cells_with_data(proxy, on_gauss=[field_name])
2309 nb_components = get_nb_components(proxy, entity, field_name)
2312 time_value = get_time(proxy, timestamp_nb)
2315 pvs.GetRenderView().ViewTime = time_value
2316 proxy.UpdatePipeline(time=time_value)
2318 # Create Gauss Points object
2319 source = pvs.GaussPoints(proxy)
2320 source.UpdatePipeline()
2322 # Get Gauss Points representation object
2323 gausspnt = pvs.GetRepresentation(source)
2326 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
2328 # Set field range if necessary
2329 data_range = get_data_range(proxy, entity,
2330 field_name, vector_mode)
2331 if hasattr(lookup_table,"LockDataRange"):
2332 lookup_table.LockDataRange = 1
2333 elif hasattr(lookup_table,"LockScalarRange"):
2334 lookup_table.LockScalarRange = 1
2336 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
2338 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
2340 # Set display properties
2342 pvs.ColorBy(gausspnt, (EntityType.get_pvtype(entity), field_name))
2344 pvs.ColorBy(gausspnt, (EntityType.get_pvtype(entity), None))
2346 gausspnt.DiffuseColor = color
2348 gausspnt.LookupTable = lookup_table
2351 add_scalar_bar(field_name, nb_components,
2352 vector_mode, lookup_table, time_value)
2354 # Set point sprite representation
2355 gausspnt.Representation = 'Point Sprite'
2357 # Point sprite settings
2358 gausspnt.InterpolateScalarsBeforeMapping = 0
2359 gausspnt.MaxPixelSize = max_pixel_size
2362 gausspnt.RenderMode = GaussType.get_mode(primitive)
2364 #if primitive == GaussType.SPRITE:
2366 # TODO(MZN): replace with pvsimple high-level interface
2367 # texture = sm.CreateProxy("textures", "SpriteTexture")
2368 # alphamprop = texture.GetProperty("AlphaMethod")
2369 # alphamprop.SetElement(0, 2) # Clamp
2370 # alphatprop = texture.GetProperty("AlphaThreshold")
2371 # alphatprop.SetElement(0, 63)
2372 # maxprop = texture.GetProperty("Maximum")
2373 # maxprop.SetElement(0, 255)
2374 # texture.UpdateVTKObjects()
2376 # gausspnt.Texture = texture
2377 #gausspnt.Texture.AlphaMethod = 'Clamp'
2378 #gausspnt.Texture.AlphaThreshold = 63
2379 #gausspnt.Texture.Maximum= 255
2381 # Proportional radius
2382 gausspnt.RadiusUseScalarRange = 0
2383 gausspnt.RadiusIsProportional = 0
2387 if mult is None and data_range[1] != 0:
2388 mult = abs(0.1 / data_range[1])
2390 gausspnt.RadiusScalarRange = data_range
2391 gausspnt.RadiusTransferFunctionEnabled = 1
2392 gausspnt.RadiusMode = 'Scalar'
2393 gausspnt.RadiusArray = ['POINTS', field_name]
2394 if nb_components > 1:
2395 v_comp = get_vector_component(vector_mode)
2396 gausspnt.RadiusVectorComponent = v_comp
2397 gausspnt.RadiusTransferFunctionMode = 'Table'
2398 gausspnt.RadiusScalarRange = data_range
2399 gausspnt.RadiusUseScalarRange = 1
2400 if mult is not None:
2401 gausspnt.RadiusIsProportional = 1
2402 gausspnt.RadiusProportionalFactor = mult
2404 gausspnt.RadiusTransferFunctionEnabled = 0
2405 gausspnt.RadiusMode = 'Constant'
2406 gausspnt.RadiusArray = ['POINTS', 'Constant Radius']
2410 def StreamLinesOnField(proxy, entity, field_name, timestamp_nb,
2411 direction='BOTH', is_colored=False, color=None,
2412 vector_mode='Magnitude'):
2413 """Creates Stream Lines presentation on the given field.
2416 proxy: the pipeline object, containig data
2417 entity: the entity type from PrsTypeEnum
2418 field_name: the field name
2419 timestamp_nb: the number of time step (1, 2, ...)
2420 direction: the stream lines direction ('FORWARD', 'BACKWARD' or 'BOTH')
2421 is_colored: this option allows to color the presentation according to
2422 the corresponding data values. If False - the presentation will
2424 color: defines the presentation color as [R, G, B] triple. Taken into
2425 account only if is_colored is False.
2426 vector_mode: the mode of transformation of vector values
2427 into scalar values, applicable only if the field contains vector values.
2428 Possible modes: 'Magnitude', 'X', 'Y' or 'Z'.
2431 Stream Lines as representation object.
2434 proxy.UpdatePipeline()
2435 # We don't need mesh parts with no data on them
2436 if entity == EntityType.NODE:
2437 select_cells_with_data(proxy, on_points=[field_name])
2439 select_cells_with_data(proxy, on_cells=[field_name])
2442 nb_components = get_nb_components(proxy, entity, field_name)
2443 check_vector_mode(vector_mode, nb_components)
2446 time_value = get_time(proxy, timestamp_nb)
2449 pvs.GetRenderView().ViewTime = time_value
2450 pvs.UpdatePipeline(time_value, proxy)
2453 source = pvs.MergeBlocks(proxy)
2454 pvs.UpdatePipeline()
2456 # Cell data to point data
2457 if is_data_on_cells(proxy, field_name):
2458 cell_to_point = pvs.CellDatatoPointData(source)
2459 cell_to_point.PassCellData = 1
2460 pvs.UpdatePipeline()
2461 source = cell_to_point
2463 vector_array = field_name
2464 # If the given vector array has only 2 components, add the third one
2465 if nb_components == 2:
2466 calc = get_add_component_calc(source, EntityType.NODE, field_name)
2467 vector_array = calc.ResultArrayName
2468 pvs.UpdatePipeline()
2472 stream = pvs.StreamTracer(source)
2473 stream.SeedType = "Point Source"
2474 stream.Vectors = ['POINTS', vector_array]
2475 stream.IntegrationDirection = direction
2476 stream.IntegratorType = 'Runge-Kutta 2'
2477 stream.SeedType = 'High Resolution Line Source'
2478 stream.UpdatePipeline()
2480 # Get Stream Lines representation object
2481 if is_empty(stream):
2483 streamlines = pvs.GetRepresentation(stream)
2486 lookup_table = get_lookup_table(field_name, nb_components, vector_mode)
2488 # Set field range if necessary
2489 data_range = get_data_range(proxy, entity,
2490 field_name, vector_mode)
2491 if hasattr(lookup_table,"LockDataRange"):
2492 lookup_table.LockDataRange = 1
2493 elif hasattr(lookup_table,"LockScalarRange"):
2494 lookup_table.LockScalarRange = 1
2496 raise RuntimeError("Object %s has no 'LockDataRange' or 'LockScalarRange' attribute!"%(lookup_table))
2498 lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0]
2502 pvs.ColorBy(streamlines, (EntityType.get_pvtype(entity), field_name))
2504 pvs.ColorBy(streamlines, (EntityType.get_pvtype(entity), None))
2506 streamlines.DiffuseColor = color
2508 streamlines.LookupTable = lookup_table
2511 add_scalar_bar(field_name, nb_components,
2512 vector_mode, lookup_table, time_value)
2517 def MeshOnEntity(proxy, mesh_name, entity):
2518 """Creates submesh of the entity type for the mesh.
2521 proxy -- the pipeline object, containig data
2522 mesh_name -- the full or short name of mesh field
2525 Submesh as representation object of the given source.
2528 proxy.UpdatePipeline()
2529 mesh_full_name = None
2530 aList = mesh_name.split('/')
2532 mesh_full_name = mesh_name
2534 mesh_full_name = find_mesh_full_name(proxy, mesh_name)
2535 if not mesh_full_name:
2536 raise RuntimeError, "The given mesh name was not found"
2537 # Select only the given mesh
2538 proxy.AllArrays = [mesh_full_name]
2539 proxy.UpdatePipeline()
2541 # Get representation object if the submesh is not empty
2543 if (proxy.GetDataInformation().GetNumberOfPoints() or
2544 proxy.GetDataInformation().GetNumberOfCells()):
2545 my_view = pvs.GetRenderView()
2546 prs = pvs.GetRepresentation(proxy, view=my_view)
2547 prs.ColorArrayName = (None, '')
2552 def MeshOnGroup(proxy, extrGroups, group_name):
2553 """Creates submesh on the group.
2556 proxy -- the pipeline object, containig data
2557 group_name -- the full group name
2558 extrGroups -- all extracted groups object
2561 Representation object of the given source with single group
2565 proxy.UpdatePipeline()
2566 # Deselect all groups
2567 extrGroups.AllGroups = []
2568 extrGroups.UpdatePipelineInformation()
2569 # Select only the group with the given name
2570 extrGroups.AllGroups = [group_name]
2571 extrGroups.UpdatePipelineInformation()
2573 # Get representation object if the submesh is not empty
2576 # Check if the group was set
2577 if len(extrGroups.AllGroups) == 1 and \
2578 extrGroups.AllGroups[0] == group_name:
2579 # Check if the submesh is not empty
2580 nb_points = proxy.GetDataInformation().GetNumberOfPoints()
2581 nb_cells = proxy.GetDataInformation().GetNumberOfCells()
2583 if nb_points or nb_cells:
2584 # prs = pvs.GetRepresentation(proxy)
2586 prs.ColorArrayName = (None, '')
2592 def CreatePrsForFile(file_name, prs_types,
2593 picture_dir, picture_ext):
2594 """Build presentations of the given types for the file.
2596 Build presentations for all fields on all timestamps.
2599 file_name: full path to the MED file
2600 prs_types: the list of presentation types to build
2601 picture_dir: the directory path for saving snapshots
2602 picture_ext: graphics files extension (determines file type)
2606 print "Import " + file_name.split(os.sep)[-1] + "..."
2609 proxy = pvs.MEDReader(FileName=file_name)
2613 #proxy.UpdatePipeline()
2619 view = pvs.GetRenderView()
2620 time_value = get_time(proxy, 0)
2621 view.ViewTime = time_value
2622 pvs.UpdatePipeline(time=time_value, proxy=proxy)
2624 # Create required presentations for the proxy
2625 CreatePrsForProxy(proxy, view, prs_types,
2626 picture_dir, picture_ext)
2628 def CreatePrsForProxy(proxy, view, prs_types, picture_dir, picture_ext):
2629 """Build presentations of the given types for all fields of the proxy.
2631 Save snapshots in graphics files (type depends on the given extension).
2632 Stores the files in the given directory.
2635 proxy: the pipeline object, containig data
2636 view: the render view
2637 prs_types: the list of presentation types to build
2638 picture_dir: the directory path for saving snapshots
2639 picture_ext: graphics files extension (determines file type)
2642 proxy.UpdatePipeline()
2643 # List of the field names
2644 fields_info = proxy.GetProperty("FieldsTreeInfo")[::2]
2646 # Add path separator to the end of picture path if necessery
2647 if not picture_dir.endswith(os.sep):
2648 picture_dir += os.sep
2651 if PrsTypeEnum.MESH in prs_types:
2653 mesh_names = get_mesh_full_names(proxy)
2654 for mesh_name in mesh_names:
2655 # Build mesh field presentation
2656 print "Creating submesh for '" + get_field_short_name(mesh_name) + "' mesh... "
2657 prs = MeshOnEntity(proxy, mesh_name, None)
2663 # Construct image file name
2664 pic_name = picture_dir + get_field_short_name(mesh_name) + "." + picture_ext
2666 # Show and dump the presentation into a graphics file
2667 process_prs_for_test(prs, view, pic_name, False)
2669 # Create Mesh presentation. Build all groups.
2670 extGrp = pvs.ExtractGroup()
2671 extGrp.UpdatePipelineInformation()
2672 if if_possible(proxy, None, None, PrsTypeEnum.MESH, extGrp):
2673 for group in get_group_names(extGrp):
2674 print "Creating submesh on group " + get_group_short_name(group) + "... "
2675 prs = MeshOnGroup(proxy, extGrp, group)
2681 # Construct image file name
2682 pic_name = picture_dir + get_group_short_name(group) + "." + picture_ext
2684 # Show and dump the presentation into a graphics file
2685 process_prs_for_test(prs, view, pic_name, False)
2687 # Presentations on fields
2688 for field in fields_info:
2689 field_name = get_field_short_name(field)
2690 # Ignore mesh presentation
2691 if field_name == get_field_mesh_name(field):
2693 field_entity = get_field_entity(field)
2694 # Select only the current field:
2695 # necessary for getting the right timestamps
2696 proxy.AllArrays = [field]
2697 proxy.UpdatePipeline()
2700 timestamps = proxy.TimestepValues.GetData()
2702 for prs_type in prs_types:
2703 # Ignore mesh presentation
2704 if prs_type == PrsTypeEnum.MESH:
2707 # Get name of presentation type
2708 prs_name = PrsTypeEnum.get_name(prs_type)
2710 # Build the presentation if possible
2711 possible = if_possible(proxy, field_name,
2712 field_entity, prs_type)
2714 # Presentation type for graphics file name
2715 f_prs_type = prs_name.replace(' ', '').upper()
2717 for timestamp_nb in xrange(1, len(timestamps) + 1):
2718 time = timestamps[timestamp_nb - 1]
2720 scalar_range = get_data_range(proxy, field_entity,
2721 field_name, cut_off=True)
2722 # exclude time stamps with null lenght of scalar range
2723 if (scalar_range[0] == scalar_range[1]):
2725 print "Creating " + prs_name + " on " + field_name + ", time = " + str(time) + "... "
2727 prs = create_prs(prs_type, proxy,
2728 field_entity, field_name, timestamp_nb)
2730 """ This exception comes from get_nb_components(...) function.
2731 The reason of exception is an implementation of MEDReader
2732 activating the first leaf when reading MED file (refer to
2733 MEDFileFieldRepresentationTree::activateTheFirst() and
2734 MEDFileFieldRepresentationTree::getTheSingleActivated(...) methods).
2736 print "ValueError exception is catched"
2744 # Construct image file name
2745 pic_name = picture_dir + field_name + "_" + str(time) + "_" + f_prs_type + "." + picture_ext
2747 # Show and dump the presentation into a graphics file
2748 process_prs_for_test(prs, view, pic_name)
2752 def delete_pv_object(obj):
2753 # There is a bug when repeating CreateRenderView/Delete calls
2754 # Here is a workaround proposed by KW (#10744)