def __init__(self, file_name_generator, data, contourBy, scalarRange=[0.0, 1.0], steps=10): """ file_name_generator: the file name generator to use. Need to have ['contourBy', 'contourValue'] as keys. """ self.file_name_generator = file_name_generator self.contour = simple.Contour(Input=data, ContourBy=contourBy[1], ComputeScalars=1) if contourBy[0] == 'POINT_DATA': self.data_range = data.GetPointDataInformation().GetArray( contourBy[1]).GetRange() else: self.data_range = data.GetCellDataInformation().GetArray( contourBy[1]).GetRange() self.scalar_origin = scalarRange[0] self.scalar_incr = (scalarRange[1] - scalarRange[0]) / float(steps) self.number_of_steps = steps self.current_step = 0 # Update file name pattern self.file_name_generator.update_active_arguments( contourBy=contourBy[1]) self.file_name_generator.update_active_arguments( contourValue=self.scalar_origin) self.file_name_generator.update_label_arguments( contourValue=str(contourBy[1]))
def run(filename=None): """Create a dummy pipeline and save the coprocessing state in the filename specified, if any, else dumps it out on stdout.""" from paraview import simple, servermanager simple.LoadDistributedPlugin("CatalystScriptGeneratorPlugin") wavelet = simple.Wavelet(registrationName="Wavelet1") contour = simple.Contour() display = simple.Show() view = simple.Render() # create a new 'Parallel PolyData Writer' parallelPolyDataWriter0 = simple.ParallelPolyDataWriter() viewname = servermanager.ProxyManager().GetProxyName("views", view.SMProxy) script = DumpPipeline( export_rendering=True, simulation_input_map={"Wavelet1": "input"}, screenshot_info={viewname: ['image.png', '1', '1', '2', '400', '400']}) if filename: f = open(filename, "w") f.write(script) f.close() else: print "# *** Generated Script Begin ***" print script print "# *** Generated Script End ***"
def calc_surf_to_vol(filename, arr_name, sample_rate): import paraview.simple as ps import numpy as np import paraview as pv from vtk.util.numpy_support import vtk_to_numpy # have paraview open the vtk data file reader = ps.OpenDataFile(filename) sys_data = pv.servermanager.Fetch(reader) nx, ny, nz = sys_data.GetDimensions() dx, dy, dz = sys_data.GetSpacing() # downsample the data (makes for a smoother contour surface) ds = ps.ExtractSubset() ds.SampleRateI = sample_rate ds.SampleRateJ = sample_rate ds.SampleRateK = sample_rate ds.VOI[1] = nx - 1 ds.VOI[3] = ny - 1 ds.VOI[4] = 1 # leave off bottom layer for CHBDThinFilm ds.VOI[5] = nz - 2 # leave off top layer for CHBDThinFilm ds.IncludeBoundary = 1 ds.UpdatePipeline() # have paraview apply a contour surface at a concentration value of cont_val contour = ps.Contour() cont_val = 0.5 # this might change depending on order parameter contour.ContourBy = ['POINTS', arr_name] # Viz is the name of the vtk array contour.Isosurfaces = [cont_val] contour.SetPropertyWithName('ComputeNormals', 0) contour.UpdatePipeline() # integrate the surface area and curvature summed_curv = ps.IntegrateVariables() summed_curv_data = pv.servermanager.Fetch(summed_curv) surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0) # calculate the surface area to volume ratio volume = nx * dx * ny * dy * nz * dz surf_to_vol = surf_area / volume # delete paraview sources and filters ps.Delete(reader) ps.Delete(ds) ps.Delete(contour) ps.Delete(summed_curv) del (sys_data) del (summed_curv_data) return surf_to_vol, surf_area, volume
def run(filename=None): """Create a dummy pipeline and save the coprocessing state in the filename specified, if any, else dumps it out on stdout.""" from paraview import simple, servermanager wavelet = simple.Wavelet(registrationName="Wavelet1") contour = simple.Contour() script = DumpCoProcessingScript(export_rendering=False, simulation_input_map={"Wavelet1": "input"}, screenshot_info={}, rescale_data_range=True, enable_live_viz=True, filename=filename) if not filename: print "# *** Generated Script Begin ***" print script print "# *** Generated Script End ***"
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()
def test2(): w = simple.Wavelet() c = simple.Contour(ComputeScalars=1, Isosurfaces=range(50, 250, 10)) r = simple.Show(c) lut = simple.GetLookupTableForArray("RTData", 1, RGBPoints=[ 43.34006881713867, 0.23, 0.299, 0.754, 160.01158714294434, 0.865, 0.865, 0.865, 276.68310546875, 0.706, 0.016, 0.15 ]) r.LookupTable = lut r.ColorArrayName = ('POINT_DATA', 'RTData') view = simple.Render() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/z', 'w_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [0, 0, 1], [10, 20]) exp.UpdatePipeline() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/y', 'cone_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [0, 1, 0], [10, 20]) exp.UpdatePipeline() exp = ThreeSixtyImageStackExporter( FileNameGenerator('/tmp/x', 'cone_{theta}_{phi}.jpg'), view, [0, 0, 0], 100, [1, 0, 0], [10, 20]) exp.UpdatePipeline() simple.ResetCamera() simple.Hide(c) slice = SliceExplorer( FileNameGenerator('/tmp/slice', 'w_{sliceColor}_{slicePosition}.jpg'), view, w, {"RTData": { "lut": lut, "type": 'POINT_DATA' }}, 50, [0, 1, 0]) slice.UpdatePipeline()
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'
for yMag in (18, 36, 72): for zMag in (5, 10, 20): fileNameTime = currentDir + "/wavelet_{:0d}_{:0d}.tvtp".format ( yMag, zMag) fTime = open(fileNameTime, "w"); fEnsemble.write ("{:d},{:d},{:s}\n".format(yMag, zMag, fileNameTime)) for step in range(numSteps): print "Timestep ", step wavelet = pvsimple.Wavelet() wavelet.Maximum = 300+50*math.sin(step * 2 * 3.1415927 / 10) wavelet.YMag = yMag wavelet.ZMag = zMag contour = pvsimple.Contour(guiName="Contour", Isosurfaces=[230.0], ContourBy=['RTData'], PointMergeMethod="Uniform Binning" ) fileName = currentDir + "/wavelet_{:0d}_{:0d}_{:0d}.vtp".format ( yMag, zMag, step) writer = pvsimple.XMLPolyDataWriter(Input = contour, FileName=fileName) writer.UpdatePipeline() pvsimple.Show() pvsimple.Render() pvsimple.Delete(wavelet) pvsimple.Delete(contour) pvsimple.Delete(writer) wavelet = None
'Pres': { 'location': 'POINT_DATA' }, 'Temp': { 'location': 'POINT_DATA' } } }, { 'parent': 'Contours', 'name': 'AsH3 0.1', 'source': simple.Contour(Input=reader, PointMergeMethod="Uniform Binning", ContourBy='AsH3', Isosurfaces=[0.1], ComputeScalars=1), 'colors': { 'AsH3': { 'constant': 0.1 }, 'Pres': { 'location': 'POINT_DATA' }, 'Temp': { 'location': 'POINT_DATA' } } }, { 'parent':
cinema.CompositeImageExporter.get_data_type()) fng = analysis.get_file_name_generator("composite") # Create pipeline to compose contour_values = [64.0, 90.6, 117.2, 143.8, 170.4, 197.0, 223.6, 250.2] color_type = [('POINT_DATA', "RTData")] luts = {"RTData": lut} filters = [data_to_explore] filters_description = [{'name': 'Wavelet'}] color_by = [color_type] for iso_value in contour_values: filters.append( simple.Contour(Input=data_to_explore, PointMergeMethod="Uniform Binning", ContourBy=['POINTS', 'RTData'], Isosurfaces=[iso_value], ComputeScalars=1)) color_by.append(color_type) filters_description.append({'name': 'iso=%s' % str(iso_value)}) # Data exploration ------------------------------------------------------------ camera_handler = cinema.ThreeSixtyCameraHandler( fng, None, [float(r) for r in range(0, 360, 72)], [float(r) for r in range(-60, 61, 45)], center_of_rotation, rotation_axis, distance) exporter = cinema.CompositeImageExporter(fng, filters, color_by, luts, camera_handler, [400, 400], filters_description, 0, 0) exporter.set_analysis(analysis) exporter.UpdatePipeline()
def test_composite(self): pv.Connect() # get a new context like a normal script would print "\nTEST_COMPOSITE" # set up some processing task view_proxy = pv.CreateRenderView() view_proxy.OrientationAxesVisibility = 0 s = pv.Wavelet() contour = pv.Contour(Input=s, ContourBy='RTData', ComputeScalars=1) sliceRep = pv.Show(contour) # make or open a cinema data store to put results in fname = "/tmp/test_pv_composite/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'composite-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.1'}) cs.filename_pattern = "results.png" cs.add_parameter( "phi", store.make_parameter('phi', [90, 120, 140])) cs.add_parameter( "theta", store.make_parameter('theta', [-90, -30, 30, 90])) cs.add_layer( "vis", store.make_parameter("vis", ['contour'])) contours = [50, 100, 150, 200] cs.add_control("isoval", store.make_parameter('isoval', contours)) cs.assign_parameter_dependence("isoval", "vis", ['contour']) cs.add_field("color", store.make_field('color', {'white': 'rgb', 'depth': 'depth', 'lum': 'luminance', 'RTData_1': 'lut'},), "isoval", contours) # associate control points with parameters of the data store cam = pv_explorers.Camera([0, 0, 0], [0, 1, 0], 75.0, view_proxy) showcontour = pv_explorers.SourceProxyInLayer("contour", sliceRep, contour) layertrack = explorers.Layer("vis", [showcontour]) filt = pv_explorers.Contour("isoval", contour) # additional specification necessary for the color field colorChoice = pv_explorers.ColorList() colorChoice.AddSolidColor('white', [1, 1, 1]) colorChoice.AddLUT('POINTS', 'RTData_1', 'X') colorChoice.AddDepth('depth') colorChoice.AddLuminance('lum') col = pv_explorers.Color("color", colorChoice, sliceRep) paramNames = ["phi", "theta", "vis", "isoval", "color"] trackList = [cam, layertrack, filt, col] e = pv_explorers.ImageExplorer(cs, paramNames, trackList, view_proxy) # run through all parameter combinations and put data into the store e.explore() # Reproduce an entry and compare vs. loaded # First set the parameters to reproduce cam.execute(store.Document({'theta': 30, 'phi': 140})) filt.execute(store.Document({'isoval': 100})) col.execute(store.Document({'color': 'RTData_1'})) imageslice = ch.pvRenderToArray(view_proxy) # Now load the corresponding cs2 = file_store.FileStore(fname) cs2.load() docs = [] for doc in cs2.find({'theta': 30, 'phi': 140, 'isoval': 100, 'color': 'RTData_1'}): docs.append(doc.data) # compare the two l2error = ch.compare_l2(imageslice, docs[0]) ncc = ch.compare_ncc(imageslice, docs[0]) success = (l2error < 1.0) and (ncc > 0.99) if not success: print "\n l2-error = ", l2error, " ; ncc = ", ncc, "\n" self.assertTrue(success) pv.Disconnect() # using a dedicated server state for each test
# ----------------------------------------------------------------------------- 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, 'core2': True, 'core3': True, 'core4': True, 'core5': True
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")
def toggleTankGeometry(self): self.printDebug() if not self.tankGeometryInit: # create a new 'Contour' self.contour2 = simple.Contour(Input=self.caseData) self.contour2.PointMergeMethod = 'Uniform Binning' # Properties modified on self.contour2 self.contour2.ContourBy = ['POINTS', 'wall_shear'] self.contour2.Isosurfaces = [0.0002] # show data in view self.contour2Display = simple.Show(self.contour2, self.renderView) # trace defaults for the display properties. self.contour2Display.Representation = 'Surface' self.contour2Display.ColorArrayName = [None, ''] self.contour2Display.OSPRayScaleFunction = 'PiecewiseFunction' self.contour2Display.SelectOrientationVectors = 'None' self.contour2Display.ScaleFactor = -2.0000000000000002e+298 self.contour2Display.SelectScaleArray = 'None' self.contour2Display.GlyphType = 'Arrow' self.contour2Display.GlyphTableIndexArray = 'None' self.contour2Display.GaussianRadius = -1.0000000000000001e+298 self.contour2Display.SetScaleArray = [None, ''] self.contour2Display.ScaleTransferFunction = 'PiecewiseFunction' self.contour2Display.OpacityArray = [None, ''] self.contour2Display.OpacityTransferFunction = 'PiecewiseFunction' self.contour2Display.DataAxesGrid = 'GridAxesRepresentation' self.contour2Display.SelectionCellLabelFontFile = '' self.contour2Display.SelectionPointLabelFontFile = '' self.contour2Display.PolarAxes = 'PolarAxesRepresentation' # init the 'GridAxesRepresentation' selected for 'DataAxesGrid' self.contour2Display.DataAxesGrid.XTitleFontFile = '' self.contour2Display.DataAxesGrid.YTitleFontFile = '' self.contour2Display.DataAxesGrid.ZTitleFontFile = '' self.contour2Display.DataAxesGrid.XLabelFontFile = '' self.contour2Display.DataAxesGrid.YLabelFontFile = '' self.contour2Display.DataAxesGrid.ZLabelFontFile = '' # init the 'PolarAxesRepresentation' selected for 'PolarAxes' self.contour2Display.PolarAxes.PolarAxisTitleFontFile = '' self.contour2Display.PolarAxes.PolarAxisLabelFontFile = '' self.contour2Display.PolarAxes.LastRadialAxisTextFontFile = '' self.contour2Display.PolarAxes.SecondaryRadialAxesTextFontFile = '' # Properties modified on contour2Display self.contour2Display.Opacity = 0.1 # change solid color self.contour2Display.DiffuseColor = [0.0, 0.5, 0.5] self.tankGeometryInit = True self.tankGeometryShown = True else: if self.tankGeometryShown: self.contour2Display = simple.Hide(self.contour2, self.renderView) self.tankGeometryShown = False else: self.contour2Display = simple.Show(self.contour2, self.renderView) self.tankGeometryShown = True self.renderView.Update()
import paraview.simple as pvs volume = GetActiveSource() colors = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75], [1.0, 1.0, 1.0], [0.5, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 0.5, 0.0], [1.0, 1.0, 0.0], [0.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.5, 0.5], [0.0, 1.0, 1.0], [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], [0.5, 0.0, 0.5]] #92 # values = [161.7609405518, 4819.0717773438, 5223.9609375, 12765.666015625, 15339.908203125, 16325.0751953125, 16970.48046875, 17532.744140625, 17930.564453125, 18244.109375, 18526.46875, 18800.091796875, 19054.736328125, 19320.5625, 19609.44921875, 19954.4765625, 21665.986328125] #333 values = [ 161.7609405518, 4910.9946289063, 5487.8041992188, 13664.4931640625, 15643.7978515625, 16500.958984375, 17210.8671875, 17694.396484375, 18051.37890625, 18352.3203125, 18611.689453125, 18870.3671875, 19126.1953125, 19370.037109375, 19641.4453125, 20000.75390625, 21665.986328125 ] #20 # values = [161.7609405518, 4550.8369140625, 5410.4838867188, 12598.25390625, 15168.3115234375, 16173.8984375, 16878.943359375, 17454.517578125, 17870.970703125, 18193.302734375, 18486.205078125, 18761.873046875, 19028.765625, 19292.73828125, 19588.91015625, 19915.8359375, 21665.986328125] rMax = len(values) - 1 for i in range(0, rMax): print i contour = pvs.Contour(Input=volume) contour.Isosurfaces = [values[i]] rep = GetDisplayProperties(contour) rep.DiffuseColor = colors[i % len(colors)]
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 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()")
def execute(self): self.cdms_variables = self.forceGetInputListFromPort('cdms_variable') for cdms_var in self.cdms_variables: #// Get the min and max to draw default contours min = cdms_var.var.min() max = cdms_var.var.max() reader = PVCDMSReader() time_values = [None, 1, True] image_data = reader.convert(cdms_var, time=time_values) #// Make white box filter so we can work at proxy level ProgrammableSource1 = pvsp.ProgrammableSource() #// Get a hole of the vtk level filter it controls ps = ProgrammableSource1.GetClientSideObject() #// Give it some data (ie the imagedata) ps.myid = image_data ProgrammableSource1.OutputDataSetType = 'vtkImageData' ProgrammableSource1.PythonPath = '' #// Make the scripts that it runs in pipeline RI and RD passes ProgrammableSource1.ScriptRequestInformation = """ executive = self.GetExecutive() outInfo = executive.GetOutputInformation(0) extents = self.myid.GetExtent() spacing = self.myid.GetSpacing() outInfo.Set(executive.WHOLE_EXTENT(), extents[0], extents[1], extents[2], extents[3], extents[4], extents[5]) outInfo.Set(vtk.vtkDataObject.SPACING(), spacing[0], spacing[1], spacing[2]) dataType = 10 # VTK_FLOAT numberOfComponents = 1 vtk.vtkDataObject.SetPointDataActiveScalarInfo(outInfo, dataType, numberOfComponents)""" ProgrammableSource1.Script = """self.GetOutput().ShallowCopy(self.myid)""" ProgrammableSource1.UpdatePipeline() pvsp.SetActiveSource(ProgrammableSource1) self.contour_var_name = str(cdms_var.varname) #// If the data is three dimensional, then don't draw the background imagery #// since it may hide the contours if not reader.is_three_dimensional(cdms_var): data_rep = pvsp.Show(view=self.view) data_rep.LookupTable = pvsp.GetLookupTableForArray( self.contour_var_name, 1, NanColor=[0.25, 0.0, 0.0], RGBPoints=[ min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15 ], VectorMode='Magnitude', ColorSpace='Diverging', LockScalarRange=1) data_rep.ColorArrayName = self.contour_var_name try: contour = pvsp.Contour() pvsp.SetActiveSource(contour) contour.ContourBy = ['POINTS', self.contour_var_name] delta = (max - min) / 10.0 contours = self.forceGetInputListFromPort("contour_values") if (len(contours) and contours): self.contour_values = [ float(d) for d in contours[0].split(',') ] # if( (self.contour_values == None) or (len(self.contour_values) == 0) ): else: self.contour_values = [(x * delta + min) for x in range(10)] functions = [] functions.append(("contour_values", [str(self.contour_values).strip('[]')])) self.update_functions('PVContourRepresentation', functions) contour.Isosurfaces = self.contour_values contour.ComputeScalars = 1 contour.ComputeNormals = 0 contour.UpdatePipeline() #// @todo: Remove hard-coded values contour_rep = pvsp.Show(view=self.view) contour_rep.Representation = 'Surface' if reader.is_three_dimensional(cdms_var): contour_rep.LookupTable = pvsp.GetLookupTableForArray( self.contour_var_name, 1, NanColor=[0.25, 0.0, 0.0], RGBPoints=[ min, 0.23, 0.299, 0.754, max, 0.706, 0.016, 0.15 ], VectorMode='Magnitude', ColorSpace='Diverging', LockScalarRange=1) contour_rep.ColorArrayName = self.contour_var_name else: contour_rep.DiffuseColor = [0.0, 0.0, 0.0] contour_rep.ColorArrayName = '' #// Scalar bar ScalarBarWidgetRepresentation1 = pvsp.CreateScalarBar( Title=self.contour_var_name, LabelFontSize=12, Enabled=1, TitleFontSize=12) self.view.Representations.append( ScalarBarWidgetRepresentation1) if not reader.is_three_dimensional(cdms_var): ScalarBarWidgetRepresentation1.LookupTable = data_rep.LookupTable else: ScalarBarWidgetRepresentation1.LookupTable = contour_rep.LookupTable except ValueError: print "[ERROR] Unable to generate contours. Please check your input values" except (RuntimeError, TypeError, NameError): print "[ERROR] Unknown error" pass
#from gen_data import * import paraview.simple as ps # reads in a vtk file test = ps.OpenDataFile("/home/james/projects/GPUE/py/test.vtk") c = ps.Contour(Input=test) c.Isosurfaces = [0.5] c.UpdatePipeline() ps.Show(test) ps.Show(c) ps.Render() ps.WriteImage("/home/james/projects/GPUE/py/check.png") print("done with test script")
'name': 'Earth', 'source': coreWithNormals, 'colors': { 'bottomDepth': { 'location': 'POINT_DATA', 'range': dataRanges['bottomDepth'] } } }, { 'parent': 'Temperatures', 'name': '5C', 'source': simple.Contour(Input=dataToPoints, PointMergeMethod="Uniform Binning", ContourBy='temperature', Isosurfaces=[5.0]), 'colors': { 'temperature': { 'constant': 5.0 }, 'salinity': { 'location': 'POINT_DATA', 'range': dataRanges['salinity'] } } }, { 'parent': 'Temperatures', 'name': '10C',
# save animation pv.SaveAnimation('/home/avmo/anim.avi', renderView1, ImageResolution=[1600, 496], FrameWindow=[0, 35]) # current camera placement for renderView1 renderView1.CameraPosition = [1.5707999467849731, 0.5, 4.076661427044123] renderView1.CameraFocalPoint = [1.5707999467849731, 0.5, 0.7853999733924866] renderView1.CameraParallelScale = 1.8259971497854517 # save screenshot pv.SaveScreenshot('/home/avmo/test.png', renderView1, ImageResolution=[1600, 499], OverrideColorPalette='WhiteBackground') # create a new 'Contour' contour1 = pv.Contour(Input=ablnek5000) contour1.ContourBy = ['POINTS', 'velocity_mag'] contour1.Isosurfaces = [0.5744097200222313] contour1.PointMergeMethod = 'Uniform Binning' # set active source pv.SetActiveSource(contour1) # show data in view contour1Display = pv.Show(contour1, renderView1) # trace defaults for the display properties. contour1Display.Representation = 'Surface' contour1Display.ColorArrayName = ['POINTS', 'velocity_mag'] contour1Display.LookupTable = velocity_magLUT contour1Display.OSPRayScaleArray = 'velocity_mag'
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) pv.Render(view=rvs) for key in contours: for x in contsphere_f[key]: pv.Show(x, view=rvs) for x in contsphere_b[key]: pv.Show(x, view=rvs) Bmag_contour[key] = pv.Contour(Input=Bmag_slice) Bmag_contour[key].ContourBy = ['POINTS', 'Bmag'] Bmag_contour[key].PointMergeMethod = 'Uniform Binning' Bmag_contour[key].Isosurfaces = contours[key] contour_disp = pv.Show(Bmag_contour[key], rvs) contour_disp.DiffuseColor = [0.0, 0.0, 0.0] pv.Render(view=rvs) pv.WriteImage("verification_" + str(key) + ".png", view=rvs) # Hide items not needed for next loop iteration pv.Hide(Bmag_contour[key], view=rvs) for x in contsphere_f[key]: pv.Hide(x, view=rvs) for x in contsphere_b[key]: pv.Hide(x, view=rvs) pv.Render(view=rvs)
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
def test_contour(self): pv.Connect() # using a dedicated server state for each test print "\nTEST_CONTOUR" # set up some processing task view_proxy = pv.CreateRenderView() view_proxy.OrientationAxesVisibility = 0 view_proxy.ViewSize = [1024, 768] s = pv.Wavelet() contour = pv.Contour(Input=s, ContourBy='RTData', ComputeScalars=1) sliceRep = pv.Show(contour) # make or open a cinema data store to put results in fname = "/tmp/test_pv_contour/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'parametric-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.0'}) cs.filename_pattern = "{phi}_{theta}_{contour}_{color}_contour.png" cs.add_parameter( "phi", store.make_parameter('phi', [90, 120, 140])) cs.add_parameter( "theta", store.make_parameter('theta', [-90, -30, 30, 90])) cs.add_parameter( "contour", store.make_parameter('contour', [50, 100, 150, 200])) cs.add_parameter( "color", store.make_parameter( 'color', ['white', 'RTData_1'], typechoice='list')) # associate control points with parameters of the data store cam = pv_explorers.Camera( [0, 0, 0], [0, 1, 0], 75.0, view_proxy) filt = pv_explorers.Contour("contour", contour) colorChoice = pv_explorers.ColorList() colorChoice.AddSolidColor('white', [1, 1, 1]) colorChoice.AddLUT('POINTS', 'RTData_1', 'X') col = pv_explorers.Color("color", colorChoice, sliceRep) params = ["phi", "theta", "contour", "color"] e = pv_explorers.ImageExplorer( cs, params, [cam, filt, col], view_proxy) # run through all parameter combinations and put data into the store e.explore() # Reproduce an entry and compare vs. loaded # First set the parameters to reproduce cam.execute(store.Document({'theta': 30, 'phi': 140})) filt.execute(store.Document({'contour': 100})) col.execute(store.Document({'color': 'RTData_1'})) imageslice = ch.pvRenderToArray(view_proxy) # Now load the corresponding cs2 = file_store.FileStore(fname) cs2.load() docs = [] for doc in cs2.find( {'theta': 30, 'phi': 140, 'contour': 100, 'color': 'RTData_1'}): docs.append(doc.data) # compare the two l2error = ch.compare_l2(imageslice, docs[0]) ncc = ch.compare_ncc(imageslice, docs[0]) success = (l2error < 1.0) and (ncc > 0.99) if not success: print "\n l2-error = ", l2error, " ; ncc = ", ncc, "\n" self.assertTrue(success) pv.Disconnect() # using a dedicated server state for each test
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] Bmag_slice2.SliceType.Normal = [0.0, 1.0, 0.0] contour1 = pv.Contour(Input=Bmag_slice) contour1.ContourBy = ['POINTS', 'Bmag'] contour1.Isosurfaces = [115, b_k1000] cont1disp = pv.Show(contour1, rvs) cont1disp.DiffuseColor = [0.0, 0.0, 0.0] contour2 = pv.Contour(Input=Bmag_slice2) contour2.ContourBy = ['POINTS', 'Bmag'] contour2.Isosurfaces = [115, b_k1000_d] cont2disp = pv.Show(contour2, rvs2) cont2disp.DiffuseColor = [0.0, 0.0, 0.0] contour3 = pv.Contour(Input=Bmag_slice) contour3.ContourBy = ['POINTS', 'Bmag'] contour3.Isosurfaces = [115, b_k1000_m] cont1disp = pv.Show(contour3, rvs3)
def get_curvatures(vtk_file, vtk_file_dir, output_file, output_file_dir, arr_name, sample_rate, gauss_filter, mean_filter): import paraview.simple as ps import numpy as np import paraview as pv from vtk.util.numpy_support import vtk_to_numpy # have paraview open the vtk data file reader = ps.OpenDataFile(vtk_file_dir + vtk_file) sys_data = pv.servermanager.Fetch(reader) nx, ny, nz = sys_data.GetDimensions() dx, dy, dz = sys_data.GetSpacing() # downsample the data (makes for a smoother contour surface) ds = ps.ExtractSubset(reader) ds.SampleRateI = sample_rate ds.SampleRateJ = sample_rate ds.SampleRateK = sample_rate ds.VOI[1] = nx - 1 ds.VOI[3] = ny - 1 ds.VOI[5] = nz - 1 ds.IncludeBoundary = 1 ds.UpdatePipeline() # have paraview apply a contour surface at a concentration value of cont_val contour = ps.Contour(ds) cont_val = 0.0 # this might change depending on order parameter contour.ContourBy = ['POINTS', arr_name] # Viz is the name of the vtk array contour.Isosurfaces = [cont_val] contour.SetPropertyWithName('ComputeNormals', 0) contour.UpdatePipeline() # have paraview calculate the curvature (default is Gaussian) curvature = ps.Curvature(contour) # filter the curvatures threshold = ps.Threshold(curvature) threshold.Scalars = ['POINTS', 'Gauss_Curvature'] threshold.ThresholdRange = [-gauss_filter, gauss_filter] threshold.AllScalars = 1 threshold.UpdatePipeline() gauss_data = pv.servermanager.Fetch(threshold) size_gauss = gauss_data.GetPointData().GetArray(0).GetSize() # convert vtk array to numpy array gauss_curv = vtk_to_numpy(gauss_data.GetPointData().GetArray(0)) # integrate the surface area and curvature summed_curv = ps.IntegrateVariables(threshold) summed_curv_data = pv.servermanager.Fetch(summed_curv) g_surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0) # have paraview recalculate the mean curvature curvature.SetPropertyWithName('CurvatureType', 'Mean') curvature.UpdatePipeline() threshold = ps.Threshold(curvature) threshold.Scalars = ['POINTS', 'Mean_Curvature'] threshold.ThresholdRange = [-mean_filter, mean_filter] threshold.UpdatePipeline() summed_curv = ps.IntegrateVariables(threshold) summed_curv.UpdatePipeline() summed_curv_data = pv.servermanager.Fetch(summed_curv) m_surf_area = summed_curv_data.GetCellData().GetArray(0).GetValue(0) mean_data = pv.servermanager.Fetch(threshold) # convert vtk array to numpy array mean_curv = vtk_to_numpy(mean_data.GetPointData().GetArray(0)) # calculate the surface area to volume ratio g_surf_to_vol = g_surf_area / (nx * dx * ny * dy * nz * dz) m_surf_to_vol = m_surf_area / (nx * dx * ny * dy * nz * dz) # calculate percent of data used in threshold curvature_data = pv.servermanager.Fetch(curvature) size_curv = curvature_data.GetPointData().GetArray(0).GetSize() # save the numpy arrays for later manipulation np.savez(output_file_dir + output_file, gauss_curv, mean_curv, g_surf_to_vol, g_surf_area, m_surf_to_vol, m_surf_area) # delete paraview sources and filters ps.Delete(summed_curv) ps.Delete(contour) ps.Delete(ds) ps.Delete(reader) del (sys_data) del (summed_curv_data) return 0
forward.DiffuseColor = [0.5, 0.0, 0.0] backward.DiffuseColor = [0., 0.0, 0.5] # Mark New Center (Should be B_min) new_center = fline.fieldLinePoints_f[0] print "New Center: ", new_center Bmag_calc = pv.Calculator(Input=t96_128_dp) 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 = pv.Contour(Input = Bmag_slice) Bmag_contour.ContourBy = ['POINTS', 'Bmag'] Bmag_contour.PointMergeMethod = 'Uniform Binning' # point = fline.get_location_for_RE(1.0) # # endPoint = pv.Sphere() # endPoint.Radius = 0.05 # endPoint.Center = point[0] # pv.Show(endPoint,rv) test_contour_list = [] test_points_b = [] test_points_f = [] test_disp_b = [] test_disp_f = []