Пример #1
0
    def getLookupTableForArrayName(self, name, numSamples=255):
        lutProxy = simple.GetColorTransferFunction(name)
        lut = lutProxy.GetClientSideObject()
        dataRange = lut.GetRange()
        delta = (dataRange[1] - dataRange[0]) / float(numSamples)

        colorArray = vtkUnsignedCharArray()
        colorArray.SetNumberOfComponents(3)
        colorArray.SetNumberOfTuples(numSamples)

        rgb = [0, 0, 0]
        for i in range(numSamples):
            lut.GetColor(dataRange[0] + float(i) * delta, rgb)
            r = int(round(rgb[0] * 255))
            g = int(round(rgb[1] * 255))
            b = int(round(rgb[2] * 255))
            colorArray.SetTuple3(i, r, g, b)

        # Add the color array to an image data
        imgData = vtkImageData()
        imgData.SetDimensions(numSamples, 1, 1)
        aIdx = imgData.GetPointData().SetScalars(colorArray)

        # Use the vtk data encoder to base-64 encode the image as png, using no compression
        encoder = vtkDataEncoder()
        # two calls in a row crash on Windows - bald timing hack to avoid the crash.
        time.sleep(0.01)
        b64Str = encoder.EncodeAsBase64Jpg(imgData, 100)

        return {
            "image": "data:image/jpg;base64," + b64Str,
            "range": dataRange,
            "name": name,
        }
Пример #2
0
 def _apply_color_map(self, color_map):
     assert self._display is not None
     assert self._data is not None
     name = self._data.PointData.GetArray(0).Name  # type: ignore
     self._display.ColorArrayName = ["POINTS", name]
     color_lut = ps.GetColorTransferFunction(name)
     color_lut.ApplyPreset(color_map, True)
Пример #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 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)
Пример #6
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
Пример #7
0
 def __init__(self):
   self.center_of_rotation = [34.5, 32.45, 27.95]
   self.rotation_axis = [0.0, 0.0, 1.0]
   self.distance = 500.0
   self.exporters = []
   self.analysis = cinema.AnalysisManager( 'cinema', "Cinema", "Test various cinema exporter.")
   self.analysis.begin()
   min = 0.0
   max = 642.0
   self.lut = simple.GetColorTransferFunction(
     "velocity",
     RGBPoints=[min, 0.23, 0.299, 0.754, (min+max)*0.5, 0.865, 0.865, 0.865, max, 0.706, 0.016, 0.15])
   # ==
   self.createSliceExporter()
   self.createComposite()
   self.createImageResampler()
   self.simple360()
Пример #8
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
    def createColorTransferFunction(self,
                                    var,
                                    colors=None,
                                    nan_color=[1.,1.,1.],
                                    nan_opacity=None,
                                    auto_rescale_range_mode="Never"):
        """Create a color transfer function/color map
        """

        # get color transfer function/color map
        fct = pv.GetColorTransferFunction(var)
        if auto_rescale_range_mode:
            fct.AutomaticRescaleRangeMode = auto_rescale_range_mode
        if colors:
            fct.RGBPoints = colors
        if nan_color:
            fct.NanColor = nan_color
        if nan_opacity is not None:
            fct.NanOpacity = nan_opacity
        fct.ScalarRangeInitialized = 1.0

        return fct
Пример #10
0
    def makeContour(self):

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

        # create a new 'Contour'
        contour = simple.Contour(Input=self.dataObject.getData())

        #print "DoubleContourValue", self.plotRecipe.get('DoubleContourValue')
        #print "EnumContourVariable", self.plotRecipe.get('EnumContourVariable')
        # Properties modified on contour
        #contour.ContourBy = ['POINTS', self.plotRecipe.get('enum.contour.variable')]
        contour.ContourBy = ['POINTS', 'uds_0_scalar']
        contour.Isosurfaces = self.plotRecipe.get('DoubleContourValue')


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

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

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

        # 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
        contourDisplay.RescaleTransferFunctionToDataRange(True, False)

        # reset view to fit data
        self.dataObject.renderView.ResetCamera()

        self.dataObject.renderView.Update()
Пример #11
0
    def colorBy(self, representation, field):
        view = self.viewSubSurface if representation == self.subSurfaceRepresentation else self.viewSurface
        representation.SetScalarBarVisibility(view, False)

        simple.ColorBy(representation, ['CELLS', field])
        applyColorMap(representation)

        representation.SetScalarBarVisibility(view, True)

        lut = simple.GetColorTransferFunction(field)
        colorBar = simple.GetScalarBar(lut, view)

        colorBar.Enabled = 1
        colorBar.Selectable = 0
        colorBar.AutoOrient = 0
        colorBar.AutomaticLabelFormat = 1
        colorBar.AddRangeLabels = 0
        colorBar.ScalarBarLength = 0.9
        colorBar.LabelColor = [0, 0, 0]
        colorBar.Position = [0.8, 0.05]
        colorBar.LockPosition = 1
        colorBar.Repositionable = 1
        colorBar.Resizable = 1
        colorBar.TitleColor = [0, 0, 0]
        class Pipeline:

            grid = coprocessor.CreateProducer(datadescription, 'input')

            # Simulation domain outline
            outline = pvs.Outline(Input=grid)

            # Horizontal slice at the bottom
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Plane'
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = [0.0, 0.0, 101.94]
            slice.SliceType.Normal = [0.0, 0.0, 1.0]
            slice.Triangulatetheslice = False

            # Glyphs for representing velocity field
            glyph = pvs.Glyph(Input=grid, GlyphType='Arrow')
            glyph.Vectors = ['CELLS', 'u']
            glyph.ScaleMode = 'vector'
            glyph.ScaleFactor = 0.01
            glyph.GlyphMode = 'Every Nth Point'
            glyph.Stride = 200

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [800, 400]
            renderView.InteractionMode = '2D'
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.CenterOfRotation = [0.18, 0.0, 102]
            renderView.StereoType = 0
            renderView.CameraPosition = [-3.4, -6.8, 107]
            renderView.CameraFocalPoint = [-0.27, -0.41, 102]
            renderView.CameraViewUp = [0.057, 0.49, 0.87]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]

            # Register the view with coprocessor
            coprocessor.RegisterView(renderView,
                                     filename='image_%t.png',
                                     freq=1,
                                     fittoscreen=0,
                                     magnification=1,
                                     width=800,
                                     height=400,
                                     cinema={})
            renderView.ViewTime = datadescription.GetTime()

            # Get color transfer function/color map for field rho
            rhoLUT = pvs.GetColorTransferFunction('rho')
            rhoLUT.RGBPoints = [
                1.17, 0.231, 0.298, 0.752, 1.33, 0.865, 0.865, 0.865, 1.49,
                0.706, 0.0157, 0.149
            ]
            rhoLUT.ScalarRangeInitialized = 1.0

            # Show slice
            sliceDisplay = pvs.Show(slice, renderView)
            sliceDisplay.Representation = 'Surface With Edges'
            sliceDisplay.ColorArrayName = ['CELLS', 'rho']
            sliceDisplay.LookupTable = rhoLUT
            sliceDisplay.ScaleFactor = 0.628
            sliceDisplay.SelectScaleArray = 'None'
            sliceDisplay.GlyphType = 'Arrow'
            sliceDisplay.GlyphTableIndexArray = 'None'
            sliceDisplay.DataAxesGrid = 'GridAxesRepresentation'
            sliceDisplay.PolarAxes = 'PolarAxesRepresentation'
            sliceDisplay.GaussianRadius = 0.314
            sliceDisplay.SetScaleArray = [None, '']
            sliceDisplay.ScaleTransferFunction = 'PiecewiseFunction'
            sliceDisplay.OpacityArray = [None, '']
            sliceDisplay.OpacityTransferFunction = 'PiecewiseFunction'

            # Show color legend
            sliceDisplay.SetScalarBarVisibility(renderView, True)

            # Show glyph
            glyphDisplay = pvs.Show(glyph, renderView)

            # Show outline
            outlineDisplay = pvs.Show(outline, renderView)

            # Get color legend/bar for rhoLUT in view renderView
            rhoLUTColorBar = pvs.GetScalarBar(rhoLUT, renderView)
            rhoLUTColorBar.WindowLocation = 'LowerRightCorner'
            rhoLUTColorBar.Title = 'rho'
            rhoLUTColorBar.ComponentTitle = ''
Пример #13
0
 def applyPreset(self, arrayName, presetName):
     lutProxy = simple.GetColorTransferFunction(arrayName)
     lutProxy.ApplyPreset(presetName, True)
     self.getApplication().InvokeEvent("UpdateEvent")
Пример #14
0
 def updateLookupTableRange(self, arrayName, dataRange):
     lutProxy = simple.GetColorTransferFunction(arrayName)
     vtkSMTransferFunctionProxy.RescaleTransferFunction(
         lutProxy.SMProxy, dataRange[0], dataRange[1], False)
     self.getApplication().InvokeEvent("UpdateEvent")
