SymPy cannot evaluate dot product of *metamorphosed* vectors - python

I am working with SymPy vectors:
from sympy import *
from sympy.vector import *
N = CoordSys3D('N')
x = symbols('x')
v = x * N.i + x**2 * N.j
vf=factor(v)
vf1=vf.as_independent(Vector)[1]
type(vf1)
# sympy.core.add.Add
I need to calculate dot(vf1,vf1). But SymPy does not evaluate the dot product:
ss = dot(vf1,vf1)
ss
# 1 + 2*Dot(N.i, N.j*x) + Dot(N.j*x, N.j*x)
I suspect, this is because vf1 has been metamorphosed into another type, i.e. sympy.core.add.Add).
Is there a way to make SymPy evaluate ss? Is there a way to cast vf1 as a sympy.vector...?
EDIT
I have written a function that does the dot product. But I need to do this the SymPy way, so I don't have to re-implement my own version of every function in sympy.vector.

Yes, the as_independent does not respect the class of Add or Mul that it is dealing with and only uses Mul/Add (instead of VectorMul/VectorAdd in your case). This can be fixed with a transform:
>>> from sympy.core.rules import Transform
>>> T = Transform(lambda x: (VectorMul if x.is_Mul else VectorAdd)(*x.args),
... lambda x: x.is_Add or x.is_Mul and any(isinstance(i,BaseVector)
... for i in x.args))
>>> vf1.xreplace(T)
N.i + x*N.j
>>> dot(_,_)
x**2 + 1

Related

How to use sympy to convert all standalone integers in an expression that aren't exponents to 1

