def move(self, u=None, deltas=None): """Move mesh according to solution `u` or from calculated vertex displacements `deltas`. """ if u is None: u = self.u if deltas is None: if self.u_values is not None: deltas = self.u_values else: deltas = _compute_uvalues(u, self.mesh) self.u_values = deltas if hasattr(self.mesh, "coordinates"): coords = self.mesh.coordinates() else: coords = self.mesh.geometry.points if coords.shape != deltas.shape: printc("ERROR: Try to move mesh with wrong solution type shape:", coords.shape, 'vs', deltas.shape, c='r') printc("Mesh is not moved. Try mode='color' in plot().", c='r') return movedpts = coords + deltas if movedpts.shape[1] == 2: #2d movedpts = np.c_[movedpts, np.zeros(movedpts.shape[0])] self.polydata(False).GetPoints().SetData( utils.numpy2vtk(movedpts, dtype=np.float)) self.polydata(False).GetPoints().Modified()
def extractCellType(self, ctype): """Extract a specific cell type and return a new UGrid.""" uarr = self._data.GetCellTypesArray() ctarrtyp = np.where(utils.vtk2numpy(uarr) == ctype)[0] uarrtyp = utils.numpy2vtk(ctarrtyp, deep=False, dtype='id') selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(uarrtyp) selection = vtk.vtkSelection() selection.AddNode(selectionNode) es = vtk.vtkExtractSelection() es.SetInputData(0, self._data) es.SetInputData(1, selection) es.Update() return UGrid(es.GetOutput())
def delaunay3D(mesh, alphaPar=0, tol=None, boundary=False): """Create 3D Delaunay triangulation of input points.""" deln = vtk.vtkDelaunay3D() if utils.isSequence(mesh): pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(utils.numpy2vtk(mesh, dtype=np.float)) pd.SetPoints(vpts) deln.SetInputData(pd) else: deln.SetInputData(mesh.GetMapper().GetInput()) deln.SetAlpha(alphaPar) deln.AlphaTetsOn() deln.AlphaTrisOff() deln.AlphaLinesOff() deln.AlphaVertsOff() if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary) deln.Update() m = TetMesh(deln.GetOutput()) return m
def _buildtetugrid(self, points, cells): ug = vtk.vtkUnstructuredGrid() if len(points) == 0: return ug if not utils.isSequence(points[0]): return ug if len(cells) == 0: return ug if not utils.isSequence(cells[0]): tets=[] nf=cells[0]+1 for i, cl in enumerate(cells): if i==nf or i==0: k = i+1 nf = cl+k cell = [cells[j+k] for j in range(cl)] tets.append(cell) cells = tets sourcePoints = vtk.vtkPoints() varr = utils.numpy2vtk(points, dtype=np.float) sourcePoints.SetData(varr) ug.SetPoints(sourcePoints) sourceTets = vtk.vtkCellArray() for f in cells: ele = vtk.vtkTetra() pid = ele.GetPointIds() for i, fi in enumerate(f): pid.SetId(i, fi) sourceTets.InsertNextCell(ele) ug.SetCells(vtk.VTK_TETRA, sourceTets) return ug
def __init__( self, inputobj=None, c='RdBu_r', alpha=(0.0, 0.0, 0.2, 0.4, 0.8, 1.0), alphaGradient=None, alphaUnit=1, mode=0, shade=False, spacing=None, dims=None, origin=None, mapper='smart', ): vtk.vtkVolume.__init__(self) BaseGrid.__init__(self) ################### if isinstance(inputobj, str): if "https://" in inputobj: from vedo.io import download inputobj = download(inputobj, verbose=False) # fpath elif os.path.isfile(inputobj): pass else: inputobj = sorted(glob.glob(inputobj)) ################### if 'gpu' in mapper: self._mapper = vtk.vtkGPUVolumeRayCastMapper() elif 'opengl_gpu' in mapper: self._mapper = vtk.vtkOpenGLGPUVolumeRayCastMapper() elif 'smart' in mapper: self._mapper = vtk.vtkSmartVolumeMapper() elif 'fixed' in mapper: self._mapper = vtk.vtkFixedPointVolumeRayCastMapper() elif isinstance(mapper, vtk.vtkMapper): self._mapper = mapper else: print("Error unknown mapper type", [mapper]) raise RuntimeError() self.SetMapper(self._mapper) ################### inputtype = str(type(inputobj)) #colors.printc('Volume inputtype', inputtype) if inputobj is None: img = vtk.vtkImageData() elif utils.isSequence(inputobj): if isinstance(inputobj[0], str): # scan sequence of BMP files ima = vtk.vtkImageAppend() ima.SetAppendAxis(2) pb = utils.ProgressBar(0, len(inputobj)) for i in pb.range(): f = inputobj[i] picr = vtk.vtkBMPReader() picr.SetFileName(f) picr.Update() mgf = vtk.vtkImageMagnitude() mgf.SetInputData(picr.GetOutput()) mgf.Update() ima.AddInputData(mgf.GetOutput()) pb.print('loading...') ima.Update() img = ima.GetOutput() else: if "ndarray" not in inputtype: inputobj = np.array(inputobj) if len(inputobj.shape) == 1: varr = utils.numpy2vtk(inputobj, dtype=np.float) else: if len(inputobj.shape) > 2: inputobj = np.transpose(inputobj, axes=[2, 1, 0]) varr = utils.numpy2vtk(inputobj.ravel(order='F'), dtype=np.float) varr.SetName('input_scalars') img = vtk.vtkImageData() if dims is not None: img.SetDimensions(dims) else: if len(inputobj.shape) == 1: colors.printc( "Error: must set dimensions (dims keyword) in Volume.", c='r') raise RuntimeError() img.SetDimensions(inputobj.shape) img.GetPointData().SetScalars(varr) #to convert rgb to numpy # img_scalar = data.GetPointData().GetScalars() # dims = data.GetDimensions() # n_comp = img_scalar.GetNumberOfComponents() # temp = utils.vtk2numpy(img_scalar) # numpy_data = temp.reshape(dims[1],dims[0],n_comp) # numpy_data = numpy_data.transpose(0,1,2) # numpy_data = np.flipud(numpy_data) elif "ImageData" in inputtype: img = inputobj elif isinstance(inputobj, Volume): img = inputobj.inputdata() elif "UniformGrid" in inputtype: img = inputobj elif hasattr( inputobj, "GetOutput"): # passing vtk object, try extract imagdedata if hasattr(inputobj, "Update"): inputobj.Update() img = inputobj.GetOutput() elif isinstance(inputobj, str): from vedo.io import loadImageData, download if "https://" in inputobj: inputobj = download(inputobj, verbose=False) img = loadImageData(inputobj) else: colors.printc("Volume(): cannot understand input type:\n", inputtype, c='r') return if dims is not None: img.SetDimensions(dims) if origin is not None: img.SetOrigin(origin) ### DIFFERENT from volume.origin()! if spacing is not None: img.SetSpacing(spacing) self._data = img self._mapper.SetInputData(img) self.mode(mode).color(c).alpha(alpha).alphaGradient(alphaGradient) self.GetProperty().SetShade(True) self.GetProperty().SetInterpolationType(1) self.GetProperty().SetScalarOpacityUnitDistance(alphaUnit) # remember stuff: self._mode = mode self._color = c self._alpha = alpha self._alphaGrad = alphaGradient self._alphaUnit = alphaUnit
def __init__(self, inputobj=None): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None self.name = "UGrid" ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() elif utils.isSequence(inputobj): pts, cells, celltypes = inputobj self._data = vtk.vtkUnstructuredGrid() if not utils.isSequence(cells[0]): tets = [] nf = cells[0] + 1 for i, cl in enumerate(cells): if i == nf or i == 0: k = i + 1 nf = cl + k cell = [cells[j + k] for j in range(cl)] tets.append(cell) cells = tets # This would fill the points and use those to define orientation vpts = utils.numpy2vtk(pts, dtype=float) points = vtk.vtkPoints() points.SetData(vpts) self._data.SetPoints(points) # This fill the points and use cells to define orientation # points = vtk.vtkPoints() # for c in cells: # for pid in c: # points.InsertNextPoint(pts[pid]) # self._data.SetPoints(points) # Fill cells # https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html for i, ct in enumerate(celltypes): cell_conn = cells[i] if ct == vtk.VTK_HEXAHEDRON: cell = vtk.vtkHexahedron() elif ct == vtk.VTK_TETRA: cell = vtk.vtkTetra() elif ct == vtk.VTK_VOXEL: cell = vtk.vtkVoxel() elif ct == vtk.VTK_WEDGE: cell = vtk.vtkWedge() elif ct == vtk.VTK_PYRAMID: cell = vtk.vtkPyramid() elif ct == vtk.VTK_HEXAGONAL_PRISM: cell = vtk.vtkHexagonalPrism() elif ct == vtk.VTK_PENTAGONAL_PRISM: cell = vtk.vtkPentagonalPrism() else: print("UGrid: cell type", ct, "not implemented. Skip.") continue cpids = cell.GetPointIds() for j, pid in enumerate(cell_conn): cpids.SetId(j, pid) self._data.InsertNextCell(ct, cpids) elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) self._data = loadUnStructuredGrid(inputobj) self.filename = inputobj else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c='r') return # self._mapper = vtk.vtkDataSetMapper() self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping( settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters( pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return # now fill the representation of the vtk unstr grid sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper) self.property = self.GetProperty()
def __init__(self, inputobj=None): vtk.vtkImageSlice.__init__(self) Base3DProp.__init__(self) BaseVolume.__init__(self) self._mapper = vtk.vtkImageResliceMapper() self._mapper.SliceFacesCameraOn() self._mapper.SliceAtFocalPointOn() self._mapper.SetAutoAdjustImageQuality(False) self._mapper.BorderOff() self.lut = None self.property = vtk.vtkImageProperty() self.property.SetInterpolationTypeToLinear() self.SetProperty(self.property) ################### if isinstance(inputobj, str): if "https://" in inputobj: from vedo.io import download inputobj = download(inputobj, verbose=False) # fpath elif os.path.isfile(inputobj): pass else: inputobj = sorted(glob.glob(inputobj)) ################### inputtype = str(type(inputobj)) if inputobj is None: img = vtk.vtkImageData() if isinstance(inputobj, Volume): img = inputobj.imagedata() self.lut = utils.ctf2lut(inputobj) elif utils.isSequence(inputobj): if isinstance(inputobj[0], str): # scan sequence of BMP files ima = vtk.vtkImageAppend() ima.SetAppendAxis(2) pb = utils.ProgressBar(0, len(inputobj)) for i in pb.range(): f = inputobj[i] picr = vtk.vtkBMPReader() picr.SetFileName(f) picr.Update() mgf = vtk.vtkImageMagnitude() mgf.SetInputData(picr.GetOutput()) mgf.Update() ima.AddInputData(mgf.GetOutput()) pb.print('loading...') ima.Update() img = ima.GetOutput() else: if "ndarray" not in inputtype: inputobj = np.array(inputobj) if len(inputobj.shape) == 1: varr = utils.numpy2vtk(inputobj, dtype=float) else: if len(inputobj.shape) > 2: inputobj = np.transpose(inputobj, axes=[2, 1, 0]) varr = utils.numpy2vtk(inputobj.ravel(order='F'), dtype=float) varr.SetName('input_scalars') img = vtk.vtkImageData() img.SetDimensions(inputobj.shape) img.GetPointData().AddArray(varr) img.GetPointData().SetActiveScalars(varr.GetName()) elif "ImageData" in inputtype: img = inputobj elif isinstance(inputobj, Volume): img = inputobj.inputdata() elif "UniformGrid" in inputtype: img = inputobj elif hasattr( inputobj, "GetOutput"): # passing vtk object, try extract imagdedata if hasattr(inputobj, "Update"): inputobj.Update() img = inputobj.GetOutput() elif isinstance(inputobj, str): from vedo.io import loadImageData, download if "https://" in inputobj: inputobj = download(inputobj, verbose=False) img = loadImageData(inputobj) else: colors.printc("VolumeSlice: cannot understand input type:\n", inputtype, c='r') return self._data = img self._mapper.SetInputData(img) self.SetMapper(self._mapper)