Пример #15
0
def main():
    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        '-d',
        '--data',
        required=True,
        help='Specify the directory containing the time series data')
    argparser.add_argument('-s',
                           '--stats',
                           help='The file name containing global statistics')
    argparser.add_argument(
        '-o',
        '--output',
        help=
        'The name for the state file to be loaded by paraview, without an extension'
    )
    options = argparser.parse_args()

    xdim, ydim = get_dims(options.data)

    virions_view = create_render_view('virions', xdim, ydim)
    virions_chart_view = create_chart_view('Average virions')
    epicells_view = create_render_view('epicells', xdim, ydim)
    epicells_chart_view = create_chart_view('epicells',
                                            log_scale=True,
                                            left_max_range=xdim * ydim)
    tcells_view = create_render_view('chemokines and tcells', xdim, ydim)
    tcells_chart_view = create_chart_view('tcells',
                                          log_scale=True,
                                          left_max_range=xdim * ydim)

    pvs.AddCameraLink(virions_view, epicells_view, 'link1')
    pvs.AddCameraLink(epicells_view, tcells_view, 'link2')

    virions_color_func = pvs.GetColorTransferFunction('virus')
    virions_color_func.RGBPoints = [
        0.0255, 0.231, 0.298, 0.753, 2.55, 0.865, 0.865, 0.865, 255.0, 0.706,
        0.0157, 0.149
    ]
    virions_color_func.UseLogScale = 0
    display_data('sample_virus_', options.data, virions_view, 'virus',
                 virions_color_func)
    display_chart(options.stats, virions_chart_view, ['virs'],
                  ['virs', 'virions'], 'virions', ['virs', '1', '0', '0'])

    epicell_cols = [
        'incb', '1.0', '0.333', '1.0', 'expr', '0.667', '0.0', '0.0', 'apop',
        '1.0', '1.0', '0', 'dead', '0.333', '0.333', '0.0'
    ]
    epicell_cols_vals = [0.8, 0.8, 0.8]
    for i in range(len(epicell_cols)):
        if i % 4 == 0: continue
        epicell_cols_vals.append(float(epicell_cols[i]))

    epicells_color_func = pvs.GetColorTransferFunction('epicell')
    epicells_color_func.InterpretValuesAsCategories = 1
    epicells_color_func.Annotations = [
        '1', 'healthy', '2', 'incubating', '3', 'expressing', '4', 'apoptotic',
        '5', 'dead'
    ]
    epicells_color_func.IndexedColors = epicell_cols_vals

    display_data('sample_epicell_', options.data, epicells_view, 'epicell',
                 epicells_color_func)
    display_chart(options.stats, epicells_chart_view,
                  ['incb', 'expr', 'apop', 'dead'], [
                      'incb', 'incubating', 'expr', 'expressing', 'apop',
                      'apoptotic', 'dead', 'dead'
                  ], 'epicells', epicell_cols)

    chemokine_color_func = pvs.GetColorTransferFunction('chemokine')
    chemokine_color_func.RGBPoints = [
        0.0249, 0.0, 0.0, 0.0, 249.0, 1.0, 1.0, 1.0
    ]
    chemokine_color_func.UseLogScale = 0
    chemokine_color_func.NanOpacity = 0.0
    display_data('sample_chemokine_', options.data, tcells_view, 'chemokine',
                 chemokine_color_func)

    tcells_color_func = pvs.GetColorTransferFunction('t-cell-tissue')
    tcells_color_func.InterpretValuesAsCategories = 1
    tcells_color_func.NanOpacity = 0.0
    tcells_color_func.Annotations = [
        '1', '>0', '2', '>0.12', '3', '>0.25', '4', '>0.5'
    ]
    tcells_color_func.IndexedColors = [
        0.0, 0.3, 0.0, 0.0, 0.5, 0.0, 0.0, 0.7, 0.0, 0.0, 1.0, 0.0
    ]
    display_data('sample_tcelltissue_', options.data, tcells_view,
                 't-cell-tissue',
                 tcells_color_func)  #, representation='Points')
    display_chart(options.stats, tcells_chart_view, ['ttis', 'tvas'],
                  ['ttis', 'tissue', 'tvas', 'vasculature'], 'tcells',
                  ['ttis', '0', '1', '0', 'tvas', '0', '0', '1'])

    layout = pvs.CreateLayout(name='Main Layout')
    layout.SplitHorizontal(0, 0.333)
    layout.SplitVertical(1, 0.7)
    layout.SplitHorizontal(2, 0.5)
    layout.SplitVertical(5, 0.7)
    layout.SplitVertical(6, 0.7)
    layout.AssignView(3, virions_view)
    layout.AssignView(4, virions_chart_view)
    layout.AssignView(11, epicells_view)
    layout.AssignView(12, epicells_chart_view)
    layout.AssignView(13, tcells_view)
    layout.AssignView(14, tcells_chart_view)

    # for view in [virions_view, epicells_view, tcells_view]:
    #      print(view.GetActiveCamera().GetViewUp())
    #      print(view.GetActiveCamera().GetPosition())
    #      print(view.GetActiveCamera().GetFocalPoint())
    # for view in [virions_view, epicells_view, tcells_view]:
    #     camera = view.GetActiveCamera()
    #     focal_point = camera.GetFocalPoint()
    #     pos = camera.GetPosition()
    #     dist = math.sqrt((pos[0] - focal_point[0]) ** 2 + (pos[1] - focal_point[1]) ** 2 + (pos[2] - focal_point[2]) ** 2)
    #     camera.SetPosition(focal_point[0], focal_point[1], focal_point[2] + dist)
    #     camera.SetViewUp(0.0, 1.0, 0.0)

    if not options.output:
        state_fname = options.data + '-state.pvsm'
    else:
        state_fname = options.output + '.pvsm'

    pvs.servermanager.SaveState(state_fname)
    print('Created a state file', state_fname, 'for paraview')
    print('Run with\n', 'paraview', state_fname)
