Example #1
0
    def loadData(self):
        global dataPath
        mainpath = os.path.join(dataPath, "main")

        if os.path.isdir(mainpath):
            files = os.listdir(mainpath)
            for file in files:
                fullpath = os.path.join(mainpath, file)
                if os.path.isfile(fullpath):
                    self.srcObj = simple.OpenDataFile(fullpath)
                    simple.SetActiveSource(self.srcObj)
                    self.rep = simple.GetDisplayProperties()
                    simple.Hide()

                    print 'Loaded %s into scene' % fullpath
        else:
            print 'Error: ' + mainpath + ' does not exist\n'
            raise Exception("The main directory does not exist")

        surfacespath = os.path.join(dataPath, "surfaces")
        files = os.listdir(surfacespath)
        for file in files:
            fullpath = os.path.join(surfacespath, file)
            if os.path.isfile(fullpath):
                self._loadSurfaceWithProperties(fullpath)

        simple.SetActiveSource(self.srcObj)
        simple.ResetCamera()
        simple.Render()
def createTemporalTransformsAxes(source="default", renderView="default"):
    """ Display orientation part of a TemporalTransforms

    Allow visualizing the orientations part of the TemporalTransforms by
    displaying the x, y and z unitary vector of the sensor reference frame.

    The source must provide transforms, for example it could be:
    a TemporalTransformReader, or the trajectory output of Lidar SLAM

    ParaView pipeline elements are created. These elements can be deleted
    using function deleteAllTemporalTransformsAxes().
    """
    # GetActiveSource() and GetRenderView() do not work if used as default
    # parameter value, so they are called here if needs be:
    if source == "default":
        source = smp.GetActiveSource()
    if renderView == "default":
        renderView = smp.GetRenderView()
    smp.SetActiveSource(source)  # maybe useless
    calculatorX = setupCalculator(source, "RX", [1.0, 0.0, 0.0], fx,
                                  renderView)
    calculatorY = setupCalculator(source, "RY", [0.0, 1.0, 0.0], fy,
                                  renderView)
    calculatorZ = setupCalculator(source, "RZ", [0.0, 0.0, 1.0], fz,
                                  renderView)
    smp.Render()
Example #3
0
    def addSource(self, algo_name, parent):
        pid = str(parent)
        parentProxy = helper.idToProxy(parent)
        if parentProxy:
            simple.SetActiveSource(parentProxy)
        else:
            pid = '0'

        # Create new source/filter
        cmdLine = 'simple.' + algo_name + '()'
        newProxy = eval(cmdLine)

        # Create its representation and render
        simple.Show()
        simple.Render()
        simple.ResetCamera()

        # Add node to pipeline
        self.pipeline.addNode(pid, newProxy.GetGlobalIDAsString())

        # Handle domains
        helper.apply_domains(parentProxy, newProxy.GetGlobalIDAsString())

        # Create LUT if need be
        if pid == '0':
            self.lutManager.registerFieldData(
                newProxy.GetPointDataInformation())
            self.lutManager.registerFieldData(
                newProxy.GetCellDataInformation())

        # Return the newly created proxy pipeline node
        return helper.getProxyAsPipelineNode(newProxy.GetGlobalIDAsString(),
                                             self.lutManager)
Example #4
0
    def probe(self, variable, point):
        """Return the value of a variable at a given point.

        Args:
            variable (str): Name of the variable.
                Probing a vector return its magnitude.
                Components of the vector are available by adding a suffix
                ' X', ' Y' or ' Z' to the vector name.
                Physical coordinates are available under the name 'X', 'Y' or 'Z'.
            point (tuple): x, y and z coordinates.

        Returns:
            float: Queried value or None.
                None is returned if the variable does not exist or the point is not
                defined at the given point.
        """

        pvs.SetActiveSource(self.reader)
        prob_loc = pvs.ProbeLocation(ProbeType="Fixed Radius Point Source")
        prob_loc.ProbeType.Center = point
        array = _get_variable_array(prob_loc, variable)

        pvs.Delete(prob_loc)

        if array is None or len(array) == 0:
            return None
        elif len(array) != 1:
            raise Exception("Unexpected length of the array.")
        else:
            return array[0]
Example #5
0
    def line(self, variable, line, npoints=100, only_inside=True):
        """Return a list of the variable values along the line.

        Args:
            variable (str): Name of the variable.
                See :py:meth:`DataSource.probe` for details.
            line (tuple): Tuple (point1, point2), where point1 and point2 are
                three-float tuples representing the coordinates of the start
                and end point of the line.
            npoints (int): Number of points along the line.
            only_inside (bool): True if the values outside of the defined data
                should be excluded. Otherwise, return NaN for these points.
                If True, length of the returned array could differ from npoints.

        Returns:
            numpy.ndarray: Variable values or None, if the variable
                does not exist.
        """
        pvs.SetActiveSource(self.reader)
        pol = pvs.PlotOverLine(Source="High Resolution Line Source")
        pol.Source.Resolution = npoints - 1
        pol.Source.Point1 = line[0]
        pol.Source.Point2 = line[1]

        array = _get_variable_array(pol, variable, only_inside)
        return array
Example #6
0
    def compute(self):
        if self.pvInstance:
            del self.pvInstance
        pv.SetActiveSource(None)
        if not self.pvInstance:
            if hasattr(self, "pvFunction"):
                self.pvInstance = self.pvFunction()
            else:
                self.pvInstance = getattr(pv, self.pvClass)()

        # We need to set input before other properties
        if self.inputPorts.has_key('Input'):
            inp = extract_pv_instances(
                self.forceGetInputListFromPort('Input'))[0]
            setattr(self.pvInstance, "Input", inp)

        for (function, connector_list) in self.inputPorts.iteritems():
            paramList = extract_pv_instances(
                self.forceGetInputListFromPort(function))
            if function != 'Input':
                if len(paramList) > 1:
                    setattr(self.pvInstance, function, paramList)
                else:
                    setattr(self.pvInstance, function, paramList[0])

        if hasattr(self.pvInstance, 'UpdatePipeline'):
            self.pvInstance.UpdatePipeline()

        self.setResult('Output', self)
