repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
marcomusy/vtkplotter
vtkplotter/plotter.py
Plotter.add
def add(self, actors): """Append input object to the internal list of actors to be shown. :return: returns input actor for possible concatenation. """ if utils.isSequence(actors): for a in actors: if a not in self.actors: self.actors.append(a) return None else: self.actors.append(actors) return actors
python
def add(self, actors): """Append input object to the internal list of actors to be shown. :return: returns input actor for possible concatenation. """ if utils.isSequence(actors): for a in actors: if a not in self.actors: self.actors.append(a) return None else: self.actors.append(actors) return actors
[ "def", "add", "(", "self", ",", "actors", ")", ":", "if", "utils", ".", "isSequence", "(", "actors", ")", ":", "for", "a", "in", "actors", ":", "if", "a", "not", "in", "self", ".", "actors", ":", "self", ".", "actors", ".", "append", "(", "a", ...
Append input object to the internal list of actors to be shown. :return: returns input actor for possible concatenation.
[ "Append", "input", "object", "to", "the", "internal", "list", "of", "actors", "to", "be", "shown", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L647-L659
train
210,400
marcomusy/vtkplotter
vtkplotter/plotter.py
Plotter.light
def light( self, pos=(1, 1, 1), fp=(0, 0, 0), deg=25, diffuse="y", ambient="r", specular="b", showsource=False, ): """ Generate a source of light placed at pos, directed to focal point fp. :param fp: focal Point, if this is a ``vtkActor`` use its position. :type fp: vtkActor, list :param deg: aperture angle of the light source :param showsource: if `True`, will show a vtk representation of the source of light as an extra actor .. hint:: |lights.py|_ """ if isinstance(fp, vtk.vtkActor): fp = fp.GetPosition() light = vtk.vtkLight() light.SetLightTypeToSceneLight() light.SetPosition(pos) light.SetPositional(1) light.SetConeAngle(deg) light.SetFocalPoint(fp) light.SetDiffuseColor(colors.getColor(diffuse)) light.SetAmbientColor(colors.getColor(ambient)) light.SetSpecularColor(colors.getColor(specular)) save_int = self.interactive self.show(interactive=0) self.interactive = save_int if showsource: lightActor = vtk.vtkLightActor() lightActor.SetLight(light) self.renderer.AddViewProp(lightActor) self.renderer.AddLight(light) return light
python
def light( self, pos=(1, 1, 1), fp=(0, 0, 0), deg=25, diffuse="y", ambient="r", specular="b", showsource=False, ): """ Generate a source of light placed at pos, directed to focal point fp. :param fp: focal Point, if this is a ``vtkActor`` use its position. :type fp: vtkActor, list :param deg: aperture angle of the light source :param showsource: if `True`, will show a vtk representation of the source of light as an extra actor .. hint:: |lights.py|_ """ if isinstance(fp, vtk.vtkActor): fp = fp.GetPosition() light = vtk.vtkLight() light.SetLightTypeToSceneLight() light.SetPosition(pos) light.SetPositional(1) light.SetConeAngle(deg) light.SetFocalPoint(fp) light.SetDiffuseColor(colors.getColor(diffuse)) light.SetAmbientColor(colors.getColor(ambient)) light.SetSpecularColor(colors.getColor(specular)) save_int = self.interactive self.show(interactive=0) self.interactive = save_int if showsource: lightActor = vtk.vtkLightActor() lightActor.SetLight(light) self.renderer.AddViewProp(lightActor) self.renderer.AddLight(light) return light
[ "def", "light", "(", "self", ",", "pos", "=", "(", "1", ",", "1", ",", "1", ")", ",", "fp", "=", "(", "0", ",", "0", ",", "0", ")", ",", "deg", "=", "25", ",", "diffuse", "=", "\"y\"", ",", "ambient", "=", "\"r\"", ",", "specular", "=", "...
Generate a source of light placed at pos, directed to focal point fp. :param fp: focal Point, if this is a ``vtkActor`` use its position. :type fp: vtkActor, list :param deg: aperture angle of the light source :param showsource: if `True`, will show a vtk representation of the source of light as an extra actor .. hint:: |lights.py|_
[ "Generate", "a", "source", "of", "light", "placed", "at", "pos", "directed", "to", "focal", "point", "fp", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L698-L738
train
210,401
marcomusy/vtkplotter
vtkplotter/plotter.py
Plotter.removeActor
def removeActor(self, a): """Remove ``vtkActor`` or actor index from current renderer.""" if not self.initializedPlotter: save_int = self.interactive self.show(interactive=0) self.interactive = save_int return if self.renderer: self.renderer.RemoveActor(a) if hasattr(a, 'renderedAt'): ir = self.renderers.index(self.renderer) a.renderedAt.discard(ir) if a in self.actors: i = self.actors.index(a) del self.actors[i]
python
def removeActor(self, a): """Remove ``vtkActor`` or actor index from current renderer.""" if not self.initializedPlotter: save_int = self.interactive self.show(interactive=0) self.interactive = save_int return if self.renderer: self.renderer.RemoveActor(a) if hasattr(a, 'renderedAt'): ir = self.renderers.index(self.renderer) a.renderedAt.discard(ir) if a in self.actors: i = self.actors.index(a) del self.actors[i]
[ "def", "removeActor", "(", "self", ",", "a", ")", ":", "if", "not", "self", ".", "initializedPlotter", ":", "save_int", "=", "self", ".", "interactive", "self", ".", "show", "(", "interactive", "=", "0", ")", "self", ".", "interactive", "=", "save_int", ...
Remove ``vtkActor`` or actor index from current renderer.
[ "Remove", "vtkActor", "or", "actor", "index", "from", "current", "renderer", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L1249-L1263
train
210,402
marcomusy/vtkplotter
vtkplotter/plotter.py
Plotter.clear
def clear(self, actors=()): """Delete specified list of actors, by default delete all.""" if not utils.isSequence(actors): actors = [actors] if len(actors): for a in actors: self.removeActor(a) else: for a in settings.collectable_actors: self.removeActor(a) settings.collectable_actors = [] self.actors = [] for a in self.getActors(): self.renderer.RemoveActor(a) for a in self.getVolumes(): self.renderer.RemoveVolume(a) for s in self.sliders: s.EnabledOff() for b in self.buttons: self.renderer.RemoveActor(b) for w in self.widgets: w.EnabledOff() for c in self.scalarbars: self.renderer.RemoveActor(c)
python
def clear(self, actors=()): """Delete specified list of actors, by default delete all.""" if not utils.isSequence(actors): actors = [actors] if len(actors): for a in actors: self.removeActor(a) else: for a in settings.collectable_actors: self.removeActor(a) settings.collectable_actors = [] self.actors = [] for a in self.getActors(): self.renderer.RemoveActor(a) for a in self.getVolumes(): self.renderer.RemoveVolume(a) for s in self.sliders: s.EnabledOff() for b in self.buttons: self.renderer.RemoveActor(b) for w in self.widgets: w.EnabledOff() for c in self.scalarbars: self.renderer.RemoveActor(c)
[ "def", "clear", "(", "self", ",", "actors", "=", "(", ")", ")", ":", "if", "not", "utils", ".", "isSequence", "(", "actors", ")", ":", "actors", "=", "[", "actors", "]", "if", "len", "(", "actors", ")", ":", "for", "a", "in", "actors", ":", "se...
Delete specified list of actors, by default delete all.
[ "Delete", "specified", "list", "of", "actors", "by", "default", "delete", "all", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/plotter.py#L1265-L1288
train
210,403
marcomusy/vtkplotter
examples/other/spherical_harmonics2.py
morph
def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients.""" clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = (90 - ilat) / 57.3 ph = ilong / 57.3 r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts
python
def morph(clm1, clm2, t, lmax): """Interpolate linearly the two sets of sph harm. coeeficients.""" clm = (1 - t) * clm1 + t * clm2 grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components agrid_reco = grid_reco.to_array() pts = [] for i, longs in enumerate(agrid_reco): ilat = grid_reco.lats()[i] for j, value in enumerate(longs): ilong = grid_reco.lons()[j] th = (90 - ilat) / 57.3 ph = ilong / 57.3 r = value + rbias p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r pts.append(p) return pts
[ "def", "morph", "(", "clm1", ",", "clm2", ",", "t", ",", "lmax", ")", ":", "clm", "=", "(", "1", "-", "t", ")", "*", "clm1", "+", "t", "*", "clm2", "grid_reco", "=", "clm", ".", "expand", "(", "lmax", "=", "lmax", ")", "# cut \"high frequency\" c...
Interpolate linearly the two sets of sph harm. coeeficients.
[ "Interpolate", "linearly", "the", "two", "sets", "of", "sph", "harm", ".", "coeeficients", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/examples/other/spherical_harmonics2.py#L49-L64
train
210,404
marcomusy/vtkplotter
vtkplotter/actors.py
mergeActors
def mergeActors(actors, tol=0): """ Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid| |thinplate_grid.py|_ """ polylns = vtk.vtkAppendPolyData() for a in actors: polylns.AddInputData(a.polydata()) polylns.Update() pd = polylns.GetOutput() return Actor(pd)
python
def mergeActors(actors, tol=0): """ Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid| |thinplate_grid.py|_ """ polylns = vtk.vtkAppendPolyData() for a in actors: polylns.AddInputData(a.polydata()) polylns.Update() pd = polylns.GetOutput() return Actor(pd)
[ "def", "mergeActors", "(", "actors", ",", "tol", "=", "0", ")", ":", "polylns", "=", "vtk", ".", "vtkAppendPolyData", "(", ")", "for", "a", "in", "actors", ":", "polylns", ".", "AddInputData", "(", "a", ".", "polydata", "(", ")", ")", "polylns", ".",...
Build a new actor formed by the fusion of the polydatas of input objects. Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid| |thinplate_grid.py|_
[ "Build", "a", "new", "actor", "formed", "by", "the", "fusion", "of", "the", "polydatas", "of", "input", "objects", ".", "Similar", "to", "Assembly", "but", "in", "this", "case", "the", "input", "objects", "become", "a", "single", "mesh", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L30-L42
train
210,405
marcomusy/vtkplotter
vtkplotter/actors.py
isosurface
def isosurface(image, smoothing=0, threshold=None, connectivity=False): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param float smoothing: gaussian filter to smooth vtkImageData, in units of sigmas :param threshold: value or list of values to draw the isosurface(s) :type threshold: float, list :param bool connectivity: if True only keeps the largest portion of the polydata .. hint:: |isosurfaces| |isosurfaces.py|_ """ if smoothing: smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) smImg.SetInputData(image) smImg.SetStandardDeviations(smoothing, smoothing, smoothing) smImg.Update() image = smImg.GetOutput() scrange = image.GetScalarRange() if scrange[1] > 1e10: print("Warning, high scalar range detected:", scrange) cf = vtk.vtkContourFilter() cf.SetInputData(image) cf.UseScalarTreeOn() cf.ComputeScalarsOn() if utils.isSequence(threshold): cf.SetNumberOfContours(len(threshold)) for i, t in enumerate(threshold): cf.SetValue(i, t) cf.Update() else: if not threshold: threshold = (2 * scrange[0] + scrange[1]) / 3.0 cf.SetValue(0, threshold) cf.Update() clp = vtk.vtkCleanPolyData() clp.SetInputConnection(cf.GetOutputPort()) clp.Update() poly = clp.GetOutput() if connectivity: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.SetInputData(poly) conn.Update() poly = conn.GetOutput() a = Actor(poly, c=None).phong() a.mapper.SetScalarRange(scrange[0], scrange[1]) return a
python
def isosurface(image, smoothing=0, threshold=None, connectivity=False): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param float smoothing: gaussian filter to smooth vtkImageData, in units of sigmas :param threshold: value or list of values to draw the isosurface(s) :type threshold: float, list :param bool connectivity: if True only keeps the largest portion of the polydata .. hint:: |isosurfaces| |isosurfaces.py|_ """ if smoothing: smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) smImg.SetInputData(image) smImg.SetStandardDeviations(smoothing, smoothing, smoothing) smImg.Update() image = smImg.GetOutput() scrange = image.GetScalarRange() if scrange[1] > 1e10: print("Warning, high scalar range detected:", scrange) cf = vtk.vtkContourFilter() cf.SetInputData(image) cf.UseScalarTreeOn() cf.ComputeScalarsOn() if utils.isSequence(threshold): cf.SetNumberOfContours(len(threshold)) for i, t in enumerate(threshold): cf.SetValue(i, t) cf.Update() else: if not threshold: threshold = (2 * scrange[0] + scrange[1]) / 3.0 cf.SetValue(0, threshold) cf.Update() clp = vtk.vtkCleanPolyData() clp.SetInputConnection(cf.GetOutputPort()) clp.Update() poly = clp.GetOutput() if connectivity: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.SetInputData(poly) conn.Update() poly = conn.GetOutput() a = Actor(poly, c=None).phong() a.mapper.SetScalarRange(scrange[0], scrange[1]) return a
[ "def", "isosurface", "(", "image", ",", "smoothing", "=", "0", ",", "threshold", "=", "None", ",", "connectivity", "=", "False", ")", ":", "if", "smoothing", ":", "smImg", "=", "vtk", ".", "vtkImageGaussianSmooth", "(", ")", "smImg", ".", "SetDimensionalit...
Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. :param float smoothing: gaussian filter to smooth vtkImageData, in units of sigmas :param threshold: value or list of values to draw the isosurface(s) :type threshold: float, list :param bool connectivity: if True only keeps the largest portion of the polydata .. hint:: |isosurfaces| |isosurfaces.py|_
[ "Return", "a", "vtkActor", "isosurface", "extracted", "from", "a", "vtkImageData", "object", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L62-L114
train
210,406
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.show
def show( self, at=None, shape=(1, 1), N=None, pos=(0, 0), size="auto", screensize="auto", title="", bg="blackboard", bg2=None, axes=4, infinity=False, verbose=True, interactive=None, offscreen=False, resetcam=True, zoom=None, viewup="", azimuth=0, elevation=0, roll=0, interactorStyle=0, newPlotter=False, depthpeeling=False, q=False, ): """ Create on the fly an instance of class ``Plotter`` or use the last existing one to show one single object. Allowed input objects are: ``Actor`` or ``Volume``. This is meant as a shortcut. If more than one object needs to be visualised please use the syntax `show([actor1, actor2,...], options)`. :param bool newPlotter: if set to `True`, a call to ``show`` will instantiate a new ``Plotter`` object (a new window) instead of reusing the first created. See e.g.: |readVolumeAsIsoSurface.py|_ :return: the current ``Plotter`` class instance. .. note:: E.g.: >>> from vtkplotter import * >>> s = Sphere() >>> s.show(at=1, N=2) >>> c = Cube() >>> c.show(at=0, interactive=True) """ from vtkplotter.plotter import show return show( self, at=at, shape=shape, N=N, pos=pos, size=size, screensize=screensize, title=title, bg=bg, bg2=bg2, axes=axes, infinity=infinity, verbose=verbose, interactive=interactive, offscreen=offscreen, resetcam=resetcam, zoom=zoom, viewup=viewup, azimuth=azimuth, elevation=elevation, roll=roll, interactorStyle=interactorStyle, newPlotter=newPlotter, depthpeeling=depthpeeling, q=q, )
python
def show( self, at=None, shape=(1, 1), N=None, pos=(0, 0), size="auto", screensize="auto", title="", bg="blackboard", bg2=None, axes=4, infinity=False, verbose=True, interactive=None, offscreen=False, resetcam=True, zoom=None, viewup="", azimuth=0, elevation=0, roll=0, interactorStyle=0, newPlotter=False, depthpeeling=False, q=False, ): """ Create on the fly an instance of class ``Plotter`` or use the last existing one to show one single object. Allowed input objects are: ``Actor`` or ``Volume``. This is meant as a shortcut. If more than one object needs to be visualised please use the syntax `show([actor1, actor2,...], options)`. :param bool newPlotter: if set to `True`, a call to ``show`` will instantiate a new ``Plotter`` object (a new window) instead of reusing the first created. See e.g.: |readVolumeAsIsoSurface.py|_ :return: the current ``Plotter`` class instance. .. note:: E.g.: >>> from vtkplotter import * >>> s = Sphere() >>> s.show(at=1, N=2) >>> c = Cube() >>> c.show(at=0, interactive=True) """ from vtkplotter.plotter import show return show( self, at=at, shape=shape, N=N, pos=pos, size=size, screensize=screensize, title=title, bg=bg, bg2=bg2, axes=axes, infinity=infinity, verbose=verbose, interactive=interactive, offscreen=offscreen, resetcam=resetcam, zoom=zoom, viewup=viewup, azimuth=azimuth, elevation=elevation, roll=roll, interactorStyle=interactorStyle, newPlotter=newPlotter, depthpeeling=depthpeeling, q=q, )
[ "def", "show", "(", "self", ",", "at", "=", "None", ",", "shape", "=", "(", "1", ",", "1", ")", ",", "N", "=", "None", ",", "pos", "=", "(", "0", ",", "0", ")", ",", "size", "=", "\"auto\"", ",", "screensize", "=", "\"auto\"", ",", "title", ...
Create on the fly an instance of class ``Plotter`` or use the last existing one to show one single object. Allowed input objects are: ``Actor`` or ``Volume``. This is meant as a shortcut. If more than one object needs to be visualised please use the syntax `show([actor1, actor2,...], options)`. :param bool newPlotter: if set to `True`, a call to ``show`` will instantiate a new ``Plotter`` object (a new window) instead of reusing the first created. See e.g.: |readVolumeAsIsoSurface.py|_ :return: the current ``Plotter`` class instance. .. note:: E.g.: >>> from vtkplotter import * >>> s = Sphere() >>> s.show(at=1, N=2) >>> c = Cube() >>> c.show(at=0, interactive=True)
[ "Create", "on", "the", "fly", "an", "instance", "of", "class", "Plotter", "or", "use", "the", "last", "existing", "one", "to", "show", "one", "single", "object", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L138-L215
train
210,407
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.addPos
def addPos(self, dp_x=None, dy=None, dz=None): """Add vector to current actor position.""" p = np.array(self.GetPosition()) if dz is None: # assume dp_x is of the form (x,y,z) self.SetPosition(p + dp_x) else: self.SetPosition(p + [dp_x, dy, dz]) if self.trail: self.updateTrail() return self
python
def addPos(self, dp_x=None, dy=None, dz=None): """Add vector to current actor position.""" p = np.array(self.GetPosition()) if dz is None: # assume dp_x is of the form (x,y,z) self.SetPosition(p + dp_x) else: self.SetPosition(p + [dp_x, dy, dz]) if self.trail: self.updateTrail() return self
[ "def", "addPos", "(", "self", ",", "dp_x", "=", "None", ",", "dy", "=", "None", ",", "dz", "=", "None", ")", ":", "p", "=", "np", ".", "array", "(", "self", ".", "GetPosition", "(", ")", ")", "if", "dz", "is", "None", ":", "# assume dp_x is of th...
Add vector to current actor position.
[ "Add", "vector", "to", "current", "actor", "position", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L245-L254
train
210,408
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.rotate
def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): """Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`.""" if rad: anglerad = angle else: anglerad = angle / 57.29578 axis = utils.versor(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd = a * a, b * b, c * c, d * d bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d R = np.array( [ [aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc], ] ) rv = np.dot(R, self.GetPosition() - np.array(axis_point)) + axis_point if rad: angle *= 57.29578 # this vtk method only rotates in the origin of the actor: self.RotateWXYZ(angle, axis[0], axis[1], axis[2]) self.SetPosition(rv) if self.trail: self.updateTrail() return self
python
def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): """Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`.""" if rad: anglerad = angle else: anglerad = angle / 57.29578 axis = utils.versor(axis) a = np.cos(anglerad / 2) b, c, d = -axis * np.sin(anglerad / 2) aa, bb, cc, dd = a * a, b * b, c * c, d * d bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d R = np.array( [ [aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc], ] ) rv = np.dot(R, self.GetPosition() - np.array(axis_point)) + axis_point if rad: angle *= 57.29578 # this vtk method only rotates in the origin of the actor: self.RotateWXYZ(angle, axis[0], axis[1], axis[2]) self.SetPosition(rv) if self.trail: self.updateTrail() return self
[ "def", "rotate", "(", "self", ",", "angle", ",", "axis", "=", "(", "1", ",", "0", ",", "0", ")", ",", "axis_point", "=", "(", "0", ",", "0", ",", "0", ")", ",", "rad", "=", "False", ")", ":", "if", "rad", ":", "anglerad", "=", "angle", "els...
Rotate ``Actor`` around an arbitrary `axis` passing through `axis_point`.
[ "Rotate", "Actor", "around", "an", "arbitrary", "axis", "passing", "through", "axis_point", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L286-L313
train
210,409
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.rotateX
def rotateX(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around x-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateX(angle) if self.trail: self.updateTrail() return self
python
def rotateX(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around x-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateX(angle) if self.trail: self.updateTrail() return self
[ "def", "rotateX", "(", "self", ",", "angle", ",", "axis_point", "=", "(", "0", ",", "0", ",", "0", ")", ",", "rad", "=", "False", ")", ":", "if", "rad", ":", "angle", "*=", "57.29578", "self", ".", "RotateX", "(", "angle", ")", "if", "self", "....
Rotate around x-axis. If angle is in radians set ``rad=True``.
[ "Rotate", "around", "x", "-", "axis", ".", "If", "angle", "is", "in", "radians", "set", "rad", "=", "True", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L315-L322
train
210,410
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.rotateY
def rotateY(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around y-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateY(angle) if self.trail: self.updateTrail() return self
python
def rotateY(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around y-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateY(angle) if self.trail: self.updateTrail() return self
[ "def", "rotateY", "(", "self", ",", "angle", ",", "axis_point", "=", "(", "0", ",", "0", ",", "0", ")", ",", "rad", "=", "False", ")", ":", "if", "rad", ":", "angle", "*=", "57.29578", "self", ".", "RotateY", "(", "angle", ")", "if", "self", "....
Rotate around y-axis. If angle is in radians set ``rad=True``.
[ "Rotate", "around", "y", "-", "axis", ".", "If", "angle", "is", "in", "radians", "set", "rad", "=", "True", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L324-L331
train
210,411
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.rotateZ
def rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around z-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateZ(angle) if self.trail: self.updateTrail() return self
python
def rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): """Rotate around z-axis. If angle is in radians set ``rad=True``.""" if rad: angle *= 57.29578 self.RotateZ(angle) if self.trail: self.updateTrail() return self
[ "def", "rotateZ", "(", "self", ",", "angle", ",", "axis_point", "=", "(", "0", ",", "0", ",", "0", ")", ",", "rad", "=", "False", ")", ":", "if", "rad", ":", "angle", "*=", "57.29578", "self", ".", "RotateZ", "(", "angle", ")", "if", "self", "....
Rotate around z-axis. If angle is in radians set ``rad=True``.
[ "Rotate", "around", "z", "-", "axis", ".", "If", "angle", "is", "in", "radians", "set", "rad", "=", "True", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L333-L340
train
210,412
marcomusy/vtkplotter
vtkplotter/actors.py
Prop.addTrail
def addTrail(self, offset=None, maxlength=None, n=25, c=None, alpha=None, lw=1): """Add a trailing line to actor. :param offset: set an offset vector from the object center. :param maxlength: length of trailing line in absolute units :param n: number of segments to control precision :param lw: line width of the trail .. hint:: |trail| |trail.py|_ """ if maxlength is None: maxlength = self.diagonalSize() * 20 if maxlength == 0: maxlength = 1 if self.trail is None: pos = self.GetPosition() self.trailPoints = [None] * n self.trailSegmentSize = maxlength / n self.trailOffset = offset ppoints = vtk.vtkPoints() # Generate the polyline poly = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk([pos] * n)) poly.SetPoints(ppoints) lines = vtk.vtkCellArray() lines.InsertNextCell(n) for i in range(n): lines.InsertCellPoint(i) poly.SetPoints(ppoints) poly.SetLines(lines) mapper = vtk.vtkPolyDataMapper() if c is None: if hasattr(self, "GetProperty"): col = self.GetProperty().GetColor() else: col = (0.1, 0.1, 0.1) else: col = colors.getColor(c) if alpha is None: alpha = 1 if hasattr(self, "GetProperty"): alpha = self.GetProperty().GetOpacity() mapper.SetInputData(poly) tline = Actor() tline.SetMapper(mapper) tline.GetProperty().SetColor(col) tline.GetProperty().SetOpacity(alpha) tline.GetProperty().SetLineWidth(lw) self.trail = tline # holds the vtkActor return self
python
def addTrail(self, offset=None, maxlength=None, n=25, c=None, alpha=None, lw=1): """Add a trailing line to actor. :param offset: set an offset vector from the object center. :param maxlength: length of trailing line in absolute units :param n: number of segments to control precision :param lw: line width of the trail .. hint:: |trail| |trail.py|_ """ if maxlength is None: maxlength = self.diagonalSize() * 20 if maxlength == 0: maxlength = 1 if self.trail is None: pos = self.GetPosition() self.trailPoints = [None] * n self.trailSegmentSize = maxlength / n self.trailOffset = offset ppoints = vtk.vtkPoints() # Generate the polyline poly = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk([pos] * n)) poly.SetPoints(ppoints) lines = vtk.vtkCellArray() lines.InsertNextCell(n) for i in range(n): lines.InsertCellPoint(i) poly.SetPoints(ppoints) poly.SetLines(lines) mapper = vtk.vtkPolyDataMapper() if c is None: if hasattr(self, "GetProperty"): col = self.GetProperty().GetColor() else: col = (0.1, 0.1, 0.1) else: col = colors.getColor(c) if alpha is None: alpha = 1 if hasattr(self, "GetProperty"): alpha = self.GetProperty().GetOpacity() mapper.SetInputData(poly) tline = Actor() tline.SetMapper(mapper) tline.GetProperty().SetColor(col) tline.GetProperty().SetOpacity(alpha) tline.GetProperty().SetLineWidth(lw) self.trail = tline # holds the vtkActor return self
[ "def", "addTrail", "(", "self", ",", "offset", "=", "None", ",", "maxlength", "=", "None", ",", "n", "=", "25", ",", "c", "=", "None", ",", "alpha", "=", "None", ",", "lw", "=", "1", ")", ":", "if", "maxlength", "is", "None", ":", "maxlength", ...
Add a trailing line to actor. :param offset: set an offset vector from the object center. :param maxlength: length of trailing line in absolute units :param n: number of segments to control precision :param lw: line width of the trail .. hint:: |trail| |trail.py|_
[ "Add", "a", "trailing", "line", "to", "actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L391-L444
train
210,413
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.updateMesh
def updateMesh(self, polydata): """ Overwrite the polygonal mesh of the actor with a new one. """ self.poly = polydata self.mapper.SetInputData(polydata) self.mapper.Modified() return self
python
def updateMesh(self, polydata): """ Overwrite the polygonal mesh of the actor with a new one. """ self.poly = polydata self.mapper.SetInputData(polydata) self.mapper.Modified() return self
[ "def", "updateMesh", "(", "self", ",", "polydata", ")", ":", "self", ".", "poly", "=", "polydata", "self", ".", "mapper", ".", "SetInputData", "(", "polydata", ")", "self", ".", "mapper", ".", "Modified", "(", ")", "return", "self" ]
Overwrite the polygonal mesh of the actor with a new one.
[ "Overwrite", "the", "polygonal", "mesh", "of", "the", "actor", "with", "a", "new", "one", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L620-L627
train
210,414
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addScalarBar
def addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None): """ Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_ """ # book it, it will be created by Plotter.show() later self.scalarbar = [c, title, horizontal, vmin, vmax] return self
python
def addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None): """ Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_ """ # book it, it will be created by Plotter.show() later self.scalarbar = [c, title, horizontal, vmin, vmax] return self
[ "def", "addScalarBar", "(", "self", ",", "c", "=", "None", ",", "title", "=", "\"\"", ",", "horizontal", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# book it, it will be created by Plotter.show() later", "self", ".", "scalar...
Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_
[ "Add", "a", "2D", "scalar", "bar", "to", "actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L629-L637
train
210,415
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addScalarBar3D
def addScalarBar3D( self, pos=(0, 0, 0), normal=(0, 0, 1), sx=0.1, sy=2, nlabels=9, ncols=256, cmap=None, c="k", alpha=1, ): """ Draw a 3D scalar bar to actor. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """ # book it, it will be created by Plotter.show() later self.scalarbar = [pos, normal, sx, sy, nlabels, ncols, cmap, c, alpha] return self
python
def addScalarBar3D( self, pos=(0, 0, 0), normal=(0, 0, 1), sx=0.1, sy=2, nlabels=9, ncols=256, cmap=None, c="k", alpha=1, ): """ Draw a 3D scalar bar to actor. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """ # book it, it will be created by Plotter.show() later self.scalarbar = [pos, normal, sx, sy, nlabels, ncols, cmap, c, alpha] return self
[ "def", "addScalarBar3D", "(", "self", ",", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "sx", "=", "0.1", ",", "sy", "=", "2", ",", "nlabels", "=", "9", ",", "ncols", "=", "256...
Draw a 3D scalar bar to actor. .. hint:: |mesh_coloring| |mesh_coloring.py|_
[ "Draw", "a", "3D", "scalar", "bar", "to", "actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L639-L658
train
210,416
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.texture
def texture(self, name, scale=1, falsecolors=False, mapTo=1): """Assign a texture to actor from image file or predefined texture name.""" import os if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() tmapper.SetInputData(self.polydata(False)) if mapTo == 1: tmapper.PreventSeamOn() xform = vtk.vtkTransformTextureCoords() xform.SetInputConnection(tmapper.GetOutputPort()) xform.SetScale(scale, scale, scale) if mapTo == 1: xform.FlipSOn() xform.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(xform.GetOutputPort()) mapper.ScalarVisibilityOff() fn = settings.textures_path + name + ".jpg" if os.path.exists(name): fn = name elif not os.path.exists(fn): colors.printc("~sad Texture", name, "not found in", settings.textures_path, c="r") colors.printc("~target Available textures:", c="m", end=" ") for ff in os.listdir(settings.textures_path): colors.printc(ff.split(".")[0], end=" ", c="m") print() return jpgReader = vtk.vtkJPEGReader() jpgReader.SetFileName(fn) atext = vtk.vtkTexture() atext.RepeatOn() atext.EdgeClampOff() atext.InterpolateOn() if falsecolors: atext.MapColorScalarsThroughLookupTableOn() atext.SetInputConnection(jpgReader.GetOutputPort()) self.GetProperty().SetColor(1, 1, 1) self.SetMapper(mapper) self.SetTexture(atext) self.Modified() return self
python
def texture(self, name, scale=1, falsecolors=False, mapTo=1): """Assign a texture to actor from image file or predefined texture name.""" import os if mapTo == 1: tmapper = vtk.vtkTextureMapToCylinder() elif mapTo == 2: tmapper = vtk.vtkTextureMapToSphere() elif mapTo == 3: tmapper = vtk.vtkTextureMapToPlane() tmapper.SetInputData(self.polydata(False)) if mapTo == 1: tmapper.PreventSeamOn() xform = vtk.vtkTransformTextureCoords() xform.SetInputConnection(tmapper.GetOutputPort()) xform.SetScale(scale, scale, scale) if mapTo == 1: xform.FlipSOn() xform.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(xform.GetOutputPort()) mapper.ScalarVisibilityOff() fn = settings.textures_path + name + ".jpg" if os.path.exists(name): fn = name elif not os.path.exists(fn): colors.printc("~sad Texture", name, "not found in", settings.textures_path, c="r") colors.printc("~target Available textures:", c="m", end=" ") for ff in os.listdir(settings.textures_path): colors.printc(ff.split(".")[0], end=" ", c="m") print() return jpgReader = vtk.vtkJPEGReader() jpgReader.SetFileName(fn) atext = vtk.vtkTexture() atext.RepeatOn() atext.EdgeClampOff() atext.InterpolateOn() if falsecolors: atext.MapColorScalarsThroughLookupTableOn() atext.SetInputConnection(jpgReader.GetOutputPort()) self.GetProperty().SetColor(1, 1, 1) self.SetMapper(mapper) self.SetTexture(atext) self.Modified() return self
[ "def", "texture", "(", "self", ",", "name", ",", "scale", "=", "1", ",", "falsecolors", "=", "False", ",", "mapTo", "=", "1", ")", ":", "import", "os", "if", "mapTo", "==", "1", ":", "tmapper", "=", "vtk", ".", "vtkTextureMapToCylinder", "(", ")", ...
Assign a texture to actor from image file or predefined texture name.
[ "Assign", "a", "texture", "to", "actor", "from", "image", "file", "or", "predefined", "texture", "name", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L661-L711
train
210,417
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.computeNormals
def computeNormals(self): """Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices. """ poly = self.polydata(False) pnormals = poly.GetPointData().GetNormals() cnormals = poly.GetCellData().GetNormals() if pnormals and cnormals: return self pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(poly) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
python
def computeNormals(self): """Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices. """ poly = self.polydata(False) pnormals = poly.GetPointData().GetNormals() cnormals = poly.GetCellData().GetNormals() if pnormals and cnormals: return self pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(poly) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
[ "def", "computeNormals", "(", "self", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "pnormals", "=", "poly", ".", "GetPointData", "(", ")", ".", "GetNormals", "(", ")", "cnormals", "=", "poly", ".", "GetCellData", "(", ")", ".", ...
Compute cell and vertex normals for the actor's mesh. .. warning:: Mesh gets modified, can have a different nr. of vertices.
[ "Compute", "cell", "and", "vertex", "normals", "for", "the", "actor", "s", "mesh", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L775-L793
train
210,418
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.clean
def clean(self, tol=None): """ Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large. If ``tol=None`` only removes coincident points. :param tol: defines how far should be the points from each other in terms of fraction of the bounding box length. .. hint:: |moving_least_squares1D| |moving_least_squares1D.py|_ |recosurface| |recosurface.py|_ """ poly = self.polydata(False) cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.PointMergingOn() cleanPolyData.ConvertLinesToPointsOn() cleanPolyData.ConvertPolysToLinesOn() cleanPolyData.SetInputData(poly) if tol: cleanPolyData.SetTolerance(tol) cleanPolyData.Update() return self.updateMesh(cleanPolyData.GetOutput())
python
def clean(self, tol=None): """ Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large. If ``tol=None`` only removes coincident points. :param tol: defines how far should be the points from each other in terms of fraction of the bounding box length. .. hint:: |moving_least_squares1D| |moving_least_squares1D.py|_ |recosurface| |recosurface.py|_ """ poly = self.polydata(False) cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.PointMergingOn() cleanPolyData.ConvertLinesToPointsOn() cleanPolyData.ConvertPolysToLinesOn() cleanPolyData.SetInputData(poly) if tol: cleanPolyData.SetTolerance(tol) cleanPolyData.Update() return self.updateMesh(cleanPolyData.GetOutput())
[ "def", "clean", "(", "self", ",", "tol", "=", "None", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "cleanPolyData", "=", "vtk", ".", "vtkCleanPolyData", "(", ")", "cleanPolyData", ".", "PointMergingOn", "(", ")", "cleanPolyData", "....
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large. If ``tol=None`` only removes coincident points. :param tol: defines how far should be the points from each other in terms of fraction of the bounding box length. .. hint:: |moving_least_squares1D| |moving_least_squares1D.py|_ |recosurface| |recosurface.py|_
[ "Clean", "actor", "s", "polydata", ".", "Can", "also", "be", "used", "to", "decimate", "a", "mesh", "if", "tol", "is", "large", ".", "If", "tol", "=", "None", "only", "removes", "coincident", "points", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L939-L960
train
210,419
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.averageSize
def averageSize(self): """Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass.""" cm = self.centerOfMass() coords = self.coordinates(copy=False) if not len(coords): return 0 s, c = 0.0, 0.0 n = len(coords) step = int(n / 10000.0) + 1 for i in np.arange(0, n, step): s += utils.mag(coords[i] - cm) c += 1 return s / c
python
def averageSize(self): """Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass.""" cm = self.centerOfMass() coords = self.coordinates(copy=False) if not len(coords): return 0 s, c = 0.0, 0.0 n = len(coords) step = int(n / 10000.0) + 1 for i in np.arange(0, n, step): s += utils.mag(coords[i] - cm) c += 1 return s / c
[ "def", "averageSize", "(", "self", ")", ":", "cm", "=", "self", ".", "centerOfMass", "(", ")", "coords", "=", "self", ".", "coordinates", "(", "copy", "=", "False", ")", "if", "not", "len", "(", "coords", ")", ":", "return", "0", "s", ",", "c", "...
Calculate the average size of a mesh. This is the mean of the vertex distances from the center of mass.
[ "Calculate", "the", "average", "size", "of", "a", "mesh", ".", "This", "is", "the", "mean", "of", "the", "vertex", "distances", "from", "the", "center", "of", "mass", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L977-L990
train
210,420
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.diagonalSize
def diagonalSize(self): """Get the length of the diagonal of actor bounding box.""" b = self.polydata().GetBounds() return np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
python
def diagonalSize(self): """Get the length of the diagonal of actor bounding box.""" b = self.polydata().GetBounds() return np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
[ "def", "diagonalSize", "(", "self", ")", ":", "b", "=", "self", ".", "polydata", "(", ")", ".", "GetBounds", "(", ")", "return", "np", ".", "sqrt", "(", "(", "b", "[", "1", "]", "-", "b", "[", "0", "]", ")", "**", "2", "+", "(", "b", "[", ...
Get the length of the diagonal of actor bounding box.
[ "Get", "the", "length", "of", "the", "diagonal", "of", "actor", "bounding", "box", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L992-L995
train
210,421
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.maxBoundSize
def maxBoundSize(self): """Get the maximum dimension in x, y or z of the actor bounding box.""" b = self.polydata(True).GetBounds() return max(abs(b[1] - b[0]), abs(b[3] - b[2]), abs(b[5] - b[4]))
python
def maxBoundSize(self): """Get the maximum dimension in x, y or z of the actor bounding box.""" b = self.polydata(True).GetBounds() return max(abs(b[1] - b[0]), abs(b[3] - b[2]), abs(b[5] - b[4]))
[ "def", "maxBoundSize", "(", "self", ")", ":", "b", "=", "self", ".", "polydata", "(", "True", ")", ".", "GetBounds", "(", ")", "return", "max", "(", "abs", "(", "b", "[", "1", "]", "-", "b", "[", "0", "]", ")", ",", "abs", "(", "b", "[", "3...
Get the maximum dimension in x, y or z of the actor bounding box.
[ "Get", "the", "maximum", "dimension", "in", "x", "y", "or", "z", "of", "the", "actor", "bounding", "box", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L997-L1000
train
210,422
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.centerOfMass
def centerOfMass(self): """Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_ """ cmf = vtk.vtkCenterOfMass() cmf.SetInputData(self.polydata(True)) cmf.Update() c = cmf.GetCenter() return np.array(c)
python
def centerOfMass(self): """Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_ """ cmf = vtk.vtkCenterOfMass() cmf.SetInputData(self.polydata(True)) cmf.Update() c = cmf.GetCenter() return np.array(c)
[ "def", "centerOfMass", "(", "self", ")", ":", "cmf", "=", "vtk", ".", "vtkCenterOfMass", "(", ")", "cmf", ".", "SetInputData", "(", "self", ".", "polydata", "(", "True", ")", ")", "cmf", ".", "Update", "(", ")", "c", "=", "cmf", ".", "GetCenter", "...
Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_
[ "Get", "the", "center", "of", "mass", "of", "actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1002-L1011
train
210,423
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.closestPoint
def closestPoint(self, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a mesh given from the input point `pt`. :param int N: if greater than 1, return a list of N ordered closest points. :param float radius: if given, get all points within that radius. :param bool returnIds: return points IDs instead of point coordinates. .. hint:: |fitplanes.py|_ |align1| |align1.py|_ |quadratic_morphing| |quadratic_morphing.py|_ .. note:: The appropriate kd-tree search locator is built on the fly and cached for speed. """ poly = self.polydata(True) if N > 1 or radius: plocexists = self.point_locator if not plocexists or (plocexists and self.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.BuildLocator() self.point_locator = point_locator vtklist = vtk.vtkIdList() if N > 1: self.point_locator.FindClosestNPoints(N, pt, vtklist) else: self.point_locator.FindPointsWithinRadius(radius, pt, vtklist) if returnIds: return [int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds())] else: trgp = [] for i in range(vtklist.GetNumberOfIds()): trgp_ = [0, 0, 0] vi = vtklist.GetId(i) poly.GetPoints().GetPoint(vi, trgp_) trgp.append(trgp_) return np.array(trgp) clocexists = self.cell_locator if not clocexists or (clocexists and self.cell_locator is None): cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(poly) cell_locator.BuildLocator() self.cell_locator = cell_locator trgp = [0, 0, 0] cid = vtk.mutable(0) dist2 = vtk.mutable(0) subid = vtk.mutable(0) self.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2) if returnIds: return int(cid) else: return np.array(trgp)
python
def closestPoint(self, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a mesh given from the input point `pt`. :param int N: if greater than 1, return a list of N ordered closest points. :param float radius: if given, get all points within that radius. :param bool returnIds: return points IDs instead of point coordinates. .. hint:: |fitplanes.py|_ |align1| |align1.py|_ |quadratic_morphing| |quadratic_morphing.py|_ .. note:: The appropriate kd-tree search locator is built on the fly and cached for speed. """ poly = self.polydata(True) if N > 1 or radius: plocexists = self.point_locator if not plocexists or (plocexists and self.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.BuildLocator() self.point_locator = point_locator vtklist = vtk.vtkIdList() if N > 1: self.point_locator.FindClosestNPoints(N, pt, vtklist) else: self.point_locator.FindPointsWithinRadius(radius, pt, vtklist) if returnIds: return [int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds())] else: trgp = [] for i in range(vtklist.GetNumberOfIds()): trgp_ = [0, 0, 0] vi = vtklist.GetId(i) poly.GetPoints().GetPoint(vi, trgp_) trgp.append(trgp_) return np.array(trgp) clocexists = self.cell_locator if not clocexists or (clocexists and self.cell_locator is None): cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(poly) cell_locator.BuildLocator() self.cell_locator = cell_locator trgp = [0, 0, 0] cid = vtk.mutable(0) dist2 = vtk.mutable(0) subid = vtk.mutable(0) self.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2) if returnIds: return int(cid) else: return np.array(trgp)
[ "def", "closestPoint", "(", "self", ",", "pt", ",", "N", "=", "1", ",", "radius", "=", "None", ",", "returnIds", "=", "False", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "if", "N", ">", "1", "or", "radius", ":", "plocexists...
Find the closest point on a mesh given from the input point `pt`. :param int N: if greater than 1, return a list of N ordered closest points. :param float radius: if given, get all points within that radius. :param bool returnIds: return points IDs instead of point coordinates. .. hint:: |fitplanes.py|_ |align1| |align1.py|_ |quadratic_morphing| |quadratic_morphing.py|_ .. note:: The appropriate kd-tree search locator is built on the fly and cached for speed.
[ "Find", "the", "closest", "point", "on", "a", "mesh", "given", "from", "the", "input", "point", "pt", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1050-L1107
train
210,424
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.transformMesh
def transformMesh(self, transformation): """ Apply this transformation to the polygonal `mesh`, not to the actor's transformation, which is reset. :param transformation: ``vtkTransform`` or ``vtkMatrix4x4`` object. """ if isinstance(transformation, vtk.vtkMatrix4x4): tr = vtk.vtkTransform() tr.SetMatrix(transformation) transformation = tr tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) tf.SetInputData(self.polydata()) tf.Update() self.PokeMatrix(vtk.vtkMatrix4x4()) # identity return self.updateMesh(tf.GetOutput())
python
def transformMesh(self, transformation): """ Apply this transformation to the polygonal `mesh`, not to the actor's transformation, which is reset. :param transformation: ``vtkTransform`` or ``vtkMatrix4x4`` object. """ if isinstance(transformation, vtk.vtkMatrix4x4): tr = vtk.vtkTransform() tr.SetMatrix(transformation) transformation = tr tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transformation) tf.SetInputData(self.polydata()) tf.Update() self.PokeMatrix(vtk.vtkMatrix4x4()) # identity return self.updateMesh(tf.GetOutput())
[ "def", "transformMesh", "(", "self", ",", "transformation", ")", ":", "if", "isinstance", "(", "transformation", ",", "vtk", ".", "vtkMatrix4x4", ")", ":", "tr", "=", "vtk", ".", "vtkTransform", "(", ")", "tr", ".", "SetMatrix", "(", "transformation", ")",...
Apply this transformation to the polygonal `mesh`, not to the actor's transformation, which is reset. :param transformation: ``vtkTransform`` or ``vtkMatrix4x4`` object.
[ "Apply", "this", "transformation", "to", "the", "polygonal", "mesh", "not", "to", "the", "actor", "s", "transformation", "which", "is", "reset", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1159-L1177
train
210,425
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.normalize
def normalize(self): """ Shift actor's center of mass at origin and scale its average size to unit. """ cm = self.centerOfMass() coords = self.coordinates() if not len(coords): return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) scale = 1 / np.sqrt(np.sum(xyz2) / len(pts)) t = vtk.vtkTransform() t.Scale(scale, scale, scale) t.Translate(-cm) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(self.poly) tf.SetTransform(t) tf.Update() return self.updateMesh(tf.GetOutput())
python
def normalize(self): """ Shift actor's center of mass at origin and scale its average size to unit. """ cm = self.centerOfMass() coords = self.coordinates() if not len(coords): return pts = coords - cm xyz2 = np.sum(pts * pts, axis=0) scale = 1 / np.sqrt(np.sum(xyz2) / len(pts)) t = vtk.vtkTransform() t.Scale(scale, scale, scale) t.Translate(-cm) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(self.poly) tf.SetTransform(t) tf.Update() return self.updateMesh(tf.GetOutput())
[ "def", "normalize", "(", "self", ")", ":", "cm", "=", "self", ".", "centerOfMass", "(", ")", "coords", "=", "self", ".", "coordinates", "(", ")", "if", "not", "len", "(", "coords", ")", ":", "return", "pts", "=", "coords", "-", "cm", "xyz2", "=", ...
Shift actor's center of mass at origin and scale its average size to unit.
[ "Shift", "actor", "s", "center", "of", "mass", "at", "origin", "and", "scale", "its", "average", "size", "to", "unit", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1180-L1198
train
210,426
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.mirror
def mirror(self, axis="x"): """ Mirror the actor polydata along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. .. hint:: |mirror| |mirror.py|_ """ poly = self.polydata(transformed=True) polyCopy = vtk.vtkPolyData() polyCopy.DeepCopy(poly) sx, sy, sz = 1, 1, 1 dx, dy, dz = self.GetPosition() if axis.lower() == "x": sx = -1 elif axis.lower() == "y": sy = -1 elif axis.lower() == "z": sz = -1 elif axis.lower() == "n": pass else: colors.printc("~times Error in mirror(): mirror must be set to x, y, z or n.", c=1) raise RuntimeError() if axis != "n": for j in range(polyCopy.GetNumberOfPoints()): p = [0, 0, 0] polyCopy.GetPoint(j, p) polyCopy.GetPoints().SetPoint( j, p[0] * sx - dx * (sx - 1), p[1] * sy - dy * (sy - 1), p[2] * sz - dz * (sz - 1), ) rs = vtk.vtkReverseSense() rs.SetInputData(polyCopy) rs.ReverseNormalsOn() rs.Update() polyCopy = rs.GetOutput() pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(polyCopy) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
python
def mirror(self, axis="x"): """ Mirror the actor polydata along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. .. hint:: |mirror| |mirror.py|_ """ poly = self.polydata(transformed=True) polyCopy = vtk.vtkPolyData() polyCopy.DeepCopy(poly) sx, sy, sz = 1, 1, 1 dx, dy, dz = self.GetPosition() if axis.lower() == "x": sx = -1 elif axis.lower() == "y": sy = -1 elif axis.lower() == "z": sz = -1 elif axis.lower() == "n": pass else: colors.printc("~times Error in mirror(): mirror must be set to x, y, z or n.", c=1) raise RuntimeError() if axis != "n": for j in range(polyCopy.GetNumberOfPoints()): p = [0, 0, 0] polyCopy.GetPoint(j, p) polyCopy.GetPoints().SetPoint( j, p[0] * sx - dx * (sx - 1), p[1] * sy - dy * (sy - 1), p[2] * sz - dz * (sz - 1), ) rs = vtk.vtkReverseSense() rs.SetInputData(polyCopy) rs.ReverseNormalsOn() rs.Update() polyCopy = rs.GetOutput() pdnorm = vtk.vtkPolyDataNormals() pdnorm.SetInputData(polyCopy) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() return self.updateMesh(pdnorm.GetOutput())
[ "def", "mirror", "(", "self", ",", "axis", "=", "\"x\"", ")", ":", "poly", "=", "self", ".", "polydata", "(", "transformed", "=", "True", ")", "polyCopy", "=", "vtk", ".", "vtkPolyData", "(", ")", "polyCopy", ".", "DeepCopy", "(", "poly", ")", "sx", ...
Mirror the actor polydata along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. .. hint:: |mirror| |mirror.py|_
[ "Mirror", "the", "actor", "polydata", "along", "one", "of", "the", "cartesian", "axes", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1200-L1249
train
210,427
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.shrink
def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,0,-0.5) show(pot, s) |shrink| |shrink.py|_ """ poly = self.polydata(True) shrink = vtk.vtkShrinkPolyData() shrink.SetInputData(poly) shrink.SetShrinkFactor(fraction) shrink.Update() return self.updateMesh(shrink.GetOutput())
python
def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,0,-0.5) show(pot, s) |shrink| |shrink.py|_ """ poly = self.polydata(True) shrink = vtk.vtkShrinkPolyData() shrink.SetInputData(poly) shrink.SetShrinkFactor(fraction) shrink.Update() return self.updateMesh(shrink.GetOutput())
[ "def", "shrink", "(", "self", ",", "fraction", "=", "0.85", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "shrink", "=", "vtk", ".", "vtkShrinkPolyData", "(", ")", "shrink", ".", "SetInputData", "(", "poly", ")", "shrink", ".", "S...
Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,0,-0.5) show(pot, s) |shrink| |shrink.py|_
[ "Shrink", "the", "triangle", "polydata", "in", "the", "representation", "of", "the", "input", "mesh", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1257-L1275
train
210,428
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.stretch
def stretch(self, q1, q2): """Stretch actor between points `q1` and `q2`. Mesh is not affected. .. hint:: |aspring| |aspring.py|_ .. note:: for ``Actors`` like helices, Line, cylinders, cones etc., two attributes ``actor.base``, and ``actor.top`` are already defined. """ if self.base is None: colors.printc('~times Error in stretch(): Please define vectors \ actor.base and actor.top at creation. Exit.', c='r') exit(0) p1, p2 = self.base, self.top q1, q2, z = np.array(q1), np.array(q2), np.array([0, 0, 1]) plength = np.linalg.norm(p2 - p1) qlength = np.linalg.norm(q2 - q1) T = vtk.vtkTransform() T.PostMultiply() T.Translate(-p1) cosa = np.dot(p2 - p1, z) / plength n = np.cross(p2 - p1, z) T.RotateWXYZ(np.arccos(cosa) * 57.3, n) T.Scale(1, 1, qlength / plength) cosa = np.dot(q2 - q1, z) / qlength n = np.cross(q2 - q1, z) T.RotateWXYZ(-np.arccos(cosa) * 57.3, n) T.Translate(q1) self.SetUserMatrix(T.GetMatrix()) if self.trail: self.updateTrail() return self
python
def stretch(self, q1, q2): """Stretch actor between points `q1` and `q2`. Mesh is not affected. .. hint:: |aspring| |aspring.py|_ .. note:: for ``Actors`` like helices, Line, cylinders, cones etc., two attributes ``actor.base``, and ``actor.top`` are already defined. """ if self.base is None: colors.printc('~times Error in stretch(): Please define vectors \ actor.base and actor.top at creation. Exit.', c='r') exit(0) p1, p2 = self.base, self.top q1, q2, z = np.array(q1), np.array(q2), np.array([0, 0, 1]) plength = np.linalg.norm(p2 - p1) qlength = np.linalg.norm(q2 - q1) T = vtk.vtkTransform() T.PostMultiply() T.Translate(-p1) cosa = np.dot(p2 - p1, z) / plength n = np.cross(p2 - p1, z) T.RotateWXYZ(np.arccos(cosa) * 57.3, n) T.Scale(1, 1, qlength / plength) cosa = np.dot(q2 - q1, z) / qlength n = np.cross(q2 - q1, z) T.RotateWXYZ(-np.arccos(cosa) * 57.3, n) T.Translate(q1) self.SetUserMatrix(T.GetMatrix()) if self.trail: self.updateTrail() return self
[ "def", "stretch", "(", "self", ",", "q1", ",", "q2", ")", ":", "if", "self", ".", "base", "is", "None", ":", "colors", ".", "printc", "(", "'~times Error in stretch(): Please define vectors \\\n actor.base and actor.top at creation. Exit.'", ",", ...
Stretch actor between points `q1` and `q2`. Mesh is not affected. .. hint:: |aspring| |aspring.py|_ .. note:: for ``Actors`` like helices, Line, cylinders, cones etc., two attributes ``actor.base``, and ``actor.top`` are already defined.
[ "Stretch", "actor", "between", "points", "q1", "and", "q2", ".", "Mesh", "is", "not", "affected", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1277-L1311
train
210,429
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.cutWithPlane
def cutWithPlane(self, origin=(0, 0, 0), normal=(1, 0, 0), showcut=False): """ Takes a ``vtkActor`` and cuts it with the plane defined by a point and a normal. :param origin: the cutting plane goes through this point :param normal: normal of the cutting plane :param showcut: if `True` show the cut off part of the mesh as thin wireframe. :Example: .. code-block:: python from vtkplotter import Cube cube = Cube().cutWithPlane(normal=(1,1,1)) cube.bc('pink').show() |cutcube| .. hint:: |trail| |trail.py|_ """ if normal is "x": normal = (1,0,0) elif normal is "y": normal = (0,1,0) elif normal is "z": normal = (0,0,1) plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) self.computeNormals() poly = self.polydata() clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) clipper.SetClipFunction(plane) if showcut: clipper.GenerateClippedOutputOn() else: clipper.GenerateClippedOutputOff() clipper.GenerateClipScalarsOff() clipper.SetValue(0) clipper.Update() self.updateMesh(clipper.GetOutput()) if showcut: c = self.GetProperty().GetColor() cpoly = clipper.GetClippedOutput() restActor = Actor(cpoly, c=c, alpha=0.05, wire=1) restActor.SetUserMatrix(self.GetMatrix()) asse = Assembly([self, restActor]) self = asse return asse else: return self
python
def cutWithPlane(self, origin=(0, 0, 0), normal=(1, 0, 0), showcut=False): """ Takes a ``vtkActor`` and cuts it with the plane defined by a point and a normal. :param origin: the cutting plane goes through this point :param normal: normal of the cutting plane :param showcut: if `True` show the cut off part of the mesh as thin wireframe. :Example: .. code-block:: python from vtkplotter import Cube cube = Cube().cutWithPlane(normal=(1,1,1)) cube.bc('pink').show() |cutcube| .. hint:: |trail| |trail.py|_ """ if normal is "x": normal = (1,0,0) elif normal is "y": normal = (0,1,0) elif normal is "z": normal = (0,0,1) plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) self.computeNormals() poly = self.polydata() clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) clipper.SetClipFunction(plane) if showcut: clipper.GenerateClippedOutputOn() else: clipper.GenerateClippedOutputOff() clipper.GenerateClipScalarsOff() clipper.SetValue(0) clipper.Update() self.updateMesh(clipper.GetOutput()) if showcut: c = self.GetProperty().GetColor() cpoly = clipper.GetClippedOutput() restActor = Actor(cpoly, c=c, alpha=0.05, wire=1) restActor.SetUserMatrix(self.GetMatrix()) asse = Assembly([self, restActor]) self = asse return asse else: return self
[ "def", "cutWithPlane", "(", "self", ",", "origin", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "1", ",", "0", ",", "0", ")", ",", "showcut", "=", "False", ")", ":", "if", "normal", "is", "\"x\"", ":", "normal", "=", "(", ...
Takes a ``vtkActor`` and cuts it with the plane defined by a point and a normal. :param origin: the cutting plane goes through this point :param normal: normal of the cutting plane :param showcut: if `True` show the cut off part of the mesh as thin wireframe. :Example: .. code-block:: python from vtkplotter import Cube cube = Cube().cutWithPlane(normal=(1,1,1)) cube.bc('pink').show() |cutcube| .. hint:: |trail| |trail.py|_
[ "Takes", "a", "vtkActor", "and", "cuts", "it", "with", "the", "plane", "defined", "by", "a", "point", "and", "a", "normal", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1313-L1367
train
210,430
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.cutWithMesh
def cutWithMesh(self, mesh, invert=False): """ Cut an ``Actor`` mesh with another ``vtkPolyData`` or ``Actor``. :param bool invert: if True return cut off part of actor. .. hint:: |cutWithMesh| |cutWithMesh.py|_ |cutAndCap| |cutAndCap.py|_ """ if isinstance(mesh, vtk.vtkPolyData): polymesh = mesh if isinstance(mesh, Actor): polymesh = mesh.polydata() else: polymesh = mesh.GetMapper().GetInput() poly = self.polydata() # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # implicit function that will be used to slice the mesh ippd = vtk.vtkImplicitPolyDataDistance() ippd.SetInput(polymesh) # Evaluate the signed distance function at all of the grid points for pointId in range(poly.GetNumberOfPoints()): p = poly.GetPoint(pointId) signedDistance = ippd.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # add the SignedDistances to the grid poly.GetPointData().SetScalars(signedDistances) # use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) if invert: clipper.InsideOutOff() else: clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() return self.updateMesh(clipper.GetOutput())
python
def cutWithMesh(self, mesh, invert=False): """ Cut an ``Actor`` mesh with another ``vtkPolyData`` or ``Actor``. :param bool invert: if True return cut off part of actor. .. hint:: |cutWithMesh| |cutWithMesh.py|_ |cutAndCap| |cutAndCap.py|_ """ if isinstance(mesh, vtk.vtkPolyData): polymesh = mesh if isinstance(mesh, Actor): polymesh = mesh.polydata() else: polymesh = mesh.GetMapper().GetInput() poly = self.polydata() # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # implicit function that will be used to slice the mesh ippd = vtk.vtkImplicitPolyDataDistance() ippd.SetInput(polymesh) # Evaluate the signed distance function at all of the grid points for pointId in range(poly.GetNumberOfPoints()): p = poly.GetPoint(pointId) signedDistance = ippd.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # add the SignedDistances to the grid poly.GetPointData().SetScalars(signedDistances) # use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) if invert: clipper.InsideOutOff() else: clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() return self.updateMesh(clipper.GetOutput())
[ "def", "cutWithMesh", "(", "self", ",", "mesh", ",", "invert", "=", "False", ")", ":", "if", "isinstance", "(", "mesh", ",", "vtk", ".", "vtkPolyData", ")", ":", "polymesh", "=", "mesh", "if", "isinstance", "(", "mesh", ",", "Actor", ")", ":", "polym...
Cut an ``Actor`` mesh with another ``vtkPolyData`` or ``Actor``. :param bool invert: if True return cut off part of actor. .. hint:: |cutWithMesh| |cutWithMesh.py|_ |cutAndCap| |cutAndCap.py|_
[ "Cut", "an", "Actor", "mesh", "with", "another", "vtkPolyData", "or", "Actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1369-L1414
train
210,431
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.cap
def cap(self, returnCap=False): """ Generate a "cap" on a clipped actor, or caps sharp edges. .. hint:: |cutAndCap| |cutAndCap.py|_ """ poly = self.polydata(True) fe = vtk.vtkFeatureEdges() fe.SetInputData(poly) fe.BoundaryEdgesOn() fe.FeatureEdgesOff() fe.NonManifoldEdgesOff() fe.ManifoldEdgesOff() fe.Update() stripper = vtk.vtkStripper() stripper.SetInputData(fe.GetOutput()) stripper.Update() boundaryPoly = vtk.vtkPolyData() boundaryPoly.SetPoints(stripper.GetOutput().GetPoints()) boundaryPoly.SetPolys(stripper.GetOutput().GetLines()) tf = vtk.vtkTriangleFilter() tf.SetInputData(boundaryPoly) tf.Update() if returnCap: return Actor(tf.GetOutput()) else: polyapp = vtk.vtkAppendPolyData() polyapp.AddInputData(poly) polyapp.AddInputData(tf.GetOutput()) polyapp.Update() return self.updateMesh(polyapp.GetOutput()).clean()
python
def cap(self, returnCap=False): """ Generate a "cap" on a clipped actor, or caps sharp edges. .. hint:: |cutAndCap| |cutAndCap.py|_ """ poly = self.polydata(True) fe = vtk.vtkFeatureEdges() fe.SetInputData(poly) fe.BoundaryEdgesOn() fe.FeatureEdgesOff() fe.NonManifoldEdgesOff() fe.ManifoldEdgesOff() fe.Update() stripper = vtk.vtkStripper() stripper.SetInputData(fe.GetOutput()) stripper.Update() boundaryPoly = vtk.vtkPolyData() boundaryPoly.SetPoints(stripper.GetOutput().GetPoints()) boundaryPoly.SetPolys(stripper.GetOutput().GetLines()) tf = vtk.vtkTriangleFilter() tf.SetInputData(boundaryPoly) tf.Update() if returnCap: return Actor(tf.GetOutput()) else: polyapp = vtk.vtkAppendPolyData() polyapp.AddInputData(poly) polyapp.AddInputData(tf.GetOutput()) polyapp.Update() return self.updateMesh(polyapp.GetOutput()).clean()
[ "def", "cap", "(", "self", ",", "returnCap", "=", "False", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "fe", "=", "vtk", ".", "vtkFeatureEdges", "(", ")", "fe", ".", "SetInputData", "(", "poly", ")", "fe", ".", "BoundaryEdgesOn"...
Generate a "cap" on a clipped actor, or caps sharp edges. .. hint:: |cutAndCap| |cutAndCap.py|_
[ "Generate", "a", "cap", "on", "a", "clipped", "actor", "or", "caps", "sharp", "edges", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1416-L1451
train
210,432
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.threshold
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalars refers to cells. .. hint:: |mesh_threshold| |mesh_threshold.py|_ """ if utils.isSequence(scalars): self.addPointScalars(scalars, "threshold") scalars = "threshold" elif self.scalars(scalars) is None: colors.printc("~times No scalars found with name", scalars, c=1) exit() thres = vtk.vtkThreshold() thres.SetInputData(self.poly) if useCells: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS else: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS thres.SetInputArrayToProcess(0, 0, 0, asso, scalars) if vmin is None and vmax is not None: thres.ThresholdByLower(vmax) elif vmax is None and vmin is not None: thres.ThresholdByUpper(vmin) else: thres.ThresholdBetween(vmin, vmax) thres.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(thres.GetOutput()) gf.Update() return self.updateMesh(gf.GetOutput())
python
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalars refers to cells. .. hint:: |mesh_threshold| |mesh_threshold.py|_ """ if utils.isSequence(scalars): self.addPointScalars(scalars, "threshold") scalars = "threshold" elif self.scalars(scalars) is None: colors.printc("~times No scalars found with name", scalars, c=1) exit() thres = vtk.vtkThreshold() thres.SetInputData(self.poly) if useCells: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS else: asso = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS thres.SetInputArrayToProcess(0, 0, 0, asso, scalars) if vmin is None and vmax is not None: thres.ThresholdByLower(vmax) elif vmax is None and vmin is not None: thres.ThresholdByUpper(vmin) else: thres.ThresholdBetween(vmin, vmax) thres.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(thres.GetOutput()) gf.Update() return self.updateMesh(gf.GetOutput())
[ "def", "threshold", "(", "self", ",", "scalars", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "useCells", "=", "False", ")", ":", "if", "utils", ".", "isSequence", "(", "scalars", ")", ":", "self", ".", "addPointScalars", "(", "scalars", ...
Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalars refers to cells. .. hint:: |mesh_threshold| |mesh_threshold.py|_
[ "Extracts", "cells", "where", "scalar", "value", "satisfies", "threshold", "criterion", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1453-L1492
train
210,433
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.triangle
def triangle(self, verts=True, lines=True): """ Converts actor polygons and strips to triangles. """ tf = vtk.vtkTriangleFilter() tf.SetPassLines(lines) tf.SetPassVerts(verts) tf.SetInputData(self.poly) tf.Update() return self.updateMesh(tf.GetOutput())
python
def triangle(self, verts=True, lines=True): """ Converts actor polygons and strips to triangles. """ tf = vtk.vtkTriangleFilter() tf.SetPassLines(lines) tf.SetPassVerts(verts) tf.SetInputData(self.poly) tf.Update() return self.updateMesh(tf.GetOutput())
[ "def", "triangle", "(", "self", ",", "verts", "=", "True", ",", "lines", "=", "True", ")", ":", "tf", "=", "vtk", ".", "vtkTriangleFilter", "(", ")", "tf", ".", "SetPassLines", "(", "lines", ")", "tf", ".", "SetPassVerts", "(", "verts", ")", "tf", ...
Converts actor polygons and strips to triangles.
[ "Converts", "actor", "polygons", "and", "strips", "to", "triangles", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1494-L1503
train
210,434
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.pointColors
def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): """ Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :param alpha: mesh transparency. Can be a ``list`` of values one for each vertex. :type alpha: float, list :param int bands: group scalars in this number of bins, typically to form bands or stripes. :param float vmin: clip scalars to this minimum value :param float vmax: clip scalars to this maximum value .. hint:: |mesh_coloring| |mesh_coloring.py|_ |mesh_alphas| |mesh_alphas.py|_ |mesh_bands| |mesh_bands.py|_ |mesh_custom| |mesh_custom.py|_ """ poly = self.polydata(False) if isinstance(scalars, str): # if a name is passed scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) n = len(scalars) useAlpha = False if n != poly.GetNumberOfPoints(): colors.printc('~times pointColors Error: nr. of scalars != nr. of points', n, poly.GetNumberOfPoints(), c=1) if utils.isSequence(alpha): useAlpha = True if len(alpha) > n: colors.printc('~times pointColors Error: nr. of scalars < nr. of alpha values', n, len(alpha), c=1) exit() if bands: scalars = utils.makeBands(scalars, bands) if vmin is None: vmin = np.min(scalars) if vmax is None: vmax = np.max(scalars) lut = vtk.vtkLookupTable() # build the look-up table if utils.isSequence(cmap): sname = "pointColors_custom" lut.SetNumberOfTableValues(len(cmap)) lut.Build() for i, c in enumerate(cmap): col = colors.getColor(c) r, g, b = col if useAlpha: lut.SetTableValue(i, r, g, b, alpha[i]) else: lut.SetTableValue(i, r, g, b, alpha) elif isinstance(cmap, vtk.vtkLookupTable): sname = "pointColors_lut" lut = cmap else: if isinstance(cmap, str): sname = "pointColors_" + cmap else: sname = "pointColors" lut.SetNumberOfTableValues(512) lut.Build() for i in range(512): r, g, b = colors.colorMap(i, cmap, 0, 512) if useAlpha: idx = int(i / 512 * len(alpha)) lut.SetTableValue(i, r, g, b, alpha[idx]) else: lut.SetTableValue(i, r, g, b, alpha) arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(sname) self.mapper.SetScalarRange(vmin, vmax) self.mapper.SetLookupTable(lut) self.mapper.ScalarVisibilityOn() poly.GetPointData().SetScalars(arr) poly.GetPointData().SetActiveScalars(sname) return self
python
def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax=None): """ Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :param alpha: mesh transparency. Can be a ``list`` of values one for each vertex. :type alpha: float, list :param int bands: group scalars in this number of bins, typically to form bands or stripes. :param float vmin: clip scalars to this minimum value :param float vmax: clip scalars to this maximum value .. hint:: |mesh_coloring| |mesh_coloring.py|_ |mesh_alphas| |mesh_alphas.py|_ |mesh_bands| |mesh_bands.py|_ |mesh_custom| |mesh_custom.py|_ """ poly = self.polydata(False) if isinstance(scalars, str): # if a name is passed scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) n = len(scalars) useAlpha = False if n != poly.GetNumberOfPoints(): colors.printc('~times pointColors Error: nr. of scalars != nr. of points', n, poly.GetNumberOfPoints(), c=1) if utils.isSequence(alpha): useAlpha = True if len(alpha) > n: colors.printc('~times pointColors Error: nr. of scalars < nr. of alpha values', n, len(alpha), c=1) exit() if bands: scalars = utils.makeBands(scalars, bands) if vmin is None: vmin = np.min(scalars) if vmax is None: vmax = np.max(scalars) lut = vtk.vtkLookupTable() # build the look-up table if utils.isSequence(cmap): sname = "pointColors_custom" lut.SetNumberOfTableValues(len(cmap)) lut.Build() for i, c in enumerate(cmap): col = colors.getColor(c) r, g, b = col if useAlpha: lut.SetTableValue(i, r, g, b, alpha[i]) else: lut.SetTableValue(i, r, g, b, alpha) elif isinstance(cmap, vtk.vtkLookupTable): sname = "pointColors_lut" lut = cmap else: if isinstance(cmap, str): sname = "pointColors_" + cmap else: sname = "pointColors" lut.SetNumberOfTableValues(512) lut.Build() for i in range(512): r, g, b = colors.colorMap(i, cmap, 0, 512) if useAlpha: idx = int(i / 512 * len(alpha)) lut.SetTableValue(i, r, g, b, alpha[idx]) else: lut.SetTableValue(i, r, g, b, alpha) arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(sname) self.mapper.SetScalarRange(vmin, vmax) self.mapper.SetLookupTable(lut) self.mapper.ScalarVisibilityOn() poly.GetPointData().SetScalars(arr) poly.GetPointData().SetActiveScalars(sname) return self
[ "def", "pointColors", "(", "self", ",", "scalars", ",", "cmap", "=", "\"jet\"", ",", "alpha", "=", "1", ",", "bands", "=", "None", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", "...
Set individual point colors by providing a list of scalar values and a color map. `scalars` can be a string name of the ``vtkArray``. :param cmap: color map scheme to transform a real number into a color. :type cmap: str, list, vtkLookupTable, matplotlib.colors.LinearSegmentedColormap :param alpha: mesh transparency. Can be a ``list`` of values one for each vertex. :type alpha: float, list :param int bands: group scalars in this number of bins, typically to form bands or stripes. :param float vmin: clip scalars to this minimum value :param float vmax: clip scalars to this maximum value .. hint:: |mesh_coloring| |mesh_coloring.py|_ |mesh_alphas| |mesh_alphas.py|_ |mesh_bands| |mesh_bands.py|_ |mesh_custom| |mesh_custom.py|_
[ "Set", "individual", "point", "colors", "by", "providing", "a", "list", "of", "scalar", "values", "and", "a", "color", "map", ".", "scalars", "can", "be", "a", "string", "name", "of", "the", "vtkArray", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1532-L1617
train
210,435
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addPointScalars
def addPointScalars(self, scalars, name): """ Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """ poly = self.polydata(False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('~times pointScalars Error: Number of scalars != nr. of points', len(scalars), poly.GetNumberOfPoints(), c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
python
def addPointScalars(self, scalars, name): """ Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_ """ poly = self.polydata(False) if len(scalars) != poly.GetNumberOfPoints(): colors.printc('~times pointScalars Error: Number of scalars != nr. of points', len(scalars), poly.GetNumberOfPoints(), c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
[ "def", "addPointScalars", "(", "self", ",", "scalars", ",", "name", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "if", "len", "(", "scalars", ")", "!=", "poly", ".", "GetNumberOfPoints", "(", ")", ":", "colors", ".", "printc", "...
Add point scalars to the actor's polydata assigning it a name. .. hint:: |mesh_coloring| |mesh_coloring.py|_
[ "Add", "point", "scalars", "to", "the", "actor", "s", "polydata", "assigning", "it", "a", "name", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1700-L1717
train
210,436
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addCellScalars
def addCellScalars(self, scalars, name): """ Add cell scalars to the actor's polydata assigning it a name. """ poly = self.polydata(False) if isinstance(scalars, str): scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) if len(scalars) != poly.GetNumberOfCells(): colors.printc("~times Number of scalars != nr. of cells", c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetCellData().AddArray(arr) poly.GetCellData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
python
def addCellScalars(self, scalars, name): """ Add cell scalars to the actor's polydata assigning it a name. """ poly = self.polydata(False) if isinstance(scalars, str): scalars = vtk_to_numpy(poly.GetPointData().GetArray(scalars)) if len(scalars) != poly.GetNumberOfCells(): colors.printc("~times Number of scalars != nr. of cells", c=1) exit() arr = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) arr.SetName(name) poly.GetCellData().AddArray(arr) poly.GetCellData().SetActiveScalars(name) self.mapper.SetScalarRange(np.min(scalars), np.max(scalars)) self.mapper.ScalarVisibilityOn() return self
[ "def", "addCellScalars", "(", "self", ",", "scalars", ",", "name", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "if", "isinstance", "(", "scalars", ",", "str", ")", ":", "scalars", "=", "vtk_to_numpy", "(", "poly", ".", "GetPointD...
Add cell scalars to the actor's polydata assigning it a name.
[ "Add", "cell", "scalars", "to", "the", "actor", "s", "polydata", "assigning", "it", "a", "name", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1719-L1736
train
210,437
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addPointVectors
def addPointVectors(self, vectors, name): """ Add a point vector field to the actor's polydata assigning it a name. """ poly = self.polydata(False) if len(vectors) != poly.GetNumberOfPoints(): colors.printc('~times addPointVectors Error: Number of vectors != nr. of points', len(vectors), poly.GetNumberOfPoints(), c=1) exit() arr = vtk.vtkDoubleArray() arr.SetNumberOfComponents(3) arr.SetName(name) for v in vectors: arr.InsertNextTuple(v) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveVectors(name) return self
python
def addPointVectors(self, vectors, name): """ Add a point vector field to the actor's polydata assigning it a name. """ poly = self.polydata(False) if len(vectors) != poly.GetNumberOfPoints(): colors.printc('~times addPointVectors Error: Number of vectors != nr. of points', len(vectors), poly.GetNumberOfPoints(), c=1) exit() arr = vtk.vtkDoubleArray() arr.SetNumberOfComponents(3) arr.SetName(name) for v in vectors: arr.InsertNextTuple(v) poly.GetPointData().AddArray(arr) poly.GetPointData().SetActiveVectors(name) return self
[ "def", "addPointVectors", "(", "self", ",", "vectors", ",", "name", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "if", "len", "(", "vectors", ")", "!=", "poly", ".", "GetNumberOfPoints", "(", ")", ":", "colors", ".", "printc", "...
Add a point vector field to the actor's polydata assigning it a name.
[ "Add", "a", "point", "vector", "field", "to", "the", "actor", "s", "polydata", "assigning", "it", "a", "name", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1738-L1754
train
210,438
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addIDs
def addIDs(self, asfield=False): """ Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data. """ ids = vtk.vtkIdFilter() ids.SetInputData(self.poly) ids.PointIdsOn() ids.CellIdsOn() if asfield: ids.FieldDataOn() else: ids.FieldDataOff() ids.Update() return self.updateMesh(ids.GetOutput())
python
def addIDs(self, asfield=False): """ Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data. """ ids = vtk.vtkIdFilter() ids.SetInputData(self.poly) ids.PointIdsOn() ids.CellIdsOn() if asfield: ids.FieldDataOn() else: ids.FieldDataOff() ids.Update() return self.updateMesh(ids.GetOutput())
[ "def", "addIDs", "(", "self", ",", "asfield", "=", "False", ")", ":", "ids", "=", "vtk", ".", "vtkIdFilter", "(", ")", "ids", ".", "SetInputData", "(", "self", ".", "poly", ")", "ids", ".", "PointIdsOn", "(", ")", "ids", ".", "CellIdsOn", "(", ")",...
Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data.
[ "Generate", "point", "and", "cell", "ids", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1756-L1771
train
210,439
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addCurvatureScalars
def addCurvatureScalars(self, method=0, lut=None): """ Build an ``Actor`` that contains the color coded surface curvature calculated in three different ways. :param int method: 0-gaussian, 1-mean, 2-max, 3-min curvature. :param float lut: optional look up table. :Example: .. code-block:: python from vtkplotter import * t = Torus().addCurvatureScalars() show(t) |curvature| """ curve = vtk.vtkCurvatures() curve.SetInputData(self.poly) curve.SetCurvatureType(method) curve.Update() self.poly = curve.GetOutput() scls = self.poly.GetPointData().GetScalars().GetRange() print("curvature(): scalar range is", scls) self.mapper.SetInputData(self.poly) if lut: self.mapper.SetLookupTable(lut) self.mapper.SetUseLookupTableScalarRange(1) self.mapper.Update() self.Modified() self.mapper.ScalarVisibilityOn() return self
python
def addCurvatureScalars(self, method=0, lut=None): """ Build an ``Actor`` that contains the color coded surface curvature calculated in three different ways. :param int method: 0-gaussian, 1-mean, 2-max, 3-min curvature. :param float lut: optional look up table. :Example: .. code-block:: python from vtkplotter import * t = Torus().addCurvatureScalars() show(t) |curvature| """ curve = vtk.vtkCurvatures() curve.SetInputData(self.poly) curve.SetCurvatureType(method) curve.Update() self.poly = curve.GetOutput() scls = self.poly.GetPointData().GetScalars().GetRange() print("curvature(): scalar range is", scls) self.mapper.SetInputData(self.poly) if lut: self.mapper.SetLookupTable(lut) self.mapper.SetUseLookupTableScalarRange(1) self.mapper.Update() self.Modified() self.mapper.ScalarVisibilityOn() return self
[ "def", "addCurvatureScalars", "(", "self", ",", "method", "=", "0", ",", "lut", "=", "None", ")", ":", "curve", "=", "vtk", ".", "vtkCurvatures", "(", ")", "curve", ".", "SetInputData", "(", "self", ".", "poly", ")", "curve", ".", "SetCurvatureType", "...
Build an ``Actor`` that contains the color coded surface curvature calculated in three different ways. :param int method: 0-gaussian, 1-mean, 2-max, 3-min curvature. :param float lut: optional look up table. :Example: .. code-block:: python from vtkplotter import * t = Torus().addCurvatureScalars() show(t) |curvature|
[ "Build", "an", "Actor", "that", "contains", "the", "color", "coded", "surface", "curvature", "calculated", "in", "three", "different", "ways", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1773-L1806
train
210,440
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.scalars
def scalars(self, name_or_idx=None, datatype="point"): """ Retrieve point or cell scalars using array name or index number. If no ``name`` is given return the list of names of existing arrays. .. hint:: |mesh_coloring.py|_ """ poly = self.polydata(False) if name_or_idx is None: # get mode behaviour ncd = poly.GetCellData().GetNumberOfArrays() npd = poly.GetPointData().GetNumberOfArrays() nfd = poly.GetFieldData().GetNumberOfArrays() arrs = [] for i in range(npd): print(i, "PointData", poly.GetPointData().GetArrayName(i)) arrs.append(["PointData", poly.GetPointData().GetArrayName(i)]) for i in range(ncd): print(i, "CellData", poly.GetCellData().GetArrayName(i)) arrs.append(["CellData", poly.GetCellData().GetArrayName(i)]) for i in range(nfd): print(i, "FieldData", poly.GetFieldData().GetArrayName(i)) arrs.append(["FieldData", poly.GetFieldData().GetArrayName(i)]) return arrs else: # set mode if "point" in datatype.lower(): data = poly.GetPointData() elif "cell" in datatype.lower(): data = poly.GetCellData() elif "field" in datatype.lower(): data = poly.GetFieldData() else: colors.printc("~times Error in scalars(): unknown datatype", datatype, c=1) exit() if isinstance(name_or_idx, int): name = data.GetArrayName(name_or_idx) if name is None: return None data.SetActiveScalars(name) return vtk_to_numpy(data.GetArray(name)) elif isinstance(name_or_idx, str): arr = data.GetArray(name_or_idx) if arr is None: return None data.SetActiveScalars(name_or_idx) return vtk_to_numpy(arr) return None
python
def scalars(self, name_or_idx=None, datatype="point"): """ Retrieve point or cell scalars using array name or index number. If no ``name`` is given return the list of names of existing arrays. .. hint:: |mesh_coloring.py|_ """ poly = self.polydata(False) if name_or_idx is None: # get mode behaviour ncd = poly.GetCellData().GetNumberOfArrays() npd = poly.GetPointData().GetNumberOfArrays() nfd = poly.GetFieldData().GetNumberOfArrays() arrs = [] for i in range(npd): print(i, "PointData", poly.GetPointData().GetArrayName(i)) arrs.append(["PointData", poly.GetPointData().GetArrayName(i)]) for i in range(ncd): print(i, "CellData", poly.GetCellData().GetArrayName(i)) arrs.append(["CellData", poly.GetCellData().GetArrayName(i)]) for i in range(nfd): print(i, "FieldData", poly.GetFieldData().GetArrayName(i)) arrs.append(["FieldData", poly.GetFieldData().GetArrayName(i)]) return arrs else: # set mode if "point" in datatype.lower(): data = poly.GetPointData() elif "cell" in datatype.lower(): data = poly.GetCellData() elif "field" in datatype.lower(): data = poly.GetFieldData() else: colors.printc("~times Error in scalars(): unknown datatype", datatype, c=1) exit() if isinstance(name_or_idx, int): name = data.GetArrayName(name_or_idx) if name is None: return None data.SetActiveScalars(name) return vtk_to_numpy(data.GetArray(name)) elif isinstance(name_or_idx, str): arr = data.GetArray(name_or_idx) if arr is None: return None data.SetActiveScalars(name_or_idx) return vtk_to_numpy(arr) return None
[ "def", "scalars", "(", "self", ",", "name_or_idx", "=", "None", ",", "datatype", "=", "\"point\"", ")", ":", "poly", "=", "self", ".", "polydata", "(", "False", ")", "if", "name_or_idx", "is", "None", ":", "# get mode behaviour", "ncd", "=", "poly", ".",...
Retrieve point or cell scalars using array name or index number. If no ``name`` is given return the list of names of existing arrays. .. hint:: |mesh_coloring.py|_
[ "Retrieve", "point", "or", "cell", "scalars", "using", "array", "name", "or", "index", "number", ".", "If", "no", "name", "is", "given", "return", "the", "list", "of", "names", "of", "existing", "arrays", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1808-L1856
train
210,441
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.subdivide
def subdivide(self, N=1, method=0): """Increase the number of vertices of a surface mesh. :param int N: number of subdivisions. :param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3) .. hint:: |tutorial_subdivide| |tutorial.py|_ """ triangles = vtk.vtkTriangleFilter() triangles.SetInputData(self.polydata()) triangles.Update() originalMesh = triangles.GetOutput() if method == 0: sdf = vtk.vtkLoopSubdivisionFilter() elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter() elif method == 2: sdf = vtk.vtkAdaptiveSubdivisionFilter() elif method == 3: sdf = vtk.vtkButterflySubdivisionFilter() else: colors.printc("~times Error in subdivide: unknown method.", c="r") exit() if method != 2: sdf.SetNumberOfSubdivisions(N) sdf.SetInputData(originalMesh) sdf.Update() return self.updateMesh(sdf.GetOutput())
python
def subdivide(self, N=1, method=0): """Increase the number of vertices of a surface mesh. :param int N: number of subdivisions. :param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3) .. hint:: |tutorial_subdivide| |tutorial.py|_ """ triangles = vtk.vtkTriangleFilter() triangles.SetInputData(self.polydata()) triangles.Update() originalMesh = triangles.GetOutput() if method == 0: sdf = vtk.vtkLoopSubdivisionFilter() elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter() elif method == 2: sdf = vtk.vtkAdaptiveSubdivisionFilter() elif method == 3: sdf = vtk.vtkButterflySubdivisionFilter() else: colors.printc("~times Error in subdivide: unknown method.", c="r") exit() if method != 2: sdf.SetNumberOfSubdivisions(N) sdf.SetInputData(originalMesh) sdf.Update() return self.updateMesh(sdf.GetOutput())
[ "def", "subdivide", "(", "self", ",", "N", "=", "1", ",", "method", "=", "0", ")", ":", "triangles", "=", "vtk", ".", "vtkTriangleFilter", "(", ")", "triangles", ".", "SetInputData", "(", "self", ".", "polydata", "(", ")", ")", "triangles", ".", "Upd...
Increase the number of vertices of a surface mesh. :param int N: number of subdivisions. :param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3) .. hint:: |tutorial_subdivide| |tutorial.py|_
[ "Increase", "the", "number", "of", "vertices", "of", "a", "surface", "mesh", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1858-L1885
train
210,442
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.decimate
def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True): """ Downsample the number of vertices in a mesh. :param float fraction: the desired target of reduction. :param int N: the desired number of final points (**fraction** is recalculated based on it). :param bool boundaries: (True), decide whether to leave boundaries untouched or not. .. note:: Setting ``fraction=0.1`` leaves 10% of the original nr of vertices. .. hint:: |skeletonize| |skeletonize.py|_ """ poly = self.polydata(True) if N: # N = desired number of points Np = poly.GetNumberOfPoints() fraction = float(N) / Np if fraction >= 1: return self decimate = vtk.vtkDecimatePro() decimate.SetInputData(poly) decimate.SetTargetReduction(1 - fraction) decimate.PreserveTopologyOff() if boundaries: decimate.BoundaryVertexDeletionOff() else: decimate.BoundaryVertexDeletionOn() decimate.Update() if verbose: print("Nr. of pts, input:", poly.GetNumberOfPoints(), end="") print(" output:", decimate.GetOutput().GetNumberOfPoints()) return self.updateMesh(decimate.GetOutput())
python
def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True): """ Downsample the number of vertices in a mesh. :param float fraction: the desired target of reduction. :param int N: the desired number of final points (**fraction** is recalculated based on it). :param bool boundaries: (True), decide whether to leave boundaries untouched or not. .. note:: Setting ``fraction=0.1`` leaves 10% of the original nr of vertices. .. hint:: |skeletonize| |skeletonize.py|_ """ poly = self.polydata(True) if N: # N = desired number of points Np = poly.GetNumberOfPoints() fraction = float(N) / Np if fraction >= 1: return self decimate = vtk.vtkDecimatePro() decimate.SetInputData(poly) decimate.SetTargetReduction(1 - fraction) decimate.PreserveTopologyOff() if boundaries: decimate.BoundaryVertexDeletionOff() else: decimate.BoundaryVertexDeletionOn() decimate.Update() if verbose: print("Nr. of pts, input:", poly.GetNumberOfPoints(), end="") print(" output:", decimate.GetOutput().GetNumberOfPoints()) return self.updateMesh(decimate.GetOutput())
[ "def", "decimate", "(", "self", ",", "fraction", "=", "0.5", ",", "N", "=", "None", ",", "boundaries", "=", "False", ",", "verbose", "=", "True", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "if", "N", ":", "# N = desired number ...
Downsample the number of vertices in a mesh. :param float fraction: the desired target of reduction. :param int N: the desired number of final points (**fraction** is recalculated based on it). :param bool boundaries: (True), decide whether to leave boundaries untouched or not. .. note:: Setting ``fraction=0.1`` leaves 10% of the original nr of vertices. .. hint:: |skeletonize| |skeletonize.py|_
[ "Downsample", "the", "number", "of", "vertices", "in", "a", "mesh", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1887-L1918
train
210,443
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.addGaussNoise
def addGaussNoise(self, sigma): """ Add gaussian noise. :param float sigma: sigma is expressed in percent of the diagonal size of actor. :Example: .. code-block:: python from vtkplotter import Sphere Sphere().addGaussNoise(1.0).show() """ sz = self.diagonalSize() pts = self.coordinates() n = len(pts) ns = np.random.randn(n, 3) * sigma * sz / 100 vpts = vtk.vtkPoints() vpts.SetNumberOfPoints(n) vpts.SetData(numpy_to_vtk(pts + ns, deep=True)) self.poly.SetPoints(vpts) self.poly.GetPoints().Modified() return self
python
def addGaussNoise(self, sigma): """ Add gaussian noise. :param float sigma: sigma is expressed in percent of the diagonal size of actor. :Example: .. code-block:: python from vtkplotter import Sphere Sphere().addGaussNoise(1.0).show() """ sz = self.diagonalSize() pts = self.coordinates() n = len(pts) ns = np.random.randn(n, 3) * sigma * sz / 100 vpts = vtk.vtkPoints() vpts.SetNumberOfPoints(n) vpts.SetData(numpy_to_vtk(pts + ns, deep=True)) self.poly.SetPoints(vpts) self.poly.GetPoints().Modified() return self
[ "def", "addGaussNoise", "(", "self", ",", "sigma", ")", ":", "sz", "=", "self", ".", "diagonalSize", "(", ")", "pts", "=", "self", ".", "coordinates", "(", ")", "n", "=", "len", "(", "pts", ")", "ns", "=", "np", ".", "random", ".", "randn", "(", ...
Add gaussian noise. :param float sigma: sigma is expressed in percent of the diagonal size of actor. :Example: .. code-block:: python from vtkplotter import Sphere Sphere().addGaussNoise(1.0).show()
[ "Add", "gaussian", "noise", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1920-L1942
train
210,444
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.smoothLaplacian
def smoothLaplacian(self, niter=15, relaxfact=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using `Laplacian` smoothing. :param int niter: number of iterations. :param float relaxfact: relaxation factor. Small `relaxfact` and large `niter` are more stable. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers.py|_ """ poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetRelaxationFactor(relaxfact) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.BoundarySmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.GenerateErrorScalarsOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
python
def smoothLaplacian(self, niter=15, relaxfact=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using `Laplacian` smoothing. :param int niter: number of iterations. :param float relaxfact: relaxation factor. Small `relaxfact` and large `niter` are more stable. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers.py|_ """ poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetRelaxationFactor(relaxfact) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.BoundarySmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.GenerateErrorScalarsOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
[ "def", "smoothLaplacian", "(", "self", ",", "niter", "=", "15", ",", "relaxfact", "=", "0.1", ",", "edgeAngle", "=", "15", ",", "featureAngle", "=", "60", ")", ":", "poly", "=", "self", ".", "poly", "cl", "=", "vtk", ".", "vtkCleanPolyData", "(", ")"...
Adjust mesh point positions using `Laplacian` smoothing. :param int niter: number of iterations. :param float relaxfact: relaxation factor. Small `relaxfact` and large `niter` are more stable. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers.py|_
[ "Adjust", "mesh", "point", "positions", "using", "Laplacian", "smoothing", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1944-L1969
train
210,445
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.smoothWSinc
def smoothWSinc(self, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using the `Windowed Sinc` function interpolation kernel. :param int niter: number of iterations. :param float passBand: set the passband value for the windowed sinc filter. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers| |mesh_smoothers.py|_ """ poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkWindowedSincPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.SetPassBand(passBand) smoothFilter.NormalizeCoordinatesOn() smoothFilter.NonManifoldSmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
python
def smoothWSinc(self, niter=15, passBand=0.1, edgeAngle=15, featureAngle=60): """ Adjust mesh point positions using the `Windowed Sinc` function interpolation kernel. :param int niter: number of iterations. :param float passBand: set the passband value for the windowed sinc filter. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers| |mesh_smoothers.py|_ """ poly = self.poly cl = vtk.vtkCleanPolyData() cl.SetInputData(poly) cl.Update() smoothFilter = vtk.vtkWindowedSincPolyDataFilter() smoothFilter.SetInputData(cl.GetOutput()) smoothFilter.SetNumberOfIterations(niter) smoothFilter.SetEdgeAngle(edgeAngle) smoothFilter.SetFeatureAngle(featureAngle) smoothFilter.SetPassBand(passBand) smoothFilter.NormalizeCoordinatesOn() smoothFilter.NonManifoldSmoothingOn() smoothFilter.FeatureEdgeSmoothingOn() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() return self.updateMesh(smoothFilter.GetOutput())
[ "def", "smoothWSinc", "(", "self", ",", "niter", "=", "15", ",", "passBand", "=", "0.1", ",", "edgeAngle", "=", "15", ",", "featureAngle", "=", "60", ")", ":", "poly", "=", "self", ".", "poly", "cl", "=", "vtk", ".", "vtkCleanPolyData", "(", ")", "...
Adjust mesh point positions using the `Windowed Sinc` function interpolation kernel. :param int niter: number of iterations. :param float passBand: set the passband value for the windowed sinc filter. :param float edgeAngle: edge angle to control smoothing along edges (either interior or boundary). :param float featureAngle: specifies the feature angle for sharp edge identification. .. hint:: |mesh_smoothers| |mesh_smoothers.py|_
[ "Adjust", "mesh", "point", "positions", "using", "the", "Windowed", "Sinc", "function", "interpolation", "kernel", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1971-L1997
train
210,446
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.fillHoles
def fillHoles(self, size=None): """Identifies and fills holes in input mesh. Holes are identified by locating boundary edges, linking them together into loops, and then triangulating the resulting loops. :param float size: approximate limit to the size of the hole that can be filled. Example: |fillholes.py|_ """ fh = vtk.vtkFillHolesFilter() if not size: mb = self.maxBoundSize() size = mb / 10 fh.SetHoleSize(size) fh.SetInputData(self.poly) fh.Update() return self.updateMesh(fh.GetOutput())
python
def fillHoles(self, size=None): """Identifies and fills holes in input mesh. Holes are identified by locating boundary edges, linking them together into loops, and then triangulating the resulting loops. :param float size: approximate limit to the size of the hole that can be filled. Example: |fillholes.py|_ """ fh = vtk.vtkFillHolesFilter() if not size: mb = self.maxBoundSize() size = mb / 10 fh.SetHoleSize(size) fh.SetInputData(self.poly) fh.Update() return self.updateMesh(fh.GetOutput())
[ "def", "fillHoles", "(", "self", ",", "size", "=", "None", ")", ":", "fh", "=", "vtk", ".", "vtkFillHolesFilter", "(", ")", "if", "not", "size", ":", "mb", "=", "self", ".", "maxBoundSize", "(", ")", "size", "=", "mb", "/", "10", "fh", ".", "SetH...
Identifies and fills holes in input mesh. Holes are identified by locating boundary edges, linking them together into loops, and then triangulating the resulting loops. :param float size: approximate limit to the size of the hole that can be filled. Example: |fillholes.py|_
[ "Identifies", "and", "fills", "holes", "in", "input", "mesh", ".", "Holes", "are", "identified", "by", "locating", "boundary", "edges", "linking", "them", "together", "into", "loops", "and", "then", "triangulating", "the", "resulting", "loops", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2000-L2016
train
210,447
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.write
def write(self, filename="mesh.vtk", binary=True): """ Write actor's polydata in its current transformation to file. """ import vtkplotter.vtkio as vtkio return vtkio.write(self, filename, binary)
python
def write(self, filename="mesh.vtk", binary=True): """ Write actor's polydata in its current transformation to file. """ import vtkplotter.vtkio as vtkio return vtkio.write(self, filename, binary)
[ "def", "write", "(", "self", ",", "filename", "=", "\"mesh.vtk\"", ",", "binary", "=", "True", ")", ":", "import", "vtkplotter", ".", "vtkio", "as", "vtkio", "return", "vtkio", ".", "write", "(", "self", ",", "filename", ",", "binary", ")" ]
Write actor's polydata in its current transformation to file.
[ "Write", "actor", "s", "polydata", "in", "its", "current", "transformation", "to", "file", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2019-L2027
train
210,448
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.normalAt
def normalAt(self, i): """Return the normal vector at vertex point `i`.""" normals = self.polydata(True).GetPointData().GetNormals() return np.array(normals.GetTuple(i))
python
def normalAt(self, i): """Return the normal vector at vertex point `i`.""" normals = self.polydata(True).GetPointData().GetNormals() return np.array(normals.GetTuple(i))
[ "def", "normalAt", "(", "self", ",", "i", ")", ":", "normals", "=", "self", ".", "polydata", "(", "True", ")", ".", "GetPointData", "(", ")", ".", "GetNormals", "(", ")", "return", "np", ".", "array", "(", "normals", ".", "GetTuple", "(", "i", ")",...
Return the normal vector at vertex point `i`.
[ "Return", "the", "normal", "vector", "at", "vertex", "point", "i", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2033-L2036
train
210,449
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.normals
def normals(self, cells=False): """Retrieve vertex normals as a numpy array. :params bool cells: if `True` return cell normals. """ if cells: vtknormals = self.polydata(True).GetCellData().GetNormals() else: vtknormals = self.polydata(True).GetPointData().GetNormals() return vtk_to_numpy(vtknormals)
python
def normals(self, cells=False): """Retrieve vertex normals as a numpy array. :params bool cells: if `True` return cell normals. """ if cells: vtknormals = self.polydata(True).GetCellData().GetNormals() else: vtknormals = self.polydata(True).GetPointData().GetNormals() return vtk_to_numpy(vtknormals)
[ "def", "normals", "(", "self", ",", "cells", "=", "False", ")", ":", "if", "cells", ":", "vtknormals", "=", "self", ".", "polydata", "(", "True", ")", ".", "GetCellData", "(", ")", ".", "GetNormals", "(", ")", "else", ":", "vtknormals", "=", "self", ...
Retrieve vertex normals as a numpy array. :params bool cells: if `True` return cell normals.
[ "Retrieve", "vertex", "normals", "as", "a", "numpy", "array", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2038-L2047
train
210,450
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.polydata
def polydata(self, transformed=True): """ Returns the ``vtkPolyData`` of an ``Actor``. .. note:: If ``transformed=True`` returns a copy of polydata that corresponds to the current actor's position in space. .. hint:: |quadratic_morphing| |quadratic_morphing.py|_ """ if not transformed: if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly M = self.GetMatrix() if utils.isIdentity(M): if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly # if identity return the original polydata # otherwise make a copy that corresponds to # the actual position in space of the actor transform = vtk.vtkTransform() transform.SetMatrix(M) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(self.poly) tp.Update() return tp.GetOutput()
python
def polydata(self, transformed=True): """ Returns the ``vtkPolyData`` of an ``Actor``. .. note:: If ``transformed=True`` returns a copy of polydata that corresponds to the current actor's position in space. .. hint:: |quadratic_morphing| |quadratic_morphing.py|_ """ if not transformed: if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly M = self.GetMatrix() if utils.isIdentity(M): if not self.poly: self.poly = self.GetMapper().GetInput() # cache it for speed return self.poly # if identity return the original polydata # otherwise make a copy that corresponds to # the actual position in space of the actor transform = vtk.vtkTransform() transform.SetMatrix(M) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(transform) tp.SetInputData(self.poly) tp.Update() return tp.GetOutput()
[ "def", "polydata", "(", "self", ",", "transformed", "=", "True", ")", ":", "if", "not", "transformed", ":", "if", "not", "self", ".", "poly", ":", "self", ".", "poly", "=", "self", ".", "GetMapper", "(", ")", ".", "GetInput", "(", ")", "# cache it fo...
Returns the ``vtkPolyData`` of an ``Actor``. .. note:: If ``transformed=True`` returns a copy of polydata that corresponds to the current actor's position in space. .. hint:: |quadratic_morphing| |quadratic_morphing.py|_
[ "Returns", "the", "vtkPolyData", "of", "an", "Actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2049-L2076
train
210,451
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.move
def move(self, u_function): """ Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes. """ if self.mesh: self.u = u_function delta = [u_function(p) for p in self.mesh.coordinates()] movedpts = self.mesh.coordinates() + delta self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts)) self.poly.GetPoints().Modified() self.u_values = delta else: colors.printc("Warning: calling move() but actor.mesh is", self.mesh, c=3) return self
python
def move(self, u_function): """ Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes. """ if self.mesh: self.u = u_function delta = [u_function(p) for p in self.mesh.coordinates()] movedpts = self.mesh.coordinates() + delta self.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts)) self.poly.GetPoints().Modified() self.u_values = delta else: colors.printc("Warning: calling move() but actor.mesh is", self.mesh, c=3) return self
[ "def", "move", "(", "self", ",", "u_function", ")", ":", "if", "self", ".", "mesh", ":", "self", ".", "u", "=", "u_function", "delta", "=", "[", "u_function", "(", "p", ")", "for", "p", "in", "self", ".", "mesh", ".", "coordinates", "(", ")", "]"...
Move a mesh by using an external function which prescribes the displacement at any point in space. Useful for manipulating ``dolfin`` meshes.
[ "Move", "a", "mesh", "by", "using", "an", "external", "function", "which", "prescribes", "the", "displacement", "at", "any", "point", "in", "space", ".", "Useful", "for", "manipulating", "dolfin", "meshes", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2107-L2122
train
210,452
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.setTransform
def setTransform(self, T): """ Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified. """ if isinstance(T, vtk.vtkMatrix4x4): self.SetUserMatrix(T) else: try: self.SetUserTransform(T) except TypeError: colors.printc('~time Error in setTransform(): consider transformPolydata() instead.', c=1) return self
python
def setTransform(self, T): """ Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified. """ if isinstance(T, vtk.vtkMatrix4x4): self.SetUserMatrix(T) else: try: self.SetUserTransform(T) except TypeError: colors.printc('~time Error in setTransform(): consider transformPolydata() instead.', c=1) return self
[ "def", "setTransform", "(", "self", ",", "T", ")", ":", "if", "isinstance", "(", "T", ",", "vtk", ".", "vtkMatrix4x4", ")", ":", "self", ".", "SetUserMatrix", "(", "T", ")", "else", ":", "try", ":", "self", ".", "SetUserTransform", "(", "T", ")", "...
Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified.
[ "Transform", "actor", "position", "and", "orientation", "wrt", "to", "its", "polygonal", "mesh", "which", "remains", "unmodified", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2140-L2152
train
210,453
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.isInside
def isInside(self, point, tol=0.0001): """ Return True if point is inside a polydata closed surface. """ poly = self.polydata(True) points = vtk.vtkPoints() points.InsertNextPoint(point) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) sep.CheckSurfaceOff() sep.SetInputData(pointsPolydata) sep.SetSurfaceData(poly) sep.Update() return sep.IsInside(0)
python
def isInside(self, point, tol=0.0001): """ Return True if point is inside a polydata closed surface. """ poly = self.polydata(True) points = vtk.vtkPoints() points.InsertNextPoint(point) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) sep = vtk.vtkSelectEnclosedPoints() sep.SetTolerance(tol) sep.CheckSurfaceOff() sep.SetInputData(pointsPolydata) sep.SetSurfaceData(poly) sep.Update() return sep.IsInside(0)
[ "def", "isInside", "(", "self", ",", "point", ",", "tol", "=", "0.0001", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "points", "=", "vtk", ".", "vtkPoints", "(", ")", "points", ".", "InsertNextPoint", "(", "point", ")", "pointsP...
Return True if point is inside a polydata closed surface.
[ "Return", "True", "if", "point", "is", "inside", "a", "polydata", "closed", "surface", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2155-L2170
train
210,454
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.cellCenters
def cellCenters(self): """Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_ """ vcen = vtk.vtkCellCenters() vcen.SetInputData(self.polydata(True)) vcen.Update() return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData())
python
def cellCenters(self): """Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_ """ vcen = vtk.vtkCellCenters() vcen.SetInputData(self.polydata(True)) vcen.Update() return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData())
[ "def", "cellCenters", "(", "self", ")", ":", "vcen", "=", "vtk", ".", "vtkCellCenters", "(", ")", "vcen", ".", "SetInputData", "(", "self", ".", "polydata", "(", "True", ")", ")", "vcen", ".", "Update", "(", ")", "return", "vtk_to_numpy", "(", "vcen", ...
Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_
[ "Get", "the", "list", "of", "cell", "centers", "of", "the", "mesh", "surface", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2212-L2220
train
210,455
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.connectedVertices
def connectedVertices(self, index, returnIds=False): """Find all vertices connected to an input vertex specified by its index. :param bool returnIds: return vertex IDs instead of vertex coordinates. .. hint:: |connVtx| |connVtx.py|_ """ mesh = self.polydata() cellIdList = vtk.vtkIdList() mesh.GetPointCells(index, cellIdList) idxs = [] for i in range(cellIdList.GetNumberOfIds()): pointIdList = vtk.vtkIdList() mesh.GetCellPoints(cellIdList.GetId(i), pointIdList) for j in range(pointIdList.GetNumberOfIds()): idj = pointIdList.GetId(j) if idj == index: continue if idj in idxs: continue idxs.append(idj) if returnIds: return idxs else: trgp = [] for i in idxs: p = [0, 0, 0] mesh.GetPoints().GetPoint(i, p) trgp.append(p) return np.array(trgp)
python
def connectedVertices(self, index, returnIds=False): """Find all vertices connected to an input vertex specified by its index. :param bool returnIds: return vertex IDs instead of vertex coordinates. .. hint:: |connVtx| |connVtx.py|_ """ mesh = self.polydata() cellIdList = vtk.vtkIdList() mesh.GetPointCells(index, cellIdList) idxs = [] for i in range(cellIdList.GetNumberOfIds()): pointIdList = vtk.vtkIdList() mesh.GetCellPoints(cellIdList.GetId(i), pointIdList) for j in range(pointIdList.GetNumberOfIds()): idj = pointIdList.GetId(j) if idj == index: continue if idj in idxs: continue idxs.append(idj) if returnIds: return idxs else: trgp = [] for i in idxs: p = [0, 0, 0] mesh.GetPoints().GetPoint(i, p) trgp.append(p) return np.array(trgp)
[ "def", "connectedVertices", "(", "self", ",", "index", ",", "returnIds", "=", "False", ")", ":", "mesh", "=", "self", ".", "polydata", "(", ")", "cellIdList", "=", "vtk", ".", "vtkIdList", "(", ")", "mesh", ".", "GetPointCells", "(", "index", ",", "cel...
Find all vertices connected to an input vertex specified by its index. :param bool returnIds: return vertex IDs instead of vertex coordinates. .. hint:: |connVtx| |connVtx.py|_
[ "Find", "all", "vertices", "connected", "to", "an", "input", "vertex", "specified", "by", "its", "index", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2246-L2278
train
210,456
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.connectedCells
def connectedCells(self, index, returnIds=False): """Find all cellls connected to an input vertex specified by its index.""" # Find all cells connected to point index dpoly = self.polydata() cellPointIds = vtk.vtkIdList() dpoly.GetPointCells(index, cellPointIds) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) rids = [] for k in range(cellPointIds.GetNumberOfIds()): cid = cellPointIds.GetId(k) ids.InsertNextValue(cid) rids.append(int(cid)) if returnIds: return rids selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, dpoly) extractSelection.SetInputData(1, selection) extractSelection.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(extractSelection.GetOutput()) gf.Update() return Actor(gf.GetOutput()).lw(1)
python
def connectedCells(self, index, returnIds=False): """Find all cellls connected to an input vertex specified by its index.""" # Find all cells connected to point index dpoly = self.polydata() cellPointIds = vtk.vtkIdList() dpoly.GetPointCells(index, cellPointIds) ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) rids = [] for k in range(cellPointIds.GetNumberOfIds()): cid = cellPointIds.GetId(k) ids.InsertNextValue(cid) rids.append(int(cid)) if returnIds: return rids selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(ids) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, dpoly) extractSelection.SetInputData(1, selection) extractSelection.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(extractSelection.GetOutput()) gf.Update() return Actor(gf.GetOutput()).lw(1)
[ "def", "connectedCells", "(", "self", ",", "index", ",", "returnIds", "=", "False", ")", ":", "# Find all cells connected to point index", "dpoly", "=", "self", ".", "polydata", "(", ")", "cellPointIds", "=", "vtk", ".", "vtkIdList", "(", ")", "dpoly", ".", ...
Find all cellls connected to an input vertex specified by its index.
[ "Find", "all", "cellls", "connected", "to", "an", "input", "vertex", "specified", "by", "its", "index", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2281-L2312
train
210,457
marcomusy/vtkplotter
vtkplotter/actors.py
Actor.intersectWithLine
def intersectWithLine(self, p0, p1): """Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code-block:: python from vtkplotter import * s = Spring(alpha=0.2) pts = s.intersectWithLine([0,0,0], [1,0.1,0]) ln = Line([0,0,0], [1,0.1,0], c='blue') ps = Points(pts, r=10, c='r') show(s, ln, ps, bg='white') |intline| """ if not self.line_locator: line_locator = vtk.vtkOBBTree() line_locator.SetDataSet(self.polydata(True)) line_locator.BuildLocator() self.line_locator = line_locator intersectPoints = vtk.vtkPoints() intersection = [0, 0, 0] self.line_locator.IntersectWithLine(p0, p1, intersectPoints, None) pts = [] for i in range(intersectPoints.GetNumberOfPoints()): intersectPoints.GetPoint(i, intersection) pts.append(list(intersection)) return pts
python
def intersectWithLine(self, p0, p1): """Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code-block:: python from vtkplotter import * s = Spring(alpha=0.2) pts = s.intersectWithLine([0,0,0], [1,0.1,0]) ln = Line([0,0,0], [1,0.1,0], c='blue') ps = Points(pts, r=10, c='r') show(s, ln, ps, bg='white') |intline| """ if not self.line_locator: line_locator = vtk.vtkOBBTree() line_locator.SetDataSet(self.polydata(True)) line_locator.BuildLocator() self.line_locator = line_locator intersectPoints = vtk.vtkPoints() intersection = [0, 0, 0] self.line_locator.IntersectWithLine(p0, p1, intersectPoints, None) pts = [] for i in range(intersectPoints.GetNumberOfPoints()): intersectPoints.GetPoint(i, intersection) pts.append(list(intersection)) return pts
[ "def", "intersectWithLine", "(", "self", ",", "p0", ",", "p1", ")", ":", "if", "not", "self", ".", "line_locator", ":", "line_locator", "=", "vtk", ".", "vtkOBBTree", "(", ")", "line_locator", ".", "SetDataSet", "(", "self", ".", "polydata", "(", "True",...
Return the list of points intersecting the actor along the segment defined by two points `p0` and `p1`. :Example: .. code-block:: python from vtkplotter import * s = Spring(alpha=0.2) pts = s.intersectWithLine([0,0,0], [1,0.1,0]) ln = Line([0,0,0], [1,0.1,0], c='blue') ps = Points(pts, r=10, c='r') show(s, ln, ps, bg='white') |intline|
[ "Return", "the", "list", "of", "points", "intersecting", "the", "actor", "along", "the", "segment", "defined", "by", "two", "points", "p0", "and", "p1", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2315-L2344
train
210,458
marcomusy/vtkplotter
vtkplotter/actors.py
Assembly.getActors
def getActors(self): """Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``.""" cl = vtk.vtkPropCollection() self.GetActors(cl) self.actors = [] cl.InitTraversal() for i in range(self.GetNumberOfPaths()): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) if act.GetPickable(): self.actors.append(act) return self.actors
python
def getActors(self): """Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``.""" cl = vtk.vtkPropCollection() self.GetActors(cl) self.actors = [] cl.InitTraversal() for i in range(self.GetNumberOfPaths()): act = vtk.vtkActor.SafeDownCast(cl.GetNextProp()) if act.GetPickable(): self.actors.append(act) return self.actors
[ "def", "getActors", "(", "self", ")", ":", "cl", "=", "vtk", ".", "vtkPropCollection", "(", ")", "self", ".", "GetActors", "(", "cl", ")", "self", ".", "actors", "=", "[", "]", "cl", ".", "InitTraversal", "(", ")", "for", "i", "in", "range", "(", ...
Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``.
[ "Unpack", "a", "list", "of", "vtkActor", "objects", "from", "a", "vtkAssembly", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2387-L2397
train
210,459
marcomusy/vtkplotter
vtkplotter/actors.py
Assembly.diagonalSize
def diagonalSize(self): """Return the maximum diagonal size of the ``Actors`` of the ``Assembly``.""" szs = [a.diagonalSize() for a in self.actors] return np.max(szs)
python
def diagonalSize(self): """Return the maximum diagonal size of the ``Actors`` of the ``Assembly``.""" szs = [a.diagonalSize() for a in self.actors] return np.max(szs)
[ "def", "diagonalSize", "(", "self", ")", ":", "szs", "=", "[", "a", ".", "diagonalSize", "(", ")", "for", "a", "in", "self", ".", "actors", "]", "return", "np", ".", "max", "(", "szs", ")" ]
Return the maximum diagonal size of the ``Actors`` of the ``Assembly``.
[ "Return", "the", "maximum", "diagonal", "size", "of", "the", "Actors", "of", "the", "Assembly", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2403-L2406
train
210,460
marcomusy/vtkplotter
vtkplotter/actors.py
Volume.threshold
def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """ th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) elif vmin is not None: th.ThresholdByUpper(vmin) elif vmax is not None: th.ThresholdByLower(vmax) if replaceWith: th.ReplaceOutOn() th.SetOutValue(replaceWith) th.Update() self.image = th.GetOutput() self.mapper.SetInputData(self.image) self.mapper.Modified() return self
python
def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """ th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) elif vmin is not None: th.ThresholdByUpper(vmin) elif vmax is not None: th.ThresholdByLower(vmax) if replaceWith: th.ReplaceOutOn() th.SetOutValue(replaceWith) th.Update() self.image = th.GetOutput() self.mapper.SetInputData(self.image) self.mapper.Modified() return self
[ "def", "threshold", "(", "self", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "replaceWith", "=", "None", ")", ":", "th", "=", "vtk", ".", "vtkImageThreshold", "(", ")", "th", ".", "SetInputData", "(", "self", ".", "image", ")", "if", "...
Binary or continuous volume thresholding.
[ "Binary", "or", "continuous", "volume", "thresholding", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L2555-L2577
train
210,461
marcomusy/vtkplotter
vtkplotter/vtkio.py
loadOFF
def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None): """Read OFF file format.""" if not os.path.exists(filename): colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1) return None f = open(filename, "r") lines = f.readlines() f.close() vertices = [] faces = [] NumberOfVertices = None i = -1 for text in lines: if len(text) == 0: continue if text == '\n': continue if "#" in text: continue if "OFF" in text: continue ts = text.split() n = len(ts) if not NumberOfVertices and n > 1: NumberOfVertices, NumberOfFaces = int(ts[0]), int(ts[1]) continue i += 1 if i < NumberOfVertices and n == 3: x, y, z = float(ts[0]), float(ts[1]), float(ts[2]) vertices.append([x, y, z]) ids = [] if NumberOfVertices <= i < (NumberOfVertices + NumberOfFaces + 1) and n > 2: ids += [int(x) for x in ts[1:]] faces.append(ids) return Actor(buildPolyData(vertices, faces), c, alpha, wire, bc)
python
def loadOFF(filename, c="gold", alpha=1, wire=False, bc=None): """Read OFF file format.""" if not os.path.exists(filename): colors.printc("~noentry Error in loadOFF: Cannot find", filename, c=1) return None f = open(filename, "r") lines = f.readlines() f.close() vertices = [] faces = [] NumberOfVertices = None i = -1 for text in lines: if len(text) == 0: continue if text == '\n': continue if "#" in text: continue if "OFF" in text: continue ts = text.split() n = len(ts) if not NumberOfVertices and n > 1: NumberOfVertices, NumberOfFaces = int(ts[0]), int(ts[1]) continue i += 1 if i < NumberOfVertices and n == 3: x, y, z = float(ts[0]), float(ts[1]), float(ts[2]) vertices.append([x, y, z]) ids = [] if NumberOfVertices <= i < (NumberOfVertices + NumberOfFaces + 1) and n > 2: ids += [int(x) for x in ts[1:]] faces.append(ids) return Actor(buildPolyData(vertices, faces), c, alpha, wire, bc)
[ "def", "loadOFF", "(", "filename", ",", "c", "=", "\"gold\"", ",", "alpha", "=", "1", ",", "wire", "=", "False", ",", "bc", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "colors", ".", "printc", ...
Read OFF file format.
[ "Read", "OFF", "file", "format", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L313-L354
train
210,462
marcomusy/vtkplotter
vtkplotter/vtkio.py
loadImageData
def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file.""" if not os.path.isfile(filename): colors.printc("~noentry File not found:", filename, c=1) return None if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in filename.lower(): reader = vtk.vtkSLCReader() if not reader.CanReadFile(filename): colors.printc("~prohibited Sorry bad slc file " + filename, c=1) exit(1) elif ".vti" in filename.lower(): reader = vtk.vtkXMLImageDataReader() elif ".mhd" in filename.lower(): reader = vtk.vtkMetaImageReader() reader.SetFileName(filename) reader.Update() image = reader.GetOutput() if len(spacing) == 3: image.SetSpacing(spacing[0], spacing[1], spacing[2]) return image
python
def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file.""" if not os.path.isfile(filename): colors.printc("~noentry File not found:", filename, c=1) return None if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in filename.lower(): reader = vtk.vtkSLCReader() if not reader.CanReadFile(filename): colors.printc("~prohibited Sorry bad slc file " + filename, c=1) exit(1) elif ".vti" in filename.lower(): reader = vtk.vtkXMLImageDataReader() elif ".mhd" in filename.lower(): reader = vtk.vtkMetaImageReader() reader.SetFileName(filename) reader.Update() image = reader.GetOutput() if len(spacing) == 3: image.SetSpacing(spacing[0], spacing[1], spacing[2]) return image
[ "def", "loadImageData", "(", "filename", ",", "spacing", "=", "(", ")", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "colors", ".", "printc", "(", "\"~noentry File not found:\"", ",", "filename", ",", "c", "=", "1...
Read and return a ``vtkImageData`` object from file.
[ "Read", "and", "return", "a", "vtkImageData", "object", "from", "file", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L508-L530
train
210,463
marcomusy/vtkplotter
vtkplotter/vtkio.py
write
def write(objct, fileoutput, binary=True): """ Write 3D object to file. Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp. """ obj = objct if isinstance(obj, Actor): obj = objct.polydata(True) elif isinstance(obj, vtk.vtkActor): obj = objct.GetMapper().GetInput() fr = fileoutput.lower() if ".vtk" in fr: w = vtk.vtkPolyDataWriter() elif ".ply" in fr: w = vtk.vtkPLYWriter() elif ".stl" in fr: w = vtk.vtkSTLWriter() elif ".vtp" in fr: w = vtk.vtkXMLPolyDataWriter() elif ".vtm" in fr: g = vtk.vtkMultiBlockDataGroupFilter() for ob in objct: g.AddInputData(ob) g.Update() mb = g.GetOutputDataObject(0) wri = vtk.vtkXMLMultiBlockDataWriter() wri.SetInputData(mb) wri.SetFileName(fileoutput) wri.Write() return mb elif ".xyz" in fr: w = vtk.vtkSimplePointsWriter() elif ".byu" in fr or fr.endswith(".g"): w = vtk.vtkBYUWriter() elif ".obj" in fr: w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace(".obj", "")) colors.printc("~target Please use write(vp.window)", c=3) w.SetInputData(obj) w.Update() colors.printc("~save Saved file: " + fileoutput, c="g") return objct elif ".tif" in fr: w = vtk.vtkTIFFWriter() w.SetFileDimensionality(len(obj.GetDimensions())) elif ".vti" in fr: w = vtk.vtkXMLImageDataWriter() elif ".png" in fr: w = vtk.vtkPNGWriter() elif ".jpg" in fr: w = vtk.vtkJPEGWriter() elif ".bmp" in fr: w = vtk.vtkBMPWriter() else: colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r") return objct try: if not ".tif" in fr and not ".vti" in fr: if binary and not ".tif" in fr and not ".vti" in fr: w.SetFileTypeToBinary() else: w.SetFileTypeToASCII() w.SetInputData(obj) w.SetFileName(fileoutput) w.Write() colors.printc("~save Saved file: " + fileoutput, c="g") except Exception as e: colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r") return objct
python
def write(objct, fileoutput, binary=True): """ Write 3D object to file. Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp. """ obj = objct if isinstance(obj, Actor): obj = objct.polydata(True) elif isinstance(obj, vtk.vtkActor): obj = objct.GetMapper().GetInput() fr = fileoutput.lower() if ".vtk" in fr: w = vtk.vtkPolyDataWriter() elif ".ply" in fr: w = vtk.vtkPLYWriter() elif ".stl" in fr: w = vtk.vtkSTLWriter() elif ".vtp" in fr: w = vtk.vtkXMLPolyDataWriter() elif ".vtm" in fr: g = vtk.vtkMultiBlockDataGroupFilter() for ob in objct: g.AddInputData(ob) g.Update() mb = g.GetOutputDataObject(0) wri = vtk.vtkXMLMultiBlockDataWriter() wri.SetInputData(mb) wri.SetFileName(fileoutput) wri.Write() return mb elif ".xyz" in fr: w = vtk.vtkSimplePointsWriter() elif ".byu" in fr or fr.endswith(".g"): w = vtk.vtkBYUWriter() elif ".obj" in fr: w = vtk.vtkOBJExporter() w.SetFilePrefix(fileoutput.replace(".obj", "")) colors.printc("~target Please use write(vp.window)", c=3) w.SetInputData(obj) w.Update() colors.printc("~save Saved file: " + fileoutput, c="g") return objct elif ".tif" in fr: w = vtk.vtkTIFFWriter() w.SetFileDimensionality(len(obj.GetDimensions())) elif ".vti" in fr: w = vtk.vtkXMLImageDataWriter() elif ".png" in fr: w = vtk.vtkPNGWriter() elif ".jpg" in fr: w = vtk.vtkJPEGWriter() elif ".bmp" in fr: w = vtk.vtkBMPWriter() else: colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r") return objct try: if not ".tif" in fr and not ".vti" in fr: if binary and not ".tif" in fr and not ".vti" in fr: w.SetFileTypeToBinary() else: w.SetFileTypeToASCII() w.SetInputData(obj) w.SetFileName(fileoutput) w.Write() colors.printc("~save Saved file: " + fileoutput, c="g") except Exception as e: colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r") return objct
[ "def", "write", "(", "objct", ",", "fileoutput", ",", "binary", "=", "True", ")", ":", "obj", "=", "objct", "if", "isinstance", "(", "obj", ",", "Actor", ")", ":", "obj", "=", "objct", ".", "polydata", "(", "True", ")", "elif", "isinstance", "(", "...
Write 3D object to file. Possile extensions are: - vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp.
[ "Write", "3D", "object", "to", "file", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L560-L632
train
210,464
marcomusy/vtkplotter
vtkplotter/vtkio.py
convertNeutral2Xml
def convertNeutral2Xml(infile, outfile=None): """Convert Neutral file format to Dolfin XML.""" f = open(infile, "r") lines = f.readlines() f.close() ncoords = int(lines[0]) fdolf_coords = [] for i in range(1, ncoords + 1): x, y, z = lines[i].split() fdolf_coords.append([float(x), float(y), float(z)]) ntets = int(lines[ncoords + 1]) idolf_tets = [] for i in range(ncoords + 2, ncoords + ntets + 2): text = lines[i].split() v0, v1, v2, v3 = text[1], text[2], text[3], text[4] idolf_tets.append([int(v0) - 1, int(v1) - 1, int(v2) - 1, int(v3) - 1]) if outfile: # write dolfin xml outF = open(outfile, "w") outF.write('<?xml version="1.0" encoding="UTF-8"?>\n') outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n') outF.write(' <mesh celltype="tetrahedron" dim="3">\n') outF.write(' <vertices size="' + str(ncoords) + '">\n') for i in range(ncoords): x, y, z = fdolf_coords[i] outF.write(' <vertex index="'+str(i) + '" x="'+str(x)+'" y="'+str(y)+'" z="'+str(z)+'"/>\n') outF.write(' </vertices>\n') outF.write(' <cells size="' + str(ntets) + '">\n') for i in range(ntets): v0, v1, v2, v3 = idolf_tets[i] outF.write(' <tetrahedron index="'+str(i) + '" v0="'+str(v0)+'" v1="'+str(v1)+'" v2="'+str(v2)+'" v3="'+str(v3)+'"/>\n') outF.write(' </cells>\n') outF.write(" </mesh>\n") outF.write("</dolfin>\n") outF.close() return fdolf_coords, idolf_tets
python
def convertNeutral2Xml(infile, outfile=None): """Convert Neutral file format to Dolfin XML.""" f = open(infile, "r") lines = f.readlines() f.close() ncoords = int(lines[0]) fdolf_coords = [] for i in range(1, ncoords + 1): x, y, z = lines[i].split() fdolf_coords.append([float(x), float(y), float(z)]) ntets = int(lines[ncoords + 1]) idolf_tets = [] for i in range(ncoords + 2, ncoords + ntets + 2): text = lines[i].split() v0, v1, v2, v3 = text[1], text[2], text[3], text[4] idolf_tets.append([int(v0) - 1, int(v1) - 1, int(v2) - 1, int(v3) - 1]) if outfile: # write dolfin xml outF = open(outfile, "w") outF.write('<?xml version="1.0" encoding="UTF-8"?>\n') outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n') outF.write(' <mesh celltype="tetrahedron" dim="3">\n') outF.write(' <vertices size="' + str(ncoords) + '">\n') for i in range(ncoords): x, y, z = fdolf_coords[i] outF.write(' <vertex index="'+str(i) + '" x="'+str(x)+'" y="'+str(y)+'" z="'+str(z)+'"/>\n') outF.write(' </vertices>\n') outF.write(' <cells size="' + str(ntets) + '">\n') for i in range(ntets): v0, v1, v2, v3 = idolf_tets[i] outF.write(' <tetrahedron index="'+str(i) + '" v0="'+str(v0)+'" v1="'+str(v1)+'" v2="'+str(v2)+'" v3="'+str(v3)+'"/>\n') outF.write(' </cells>\n') outF.write(" </mesh>\n") outF.write("</dolfin>\n") outF.close() return fdolf_coords, idolf_tets
[ "def", "convertNeutral2Xml", "(", "infile", ",", "outfile", "=", "None", ")", ":", "f", "=", "open", "(", "infile", ",", "\"r\"", ")", "lines", "=", "f", ".", "readlines", "(", ")", "f", ".", "close", "(", ")", "ncoords", "=", "int", "(", "lines", ...
Convert Neutral file format to Dolfin XML.
[ "Convert", "Neutral", "file", "format", "to", "Dolfin", "XML", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L635-L678
train
210,465
marcomusy/vtkplotter
vtkplotter/vtkio.py
screenshot
def screenshot(filename="screenshot.png"): """ Save a screenshot of the current rendering window. """ if not settings.plotter_instance.window: colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1) return w2if = vtk.vtkWindowToImageFilter() w2if.ShouldRerenderOff() w2if.SetInput(settings.plotter_instance.window) w2if.ReadFrontBufferOff() # read from the back buffer w2if.Update() pngwriter = vtk.vtkPNGWriter() pngwriter.SetFileName(filename) pngwriter.SetInputConnection(w2if.GetOutputPort()) pngwriter.Write()
python
def screenshot(filename="screenshot.png"): """ Save a screenshot of the current rendering window. """ if not settings.plotter_instance.window: colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1) return w2if = vtk.vtkWindowToImageFilter() w2if.ShouldRerenderOff() w2if.SetInput(settings.plotter_instance.window) w2if.ReadFrontBufferOff() # read from the back buffer w2if.Update() pngwriter = vtk.vtkPNGWriter() pngwriter.SetFileName(filename) pngwriter.SetInputConnection(w2if.GetOutputPort()) pngwriter.Write()
[ "def", "screenshot", "(", "filename", "=", "\"screenshot.png\"", ")", ":", "if", "not", "settings", ".", "plotter_instance", ".", "window", ":", "colors", ".", "printc", "(", "'~bomb screenshot(): Rendering window is not present, skip.'", ",", "c", "=", "1", ")", ...
Save a screenshot of the current rendering window.
[ "Save", "a", "screenshot", "of", "the", "current", "rendering", "window", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L793-L808
train
210,466
marcomusy/vtkplotter
vtkplotter/vtkio.py
Video.addFrame
def addFrame(self): """Add frame to current video.""" fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png" screenshot(fr) self.frames.append(fr)
python
def addFrame(self): """Add frame to current video.""" fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png" screenshot(fr) self.frames.append(fr)
[ "def", "addFrame", "(", "self", ")", ":", "fr", "=", "\"/tmp/vpvid/\"", "+", "str", "(", "len", "(", "self", ".", "frames", ")", ")", "+", "\".png\"", "screenshot", "(", "fr", ")", "self", ".", "frames", ".", "append", "(", "fr", ")" ]
Add frame to current video.
[ "Add", "frame", "to", "current", "video", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L837-L841
train
210,467
marcomusy/vtkplotter
vtkplotter/vtkio.py
Video.pause
def pause(self, pause=0): """Insert a `pause`, in seconds.""" fr = self.frames[-1] n = int(self.fps * pause) for i in range(n): fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png" self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2))
python
def pause(self, pause=0): """Insert a `pause`, in seconds.""" fr = self.frames[-1] n = int(self.fps * pause) for i in range(n): fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png" self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2))
[ "def", "pause", "(", "self", ",", "pause", "=", "0", ")", ":", "fr", "=", "self", ".", "frames", "[", "-", "1", "]", "n", "=", "int", "(", "self", ".", "fps", "*", "pause", ")", "for", "i", "in", "range", "(", "n", ")", ":", "fr2", "=", "...
Insert a `pause`, in seconds.
[ "Insert", "a", "pause", "in", "seconds", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L843-L850
train
210,468
marcomusy/vtkplotter
vtkplotter/vtkio.py
Video.close
def close(self): """Render the video and write to file.""" if self.duration: _fps = len(self.frames) / float(self.duration) colors.printc("Recalculated video FPS to", round(_fps, 3), c="yellow") else: _fps = int(_fps) self.name = self.name.split('.')[0]+'.mp4' out = os.system("ffmpeg -loglevel panic -y -r " + str(_fps) + " -i /tmp/vpvid/%01d.png "+self.name) if out: colors.printc("ffmpeg returning error", c=1) colors.printc("~save Video saved as", self.name, c="green") return
python
def close(self): """Render the video and write to file.""" if self.duration: _fps = len(self.frames) / float(self.duration) colors.printc("Recalculated video FPS to", round(_fps, 3), c="yellow") else: _fps = int(_fps) self.name = self.name.split('.')[0]+'.mp4' out = os.system("ffmpeg -loglevel panic -y -r " + str(_fps) + " -i /tmp/vpvid/%01d.png "+self.name) if out: colors.printc("ffmpeg returning error", c=1) colors.printc("~save Video saved as", self.name, c="green") return
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "duration", ":", "_fps", "=", "len", "(", "self", ".", "frames", ")", "/", "float", "(", "self", ".", "duration", ")", "colors", ".", "printc", "(", "\"Recalculated video FPS to\"", ",", "round"...
Render the video and write to file.
[ "Render", "the", "video", "and", "write", "to", "file", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L852-L865
train
210,469
marcomusy/vtkplotter
examples/other/dolfin/elastodynamics.py
update_fields
def update_fields(u, u_old, v_old, a_old): """Update fields at the end of each time step.""" # Get vectors (references) u_vec, u0_vec = u.vector(), u_old.vector() v0_vec, a0_vec = v_old.vector(), a_old.vector() # use update functions using vector arguments a_vec = update_a(u_vec, u0_vec, v0_vec, a0_vec, ufl=False) v_vec = update_v(a_vec, u0_vec, v0_vec, a0_vec, ufl=False) # Update (u_old <- u) v_old.vector()[:], a_old.vector()[:] = v_vec, a_vec u_old.vector()[:] = u.vector()
python
def update_fields(u, u_old, v_old, a_old): """Update fields at the end of each time step.""" # Get vectors (references) u_vec, u0_vec = u.vector(), u_old.vector() v0_vec, a0_vec = v_old.vector(), a_old.vector() # use update functions using vector arguments a_vec = update_a(u_vec, u0_vec, v0_vec, a0_vec, ufl=False) v_vec = update_v(a_vec, u0_vec, v0_vec, a0_vec, ufl=False) # Update (u_old <- u) v_old.vector()[:], a_old.vector()[:] = v_vec, a_vec u_old.vector()[:] = u.vector()
[ "def", "update_fields", "(", "u", ",", "u_old", ",", "v_old", ",", "a_old", ")", ":", "# Get vectors (references)", "u_vec", ",", "u0_vec", "=", "u", ".", "vector", "(", ")", ",", "u_old", ".", "vector", "(", ")", "v0_vec", ",", "a0_vec", "=", "v_old",...
Update fields at the end of each time step.
[ "Update", "fields", "at", "the", "end", "of", "each", "time", "step", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/examples/other/dolfin/elastodynamics.py#L122-L135
train
210,470
marcomusy/vtkplotter
examples/other/dolfin/elastodynamics.py
local_project
def local_project(v, V, u=None): """Element-wise projection using LocalSolver""" dv = TrialFunction(V) v_ = TestFunction(V) a_proj = inner(dv, v_)*dx b_proj = inner(v, v_)*dx solver = LocalSolver(a_proj, b_proj) solver.factorize() if u is None: u = Function(V) solver.solve_local_rhs(u) return u else: solver.solve_local_rhs(u) return
python
def local_project(v, V, u=None): """Element-wise projection using LocalSolver""" dv = TrialFunction(V) v_ = TestFunction(V) a_proj = inner(dv, v_)*dx b_proj = inner(v, v_)*dx solver = LocalSolver(a_proj, b_proj) solver.factorize() if u is None: u = Function(V) solver.solve_local_rhs(u) return u else: solver.solve_local_rhs(u) return
[ "def", "local_project", "(", "v", ",", "V", ",", "u", "=", "None", ")", ":", "dv", "=", "TrialFunction", "(", "V", ")", "v_", "=", "TestFunction", "(", "V", ")", "a_proj", "=", "inner", "(", "dv", ",", "v_", ")", "*", "dx", "b_proj", "=", "inne...
Element-wise projection using LocalSolver
[ "Element", "-", "wise", "projection", "using", "LocalSolver" ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/examples/other/dolfin/elastodynamics.py#L167-L181
train
210,471
marcomusy/vtkplotter
vtkplotter/shapes.py
Point
def Point(pos=(0, 0, 0), r=12, c="red", alpha=1): """Create a simple point actor.""" if len(pos) == 2: pos = (pos[0], pos[1], 0) actor = Points([pos], r, c, alpha) return actor
python
def Point(pos=(0, 0, 0), r=12, c="red", alpha=1): """Create a simple point actor.""" if len(pos) == 2: pos = (pos[0], pos[1], 0) actor = Points([pos], r, c, alpha) return actor
[ "def", "Point", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "r", "=", "12", ",", "c", "=", "\"red\"", ",", "alpha", "=", "1", ")", ":", "if", "len", "(", "pos", ")", "==", "2", ":", "pos", "=", "(", "pos", "[", "0", "]", ...
Create a simple point actor.
[ "Create", "a", "simple", "point", "actor", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L53-L58
train
210,472
marcomusy/vtkplotter
vtkplotter/shapes.py
Tube
def Tube(points, r=1, c="r", alpha=1, res=12): """Build a tube along the line defined by a set of points. :param r: constant radius or list of radii. :type r: float, list :param c: constant color or list of colors for each point. :type c: float, list .. hint:: |ribbon| |ribbon.py|_ |tube| |tube.py|_ """ ppoints = vtk.vtkPoints() # Generate the polyline ppoints.SetData(numpy_to_vtk(points, deep=True)) lines = vtk.vtkCellArray() lines.InsertNextCell(len(points)) for i in range(len(points)): lines.InsertCellPoint(i) polyln = vtk.vtkPolyData() polyln.SetPoints(ppoints) polyln.SetLines(lines) tuf = vtk.vtkTubeFilter() tuf.CappingOn() tuf.SetNumberOfSides(res) tuf.SetInputData(polyln) if utils.isSequence(r): arr = numpy_to_vtk(np.ascontiguousarray(r), deep=True) arr.SetName("TubeRadius") polyln.GetPointData().AddArray(arr) polyln.GetPointData().SetActiveScalars("TubeRadius") tuf.SetVaryRadiusToVaryRadiusByAbsoluteScalar() else: tuf.SetRadius(r) usingColScals = False if utils.isSequence(c) and len(c) != 3: usingColScals = True cc = vtk.vtkUnsignedCharArray() cc.SetName("TubeColors") cc.SetNumberOfComponents(3) cc.SetNumberOfTuples(len(c)) for i, ic in enumerate(c): r, g, b = colors.getColor(ic) cc.InsertTuple3(i, int(255 * r), int(255 * g), int(255 * b)) polyln.GetPointData().AddArray(cc) c = None tuf.Update() polytu = tuf.GetOutput() actor = Actor(polytu, c=c, alpha=alpha, computeNormals=0) actor.phong() if usingColScals: actor.mapper.SetScalarModeToUsePointFieldData() actor.mapper.ScalarVisibilityOn() actor.mapper.SelectColorArray("TubeColors") actor.mapper.Modified() actor.base = np.array(points[0]) actor.top = np.array(points[-1]) settings.collectable_actors.append(actor) return actor
python
def Tube(points, r=1, c="r", alpha=1, res=12): """Build a tube along the line defined by a set of points. :param r: constant radius or list of radii. :type r: float, list :param c: constant color or list of colors for each point. :type c: float, list .. hint:: |ribbon| |ribbon.py|_ |tube| |tube.py|_ """ ppoints = vtk.vtkPoints() # Generate the polyline ppoints.SetData(numpy_to_vtk(points, deep=True)) lines = vtk.vtkCellArray() lines.InsertNextCell(len(points)) for i in range(len(points)): lines.InsertCellPoint(i) polyln = vtk.vtkPolyData() polyln.SetPoints(ppoints) polyln.SetLines(lines) tuf = vtk.vtkTubeFilter() tuf.CappingOn() tuf.SetNumberOfSides(res) tuf.SetInputData(polyln) if utils.isSequence(r): arr = numpy_to_vtk(np.ascontiguousarray(r), deep=True) arr.SetName("TubeRadius") polyln.GetPointData().AddArray(arr) polyln.GetPointData().SetActiveScalars("TubeRadius") tuf.SetVaryRadiusToVaryRadiusByAbsoluteScalar() else: tuf.SetRadius(r) usingColScals = False if utils.isSequence(c) and len(c) != 3: usingColScals = True cc = vtk.vtkUnsignedCharArray() cc.SetName("TubeColors") cc.SetNumberOfComponents(3) cc.SetNumberOfTuples(len(c)) for i, ic in enumerate(c): r, g, b = colors.getColor(ic) cc.InsertTuple3(i, int(255 * r), int(255 * g), int(255 * b)) polyln.GetPointData().AddArray(cc) c = None tuf.Update() polytu = tuf.GetOutput() actor = Actor(polytu, c=c, alpha=alpha, computeNormals=0) actor.phong() if usingColScals: actor.mapper.SetScalarModeToUsePointFieldData() actor.mapper.ScalarVisibilityOn() actor.mapper.SelectColorArray("TubeColors") actor.mapper.Modified() actor.base = np.array(points[0]) actor.top = np.array(points[-1]) settings.collectable_actors.append(actor) return actor
[ "def", "Tube", "(", "points", ",", "r", "=", "1", ",", "c", "=", "\"r\"", ",", "alpha", "=", "1", ",", "res", "=", "12", ")", ":", "ppoints", "=", "vtk", ".", "vtkPoints", "(", ")", "# Generate the polyline", "ppoints", ".", "SetData", "(", "numpy_...
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|_
[ "Build", "a", "tube", "along", "the", "line", "defined", "by", "a", "set", "of", "points", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L336-L398
train
210,473
marcomusy/vtkplotter
vtkplotter/shapes.py
Ribbon
def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.vtkPoints() # Generate the polyline1 ppoints1.SetData(numpy_to_vtk(line1, deep=True)) lines1 = vtk.vtkCellArray() lines1.InsertNextCell(len(line1)) for i in range(len(line1)): lines1.InsertCellPoint(i) poly1 = vtk.vtkPolyData() poly1.SetPoints(ppoints1) poly1.SetLines(lines1) ppoints2 = vtk.vtkPoints() # Generate the polyline2 ppoints2.SetData(numpy_to_vtk(line2, deep=True)) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(len(line2)) for i in range(len(line2)): lines2.InsertCellPoint(i) poly2 = vtk.vtkPolyData() poly2.SetPoints(ppoints2) poly2.SetLines(lines2) # build the lines lines1 = vtk.vtkCellArray() lines1.InsertNextCell(poly1.GetNumberOfPoints()) for i in range(poly1.GetNumberOfPoints()): lines1.InsertCellPoint(i) polygon1 = vtk.vtkPolyData() polygon1.SetPoints(ppoints1) polygon1.SetLines(lines1) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(poly2.GetNumberOfPoints()) for i in range(poly2.GetNumberOfPoints()): lines2.InsertCellPoint(i) polygon2 = vtk.vtkPolyData() polygon2.SetPoints(ppoints2) polygon2.SetLines(lines2) mergedPolyData = vtk.vtkAppendPolyData() mergedPolyData.AddInputData(polygon1) mergedPolyData.AddInputData(polygon2) mergedPolyData.Update() rsf = vtk.vtkRuledSurfaceFilter() rsf.CloseSurfaceOff() rsf.SetRuledModeToResample() rsf.SetResolution(res[0], res[1]) rsf.SetInputData(mergedPolyData.GetOutput()) rsf.Update() actor = Actor(rsf.GetOutput(), c=c, alpha=alpha) settings.collectable_actors.append(actor) return actor
python
def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)): """Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() ppoints1 = vtk.vtkPoints() # Generate the polyline1 ppoints1.SetData(numpy_to_vtk(line1, deep=True)) lines1 = vtk.vtkCellArray() lines1.InsertNextCell(len(line1)) for i in range(len(line1)): lines1.InsertCellPoint(i) poly1 = vtk.vtkPolyData() poly1.SetPoints(ppoints1) poly1.SetLines(lines1) ppoints2 = vtk.vtkPoints() # Generate the polyline2 ppoints2.SetData(numpy_to_vtk(line2, deep=True)) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(len(line2)) for i in range(len(line2)): lines2.InsertCellPoint(i) poly2 = vtk.vtkPolyData() poly2.SetPoints(ppoints2) poly2.SetLines(lines2) # build the lines lines1 = vtk.vtkCellArray() lines1.InsertNextCell(poly1.GetNumberOfPoints()) for i in range(poly1.GetNumberOfPoints()): lines1.InsertCellPoint(i) polygon1 = vtk.vtkPolyData() polygon1.SetPoints(ppoints1) polygon1.SetLines(lines1) lines2 = vtk.vtkCellArray() lines2.InsertNextCell(poly2.GetNumberOfPoints()) for i in range(poly2.GetNumberOfPoints()): lines2.InsertCellPoint(i) polygon2 = vtk.vtkPolyData() polygon2.SetPoints(ppoints2) polygon2.SetLines(lines2) mergedPolyData = vtk.vtkAppendPolyData() mergedPolyData.AddInputData(polygon1) mergedPolyData.AddInputData(polygon2) mergedPolyData.Update() rsf = vtk.vtkRuledSurfaceFilter() rsf.CloseSurfaceOff() rsf.SetRuledModeToResample() rsf.SetResolution(res[0], res[1]) rsf.SetInputData(mergedPolyData.GetOutput()) rsf.Update() actor = Actor(rsf.GetOutput(), c=c, alpha=alpha) settings.collectable_actors.append(actor) return actor
[ "def", "Ribbon", "(", "line1", ",", "line2", ",", "c", "=", "\"m\"", ",", "alpha", "=", "1", ",", "res", "=", "(", "200", ",", "5", ")", ")", ":", "if", "isinstance", "(", "line1", ",", "Actor", ")", ":", "line1", "=", "line1", ".", "coordinate...
Connect two lines to generate the surface inbetween. .. hint:: |ribbon| |ribbon.py|_
[ "Connect", "two", "lines", "to", "generate", "the", "surface", "inbetween", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L401-L463
train
210,474
marcomusy/vtkplotter
vtkplotter/shapes.py
FlatArrow
def FlatArrow(line1, line2, c="m", alpha=1, tipSize=1, tipWidth=1): """Build a 2D arrow in 3D space by joining two close lines. .. hint:: |flatarrow| |flatarrow.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() sm1, sm2 = np.array(line1[-1]), np.array(line2[-1]) v = (sm1-sm2)/3*tipWidth p1 = sm1+v p2 = sm2-v pm1 = (sm1+sm2)/2 pm2 = (np.array(line1[-2])+np.array(line2[-2]))/2 pm12 = pm1-pm2 tip = pm12/np.linalg.norm(pm12)*np.linalg.norm(v)*3*tipSize/tipWidth + pm1 line1.append(p1) line1.append(tip) line2.append(p2) line2.append(tip) resm = max(100, len(line1)) actor = Ribbon(line1, line2, alpha=alpha, c=c, res=(resm, 1)).phong() settings.collectable_actors.pop() settings.collectable_actors.append(actor) return actor
python
def FlatArrow(line1, line2, c="m", alpha=1, tipSize=1, tipWidth=1): """Build a 2D arrow in 3D space by joining two close lines. .. hint:: |flatarrow| |flatarrow.py|_ """ if isinstance(line1, Actor): line1 = line1.coordinates() if isinstance(line2, Actor): line2 = line2.coordinates() sm1, sm2 = np.array(line1[-1]), np.array(line2[-1]) v = (sm1-sm2)/3*tipWidth p1 = sm1+v p2 = sm2-v pm1 = (sm1+sm2)/2 pm2 = (np.array(line1[-2])+np.array(line2[-2]))/2 pm12 = pm1-pm2 tip = pm12/np.linalg.norm(pm12)*np.linalg.norm(v)*3*tipSize/tipWidth + pm1 line1.append(p1) line1.append(tip) line2.append(p2) line2.append(tip) resm = max(100, len(line1)) actor = Ribbon(line1, line2, alpha=alpha, c=c, res=(resm, 1)).phong() settings.collectable_actors.pop() settings.collectable_actors.append(actor) return actor
[ "def", "FlatArrow", "(", "line1", ",", "line2", ",", "c", "=", "\"m\"", ",", "alpha", "=", "1", ",", "tipSize", "=", "1", ",", "tipWidth", "=", "1", ")", ":", "if", "isinstance", "(", "line1", ",", "Actor", ")", ":", "line1", "=", "line1", ".", ...
Build a 2D arrow in 3D space by joining two close lines. .. hint:: |flatarrow| |flatarrow.py|_
[ "Build", "a", "2D", "arrow", "in", "3D", "space", "by", "joining", "two", "close", "lines", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L466-L495
train
210,475
marcomusy/vtkplotter
vtkplotter/shapes.py
Polygon
def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral", bc="darkgreen", lw=1, alpha=1, followcam=False): """ Build a 2D polygon of `nsides` of radius `r` oriented as `normal`. :param followcam: if `True` the text will auto-orient itself to the active camera. A ``vtkCamera`` object can also be passed. :type followcam: bool, vtkCamera |Polygon| """ ps = vtk.vtkRegularPolygonSource() ps.SetNumberOfSides(nsides) ps.SetRadius(r) ps.SetNormal(-np.array(normal)) ps.Update() tf = vtk.vtkTriangleFilter() tf.SetInputConnection(ps.GetOutputPort()) tf.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tf.GetOutputPort()) if followcam: actor = vtk.vtkFollower() if isinstance(followcam, vtk.vtkCamera): actor.SetCamera(followcam) else: actor.SetCamera(settings.plotter_instance.camera) else: actor = Actor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Polygon(pos=(0, 0, 0), normal=(0, 0, 1), nsides=6, r=1, c="coral", bc="darkgreen", lw=1, alpha=1, followcam=False): """ Build a 2D polygon of `nsides` of radius `r` oriented as `normal`. :param followcam: if `True` the text will auto-orient itself to the active camera. A ``vtkCamera`` object can also be passed. :type followcam: bool, vtkCamera |Polygon| """ ps = vtk.vtkRegularPolygonSource() ps.SetNumberOfSides(nsides) ps.SetRadius(r) ps.SetNormal(-np.array(normal)) ps.Update() tf = vtk.vtkTriangleFilter() tf.SetInputConnection(ps.GetOutputPort()) tf.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tf.GetOutputPort()) if followcam: actor = vtk.vtkFollower() if isinstance(followcam, vtk.vtkCamera): actor.SetCamera(followcam) else: actor.SetCamera(settings.plotter_instance.camera) else: actor = Actor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Polygon", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "nsides", "=", "6", ",", "r", "=", "1", ",", "c", "=", "\"coral\"", ",", "bc", "=", "\"darkgreen\"", ",", "l...
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|
[ "Build", "a", "2D", "polygon", "of", "nsides", "of", "radius", "r", "oriented", "as", "normal", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L588-L632
train
210,476
marcomusy/vtkplotter
vtkplotter/shapes.py
Rectangle
def Rectangle(p1=(0, 0, 0), p2=(2, 1, 0), c="k", bc="dg", lw=1, alpha=1, texture=None): """Build a rectangle in the xy plane identified by two corner points.""" p1 = np.array(p1) p2 = np.array(p2) pos = (p1 + p2) / 2 length = abs(p2[0] - p1[0]) height = abs(p2[1] - p1[1]) return Plane(pos, [0, 0, -1], length, height, c, bc, alpha, texture)
python
def Rectangle(p1=(0, 0, 0), p2=(2, 1, 0), c="k", bc="dg", lw=1, alpha=1, texture=None): """Build a rectangle in the xy plane identified by two corner points.""" p1 = np.array(p1) p2 = np.array(p2) pos = (p1 + p2) / 2 length = abs(p2[0] - p1[0]) height = abs(p2[1] - p1[1]) return Plane(pos, [0, 0, -1], length, height, c, bc, alpha, texture)
[ "def", "Rectangle", "(", "p1", "=", "(", "0", ",", "0", ",", "0", ")", ",", "p2", "=", "(", "2", ",", "1", ",", "0", ")", ",", "c", "=", "\"k\"", ",", "bc", "=", "\"dg\"", ",", "lw", "=", "1", ",", "alpha", "=", "1", ",", "texture", "="...
Build a rectangle in the xy plane identified by two corner points.
[ "Build", "a", "rectangle", "in", "the", "xy", "plane", "identified", "by", "two", "corner", "points", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L635-L642
train
210,477
marcomusy/vtkplotter
vtkplotter/shapes.py
Disc
def Disc( pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """ ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(ps.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(pd) actor = Actor() # vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Disc( pos=(0, 0, 0), normal=(0, 0, 1), r1=0.5, r2=1, c="coral", bc="darkgreen", lw=1, alpha=1, res=12, resphi=None, ): """ Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk| """ ps = vtk.vtkDiskSource() ps.SetInnerRadius(r1) ps.SetOuterRadius(r2) ps.SetRadialResolution(res) if not resphi: resphi = 6 * res ps.SetCircumferentialResolution(resphi) ps.Update() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(ps.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(pd) actor = Actor() # vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.getColor(c)) actor.GetProperty().SetOpacity(alpha) actor.GetProperty().SetLineWidth(lw) actor.GetProperty().SetInterpolationToFlat() if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Disc", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "r1", "=", "0.5", ",", "r2", "=", "1", ",", "c", "=", "\"coral\"", ",", "bc", "=", "\"darkgreen\"", ",", "lw", ...
Build a 2D disc of internal radius `r1` and outer radius `r2`, oriented perpendicular to `normal`. |Disk|
[ "Build", "a", "2D", "disc", "of", "internal", "radius", "r1", "and", "outer", "radius", "r2", "oriented", "perpendicular", "to", "normal", ".", "|Disk|" ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L645-L701
train
210,478
marcomusy/vtkplotter
vtkplotter/shapes.py
Sphere
def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24): """Build a sphere at position `pos` of radius `r`. |Sphere| """ ss = vtk.vtkSphereSource() ss.SetRadius(r) ss.SetThetaResolution(2 * res) ss.SetPhiResolution(res) ss.Update() pd = ss.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24): """Build a sphere at position `pos` of radius `r`. |Sphere| """ ss = vtk.vtkSphereSource() ss.SetRadius(r) ss.SetThetaResolution(2 * res) ss.SetPhiResolution(res) ss.Update() pd = ss.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Sphere", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "r", "=", "1", ",", "c", "=", "\"r\"", ",", "alpha", "=", "1", ",", "res", "=", "24", ")", ":", "ss", "=", "vtk", ".", "vtkSphereSource", "(", ")", "ss", ".", "SetR...
Build a sphere at position `pos` of radius `r`. |Sphere|
[ "Build", "a", "sphere", "at", "position", "pos", "of", "radius", "r", ".", "|Sphere|" ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L704-L719
train
210,479
marcomusy/vtkplotter
vtkplotter/shapes.py
Earth
def Earth(pos=(0, 0, 0), r=1, lw=1): """Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_ """ import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() earthMapper.SetInputConnection(tss.GetOutputPort()) earthActor = Actor(c="w") earthActor.SetMapper(earthMapper) atext = vtk.vtkTexture() pnmReader = vtk.vtkPNMReader() cdir = os.path.dirname(__file__) if cdir == "": cdir = "." fn = settings.textures_path + "earth.ppm" pnmReader.SetFileName(fn) atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOn() earthActor.SetTexture(atext) if not lw: earthActor.SetPosition(pos) return earthActor es = vtk.vtkEarthSource() es.SetRadius(r / 0.995) earth2Mapper = vtk.vtkPolyDataMapper() earth2Mapper.SetInputConnection(es.GetOutputPort()) earth2Actor = Actor() # vtk.vtkActor() earth2Actor.SetMapper(earth2Mapper) earth2Mapper.ScalarVisibilityOff() earth2Actor.GetProperty().SetLineWidth(lw) ass = Assembly([earthActor, earth2Actor]) ass.SetPosition(pos) settings.collectable_actors.append(ass) return ass
python
def Earth(pos=(0, 0, 0), r=1, lw=1): """Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_ """ import os tss = vtk.vtkTexturedSphereSource() tss.SetRadius(r) tss.SetThetaResolution(72) tss.SetPhiResolution(36) earthMapper = vtk.vtkPolyDataMapper() earthMapper.SetInputConnection(tss.GetOutputPort()) earthActor = Actor(c="w") earthActor.SetMapper(earthMapper) atext = vtk.vtkTexture() pnmReader = vtk.vtkPNMReader() cdir = os.path.dirname(__file__) if cdir == "": cdir = "." fn = settings.textures_path + "earth.ppm" pnmReader.SetFileName(fn) atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOn() earthActor.SetTexture(atext) if not lw: earthActor.SetPosition(pos) return earthActor es = vtk.vtkEarthSource() es.SetRadius(r / 0.995) earth2Mapper = vtk.vtkPolyDataMapper() earth2Mapper.SetInputConnection(es.GetOutputPort()) earth2Actor = Actor() # vtk.vtkActor() earth2Actor.SetMapper(earth2Mapper) earth2Mapper.ScalarVisibilityOff() earth2Actor.GetProperty().SetLineWidth(lw) ass = Assembly([earthActor, earth2Actor]) ass.SetPosition(pos) settings.collectable_actors.append(ass) return ass
[ "def", "Earth", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "r", "=", "1", ",", "lw", "=", "1", ")", ":", "import", "os", "tss", "=", "vtk", ".", "vtkTexturedSphereSource", "(", ")", "tss", ".", "SetRadius", "(", "r", ")", "tss",...
Build a textured actor representing the Earth. .. hint:: |geodesic| |geodesic.py|_
[ "Build", "a", "textured", "actor", "representing", "the", "Earth", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L814-L853
train
210,480
marcomusy/vtkplotter
vtkplotter/shapes.py
Grid
def Grid( pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=1, c="g", bc="darkgreen", lw=1, alpha=1, resx=10, resy=10, ): """Return a grid plane. .. hint:: |brownian2D| |brownian2D.py|_ """ ps = vtk.vtkPlaneSource() ps.SetResolution(resx, resy) ps.Update() poly0 = ps.GetOutput() t0 = vtk.vtkTransform() t0.Scale(sx, sy, 1) tf0 = vtk.vtkTransformPolyDataFilter() tf0.SetInputData(poly0) tf0.SetTransform(t0) tf0.Update() poly = tf0.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(lw) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Grid( pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=1, c="g", bc="darkgreen", lw=1, alpha=1, resx=10, resy=10, ): """Return a grid plane. .. hint:: |brownian2D| |brownian2D.py|_ """ ps = vtk.vtkPlaneSource() ps.SetResolution(resx, resy) ps.Update() poly0 = ps.GetOutput() t0 = vtk.vtkTransform() t0.Scale(sx, sy, 1) tf0 = vtk.vtkTransformPolyDataFilter() tf0.SetInputData(poly0) tf0.SetTransform(t0) tf0.Update() poly = tf0.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(lw) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Grid", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "sx", "=", "1", ",", "sy", "=", "1", ",", "c", "=", "\"g\"", ",", "bc", "=", "\"darkgreen\"", ",", "lw", "=",...
Return a grid plane. .. hint:: |brownian2D| |brownian2D.py|_
[ "Return", "a", "grid", "plane", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L901-L945
train
210,481
marcomusy/vtkplotter
vtkplotter/shapes.py
Plane
def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane| """ if sy is None: sy = sx ps = vtk.vtkPlaneSource() ps.SetResolution(1, 1) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(ps.GetOutputPort()) tri.Update() poly = tri.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.Scale(sx, sy, 1) t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", bc="darkgreen", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane| """ if sy is None: sy = sx ps = vtk.vtkPlaneSource() ps.SetResolution(1, 1) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(ps.GetOutputPort()) tri.Update() poly = tri.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.Scale(sx, sy, 1) t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c=c, bc=bc, alpha=alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Plane", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "sx", "=", "1", ",", "sy", "=", "None", ",", "c", "=", "\"g\"", ",", "bc", "=", "\"darkgreen\"", ",", "alpha",...
Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane|
[ "Draw", "a", "plane", "of", "size", "sx", "and", "sy", "oriented", "perpendicular", "to", "vector", "normal", "and", "so", "that", "it", "passes", "through", "point", "pos", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L948-L980
train
210,482
marcomusy/vtkplotter
vtkplotter/shapes.py
Box
def Box(pos=(0, 0, 0), length=1, width=2, height=3, normal=(0, 0, 1), c="g", alpha=1, texture=None): """ Build a box of dimensions `x=length, y=width and z=height` oriented along vector `normal`. .. hint:: |aspring| |aspring.py|_ """ src = vtk.vtkCubeSource() src.SetXLength(length) src.SetYLength(width) src.SetZLength(height) src.Update() poly = src.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Box(pos=(0, 0, 0), length=1, width=2, height=3, normal=(0, 0, 1), c="g", alpha=1, texture=None): """ Build a box of dimensions `x=length, y=width and z=height` oriented along vector `normal`. .. hint:: |aspring| |aspring.py|_ """ src = vtk.vtkCubeSource() src.SetXLength(length) src.SetYLength(width) src.SetZLength(height) src.Update() poly = src.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Box", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "length", "=", "1", ",", "width", "=", "2", ",", "height", "=", "3", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"g\"", ",", "alpha", "="...
Build a box of dimensions `x=length, y=width and z=height` oriented along vector `normal`. .. hint:: |aspring| |aspring.py|_
[ "Build", "a", "box", "of", "dimensions", "x", "=", "length", "y", "=", "width", "and", "z", "=", "height", "oriented", "along", "vector", "normal", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L983-L1014
train
210,483
marcomusy/vtkplotter
vtkplotter/shapes.py
Cube
def Cube(pos=(0, 0, 0), side=1, normal=(0, 0, 1), c="g", alpha=1, texture=None): """Build a cube of size `side` oriented along vector `normal`. .. hint:: |colorcubes| |colorcubes.py|_ """ return Box(pos, side, side, side, normal, c, alpha, texture)
python
def Cube(pos=(0, 0, 0), side=1, normal=(0, 0, 1), c="g", alpha=1, texture=None): """Build a cube of size `side` oriented along vector `normal`. .. hint:: |colorcubes| |colorcubes.py|_ """ return Box(pos, side, side, side, normal, c, alpha, texture)
[ "def", "Cube", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "side", "=", "1", ",", "normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"g\"", ",", "alpha", "=", "1", ",", "texture", "=", "None", ")", ":", "ret...
Build a cube of size `side` oriented along vector `normal`. .. hint:: |colorcubes| |colorcubes.py|_
[ "Build", "a", "cube", "of", "size", "side", "oriented", "along", "vector", "normal", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1017-L1022
train
210,484
marcomusy/vtkplotter
vtkplotter/shapes.py
Spring
def Spring( startPoint=(0, 0, 0), endPoint=(1, 0, 0), coils=20, r=0.1, r2=None, thickness=None, c="grey", alpha=1, ): """ Build a spring of specified nr of `coils` between `startPoint` and `endPoint`. :param int coils: number of coils :param float r: radius at start point :param float r2: radius at end point :param float thickness: thickness of the coil section .. hint:: |aspring| |aspring.py|_ """ diff = endPoint - np.array(startPoint) length = np.linalg.norm(diff) if not length: return None if not r: r = length / 20 trange = np.linspace(0, length, num=50 * coils) om = 6.283 * (coils - 0.5) / length if not r2: r2 = r pts = [] for t in trange: f = (length - t) / length rd = r * f + r2 * (1 - f) pts.append([rd * np.cos(om * t), rd * np.sin(om * t), t]) pts = [[0, 0, 0]] + pts + [[0, 0, length]] diff = diff / length theta = np.arccos(diff[2]) phi = np.arctan2(diff[1], diff[0]) sp = Line(pts).polydata(False) t = vtk.vtkTransform() t.RotateZ(phi * 57.3) t.RotateY(theta * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(sp) tf.SetTransform(t) tf.Update() tuf = vtk.vtkTubeFilter() tuf.SetNumberOfSides(12) tuf.CappingOn() tuf.SetInputData(tf.GetOutput()) if not thickness: thickness = r / 10 tuf.SetRadius(thickness) tuf.Update() poly = tuf.GetOutput() actor = Actor(poly, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(startPoint) actor.base = np.array(startPoint) actor.top = np.array(endPoint) settings.collectable_actors.append(actor) return actor
python
def Spring( startPoint=(0, 0, 0), endPoint=(1, 0, 0), coils=20, r=0.1, r2=None, thickness=None, c="grey", alpha=1, ): """ Build a spring of specified nr of `coils` between `startPoint` and `endPoint`. :param int coils: number of coils :param float r: radius at start point :param float r2: radius at end point :param float thickness: thickness of the coil section .. hint:: |aspring| |aspring.py|_ """ diff = endPoint - np.array(startPoint) length = np.linalg.norm(diff) if not length: return None if not r: r = length / 20 trange = np.linspace(0, length, num=50 * coils) om = 6.283 * (coils - 0.5) / length if not r2: r2 = r pts = [] for t in trange: f = (length - t) / length rd = r * f + r2 * (1 - f) pts.append([rd * np.cos(om * t), rd * np.sin(om * t), t]) pts = [[0, 0, 0]] + pts + [[0, 0, length]] diff = diff / length theta = np.arccos(diff[2]) phi = np.arctan2(diff[1], diff[0]) sp = Line(pts).polydata(False) t = vtk.vtkTransform() t.RotateZ(phi * 57.3) t.RotateY(theta * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(sp) tf.SetTransform(t) tf.Update() tuf = vtk.vtkTubeFilter() tuf.SetNumberOfSides(12) tuf.CappingOn() tuf.SetInputData(tf.GetOutput()) if not thickness: thickness = r / 10 tuf.SetRadius(thickness) tuf.Update() poly = tuf.GetOutput() actor = Actor(poly, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(startPoint) actor.base = np.array(startPoint) actor.top = np.array(endPoint) settings.collectable_actors.append(actor) return actor
[ "def", "Spring", "(", "startPoint", "=", "(", "0", ",", "0", ",", "0", ")", ",", "endPoint", "=", "(", "1", ",", "0", ",", "0", ")", ",", "coils", "=", "20", ",", "r", "=", "0.1", ",", "r2", "=", "None", ",", "thickness", "=", "None", ",", ...
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|_
[ "Build", "a", "spring", "of", "specified", "nr", "of", "coils", "between", "startPoint", "and", "endPoint", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1025-L1088
train
210,485
marcomusy/vtkplotter
vtkplotter/shapes.py
Cylinder
def Cylinder(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="teal", alpha=1, res=24): """ Build a cylinder of specified height and radius `r`, centered at `pos`. If `pos` is a list of 2 Points, e.g. `pos=[v1,v2]`, build a cylinder with base centered at `v1` and top at `v2`. |Cylinder| """ if utils.isSequence(pos[0]): # assume user is passing pos=[base, top] base = np.array(pos[0]) top = np.array(pos[1]) pos = (base + top) / 2 height = np.linalg.norm(top - base) axis = top - base axis = utils.versor(axis) else: axis = utils.versor(axis) base = pos - axis * height / 2 top = pos + axis * height / 2 cyl = vtk.vtkCylinderSource() cyl.SetResolution(res) cyl.SetRadius(r) cyl.SetHeight(height) cyl.Update() theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateX(90) # put it along Z t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(cyl.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) actor.base = base + pos actor.top = top + pos settings.collectable_actors.append(actor) return actor
python
def Cylinder(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="teal", alpha=1, res=24): """ Build a cylinder of specified height and radius `r`, centered at `pos`. If `pos` is a list of 2 Points, e.g. `pos=[v1,v2]`, build a cylinder with base centered at `v1` and top at `v2`. |Cylinder| """ if utils.isSequence(pos[0]): # assume user is passing pos=[base, top] base = np.array(pos[0]) top = np.array(pos[1]) pos = (base + top) / 2 height = np.linalg.norm(top - base) axis = top - base axis = utils.versor(axis) else: axis = utils.versor(axis) base = pos - axis * height / 2 top = pos + axis * height / 2 cyl = vtk.vtkCylinderSource() cyl.SetResolution(res) cyl.SetRadius(r) cyl.SetHeight(height) cyl.Update() theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateX(90) # put it along Z t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(cyl.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) actor.base = base + pos actor.top = top + pos settings.collectable_actors.append(actor) return actor
[ "def", "Cylinder", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "r", "=", "1", ",", "height", "=", "1", ",", "axis", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"teal\"", ",", "alpha", "=", "1", ",", "res", "=",...
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|
[ "Build", "a", "cylinder", "of", "specified", "height", "and", "radius", "r", "centered", "at", "pos", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1091-L1138
train
210,486
marcomusy/vtkplotter
vtkplotter/shapes.py
Cone
def Cone(pos=(0, 0, 0), r=1, height=3, axis=(0, 0, 1), c="dg", alpha=1, res=48): """ Build a cone of specified radius `r` and `height`, centered at `pos`. |Cone| """ con = vtk.vtkConeSource() con.SetResolution(res) con.SetRadius(r) con.SetHeight(height) con.SetDirection(axis) con.Update() actor = Actor(con.GetOutput(), c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) v = utils.versor(axis) * height / 2 actor.base = pos - v actor.top = pos + v settings.collectable_actors.append(actor) return actor
python
def Cone(pos=(0, 0, 0), r=1, height=3, axis=(0, 0, 1), c="dg", alpha=1, res=48): """ Build a cone of specified radius `r` and `height`, centered at `pos`. |Cone| """ con = vtk.vtkConeSource() con.SetResolution(res) con.SetRadius(r) con.SetHeight(height) con.SetDirection(axis) con.Update() actor = Actor(con.GetOutput(), c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) v = utils.versor(axis) * height / 2 actor.base = pos - v actor.top = pos + v settings.collectable_actors.append(actor) return actor
[ "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|
[ "Build", "a", "cone", "of", "specified", "radius", "r", "and", "height", "centered", "at", "pos", ".", "|Cone|" ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1141-L1160
train
210,487
marcomusy/vtkplotter
vtkplotter/shapes.py
Pyramid
def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1): """ Build a pyramid of specified base size `s` and `height`, centered at `pos`. """ return Cone(pos, s, height, axis, c, alpha, 4)
python
def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1): """ Build a pyramid of specified base size `s` and `height`, centered at `pos`. """ return Cone(pos, s, height, axis, c, alpha, 4)
[ "def", "Pyramid", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "s", "=", "1", ",", "height", "=", "1", ",", "axis", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"dg\"", ",", "alpha", "=", "1", ")", ":", "return",...
Build a pyramid of specified base size `s` and `height`, centered at `pos`.
[ "Build", "a", "pyramid", "of", "specified", "base", "size", "s", "and", "height", "centered", "at", "pos", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1163-L1167
train
210,488
marcomusy/vtkplotter
vtkplotter/shapes.py
Torus
def Torus(pos=(0, 0, 0), r=1, thickness=0.1, axis=(0, 0, 1), c="khaki", alpha=1, res=30): """ Build a torus of specified outer radius `r` internal radius `thickness`, centered at `pos`. .. hint:: |gas| |gas.py|_ """ rs = vtk.vtkParametricTorus() rs.SetRingRadius(r) rs.SetCrossSectionRadius(thickness) pfs = vtk.vtkParametricFunctionSource() pfs.SetParametricFunction(rs) pfs.SetUResolution(res * 3) pfs.SetVResolution(res) pfs.Update() nax = np.linalg.norm(axis) if nax: axis = np.array(axis) / nax theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(pfs.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
python
def Torus(pos=(0, 0, 0), r=1, thickness=0.1, axis=(0, 0, 1), c="khaki", alpha=1, res=30): """ Build a torus of specified outer radius `r` internal radius `thickness`, centered at `pos`. .. hint:: |gas| |gas.py|_ """ rs = vtk.vtkParametricTorus() rs.SetRingRadius(r) rs.SetCrossSectionRadius(thickness) pfs = vtk.vtkParametricFunctionSource() pfs.SetParametricFunction(rs) pfs.SetUResolution(res * 3) pfs.SetVResolution(res) pfs.Update() nax = np.linalg.norm(axis) if nax: axis = np.array(axis) / nax theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.RotateY(theta * 57.3) t.RotateZ(phi * 57.3) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(pfs.GetOutput()) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha) actor.GetProperty().SetInterpolationToPhong() actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
[ "def", "Torus", "(", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "r", "=", "1", ",", "thickness", "=", "0.1", ",", "axis", "=", "(", "0", ",", "0", ",", "1", ")", ",", "c", "=", "\"khaki\"", ",", "alpha", "=", "1", ",", "res", "...
Build a torus of specified outer radius `r` internal radius `thickness`, centered at `pos`. .. hint:: |gas| |gas.py|_
[ "Build", "a", "torus", "of", "specified", "outer", "radius", "r", "internal", "radius", "thickness", "centered", "at", "pos", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/shapes.py#L1170-L1204
train
210,489
marcomusy/vtkplotter
vtkplotter/colors.py
getColorName
def getColorName(c): """Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_ """ c = np.array(getColor(c)) # reformat to rgb mdist = 99.0 kclosest = "" for key in colors.keys(): ci = np.array(getColor(key)) d = np.linalg.norm(c - ci) if d < mdist: mdist = d kclosest = str(key) return kclosest
python
def getColorName(c): """Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_ """ c = np.array(getColor(c)) # reformat to rgb mdist = 99.0 kclosest = "" for key in colors.keys(): ci = np.array(getColor(key)) d = np.linalg.norm(c - ci) if d < mdist: mdist = d kclosest = str(key) return kclosest
[ "def", "getColorName", "(", "c", ")", ":", "c", "=", "np", ".", "array", "(", "getColor", "(", "c", ")", ")", "# reformat to rgb", "mdist", "=", "99.0", "kclosest", "=", "\"\"", "for", "key", "in", "colors", ".", "keys", "(", ")", ":", "ci", "=", ...
Find the name of a color. .. hint:: |colorpalette| |colorpalette.py|_
[ "Find", "the", "name", "of", "a", "color", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L265-L279
train
210,490
marcomusy/vtkplotter
vtkplotter/colors.py
makePalette
def makePalette(color1, color2, N, hsv=True): """ Generate N colors starting from `color1` to `color2` by linear interpolation HSV in or RGB spaces. :param int N: number of output colors. :param color1: first rgb color. :param color2: second rgb color. :param bool hsv: if `False`, interpolation is calculated in RGB space. .. hint:: Example: |colorpalette.py|_ """ if hsv: color1 = rgb2hsv(color1) color2 = rgb2hsv(color2) c1 = np.array(getColor(color1)) c2 = np.array(getColor(color2)) cols = [] for f in np.linspace(0, 1, N - 1, endpoint=True): c = c1 * (1 - f) + c2 * f if hsv: c = np.array(hsv2rgb(c)) cols.append(c) return cols
python
def makePalette(color1, color2, N, hsv=True): """ Generate N colors starting from `color1` to `color2` by linear interpolation HSV in or RGB spaces. :param int N: number of output colors. :param color1: first rgb color. :param color2: second rgb color. :param bool hsv: if `False`, interpolation is calculated in RGB space. .. hint:: Example: |colorpalette.py|_ """ if hsv: color1 = rgb2hsv(color1) color2 = rgb2hsv(color2) c1 = np.array(getColor(color1)) c2 = np.array(getColor(color2)) cols = [] for f in np.linspace(0, 1, N - 1, endpoint=True): c = c1 * (1 - f) + c2 * f if hsv: c = np.array(hsv2rgb(c)) cols.append(c) return cols
[ "def", "makePalette", "(", "color1", ",", "color2", ",", "N", ",", "hsv", "=", "True", ")", ":", "if", "hsv", ":", "color1", "=", "rgb2hsv", "(", "color1", ")", "color2", "=", "rgb2hsv", "(", "color2", ")", "c1", "=", "np", ".", "array", "(", "ge...
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|_
[ "Generate", "N", "colors", "starting", "from", "color1", "to", "color2", "by", "linear", "interpolation", "HSV", "in", "or", "RGB", "spaces", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L360-L383
train
210,491
marcomusy/vtkplotter
vtkplotter/colors.py
kelvin2rgb
def kelvin2rgb(temperature): """ Converts from Kelvin temperature to an RGB color. Algorithm credits: |tannerhelland|_ """ # range check if temperature < 1000: temperature = 1000 elif temperature > 40000: temperature = 40000 tmp_internal = temperature / 100.0 # red if tmp_internal <= 66: red = 255 else: tmp_red = 329.698727446 * np.power(tmp_internal - 60, -0.1332047592) if tmp_red < 0: red = 0 elif tmp_red > 255: red = 255 else: red = tmp_red # green if tmp_internal <= 66: tmp_green = 99.4708025861 * np.log(tmp_internal) - 161.1195681661 if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green else: tmp_green = 288.1221695283 * np.power(tmp_internal - 60, -0.0755148492) if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green # blue if tmp_internal >= 66: blue = 255 elif tmp_internal <= 19: blue = 0 else: tmp_blue = 138.5177312231 * np.log(tmp_internal - 10) - 305.0447927307 if tmp_blue < 0: blue = 0 elif tmp_blue > 255: blue = 255 else: blue = tmp_blue return [red / 255, green / 255, blue / 255]
python
def kelvin2rgb(temperature): """ Converts from Kelvin temperature to an RGB color. Algorithm credits: |tannerhelland|_ """ # range check if temperature < 1000: temperature = 1000 elif temperature > 40000: temperature = 40000 tmp_internal = temperature / 100.0 # red if tmp_internal <= 66: red = 255 else: tmp_red = 329.698727446 * np.power(tmp_internal - 60, -0.1332047592) if tmp_red < 0: red = 0 elif tmp_red > 255: red = 255 else: red = tmp_red # green if tmp_internal <= 66: tmp_green = 99.4708025861 * np.log(tmp_internal) - 161.1195681661 if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green else: tmp_green = 288.1221695283 * np.power(tmp_internal - 60, -0.0755148492) if tmp_green < 0: green = 0 elif tmp_green > 255: green = 255 else: green = tmp_green # blue if tmp_internal >= 66: blue = 255 elif tmp_internal <= 19: blue = 0 else: tmp_blue = 138.5177312231 * np.log(tmp_internal - 10) - 305.0447927307 if tmp_blue < 0: blue = 0 elif tmp_blue > 255: blue = 255 else: blue = tmp_blue return [red / 255, green / 255, blue / 255]
[ "def", "kelvin2rgb", "(", "temperature", ")", ":", "# range check", "if", "temperature", "<", "1000", ":", "temperature", "=", "1000", "elif", "temperature", ">", "40000", ":", "temperature", "=", "40000", "tmp_internal", "=", "temperature", "/", "100.0", "# r...
Converts from Kelvin temperature to an RGB color. Algorithm credits: |tannerhelland|_
[ "Converts", "from", "Kelvin", "temperature", "to", "an", "RGB", "color", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/colors.py#L416-L474
train
210,492
marcomusy/vtkplotter
vtkplotter/analysis.py
geometry
def geometry(obj): """ Apply ``vtkGeometryFilter``. """ gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
python
def geometry(obj): """ Apply ``vtkGeometryFilter``. """ gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
[ "def", "geometry", "(", "obj", ")", ":", "gf", "=", "vtk", ".", "vtkGeometryFilter", "(", ")", "gf", ".", "SetInputData", "(", "obj", ")", "gf", ".", "Update", "(", ")", "return", "gf", ".", "GetOutput", "(", ")" ]
Apply ``vtkGeometryFilter``.
[ "Apply", "vtkGeometryFilter", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L67-L74
train
210,493
marcomusy/vtkplotter
vtkplotter/analysis.py
spline
def spline(points, smooth=0.5, degree=2, s=2, c="b", alpha=1.0, nodes=False, res=20): """ Return an ``Actor`` for a spline so that it does not necessarly pass exactly throught all points. :param float smooth: smoothing factor. 0 = interpolate points exactly. 1 = average point positions. :param int degree: degree of the spline (1<degree<5) :param bool nodes: if `True`, show also the input points. .. hint:: |tutorial_spline| |tutorial.py|_ """ from scipy.interpolate import splprep, splev Nout = len(points) * res # Number of points on the spline points = np.array(points) minx, miny, minz = np.min(points, axis=0) maxx, maxy, maxz = np.max(points, axis=0) maxb = max(maxx - minx, maxy - miny, maxz - minz) smooth *= maxb / 2 # must be in absolute units x, y, z = points[:, 0], points[:, 1], points[:, 2] tckp, _ = splprep([x, y, z], task=0, s=smooth, k=degree) # find the knots # evaluate spLine, including interpolated points: xnew, ynew, znew = splev(np.linspace(0, 1, Nout), tckp) ppoints = vtk.vtkPoints() # Generate the polyline for the spline profileData = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk(list(zip(xnew, ynew, znew)), deep=True)) lines = vtk.vtkCellArray() # Create the polyline lines.InsertNextCell(Nout) for i in range(Nout): lines.InsertCellPoint(i) profileData.SetPoints(ppoints) profileData.SetLines(lines) actline = Actor(profileData, c=c, alpha=alpha) actline.GetProperty().SetLineWidth(s) if nodes: actnodes = vs.Points(points, r=5, c=c, alpha=alpha) ass = Assembly([actline, actnodes]) return ass else: return actline
python
def spline(points, smooth=0.5, degree=2, s=2, c="b", alpha=1.0, nodes=False, res=20): """ Return an ``Actor`` for a spline so that it does not necessarly pass exactly throught all points. :param float smooth: smoothing factor. 0 = interpolate points exactly. 1 = average point positions. :param int degree: degree of the spline (1<degree<5) :param bool nodes: if `True`, show also the input points. .. hint:: |tutorial_spline| |tutorial.py|_ """ from scipy.interpolate import splprep, splev Nout = len(points) * res # Number of points on the spline points = np.array(points) minx, miny, minz = np.min(points, axis=0) maxx, maxy, maxz = np.max(points, axis=0) maxb = max(maxx - minx, maxy - miny, maxz - minz) smooth *= maxb / 2 # must be in absolute units x, y, z = points[:, 0], points[:, 1], points[:, 2] tckp, _ = splprep([x, y, z], task=0, s=smooth, k=degree) # find the knots # evaluate spLine, including interpolated points: xnew, ynew, znew = splev(np.linspace(0, 1, Nout), tckp) ppoints = vtk.vtkPoints() # Generate the polyline for the spline profileData = vtk.vtkPolyData() ppoints.SetData(numpy_to_vtk(list(zip(xnew, ynew, znew)), deep=True)) lines = vtk.vtkCellArray() # Create the polyline lines.InsertNextCell(Nout) for i in range(Nout): lines.InsertCellPoint(i) profileData.SetPoints(ppoints) profileData.SetLines(lines) actline = Actor(profileData, c=c, alpha=alpha) actline.GetProperty().SetLineWidth(s) if nodes: actnodes = vs.Points(points, r=5, c=c, alpha=alpha) ass = Assembly([actline, actnodes]) return ass else: return actline
[ "def", "spline", "(", "points", ",", "smooth", "=", "0.5", ",", "degree", "=", "2", ",", "s", "=", "2", ",", "c", "=", "\"b\"", ",", "alpha", "=", "1.0", ",", "nodes", "=", "False", ",", "res", "=", "20", ")", ":", "from", "scipy", ".", "inte...
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|_
[ "Return", "an", "Actor", "for", "a", "spline", "so", "that", "it", "does", "not", "necessarly", "pass", "exactly", "throught", "all", "points", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L77-L118
train
210,494
marcomusy/vtkplotter
vtkplotter/analysis.py
histogram
def histogram(values, bins=10, vrange=None, title="", c="g", corner=1, lines=True): """ Build a 2D histogram from a list of values in n bins. Use *vrange* to restrict the range of the histogram. Use *corner* to assign its position: - 1, topleft, - 2, topright, - 3, bottomleft, - 4, bottomright. .. hint:: Example: |fitplanes.py|_ """ fs, edges = np.histogram(values, bins=bins, range=vrange) pts = [] for i in range(len(fs)): pts.append([(edges[i] + edges[i + 1]) / 2, fs[i]]) return xyplot(pts, title, c, corner, lines)
python
def histogram(values, bins=10, vrange=None, title="", c="g", corner=1, lines=True): """ Build a 2D histogram from a list of values in n bins. Use *vrange* to restrict the range of the histogram. Use *corner* to assign its position: - 1, topleft, - 2, topright, - 3, bottomleft, - 4, bottomright. .. hint:: Example: |fitplanes.py|_ """ fs, edges = np.histogram(values, bins=bins, range=vrange) pts = [] for i in range(len(fs)): pts.append([(edges[i] + edges[i + 1]) / 2, fs[i]]) return xyplot(pts, title, c, corner, lines)
[ "def", "histogram", "(", "values", ",", "bins", "=", "10", ",", "vrange", "=", "None", ",", "title", "=", "\"\"", ",", "c", "=", "\"g\"", ",", "corner", "=", "1", ",", "lines", "=", "True", ")", ":", "fs", ",", "edges", "=", "np", ".", "histogr...
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|_
[ "Build", "a", "2D", "histogram", "from", "a", "list", "of", "values", "in", "n", "bins", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L190-L208
train
210,495
marcomusy/vtkplotter
vtkplotter/analysis.py
delaunay2D
def delaunay2D(plist, mode='xy', tol=None): """ Create a mesh from points in the XY plane. If `mode='fit'` then the filter computes a best fitting plane and projects the points onto it. .. hint:: |delaunay2d| |delaunay2d.py|_ """ pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(plist, deep=True)) pd.SetPoints(vpts) delny = vtk.vtkDelaunay2D() delny.SetInputData(pd) if tol: delny.SetTolerance(tol) if mode=='fit': delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) delny.Update() return Actor(delny.GetOutput())
python
def delaunay2D(plist, mode='xy', tol=None): """ Create a mesh from points in the XY plane. If `mode='fit'` then the filter computes a best fitting plane and projects the points onto it. .. hint:: |delaunay2d| |delaunay2d.py|_ """ pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(plist, deep=True)) pd.SetPoints(vpts) delny = vtk.vtkDelaunay2D() delny.SetInputData(pd) if tol: delny.SetTolerance(tol) if mode=='fit': delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) delny.Update() return Actor(delny.GetOutput())
[ "def", "delaunay2D", "(", "plist", ",", "mode", "=", "'xy'", ",", "tol", "=", "None", ")", ":", "pd", "=", "vtk", ".", "vtkPolyData", "(", ")", "vpts", "=", "vtk", ".", "vtkPoints", "(", ")", "vpts", ".", "SetData", "(", "numpy_to_vtk", "(", "plist...
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|_
[ "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", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L423-L442
train
210,496
marcomusy/vtkplotter
vtkplotter/analysis.py
delaunay3D
def delaunay3D(dataset, alpha=0, tol=None, boundary=True): """Create 3D Delaunay triangulation of input points.""" deln = vtk.vtkDelaunay3D() deln.SetInputData(dataset) deln.SetAlpha(alpha) if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary) deln.Update() return deln.GetOutput()
python
def delaunay3D(dataset, alpha=0, tol=None, boundary=True): """Create 3D Delaunay triangulation of input points.""" deln = vtk.vtkDelaunay3D() deln.SetInputData(dataset) deln.SetAlpha(alpha) if tol: deln.SetTolerance(tol) deln.SetBoundingTriangulation(boundary) deln.Update() return deln.GetOutput()
[ "def", "delaunay3D", "(", "dataset", ",", "alpha", "=", "0", ",", "tol", "=", "None", ",", "boundary", "=", "True", ")", ":", "deln", "=", "vtk", ".", "vtkDelaunay3D", "(", ")", "deln", ".", "SetInputData", "(", "dataset", ")", "deln", ".", "SetAlpha...
Create 3D Delaunay triangulation of input points.
[ "Create", "3D", "Delaunay", "triangulation", "of", "input", "points", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L445-L454
train
210,497
marcomusy/vtkplotter
vtkplotter/analysis.py
normalLines
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8): """ Build an ``vtkActor`` made of the normals at vertices shown as lines. """ maskPts = vtk.vtkMaskPoints() maskPts.SetOnRatio(ratio) maskPts.RandomModeOff() actor = actor.computeNormals() src = actor.polydata() maskPts.SetInputData(src) arrow = vtk.vtkLineSource() arrow.SetPoint1(0, 0, 0) arrow.SetPoint2(0.75, 0, 0) glyph = vtk.vtkGlyph3D() glyph.SetSourceConnection(arrow.GetOutputPort()) glyph.SetInputConnection(maskPts.GetOutputPort()) glyph.SetVectorModeToUseNormal() b = src.GetBounds() sc = max([b[1] - b[0], b[3] - b[2], b[5] - b[4]]) / 20.0 glyph.SetScaleFactor(sc) glyph.OrientOn() glyph.Update() glyphActor = Actor(glyph.GetOutput(), c=vc.getColor(c), alpha=alpha) glyphActor.mapper.SetScalarModeToUsePointFieldData() glyphActor.PickableOff() prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) glyphActor.SetProperty(prop) return glyphActor
python
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8): """ Build an ``vtkActor`` made of the normals at vertices shown as lines. """ maskPts = vtk.vtkMaskPoints() maskPts.SetOnRatio(ratio) maskPts.RandomModeOff() actor = actor.computeNormals() src = actor.polydata() maskPts.SetInputData(src) arrow = vtk.vtkLineSource() arrow.SetPoint1(0, 0, 0) arrow.SetPoint2(0.75, 0, 0) glyph = vtk.vtkGlyph3D() glyph.SetSourceConnection(arrow.GetOutputPort()) glyph.SetInputConnection(maskPts.GetOutputPort()) glyph.SetVectorModeToUseNormal() b = src.GetBounds() sc = max([b[1] - b[0], b[3] - b[2], b[5] - b[4]]) / 20.0 glyph.SetScaleFactor(sc) glyph.OrientOn() glyph.Update() glyphActor = Actor(glyph.GetOutput(), c=vc.getColor(c), alpha=alpha) glyphActor.mapper.SetScalarModeToUsePointFieldData() glyphActor.PickableOff() prop = vtk.vtkProperty() prop.DeepCopy(actor.GetProperty()) glyphActor.SetProperty(prop) return glyphActor
[ "def", "normalLines", "(", "actor", ",", "ratio", "=", "1", ",", "c", "=", "(", "0.6", ",", "0.6", ",", "0.6", ")", ",", "alpha", "=", "0.8", ")", ":", "maskPts", "=", "vtk", ".", "vtkMaskPoints", "(", ")", "maskPts", ".", "SetOnRatio", "(", "rat...
Build an ``vtkActor`` made of the normals at vertices shown as lines.
[ "Build", "an", "vtkActor", "made", "of", "the", "normals", "at", "vertices", "shown", "as", "lines", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L457-L485
train
210,498
marcomusy/vtkplotter
vtkplotter/analysis.py
extractLargestRegion
def extractLargestRegion(actor): """Keep only the largest connected part of a mesh and discard all the smaller pieces. .. hint:: |largestregion.py|_ """ conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.GetMapper().GetInput() conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() eact = Actor(epoly) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) eact.SetProperty(pr) return eact
python
def extractLargestRegion(actor): """Keep only the largest connected part of a mesh and discard all the smaller pieces. .. hint:: |largestregion.py|_ """ conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.GetMapper().GetInput() conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() eact = Actor(epoly) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) eact.SetProperty(pr) return eact
[ "def", "extractLargestRegion", "(", "actor", ")", ":", "conn", "=", "vtk", ".", "vtkConnectivityFilter", "(", ")", "conn", ".", "SetExtractionModeToLargestRegion", "(", ")", "conn", ".", "ScalarConnectivityOff", "(", ")", "poly", "=", "actor", ".", "GetMapper", ...
Keep only the largest connected part of a mesh and discard all the smaller pieces. .. hint:: |largestregion.py|_
[ "Keep", "only", "the", "largest", "connected", "part", "of", "a", "mesh", "and", "discard", "all", "the", "smaller", "pieces", "." ]
692c3396782722ec525bc1346a26999868c650c6
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L488-L504
train
210,499