예제 #1
0
    def processFile(self):
        self._download_mesh_file()

        reader = simple.OpenDataFile(_MeshViewer.meshFile)
        reader.UpdatePipeline()
        self.outline = simple.Show(reader)
        self.outline.Representation = 'Outline'

        # Get information about cell data arrays
        nbFaces = 0
        cdInfo = reader.GetCellDataInformation()
        numberOfCellArrays = cdInfo.GetNumberOfArrays()
        for idx in xrange(numberOfCellArrays):
            array = cdInfo.GetArray(idx)
            if array.GetName() != 'modelfaceids':
                continue
            nbFaces = int(array.GetRange(-1)[1])

        # Extract each face and keep representation around
        _MeshViewer.faces = []
        for idx in range(nbFaces):
            threshold = simple.Threshold(Scalars=['CELLS', 'modelfaceids'],
                                         Input=reader,
                                         ThresholdRange=[idx, idx])
            rep = simple.Show(threshold)
            _MeshViewer.faces.append(rep)

        self.view = simple.Render()
        self.view.Background = [0, 0, 0]
예제 #2
0
def customStartupProcessing(files):
    rv = simple.Render()
    rv.ResetCamera()
    rv.Background = [0.0, 0.0, 0.0]
    simple.Render()

    gior = simple.GenericIOReader(FileName=files)

    gior.xAxis = 'x'
    gior.yAxis = 'y'
    gior.zAxis = 'z'
    gior.PointArrayStatus = ['vx', 'vy', 'vz', 'id', 'fof_halo_tag']

    gior_rep = simple.Show(gior)
    gior_rep.SetRepresentationType('Outline')
    simple.Render()

    gior_rep.ColorArrayName = 'id'
    tag_array = gior.PointData.GetArray('id')
    simple.AssignLookupTable(tag_array, 'erdc_rainbow_bright')

    calc = simple.Calculator()
    calc.Function = 'iHat*vx + jHat*vy + kHat*vz'
    calc.ResultArrayName = 'velocity'

    simple.Render()

    calc_rep = simple.Show(calc)
    calc_rep.ColorArrayName = 'velocity'
    vel_array = calc.PointData.GetArray('velocity')
    simple.AssignLookupTable(vel_array, 'Cool to Warm')

    rv.ResetCamera()
    simple.Render()