Example #7
0
    def extractSubgrid(self, bounds):
        if (self.subgrid is not None):
            simple.Delete(self.subgrid)
        simple.SetActiveSource(self.srcObj)
        self.subgrid = simple.ExtractSubset()
        self.subgrid.VOI = bounds
        simple.SetActiveSource(self.subgrid)

        self.rep = simple.Show()
        self.rep.ScalarOpacityFunction = self.sof
        self.rep.ColorArrayName = self.colorArrayName
        self.rep.Representation = 'Volume'
        self.rep.SelectionPointFieldDataArrayName = self.colorArrayName
        self.rep.LookupTable = self.lookupTable

        simple.Hide(self.srcObj)
        simple.SetActiveSource(self.subgrid)
        simple.Render()
Example #8
0
    def _sliceSurfaces(self, slice):
        if self.meshSlice is not None:
            simple.Delete(self.meshSlice)
            self.meshSlice = None

        for surface in self.surfaces:
            rep = simple.Show(surface)

            if self.sliceMode == 'XY Plane':
                origin = [
                    0.0, 0.0,
                    math.cos(math.radians(rep.Orientation[2])) * slice
                ]
                normal = [0.0, 0.0, 1.0]
            elif self.sliceMode == 'XZ Plane':
                origin = [
                    0.0,
                    math.cos(math.radians(rep.Orientation[1])) * slice, 0.0
                ]
                normal = [0.0, 1.0, 0.0]
            else:
                origin = [
                    math.cos(math.radians(rep.Orientation[0])) * slice, 0.0,
                    0.0
                ]
                normal = [1.0, 0.0, 0.0]

            simple.Hide(surface)
            self.meshSlice = simple.Slice(Input=surface, SliceType='Plane')
            simple.SetActiveSource(self.srcObj)

            self.meshSlice.SliceOffsetValues = [0.0]
            self.meshSlice.SliceType = 'Plane'
            self.meshSlice.SliceType.Origin = origin
            self.meshSlice.SliceType.Normal = normal
            meshDataRep = simple.Show(self.meshSlice)

            meshDataRep.Representation = 'Points'
            meshDataRep.LineWidth = self.CONTOUR_LINE_WIDTH
            meshDataRep.PointSize = self.CONTOUR_LINE_WIDTH
            meshDataRep.AmbientColor = rep.DiffuseColor
            meshDataRep.Orientation = rep.Orientation

        simple.SetActiveSource(self.srcObj)
Example #9
0
def fitPlane():
    src = smp.GetActiveSource()

    selection = GetSelectionSource(src)

    if not selection:
        return

    extracter = smp.ExtractSelection()
    extracter.Selection = selection
    extracter.Input = src
    smp.Show(extracter)

    try:
        pd = extracter.GetClientSideObject().GetOutput()

        origin = range(3)
        normal = range(3)
        mind, maxd, stddev = vtk.mutable(0), vtk.mutable(0), vtk.mutable(0)

        channelMean = range(32)
        channelStdDev = range(32)
        channelNpts = range(32)

        vvmod.vtkPlaneFitter.PlaneFit(pd, origin, normal, mind, maxd, stddev, channelMean, channelStdDev, channelNpts)
        rows = [['overall', origin, normal, 0.0, stddev, stddev, pd.GetNumberOfPoints()]]
        rows = rows + [['%d' % i, origin, normal,
                        channelMean[i], channelStdDev[i],
                        math.sqrt(channelMean[i]**2 + channelStdDev[i]**2),
                        channelNpts[i]]
                       for i in range(32)]

        def rowconverter(x):
            try:
                return '\t'.join(['%.4f' % d for d in x])
            except TypeError:
                try:
                    x = x.get()
                except AttributeError:
                    pass
                if type(x) == float:
                    return '%.4f' % x
                elif type(x) in (int, long):
                    return '%d' % x
                else:
                    return x

        print '\t'.join(['channel','originx','originy','originz','normalx','normaly','normalz',
                         'mean','stddev','RMS','npts'])
        for r in rows:
            if r[-1] == 0:
                r[-4:-1] = ['nan', 'nan', 'nan']
            print '\t'.join([rowconverter(x) for x in r])
    finally:
        smp.Delete(extracter)
        smp.SetActiveSource(src)
Example #10
0
 def test_RenameSource(self):
     source = simple.Sphere(guiName='oldName')
     simple.SetActiveSource(source)
     simple.RenameSource('newName')
     # changing the source name should unregister the old name
     self.assertEqual(None, self.pxm.GetProxy('sources', 'oldName'))
     self.assertEqual(source, self.pxm.GetProxy('sources', 'newName'))
     # renaming as the current name should not unregister the source
     simple.RenameSource('newName')
     self.assertEqual(source, self.pxm.GetProxy('sources', 'newName'))
Example #11
0
    def showSphere(self, params):
        if self.sphere is not None:
            simple.Delete(self.sphere)

        maxDim = max(self.bounds[1] - self.bounds[0],
                     self.bounds[3] - self.bounds[2],
                     self.bounds[5] - self.bounds[4])

        self.sphere = simple.Sphere()
        self.sphere.Radius = maxDim / 100.0
        self.sphere.Center = params['point']
        rep = simple.Show()
        rep.Representation = 'Surface'
        rep.DiffuseColor = params['color']

        simple.SetActiveSource(self.srcObj)
    def drawCone(self):

        ##################################################
        # create a new Cone object
        self.cone1 = simple.Cone()

        ## In a Paraview Trace recorded session, the 'simple.' object is
        ## not necessary.  Take your Trace output and add 'simple.' to all
        ## the capitalized functions and add 'self.' to the local
        ## variables, and try just dropping it in here.

        # set active source
        simple.SetActiveSource(self.cone1)

        # get active view
        self.renderView1 = simple.GetActiveViewOrCreate('RenderView')

        # show data in view
        self.cone1Display = simple.Show(self.cone1, self.renderView1)

        # trace defaults for the display properties.
        self.cone1Display.Representation = 'Surface'

        # reset view to fit data
        self.renderView1.ResetCamera()

        # Properties modified on cone1
        self.cone1.Resolution = 12

        # change solid color
        self.cone1Display.DiffuseColor = [0.666, 0.0, 1.0]

        # reset view to fit data
        self.renderView1.ResetCamera()

        # update the view to ensure updated data information
        self.renderView1.Update()

        # current camera placement for renderView1
        self.renderView1.CameraPosition = [1.25, -3.0, -0.4]
        self.renderView1.CameraViewUp = [0.75, 0.2, 0.6]
        self.renderView1.CameraParallelScale = 0.85