Пример #16
0
        class Pipeline:

            # Read topographic data
            topo = pvs.XMLPolyDataReader(FileName="ETOPO_10min_Ice.vtp")

            # Scale data to just under radius of the sphere
            toposcaled = pvs.Calculator(Input=topo)
            toposcaled.CoordinateResults = 1
            toposcaled.Function = '%i*coords' % (sphere_radius * 0.99)

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            ghosts = pvs.GhostCellsGenerator(Input=grid)
            ghosts.BuildIfRequired = 0
            ghosts.MinimumNumberOfGhostLevels = 1

            # Create a spherical slice
            slice = pvs.Slice(Input=ghosts)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Convert cell data to point data, which is required for good contour results
            #
            # CAUTION: THIS FILTER AVERAGES DATA FROM ALL CELLS SURROUNDING A POINT,
            #          WHICH REDUCES ACCURACY
            cell2point = pvs.CellDatatoPointData(Input=slice)
            cell2point.PassCellData = 0
            cell2point.PieceInvariant = 0

            # Create contours
            # Note that the "tube" filter can be used to highlight contours if needed.
            contours = pvs.Contour(Input=cell2point)
            contours.Isosurfaces = contour_values
            contours.ContourBy = ['POINTS', 'rho']
            contours.PointMergeMethod = 'Uniform Binning'

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0.0, 1.0, 0.3]
            renderView.CameraViewUp = [0.0, 0.0, 1.0]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='topo_contours_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=800,
                                     height=800,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('altitude')
            # Use Wikipedia LUT as provided on http://www.earthmodels.org/data-and-tools/color-tables
            LUT.RGBPoints = [
                -11000, 0.141176470588235, 0.149019607843137,
                0.686274509803922, -5499.999, 0.219607843137255,
                0.227450980392157, 0.764705882352941, -5500, 0.219607843137255,
                0.227450980392157, 0.764705882352941, -2999.999,
                0.274509803921569, 0.282352941176471, 0.83921568627451, -3000,
                0.274509803921569, 0.282352941176471, 0.83921568627451,
                -1999.999, 0.317647058823529, 0.4, 0.850980392156863, -2000,
                0.317647058823529, 0.4, 0.850980392156863, -749.999,
                0.392156862745098, 0.505882352941176, 0.874509803921569, -750,
                0.392156862745098, 0.505882352941176, 0.874509803921569,
                -69.999, 0.513725490196078, 0.631372549019608,
                0.901960784313726, -70, 0.513725490196078, 0.631372549019608,
                0.901960784313726, -19.999, 0.643137254901961,
                0.752941176470588, 0.941176470588235, -20, 0.643137254901961,
                0.752941176470588, 0.941176470588235, 0.001, 0.666666666666667,
                0.784313725490196, 1, 0, 0, 0.380392156862745,
                0.27843137254902, 50.001, 0.0627450980392157, 0.47843137254902,
                0.184313725490196, 50, 0.0627450980392157, 0.47843137254902,
                0.184313725490196, 500.001, 0.909803921568627,
                0.843137254901961, 0.490196078431373, 500, 0.909803921568627,
                0.843137254901961, 0.490196078431373, 1200.001,
                0.631372549019608, 0.262745098039216, 0, 1200,
                0.631372549019608, 0.262745098039216, 0, 1700.001,
                0.509803921568627, 0.117647058823529, 0.117647058823529, 1700,
                0.509803921568627, 0.117647058823529, 0.117647058823529,
                2800.001, 0.431372549019608, 0.431372549019608,
                0.431372549019608, 2800, 0.431372549019608, 0.431372549019608,
                0.431372549019608, 4000.001, 1, 1, 1, 4000, 1, 1, 1, 6000.001,
                1, 1, 1
            ]

            LUT.ScalarRangeInitialized = 1.0

            # Show topo data
            sphereDisplay = pvs.Show(toposcaled, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['POINTS', 'altitude']
            sphereDisplay.LookupTable = LUT
            sphereDisplay.Opacity = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(contours, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.Opacity = 1.0
Пример #17
0
materialLibrary1 = pv.GetMaterialLibrary()

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

# set scalar coloring
pv.ColorBy(ablnek5000Display, ('POINTS', 'x_velocity'))

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

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

# get color transfer function/color map for 'x_velocity'
x_velocityLUT = pv.GetColorTransferFunction('x_velocity')

# get opacity transfer function/opacity map for 'x_velocity'
x_velocityPWF = pv.GetOpacityTransferFunction('x_velocity')

# set scalar coloring
pv.ColorBy(ablnek5000Display, ('POINTS', 'y_velocity'))

# Hide the scalar bar for this color map if no visible data is colored by it.
pv.HideScalarBarIfNotNeeded(x_velocityLUT, renderView1)

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

# show color bar/color legend
ablnek5000Display.SetScalarBarVisibility(renderView1, True)
Пример #18
0
    def initialize(self):

        # Bring used components
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebMouseHandler())
        self.registerVtkWebProtocol(pv_protocols.ParaViewWebViewPort())
        self.registerVtkWebProtocol(
            pv_protocols.ParaViewWebViewPortImageDelivery())
        self.registerVtkWebProtocol(amsProtocol())
        self.updateSecret(_DemoServer.authKey)

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

        # create a new 'EnSight Reader'

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

        # create a new 'EnSight Reader'
        matvizmofTFF90L91lpm100rpmcase = simple.EnSightReader(
            CaseFileName=
            '/Users/tomfool/tech/18/amgen/ams-102-AgileViz/EnSight/mat-viz-mofTFF-90L-9.1lpm-100rpm/mat-viz-mofTFF-90L-9.1lpm-100rpm.case'
        )
        matvizmofTFF90L91lpm100rpmcase.PointArrays = [
            'pressure', 'pressure_coefficient', 'dynamic_pressure',
            'absolute_pressure', 'total_pressure', 'rel_total_pressure',
            'density', 'density_all', 'velocity_magnitude', 'x_velocity',
            'y_velocity', 'z_velocity', 'axial_velocity', 'radial_velocity',
            'tangential_velocity', 'rel_velocity_magnitude',
            'relative_x_velocity', 'relative_y_velocity',
            'relative_z_velocity', 'rel_tangential_velocity',
            'mesh_x_velocity', 'mesh_y_velocity', 'mesh_z_velocity',
            'velocity_angle', 'relative_velocity_angle', 'vorticity_mag',
            'helicity', 'x_vorticity', 'y_vorticity', 'z_vorticity',
            'cell_reynolds_number', 'turb_kinetic_energy', 'turb_intensity',
            'turb_diss_rate', 'production_of_k', 'viscosity_turb',
            'viscosity_eff', 'viscosity_ratio', 'y_star', 'y_plus',
            'uds_0_scalar', 'uds_0_diff_scalar', 'viscosity_lam', 'wall_shear',
            'x_wall_shear', 'y_wall_shear', 'z_wall_shear',
            'skin_friction_coef', 'cell_partition_active',
            'cell_partition_stored', 'cell_id', 'cell_element_type',
            'cell_type', 'cell_zone', 'partition_neighbors', 'cell_weight',
            'x_coordinate', 'y_coordinate', 'z_coordinate', 'axial_coordinate',
            'angular_coordinate', 'abs_angular_coordinate',
            'radial_coordinate', 'face_area_magnitude', 'x_face_area',
            'y_face_area', 'z_face_area', 'cell_volume', 'orthogonal_quality',
            'cell_equiangle_skew', 'cell_equivolume_skew', 'face_handedness',
            'mark_poor_elememts', 'interface_overlap_fraction',
            'cell_wall_distance', 'adaption_function', 'adaption_curvature',
            'adaption_space_gradient', 'adaption_iso_value',
            'boundary_cell_dist', 'boundary_normal_dist', 'cell_volume_change',
            'cell_surface_area', 'cell_warp', 'cell_children',
            'cell_refine_level', 'mass_imbalance', 'strain_rate_mag',
            'dx_velocity_dx', 'dy_velocity_dx', 'dz_velocity_dx',
            'dx_velocity_dy', 'dy_velocity_dy', 'dz_velocity_dy',
            'dx_velocity_dz', 'dy_velocity_dz', 'dz_velocity_dz', 'dp_dx',
            'dp_dy', 'dp_dz', 'velocity'
        ]

        # get active view
        renderView1 = simple.GetActiveViewOrCreate('RenderView')
        # uncomment following to set a specific view size
        # renderView1.ViewSize = [1638, 1076]

        # show data in view
        matvizmofTFF90L91lpm100rpmcaseDisplay = simple.Show(
            matvizmofTFF90L91lpm100rpmcase, renderView1)

        # get color transfer function/color map for 'pressure'
        pressureLUT = simple.GetColorTransferFunction('pressure')

        # get opacity transfer function/opacity map for 'pressure'
        pressurePWF = simple.GetOpacityTransferFunction('pressure')

        # trace defaults for the display properties.
        matvizmofTFF90L91lpm100rpmcaseDisplay.Representation = 'Surface'
        matvizmofTFF90L91lpm100rpmcaseDisplay.ColorArrayName = [
            'POINTS', 'pressure'
        ]
        matvizmofTFF90L91lpm100rpmcaseDisplay.LookupTable = pressureLUT
        matvizmofTFF90L91lpm100rpmcaseDisplay.OSPRayScaleArray = 'pressure'
        matvizmofTFF90L91lpm100rpmcaseDisplay.OSPRayScaleFunction = 'PiecewiseFunction'
        matvizmofTFF90L91lpm100rpmcaseDisplay.SelectOrientationVectors = 'velocity'
        matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleFactor = 0.07445502169430256
        matvizmofTFF90L91lpm100rpmcaseDisplay.SelectScaleArray = 'pressure'
        matvizmofTFF90L91lpm100rpmcaseDisplay.GlyphType = 'Arrow'
        matvizmofTFF90L91lpm100rpmcaseDisplay.GlyphTableIndexArray = 'pressure'
        matvizmofTFF90L91lpm100rpmcaseDisplay.GaussianRadius = 0.03722751084715128
        matvizmofTFF90L91lpm100rpmcaseDisplay.SetScaleArray = [
            'POINTS', 'pressure'
        ]
        matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleTransferFunction = 'PiecewiseFunction'
        matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityArray = [
            'POINTS', 'pressure'
        ]
        matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityTransferFunction = 'PiecewiseFunction'
        matvizmofTFF90L91lpm100rpmcaseDisplay.DataAxesGrid = 'GridAxesRepresentation'
        matvizmofTFF90L91lpm100rpmcaseDisplay.SelectionCellLabelFontFile = ''
        matvizmofTFF90L91lpm100rpmcaseDisplay.SelectionPointLabelFontFile = ''
        matvizmofTFF90L91lpm100rpmcaseDisplay.PolarAxes = 'PolarAxesRepresentation'
        matvizmofTFF90L91lpm100rpmcaseDisplay.ScalarOpacityFunction = pressurePWF
        matvizmofTFF90L91lpm100rpmcaseDisplay.ScalarOpacityUnitDistance = 0.007476863260594431

        # init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'
        matvizmofTFF90L91lpm100rpmcaseDisplay.ScaleTransferFunction.Points = [
            -152.6022491455078, 0.0, 0.5, 0.0, 144.73870849609375, 1.0, 0.5,
            0.0
        ]

        # init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'
        matvizmofTFF90L91lpm100rpmcaseDisplay.OpacityTransferFunction.Points = [
            -152.6022491455078, 0.0, 0.5, 0.0, 144.73870849609375, 1.0, 0.5,
            0.0
        ]

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

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

        # reset view to fit data
        renderView1.ResetCamera()

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

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

        # hide data in view
        simple.Hide(matvizmofTFF90L91lpm100rpmcase, renderView1)

        # create a new 'Contour'
        contour1 = simple.Contour(Input=matvizmofTFF90L91lpm100rpmcase)
        contour1.ContourBy = ['POINTS', 'pressure']
        contour1.Isosurfaces = [-3.9317703247070312]
        contour1.PointMergeMethod = 'Uniform Binning'

        # Properties modified on contour1
        contour1.ContourBy = ['POINTS', 'uds_0_scalar']
        contour1.Isosurfaces = [480.0, 570.0]

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

        # trace defaults for the display properties.
        contour1Display.Representation = 'Surface'
        contour1Display.ColorArrayName = ['POINTS', 'pressure']
        contour1Display.LookupTable = pressureLUT
        contour1Display.OSPRayScaleArray = 'Normals'
        contour1Display.OSPRayScaleFunction = 'PiecewiseFunction'
        contour1Display.SelectOrientationVectors = 'velocity'
        contour1Display.ScaleFactor = 0.07228952534496784
        contour1Display.SelectScaleArray = 'None'
        contour1Display.GlyphType = 'Arrow'
        contour1Display.GlyphTableIndexArray = 'None'
        contour1Display.GaussianRadius = 0.03614476267248392
        contour1Display.SetScaleArray = ['POINTS', 'Normals']
        contour1Display.ScaleTransferFunction = 'PiecewiseFunction'
        contour1Display.OpacityArray = ['POINTS', 'Normals']
        contour1Display.OpacityTransferFunction = 'PiecewiseFunction'
        contour1Display.DataAxesGrid = 'GridAxesRepresentation'
        contour1Display.SelectionCellLabelFontFile = ''
        contour1Display.SelectionPointLabelFontFile = ''
        contour1Display.PolarAxes = 'PolarAxesRepresentation'

        # init the 'PiecewiseFunction' selected for 'ScaleTransferFunction'
        contour1Display.ScaleTransferFunction.Points = [
            -0.9995924830436707, 0.0, 0.5, 0.0, 0.9998393058776855, 1.0, 0.5,
            0.0
        ]

        # init the 'PiecewiseFunction' selected for 'OpacityTransferFunction'
        contour1Display.OpacityTransferFunction.Points = [
            -0.9995924830436707, 0.0, 0.5, 0.0, 0.9998393058776855, 1.0, 0.5,
            0.0
        ]

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

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

        # reset view to fit data
        renderView1.ResetCamera()

        # hide data in view
        simple.Hide(matvizmofTFF90L91lpm100rpmcase, renderView1)

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

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

        # set scalar coloring
        simple.ColorBy(contour1Display, ('POINTS', 'velocity_magnitude'))

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

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

        # get color transfer function/color map for 'velocity_magnitude'
        velocity_magnitudeLUT = simple.GetColorTransferFunction(
            'velocity_magnitude')

        #### saving camera placements for all active views

        # current camera placement for renderView1
        renderView1.CameraPosition = [
            1.3051878628081257, -1.32358496378265, -0.017141331493847792
        ]
        renderView1.CameraFocalPoint = [
            -0.052487090229988105, 0.03264869749546056, -0.3026974257081747
        ]
        renderView1.CameraViewUp = [
            -0.5051031518286454, -0.33848038039346323, 0.7939155106820026
        ]
        renderView1.CameraParallelScale = 0.5021485229089222

        #### uncomment the following to render all views
        # RenderAllViews()
        # alternatively, if you want to write images, you can use SaveScreenshot(...).

        ### OLD FOLLOWS

        simple.Render()

        # Update interaction mode
        pxm = simple.servermanager.ProxyManager()
        interactionProxy = pxm.GetProxy('settings',
                                        'RenderViewInteractionSettings')
        print(dir(interactionProxy))

        interactionProxy.Camera3DManipulators = [
            'Rotate', 'Pan', 'Zoom', 'Pan', 'Roll', 'Pan', 'Zoom', 'Rotate',
            'Zoom'
        ]

        print("done with initialize()")
Пример #19
0
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Horizontal slice at the bottom
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Plane'
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = [0.0, 0.0, 101.94]
            slice.SliceType.Normal = [0.0, 0.0, 1.0]
            slice.Triangulatetheslice = False

            # Set up spherical projection filter - we need to bridge into the
            # VTK universe and use a VTK transform filter; the ParaView transform filter
            # does not support geo transforms

            # Source projection - simulation data is provided in lon lat rad coordinates
            latlonproj = vtk.vtkGeoProjection()
            latlonproj.SetName('lonlat')
            latlonproj.SetCentralMeridian(0)

            # Target projection - use Mollweide here
            targetproj = vtk.vtkGeoProjection()
            targetproj.SetName('moll')
            targetproj.SetCentralMeridian(0)

            # Set up vtkGeoTransform object that defines the transformation
            transform = vtk.vtkGeoTransform()
            transform.SetSourceProjection(latlonproj)
            transform.SetDestinationProjection(targetproj)

            # Set up VTK transform filter object
            tffilter = vtk.vtkTransformFilter()
            tffilter.SetTransform(transform)
            tffilter.SetInputConnection(
                slice.GetClientSideObject().GetOutputPort(0))

            # Return to ParaView universe by using a simple PassThrough filter to receive
            # output of the VTK transform filter
            passthrough = pvs.PassThrough()
            passthrough.GetClientSideObject().SetInputConnection(
                tffilter.GetOutputPort())

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0, 0, 4]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='spherical_slice_%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 = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(passthrough, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', fieldname]
            sphereDisplay.LookupTable = LUT