예제 #3
0
    def processFile(self):
        self._download_mesh_file()
        self.sideVisibility = []
        self.sideNames = []
        self.sideObjectValue = []

        self.reader = simple.OpenDataFile(_MeshViewer.fileName)
        domain = self.reader.GetProperty('SideSetArrayStatus').GetDomain(
            'array_list')
        sides = []

        for i in range(domain.GetNumberOfStrings()):
            sideName = domain.GetString(i)
            self.sideVisibility.append(True)
            self.sideObjectValue.append(int(sideName.split(': ')[1]))
            self.sideNames.append(sideName)
            sides.append(sideName)

        self.reader.SideSetArrayStatus = sides
        self.reader.ElementBlocks = []
        self.reader.UpdatePipeline()

        bounds = self.reader.GetDataInformation().GetBounds()
        box = simple.Box(XLength=(bounds[1] - bounds[0]),
                         YLength=(bounds[3] - bounds[2]),
                         ZLength=(bounds[5] - bounds[4]),
                         Center=[
                             0.5 * (bounds[0] + bounds[1]),
                             0.5 * (bounds[2] + bounds[3]),
                             0.5 * (bounds[4] + bounds[5])
                         ])
        self.outline = simple.Show(box)
        self.outline.Representation = 'Outline'

        # Color/Annotation management
        annotations = []
        self.colors = []

        for i in range(domain.GetNumberOfStrings()):
            annotations.append(str(self.sideObjectValue[i]))
            annotations.append(self.sideNames[i])
            self.colors.append(0.5)
            self.colors.append(0.5)
            self.colors.append(0.5)

        # Color management
        self.lut = simple.GetColorTransferFunction('ObjectId')
        self.lut.InterpretValuesAsCategories = 1
        self.lut.Annotations = annotations
        self.lut.IndexedColors = self.colors

        mainRep = simple.Show(self.reader)
        vtkSMPVRepresentationProxy.SetScalarColoring(mainRep.SMProxy,
                                                     'ObjectId',
                                                     vtkDataObject.CELL)

        self.view = simple.Render()
        self.view.Background = [0, 0, 0]
    def processFile(self):
        self.sideVisibility = []
        self.sideNames = []
        self.sideObjectValue = []

        self.blockVisibility = []
        self.blockNames = []
        self.blockObjectValue = []

        self.reader = simple.OpenDataFile(_MeshViewer.fileName)

        # Get information about faces and blocks
        self.sideNames, self.sideValues = self.extractSubset(
            'SideSetArrayStatus')
        self.blockNames, self.blockValues = self.extractSubset('ElementBlocks')

        # Show faces to start
        self.reader.SideSetArrayStatus = self.sideNames
        self.reader.ElementBlocks = []
        self.reader.UpdatePipeline()

        # Set up initial visibilities
        self.sideVisibility = [True for i in xrange(len(self.sideNames))]
        self.blockVisibility = [True for i in xrange(len(self.blockNames))]
        self.showingFaces = True

        bounds = self.reader.GetDataInformation().GetBounds()
        box = simple.Box(XLength=(bounds[1] - bounds[0]),
                         YLength=(bounds[3] - bounds[2]),
                         ZLength=(bounds[5] - bounds[4]),
                         Center=[
                             0.5 * (bounds[0] + bounds[1]),
                             0.5 * (bounds[2] + bounds[3]),
                             0.5 * (bounds[4] + bounds[5])
                         ])
        self.outline = simple.Show(box)
        self.outline.Representation = 'Outline'

        # Color/Annotation management
        self.faceAnnotations, self.faceColors = self.setupInitialColors(
            self.sideNames, self.sideValues)
        self.blockAnnotations, self.blockColors = self.setupInitialColors(
            self.blockNames, self.blockValues)

        # Color management, start with faces
        self.lut = simple.GetColorTransferFunction('ObjectId')
        self.lut.InterpretValuesAsCategories = 1
        self.lut.Annotations = self.faceAnnotations
        self.lut.IndexedColors = self.faceColors

        mainRep = simple.Show(self.reader)
        vtkSMPVRepresentationProxy.SetScalarColoring(mainRep.SMProxy,
                                                     'ObjectId',
                                                     vtkDataObject.CELL)

        self.view = simple.Render()
        self.view.Background = [0, 0, 0]
def test():
    w = simple.Wavelet()

    dataRange = [40.0, 270.0]
    arrayName = ('POINT_DATA', 'RTData')
    fileGenerator = FileNameGenerator(
        '/tmp/iso', '{contourBy}_{contourValue}_{theta}_{phi}.jpg')

    cExplorer = ContourExplorer(fileGenerator, w, arrayName, dataRange, 25)
    proxy = cExplorer.getContour()
    rep = simple.Show(proxy)

    lut = simple.GetLookupTableForArray("RTData",
                                        1,
                                        RGBPoints=[
                                            43.34006881713867, 0.23, 0.299,
                                            0.754, 160.01158714294434, 0.865,
                                            0.865, 0.865, 276.68310546875,
                                            0.706, 0.016, 0.15
                                        ])
    rep.LookupTable = lut
    rep.ColorArrayName = arrayName
    view = simple.Render()

    exp = ThreeSixtyImageStackExporter(fileGenerator, view, [0, 0, 0], 100,
                                       [0, 0, 1], [30, 45])
    for progress in cExplorer:
        exp.UpdatePipeline()
        print progress
    def showCone(self):

        print("Showing cone.")
        self.cone1Display = simple.Show(self.cone1, self.renderView1)
        self.renderView1.Update()
        self.coneShown = True
        return "**** executed showCone() ****"
