def Contours(self, num, opacity=0.2): contour = vtk.vtkMarchingContourFilter() contour.SetInput(self.vtkgrid) r = max(abs(self.vmin), abs(self.vmax)) if num % 2 == 0 or self.vmin * self.vmax >= 0: contour.GenerateValues( num, (self.vmin + r / num, self.vmax - r / num)) elif num == 1: contour.SetValue(0, 0) else: r = r - r / num contour.GenerateValues(num, -r, r) contour.ComputeScalarsOn() contour.UseScalarTreeOn() contour.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(contour.GetOutput()) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) actor.GetProperty().SetLineWidth(3) return actor
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkMarchingContourFilter(), 'Processing.', ('vtkDataSet',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def Contours(self, num, opacity=0.2): """Create contours.""" contour = vtk.vtkMarchingContourFilter() contour.SetInput(self.vtkgrid[self.dim]) r = (self.vrange[1]-self.vrange[0]) / 2.0 / num if num == 1: contour.SetValue(0, 0) else: contour.GenerateValues( num, (self.vrange[0] + r, self.vrange[1] - r)) contour.ComputeScalarsOn() contour.UseScalarTreeOn() contour.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(contour.GetOutput()) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.SetLookupTable(self.lut) # bw contours are barely visible without this modification # also account for flip if not self.color: if self.flip: mapper.SetScalarRange(2*self.vmin-self.vmax, self.vmax) else: mapper.SetScalarRange(self.vmin, 2*self.vmax-self.vmin) else: mapper.SetScalarRange(self.vmin, self.vmax) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) actor.GetProperty().SetLineWidth(3) return actor
def __init__(self, renwin, data, isovalue, color=(0, 0.5, 0.75), rendering_type='surface'): self.renwin = renwin self.data = data self.iren = renwin.GetInteractor() self.renderer = renwin.GetRenderers().GetFirstRenderer() self.camera = self.renderer.GetActiveCamera() self.rendering_type = rendering_type # Among 'surface', 'wireframe', 'points' self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.iso.SetInput(self.data) else: self.iso.SetInputData(self.data) self.iso.SetValue(0, isovalue) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(self.iso.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(self.camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surf = vtk.vtkActor() self.surf.SetMapper(mapper) self.surf.GetProperty().SetColor(color) self.surf.PickableOff() if self.rendering_type == 'wireframe': self.surf.GetProperty().SetRepresentationToWireframe() elif self.rendering_type == 'surface': self.surf.GetProperty().SetRepresentationToSurface() elif self.rendering_type == 'points': self.surf.GetProperty().SetRepresentationToPoints() self.surf.GetProperty().SetPointSize(5) else: self.surf.GetProperty().SetRepresentationToWireframe() self.surf.GetProperty().SetInterpolationToGouraud() self.surf.GetProperty().SetSpecular(.4) self.surf.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surf) self.renwin.Render()
def draw_isosurface(self, data, rendtype, opacity, origin, spacing): self.image = self.array_to_3d_imagedata(data, spacing) isovalue = data.mean() mi, ma = data.min(), data.max() self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion()<6: self.iso.SetInput(self.image) else: self.iso.SetInputData(self.image) self.iso.SetValue(0,isovalue) self.depthSort = vtk.vtkDepthSortPolyData() self.depthSort.SetInputConnection(self.iso.GetOutputPort()) self.depthSort.SetDirectionToBackToFront() self.depthSort.SetVector(1, 1, 1) self.depthSort.SetCamera(self.camera) self.depthSort.SortScalarsOn() self.depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surface = vtk.vtkActor() self.surface.SetMapper(mapper) self.surface.GetProperty().SetColor((0,0.5,0.75)) self.surface.GetProperty().SetOpacity(opacity) self.surface.PickableOff() if rendtype=='wireframe': self.surface.GetProperty().SetRepresentationToWireframe() elif rendtype=='surface': self.surface.GetProperty().SetRepresentationToSurface() elif rendtype=='points': self.surface.GetProperty().SetRepresentationToPoints() self.surface.GetProperty().SetPointSize(5) else: self.surface.GetProperty().SetRepresentationToWireframe() self.surface.GetProperty().SetInterpolationToGouraud() self.surface.GetProperty().SetSpecular(.4) self.surface.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surface) self.surface.SetPosition(origin[0], origin[1], origin[2]) self.iren.Render() return mi, ma
def marching_cubes(image_data, contours, connectivity=False, path=None): """ """ if isinstance(image_data, VTKImage): info = image_data.information() importer = vtk.vtkImageImport() importer.SetDataScalarType(info.datatype) importer.SetNumberOfScalarComponents(1) importer.SetDataExtent(info.extent) importer.SetWholeExtent(info.extent) importer.SetDataOrigin(info.origin) importer.SetDataSpacing(info.spacing) size = len(image_data.flat) * image_data.dtype.itemsize array = image_data.flatten('F') vtk_array = numpy_support.numpy_to_vtk(array, 1, info.datatype) importer.CopyImportVoidPointer(vtk_array.GetVoidPointer(0), size) importer.Update() image_data = importer.GetOutput() if isinstance(contours, (int, float)): contours = (contours, ) contour = vtk.vtkMarchingContourFilter() contour.SetInputData(image_data) for i, value in enumerate(contours): contour.SetValue(0, value) contour.Update() poly_data = contour.GetOutput() if connectivity: connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(poly_data) connectivity.SetExtractionModeToLargestRegion() connectivity.Update() mapper = vtk.vtkGeometryFilter() mapper.SetInputData(connectivity.GetOutput()) mapper.Update() poly_data = mapper.GetOutput() if isinstance(path, str): writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(path) writer.SetInputData(poly_data) writer.Write() return poly_data
def load_maps(mol,rendmod,gfx,atomcol): mol.reader = vtk.vtkStructuredPointsReader() mol.reader.SetFileName(mol.mod.dfn) mol.reader.Update() #by calling Update() we read the file mol.iso = vtk.vtkMarchingContourFilter() mol.iso.UseScalarTreeOn() mol.iso.ComputeNormalsOn() mol.iso.SetInputConnection(mol.reader.GetOutputPort()) mol.iso.SetValue(0,mol.mod.isov*mol.mod.sigavg[0]+mol.mod.sigavg[1]) clean = vtk.vtkCleanPolyData() clean.SetInputConnection(mol.iso.GetOutputPort()) clean.ConvertStripsToPolysOn() smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInputConnection(clean.GetOutputPort()) smooth.BoundarySmoothingOn() smooth.GenerateErrorVectorsOn() smooth.GenerateErrorScalarsOn() smooth.NormalizeCoordinatesOn() smooth.NonManifoldSmoothingOn() smooth.FeatureEdgeSmoothingOn() smooth.SetEdgeAngle(90) smooth.SetFeatureAngle(90) smooth.Update() mol.mapper = vtk.vtkOpenGLPolyDataMapper() mol.mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here mol.mapper.ScalarVisibilityOff() mol.mapper.Update() mol.acteur= vtk.vtkOpenGLActor() mol.acteur.SetMapper(mol.mapper) mol.acteur.GetProperty().SetColor(mol.col) if rendmod==5: mol.acteur.GetProperty().SetRepresentationToSurface() elif rendmod==6: mol.acteur.GetProperty().SetRepresentationToWireframe() elif rendmod==7: mol.acteur.GetProperty().SetRepresentationToPoints() else : mol.acteur.GetProperty().SetRepresentationToSurface() mol.acteur.GetProperty().SetInterpolationToGouraud() mol.acteur.GetProperty().SetSpecular(.4) mol.acteur.GetProperty().SetSpecularPower(10) gfx.renderer.AddActor(mol.acteur) gfx.renwin.Render()
ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create pipeline # v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64,64) v16.GetOutput().SetOrigin(0.0,0.0,0.0) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") v16.SetImageRange(1,93) v16.SetDataSpacing(3.2,3.2,1.5) v16.Update() iso = vtk.vtkMarchingContourFilter() iso.SetInputConnection(v16.GetOutputPort()) iso.SetValue(0,1125) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(antique_white) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(v16.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff()
def plot_fermisurface(data, equivalences, ebands, mu, nworkers=1): """Launch an interactive VTK representation of the Fermi surface. Make sure to check the module-level variable "available" before calling this function. Args: data: a DFTData object equivalences: list of k-point equivalence classes ebands: eband: (nbands, nkpoints) array with the band energies mu: initial value of the energy at which the surface will be plotted, with respect to data.fermi. This can later be changed by the user using an interactive slider. nworkers: number of worker processes to use for the band reconstruction Returns: None. """ lattvec = data.get_lattvec() rlattvec = 2. * np.pi * la.inv(lattvec).T # Obtain the first Brillouin zone as the Voronoi polyhedron of Gamma points = [] for ijk0 in itertools.product(range(5), repeat=3): ijk = [i if i <= 2 else i - 5 for i in ijk0] points.append(rlattvec @ np.array(ijk)) voronoi = scipy.spatial.Voronoi(points) region_index = voronoi.point_region[0] vertex_indices = voronoi.regions[region_index] vertices = voronoi.vertices[vertex_indices, :] # Compute a center and an outward-pointing normal for each of the facets # of the BZ facets = [] for ridge in voronoi.ridge_vertices: if all(i in vertex_indices for i in ridge): facets.append(ridge) centers = [] normals = [] for f in facets: corners = np.array([voronoi.vertices[i, :] for i in f]) center = corners.mean(axis=0) v1 = corners[0, :] for i in range(1, corners.shape[0]): v2 = corners[i, :] prod = np.cross(v1 - center, v2 - center) if not np.allclose(prod, 0.): break if np.dot(center, prod) < 0.: prod = -prod centers.append(center) normals.append(prod) # Get the extent of the regular grid in reciprocal space hdims = np.max(np.abs(np.vstack(equivalences)), axis=0) dims = 2 * hdims + 1 class PointPickerInteractorStyle(vtk.vtkInteractorStyleTrackballCamera): """Custom interaction style enabling the user to pick points on the screen. """ def __init__(self, parent=None): """Simple constructor that adds an observer to the middle mouse button press. """ self.AddObserver("MiddleButtonPressEvent", self.pick_point) def pick_point(self, obj, event): """Get the coordinates of the point selected with the middle mouse button, find the nearest data point, and print its direct coordinates. """ interactor = self.GetInteractor() picker = interactor.GetPicker() pos = interactor.GetEventPosition() picker.Pick( pos[0], pos[1], 0, interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()) picked = np.array(picker.GetPickPosition()) # Move the sphere to the new coordinates and make it visible sphere.SetCenter(*picked.tolist()) sphere_actor.VisibilityOn() picked = la.solve(rlattvec, picked) print("Point picked:", picked) self.OnMiddleButtonDown() # Create the VTK representation of the grid sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions(*dims) spoints = vtk.vtkPoints() for ijk0 in itertools.product(*(range(0, d) for d in dims)): ijk = [ ijk0[i] if ijk0[i] <= hdims[i] else ijk0[i] - dims[i] for i in range(len(dims)) ] abc = np.array(ijk, dtype=np.float64) / np.array(dims) xyz = rlattvec @ abc spoints.InsertNextPoint(*xyz.tolist()) sgrid.SetPoints(spoints) # Find the shortest distance between points to compute a good # radius for the selector sphere later. dmin = np.infty for i in range(3): abc = np.zeros(3) abc[i] = 1. / dims[i] xyz = rlattvec @ abc dmin = min(dmin, la.norm(xyz)) ebands -= data.fermi emax = ebands.max(axis=1) emin = ebands.min(axis=1) # Remove all points outside the BZ for i, ijk0 in enumerate(itertools.product(*(range(0, d) for d in dims))): ijk = [ ijk0[j] if ijk0[j] <= hdims[j] else ijk0[j] - dims[j] for j in range(len(dims)) ] abc = np.array(ijk, dtype=np.float64) / np.array(dims) xyz = rlattvec @ abc for c, n in zip(centers, normals): if np.dot(xyz - c, n) > 0.: ebands[:, i] = np.nan break # Create a 2D chemical potential slider slider = vtk.vtkSliderRepresentation2D() slider.SetMinimumValue(emin.min()) slider.SetMaximumValue(emax.max()) slider.SetValue(mu) slider.SetTitleText("Chemical potential") slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() slider.GetPoint1Coordinate().SetValue(0.1, 0.9) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() slider.GetPoint2Coordinate().SetValue(0.9, 0.9) slider.GetTubeProperty().SetColor(*colors.hex2color("#2e3436")) slider.GetSliderProperty().SetColor(*colors.hex2color("#a40000")) slider.GetCapProperty().SetColor(*colors.hex2color("#babdb6")) slider.GetSelectedProperty().SetColor(*colors.hex2color("#a40000")) slider.GetTitleProperty().SetColor(*colors.hex2color("#2e3436")) # Find all the isosurfaces with energy equal to the threshold allcontours = [] with TimerContext() as timer: fermiactors = [] for band in ebands: sgridp = vtk.vtkStructuredGrid() sgridp.DeepCopy(sgrid) # Feed the energies to VTK scalar = vtk.vtkFloatArray() for i in band: scalar.InsertNextValue(i) sgridp.GetPointData().SetScalars(scalar) # Estimate the isosurfaces contours = vtk.vtkMarchingContourFilter() contours.SetInputData(sgridp) contours.UseScalarTreeOn() contours.SetValue(0, mu) contours.ComputeNormalsOff() contours.ComputeGradientsOff() allcontours.append(contours) # Use vtkStrippers to plot the surfaces faster stripper = vtk.vtkStripper() stripper.SetInputConnection(contours.GetOutputPort()) # Compute the normals to the surfaces to obtain better lighting normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(stripper.GetOutputPort()) normals.ComputeCellNormalsOn() normals.ComputePointNormalsOn() # Create a mapper and an actor for the surfaces mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(normals.GetOutputPort()) mapper.ScalarVisibilityOff() fermiactors.append(vtk.vtkActor()) fermiactors[-1].SetMapper(mapper) fermiactors[-1].GetProperty().SetColor(*colors.hex2color( "#a40000")) deltat = timer.get_deltat() info("building the surfaces took {:.3g} s".format(deltat)) # Represent the BZ as a polyhedron in VTK points = vtk.vtkPoints() for v in voronoi.vertices: points.InsertNextPoint(*v) fids = vtk.vtkIdList() fids.InsertNextId(len(facets)) for f in facets: fids.InsertNextId(len(f)) for i in f: fids.InsertNextId(i) fgrid = vtk.vtkUnstructuredGrid() fgrid.SetPoints(points) fgrid.InsertNextCell(vtk.VTK_POLYHEDRON, fids) # Create an actor and a mapper for the BZ mapper = vtk.vtkDataSetMapper() mapper.SetInputData(fgrid) bzactor = vtk.vtkActor() bzactor.SetMapper(mapper) bzactor.GetProperty().SetColor(*colors.hex2color("#204a87")) bzactor.GetProperty().SetOpacity(0.2) # Create a visual representation of the selected point, and hide # it for the time being. sphere = vtk.vtkSphereSource() sphere.SetRadius(dmin / 2.) sphere_mapper = vtk.vtkPolyDataMapper() sphere_mapper.SetInputConnection(sphere.GetOutputPort()) sphere_mapper.ScalarVisibilityOff() sphere_actor = vtk.vtkActor() sphere_actor.SetMapper(sphere_mapper) sphere_actor.GetProperty().SetColor(*colors.hex2color("#f57900")) sphere_actor.VisibilityOff() # Create a VTK window and other elements of an interactive scene renderer = vtk.vtkRenderer() renderer.AddActor(bzactor) renderer.AddActor(sphere_actor) for f in fermiactors: renderer.AddActor(f) renderer.ResetCamera() renderer.GetActiveCamera().Zoom(5.) renderer.SetBackground(1., 1., 1.) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(PointPickerInteractorStyle()) interactor.SetRenderWindow(window) # Add a set of axes axes = vtk.vtkAxesActor() assembly = vtk.vtkPropAssembly() assembly.AddPart(axes) marker = vtk.vtkOrientationMarkerWidget() marker.SetOrientationMarker(assembly) marker.SetInteractor(interactor) marker.SetEnabled(1) marker.InteractiveOff() def callback(obj, ev): """Update the isosurface with a new value""" mu = obj.GetRepresentation().GetValue() for e, E, c, a in zip(emin, emax, allcontours, fermiactors): visible = e <= mu and E >= mu a.SetVisibility(visible) if visible: c.SetValue(0, mu) # Add the slider widget widget = vtk.vtkSliderWidget() widget.SetInteractor(interactor) widget.SetRepresentation(slider) widget.SetAnimationModeToJump() widget.EnabledOn() widget.AddObserver(vtk.vtkCommand.InteractionEvent, callback) # Launch the visualization interactor.Initialize() window.Render() interactor.Start()
def display_mod(self,mod): self.renderer.RemoveAllViewProps() if mod.type == 'mol': if mod.dspmodtype == 'CA': reader = vtk.vtkPDBReader() reader.SetFileName(mod.dfn) reader.SetHBScale(0) reader.SetBScale(4.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) mapper.SetScalarModeToDefault() acteur = vtk.vtkActor() acteur.SetMapper(mapper) else: #all atoms or backbone case reader = vtk.vtkPDBReader() reader.SetFileName(mod.dfn) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) mapper.SetScalarModeToDefault() acteur = vtk.vtkActor() acteur.SetMapper(mapper) self.camera.SetFocalPoint(0, 0, 0) self.camera.SetPosition(0, 0, 250) elif mod.type=='map': reader = vtk.vtkStructuredPointsReader() reader.SetFileName(mod.dfn) reader.Update() #by calling Update() we read the file iso = vtk.vtkMarchingContourFilter() iso.UseScalarTreeOn() iso.ComputeNormalsOn() iso.SetInputConnection(reader.GetOutputPort()) iso.SetValue(0,mod.isov*mod.sigavg[0]+mod.sigavg[1]) mapper = vtk.vtkOpenGLPolyDataMapper() mapper.SetInputConnection(iso.GetOutputPort()) ### <- connection here mapper.ScalarVisibilityOff() mapper.Update() acteur= vtk.vtkOpenGLActor() acteur.SetMapper(mapper) acteur.GetProperty().SetColor(0,0.35,1) if mod.rep=='Wireframe': acteur.GetProperty().SetRepresentationToWireframe() elif mod.rep=='Surface': acteur.GetProperty().SetRepresentationToSurface() else : acteur.GetProperty().SetRepresentationToWireframe() acteur.GetProperty().SetInterpolationToGouraud() acteur.GetProperty().SetSpecular(.4) acteur.GetProperty().SetSpecularPower(10) (xmin,xmax,ymin,ymax,zmin,zmax)=acteur.GetBounds() maxi=max(xmax-xmin,ymax-ymin,zmax-zmin) mini=min(xmax-xmin,ymax-ymin,zmax-zmin) fp=((xmax+xmin)/2.,(ymax+ymin)/2.,(zmax+zmin)/2.) self.camera.SetFocalPoint(fp[0],fp[1],fp[2]) self.camera.SetPosition(fp[0],fp[1],fp[2]+(zmax-zmin)*4.) else : print 'strange Error in mod.type' (xl, xu, yl, yu, zl, zu)=acteur.GetBounds() mod.coldist = min(xu-xl,yu-yl,zu-zl)/2. mod.sphdist = max(xu-xl,yu-yl,zu-zl)/2. self.renderer.AddActor(acteur) self.renderer.ResetCameraClippingRange() self.renwin.Render()
theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # iso-surface to create geometry theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25) theConeSample.SetSampleDimensions(60, 60, 60) theConeSample.ComputeNormalsOff() theConeSurface = vtk.vtkMarchingContourFilter() theConeSurface.SetInputConnection(theConeSample.GetOutputPort()) theConeSurface.SetValue(0, 0.0) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(theConeSurface.GetOutputPort()) coneMapper.ScalarVisibilityOff() coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(GetRGBColor('chocolate')) # iso-surface to create geometry theCreamSample = vtk.vtkSampleFunction() theCreamSample.SetImplicitFunction(theCream) theCreamSample.SetModelBounds(0, 2.5, -1.25, 1.25, -1.25, 1.25)
def testimageMCAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") colors = [ "flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate" ] types = [ "UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double" ] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colorWrapper = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval('cast[idx].SetOutputScalarTypeTo' + vtkType + '()') cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkMarchingContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ScalarVisibilityOff() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) # actor[idx].Actor.GetProperty().SetDiffuseColor(lindex.colors.c.lindex.colors.c+1.lindex.colors.c+1) actor[idx].GetProperty().SetDiffuseColor( colorWrapper.GetRGBColor(colors[c])) actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 1 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "imageMCAll.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
theCone = vtk.vtkImplicitBoolean() theCone.SetOperationTypeToIntersection() theCone.AddFunction(cone) theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # iso-surface to create geometry theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1,1.5,-1.25,1.25,-1.25,1.25) theConeSample.SetSampleDimensions(60,60,60) theConeSample.ComputeNormalsOff() theConeSurface = vtk.vtkMarchingContourFilter() theConeSurface.SetInputConnection(theConeSample.GetOutputPort()) theConeSurface.SetValue(0,0.0) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(theConeSurface.GetOutputPort()) coneMapper.ScalarVisibilityOff() coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(chocolate) # iso-surface to create geometry theCreamSample = vtk.vtkSampleFunction() theCreamSample.SetImplicitFunction(theCream) theCreamSample.SetModelBounds(0,2.5,-1.25,1.25,-1.25,1.25) theCreamSample.SetSampleDimensions(60,60,60) theCreamSample.ComputeNormalsOff() theCreamSurface = vtk.vtkMarchingContourFilter()
def isosurface(self, data, isovalue, rendtype): self.data = data self.settings = wx.Panel(self) self.plot_type = self.type = 'isosurface' self.image = self.array_to_3d_imagedata() self.iso = vtk.vtkMarchingContourFilter() self.iso.UseScalarTreeOn() self.iso.ComputeNormalsOn() if vtk.vtkVersion.GetVTKMajorVersion()<6: self.iso.SetInput(self.image) else: self.iso.SetInputData(self.image) self.iso.SetValue(0,isovalue) depthSort = vtk.vtkDepthSortPolyData() depthSort.SetInputConnection(self.iso.GetOutputPort()) depthSort.SetDirectionToBackToFront() depthSort.SetVector(1, 1, 1) depthSort.SetCamera(self.camera) depthSort.SortScalarsOn() depthSort.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(depthSort.GetOutputPort()) mapper.ScalarVisibilityOff() mapper.Update() self.surf = vtk.vtkActor() self.surf.SetMapper(mapper) self.surf.GetProperty().SetColor((0,0.5,0.75)) self.surf.PickableOff() outline = vtk.vtkOutlineFilter() if vtk.vtkVersion.GetVTKMajorVersion()<6: outline.SetInput(self.image) else: outline.SetInputData(self.image) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) box=vtk.vtkActor() box.SetMapper( outlineMapper ) box.GetProperty().SetColor((0,0,0)) box.PickableOff() self.renderer.AddActor(box) if rendtype=='w': self.surf.GetProperty().SetRepresentationToWireframe() elif rendtype=='s': self.surf.GetProperty().SetRepresentationToSurface() elif rendtype=='p': self.surf.GetProperty().SetRepresentationToPoints() self.surf.GetProperty().SetPointSize(5) else: self.surf.GetProperty().SetRepresentationToWireframe() self.surf.GetProperty().SetInterpolationToGouraud() self.surf.GetProperty().SetSpecular(.4) self.surf.GetProperty().SetSpecularPower(10) self.renderer.AddActor(self.surf) self.build_axes() self.center_on_actor(self.surf, out=True) sb1 = wx.StaticBox(self.settings, wx.ID_ANY, label = "Contour Level") isovSizer = wx.StaticBoxSizer(sb1, wx.HORIZONTAL) self.isov_scale = 100. self.isov_slider = wx.Slider(self.settings, wx.ID_ANY, value = isovalue*self.isov_scale , minValue = int(self.data.min()*self.isov_scale) , maxValue = int(self.data.max()*self.isov_scale), size = (60,27), style = wx.SL_HORIZONTAL) self.isov_slider.Bind(wx.EVT_SCROLL,self.on_change_isov) isovSizer.Add(self.isov_slider, 1, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer = wx.BoxSizer() self.rendlist_label = wx.StaticText(self.settings, label="Rendering mode") self.rendlist = wx.ComboBox(self.settings, id = wx.ID_ANY, choices=["surface","wireframe", "points"], style=wx.CB_READONLY) self.rendlist.SetValue("wireframe") self.rendlist.Bind(wx.EVT_COMBOBOX, self.on_change_surf_rend_mode) self.opacity_label = wx.StaticText(self.settings, label="Opacity level [0-1]") self.opacity = wx.TextCtrl(self.settings, wx.ID_ANY, style= wx.SL_HORIZONTAL|wx.TE_PROCESS_ENTER) self.opacity.SetValue(str(1.0)) self.opacity.Bind(wx.EVT_TEXT_ENTER, self.on_set_opacity) rendSizer.Add(self.rendlist_label, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.rendlist, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.opacity_label, 0, wx.ALIGN_CENTER_VERTICAL, 0) rendSizer.Add(self.opacity, 0, wx.ALIGN_CENTER_VERTICAL, 0) sb = wx.StaticBox(self.settings, wx.ID_ANY, label = "Slice orientation") sliceSizer = wx.StaticBoxSizer(sb, wx.HORIZONTAL) self.sagittal = wx.RadioButton(self.settings, wx.ID_ANY, label = "sagittal (// to Y,Z)") self.axial = wx.RadioButton(self.settings, wx.ID_ANY, label = "axial (// to X,Y)") self.coronal = wx.RadioButton(self.settings, wx.ID_ANY, label = "coronal (// to X,Z)") self.oblique = wx.RadioButton(self.settings, wx.ID_ANY, label = "oblique (// to X,Y+Z)") self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.sagittal) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.axial) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.coronal) self.Bind(wx.EVT_RADIOBUTTON, self.on_slice_selection, self.oblique) sliceSizer.Add(self.sagittal, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.axial, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.coronal, 1, wx.ALIGN_CENTER_VERTICAL, 0) sliceSizer.Add(self.oblique, 1, wx.ALIGN_CENTER_VERTICAL, 0) self.iren.AddObserver("CharEvent", self.on_keyboard_input) self.reslice = None key_doc = wx.StaticText(self.settings, wx.ID_ANY, label = "Press '+' and '-' keys to translate the slice") self.save_fig = wx.Button(self.settings, wx.ID_ANY, label="Save current view") self.save_fig.Bind(wx.EVT_BUTTON, self.Screen_shot) Sizer = wx.BoxSizer(wx.VERTICAL) Sizer.Add(rendSizer, 0, wx.EXPAND, 0) Sizer.Add(isovSizer, 0, wx.EXPAND, 0) Sizer.Add(sliceSizer, 0, wx.EXPAND, 0) Sizer.Add(key_doc, 0, wx.EXPAND, 0) Sizer.Add(self.save_fig, 0, wx.EXPAND, 0) self.iren.Render() self.settings.SetSizer(Sizer) Sizer.Fit(self.settings) self.settings.Layout() self._mgr.AddPane(self.settings, wxaui.AuiPaneInfo().Center().Dock().Bottom().CloseButton(False).CaptionVisible(False)) self._mgr.Update()
def Execute(self): if self.GaussFiltering: gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(self.Image) gauss.SetStandardDeviations(self.StandardDeviations) gauss.SetRadiusFactors(self.RadiusFactors) if self.Shape.find('2d') != -1: gauss.SetDimensionality(2) elif self.Shape.find('3d') != -1: gauss.SetDimensionality(3) else: gauss.SetDimensionality(3) gauss.Update() self.Image = gauss.GetOutput() scalarRange = [0.0,0.0] if self.FWHMRegion == 'image': scalarRange = self.Image.GetScalarRange() elif self.FWHMRegion == 'midline': extent = self.Image.GetWholeExtent() newYExtent = extent[2]+(extent[3]-extent[2])/2 clip = vtk.vtkImageClip() clip.SetInput(self.Image) clip.SetOutputWholeExtent(extent[0],extent[1],newYExtent,newYExtent,extent[4],extent[5]) clip.ClipDataOn() clip.Update() scalarRange = clip.GetOutput().GetScalarRange() self.FWHMLevel = (scalarRange[1] - scalarRange[0]) * self.FWHMRatio + scalarRange[0] if self.FWHMBackground != None: self.FWHMLevel = (scalarRange[1] - self.FWHMBackground) * self.FWHMRatio + self.FWHMBackground if self.Method == 'levelsets': if self.Shape.find('2d') != -1: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetDimensionality(2) elif self.Shape.find('3d') != -1: if self.FeatureImageType == 'gradient': gradientMagnitude = vtkvmtk.vtkvmtkGradientMagnitudeImageFilter() elif self.FeatureImageType == 'upwind': gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter() gradientMagnitude.SetUpwindFactor(self.UpwindFactor) else: self.PrintError('Unsupported feature image type: choices are "gradient", "upwind".') return else: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetInput(self.Image) gradientMagnitude.Update() boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter() boundedReciprocal.SetInput(gradientMagnitude.GetOutput()) boundedReciprocal.Update() self.FeatureImage = vtk.vtkImageData() self.FeatureImage.DeepCopy(boundedReciprocal.GetOutput()) levelSetsFilter = None if self.Shape.find('2d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSet2DImageFilter() elif self.Shape.find('3d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() else: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() levelSetsFilter.SetInput(self.Image) levelSetsFilter.SetFeatureImage(boundedReciprocal.GetOutput()) levelSetsFilter.SetDerivativeSigma(0.0) levelSetsFilter.SetAutoGenerateSpeedAdvection(1) levelSetsFilter.SetNumberOfIterations(self.LevelSetsIterations) levelSetsFilter.SetPropagationScaling(0.0) levelSetsFilter.SetCurvatureScaling(self.CurvatureScaling) levelSetsFilter.SetAdvectionScaling(1.0) levelSetsFilter.SetIsoSurfaceValue(self.FWHMLevel) levelSetsFilter.SetInterpolateSurfaceLocation(1) levelSetsFilter.SetMaximumRMSError(1E-10) levelSetsFilter.Update() self.LevelSets = vtk.vtkImageData() self.LevelSets.DeepCopy(levelSetsFilter.GetOutput()) contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.LevelSets) contourFilter.SetValue(0,0.0) contourFilter.Update() self.Contour = contourFilter.GetOutput() elif self.Method == 'fwhm': contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.Image) contourFilter.SetValue(0,self.FWHMLevel) contourFilter.Update() self.Contour = contourFilter.GetOutput() else: self.PrintError('Unsupported method: choices are "levelsets", "fwhm".') return if self.Smoothing: smoothingFilter = vtk.vtkWindowedSincPolyDataFilter() smoothingFilter.SetInput(self.Contour) smoothingFilter.SetNumberOfIterations(self.SmoothingIterations) smoothingFilter.SetPassBand(self.SmoothingPassBand) smoothingFilter.Update() self.Contour = smoothingFilter.GetOutput() measurementFilter = None if self.Shape is 'thickplane2d': measurementFilter = femri2DPlaneThickness() elif self.Shape is 'cylinder2d': measurementFilter = femri2DCylinderThickness() elif self.Shape is 'hollowcylinder2d': measurementFilter = femri2DHollowCylinderThickness() elif self.Shape is 'cylinder3d': measurementFilter = femri3DCylinderThickness() else: self.PrintError('Unsupported shape: choices are "thickplane2d", "cylinder2d", "hollowcylinder2d", "cylinder3d".') return measurementFilter.Contour = self.Contour measurementFilter.Center = self.Center measurementFilter.TiltingAngle = math.radians(self.TiltingAngle) measurementFilter.RotationAngle = math.radians(self.RotationAngle) measurementFilter.Execute() if self.Shape is 'hollowcylinder2d': measurementFilter.ComputeAreas() self.InnerArea = measurementFilter.InnerArea self.OuterArea = measurementFilter.OuterArea self.Thickness = measurementFilter.Thickness self.Thickness3D = measurementFilter.Thickness3D self.Locations = measurementFilter.Locations self.Contour = measurementFilter.Contour self.OutputText('\n') self.OutputText('Thickness: ' + str(self.Thickness) + '\n') self.OutputText('Thickness3D: ' + str(self.Thickness3D) + '\n') self.OutputText('Locations: ' + str(self.Locations) + '\n') if self.Shape is 'hollowcylinder2d': self.OutputText('InnerArea: ' + str(self.InnerArea) + '\n') self.OutputText('OuterArea: ' + str(self.OuterArea) + '\n') self.OutputText('\n')
math.Random(0, 1)) i = i + 1 profile = vtk.vtkPolyData() profile.SetPoints(points) # Checkerboard cbdSplatter = vtk.vtkCheckerboardSplatter() cbdSplatter.SetInputData(profile) cbdSplatter.SetSampleDimensions(100, 100, 100) cbdSplatter.ScalarWarpingOff() cbdSplatter.SetFootprint(2) cbdSplatter.SetParallelSplatCrossover(2) #cbdSplatter.SetRadius(0.05) cbdSurface = vtk.vtkMarchingContourFilter() cbdSurface.SetInputConnection(cbdSplatter.GetOutputPort()) cbdSurface.SetValue(0, 0.01) cbdMapper = vtk.vtkPolyDataMapper() cbdMapper.SetInputConnection(cbdSurface.GetOutputPort()) cbdMapper.ScalarVisibilityOff() cbdActor = vtk.vtkActor() cbdActor.SetMapper(cbdMapper) cbdActor.GetProperty().SetColor(1.0, 0.0, 0.0) timer = vtk.vtkExecutionTimer() timer.SetFilter(cbdSplatter) cbdSplatter.Update() CBDwallClock = timer.GetElapsedWallClockTime()
renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create pipeline # v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.GetOutput().SetOrigin(0.0, 0.0, 0.0) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter") v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) v16.Update() iso = vtk.vtkMarchingContourFilter() iso.SetInputConnection(v16.GetOutputPort()) iso.SetValue(0, 1125) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(GetRGBColor('antique_white')) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(v16.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper()
def testFinancialField(self): """ Demonstrate the use and manipulation of fields and use of vtkProgrammableDataObjectSource. This creates fields the hard way (as compared to reading a vtk field file), but shows you how to interface to your own raw data. The image should be the same as financialField.tcl """ xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Parse an ascii file and manually create a field. Then construct a # dataset from the field. dos = vtk.vtkProgrammableDataObjectSource() def parseFile(): f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r") line = f.readline().split() # From the size calculate the number of lines. numPts = int(line[1]) numLines = (numPts - 1) / 8 + 1 # create the data object field = vtk.vtkFieldData() field.AllocateArrays(4) # read TIME_LATE - dependent variable while True: line = f.readline().split() if len(line) > 0: break; timeLate = vtk.vtkFloatArray() timeLate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: timeLate.InsertNextValue(float(j)) field.AddArray(timeLate) # MONTHLY_PAYMENT - independent variable while True: line = f.readline().split() if len(line) > 0: break; monthlyPayment = vtk.vtkFloatArray() monthlyPayment.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyPayment.InsertNextValue(float(j)) field.AddArray(monthlyPayment) # UNPAID_PRINCIPLE - skip while True: line = f.readline().split() if len(line) > 0: break; for i in range(0, numLines): line = f.readline() # LOAN_AMOUNT - skip while True: line = f.readline().split() if len(line) > 0: break; for i in range(0, numLines): line = f.readline() # INTEREST_RATE - independent variable while True: line = f.readline().split() if len(line) > 0: break; interestRate = vtk.vtkFloatArray() interestRate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: interestRate.InsertNextValue(float(j)) field.AddArray(interestRate) # MONTHLY_INCOME - independent variable while True: line = f.readline().split() if len(line) > 0: break; monthlyIncome = vtk.vtkFloatArray() monthlyIncome.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyIncome.InsertNextValue(float(j)) field.AddArray(monthlyIncome) dos.GetOutput().SetFieldData(field) dos.SetExecuteMethod(parseFile) # Create the dataset do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(dos.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputConnection(do2ds.GetOutputPort()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.DefaultNormalizeOn() fd2ad.SetScalarComponent(0, scalar, 0) # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(fd2ad.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkMarchingContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(fd2ad.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkMarchingContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk - Field.Data") # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) renWin.SetSize(500, 500) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "financialField2.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def testFinancialField(self): """ Demonstrate the use and manipulation of fields and use of vtkProgrammableDataObjectSource. This creates fields the hard way (as compared to reading a vtk field file), but shows you how to interface to your own raw data. The image should be the same as financialField.tcl """ xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Parse an ascii file and manually create a field. Then construct a # dataset from the field. dos = vtk.vtkProgrammableDataObjectSource() def parseFile(): f = open(VTK_DATA_ROOT + "/Data/financial.txt", "r") line = f.readline().split() # From the size calculate the number of lines. numPts = int(line[1]) numLines = (numPts - 1) / 8 + 1 # create the data object field = vtk.vtkFieldData() field.AllocateArrays(4) # read TIME_LATE - dependent variable while True: line = f.readline().split() if len(line) > 0: break timeLate = vtk.vtkFloatArray() timeLate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: timeLate.InsertNextValue(float(j)) field.AddArray(timeLate) # MONTHLY_PAYMENT - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyPayment = vtk.vtkFloatArray() monthlyPayment.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyPayment.InsertNextValue(float(j)) field.AddArray(monthlyPayment) # UNPAID_PRINCIPLE - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # LOAN_AMOUNT - skip while True: line = f.readline().split() if len(line) > 0: break for i in range(0, numLines): line = f.readline() # INTEREST_RATE - independent variable while True: line = f.readline().split() if len(line) > 0: break interestRate = vtk.vtkFloatArray() interestRate.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: interestRate.InsertNextValue(float(j)) field.AddArray(interestRate) # MONTHLY_INCOME - independent variable while True: line = f.readline().split() if len(line) > 0: break monthlyIncome = vtk.vtkFloatArray() monthlyIncome.SetName(line[0]) for i in range(0, numLines): line = f.readline().split() for j in line: monthlyIncome.InsertNextValue(float(j)) field.AddArray(monthlyIncome) dos.GetOutput().SetFieldData(field) dos.SetExecuteMethod(parseFile) # Create the dataset do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(dos.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputConnection(do2ds.GetOutputPort()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.DefaultNormalizeOn() fd2ad.SetScalarComponent(0, scalar, 0) # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(fd2ad.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkMarchingContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(fd2ad.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkMarchingContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk - Field.Data") # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) renWin.SetSize(500, 500) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "financialField2.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def load_map(gfx,mapfile,root,status,scale,rendtype,isov,opct,cropentry,nfv,vardeci,varsmooth,color,caller): if caller != 'fit': root.configure(cursor='watch') status.set('Map loading ... please wait') if mapfile =='' or mapfile == None or mapfile ==() : MB.showwarning('Info','Select map file') status.clear() root.configure(cursor='arrow') return try: gfx.renderer.RemoveActor(gfx.map[0].acteur) gfx.renderer.RemoveActor(gfx.map[0].box) except: pass if mapfile == 0: mapfile = gfx.map[0].fn if gfx.map == []: gfx.map = [Map()] gfx.map[0].id=0 if 'map' in caller : clean_map(gfx) #supression des fichiers sort.s xudi et iudi if '.vtk' in mapfile: chdir(gfx.tmpdir) v2v_out='info_map' if caller != 'crop': gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(v2v_out) if scale != gfx.map[0].scale: spc = None o = None f = open(mapfile,'r') for l in f: if l.startswith('SPACING'): spc = l.split()[1:4] if l.startswith('ORIGIN'): o = l.split()[1:4] if spc != None and o != None: break f.close() gfx.map[0].ratio = scale/gfx.map[0].scale if spc != None and o != None: system("sed -i -e /^SPACING/s/.*/'SPACING %f %f %f'/ %s"%(float(spc[0])*gfx.map[0].ratio,float(spc[1])*gfx.map[0].ratio,float(spc[2])*gfx.map[0].ratio,mapfile)) system("sed -i -e /^ORIGIN/s/.*/'ORIGIN %f %f %f'/ %s"%(float(o[0])*gfx.map[0].ratio,float(o[1])*gfx.map[0].ratio,float(o[2])*gfx.map[0].ratio,mapfile)) chdir(gfx.workdir) if '.ezd' in mapfile: chdir(gfx.tmpdir) mapfileout = extract_file_from_path(mapfile)[:-4]+'.vtk' e2v_out='info_map' system(gfx.vedabin+'/e2v.exe >> %s <<ENDOF\n%s \n%f \n%s \nENDOF'%(e2v_out,mapfile,scale,mapfileout)) mapfile = gfx.tmpdir + '/' + mapfileout gfx.map[0].sigma,gfx.map[0].avg = map_sigma_avg(e2v_out) chdir(gfx.workdir) gfx.map[0].fn = mapfile gfx.map[0].id = set_map_id(gfx) gfx.map[0].color = color gfx.map[0].oldscale = gfx.map[0].scale gfx.map[0].scale = scale if nfv !=None: nfv.set(extract_file_from_path(gfx.map[0].fn)) reader = vtk.vtkStructuredPointsReader() reader.SetFileName(mapfile) reader.Update() #by calling Update() we read the file gfx.map[0].reader=reader iso = vtk.vtkMarchingContourFilter() iso.UseScalarTreeOn() iso.ComputeNormalsOn() iso.SetInputConnection(reader.GetOutputPort()) iso.SetValue(0,isov*gfx.map[0].sigma+gfx.map[0].avg) gfx.map[0].iso=iso gfx.map[0].isov=isov if varsmooth == '1': #generate vectors clean = vtk.vtkCleanPolyData() clean.SetInputConnection(iso.GetOutputPort()) clean.ConvertStripsToPolysOn() smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInputConnection(clean.GetOutputPort()) smooth.BoundarySmoothingOn() smooth.GenerateErrorVectorsOn() smooth.GenerateErrorScalarsOn() smooth.NormalizeCoordinatesOn() smooth.NonManifoldSmoothingOn() smooth.FeatureEdgeSmoothingOn() smooth.SetEdgeAngle(90) smooth.SetFeatureAngle(90) smooth.Update() if vardeci=='1': deci = vtk.vtkDecimatePro() if varsmooth == '0': deci.SetInput(iso.GetOutput()) else : deci.SetInput(smooth.GetOutput()) deci.PreserveTopologyOn() deci.BoundaryVertexDeletionOn() deci.SplittingOn() deci.PreSplitMeshOn() deci.SetTargetReduction(0.97) gfx.map[0].isdeci='1' mapper = vtk.vtkOpenGLPolyDataMapper() mapper.SetInputConnection(deci.GetOutputPort()) else : mapper = vtk.vtkOpenGLPolyDataMapper() if varsmooth == '1': mapper.SetInputConnection(smooth.GetOutputPort()) ### <- connection here else : mapper.SetInputConnection(iso.GetOutputPort()) #mapper.SetInput(newpd) ### <- newpd connect there gfx.map[0].isdeci='0' mapper.ScalarVisibilityOff() mapper.Update() gfx.map[0].mapper=mapper actor = vtk.vtkOpenGLActor() actor.SetMapper(mapper) gfx.map[0].acteur=actor #actor.SetScale(scale,scale,scale) gerer differament actor.GetProperty().SetColor(gfx.map[0].color) actor.PickableOff() #definition de la box outline = vtk.vtkOutlineFilter() outline.SetInput(reader.GetOutput()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInput(outline.GetOutput()) box=vtk.vtkActor() box.SetMapper( outlineMapper ) box.GetProperty().SetColor((invcolor(gfx.map[0].color))) box.PickableOff() #box.SetScale(scale,scale,scale) gfx.map[0].box = box #get boxwidget bounds and set axes lenth (xmin,xmax,ymin,ymax,zmin,zmax)=box.GetBounds() x=abs(xmin-xmax)/2.0 y=abs(ymin-ymax)/2.0 z=abs(zmin-zmax)/2.0 gfx.axes.SetTotalLength( x, y , z ) #defini la longeurs des axe init_cam_slab(gfx,(xmin,xmax,ymin,ymax,zmin,zmax)) #defini le slab correct gfx.map[0].rendtype=rendtype if rendtype=='Wireframe': actor.GetProperty().SetRepresentationToWireframe() elif rendtype=='Surface': actor.GetProperty().SetRepresentationToSurface() elif rendtype=='Points': actor.GetProperty().SetRepresentationToPoints() actor.GetProperty().SetPointSize(5) else : actor.GetProperty().SetRepresentationToWireframe() gfx.map[0].opct=opct actor.GetProperty().SetOpacity(opct) actor.GetProperty().SetInterpolationToGouraud() actor.GetProperty().SetSpecular(.4) actor.GetProperty().SetSpecularPower(10) if cropentry!=None: if gfx.crop==None: gfx.crop=Crop(gfx,iso,cropentry,None) #here entryval = None rendermap(gfx) #ajustement pour la symetry helicoidale if gfx.map[0].scale != gfx.map[0].oldscale:#changement de scale gfx.itf.propagate_scale(gfx,scale,caller) if gfx.ps != None: if gfx.ps.solidtype == 'Helicoidal': gfx.ps.display_tube(gfx,caller) elif gfx.ps.solidtype == 'Icosahedral' or gfx.ps.solidtype =='Octahedral' or gfx.ps.solidtype == 'Tetrahedral': gfx.ps.display_platonic(gfx,gfx.ps.ori) elif gfx.ps.solidtype =='Cn' or gfx.ps.solidtype == 'Dn': gfx.ps.display_Xn(gfx) if caller == 'crop':#crop uniquement helicoidal if gfx.ps != None: if gfx.ps.solidtype == 'Helicoidal': gfx.ps.display_tube(gfx,caller) if caller != 'fit': status.clear() root.configure(cursor='arrow')
def testFinancialField(self): size = 3187 #maximum number possible #set size 100 #maximum number possible xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # extract data from field as a polydata (just points), then extract scalars fdr = vtk.vtkDataObjectReader() fdr.SetFileName(VTK_DATA_ROOT + "/Data/financial.vtk") do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(fdr.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0, 0, size, 1) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() if fdr.GetOutput().GetFieldData().GetAbstractArray( "Some Text").GetValue(0) != "Test me": raise RuntimeError, 'Could not properly read string array "Some Text"' fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputConnection(do2ds.GetOutputPort()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.DefaultNormalizeOn() fd2ad.SetScalarComponent(0, scalar, 0) # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(fd2ad.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkMarchingContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(fd2ad.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkMarchingContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk - Field.Data") # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "financialField.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def load_map(gfx, mapfile, root, status, scale, rendtype, isov, opct, cropentry, nfv, vardeci, varsmooth, color, caller): if caller != 'fit': root.configure(cursor='watch') status.set('Map loading ... please wait') if mapfile == '' or mapfile == None or mapfile == (): MB.showwarning('Info', 'Select map file') status.clear() root.configure(cursor='arrow') return try: gfx.renderer.RemoveActor(gfx.map[0].acteur) gfx.renderer.RemoveActor(gfx.map[0].box) except: pass if mapfile == 0: mapfile = gfx.map[0].fn if gfx.map == []: gfx.map = [Map()] gfx.map[0].id = 0 if 'map' in caller: clean_map(gfx) #supression des fichiers sort.s xudi et iudi if '.vtk' in mapfile: chdir(gfx.tmpdir) v2v_out = 'info_map' if caller != 'crop': gfx.map[0].sigma, gfx.map[0].avg = map_sigma_avg(v2v_out) if scale != gfx.map[0].scale: spc = None o = None f = open(mapfile, 'r') for l in f: if l.startswith('SPACING'): spc = l.split()[1:4] if l.startswith('ORIGIN'): o = l.split()[1:4] if spc != None and o != None: break f.close() gfx.map[0].ratio = scale / gfx.map[0].scale if spc != None and o != None: system("sed -i -e /^SPACING/s/.*/'SPACING %f %f %f'/ %s" % (float(spc[0]) * gfx.map[0].ratio, float(spc[1]) * gfx.map[0].ratio, float(spc[2]) * gfx.map[0].ratio, mapfile)) system("sed -i -e /^ORIGIN/s/.*/'ORIGIN %f %f %f'/ %s" % (float(o[0]) * gfx.map[0].ratio, float(o[1]) * gfx.map[0].ratio, float(o[2]) * gfx.map[0].ratio, mapfile)) chdir(gfx.workdir) if '.ezd' in mapfile: chdir(gfx.tmpdir) mapfileout = extract_file_from_path(mapfile)[:-4] + '.vtk' e2v_out = 'info_map' system(gfx.vedabin + '/e2v.exe >> %s <<ENDOF\n%s \n%f \n%s \nENDOF' % (e2v_out, mapfile, scale, mapfileout)) mapfile = gfx.tmpdir + '/' + mapfileout gfx.map[0].sigma, gfx.map[0].avg = map_sigma_avg(e2v_out) chdir(gfx.workdir) gfx.map[0].fn = mapfile gfx.map[0].id = set_map_id(gfx) gfx.map[0].color = color gfx.map[0].oldscale = gfx.map[0].scale gfx.map[0].scale = scale if nfv != None: nfv.set(extract_file_from_path(gfx.map[0].fn)) reader = vtk.vtkStructuredPointsReader() reader.SetFileName(mapfile) reader.Update() #by calling Update() we read the file gfx.map[0].reader = reader iso = vtk.vtkMarchingContourFilter() iso.UseScalarTreeOn() iso.ComputeNormalsOn() iso.SetInputConnection(reader.GetOutputPort()) iso.SetValue(0, isov * gfx.map[0].sigma + gfx.map[0].avg) gfx.map[0].iso = iso gfx.map[0].isov = isov if varsmooth == '1': #generate vectors clean = vtk.vtkCleanPolyData() clean.SetInputConnection(iso.GetOutputPort()) clean.ConvertStripsToPolysOn() smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInputConnection(clean.GetOutputPort()) smooth.BoundarySmoothingOn() smooth.GenerateErrorVectorsOn() smooth.GenerateErrorScalarsOn() smooth.NormalizeCoordinatesOn() smooth.NonManifoldSmoothingOn() smooth.FeatureEdgeSmoothingOn() smooth.SetEdgeAngle(90) smooth.SetFeatureAngle(90) smooth.Update() if vardeci == '1': deci = vtk.vtkDecimatePro() if varsmooth == '0': deci.SetInput(iso.GetOutput()) else: deci.SetInput(smooth.GetOutput()) deci.PreserveTopologyOn() deci.BoundaryVertexDeletionOn() deci.SplittingOn() deci.PreSplitMeshOn() deci.SetTargetReduction(0.97) gfx.map[0].isdeci = '1' mapper = vtk.vtkOpenGLPolyDataMapper() mapper.SetInputConnection(deci.GetOutputPort()) else: mapper = vtk.vtkOpenGLPolyDataMapper() if varsmooth == '1': mapper.SetInputConnection( smooth.GetOutputPort()) ### <- connection here else: mapper.SetInputConnection(iso.GetOutputPort()) #mapper.SetInput(newpd) ### <- newpd connect there gfx.map[0].isdeci = '0' mapper.ScalarVisibilityOff() mapper.Update() gfx.map[0].mapper = mapper actor = vtk.vtkOpenGLActor() actor.SetMapper(mapper) gfx.map[0].acteur = actor #actor.SetScale(scale,scale,scale) gerer differament actor.GetProperty().SetColor(gfx.map[0].color) actor.PickableOff() #definition de la box outline = vtk.vtkOutlineFilter() outline.SetInput(reader.GetOutput()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInput(outline.GetOutput()) box = vtk.vtkActor() box.SetMapper(outlineMapper) box.GetProperty().SetColor((invcolor(gfx.map[0].color))) box.PickableOff() #box.SetScale(scale,scale,scale) gfx.map[0].box = box #get boxwidget bounds and set axes lenth (xmin, xmax, ymin, ymax, zmin, zmax) = box.GetBounds() x = abs(xmin - xmax) / 2.0 y = abs(ymin - ymax) / 2.0 z = abs(zmin - zmax) / 2.0 gfx.axes.SetTotalLength(x, y, z) #defini la longeurs des axe init_cam_slab( gfx, (xmin, xmax, ymin, ymax, zmin, zmax)) #defini le slab correct gfx.map[0].rendtype = rendtype if rendtype == 'Wireframe': actor.GetProperty().SetRepresentationToWireframe() elif rendtype == 'Surface': actor.GetProperty().SetRepresentationToSurface() elif rendtype == 'Points': actor.GetProperty().SetRepresentationToPoints() actor.GetProperty().SetPointSize(5) else: actor.GetProperty().SetRepresentationToWireframe() gfx.map[0].opct = opct actor.GetProperty().SetOpacity(opct) actor.GetProperty().SetInterpolationToGouraud() actor.GetProperty().SetSpecular(.4) actor.GetProperty().SetSpecularPower(10) if cropentry != None: if gfx.crop == None: gfx.crop = Crop(gfx, iso, cropentry, None) #here entryval = None rendermap(gfx) #ajustement pour la symetry helicoidale if gfx.map[0].scale != gfx.map[0].oldscale: #changement de scale gfx.itf.propagate_scale(gfx, scale, caller) if gfx.ps != None: if gfx.ps.solidtype == 'Helicoidal': gfx.ps.display_tube(gfx, caller) elif gfx.ps.solidtype == 'Icosahedral' or gfx.ps.solidtype == 'Octahedral' or gfx.ps.solidtype == 'Tetrahedral': gfx.ps.display_platonic(gfx, gfx.ps.ori) elif gfx.ps.solidtype == 'Cn' or gfx.ps.solidtype == 'Dn': gfx.ps.display_Xn(gfx) if caller == 'crop': #crop uniquement helicoidal if gfx.ps != None: if gfx.ps.solidtype == 'Helicoidal': gfx.ps.display_tube(gfx, caller) if caller != 'fit': status.clear() root.configure(cursor='arrow')
points.InsertPoint(i,math.Random(0,1),math.Random(0,1),math.Random(0,1)) i = i + 1 profile = vtk.vtkPolyData() profile.SetPoints(points) # Checkerboard cbdSplatter = vtk.vtkCheckerboardSplatter() cbdSplatter.SetInputData(profile) cbdSplatter.SetSampleDimensions(100, 100, 100) cbdSplatter.ScalarWarpingOff() cbdSplatter.SetFootprint(2) cbdSplatter.SetParallelSplatCrossover(2) #cbdSplatter.SetRadius(0.05) cbdSurface = vtk.vtkMarchingContourFilter() cbdSurface.SetInputConnection(cbdSplatter.GetOutputPort()) cbdSurface.SetValue(0, 0.01) cbdMapper = vtk.vtkPolyDataMapper() cbdMapper.SetInputConnection(cbdSurface.GetOutputPort()) cbdMapper.ScalarVisibilityOff() cbdActor = vtk.vtkActor() cbdActor.SetMapper(cbdMapper) cbdActor.GetProperty().SetColor(1.0, 0.0, 0.0) timer = vtk.vtkExecutionTimer() timer.SetFilter(cbdSplatter) cbdSplatter.Update() CBDwallClock = timer.GetElapsedWallClockTime()
def testFinancialField(self): size = 3187 #maximum number possible #set size 100 #maximum number possible xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # extract data from field as a polydata (just points), then extract scalars fdr = vtk.vtkDataObjectReader() fdr.SetFileName(VTK_DATA_ROOT + "/Data/financial.vtk") do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(fdr.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() #format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0, 0, size, 1) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputConnection(do2ds.GetOutputPort()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.DefaultNormalizeOn() fd2ad.SetScalarComponent(0, scalar, 0) # construct pipeline for original population popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(fd2ad.GetOutputPort()) popSplatter.SetSampleDimensions(50, 50, 50) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkMarchingContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(.9, .9, .9) # construct pipeline for delinquent population lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(fd2ad.GetOutputPort()) lateSplatter.SetSampleDimensions(50, 50, 50) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkMarchingContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(1.0, 0.0, 0.0) # create axes popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # label the axes XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName("vtk - Field.Data") # Add the actors to the renderer, set the background and size # ren.AddActor(axesActor) ren.AddActor(lateActor) ren.AddActor(XActor) ren.AddActor(YActor) ren.AddActor(ZActor) ren.AddActor(popActor) #it's last because its translucent) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) ren.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "financialField.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def testimageMCAll(self): # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create pipeline # slc = vtk.vtkStructuredPointsReader() slc.SetFileName(VTK_DATA_ROOT + "/Data/ironProt.vtk") colors = ["flesh", "banana", "grey", "pink", "carrot", "gainsboro", "tomato", "gold", "thistle", "chocolate"] types = ["UnsignedChar", "Char", "Short", "UnsignedShort", "Int", "UnsignedInt", "Long", "UnsignedLong", "Float", "Double"] i = 1 c = 0 clip = list() cast = list() iso = list() mapper = list() actor = list() colorWrapper = self.Colors() for idx, vtkType in enumerate(types): clip.append(vtk.vtkImageClip()) clip[idx].SetInputConnection(slc.GetOutputPort()) clip[idx].SetOutputWholeExtent(-1000, 1000, -1000, 1000, i, i + 5) i += 5 cast.append(vtk.vtkImageCast()) eval('cast[idx].SetOutputScalarTypeTo' + vtkType + '()') cast[idx].SetInputConnection(clip[idx].GetOutputPort()) cast[idx].ClampOverflowOn() iso.append(vtk.vtkMarchingContourFilter()) iso[idx].SetInputConnection(cast[idx].GetOutputPort()) iso[idx].GenerateValues(1, 30, 30) mapper.append(vtk.vtkPolyDataMapper()) mapper[idx].SetInputConnection(iso[idx].GetOutputPort()) mapper[idx].ScalarVisibilityOff() actor.append(vtk.vtkActor()) actor[idx].SetMapper(mapper[idx]) # actor[idx].Actor.GetProperty().SetDiffuseColor(lindex.colors.c.lindex.colors.c+1.lindex.colors.c+1) actor[idx].GetProperty().SetDiffuseColor(colorWrapper.GetRGBColor(colors[c])) actor[idx].GetProperty().SetSpecularPower(30) actor[idx].GetProperty().SetDiffuse(.7) actor[idx].GetProperty().SetSpecular(.5) c += 1 ren.AddActor(actor[idx]) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(slc.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.VisibilityOff() # Add the actors to the renderer, set the background and size # ren.AddActor(outlineActor) ren.SetBackground(0.9, .9, .9) ren.ResetCamera() ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Azimuth(20) ren.GetActiveCamera().Zoom(1.5) ren.ResetCameraClippingRange() renWin.SetSize(400, 400) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "imageMCAll.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def main(): ifn = get_program_parameters() colors = vtk.vtkNamedColors() reader = vtk.vtkDataObjectReader() reader.SetFileName(ifn) size = 3187 # maximum number possible xAxis = "INTEREST_RATE" yAxis = "MONTHLY_PAYMENT" zAxis = "MONTHLY_INCOME" scalar = "TIME_LATE" # Extract data from field as a polydata (just points), then extract scalars. do2ds = vtk.vtkDataObjectToDataSetFilter() do2ds.SetInputConnection(reader.GetOutputPort()) do2ds.SetDataSetTypeToPolyData() # format: component#, arrayname, arraycomp, minArrayId, maxArrayId, normalize do2ds.DefaultNormalizeOn() do2ds.SetPointComponent(0, xAxis, 0) do2ds.SetPointComponent(1, yAxis, 0, 0, size, 1) do2ds.SetPointComponent(2, zAxis, 0) do2ds.Update() fd2ad = vtk.vtkFieldDataToAttributeDataFilter() fd2ad.SetInputConnection(do2ds.GetOutputPort()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.DefaultNormalizeOn() fd2ad.SetScalarComponent(0, scalar, 0) # Construct the pipeline for the original population. popSplatter = vtk.vtkGaussianSplatter() popSplatter.SetInputConnection(fd2ad.GetOutputPort()) popSplatter.SetSampleDimensions(150, 150, 150) popSplatter.SetRadius(0.05) popSplatter.ScalarWarpingOff() popSurface = vtk.vtkMarchingContourFilter() popSurface.SetInputConnection(popSplatter.GetOutputPort()) popSurface.SetValue(0, 0.01) popMapper = vtk.vtkPolyDataMapper() popMapper.SetInputConnection(popSurface.GetOutputPort()) popMapper.ScalarVisibilityOff() popActor = vtk.vtkActor() popActor.SetMapper(popMapper) popActor.GetProperty().SetOpacity(0.3) popActor.GetProperty().SetColor(colors.GetColor3d("Gold")) # Construct the pipeline for the delinquent population. lateSplatter = vtk.vtkGaussianSplatter() lateSplatter.SetInputConnection(fd2ad.GetOutputPort()) lateSplatter.SetSampleDimensions(150, 150, 150) lateSplatter.SetRadius(0.05) lateSplatter.SetScaleFactor(0.05) lateSurface = vtk.vtkMarchingContourFilter() lateSurface.SetInputConnection(lateSplatter.GetOutputPort()) lateSurface.SetValue(0, 0.01) lateMapper = vtk.vtkPolyDataMapper() lateMapper.SetInputConnection(lateSurface.GetOutputPort()) lateMapper.ScalarVisibilityOff() lateActor = vtk.vtkActor() lateActor.SetMapper(lateMapper) lateActor.GetProperty().SetColor(colors.GetColor3d("Tomato")) # Create the axes. popSplatter.Update() bounds = popSplatter.GetOutput().GetBounds() axes = vtk.vtkAxes() axes.SetOrigin(bounds[0], bounds[2], bounds[4]) axes.SetScaleFactor(popSplatter.GetOutput().GetLength() / 5.0) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInputConnection(axes.GetOutputPort()) axesTubes.SetRadius(axes.GetScaleFactor() / 25.0) axesTubes.SetNumberOfSides(6) axesMapper = vtk.vtkPolyDataMapper() axesMapper.SetInputConnection(axesTubes.GetOutputPort()) axesActor = vtk.vtkActor() axesActor.SetMapper(axesMapper) # Label the axes. XText = vtk.vtkVectorText() XText.SetText(xAxis) XTextMapper = vtk.vtkPolyDataMapper() XTextMapper.SetInputConnection(XText.GetOutputPort()) XActor = vtk.vtkFollower() XActor.SetMapper(XTextMapper) XActor.SetScale(0.02, .02, .02) XActor.SetPosition(0.35, -0.05, -0.05) XActor.GetProperty().SetColor(0, 0, 0) YText = vtk.vtkVectorText() YText.SetText(yAxis) YTextMapper = vtk.vtkPolyDataMapper() YTextMapper.SetInputConnection(YText.GetOutputPort()) YActor = vtk.vtkFollower() YActor.SetMapper(YTextMapper) YActor.SetScale(0.02, .02, .02) YActor.SetPosition(-0.05, 0.35, -0.05) YActor.GetProperty().SetColor(0, 0, 0) ZText = vtk.vtkVectorText() ZText.SetText(zAxis) ZTextMapper = vtk.vtkPolyDataMapper() ZTextMapper.SetInputConnection(ZText.GetOutputPort()) ZActor = vtk.vtkFollower() ZActor.SetMapper(ZTextMapper) ZActor.SetScale(0.02, .02, .02) ZActor.SetPosition(-0.05, -0.05, 0.35) ZActor.GetProperty().SetColor(0, 0, 0) # Graphics stuff. renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetWindowName("vtk - Field.Data") # Add the actors to the renderer, set the background and size. renderer.AddActor(axesActor) renderer.AddActor(lateActor) renderer.AddActor(XActor) renderer.AddActor(YActor) renderer.AddActor(ZActor) renderer.AddActor(popActor) renderer.SetBackground(colors.GetColor3d("SlateGray")) renderWindow.SetSize(650, 480) camera = vtk.vtkCamera() camera.SetClippingRange(.274, 13.72) camera.SetFocalPoint(0.433816, 0.333131, 0.449) camera.SetPosition(-1.96987, 1.15145, 1.49053) camera.SetViewUp(0.378927, 0.911821, 0.158107) renderer.SetActiveCamera(camera) XActor.SetCamera(camera) YActor.SetCamera(camera) ZActor.SetCamera(camera) # Render and interact with the data. interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()