Example #13
0
    def show(self, key_array="x_velocity", source=None, rescale=False):
        """Show the rendered output on the screen."""
        Input = source if source else self.nek5000

        display = pv.Show(Input, self.renderView1)
        pv.ColorBy(display, ("POINTS", key_array))
        if rescale:
            display.RescaleTransferFunctionToDataRange(True, False)
        display.SetScalarBarVisibility(source, True)

        # ... lot of parameters are possible here

        pv.SetActiveSource(source)

        try:
            LUT = pv.GetColorTransferFunction(key_array)
            PWF = pv.GetOpacityTransferFunction(key_array)
        except AttributeError:
            pass

        return display
Example #14
0
    def boundary_line(self,
                      variable,
                      plane_point,
                      plane_normal,
                      bounding_box=None):
        """ Return a list of the variable values along the intersection of the
        domain boundary with a plane.

        Args:
            variable (str): Name of the variable.
                See :py:meth:`DataSource.probe` for details.
            plane_point (tuple): three-float tuple representing the point on
                the plane.
            plane_normal (tuple): three-float tuple representing the normal of
                the plane.
            bounding_box (tuple): Tuple (minx, miny, minz, maxx, maxy, maxz),
                where the values are the limits of the bounding box. Each point
                can be replaced by None if the appropriate bound is missing.


        Returns:
            numpy.ndarray: Variable values or None, if the variable
                does not exist.
        """
        pvs.SetActiveSource(self.reader)

        poic = pvs.PlotOnIntersectionCurves(Input=self.reader)
        poic.SliceType = 'Plane'
        poic.SliceType.Origin = plane_point
        poic.SliceType.Normal = plane_normal

        latest = poic
        if bounding_box:
            latest = _add_bounding_box(latest, bounding_box)

        array = _get_variable_array(latest, variable, True)
        return array
Example #15
0
    def ArrowsScript(Input1, Input2, Output, CamDirVec=None, CamUpVec=None):

        #### disable automatic camera reset on 'Show'
        pvs._DisableFirstRenderCameraReset()

        # create a new 'XML Unstructured Grid Reader'
        VTU1 = pvs.XMLUnstructuredGridReader(FileName=[Input1])
        VTU1.PointArrayStatus = ['Curvature']

        # create a new 'XML Unstructured Grid Reader'
        VTU2 = pvs.XMLUnstructuredGridReader(FileName=[Input2])
        VTU2.PointArrayStatus = ['Curvature']

        # get active view
        renderView1 = pvs.GetActiveViewOrCreate('RenderView')

        # show data in view
        VTU1Display = pvs.Show(VTU1, renderView1)
        VTU1Display.Representation = 'Surface'
        VTU1Display.Diffuse = 0.85
        VTU1Display.Ambient = 0.25

        makeGlyph(VTU1, renderView1, scale=40.0, color=[1.0, 0.0, 0.0])
        makeGlyph(VTU2, renderView1, scale=30.0, color=[0.0, 0.0, 1.0])

        # Save Screenshot
        AdjustCameraAndSave(renderView1,
                            Output,
                            ImageResolution=(2048, 2048),
                            CamDirVec=CamDirVec,
                            CamUpVec=CamUpVec)

        # set active source
        pvs.SetActiveSource(None)
        pvs.SetActiveView(None)
        pvs.Disconnect()
Example #16
0
 def updateEventCb(self, obj, event):
     name = self._getSourceToExtractName(obj)
     if not self.source:
         self.source = simple.FindSource(name)
     simple.SetActiveSource(self.source)
     if self.source and not self.rep:
         self.outline = simple.Outline(self.source)
         self.rep = simple.Show(self.source)
         self.outline.UpdatePipeline()
         self.outlineRep = simple.Show(self.outline)
         # TODO: this is for the demo
         # TODO: what would be the best way to change sources and representations from the client ?
         # create a protocol for liveInsituLink.GetInsituProxyManager() ?
         # or setActiveSource endpoint ?
         # or is there a better way ?
         info = self.source.GetPointDataInformation()
         if info.GetNumberOfArrays() > 0:
             arrName = info.GetArray(0).Name
             self.rep.ColorArrayName = ['POINTS', arrName]
             simple.ColorBy(self.rep, arrName)
         # Point gaussian
         props = simple.GetDisplayProperties(self.source)
         props.SetRepresentationType('Point Gaussian')
         props.GaussianRadius = 0.01
Example #17
0
    raise WrongInput('Source has no information, uncomplete.')
composite_class = info.GetCompositeDataClassName()
if composite_class is None or not composite_class == 'vtkMultiBlockDataSet':
    raise WrongInput(
        'Source produce wrong type of data. MultiBlockDataSet required.')

# make a filter to collect all well lines in order
# to workaround a bug that do not porduce selsection labels
# on composite datasets
merged = ps.ProgrammableFilter()
merged.Script = merge_groups_script
merged.OutputDataSetType = 0  # PolyData
merged.Input = source

# update pipeline in order to get total number of points
ps.SetActiveSource(merged)
ps.UpdatePipeline()