예제 #7
0
 def show(self, name='input'):
     print("show")
     source = simple.FindSource(name)
     if source:
         rep = simple.Show(source)
         return {'id': rep.SMProxy.GetGlobalIDAsString()} if rep else {}
     return {}
예제 #8
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebPublishImageDelivery(decode=False))
        self.updateSecret(_DemoServer.authKey)

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Disable interactor-based render calls
        simple.GetRenderView().EnableRenderOnInteraction = 0
        simple.GetRenderView().Background = [0, 0, 0]
        cone = simple.Cone()
        simple.Show(cone)
        simple.Render()

        # Update interaction mode
        pxm = simple.servermanager.ProxyManager()
        interactionProxy = pxm.GetProxy('settings',
                                        'RenderViewInteractionSettings')
        interactionProxy.Camera3DManipulators = [
            'Rotate', 'Pan', 'Zoom', 'Pan', 'Roll', 'Pan', 'Zoom', 'Rotate',
            'Zoom'
        ]
예제 #9
0
파일: cpstate.py 프로젝트: ufz/catalyst-gui
def run(filename=None):
    """Create a dummy pipeline and save the coprocessing state in the filename
        specified, if any, else dumps it out on stdout."""

    from paraview import simple, servermanager
    simple.LoadDistributedPlugin("CatalystScriptGeneratorPlugin")
    wavelet = simple.Wavelet(registrationName="Wavelet1")
    contour = simple.Contour()
    display = simple.Show()
    view = simple.Render()
    # create a new 'Parallel PolyData Writer'
    parallelPolyDataWriter0 = simple.ParallelPolyDataWriter()

    viewname = servermanager.ProxyManager().GetProxyName("views", view.SMProxy)
    script = DumpPipeline(
        export_rendering=True,
        simulation_input_map={"Wavelet1": "input"},
        screenshot_info={viewname: ['image.png', '1', '1', '2', '400', '400']})
    if filename:
        f = open(filename, "w")
        f.write(script)
        f.close()
    else:
        print "# *** Generated Script Begin ***"
        print script
        print "# *** Generated Script End ***"
예제 #10
0
def loadScene(objFilePath, mtlFilePath):
    mtlReader = MTLParser(mtlFilePath)
    mtlReader.reduceMaterialDefinitions()

    objReader = OBJParser(objFilePath, 'usemtl')
    meshBaseDirectory = os.path.join(os.path.dirname(objFilePath),
                                     os.path.basename(objFilePath)[:-4])

    # custom remap
    mapToSha = {}
    for key in mtlReader.reducedMaterialMap:
        mapToSha[key] = mtlReader.reducedMaterialMap[nameRemap(key)]

    meshMapping = writeMeshes(meshBaseDirectory, objReader, mapToSha)
    for name in meshMapping:
        source = simple.OpenDataFile(meshMapping[name], guiName=name)
        rep = simple.Show(source)
        mtlReader.applyMaterialToRepresentation(name, rep)

    with open('%s/representations.json' % meshBaseDirectory,
              "w",
              encoding="utf-8") as text_file:
        text_file.write(
            json.dumps(mtlReader.representationsParameters,
                       indent=2,
                       sort_keys=True))

    simple.Render()
 def endSelection(self, area, extract):
     """
     Method used to finalize an interactive selection by providing
     the [ startPointX, startPointY, endPointX, endPointY ] area
     where (0,0) match the lower left corner of the pixel screen.
     """
     if self.active_view:
         self.active_view.InteractionMode = self.previous_interaction
         representations = vtkCollection()
         sources = vtkCollection()
         if self.selection_type == 0:
             self.active_view.SelectSurfacePoints(area, representations, sources, False)
         elif self.selection_type == 1:
             self.active_view.SelectSurfaceCells(area, representations, sources, False)
         elif self.selection_type == 2:
             self.active_view.SelectFrustumPoints(area, representations, sources, False)
         elif self.selection_type == 3:
             self.active_view.SelectFrustumCells(area, representations, sources, False)
         else:
             self.active_view.SelectSurfacePoints(area, representations, sources, False)
         # Don't know what to do if more than one representation/source
         if representations.GetNumberOfItems() == sources.GetNumberOfItems() and sources.GetNumberOfItems() == 1:
             # We are good for selection
             rep = servermanager._getPyProxy(representations.GetItemAsObject(0))
             selection = servermanager._getPyProxy(sources.GetItemAsObject(0))
             if extract:
                 extract = simple.ExtractSelection(Input=rep.Input, Selection=selection)
                 simple.Show(extract)
                 simple.Render()
             else:
                 rep.Input.SMProxy.SetSelectionInput(0, selection.SMProxy, 0)