Пример #20
0
data.UseCartesiancoordinates = 1

# Add a clip filter to the pipeline and set plane orientation
clip = pvs.Clip(Input=data)
clip.ClipType = 'Plane'
clip.ClipType.Normal = [0.0, 0.0, 1.0]

# Set up a new render view for displaying the grid and data
renderView = pvs.CreateView('RenderView')
renderView.ViewSize = [1600, 800]
renderView.CameraPosition = [-43.0, 39.0, 32.0]
renderView.CameraViewUp = [0.76, 0.44, 0.49]

# Define a colour look-up table using (data value, r, g, b) tuples
# Use value range from first timestep
lut = pvs.GetColorTransferFunction('pressure')
valueRange = data.CellData['pressure'].GetRange()
lut.RGBPoints = [
    valueRange[0], 0.23, 0.30, 0.75, valueRange[1], 0.71, 0.02, 0.15
]

# Show clip filter in the render view, render grid surfaces,
# and colour surfaces using the pressure field and our LUT
clipDisplay = pvs.Show(clip, renderView)
clipDisplay.Representation = 'Surface With Edges'
clipDisplay.ColorArrayName = ['CELLS', 'pressure']
clipDisplay.LookupTable = lut

# Loop over time steps and render an image for each one
timeSteps = data.TimestepValues
for istep in range(0, len(timeSteps)):
Пример #21
0
renderView1.OrientationAxesLabelColor = [0.313, 0.313, 0.313]
renderView1.StereoType = 0
renderView1.LightSwitch = 1
renderView1.LightIntensity = 0.2
renderView1.CameraParallelScale = 6520917.036707207
renderView1.Background = [1.0, 1.0, 1.0]

kerner_kernelxdmf = simple.XDMFReader(FileNames=['kerner_kernel.xdmf'])

kerner_kernelxdmf.GridStatus = ['grid']

kerner_all = simple.servermanager.Fetch(kerner_kernelxdmf)

# Apparently, it is possible to use any name here. We just need a
# transfer function which we can modify later
LUT = simple.GetColorTransferFunction('HalliGalli')
LUT.RGBPoints = [
    -1e-10, 0.231373, 0.298039, 0.752941, 0, 1.0, 1.0, 1.0, 1e-10, 0.705882,
    0.0156863, 0.14902
]
LUT.NanColor = [0.500008, 0.0, 0.0]
LUT.ScalarRangeInitialized = 1.0

# get any opacity transfer function/opacity map
# Not used so far
PWF = simple.GetOpacityTransferFunction('HalliGalli')
PWF.Points = [-1e-10, 0.0, 0.5, 0.0, 1e-10, 1.0, 0.5, 0.0]
PWF.ScalarRangeInitialized = 1

# setup the color legend parameters for each legend in this view
Пример #22
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)

            # Combine uu and vv components into velocity vector field
            calculatorVelField = pvs.Calculator(Input=simData)
            calculatorVelField.AttributeType = 'Cell Data'
            calculatorVelField.ResultArrayName = 'velocity'
            calculatorVelField.Function = 'uu*iHat+vv*jHat'

            # Compute velocity field magnitudes
            calculatorVelMag = pvs.Calculator(Input=calculatorVelField)
            calculatorVelMag.AttributeType = 'Cell Data'
            calculatorVelMag.ResultArrayName = 'mag'
            calculatorVelMag.Function = 'mag(velocity)'

            # Remove cells with vanishing velocity magnitude
            velMagThreshold = pvs.Threshold(calculatorVelMag)
            velMagThreshold.Scalars = ['CELLS', 'mag']
            velMagThreshold.ThresholdRange = [1.0e-6, 1.0e30]

            # Visualise remaining velocity vector field using arrows with fixed length
            # and skipping cells to avoid crowding
            glyphs = pvs.Glyph(Input=velMagThreshold, GlyphType='Arrow')
            glyphs.Vectors = ['CELLS', 'velocity']
            glyphs.ScaleFactor = 0.2
            glyphs.GlyphMode = 'Every Nth Point'
            glyphs.Stride = 100
            glyphs.GlyphTransform = 'Transform2'

            # 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=0,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('hh')
            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', 'hh']
            fieldDisplay.LookupTable = LUT

            # Add velocity field visualisation
            velfieldDisplay = pvs.Show(glyphs, renderView)