# make selection where to show labels
n_points = merged.GetDataInformation().DataInformation.GetNumberOfPoints()
selection = ps.IDSelectionSource()
IDs = []
for i in range(n_points):
    # select only non-head points
    IDs.append(0L)
    IDs.append(long(i))
selection.IDs = IDs
selection.FieldType = 1  # select point
merged.SetSelectionInput(0, selection, 0)

# get representation and select its selection properties
Example #18
0
    def execute(self):
        self.cdms_variables = self.forceGetInputListFromPort('cdms_variable')
        for cdms_var in self.cdms_variables:

            #// @todo: hardcoded for now
            time_values = [None, 1, True]

            #// Get the min and max to draw default contours
            min = cdms_var.var.min()
            max = cdms_var.var.max()

            reader = PVCDMSReader()
            image_data = reader.convert(cdms_var, time=time_values)

            #// Make white box filter so we can work at proxy level
            programmable_source = pvsp.ProgrammableSource()

            #// Get a hole of the vtk level filter it controls
            ps = programmable_source.GetClientSideObject()

            #//  Give it some data (ie the imagedata)
            ps.myid = image_data

            programmable_source.OutputDataSetType = 'vtkImageData'
            programmable_source.PythonPath = ''

            #// Make the scripts that it runs in pipeline RI and RD passes
            programmable_source.ScriptRequestInformation = """
executive = self.GetExecutive()
outInfo = executive.GetOutputInformation(0)
extents = self.myid.GetExtent()
spacing = self.myid.GetSpacing()
outInfo.Set(executive.WHOLE_EXTENT(), extents[0], extents[1], extents[2], extents[3], extents[4], extents[5])
outInfo.Set(vtk.vtkDataObject.SPACING(), spacing[0], spacing[1], spacing[2])
dataType = 10 # VTK_FLOAT
numberOfComponents = 1
vtk.vtkDataObject.SetPointDataActiveScalarInfo(outInfo, dataType, numberOfComponents)"""

            programmable_source.Script = """self.GetOutput().ShallowCopy(self.myid)"""
            programmable_source.UpdatePipeline()
            pvsp.SetActiveSource(programmable_source)

            self.slice_by_var_name = cdms_var.varname
            self.slice_by_var_type = 'POINTS'

            if not reader.is_three_dimensional(cdms_var):
                data_rep = pvsp.Show(view=self.view)
                data_rep.LookupTable = pvsp.GetLookupTableForArray(
                    self.slice_by_var_name,
                    1,
                    NanColor=[0.25, 0.0, 0.0],
                    RGBPoints=[
                        min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15
                    ],
                    VectorMode='Magnitude',
                    ColorSpace='Diverging',
                    LockScalarRange=1)
                data_rep.ColorArrayName = self.slice_by_var_name
                continue

            functions = []
            try:
                slice_origin = self.forceGetInputListFromPort("slice_origin")
                if (slice_origin == None) or len(slice_origin) == 0:
                    bounds = image_data.GetBounds()
                    self.slice_origin = []
                    self.slice_origin.append((bounds[1] + bounds[0]) / 2.0)
                    self.slice_origin.append((bounds[3] + bounds[2]) / 2.0)
                    self.slice_origin.append((bounds[5] + bounds[4]) / 2.0)
                    functions.append(
                        ('slice_origin', [str(self.slice_origin).strip('[]')]))
                else:
                    self.slice_origin = [
                        float(d) for d in slice_origin[0].split(',')
                    ]

                slice_normal = self.forceGetInputListFromPort("slice_normal")
                if slice_normal == None or len(slice_normal) == 0:
                    self.slice_normal = [0.0, 0.0, 1.0]
                    functions.append(
                        ('slice_normal', [str(self.slice_normal).strip('[]')]))
                else:
                    self.slice_normal = [
                        float(d) for d in slice_normal[0].split(',')
                    ]

                slice_offset_values = self.forceGetInputListFromPort(
                    "slice_offset_values")
                if (len(slice_offset_values) and slice_offset_values):
                    self.slice_offset_values = [
                        float(d) for d in slice_offset_values[0].split(',')
                    ]
                else:
                    self.slice_offset_values = [0.0]
                    functions.append(
                        ('slice_offset_values',
                         [str(self.slice_offset_values).strip('[]')]))

                if len(functions) > 0:
                    self.update_functions('PVSliceRepresentation', functions)

                #// Create a slice representation
                plane_slice = pvsp.Slice(SliceType="Plane")
                pvsp.SetActiveSource(plane_slice)

                plane_slice.SliceType.Normal = self.slice_normal
                plane_slice.SliceType.Origin = self.slice_origin
                plane_slice.SliceOffsetValues = self.slice_offset_values

                slice_rep = pvsp.Show(view=self.view)

                slice_rep.LookupTable = pvsp.GetLookupTableForArray(
                    self.slice_by_var_name,
                    1,
                    NanColor=[0.25, 0.0, 0.0],
                    RGBPoints=[
                        min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15
                    ],
                    VectorMode='Magnitude',
                    ColorSpace='Diverging',
                    LockScalarRange=1)
                slice_rep.ColorArrayName = self.slice_by_var_name
                slice_rep.Representation = 'Surface'

                #// Scalar bar
                ScalarBarWidgetRepresentation1 = pvsp.CreateScalarBar(
                    Title=self.slice_by_var_name,
                    LabelFontSize=12,
                    Enabled=1,
                    TitleFontSize=12)
                self.view.Representations.append(
                    ScalarBarWidgetRepresentation1)

                if not reader.is_three_dimensional(cdms_var):
                    ScalarBarWidgetRepresentation1.LookupTable = data_rep.LookupTable
                else:
                    ScalarBarWidgetRepresentation1.LookupTable = slice_rep.LookupTable

            except ValueError:
                print "[ERROR] Unable to generate slice. Please check your input values"
            except (RuntimeError, TypeError, NameError):
                print "[ERROR] Unknown error"
