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() # vtkActorColle...
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...
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", "...
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: ...
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 ...
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): ...
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 ...
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 "...
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...
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 th...
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 -...
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.c...
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) #...
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) ...
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...
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.SetNumbe...
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...
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...
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 al...
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]) *...
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....
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(line...
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])...
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 ...
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.SetTipRadiu...
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 ...
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.GetOu...
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....
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) r...
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: mis...
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 = v...
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.ar...
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.arr...
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.a...
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.Post...
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: ...
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(axi...
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 a...
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....
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) sam...
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...
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 ...
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: ...
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 - s...
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") ...
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:: ...
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)) co...
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: |...
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.B...
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 ca...
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) ...
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 #...
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...
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]) ...
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...
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) ...
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...
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...
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.Se...
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.GetL...
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...
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()) ...
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 re...
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) ...
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) ...
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 ran...
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(point...
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['v...
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() - a...
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 nei...
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 ...
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 ...
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...
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...
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.SetOperationToInterse...
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.InsertNe...
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) # ...
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....
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() ...
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``, ...
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() ...
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) ...
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(poin...
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.vtk...
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 Thi...
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() ...
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.SetScalarR...
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_...
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.SetExtra...
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 distan...
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 == ma...
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.GenerateV...
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: dijks...
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 ...
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() dela...
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, ...
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 + ...
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), ...
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...
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[le...
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) ...
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: ...
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...
2.177118
2.185701
0.996073