예제 #12
0
def testUserInput():
    fileName = QtGui.QFileDialog.getOpenFileName(getMainWindow(), 'Open file',)
    if fileName:
        smp.OpenDataFile(fileName, guiName=os.path.basename(fileName))
        smp.Show()
        smp.ResetCamera()
        smp.Render()
예제 #13
0
    def __init__(self,
                 location,
                 sceneConfig,
                 cameraInfo,
                 metadata={},
                 sections={}):
        DataSetBuilder.__init__(self, location, cameraInfo, metadata, sections)

        self.view = simple.CreateView('RenderView')
        self.view.ViewSize = sceneConfig['size']
        self.view.CenterAxesVisibility = 0
        self.view.OrientationAxesVisibility = 0
        self.view.UpdatePropertyInformation()

        # Initialize camera
        for key, value in sceneConfig['camera'].iteritems():
            self.view.GetProperty(key).SetData(value)

        # Create a representation for all scene sources
        self.config = sceneConfig
        self.representations = []
        for data in self.config['scene']:
            rep = simple.Show(data['source'], self.view)
            self.representations.append(rep)

        # Add directory path
        self.dataHandler.registerData(name='directory',
                                      rootFile=True,
                                      fileName='file.txt',
                                      categories=['trash'])
예제 #14
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)
예제 #15
0
    def loadData(self, datafile):
        """Load a data file. The argument is a path relative to the DataPath
        pointing to the dataset to load.

        Returns True if the dataset was loaded successfully, otherwise returns
        False.

        If the dataset is loaded, this methods setups the visualization
        pipelines for interactive probing all loaded datasets.
        """

        datafile = os.path.join(_DataProber.DataPath, datafile)
        log.msg("Loading data-file", datafile, logLevel=logging.DEBUG)
        reader = simple.OpenDataFile(datafile)
        if not reader:
            return False
        rep = simple.Show(reader, Representation="Wireframe")
        probe = simple.PlotOverLine(Source="High Resolution Line Source")

        item = {}
        item["Reader"] = reader
        item["ReaderRepresentation"] = rep
        item["Probe"] = probe
        item["name"] = os.path.split(datafile)[1]
        _DataProber.PipelineObjects.append(item)
예제 #16
0
    def __init__(self, dataCatalogEntry):

        self.debug = True
        
        self.dataFile = dataCatalogEntry["fileName"]
        self.description = dataCatalogEntry["description"]
        
        self.renderView = simple.GetActiveViewOrCreate('RenderView')

        # create a new 'EnSight Reader'
        self.caseData = simple.EnSightReader(CaseFileName=self.dataFile)

        # show data in view
        self.caseDataDisplay = simple.Show(self.caseData, self.renderView)

        # Get variables and range data from the newly-opened file.
        self.variables = {}  #***************************TBD

        # Set some defaults for the display properties.
        self.caseDataDisplay.Representation = 'Surface'

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

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

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

        self.tankGeometryShown = False
        self.tankGeometryInit = False
