text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): """ Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :param alpha: mesh transparency. Can be a ``list`` of values one for each vertex. :type alpha: float, list :param int bands: group scalars in this number of bins, typically to form bands or stripes. :param float vmin: clip scalars to this minimum value :param float vmax: clip scalars to this maximum value .. hint:: |mesh_coloring| |mesh_coloring.py|_ |mesh_alphas| |mesh_alphas.py|_ |mesh_bands| |mesh_bands.py|_ |mesh_custom| |mesh_custom.py|_ """
poly = self.polydata(False) if isinstance(scalars, str): # if a name is passed scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) n = len(scalars) useAlpha = False if n != poly.GetNumberOfPoints(): colors.printc('~times pointColors Error: nr. of scalars != nr. of points', n, poly.GetNumberOfPoints(), c=1) if utils.isSequence(alpha): useAlpha = True if len(alpha) > n: colors.printc('~times pointColors Error: nr. of scalars < nr. of alpha values', n, len(alpha), c=1) exit() if bands: scalars = utils.makeBands(scalars, bands) if vmin is None: vmin = np.min(scalars) if vmax is None: vmax = np.max(scalars) lut = vtk.vtkLookupTable() # build the look-up table if utils.isSequence(cmap): sname = "pointColors_custom" lut.SetNumberOfTableValues(len(cmap)) lut.Build() for i, c in enumerate(cmap): col = colors.getColor(c) r, g, b = col if useAlpha: lut.SetTableValue(i, r, g, b, alpha[i]) else: lut.SetTableValue(i, r, g, b, alpha) elif isinstance(cmap, vtk.vtkLookupTable): sname = "pointColors_lut" lut = cmap else: if isinstance(cmap, str): sname = "pointColors_" + cmap else: sname = "pointColors" lut.SetNumberOfTableValues(512) lut.Build() for i in range(512): r, g, b = colors.colorMap(i, cmap, 0, 512) if useAlpha: idx = int(i / 512 * len(alpha)) lut.SetTableValue(i, r, g, b, alpha[idx]) else: lut.SetTableValue(i, r, g, b, alpha) arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(sname) self.mapper.SetScalarRange(vmin, vmax) self.mapper.SetLookupTable(lut) self.mapper.ScalarVisibilityOn() poly.GetPointData().SetScalars(arr) poly.GetPointData().SetActiveScalars(sname) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPointScalars(self, scalars, name): """ Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """
poly = self.polydata(False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('~times pointScalars Error: Number of scalars != nr. of points', len(scalars), poly.GetNumberOfPoints(), c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCellScalars(self, scalars, name): """ Add cell scalars to the actor's polydata assigning it a name. """
poly = self.polydata(False) if isinstance(scalars, str): scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) if len(scalars) != poly.GetNumberOfCells(): colors.printc("~times Number of scalars != nr. of cells", c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetCellData().AddArray(arr) poly.GetCellData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPointVectors(self, vectors, name): """ Add a point vector field to the actor's polydata assigning it a name. """
poly = self.polydata(False) if len(vectors) != poly.GetNumberOfPoints(): colors.printc('~times addPointVectors Error: Number of vectors != nr. of points', len(vectors), poly.GetNumberOfPoints(), c=1) exit() arr = vtk.vtkDoubleArray() arr.SetNumberOfComponents(3) arr.SetName(name) for v in vectors: arr.InsertNextTuple(v) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveVectors(name) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addIDs(self, asfield=False): """ Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data. """
ids = vtk.vtkIdFilter() ids.SetInputData(self.poly) ids.PointIdsOn() ids.CellIdsOn() if asfield: ids.FieldDataOn() else: ids.FieldDataOff() ids.Update() return self.updateMesh(ids.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addCurvatureScalars(self, method=0, lut=None): """ Build an ``Actor`` that contains the color coded surface curvature calculated in three different ways. :param int method: 0-gaussian, 1-mean, 2-max, 3-min curvature. :param float lut: optional look up table. :Example: .. code-block:: python from vtkplotter import * t = Torus().addCurvatureScalars() show(t) |curvature| """
curve = vtk.vtkCurvatures() curve.SetInputData(self.poly) curve.SetCurvatureType(method) curve.Update() self.poly = curve.GetOutput() scls = self.poly.GetPointData().GetScalars().GetRange() print("curvature(): scalar range is", scls) self.mapper.SetInputData(self.poly) if lut: self.mapper.SetLookupTable(lut) self.mapper.SetUseLookupTableScalarRange(1) self.mapper.Update() self.Modified() self.mapper.ScalarVisibilityOn() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalars(self, name_or_idx=None, datatype="point"): """ Retrieve point or cell scalars using array name or index number. If no ``name`` is given return the list of names of existing arrays. .. hint:: |mesh_coloring.py|_ """
poly = self.polydata(False) if name_or_idx is None: # get mode behaviour ncd = poly.GetCellData().GetNumberOfArrays() npd = poly.GetPointData().GetNumberOfArrays() nfd = poly.GetFieldData().GetNumberOfArrays() arrs = [] for i in range(npd): print(i, "PointData", poly.GetPointData().GetArrayName(i)) arrs.append(["PointData", poly.GetPointData().GetArrayName(i)]) for i in range(ncd): print(i, "CellData", poly.GetCellData().GetArrayName(i)) arrs.append(["CellData", poly.GetCellData().GetArrayName(i)]) for i in range(nfd): print(i, "FieldData", poly.GetFieldData().GetArrayName(i)) arrs.append(["FieldData", poly.GetFieldData().GetArrayName(i)]) return arrs else: # set mode if "point" in datatype.lower(): data = poly.GetPointData() elif "cell" in datatype.lower(): data = poly.GetCellData() elif "field" in datatype.lower(): data = poly.GetFieldData() else: colors.printc("~times Error in scalars(): unknown datatype", datatype, c=1) exit() if isinstance(name_or_idx, int): name = data.GetArrayName(name_or_idx) if name is None: return None data.SetActiveScalars(name) return vtk_to_numpy(data.GetArray(name)) elif isinstance(name_or_idx, str): arr = data.GetArray(name_or_idx) if arr is None: return None data.SetActiveScalars(name_or_idx) return vtk_to_numpy(arr) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subdivide(self, N=1, method=0): """Increase the number of vertices of a surface mesh. :param int N: number of subdivisions. :param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3) .. hint:: |tutorial_subdivide| |tutorial.py|_ """
triangles = vtk.vtkTriangleFilter() triangles.SetInputData(self.polydata()) triangles.Update() originalMesh = triangles.GetOutput() if method == 0: sdf = vtk.vtkLoopSubdivisionFilter() elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter() elif method == 2: sdf = vtk.vtkAdaptiveSubdivisionFilter() elif method == 3: sdf = vtk.vtkButterflySubdivisionFilter() else: colors.printc("~times Error in subdivide: unknown method.", c="r") exit() if method != 2: sdf.SetNumberOfSubdivisions(N) sdf.SetInputData(originalMesh) sdf.Update() return self.updateMesh(sdf.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True): """ Downsample the number of vertices in a mesh. :param float fraction: the desired target of reduction. :param int N: the desired number of final points (**fraction** is recalculated based on it). :param bool boundaries: (True), decide whether to leave boundaries untouched or not. .. note:: Setting ``fraction=0.1`` leaves 10% of the original nr of vertices. .. hint:: |skeletonize| |skeletonize.py|_ """
poly = self.polydata(True) if N: # N = desired number of points Np = poly.GetNumberOfPoints() fraction = float(N) / Np if fraction >= 1: return self decimate = vtk.vtkDecimatePro() decimate.SetInputData(poly) decimate.SetTargetReduction(1 - fraction) decimate.PreserveTopologyOff() if boundaries: decimate.BoundaryVertexDeletionOff() else: decimate.BoundaryVertexDeletionOn() decimate.Update() if verbose: print("Nr. of pts, input:", poly.GetNumberOfPoints(), end="") print(" output:", decimate.GetOutput().GetNumberOfPoints()) return self.updateMesh(decimate.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addGaussNoise(self, sigma): """ Add gaussian noise. :param float sigma: sigma is expressed in percent of the diagonal size of actor. :Example: .. code-block:: python from vtkplotter import Sphere Sphere().addGaussNoise(1.0).show() """
sz = self.diagonalSize() pts = self.coordinates() n = len(pts) ns = np.random.randn(n, 3) * sigma * sz / 100 vpts = vtk.vtkPoints() vpts.SetNumberOfPoints(n) vpts.SetData(numpy_to_vtk(pts + ns, deep=True)) self.poly.SetPoints(vpts) self.poly.GetPoints().Modified() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothLaplacian(self, niter=15, relaxfact=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using `Laplacian` smoothing. :param int niter: number of iterations. :param float relaxfact: relaxation factor. Small `relaxfact` and large `niter` are more stable. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers.py|_ """
poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetRelaxationFactor(relaxfact) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.BoundarySmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.GenerateErrorScalarsOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothWSinc(self, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using the `Windowed Sinc` function interpolation kernel. :param int niter: number of iterations. :param float passBand: set the passband value for the windowed sinc filter. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers| |mesh_smoothers.py|_ """
poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkWindowedSincPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.SetPassBand(passBand) smoothFilter.NormalizeCoordinatesOn() smoothFilter.NonManifoldSmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fillHoles(self, size=None): """Identifies and fills holes in input mesh. Holes are identified by locating boundary edges, linking them together into loops, and then triangulating the resulting loops. :param float size: approximate limit to the size of the hole that can be filled. Example: |fillholes.py|_ """
fh = vtk.vtkFillHolesFilter() if not size: mb = self.maxBoundSize() size = mb / 10 fh.SetHoleSize(size) fh.SetInputData(self.poly) fh.Update() return self.updateMesh(fh.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, filename="mesh.vtk", binary=True): """ Write actor's polydata in its current transformation to file. """
import vtkplotter.vtkio as vtkio return vtkio.write(self, filename, binary)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalAt(self, i): """Return the normal vector at vertex point `i`."""
normals = self.polydata(True).GetPointData().GetNormals() return np.array(normals.GetTuple(i))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normals(self, cells=False): """Retrieve vertex normals as a numpy array. :params bool cells: if `True` return cell normals. """
if cells: vtknormals = self.polydata(True).GetCellData().GetNormals() else: vtknormals = self.polydata(True).GetPointData().GetNormals() return vtk_to_numpy(vtknormals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def polydata(self, transformed=True): """ Returns the ``vtkPolyData`` of an ``Actor``. .. note:: If ``transformed=True`` returns a copy of polydata that corresponds to the current actor's position in space. .. hint:: |quadratic_morphing| |quadratic_morphing.py|_ """
if not transformed: if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly M = self.GetMatrix() if utils.isIdentity(M): if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly # if identity return the original polydata # otherwise make a copy that corresponds to # the actual position in space of the actor transform = vtk.vtkTransform() transform.SetMatrix(M) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(self.poly) tp.Update() return tp.GetOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, u_function): """ Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes. """
if self.mesh: self.u = u_function delta = [u_function(p) for p in self.mesh.coordinates()] movedpts = self.mesh.coordinates() + delta self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts)) self.poly.GetPoints().Modified() self.u_values = delta else: colors.printc("Warning: calling move() but actor.mesh is", self.mesh, c=3) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setTransform(self, T): """ Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified. """
if isinstance(T, vtk.vtkMatrix4x4): self.SetUserMatrix(T) else: try: self.SetUserTransform(T) except TypeError: colors.printc('~time Error in setTransform(): consider transformPolydata() instead.', c=1) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isInside(self, point, tol=0.0001): """ Return True if point is inside a polydata closed surface. """
poly = self.polydata(True) points = vtk.vtkPoints() points.InsertNextPoint(point) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) sep.CheckSurfaceOff() sep.SetInputData(pointsPolydata) sep.SetSurfaceData(poly) sep.Update() return sep.IsInside(0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cellCenters(self): """Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_ """
vcen = vtk.vtkCellCenters() vcen.SetInputData(self.polydata(True)) vcen.Update() return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectedVertices(self, index, returnIds=False): """Find all vertices connected to an input vertex specified by its index. :param bool returnIds: return vertex IDs instead of vertex coordinates. .. hint:: |connVtx| |connVtx.py|_ """
mesh = self.polydata() cellIdList = vtk.vtkIdList() mesh.GetPointCells(index, cellIdList) idxs = [] for i in range(cellIdList.GetNumberOfIds()): pointIdList = vtk.vtkIdList() mesh.GetCellPoints(cellIdList.GetId(i), pointIdList) for j in range(pointIdList.GetNumberOfIds()): idj = pointIdList.GetId(j) if idj == index: continue if idj in idxs: continue idxs.append(idj) if returnIds: return idxs else: trgp = [] for i in idxs: p = [0, 0, 0] mesh.GetPoints().GetPoint(i, p) trgp.append(p) return np.array(trgp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectedCells(self, index, returnIds=False): """Find all cellls connected to an input vertex specified by its index."""
# Find all cells connected to point index dpoly = self.polydata() cellPointIds = vtk.vtkIdList() dpoly.GetPointCells(index, cellPointIds) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) rids = [] for k in range(cellPointIds.GetNumberOfIds()): cid = cellPointIds.GetId(k) ids.InsertNextValue(cid) rids.append(int(cid)) if returnIds: return rids selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, dpoly) extractSelection.SetInputData(1, selection) extractSelection.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(extractSelection.GetOutput()) gf.Update() return Actor(gf.GetOutput()).lw(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersectWithLine(self, p0, p1): """Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code-block:: python from vtkplotter import * s = Spring(alpha=0.2) pts = s.intersectWithLine([0,0,0], [1,0.1,0]) ln = Line([0,0,0], [1,0.1,0], c='blue') ps = Points(pts, r=10, c='r') show(s, ln, ps, bg='white') |intline| """
if not self.line_locator: line_locator = vtk.vtkOBBTree() line_locator.SetDataSet(self.polydata(True)) line_locator.BuildLocator() self.line_locator = line_locator intersectPoints = vtk.vtkPoints() intersection = [0, 0, 0] self.line_locator.IntersectWithLine(p0, p1, intersectPoints, None) pts = [] for i in range(intersectPoints.GetNumberOfPoints()): intersectPoints.GetPoint(i, intersection) pts.append(list(intersection)) return pts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getActors(self): """Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``."""
cl = vtk.vtkPropCollection() self.GetActors(cl) self.actors = [] cl.InitTraversal() for i in range(self.GetNumberOfPaths()): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) if act.GetPickable(): self.actors.append(act) return self.actors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagonalSize(self): """Return the maximum diagonal size of the ``Actors`` of the ``Assembly``."""
szs = [a.diagonalSize() for a in self.actors] return np.max(szs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """
th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) elif vmin is not None: th.ThresholdByUpper(vmin) elif vmax is not None: th.ThresholdByLower(vmax) if replaceWith: th.ReplaceOutOn() th.SetOutValue(replaceWith) th.Update() self.image = th.GetOutput() self.mapper.SetInputData(self.image) self.mapper.Modified() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None): """Read OFF file format."""
if not os.path.exists(filename): colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1) return None f = open(filename, "r") lines = f.readlines() f.close() vertices = [] faces = [] NumberOfVertices = None i = -1 for text in lines: if len(text) == 0: continue if text == '\n': continue if "#" in text: continue if "OFF" in text: continue ts = text.split() n = len(ts) if not NumberOfVertices and n > 1: NumberOfVertices, NumberOfFaces = int(ts[0]), int(ts[1]) continue i += 1 if i < NumberOfVertices and n == 3: x, y, z = float(ts[0]), float(ts[1]), float(ts[2]) vertices.append([x, y, z]) ids = [] if NumberOfVertices <= i < (NumberOfVertices + NumberOfFaces + 1) and n > 2: ids += [int(x) for x in ts[1:]] faces.append(ids) return Actor(buildPolyData(vertices, faces), c, alpha, wire, bc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file."""
if not os.path.isfile(filename): colors.printc("~noentry File not found:", filename, c=1) return None if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in filename.lower(): reader = vtk.vtkSLCReader() if not reader.CanReadFile(filename): colors.printc("~prohibited Sorry bad slc file " + filename, c=1) exit(1) elif ".vti" in filename.lower(): reader = vtk.vtkXMLImageDataReader() elif ".mhd" in filename.lower(): reader = vtk.vtkMetaImageReader() reader.SetFileName(filename) reader.Update() image = reader.GetOutput() if len(spacing) == 3: image.SetSpacing(spacing[0], spacing[1], spacing[2]) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(objct, fileoutput, binary=True): """ Write 3D object to file. Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp. """
obj = objct if isinstance(obj, Actor): obj = objct.polydata(True) elif isinstance(obj, vtk.vtkActor): obj = objct.GetMapper().GetInput() fr = fileoutput.lower() if ".vtk" in fr: w = vtk.vtkPolyDataWriter() elif ".ply" in fr: w = vtk.vtkPLYWriter() elif ".stl" in fr: w = vtk.vtkSTLWriter() elif ".vtp" in fr: w = vtk.vtkXMLPolyDataWriter() elif ".vtm" in fr: g = vtk.vtkMultiBlockDataGroupFilter() for ob in objct: g.AddInputData(ob) g.Update() mb = g.GetOutputDataObject(0) wri = vtk.vtkXMLMultiBlockDataWriter() wri.SetInputData(mb) wri.SetFileName(fileoutput) wri.Write() return mb elif ".xyz" in fr: w = vtk.vtkSimplePointsWriter() elif ".byu" in fr or fr.endswith(".g"): w = vtk.vtkBYUWriter() elif ".obj" in fr: w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace(".obj", "")) colors.printc("~target Please use write(vp.window)", c=3) w.SetInputData(obj) w.Update() colors.printc("~save Saved file: " + fileoutput, c="g") return objct elif ".tif" in fr: w = vtk.vtkTIFFWriter() w.SetFileDimensionality(len(obj.GetDimensions())) elif ".vti" in fr: w = vtk.vtkXMLImageDataWriter() elif ".png" in fr: w = vtk.vtkPNGWriter() elif ".jpg" in fr: w = vtk.vtkJPEGWriter() elif ".bmp" in fr: w = vtk.vtkBMPWriter() else: colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r") return objct try: if not ".tif" in fr and not ".vti" in fr: if binary and not ".tif" in fr and not ".vti" in fr: w.SetFileTypeToBinary() else: w.SetFileTypeToASCII() w.SetInputData(obj) w.SetFileName(fileoutput) w.Write() colors.printc("~save Saved file: " + fileoutput, c="g") except Exception as e: colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r") return objct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertNeutral2Xml(infile, outfile=None): """Convert Neutral file format to Dolfin XML."""
f = open(infile, "r") lines = f.readlines() f.close() ncoords = int(lines[0]) fdolf_coords = [] for i in range(1, ncoords + 1): x, y, z = lines[i].split() fdolf_coords.append([float(x), float(y), float(z)]) ntets = int(lines[ncoords + 1]) idolf_tets = [] for i in range(ncoords + 2, ncoords + ntets + 2): text = lines[i].split() v0, v1, v2, v3 = text[1], text[2], text[3], text[4] idolf_tets.append([int(v0) - 1, int(v1) - 1, int(v2) - 1, int(v3) - 1]) if outfile: # write dolfin xml outF = open(outfile, "w") outF.write('<?xml version="1.0" encoding="UTF-8"?>\n') outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n') outF.write(' <mesh celltype="tetrahedron" dim="3">\n') outF.write(' <vertices size="' + str(ncoords) + '">\n') for i in range(ncoords): x, y, z = fdolf_coords[i] outF.write(' <vertex index="'+str(i) + '" x="'+str(x)+'" y="'+str(y)+'" z="'+str(z)+'"/>\n') outF.write(' </vertices>\n') outF.write(' <cells size="' + str(ntets) + '">\n') for i in range(ntets): v0, v1, v2, v3 = idolf_tets[i] outF.write(' <tetrahedron index="'+str(i) + '" v0="'+str(v0)+'" v1="'+str(v1)+'" v2="'+str(v2)+'" v3="'+str(v3)+'"/>\n') outF.write(' </cells>\n') outF.write(" </mesh>\n") outF.write("</dolfin>\n") outF.close() return fdolf_coords, idolf_tets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def screenshot(filename="screenshot.png"): """ Save a screenshot of the current rendering window. """
if not settings.plotter_instance.window: colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1) return w2if = vtk.vtkWindowToImageFilter() w2if.ShouldRerenderOff() w2if.SetInput(settings.plotter_instance.window) w2if.ReadFrontBufferOff() # read from the back buffer w2if.Update() pngwriter = vtk.vtkPNGWriter() pngwriter.SetFileName(filename) pngwriter.SetInputConnection(w2if.GetOutputPort()) pngwriter.Write()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addFrame(self): """Add frame to current video."""
fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png" screenshot(fr) self.frames.append(fr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self, pause=0): """Insert a `pause`, in seconds."""
fr = self.frames[-1] n = int(self.fps * pause) for i in range(n): fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png" self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Render the video and write to file."""
if self.duration: _fps = len(self.frames) / float(self.duration) colors.printc("Recalculated video FPS to", round(_fps, 3), c="yellow") else: _fps = int(_fps) self.name = self.name.split('.')[0]+'.mp4' out = os.system("ffmpeg -loglevel panic -y -r " + str(_fps) + " -i /tmp/vpvid/%01d.png "+self.name) if out: colors.printc("ffmpeg returning error", c=1) colors.printc("~save Video saved as", self.name, c="green") return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_fields(u, u_old, v_old, a_old): """Update fields at the end of each time step."""
# Get vectors (references) u_vec, u0_vec = u.vector(), u_old.vector() v0_vec, a0_vec = v_old.vector(), a_old.vector() # use update functions using vector arguments a_vec = update_a(u_vec, u0_vec, v0_vec, a0_vec, ufl=False) v_vec = update_v(a_vec, u0_vec, v0_vec, a0_vec, ufl=False) # Update (u_old <- u) v_old.vector()[:], a_old.vector()[:] = v_vec, a_vec u_old.vector()[:] = u.vector()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_project(v, V, u=None): """Element-wise projection using LocalSolver"""
dv = TrialFunction(V) v_ = TestFunction(V) a_proj = inner(dv, v_)*dx b_proj = inner(v, v_)*dx solver = LocalSolver(a_proj, b_proj) solver.factorize() if u is None: u = Function(V) solver.solve_local_rhs(u) return u else: solver.solve_local_rhs(u) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Point(pos=(0, 0, 0), r=12, c="red", alpha=1): """Create a simple point actor."""
if len(pos) == 2: pos = (pos[0], pos[1], 0) actor = Points([pos], r, c, alpha) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Tube(points, r=1, c="r", alpha=1, res=12): """Build a tube along the line defined by a set of points. :param r: constant radius or list of radii. :type r: float, list :param c: constant color or list of colors for each point. :type c: float, list .. hint:: |ribbon| |ribbon.py|_ |tube| |tube.py|_ """
ppoints = vtk.vtkPoints() # Generate the polyline ppoints.SetData(numpy_to_vtk(points, deep=True)) lines = vtk.vtkCellArray() lines.InsertNextCell(len(points)) for i in range(len(points)): lines.InsertCellPoint(i) polyln = vtk.vtkPolyData() polyln.SetPoints(ppoints) polyln.SetLines(lines) tuf = vtk.vtkTubeFilter() tuf.CappingOn() tuf.SetNumberOfSides(res) tuf.SetInputData(polyln) if utils.isSequence(r): arr = numpy_to_vtk(np.ascontiguousarray(r), deep=True) arr.SetName("TubeRadius") polyln.GetPointData().AddArray(arr) polyln.GetPointData().SetActiveScalars("TubeRadius") tuf.SetVaryRadiusToVaryRadiusByAbsoluteScalar() else: tuf.SetRadius(r) usingColScals = False if utils.isSequence(c) and len(c) != 3: usingColScals = True cc = vtk.vtkUnsignedCharArray() cc.SetName("TubeColors") cc.SetNumberOfComponents(3) cc.SetNumberOfTuples(len(c)) for i, ic in enumerate(c): r, g, b = colors.getColor(ic) cc.InsertTuple3(i, int(255 * r), int(255 * g), int(255 * b)) polyln.GetPointData().AddArray(cc) c = None tuf.Update() polytu = tuf.GetOutput() actor = Actor(polytu, c=c, alpha=alpha, computeNormals=0) actor.phong() if usingColScals: actor.mapper.SetScalarModeToUsePointFieldData() actor.mapper.ScalarVisibilityOn() actor.mapper.SelectColorArray("TubeColors") actor.mapper.Modified() actor.base = np.array(points[0]) actor.top = np.array(points[-1]) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """
if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.vtkPoints() # Generate the polyline1 ppoints1.SetData(numpy_to_vtk(line1, deep=True)) lines1 = vtk.vtkCellArray() lines1.InsertNextCell(len(line1)) for i in range(len(line1)): lines1.InsertCellPoint(i) poly1 = vtk.vtkPolyData() poly1.SetPoints(ppoints1) poly1.SetLines(lines1) ppoints2 = vtk.vtkPoints() # Generate the polyline2 ppoints2.SetData(numpy_to_vtk(line2, deep=True)) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(len(line2)) for i in range(len(line2)): lines2.InsertCellPoint(i) poly2 = vtk.vtkPolyData() poly2.SetPoints(ppoints2) poly2.SetLines(lines2) # build the lines lines1 = vtk.vtkCellArray() lines1.InsertNextCell(poly1.GetNumberOfPoints()) for i in range(poly1.GetNumberOfPoints()): lines1.InsertCellPoint(i) polygon1 = vtk.vtkPolyData() polygon1.SetPoints(ppoints1) polygon1.SetLines(lines1) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(poly2.GetNumberOfPoints()) for i in range(poly2.GetNumberOfPoints()): lines2.InsertCellPoint(i) polygon2 = vtk.vtkPolyData() polygon2.SetPoints(ppoints2) polygon2.SetLines(lines2) mergedPolyData = vtk.vtkAppendPolyData() mergedPolyData.AddInputData(polygon1) mergedPolyData.AddInputData(polygon2) mergedPolyData.Update() rsf = vtk.vtkRuledSurfaceFilter() rsf.CloseSurfaceOff() rsf.SetRuledModeToResample() rsf.SetResolution(res[0], res[1]) rsf.SetInputData(mergedPolyData.GetOutput()) rsf.Update() actor = Actor(rsf.GetOutput(), c=c, alpha=alpha) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FlatArrow(line1, line2, c="m", alpha=1, tipSize=1, tipWidth=1): """Build a 2D arrow in 3D space by joining two close lines. .. hint:: |flatarrow| |flatarrow.py|_ """
if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() sm1, sm2 = np.array(line1[-1]), np.array(line2[-1]) v = (sm1-sm2)/3*tipWidth p1 = sm1+v p2 = sm2-v pm1 = (sm1+sm2)/2 pm2 = (np.array(line1[-2])+np.array(line2[-2]))/2 pm12 = pm1-pm2 tip = pm12/np.linalg.norm(pm12)*np.linalg.norm(v)*3*tipSize/tipWidth + pm1 line1.append(p1) line1.append(tip) line2.append(p2) line2.append(tip) resm = max(100, len(line1)) actor = Ribbon(line1, line2, alpha=alpha, c=c, res=(resm, 1)).phong() settings.collectable_actors.pop() settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral", bc="darkgreen", lw=1, alpha=1, followcam=False): """ Build a 2D polygon of `nsides` of radius `r` oriented as `normal`. :param followcam: if `True` the text will auto-orient itself to the active camera. A ``vtkCamera`` object can also be passed. :type followcam: bool, vtkCamera |Polygon| """
ps = vtk.vtkRegularPolygonSource() ps.SetNumberOfSides(nsides) ps.SetRadius(r) ps.SetNormal(-np.array(normal)) ps.Update() tf = vtk.vtkTriangleFilter() tf.SetInputConnection(ps.GetOutputPort()) tf.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tf.GetOutputPort()) if followcam: actor = vtk.vtkFollower() if isinstance(followcam, vtk.vtkCamera): actor.SetCamera(followcam) else: actor.SetCamera(settings.plotter_instance.camera) else: actor = Actor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Rectangle(p1=(0, 0, 0), p2=(2, 1, 0), c="k", bc="dg", lw=1, alpha=1, texture=None): """Build a rectangle in the xy plane identified by two corner points."""
p1 = np.array(p1) p2 = np.array(p2) pos = (p1 + p2) / 2 length = abs(p2[0] - p1[0]) height = abs(p2[1] - p1[1]) return Plane(pos, [0, 0, -1], length, height, c, bc, alpha, texture)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Disc( pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """
ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(ps.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(pd) actor = Actor() # vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24): """Build a sphere at position `pos` of radius `r`. |Sphere| """
ss = vtk.vtkSphereSource() ss.SetRadius(r) ss.SetThetaResolution(2 * res) ss.SetPhiResolution(res) ss.Update() pd = ss.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Earth(pos=(0, 0, 0), r=1, lw=1): """Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_ """
import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() earthMapper.SetInputConnection(tss.GetOutputPort()) earthActor = Actor(c="w") earthActor.SetMapper(earthMapper) atext = vtk.vtkTexture() pnmReader = vtk.vtkPNMReader() cdir = os.path.dirname(__file__) if cdir == "": cdir = "." fn = settings.textures_path + "earth.ppm" pnmReader.SetFileName(fn) atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOn() earthActor.SetTexture(atext) if not lw: earthActor.SetPosition(pos) return earthActor es = vtk.vtkEarthSource() es.SetRadius(r / 0.995) earth2Mapper = vtk.vtkPolyDataMapper() earth2Mapper.SetInputConnection(es.GetOutputPort()) earth2Actor = Actor() # vtk.vtkActor() earth2Actor.SetMapper(earth2Mapper) earth2Mapper.ScalarVisibilityOff() earth2Actor.GetProperty().SetLineWidth(lw) ass = Assembly([earthActor, earth2Actor]) ass.SetPosition(pos) settings.collectable_actors.append(ass) return ass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Grid( pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=1, c="g", bc="darkgreen", lw=1, alpha=1, resx=10, resy=10, ): """Return a grid plane. .. hint:: |brownian2D| |brownian2D.py|_ """
ps = vtk.vtkPlaneSource() ps.SetResolution(resx, resy) ps.Update() poly0 = ps.GetOutput() t0 = vtk.vtkTransform() t0.Scale(sx, sy, 1) tf0 = vtk.vtkTransformPolyDataFilter() tf0.SetInputData(poly0) tf0.SetTransform(t0) tf0.Update() poly = tf0.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(lw) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane| """
if sy is None: sy = sx ps = vtk.vtkPlaneSource() ps.SetResolution(1, 1) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(ps.GetOutputPort()) tri.Update() poly = tri.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.Scale(sx, sy, 1) t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Box(pos=(0, 0, 0), length=1, width=2, height=3, normal=(0, 0, 1), c="g", alpha=1, texture=None): """ Build a box of dimensions `x=length, y=width and z=height` oriented along vector `normal`. .. hint:: |aspring| |aspring.py|_ """
src = vtk.vtkCubeSource() src.SetXLength(length) src.SetYLength(width) src.SetZLength(height) src.Update() poly = src.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cube(pos=(0, 0, 0), side=1, normal=(0, 0, 1), c="g", alpha=1, texture=None): """Build a cube of size `side` oriented along vector `normal`. .. hint:: |colorcubes| |colorcubes.py|_ """
return Box(pos, side, side, side, normal, c, alpha, texture)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Spring( startPoint=(0, 0, 0), endPoint=(1, 0, 0), coils=20, r=0.1, r2=None, thickness=None, c="grey", alpha=1, ): """ Build a spring of specified nr of `coils` between `startPoint` and `endPoint`. :param int coils: number of coils :param float r: radius at start point :param float r2: radius at end point :param float thickness: thickness of the coil section .. hint:: |aspring| |aspring.py|_ """
diff = endPoint - np.array(startPoint) length = np.linalg.norm(diff) if not length: return None if not r: r = length / 20 trange = np.linspace(0, length, num=50 * coils) om = 6.283 * (coils - 0.5) / length if not r2: r2 = r pts = [] for t in trange: f = (length - t) / length rd = r * f + r2 * (1 - f) pts.append([rd * np.cos(om * t), rd * np.sin(om * t), t]) pts = [[0, 0, 0]] + pts + [[0, 0, length]] diff = diff / length theta = np.arccos(diff[2]) phi = np.arctan2(diff[1], diff[0]) sp = Line(pts).polydata(False) t = vtk.vtkTransform() t.RotateZ(phi * 57.3) t.RotateY(theta * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(sp) tf.SetTransform(t) tf.Update() tuf = vtk.vtkTubeFilter() tuf.SetNumberOfSides(12) tuf.CappingOn() tuf.SetInputData(tf.GetOutput()) if not thickness: thickness = r / 10 tuf.SetRadius(thickness) tuf.Update() poly = tuf.GetOutput() actor = Actor(poly, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(startPoint) actor.base = np.array(startPoint) actor.top = np.array(endPoint) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cylinder(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="teal", alpha=1, res=24): """ Build a cylinder of specified height and radius `r`, centered at `pos`. If `pos` is a list of 2 Points, e.g. `pos=[v1,v2]`, build a cylinder with base centered at `v1` and top at `v2`. |Cylinder| """
if utils.isSequence(pos[0]): # assume user is passing pos=[base, top] base = np.array(pos[0]) top = np.array(pos[1]) pos = (base + top) / 2 height = np.linalg.norm(top - base) axis = top - base axis = utils.versor(axis) else: axis = utils.versor(axis) base = pos - axis * height / 2 top = pos + axis * height / 2 cyl = vtk.vtkCylinderSource() cyl.SetResolution(res) cyl.SetRadius(r) cyl.SetHeight(height) cyl.Update() theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateX(90) # put it along Z t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(cyl.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) actor.base = base + pos actor.top = top + pos settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Cone(pos=(0, 0, 0), r=1, height=3, axis=(0, 0, 1), c="dg", alpha=1, res=48): """ Build a cone of specified radius `r` and `height`, centered at `pos`. |Cone| """
con = vtk.vtkConeSource() con.SetResolution(res) con.SetRadius(r) con.SetHeight(height) con.SetDirection(axis) con.Update() actor = Actor(con.GetOutput(), c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) v = utils.versor(axis) * height / 2 actor.base = pos - v actor.top = pos + v settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1): """ Build a pyramid of specified base size `s` and `height`, centered at `pos`. """
return Cone(pos, s, height, axis, c, alpha, 4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Torus(pos=(0, 0, 0), r=1, thickness=0.1, axis=(0, 0, 1), c="khaki", alpha=1, res=30): """ Build a torus of specified outer radius `r` internal radius `thickness`, centered at `pos`. .. hint:: |gas| |gas.py|_ """
rs = vtk.vtkParametricTorus() rs.SetRingRadius(r) rs.SetCrossSectionRadius(thickness) pfs = vtk.vtkParametricFunctionSource() pfs.SetParametricFunction(rs) pfs.SetUResolution(res * 3) pfs.SetVResolution(res) pfs.Update() nax = np.linalg.norm(axis) if nax: axis = np.array(axis) / nax theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(pfs.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getColorName(c): """Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_ """
c = np.array(getColor(c)) # reformat to rgb mdist = 99.0 kclosest = "" for key in colors.keys(): ci = np.array(getColor(key)) d = np.linalg.norm(c - ci) if d < mdist: mdist = d kclosest = str(key) return kclosest
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makePalette(color1, color2, N, hsv=True): """ Generate N colors starting from `color1` to `color2` by linear interpolation HSV in or RGB spaces. :param int N: number of output colors. :param color1: first rgb color. :param color2: second rgb color. :param bool hsv: if `False`, interpolation is calculated in RGB space. .. hint:: Example: |colorpalette.py|_ """
if hsv: color1 = rgb2hsv(color1) color2 = rgb2hsv(color2) c1 = np.array(getColor(color1)) c2 = np.array(getColor(color2)) cols = [] for f in np.linspace(0, 1, N - 1, endpoint=True): c = c1 * (1 - f) + c2 * f if hsv: c = np.array(hsv2rgb(c)) cols.append(c) return cols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kelvin2rgb(temperature): """ Converts from Kelvin temperature to an RGB color. Algorithm credits: |tannerhelland|_ """
# range check if temperature < 1000: temperature = 1000 elif temperature > 40000: temperature = 40000 tmp_internal = temperature / 100.0 # red if tmp_internal <= 66: red = 255 else: tmp_red = 329.698727446 * np.power(tmp_internal - 60, -0.1332047592) if tmp_red < 0: red = 0 elif tmp_red > 255: red = 255 else: red = tmp_red # green if tmp_internal <= 66: tmp_green = 99.4708025861 * np.log(tmp_internal) - 161.1195681661 if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green else: tmp_green = 288.1221695283 * np.power(tmp_internal - 60, -0.0755148492) if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green # blue if tmp_internal >= 66: blue = 255 elif tmp_internal <= 19: blue = 0 else: tmp_blue = 138.5177312231 * np.log(tmp_internal - 10) - 305.0447927307 if tmp_blue < 0: blue = 0 elif tmp_blue > 255: blue = 255 else: blue = tmp_blue return [red / 255, green / 255, blue / 255]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geometry(obj): """ Apply ``vtkGeometryFilter``. """
gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spline(points, smooth=0.5, degree=2, s=2, c="b", alpha=1.0, nodes=False, res=20): """ Return an ``Actor`` for a spline so that it does not necessarly pass exactly throught all points. :param float smooth: smoothing factor. 0 = interpolate points exactly. 1 = average point positions. :param int degree: degree of the spline (1<degree<5) :param bool nodes: if `True`, show also the input points. .. hint:: |tutorial_spline| |tutorial.py|_ """
from scipy.interpolate import splprep, splev Nout = len(points) * res # Number of points on the spline points = np.array(points) minx, miny, minz = np.min(points, axis=0) maxx, maxy, maxz = np.max(points, axis=0) maxb = max(maxx - minx, maxy - miny, maxz - minz) smooth *= maxb / 2 # must be in absolute units x, y, z = points[:, 0], points[:, 1], points[:, 2] tckp, _ = splprep([x, y, z], task=0, s=smooth, k=degree) # find the knots # evaluate spLine, including interpolated points: xnew, ynew, znew = splev(np.linspace(0, 1, Nout), tckp) ppoints = vtk.vtkPoints() # Generate the polyline for the spline profileData = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk(list(zip(xnew, ynew, znew)), deep=True)) lines = vtk.vtkCellArray() # Create the polyline lines.InsertNextCell(Nout) for i in range(Nout): lines.InsertCellPoint(i) profileData.SetPoints(ppoints) profileData.SetLines(lines) actline = Actor(profileData, c=c, alpha=alpha) actline.GetProperty().SetLineWidth(s) if nodes: actnodes = vs.Points(points, r=5, c=c, alpha=alpha) ass = Assembly([actline, actnodes]) return ass else: return actline
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def histogram(values, bins=10, vrange=None, title="", c="g", corner=1, lines=True): """ Build a 2D histogram from a list of values in n bins. Use *vrange* to restrict the range of the histogram. Use *corner* to assign its position: - 1, topleft, - 2, topright, - 3, bottomleft, - 4, bottomright. .. hint:: Example: |fitplanes.py|_ """
fs, edges = np.histogram(values, bins=bins, range=vrange) pts = [] for i in range(len(fs)): pts.append([(edges[i] + edges[i + 1]) / 2, fs[i]]) return xyplot(pts, title, c, corner, lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delaunay2D(plist, mode='xy', tol=None): """ Create a mesh from points in the XY plane. If `mode='fit'` then the filter computes a best fitting plane and projects the points onto it. .. hint:: |delaunay2d| |delaunay2d.py|_ """
pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(plist, deep=True)) pd.SetPoints(vpts) delny = vtk.vtkDelaunay2D() delny.SetInputData(pd) if tol: delny.SetTolerance(tol) if mode=='fit': delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) delny.Update() return Actor(delny.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delaunay3D(dataset, alpha=0, tol=None, boundary=True): """Create 3D Delaunay triangulation of input points."""
deln = vtk.vtkDelaunay3D() deln.SetInputData(dataset) deln.SetAlpha(alpha) if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary) deln.Update() return deln.GetOutput()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8): """ Build an ``vtkActor`` made of the normals at vertices shown as lines. """
maskPts = vtk.vtkMaskPoints() maskPts.SetOnRatio(ratio) maskPts.RandomModeOff() actor = actor.computeNormals() src = actor.polydata() maskPts.SetInputData(src) arrow = vtk.vtkLineSource() arrow.SetPoint1(0, 0, 0) arrow.SetPoint2(0.75, 0, 0) glyph = vtk.vtkGlyph3D() glyph.SetSourceConnection(arrow.GetOutputPort()) glyph.SetInputConnection(maskPts.GetOutputPort()) glyph.SetVectorModeToUseNormal() b = src.GetBounds() sc = max([b[1] - b[0], b[3] - b[2], b[5] - b[4]]) / 20.0 glyph.SetScaleFactor(sc) glyph.OrientOn() glyph.Update() glyphActor = Actor(glyph.GetOutput(), c=vc.getColor(c), alpha=alpha) glyphActor.mapper.SetScalarModeToUsePointFieldData() glyphActor.PickableOff() prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) glyphActor.SetProperty(prop) return glyphActor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractLargestRegion(actor): """Keep only the largest connected part of a mesh and discard all the smaller pieces. .. hint:: |largestregion.py|_ """
conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.GetMapper().GetInput() conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() eact = Actor(epoly) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) eact.SetProperty(pr) return eact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignLandmarks(source, target, rigid=False): """ Find best matching of source points towards target in the mean least square sense, in one single step. """
lmt = vtk.vtkLandmarkTransform() ss = source.polydata().GetPoints() st = target.polydata().GetPoints() if source.N() != target.N(): vc.printc('~times Error in alignLandmarks(): Source and Target with != nr of points!', source.N(), target.N(), c=1) exit() lmt.SetSourceLandmarks(ss) lmt.SetTargetLandmarks(st) if rigid: lmt.SetModeToRigidBody() lmt.Update() tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(source.polydata()) tf.SetTransform(lmt) tf.Update() actor = Actor(tf.GetOutput()) actor.info["transform"] = lmt pr = vtk.vtkProperty() pr.DeepCopy(source.GetProperty()) actor.SetProperty(pr) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignICP(source, target, iters=100, rigid=False): """ Return a copy of source actor which is aligned to target actor through the `Iterative Closest Point` algorithm. The core of the algorithm is to match each vertex in one surface with the closest surface point on the other, then apply the transformation that modify one surface to best match the other (in the least-square sense). .. hint:: |align1| |align1.py|_ |align2| |align2.py|_ """
if isinstance(source, Actor): source = source.polydata() if isinstance(target, Actor): target = target.polydata() icp = vtk.vtkIterativeClosestPointTransform() icp.SetSource(source) icp.SetTarget(target) icp.SetMaximumNumberOfIterations(iters) if rigid: icp.GetLandmarkTransform().SetModeToRigidBody() icp.StartByMatchingCentroidsOn() icp.Update() icpTransformFilter = vtk.vtkTransformPolyDataFilter() icpTransformFilter.SetInputData(source) icpTransformFilter.SetTransform(icp) icpTransformFilter.Update() poly = icpTransformFilter.GetOutput() actor = Actor(poly) # actor.info['transform'] = icp.GetLandmarkTransform() # not working! # do it manually... sourcePoints = vtk.vtkPoints() targetPoints = vtk.vtkPoints() for i in range(10): p1 = [0, 0, 0] source.GetPoints().GetPoint(i, p1) sourcePoints.InsertNextPoint(p1) p2 = [0, 0, 0] poly.GetPoints().GetPoint(i, p2) targetPoints.InsertNextPoint(p2) # Setup the transform landmarkTransform = vtk.vtkLandmarkTransform() landmarkTransform.SetSourceLandmarks(sourcePoints) landmarkTransform.SetTargetLandmarks(targetPoints) if rigid: landmarkTransform.SetModeToRigidBody() actor.info["transform"] = landmarkTransform return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignProcrustes(sources, rigid=False): """ Return an ``Assembly`` of aligned source actors with the `Procrustes` algorithm. The output ``Assembly`` is normalized in size. `Procrustes` algorithm takes N set of points and aligns them in a least-squares sense to their mutual mean. The algorithm is iterated until convergence, as the mean must be recomputed after each alignment. :param bool rigid: if `True` scaling is disabled. .. hint:: |align3| |align3.py|_ """
group = vtk.vtkMultiBlockDataGroupFilter() for source in sources: if sources[0].N() != source.N(): vc.printc("~times Procrustes error in align():", c=1) vc.printc(" sources have different nr of points", c=1) exit(0) group.AddInputData(source.polydata()) procrustes = vtk.vtkProcrustesAlignmentFilter() procrustes.StartFromCentroidOn() procrustes.SetInputConnection(group.GetOutputPort()) if rigid: procrustes.GetLandmarkTransform().SetModeToRigidBody() procrustes.Update() acts = [] for i, s in enumerate(sources): poly = procrustes.GetOutput().GetBlock(i) actor = Actor(poly) actor.SetProperty(s.GetProperty()) acts.append(actor) assem = Assembly(acts) assem.info["transform"] = procrustes.GetLandmarkTransform() return assem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitLine(points, c="orange", lw=1): """ Fits a line through points. Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``. .. hint:: |fitline| |fitline.py|_ """
data = np.array(points) datamean = data.mean(axis=0) uu, dd, vv = np.linalg.svd(data - datamean) vv = vv[0] / np.linalg.norm(vv[0]) # vv contains the first principal component, i.e. the direction # vector of the best fit line in the least squares sense. xyz_min = points.min(axis=0) xyz_max = points.max(axis=0) a = np.linalg.norm(xyz_min - datamean) b = np.linalg.norm(xyz_max - datamean) p1 = datamean - a * vv p2 = datamean + b * vv l = vs.Line(p1, p2, c=c, lw=lw, alpha=1) l.info["slope"] = vv l.info["center"] = datamean l.info["variances"] = dd return l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitPlane(points, c="g", bc="darkgreen"): """ Fits a plane to a set of points. Extra info is stored in ``actor.info['normal']``, ``actor.info['center']``, ``actor.info['variance']``. .. hint:: Example: |fitplanes.py|_ """
data = np.array(points) datamean = data.mean(axis=0) res = np.linalg.svd(data - datamean) dd, vv = res[1], res[2] xyz_min = points.min(axis=0) xyz_max = points.max(axis=0) s = np.linalg.norm(xyz_max - xyz_min) n = np.cross(vv[0], vv[1]) pla = vs.Plane(datamean, n, s, s, c, bc) pla.info["normal"] = n pla.info["center"] = datamean pla.info["variance"] = dd[2] return pla
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fitSphere(coords): """ Fits a sphere to a set of points. Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``. .. hint:: Example: |fitspheres1.py|_ |fitspheres2| |fitspheres2.py|_ """
coords = np.array(coords) n = len(coords) A = np.zeros((n, 4)) A[:, :-1] = coords * 2 A[:, 3] = 1 f = np.zeros((n, 1)) x = coords[:, 0] y = coords[:, 1] z = coords[:, 2] f[:, 0] = x * x + y * y + z * z C, residue, rank, sv = np.linalg.lstsq(A, f) # solve AC=f if rank < 4: return None t = (C[0] * C[0]) + (C[1] * C[1]) + (C[2] * C[2]) + C[3] radius = np.sqrt(t)[0] center = np.array([C[0][0], C[1][0], C[2][0]]) if len(residue): residue = np.sqrt(residue[0]) / n else: residue = 0 s = vs.Sphere(center, radius, c="r", alpha=1).wire(1) s.info["radius"] = radius s.info["center"] = center s.info["residue"] = residue return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def booleanOperation(actor1, operation, actor2, c=None, alpha=1, wire=False, bc=None, texture=None): """Volumetric union, intersection and subtraction of surfaces. :param str operation: allowed operations: ``'plus'``, ``'intersect'``, ``'minus'``. .. hint:: |boolean| |boolean.py|_ """
bf = vtk.vtkBooleanOperationPolyDataFilter() poly1 = actor1.computeNormals().polydata() poly2 = actor2.computeNormals().polydata() if operation.lower() == "plus" or operation.lower() == "+": bf.SetOperationToUnion() elif operation.lower() == "intersect": bf.SetOperationToIntersection() elif operation.lower() == "minus" or operation.lower() == "-": bf.SetOperationToDifference() bf.ReorientDifferenceCellsOn() bf.SetInputData(0, poly1) bf.SetInputData(1, poly2) bf.Update() actor = Actor(bf.GetOutput(), c, alpha, wire, bc, texture) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3): """Intersect 2 surfaces and return a line actor. .. hint:: |surfIntersect.py|_ """
bf = vtk.vtkIntersectionPolyDataFilter() poly1 = actor1.GetMapper().GetInput() poly2 = actor2.GetMapper().GetInput() bf.SetInputData(0, poly1) bf.SetInputData(1, poly2) bf.Update() actor = Actor(bf.GetOutput(), "k", 1) actor.GetProperty().SetLineWidth(lw) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probePoints(img, pts): """ Takes a ``vtkImageData`` and probes its scalars at the specified points in space. """
src = vtk.vtkProgrammableSource() def readPoints(): output = src.GetPolyDataOutput() points = vtk.vtkPoints() for p in pts: x, y, z = p points.InsertNextPoint(x, y, z) output.SetPoints(points) cells = vtk.vtkCellArray() cells.InsertNextCell(len(pts)) for i in range(len(pts)): cells.InsertCellPoint(i) output.SetVerts(cells) src.SetExecuteMethod(readPoints) src.Update() probeFilter = vtk.vtkProbeFilter() probeFilter.SetSourceData(img) probeFilter.SetInputConnection(src.GetOutputPort()) probeFilter.Update() pact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn pact.mapper.SetScalarRange(img.GetScalarRange()) return pact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probeLine(img, p1, p2, res=100): """ Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`. .. hint:: |probeLine| |probeLine.py|_ """
line = vtk.vtkLineSource() line.SetResolution(res) line.SetPoint1(p1) line.SetPoint2(p2) probeFilter = vtk.vtkProbeFilter() probeFilter.SetSourceData(img) probeFilter.SetInputConnection(line.GetOutputPort()) probeFilter.Update() lact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn lact.mapper.SetScalarRange(img.GetScalarRange()) return lact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)): """ Takes a ``vtkImageData`` and probes its scalars on a plane. .. hint:: |probePlane| |probePlane.py|_ """
plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) planeCut = vtk.vtkCutter() planeCut.SetInputData(img) planeCut.SetCutFunction(plane) planeCut.Update() cutActor = Actor(planeCut.GetOutput(), c=None) # ScalarVisibilityOn cutActor.mapper.SetScalarRange(img.GetPointData().GetScalars().GetRange()) return cutActor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recoSurface(points, bins=256): """ Surface reconstruction from a scattered cloud of points. :param int bins: number of voxels in x, y and z. .. hint:: |recosurface| |recosurface.py|_ """
if isinstance(points, vtk.vtkActor): points = points.coordinates() N = len(points) if N < 50: print("recoSurface: Use at least 50 points.") return None points = np.array(points) ptsSource = vtk.vtkPointSource() ptsSource.SetNumberOfPoints(N) ptsSource.Update() vpts = ptsSource.GetOutput().GetPoints() for i, p in enumerate(points): vpts.SetPoint(i, p) polyData = ptsSource.GetOutput() distance = vtk.vtkSignedDistance() f = 0.1 x0, x1, y0, y1, z0, z1 = polyData.GetBounds() distance.SetBounds(x0-(x1-x0)*f, x1+(x1-x0)*f, y0-(y1-y0)*f, y1+(y1-y0)*f, z0-(z1-z0)*f, z1+(z1-z0)*f) if polyData.GetPointData().GetNormals(): distance.SetInputData(polyData) else: normals = vtk.vtkPCANormalEstimation() normals.SetInputData(polyData) normals.SetSampleSize(int(N / 50)) normals.SetNormalOrientationToGraphTraversal() distance.SetInputConnection(normals.GetOutputPort()) print("Recalculating normals for", N, "Points, sample size=", int(N / 50)) b = polyData.GetBounds() diagsize = np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2) radius = diagsize / bins * 5 distance.SetRadius(radius) distance.SetDimensions(bins, bins, bins) distance.Update() print("Calculating mesh from points with R =", radius) surface = vtk.vtkExtractSurface() surface.SetRadius(radius * 0.99) surface.HoleFillingOn() surface.ComputeNormalsOff() surface.ComputeGradientsOff() surface.SetInputConnection(distance.GetOutputPort()) surface.Update() return Actor(surface.GetOutput(), "gold", 1, 0, "tomato")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster(points, radius): """ Clustering of points in space. `radius` is the radius of local search. Individual subsets can be accessed through ``actor.clusters``. .. hint:: |clustering| |clustering.py|_ """
if isinstance(points, vtk.vtkActor): poly = points.GetMapper().GetInput() else: src = vtk.vtkPointSource() src.SetNumberOfPoints(len(points)) src.Update() vpts = src.GetOutput().GetPoints() for i, p in enumerate(points): vpts.SetPoint(i, p) poly = src.GetOutput() cluster = vtk.vtkEuclideanClusterExtraction() cluster.SetInputData(poly) cluster.SetExtractionModeToAllClusters() cluster.SetRadius(radius) cluster.ColorClustersOn() cluster.Update() idsarr = cluster.GetOutput().GetPointData().GetArray("ClusterId") Nc = cluster.GetNumberOfExtractedClusters() sets = [[] for i in range(Nc)] for i, p in enumerate(points): sets[idsarr.GetValue(i)].append(p) acts = [] for i, aset in enumerate(sets): acts.append(vs.Points(aset, c=i)) actor = Assembly(acts) actor.info["clusters"] = sets print("Nr. of extracted clusters", Nc) if Nc > 10: print("First ten:") for i in range(Nc): if i > 9: print("...") break print("Cluster #" + str(i) + ", N =", len(sets[i])) print("Access individual clusters through attribute: actor.cluster") return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeOutliers(points, radius): """ Remove outliers from a cloud of points within the specified `radius` search. .. hint:: |clustering| |clustering.py|_ """
isactor = False if isinstance(points, vtk.vtkActor): isactor = True poly = points.GetMapper().GetInput() else: src = vtk.vtkPointSource() src.SetNumberOfPoints(len(points)) src.Update() vpts = src.GetOutput().GetPoints() for i, p in enumerate(points): vpts.SetPoint(i, p) poly = src.GetOutput() removal = vtk.vtkRadiusOutlierRemoval() removal.SetInputData(poly) removal.SetRadius(radius) removal.SetNumberOfNeighbors(5) removal.GenerateOutliersOff() removal.Update() rpoly = removal.GetOutput() print("# of removed outlier points: ", removal.GetNumberOfPointsRemoved(), '/', poly.GetNumberOfPoints()) outpts = [] for i in range(rpoly.GetNumberOfPoints()): outpts.append(list(rpoly.GetPoint(i))) outpts = np.array(outpts) if not isactor: return outpts actor = vs.Points(outpts) return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thinPlateSpline(actor, sourcePts, targetPts, userFunctions=(None, None)): """ `Thin Plate Spline` transformations describe a nonlinear warp transform defined by a set of source and target landmarks. Any point on the mesh close to a source landmark will be moved to a place close to the corresponding target landmark. The points in between are interpolated smoothly using Bookstein's Thin Plate Spline algorithm. Transformation object is saved in ``actor.info['transform']``. :param userFunctions: You must supply both the function and its derivative with respect to r. .. hint:: |thinplate| |thinplate.py|_ |thinplate_grid| |thinplate_grid.py|_ |thinplate_morphing| |thinplate_morphing.py|_ |interpolateField| |interpolateField.py|_ """
ns = len(sourcePts) ptsou = vtk.vtkPoints() ptsou.SetNumberOfPoints(ns) for i in range(ns): ptsou.SetPoint(i, sourcePts[i]) nt = len(sourcePts) if ns != nt: vc.printc("~times thinPlateSpline Error: #source != #target points", ns, nt, c=1) exit() pttar = vtk.vtkPoints() pttar.SetNumberOfPoints(nt) for i in range(ns): pttar.SetPoint(i, targetPts[i]) transform = vtk.vtkThinPlateSplineTransform() transform.SetBasisToR() if userFunctions[0]: transform.SetBasisFunction(userFunctions[0]) transform.SetBasisDerivative(userFunctions[1]) transform.SetSigma(1) transform.SetSourceLandmarks(ptsou) transform.SetTargetLandmarks(pttar) tfa = transformFilter(actor.polydata(), transform) tfa.info["transform"] = transform return tfa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transformFilter(actor, transformation): """ Transform a ``vtkActor`` and return a new object. """
tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) prop = None if isinstance(actor, vtk.vtkPolyData): tf.SetInputData(actor) else: tf.SetInputData(actor.polydata()) prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) tf.Update() tfa = Actor(tf.GetOutput()) if prop: tfa.SetProperty(prop) return tfa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitByConnectivity(actor, maxdepth=100): """ Split a mesh by connectivity and order the pieces by increasing area. :param int maxdepth: only consider this number of mesh parts. .. hint:: |splitmesh| |splitmesh.py|_ """
actor.addIDs() pd = actor.polydata() cf = vtk.vtkConnectivityFilter() cf.SetInputData(pd) cf.SetExtractionModeToAllRegions() cf.ColorRegionsOn() cf.Update() cpd = cf.GetOutput() a = Actor(cpd) alist = [] for t in range(max(a.scalars("RegionId")) - 1): if t == maxdepth: break suba = a.clone().threshold("RegionId", t - 0.1, t + 0.1) area = suba.area() alist.append([suba, area]) alist.sort(key=lambda x: x[1]) alist.reverse() blist = [] for i, l in enumerate(alist): l[0].color(i + 1) l[0].mapper.ScalarVisibilityOff() blist.append(l[0]) return blist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pointSampler(actor, distance=None): """ Algorithm to generate points the specified distance apart. """
poly = actor.polydata(True) pointSampler = vtk.vtkPolyDataPointSampler() if not distance: distance = actor.diagonalSize() / 100.0 pointSampler.SetDistance(distance) # pointSampler.GenerateVertexPointsOff() # pointSampler.GenerateEdgePointsOff() # pointSampler.GenerateVerticesOn() # pointSampler.GenerateInteriorPointsOn() pointSampler.SetInputData(poly) pointSampler.Update() uactor = Actor(pointSampler.GetOutput()) prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) uactor.SetProperty(prop) return uactor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geodesic(actor, start, end): """ Dijkstra algorithm to compute the graph geodesic. Takes as input a polygonal mesh and performs a single source shortest path calculation. :param start: start vertex index or close point `[x,y,z]` :type start: int, list :param end: end vertex index or close point `[x,y,z]` :type start: int, list .. hint:: |geodesic| |geodesic.py|_ """
dijkstra = vtk.vtkDijkstraGraphGeodesicPath() if vu.isSequence(start): cc = actor.coordinates() pa = vs.Points(cc) start = pa.closestPoint(start, returnIds=True) end = pa.closestPoint(end, returnIds=True) dijkstra.SetInputData(pa.polydata()) else: dijkstra.SetInputData(actor.polydata()) dijkstra.SetStartVertex(start) dijkstra.SetEndVertex(end) dijkstra.Update() weights = vtk.vtkDoubleArray() dijkstra.GetCumulativeWeights(weights) length = weights.GetMaxId() + 1 arr = np.zeros(length) for i in range(length): arr[i] = weights.GetTuple(i)[0] dactor = Actor(dijkstra.GetOutput()) prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) prop.SetLineWidth(3) prop.SetOpacity(1) dactor.SetProperty(prop) dactor.info["CumulativeWeights"] = arr return dactor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convexHull(actor_or_list, alphaConstant=0): """ Create a 3D Delaunay triangulation of input points. :param actor_or_list: can be either an ``Actor`` or a list of 3D points. :param float alphaConstant: For a non-zero alpha value, only verts, edges, faces, or tetra contained within the circumsphere (of radius alpha) will be output. Otherwise, only tetrahedra will be output. .. hint:: |convexHull| |convexHull.py|_ """
if vu.isSequence(actor_or_list): actor = vs.Points(actor_or_list) else: actor = actor_or_list apoly = actor.clean().polydata() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(apoly) triangleFilter.Update() poly = triangleFilter.GetOutput() delaunay = vtk.vtkDelaunay3D() # Create the convex hull of the pointcloud if alphaConstant: delaunay.SetAlpha(alphaConstant) delaunay.SetInputData(poly) delaunay.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) surfaceFilter.Update() chuact = Actor(surfaceFilter.GetOutput()) return chuact
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractSurface(image, radius=0.5): """ ``vtkExtractSurface`` filter. Input is a ``vtkImageData``. Generate zero-crossing isosurface from truncated signed distance volume. """
fe = vtk.vtkExtractSurface() fe.SetInputData(image) fe.SetRadius(radius) fe.Update() return Actor(fe.GetOutput())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def projectSphereFilter(actor): """ Project a spherical-like object onto a plane. .. hint:: |projectsphere| |projectsphere.py|_ """
poly = actor.polydata() psf = vtk.vtkProjectSphereFilter() psf.SetInputData(poly) psf.Update() a = Actor(psf.GetOutput()) return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, timeout=None): """ Wait for events. """
try: if timeout: gevent.sleep(timeout) else: while True: gevent.sleep(1000) except (KeyboardInterrupt, SystemExit, Exception): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover(self, seconds=2): """ Discover devices in the environment. @param seconds: Number of seconds to broadcast requests. @type seconds: int """
log.info("Discovering devices") with gevent.Timeout(seconds, StopBroadcasting) as timeout: try: try: while True: self.upnp.broadcast() gevent.sleep(1) except Exception as e: raise StopBroadcasting(e) except StopBroadcasting: return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. Arguments: sender The sender of the signal. Either a specific object or None. named Named arguments which will be passed to receivers. """
responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses for receiver in self._live_receivers(sender): response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. These arguments must be a subset of the argument names defined in providing_args. DispatcherKeyError. If any receiver raises an error (specifically any subclass of Exception), the error instance is returned as the result for that receiver. The traceback is always attached to the error at ``__traceback__``. """
responses = [] if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS: return responses # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: if not hasattr(err, '__traceback__'): err.__traceback__ = sys.exc_info()[2] responses.append((receiver, err)) else: responses.append((receiver, response)) return responses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """
receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receivers() due to concurrent .send() call. if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = [] for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note, we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_receivers = [] for receiver in receivers: if isinstance(receiver, weakref.ReferenceType): # Dereference the weak reference. receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_state(self, state): """ Set the state of this device to on or off. """
self.basicevent.SetBinaryState(BinaryState=int(state)) self._state = int(state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def broadcast(self): """ Send a multicast M-SEARCH request asking for devices to report in. """
log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port) request = '\r\n'.join(("M-SEARCH * HTTP/1.1", "HOST:{mcast_ip}:{mcast_port}", "ST:upnp:rootdevice", "MX:2", 'MAN:"ssdp:discover"', "", "")).format(**self.__dict__) self.server.sendto(request.encode(), (self.mcast_ip, self.mcast_port))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_with_delay(f, delay=60): """ Retry the wrapped requests.request function in case of ConnectionError. Optionally limit the number of retries or set the delay between retries. """
@wraps(f) def inner(*args, **kwargs): kwargs['timeout'] = 5 remaining = get_retries() + 1 while remaining: remaining -= 1 try: return f(*args, **kwargs) except (requests.ConnectionError, requests.Timeout): if not remaining: raise gevent.sleep(delay) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchType(libtype): """ Returns the integer value of the library string type. Parameters: libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track, collection) Raises: :class:`plexapi.exceptions.NotFound`: Unknown libtype """
libtype = compat.ustr(libtype) if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]: return libtype if SEARCHTYPES.get(libtype) is not None: return SEARCHTYPES[libtype] raise NotFound('Unknown libtype: %s' % libtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toDatetime(value, format=None): """ Returns a datetime object from the specified value. Parameters: value (str): value to return as a datetime format (str): Format to pass strftime (optional; if value is a str). """
if value and value is not None: if format: value = datetime.strptime(value, format) else: # https://bugs.python.org/issue30684 # And platform support for before epoch seems to be flaky. # TODO check for others errors too. if int(value) == 0: value = 86400 value = datetime.fromtimestamp(int(value)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toList(value, itemcast=None, delim=','): """ Returns a list of strings from the specified value. Parameters: value (str): comma delimited string to convert to list. itemcast (func): Function to cast each list item to (default str). delim (str): string delimiter (optional; default ','). """
value = value or '' itemcast = itemcast or str return [itemcast(item) for item in value.split(delim) if item != '']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downloadSessionImages(server, filename=None, height=150, width=150, opacity=100, saturation=100): # pragma: no cover """ Helper to download a bif image or thumb.url from plex.server.sessions. Parameters: filename (str): default to None, height (int): Height of the image. width (int): width of the image. opacity (int): Opacity of the resulting image (possibly deprecated). saturation (int): Saturating of the resulting image. Returns: {'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'}, """
info = {} for media in server.sessions(): url = None for part in media.iterParts(): if media.thumb: url = media.thumb if part.indexes: # always use bif images if available. url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset) if url: if filename is None: prettyname = media._prettyfilename() filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time())) url = server.transcodeImage(url, height, width, opacity, saturation) filepath = download(url, filename=filename) info['username'] = {'filepath': filepath, 'url': url} return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(url, token, filename=None, savepath=None, session=None, chunksize=4024, unpack=False, mocked=False, showstatus=False): """ Helper to download a thumb, videofile or other media item. Returns the local path to the downloaded file. Parameters: url (str): URL where the content be reached. token (str): Plex auth token to include in headers. filename (str): Filename of the downloaded file, default None. savepath (str): Defaults to current working dir. chunksize (int): What chunksize read/write at the time. mocked (bool): Helper to do evertything except write the file. unpack (bool): Unpack the zip file. showstatus(bool): Display a progressbar. Example: /path/to/file """
from plexapi import log # fetch the data to be saved session = session or requests.Session() headers = {'X-Plex-Token': token} response = session.get(url, headers=headers, stream=True) # make sure the savepath directory exists savepath = savepath or os.getcwd() compat.makedirs(savepath, exist_ok=True) # try getting filename from header if not specified in arguments (used for logs, db) if not filename and response.headers.get('Content-Disposition'): filename = re.findall(r'filename=\"(.+)\"', response.headers.get('Content-Disposition')) filename = filename[0] if filename[0] else None filename = os.path.basename(filename) fullpath = os.path.join(savepath, filename) # append file.ext from content-type if not already there extension = os.path.splitext(fullpath)[-1] if not extension: contenttype = response.headers.get('content-type') if contenttype and 'image' in contenttype: fullpath += contenttype.split('/')[1] # check this is a mocked download (testing) if mocked: log.debug('Mocked download %s', fullpath) return fullpath # save the file to disk log.info('Downloading: %s', fullpath) if showstatus: # pragma: no cover total = int(response.headers.get('content-length', 0)) bar = tqdm(unit='B', unit_scale=True, total=total, desc=filename) with open(fullpath, 'wb') as handle: for chunk in response.iter_content(chunk_size=chunksize): handle.write(chunk) if showstatus: bar.update(len(chunk)) if showstatus: # pragma: no cover bar.close() # check we want to unzip the contents if fullpath.endswith('zip') and unpack: with zipfile.ZipFile(fullpath, 'r') as handle: handle.extractall(savepath) return fullpath