Пример #23
0
def render_frames(
    scene,
    frames_dir=None,
    frame_window=None,
    render_missing_frames=False,
    save_state_to_file=None,
    no_render=False,
    show_preview=False,
    show_progress=False,
    job_id=None,
):
    # Validate scene
    if scene["View"]["ViewSize"][0] % 16 != 0:
        logger.warning(
            "The view width should be a multiple of 16 to be compatible with"
            " QuickTime.")
    if scene["View"]["ViewSize"][1] % 2 != 0:
        logger.warning(
            "The view height should be even to be compatible with QuickTime.")

    render_start_time = time.time()

    # Setup layout
    layout = pv.CreateLayout("Layout")

    # Setup view
    if "Background" in scene["View"]:
        bg_config = scene["View"]["Background"]
        del scene["View"]["Background"]
        if isinstance(bg_config, list):
            if isinstance(bg_config[0], list):
                assert len(bg_config) == 2, (
                    "When 'Background' is a list of colors, it must have 2"
                    " entries.")
                bg_config = dict(
                    BackgroundColorMode="Gradient",
                    Background=parse_as.color(bg_config[0]),
                    Background2=parse_as.color(bg_config[1]),
                )
            else:
                bg_config = dict(
                    BackgroundColorMode="Single Color",
                    Background=parse_as.color(bg_config),
                )
            bg_config["UseColorPaletteForBackground"] = 0
            scene["View"].update(bg_config)
            bg_config = None
    else:
        bg_config = None
    view = pv.CreateRenderView(**scene["View"])
    pv.AssignViewToLayout(view=view, layout=layout, hint=0)

    # Set spherical background texture
    if bg_config is not None:
        bg_config["BackgroundColorMode"] = "Texture"
        skybox_datasource = bg_config["Datasource"]
        del bg_config["Datasource"]
        background_texture = pvserver.rendering.ImageTexture(
            FileName=parse_as.path(scene["Datasources"][skybox_datasource]))
        background_sphere = pv.Sphere(Radius=bg_config["Radius"],
                                      ThetaResolution=100,
                                      PhiResolution=100)
        background_texture_map = pv.TextureMaptoSphere(Input=background_sphere)
        pv.Show(
            background_texture_map,
            view,
            Texture=background_texture,
            BackfaceRepresentation="Cull Frontface",
            Ambient=1.0,
        )

    # Load the waveform data file
    waveform_h5file, waveform_subfile = parse_as.file_and_subfile(
        scene["Datasources"]["Waveform"])
    waveform_data = WaveformDataReader(FileName=waveform_h5file,
                                       Subfile=waveform_subfile)
    pv.UpdatePipeline()

    # Generate volume data from the waveform. Also sets the available time range.
    # TODO: Pull KeepEveryNthTimestep out of datasource
    waveform_to_volume_configs = scene["WaveformToVolume"]
    if isinstance(waveform_to_volume_configs, dict):
        waveform_to_volume_configs = [{
            "Object": waveform_to_volume_configs,
        }]
        if "VolumeRepresentation" in scene:
            waveform_to_volume_configs[0]["VolumeRepresentation"] = scene[
                "VolumeRepresentation"]
    waveform_to_volume_objects = []
    for waveform_to_volume_config in waveform_to_volume_configs:
        volume_data = WaveformToVolume(
            WaveformData=waveform_data,
            SwshCacheDirectory=parse_as.path(
                scene["Datasources"]["SwshCache"]),
            **waveform_to_volume_config["Object"],
        )
        if "Modes" in waveform_to_volume_config["Object"]:
            volume_data.Modes = waveform_to_volume_config["Object"]["Modes"]
        if "Polarizations" in waveform_to_volume_config["Object"]:
            volume_data.Polarizations = waveform_to_volume_config["Object"][
                "Polarizations"]
        waveform_to_volume_objects.append(volume_data)

    # Compute timing and frames information
    time_range_in_M = (
        volume_data.TimestepValues[0],
        volume_data.TimestepValues[-1],
    )
    logger.debug(f"Full available data time range: {time_range_in_M} (in M)")
    if "FreezeTime" in scene["Animation"]:
        frozen_time = scene["Animation"]["FreezeTime"]
        logger.info(f"Freezing time at {frozen_time}.")
        view.ViewTime = frozen_time
        animation = None
    else:
        if "Crop" in scene["Animation"]:
            time_range_in_M = scene["Animation"]["Crop"]
            logger.debug(f"Cropping time range to {time_range_in_M} (in M).")
        animation_speed = scene["Animation"]["Speed"]
        frame_rate = scene["Animation"]["FrameRate"]
        num_frames = animate.num_frames(
            max_animation_length=time_range_in_M[1] - time_range_in_M[0],
            animation_speed=animation_speed,
            frame_rate=frame_rate,
        )
        animation_length_in_seconds = num_frames / frame_rate
        animation_length_in_M = animation_length_in_seconds * animation_speed
        time_per_frame_in_M = animation_length_in_M / num_frames
        logger.info(f"Rendering {animation_length_in_seconds:.2f}s movie with"
                    f" {num_frames} frames ({frame_rate} FPS or"
                    f" {animation_speed:.2e} M/s or"
                    f" {time_per_frame_in_M:.2e} M/frame)...")
        if frame_window is not None:
            animation_window_num_frames = frame_window[1] - frame_window[0]
            animation_window_time_range = (
                time_range_in_M[0] + frame_window[0] * time_per_frame_in_M,
                time_range_in_M[0] +
                (frame_window[1] - 1) * time_per_frame_in_M,
            )
            logger.info(
                f"Restricting rendering to {animation_window_num_frames} frames"
                f" (numbers {frame_window[0]} to {frame_window[1] - 1}).")
        else:
            animation_window_num_frames = num_frames
            animation_window_time_range = time_range_in_M
            frame_window = (0, num_frames)

        # Setup animation so that sources can retrieve the `UPDATE_TIME_STEP`
        animation = pv.GetAnimationScene()
        # animation.UpdateAnimationUsingDataTimeSteps()
        # Since the data can be evaluated at arbitrary times we define the time steps
        # here by setting the number of frames within the full range
        animation.PlayMode = "Sequence"
        animation.StartTime = animation_window_time_range[0]
        animation.EndTime = animation_window_time_range[1]
        animation.NumberOfFrames = animation_window_num_frames
        logger.debug(
            f"Animating from scene time {animation.StartTime} to"
            f" {animation.EndTime} in {animation.NumberOfFrames} frames.")

        def scene_time_from_real(real_time):
            return (real_time / animation_length_in_seconds *
                    animation_length_in_M)

        # For some reason the keyframe time for animations is expected to be within
        # (0, 1) so we need to transform back and forth from this "normalized" time
        def scene_time_from_normalized(normalized_time):
            return animation.StartTime + normalized_time * (
                animation.EndTime - animation.StartTime)

        def normalized_time_from_scene(scene_time):
            return (scene_time - animation.StartTime) / (animation.EndTime -
                                                         animation.StartTime)

        # Setup progress measuring already here so volume data computing for
        # initial frame is measured
        if show_progress and not no_render:
            logging.getLogger().handlers = [TqdmLoggingHandler()]
            animation_window_frame_range = tqdm.trange(
                animation_window_num_frames,
                desc="Rendering",
                unit="frame",
                miniters=1,
                position=job_id,
            )
        else:
            animation_window_frame_range = range(animation_window_num_frames)

        # Set the initial time step
        animation.GoToFirst()

    # Display the volume data. This will trigger computing the volume data at the
    # current time step.
    for volume_data, waveform_to_volume_config in zip(
            waveform_to_volume_objects, waveform_to_volume_configs):
        vol_repr = (waveform_to_volume_config["VolumeRepresentation"]
                    if "VolumeRepresentation" in waveform_to_volume_config else
                    {})
        volume_color_by = config_color.extract_color_by(vol_repr)
        if (vol_repr["VolumeRenderingMode"] == "GPU Based"
                and len(volume_color_by) > 2):
            logger.warning(
                "The 'GPU Based' volume renderer doesn't support multiple"
                " components.")
        volume = pv.Show(volume_data, view, **vol_repr)
        pv.ColorBy(volume, value=volume_color_by)

    if "Slices" in scene:
        for slice_config in scene["Slices"]:
            slice_obj_config = slice_config.get("Object", {})
            slice = pv.Slice(Input=volume_data)
            slice.SliceType = "Plane"
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = slice_obj_config.get(
                "Origin", [0.0, 0.0, -0.3])
            slice.SliceType.Normal = slice_obj_config.get(
                "Normal", [0.0, 0.0, 1.0])
            slice_rep = pv.Show(slice, view,
                                **slice_config.get("Representation", {}))
            pv.ColorBy(slice_rep, value=volume_color_by)

    # Display the time
    if "TimeAnnotation" in scene:
        time_annotation = pv.AnnotateTimeFilter(volume_data,
                                                **scene["TimeAnnotation"])
        pv.Show(time_annotation, view, **scene["TimeAnnotationRepresentation"])

    # Add spheres
    if "Spheres" in scene:
        for sphere_config in scene["Spheres"]:
            sphere = pv.Sphere(**sphere_config["Object"])
            pv.Show(sphere, view, **sphere_config["Representation"])

    # Add trajectories and objects that follow them
    if "Trajectories" in scene:
        for trajectory_config in scene["Trajectories"]:
            trajectory_name = trajectory_config["Name"]
            radial_scale = (trajectory_config["RadialScale"]
                            if "RadialScale" in trajectory_config else 1.0)
            # Load the trajectory data
            traj_data_reader = TrajectoryDataReader(
                RadialScale=radial_scale,
                **scene["Datasources"]["Trajectories"][trajectory_name],
            )
            # Make sure the data is loaded so we can retrieve timesteps.
            # TODO: This should be fixed in `TrajectoryDataReader` by
            # communicating time range info down the pipeline, but we had issues
            # with that (see also `WaveformDataReader`).
            traj_data_reader.UpdatePipeline()
            if "Objects" in trajectory_config:
                with animate.restore_animation_state(animation):
                    follow_traj = FollowTrajectory(
                        TrajectoryData=traj_data_reader)
                for traj_obj_config in trajectory_config["Objects"]:
                    for traj_obj_key in traj_obj_config:
                        if traj_obj_key in [
                                "Representation",
                                "Visibility",
                                "TimeShift",
                                "Glyph",
                        ]:
                            continue
                        traj_obj_type = getattr(pv, traj_obj_key)
                        traj_obj_glyph = traj_obj_type(
                            **traj_obj_config[traj_obj_key])
                    follow_traj.UpdatePipeline()
                    traj_obj = pv.Glyph(Input=follow_traj,
                                        GlyphType=traj_obj_glyph)
                    # Can't set this in the constructor for some reason
                    traj_obj.ScaleFactor = 1.0
                    for glyph_property in (traj_obj_config["Glyph"] if "Glyph"
                                           in traj_obj_config else []):
                        setattr(
                            traj_obj,
                            glyph_property,
                            traj_obj_config["Glyph"][glyph_property],
                        )
                    traj_obj.UpdatePipeline()
                    if "TimeShift" in traj_obj_config:
                        traj_obj = animate.apply_time_shift(
                            traj_obj, traj_obj_config["TimeShift"])
                    pv.Show(traj_obj, view,
                            **traj_obj_config["Representation"])
                    if "Visibility" in traj_obj_config:
                        animate.apply_visibility(
                            traj_obj,
                            traj_obj_config["Visibility"],
                            normalized_time_from_scene,
                            scene_time_from_real,
                        )
            if "Tail" in trajectory_config:
                with animate.restore_animation_state(animation):
                    traj_tail = TrajectoryTail(TrajectoryData=traj_data_reader)
                if "TimeShift" in trajectory_config:
                    traj_tail = animate.apply_time_shift(
                        traj_tail, trajectory_config["TimeShift"])
                tail_config = trajectory_config["Tail"]
                traj_color_by = config_color.extract_color_by(tail_config)
                if "Visibility" in tail_config:
                    tail_visibility_config = tail_config["Visibility"]
                    del tail_config["Visibility"]
                else:
                    tail_visibility_config = None
                tail_rep = pv.Show(traj_tail, view, **tail_config)
                pv.ColorBy(tail_rep, value=traj_color_by)
                if tail_visibility_config is not None:
                    animate.apply_visibility(
                        traj_tail,
                        tail_visibility_config,
                        normalized_time_from_scene=normalized_time_from_scene,
                        scene_time_from_real=scene_time_from_real,
                    )
            if "Move" in trajectory_config:
                move_config = trajectory_config["Move"]
                logger.debug(
                    f"Animating '{move_config['guiName']}' along trajectory.")
                with h5py.File(trajectory_file, "r") as traj_data_file:
                    trajectory_data = np.array(
                        traj_data_file[trajectory_subfile])
                if radial_scale != 1.0:
                    trajectory_data[:, 1:] *= radial_scale
                logger.debug(f"Trajectory data shape: {trajectory_data.shape}")
                animate.follow_path(
                    gui_name=move_config["guiName"],
                    trajectory_data=trajectory_data,
                    num_keyframes=move_config["NumKeyframes"],
                    scene_time_range=time_range_in_M,
                    normalized_time_from_scene=normalized_time_from_scene,
                )

    # Add non-spherical horizon shapes (instead of spherical objects following
    # trajectories)
    if "Horizons" in scene:
        for horizon_config in scene["Horizons"]:
            with animate.restore_animation_state(animation):
                horizon = pv.PVDReader(FileName=scene["Datasources"]
                                       ["Horizons"][horizon_config["Name"]])
                if horizon_config.get("InterpolateTime", False):
                    horizon = pv.TemporalInterpolator(
                        Input=horizon, DiscreteTimeStepInterval=0)
            if "TimeShift" in horizon_config:
                horizon = animate.apply_time_shift(horizon,
                                                   horizon_config["TimeShift"],
                                                   animation)
            # Try to make horizon surfaces smooth. At low angular resoluton
            # they still show artifacts, so perhaps more can be done.
            horizon = pv.ExtractSurface(Input=horizon)
            horizon = pv.GenerateSurfaceNormals(Input=horizon)
            horizon_rep_config = horizon_config.get("Representation", {})
            if "Representation" not in horizon_rep_config:
                horizon_rep_config["Representation"] = "Surface"
            if "AmbientColor" not in horizon_rep_config:
                horizon_rep_config["AmbientColor"] = [0.0, 0.0, 0.0]
            if "DiffuseColor" not in horizon_rep_config:
                horizon_rep_config["DiffuseColor"] = [0.0, 0.0, 0.0]
            if "Specular" not in horizon_rep_config:
                horizon_rep_config["Specular"] = 0.2
            if "SpecularPower" not in horizon_rep_config:
                horizon_rep_config["SpecularPower"] = 10
            if "SpecularColor" not in horizon_rep_config:
                horizon_rep_config["SpecularColor"] = [1.0, 1.0, 1.0]
            if "ColorBy" in horizon_rep_config:
                horizon_color_by = config_color.extract_color_by(
                    horizon_rep_config)
            else:
                horizon_color_by = None
            horizon_rep = pv.Show(horizon, view, **horizon_rep_config)
            if horizon_color_by is not None:
                pv.ColorBy(horizon_rep, value=horizon_color_by)
            # Animate visibility
            if "Visibility" in horizon_config:
                animate.apply_visibility(
                    horizon,
                    horizon_config["Visibility"],
                    normalized_time_from_scene=normalized_time_from_scene,
                    scene_time_from_real=scene_time_from_real,
                )
            if "Contours" in horizon_config:
                for contour_config in horizon_config["Contours"]:
                    contour = pv.Contour(Input=horizon,
                                         **contour_config["Object"])
                    contour_rep = pv.Show(contour, view,
                                          **contour_config["Representation"])
                    pv.ColorBy(contour_rep, None)
                    if "Visibility" in horizon_config:
                        animate.apply_visibility(
                            contour,
                            horizon_config["Visibility"],
                            normalized_time_from_scene=
                            normalized_time_from_scene,
                            scene_time_from_real=scene_time_from_real,
                        )

    # Configure transfer functions
    if "TransferFunctions" in scene:
        for tf_config in scene["TransferFunctions"]:
            colored_field = tf_config["Field"]
            transfer_fctn = pv.GetColorTransferFunction(colored_field)
            opacity_fctn = pv.GetOpacityTransferFunction(colored_field)
            tf.configure_transfer_function(transfer_fctn, opacity_fctn,
                                           tf_config["TransferFunction"])

    # Save state file before configuring camera keyframes.
    # TODO: Make camera keyframes work with statefile
    if save_state_to_file is not None:
        pv.SaveState(save_state_to_file + ".pvsm")

    # Camera shots
    # TODO: Make this work with freezing time while the camera is swinging
    if animation is None:
        for i, shot in enumerate(scene["CameraShots"]):
            if (i == len(scene["CameraShots"]) - 1 or
                (shot["Time"] if "Time" in shot else 0.0) >= view.ViewTime):
                camera_motion.apply(shot)
                break
    else:
        camera_motion.apply_swings(
            scene["CameraShots"],
            scene_time_range=time_range_in_M,
            scene_time_from_real=scene_time_from_real,
            normalized_time_from_scene=normalized_time_from_scene,
        )

    # Report time
    if animation is not None:
        report_time_cue = pv.PythonAnimationCue()
        report_time_cue.Script = """
def start_cue(self): pass

def tick(self):
    import paraview.simple as pv
    import logging
    logger = logging.getLogger('Animation')
    scene_time = pv.GetActiveView().ViewTime
    logger.info(f"Scene time: {scene_time}")

def end_cue(self): pass
"""
        animation.Cues.append(report_time_cue)

    if show_preview and animation is not None:
        animation.PlayMode = "Real Time"
        animation.Duration = 10
        animation.Play()
        animation.PlayMode = "Sequence"

    if no_render:
        logger.info("No rendering requested. Total time:"
                    f" {time.time() - render_start_time:.2f}s")
        return

    if frames_dir is None:
        raise RuntimeError("Trying to render but `frames_dir` is not set.")
    if os.path.exists(frames_dir):
        logger.warning(
            f"Output directory '{frames_dir}' exists, files may be overwritten."
        )
    else:
        os.makedirs(frames_dir)

    if animation is None:
        pv.Render()
        pv.SaveScreenshot(os.path.join(frames_dir, "frame.png"))
    else:
        # Iterate over frames manually to support filling in missing frames.
        # If `pv.SaveAnimation` would support that, here's how it could be
        # invoked:
        # pv.SaveAnimation(
        #     os.path.join(frames_dir, 'frame.png'),
        #     view,
        #     animation,
        #     FrameWindow=frame_window,
        #     SuffixFormat='.%06d')
        # Note that `FrameWindow` appears to be buggy, so we set up the
        # `animation` according to the `frame_window` above so the frame files
        # are numberd correctly.
        for animation_window_frame_i in animation_window_frame_range:
            frame_i = frame_window[0] + animation_window_frame_i
            frame_file = os.path.join(frames_dir, f"frame.{frame_i:06d}.png")
            if render_missing_frames and os.path.exists(frame_file):
                continue
            logger.debug(f"Rendering frame {frame_i}...")
            animation.AnimationTime = (
                animation.StartTime +
                time_per_frame_in_M * animation_window_frame_i)
            pv.Render()
            pv.SaveScreenshot(frame_file)
            logger.info(f"Rendered frame {frame_i}.")

    logger.info(
        f"Rendering done. Total time: {time.time() - render_start_time:.2f}s")