예제 #17
0
    def openRelativeFile(self, relativePath):
        fileToLoad = []
        if type(relativePath) == list:
            for file in relativePath:
                fileToLoad.append(os.path.join(self.baseDir, file))
        else:
            fileToLoad.append(os.path.join(self.baseDir, relativePath))

        reader = simple.OpenDataFile(fileToLoad)
        name = fileToLoad[0].split("/")[-1]
        if len(name) > 15:
            name = name[:15] + '*'
        simple.RenameSource(name, reader)
        simple.Show()
        simple.Render()
        simple.ResetCamera()

        # Add node to pipeline
        self.pipeline.addNode('0', reader.GetGlobalIDAsString())

        # Create LUT if need be
        self.lutManager.registerFieldData(reader.GetPointDataInformation())
        self.lutManager.registerFieldData(reader.GetCellDataInformation())

        return helper.getProxyAsPipelineNode(reader.GetGlobalIDAsString(),
                                             self.lutManager)
예제 #18
0
    def writeLightArray(self, path, source):
        rep = simple.Show(source, self.view)
        rep.Representation = 'Surface'
        rep.DiffuseColor = [1, 1, 1]
        simple.ColorBy(rep, ('POINTS', None))

        # Grab data
        tmpFileName = path + '__.png'
        self.view.LockBounds = 1
        simple.SaveScreenshot(tmpFileName, self.view)
        self.view.LockBounds = 0

        if self.canWrite:
            # Convert data
            self.reader.SetFileName(tmpFileName)
            self.reader.Update()

            rgbArray = self.reader.GetOutput().GetPointData().GetArray(0)
            arraySize = rgbArray.GetNumberOfTuples()

            rawArray = vtkUnsignedCharArray()
            rawArray.SetNumberOfTuples(arraySize)

            for idx in range(arraySize):
                light = rgbArray.GetTuple3(idx)[0]
                rawArray.SetTuple1(idx, light)

            with open(path, 'wb') as f:
                f.write(buffer(rawArray))

            # Delete temporary file
            if self.cleanAfterMe:
                os.remove(tmpFileName)

        simple.Hide(source, self.view)
예제 #19
0
    def initialize(self):
        # Bring used components
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebStartupRemoteConnection(
                _FileOpener.dsHost, _FileOpener.dsPort, _FileOpener.rsHost,
                _FileOpener.rsPort))
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebFileListing(_FileOpener.pathToList,
                                                "Home"))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler())

        # Update authentication key to use
        self.updateSecret(_FileOpener.authKey)

        # Create default pipeline
        if _FileOpener.fileToLoad:
            _FileOpener.reader = simple.OpenDataFile(_FileOpener.fileToLoad)
            simple.Show()

            _FileOpener.view = simple.Render()
            _FileOpener.view.ViewSize = [800, 800]
            # If this is running on a Mac DO NOT use Offscreen Rendering
            #view.UseOffscreenRendering = 1
            simple.ResetCamera()
        else:
            _FileOpener.view = simple.GetRenderView()
            simple.Render()
            _FileOpener.view.ViewSize = [800, 800]
        simple.SetActiveView(_FileOpener.view)
예제 #20
0
    def initialize(self):
        from paraview import simple
        from paraview.web import protocols as pv_protocols

        # Make sure ParaView is initialized
        if not simple.servermanager.ActiveConnection:
            simple.Connect()

        if not IPythonProtocol.producer:
            IPythonProtocol.producer = simple.DistributedTrivialProducer()
            IPythonProtocol.ActivateDataSet('iPython-demo')
            simple.Show(IPythonProtocol.producer)
            simple.Render()

        # Bring used components
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebFileListing(IPythonProtocol.dataDir, "Home", IPythonProtocol.excludeRegex, IPythonProtocol.groupRegex))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebPipelineManager(IPythonProtocol.dataDir, IPythonProtocol.fileToLoad))
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPortGeometryDelivery())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebTimeHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebRemoteConnection())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebFileManager(IPythonProtocol.dataDir))

        # Update authentication key to use
        self.updateSecret(IPythonProtocol.authKey)