Example #19
0
    def StreamlinesScript(Input1,
                          Input2,
                          Output,
                          N1=None,
                          N2=None,
                          Offset1=0.0,
                          Offset2=0.0,
                          CamDirVec=None,
                          CamUpVec=None,
                          Origin=None):
        ''' Creates an image with the streamlines from two VTUs.

            Inputs:
                Input1 - VTU with first direction of curvatures
                Input2 - VTU with second direction of curvatures
                N1 - List of normal of slice for VTU1
                N2 - List of normal of slice for VTU2
                Offset1 - Value of offset for slice of VTU1
                Offset2 - Value of offset for slice of VTU2
                CamDirVec - Vector for camera direction
                CamUpVec - Vector for camera up direction
                Origin - Vector with the position for the origin'''

        #### disable automatic camera reset on 'Show'
        pvs._DisableFirstRenderCameraReset()

        # create a new 'XML Unstructured Grid Reader'
        VTU1 = pvs.XMLUnstructuredGridReader(FileName=[Input1])
        VTU1.PointArrayStatus = ['Curvature']

        ## Fix data for Slices
        if N1 is None:
            N1 = [0.9, 0.4, 0.2]
        if N2 is None:
            # N2 = np.cross(N1,[0,0,1])
            N2 = [-0.8, 0.5, 0.16]
        if Origin is None:
            Origin = paraview.servermanager.Fetch(
                pvs.IntegrateVariables(Input=VTU1)).GetPoint(0)

        # create a new 'XML Unstructured Grid Reader'
        VTU2 = pvs.XMLUnstructuredGridReader(FileName=[Input2])
        VTU2.PointArrayStatus = ['Curvature']

        # get active view
        renderView1 = pvs.GetActiveViewOrCreate('RenderView')

        # show data in view
        VTU1Display = pvs.Show(VTU1, renderView1)
        VTU1Display.Representation = 'Surface'
        VTU1Display.Diffuse = 0.85
        VTU1Display.Ambient = 0.25
        # show data in view
        VTU2Display = pvs.Show(VTU2, renderView1)
        VTU2Display.Representation = 'Surface'
        VTU2Display.Diffuse = 0.85
        VTU2Display.Ambient = 0.25

        # create a new 'Slice'
        slice1 = pvs.Slice(Input=VTU1)
        slice1.SliceType.Origin = Origin
        slice1.SliceType.Normal = N1
        slice1.SliceType.Offset = 0.0
        slice1.SliceOffsetValues = [Offset1]

        # create a new 'Slice'
        slice2 = pvs.Slice(Input=VTU2)
        slice2.SliceType.Origin = Origin
        slice2.SliceType.Normal = N2
        slice2.SliceType.Offset = 0.0
        slice2.SliceOffsetValues = [Offset2]

        # make stremlines
        makestream(VTU1, slice1, renderView1, [1.0, 0.0, 0.0])
        makestream(VTU2, slice2, renderView1, [0.0, 0.0, 1.0])

        # Save Screenshot
        AdjustCameraAndSave(renderView1,
                            Output,
                            ImageResolution=(2048, 2048),
                            CamDirVec=CamDirVec,
                            CamUpVec=CamUpVec)

        # set active source
        pvs.SetActiveSource(None)
        pvs.SetActiveView(None)
        pvs.Disconnect()
Example #20
0
        nc.GetColorRGB("Black", rgb)
        rgbPoints += [float(maxAmb)] + rgb  # Rejected Ambiguity
    cLUT.RGBPoints = rgbPoints

# show data in view
glyph1Display = pv.Show(glyph1, renderView1)
glyph1Display.ColorArrayName = ['POINTS', args.colourColumn]
glyph1Display.LookupTable = cLUT
if args.pcaFile:
    glyph1Display.Opacity = .1

# show color bar/color legend
glyph1Display.SetScalarBarVisibility(renderView1, True)

# set active source
pv.SetActiveSource(None)

cylinder1 = pv.Cylinder()

# Properties modified on cylinder1
cylinder1.Resolution = 60
cylinder1.Height = tpcLength
cylinder1.Radius = tpcRadius

