def customStartupProcessing(files): rv = simple.Render() rv.ResetCamera() rv.Background = [0.0, 0.0, 0.0] simple.Render() gior = simple.GenericIOReader(FileName=files) gior.xAxis = 'x' gior.yAxis = 'y' gior.zAxis = 'z' gior.PointArrayStatus = ['vx', 'vy', 'vz', 'id', 'fof_halo_tag'] gior_rep = simple.Show(gior) gior_rep.SetRepresentationType('Outline') simple.Render() gior_rep.ColorArrayName = 'id' tag_array = gior.PointData.GetArray('id') simple.AssignLookupTable(tag_array, 'erdc_rainbow_bright') calc = simple.Calculator() calc.Function = 'iHat*vx + jHat*vy + kHat*vz' calc.ResultArrayName = 'velocity' simple.Render() calc_rep = simple.Show(calc) calc_rep.ColorArrayName = 'velocity' vel_array = calc.PointData.GetArray('velocity') simple.AssignLookupTable(vel_array, 'Cool to Warm') rv.ResetCamera() simple.Render()
def extractParaviewLineData(caseDir, varList, coords, calcDict, csvOutputVar, time): try: reader = ps.OpenFOAMReader(FileName=caseDir + '/case.foam') except: ps.Connect() reader = ps.OpenFOAMReader(FileName=caseDir + '/case.foam') try: reader.CellArrays = varList except: print("Variables {} were not found in results. Exiting ...".format( varList)) reader.MeshRegions = ['internalMesh'] if (time in reader.TimestepValues): reader.SMProxy.UpdatePipeline(time) reader.UpdatePipelineInformation() #view = ps.CreateRenderView() #view.ViewTime = time else: print("Time-directory {} does not exist. Exiting ...".format(time)) sys.exit(1) if (calcDict): calc = ps.Calculator(reader) calc.Function = calcDict["Function"] calc.ResultArrayName = calcDict["ResultArrayName"] plotLine = ps.PlotOverLine(Source="High Resolution Line Source") plotLine.Source.Resolution = 450 plotLine.Source.Point1 = coords[0] # [0.0, 0.0008, 0.0] plotLine.Source.Point2 = coords[1] # [0.59, 0.0008, 0.0] filePath = caseDir + "/tmp.csv" writer = ps.CreateWriter(filePath, plotLine) writer.WriteAllTimeSteps = False writer.UseScientificNotation = 1 #print("Writing file tmp.csv ... ") writer.UpdatePipeline() #print("Done!") ps.Delete(reader) ps.Delete(calc) #; ps.Delete(writer) ps.Delete(plotLine) reader = None del reader calc = None del calc plotLine = None del plotLine del writer if (np.mod((100. * time), 1) == 0): print("Disconnecting ... ") ps.Disconnect() # Clear memory occasionally. data = extractFromCSV("tmp.csv", csvOutputVar) return data
def createCalculator(self, reader, fct, var): """Create a new 'Calculator' """ calculator = pv.Calculator(Input=reader) calculator.ResultArrayName = "{}_{}".format(fct, var.lower()) calculator.Function = "{}({})".format(fct, var) return calculator
def _state2png(args): # pv._DisableFirstRenderCameraReset() # Open the data file. # solution_e = pv.OpenDataFile(args.filename) # solution_e.FileRange = [0, 0] # solution_e.FilePrefix = args.solution_file # solution_e.XMLFileName = '' # solution_e.FilePattern = '%s' # solution_e.PointVariables = ['psi_'] # solution_e.ElementBlocks = ['block_5'] # AnimationScene1 = GetAnimationScene() # AnimationScene1.EndTime = 5040.0 # AnimationScene1.PlayMode = 'Snap To TimeSteps' _set_camera(args.timestep) filenames = {} # create arrays array_name = "|psi|^2" calc1 = pv.Calculator(ResultArrayName=array_name) calc1.AttributeMode = "point_data" calc1.Function = "psi__X^2 + psi__Y^2" filenames[array_name] = "abs.png" # Use Calculator conditionals # <http://www.itk.org/Wiki/ParaView/Users_Guide/Calculator>. # to imitate the atan2() function with atan(). # See <http://en.wikipedia.org/wiki/Atan2#Definition>. array_name = "arg(psi)" calc2 = pv.Calculator(ResultArrayName=array_name) calc2.AttributeMode = "point_data" calc2.Function = ( "if(psi__X>0, atan(psi__Y/psi__X)," + "if(psi__X<0," + "if (psi__Y<0, - %s + atan(psi__Y/psi__X), %s + atan(psi__Y/psi__X))," % (np.pi, np.pi) + "if (psi__Y>0, %s, if(psi__Y<0, -%s, 0.0))" % (np.pi / 2, np.pi / 2) + "))") filenames[array_name] = "arg.png" _absarg2png(filenames) # for filename in filenames.items(): # _autocrop(filename) return
def setupCalculator(source, arrayName, color, fctString, renderView): calculator = smp.Calculator(Input=source) smp.RenameSource(getCalculatorName(arrayName), calculator) calculator.Function = '' calculator.ResultArrayName = arrayName calculator.Function = fctString calculatorDisplay = smp.GetDisplayProperties(calculator, view=renderView) calculatorDisplay.SetRepresentationType('3D Glyphs') calculatorDisplay.DiffuseColor = color calculatorDisplay.Orient = 1 calculatorDisplay.SelectOrientationVectors = 'Orientation(AxisAngle)' calculatorDisplay.SelectOrientationVectors = arrayName
# create a sphere to represent Earth earth = pv.Sphere() earth.Radius = 1.0 earth.ThetaResolution = 128 earth.PhiResolution = 128 earth_disp = pv.Show(earth, rvs) earth_disp2 = pv.Show(earth, rvs2) earth_disp3 = pv.Show(earth, rvs3) earth_disp4 = pv.Show(earth, rvs4) earth_disp4.DiffuseColor = [0.81, 0.81, 0.81] earth_disp3.DiffuseColor = [0.333, 0.333, 0.333] earth_disp2.DiffuseColor = [0.333, 0.333, 0.333] earth_disp.DiffuseColor = [0.333, 0.333, 0.333] Bmag_calc = pv.Calculator(Input=t96) Bmag_calc.ResultArrayName = 'Bmag' Bmag_calc.Function = 'mag(B)' Bmag_slice = pv.Slice(Input=Bmag_calc) Bmag_slice.SliceType = 'Plane' Bmag_slice.SliceOffsetValues = [0.0] Bmag_slice.SliceType.Origin = [-20.0, 0.0, 0.0] Bmag_slice.SliceType.Normal = [0.0, 1.0, 0.0] Bmag_calc2 = pv.Calculator(Input=dipole) Bmag_calc2.ResultArrayName = 'Bmag' Bmag_calc2.Function = 'mag(B)' Bmag_slice2 = pv.Slice(Input=Bmag_calc2) Bmag_slice2.SliceType = 'Plane' Bmag_slice2.SliceOffsetValues = [0.0] Bmag_slice2.SliceType.Origin = [-20.0, 0.0, 0.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
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, '']
def calculate(self, name="u_prime", func="s1_average - s1"): calculator1 = pv.Calculator(Input=self.groupDatasets1) calculator1.ResultArrayName = name calculator1.Function = func return calculator1
import paraview.simple as pv import glob import numpy as np pv.LoadPlugin("/Users/jjm390/libGhostKit.dylib") filelist = glob.glob("/Volumes/Data 1/PhD Data/MHD/LFMRCM/ToProcess/*.hdf") filelist = sorted(filelist) currentfile = pv.vtkLFMReader(FileNames=filelist[0]) currentfile.GridScaleFactor = 'Earth Radius: 6.5e8 cm' currentfile.CellArrayStatus = ['Magnetic Field Vector'] calc = pv.Calculator() calc.Input = currentfile calc.Function = 'Magnetic Field Vector * 1e5' calc.ResultArrayName = 'B' DataRepresentation1 = pv.Show() DataRepresentation1.SelectionPointFieldDataArrayName = 'Magnetic Field Vector' segment = 16 end = None outdir = "./outdata3/" for file in filelist[segment:]: print("Number: {0}".format(segment)) print("Loading File:", file) fileparts = str.split(file, '/') nameparts = str.split(fileparts[-1], '.')
test_disp_f[-1].DiffuseColor = [0.9, 0.1, 0.1] test_contour_list.append( ih.mag(flines[start_p].fieldLineData_f[(n * num_divs)])) contours[start_p] = test_contour_list contsphere_b[start_p] = test_points_b contsphere_f[start_p] = test_points_f min_sphr[start_p] = pv.Sphere() min_sphr[start_p].Radius = 0.06 min_sphr[start_p].Center = Bmin_loc min_sphr_disp[start_p] = pv.Show(min_sphr[start_p], rvs) min_sphr_disp[start_p].DiffuseColor = [0.0, 0.0, 0.0] Bmag_calc = pv.Calculator(Input=t96_128) Bmag_calc.ResultArrayName = 'Bmag' Bmag_calc.Function = 'mag(B)' Bmag_slice = pv.Slice(Input=Bmag_calc) Bmag_slice.SliceType = 'Plane' Bmag_slice.SliceOffsetValues = [0.0] Bmag_slice.SliceType.Origin = [-20.0, 0.0, 0.0] Bmag_slice.SliceType.Normal = [0.0, 1.0, 0.0] Bmag_contour = {} for key in contsphere_b: for x in contsphere_f[key]: pv.Hide(x, view=rvs) for x in contsphere_b[key]: pv.Hide(x, view=rvs)
def generateData(datasetPath, outputDir) : if not os.path.exists(outputDir): os.makedirs(outputDir) resolution = 500 center_of_rotation = [0.0, 0.0, 0.0] rotation_axis = [0.0, 0.0, 1.0] distance = 45.0 disk_out_refex2 = simple.ExodusIIReader(FileName=[datasetPath]) disk_out_refex2.PointVariables = ['Temp', 'V', 'Pres', 'AsH3', 'GaMe3', 'CH4', 'H2'] disk_out_refex2.NodeSetArrayStatus = [] disk_out_refex2.SideSetArrayStatus = [] disk_out_refex2.ElementBlocks = ['Unnamed block ID: 1 Type: HEX8'] filters = [] filters_description = [] calculator1 = simple.Calculator(Input=disk_out_refex2) calculator1.ResultArrayName = 'Velocity' calculator1.Function = 'mag(V)' simple.UpdatePipeline() color_by = [] # # COMPLAINT # # As a user of this system, I'd like not to have to specify that I need # 'nX', 'nY', and 'nZ' when I add a colorby of type "VALUE". Instead, # I'd like it to figure out that I'm going to need normals for that kind # of rendering and add them for me. # color_type = [ ('VALUE', "Velocity"), ('VALUE', "Pres"), ('VALUE', "Temp"), ('VALUE', "nX"), ('VALUE', "nY"), ('VALUE', "nZ") ] pdi = calculator1.GetPointDataInformation() # # COMPLAINT # # Ditto the above complaint here. # luts = { "Velocity": ["point", "Velocity", 0, pdi.GetArray("Velocity").GetRange()], "Pres": ["point", "Pres", 0, pdi.GetArray("Pres").GetRange()], "Temp": ["point", "Temp", 0, pdi.GetArray("Temp").GetRange()], "nX": ["point", "Normals", 0, (-1,1)], "nY": ["point", "Normals", 1, (-1,1)], "nZ": ["point", "Normals", 2, (-1,1)] } contour_values = [ 300.0, 600.0, 900.0 ] for iso_value in contour_values: contour = simple.Contour( Input=calculator1, PointMergeMethod="Uniform Binning", ContourBy = ['POINTS', 'Temp'], Isosurfaces = [iso_value], ComputeScalars = 1) # Add this isocontour to my list of filters filters.append( contour ) color_by.append( color_type ) filters_description.append( {'name': 'iso=%s' % str(iso_value), 'parent': "Contour by temperature"} ) # create a new 'Stream Tracer' streamTracer1 = StreamTracer(Input=calculator1, SeedType='High Resolution Line Source') streamTracer1.Vectors = ['POINTS', 'V'] streamTracer1.MaximumStreamlineLength = 20.15999984741211 # init the 'High Resolution Line Source' selected for 'SeedType' streamTracer1.SeedType.Point1 = [-5.75, -5.75, -10.0] streamTracer1.SeedType.Point2 = [5.75, 5.75, 10.15999984741211] # create a new 'Tube' tube1 = Tube(Input=streamTracer1) tube1.Scalars = ['POINTS', 'Velocity'] tube1.Vectors = ['POINTS', 'Normals'] tube1.Radius = 0.10474160957336426 # # COMPLAINT # # Here, because the "Normals" field of the tube filter is all funky # (directions seem to change at the seed points, when integration # proceeded in both directions), I actually needed to play around # with ParaView until I found a filter that would get me nice # looking normals. Then, that filter didn't have a "Normals" field, # so I had to use a calculator to create it. Not super nice from a # users perspective. # surfaceVectors1 = SurfaceVectors(Input=tube1) surfaceVectors1.SelectInputVectors = ['POINTS', 'TubeNormals'] calculator2 = simple.Calculator(Input=surfaceVectors1) calculator2.ResultArrayName = 'Normals' calculator2.Function = 'TubeNormals' # Now add the stream tubes to the filters list filters.append(calculator2); color_by.append(color_type); filters_description.append({'name': 'Stream Tubes'}) # create a new 'Clip' clip1 = Clip(Input=calculator1) clip1.ClipType = 'Plane' clip1.Value = 11.209410083552676 clip1.InsideOut = 1 # init the 'Plane' selected for 'ClipType' clip1.ClipType.Origin = [0.0, 0.0, 0.07999992370605469] clip1.ClipType.Normal = [0.7, 0.0, -0.4] # # COMPLAINT # # Here again, the output of the clip filter doesn't have a "Normals" # field on points, so I have to do some funky stuff to get what I # need. It would be nice if this could be figured out for me # somehow. # extractSurface1 = ExtractSurface(Input=clip1) generateSurfaceNormals1 = GenerateSurfaceNormals(Input=extractSurface1) # Now add the first clip to the filters list filters.append(generateSurfaceNormals1); color_by.append(color_type); filters_description.append({'name': 'Clip One'}) # create a new 'Clip' clip2 = Clip(Input=calculator1) clip2.ClipType = 'Plane' clip2.Value = 11.209410083552676 clip2.InsideOut = 0 # init the 'Plane' selected for 'ClipType' clip2.ClipType.Origin = [0.0, 0.0, 0.07999992370605469] clip2.ClipType.Normal = [0.7, 0.0, -0.4] # # COMPLAINT # # Ditto the above complaint here. # extractSurface2 = ExtractSurface(Input=clip2) generateSurfaceNormals2 = GenerateSurfaceNormals(Input=extractSurface2) # Now add the second clip to the filters list filters.append(generateSurfaceNormals2); color_by.append(color_type); filters_description.append({'name': 'Clip Two'}) title = "Composite Dynamic Rendering - Disk Out Ref" description = "A sample dataset for dynamic rendering" analysis = wx.AnalysisManager(outputDir, title, description) id = 'composite' title = '3D composite' description = "contour set" analysis.register_analysis(id, title, description, '{theta}/{phi}/{filename}', wx.CompositeImageExporter.get_data_type()+"-light") fng = analysis.get_file_name_generator(id) camera_handler = wx.ThreeSixtyCameraHandler( fng, None, [ float(r) for r in range(0, 360, 30) ], [ float(r) for r in range(-60, 61, 60) ], center_of_rotation, rotation_axis, distance) exporter = wx.CompositeImageExporter( fng, filters, color_by, luts, camera_handler, [resolution,resolution], filters_description, 0, 0, 'png') exporter.set_analysis(analysis) analysis.begin() exporter.UpdatePipeline(0) analysis.end()
def openFile(self, files): id = "" if _FileOpener.reader: try: simple.Delete(_FileOpener.reader) except: _FileOpener.reader = None try: #_FileOpener.reader = simple.OpenDataFile(files) #simple.Show() #simple.Render() #simple.ResetCamera() #id = _FileOpener.reader.GetGlobalIDAsString() m000_ = simple.GenericIOReader(FileName=files) m000_.xAxis = 'x' m000_.yAxis = 'y' m000_.zAxis = 'z' m000_.PointArrayStatus = ['vx', 'vy', 'vz', 'id', 'fof_halo_tag'] #_FileOpener.view = simple.GetRenderView() DataRepresentation1 = simple.Show() DataRepresentation1.ScaleFactor = 12.799999237060547 DataRepresentation1.ScalarOpacityUnitDistance = 1.7320512506334491 DataRepresentation1.SelectionPointFieldDataArrayName = 'fof_halo_tag' DataRepresentation1.EdgeColor = [0.0, 0.0, 0.50000762951094835] _FileOpener.view.CenterOfRotation = [ 63.999996662139893, 63.999996185302734, 63.999996185302734 ] Calculator1 = simple.Calculator() _FileOpener.view.CameraPosition = [ 63.999996662139893, 63.999996185302734, 492.29631710692331 ] _FileOpener.view.CameraFocalPoint = [ 63.999996662139893, 63.999996185302734, 63.999996185302734 ] _FileOpener.view.CameraClippingRange = [ 296.65336530365192, 595.04075617962826 ] _FileOpener.view.CameraParallelScale = 110.85124480185661 DataRepresentation2 = simple.Show() DataRepresentation2.ScaleFactor = 12.799999237060547 DataRepresentation2.ScalarOpacityUnitDistance = 1.7320512506334491 DataRepresentation2.SelectionPointFieldDataArrayName = 'fof_halo_tag' DataRepresentation2.EdgeColor = [0.0, 0.0, 0.50000762951094835] DataRepresentation1.Visibility = 0 Calculator1.Function = 'iHat*vx + jHat*vy + kHat*vz' Calculator1.ResultArrayName = 'velocity' _FileOpener.view.Background2 = [0.0, 0.0, 0.16470588235294117] _FileOpener.view.Background = [0.0, 0.0, 0.0] _FileOpener.view.CenterAxesVisibility = 0 a3_velocity_PVLookupTable = GetLookupTableForArray( "velocity", 3, RGBPoints=[ 22.220290592721472, 0.27843099999999998, 0.27843099999999998, 0.85882400000000003, 2772.329145661583, 0.0, 0.0, 0.36078399999999999, 5503.2064702754178, 0.0, 1.0, 1.0, 8272.5468557993063, 0.0, 0.50196099999999999, 0.0, 11003.42418041314, 1.0, 1.0, 0.0, 13753.533035482002, 1.0, 0.38039200000000001, 0.0, 16503.641890550865, 0.41960799999999998, 0.0, 0.0, 19253.750745619727, 0.87843099999999996, 0.30196099999999998, 0.30196099999999998 ], VectorMode='Magnitude', NanColor=[1.0, 1.0, 0.0], ColorSpace='RGB', ScalarRangeInitialized=1.0) a3_velocity_PiecewiseFunction = CreatePiecewiseFunction(Points=[ 22.220290592721472, 0.0, 0.5, 0.0, 19253.750745619727, 1.0, 0.5, 0.0 ]) ScalarBarWidgetRepresentation1 = CreateScalarBar( ComponentTitle='Magnitude', Title='velocity', Enabled=1, LabelFontSize=8, TitleFontSize=8) ScalarBarWidgetRepresentation1.LookupTable = a3_velocity_PVLookupTable _FileOpener.view.Representations.append( ScalarBarWidgetRepresentation1) DataRepresentation2.ScalarOpacityFunction = a3_velocity_PiecewiseFunction DataRepresentation2.ColorArrayName = ('POINT_DATA', 'velocity') DataRepresentation2.PointSize = 1.0 DataRepresentation2.LookupTable = a3_velocity_PVLookupTable a3_velocity_PVLookupTable.ScalarOpacityFunction = a3_velocity_PiecewiseFunction simple.Render() # Fix lookup table range data = simple.Calculator1.GetPointDataInformation() (minValue, maxValue) = data.GetArray('velocity').GetRange(-1) rgbPoints = a3_velocity_PVLookupTable.RGBPoints rgbPointsMod = [] for i in range(8): alpha = i / 7.0 rgbPointsMod.append((1 - alpha) * minValue + alpha * maxValue) rgbPointsMod.append(rgbPoints[4 * i + 1]) rgbPointsMod.append(rgbPoints[4 * i + 2]) rgbPointsMod.append(rgbPoints[4 * i + 3]) a3_velocity_PVLookupTable.RGBPoints = rgbPointsMod simple.Render() _FileOpener.reader = m000 id = _FileOpener.reader.GetGlobalIDAsString() except: _FileOpener.reader = None return id
def _plot_continuation(): """Main function.""" pv._DisableFirstRenderCameraReset() solution_e = pv.OpenDataFile(args.solution_file) # AnimationScene1 = GetAnimationScene() solution_e.FileRange = [0, 0] solution_e.FilePrefix = solution_file solution_e.XMLFileName = "" solution_e.FilePattern = "%s" # AnimationScene1.EndTime = 5040.0 # AnimationScene1.PlayMode = 'Snap To TimeSteps' solution_e.PointVariables = ["psi_"] solution_e.ElementBlocks = ["block_5"] # create calculator filter that computes the Cooper pair density calc1 = pv.Calculator(ResultArrayName="|psi|^2") calc1.AttributeMode = "point_data" calc1.Function = "psi__X^2 + psi__Y^2" # Use Calculator conditionals # <http://www.itk.org/Wiki/ParaView/Users_Guide/Calculator> # to imitate the atan2() function with atan(). # See <http://en.wikipedia.org/wiki/Atan2#Definition>. calc2 = pv.Calculator(ResultArrayName="arg(psi)") calc2.AttributeMode = "point_data" calc2.Function = ( "if(psi__X>0, atan(psi__Y/psi__X)," + "if(psi__X<0," + "if (psi__Y<0, - %s + atan(psi__Y/psi__X), %s + atan(psi__Y/psi__X))," % (np.pi, np.pi) + "if (psi__Y>0, %s, if(psi__Y<0, -%s, 0.0))" % (np.pi / 2, np.pi / 2) + "))") # set view angle etc. _set_camera() data_representation = pv.Show() # read the continuation file continuation_data = np.loadtxt(continuation_file) plot_columns = {"mu": 1, "energy": 9} # plot the continuation data x_values = continuation_data[0:, plot_columns["mu"]] y_values = continuation_data[0:, plot_columns["energy"]] # prepare the plot fig = pp.figure() # Adjust the size of the figure to host two figures next to each other # with little distortion. default_size = fig.get_size_inches() fig.set_size_inches((default_size[0] * 2, default_size[1]), forward=True) # draw first diagram diagram_ax = fig.add_subplot(1, 3, 3) pp.plot(x_values, y_values, "r-") max_val = int(10 * max(y_values)) / 10.0 # round to -0.3, -0.4, ... pp.ylim(-1.0, max_val) pp.xlabel("$\mu$") pp.ylabel("$F/F_0$") # prepare for the blue moving dot line, = diagram_ax.plot([], [], "bo") ## take screenshot # filename = 'test0.png' # tstep = 0 # _take_screenshot(view, tstep, data_representation, filename) # plot screenshot fig.add_subplot(1, 3, 1) # turn off ticks pp.title("$|\psi|^2$") pp.xticks([]) pp.yticks([]) pp.box("off") fig.add_subplot(1, 3, 2) pp.title("$\mathrm{arg}\,\psi$") # turn off ticks pp.xticks([]) pp.yticks([]) pp.box("off") # Creating a movie won't work before a proper PNG filter is in # ffmpeg/libav, see # http://stackoverflow.com/questions/4092927/generating-movie-from-python-without-saving-individual-frames-to-files # outf = 'test.avi' # rate = 1 # cmdstring = ('/usr/bin/ffmpeg', # '-r', '%d' % rate, # '-f','image2pipe', # '-vcodec', 'png', # '-i', 'pipe:', outf # ) # p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE) # Create cache folder for all the PNGs. cache_folder = os.path.join(folder, "data") if not os.path.exists(cache_folder): os.makedirs(cache_folder) # begin the loop num_steps = len(solution_e.TimestepValues) max_number_of_digits = int(np.ceil(np.log10(num_steps + 1))) for k, tstep in enumerate(solution_e.TimestepValues): # plot the blue moving dot line.set_data( continuation_data[k, plot_columns["mu"]], continuation_data[k, plot_columns["energy"]], ) # Take screenshot. # For int formatting see # http://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros suffix = "%0*d.png" % (max_number_of_digits, int(tstep)) filenames = { "abs": os.path.join(cache_folder, "abs%s" % suffix), "arg": os.path.join(cache_folder, "arg%s" % suffix), } view.ViewTime = tstep _take_screenshots(data_representation, filenames) # autocrop image _autocrop(filenames["abs"]) _autocrop(filenames["arg"]) # Plot abs. fig.add_subplot(1, 3, 1) pp.imshow(mpimg.imread(filenames["abs"]), cmap=cm.gray, vmin=0.0, vmax=1.0) # set colorbar if k == 0: pp.colorbar(ticks=[0, 0.5, 1], shrink=0.6) # Plot arg. fig.add_subplot(1, 3, 2) pp.imshow(mpimg.imread(filenames["arg"]), cmap=cm.hsv, vmin=-np.pi, vmax=np.pi) # set colorbar if k == 0: cbar1 = pp.colorbar(ticks=[-np.pi, 0, np.pi], shrink=0.6) cbar1.set_ticklabels(["$-\pi$", "$0$", "$\pi$"]) # draw the thing # pp.draw() # pp.show() patch_file = os.path.join(cache_folder, "patched%s" % suffix) pp.savefig(patch_file, format="png") # pp.savefig(p.stdin, format='jpg') print("%d / %d" % (k, num_steps)) return
def __init__(self, filepath='.'): self.filepath = filepath self.time = 0.0 self.surfaceColorMode = 0 # Local range self.subSurfaceColorMode = 0 # Local range # Surface View self.viewSurface = simple.CreateRenderView(True) self.viewSurface.EnableRenderOnInteraction = 0 self.viewSurface.OrientationAxesVisibility = 0 self.viewSurface.Background = [0.9, 0.9, 0.9] self.viewSurface.InteractionMode = '2D' self.viewSurface.CameraParallelProjection = 1 # SubSurface view self.viewSubSurface = simple.CreateRenderView(True) self.viewSubSurface.EnableRenderOnInteraction = 0 self.viewSubSurface.OrientationAxesVisibility = 0 self.viewSubSurface.Background = [0.9, 0.9, 0.9] self.viewSubSurface.InteractionMode = '2D' self.viewSubSurface.CameraParallelProjection = 1 # Read dataset self.reader = simple.ParFlowReader(FileName=filepath, DeflectTerrain=1) self.readerSurface = simple.OutputPort(self.reader, 1) self.readerSubSurface = simple.OutputPort(self.reader, 0) # Water table depth self.waterTableDepth = simple.WaterTableDepth( Subsurface=self.readerSubSurface, Surface=self.readerSurface) self.cellCenter = simple.CellCenters(Input=self.waterTableDepth) self.wtdVectCalc = simple.Calculator(Input=self.cellCenter) self.wtdVectCalc.ResultArrayName = 'wtdVect' self.wtdVectCalc.Function = 'iHat + jHat + kHat * water table depth' self.waterTableDepthGlyph = simple.Glyph( Input=self.wtdVectCalc, GlyphType='Cylinder', ScaleFactor=500, GlyphMode='All Points', GlyphTransform='Transform2', ScaleArray=['POINTS', 'wtdVect'], VectorScaleMode='Scale by Components', ) self.waterTableDepthGlyph.GlyphTransform.Rotate = [90.0, 0.0, 0.0] self.waterTableDepthGlyph.GlyphType.Resolution = 12 self.waterTableDepthGlyph.GlyphType.Radius = 0.25 self.waterTableRepresentation = simple.Show(self.waterTableDepthGlyph, self.viewSubSurface) self.waterTableRepresentation.Visibility = 0 # Water balance self.waterBalance = simple.WaterBalance( Subsurface=self.readerSubSurface, Surface=self.readerSurface) self.waterBalanceOverTime = simple.PlotGlobalVariablesOverTime( Input=self.waterBalance) # Surface representation self.surfaceRepresentation = simple.Show(self.readerSurface, self.viewSurface) self.surfaceRepresentation.SetScalarBarVisibility( self.viewSurface, True) # SubSurface representation + slice extract self.reader.UpdatePipeline() self.voi = self.reader.GetClientSideObject().GetOutputDataObject( 0).GetExtent() self.extractSubset = simple.ExtractSubset(Input=self.readerSubSurface) self.subSurfaceRepresentation = simple.Show(self.extractSubset, self.viewSubSurface) self.subSurfaceRepresentation.Representation = 'Surface' # Reset camera + center of rotation simple.Render(self.viewSurface) simple.ResetCamera(self.viewSurface) self.viewSurface.CenterOfRotation = self.viewSurface.CameraFocalPoint simple.Render(self.viewSubSurface) simple.ResetCamera(self.viewSubSurface) self.viewSubSurface.CenterOfRotation = self.viewSubSurface.CameraFocalPoint # Time management self.animationScene = simple.GetAnimationScene() self.animationScene.UpdateAnimationUsingDataTimeSteps()
ordinalRange = [0, NUM_POINTS - 1] ordinalArray = vtkDoubleArray() ordinalArray.SetName(ordinalArrayName) ordinalArray.SetNumberOfComponents(1) ordinalArray.SetNumberOfTuples(NUM_POINTS) for i in xrange(NUM_POINTS): ordinalArray.SetTuple1(i, i) pointData.AddArray(ordinalArray) source = simple.TrivialProducer() source.GetClientSideObject().SetOutput(polyData) # create a calculator to compute distance calculator1 = simple.Calculator(Input=source) calculator1.ResultArrayName = 'Distance' calculator1.Function = 'mag(coords)' # create another calculator to compute inverse distance calculator2 = simple.Calculator(Input=calculator1) calculator2.ResultArrayName = 'Inverse Distance' calculator2.Function = '%s-Distance' % str(NUM_POINTS - 1) # Get the representation rep = simple.Show(calculator2) # Set up coloring by one array rep.Representation = 'Point Gaussian' simple.ColorBy(rep, ('POINTS', 'Ordinal')) vtkSMPVRepresentationProxy.RescaleTransferFunctionToDataRange(
PF.Script = Script01 Simple.Show(PF) #-------------------------------------------------------------------------||---# #-------------------------------------------------------------------------||---# Coords = Read_dat("XXX_COORDINATES.alya") for coord in Coords: print coord, Simple.SetActiveSource(InputData) Slice01 = Simple.Slice( guiName="Slice2", SliceOffsetValues=[0.0], SliceType="Plane" ) Slice01.SliceType.Origin = coord Slice01.SliceType.Normal = [0.0, 0.0, 1.0] Simple.SetActiveSource(Slice01) Calculator01 = Simple.Calculator(guiName="Calculator1", Function='VELOC_Z*TEMPE', ResultArrayName='UT') Simple.SetActiveSource(Calculator01) IntegrateVariables01 = Simple.IntegrateVariables( guiName="IntegrateVariables2" ) Simple.SetActiveSource(IntegrateVariables01) PF = Simple.ProgrammableFilter() PF.Script = Script02 Simple.Show(PF) #print "ok!" #-------------------------------------------------------------------------||---# #-------------------------------------------------------------------------||---# #-------------------------------------------------------------------------||---#
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)
# ----------------------------------------------------------------------------- # User configuration # ----------------------------------------------------------------------------- outputDir = '/Users/seb/Desktop/float-image/' # ----------------------------------------------------------------------------- from paraview import simple from paraview.web.dataset_builder import * # ----------------------------------------------------------------------------- # VTK Pipeline creation # ----------------------------------------------------------------------------- wavelet = simple.Wavelet() calc = simple.Calculator() calc.Function = 'coordsX' calc.ResultArrayName = 'x' contour = simple.Contour(PointMergeMethod="Uniform Binning", ComputeScalars=1, ComputeNormals=1, Isosurfaces=157.09, ContourBy=['POINTS', 'RTData']) clip = simple.Clip() clip.ClipType.Normal = [0.0, 0.0, -1.0] # ----------------------------------------------------------------------------- # Data To Export # ----------------------------------------------------------------------------- layerMesh = { 'core1': False,
class Pipeline: # Read coastlines clines = pvs.XMLPolyDataReader( FileName="Coastlines_Los_Alamos.vtp") # Scale data to radius of the sphere clinesscaled = pvs.Calculator(Input=clines) clinesscaled.CoordinateResults = 1 clinesscaled.Function = '%i*coords' % sphere_radius # 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=800, height=800, 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 sphereDisplay.Opacity = 1.0 # Show coastlines sphereDisplay = pvs.Show(clinesscaled, renderView) sphereDisplay.Representation = 'Surface' sphereDisplay.Opacity = 1.0