Skip to content

Commit

Permalink
fix quiver
Browse files Browse the repository at this point in the history
  • Loading branch information
marcomusy committed May 3, 2020
1 parent 5e30050 commit bb40ca1
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 47 deletions.
12 changes: 6 additions & 6 deletions vtkplotter/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
def getNotebookBackend(actors2show, zoom, viewup):

vp = settings.plotter_instance

if isinstance(vp.shape, str) or sum(vp.shape) > 2:
colors.printc("Multirendering is not supported in jupyter.", c=1)
return
Expand Down Expand Up @@ -101,7 +101,7 @@ def getNotebookBackend(actors2show, zoom, viewup):
kobj = None
kcmap= None
name = None

#####################################################################scalars
# work out scalars first, Points Lines are also Mesh objs
if isinstance(ia, (Mesh, shapes.Line, shapes.Points)):
Expand Down Expand Up @@ -179,7 +179,7 @@ def getNotebookBackend(actors2show, zoom, viewup):
pos = (ia.GetPosition()[0],ia.GetPosition()[1])
kobj = k3d.text2d(ia.info['formula'], position=pos)
settings.notebook_plotter += kobj

#####################################################################Points
elif isinstance(ia, shapes.Points) or ia.NPoints() == ia.NCells():
# print('Points', ia.name, ia.N())
Expand Down Expand Up @@ -227,9 +227,9 @@ def getNotebookBackend(actors2show, zoom, viewup):
kcols = k3d.helpers.map_colors(scals, kcmap,
[scals_min,scals_max]).astype(numpy.uint32)
sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

for i, ln_idx in enumerate(ia.lines(joined=True)):
if i>200:
if i>200:
print('WARNING: K3D nr of line segments is limited to 200.')
break
pts = ia.points()[ln_idx]
Expand All @@ -241,7 +241,7 @@ def getNotebookBackend(actors2show, zoom, viewup):
width=iap.GetLineWidth()*sqsize/1000,
name=name,
)

settings.notebook_plotter += kobj


Expand Down
20 changes: 10 additions & 10 deletions vtkplotter/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ def addPointArray(self, input_array, name):
colors.printc('~times addPointArray(): Number of elements != nr. of points',
len(input_array), data.GetNumberOfPoints(), c=1)
raise RuntimeError()

nparr = np.ascontiguousarray(input_array)
if len(nparr.shape)==1: # scalars
varr = numpy_to_vtk(nparr, deep=True)
Expand Down Expand Up @@ -777,12 +777,12 @@ def addCellArray(self, input_array, name):
self._mapper.SetArrayName(name)
self._mapper.SetScalarModeToUseCellData()
return self

if len(input_array) != data.GetNumberOfCells():
colors.printc('~times addCellArray(): Number of elements != nr. of Cells',
len(input_array), data.GetNumberOfCells(), c=1)
raise RuntimeError()

nparr = np.ascontiguousarray(input_array)
if len(nparr.shape)==1: # scalars
varr = numpy_to_vtk(nparr, deep=True)
Expand All @@ -791,7 +791,7 @@ def addCellArray(self, input_array, name):
data.GetCellData().SetActiveScalars(name)
self._mapper.ScalarVisibilityOn()
self._mapper.SetScalarRange(varr.GetRange())

elif len(nparr.shape)==2: # vectors or higher dim ntuples
varr = vtk.vtkFloatArray()
varr.SetNumberOfComponents(nparr.shape[1])
Expand Down Expand Up @@ -871,7 +871,7 @@ def addScalarBar(self,
useAlpha=True,
):
"""
Add a 2D scalar bar for the specified obj.
Add a 2D scalar bar for the specified obj.
.. hint:: |mesh_coloring| |mesh_coloring.py|_ |scalarbars.py|_
"""
Expand All @@ -888,7 +888,7 @@ def addScalarBar(self,
useAlpha,
)
return self


