From 8aade862766431ee60f9631088f6b0461b63c7f8 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:40:45 +0200 Subject: [PATCH 01/67] Updated Video class to work with Windows --- vtkplotter/vtkio.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/vtkplotter/vtkio.py b/vtkplotter/vtkio.py index fd7b76d9..1a4d051b 100644 --- a/vtkplotter/vtkio.py +++ b/vtkplotter/vtkio.py @@ -893,32 +893,33 @@ def screenshot(filename="screenshot.png"): class Video: """ Class to generate a video from the specified rendering window. - Only tested on linux systems with ``ffmpeg`` installed. + Program ``ffmpeg`` is used to create video from each generated frame. :param str name: name of the output file. :param int fps: set the number of frames per second. :param float duration: set the total `duration` of the video and recalculates `fps` accordingly. + :param str ffmpeg: set path to ffmpeg program. Default value considers ffmpeg is in the path. .. hint:: |makeVideo| |makeVideo.py|_ """ - def __init__(self, name="movie.avi", fps=12, duration=None): + def __init__(self, name="movie.avi", **kwargs): import glob + from tempfile import TemporaryDirectory self.name = name - self.duration = duration - self.fps = float(fps) + self.duration = kwargs.pop('duration', None) + self.fps = float(kwargs.pop('fps', 12)) + self.ffmpeg = kwargs.pop('ffmpeg', 'ffmpeg') self.frames = [] - if not os.path.exists("/tmp/vpvid"): - os.mkdir("/tmp/vpvid") - for fl in glob.glob("/tmp/vpvid/*.png"): - os.remove(fl) + self.tmp_dir = TemporaryDirectory() + self.get_filename = lambda x: os.path.join(self.tmp_dir.name, x) colors.printc("~video Video", name, "is open...", c="m") def addFrame(self): """Add frame to current video.""" - fr = "/tmp/vpvid/" + str(len(self.frames)) + ".png" + fr = self.get_filename(str(len(self.frames)) + ".png") screenshot(fr) self.frames.append(fr) @@ -926,8 +927,8 @@ 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" + for _ in range(n): + fr2 = self.get_filename(str(len(self.frames)) + ".png") self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2)) @@ -939,11 +940,12 @@ def close(self): 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) + out = os.system(self.ffmpeg + " -loglevel panic -y -r " + str(_fps) + + " -i " + self.tmp_dir.name + os.sep + "%01d.png " + self.name) if out: colors.printc("ffmpeg returning error", c=1) colors.printc("~save Video saved as", self.name, c="green") + self.tmp_dir.cleanup() return # ############################################################### Mouse Events From 887c1985176be672c50d492f69c37e772ce5ec98 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:41:04 +0200 Subject: [PATCH 02/67] Removed trailing spaces in vtkio.py --- vtkplotter/vtkio.py | 70 ++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/vtkplotter/vtkio.py b/vtkplotter/vtkio.py index 1a4d051b..ebf8eeee 100644 --- a/vtkplotter/vtkio.py +++ b/vtkplotter/vtkio.py @@ -35,14 +35,14 @@ def load(inputobj, c="gold", alpha=1, threshold=False, spacing=(), unpack=True): """ Load ``Actor`` and ``Volume`` from file. - + The output will depend on the file extension. See examples below. - + :param c: color in RGB format, hex, symbol or name :param alpha: transparency/opacity of the polygonal data. For volumetric data `(tiff, slc, vti etc..)`: - + :param list c: can be a list of any length of colors. This list represents the color transfer function values equally spaced along the range of the volumetric scalar. :param list alpha: can be a list of any length of tranparencies. This list represents the @@ -51,33 +51,33 @@ def load(inputobj, c="gold", alpha=1, threshold=False, spacing=(), unpack=True): If set to True will return an ``Actor`` with automatic choice of the isosurfacing threshold. :param list spacing: specify the voxel spacing in the three dimensions :param bool unpack: only for multiblock data, if True returns a flat list of objects. - + :Examples: .. code-block:: python - + from vtkplotter import datadir, load, show - + # Return an Actor g = load(datadir+'250.vtk') show(g) - + # Return a list of 2 Actors g = load([datadir+'250.vtk', datadir+'270.vtk']) show(g) - + # Return a list of actors by reading all files in a directory # (if directory contains DICOM files then a Volume is returned) g = load(datadir+'timecourse1d/') show(g) - + # Return a Volume. Color/Opacity transfer functions can be specified too. g = load(datadir+'embryo.slc') g.c(['y','lb','w']).alpha((0.0, 0.4, 0.9, 1)) show(g) - + # Return an Actor from a SLC volume with automatic thresholding g = load(datadir+'embryo.slc', threshold=True) - show(g) + show(g) """ acts = [] if utils.isSequence(inputobj): @@ -135,7 +135,7 @@ def _load_file(filename, c, alpha, threshold, spacing, unpack): reader.SetFileName(filename) reader.Update() actor = Actor(reader.GetOutput(), c, alpha) - + ################################################################# volumetric: elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \ or fl.endswith(".mhd") or fl.endswith(".nrrd"): @@ -223,13 +223,13 @@ def _load_file(filename, c, alpha, threshold, spacing, unpack): reader.SetFileName(filename) reader.Update() poly = reader.GetOutput() - + if fl.endswith(".vts") or fl.endswith(".vtu"): # un/structured grid gf = vtk.vtkGeometryFilter() gf.SetInputData(poly) gf.Update() poly = gf.GetOutput() - + if not poly: colors.printc("~noentry Unable to load", filename, c=1) return None @@ -237,7 +237,7 @@ def _load_file(filename, c, alpha, threshold, spacing, unpack): actor = Actor(poly, c, alpha) if fl.endswith(".txt") or fl.endswith(".xyz"): actor.GetProperty().SetPointSize(4) - + actor.filename = filename return actor @@ -658,17 +658,17 @@ def save(objct, fileoutput, binary=True): ########################################################### def exportWindow(fileoutput, binary=False, speed=None, html=True): ''' - Exporter which writes out the renderered scene into an OBJ or X3D file. + Exporter which writes out the renderered scene into an OBJ or X3D file. X3D is an XML-based format for representation 3D scenes (similar to VRML). Check out http://www.web3d.org/x3d for more details. - + :param float speed: set speed for x3d files. :param bool html: generate a test html page for x3d files. - + .. hint:: |export_x3d| |export_x3d.py|_ - + `generated webpage `_ - + See also: FEniCS test `webpage `_. ''' fr = fileoutput.lower() @@ -720,9 +720,9 @@ def buildPolyDataFast(vertices, faces=None, indexOffset=None): from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray dts = vtk.vtkIdTypeArray().GetDataTypeSize() - ast = numpy.int32 + ast = numpy.int32 if dts != 4: - ast = numpy.int64 + ast = numpy.int64 if not utils.isSequence(vertices): # assume a dolfin.Mesh from dolfin import Mesh, BoundaryMesh @@ -731,8 +731,8 @@ def buildPolyDataFast(vertices, faces=None, indexOffset=None): vertices = mesh.coordinates() faces = mesh.cells() - # must fix dim=3 of vertices.. todo - + # must fix dim=3 of vertices.. todo + poly = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(vertices, deep=True)) @@ -742,9 +742,9 @@ def buildPolyDataFast(vertices, faces=None, indexOffset=None): if faces is not None: nf, nc = faces.shape dts = vtk.vtkIdTypeArray().GetDataTypeSize() - ast = numpy.int32 + ast = numpy.int32 if dts != 4: - ast = numpy.int64 + ast = numpy.int64 hs = numpy.hstack((numpy.zeros(nf)[:,None] + nc, faces)).astype(ast).ravel() arr = numpy_to_vtkIdTypeArray(hs, deep=True) cells.SetCells(nf, arr) @@ -786,11 +786,11 @@ def buildPolyData(vertices, faces=None, indexOffset=0): aid = sourcePoints.InsertNextPoint(pt[0], 0, 0) else: aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0) - + if faces is None: sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(aid) - + if faces is not None: showbar = False if len(faces) > 25000: @@ -811,7 +811,7 @@ def buildPolyData(vertices, faces=None, indexOffset=0): pid1 = ele1.GetPointIds() pid2 = ele2.GetPointIds() pid3 = ele3.GetPointIds() - + pid0.SetId(0, f0) pid0.SetId(1, f1) pid0.SetId(2, f2) @@ -832,7 +832,7 @@ def buildPolyData(vertices, faces=None, indexOffset=0): sourcePolygons.InsertNextCell(ele1) sourcePolygons.InsertNextCell(ele2) sourcePolygons.InsertNextCell(ele3) - + # if n == 4: #problematic because of faces orientation # ele = vtk.vtkTetra() # pids = ele.GetPointIds() @@ -863,7 +863,7 @@ def buildPolyData(vertices, faces=None, indexOffset=0): poly.SetVerts(sourceVertices) else: poly.SetPolys(sourcePolygons) - + return poly @@ -958,7 +958,7 @@ def _mouse_enter(iren, event): if ivp.interactor != iren: if ivp.camera == iren.GetActiveCamera(): ivp.interactor.Render() - + def _mouseleft(iren, event): @@ -976,7 +976,7 @@ def _mouseleft(iren, event): return vp.renderer = renderer - + picker = vtk.vtkPropPicker() picker.PickProp(x, y, renderer) clickedActor = picker.GetActor() @@ -1000,7 +1000,7 @@ def _mouseleft(iren, event): if vp.mouseLeftClickFunction: vp.mouseLeftClickFunction(clickedActor) - + def _mouseright(iren, event): @@ -1055,7 +1055,7 @@ def _mousemiddle(iren, event): return vp.renderer = renderer - + picker = vtk.vtkPropPicker() picker.PickProp(x, y, renderer) clickedActor = picker.GetActor() From f58112749a80f704442606be481a3cae365e2baf Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 03/67] Typo update for examples/basic/closewindow.py --- examples/basic/closewindow.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/basic/closewindow.py b/examples/basic/closewindow.py index ad3e4021..cc5f5749 100644 --- a/examples/basic/closewindow.py +++ b/examples/basic/closewindow.py @@ -8,11 +8,11 @@ mesh = Paraboloid() vp1 = show(mesh, Text(__doc__), title='First Plotter instance') - -# Now press 'q' to exit the window interaction, + +# Now press 'q' to exit the window interaction, # windows stays open but not reactive anymore. -# You can go back to interation mode by simpy calling: +# You can go back to interavtion mode by simply calling: #show() input('\nControl returned to terminal shell:\nwindow is now unresponsive (press Enter)') @@ -23,7 +23,7 @@ # but mesh objects still exist in it: print("First Plotter actors:", vp1.actors) -vp1.show() #THIS HAS NO EFFECT: window does not exist anymore. Cannot reopen. +vp1.show() # THIS HAS NO EFFECT: window does not exist anymore. Cannot reopen. ################################################################## # Can now create a brand new Plotter and show the old object in it @@ -40,6 +40,6 @@ vp3.show(Hyperboloid()) from vtkplotter import closeWindow -closeWindow() # automatically find and close the current window +closeWindow() # automatically find and close the current window print('done.') From 7016a11cba3006d3032d82a89b525074fe9b17d6 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 04/67] Typo update for vtkplotter/__init__.py --- vtkplotter/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vtkplotter/__init__.py b/vtkplotter/__init__.py index 765ba374..aeeca815 100644 --- a/vtkplotter/__init__.py +++ b/vtkplotter/__init__.py @@ -7,7 +7,7 @@ .. note:: **Please check out the** `git repository `_. A full list of examples can be found in directories: - + - `examples/basic `_ , - `examples/advanced `_ , - `examples/volumetric `_, @@ -33,7 +33,7 @@ **Have you found this software useful for your research? Please cite it as:** -M. Musy, et al., +M. Musy, et al., "`vtkplotter`, a python module for scientific visualization, analysis and animation of 3D objects and point clouds based on VTK." (version v8.9.0). Zenodo, `doi: 10.5281/zenodo.2561402 `_, 10 February 2019. From fe02115a093d72c416c5e75530f80fe73a9c9cdb Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 05/67] Typo update for vtkplotter/actors.py --- vtkplotter/actors.py | 160 +++++++++++++++++++++---------------------- 1 file changed, 80 insertions(+), 80 deletions(-) diff --git a/vtkplotter/actors.py b/vtkplotter/actors.py index 734a8834..4a4c7fd1 100644 --- a/vtkplotter/actors.py +++ b/vtkplotter/actors.py @@ -50,11 +50,11 @@ def collection(): def isolines(actor, n=10, vmin=None, vmax=None): """ Return the actor representing the isolines of the active scalars. - + :param int n: number of isolines in the range :param float vmin: minimum of the range :param float vmax: maximum of the range - + .. hint:: |isolines| |isolines.py|_ """ bcf = vtk.vtkBandedPolyDataContourFilter() @@ -73,7 +73,7 @@ def isolines(actor, n=10, vmin=None, vmax=None): zbandsact.GetProperty().SetLineWidth(1.5) return zbandsact - + def isosurface(volume, threshold=True, connectivity=False, smoothing=0): """Return a ``vtkActor`` isosurface extracted from a ``vtkImageData`` object. @@ -88,7 +88,7 @@ def isosurface(volume, threshold=True, connectivity=False, smoothing=0): image = volume # assume is passing a vtkImageData else: image = volume.GetMapper().GetInput() - + if smoothing: smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) @@ -138,12 +138,12 @@ def legosurface(image, vmin=None, vmax=None, cmap='afmhot_r'): Represent a ``vtkVolume`` or ``vtkImageData`` as lego blocks (voxels). By default colors correspond to the volume's scalar. Returns an ``Actor``. - + :param float vmin: the lower threshold, voxels below this value are not shown. :param float vmax: the upper threshold, voxels above this value are not shown. :param str cmap: color mapping of the scalar associated to the voxels. - - .. hint:: |legosurface| |legosurface.py|_ + + .. hint:: |legosurface| |legosurface.py|_ """ if isinstance(image, vtk.vtkVolume): image = image.GetMapper().GetInput() @@ -151,23 +151,23 @@ def legosurface(image, vmin=None, vmax=None, cmap='afmhot_r'): dataset.SetDataSet(image) window = vtk.vtkImplicitWindowFunction() window.SetImplicitFunction(dataset) - - srng = list(image.GetScalarRange()) + + srng = list(image.GetScalarRange()) if vmin is not None: srng[0] = vmin if vmax is not None: srng[1] = vmax window.SetWindowRange(srng) - + extract = vtk.vtkExtractGeometry() extract.SetInputData(image) extract.SetImplicitFunction(window) extract.ExtractInsideOff() extract.ExtractBoundaryCellsOff() extract.Update() - + gf = vtk.vtkGeometryFilter() gf.SetInputData(extract.GetOutput()) gf.Update() - + a = Actor(gf.GetOutput()).lw(0.1) a.GetProperty().SetInterpolationToFlat() @@ -185,7 +185,7 @@ def mergeActors(*actors): Similar to Assembly, but in this case the input objects become a single mesh. .. hint:: |thinplate_grid.py|_ |value-iteration.py|_ - + |thinplate_grid| |value-iteration| """ acts = [] @@ -208,7 +208,7 @@ def mergeActors(*actors): ################################################# classes class Prop(object): """Adds functionality to ``Actor``, ``Assembly`` and ``Volume`` objects. - + .. warning:: Do not use this class to instance objects, use the above ones. """ @@ -249,7 +249,7 @@ def show(self, **options): .. note:: E.g.: .. code-block:: python - + from vtkplotter import * s = Sphere() s.show(at=1, N=2) @@ -368,9 +368,9 @@ def rotate(self, angle, axis=(1, 0, 0), axis_point=(0, 0, 0), rad=False): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self def rotateX(self, angle, axis_point=(0, 0, 0), rad=False): @@ -381,9 +381,9 @@ def rotateX(self, angle, axis_point=(0, 0, 0), rad=False): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self def rotateY(self, angle, axis_point=(0, 0, 0), rad=False): @@ -394,9 +394,9 @@ def rotateY(self, angle, axis_point=(0, 0, 0), rad=False): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self def rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): @@ -407,9 +407,9 @@ def rotateZ(self, angle, axis_point=(0, 0, 0), rad=False): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self def orientation(self, newaxis=None, rotation=0, rad=False): @@ -441,9 +441,9 @@ def orientation(self, newaxis=None, rotation=0, rad=False): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self def scale(self, s=None): @@ -468,17 +468,17 @@ def time(self, t=None): def addShadow(self, x=None, y=None, z=None, c=(0.5,0.5,0.5), alpha=1): """ - Generate a shadow out of an ``Actor`` on one of the three Cartesian planes. + Generate a shadow out of an ``Actor`` on one of the three Cartesian planes. The output is a new ``Actor`` representing the shadow. This new actor is accessible through `actor.shadow`. By default the actor is placed on the bottom/back wall of the bounding box. - + :param float x,y,z: identify the plane to cast the shadow to ['x', 'y' or 'z']. The shadow will lay on the orthogonal plane to the specified axis at the specified value of either x, y or z. - + .. hint:: |shadow| |shadow.py|_ - + |airplanes| |airplanes.py|_ """ if x is not None: @@ -520,7 +520,7 @@ def addTrail(self, offset=None, maxlength=None, n=50, c=None, alpha=None, lw=2): :param lw: line width of the trail .. hint:: See examples: |trail.py|_ |airplanes.py|_ - + |airplanes| """ if maxlength is None: @@ -601,9 +601,9 @@ def off(self): def box(self, scale=1): """Return the bounding box as a new ``Actor``. - + :param float scale: box size can be scaled by a factor - + .. hint:: |latex.py|_ """ b = self.GetBounds() @@ -624,8 +624,8 @@ def printHistogram(self, bins=10, height=10, logscale=False, minbin=0, """ Ascii histogram printing. Input can also be ``Volume`` or ``Actor``. - Returns the raw data before binning (useful when passing vtk objects). - + Returns the raw data before binning (useful when passing vtk objects). + :param int bins: number of histogram bins :param int height: height of the histogram in character units :param bool logscale: use logscale for frequencies @@ -635,17 +635,17 @@ def printHistogram(self, bins=10, height=10, logscale=False, minbin=0, :param str,int c: ascii color :param bool char: use boldface :param str title: histogram title - + :Example: .. code-block:: python - + from vtkplotter import printHistogram import numpy as np d = np.random.normal(size=1000) data = printHistogram(d, c='blue', logscale=True, title='my scalars') data = printHistogram(d, c=1, horizontal=1) print(np.mean(data)) # data here is same as d - + |printhisto| """ utils.printHistogram(self, bins, height, logscale, minbin, @@ -671,14 +671,14 @@ class Actor(vtk.vtkActor, Prop): """Build an instance of object ``Actor`` derived from ``vtkActor``. Input can be ``vtkPolyData``, ``vtkActor``, or a python list of [vertices, faces]. - + If input is any of ``vtkUnstructuredGrid``, ``vtkStructuredGrid`` or ``vtkRectilinearGrid`` the goemetry is extracted. In this case the original VTK data structures can be accessed as: `actor.UnstructuredGrid`, `actor.RectilinearGrid` and `actor.StructuredGrid`, Finally input can be a list of vertices and their connectivity (faces of the polygonal mesh). For point clouds - e.i. no faces - just substitute the `faces` list with ``None``. - + E.g.: `Actor( [ [[x1,y1,z1],[x2,y2,z2], ...], [[0,1,2], [1,2,3], ...] ] )` :param c: color in RGB format, hex, symbol or name @@ -687,9 +687,9 @@ class Actor(vtk.vtkActor, Prop): :param bc: backface color of internal surface :param str texture: jpg file name or surface texture name :param bool computeNormals: compute point and cell normals at creation - + .. hint:: A mesh can be built from vertices and their connectivity. See e.g.: - + |buildmesh| |buildmesh.py|_ """ @@ -706,7 +706,7 @@ def __init__( ): vtk.vtkActor.__init__(self) Prop.__init__(self) - + self.UnstructuredGrid = None self.StructuredGrid = None self.RectilinearGrid = None @@ -724,8 +724,8 @@ def __init__( for i in range(poly.GetNumberOfPoints()): carr.InsertNextCell(1) carr.InsertCellPoint(i) - poly.SetVerts(carr) - self.poly = poly # cache vtkPolyData and mapper for speed + poly.SetVerts(carr) + self.poly = poly # cache vtkPolyData and mapper for speed self.mapper = vtk.vtkPolyDataMapper() elif "vtkUnstructuredGrid" in inputtype: gf = vtk.vtkGeometryFilter() @@ -752,7 +752,7 @@ def __init__( from vtkplotter.vtkio import buildPolyData self.poly = buildPolyData(poly[0], poly[1]) self.mapper = vtk.vtkPolyDataMapper() - + if self.mapper: self.SetMapper(self.mapper) @@ -781,7 +781,7 @@ def __init__( prp = self.GetProperty() prp.SetInterpolationToFlat() - + if settings.renderPointsAsSpheres: if hasattr(prp, 'RenderPointsAsSpheresOn'): prp.RenderPointsAsSpheresOn() @@ -792,7 +792,7 @@ def __init__( else: self.mapper.ScalarVisibilityOff() c = colors.getColor(c) - prp.SetColor(c) + prp.SetColor(c) prp.SetAmbient(0.1) prp.SetDiffuse(1) prp.SetSpecular(.05) @@ -889,7 +889,7 @@ def texture(self, tname): tmapper.AutomaticPlaneGenerationOn() tmapper.SetInputData(self.polydata()) tmapper.Update() - + tc = tmapper.GetOutput().GetPointData().GetTCoords() self.polydata().GetPointData().SetTCoords(tc) self.polydata().GetPointData().AddArray(tc) @@ -1065,7 +1065,7 @@ def wire(self, wireframe=True): def flat(self): """Set surface interpolation to Flat. - + .. image:: https://upload.wikimedia.org/wikipedia/commons/8/84/Phong-shading-sample.jpg """ self.GetProperty().SetInterpolationToFlat() @@ -1080,13 +1080,13 @@ def gouraud(self): """Set surface interpolation to Gouraud.""" self.GetProperty().SetInterpolationToGouraud() return self - + def lighting(self, style='', ambient=None, diffuse=None, specular=None, specularPower=None, specularColor=None, enabled=True): """ Set the ambient, diffuse, specular and specularPower lighting constants. - + :param str style: preset style, can be `[metallic, plastic, shiny, reflective]` :param float ambient: ambient fraction of emission [0-1] :param float diffuse: emission of diffused light in fraction [0-1] @@ -1094,9 +1094,9 @@ def lighting(self, style='', ambient=None, diffuse=None, :param float specularPower: precision of reflection [1-100] :param color specularColor: color that is being reflected by the surface :param bool enabled: enable/disable all surface light emission - + .. image:: https://upload.wikimedia.org/wikipedia/commons/6/6b/Phong_components_version_4.png - + .. hint:: |specular| |specular.py|_ """ pr = self.GetProperty() @@ -1117,7 +1117,7 @@ def lighting(self, style='', ambient=None, diffuse=None, pr.SetSpecular(pars[2]) pr.SetSpecularPower(pars[3]) pr.SetSpecularColor(pars[4]) - + if ambient is not None: pr.SetAmbient(ambient) if diffuse is not None: pr.SetDiffuse(diffuse) if specular is not None: pr.SetSpecular(specular) @@ -1258,12 +1258,12 @@ def clean(self, tol=None): def quantize(self, binSize): """ - The user should input binSize and all {x,y,z} coordinates + The user should input binSize and all {x,y,z} coordinates will be quantized to that absolute grain size. - + Example: .. code-block:: python - + from vtkplotter import Paraboloid Paraboloid().lw(0.1).quantize(0.1).show() """ @@ -1471,9 +1471,9 @@ def clone(self, transformed=True): cloned.addTrail(self.trailOffset, self.trailSegmentSize*n, n, None, None, self.trail.GetProperty().GetLineWidth()) if self.shadow: - cloned.addShadow(self.shadowX, self.shadowY, self.shadowZ, + cloned.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return cloned @@ -1630,9 +1630,9 @@ def stretch(self, q1, q2): if self.trail: self.updateTrail() if self.shadow: - self.addShadow(self.shadowX, self.shadowY, self.shadowZ, + self.addShadow(self.shadowX, self.shadowY, self.shadowZ, self.shadow.GetProperty().GetColor(), - self.shadow.GetProperty().GetOpacity()) + self.shadow.GetProperty().GetOpacity()) return self @@ -1645,13 +1645,13 @@ def crop(self, top=None, bottom=None, right=None, left=None, front=None, back=No :param float back: fraction to crop from the back plane (negative y) :param float right: fraction to crop from the right plane (positive x) :param float left: fraction to crop from the left plane (negative x) - + Example: .. code-block:: python - + from vtkplotter import Sphere Sphere().crop(right=0.3, left=0.1).show() - + |cropped| """ x0,x1, y0,y1, z0,z1 = self.GetBounds() @@ -1665,7 +1665,7 @@ def crop(self, top=None, bottom=None, right=None, left=None, front=None, back=No if right: x1 = x1 - right*dx if left: x0 = x0 + left*dx cu.SetBounds(x0,x1, y0,y1, z0,z1) - + poly = self.polydata() clipper = vtk.vtkClipPolyData() clipper.SetInputData(poly) @@ -1928,7 +1928,7 @@ def pointColors(self, scalars, cmap="jet", alpha=1, bands=None, vmin=None, vmax= if hasattr(scalars, 'astype'): scalars = scalars.astype(np.float) - + useAlpha = False if n != poly.GetNumberOfPoints(): colors.printc('~times pointColors Error: nr. of scalars != nr. of points', @@ -2749,21 +2749,21 @@ def projectOnPlane(self, direction='z'): exit() self.alpha(0.1).polydata(False).GetPoints().Modified() return self - + def silhouette(self, direction=None, borderEdges=True, featureAngle=None): """ Return a new line ``Actor`` which corresponds to the outer `silhouette` - of the input as seen along a specified `direction`, this can also be + of the input as seen along a specified `direction`, this can also be a ``vtkCamera`` object. - + :param list direction: viewpoint direction vector. If *None* this is guessed by looking at the minimum of the sides of the bounding box. :param bool borderEdges: enable or disable generation of border edges :param float borderEdges: minimal angle for sharp edges detection. If set to `False` the functionality is disabled. - + .. hint:: |silhouette| |silhouette.py|_ """ sil = vtk.vtkPolyDataSilhouette() @@ -2839,13 +2839,13 @@ 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 lighting(self, *args, **lgt): """Set the lighting type to all ``Actor`` in the ``Assembly``.""" for a in self.actors: a.lighting(**lgt) return self - + ################################################# class Image(vtk.vtkImageActor, Prop): @@ -2874,7 +2874,7 @@ def crop(self, top=None, bottom=None, right=None, left=None): :param float bottom: fraction to crop from the bottom margin :param float left: fraction to crop from the left margin :param float right: fraction to crop from the right margin - + .. hint:: |legosurface| |legosurface.py|_ """ extractVOI = vtk.vtkExtractVOI() @@ -2920,7 +2920,7 @@ def __init__(self, img, :type c: list, str :param alpha: sets transparencies along the scalar range :type c: float, list - + if a `list` of values is used for `alpha` this is interpreted as a transfer function along the range. """ @@ -2984,7 +2984,7 @@ def color(self, color="blue"): def alpha(self, alpha=(0.0, 0.4, 0.9, 1)): """Assign a set of tranparencies to a volume along the range of the scalar value. - + E.g.: say alpha=(0.0, 0.3, 0.9, 1) and the scalar range goes from -10 to 150. Then all voxels with a value close to -10 will be completely transparent, voxels at 1/4 of the range will get an alpha equal to 0.3 and voxels with value close to 150 @@ -3026,7 +3026,7 @@ def threshold(self, vmin=None, vmax=None, replaceWith=None): if replaceWith is None: colors.printc("Error in threshold(); you must provide replaceWith", c=1) exit() - + th.SetInValue(replaceWith) th.Update() @@ -3049,7 +3049,7 @@ def crop(self, top=None, bottom=None, :param float right: fraction to crop from the right plane (positive x) :param float left: fraction to crop from the left plane (negative x) :param list VOI: extract Volume Of Interest expressed in voxel numbers - + Eg.: vol.crop(VOI=(xmin, xmax, ymin, ymax, zmin, zmax)) # all integers nrs """ extractVOI = vtk.vtkExtractVOI() @@ -3099,7 +3099,7 @@ def normalize(self): self.GetMapper().SetInputData(self.image) self.GetMapper().Modified() return self - + def scaleVoxelsScalar(self, scale=1): """Scale the voxel content""" @@ -3111,7 +3111,7 @@ def scaleVoxelsScalar(self, scale=1): self.GetMapper().SetInputData(self.image) self.GetMapper().Modified() return self - + def mirror(self, axis="x"): """ @@ -3139,7 +3139,7 @@ def mirror(self, axis="x"): self.GetMapper().SetInputData(self.image) self.GetMapper().Modified() return self - + def getVoxelScalar(self, vmin=None, vmax=None): """ From 5b7ec737f64fdb0c3e575617271b1ffc46d19aae Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 06/67] Typo update for vtkplotter/addons.py --- vtkplotter/addons.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vtkplotter/addons.py b/vtkplotter/addons.py index 480be083..273d30c2 100644 --- a/vtkplotter/addons.py +++ b/vtkplotter/addons.py @@ -32,7 +32,7 @@ ] -def addScalarBar(actor=None, c=None, title="", +def addScalarBar(actor=None, c=None, title="", horizontal=False, vmin=None, vmax=None): """Add a 2D scalar bar for the specified actor. @@ -110,7 +110,7 @@ def addScalarBar(actor=None, c=None, title="", sb.SetPosition(0.87, 0.05) sb.SetMaximumWidthInPixels(80) sb.SetMaximumHeightInPixels(500) - + sctxt = sb.GetLabelTextProperty() sctxt.SetColor(c) sctxt.SetShadow(0) From 1094a13d44b6841610526c3a86a643b5672d09f8 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 07/67] Typo update for vtkplotter/analysis.py --- vtkplotter/analysis.py | 146 ++++++++++++++++++++--------------------- 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/vtkplotter/analysis.py b/vtkplotter/analysis.py index c7e411e5..348db129 100644 --- a/vtkplotter/analysis.py +++ b/vtkplotter/analysis.py @@ -461,8 +461,8 @@ def delaunay3D(dataset, alpha=0, tol=None, boundary=True): deln.SetBoundingTriangulation(boundary) deln.Update() return deln.GetOutput() - - + + 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. @@ -1135,7 +1135,7 @@ def imageOperation(volume1, operation, volume2=None): """Deprecated: use volumeOperation().""" print("\n\n imageOperation() is no more valid: use volumeOperation() instead.") exit() - + def volumeOperation(volume1, operation, volume2=None): """ Perform operations with ``Volume`` objects. @@ -1158,7 +1158,7 @@ def volumeOperation(volume1, operation, volume2=None): image2 = volume2.GetMapper().GetInput() else: image2 = volume2 - + if op in ["median"]: mf = vtk.vtkImageMedian3D() @@ -1426,7 +1426,7 @@ def thinPlateSpline(actor, sourcePts, targetPts, userFunctions=(None, None)): and its derivative with respect to r. .. hint:: Examples: |thinplate.py|_ |thinplate_grid.py|_ |thinplate_morphing.py|_ |interpolateField.py|_ - + |thinplate| |thinplate_grid| |thinplate_morphing| |interpolateField| """ ns = len(sourcePts) @@ -1540,11 +1540,11 @@ def meshQuality(actor, measure=6): def connectedPoints(actor, radius, mode=0, regions=(), vrange=(0,1), seeds=(), angle=0): """ - Extracts and/or segments points from a point cloud based on geometric distance measures - (e.g., proximity, normal alignments, etc.) and optional measures such as scalar range. + Extracts and/or segments points from a point cloud based on geometric distance measures + (e.g., proximity, normal alignments, etc.) and optional measures such as scalar range. The default operation is to segment the points into "connected" regions where the connection - is determined by an appropriate distance measure. Each region is given a region id. - + is determined by an appropriate distance measure. Each region is given a region id. + Optionally, the filter can output the largest connected region of points; a particular region (via id specification); those regions that are seeded using a list of input point ids; or the region of points closest to a specified position. @@ -1563,21 +1563,21 @@ def connectedPoints(actor, radius, mode=0, regions=(), vrange=(0,1), seeds=(), a On output, all points are labeled with a region number. However note that the number of input and output points may not be the same: if not extracting all regions then the output size may be less than the input size. - + :param float radius: radius variable specifying a local sphere used to define local point neighborhood - :param int mode: - + :param int mode: + - 0, Extract all regions - 1, Extract point seeded regions - 2, Extract largest region - 3, Test specified regions - 4, Extract all regions with scalar connectivity - 5, Extract point seeded regions - + :param list regions: a list of non-negative regions id to extract :param list vrange: scalar range to use to extract points based on scalar connectivity :param list seeds: a list of non-negative point seed ids - :param list angle: points are connected if the angle between their normals is + :param list angle: points are connected if the angle between their normals is within this angle threshold (expressed in degrees). """ # https://vtk.org/doc/nightly/html/classvtkConnectedPointsFilter.html @@ -1586,37 +1586,37 @@ def connectedPoints(actor, radius, mode=0, regions=(), vrange=(0,1), seeds=(), a cpf.SetRadius(radius) if mode == 0: # Extract all regions pass - + elif mode == 1: # Extract point seeded regions cpf.SetExtractionModeToPointSeededRegions() for s in seeds: cpf.AddSeed(s) - + elif mode == 2: # Test largest region cpf.SetExtractionModeToLargestRegion() - + elif mode == 3: # Test specified regions cpf.SetExtractionModeToSpecifiedRegions() for r in regions: cpf.AddSpecifiedRegion(r) - + elif mode == 4: # Extract all regions with scalar connectivity cpf.SetExtractionModeToLargestRegion() cpf.ScalarConnectivityOn() cpf.SetScalarRange(vrange[0], vrange[1]) - + elif mode == 5: # Extract point seeded regions cpf.SetExtractionModeToLargestRegion() cpf.ScalarConnectivityOn() cpf.SetScalarRange(vrange[0], vrange[1]) cpf.AlignedNormalsOn() cpf.SetNormalAngle(angle) - - cpf.Update() + + cpf.Update() return Actor(cpf.GetOutput()) - + def splitByConnectivity(actor, maxdepth=100): """ Split a mesh by connectivity and order the pieces by increasing area. @@ -1818,7 +1818,7 @@ def actor2Volume(actor, spacing=(1, 1, 1)): def signedDistance(actor, maxradius=0.5, bounds=(0, 1, 0, 1, 0, 1), dims=(10, 10, 10)): """ Compute signed distances over a volume from an input point cloud or mesh. - The output is a ``Volume`` object whose voxels contains the signed distance from + The output is a ``Volume`` object whose voxels contains the signed distance from the mesh. :param float maxradius: how far out to propagate distance calculation @@ -1890,7 +1890,7 @@ def voronoi3D(nuclei, bbfactor=1, tol=None): print('from vtkplotter import settings"') print('settings.voro_path="path_to_voro++_executable"') exit() - + # build polydata sourcePoints = vtk.vtkPoints() sourcePolygons = vtk.vtkCellArray() @@ -1906,7 +1906,7 @@ def voronoi3D(nuclei, bbfactor=1, tol=None): aid = sourcePoints.InsertNextPoint(p[0], p[1], p[2]) if tol: bp = np.array([p[0]-b[0], p[0]-b[1], - p[1]-b[2], p[1]-b[3], + p[1]-b[2], p[1]-b[3], p[2]-b[4], p[2]-b[5]]) bp = np.abs(bp) < tol if np.any(bp): @@ -1915,7 +1915,7 @@ def voronoi3D(nuclei, bbfactor=1, tol=None): ids.append(aid) else: ids.append(aid) - + # fill polygon elements if None in ids: continue @@ -1945,14 +1945,14 @@ def voronoi3D(nuclei, bbfactor=1, tol=None): return voro -def interpolateToVolume(actor, kernel='shepard', radius=None, +def interpolateToVolume(actor, kernel='shepard', radius=None, bounds=None, nullValue=None, dims=(20,20,20)): """ Generate a ``Volume`` by interpolating a scalar or vector field which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, voronoi, linear. - + :param str kernel: interpolation kernel type [shepard] :param float radius: radius of the local search :param list bounds: bounding box of the output Volume object @@ -1960,17 +1960,17 @@ def interpolateToVolume(actor, kernel='shepard', radius=None, :param float nullValue: value to be assigned to invalid points """ output = actor.polydata() - + # Create a probe volume probe = vtk.vtkImageData() probe.SetDimensions(dims) if bounds is None: - bounds = output.GetBounds() + bounds = output.GetBounds() probe.SetOrigin(bounds[0],bounds[2],bounds[4]) probe.SetSpacing((bounds[1]-bounds[0])/(dims[0]-1), (bounds[3]-bounds[2])/(dims[1]-1), (bounds[5]-bounds[4])/(dims[2]-1)) - + if radius is None: radius = min(bounds[1]-bounds[0], bounds[3]-bounds[2], bounds[5]-bounds[4])/3 @@ -1987,7 +1987,7 @@ def interpolateToVolume(actor, kernel='shepard', radius=None, kern.SetRadius(radius) elif kernel == 'voronoi': kern = vtk.vtkVoronoiKernel() - elif kernel == 'linear': + elif kernel == 'linear': kern = vtk.vtkLinearKernel() kern.SetRadius(radius) else: @@ -2008,14 +2008,14 @@ def interpolateToVolume(actor, kernel='shepard', radius=None, return Volume(interpolator.GetOutput()) -def interpolateToStructuredGrid(actor, kernel=None, radius=None, +def interpolateToStructuredGrid(actor, kernel=None, radius=None, bounds=None, nullValue=None, dims=None): """ Generate a volumetric dataset (vtkStructuredData) by interpolating a scalar or vector field which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, voronoi, linear. - + :param str kernel: interpolation kernel type [shepard] :param float radius: radius of the local search :param list bounds: bounding box of the output vtkStructuredGrid object @@ -2029,7 +2029,7 @@ def interpolateToStructuredGrid(actor, kernel=None, radius=None, if bounds is None: bounds = output.GetBounds() - + # Create a probe volume probe = vtk.vtkStructuredGrid() probe.SetDimensions(dims) @@ -2063,7 +2063,7 @@ def interpolateToStructuredGrid(actor, kernel=None, radius=None, kern.SetRadius(radius) elif kernel == 'voronoi': kern = vtk.vtkVoronoiKernel() - elif kernel == 'linear': + elif kernel == 'linear': kern = vtk.vtkLinearKernel() kern.SetRadius(radius) else: @@ -2082,9 +2082,9 @@ def interpolateToStructuredGrid(actor, kernel=None, radius=None, interpolator.SetNullPointsStrategyToClosestPoint() interpolator.Update() return interpolator.GetOutput() - -def streamLines(domain, probe, + +def streamLines(domain, probe, integrator='rk4', direction='forward', initialStepSize=None, @@ -2100,12 +2100,12 @@ def streamLines(domain, probe, ): """ Integrate a vector field to generate streamlines. - + The integration is performed using a specified integrator (Runge-Kutta). The length of a streamline is governed by specifying a maximum value either in physical arc length or in (local) cell length. Otherwise, the integration terminates upon exiting the field domain. - + :param domain: the vtk object that contains the vector field :param Actor probe: the Actor that probes the domain. Its coordinates will be the seeds for the streamlines @@ -2116,7 +2116,7 @@ def streamLines(domain, probe, :param float stepLength: length of step integration. :param dict extrapolateToBoundingBox: Vectors defined on a surface are extrapolated to the entire volume defined by its bounding box - + - kernel, (str) - interpolation kernel type [shepard] - radius (float)- radius of the local search - bounds, (list) - bounding box of the output Volume @@ -2129,21 +2129,21 @@ def streamLines(domain, probe, :param int ribbons: render lines as ribbons by joining them. An integer value represent the ratio of joining (e.g.: ribbons=2 groups lines 2 by 2) :param dict tubes: dictionary containing the parameters for the tube representation: - + - ratio, (int) - draws tube as longitudinal stripes - res, (int) - tube resolution (nr. of sides, 24 by default) - maxRadiusFactor (float) - max tube radius as a multiple of the min radius - varyRadius, (int) - radius varies based on the scalar or vector magnitude: - + - 0 - do not vary radius - 1 - vary radius by scalar - 2 - vary radius by vector - 3 - vary radius by absolute value of scalar - + :param list scalarRange: specify the scalar range for coloring - + .. hint:: Examples: |streamlines1.py|_ |streamribbons.py|_ |office.py|_ |streamlines2.py|_ - + |streamlines2| |office| |streamribbons| |streamlines1| """ @@ -2184,7 +2184,7 @@ def readPoints(): st.SetSurfaceStreamlines(surfaceConstrain) if stepLength: st.SetStepLength(stepLength) - + if 'f' in direction: st.SetIntegrationDirectionToForward() elif 'back' in direction: @@ -2200,10 +2200,10 @@ def readPoints(): st.SetIntegratorTypeToRungeKutta45() else: vc.printc("Error in streamlines, unknown integrator", integrator, c=1) - + st.Update() output = st.GetOutput() - + if ribbons: scalarSurface = vtk.vtkRuledSurfaceFilter() scalarSurface.SetInputConnection(st.GetOutputPort()) @@ -2211,7 +2211,7 @@ def readPoints(): scalarSurface.SetRuledModeToPointWalk() scalarSurface.Update() output = scalarSurface.GetOutput() - + if len(tubes): streamTube = vtk.vtkTubeFilter() streamTube.SetNumberOfSides(24) @@ -2221,13 +2221,13 @@ def readPoints(): streamTube.SetNumberOfSides(tubes['res']) # max tube radius as a multiple of the min radius - streamTube.SetRadiusFactor(50) + streamTube.SetRadiusFactor(50) if 'maxRadiusFactor' in tubes: streamTube.SetRadius(tubes['maxRadiusFactor']) - + if 'ratio' in tubes: streamTube.SetOnRatio(int(tubes['ratio'])) - + if 'varyRadius' in tubes: streamTube.SetVaryRadius(int(tubes['varyRadius'])) @@ -2246,7 +2246,7 @@ def readPoints(): sta.GetProperty().BackfaceCullingOn() sta.phong() return sta - + sta = Actor(output, c=None) sta.mapper.SetScalarRange(grid.GetPointData().GetScalars().GetRange()) if scalarRange is not None: @@ -2255,17 +2255,17 @@ def readPoints(): def densifyCloud(actor, targetDistance, closestN=6, radius=0, maxIter=None, maxN=None): - """Adds new points to an input point cloud. - The new points are created in such a way that all points in any local neighborhood are - within a target distance of one another. - - The algorithm works as follows. For each input point, the distance to all points + """Adds new points to an input point cloud. + The new points are created in such a way that all points in any local neighborhood are + within a target distance of one another. + + The algorithm works as follows. For each input point, the distance to all points in its neighborhood is computed. If any of its neighbors is further than the target distance, the edge connecting the point and its neighbor is bisected and a new point is inserted at the - bisection point. A single pass is completed once all the input points are visited. + bisection point. A single pass is completed once all the input points are visited. Then the process repeats to the limit of the maximum number of iterations. - .. note:: Points will be created in an iterative fashion until all points in their + .. note:: Points will be created in an iterative fashion until all points in their local neighborhood are the target distance apart or less. Note that the process may terminate early due to the limit on the maximum number of iterations. By default the target distance is set to 0.5. @@ -2303,7 +2303,7 @@ def readPoints(): dens.SetNumberOfClosestPoints(closestN) else: vc.printc("Error in densifyCloud: set either radius or closestN", c=1) - exit() + exit() dens.Update() pts = vtk_to_numpy(dens.GetOutput().GetPoints().GetData()) return vs.Points(pts, c=None).pointSize(3) @@ -2314,33 +2314,33 @@ def frequencyPassFilter(volume, lowcutoff=None, highcutoff=None, order=1): Low-pass and high-pass filtering become trivial in the frequency domain. A portion of the pixels/voxels are simply masked or attenuated. This function applies a high pass Butterworth filter that attenuates the frequency domain - image with the function - + image with the function + .. image:: https://wikimedia.org/api/rest_v1/media/math/render/svg/9c4d02a66b6ff279aae0c4bf07c25e5727d192e4 - - The gradual attenuation of the filter is important. + + The gradual attenuation of the filter is important. A simple high-pass filter would simply mask a set of pixels in the frequency domain, - but the abrupt transition would cause a ringing effect in the spatial domain. - + but the abrupt transition would cause a ringing effect in the spatial domain. + :param list lowcutoff: the cutoff frequencies for x, y and z :param list highcutoff: the cutoff frequencies for x, y and z :param int order: order determines sharpness of the cutoff curve - Check out also this example: - + Check out also this example: + |idealpass| - """ + """ #https://lorensen.github.io/VTKExamples/site/Cxx/ImageProcessing/IdealHighPass if isinstance(volume, Volume): img = volume.imagedata() elif isinstance(volume, vtk.vtkImageData): img = volume - + fft = vtk.vtkImageFFT() fft.SetInputData(img) fft.Update() out = fft.GetOutput() - + if highcutoff: butterworthLowPass = vtk.vtkImageButterworthLowPass() butterworthLowPass.SetInputData(out) From 12f22d81f44a4c10765e4925b6232378fb6ccf2e Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 08/67] Typo update for vtkplotter/colors.py --- vtkplotter/colors.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/vtkplotter/colors.py b/vtkplotter/colors.py index b8841c46..a3bbc878 100644 --- a/vtkplotter/colors.py +++ b/vtkplotter/colors.py @@ -182,7 +182,7 @@ def getColor(rgb=None, hsv=None): for sc in rgb: seqcol.append(getColor(sc)) return seqcol - + if str(rgb).isdigit(): rgb = int(rgb) @@ -272,7 +272,7 @@ def rgb2hsv(rgb): """Convert RGB to HSV color.""" ma = vtk.vtkMath() return ma.RGBToHSV(getColor(rgb)) - + def colorMap(value, name="jet", vmin=None, vmax=None): """Map a real value in range [vmin, vmax] to a (r,g,b) color scale. @@ -287,20 +287,20 @@ def colorMap(value, name="jet", vmin=None, vmax=None): .. note:: Most frequently used color maps: |colormaps| - + Matplotlib full list: - + .. image:: https://matplotlib.org/1.2.1/_images/show_colormaps.png .. tip:: Can also use directly a matplotlib color map: :Example: .. code-block:: python - + from vtkplotter import colorMap import matplotlib.cm as cm print( colorMap(0.2, cm.flag, 0, 1) ) - + (1.0, 0.809016994374948, 0.6173258487801733) """ if not _mapscales: @@ -616,8 +616,8 @@ def printc(*strings, **keys): printc('anything', c='red', bold=False, end='' ) printc('anything', 455.5, vtkObject, c='green') printc(299792.48, c=4) # 4 is blue - - .. hint:: |colorprint.py|_ + + .. hint:: |colorprint.py|_ |colorprint| """ @@ -646,7 +646,7 @@ def printc(*strings, **keys): dim = keys.pop("dim", False) invert = keys.pop("invert", False) box = keys.pop("box", "") - + if c is True: c = 'green' elif c is False: @@ -660,7 +660,7 @@ def printc(*strings, **keys): for i, s in enumerate(strings): if i == ns: separator = "" - + #txt += str(s) + separator if "~" in str(s): # "in" for some reasons changes s for k in emoji.keys(): @@ -730,7 +730,7 @@ def printc(*strings, **keys): sys.stdout.write(outtxt) else: sys.stdout.write(special + cseq + txt + "\x1b[0m" + end) - + except: print(*strings, end=end) From 749d75fbfb5de59ee7bde3c419c217b634327417 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 09/67] Typo update for vtkplotter/docs.py --- vtkplotter/docs.py | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/vtkplotter/docs.py b/vtkplotter/docs.py index 0567b290..66135419 100644 --- a/vtkplotter/docs.py +++ b/vtkplotter/docs.py @@ -6,7 +6,7 @@ .. note:: **Please check out the** `git repository `_. A full list of examples can be found in directories: - + - `examples/basic `_ , - `examples/advanced `_ , - `examples/volumetric `_, @@ -87,7 +87,7 @@ def tips():

