code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
renderer = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
importer = vtk.vtk3DSImporter()
importer.SetFileName(filename)
importer.ComputeNormalsOn()
importer.SetRenderWindow(renWin)
importer.Update()
actors = renderer.GetActors() # vtkActorCollection
acts = []
for i in range(actors.GetNumberOfItems()):
a = actors.GetItemAsObject(i)
acts.append(a)
del renWin
return Assembly(acts) | def load3DS(filename) | Load ``3DS`` file format from file. Return an ``Assembly(vtkAssembly)`` object. | 2.848562 | 2.463313 | 1.156395 |
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) | def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None) | Read OFF file format. | 2.957467 | 2.933756 | 1.008082 |
if not os.path.exists(filename):
colors.printc("~noentry Error in loadDolfin: Cannot find", filename, c=1)
return None
import xml.etree.ElementTree as et
if filename.endswith(".gz"):
import gzip
inF = gzip.open(filename, "rb")
outF = open("/tmp/filename.xml", "wb")
outF.write(inF.read())
outF.close()
inF.close()
tree = et.parse("/tmp/filename.xml")
else:
tree = et.parse(filename)
coords, connectivity = [], []
for mesh in tree.getroot():
for elem in mesh:
for e in elem.findall("vertex"):
x = float(e.get("x"))
y = float(e.get("y"))
ez = e.get("z")
if ez is None:
coords.append([x, y])
else:
z = float(ez)
coords.append([x, y, z])
tets = elem.findall("tetrahedron")
if not len(tets):
tris = elem.findall("triangle")
for e in tris:
v0 = int(e.get("v0"))
v1 = int(e.get("v1"))
v2 = int(e.get("v2"))
connectivity.append([v0, v1, v2])
else:
for e in tets:
v0 = int(e.get("v0"))
v1 = int(e.get("v1"))
v2 = int(e.get("v2"))
v3 = int(e.get("v3"))
connectivity.append([v0, v1, v2, v3])
poly = buildPolyData(coords, connectivity)
return Actor(poly, c, alpha, True, bc) | def loadDolfin(filename, c="gold", alpha=0.5, wire=None, bc=None) | Reads a `Fenics/Dolfin` file format. Return an ``Actor(vtkActor)`` object. | 2.226673 | 2.128745 | 1.046003 |
if not os.path.exists(filename):
colors.printc("~noentry Error in loadNeutral: Cannot find", filename, c=1)
return None
coords, connectivity = convertNeutral2Xml(filename)
poly = buildPolyData(coords, connectivity, indexOffset=0)
return Actor(poly, c, alpha, wire, bc) | def loadNeutral(filename, c="gold", alpha=1, wire=False, bc=None) | Reads a `Neutral` tetrahedral file format. Return an ``Actor(vtkActor)`` object. | 9.745509 | 8.186733 | 1.190403 |
if not os.path.exists(filename):
colors.printc("~noentry Error in loadGmesh: Cannot find", filename, c=1)
return None
f = open(filename, "r")
lines = f.readlines()
f.close()
nnodes = 0
index_nodes = 0
for i, line in enumerate(lines):
if "$Nodes" in line:
index_nodes = i + 1
nnodes = int(lines[index_nodes])
break
node_coords = []
for i in range(index_nodes + 1, index_nodes + 1 + nnodes):
cn = lines[i].split()
node_coords.append([float(cn[1]), float(cn[2]), float(cn[3])])
nelements = 0
index_elements = 0
for i, line in enumerate(lines):
if "$Elements" in line:
index_elements = i + 1
nelements = int(lines[index_elements])
break
elements = []
for i in range(index_elements + 1, index_elements + 1 + nelements):
ele = lines[i].split()
elements.append([int(ele[-3]), int(ele[-2]), int(ele[-1])])
poly = buildPolyData(node_coords, elements, indexOffset=1)
return Actor(poly, c, alpha, wire, bc) | def loadGmesh(filename, c="gold", alpha=1, wire=False, bc=None) | Reads a `gmesh` file format. Return an ``Actor(vtkActor)`` object. | 2.283282 | 2.199426 | 1.038126 |
if not os.path.exists(filename):
colors.printc("~noentry Error in loadPCD: Cannot find file", filename, c=1)
return None
f = open(filename, "r")
lines = f.readlines()
f.close()
start = False
pts = []
N, expN = 0, 0
for text in lines:
if start:
if N >= expN:
break
l = text.split()
pts.append([float(l[0]), float(l[1]), float(l[2])])
N += 1
if not start and "POINTS" in text:
expN = int(text.split()[1])
if not start and "DATA ascii" in text:
start = True
if expN != N:
colors.printc("~!? Mismatch in pcd file", expN, len(pts), c="red")
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(pts))
src.Update()
poly = src.GetOutput()
for i, p in enumerate(pts):
poly.GetPoints().SetPoint(i, p)
if not poly:
colors.printc("~noentry Unable to load", filename, c="red")
return False
actor = Actor(poly, colors.getColor(c), alpha)
actor.GetProperty().SetPointSize(4)
return actor | def loadPCD(filename, c="gold", alpha=1) | Return ``vtkActor`` from `Point Cloud` file format. Return an ``Actor(vtkActor)`` object. | 3.126018 | 2.943649 | 1.061953 |
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 | def loadImageData(filename, spacing=()) | Read and return a ``vtkImageData`` object from file. | 2.753974 | 2.642035 | 1.042368 |
fl = filename.lower()
if ".png" in fl:
picr = vtk.vtkPNGReader()
elif ".jpg" in fl or ".jpeg" in fl:
picr = vtk.vtkJPEGReader()
elif ".bmp" in fl:
picr = vtk.vtkBMPReader()
picr.Allow8BitBMPOff()
else:
colors.printc("~times File must end with png, bmp or jp(e)g", c=1)
exit(1)
picr.SetFileName(filename)
picr.Update()
vactor = ImageActor() # vtk.vtkImageActor()
vactor.SetInputData(picr.GetOutput())
if alpha is None:
alpha = 1
vactor.SetOpacity(alpha)
return vactor | def load2Dimage(filename, alpha=1) | Read a JPEG/PNG/BMP image from file. Return an ``ImageActor(vtkImageActor)`` object.
.. hint:: |rotateImage| |rotateImage.py|_ | 3.54095 | 3.323297 | 1.065493 |
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 | 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. | 2.580325 | 2.541479 | 1.015285 |
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 | def convertNeutral2Xml(infile, outfile=None) | Convert Neutral file format to Dolfin XML. | 1.651643 | 1.604429 | 1.029427 |
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() | def screenshot(filename="screenshot.png") | Save a screenshot of the current rendering window. | 4.691407 | 4.270018 | 1.098686 |
fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png"
screenshot(fr)
self.frames.append(fr) | def addFrame(self) | Add frame to current video. | 10.35079 | 8.629126 | 1.199518 |
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)) | def pause(self, pause=0) | Insert a `pause`, in seconds. | 4.676514 | 4.395671 | 1.063891 |
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 | def close(self) | Render the video and write to file. | 5.927529 | 5.469843 | 1.083674 |
if s is None:
return self.states[self._status]
if isinstance(s, str):
s = self.states.index(s)
self._status = s
self.textproperty.SetLineOffset(self.offset)
self.actor.SetInput(self.spacer + self.states[s] + self.spacer)
s = s % len(self.colors) # to avoid mismatch
self.textproperty.SetColor(colors.getColor(self.colors[s]))
bcc = numpy.array(colors.getColor(self.bcolors[s]))
self.textproperty.SetBackgroundColor(bcc)
if self.showframe:
self.textproperty.FrameOn()
self.textproperty.SetFrameWidth(self.framewidth)
self.textproperty.SetFrameColor(numpy.sqrt(bcc)) | def status(self, s=None) | Set/Get the status of the button. | 4.233172 | 4.322971 | 0.979227 |
self._status = (self._status + 1) % len(self.states)
self.status(self._status) | def switch(self) | Change/cycle button status to the next defined status in states list. | 4.898286 | 3.158512 | 1.550821 |
# 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() | def update_fields(u, u_old, v_old, a_old) | Update fields at the end of each time step. | 3.454438 | 3.350798 | 1.03093 |
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 | def local_project(v, V, u=None) | Element-wise projection using LocalSolver | 2.85362 | 2.539484 | 1.123701 |
if len(pos) == 2:
pos = (pos[0], pos[1], 0)
actor = Points([pos], r, c, alpha)
return actor | def Point(pos=(0, 0, 0), r=12, c="red", alpha=1) | Create a simple point actor. | 3.172791 | 2.719393 | 1.166728 |
def _colorPoints(plist, cols, r, alpha):
n = len(plist)
if n > len(cols):
colors.printc("~times Error: mismatch in colorPoints()", n, len(cols), c=1)
exit()
if n != len(cols):
colors.printc("~lightning Warning: mismatch in colorPoints()", n, len(cols))
src = vtk.vtkPointSource()
src.SetNumberOfPoints(n)
src.Update()
vgf = vtk.vtkVertexGlyphFilter()
vgf.SetInputData(src.GetOutput())
vgf.Update()
pd = vgf.GetOutput()
ucols = vtk.vtkUnsignedCharArray()
ucols.SetNumberOfComponents(3)
ucols.SetName("pointsRGB")
for i in range(len(plist)):
c = np.array(colors.getColor(cols[i])) * 255
ucols.InsertNextTuple3(c[0], c[1], c[2])
pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
pd.GetPointData().SetScalars(ucols)
actor = Actor(pd, c, alpha)
actor.mapper.ScalarVisibilityOn()
actor.GetProperty().SetInterpolationToFlat()
actor.GetProperty().SetPointSize(r)
settings.collectable_actors.append(actor)
return actor
n = len(plist)
if n == 0:
return None
elif n == 3: # assume plist is in the format [all_x, all_y, all_z]
if utils.isSequence(plist[0]) and len(plist[0]) > 3:
plist = list(zip(plist[0], plist[1], plist[2]))
elif n == 2: # assume plist is in the format [all_x, all_y, 0]
if utils.isSequence(plist[0]) and len(plist[0]) > 3:
plist = list(zip(plist[0], plist[1], [0] * len(plist[0])))
if utils.isSequence(c) and len(c) > 3:
actor = _colorPoints(plist, c, r, alpha)
settings.collectable_actors.append(actor)
return actor
################
n = len(plist) # refresh
sourcePoints = vtk.vtkPoints()
sourceVertices = vtk.vtkCellArray()
is3d = len(plist[0]) > 2
if is3d: # its faster
for pt in plist:
aid = sourcePoints.InsertNextPoint(pt)
sourceVertices.InsertNextCell(1)
sourceVertices.InsertCellPoint(aid)
else:
for pt in plist:
aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0)
sourceVertices.InsertNextCell(1)
sourceVertices.InsertCellPoint(aid)
pd = vtk.vtkPolyData()
pd.SetPoints(sourcePoints)
pd.SetVerts(sourceVertices)
if n == 1: # passing just one point
pd.GetPoints().SetPoint(0, [0, 0, 0])
else:
pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
actor = Actor(pd, c, alpha)
actor.GetProperty().SetPointSize(r)
if n == 1:
actor.SetPosition(plist[0])
settings.collectable_actors.append(actor)
return actor | def Points(plist, r=5, c="gray", alpha=1) | Build a point ``Actor`` for a list of points.
:param float r: point radius.
:param c: color name, number, or list of [R,G,B] colors of same length as plist.
:type c: int, str, list
:param float alpha: transparency in range [0,1].
.. hint:: |lorenz| |lorenz.py|_ | 2.431367 | 2.395094 | 1.015145 |
cmap = None
# user passing a color map to map orientationArray sizes
if c in list(colors._mapscales.keys()):
cmap = c
c = None
# user is passing an array of point colors
if utils.isSequence(c) and len(c) > 3:
ucols = vtk.vtkUnsignedCharArray()
ucols.SetNumberOfComponents(3)
ucols.SetName("glyphRGB")
for col in c:
cl = colors.getColor(col)
ucols.InsertNextTuple3(cl[0]*255, cl[1]*255, cl[2]*255)
actor.polydata().GetPointData().SetScalars(ucols)
c = None
if isinstance(glyphObj, Actor):
glyphObj = glyphObj.clean().polydata()
gly = vtk.vtkGlyph3D()
gly.SetInputData(actor.polydata())
gly.SetSourceData(glyphObj)
gly.SetColorModeToColorByScalar()
if orientationArray != "":
gly.OrientOn()
gly.SetScaleFactor(1)
if scaleByVectorSize:
gly.SetScaleModeToScaleByVector()
else:
gly.SetScaleModeToDataScalingOff()
if orientationArray == "normals" or orientationArray == "Normals":
gly.SetVectorModeToUseNormal()
elif isinstance(orientationArray, vtk.vtkAbstractArray):
actor.GetMapper().GetInput().GetPointData().AddArray(orientationArray)
actor.GetMapper().GetInput().GetPointData().SetActiveVectors("glyph_vectors")
gly.SetInputArrayToProcess(0, 0, 0, 0, "glyph_vectors")
gly.SetVectorModeToUseVector()
elif utils.isSequence(orientationArray): # passing a list
actor.addPointVectors(orientationArray, "glyph_vectors")
gly.SetInputArrayToProcess(0, 0, 0, 0, "glyph_vectors")
else: # passing a name
gly.SetInputArrayToProcess(0, 0, 0, 0, orientationArray)
gly.SetVectorModeToUseVector()
if cmap:
gly.SetColorModeToColorByVector ()
else:
gly.SetColorModeToColorByScalar ()
gly.Update()
pd = gly.GetOutput()
actor = Actor(pd, c, alpha)
if cmap:
lut = vtk.vtkLookupTable()
lut.SetNumberOfTableValues(512)
lut.Build()
for i in range(512):
r, g, b = colors.colorMap(i, cmap, 0, 512)
lut.SetTableValue(i, r, g, b, 1)
actor.mapper.SetLookupTable(lut)
actor.mapper.ScalarVisibilityOn()
actor.mapper.SetScalarModeToUsePointData()
rng = pd.GetPointData().GetScalars().GetRange()
actor.mapper.SetScalarRange(rng[0], rng[1])
actor.GetProperty().SetInterpolationToFlat()
settings.collectable_actors.append(actor)
return actor | def Glyph(actor, glyphObj, orientationArray="",
scaleByVectorSize=False, c=None, alpha=1) | At each vertex of a mesh, another mesh - a `'glyph'` - is shown with
various orientation options and coloring.
Color can be specfied as a colormap which maps the size of the orientation
vectors in `orientationArray`.
:param orientationArray: list of vectors, ``vtkAbstractArray``
or the name of an already existing points array.
:type orientationArray: list, str, vtkAbstractArray
:param bool scaleByVectorSize: glyph mesh is scaled by the size of
the vectors.
.. hint:: |glyphs| |glyphs.py|_
|glyphs_arrow| |glyphs_arrow.py|_ | 2.508747 | 2.50449 | 1.001699 |
# detect if user is passing a 2D ist of points as p0=xlist, p1=ylist:
if len(p0) > 3:
if not utils.isSequence(p0[0]) and not utils.isSequence(p1[0]) and len(p0)==len(p1):
# assume input is 2D xlist, ylist
p0 = list(zip(p0, p1))
p1 = None
# detect if user is passing a list of points:
if utils.isSequence(p0[0]):
ppoints = vtk.vtkPoints() # Generate the polyline
dim = len((p0[0]))
if dim == 2:
for i, p in enumerate(p0):
ppoints.InsertPoint(i, p[0], p[1], 0)
else:
ppoints.SetData(numpy_to_vtk(p0, deep=True))
lines = vtk.vtkCellArray() # Create the polyline.
lines.InsertNextCell(len(p0))
for i in range(len(p0)):
lines.InsertCellPoint(i)
poly = vtk.vtkPolyData()
poly.SetPoints(ppoints)
poly.SetLines(lines)
else: # or just 2 points to link
lineSource = vtk.vtkLineSource()
lineSource.SetPoint1(p0)
lineSource.SetPoint2(p1)
lineSource.Update()
poly = lineSource.GetOutput()
actor = Actor(poly, c, alpha)
actor.GetProperty().SetLineWidth(lw)
if dotted:
actor.GetProperty().SetLineStipplePattern(0xF0F0)
actor.GetProperty().SetLineStippleRepeatFactor(1)
actor.base = np.array(p0)
actor.top = np.array(p1)
settings.collectable_actors.append(actor)
return actor | def Line(p0, p1=None, lw=1, c="r", alpha=1, dotted=False) | Build the line segment between points `p0` and `p1`.
If `p0` is a list of points returns the line connecting them.
A 2D set of coords can also be passed as p0=[x..], p1=[y..].
:param lw: line width.
:param c: color name, number, or list of [R,G,B] colors.
:type c: int, str, list
:param float alpha: transparency in range [0,1].
:param bool dotted: draw a dotted line | 2.689538 | 2.673389 | 1.00604 |
if endPoints is not None:
startPoints = list(zip(startPoints, endPoints))
polylns = vtk.vtkAppendPolyData()
for twopts in startPoints:
lineSource = vtk.vtkLineSource()
lineSource.SetPoint1(twopts[0])
if scale != 1:
vers = (np.array(twopts[1]) - twopts[0]) * scale
pt2 = np.array(twopts[0]) + vers
else:
pt2 = twopts[1]
lineSource.SetPoint2(pt2)
polylns.AddInputConnection(lineSource.GetOutputPort())
polylns.Update()
actor = Actor(polylns.GetOutput(), c, alpha)
actor.GetProperty().SetLineWidth(lw)
if dotted:
actor.GetProperty().SetLineStipplePattern(0xF0F0)
actor.GetProperty().SetLineStippleRepeatFactor(1)
settings.collectable_actors.append(actor)
return actor | def Lines(startPoints, endPoints=None, scale=1, lw=1, c=None, alpha=1, dotted=False) | Build the line segments between two lists of points `startPoints` and `endPoints`.
`startPoints` can be also passed in the form ``[[point1, point2], ...]``.
:param float scale: apply a rescaling factor to the length
|lines|
.. hint:: |fitspheres2.py|_ | 2.68668 | 2.814734 | 0.954506 |
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 | 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|_ | 2.359808 | 2.454078 | 0.961586 |
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 | def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)) | Connect two lines to generate the surface inbetween.
.. hint:: |ribbon| |ribbon.py|_ | 1.620631 | 1.63069 | 0.993831 |
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 | 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|_ | 3.375246 | 3.487056 | 0.967936 |
axis = np.array(endPoint) - np.array(startPoint)
length = np.linalg.norm(axis)
if length:
axis = axis / length
theta = np.arccos(axis[2])
phi = np.arctan2(axis[1], axis[0])
arr = vtk.vtkArrowSource()
arr.SetShaftResolution(res)
arr.SetTipResolution(res)
if s:
sz = 0.02
arr.SetTipRadius(sz)
arr.SetShaftRadius(sz / 1.75)
arr.SetTipLength(sz * 15)
arr.Update()
t = vtk.vtkTransform()
t.RotateZ(phi * 57.3)
t.RotateY(theta * 57.3)
t.RotateY(-90) # put it along Z
if s:
sz = 800.0 * s
t.Scale(length, sz, sz)
else:
t.Scale(length, length, length)
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(arr.GetOutput())
tf.SetTransform(t)
tf.Update()
actor = Actor(tf.GetOutput(), c, alpha)
actor.GetProperty().SetInterpolationToPhong()
actor.SetPosition(startPoint)
actor.DragableOff()
actor.PickableOff()
actor.base = np.array(startPoint)
actor.top = np.array(endPoint)
settings.collectable_actors.append(actor)
return actor | def Arrow(startPoint, endPoint, s=None, c="r", alpha=1, res=12) | Build a 3D arrow from `startPoint` to `endPoint` of section size `s`,
expressed as the fraction of the window size.
.. note:: If ``s=None`` the arrow is scaled proportionally to its length,
otherwise it represents the fraction of the window size.
|OrientedArrow| | 2.513486 | 2.572157 | 0.97719 |
startPoints = np.array(startPoints)
if endPoints is None:
strt = startPoints[:,0]
endPoints = startPoints[:,1]
startPoints = strt
arr = vtk.vtkArrowSource()
arr.SetShaftResolution(res)
arr.SetTipResolution(res)
if s:
sz = 0.02 * s
arr.SetTipRadius(sz*2)
arr.SetShaftRadius(sz)
arr.SetTipLength(sz * 10)
arr.Update()
pts = Points(startPoints)
orients = (endPoints - startPoints) * scale
arrg = Glyph(pts, arr.GetOutput(),
orientationArray=orients, scaleByVectorSize=True,
c=c, alpha=alpha)
settings.collectable_actors.append(arrg)
return arrg | def Arrows(startPoints, endPoints=None, s=None, scale=1, c="r", alpha=1, res=12) | Build arrows between two lists of points `startPoints` and `endPoints`.
`startPoints` can be also passed in the form ``[[point1, point2], ...]``.
Color can be specfied as a colormap which maps the size of the arrows.
:param float s: fix aspect-ratio of the arrow and scale its cross section
:param float scale: apply a rescaling factor to the length
:param c: color or array of colors
:param str cmap: color arrows by size using this color map
:param float alpha: set transparency
:param int res: set arrow resolution
.. hint:: |glyphs_arrow| |glyphs_arrow.py|_ | 3.773953 | 4.206166 | 0.897243 |
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 | 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| | 2.232606 | 2.27221 | 0.98257 |
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) | 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. | 2.141936 | 2.060194 | 1.039677 |
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 | 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| | 2.234048 | 2.248658 | 0.993503 |
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 | def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24) | Build a sphere at position `pos` of radius `r`.
|Sphere| | 2.8249 | 3.126638 | 0.903495 |
cisseq = False
if utils.isSequence(c):
cisseq = True
if cisseq:
if len(centers) > len(c):
colors.printc("~times Mismatch in Spheres() colors", len(centers), len(c), c=1)
exit()
if len(centers) != len(c):
colors.printc("~lightningWarning: mismatch in Spheres() colors", len(centers), len(c))
risseq = False
if utils.isSequence(r):
risseq = True
if risseq:
if len(centers) > len(r):
colors.printc("times Mismatch in Spheres() radius", len(centers), len(r), c=1)
exit()
if len(centers) != len(r):
colors.printc("~lightning Warning: mismatch in Spheres() radius", len(centers), len(r))
if cisseq and risseq:
colors.printc("~noentry Limitation: c and r cannot be both sequences.", c=1)
exit()
src = vtk.vtkSphereSource()
if not risseq:
src.SetRadius(r)
src.SetPhiResolution(res)
src.SetThetaResolution(2 * res)
src.Update()
psrc = vtk.vtkPointSource()
psrc.SetNumberOfPoints(len(centers))
psrc.Update()
pd = psrc.GetOutput()
vpts = pd.GetPoints()
glyph = vtk.vtkGlyph3D()
glyph.SetSourceConnection(src.GetOutputPort())
if cisseq:
glyph.SetColorModeToColorByScalar()
ucols = vtk.vtkUnsignedCharArray()
ucols.SetNumberOfComponents(3)
ucols.SetName("colors")
for i, p in enumerate(centers):
vpts.SetPoint(i, p)
cx, cy, cz = colors.getColor(c[i])
ucols.InsertNextTuple3(cx * 255, cy * 255, cz * 255)
pd.GetPointData().SetScalars(ucols)
glyph.ScalingOff()
elif risseq:
glyph.SetScaleModeToScaleByScalar()
urads = vtk.vtkFloatArray()
urads.SetName("scales")
for i, p in enumerate(centers):
vpts.SetPoint(i, p)
urads.InsertNextValue(r[i])
pd.GetPointData().SetScalars(urads)
else:
for i, p in enumerate(centers):
vpts.SetPoint(i, p)
glyph.SetInputData(pd)
glyph.Update()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(glyph.GetOutput())
actor = Actor()
actor.SetMapper(mapper)
actor.GetProperty().SetInterpolationToPhong()
actor.GetProperty().SetOpacity(alpha)
if cisseq:
mapper.ScalarVisibilityOn()
else:
mapper.ScalarVisibilityOff()
actor.GetProperty().SetColor(colors.getColor(c))
settings.collectable_actors.append(actor)
return actor | def Spheres(centers, r=1, c="r", alpha=1, res=8) | Build a (possibly large) set of spheres at `centers` of radius `r`.
Either `c` or `r` can be a list of RGB colors or radii.
.. hint:: |manyspheres| |manyspheres.py|_ | 2.261144 | 2.228167 | 1.0148 |
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 | def Earth(pos=(0, 0, 0), r=1, lw=1) | Build a textured actor representing the Earth.
.. hint:: |geodesic| |geodesic.py|_ | 2.683356 | 2.676399 | 1.002599 |
elliSource = vtk.vtkSphereSource()
elliSource.SetThetaResolution(res)
elliSource.SetPhiResolution(res)
elliSource.Update()
l1 = np.linalg.norm(axis1)
l2 = np.linalg.norm(axis2)
l3 = np.linalg.norm(axis3)
axis1 = np.array(axis1) / l1
axis2 = np.array(axis2) / l2
axis3 = np.array(axis3) / l3
angle = np.arcsin(np.dot(axis1, axis2))
theta = np.arccos(axis3[2])
phi = np.arctan2(axis3[1], axis3[0])
t = vtk.vtkTransform()
t.PostMultiply()
t.Scale(l1, l2, l3)
t.RotateX(angle * 57.3)
t.RotateY(theta * 57.3)
t.RotateZ(phi * 57.3)
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(elliSource.GetOutput())
tf.SetTransform(t)
tf.Update()
pd = tf.GetOutput()
actor = Actor(pd, c=c, alpha=alpha)
actor.GetProperty().BackfaceCullingOn()
actor.GetProperty().SetInterpolationToPhong()
actor.SetPosition(pos)
actor.base = -np.array(axis1) / 2 + pos
actor.top = np.array(axis1) / 2 + pos
settings.collectable_actors.append(actor)
return actor | def Ellipsoid(pos=(0, 0, 0), axis1=(1, 0, 0), axis2=(0, 2, 0), axis3=(0, 0, 3),
c="c", alpha=1, res=24) | Build a 3D ellipsoid centered at position `pos`.
.. note:: `axis1` and `axis2` are only used to define sizes and one azimuth angle.
|projectsphere| | 1.960287 | 2.004439 | 0.977973 |
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 | 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|_ | 1.998805 | 2.048587 | 0.9757 |
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 | 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| | 2.036326 | 2.100487 | 0.969454 |
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 | 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|_ | 2.110721 | 2.26507 | 0.931857 |
return Box(pos, side, side, side, normal, c, alpha, texture) | 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|_ | 3.710321 | 7.531728 | 0.492625 |
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 | 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|_ | 2.591514 | 2.686839 | 0.964522 |
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 | 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| | 2.426431 | 2.417355 | 1.003755 |
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 | 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| | 3.120995 | 3.313662 | 0.941857 |
return Cone(pos, s, height, axis, c, alpha, 4) | 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`. | 4.886455 | 5.352684 | 0.912898 |
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 | 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|_ | 2.340227 | 2.510956 | 0.932006 |
quadric = vtk.vtkQuadric()
quadric.SetCoefficients(1, 1, 0, 0, 0, 0, 0, 0, height / 4, 0)
# F(x,y,z) = a0*x^2 + a1*y^2 + a2*z^2
# + a3*x*y + a4*y*z + a5*x*z
# + a6*x + a7*y + a8*z +a9
sample = vtk.vtkSampleFunction()
sample.SetSampleDimensions(res, res, res)
sample.SetImplicitFunction(quadric)
contours = vtk.vtkContourFilter()
contours.SetInputConnection(sample.GetOutputPort())
contours.GenerateValues(1, 0.01, 0.01)
contours.Update()
axis = np.array(axis) / np.linalg.norm(axis)
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)
t.Scale(r, r, r)
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(contours.GetOutput())
tf.SetTransform(t)
tf.Update()
pd = tf.GetOutput()
actor = Actor(pd, c, alpha).flipNormals()
actor.GetProperty().SetInterpolationToPhong()
actor.mapper.ScalarVisibilityOff()
actor.SetPosition(pos)
settings.collectable_actors.append(actor)
return actor | def Paraboloid(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="cyan", alpha=1, res=50) | Build a paraboloid of specified height and radius `r`, centered at `pos`.
.. note::
Full volumetric expression is:
:math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`
|paraboloid| | 2.203453 | 2.166626 | 1.016997 |
try:
#def _Latex(formula, pos, normal, c, s, bg, alpha, res, usetex, fromweb):
def build_img_web(formula, tfile):
import requests
if c == 'k':
ct = 'Black'
else:
ct = 'White'
wsite = 'http://latex.codecogs.com/png.latex'
try:
r = requests.get(wsite+'?\dpi{100} \huge \color{'+ct+'} ' + formula)
f = open(tfile, 'wb')
f.write(r.content)
f.close()
except requests.exceptions.ConnectionError:
colors.printc('Latex error. Web site unavailable?', wsite, c=1)
return None
def build_img_plt(formula, tfile):
import matplotlib.pyplot as plt
plt.rc('text', usetex=usetex)
formula1 = '$'+formula+'$'
plt.axis('off')
col = colors.getColor(c)
if bg:
bx = dict(boxstyle="square", ec=col, fc=colors.getColor(bg))
else:
bx = None
plt.text(0.5, 0.5, formula1,
size=res,
color=col,
alpha=alpha,
ha="center",
va="center",
bbox=bx)
plt.savefig('_lateximg.png', format='png',
transparent=True, bbox_inches='tight', pad_inches=0)
plt.close()
if fromweb:
build_img_web(formula, '_lateximg.png')
else:
build_img_plt(formula, '_lateximg.png')
from vtkplotter.actors import ImageActor
picr = vtk.vtkPNGReader()
picr.SetFileName('_lateximg.png')
picr.Update()
vactor = ImageActor()
vactor.SetInputData(picr.GetOutput())
vactor.alpha(alpha)
b = vactor.GetBounds()
xm, ym = (b[1]+b[0])/200*s, (b[3]+b[2])/200*s
vactor.SetOrigin(-xm, -ym, 0)
nax = np.linalg.norm(normal)
if nax:
normal = np.array(normal) / nax
theta = np.arccos(normal[2])
phi = np.arctan2(normal[1], normal[0])
vactor.SetScale(0.25/res*s, 0.25/res*s, 0.25/res*s)
vactor.RotateZ(phi * 57.3)
vactor.RotateY(theta * 57.3)
vactor.SetPosition(pos)
try:
import os
os.unlink('_lateximg.png')
except FileNotFoundError:
pass
return vactor
except:
colors.printc('Error in Latex()\n', formula, c=1)
colors.printc(' latex or dvipng not installed?', c=1)
colors.printc(' Try: usetex=False' , c=1)
colors.printc(' Try: sudo apt install dvipng' , c=1)
return None | def Latex(
formula,
pos=(0, 0, 0),
normal=(0, 0, 1),
c='k',
s=1,
bg=None,
alpha=1,
res=30,
usetex=False,
fromweb=False,
) | Render Latex formulas.
:param str formula: latex text string
:param list pos: position coordinates in space
:param list normal: normal to the plane of the image
:param c: face color
:param bg: background color box
:param int res: dpi resolution
:param bool usetex: use latex compiler of matplotlib
:param fromweb: retrieve the latex image from online server (codecogs)
.. hint:: |latex| |latex.py|_ | 3.002076 | 3.070008 | 0.977873 |
#recursion, return a list if input is list of colors:
if _isSequence(rgb) and len(rgb) > 3:
seqcol = []
for sc in rgb:
seqcol.append(getColor(sc))
return seqcol
if str(rgb).isdigit():
rgb = int(rgb)
if hsv:
c = hsv2rgb(hsv)
else:
c = rgb
if _isSequence(c):
if c[0] <= 1 and c[1] <= 1 and c[2] <= 1:
return c # already rgb
else:
if len(c) == 3:
return list(np.array(c) / 255.0) # RGB
else:
return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3]) # RGBA
elif isinstance(c, str): # is string
c = c.replace(",", " ").replace("/", " ").replace("alpha=", "")
c = c.replace("grey", "gray")
c = c.split()[0] # ignore possible opacity float inside string
if 0 < len(c) < 3: # single/double letter color
if c.lower() in color_nicks.keys():
c = color_nicks[c.lower()]
else:
print("Unknow color nickname:", c)
print("Available abbreviations:", color_nicks)
return (0.5, 0.5, 0.5)
if c.lower() in colors.keys(): # matplotlib name color
c = colors[c.lower()]
else: # vtk name color
namedColors = vtk.vtkNamedColors()
rgba = [0, 0, 0, 0]
namedColors.GetColor(c, rgba)
return list(np.array(rgba[0:3]) / 255.0)
if "#" in c: # hex to rgb
h = c.lstrip("#")
rgb255 = list(int(h[i : i + 2], 16) for i in (0, 2, 4))
rgbh = np.array(rgb255) / 255.0
if np.sum(rgbh) > 3:
print("Error in getColor(): Wrong hex color", c)
return (0.5, 0.5, 0.5)
return tuple(rgbh)
elif isinstance(c, int): # color number
if c >= 0:
return colors1[c % 10]
else:
return colors2[-c % 10]
elif isinstance(c, float):
if c >= 0:
return colors1[int(c) % 10]
else:
return colors2[int(-c) % 10]
#print("Unknown color:", c)
return (0.5, 0.5, 0.5) | def getColor(rgb=None, hsv=None) | Convert a color or list of colors to (r,g,b) format from many input formats.
:param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value).
Example:
- RGB = (255, 255, 255), corresponds to white
- rgb = (1,1,1) is white
- hex = #FFFF00 is yellow
- string = 'white'
- string = 'w' is white nickname
- string = 'dr' is darkred
- int = 7 picks color nr. 7 in a predefined color list
- int = -7 picks color nr. 7 in a different predefined list
.. hint:: |colorcubes| |colorcubes.py|_ | 2.705515 | 2.725967 | 0.992498 |
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 | def getColorName(c) | Find the name of a color.
.. hint:: |colorpalette| |colorpalette.py|_ | 3.936952 | 4.409743 | 0.892785 |
if not _mapscales:
print("-------------------------------------------------------------------")
print("WARNING : cannot import matplotlib.cm (colormaps will show up gray).")
print("Try e.g.: sudo apt-get install python3-matplotlib")
print(" or : pip install matplotlib")
print(" or : build your own map (see example in basic/mesh_custom.py).")
return (0.5, 0.5, 0.5)
if isinstance(name, matplotlib.colors.LinearSegmentedColormap):
mp = name
else:
if name in _mapscales.keys():
mp = _mapscales[name]
else:
print("Error in colorMap():", name, "\navaliable maps =", sorted(_mapscales.keys()))
exit(0)
if _isSequence(value):
values = np.array(value)
if vmin is None:
vmin = np.min(values)
if vmax is None:
vmax = np.max(values)
values = np.clip(values, vmin, vmax)
values -= vmin
values /= vmax - vmin
cols = []
mp = _mapscales[name]
for v in values:
cols.append(mp(v)[0:3])
return np.array(cols)
else:
value -= vmin
value /= vmax - vmin
if value > 0.999:
value = 0.999
elif value < 0:
value = 0
return mp(value)[0:3] | def colorMap(value, name="jet", vmin=None, vmax=None) | Map a real value in range [vmin, vmax] to a (r,g,b) color scale.
:param value: scalar value to transform into a color
:type value: float, list
:param name: color map name
:type name: str, matplotlib.colors.LinearSegmentedColormap
:return: (r,g,b) color, or a list of (r,g,b) colors.
.. note:: Available color maps:
|colormaps|
.. tip:: Can also use directly a matplotlib color map:
:Example:
.. code-block:: python
from vtkplotter import colorMap
import matplotlib.cm as cm
print( colorMap(0.2, cm.flag, 0, 1) )
(1.0, 0.809016994374948, 0.6173258487801733) | 3.347607 | 3.303293 | 1.013415 |
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 | 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|_ | 2.008097 | 2.385837 | 0.841674 |
ctf = vtk.vtkColorTransferFunction()
ctf.SetColorSpaceToDiverging()
for sc in sclist:
scalar, col = sc
r, g, b = getColor(col)
ctf.AddRGBPoint(scalar, r, g, b)
if N is None:
N = len(sclist)
lut = vtk.vtkLookupTable()
lut.SetNumberOfTableValues(N)
lut.Build()
for i in range(N):
rgb = list(ctf.GetColor(float(i) / N)) + [1]
lut.SetTableValue(i, rgb)
return lut | def makeLUTfromCTF(sclist, N=None) | Use a Color Transfer Function to generate colors in a vtk lookup table.
See `here <http://www.vtk.org/doc/nightly/html/classvtkColorTransferFunction.html>`_.
:param list sclist: a list in the form ``[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]``.
:return: the lookup table object ``vtkLookupTable``. This can be fed into ``colorMap``. | 2.041434 | 2.007012 | 1.017151 |
# 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] | def kelvin2rgb(temperature) | Converts from Kelvin temperature to an RGB color.
Algorithm credits: |tannerhelland|_ | 1.268965 | 1.271431 | 0.99806 |
gf = vtk.vtkGeometryFilter()
gf.SetInputData(obj)
gf.Update()
return gf.GetOutput() | def geometry(obj) | Apply ``vtkGeometryFilter``. | 2.904174 | 2.449619 | 1.185562 |
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 | 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|_ | 2.838392 | 2.925744 | 0.970144 |
c = vc.getColor(c) # allow different codings
array_x = vtk.vtkFloatArray()
array_y = vtk.vtkFloatArray()
array_x.SetNumberOfTuples(len(points))
array_y.SetNumberOfTuples(len(points))
for i, p in enumerate(points):
array_x.InsertValue(i, p[0])
array_y.InsertValue(i, p[1])
field = vtk.vtkFieldData()
field.AddArray(array_x)
field.AddArray(array_y)
data = vtk.vtkDataObject()
data.SetFieldData(field)
plot = vtk.vtkXYPlotActor()
plot.AddDataObjectInput(data)
plot.SetDataObjectXComponent(0, 0)
plot.SetDataObjectYComponent(0, 1)
plot.SetXValuesToValue()
plot.SetXTitle(title)
plot.SetYTitle("")
plot.ExchangeAxesOff()
plot.PlotPointsOn()
if not lines:
plot.PlotLinesOff()
plot.GetProperty().SetPointSize(5)
plot.GetProperty().SetLineWidth(2)
plot.SetNumberOfXLabels(3) # not working
plot.GetProperty().SetColor(0, 0, 0)
plot.GetProperty().SetOpacity(0.7)
plot.SetPlotColor(0, c[0], c[1], c[2])
tprop = plot.GetAxisLabelTextProperty()
tprop.SetColor(0, 0, 0)
tprop.SetOpacity(0.7)
tprop.SetFontFamily(0)
tprop.BoldOff()
tprop.ItalicOff()
tprop.ShadowOff()
tprop.SetFontSize(3) # not working
plot.SetAxisTitleTextProperty(tprop)
plot.SetAxisLabelTextProperty(tprop)
plot.SetTitleTextProperty(tprop)
if corner == 1:
plot.GetPositionCoordinate().SetValue(0.0, 0.8, 0)
if corner == 2:
plot.GetPositionCoordinate().SetValue(0.7, 0.8, 0)
if corner == 3:
plot.GetPositionCoordinate().SetValue(0.0, 0.0, 0)
if corner == 4:
plot.GetPositionCoordinate().SetValue(0.7, 0.0, 0)
plot.GetPosition2Coordinate().SetValue(0.3, 0.2, 0)
return plot | def xyplot(points, title="", c="b", corner=1, lines=False) | Return a ``vtkXYPlotActor`` that is a plot of `x` versus `y`,
where `points` is a list of `(x,y)` points.
:param int corner: assign position:
- 1, topleft,
- 2, topright,
- 3, bottomleft,
- 4, bottomright.
.. hint:: Example: |fitspheres1.py|_ | 2.057113 | 2.056604 | 1.000247 |
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) | 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|_ | 2.780334 | 3.575773 | 0.777548 |
xmin, xmax = np.min(xvalues), np.max(xvalues)
ymin, ymax = np.min(yvalues), np.max(yvalues)
dx, dy = xmax - xmin, ymax - ymin
if xmax - xmin < ymax - ymin:
n = bins
m = np.rint(dy / dx * n / 1.2 + 0.5).astype(int)
else:
m = bins
n = np.rint(dx / dy * m * 1.2 + 0.5).astype(int)
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(xvalues))
src.Update()
pointsPolydata = src.GetOutput()
values = list(zip(xvalues, yvalues))
zs = [[0.0]] * len(values)
values = np.append(values, zs, axis=1)
pointsPolydata.GetPoints().SetData(numpy_to_vtk(values, deep=True))
cloud = Actor(pointsPolydata)
c1 = vc.getColor(c)
c2 = np.array(c1) * 0.7
r = 0.47 / n * 1.2 * dx
hexs, binmax = [], 0
for i in range(n + 3):
for j in range(m + 2):
cyl = vtk.vtkCylinderSource()
cyl.SetResolution(6)
cyl.CappingOn()
cyl.SetRadius(0.5)
cyl.SetHeight(0.1)
cyl.Update()
t = vtk.vtkTransform()
if not i % 2:
p = (i / 1.33, j / 1.12, 0)
c = c1
else:
p = (i / 1.33, j / 1.12 + 0.443, 0)
c = c2
q = (p[0] / n * 1.2 * dx + xmin, p[1] / m * dy + ymin, 0)
ids = cloud.closestPoint(q, radius=r, returnIds=True)
ne = len(ids)
if fill:
t.Translate(p[0], p[1], ne / 2)
t.Scale(1, 1, ne * 5)
else:
t.Translate(p[0], p[1], ne)
t.RotateX(90) # put it along Z
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(cyl.GetOutput())
tf.SetTransform(t)
tf.Update()
h = Actor(tf.GetOutput(), c=c, alpha=alpha)
h.PickableOff()
hexs.append(h)
if ne > binmax:
binmax = ne
asse = Assembly(hexs)
asse.SetScale(1 / n * 1.2 * dx, 1 / m * dy, norm / binmax * (dx + dy) / 4)
asse.SetPosition(xmin, ymin, 0)
return asse | def histogram2D(xvalues, yvalues, bins=12, norm=1, c="g", alpha=1, fill=False) | Build a 2D hexagonal histogram from a list of x and y values.
:param bool bins: nr of bins for the smaller range in x or y.
:param float norm: sets a scaling factor for the z axis.
:param bool fill: draw solid hexagons.
.. hint:: |histo2D| |histo2D.py|_ | 2.663569 | 2.673003 | 0.996471 |
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()) | 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|_ | 2.603735 | 2.412486 | 1.079275 |
deln = vtk.vtkDelaunay3D()
deln.SetInputData(dataset)
deln.SetAlpha(alpha)
if tol:
deln.SetTolerance(tol)
deln.SetBoundingTriangulation(boundary)
deln.Update()
return deln.GetOutput() | def delaunay3D(dataset, alpha=0, tol=None, boundary=True) | Create 3D Delaunay triangulation of input points. | 2.306903 | 2.285061 | 1.009559 |
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 | 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. | 2.470643 | 2.434517 | 1.014839 |
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 | def extractLargestRegion(actor) | Keep only the largest connected part of a mesh and discard all the smaller pieces.
.. hint:: |largestregion.py|_ | 3.423074 | 3.348107 | 1.022391 |
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 | def alignLandmarks(source, target, rigid=False) | Find best matching of source points towards target
in the mean least square sense, in one single step. | 3.844069 | 3.837896 | 1.001608 |
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 | 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|_ | 2.041583 | 2.032527 | 1.004455 |
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 | 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|_ | 3.899233 | 3.925994 | 0.993184 |
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 | 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|_ | 2.639031 | 2.510887 | 1.051035 |
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 | 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|_ | 3.018726 | 2.838097 | 1.063645 |
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 | 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|_ | 2.633111 | 2.682091 | 0.981738 |
try:
from scipy.stats import f
except ImportError:
vc.printc("~times Error in Ellipsoid(): scipy not installed. Skip.", c=1)
return None
if isinstance(points, vtk.vtkActor):
points = points.coordinates()
if len(points) == 0:
return None
P = np.array(points, ndmin=2, dtype=float)
cov = np.cov(P, rowvar=0) # covariance matrix
U, s, R = np.linalg.svd(cov) # singular value decomposition
p, n = s.size, P.shape[0]
fppf = f.ppf(pvalue, p, n-p)*(n-1)*p*(n+1)/n/(n-p) # f % point function
ua, ub, uc = np.sqrt(s*fppf)*2 # semi-axes (largest first)
center = np.mean(P, axis=0) # centroid of the hyperellipsoid
sphericity = ( ((ua-ub)/(ua+ub))**2
+ ((ua-uc)/(ua+uc))**2
+ ((ub-uc)/(ub+uc))**2)/3. * 4.
elliSource = vtk.vtkSphereSource()
elliSource.SetThetaResolution(48)
elliSource.SetPhiResolution(48)
matri = vtk.vtkMatrix4x4()
matri.DeepCopy((R[0][0] * ua, R[1][0] * ub, R[2][0] * uc, center[0],
R[0][1] * ua, R[1][1] * ub, R[2][1] * uc, center[1],
R[0][2] * ua, R[1][2] * ub, R[2][2] * uc, center[2], 0, 0, 0, 1))
vtra = vtk.vtkTransform()
vtra.SetMatrix(matri)
ftra = vtk.vtkTransformFilter()
ftra.SetTransform(vtra)
ftra.SetInputConnection(elliSource.GetOutputPort())
ftra.Update()
actor_elli = Actor(ftra.GetOutput(), "c", 0.5)
actor_elli.GetProperty().BackfaceCullingOn()
actor_elli.GetProperty().SetInterpolationToPhong()
if pcaAxes:
axs = []
for ax in ([1, 0, 0], [0, 1, 0], [0, 0, 1]):
l = vtk.vtkLineSource()
l.SetPoint1([0, 0, 0])
l.SetPoint2(ax)
l.Update()
t = vtk.vtkTransformFilter()
t.SetTransform(vtra)
t.SetInputData(l.GetOutput())
t.Update()
axs.append(Actor(t.GetOutput(), "c", 0.5).lineWidth(3))
finact = Assembly([actor_elli] + axs)
else:
finact = actor_elli
finact.info["sphericity"] = sphericity
finact.info["va"] = ua
finact.info["vb"] = ub
finact.info["vc"] = uc
return finact | def pcaEllipsoid(points, pvalue=0.95, pcaAxes=False) | Show the oriented PCA ellipsoid that contains fraction `pvalue` of points.
:param float pvalue: ellypsoid will contain the specified fraction of points.
:param bool pcaAxes: if `True`, show the 3 PCA semi axes.
Extra info is stored in ``actor.info['sphericity']``,
``actor.info['va']``, ``actor.info['vb']``, ``actor.info['vc']``
(sphericity is equal to 0 for a perfect sphere).
.. hint:: |pca| |pca.py|_
|cell_main| |cell_main.py|_ | 2.761795 | 2.654107 | 1.040574 |
from scipy.spatial import KDTree
coords4d = []
for a in actors: # build the list of 4d coordinates
coords3d = a.coordinates()
n = len(coords3d)
pttimes = [[a.time()]] * n
coords4d += np.append(coords3d, pttimes, axis=1).tolist()
avedt = float(actors[-1].time() - actors[0].time()) / len(actors)
print("Average time separation between actors dt =", round(avedt, 3))
coords4d = np.array(coords4d)
newcoords4d = []
kd = KDTree(coords4d, leafsize=neighbours)
suggest = ""
pb = vio.ProgressBar(0, len(coords4d))
for i in pb.range():
mypt = coords4d[i]
# dr = np.sqrt(3*dx**2+dt**2)
# iclosest = kd.query_ball_Point(mypt, r=dr)
# dists, iclosest = kd.query(mypt, k=None, distance_upper_bound=dr)
dists, iclosest = kd.query(mypt, k=neighbours)
closest = coords4d[iclosest]
nc = len(closest)
if nc >= neighbours and nc > 5:
m = np.linalg.lstsq(closest, [1.0] * nc)[0] # needs python3
vers = m / np.linalg.norm(m)
hpcenter = np.mean(closest, axis=0) # hyperplane center
dist = np.dot(mypt - hpcenter, vers)
projpt = mypt - dist * vers
newcoords4d.append(projpt)
if not i % 1000: # work out some stats
v = np.std(closest, axis=0)
vx = round((v[0] + v[1] + v[2]) / 3, 3)
suggest = "data suggest dt=" + str(vx)
pb.print(suggest)
newcoords4d = np.array(newcoords4d)
ctimes = newcoords4d[:, 3]
ccoords3d = np.delete(newcoords4d, 3, axis=1) # get rid of time
act = vs.Points(ccoords3d)
act.pointColors(ctimes, cmap="jet") # use a colormap to associate a color to time
return act | def smoothMLS3D(actors, neighbours=10) | A time sequence of actors is being smoothed in 4D
using a `MLS (Moving Least Squares)` variant.
The time associated to an actor must be specified in advance with ``actor.time()`` method.
Data itself can suggest a meaningful time separation based on the spatial
distribution of points.
:param int neighbours: fixed nr. of neighbours in space-time to take into account in the fit.
.. hint:: |moving_least_squares3D| |moving_least_squares3D.py|_ | 4.235018 | 4.182946 | 1.012449 |
coords = actor.coordinates()
ncoords = len(coords)
Ncp = int(ncoords * f / 100)
nshow = int(ncoords / decimate)
if showNPlanes:
ndiv = int(nshow / showNPlanes * decimate)
if Ncp < 5:
vc.printc("~target Please choose a fraction higher than " + str(f), c=1)
Ncp = 5
print("smoothMLS: Searching #neighbours, #pt:", Ncp, ncoords)
poly = actor.GetMapper().GetInput()
vpts = poly.GetPoints()
locator = vtk.vtkPointLocator()
locator.SetDataSet(poly)
locator.BuildLocator()
vtklist = vtk.vtkIdList()
variances, newsurf, acts = [], [], []
pb = vio.ProgressBar(0, ncoords)
for i, p in enumerate(coords):
pb.print("smoothing...")
if i % decimate:
continue
locator.FindClosestNPoints(Ncp, p, vtklist)
points = []
for j in range(vtklist.GetNumberOfIds()):
trgp = [0, 0, 0]
vpts.GetPoint(vtklist.GetId(j), trgp)
points.append(trgp)
if len(points) < 5:
continue
points = np.array(points)
pointsmean = points.mean(axis=0) # plane center
uu, dd, vv = np.linalg.svd(points - pointsmean)
a, b, c = np.cross(vv[0], vv[1]) # normal
d, e, f = pointsmean # plane center
x, y, z = p
t = a * d - a * x + b * e - b * y + c * f - c * z # /(a*a+b*b+c*c)
newp = [x + t * a, y + t * b, z + t * c]
variances.append(dd[2])
newsurf.append(newp)
if recursive:
vpts.SetPoint(i, newp)
if showNPlanes and not i % ndiv:
plane = fitPlane(points).alpha(0.3) # fitting plane
iapts = vs.Points(points) # blue points
acts += [plane, iapts]
if decimate == 1 and not recursive:
for i in range(ncoords):
vpts.SetPoint(i, newsurf[i])
actor.info["variances"] = np.array(variances)
if showNPlanes:
apts = vs.Points(newsurf, c="r 0.6", r=2)
ass = Assembly([apts] + acts)
return ass # NB: a demo actor is returned
return actor | def smoothMLS2D(actor, f=0.2, decimate=1, recursive=0, showNPlanes=0) | Smooth actor or points with a `Moving Least Squares` variant.
The list ``actor.info['variances']`` contains the residue calculated for each point.
Input actor's polydata is modified.
:param f: smoothing factor - typical range is [0,2].
:param decimate: decimation factor (an integer number).
:param recursive: move points while algorithm proceedes.
:param showNPlanes: build an actor showing the fitting plane for N random points.
.. hint:: |mesh_smoothers| |mesh_smoothers.py|_
|moving_least_squares2D| |moving_least_squares2D.py|_
|recosurface| |recosurface.py|_ | 4.558927 | 4.392135 | 1.037975 |
coords = actor.coordinates()
ncoords = len(coords)
Ncp = int(ncoords * f / 10)
nshow = int(ncoords)
if showNLines:
ndiv = int(nshow / showNLines)
if Ncp < 3:
vc.printc("~target Please choose a fraction higher than " + str(f), c=1)
Ncp = 3
poly = actor.GetMapper().GetInput()
vpts = poly.GetPoints()
locator = vtk.vtkPointLocator()
locator.SetDataSet(poly)
locator.BuildLocator()
vtklist = vtk.vtkIdList()
variances, newline, acts = [], [], []
for i, p in enumerate(coords):
locator.FindClosestNPoints(Ncp, p, vtklist)
points = []
for j in range(vtklist.GetNumberOfIds()):
trgp = [0, 0, 0]
vpts.GetPoint(vtklist.GetId(j), trgp)
points.append(trgp)
if len(points) < 2:
continue
points = np.array(points)
pointsmean = points.mean(axis=0) # plane center
uu, dd, vv = np.linalg.svd(points - pointsmean)
newp = np.dot(p - pointsmean, vv[0]) * vv[0] + pointsmean
variances.append(dd[1] + dd[2])
newline.append(newp)
if showNLines and not i % ndiv:
fline = fitLine(points, lw=4) # fitting plane
iapts = vs.Points(points) # blue points
acts += [fline, iapts]
for i in range(ncoords):
vpts.SetPoint(i, newline[i])
if showNLines:
apts = vs.Points(newline, c="r 0.6", r=2)
ass = Assembly([apts] + acts)
return ass # NB: a demo actor is returned
actor.info["variances"] = np.array(variances)
return actor | def smoothMLS1D(actor, f=0.2, showNLines=0) | Smooth actor or points with a `Moving Least Squares` variant.
The list ``actor.info['variances']`` contain the residue calculated for each point.
Input actor's polydata is modified.
:param float f: smoothing factor - typical range is [0,2].
:param int showNLines: build an actor showing the fitting line for N random points.
.. hint:: |moving_least_squares1D| |moving_least_squares1D.py|_
|skeletonize| |skeletonize.py|_ | 4.696812 | 4.538127 | 1.034967 |
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 | 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|_ | 2.339229 | 2.437074 | 0.959851 |
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 | def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3) | Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_ | 2.876925 | 3.209591 | 0.896352 |
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 | def probePoints(img, pts) | Takes a ``vtkImageData`` and probes its scalars at the specified points in space. | 2.552973 | 2.482833 | 1.02825 |
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 | 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|_ | 2.886573 | 2.93953 | 0.981985 |
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 | 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|_ | 2.742788 | 3.110353 | 0.881825 |
op = operation.lower()
if op in ["median"]:
mf = vtk.vtkImageMedian3D()
mf.SetInputData(image1)
mf.Update()
return mf.GetOutput()
elif op in ["mag"]:
mf = vtk.vtkImageMagnitude()
mf.SetInputData(image1)
mf.Update()
return mf.GetOutput()
elif op in ["dot", "dotproduct"]:
mf = vtk.vtkImageDotProduct()
mf.SetInput1Data(image1)
mf.SetInput2Data(image2)
mf.Update()
return mf.GetOutput()
elif op in ["grad", "gradient"]:
mf = vtk.vtkImageGradient()
mf.SetDimensionality(3)
mf.SetInputData(image1)
mf.Update()
return mf.GetOutput()
elif op in ["div", "divergence"]:
mf = vtk.vtkImageDivergence()
mf.SetInputData(image1)
mf.Update()
return mf.GetOutput()
elif op in ["laplacian"]:
mf = vtk.vtkImageLaplacian()
mf.SetDimensionality(3)
mf.SetInputData(image1)
mf.Update()
return mf.GetOutput()
mat = vtk.vtkImageMathematics()
mat.SetInput1Data(image1)
K = None
if image2:
if isinstance(image2, vtk.vtkImageData):
mat.SetInput2Data(image2)
else: # assume image2 is a constant value
K = image2
mat.SetConstantK(K)
mat.SetConstantC(K)
if op in ["+", "add", "plus"]:
if K:
mat.SetOperationToAddConstant()
else:
mat.SetOperationToAdd()
elif op in ["-", "subtract", "minus"]:
if K:
mat.SetConstantC(-K)
mat.SetOperationToAddConstant()
else:
mat.SetOperationToSubtract()
elif op in ["*", "multiply", "times"]:
if K:
mat.SetOperationToMultiplyByK()
else:
mat.SetOperationToMultiply()
elif op in ["/", "divide"]:
if K:
mat.SetConstantK(1.0 / K)
mat.SetOperationToMultiplyByK()
else:
mat.SetOperationToDivide()
elif op in ["1/x", "invert"]:
mat.SetOperationToInvert()
elif op in ["sin"]:
mat.SetOperationToSin()
elif op in ["cos"]:
mat.SetOperationToCos()
elif op in ["exp"]:
mat.SetOperationToExp()
elif op in ["log"]:
mat.SetOperationToLog()
elif op in ["abs"]:
mat.SetOperationToAbsoluteValue()
elif op in ["**2", "square"]:
mat.SetOperationToSquare()
elif op in ["sqrt", "sqr"]:
mat.SetOperationToSquareRoot()
elif op in ["min"]:
mat.SetOperationToMin()
elif op in ["max"]:
mat.SetOperationToMax()
elif op in ["atan"]:
mat.SetOperationToATAN()
elif op in ["atan2"]:
mat.SetOperationToATAN2()
else:
vc.printc("~times Error in imageOperation: unknown operation", operation, c=1)
exit()
mat.Update()
return mat.GetOutput() | def imageOperation(image1, operation, image2=None) | Perform operations with ``vtkImageData`` objects.
`image2` can be a constant value.
Possible operations are: ``+``, ``-``, ``/``, ``1/x``, ``sin``, ``cos``, ``exp``, ``log``,
``abs``, ``**2``, ``sqrt``, ``min``, ``max``, ``atan``, ``atan2``, ``median``,
``mag``, ``dot``, ``gradient``, ``divergence``, ``laplacian``.
.. hint:: |imageOperations| |imageOperations.py|_ | 1.85964 | 1.686001 | 1.102989 |
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") | 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|_ | 2.852012 | 2.866945 | 0.994791 |
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 | 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|_ | 3.374085 | 3.263726 | 1.033814 |
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 | def removeOutliers(points, radius) | Remove outliers from a cloud of points within the specified `radius` search.
.. hint:: |clustering| |clustering.py|_ | 2.666253 | 2.747932 | 0.970276 |
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 | 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|_ | 3.503775 | 3.22291 | 1.087147 |
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 | def transformFilter(actor, transformation) | Transform a ``vtkActor`` and return a new object. | 2.738102 | 2.691306 | 1.017388 |
mesh = actor.GetMapper().GetInput()
qf = vtk.vtkMeshQuality()
qf.SetInputData(mesh)
qf.SetTriangleQualityMeasure(measure)
qf.SaveCellQualityOn()
qf.Update()
pd = vtk.vtkPolyData()
pd.ShallowCopy(qf.GetOutput())
qactor = Actor(pd, c=None, alpha=1)
qactor.mapper.SetScalarRange(pd.GetScalarRange())
return qactor | def meshQuality(actor, measure=6) | Calculate functions of quality of the elements of a triangular mesh.
See class `vtkMeshQuality <https://vtk.org/doc/nightly/html/classvtkMeshQuality.html>`_
for explaination.
:param int measure: type of estimator
- EDGE_RATIO, 0
- ASPECT_RATIO, 1
- RADIUS_RATIO, 2
- ASPECT_FROBENIUS, 3
- MED_ASPECT_FROBENIUS, 4
- MAX_ASPECT_FROBENIUS, 5
- MIN_ANGLE, 6
- COLLAPSE_RATIO, 7
- MAX_ANGLE, 8
- CONDITION, 9
- SCALED_JACOBIAN, 10
- SHEAR, 11
- RELATIVE_SIZE_SQUARED, 12
- SHAPE, 13
- SHAPE_AND_SIZE, 14
- DISTORTION, 15
- MAX_EDGE_RATIO, 16
- SKEW, 17
- TAPER, 18
- VOLUME, 19
- STRETCH, 20
- DIAGONAL, 21
- DIMENSION, 22
- ODDY, 23
- SHEAR_AND_SIZE, 24
- JACOBIAN, 25
- WARPAGE, 26
- ASPECT_GAMMA, 27
- AREA, 28
- ASPECT_BETA, 29
.. hint:: |meshquality| |meshquality.py|_ | 3.369062 | 3.816262 | 0.882817 |
# https://vtk.org/doc/nightly/html/classvtkConnectedPointsFilter.html
cpf = vtk.vtkConnectedPointsFilter()
cpf.SetInputData(actor.polydata())
cpf.SetRadius(radius)
if mode == 0: # Extract all regions
pass
elif mode == 1: # Extract point seeded regions
cpf.SetExtractionModeToPointSeededRegions()
for s in seeds:
cpf.AddSeed(s)
elif mode == 2: # Test largest region
cpf.SetExtractionModeToLargestRegion()
elif mode == 3: # Test specified regions
cpf.SetExtractionModeToSpecifiedRegions()
for r in regions:
cpf.AddSpecifiedRegion(r)
elif mode == 4: # Extract all regions with scalar connectivity
cpf.SetExtractionModeToLargestRegion()
cpf.ScalarConnectivityOn()
cpf.SetScalarRange(vrange[0], vrange[1])
elif mode == 5: # Extract point seeded regions
cpf.SetExtractionModeToLargestRegion()
cpf.ScalarConnectivityOn()
cpf.SetScalarRange(vrange[0], vrange[1])
cpf.AlignedNormalsOn()
cpf.SetNormalAngle(angle)
cpf.Update()
return Actor(cpf.GetOutput()) | def connectedPoints(actor, radius, mode=0, regions=(), vrange=(0,1), seeds=(), angle=0) | Extracts and/or segments points from a point cloud based on geometric distance measures
(e.g., proximity, normal alignments, etc.) and optional measures such as scalar range.
The default operation is to segment the points into "connected" regions where the connection
is determined by an appropriate distance measure. Each region is given a region id.
Optionally, the filter can output the largest connected region of points; a particular region
(via id specification); those regions that are seeded using a list of input point ids;
or the region of points closest to a specified position.
The key parameter of this filter is the radius defining a sphere around each point which defines
a local neighborhood: any other points in the local neighborhood are assumed connected to the point.
Note that the radius is defined in absolute terms.
Other parameters are used to further qualify what it means to be a neighboring point.
For example, scalar range and/or point normals can be used to further constrain the neighborhood.
Also the extraction mode defines how the filter operates.
By default, all regions are extracted but it is possible to extract particular regions;
the region closest to a seed point; seeded regions; or the largest region found while processing.
By default, all regions are extracted.
On output, all points are labeled with a region number.
However note that the number of input and output points may not be the same:
if not extracting all regions then the output size may be less than the input size.
:param float radius: radius variable specifying a local sphere used to define local point neighborhood
:param int mode:
- 0, Extract all regions
- 1, Extract point seeded regions
- 2, Extract largest region
- 3, Test specified regions
- 4, Extract all regions with scalar connectivity
- 5, Extract point seeded regions
:param list regions: a list of non-negative regions id to extract
:param list vrange: scalar range to use to extract points based on scalar connectivity
:param list seeds: a list of non-negative point seed ids
:param list angle: points are connected if the angle between their normals is
within this angle threshold (expressed in degrees). | 2.634255 | 2.151192 | 1.224556 |
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 | 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|_ | 3.372714 | 3.404362 | 0.990704 |
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 | def pointSampler(actor, distance=None) | Algorithm to generate points the specified distance apart. | 3.41063 | 3.456565 | 0.986711 |
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 | 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|_ | 3.423521 | 3.398068 | 1.00749 |
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 | 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|_ | 2.89204 | 2.930881 | 0.986748 |
# https://vtk.org/Wiki/VTK/Examples/Cxx/PolyData/PolyDataToImageData
pd = actor.polydata()
whiteImage = vtk.vtkImageData()
bounds = pd.GetBounds()
whiteImage.SetSpacing(spacing)
# compute dimensions
dim = [0, 0, 0]
for i in [0, 1, 2]:
dim[i] = int(np.ceil((bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i]))
whiteImage.SetDimensions(dim)
whiteImage.SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1)
origin = [0, 0, 0]
origin[0] = bounds[0] + spacing[0] / 2
origin[1] = bounds[2] + spacing[1] / 2
origin[2] = bounds[4] + spacing[2] / 2
whiteImage.SetOrigin(origin)
whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
# fill the image with foreground voxels:
inval = 255
count = whiteImage.GetNumberOfPoints()
for i in range(count):
whiteImage.GetPointData().GetScalars().SetTuple1(i, inval)
# polygonal data --> image stencil:
pol2stenc = vtk.vtkPolyDataToImageStencil()
pol2stenc.SetInputData(pd)
pol2stenc.SetOutputOrigin(origin)
pol2stenc.SetOutputSpacing(spacing)
pol2stenc.SetOutputWholeExtent(whiteImage.GetExtent())
pol2stenc.Update()
# cut the corresponding white image and set the background:
outval = 0
imgstenc = vtk.vtkImageStencil()
imgstenc.SetInputData(whiteImage)
imgstenc.SetStencilConnection(pol2stenc.GetOutputPort())
imgstenc.ReverseStencilOff()
imgstenc.SetBackgroundValue(outval)
imgstenc.Update()
return imgstenc.GetOutput() | def actor2ImageData(actor, spacing=(1, 1, 1)) | Convert a mesh it into volume representation as ``vtkImageData``
where the foreground (exterior) voxels are 1 and the background
(interior) voxels are 0.
Internally the ``vtkPolyDataToImageStencil`` class is used.
.. hint:: |mesh2volume| |mesh2volume.py|_ | 2.048874 | 2.022106 | 1.013238 |
dist = vtk.vtkSignedDistance()
dist.SetInputData(actor.polydata(True))
dist.SetRadius(maxradius)
dist.SetBounds(bounds)
dist.SetDimensions(dims)
dist.Update()
return Volume(dist.GetOutput()) | def signedDistance(actor, maxradius=0.5, bounds=(0, 1, 0, 1, 0, 1), dims=(10, 10, 10)) | ``vtkSignedDistance`` filter.
:param float maxradius: how far out to propagate distance calculation
:param list bounds: volume bounds. | 2.725326 | 3.245981 | 0.8396 |
fe = vtk.vtkExtractSurface()
fe.SetInputData(image)
fe.SetRadius(radius)
fe.Update()
return Actor(fe.GetOutput()) | def extractSurface(image, radius=0.5) | ``vtkExtractSurface`` filter. Input is a ``vtkImageData``.
Generate zero-crossing isosurface from truncated signed distance volume. | 4.012754 | 3.843775 | 1.043962 |
poly = actor.polydata()
psf = vtk.vtkProjectSphereFilter()
psf.SetInputData(poly)
psf.Update()
a = Actor(psf.GetOutput())
return a | def projectSphereFilter(actor) | Project a spherical-like object onto a plane.
.. hint:: |projectsphere| |projectsphere.py|_ | 4.000448 | 4.233358 | 0.944982 |
output = actor.polydata()
# Create a probe volume
probe = vtk.vtkImageData()
probe.SetDimensions(dims)
if bounds is None:
bounds = output.GetBounds()
probe.SetOrigin(bounds[0],bounds[2],bounds[4])
probe.SetSpacing((bounds[1]-bounds[0])/(dims[0]-1),
(bounds[3]-bounds[2])/(dims[1]-1),
(bounds[5]-bounds[4])/(dims[2]-1))
if radius is None:
radius = min(bounds[1]-bounds[0], bounds[3]-bounds[2], bounds[5]-bounds[4])/3
locator = vtk.vtkPointLocator()
locator.SetDataSet(output)
locator.BuildLocator()
if kernel == 'shepard':
kern = vtk.vtkShepardKernel()
kern.SetPowerParameter(2)
kern.SetRadius(radius)
elif kernel == 'gaussian':
kern = vtk.vtkGaussianKernel()
kern.SetRadius(radius)
elif kernel == 'voronoi':
kern = vtk.vtkVoronoiKernel()
elif kernel == 'linear':
kern = vtk.vtkLinearKernel()
kern.SetRadius(radius)
else:
print('Error in interpolateToImageData, available kernels are:')
print(' [shepard, gaussian, voronoi, linear]')
exit()
interpolator = vtk.vtkPointInterpolator()
interpolator.SetInputData(probe)
interpolator.SetSourceData(output)
interpolator.SetKernel(kern)
interpolator.SetLocator(locator)
if nullValue is not None:
interpolator.SetNullValue(nullValue)
else:
interpolator.SetNullPointsStrategyToClosestPoint()
interpolator.Update()
return interpolator.GetOutput() | def interpolateToImageData(actor, kernel='shepard', radius=None,
bounds=None, nullValue=None,
dims=(20,20,20)) | Generate a voxel dataset (vtkImageData) by interpolating a scalar
which is only known on a scattered set of points or mesh.
Available interpolation kernels are: shepard, gaussian, voronoi, linear.
:param str kernel: interpolation kernel type [shepard]
:param float radius: radius of the local search
:param list bounds: bounding box of the output vtkImageData object
:param list dims: dimensions of the output vtkImageData object
:param float nullValue: value to be assigned to invalid points | 1.917264 | 1.963309 | 0.976547 |
if six.PY2:
argspec = inspect.getargspec(func)
args = argspec.args[1:] # ignore 'self'
defaults = argspec.defaults or []
# Split args into two lists depending on whether they have default value
no_default = args[:len(args) - len(defaults)]
with_default = args[len(args) - len(defaults):]
# Join the two lists and combine it with default values
args = [(arg,) for arg in no_default] + zip(with_default, defaults)
# Add possible *args and **kwargs and prepend them with '*' or '**'
varargs = [('*' + argspec.varargs,)] if argspec.varargs else []
kwargs = [('**' + argspec.keywords,)] if argspec.keywords else []
return args + varargs + kwargs
sig = inspect.signature(func)
args = []
for arg_name, param in sig.parameters.items():
name = arg_name
# Ignore 'self'
if name == 'self':
continue
if param.kind == inspect.Parameter.VAR_POSITIONAL:
name = '*' + name
elif param.kind == inspect.Parameter.VAR_KEYWORD:
name = '**' + name
if param.default != inspect.Parameter.empty:
args.append((name, param.default))
else:
args.append((name,))
return args | def get_func_full_args(func) | Return a list of (argument name, default value) tuples. If the argument
does not have a default value, omit it in the tuple. Arguments such as
*args and **kwargs are also included. | 2.325894 | 2.331761 | 0.997484 |
if six.PY2:
return inspect.getargspec(func)[1] is not None
return any(
p for p in inspect.signature(func).parameters.values()
if p.kind == p.VAR_POSITIONAL
) | def func_accepts_var_args(func) | Return True if function 'func' accepts positional arguments *args. | 3.189917 | 2.833006 | 1.125983 |
if self._with_discovery:
# Start the server to listen to new devices
self.upnp.server.set_spawn(2)
self.upnp.server.start()
if self._with_subscribers:
# Start the server to listen to events
self.registry.server.set_spawn(2)
self.registry.server.start() | def start(self) | Start the server(s) necessary to receive information from devices. | 5.483813 | 4.43391 | 1.236789 |
try:
if timeout:
gevent.sleep(timeout)
else:
while True:
gevent.sleep(1000)
except (KeyboardInterrupt, SystemExit, Exception):
pass | def wait(self, timeout=None) | Wait for events. | 3.415841 | 3.352159 | 1.018997 |
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 | def discover(self, seconds=2) | Discover devices in the environment.
@param seconds: Number of seconds to broadcast requests.
@type seconds: int | 4.622562 | 4.440219 | 1.041066 |
if force_update or self._state is None:
return int(self.basicevent.GetBinaryState()['BinaryState'])
return self._state | def get_state(self, force_update=False) | Returns 0 if off and 1 if on. | 7.670384 | 5.329496 | 1.439232 |
def _decorator(func):
if isinstance(signal, (list, tuple)):
for s in signal:
s.connect(func, **kwargs)
else:
signal.connect(func, **kwargs)
return func
return _decorator | def receiver(signal, **kwargs) | A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_save, post_delete], sender=MyModel)
def signals_receiver(sender, **kwargs):
... | 2.177118 | 2.185701 | 0.996073 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.