Пример #24
0
    def updateUserSelectionLutProperties(self):
        lutProxy = simple.GetColorTransferFunction(USER_SELECTION)
        lutPwf = simple.GetOpacityTransferFunction(USER_SELECTION)

        if not lutProxy:
            print(
                'There is no such color transfer function (%s) at this time' %
                USER_SELECTION)
            return

        if not lutPwf:
            print(
                'There is no such opacity transfer function (%s) at this time'
                % USER_SELECTION)
            return

        preset = self.lutMap[SELECTION_COLORMAP]['IndexedColors']
        if not preset:
            print('You are missing the "%s" color map definition' %
                  SELECTION_COLORMAP)
            return

        activeAnnotation = self.activeSelectionInformation["activeAnnotation"]
        activeScores = self.activeSelectionInformation["activeScores"]

        annoType = activeAnnotation['selection']['type']
        annoScore = activeAnnotation['score']

        # append a 0 so unselected scores don't show by default.
        scoreOpacities = [ 1.0 if score['index'] in activeScores else 0.0 for score in self._serverScores ] + \
          [1.0 if self._unselectedIndex in activeScores else 0.0]

        numScores = len(self._serverScores)
        pwfPoints = []
        rgbPoints = []
        delX = 0.49

        # import pdb; pdb.set_trace()

        ### Inside the cases below I also need to create custom opacity and size pwfs for
        ### the "user selection" array

        ### We take into account the "activeScores" pushed here by the client
        ### so we can show/hide the appropriate subsets of points using a dedicated
        ### opacity transfer function on the lookup table

        usRange = [
            self.userSelPointSizeRange[0], self.userSelPointSizeRange[1]
        ]
        usDelta = (usRange[1] - usRange[0]) / numScores
        # unselected value is last, should be the minimum value.
        sizeStops = [
            usRange[0] + (i + 1) * usDelta for i in range(numScores - 1)
        ] + [usRange[1], usRange[0]]

        if annoType == 'range':
            scoreIndex = annoScore[0]
            rgbPoints = []
            pwfPoints = []
            self.userSelScalePoints = []
            for selVal in [scoreIndex, self._unselectedIndex]:
                presetOffset = selVal * 3
                # add the selected color
                rgbPoints += [selVal - delX
                              ] + preset[presetOffset:presetOffset + 3] + [
                                  selVal + delX
                              ] + preset[presetOffset:presetOffset + 3]
                opacity = scoreOpacities[selVal]
                pwfPoints += [
                    selVal - delX, opacity, 0.5, 0.0, selVal + delX, opacity,
                    0.5, 0.0
                ]
                self.userSelScalePoints += [
                    selVal - delX, sizeStops[selVal], 0.5, 0.0, selVal + delX,
                    sizeStops[selVal], 0.5, 0.0
                ]

        elif annoType == 'partition':
            self.userSelScalePoints = []
            for idx in range(len(annoScore)):
                scoreIndex = annoScore[idx]
                presetOffset = scoreIndex * 3

                x1 = scoreIndex - delX
                x2 = scoreIndex + delX
                opacity = scoreOpacities[scoreIndex]

                rgbPoints += [x1] + preset[presetOffset:presetOffset + 3]
                rgbPoints += [x2] + preset[presetOffset:presetOffset + 3]
                pwfPoints += [x1, opacity, 0.5, 0.0, x2, opacity, 0.5, 0.0]
                self.userSelScalePoints += [
                    x1, sizeStops[scoreIndex], 0.5, 0.0, x2,
                    sizeStops[scoreIndex], 0.5, 0.0
                ]
        elif annoType == 'empty':
            selVal = self._unselectedIndex
            opacity = scoreOpacities[selVal]
            rgbPoints = [selVal - delX] + preset[3 * selVal:3 * selVal + 3] + [
                selVal + delX
            ] + preset[3 * selVal:3 * selVal + 3]
            pwfPoints = [
                selVal - delX, opacity, 0.5, 0.0, selVal + delX, opacity, 0.5,
                0.0
            ]
            self.userSelScalePoints = [
                selVal - delX, usRange[0], 0.5, 0.0, selVal + delX, usRange[0],
                0.5, 0.0
            ]
        else:
            print('Unknown annotation selection type: %s' % annoType)
            return

        # print('rgbPoints', rgbPoints)
        # print('pwfPoints', pwfPoints)
        lutProxy.RGBPoints = rgbPoints
        lutProxy.ScalarRangeInitialized = 1.0

        if len(pwfPoints) > 0:
            lutPwf.Points = pwfPoints
            lutPwf.ScalarRangeInitialized = 1
            lutProxy.EnableOpacityMapping = 1
        else:
            lutProxy.EnableOpacityMapping = 0

        self._selectionLutInitialized = True

        # Let PV know that the VTK data has been modified
        if self.trivProducer:
            self.trivProducer.MarkModified(self.trivProducer)

        self.getApplication().InvokeEvent('UpdateEvent')
