pythonplotphysicspyvista

Truth value of an array is ambiguous in PyVista glyph, orient does not recognize my vector array


I am trying to add spin vectors as arrows onto the vertices of a lattice. However I always get :

line 2382, in glyph if orient: ^^^^^^ ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This is my first time using PyVista and I have no clue.

import numpy as np
import vtk
import pyvista as pv

cols = 12
rows = 12
spacing = 10.0


points = []

# create lattice
for i in range(rows):
    for j in range(cols):
        x = j * spacing
        y = i * (spacing * np.sqrt(3) / 2)
        if i % 2 == 1:  
            x += spacing / 2
        points.append([x, y, 0.0])

points = np.array(points)  
spins = np.random.choice([-1, 1], size=(len(points), 3))


normed_spins = spins / np.linalg.norm(spins, axis=1)[:, np.newaxis]


lattice = pv.PolyData(points)

arrows = lattice.glyph(orient=normed_spins, scale=True, factor=0.5)
print(spins[:5])

plotter = pv.Plotter()


plotter.add_mesh(lattice, color="black", point_size=10, render_points_as_spheres=True, label="Gitterpunkte")


plotter.add_mesh(arrows, color="red", label="Spins")


plotter.show_bounds(grid="front", location="outer", all_edges=True)
plotter.show(title=)


Solution

  • You are using glyph incorrectly

    glyph(orient=True, scale=True, factor=1.0, geom=None, indices=None, tolerance=None, absolute=False, clamping=False, rng=None, color_mode='scale', progress_bar=False) method of pyvista.core.pointset.PolyData instance
        Copy a geometric representation (called a glyph) to the input dataset.
    
        The glyph may be oriented along the input vectors, and it may
        be scaled according to scalar data or vector
        magnitude. Passing a table of glyphs to choose from based on
        scalars or vector magnitudes is also supported.  The arrays
        used for ``orient`` and ``scale`` must be either both point data
        or both cell data.
    
        Parameters
        ----------
        orient : bool | str, default: True
            If ``True``, use the active vectors array to orient the glyphs.
            If string, the vector array to use to orient the glyphs.
            If ``False``, the glyphs will not be orientated.
        enter code here
    ...
    

    Notice that orient can either be a string or a bool. You are passing the wrong datatype. You're passing a numpy array (normed_spins) as the value for the orient parameter in the lattice.glyph() function. PyVista's glyph() method expects the orient argument to be the name of a vector array present in the PolyData object rather than the array itself.

    Source: https://tutorial.pyvista.org/tutorial/04_filters/solutions/e_glyphs.html

    Try

    lattice = pv.PolyData(points)
    lattice['vectors'] = normed_spins
    arrows = lattice.glyph(orient='vectors', scale=True, factor=0.5)