2

How can I tell if a sympy expression is a vector? See the following example:

from sympy import *
from sympy.vector import *
N = CoordSys3D('N')
x = symbols('x')
v = x * N.i + x**2 * N.j + x**3 * N.k
type(v)
# sympy.vector.vector.VectorAdd

vf=factor(v)
vfs = vf.as_ordered_factors()
vfs
#[x, N.i + N.j*x + N.k*x**2]

type(vfs[1])
# sympy.core.add.Add

After v was factored, none of its factors have a sympy.vector... type. How can I tell which one of its factors is a vector? Is there a test for that?

Eliad
  • 894
  • 6
  • 20
  • I had a similar problem recently but with transfer functions. Because of how `SymPy` by default simplifies some expressions. The conclusion to which I came is that you simply have to assume that the type may change over time. For example if you tell it to give you its denominator of a transfer function in the s domain, because that denominator may be a single real number like `1` or `15` it will convert it into SymPys number class. So my guess is to just to either plan ahead for certain assumptions so like `if this and that is a number then this` or forcefully convert it into something. – John May 25 '20 at 17:07
  • Altho here I found something useful: https://stackoverflow.com/questions/30023064/detect-if-variable-is-of-sympy-type/30039361 You may try to check its class and then work around it changing it by default – John May 25 '20 at 17:09

1 Answers1

1

SymPy has a variety of ways to search/parse expressions. Something that may work for you is the as_independent method:

>>> vf.as_independent(Vector)
(x, N.i + N.j*x + N.k*x**2)

You Vector-dependent part of vf will be the rightmost element.

smichr
  • 16,948
  • 2
  • 27
  • 34
  • Is this guaranteed? In other words, is this the expected (defined) behavior of `as_dependent(Vector)`? – Eliad May 26 '20 at 09:23
  • Yes. If `vf` is a Vector or has a single Vector as a factor in a product, the rightmost argument of the return tuple will be that Vector. – smichr May 26 '20 at 13:52