My x3d rendering web page

- This example loads a 3D scene from file ~fileoutput generated by + This example loads a 3D scene from file ~fileoutput generated by vtkplotter (see e.g. export_x3d.py). @@ -105,9 +105,9 @@ def tips():
-
PS: This should work with Firefox/IE. +
PS: This should work with Firefox/IE. With Chrome, webgl might not be active by default, then try:
-google-chrome --enable-webgl --use-gl=desktop +google-chrome --enable-webgl --use-gl=desktop --log-level=0 --allow-file-access-from-files --allow-file-access ~fileoutput @@ -129,14 +129,14 @@ def tips(): :width: 250 px :target: thinplate_grid.py_ :alt: thinplate_grid.py - + .. |gyroscope2.py| replace:: gyroscope2.py .. _gyroscope2.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/simulations/gyroscope2.py .. |gyroscope2| image:: https://user-images.githubusercontent.com/32848391/50738942-687b5780-11d9-11e9-97f0-72bbd63f7d6e.gif :width: 250 px :target: gyroscope2.py_ :alt: gyroscope2.py - + .. |trail.py| replace:: trail.py .. _trail.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/trail.py .. |trail| image:: https://user-images.githubusercontent.com/32848391/50738846-be033480-11d8-11e9-99b7-c4ceb90ae482.jpg @@ -545,8 +545,8 @@ def tips(): :width: 250 px :target: geodesic.py_ :alt: geodesic.py - - + + .. |cutAndCap.py| replace:: cutAndCap.py .. _cutAndCap.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/cutAndCap.py .. |cutAndCap| image:: https://user-images.githubusercontent.com/32848391/51930515-16ee7300-23fb-11e9-91af-2b6b3d626246.png @@ -756,7 +756,7 @@ def tips(): .. |pmatrix| image:: https://user-images.githubusercontent.com/32848391/55098070-6da3c080-50bd-11e9-8f2b-be94a3f01831.png :width: 250 px - + .. |distance2mesh.py| replace:: distance2mesh.py .. _distance2mesh.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/distance2mesh.py .. |distance2mesh| image:: https://user-images.githubusercontent.com/32848391/55965881-b5a71380-5c77-11e9-8680-5bddceab813a.png @@ -770,21 +770,21 @@ def tips(): :width: 250 px :target: pendulum.py_ :alt: pendulum.py - + .. |latex.py| replace:: latex.py .. _latex.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/latex.py .. |latex| image:: https://user-images.githubusercontent.com/32848391/55568648-6190b200-5700-11e9-9547-0798c588a7a5.png :width: 250 px :target: latex.py_ :alt: latex.py - + .. |ft04_heat_gaussian.py| replace:: ft04_heat_gaussian.py .. _ft04_heat_gaussian.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/other/dolfin/ft04_heat_gaussian.py .. |ft04_heat_gaussian| image:: https://user-images.githubusercontent.com/32848391/55578167-88a5ae80-5715-11e9-84ea-bdab54099887.gif :width: 250 px :target: ft04_heat_gaussian.py_ :alt: ft04_heat_gaussian.py - + .. |scalbar| image:: https://user-images.githubusercontent.com/32848391/55964528-2ac51980-5c75-11e9-9357-8c13d753a612.png :width: 250 px @@ -806,23 +806,23 @@ def tips(): :width: 250 px :target: turing_pattern.py_ :alt: turing_pattern.py - + .. |demo_cahn-hilliard.py| replace:: demo_cahn-hilliard.py .. _demo_cahn-hilliard.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/other/dolfin/demo_cahn-hilliard.py .. |demo_cahn-hilliard| image:: https://user-images.githubusercontent.com/32848391/56664730-edb34b00-66a8-11e9-9bf3-73431f2a98ac.gif :width: 250 px :target: demo_cahn-hilliard.py_ :alt: demo_cahn-hilliard.py - - + + .. |navier-stokes_lshape.py| replace:: navier-stokes_lshape.py .. _navier-stokes_lshape.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/other/dolfin/navier-stokes_lshape.py .. |navier-stokes_lshape| image:: https://user-images.githubusercontent.com/32848391/56671156-6bc91f00-66b4-11e9-8c58-e6b71e2ad1d0.gif :width: 250 px :target: navier-stokes_lshape.py_ :alt: navier-stokes_lshape.py - - + + .. |mesh_map2cell.py| replace:: mesh_map2cell.py .. _mesh_map2cell.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/mesh_map2cell.py .. |mesh_map2cell| image:: https://user-images.githubusercontent.com/32848391/56600859-0153a880-65fa-11e9-88be-34fd96b18e9a.png @@ -837,7 +837,7 @@ def tips(): :width: 250 px :target: ex03_poisson.py_ :alt: ex03_poisson.py - + .. |elastodynamics.py| replace:: elastodynamics.py .. _elastodynamics.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/other/dolfin/elastodynamics.py .. |elastodynamics| image:: https://user-images.githubusercontent.com/32848391/54932788-bd4a8680-4f1b-11e9-9326-33645171a45e.gif @@ -880,7 +880,7 @@ def tips(): :width: 250 px :target: pi_estimate.py_ :alt: pi_estimate.py - + .. |isolines.py| replace:: isolines.py .. _isolines.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/isolines.py .. |isolines| image:: https://user-images.githubusercontent.com/32848391/56752570-de0b3380-6788-11e9-8679-6697c6fa7e5a.png @@ -1003,7 +1003,7 @@ def tips(): :width: 300 px :target: elasticbeam.py_ :alt: elasticbeam.py - + .. |specular.py| replace:: specular.py .. _specular.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/specular.py .. |specular| image:: https://user-images.githubusercontent.com/32848391/57543051-8c030a00-7353-11e9-84cd-b01f3449d255.jpg @@ -1030,13 +1030,13 @@ def tips(): .. |idealpass| image:: https://raw.githubusercontent.com/lorensen/VTKExamples/master/src/Testing/Baseline/Cxx/ImageProcessing/TestIdealHighPass.png :width: 250 px :target: idealpass.link_ - + .. |buildmesh.py| replace:: buildmesh.py .. _buildmesh.py: https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/buildmesh.py .. |buildmesh| image:: https://user-images.githubusercontent.com/32848391/57858625-b0e2fb80-77f1-11e9-94f0-1973ed86ae70.png :width: 250 px :target: buildmesh.py_ :alt: buildmesh.py - + """ From d49eaa67101f5fc8f108d929d4ff2097d94dbc77 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 10/67] Typo update for vtkplotter/dolfin.py --- vtkplotter/dolfin.py | 118 +++++++++++++++++++++---------------------- 1 file changed, 59 insertions(+), 59 deletions(-) diff --git a/vtkplotter/dolfin.py b/vtkplotter/dolfin.py index 9c83f610..fa56494d 100644 --- a/vtkplotter/dolfin.py +++ b/vtkplotter/dolfin.py @@ -36,23 +36,23 @@ Install with commands (e.g. in Anaconda3): .. code-block:: bash - + conda install -c conda-forge fenics pip install vtkplotter Basic example: - + .. code-block:: python - + import dolfin from vtkplotter.dolfin import datadir, plot - + mesh = dolfin.Mesh(datadir+"dolfin_fine.xml") - + plot(mesh) |dolfinmesh| - + Find many more examples in `vtkplotter/examples/dolfin `_ @@ -134,18 +134,18 @@ def _inputsort(obj): mesh = None if not utils.isSequence(obj): obj = [obj] - + for ob in obj: inputtype = str(type(ob)) #printc('inputtype is', inputtype, c=2) - + if "vtk" in inputtype: # skip vtk objects, will be added later continue - + if "dolfin" in inputtype: if "MeshFunction" in inputtype: mesh = ob.mesh() - + try: import dolfin r = ob.dim() @@ -158,13 +158,13 @@ def _inputsort(obj): u = dolfin.Function(V) v2d = dolfin.vertex_to_dof_map(V) u.vector()[v2d] = ob.array() - + except: printc('~times Sorry could not deal with your MeshFunction', c=1) return None # tdim = mesh.topology().dim() -# d = ob.dim() +# d = ob.dim() # if tdim == 2 and d == 2: # import matplotlib.tri as tri # xy = mesh.coordinates() @@ -178,7 +178,7 @@ def _inputsort(obj): u = ob elif "Mesh" in inputtype: mesh = ob - + if "str" in inputtype: import dolfin mesh = dolfin.Mesh(ob) @@ -189,7 +189,7 @@ def _inputsort(obj): mesh = V.mesh() if u and not mesh and hasattr(u, "mesh"): mesh = u.mesh() - + if not mesh: printc("~times Error: dolfin mesh is not defined.", c=1) exit() @@ -205,24 +205,24 @@ def _inputsort(obj): def plot(*inputobj, **options): """ Plot the object(s) provided. - + Input can be: ``vtkActor``, ``vtkVolume``, ``dolfin.Mesh``, ``dolfin.MeshFunction*``, ``dolfin.Expression`` or ``dolfin.Function``. :return: the current ``Plotter`` class instance. :param str mode: one or more of the following can be combined in any order - + - `mesh`/`color`, will plot the mesh, by default colored with a scalar if available - + - `warp`, mesh will be modified by a displacement function - `contour`, to be implemented - `arrows`, mesh displacements are plotted as scaled arrows. - `lines`, mesh displacements are plotted as scaled lines. - `tensors`, to be implemented - - :param bool add: add the input objects without clearing the already plotted ones - :param float density: show only a subset of lines or arrows [0-1] + + :param bool add: add the input objects without clearing the already plotted ones + :param float density: show only a subset of lines or arrows [0-1] :param bool wire[frame]: visualize mesh as wireframe [False] :param c[olor]: set mesh color [None] :param float alpha: set object's transparency [1] @@ -238,14 +238,14 @@ def plot(*inputobj, **options): :param int bands: group colors in `n` bands :param str shading: mesh shading ['flat', 'phong', 'gouraud'] :param str text: add a gray text comment to the top-left of the window [None] - + :param dict isolines: dictionary of isolines properties - + - n, (int) - add this number of isolines to the mesh - c, - isoline color - lw, (float) - isoline width - z, (float) - add to the isoline z coordinate to make them more visible - + :param float warpZfactor: elevate z-axis by scalar value (useful for 2D geometries) :param float warpYfactor: elevate z-axis by scalar value (useful for 1D geometries) @@ -255,7 +255,7 @@ def plot(*inputobj, **options): :param int N: automatically subdvide window in N renderers :param list pos: (x,y) coordinates of the window position on screen :param size: window size (x,y) - + :param str title: window title :param bg: background color name of window :param bg2: second background color name to create a color gradient @@ -292,55 +292,55 @@ def plot(*inputobj, **options): :param float azimuth: add azimuth rotation of the scene, in degrees :param float elevation: add elevation rotation of the scene, in degrees :param float roll: add roll-type rotation of the scene, in degrees - + :param dict camera: Camera parameters can further be specified with a dictionary assigned to the ``camera`` keyword: (E.g. `show(camera={'pos':(1,2,3), 'thickness':1000,})`) - + - pos, `(list)`, the position of the camera in world coordinates - focalPoint `(list)`, the focal point of the camera in world coordinates - viewup `(list)`, the view up direction for the camera - distance `(float)`, set the focal point to the specified distance from the camera position. - clippingRange `(float)`, distance of the near and far clipping planes along the direction of projection. - parallelScale `(float)`, - scaling used for a parallel projection, i.e. the height of the viewport + scaling used for a parallel projection, i.e. the height of the viewport in world-coordinate distances. The default is 1. Note that the "scale" parameter works as - an "inverse scale", larger numbers produce smaller images. + an "inverse scale", larger numbers produce smaller images. This method has no effect in perspective projection mode. - thickness `(float)`, - set the distance between clipping planes. This method adjusts the far clipping + set the distance between clipping planes. This method adjusts the far clipping plane to be set a distance 'thickness' beyond the near clipping plane. - viewAngle `(float)`, the camera view angle, which is the angular height of the camera view measured in degrees. The default angle is 30 degrees. - This method has no effect in parallel projection mode. + This method has no effect in parallel projection mode. The formula for setting the angle up for perfect perspective viewing is: angle = 2*atan((h/2)/d) where h is the height of the RenderWindow (measured by holding a ruler up to your screen) and d is the distance from your eyes to the screen. - + :param int interactorStyle: change the style of muose interaction of the scene :param bool q: exit python session after returning. """ - + if len(inputobj) == 0: return interactive() - + mesh, u = _inputsort(inputobj) mode = options.pop("mode", 'mesh') ttime = options.pop("z", None) - + add = options.pop("add", False) wire = options.pop("wire", False) wireframe = options.pop("wireframe", None) if wireframe is not None: wire = wireframe - + c = options.pop("c", None) color = options.pop("color", None) if color is not None: c = color - + lc = options.pop("lc", None) alpha = options.pop("alpha", 1) @@ -390,13 +390,13 @@ def plot(*inputobj, **options): aet = settings.plotter_instance.axes_instances if len(aet)>at and isinstance(aet[at], vtk.vtkCubeAxesActor): aet[at].SetZTitle(settings.ztitle) - + # change some default to emulate standard behaviours options['verbose'] = False # dont disturb if style == 0 or style == 'vtk': font = 'courier' - axes = options.pop('axes', None) + axes = options.pop('axes', None) if axes is None: options['axes'] = 8 else: @@ -405,12 +405,12 @@ def plot(*inputobj, **options): cmap = 'rainbow' elif style == 1 or style == 'matplotlib': font = 'courier' - bg = options.pop('bg', None) + bg = options.pop('bg', None) if bg is None: options['bg'] = 'white' else: options['bg'] = bg - axes = options.pop('axes', None) + axes = options.pop('axes', None) if axes is None: options['axes'] = 8 else: @@ -419,7 +419,7 @@ def plot(*inputobj, **options): cmap = 'viridis' elif style == 2 or style == 'paraview': font = 'arial' - bg = options.pop('bg', None) + bg = options.pop('bg', None) if bg is None: options['bg'] = (82, 87, 110) else: @@ -434,7 +434,7 @@ def plot(*inputobj, **options): options['bg2'] = (117, 117, 234) else: options['bg'] = bg - axes = options.pop('axes', None) + axes = options.pop('axes', None) if axes is None: options['axes'] = 10 else: @@ -455,17 +455,17 @@ def plot(*inputobj, **options): options['axes'] = axes # put back if cmap is None: cmap = 'binary' - + ################################################################# actors = [] if add and settings.plotter_instance: - actors = settings.plotter_instance.actors + actors = settings.plotter_instance.actors if 'mesh' in mode or 'color' in mode or 'warp' in mode or 'displac' in mode: if 'warp' in mode: #deprecation printc("~bomb Please use 'displacement' instead of 'warp' in mode!", c=1) - + actor = MeshActor(u, mesh, wire=wire) if lighting: actor.lighting(lighting) @@ -508,7 +508,7 @@ def plot(*inputobj, **options): actor.addScalarBar(horizontal=True, vmin=vmin, vmax=vmax) else: actor.addScalarBar(horizontal=False, vmin=vmin, vmax=vmax) - + if 'warp' in mode or 'displac' in mode: if delta is None: delta = [u(p) for p in mesh.coordinates()] @@ -516,7 +516,7 @@ def plot(*inputobj, **options): actor.polydata(False).GetPoints().SetData(numpy_to_vtk(movedpts)) actor.poly.GetPoints().Modified() actor.u_values = delta - + if warpZfactor: scals = actor.scalars(0) if len(scals): @@ -527,16 +527,16 @@ def plot(*inputobj, **options): if len(scals): pts_act = actor.getPoints(copy=False) pts_act[:, 1] = scals*warpYfactor - + if len(isolns) > 0: ison = isolns.pop("n", 10) isocol = isolns.pop("c", 'black') isoalpha = isolns.pop("alpha", 1) isolw = isolns.pop("lw", 1) - + isos = isolines(actor, n=ison).color(isocol).lw(isolw).alpha(isoalpha) - isoz = isolns.pop("z", None) + isoz = isolns.pop("z", None) if isoz is not None: # kind of hack to make isolines visible on flat meshes d = isoz else: @@ -545,8 +545,8 @@ def plot(*inputobj, **options): actors.append(isos) actors.append(actor) - - + + ################################################################# if 'arrow' in mode or 'line' in mode: if 'arrow' in mode: @@ -577,7 +577,7 @@ def plot(*inputobj, **options): if text: textact = Text(text, font=font) actors.append(textact) - + if 'at' in options.keys() and 'interactive' not in options.keys(): if settings.plotter_instance: N = settings.plotter_instance.shape[0]*settings.plotter_instance.shape[1] @@ -590,9 +590,9 @@ def plot(*inputobj, **options): if 0 in a2.renderedAt: # remove old message settings.plotter_instance.removeActor(a2) break - + return show(actors, **options) - + ################################################################################### class MeshActor(Actor): @@ -630,7 +630,7 @@ def __init__( if u: u_values = np.array([u(p) for p in self.mesh.coordinates()]) #print(u_values) - + if u_values is not None: # colorize if a dolfin function is passed if len(u_values.shape) == 2: if u_values.shape[1] in [2, 3]: # u_values is 2D or 3D @@ -639,7 +639,7 @@ def __init__( else: # u_values is 1D dispsizes = u_values self.addPointScalars(dispsizes, "u_values") - + def MeshPoints(*inputobj, **options): """ @@ -719,7 +719,7 @@ def MeshLines(*inputobj, **options): def MeshArrows(*inputobj, **options): """ Build arrows representing displacements. - + :param float s: cross-section size of the arrow :param float rescale: apply a rescaling factor to the length """ @@ -821,7 +821,7 @@ def MeshArrows(*inputobj, **options): # ## Mapping from submesh to grandparent mesh (less than satisfying solution to question in fenics forum link) ## Bonus points for getting this kind of map composition to work: -## u_test_a = u_test.vector().get_local() # destination array +## u_test_a = u_test.vector().get_local() # destination array ## u_test_a[m[b[t]]] = us_a[s] # transfer ( not working ) ## u_test.vector().set_local(u_test_a) #for Vs_dof, val in enumerate(us.vector().get_local()): From 60a6878fde4392eb6046d806d3ae9f6e20b0f972 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:34 +0200 Subject: [PATCH 11/67] Typo update for vtkplotter/plotter.py --- vtkplotter/plotter.py | 98 +++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/vtkplotter/plotter.py b/vtkplotter/plotter.py index 32009f34..69ecf81a 100644 --- a/vtkplotter/plotter.py +++ b/vtkplotter/plotter.py @@ -53,7 +53,7 @@ def show(*actors, **options """ Create on the fly an instance of class ``Plotter`` and show the object(s) provided. - Allowed input objects are: ``filename``, ``vtkPolyData``, ``vtkActor``, + Allowed input objects are: ``filename``, ``vtkPolyData``, ``vtkActor``, ``vtkActor2D``, ``vtkImageActor``, ``vtkAssembly`` or ``vtkVolume``. If filename is given, its type is guessed based on its extension. @@ -85,28 +85,28 @@ def show(*actors, **options :param dict camera: Camera parameters can further be specified with a dictionary assigned to the ``camera`` keyword: (E.g. `show(camera={'pos':(1,2,3), 'thickness':1000,})`) - + - pos, `(list)`, the position of the camera in world coordinates - focalPoint `(list)`, the focal point of the camera in world coordinates - viewup `(list)`, the view up direction for the camera - distance `(float)`, set the focal point to the specified distance from the camera position. - clippingRange `(float)`, distance of the near and far clipping planes along the direction of projection. - parallelScale `(float)`, - scaling used for a parallel projection, i.e. the height of the viewport + scaling used for a parallel projection, i.e. the height of the viewport in world-coordinate distances. The default is 1. Note that the "scale" parameter works as - an "inverse scale", larger numbers produce smaller images. + an "inverse scale", larger numbers produce smaller images. This method has no effect in perspective projection mode. - thickness `(float)`, - set the distance between clipping planes. This method adjusts the far clipping + set the distance between clipping planes. This method adjusts the far clipping plane to be set a distance 'thickness' beyond the near clipping plane. - viewAngle `(float)`, the camera view angle, which is the angular height of the camera view measured in degrees. The default angle is 30 degrees. - This method has no effect in parallel projection mode. + This method has no effect in parallel projection mode. The formula for setting the angle up for perfect perspective viewing is: angle = 2*atan((h/2)/d) where h is the height of the RenderWindow (measured by holding a ruler up to your screen) and d is the distance from your eyes to the screen. - + :param bool interactive: pause and interact with window (True) or continue execution (False) :param float rate: maximum rate of `show()` in Hertz @@ -130,7 +130,7 @@ def show(*actors, **options .. note:: With multiple renderers, keyword ``at`` can become a `list`, e.g. .. code-block:: python - + from vtkplotter import * s = Sphere() c = Cube() @@ -258,8 +258,8 @@ def interactive(): if hasattr(settings.plotter_instance, 'interactor'): settings.plotter_instance.interactor.Start() return settings.plotter_instance - - + + def clear(actor=()): """ Clear specific actor or list of actors from the current rendering window. @@ -284,23 +284,23 @@ def closeWindow(plotterInstance=None): def plotMatrix(M, title='matrix', continuous=True, cmap='Greys'): """ Plot a matrix using `matplotlib`. - + :Example: .. code-block:: python from vtkplotter.dolfin import plotMatrix import numpy as np - + M = np.eye(9) + np.random.randn(9,9)/4 - + plotMatrix(M) - + |pmatrix| """ import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.axes_grid1 import make_axes_locatable - + M = numpy.array(M) m,n = numpy.shape(M) M = M.round(decimals=2) @@ -321,14 +321,14 @@ def plotMatrix(M, title='matrix', continuous=True, cmap='Greys'): cb.set_ticks(unq) cb.set_ticklabels(unq) plt.show() - - + + ######################################################################## class Plotter: """ Main class to manage actors. - :param list shape: shape of the grid of renderers in format (rows, columns). + :param list shape: shape of the grid of renderers in format (rows, columns). Ignored if N is specified. :param int N: number of desired renderers arranged in a grid automatically. :param list pos: (x,y) position in pixels of top-left corneer of the rendering window @@ -359,7 +359,7 @@ class Plotter: |multiwindows| """ - + def __init__( self, shape=(1, 1), @@ -434,7 +434,7 @@ def __init__( self.mouseMiddleClickFunction = None self.mouseRightClickFunction = None self._first_viewup = True - + self.xtitle = settings.xtitle # x axis label and units self.ytitle = settings.ytitle # y axis label and units self.ztitle = settings.ztitle # z axis label and units @@ -476,7 +476,7 @@ def __init__( ind = i minl = l shape = lm[ind] - + if size == "auto": # figure out a reasonable window size f = 1.5 xs = y / f * shape[1] # because y Date: Tue, 21 May 2019 22:59:35 +0200 Subject: [PATCH 12/67] Typo update for vtkplotter/settings.py --- vtkplotter/settings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vtkplotter/settings.py b/vtkplotter/settings.py index 06dba0c4..5b927361 100644 --- a/vtkplotter/settings.py +++ b/vtkplotter/settings.py @@ -8,7 +8,7 @@ .. note:: **Please check out the** `git repository `_. A full list of examples can be found in directories: - + - `examples/basic `_ , - `examples/advanced `_ , - `examples/volumetric `_, From 5197f2fdbc89ac92e25f28742076575c75dab931 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:35 +0200 Subject: [PATCH 13/67] Typo update for vtkplotter/shapes.py --- vtkplotter/shapes.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/vtkplotter/shapes.py b/vtkplotter/shapes.py index 66a69d57..dfff4284 100644 --- a/vtkplotter/shapes.py +++ b/vtkplotter/shapes.py @@ -1329,9 +1329,9 @@ def Text( 6, middle-right 7, middle-left 8, top-middle - + If a pair (x,y) is passed as input the 2D text is place at that - position in the coordinate system of the 2D screen (with the + position in the coordinate system of the 2D screen (with the origin sitting at the bottom left). :type pos: list, int @@ -1341,7 +1341,7 @@ def Text( (bottom-left, bottom-right, top-left, top-right, centered). :param bg: background color of corner annotations. Only applies of `pos` is ``int``. :param str font: additional available fonts are: - + - Ageo - Aldora - CallingCode @@ -1358,14 +1358,14 @@ def Text( - PointedLaidSt - SchoolTeacher - SpecialElite - + Font choice does not apply for 3D text. A path to `otf` or `ttf` font-file can also be supplied as input. - + All fonts are free for personal use. Check out conditions in `vtkplotter/fonts/licenses` for commercial use and: https://www.1001freefonts.com - + :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 @@ -1373,7 +1373,7 @@ def Text( .. hint:: Examples, |fonts.py|_ |colorcubes.py|_ |markpoint.py|_ |annotations.py|_ |colorcubes| |markpoint| - + |fonts| """ if c is None: # automatic black or white @@ -1410,7 +1410,7 @@ def Text( setattr(ca, 'renderedAt', set()) settings.collectable_actors.append(ca) return ca - + elif len(pos)==2: # passing (x,y) coords actor2d = vtk.vtkActor2D() @@ -1478,7 +1478,7 @@ def Text( ttactor.SetMapper(ttmapper) ttactor.GetProperty().SetColor(colors.getColor(c)) ttmapper.Update() - + bb = tt.GetOutput().GetBounds() dx, dy = (bb[1] - bb[0]) / 2 * s, (bb[3] - bb[2]) / 2 * s cm = np.array([(bb[1] + bb[0]) / 2, (bb[3] + bb[2]) / 2, (bb[5] + bb[4]) / 2]) * s @@ -1495,9 +1495,9 @@ def Text( shift += np.array([-dx, -dy, 0]) else: colors.printc("~lightning Text(): Unknown justify type", justify, c=1) - + ttactor.GetProperty().SetOpacity(alpha) - + nax = np.linalg.norm(normal) if nax: normal = np.array(normal) / nax @@ -1621,5 +1621,5 @@ def build_img_plt(formula, tfile): colors.printc(' latex or dvipng not installed?', c=1) colors.printc(' Try: usetex=False' , c=1) colors.printc(' Try: sudo apt install dvipng' , c=1) - + return vactor From 040d4326159eecc910af464db9100c20f128c82b Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 22:59:36 +0200 Subject: [PATCH 14/67] Typo update for vtkplotter/utils.py --- vtkplotter/utils.py | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/vtkplotter/utils.py b/vtkplotter/utils.py index dd564329..1295e066 100644 --- a/vtkplotter/utils.py +++ b/vtkplotter/utils.py @@ -41,7 +41,7 @@ class ProgressBar: :Example: .. code-block:: python - + import time pb = ProgressBar(0,400, c='red') for i in pb.range(): @@ -249,7 +249,7 @@ def precision(x, p): """ Returns a string representation of `x` formatted with precision `p`. - Based on the webkit javascript implementation taken + Based on the webkit javascript implementation taken `from here `_, and implemented by `randlet `_. """ @@ -474,7 +474,7 @@ def printvtkactor(actor, tab=""): colors.printc(tab + " diag. size: ", c="g", bold=1, end="") colors.printc(precision(actor.diagonalSize(), 6), c="g", bold=0) - + _area = actor.area() if _area: colors.printc(tab + " area: ", c="g", bold=1, end="") @@ -641,7 +641,7 @@ def printHistogram(data, bins=10, height=10, logscale=False, minbin=0, """ Ascii histogram printing. Input can also be ``Volume`` or ``Actor``. - Returns the raw data before binning (useful when passing vtk objects). + Returns the raw data before binning (useful when passing vtk objects). :param int bins: number of histogram bins :param int height: height of the histogram in character units @@ -652,10 +652,10 @@ def printHistogram(data, bins=10, height=10, logscale=False, minbin=0, :param str,int c: ascii color :param bool char: use boldface :param str title: histogram title - + :Example: .. code-block:: python - + from vtkplotter import printHistogram import numpy as np d = np.random.normal(size=1000) @@ -666,10 +666,10 @@ def printHistogram(data, bins=10, height=10, logscale=False, minbin=0, |printhisto| """ # Adapted from http://pyinsci.blogspot.com/2009/10/ascii-histograms.html - + if not horizontal: # better aspect ratio bins *= 2 - + isimg = isinstance(data, vtk.vtkImageData) isvol = isinstance(data, vtk.vtkVolume) if isimg or isvol: @@ -690,7 +690,7 @@ def printHistogram(data, bins=10, height=10, logscale=False, minbin=0, arr = data.polydata().GetCellData().GetScalars() if not arr: return - + from vtk.util.numpy_support import vtk_to_numpy data = vtk_to_numpy(arr) @@ -700,7 +700,7 @@ def printHistogram(data, bins=10, height=10, logscale=False, minbin=0, hi = h[0][minbin:-1] else: hi = h[0] - + if sys.version_info[0] < 3 and char == u"\U00002589": char = "*" # python2 hack if char == u"\U00002589" and horizontal: @@ -783,11 +783,11 @@ def makeBands(inputlist, numberOfBands): return np.array(newlist) - - + + def resampleArrays(source, target, tol=None): """Resample point and cell data of a dataset on points from another dataset. - + :param float tol: set the tolerance used to compute whether a point in the target is in a cell of the source. Points without resampled values, and their cells, are be marked as blank. @@ -802,7 +802,6 @@ def resampleArrays(source, target, tol=None): rs.SetTolerance(tol) rs.Update() return rs.GetOutput() - - - - \ No newline at end of file + + + From 9636e346deef4bdd0622055ad338a2ffb74b1623 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:13 +0200 Subject: [PATCH 15/67] Removed trailing spaces in examples/volumetric/interpolateVolume.py --- examples/volumetric/interpolateVolume.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/volumetric/interpolateVolume.py b/examples/volumetric/interpolateVolume.py index ca126ae2..47708534 100644 --- a/examples/volumetric/interpolateVolume.py +++ b/examples/volumetric/interpolateVolume.py @@ -2,7 +2,7 @@ Generate a voxel dataset (vtkImageData) by interpolating a scalar which is only known on a scattered set of points or mesh. Available interpolation kernels are: shepard, gaussian, voronoi, linear. -The blue layer is the result of thresholding the volume +The blue layer is the result of thresholding the volume between 0.3 and 0.4 and assigning it the new value 0.9 """ # Author: Giovanni Dalmasso From 130cc52a03961e9ef150fa3e2d9549f342e2be46 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:13 +0200 Subject: [PATCH 16/67] Removed trailing spaces in examples/volumetric/office.py --- examples/volumetric/office.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/volumetric/office.py b/examples/volumetric/office.py index 5165c3db..7351e523 100644 --- a/examples/volumetric/office.py +++ b/examples/volumetric/office.py @@ -1,6 +1,6 @@ """ Stream tubes originating from a probing grid of points. -Data is from CFD analysis of airflow in an office with +Data is from CFD analysis of airflow in an office with ventilation and a burning cigarette. """ # see original script at: From 52c99a7281ac474052689f6d1eceb71ee5858164 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:14 +0200 Subject: [PATCH 17/67] Removed trailing spaces in examples/volumetric/office_furniture.py --- examples/volumetric/office_furniture.py | 44 ++++++++++++------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/examples/volumetric/office_furniture.py b/examples/volumetric/office_furniture.py index 5dbff54b..be53067f 100644 --- a/examples/volumetric/office_furniture.py +++ b/examples/volumetric/office_furniture.py @@ -11,7 +11,7 @@ def furniture(): reader.SetFileName(datadir + "office.binary.vtk") reader.Update() sgrid = reader.GetOutput() - + table1 = vtk.vtkStructuredGridGeometryFilter() table1.SetInputData(sgrid) table1.SetExtent(11, 15, 7, 9, 8, 8) @@ -21,7 +21,7 @@ def furniture(): table1Actor = vtk.vtkActor() table1Actor.SetMapper(mapTable1) table1Actor.GetProperty().SetColor(.59, .427, .392) - + table2 = vtk.vtkStructuredGridGeometryFilter() table2.SetInputData(sgrid) table2.SetExtent(11, 15, 10, 12, 8, 8) @@ -31,7 +31,7 @@ def furniture(): table2Actor = vtk.vtkActor() table2Actor.SetMapper(mapTable2) table2Actor.GetProperty().SetColor(.59, .427, .392) - + FilingCabinet1 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet1.SetInputData(sgrid) FilingCabinet1.SetExtent(15, 15, 7, 9, 0, 8) @@ -41,7 +41,7 @@ def furniture(): FilingCabinet1Actor = vtk.vtkActor() FilingCabinet1Actor.SetMapper(mapFilingCabinet1) FilingCabinet1Actor.GetProperty().SetColor(.8, .8, .6) - + FilingCabinet2 = vtk.vtkStructuredGridGeometryFilter() FilingCabinet2.SetInputData(sgrid) FilingCabinet2.SetExtent(15, 15, 10, 12, 0, 8) @@ -51,7 +51,7 @@ def furniture(): FilingCabinet2Actor = vtk.vtkActor() FilingCabinet2Actor.SetMapper(mapFilingCabinet2) FilingCabinet2Actor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1Top = vtk.vtkStructuredGridGeometryFilter() bookshelf1Top.SetInputData(sgrid) bookshelf1Top.SetExtent(13, 13, 0, 4, 0, 11) @@ -61,7 +61,7 @@ def furniture(): bookshelf1TopActor = vtk.vtkActor() bookshelf1TopActor.SetMapper(mapBookshelf1Top) bookshelf1TopActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf1Bottom.SetInputData(sgrid) bookshelf1Bottom.SetExtent(20, 20, 0, 4, 0, 11) @@ -71,7 +71,7 @@ def furniture(): bookshelf1BottomActor = vtk.vtkActor() bookshelf1BottomActor.SetMapper(mapBookshelf1Bottom) bookshelf1BottomActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1Front = vtk.vtkStructuredGridGeometryFilter() bookshelf1Front.SetInputData(sgrid) bookshelf1Front.SetExtent(13, 20, 0, 0, 0, 11) @@ -81,7 +81,7 @@ def furniture(): bookshelf1FrontActor = vtk.vtkActor() bookshelf1FrontActor.SetMapper(mapBookshelf1Front) bookshelf1FrontActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1Back = vtk.vtkStructuredGridGeometryFilter() bookshelf1Back.SetInputData(sgrid) bookshelf1Back.SetExtent(13, 20, 4, 4, 0, 11) @@ -91,7 +91,7 @@ def furniture(): bookshelf1BackActor = vtk.vtkActor() bookshelf1BackActor.SetMapper(mapBookshelf1Back) bookshelf1BackActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1LHS.SetInputData(sgrid) bookshelf1LHS.SetExtent(13, 20, 0, 4, 0, 0) @@ -101,7 +101,7 @@ def furniture(): bookshelf1LHSActor = vtk.vtkActor() bookshelf1LHSActor.SetMapper(mapBookshelf1LHS) bookshelf1LHSActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf1RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf1RHS.SetInputData(sgrid) bookshelf1RHS.SetExtent(13, 20, 0, 4, 11, 11) @@ -111,7 +111,7 @@ def furniture(): bookshelf1RHSActor = vtk.vtkActor() bookshelf1RHSActor.SetMapper(mapBookshelf1RHS) bookshelf1RHSActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2Top = vtk.vtkStructuredGridGeometryFilter() bookshelf2Top.SetInputData(sgrid) bookshelf2Top.SetExtent(13, 13, 15, 19, 0, 11) @@ -121,7 +121,7 @@ def furniture(): bookshelf2TopActor = vtk.vtkActor() bookshelf2TopActor.SetMapper(mapBookshelf2Top) bookshelf2TopActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2Bottom = vtk.vtkStructuredGridGeometryFilter() bookshelf2Bottom.SetInputData(sgrid) bookshelf2Bottom.SetExtent(20, 20, 15, 19, 0, 11) @@ -131,7 +131,7 @@ def furniture(): bookshelf2BottomActor = vtk.vtkActor() bookshelf2BottomActor.SetMapper(mapBookshelf2Bottom) bookshelf2BottomActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2Front = vtk.vtkStructuredGridGeometryFilter() bookshelf2Front.SetInputData(sgrid) bookshelf2Front.SetExtent(13, 20, 15, 15, 0, 11) @@ -141,7 +141,7 @@ def furniture(): bookshelf2FrontActor = vtk.vtkActor() bookshelf2FrontActor.SetMapper(mapBookshelf2Front) bookshelf2FrontActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2Back = vtk.vtkStructuredGridGeometryFilter() bookshelf2Back.SetInputData(sgrid) bookshelf2Back.SetExtent(13, 20, 19, 19, 0, 11) @@ -151,7 +151,7 @@ def furniture(): bookshelf2BackActor = vtk.vtkActor() bookshelf2BackActor.SetMapper(mapBookshelf2Back) bookshelf2BackActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2LHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2LHS.SetInputData(sgrid) bookshelf2LHS.SetExtent(13, 20, 15, 19, 0, 0) @@ -161,7 +161,7 @@ def furniture(): bookshelf2LHSActor = vtk.vtkActor() bookshelf2LHSActor.SetMapper(mapBookshelf2LHS) bookshelf2LHSActor.GetProperty().SetColor(.8, .8, .6) - + bookshelf2RHS = vtk.vtkStructuredGridGeometryFilter() bookshelf2RHS.SetInputData(sgrid) bookshelf2RHS.SetExtent(13, 20, 15, 19, 11, 11) @@ -171,7 +171,7 @@ def furniture(): bookshelf2RHSActor = vtk.vtkActor() bookshelf2RHSActor.SetMapper(mapBookshelf2RHS) bookshelf2RHSActor.GetProperty().SetColor(.8, .8, .6) - + window = vtk.vtkStructuredGridGeometryFilter() window.SetInputData(sgrid) window.SetExtent(20, 20, 6, 13, 10, 13) @@ -181,7 +181,7 @@ def furniture(): windowActor = vtk.vtkActor() windowActor.SetMapper(mapWindow) windowActor.GetProperty().SetColor(.3, .3, .5) - + outlet = vtk.vtkStructuredGridGeometryFilter() outlet.SetInputData(sgrid) outlet.SetExtent(0, 0, 9, 10, 14, 16) @@ -191,7 +191,7 @@ def furniture(): outletActor = vtk.vtkActor() outletActor.SetMapper(mapOutlet) outletActor.GetProperty().SetColor(1, 1, 1) - + inlet = vtk.vtkStructuredGridGeometryFilter() inlet.SetInputData(sgrid) inlet.SetExtent(0, 0, 9, 10, 0, 6) @@ -201,7 +201,7 @@ def furniture(): inletActor = vtk.vtkActor() inletActor.SetMapper(mapInlet) inletActor.GetProperty().SetColor(1, 1, 1) - + outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(sgrid) mapOutline = vtk.vtkPolyDataMapper() @@ -235,7 +235,7 @@ def furniture(): return acts if __name__ == "__main__": - + from vtkplotter import show - + show(furniture()) From 4fced5dba39d8ef9b13f87798d4f390f4fb0fd52 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:14 +0200 Subject: [PATCH 18/67] Removed trailing spaces in examples/volumetric/streamlines1.py --- examples/volumetric/streamlines1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/volumetric/streamlines1.py b/examples/volumetric/streamlines1.py index 192afb5d..ee204304 100644 --- a/examples/volumetric/streamlines1.py +++ b/examples/volumetric/streamlines1.py @@ -14,7 +14,7 @@ probe = Sphere(pos=[0,0.6,0.3], r=0.3, res=8).clean() probe.wire().alpha(0.2).color('g') -stream = streamLines(mesh, probe, +stream = streamLines(mesh, probe, maxPropagation=0.3, extrapolateToBoundingBox={'dims':(10,10,10)}) From 598b93f9bd525dd9838a91a90359380936b8935e Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:14 +0200 Subject: [PATCH 19/67] Removed trailing spaces in examples/volumetric/streamlines2.py --- examples/volumetric/streamlines2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/volumetric/streamlines2.py b/examples/volumetric/streamlines2.py index 32dad0a7..44bfb0b2 100644 --- a/examples/volumetric/streamlines2.py +++ b/examples/volumetric/streamlines2.py @@ -13,7 +13,7 @@ pl3d.SetVectorFunctionNumber(202) pl3d.Update() # this vtkStructuredData already has a vector field: -domain = pl3d.GetOutput().GetBlock(0) +domain = pl3d.GetOutput().GetBlock(0) ######################## vtkplotter comment = Text(__doc__, c='w') From e344b4c1a1113bef50e44138c18510bd6d76f3aa Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:07:15 +0200 Subject: [PATCH 20/67] Removed trailing spaces in examples/volumetric/streamribbons.py --- examples/volumetric/streamribbons.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/volumetric/streamribbons.py b/examples/volumetric/streamribbons.py index 24db689a..570c667e 100644 --- a/examples/volumetric/streamribbons.py +++ b/examples/volumetric/streamribbons.py @@ -13,7 +13,7 @@ pl3d.SetVectorFunctionNumber(202) pl3d.Update() # this vtkStructuredData already contains a vector field: -domain = pl3d.GetOutput().GetBlock(0) +domain = pl3d.GetOutput().GetBlock(0) ######################## vtkplotter msg = Text(__doc__, c='w') From 6e3fdadb76ee527a094f5224ab069c075922f896 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:14 +0200 Subject: [PATCH 21/67] Removed trailing spaces in examples/advanced/densifycloud.py --- examples/advanced/densifycloud.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/advanced/densifycloud.py b/examples/advanced/densifycloud.py index 9cc6b3b7..b2819c69 100644 --- a/examples/advanced/densifycloud.py +++ b/examples/advanced/densifycloud.py @@ -1,7 +1,7 @@ -"""Adds new points to an input point cloud. +"""Adds new points to an input point cloud. The new points are created in such a way that -all points in any local neighborhood are -within a target distance of one another. +all points in any local neighborhood are +within a target distance of one another. """ from vtkplotter import * import numpy as np @@ -17,4 +17,4 @@ print(apts.N(), '->', densecloud.N()) ppp = Points(densecloud.coordinates()) -show(apts, densecloud, Text(__doc__), axes=8) \ No newline at end of file +show(apts, densecloud, Text(__doc__), axes=8) From c1e9fb3a15066ec5cca150faf9ce4f27f426b577 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:14 +0200 Subject: [PATCH 22/67] Removed trailing spaces in examples/advanced/fitplanes.py --- examples/advanced/fitplanes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/advanced/fitplanes.py b/examples/advanced/fitplanes.py index 41a65eeb..9ed09d18 100644 --- a/examples/advanced/fitplanes.py +++ b/examples/advanced/fitplanes.py @@ -4,7 +4,7 @@ For some of these point we show the fitting plane. Black points are the N points used for fitting. Green histogram is the distribution of residuals from the fitting. -Both plane center and normal can be accessed from the +Both plane center and normal can be accessed from the attribute plane.info['center'] and plane.info['normal']. """ from vtkplotter import * From c7f529e392dc16fb6dfd805543a05fd497a42333 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 23/67] Removed trailing spaces in examples/advanced/interpolateField.py --- examples/advanced/interpolateField.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/advanced/interpolateField.py b/examples/advanced/interpolateField.py index 3b737a00..cd7a00c5 100644 --- a/examples/advanced/interpolateField.py +++ b/examples/advanced/interpolateField.py @@ -3,7 +3,7 @@ Thin Plate Spline or Radial Basis Function. -Example shows how to share the same vtkCamera +Example shows how to share the same vtkCamera between different Plotter windows. """ from vtkplotter import Plotter, thinPlateSpline, Points, Arrows, show, Text From a10c799ecd3ee75ed882b66ab0a984144f7f40ec Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 24/67] Removed trailing spaces in examples/advanced/moving_least_squares1D.py --- examples/advanced/moving_least_squares1D.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/advanced/moving_least_squares1D.py b/examples/advanced/moving_least_squares1D.py index ea249531..4714633f 100644 --- a/examples/advanced/moving_least_squares1D.py +++ b/examples/advanced/moving_least_squares1D.py @@ -1,5 +1,5 @@ """ -This example shows how to use a variant of a 1 dimensional +This example shows how to use a variant of a 1 dimensional Moving Least Squares (MLS) algorithm to project a cloud of unordered points to become a smooth line. The parameter f controls the size of the local regression. From 776c7bf9d5996a5beb3566ce6baf438328947b3b Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 25/67] Removed trailing spaces in examples/advanced/moving_least_squares2D.py --- examples/advanced/moving_least_squares2D.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/advanced/moving_least_squares2D.py b/examples/advanced/moving_least_squares2D.py index cac0a3ff..b45f1046 100644 --- a/examples/advanced/moving_least_squares2D.py +++ b/examples/advanced/moving_least_squares2D.py @@ -1,11 +1,11 @@ """ -This example shows how to use a variant of the -Moving Least Squares (MLS) algorithm to project a cloud +This example shows how to use a variant of the +Moving Least Squares (MLS) algorithm to project a cloud of points to become a smooth surface. The parameter f controls the size of the local regression. The input actor's polydata is modified by the method so more than one pass is possible. -If showNPlanes>0 an actor is built demonstrating the +If showNPlanes>0 an actor is built demonstrating the details of the regression for some random points In the second window we show the error estimated for each point in color scale (left) or in size scale (right). From 26daa34ef1d104cd4232fd2768ed15079a8f0858 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 26/67] Removed trailing spaces in examples/advanced/quadratic_morphing.py --- examples/advanced/quadratic_morphing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/advanced/quadratic_morphing.py b/examples/advanced/quadratic_morphing.py index 35a5e807..7501b5bc 100644 --- a/examples/advanced/quadratic_morphing.py +++ b/examples/advanced/quadratic_morphing.py @@ -1,6 +1,6 @@ """ Takes 2 shapes, source and target, and morphs source on target -this is obtained by fitting 18 parameters of a non linear, +this is obtained by fitting 18 parameters of a non linear, quadratic, transformation defined in transform() The fitting minimizes the distance to the target surface using algorithms available in the scipy.optimize package. From a7c33c838ba0d5de99be7c431721e49680a613ae Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 27/67] Removed trailing spaces in examples/basic/align2.py --- examples/basic/align2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/align2.py b/examples/basic/align2.py index 98df6364..0feba848 100644 --- a/examples/basic/align2.py +++ b/examples/basic/align2.py @@ -1,6 +1,6 @@ """ Example usage of align() method: - generate two random sets of points as 2 actors + generate two random sets of points as 2 actors and align them using the Iterative Closest Point algorithm. """ from __future__ import division From 1ffcf1f29908b7280d740ff565df8b11319bada0 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 28/67] Removed trailing spaces in examples/basic/bgImage.py --- examples/basic/bgImage.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/basic/bgImage.py b/examples/basic/bgImage.py index 4bcfa632..b791e47f 100644 --- a/examples/basic/bgImage.py +++ b/examples/basic/bgImage.py @@ -1,12 +1,12 @@ -"""Set a jpeg background image on a -vtkRenderingWindow layer, after -the first rendering it can be +"""Set a jpeg background image on a +vtkRenderingWindow layer, after +the first rendering it can be zoomed to fill the window.""" from vtkplotter import Plotter, load, Polygon, Text, datadir doc = Text(__doc__, c="k", bg="w") -vp = Plotter(N=2, size=(400, 800), axes=4, sharecam=0, +vp = Plotter(N=2, size=(400, 800), axes=4, sharecam=0, bg=datadir+"images/tropical.jpg") a1 = load(datadir+"flamingo.3ds").rotateX(-90) From be28ad7d1496ad5e9f94234ee152ef8e853c07cd Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 29/67] Removed trailing spaces in examples/basic/buildmesh.py --- examples/basic/buildmesh.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/buildmesh.py b/examples/basic/buildmesh.py index 686eaa6a..a5207c1d 100644 --- a/examples/basic/buildmesh.py +++ b/examples/basic/buildmesh.py @@ -15,4 +15,4 @@ print('getCells() format is :', a.getCells()) print('getConnectivity() format is:', a.getConnectivity()) -show(a, Text(__doc__), viewup='z', axes=8) \ No newline at end of file +show(a, Text(__doc__), viewup='z', axes=8) From 0facb6e08bc1336d17bab69ef1263ad350e8014a Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 30/67] Removed trailing spaces in examples/basic/clustering.py --- examples/basic/clustering.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/clustering.py b/examples/basic/clustering.py index 33031e48..f42d61da 100644 --- a/examples/basic/clustering.py +++ b/examples/basic/clustering.py @@ -1,5 +1,5 @@ """ -Example usage of removeOutliers() +Example usage of removeOutliers() and cluster() methods. """ from vtkplotter import show, cluster, removeOutliers, Text From ad68b0fa8ceca2a343b771232ccb607498eec1b7 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:15 +0200 Subject: [PATCH 31/67] Removed trailing spaces in examples/basic/colormaps.py --- examples/basic/colormaps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/colormaps.py b/examples/basic/colormaps.py index 18484258..034a991b 100644 --- a/examples/basic/colormaps.py +++ b/examples/basic/colormaps.py @@ -1,5 +1,5 @@ """ -Example usage of pointColors to assign a color to each mesh vertex +Example usage of pointColors to assign a color to each mesh vertex by looking it up in matplotlib database of colormaps """ print(__doc__) From 34b29f9bab87e1b1e1e31fe97d6c8fe5ad79629c Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 32/67] Removed trailigit add examplesic/manyspheres.py --- examples/basic/manyspheres.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/manyspheres.py b/examples/basic/manyspheres.py index 67c645f1..5ba5fdd6 100644 --- a/examples/basic/manyspheres.py +++ b/examples/basic/manyspheres.py @@ -1,5 +1,5 @@ """ -Example that shows how to draw very large number of +Example that shows how to draw very large number of spheres (same for Points, lines) with different colors or different radius. Resolution (res) can be specified. """ From cad4c6f7b26dc3bdb0a4179b042cec0320a37e66 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 33/67] Removed trailigit add examplesic/markpoint.py --- examples/basic/markpoint.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/markpoint.py b/examples/basic/markpoint.py index 824f83d2..789d3ed1 100644 --- a/examples/basic/markpoint.py +++ b/examples/basic/markpoint.py @@ -1,5 +1,5 @@ """ -Mark a specific point +Mark a specific point on a mesh with some text. """ from vtkplotter import Sphere, Point, show, Text From fa93e7dec362ad54d83693fcf0c9d14c0d9cbd0a Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 34/67] Removed trgit add n examples/basic/mesh_coloring.py --- examples/basic/mesh_coloring.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/basic/mesh_coloring.py b/examples/basic/mesh_coloring.py index 5c274c67..20597ec4 100644 --- a/examples/basic/mesh_coloring.py +++ b/examples/basic/mesh_coloring.py @@ -1,6 +1,6 @@ """ -Example on how to specify a color for each individual cell -or point of an actor's mesh. +Example on how to specify a color for each individual cell +or point of an actor's mesh. Last example also shows the usage of addScalarBar3D(). """ print(__doc__) From ea678caa27419eacbd3967e3df4b12925f6b92ed Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 35/67] Removed trailing spaces in examples/basic/mesh_map2cell.py --- examples/basic/mesh_map2cell.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/mesh_map2cell.py b/examples/basic/mesh_map2cell.py index f301157d..67d65627 100644 --- a/examples/basic/mesh_map2cell.py +++ b/examples/basic/mesh_map2cell.py @@ -1,4 +1,4 @@ -"""How to transform/map an array +"""How to transform/map an array which is defined on the vertices of a mesh to its cells with mapPointsToCells() """ From 9507a7553a956aca3178fe50a6506accdbc3486e Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 36/67] Removed trailing spaces in examples/basic/mesh_modify.py --- examples/basic/mesh_modify.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/mesh_modify.py b/examples/basic/mesh_modify.py index bfacefee..93e0d8d7 100644 --- a/examples/basic/mesh_modify.py +++ b/examples/basic/mesh_modify.py @@ -12,4 +12,4 @@ dsc.setPoints(coords) # modify mesh show(dsc, t, axes=8, resetcam=0, interactive=0) -interactive() \ No newline at end of file +interactive() From fd231d44946e89677a8d23ecd6e35687f5fd5f76 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 37/67] Removed trailing spaces in examples/basic/mesh_sharemap.py --- examples/basic/mesh_sharemap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/mesh_sharemap.py b/examples/basic/mesh_sharemap.py index 52e3ece2..93608bfa 100644 --- a/examples/basic/mesh_sharemap.py +++ b/examples/basic/mesh_sharemap.py @@ -1,5 +1,5 @@ """ -How to share the same color map +How to share the same color map across different meshes. """ print(__doc__) From 88657d62a76c9ab2b597146c624e8264533f9ad3 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 38/67] Removed trailing spaces in examples/other/icon.py --- examples/basic/multiblocks.py | 2 +- examples/other/icon.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/basic/multiblocks.py b/examples/basic/multiblocks.py index f0d112e9..1a9de6cf 100644 --- a/examples/basic/multiblocks.py +++ b/examples/basic/multiblocks.py @@ -12,7 +12,7 @@ filename = "multiblock.vtm" mblock = write([poly, img], filename) #returns a vtkMultiBlockData -printc("~save wrote file", filename, +printc("~save wrote file", filename, "and corresponding directory", c='g') # load back from file into a list of actors/volumes diff --git a/examples/other/icon.py b/examples/other/icon.py index d66e768a..17179104 100644 --- a/examples/other/icon.py +++ b/examples/other/icon.py @@ -1,6 +1,6 @@ """ -Make a icon actor to indicate orientation -and place it in one of the 4 corners +Make a icon actor to indicate orientation +and place it in one of the 4 corners within the same renderer. """ from vtkplotter import * From d9b949be81bf26d72eda20ad79c21e0aba7a297d Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 39/67] Removed trailing spaces in examples/other/makeVideo.py --- examples/other/makeVideo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/other/makeVideo.py b/examples/other/makeVideo.py index 04aca7f5..fdb3f858 100644 --- a/examples/other/makeVideo.py +++ b/examples/other/makeVideo.py @@ -16,7 +16,7 @@ for i in range(80): vp.show() # render the scene first - vp.camera.Elevation(1) + vp.camera.Elevation(1) vp.camera.Azimuth(2) # rotate by 5 deg at each iteration video.addFrame() From 177b33f1fea111630bb81be54c5c500627cdec15 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:16 +0200 Subject: [PATCH 40/67] Removed trailing spaces in examples/simulations/tunnelling2.py --- examples/simulations/tunnelling2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simulations/tunnelling2.py b/examples/simulations/tunnelling2.py index 48569022..1d06ebd0 100644 --- a/examples/simulations/tunnelling2.py +++ b/examples/simulations/tunnelling2.py @@ -1,7 +1,7 @@ """ Quantum Tunnelling effect using 4th order Runge-Kutta method with arbitrary potential shape. -The animation shows the evolution of a particle of relatively well defined +The animation shows the evolution of a particle of relatively well defined momentum (hence undefined position) in a box hitting a potential barrier. """ print(__doc__) From 86206216044f8615be54da906ca2b362e35fbde7 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:19:17 +0200 Subject: [PATCH 41/67] Removed trailing spaces in examples/simulations/turing.py --- examples/simulations/turing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simulations/turing.py b/examples/simulations/turing.py index 09e7e154..6efe790e 100644 --- a/examples/simulations/turing.py +++ b/examples/simulations/turing.py @@ -1,5 +1,5 @@ """ -Scalar values are read from a file and represented +Scalar values are read from a file and represented on a green scale on a mesh as a function of time. The difference between one time point and the next is shown as a blue component. From 8bf7f3f86b7dbaeab2c648ab7893591bf6ed4e15 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 42/67] Removed trailing spaces in examples/basic/connCells.py --- examples/basic/connCells.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/basic/connCells.py b/examples/basic/connCells.py index 89e53e9f..3c9c825b 100644 --- a/examples/basic/connCells.py +++ b/examples/basic/connCells.py @@ -17,16 +17,16 @@ s = actor.subdivide(sub).clean(tol) -coords = s.coordinates() +coords = s.coordinates() pactor = Points(coords) tomerge = [] for p in coords: ipts = s.closestPoint(p, N=N, returnIds=True) pts = coords[ipts] - + d = delaunay2D(pts, mode='fit').c('blue').wire() - + piece = d.connectedCells(0, returnIds=False) show(pactor, d, piece, Point(p, c='r'), interactive=0) From a81ce2e58dbf3b82f544313f728d841ba883f4bf Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 43/67] Removed trailing spaces in examples/basic/connVtx.py --- examples/basic/connVtx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/connVtx.py b/examples/basic/connVtx.py index ce848f17..fca1b7c1 100644 --- a/examples/basic/connVtx.py +++ b/examples/basic/connVtx.py @@ -1,5 +1,5 @@ """ -Find the vertices that are connected +Find the vertices that are connected to a specific vertex in a mesh. """ from vtkplotter import * From 39f051c194c42dc4b6a11f5a24a4280eb43e456f Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 44/67] Removed trailing spaces in examples/basic/flatarrow.py --- examples/basic/flatarrow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/flatarrow.py b/examples/basic/flatarrow.py index 105b3d8e..236e87e7 100644 --- a/examples/basic/flatarrow.py +++ b/examples/basic/flatarrow.py @@ -7,7 +7,7 @@ s, c = sin(i), cos(i) l1 = [[sin(x)+c, -cos(x)+s, x] for x in arange(0,3, 0.1)] l2 = [[sin(x)+c+0.1, -cos(x)+s + x/15, x] for x in arange(0,3, 0.1)] - + FlatArrow(l1, l2, c=i, tipSize=1, tipWidth=1) show(collection(), viewup="z", axes=1, bg="w") From 4fcd1aa88904db327895906009f8ffaee40bc8fb Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 45/67] Removed trailing spaces in examples/basic/glyphs_arrows.py --- examples/basic/glyphs_arrows.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/glyphs_arrows.py b/examples/basic/glyphs_arrows.py index b215f830..8e58a35d 100644 --- a/examples/basic/glyphs_arrows.py +++ b/examples/basic/glyphs_arrows.py @@ -17,7 +17,7 @@ # get a list of random rgb colors nrs = np.random.randint(0, 10, len(coords1)) -cols = getColor(nrs) +cols = getColor(nrs) a2 = Arrows(coords1, coords2, c=cols, scale=0.5) From b79e9dd25093b1cf5572496905db6f1a0cfa3dcd Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 46/67] Removed trailing spaces in examples/basic/isolines.py --- examples/basic/isolines.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/isolines.py b/examples/basic/isolines.py index 045822b2..2b2daec0 100644 --- a/examples/basic/isolines.py +++ b/examples/basic/isolines.py @@ -1,5 +1,5 @@ """ -Draw the isolines of the +Draw the isolines of the active scalars on a surface """ from vtkplotter import * From d4e4889ceedddc164200095134f7d987b1950d2a Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:00 +0200 Subject: [PATCH 47/67] Removed trailing spaces in examples/basic/keypress.py --- examples/basic/keypress.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/keypress.py b/examples/basic/keypress.py index 184f1411..6e06ebc0 100644 --- a/examples/basic/keypress.py +++ b/examples/basic/keypress.py @@ -1,5 +1,5 @@ """ -This example shows how to implement a custom function that is triggered by +This example shows how to implement a custom function that is triggered by pressing a keyboard button when the rendering window is in interactive mode. Every time a key is pressed the picked point of the mesh is used to add a sphere and some info is printed. From f96bafa0a659f90603c3e979faef942eb56956c2 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:01 +0200 Subject: [PATCH 48/67] Removed trailing spaces in examples/basic/multiwindows.py --- examples/basic/multiwindows.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/multiwindows.py b/examples/basic/multiwindows.py index f0554536..7a4a2fb8 100644 --- a/examples/basic/multiwindows.py +++ b/examples/basic/multiwindows.py @@ -1,5 +1,5 @@ """ -Example of drawing objects on different windows +Example of drawing objects on different windows and/or subwindows within the same window. We split the main window in a 25 subwindows and draw something in specific windows numbers. From 98da16341212bb001f13309a59e0978e77cff02d Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:01 +0200 Subject: [PATCH 49/67] Removed trailing spaces in examples/basic/pca.py --- examples/basic/pca.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/pca.py b/examples/basic/pca.py index a20b986a..2dc0ed7d 100644 --- a/examples/basic/pca.py +++ b/examples/basic/pca.py @@ -1,5 +1,5 @@ """ -Draw the PCA (Principal Component Analysis) ellipsoid that contains +Draw the PCA (Principal Component Analysis) ellipsoid that contains 50% of a cloud of Points, then check if points are inside the surface. Extra info is stored in actor.info['sphericity'], 'va', 'vb', 'vc'. """ From ad92f480fd42a17f09068a1e3dcbd30f340fd8c6 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:01 +0200 Subject: [PATCH 50/67] Removed trailing spaces in examples/other/export_x3d.py --- examples/other/export_x3d.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/other/export_x3d.py b/examples/other/export_x3d.py index e44fcc3d..695300ea 100644 --- a/examples/other/export_x3d.py +++ b/examples/other/export_x3d.py @@ -1,5 +1,5 @@ -"""Embed a 3D scene -in a webpage with +"""Embed a 3D scene +in a webpage with x3dom and vtkplotter""" from vtkplotter import * @@ -10,7 +10,7 @@ t = Text(__doc__, pos=(3e03,5.5e03,1e04), s=350) show(e, t) -# This exports the scene and generates 2 files: +# This exports the scene and generates 2 files: # embryo.x3d and an example embryo.html to inspect in the browser exportWindow('embryo.x3d') From 3ea800c2bd838752ec17e2fd26025931fd4b7e72 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:01 +0200 Subject: [PATCH 51/67] Removed trailing spaces in examples/other/remesh_ACVD.py --- examples/other/remesh_ACVD.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/other/remesh_ACVD.py b/examples/other/remesh_ACVD.py index 02528c77..ac760f93 100644 --- a/examples/other/remesh_ACVD.py +++ b/examples/other/remesh_ACVD.py @@ -10,7 +10,7 @@ # Create clustering object poly = amesh.clone().triangle().clean().polydata() -cobj = Clustering.Cluster(poly) +cobj = Clustering.Cluster(poly) # Generate clusters cobj.GenClusters(1000, max_iter=10000, subratio=10) From 3143c122c3c4fe3ffb6042c9c64aa1e2ea0adc28 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 52/67] Removed trailing spaces in examples/other/self_org_maps2d.py --- examples/other/self_org_maps2d.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/other/self_org_maps2d.py b/examples/other/self_org_maps2d.py index 14b00d5c..198db320 100644 --- a/examples/other/self_org_maps2d.py +++ b/examples/other/self_org_maps2d.py @@ -28,7 +28,7 @@ def learn(self, n_epoch=10000, sigma=(0.25,0.01), lrate=(0.5,0.01)): self.samples = self.samples[I] pts = Points(self.samples, r=2) doc = Text(__doc__) - + pb = ProgressBar(0,n_epoch) for i in pb.range(): pb.print("epochs") @@ -43,7 +43,7 @@ def learn(self, n_epoch=10000, sigma=(0.25,0.01), lrate=(0.5,0.01)): # Move nodes towards sample according to Gaussian self.codebook -= lrate[i] * G[..., np.newaxis] * (self.codebook-data) - + # Draw network if i>500 and not i%20 or i==n_epoch-1: x, y, z = [self.codebook[:,i].reshape(n,n) for i in range(3)] @@ -58,15 +58,15 @@ def learn(self, n_epoch=10000, sigma=(0.25,0.01), lrate=(0.5,0.01)): # ------------------------------------------------------------------------------- if __name__ == "__main__": - + n = 25 X, Y = np.meshgrid(np.linspace(0, 1, n), np.linspace(0, 1, n)) P = np.c_[X.ravel(), Y.ravel()] D = scipy.spatial.distance.cdist(P, P) - + s = Sphere(res=90).cutWithPlane(origin=(0,-.3,0), normal='y').clean(0.01) som = SOM((len(P), 3), D) som.samples = s.coordinates() som.learn(n_epoch=7000, sigma=(1, 0.01), lrate=(1, 0.01)) - + From 260ecf40fb70a7930ca680056ceb2ae92fe8ae29 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 53/67] Removed trailing spaces in examples/other/spherical_harmonics1.py --- examples/other/spherical_harmonics1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/other/spherical_harmonics1.py b/examples/other/spherical_harmonics1.py index f222b979..90e32c99 100644 --- a/examples/other/spherical_harmonics1.py +++ b/examples/other/spherical_harmonics1.py @@ -50,7 +50,7 @@ ############################################################ # Please install pyshtools to continue this example # Follow instructions at https://shtools.oca.eu/shtools -import pyshtools +import pyshtools grid = pyshtools.SHGrid.from_array(agrid) clm = grid.expand() From c9480c3d8eef4b15029f6a2b5fbfae414f9aba1f Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 54/67] Removed trailing spaces in examples/other/tf_learn_embryo.py --- examples/other/tf_learn_embryo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/other/tf_learn_embryo.py b/examples/other/tf_learn_embryo.py index 4dabd266..0e53a680 100644 --- a/examples/other/tf_learn_embryo.py +++ b/examples/other/tf_learn_embryo.py @@ -43,7 +43,7 @@ model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"]) -model.fit(shuffled_datalist, shuffled_scalars, +model.fit(shuffled_datalist, shuffled_scalars, epochs=epochs, batch_size=max(nx,ny,nz)) predicted_scalars = model.predict(datalist) From a25cba7aae9fb89e76b310d207ad66eae9f1d5e0 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 55/67] Removed trailing spaces in examples/other/value-iteration.py --- examples/other/value-iteration.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/other/value-iteration.py b/examples/other/value-iteration.py index 6d7b96b6..d397cc36 100644 --- a/examples/other/value-iteration.py +++ b/examples/other/value-iteration.py @@ -51,7 +51,7 @@ def diffuse(Z, gamma=0.99): G = Z * generic_filter(G, diffuse, footprint=[[0, 1, 0], [1, 1, 1], [0, 1, 0]]) - + # Descent gradient to find shortest path from entrance to exit y, x = goal dirs = (0,-1), (0,+1), (-1,0), (+1,0) @@ -66,9 +66,9 @@ def diffuse(Z, gamma=0.99): a = np.argmax(neighbours) x, y = x + dirs[a][1], y + dirs[a][0] P.append((y,x)) - + return P, G - + def printSolution(S, start, goal): for y,line in enumerate(Z): for x,c in enumerate(line): @@ -99,18 +99,18 @@ def showSolution3D(S, start, goal): txts.append(Text(__doc__, c='k')) txts.append(Text('Start', pos=[start[1]-1,-start[0]+1.5,1], c='k')) - txts.append(Text('Goal!', pos=[goal[1] -2,-goal[0] -2.7,1], c='k')) + txts.append(Text('Goal!', pos=[goal[1] -2,-goal[0] -2.7,1], c='k')) show(path, walls, grd, txts, bg='white', axes=0, zoom=1.2) - - + + ########################################################################## if __name__ == '__main__': np.random.seed(4) - + Z = maze(shape=(50, 70)) start, goal = (1,1), (Z.shape[0]-2, Z.shape[1]-2) S = solve(Z, start, goal) - + #printSolution(S, start, goal) showSolution3D(S, start, goal) From 46a169d22717845d6ee3e5a09a71b38c6b5dd898 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 56/67] Removed trailing spaces in examples/simulations/aspring.py --- examples/simulations/aspring.py | 90 ++++++++++++++++----------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/examples/simulations/aspring.py b/examples/simulations/aspring.py index b06cfebe..c286bfb1 100644 --- a/examples/simulations/aspring.py +++ b/examples/simulations/aspring.py @@ -1,45 +1,45 @@ -""" -Simulation of a block connected -to a spring in a vicous medium. -""" -from __future__ import division, print_function -from vtkplotter import * - -vp = Plotter(interactive=0, axes=0) - -L = 0.1 # spring x position at rest -x0 = 0.85 # initial x-coordinate of the block -k = 25 # spring constant -m = 20 # block mass -b = 0.5 # viscosity friction (proportional to velocity) -dt = 0.15 # time step - -# initial conditions -v = vector(0, 0, 0.2) -x = vector(x0, 0, 0) -xr = vector(L, 0, 0) -sx0 = vector(-0.8, 0, 0) -offx = vector(0, 0.3, 0) - -vp.add(Box(pos=(0, -0.1, 0), length=2.0, width=0.02, height=0.5)) # surface -vp.add(Box(pos=(-0.82, 0.15, 0), length=0.04, width=0.50, height=0.3)) # wall - -block = Cube(pos=x, side=0.2, c="tomato") -block.addTrail(offset=[0, 0.2, 0], alpha=0.6, lw=2, n=500) -spring = Spring(sx0, x, r=0.06, thickness=0.01) -vp.add([block, spring, Text(__doc__)]) - -pb = ProgressBar(0, 300, c="r") -for i in pb.range(): - F = -k * (x - xr) - b * v # Force and friction - a = F / m # acceleration - v = v + a * dt # velocity - x = x + v * dt + 1 / 2 * a * dt ** 2 # position - - block.pos(x) # update block position and trail - spring.stretch(sx0, x) # stretch helix accordingly - - vp.show(elevation=0.1, azimuth=0.1) - pb.print() - -vp.show(interactive=1) +""" +Simulation of a block connected +to a spring in a vicous medium. +""" +from __future__ import division, print_function +from vtkplotter import * + +vp = Plotter(interactive=0, axes=0) + +L = 0.1 # spring x position at rest +x0 = 0.85 # initial x-coordinate of the block +k = 25 # spring constant +m = 20 # block mass +b = 0.5 # viscosity friction (proportional to velocity) +dt = 0.15 # time step + +# initial conditions +v = vector(0, 0, 0.2) +x = vector(x0, 0, 0) +xr = vector(L, 0, 0) +sx0 = vector(-0.8, 0, 0) +offx = vector(0, 0.3, 0) + +vp.add(Box(pos=(0, -0.1, 0), length=2.0, width=0.02, height=0.5)) # surface +vp.add(Box(pos=(-0.82, 0.15, 0), length=0.04, width=0.50, height=0.3)) # wall + +block = Cube(pos=x, side=0.2, c="tomato") +block.addTrail(offset=[0, 0.2, 0], alpha=0.6, lw=2, n=500) +spring = Spring(sx0, x, r=0.06, thickness=0.01) +vp.add([block, spring, Text(__doc__)]) + +pb = ProgressBar(0, 300, c="r") +for i in pb.range(): + F = -k * (x - xr) - b * v # Force and friction + a = F / m # acceleration + v = v + a * dt # velocity + x = x + v * dt + 1 / 2 * a * dt ** 2 # position + + block.pos(x) # update block position and trail + spring.stretch(sx0, x) # stretch helix accordingly + + vp.show(elevation=0.1, azimuth=0.1) + pb.print() + +vp.show(interactive=1) From 91710a87b24d81c065945b1674f1a129172b0bfe Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 57/67] Removed trailing spaces in examples/simulations/doubleslit.py --- examples/simulations/doubleslit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simulations/doubleslit.py b/examples/simulations/doubleslit.py index 9b656951..6274e9d1 100644 --- a/examples/simulations/doubleslit.py +++ b/examples/simulations/doubleslit.py @@ -3,7 +3,7 @@ Units are meters. Any number of slits of any geometry can be added. Slit sources are placed on the plane shown as a thin grid (as source are in scale, too small to be seen, they are magnified x200). -Can simulate the 'Arago spot', the bright point at the center of +Can simulate the 'Arago spot', the bright point at the center of a circular object shadow (https://en.wikipedia.org/wiki/Arago_spot). """ from numpy import conj, real, pi, array From 1afdd98fce2dc705818f32fc5770c27e86270234 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 58/67] Removed trailing spaces in examples/simulations/gas.py --- examples/simulations/gas.py | 274 ++++++++++++++++++------------------ 1 file changed, 137 insertions(+), 137 deletions(-) diff --git a/examples/simulations/gas.py b/examples/simulations/gas.py index f9834c93..d1dbd540 100644 --- a/examples/simulations/gas.py +++ b/examples/simulations/gas.py @@ -1,137 +1,137 @@ -""" -A model of an ideal gas with hard-sphere collisions. -""" -## Based on gas.py by Bruce Sherwood for a cube as a container -## Sligthly modified by Andrey Antonov for a torus. -## Adapted by M. Musy for vtkplotter -## relevant points in the code are marked with '### <--' -from __future__ import division, print_function -from random import random -from vtkplotter import Plotter, ProgressBar, mag, versor, Text -from vtkplotter import Torus, Sphere -import numpy as np - -############################################################# -Natoms = 400 # change this to have more or fewer atoms -Nsteps = 350 # nr of steps in the simulation -Matom = 4e-3 / 6e23 # helium mass -Ratom = 0.025 # wildly exaggerated size of helium atom -RingThickness = 0.3 # thickness of the toroid -RingRadius = 1 -k = 1.4e-23 # Boltzmann constant -T = 300 # room temperature -dt = 1.5e-5 -############################################################# - - -def reflection(p, pos): - n = versor(pos) - return np.dot(np.identity(3) - 2 * n * n[:, np.newaxis], p) - - -vp = Plotter(title="gas in toroid", interactive=0, axes=0, bg="w") - -vp.add(Text(__doc__)) - -vp.add(Torus(c="g", r=RingRadius, thickness=RingThickness, alpha=0.1).wire(1)) ### <-- - -Atoms = [] -poslist = [] -plist, mlist, rlist = [], [], [] -mass = Matom * Ratom ** 3 / Ratom ** 3 -pavg = np.sqrt(2.0 * mass * 1.5 * k * T) # average kinetic energy p**2/(2mass) = (3/2)kT - -for i in range(Natoms): - alpha = 2 * np.pi * random() - x = RingRadius * np.cos(alpha) * 0.9 - y = RingRadius * np.sin(alpha) * 0.9 - z = 0 - Atoms = Atoms + [vp.add(Sphere(pos=(x, y, z), r=Ratom, c=i))] ### <-- - theta = np.pi * random() - phi = 2 * np.pi * random() - px = pavg * np.sin(theta) * np.cos(phi) - py = pavg * np.sin(theta) * np.sin(phi) - pz = pavg * np.cos(theta) - poslist.append((x, y, z)) - plist.append((px, py, pz)) - mlist.append(mass) - rlist.append(Ratom) - -pos = np.array(poslist) -poscircle = pos -p = np.array(plist) -m = np.array(mlist) -m.shape = (Natoms, 1) -radius = np.array(rlist) -r = pos - pos[:, np.newaxis] # all pairs of atom-to-atom vectors - -ds = (p / m) * (dt / 2.0) -if "False" not in np.less_equal(mag(ds), radius).tolist(): - pos = pos + (p / mass) * (dt / 2.0) # initial half-step - -pb = ProgressBar(0, Nsteps, c=1) -for i in pb.range(): - - # Update all positions - ds = mag((p / m) * (dt / 2.0)) - if "False" not in np.less_equal(ds, radius).tolist(): - pos = pos + (p / m) * dt - - r = pos - pos[:, np.newaxis] # all pairs of atom-to-atom vectors - rmag = np.sqrt(np.sum(np.square(r), -1)) # atom-to-atom scalar distances - hit = np.less_equal(rmag, radius + radius[:, None]) - np.identity(Natoms) - hitlist = np.sort(np.nonzero(hit.flat)[0]).tolist() # i,j encoded as i*Natoms+j - - # If any collisions took place: - for ij in hitlist: - i, j = divmod(ij, Natoms) # decode atom pair - hitlist.remove(j * Natoms + i) # remove symmetric j,i pair from list - ptot = p[i] + p[j] - mi = m[i, 0] - mj = m[j, 0] - vi = p[i] / mi - vj = p[j] / mj - ri = Ratom - rj = Ratom - a = mag(vj - vi) ** 2 - if a == 0: - continue # exactly same velocities - b = 2 * np.dot(pos[i] - pos[j], vj - vi) - c = mag(pos[i] - pos[j]) ** 2 - (ri + rj) ** 2 - d = b ** 2 - 4.0 * a * c - if d < 0: - continue # something wrong; ignore this rare case - deltat = (-b + np.sqrt(d)) / (2.0 * a) # t-deltat is when they made contact - pos[i] = pos[i] - (p[i] / mi) * deltat # back up to contact configuration - pos[j] = pos[j] - (p[j] / mj) * deltat - mtot = mi + mj - pcmi = p[i] - ptot * mi / mtot # transform momenta to cm frame - pcmj = p[j] - ptot * mj / mtot - rrel = versor(pos[j] - pos[i]) - pcmi = pcmi - 2 * np.dot(pcmi, rrel) * rrel # bounce in cm frame - pcmj = pcmj - 2 * np.dot(pcmj, rrel) * rrel - p[i] = pcmi + ptot * mi / mtot # transform momenta back to lab frame - p[j] = pcmj + ptot * mj / mtot - pos[i] = pos[i] + (p[i] / mi) * deltat # move forward deltat in time - pos[j] = pos[j] + (p[j] / mj) * deltat - - # Bounce off the boundary of the torus - for j in range(Natoms): - poscircle[j] = versor(pos[j]) * RingRadius * [1, 1, 0] - outside = np.greater_equal(mag(poscircle - pos), RingThickness - 2 * Ratom) - - for k in range(len(outside)): - if outside[k] == 1 and np.dot(p[k], pos[k] - poscircle[k]) > 0: - p[k] = reflection(p[k], pos[k] - poscircle[k]) - - # then update positions of display objects - for i in range(Natoms): - Atoms[i].pos(pos[i]) ### <-- - outside = np.greater_equal(mag(pos), RingRadius + RingThickness) - - vp.show() ### <-- - vp.camera.Azimuth(0.5) - vp.camera.Elevation(0.1) - pb.print() - -vp.show(interactive=1) +""" +A model of an ideal gas with hard-sphere collisions. +""" +## Based on gas.py by Bruce Sherwood for a cube as a container +## Sligthly modified by Andrey Antonov for a torus. +## Adapted by M. Musy for vtkplotter +## relevant points in the code are marked with '### <--' +from __future__ import division, print_function +from random import random +from vtkplotter import Plotter, ProgressBar, mag, versor, Text +from vtkplotter import Torus, Sphere +import numpy as np + +############################################################# +Natoms = 400 # change this to have more or fewer atoms +Nsteps = 350 # nr of steps in the simulation +Matom = 4e-3 / 6e23 # helium mass +Ratom = 0.025 # wildly exaggerated size of helium atom +RingThickness = 0.3 # thickness of the toroid +RingRadius = 1 +k = 1.4e-23 # Boltzmann constant +T = 300 # room temperature +dt = 1.5e-5 +############################################################# + + +def reflection(p, pos): + n = versor(pos) + return np.dot(np.identity(3) - 2 * n * n[:, np.newaxis], p) + + +vp = Plotter(title="gas in toroid", interactive=0, axes=0, bg="w") + +vp.add(Text(__doc__)) + +vp.add(Torus(c="g", r=RingRadius, thickness=RingThickness, alpha=0.1).wire(1)) ### <-- + +Atoms = [] +poslist = [] +plist, mlist, rlist = [], [], [] +mass = Matom * Ratom ** 3 / Ratom ** 3 +pavg = np.sqrt(2.0 * mass * 1.5 * k * T) # average kinetic energy p**2/(2mass) = (3/2)kT + +for i in range(Natoms): + alpha = 2 * np.pi * random() + x = RingRadius * np.cos(alpha) * 0.9 + y = RingRadius * np.sin(alpha) * 0.9 + z = 0 + Atoms = Atoms + [vp.add(Sphere(pos=(x, y, z), r=Ratom, c=i))] ### <-- + theta = np.pi * random() + phi = 2 * np.pi * random() + px = pavg * np.sin(theta) * np.cos(phi) + py = pavg * np.sin(theta) * np.sin(phi) + pz = pavg * np.cos(theta) + poslist.append((x, y, z)) + plist.append((px, py, pz)) + mlist.append(mass) + rlist.append(Ratom) + +pos = np.array(poslist) +poscircle = pos +p = np.array(plist) +m = np.array(mlist) +m.shape = (Natoms, 1) +radius = np.array(rlist) +r = pos - pos[:, np.newaxis] # all pairs of atom-to-atom vectors + +ds = (p / m) * (dt / 2.0) +if "False" not in np.less_equal(mag(ds), radius).tolist(): + pos = pos + (p / mass) * (dt / 2.0) # initial half-step + +pb = ProgressBar(0, Nsteps, c=1) +for i in pb.range(): + + # Update all positions + ds = mag((p / m) * (dt / 2.0)) + if "False" not in np.less_equal(ds, radius).tolist(): + pos = pos + (p / m) * dt + + r = pos - pos[:, np.newaxis] # all pairs of atom-to-atom vectors + rmag = np.sqrt(np.sum(np.square(r), -1)) # atom-to-atom scalar distances + hit = np.less_equal(rmag, radius + radius[:, None]) - np.identity(Natoms) + hitlist = np.sort(np.nonzero(hit.flat)[0]).tolist() # i,j encoded as i*Natoms+j + + # If any collisions took place: + for ij in hitlist: + i, j = divmod(ij, Natoms) # decode atom pair + hitlist.remove(j * Natoms + i) # remove symmetric j,i pair from list + ptot = p[i] + p[j] + mi = m[i, 0] + mj = m[j, 0] + vi = p[i] / mi + vj = p[j] / mj + ri = Ratom + rj = Ratom + a = mag(vj - vi) ** 2 + if a == 0: + continue # exactly same velocities + b = 2 * np.dot(pos[i] - pos[j], vj - vi) + c = mag(pos[i] - pos[j]) ** 2 - (ri + rj) ** 2 + d = b ** 2 - 4.0 * a * c + if d < 0: + continue # something wrong; ignore this rare case + deltat = (-b + np.sqrt(d)) / (2.0 * a) # t-deltat is when they made contact + pos[i] = pos[i] - (p[i] / mi) * deltat # back up to contact configuration + pos[j] = pos[j] - (p[j] / mj) * deltat + mtot = mi + mj + pcmi = p[i] - ptot * mi / mtot # transform momenta to cm frame + pcmj = p[j] - ptot * mj / mtot + rrel = versor(pos[j] - pos[i]) + pcmi = pcmi - 2 * np.dot(pcmi, rrel) * rrel # bounce in cm frame + pcmj = pcmj - 2 * np.dot(pcmj, rrel) * rrel + p[i] = pcmi + ptot * mi / mtot # transform momenta back to lab frame + p[j] = pcmj + ptot * mj / mtot + pos[i] = pos[i] + (p[i] / mi) * deltat # move forward deltat in time + pos[j] = pos[j] + (p[j] / mj) * deltat + + # Bounce off the boundary of the torus + for j in range(Natoms): + poscircle[j] = versor(pos[j]) * RingRadius * [1, 1, 0] + outside = np.greater_equal(mag(poscircle - pos), RingThickness - 2 * Ratom) + + for k in range(len(outside)): + if outside[k] == 1 and np.dot(p[k], pos[k] - poscircle[k]) > 0: + p[k] = reflection(p[k], pos[k] - poscircle[k]) + + # then update positions of display objects + for i in range(Natoms): + Atoms[i].pos(pos[i]) ### <-- + outside = np.greater_equal(mag(pos), RingRadius + RingThickness) + + vp.show() ### <-- + vp.camera.Azimuth(0.5) + vp.camera.Elevation(0.1) + pb.print() + +vp.show(interactive=1) From ecb8873d7a913927e1c00821586bbe2599fc32e8 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:02 +0200 Subject: [PATCH 59/67] Removed trailing spaces in examples/simulations/multiple_pendulum.py --- examples/simulations/multiple_pendulum.py | 220 +++++++++++----------- 1 file changed, 110 insertions(+), 110 deletions(-) diff --git a/examples/simulations/multiple_pendulum.py b/examples/simulations/multiple_pendulum.py index 2e734d45..53f98b6d 100644 --- a/examples/simulations/multiple_pendulum.py +++ b/examples/simulations/multiple_pendulum.py @@ -1,110 +1,110 @@ -from __future__ import division, print_function -from vtkplotter import Plotter, printc, mag, versor, vector -from vtkplotter import Cylinder, Spring, Box, Sphere -import numpy as np - -############## Constants -N = 5 # number of bobs -R = 0.3 # radius of bob (separation between bobs=1) -Ks = 50 # k of springs (masses=1) -g = 9.81 # gravity acceleration -gamma = 0.1 # some friction -Dt = 0.03 # time step - -# Create the initial positions and velocities (0,0) of the bobs -bob_x = [0] -bob_y = [0] -x_dot = [0] * (N + 1) # velocities -y_dot = [0] * (N + 1) - -for k in range(1, N + 1): - alpha = np.pi / 5 * k / 10 - bob_x.append(bob_x[k - 1] + np.cos(alpha) + np.random.normal(0, 0.1)) - bob_y.append(bob_y[k - 1] + np.sin(alpha) + np.random.normal(0, 0.1)) - -# Create the bobs -vp = Plotter(title="Multiple Pendulum", axes=0, interactive=0) -vp.add(Box(pos=(0, -5, 0), length=12, width=12, height=0.7, c="k").wire(1)) -bob = [vp.add(Sphere(pos=(bob_x[0], bob_y[0], 0), r=R / 2, c="gray"))] -for k in range(1, N + 1): - bob.append(vp.add(Cylinder(pos=(bob_x[k], bob_y[k], 0), r=R, height=0.3, c=k))) - -# Create the springs out of N links -link = [0] * N -for k in range(N): - p0 = bob[k].pos() - p1 = bob[k + 1].pos() - link[k] = vp.add(Spring(p0, p1, thickness=0.015, r=R / 3, c="gray")) - -# Create some auxiliary variables -x_dot_m = [0] * (N + 1) -y_dot_m = [0] * (N + 1) -dij = [0] * (N + 1) # array with distances to previous bob -dij_m = [0] * (N + 1) -for k in range(1, N + 1): - dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) - -fctr = lambda x: (x - 1) / x -Dt *= np.sqrt(1 / g) -Dt2 = Dt / 2 # Midpoint time step -DiaSq = (2 * R) ** 2 # Diameter of bob squared - -printc("Press F1 to abort execution.", c="red") - -while True: - bob_x_m = list(map((lambda x, dx: x + Dt2 * dx), bob_x, x_dot)) # midpoint variables - bob_y_m = list(map((lambda y, dy: y + Dt2 * dy), bob_y, y_dot)) - - for k in range(1, N + 1): - factor = fctr(dij[k]) - x_dot_m[k] = x_dot[k] - Dt2 * (Ks * (bob_x[k] - bob_x[k - 1]) * factor + gamma * x_dot[k]) - y_dot_m[k] = y_dot[k] - Dt2 * ( - Ks * (bob_y[k] - bob_y[k - 1]) * factor + gamma * y_dot[k] + g - ) - - for k in range(1, N): - factor = fctr(dij[k + 1]) - x_dot_m[k] -= Dt2 * Ks * (bob_x[k] - bob_x[k + 1]) * factor - y_dot_m[k] -= Dt2 * Ks * (bob_y[k] - bob_y[k + 1]) * factor - - # Compute the full step variables - bob_x = list(map((lambda x, dx: x + Dt * dx), bob_x, x_dot_m)) - bob_y = list(map((lambda y, dy: y + Dt * dy), bob_y, y_dot_m)) - - for k in range(1, N + 1): - dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) - dij_m[k] = mag([bob_x_m[k] - bob_x_m[k - 1], bob_y_m[k] - bob_y_m[k - 1]]) - factor = fctr(dij_m[k]) - x_dot[k] -= Dt * (Ks * (bob_x_m[k] - bob_x_m[k - 1]) * factor + gamma * x_dot_m[k]) - y_dot[k] -= Dt * (Ks * (bob_y_m[k] - bob_y_m[k - 1]) * factor + gamma * y_dot_m[k] + g) - - for k in range(1, N): - factor = fctr(dij_m[k + 1]) - x_dot[k] -= Dt * Ks * (bob_x_m[k] - bob_x_m[k + 1]) * factor - y_dot[k] -= Dt * Ks * (bob_y_m[k] - bob_y_m[k + 1]) * factor - - # Check to see if they are colliding - for i in range(1, N): - for j in range(i + 1, N + 1): - dist2 = (bob_x[i] - bob_x[j]) ** 2 + (bob_y[i] - bob_y[j]) ** 2 - if dist2 < DiaSq: # are colliding - Ddist = np.sqrt(dist2) - 2 * R - tau = versor([bob_x[j] - bob_x[i], bob_y[j] - bob_y[i],0]) - DR = Ddist / 2 * tau - bob_x[i] += DR[0] # DR.x - bob_y[i] += DR[1] # DR.y - bob_x[j] -= DR[0] # DR.x - bob_y[j] -= DR[1] # DR.y - Vji = vector(x_dot[j] - x_dot[i], y_dot[j] - y_dot[i]) - DV = np.dot(Vji, tau) * tau - x_dot[i] += DV[0] # DV.x - y_dot[i] += DV[1] # DV.y - x_dot[j] -= DV[0] # DV.x - y_dot[j] -= DV[1] # DV.y - - # Update the locations of the bobs and the stretching of the springs - for k in range(1, N + 1): - bob[k].pos([bob_x[k], bob_y[k], 0]) - link[k - 1].stretch(bob[k - 1].pos(), bob[k].pos()) - - vp.show() +from __future__ import division, print_function +from vtkplotter import Plotter, printc, mag, versor, vector +from vtkplotter import Cylinder, Spring, Box, Sphere +import numpy as np + +############## Constants +N = 5 # number of bobs +R = 0.3 # radius of bob (separation between bobs=1) +Ks = 50 # k of springs (masses=1) +g = 9.81 # gravity acceleration +gamma = 0.1 # some friction +Dt = 0.03 # time step + +# Create the initial positions and velocities (0,0) of the bobs +bob_x = [0] +bob_y = [0] +x_dot = [0] * (N + 1) # velocities +y_dot = [0] * (N + 1) + +for k in range(1, N + 1): + alpha = np.pi / 5 * k / 10 + bob_x.append(bob_x[k - 1] + np.cos(alpha) + np.random.normal(0, 0.1)) + bob_y.append(bob_y[k - 1] + np.sin(alpha) + np.random.normal(0, 0.1)) + +# Create the bobs +vp = Plotter(title="Multiple Pendulum", axes=0, interactive=0) +vp.add(Box(pos=(0, -5, 0), length=12, width=12, height=0.7, c="k").wire(1)) +bob = [vp.add(Sphere(pos=(bob_x[0], bob_y[0], 0), r=R / 2, c="gray"))] +for k in range(1, N + 1): + bob.append(vp.add(Cylinder(pos=(bob_x[k], bob_y[k], 0), r=R, height=0.3, c=k))) + +# Create the springs out of N links +link = [0] * N +for k in range(N): + p0 = bob[k].pos() + p1 = bob[k + 1].pos() + link[k] = vp.add(Spring(p0, p1, thickness=0.015, r=R / 3, c="gray")) + +# Create some auxiliary variables +x_dot_m = [0] * (N + 1) +y_dot_m = [0] * (N + 1) +dij = [0] * (N + 1) # array with distances to previous bob +dij_m = [0] * (N + 1) +for k in range(1, N + 1): + dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) + +fctr = lambda x: (x - 1) / x +Dt *= np.sqrt(1 / g) +Dt2 = Dt / 2 # Midpoint time step +DiaSq = (2 * R) ** 2 # Diameter of bob squared + +printc("Press F1 to abort execution.", c="red") + +while True: + bob_x_m = list(map((lambda x, dx: x + Dt2 * dx), bob_x, x_dot)) # midpoint variables + bob_y_m = list(map((lambda y, dy: y + Dt2 * dy), bob_y, y_dot)) + + for k in range(1, N + 1): + factor = fctr(dij[k]) + x_dot_m[k] = x_dot[k] - Dt2 * (Ks * (bob_x[k] - bob_x[k - 1]) * factor + gamma * x_dot[k]) + y_dot_m[k] = y_dot[k] - Dt2 * ( + Ks * (bob_y[k] - bob_y[k - 1]) * factor + gamma * y_dot[k] + g + ) + + for k in range(1, N): + factor = fctr(dij[k + 1]) + x_dot_m[k] -= Dt2 * Ks * (bob_x[k] - bob_x[k + 1]) * factor + y_dot_m[k] -= Dt2 * Ks * (bob_y[k] - bob_y[k + 1]) * factor + + # Compute the full step variables + bob_x = list(map((lambda x, dx: x + Dt * dx), bob_x, x_dot_m)) + bob_y = list(map((lambda y, dy: y + Dt * dy), bob_y, y_dot_m)) + + for k in range(1, N + 1): + dij[k] = mag([bob_x[k] - bob_x[k - 1], bob_y[k] - bob_y[k - 1]]) + dij_m[k] = mag([bob_x_m[k] - bob_x_m[k - 1], bob_y_m[k] - bob_y_m[k - 1]]) + factor = fctr(dij_m[k]) + x_dot[k] -= Dt * (Ks * (bob_x_m[k] - bob_x_m[k - 1]) * factor + gamma * x_dot_m[k]) + y_dot[k] -= Dt * (Ks * (bob_y_m[k] - bob_y_m[k - 1]) * factor + gamma * y_dot_m[k] + g) + + for k in range(1, N): + factor = fctr(dij_m[k + 1]) + x_dot[k] -= Dt * Ks * (bob_x_m[k] - bob_x_m[k + 1]) * factor + y_dot[k] -= Dt * Ks * (bob_y_m[k] - bob_y_m[k + 1]) * factor + + # Check to see if they are colliding + for i in range(1, N): + for j in range(i + 1, N + 1): + dist2 = (bob_x[i] - bob_x[j]) ** 2 + (bob_y[i] - bob_y[j]) ** 2 + if dist2 < DiaSq: # are colliding + Ddist = np.sqrt(dist2) - 2 * R + tau = versor([bob_x[j] - bob_x[i], bob_y[j] - bob_y[i],0]) + DR = Ddist / 2 * tau + bob_x[i] += DR[0] # DR.x + bob_y[i] += DR[1] # DR.y + bob_x[j] -= DR[0] # DR.x + bob_y[j] -= DR[1] # DR.y + Vji = vector(x_dot[j] - x_dot[i], y_dot[j] - y_dot[i]) + DV = np.dot(Vji, tau) * tau + x_dot[i] += DV[0] # DV.x + y_dot[i] += DV[1] # DV.y + x_dot[j] -= DV[0] # DV.x + y_dot[j] -= DV[1] # DV.y + + # Update the locations of the bobs and the stretching of the springs + for k in range(1, N + 1): + bob[k].pos([bob_x[k], bob_y[k], 0]) + link[k - 1].stretch(bob[k - 1].pos(), bob[k].pos()) + + vp.show() From c2be953202aa6938b9deec4c512ad949a589f019 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:23:09 +0200 Subject: [PATCH 60/67] Removed trailing spaces in examples/simulations/pendulum.py --- examples/simulations/pendulum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simulations/pendulum.py b/examples/simulations/pendulum.py index 0273d332..43797620 100644 --- a/examples/simulations/pendulum.py +++ b/examples/simulations/pendulum.py @@ -1,7 +1,7 @@ ''' Visualize the phase space of a simple pendulum. x = starting angle theta -y = starting angular velocity +y = starting angular velocity ''' # From https://www.youtube.com/watch?v=p_di4Zn4wz4 # Overview of differential equations | Chapter 1 From a11957ece06e8beb5e29d9c410e031ccb75d049c Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:34 +0200 Subject: [PATCH 61/67] Removed trailing spaces in examples/basic/silhouette.py --- examples/basic/silhouette.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/silhouette.py b/examples/basic/silhouette.py index ceab9356..8b09655a 100644 --- a/examples/basic/silhouette.py +++ b/examples/basic/silhouette.py @@ -13,4 +13,4 @@ sx.silhouette(), sy.silhouette(), sz.silhouette(), - Text(__doc__), axes=1, viewup='z', bg='w') \ No newline at end of file + Text(__doc__), axes=1, viewup='z', bg='w') From 424f56b7cbbcb0ca5619e3c70cbf3a2b105cc2c3 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:34 +0200 Subject: [PATCH 62/67] Removed trailing spaces in examples/basic/sliders.py --- examples/basic/sliders.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/sliders.py b/examples/basic/sliders.py index 4d511ada..c3130c0d 100644 --- a/examples/basic/sliders.py +++ b/examples/basic/sliders.py @@ -22,7 +22,7 @@ def slider2(widget, event): vp.addSlider2D(slider1, -9, 9, value=0, pos=4, title="color number") vp.addSlider2D( - slider2, xmin=0.01, xmax=0.99, value=0.5, + slider2, xmin=0.01, xmax=0.99, value=0.5, pos=14, c="blue", title="alpha value (opacity)" ) vp.show() From 4ee1a9148fd363f46d259b84b020efb6836c9c5e Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:34 +0200 Subject: [PATCH 63/67] Removed trailing spaces in examples/basic/specular.py --- examples/basic/specular.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/basic/specular.py b/examples/basic/specular.py index ca8179f3..25a1ebb1 100644 --- a/examples/basic/specular.py +++ b/examples/basic/specular.py @@ -15,17 +15,17 @@ for i in range(8): s = vp.load(datadir+'pumpkin.vtk')#.color(i) s.normalize().pos((i%4)*2.2, int(i<4)*3, 0) - + #s.phong() #s.gouraud() s.flat() - + # modify the default with specific values s.lighting('default', ambient, diffuse, specular, specularPower, specularColor) #ambient += 0.125 diffuse += 0.125 specular += 0.125 - + vp.add(Text(__doc__)) vp.show() From 24ec5c56ca52dbe29de14a79dbf6b915c680ea13 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:34 +0200 Subject: [PATCH 64/67] Removed trailing spaces in examples/basic/trail.py --- examples/basic/trail.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/trail.py b/examples/basic/trail.py index 1fe9ae65..1121fb6a 100644 --- a/examples/basic/trail.py +++ b/examples/basic/trail.py @@ -1,5 +1,5 @@ """ -Example usage of addTrail(). +Example usage of addTrail(). Add a trailing line to a moving object. """ print(__doc__) From 6f3622da1b23351c510af9bb18911e1fc3904f7f Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:34 +0200 Subject: [PATCH 65/67] Removed trailing spaces in examples/basic/tube.py --- examples/basic/tube.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basic/tube.py b/examples/basic/tube.py index 4bcf267b..c224ff4b 100644 --- a/examples/basic/tube.py +++ b/examples/basic/tube.py @@ -1,5 +1,5 @@ """ -A scalar array can be specified to vary +A scalar array can be specified to vary radius and color of a line represented as a tube. """ print(__doc__) From fdbd087c676b3824b4d3f839da61c58df670bef1 Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Tue, 21 May 2019 23:25:45 +0200 Subject: [PATCH 66/67] Removed trailing spaces in examples/other/qt_embed.py --- examples/other/qt_embed.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/other/qt_embed.py b/examples/other/qt_embed.py index fa281fd3..bf0e4215 100644 --- a/examples/other/qt_embed.py +++ b/examples/other/qt_embed.py @@ -1,5 +1,5 @@ """ -A sort of minimal example of how to embed a rendering window +A sort of minimal example of how to embed a rendering window into a qt application. """ print(__doc__) From dc865f28dec0c6f10de159dc1f8f20dd69ee74cf Mon Sep 17 00:00:00 2001 From: Guillaume Jacquenot Date: Wed, 22 May 2019 16:56:50 +0200 Subject: [PATCH 67/67] Typo update in actors.py --- vtkplotter/actors.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/vtkplotter/actors.py b/vtkplotter/actors.py index 4a4c7fd1..a357b219 100644 --- a/vtkplotter/actors.py +++ b/vtkplotter/actors.py @@ -964,7 +964,7 @@ def getPoints(self, transformed=True, copy=True): Return the list of vertex coordinates of the input mesh. Same as `actor.coordinates()`. - :param bool transformed: if `False` ignore any previous trasformation + :param bool transformed: if `False` ignore any previous transformation applied to the mesh. :param bool copy: if `False` return the reference to the points so that they can be modified in place. @@ -1451,7 +1451,7 @@ def clone(self, transformed=True): """ Clone a ``Actor(vtkActor)`` and make an exact copy of it. - :param transformed: if `False` ignore any previous trasformation applied to the mesh. + :param transformed: if `False` ignore any previous transformation applied to the mesh. .. hint:: |carcrash| |carcrash.py|_ """ @@ -2465,7 +2465,7 @@ def coordinates(self, transformed=True, copy=False): """ Return the list of vertex coordinates of the input mesh. Same as `actor.getPoints()`. - :param bool transformed: if `False` ignore any previous trasformation applied to the mesh. + :param bool transformed: if `False` ignore any previous transformation applied to the mesh. :param bool copy: if `False` return the reference to the points so that they can be modified in place, otherwise a copy is built. @@ -3163,8 +3163,3 @@ def getVoxelScalar(self, vmin=None, vmax=None): s = (s - vmin) / (vmax - vmin) voxdata[i, j, k] = s return voxdata - - - - -