# show data in view
cylinder1Display = pv.Show(cylinder1, renderView1)
cylinder1Display.Orientation = [90.0, 0.0, 0.0]
cylinder1Display.Opacity = 0.05
nc.GetColorRGB("White", rgb)
cylinder1Display.DiffuseColor = rgb
Example #21
0
    def execute(self):
        self.cdms_variables = self.forceGetInputListFromPort('cdms_variable')
        for cdms_var in self.cdms_variables:

            #// Get the min and max to draw default contours
            min = cdms_var.var.min()
            max = cdms_var.var.max()

            reader = PVCDMSReader()
            time_values = [None, 1, True]
            image_data = reader.convert(cdms_var, time=time_values)

            #// Make white box filter so we can work at proxy level
            ProgrammableSource1 = pvsp.ProgrammableSource()

            #// Get a hole of the vtk level filter it controls
            ps = ProgrammableSource1.GetClientSideObject()

            #//  Give it some data (ie the imagedata)
            ps.myid = image_data

            ProgrammableSource1.OutputDataSetType = 'vtkImageData'
            ProgrammableSource1.PythonPath = ''

            #// Make the scripts that it runs in pipeline RI and RD passes
            ProgrammableSource1.ScriptRequestInformation = """
executive = self.GetExecutive()
outInfo = executive.GetOutputInformation(0)
extents = self.myid.GetExtent()
spacing = self.myid.GetSpacing()
outInfo.Set(executive.WHOLE_EXTENT(), extents[0], extents[1], extents[2], extents[3], extents[4], extents[5])
outInfo.Set(vtk.vtkDataObject.SPACING(), spacing[0], spacing[1], spacing[2])
dataType = 10 # VTK_FLOAT
numberOfComponents = 1
vtk.vtkDataObject.SetPointDataActiveScalarInfo(outInfo, dataType, numberOfComponents)"""

            ProgrammableSource1.Script = """self.GetOutput().ShallowCopy(self.myid)"""
            ProgrammableSource1.UpdatePipeline()
            pvsp.SetActiveSource(ProgrammableSource1)

            self.contour_var_name = str(cdms_var.varname)

            #// If the data is three dimensional, then don't draw the background imagery
            #// since it may hide the contours
            if not reader.is_three_dimensional(cdms_var):
                data_rep = pvsp.Show(view=self.view)
                data_rep.LookupTable = pvsp.GetLookupTableForArray(
                    self.contour_var_name,
                    1,
                    NanColor=[0.25, 0.0, 0.0],
                    RGBPoints=[
                        min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15
                    ],
                    VectorMode='Magnitude',
                    ColorSpace='Diverging',
                    LockScalarRange=1)
                data_rep.ColorArrayName = self.contour_var_name

            try:
                contour = pvsp.Contour()
                pvsp.SetActiveSource(contour)
                contour.ContourBy = ['POINTS', self.contour_var_name]

                delta = (max - min) / 10.0

                contours = self.forceGetInputListFromPort("contour_values")
                if (len(contours) and contours):
                    self.contour_values = [
                        float(d) for d in contours[0].split(',')
                    ]

                # if( (self.contour_values == None) or (len(self.contour_values) == 0) ):
                else:
                    self.contour_values = [(x * delta + min)
                                           for x in range(10)]
                    functions = []
                    functions.append(("contour_values",
                                      [str(self.contour_values).strip('[]')]))
                    self.update_functions('PVContourRepresentation', functions)

                contour.Isosurfaces = self.contour_values
                contour.ComputeScalars = 1
                contour.ComputeNormals = 0
                contour.UpdatePipeline()

                #// @todo: Remove hard-coded values
                contour_rep = pvsp.Show(view=self.view)
                contour_rep.Representation = 'Surface'
                if reader.is_three_dimensional(cdms_var):
                    contour_rep.LookupTable = pvsp.GetLookupTableForArray(
                        self.contour_var_name,
                        1,
                        NanColor=[0.25, 0.0, 0.0],
                        RGBPoints=[
                            min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15
                        ],
                        VectorMode='Magnitude',
                        ColorSpace='Diverging',
                        LockScalarRange=1)
                    contour_rep.ColorArrayName = self.contour_var_name
                else:
                    contour_rep.DiffuseColor = [0.0, 0.0, 0.0]
                    contour_rep.ColorArrayName = ''

                #// Scalar bar
                ScalarBarWidgetRepresentation1 = pvsp.CreateScalarBar(
                    Title=self.contour_var_name,
                    LabelFontSize=12,
                    Enabled=1,
                    TitleFontSize=12)
                self.view.Representations.append(
                    ScalarBarWidgetRepresentation1)

                if not reader.is_three_dimensional(cdms_var):
                    ScalarBarWidgetRepresentation1.LookupTable = data_rep.LookupTable
                else:
                    ScalarBarWidgetRepresentation1.LookupTable = contour_rep.LookupTable

            except ValueError:
                print "[ERROR] Unable to generate contours. Please check your input values"
            except (RuntimeError, TypeError, NameError):
                print "[ERROR] Unknown error"
                pass
    def createViews(self):
        """Create views
        """
        # Disable automatic camera reset on 'Show'
        pv._DisableFirstRenderCameraReset()

        # Create render view
        renderView = self.createRenderView([900, 900])

        # Activate render view
        pv.SetActiveView(renderView)

        # Create ExodusII reader
        reader = self.createExodusIIReader("Weight", "Load")

        # Create sqrt(load) calculator to optimize visuals
        sqrt_load = self.createCalculator(reader, "sqrt", "Load")

        # Create sqrt(load) glyph
        glyph = self.createGlyph(sqrt_load,
                                      factor=0.05)

        # Instantiate weight colors and points
        weight_colors = [223.48540319420192,
                         0.231373,
                         0.298039,
                         0.752941,
                         784.8585271892204,
                         0.865003,
                         0.865003,
                         0.865003,
                         1346.2316511842387,
                         0.705882,
                         0.0156863,
                         0.14902]
        weight_points = [223.48540319420192,
                         0.0,
                         0.5,
                         0.0,
                         1346.2316511842387,
                         1.0,
                         0.5,
                         0.0]
        # Create color transfert functions
        weightLUT = self.createColorTransferFunction(
            "Weight",
            weight_colors,
            [1., 1., 1.],
            0.0)
        weightPWF = self.createOpacityTransferFunction(
            "Weight",
            weight_points)

        readerDisplay = self.createDisplay(
            reader,
            renderView,
            ['CELLS', 'Weight'],
            weightLUT,
            4.0,
            None,
            None,
            weightPWF)

        # Instantiate load colors and points
        load_colors = [0.0,
                       0.231373,
                       0.298039,
                       0.752941,
                       130.73569142337513,
                       0.865003,
                       0.865003,
                       0.865003,
                       261.47138284675026,
                       0.705882,
                       0.0156863,
                       0.14902]
        load_points = [0.0,
                       0.0,
                       0.5,
                       0.0,
                       261.47138284675026,
                       1.0,
                       0.5,
                       0.0]

        # Create color transfert functions
        loadLUT = self.createColorTransferFunction(
            "Load",
            load_colors,
            [1.,1.,1.],
            None,
            "Never")
        loadPWF = self.createOpacityTransferFunction(
            "Load",
            load_points)

        # Create displays
        glyphDisplay = self.createDisplay(
            glyph,
            renderView,
            ['POINTS', 'Load'],
            loadLUT,
            None,
            0.005)

        # Activate glyph source
        pv.SetActiveSource(glyph)

        return reader