Пример #25
0
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Create a spherical slice
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Create writer for this data and register it with the pipeline
            sliceWriter = pvs.XMLPPolyDataWriter(Input=slice,
                                                 DataMode="Appended",
                                                 CompressorType="ZLib")
            coprocessor.RegisterWriter(sliceWriter,
                                       filename='spherical_slice_%t.pvtp',
                                       freq=1)

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [-5, -2, 4]
            renderView.CameraViewUp = [0.5, 0.3, 0.8]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='spherical_slice_%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 = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(slice, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', fieldname]
            sphereDisplay.LookupTable = LUT
        class Pipeline:

            grid = coprocessor.CreateProducer(datadescription, 'input')

            # Normalise radius - simplifies creating glyphs
            normalise = pvs.Calculator(Input=grid)
            normalise.CoordinateResults = 1
            normalise.Function = 'coords/%i' % sphere_radius

            # Visualise velocity field using arrows
            glyph = pvs.Glyph(Input=normalise, GlyphType='Arrow')
            glyph.Scalars = ['POINTS', 'None']
            glyph.Vectors = ['CELLS', 'u']
            glyph.ScaleFactor = 0.2
            glyph.GlyphTransform = 'Transform2'
            glyph.GlyphType.TipResolution = 12
            glyph.GlyphType.TipRadius = 0.05
            glyph.GlyphType.ShaftRadius = 0.015

            # Create a new 'Render View'
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [-5, -2, 4]
            renderView.CameraViewUp = [0.5, 0.3, 0.8]
            renderView.CameraParallelScale = 1.7
            renderView.Background = [0.32, 0.34, 0.43]

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='velocity_field_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=800,
                                     height=800,
                                     cinema={})
            renderView.ViewTime = datadescription.GetTime()

            # Create colour transfer function for velocity field
            uLUT = pvs.GetColorTransferFunction('u')
            uLUT.RGBPoints = [
                1.7, 0.23, 0.30, 0.75, 20.9, 0.87, 0.87, 0.87, 40.0, 0.71,
                0.016, 0.15
            ]
            uLUT.ScalarRangeInitialized = 1.0

            # Show velocity field magnitude
            velocitymagDisplay = pvs.Show(normalise, renderView)
            velocitymagDisplay.Representation = 'Surface'
            velocitymagDisplay.ColorArrayName = ['CELLS', 'u']
            velocitymagDisplay.LookupTable = uLUT

            # Show colour legend
            uLUTColorBar = pvs.GetScalarBar(uLUT, renderView)
            uLUTColorBar.Title = 'u'
            uLUTColorBar.ComponentTitle = 'Magnitude'
            velocitymagDisplay.SetScalarBarVisibility(renderView, True)

            # Show velocity field glyphs
            glyphDisplay = pvs.Show(glyph, renderView)
            glyphDisplay.Representation = 'Surface'
            glyphDisplay.ColorArrayName = [None, '']
        class Pipeline:

            # Define source of pipeline
            grid = coprocessor.CreateProducer(datadescription, "input")

            if (write_full_output == True):
                fullWriter = pvs.XMLPUnstructuredGridWriter(
                    Input=grid, DataMode="Appended", CompressorType="ZLib")
                coprocessor.RegisterWriter(fullWriter,
                                           filename='full_output_%t.pvtu',
                                           freq=1)

            # Create a spherical slice
            slice = pvs.Slice(Input=grid)
            slice.SliceType = 'Sphere'
            slice.Triangulatetheslice = 0
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Radius = sphere_radius

            # Generate ghost cells - needed by CellDatatoPointData filter
            ghosts = pvs.GhostCellsGenerator(Input=grid)
            ghosts.BuildIfRequired = 0
            ghosts.MinimumNumberOfGhostLevels = 1

            # Convert cell data to point data, which is required for good contour results
            # Request "piece invariance" to ensure consistent values at
            # partition boundaries.
            #
            # CAUTION: THIS FILTER AVERAGES DATA FROM ALL CELLS SURROUNDING A POINT,
            #          WHICH REDUCES ACCURACY
            cell2point = pvs.CellDatatoPointData(Input=ghosts)

            # Create contours
            # Note that the "tube" filter can be used to highlight contours if needed.
            contours = pvs.Contour(Input=cell2point)
            contours.Isosurfaces = contour_values
            contours.ContourBy = ['POINTS', 'rho']
            contours.PointMergeMethod = 'Uniform Binning'

            # Create writers for slice and contour data and register them with the pipeline
            # Note that slice and contours generate separate datasets, so they need to be
            # written to separate files.
            sliceWriter = pvs.XMLPPolyDataWriter(Input=slice,
                                                 DataMode="Appended",
                                                 CompressorType="ZLib")
            coprocessor.RegisterWriter(sliceWriter,
                                       filename='spherical_slice_%t.pvtp',
                                       freq=1)

            # Create a new render view
            renderView = pvs.CreateView('RenderView')
            renderView.ViewSize = [1500, 768]
            renderView.AxesGrid = 'GridAxes3DActor'
            renderView.StereoType = 0
            renderView.CameraPosition = [0.0, 1.0, 0.3]
            renderView.CameraViewUp = [0.0, 0.0, 1.0]
            renderView.CameraParallelScale = 1.0
            renderView.Background = [0.32, 0.34, 0.43]
            renderView.ViewTime = datadescription.GetTime()

            # Register the view with coprocessor
            # and provide it with information such as the filename to use,
            # how frequently to write the images, etc.
            coprocessor.RegisterView(renderView,
                                     filename='contours_%t.png',
                                     freq=1,
                                     fittoscreen=1,
                                     magnification=1,
                                     width=1500,
                                     height=768,
                                     cinema={})

            # Create colour transfer function for field
            LUT = pvs.GetColorTransferFunction('rho')
            LUT.RGBPoints = [
                dataRange[0], 0.23, 0.30, 0.75, 0.5 * sum(dataRange), 0.87,
                0.87, 0.87, dataRange[1], 0.71, 0.016, 0.15
            ]
            LUT.ScalarRangeInitialized = 1.0

            # Show surface and colour by field value (which is cell data) using lookup table
            sphereDisplay = pvs.Show(slice, renderView)
            sphereDisplay.Representation = 'Surface'
            sphereDisplay.ColorArrayName = ['CELLS', 'rho']
            sphereDisplay.LookupTable = LUT

            # Show coastlines
            contourDisplay = pvs.Show(contours, renderView)
            contourDisplay.Representation = 'Surface'
            contourDisplay.ColorArrayName = [None, '']
            contourDisplay.OSPRayScaleArray = 'theta '
            contourDisplay.OSPRayScaleFunction = 'PiecewiseFunction'
            contourDisplay.SelectOrientationVectors = 'None'
            contourDisplay.ScaleFactor = 1193042.2418936265
            contourDisplay.SelectScaleArray = 'None'
            contourDisplay.GlyphType = 'Arrow'
            contourDisplay.GlyphTableIndexArray = 'None'
            contourDisplay.DataAxesGrid = 'GridAxesRepresentation'
            contourDisplay.PolarAxes = 'PolarAxesRepresentation'
            contourDisplay.GaussianRadius = 596521.1209468133
            contourDisplay.SetScaleArray = ['POINTS', 'theta ']
            contourDisplay.ScaleTransferFunction = 'PiecewiseFunction'
            contourDisplay.OpacityArray = ['POINTS', 'theta ']
            contourDisplay.OpacityTransferFunction = 'PiecewiseFunction'
Пример #28
0
# set active view
pv.SetActiveView(renderView1)

# create a new 'Glyph'
# sphere
glyph1 = pv.Glyph(Input=tableToPoints1, GlyphType='Sphere')
glyph1.Scalars = ['POINTS', 'Q']
glyph1.ScaleMode = 'scalar'
glyph1.ScaleFactor = scaleFactor
glyph1.GlyphMode = 'All Points'
#glyph1.GlyphType.ThetaResolution = 8
#glyph1.GlyphType.PhiResolution = 8