예제 #21
0
    class Pipeline:

      # Create data source "input" (provides simulation fields)
      simData = coprocessor.CreateProducer( datadescription, "input" )

      # Write VTK output if requested
      if writeVtkOutput:
        fullWriter = pvs.XMLHierarchicalBoxDataWriter(Input=simData, DataMode="Appended",
                                                      CompressorType="ZLib")
        # Set freq=1 to ensure that output is written whenever the pipeline runs
        coprocessor.RegisterWriter(fullWriter, filename='bg_out_%t.vth', freq=1)

      # Create a new render view to generate images
      renderView = pvs.CreateView('RenderView')
      renderView.ViewSize = [1500, 768]
      renderView.InteractionMode = '2D'
      renderView.AxesGrid = 'GridAxes3DActor'
      renderView.CenterOfRotation = [2.8, 1.7, 0.0]
      renderView.StereoType = 0
      renderView.CameraPosition = [2.8, 1.7, 10000.0]
      renderView.CameraFocalPoint = [2.8, 1.7, 0.0]
      renderView.CameraParallelScale = 3.386
      renderView.Background = [0.32, 0.34, 0.43]
      renderView.ViewTime = datadescription.GetTime()

      # Show simulation time with 1 digit after decimal point
      annotateTime = pvs.AnnotateTime()
      annotateTime.Format = 'time: %.1f'
      timeDisplay = pvs.Show(annotateTime, renderView)

      # Register the view with coprocessor and provide it with information such as
      # the filename to use. Set freq=1 to ensure that images are rendered whenever
      # the pipeline runs
      coprocessor.RegisterView(renderView, filename='bg_out_%t.png', freq=1,
                               fittoscreen=1, magnification=1, width=1500, height=768,
                               cinema={})

      # Create colour transfer function for field
      LUT = pvs.GetColorTransferFunction(fieldName)
      LUT.RGBPoints = [9.355e-05, 0.231, 0.298, 0.753, 0.0674, 0.865, 0.865, 0.865, 0.135, 0.706, 0.0157, 0.149]
      LUT.ScalarRangeInitialized = 1.0

      # Render data field and colour by field value using lookup table
      fieldDisplay = pvs.Show(simData, renderView)
      fieldDisplay.Representation = 'Surface'
      fieldDisplay.ColorArrayName = ['CELLS', fieldName]
      fieldDisplay.LookupTable = LUT
예제 #22
0
    def addView(self, sourceProxy):
        view = simple.CreateView('RenderView')
        view.EnableRenderOnInteraction = 0
        view.Background = [0, 0, 0]

        simple.Show(sourceProxy, view)

        return view.GetGlobalIDAsString()