Example #23
0
def fitPlane():
    src = smp.GetActiveSource()
    if not src:
        return

    selection = GetSelectionSource(src)

    if not selection:
        return

    extracter = smp.ExtractSelection()
    extracter.Selection = selection
    extracter.Input = src
    smp.Show(extracter)

    try:
        pd = extracter.GetClientSideObject().GetOutput()

        if pd.IsTypeOf("vtkMultiBlockDataSet"):
            appendFilter = vtk.vtkAppendFilter()
            for i in range(pd.GetNumberOfBlocks()):
                appendFilter.AddInputData(pd.GetBlock(i))
            appendFilter.Update()
            pd = appendFilter.GetOutput()

        max_laser_id = pd.GetPointData().GetArray("laser_id").GetRange()[1]
        nchannels = 2**vtk.vtkMath.CeilLog2(int(max_laser_id))

        origin = range(3)
        normal = range(3)
        mind, maxd, stddev = vtk.mutable(0), vtk.mutable(0), vtk.mutable(0)

        channelMean = range(nchannels)
        channelStdDev = range(nchannels)
        channelNpts = range(nchannels)

        vvmod.vtkPlaneFitter.PlaneFit(pd, origin, normal, mind, maxd, stddev,
                                      channelMean, channelStdDev, channelNpts,
                                      nchannels)
        rows = [[
            'overall', origin, normal, 0.0, stddev, stddev,
            pd.GetNumberOfPoints()
        ]]
        rows = rows + [[
            '%d' % i, origin, normal, channelMean[i], channelStdDev[i],
            math.sqrt(channelMean[i]**2 + channelStdDev[i]**2), channelNpts[i]
        ] for i in range(nchannels)]

        def rowconverter(x):
            try:
                return '\t'.join(['%.4f' % d for d in x])
            except TypeError:
                try:
                    x = x.get()
                except AttributeError:
                    pass
                if type(x) == float:
                    return '%.4f' % x
                elif type(x) in (int, long):
                    return '%d' % x
                else:
                    return x

        print '\t'.join([
            'channel', 'originx', 'originy', 'originz', 'normalx', 'normaly',
            'normalz', 'mean', 'stddev', 'RMS', 'npts'
        ])
        for r in rows:
            if r[-1] == 0:
                r[-4:-1] = ['nan', 'nan', 'nan']
            print '\t'.join([rowconverter(x) for x in r])
    finally:
        smp.Delete(extracter)
        smp.SetActiveSource(src)
Example #24
0
renderView1.CameraPosition = [1.5707999467849731, 0.5, 4.076661427044123]
renderView1.CameraFocalPoint = [1.5707999467849731, 0.5, 0.7853999733924866]
renderView1.CameraParallelScale = 1.8259971497854517

# save screenshot
pv.SaveScreenshot('/home/avmo/test.png', renderView1, ImageResolution=[1600, 499],
    OverrideColorPalette='WhiteBackground')

# create a new 'Contour'
contour1 = pv.Contour(Input=ablnek5000)
contour1.ContourBy = ['POINTS', 'velocity_mag']
contour1.Isosurfaces = [0.5744097200222313]
contour1.PointMergeMethod = 'Uniform Binning'

# set active source
pv.SetActiveSource(contour1)

# show data in view
contour1Display = pv.Show(contour1, renderView1)

# trace defaults for the display properties.
contour1Display.Representation = 'Surface'
contour1Display.ColorArrayName = ['POINTS', 'velocity_mag']
contour1Display.LookupTable = velocity_magLUT
contour1Display.OSPRayScaleArray = 'velocity_mag'
contour1Display.OSPRayScaleFunction = 'PiecewiseFunction'
contour1Display.SelectOrientationVectors = 'None'
contour1Display.ScaleFactor = 0.31415998935699463
contour1Display.SelectScaleArray = 'velocity_mag'
contour1Display.GlyphType = 'Arrow'
contour1Display.GlyphTableIndexArray = 'velocity_mag'
Example #25
0
#-------------------------------------------------------------------------||---#
PlotOverLine01 = Simple.PlotOverLine( guiName="PlotOverLine01", Source="High Resolution Line Source" )
PlotOverLine01.Source.Resolution = 100
PlotOverLine01.Source.Point2 = [0.00, 0.0, 20.0]
PlotOverLine01.Source.Point1 = [0.00, 0.0, 0.0]
#
PF = Simple.ProgrammableFilter()
PF.Script = Script01
Simple.Show(PF)
#-------------------------------------------------------------------------||---#

#-------------------------------------------------------------------------||---#
Coords = Read_dat("XXX_COORDINATES.alya")
for coord in Coords: 
  print coord, 
  Simple.SetActiveSource(InputData)
  Slice01 = Simple.Slice( guiName="Slice2", SliceOffsetValues=[0.0], SliceType="Plane" )
  Slice01.SliceType.Origin = coord
  Slice01.SliceType.Normal = [0.0, 0.0, 1.0]
  Simple.SetActiveSource(Slice01)

  Calculator01 = Simple.Calculator(guiName="Calculator1", 
                            Function='VELOC_Z*TEMPE', 
                            ResultArrayName='UT')
  Simple.SetActiveSource(Calculator01)

  IntegrateVariables01 = Simple.IntegrateVariables( guiName="IntegrateVariables2" )
  Simple.SetActiveSource(IntegrateVariables01)

  PF = Simple.ProgrammableFilter()
  PF.Script = Script02 