# get color transfer function/color map for args.colourColumn
cLUT = pv.GetColorTransferFunction(args.colourColumn)
nc = vtk.vtkNamedColors()
rgb = [0. for i in range(3)]
if args.colourColumn == 'Q':
    cLUT.ApplyPreset("Plasma (matplotlib)")
else:
    nc.GetColorRGB("Magenta", rgb)
    rgbPoints = [-1.] + rgb  # Rejected Hit
    nc.GetColorRGB("Lime", rgb)
    rgbPoints += [0.] + rgb  # Unambiguous Hit
    if args.detail:
        nc.GetColorRGB("Green", rgb)
    else:
        nc.GetColorRGB("Lime", rgb)
    rgbPoints += [1.] + rgb  # Accepted Ambiguity
    nc.GetColorRGB("Maroon", rgb)
Пример #29
0
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
def pvd_to_mp4(sim_dir,
               path_to_movies,
               movie_name='movie',
               representation='Surface',
               num_regions=0):

    ###############################
    # Validate directory and data #
    ###############################

    if not (os.path.isdir(sim_dir)):
        raise Exception('pvd_to_mp4: Invalid simulation directory')

    if not (os.path.isdir(path_to_movies)):
        raise Exception('pvd_to_mp4: Invalid movie directory')

    if representation not in ['Surface', 'Points']:
        raise Exception(
            'pvd_to_mp4: Representation must be either Surface or Points')

    if num_regions not in [0, 9]:
        raise Exception(
            'pvd_to_mp4: Currently there is only support for 9 node regions')

    # sim_id = os.path.basename(os.path.normpath(sim_dir))

    possible_data_directories = []
    for directory in os.listdir(sim_dir):
        if directory.startswith('results_from_time'):
            possible_data_directories.append(os.path.join(sim_dir, directory))

    if len(possible_data_directories) == 0:
        raise Exception(
            'pvd_to_mp4: Could not find a "results_from_time_X" directory')

    # The last directory alphabetically will be the one after any initial relaxation simulation
    data_directory = sorted(possible_data_directories)[-1]

    # Get the location of the pvd file
    pvd_file = os.path.join(data_directory, 'results.pvd')
    if not (os.path.isfile(pvd_file)):
        raise Exception('pvd_to_mp4: Could not find a pvd data file')

    if os.path.getsize(pvd_file) < 1024:
        raise Exception(
            'pvd_to_mp4: pvd file exists but is < 1kb. Presumably simulation failed to finish as expected.'
        )

    full_movie_path = os.path.join(path_to_movies,
                                   movie_name + '_' + representation + '.mp4')

    ##################################
    # Set up scene with box and data #
    ##################################

    # Get active view. This is the ParaView default view - blue background with cross hairs and orientation axes
    render_view = pv.GetActiveViewOrCreate('RenderView')

    # Change parameters to be how we want them for output
    render_view.ViewSize = [1600, 900]  # Size of output (pixels)
    render_view.CenterAxesVisibility = 0  # Remove cross hairs
    render_view.OrientationAxesVisibility = 0  # Remove orientation axes
    render_view.Background = [0.5, 0.5,
                              0.5]  # Set background colour to 50% grey

    # Create a unit square (a 3D Box with ZLength set to zero)
    unit_square = pv.Box()
    unit_square.ZLength = 0.0
    unit_square.YLength = 9.0 / 16.0
    unit_square.Center = [0.5, 0.5, 0.0]

    # Show the box in the current render view, and colour it black
    unit_square_display = pv.Show(unit_square, render_view)
    unit_square_display.DiffuseColor = [0.0, 0.0, 0.0]

    # Read the relevant pvd file from the Chaste output
    results_pvd = pv.PVDReader(FileName=pvd_file)

    # Show the data in the current render view as a surface
    results_pvd_display = pv.Show(results_pvd, render_view)
    results_pvd_display.Representation = representation

    if representation == 'Points' and num_regions == 9:
        pv.ColorBy(results_pvd_display, ('POINTS', 'Node Regions'))
        node_regions_lut = pv.GetColorTransferFunction('NodeRegions')

        # Each four digits are: data value, r, g, b (colour)
        node_regions_lut.RGBPoints = [
            0.0,
            1.00,
            0.00,
            0.00,  # LEFT_APICAL_REGION, red
            1.0,
            1.00,
            0.00,
            0.00,  # RIGHT_APICAL_REGION, red
            2.0,
            1.00,
            0.00,
            1.00,  # LEFT_PERIAPICAL_REGION, purple
            3.0,
            1.00,
            0.00,
            1.00,  # RIGHT_PERIAPICAL_REGION, purple
            4.0,
            0.00,
            0.00,
            1.00,  # LEFT_LATERAL_REGION, blue
            5.0,
            0.00,
            0.00,
            1.00,  # RIGHT_LATERAL_REGION, blue
            6.0,
            1.00,
            1.00,
            1.00,  # LEFT_BASAL_REGION, white
            7.0,
            1.00,
            1.00,
            1.00,  # RIGHT_BASAL_REGION, white
            8.0,
            1.00,
            1.00,
            1.00
        ]  # LAMINA_REGION, white

        cell_regions_lut = pv.GetColorTransferFunction('CellRegions')
        cell_regions_lut.RGBPoints = [
            -1.0,
            0.0,
            0.00,
            0.00,  # basal lamina, black
            0.0,
            0.00,
            0.00,
            1.00,  # left region, blue
            1.0,
            1.00,
            1.00,
            1.00,  # centre_region, white
            2.0,
            1.00,
            0.00,
            0.00
        ]  # right_region, red

        # Glyphs for cell region
        cell_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph')

        cell_glyphs.Scalars = ['CELLS', 'Cell Regions']
        cell_glyphs.ScaleFactor = 0.01
        cell_glyphs.GlyphMode = 'All Points'
        cell_glyphs.GlyphType.GlyphType = 'Diamond'
        cell_glyphs.GlyphType.Filled = 1
        cell_glyphs.GlyphTransform.Scale = [1.0, 2.0, 1.0]

        cell_glyphs_display = pv.Show(cell_glyphs, render_view)
        cell_glyphs_display.Opacity = 0.5

        # Glyphs for node region
        node_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph')

        node_glyphs.Scalars = ['POINTS', 'Node Regions']
        node_glyphs.ScaleFactor = 0.002
        node_glyphs.GlyphMode = 'All Points'
        node_glyphs.GlyphType.GlyphType = 'Circle'
        node_glyphs.GlyphType.Filled = 1

        pv.Show(node_glyphs, render_view)

    ###################################
    # Put the camera where we want it #
    ###################################

    # This happens after all calls to Show, as Show may do some automatic camera re-setting
    render_view.InteractionMode = '2D'
    render_view.CameraPosition = [0.5, 0.5, 1.0]
    render_view.CameraFocalPoint = [0.5, 0.5, 0.0]

    # This parameter sets the 'zoom' and needs fine-tuning by the aspect ratio
    render_view.CameraParallelScale = 0.5 * 9.0 / 16.0

    ##################################
    # Set up and write the animation #
    ##################################

    # Get an animation scene, which has parameters we need to change before output
    animation_scene = pv.GetAnimationScene()

    # Get a list of time step values from the pvd file.  Typically this will look like [t_0, t1, t2, ..., t_end]
    time_step_info = results_pvd.TimestepValues
    num_time_steps = len(time_step_info)

    # Set the animation parameters
    animation_scene.NumberOfFrames = num_time_steps  # If num frames != num time steps, some interpolation will be used
    animation_scene.StartTime = time_step_info[
        0]  # Usually t_0, the first entry in time_step_info
    animation_scene.EndTime = time_step_info[
        -1]  # Usually t_end, the final entry in time_step_info

    # Write the animation as a series of uncompressed png files, with no magnification
    pv.WriteAnimation(sim_dir + 'results_' + representation + '.png',
                      Magnification=1,
                      Compression=False)

    # Raise exception if the png files are not generated as expected
    if not (os.path.isfile(sim_dir + 'results_' + representation +
                           '.0000.png')):
        raise Exception('pvd_to_mp4: png sequence not exported as expected')

    #######################################
    # Convert from png to mp4 and tidy up #
    #######################################

    # Ubuntu 14.04 (trusty) came bundled with avconv instead of ffmpeg, but they're nearly the same software
    # so we don't have to change the command other than the name of the video converter to use
    if platform.linux_distribution()[2] == 'trusty':
        video_converter = 'avconv'
    else:
        video_converter = 'ffmpeg'

    # Set how long you want the video to be (in seconds), and set the frame rate accordingly
    video_duration = 15.0
    frame_rate = str(num_time_steps / video_duration)

    # Send the system command to run avconv/ffmpeg. Parameters:
    #   -v 0                        Suppress console output so as not to clutter the terminal
    #   -r frame_rate               Set the frame rate calculated above
    #   -f image2                   Set the convert format (image sequence to video)
    #   -i dir/results.%04d.png     Input expected as dir/results.####.png, the output from WriteAnimation above
    #   -c:v h264                   Video codec to use is h264
    #   -crf 0                      Set video quality: 0 best, 51 worst (https://trac.ffmpeg.org/wiki/Encode/H.264)
    #   -y dir/movie.mp4            Output directory and name
    os.system(video_converter + ' -v 0 -r ' + frame_rate + ' -f image2 -i ' +
              sim_dir + 'results_' + representation +
              '.%04d.png -c:v h264 -crf 0 -y ' + full_movie_path)

    # Raise exception if the mp4 file is not generated as expected
    if not (os.path.isfile(full_movie_path)):
        raise Exception('pvd_to_mp4: mp4 not generated as expected')

    # Raise exception if the mp4 file file is created but is smaller than 1kb - ffmpeg sometimes
    # generates an empty file even if an error occurs
    if os.path.getsize(full_movie_path) < 1024:
        raise Exception('pvd_to_mp4: mp4 not generated as expected')

    # Clean up the png files created by WriteAnimation
    os.system('rm ' + sim_dir + '*.png')