def addScalarBar3D(self,
pos=None,
Expand All @@ -908,15 +908,15 @@ def addScalarBar3D(self,
):
"""
Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)`,
- a ``Mesh`` already containing a set of scalars associated to vertices or cells,
- if ``None`` the last object in the list of actors will be used.
Return an ``Assembly`` object.
:param float sx: thickness of scalarbar
:param float sy: length of scalarbar
:param str title: scalar bar title
Expand All @@ -928,7 +928,7 @@ def addScalarBar3D(self,
:param float labelOffset: space btw numeric labels and scale
:param bool,float italic: use italic font for title and labels
:param bool useAlpha: render transparency of the color bar, otherwise ignore
:param bool drawBox: draw a box around the colorbar (useful with useAlpha=True)
:param bool drawBox: draw a box around the colorbar (useful with useAlpha=True)
|mesh_coloring| |mesh_coloring.py|_
"""
Expand Down
2 changes: 1 addition & 1 deletion vtkplotter/dolfin.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def _compute_uvalues(u, mesh):

if hasattr(u, 'compute_vertex_values'): # old dolfin, works fine
u_values = u.compute_vertex_values(mesh)


if u.value_rank() and u.value_dimension(0)>1:
l = u_values.shape[0]
Expand Down
2 changes: 1 addition & 1 deletion vtkplotter/examples/pyplot/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

qp = quiver(pts1, # points
pts2-pts1, # associated vectors
cmap='jet', # can also be a fixed color
c='r',
)

show(qp, __doc__, axes=1)
5 changes: 3 additions & 2 deletions vtkplotter/examples/volumetric/tet_mesh_ugrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@

cmap = 'nipy_spectral'

vol = Volume(ug).color(cmap)
vol = Volume(ug, c=cmap)

################################
# if False will only show the outer surface:
settings.visibleGridEdges = True

mesh = Mesh(ug).color(cmap).alpha(0.2).addScalarBar(c='w')
mesh = Mesh(ug).cellColors(cmap=cmap).alpha(0.2)
mesh.addScalarBar(c='w')

show([(vol,__doc__), mesh], N=2, bg='bb')
8 changes: 4 additions & 4 deletions vtkplotter/mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,17 +360,17 @@ def faces(self):
def lines(self, joined=False, flat=False):
"""Get lines connectivity ids as a numpy array.
Default format is [[id0,id1], [id3,id4], ...]
:param bool joined: join ends in format, [(1,2), (2,3,4)] -> [(1,2,3,4)]
:param bool flat: 1D numpy array as [2, 10,20, 3, 10,11,12, 2, 70,80, ...]
"""
#Get cell connettivity ids as a 1D array. The vtk format is:
# [nids1, id0 ... idn, niids2, id0 ... idm, etc].
arr1d = vtk_to_numpy(self.polydata(False).GetLines().GetData())

if flat:
return arr1d

i = 0
conn = []
n = len(arr1d)
Expand All @@ -380,7 +380,7 @@ def lines(self, joined=False, flat=False):
i += arr1d[i]+1
if i >= n:
break

if joined: # join ends: [(1,2), (2,3,4)] -> [(1,2,3,4)]
conn = sorted(conn, key=lambda x:x[0])
res=[conn[0]]
Expand Down
2 changes: 1 addition & 1 deletion vtkplotter/picture.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def __init__(self, obj=None):
picr = vtk.vtkTIFFReader()
else:
colors.printc("Cannot understand picture format", obj, c=1)

picr.SetFileName(obj)
picr.Update()
img = picr.GetOutput()
Expand Down
14 changes: 4 additions & 10 deletions vtkplotter/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,6 @@ def _plotxy(
pad=0.05,
axes={},
):
# settings.defaultAxesType = 0 # because of yscaling
ncolls = len(settings.collectable_actors)

if marker == "" and not line and not spline:
Expand Down Expand Up @@ -845,7 +844,6 @@ def _plotFxy(
acts.append(nansact)

if axes:
# settings.defaultAxesType = 0
axs = addons.buildAxes(mesh)
acts.append(axs)
asse = Assembly(acts)
Expand Down Expand Up @@ -910,7 +908,6 @@ def _plotFz(

acts = [mesh]
if axes:
# settings.defaultAxesType = 0
axs = addons.buildAxes(mesh, ztitle="Real part")
acts.append(axs)
asse = Assembly(acts)
Expand Down Expand Up @@ -1141,7 +1138,6 @@ def _histogram1D(
axes={},
bc="k",
):
# settings.defaultAxesType = 0 # because of yscaling
ncolls = len(settings.collectable_actors)

# purge NaN from data
Expand Down Expand Up @@ -1397,7 +1393,6 @@ def _histogram2D(
axes=True,
bc="k",
):
# settings.defaultAxesType = 0 # because of yscaling
ncolls = len(settings.collectable_actors)
offs = 0 # z offset

Expand Down Expand Up @@ -1446,15 +1441,14 @@ def _histogram2D(
resx=bins[0],
resy=bins[1],
)
g.alpha(alpha).lw(lw).wireframe(0).flat().lighting("ambient")
g.alpha(alpha).lw(lw).wireframe(0).flat().lighting(enabled=False)
g.cellColors(np.ravel(H.T), cmap=cmap)
g.SetOrigin(x0lim, y0lim, 0)
if scalarbar:
sc = addons.addScalarBar3D(g, c=bc)
sc = g.addScalarBar3D(c=bc)
scy0, scy1 = sc.ybounds()
sc_scale = (y1lim-y0lim)/(scy1-scy0)
sc.scale(sc_scale)
sc.pos(x1lim-sc.xbounds()[0]*1.1, (y0lim+y1lim)/2, offs)
acts.append(sc)
g.base = np.array([0, 0, 0])
g.top = np.array([0, 0, 1])
Expand Down Expand Up @@ -1933,7 +1927,7 @@ def donut(
def quiver(
points,
vectors,
cmap="jet",
c="k",
alpha=1,
shaftLength=0.8,
shaftWidth=0.05,
Expand Down Expand Up @@ -1969,7 +1963,7 @@ def quiver(
arrs2d = shapes.Arrows2D(
spts,
epts,
c=cmap,
c=c,
shaftLength=shaftLength,
shaftWidth=shaftWidth,
headLength=headLength,
Expand Down
7 changes: 4 additions & 3 deletions vtkplotter/shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,7 @@ def __init__(self, startPoint, endPoint,
tf.Update()

Mesh.__init__(self, tf.GetOutput(), c, alpha)
self.printInfo()
self.SetPosition(startPoint)
self.flat().lighting('ambient')
self.DragableOff()
Expand Down Expand Up @@ -1281,7 +1282,7 @@ class Disc(Mesh):
"""
Build a 2D disc of inner radius `r1` and outer radius `r2`.
:param list res: resolution in R and Phi
:param list res: resolution in R and Phi
|Disk|
"""
Expand Down Expand Up @@ -1472,7 +1473,7 @@ def __init__(self, centers, r=1, c="r", alpha=1, res=8):
res_t, res_phi = res
else:
res_t, res_phi = 2*res, res

src.SetThetaResolution(res_t)
src.SetPhiResolution(res_phi)
src.Update()
Expand Down Expand Up @@ -1570,7 +1571,7 @@ def __init__(self, pos=(0, 0, 0), axis1=(1, 0, 0), axis2=(0, 2, 0), axis3=(0, 0,
res_t, res_phi = res
else:
res_t, res_phi = 2*res, res

elliSource = vtk.vtkSphereSource()
elliSource.SetThetaResolution(res_t)
elliSource.SetPhiResolution(res_phi)
Expand Down
2 changes: 1 addition & 1 deletion vtkplotter/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def buildPolyData(vertices, faces=None, lines=None, indexOffset=0, fast=True, te
sourceVertices.InsertCellPoint(i)
poly.SetVerts(sourceVertices)
return poly ###################


# faces exist
sourcePolygons = vtk.vtkCellArray()
Expand Down
2 changes: 1 addition & 1 deletion vtkplotter/volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ def zSlice(self, k):

def slicePlane(self, origin=(0,0,0), normal=(1,1,1)):
"""Extract the slice along a given plane position and normal.
|slicePlane| |slicePlane.py|_
"""
reslice = vtk.vtkImageReslice()
Expand Down
14 changes: 7 additions & 7 deletions vtkplotter/vtkio.py
Original file line number Diff line number Diff line change
Expand Up @@ -1211,7 +1211,7 @@ def exportWindow(fileoutput, binary=False, speed=None):
outF.close()
colors.printc("~save Saved files:", fileoutput,
fileoutput.replace('.x3d', '.html'), c="g")

elif fr.endswith(".npy"):
sdict = dict()
vp = settings.plotter_instance
Expand All @@ -1237,22 +1237,22 @@ def exportWindow(fileoutput, binary=False, speed=None):
for a in vp.getMeshes() + vp.getVolumes():
sdict['objects'].append(_np_dump(a))
np.save(fileoutput, [sdict])

elif fr.endswith(".html"):
from vtkplotter.backends import getNotebookBackend

savebk = settings.notebookBackend
settings.notebookBackend='k3d'
plt = getNotebookBackend(settings.plotter_instance.actors, 1.5, '')

with open(fileoutput,'w') as fp:
fp.write(plt.get_snapshot())

settings.notebookBackend = savebk

else:
colors.printc("Export extensions is not supported.", c=1)


return

Expand Down Expand Up @@ -1307,7 +1307,7 @@ def importWindow(fileinput, mtlFile=None, texturePath=None):
#colors.printc("Trying to import a single mesh.. use load() instead.", c=1)
#colors.printc(" -> try to load a single object with load().", c=1)
objs = [loadNumpy(fileinput)]

vp.actors = objs
return vp

Expand Down

0 comments on commit bb40ca1

Please sign in to comment.