def batchVis(c1File,particleFile,step,saveAs):
    """Renders a bijel top down view in paraview and saves a screenshot."""
    import paraview.simple as pv
    # visualize a vtk file 
    c1 = pv.LegacyVTKReader(FileNames=c1File)
    p = pv.LegacyVTKReader(FileNames=particleFile)
    renderView1 = pv.GetActiveViewOrCreate('RenderView')
    renderView1.ViewSize = [1298, 860]
    renderView1.Background = [1.0, 1.0, 1.0]
    renderView1.InteractionMode = '2D'
    pDisplay = pv.Show(p, renderView1)
    c1Display = pv.Show(c1, renderView1)

    # create particle glyphs
    glyph = pv.Glyph(Input=p,GlyphType="Sphere")
    glyph.ScaleFactor = 1.0
    glyph.GlyphMode = 'All Points'
    glyph.GlyphType.Radius = 1.0
    glyph.GlyphType.ThetaResolution = 20
    glyph.GlyphType.PhiResolution = 20
    glyph.Scalars = ['POINTS','radius']
    glyph.Vectors = ['POINTS','None']
    glyph.ScaleMode = 'scalar'

    # show data in view
    glyphDisplay = pv.Show(glyph, renderView1)
    pv.ColorBy(glyphDisplay, None)
    pv.SetActiveSource(c1)
    pv.ColorBy(c1Display, ('POINTS', 'c1'))
    c1Display.RescaleTransferFunctionToDataRange(True)
    c1Display.SetRepresentationType('Volume')

    # make box outline
    # box = pv.Box()
    # box.XLength = 128.0
    # box.YLength = 128.0
    # box.ZLength = 64.0
    # box.Center = [64.0, 64.0, 32.0]
    # boxDisplay = pv.Show(box, renderView1)
    # boxDisplay.SetRepresentationType('Outline')
    # boxDisplay.AmbientColor = [0.0, 0.0, 0.0]

    # set coloring of c1
    c1LUT = pv.GetColorTransferFunction('c1')
    c1LUT.RGBPoints = [0.006000000052154064, 0.231373, 0.298039, 0.752941, 0.5120000033639371, 0.865003, 0.865003, 0.865003, 1.0180000066757202, 0.705882, 0.0156863, 0.14902]
    c1LUT.ColorSpace = 'Diverging'
    c1LUT.BelowRangeColor = [0.0, 0.0, 0.0]
    c1LUT.AboveRangeColor = [1.0, 1.0, 1.0]
    c1LUT.NanColor = [1.0, 1.0, 0.0]
    c1LUT.Discretize = 1
    c1LUT.NumberOfTableValues = 256
    c1LUT.ScalarRangeInitialized = 1.0
    c1LUT.AllowDuplicateScalars = 1

    c1PWF = pv.GetOpacityTransferFunction('c1')
    c1PWF.Points = [0.0, 0.05, 0.5, 0.0, 0.3, 0.05, 0.5, 0.0, 0.4, 0.5, 0.5, 0.0, 0.6, 0.5, 0.5, 0.0, 0.7, 0.05, 0.5, 0.0, 1., 0.05, 0.5, 0.0]

    # annotate time step in rendering
    # text = pv.Text
    # text.Text = 'Step '+str(step)
    # textDisplay = pv.Show(text,renderView1)
    # textDisplay.Color = [0.0, 0.0, 0.0]
    # textDisplay.WindowLocation = 'UpperCenter'

    # reset view to fit data
    renderView1.ResetCamera()
    # pv.Render()

    # save screen shot
    viewLayout1 = pv.GetLayout()
    print(saveAs)
    pv.SaveScreenshot(saveAs, layout=viewLayout1, magnification=1, quality=100)

    # clean up
    # pv.Delete(box)
    pv.Delete(glyph)
    pv.Delete(p)
    pv.Delete(c1)
    del c1
    del p
    del glyph
Example #27
0
 def showme(self):
     simple.SetActiveSource(self.proxy)
     self.representation.Visibility = 1
Example #28
0
    def makeStream(self):

        # get color transfer function/color map for the data to color with.
        dataLUT = simple.GetColorTransferFunction(self.plotRecipe.get('EnumColorVariable'))

        # create a new 'Stream Tracer'
        streamTracer = simple.StreamTracer(Input=self.dataObject.getData(),
                                           SeedType='High Resolution Line Source')

        # Properties modified on streamTracer.SeedType
        streamTracer.SeedType.Resolution = 450

        # Properties modified on streamTracer
        streamTracer.MaximumSteps = 600

        # show data in view
        streamTracerDisplay = simple.Show(streamTracer, self.dataObject.renderView)
        # trace defaults for the display properties.
        streamTracerDisplay.Representation = 'Surface'

        # show color bar/color legend
        streamTracerDisplay.SetScalarBarVisibility(self.dataObject.renderView, False)

        # update the view to ensure updated data information
        self.dataObject.renderView.Update()

        # create a new 'Ribbon'
        ribbon = simple.Ribbon(Input=streamTracer)

        # Properties modified on ribbon
        ribbon.Scalars = ['POINTS', self.plotRecipe.get('EnumColorVariable')]

        # show data in view
        ribbonDisplay = simple.Show(ribbon, self.dataObject.renderView)
        # trace defaults for the display properties.
        ribbonDisplay.Representation = 'Surface'

        # hide data in view
        simple.Hide(streamTracer, self.dataObject.renderView)

        # show color bar/color legend
        ribbonDisplay.SetScalarBarVisibility(self.dataObject.renderView, True)

        # update the view to ensure updated data information
        self.dataObject.renderView.Update()

        # set scalar coloring
        ColorBy(ribbonDisplay, ('POINTS', self.plotRecipe.get('EnumColorVariable')))

        # Hide the scalar bar for this color map if no visible data is
        # colored by it.
        simple.HideScalarBarIfNotNeeded(dataLUT, self.dataObject.renderView)

        # rescale color and/or opacity maps used to include current data range
        ribbonDisplay.RescaleTransferFunctionToDataRange(True, False)

        # show color bar/color legend
        ribbonDisplay.SetScalarBarVisibility(self.dataObject.renderView, True)

        # get color transfer function/color map for 'uds_0_scalar'
        colorLUT = simple.GetColorTransferFunction(self.plotRecipe.get('EnumColorVariable'))

        # Properties modified on ribbon
        ribbon.Width = 0.003

        self.dataObject.renderView.ResetCamera()
    
        # update the view to ensure updated data information
        self.dataObject.renderView.Update()

        # set active source
        simple.SetActiveSource(streamTracer)

        # Properties modified on streamTracer.SeedType
        streamTracer.SeedType.Resolution = 200

        # update the view to ensure updated data information
        self.dataObject.renderView.Update()