예제 #23
0
def animate(fn):
    casefoam = pv.OpenFOAMReader(FileName=fn)
    pv.Show(casefoam)
    dp = pv.GetDisplayProperties(casefoam)
    dp.SetPropertyWithName('ColorArrayName', ['POINTS', 'U'])
    view = pv.GetActiveView()
    reader = pv.GetActiveSource()
    tsteps = reader.TimestepValues
    annTime = pv.AnnotateTimeFilter(reader)
    pv.Show(annTime)
    pv.Render()
    while True:
        try:
            for t in tsteps:
                view.ViewTime = t
                pv.Render()
        except KeyboardInterrupt:
            sys.exit(0)
    def createDisplay(self,
                      reader,
                      renderView,
                      array_name,
                      color_transfert_fct,
                      line_width=None,
                      scale_factor=0.3,
                      glyph_type="Box",
                      opacity_fct=None):
        """Create a 'Display'
        """

        # Show data from reader
        display = pv.Show(reader, renderView)

        display.Representation = 'Surface'
        display.ColorArrayName = array_name
        display.LookupTable = color_transfert_fct
        if line_width:
            display.LineWidth = line_width
        display.OSPRayScaleArray = 'Load'
        display.OSPRayScaleFunction = 'PiecewiseFunction'
        display.SelectOrientationVectors = 'Load'
        if scale_factor:
            display.ScaleFactor = scale_factor
        display.SelectScaleArray = 'Load'
        if glyph_type:
            display.GlyphType = glyph_type
        display.GlyphTableIndexArray = 'Load'
        display.GaussianRadius = 0.015
        display.SetScaleArray = array_name
        display.ScaleTransferFunction = 'PiecewiseFunction'
        display.OpacityArray = array_name
        display.OpacityTransferFunction = 'PiecewiseFunction'
        display.DataAxesGrid = 'GridAxesRepresentation'
        display.SelectionCellLabelFontFile = ''
        display.SelectionPointLabelFontFile = ''
        display.PolarAxes = 'PolarAxesRepresentation'
        if opacity_fct:
            display.ScalarOpacityFunction = opacity_fct
            display.ScalarOpacityUnitDistance = 0.8601532551232605

        # init the 'GridAxesRepresentation' selected for 'DataAxesGrid'
        display.DataAxesGrid.XTitleFontFile = ''
        display.DataAxesGrid.YTitleFontFile = ''
        display.DataAxesGrid.ZTitleFontFile = ''
        display.DataAxesGrid.XLabelFontFile = ''
        display.DataAxesGrid.YLabelFontFile = ''
        display.DataAxesGrid.ZLabelFontFile = ''

        # init the 'PolarAxesRepresentation' selected for 'PolarAxes'
        display.PolarAxes.PolarAxisTitleFontFile = ''
        display.PolarAxes.PolarAxisLabelFontFile = ''
        display.PolarAxes.LastRadialAxisTextFontFile = ''
        display.PolarAxes.SecondaryRadialAxesTextFontFile = ''

        return display
예제 #25
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)
예제 #26
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)
예제 #27
0
파일: krak.py 프로젝트: yetisir/krak-server
    def __init__(self):
        from pyvista import examples
        topo = examples.load_random_hills()

        from paraview import simple

        tp = simple.TrivialProducer()
        tp.GetClientSideObject().SetOutput(topo)

        simple.Show(tp)
예제 #28
0
def applyMaterialToRepresentation(filepath):
    view = simple.Render()
    with open(filepath) as json_file:
        props = json.load(json_file)

        for key in props:
            for proxy in proxyMapping[str(key)]:
                simple.Show(proxy=proxy, view=view, **props[key])

    simple.Render()
    def render(self):
        self.view = paraview.CreateRenderView()
        self.source = paraview.DICOMReaderdirectory(
            FileName=self.directory_path)
        self.display = paraview.Show(self.source, self.view)

        paraview.ResetCamera()
        camera = paraview.GetActiveCamera()
        self.view.CenterOfRotation = camera.GetFocalPoint()
        self.view.CameraParallelProjection = 1
        self.view.Background = [0, 0, 0]

        self.current_slice = self.display.Slice
        self.display.Representation = self.representation
        self.display.ColorArrayName = self.array_name
        paraview.ColorBy(self.display, self.array_name)

        color_map = paraview.GetColorTransferFunction(self.array_name,
                                                      self.display)
        opacity_map = paraview.GetOpacityTransferFunction(
            self.array_name, self.display)

        scale_min = color_map.RGBPoints[0]
        scale_max = color_map.RGBPoints[-4]
        scale_middle = (scale_max - scale_min) / 2
        self.scale_range = (scale_min, scale_max)

        color_map.RGBPoints = [
            scale_min,
            0.0,
            0.0,
            0.0,
            scale_max,
            1.0,
            1.0,
            1.0,
        ]

        opacity_map.Points = [
            scale_min,
            0.0,
            0.5,
            0.0,
            scale_middle,
            0.5,
            0.5,
            0.0,
            scale_max,
            1.0,
            0.5,
            0.0,
        ]

        paraview.Render(self.view)
예제 #30
0
 def finish(self):
     super(ImageExplorer, self).finish()
     #TODO: actually record state in init and restore here, for now just
     #make an assumption
     self.view.StopCaptureValues()
     if self.UsingGL2:
         self.view.StopCaptureLuminance()
     try:
         simple.Show()
         simple.Render()
     except RuntimeError:
         pass