Is there a way to use sympy to find/replace all standalone integers (that aren't exponents) to 1.
For example, converting the following:
F(x) = (2/x^2) + (3/x^3) + 4
To:
F(x) = (1/x^2) + (1/x^3) + 1
I've searched extensively on stackoverflow for sympy expression.match/replace/find solutions, and have tried using a Wildcard symbol to find and replace all numbers in the expression but I keep running into the issue of matching and replacing the exponents (2 and 3 in this example) as well as they are also considered numbers.
Is there a simple (pythonic) way to achieve the above?
Thanks!
setdefault used with replace is a nice way to go. The single expression below has 3 steps:
mask off powers and record
change Rationals to 1 (to handle integers in numer or denom)
restore powers
>>> from sympy.abc import x
>>> from sympy import Dummy
>>> eq = (2/x**2) + (3/x**3) + 4 + 1/x/8
>>> reps = {}
>>> eq = eq.replace(lambda x: x.is_Pow, lambda x: reps.setdefault(x, Dummy())
).replace(lambda x: x.is_Rational, lambda x: 1
).xreplace({v:k for k,v in reps.items()})
1 + 1/x + 1/x**2 + 1/x**3
You can write a function that will recurse into your expression. For any expression expr, expr.args will give you the components of that expression. expr.is_constant() will tell you if it's a constant. expr.is_Pow will tell you if it's an exponential expression, so you can choose not to drill down into these expressions.
import sympy
def get_constants(expr):
c = set()
for x in expr.args:
if x.is_constant(): c |= {x}
if not x.is_Pow:
c |= get_constants(x)
return c
Now, you can get all the constants in said expression, and replace each of these constants using expr.replace().
def replace_constants(expr, repl):
for const in get_constants(expr):
expr = expr.replace(const, repl)
return expr
With your example expression, we get:
x = sympy.symbols('x')
F = 2/x**2 + 3/x**3 + 4
G = replace_constants(F, 1)
print(F) # 4 + 2/x**2 + 3/x**3
print(G) # 1 + x**(-2) + x**(-3)

How to calculate 2x + 4 = 10 using sympy?

How to calculate 2x + 4 = 10 using Sympy? Is it even possible?
It does not run on Sympy gamma but it runs on Wolframalpha and Cymath. Is it normal or is there some built-in library that should be used with this type of equation?
To represent it,
>>> from sympy.abc import x
>>> from sympy import S, Eq, solve
>>> eq = Eq(2*x + 4, 10)
>>> pprint(eq)
2*x + 4 = 10
To solve it:
>>> solve(eq)
[3]
To interpret input:
>>> s = '2*x + 4 = 10'
>>> eq = Eq(*map(S, s.split('=')))

Taylor series sympy expression of a python function

I have a very complicated non-linear function f. I want to get taylor series till degree n in a form of sympy expression for the function f at value x.
f is a regular python function not a sympy expression. Output of get_polynomial should be a sympy expression.
Is there any function that will get taylor-series of a function?
from math import sin, cos, log, e
def f(x):
# a very complicated function
y = sin(x) + cos(x) + log(abs(x)+2)**2/e**2 + sin(cos(x/2)**2) + 1
return y
def get_polynomial(function, x, degree):
# .......
# using Taylor Series
# .......
return sympy_expression_for_function_at_value_x
Output:
get_polynomial(sin, 0, 3) ---> 0 + x + 0*x**2 + (1/6)*x**3
get_polynomial(lambda x: e**x, 0, 1) --> 1 + x
In a similar manner I wanna calculate get_polynomial(f, 0, 3)
The following code is close to what you're looking for. What this does it to parse the code the of the function you wish you expand into a Taylor series, convert it into a symbolic representation using Sympy and then compute the Taylor expansion.
One limitation is that you need to have an explicit function definition so you can't use lambda expressions. This can be solved with further work. Otherwise the code does what you ask for. Note that when you define a function, it has to contain a line of the form y = ... for this code to work
from inspect import *
import sympy
def f(x):
# a very complicated function
y = sin(x) + cos(x) + log(abs(x)+2)**2/e**2 + sin(cos(x/2)**2) + 1
return y
def my_sin(x):
y = sin(x)
return y
def my_exp(x):
y = e**x
return y
x = sympy.Symbol('x')
def get_polynomial(function, x0, degree):
# parse function definition code
lines_list = getsource(function).split("\n")
for line in lines_list:
if '=' in line:
func_def = line
elements = func_def.split('=')
line = ' '.join(elements[1:])
sympy_function = sympy.sympify(line)
# compute taylor expansion symbolically
i = 0
taylor_exp = sympy.Integer(0)
while i <= degree:
taylor_exp = taylor_exp + (sympy.diff(sympy_function,x,i).subs(x,x0))/(sympy.factorial(i))*(x-x0)**i
i += 1
return taylor_exp
print (get_polynomial(my_sin,0,5))
print (get_polynomial(my_exp,0,5))
print (get_polynomial(f,0,5))

Isolate all variables to LHS in sympy?

I am using sympy to process some equations. I want to write the equations in a canonical form such that variables of interest are all on LHS. For eg. if I have,
lhs = sympify("e*x +f")`
rhs = sympify("g*y + t*x +h")`
eq = Eq(lhs,rhs)
e*x + f == g*y + h + t*x
I need a function which can isolate a list of given variables (my so called canonical form), like
IsolateVariablesToLHS(eq,[x,y]) # desired function
(e-t)*x - g*y == h-f # now x and y are on LHS and remaining are on RHS
I have the assurance that I will only get linear equations, so this is always possible.
>>> import sympy as sm
>>> lhs = sm.sympify('e*x + f')
>>> rhs = sm.sympify('g*y + t*x + h')
>>> eq = sm.Eq(lhs, rhs)
Here's a simple construct
def isolateVariablesToLHS(eq, syms):
l = sm.S.Zero
eq = eq.args[0] - eq.args[1]
for e in syms:
ind = eq.as_independent(e)[1]
l += ind
eq -= ind
return sm.Eq(l, eq)
>>> isolateVariablesToLHS(eq, [x, y])
Eq(e*x - g*y - t*x, f - h)
With the equation as provided in the question combine all the terms and construct a filter for discovering the required variables.
>>> from itertools import filterfalse
>>> terms = eq.lhs - eq.rhs
>>> vars = ['x', 'y']
>>> filt = lambda t: any(t.has(v) for v in vars)
>>> result = Eq(sum(filter(filt, terms.args)), - sum(filterfalse(filt, terms.args))
>>> result
e*x - g*y - t*x == -f + h
I'm not familiar with sympy but I think this will work for equations consisting of proper atoms such as Symbols. Make sure you replace the vars list with the actual instantiated Symbols x, y instead of the 'ascii' representations. This is probably required to combine terms that have variables in common.
filter and filterfalse might have different names in python 2.x, but this functionality is probably still in the itertools package.

Differentiation in python using Sympy

How do i implement this kind of equation in python dC/dt = r + kI - dC where the left hand side are constants and the right hand side are varibles?
i am relatively new to python and as such can't really do much.
from sympy.solvers import ode
r=float(input("enter r:"))
k=float(input("enter k:"))
I=float(input("enter I:"))
d=float(input("enter d:"))
C=float(input("enter C:"))
dC/dt=x
x=r + kI-dC
print(x)
what it just does equate the values of x and not any differential, would like help getting this to work.
if possible i would like to get answer specifying the using of sympy,
but all answers are truly appreciated.
You asigned values to all the variables that are on the rhs of x so when you show x you see the value that it took on with the variables that you defined. Rather than input values, why not try solve the ode symbolically if possible?
>>> from sympy import *
>>> var('r k I d C t')
(r, k, I, d, C, t)
>>> eq = Eq(C(t).diff(t), r + k*I + d*C(t)) # note d*C(t) not d*C
>>> ans = dsolve(eq); ans
C(t) == (-I*k - r + exp(d*(C1 + t)))/d
Now you can substitute in values for the variables to see the result:
>>> ans.subs({k: 0})
C(t) == (-r + exp(d*(C1 + t)))/d

Categories