how pass variable as string, then later use it as sympy symbol? - sympy

I have need to pass to a function, both the integrand and also the integration variable as string. It is not possible to do it in other ways (too long to explain).
The question is, how to do the standard thing, which is x = symbols('x') to define the integration variable (which is passed as string) inside the called function in order to use it in the next call to integrate?
Here is a MWE, and showing what I tried
from sympy import *
def foo(integrand,var):
var = symbols(var)
anti = integrate(integrand,x)
return anti
foo("x*cos(x)","x")
This ofcourse does not work, since var is string on both sides of var = symbols(var)
Then I tried to use eval to first convert the string var which is "x" to variable x, but this does not work either,
x = eval(var)
x = symbols('x')
This fail since x is not defined.
Ofcourse, I could do this
from sympy import *
x = symbols('x')
def foo(integrand,var):
anti = integrate(integrand,x)
return anti
foo("x*cos(x)","x")
But this is not what I want, since the function foo being called, needs to be called with different integration variables from outside, and these have to be strings.
Any suggestion how to handle this? Notice that the issue is with the integration variable only. sympy integrate accepts the integrand as string with no problem, but not the integration variable. So this would also fail
def foo(integrand,var):
anti = integrate(integrand,var)
Python 4.7 with sympy 1.5

Everything is almost fine. Just use var instead of x as the second arg of integrate: it is the name of the Python variable that is connected to the SymPy symbol x:
>>> def foo(integrand,var):
... var = symbols(var)
... anti = integrate(integrand,var)
... return anti
...
>>> foo("x*cos(x)","x")
x*sin(x) + cos(x)

Related

sympy function compose - bizzare results

I'm trying to compose two functions and I get a bizzare result
'''
#!/usr/bin/python
from sympy import *
init_printing(use_unicode=True)
x= symbols('x')
f = x/(x+1);
g = x/(x+2);
print(compose(f,g))
This shows : x/((x + 1)*(x + 2))
Should be x/(2x+2)
I don't get it. Does anyone has an idea?
Thanks
Despite being available in the top-level sympy namespace under the plain name compose, sympy.compose doesn't actually do general function composition.
sympy.compose is actually sympy.polys.polytools.compose. It's actually a function for polynomial composition. When you try to compose x/(x+1) and x/(x+2), it ends up interpreting these inputs as multivariate polynomials in 3 variables, x, 1/(x+1), and 1/(x+2), and the results are total nonsense.

Sympy: prevent a subscripted symbol to be evaluated

Given a symbol s, which ultimately will be an Array, I want to define the following expression
A = Array([-s[1]/2, s[0]/2])
but I'd like A to be evaluated only when I compute some other expressions containing it, because s changes over time. I tried
A = UnevaluatedExpr(Array([-s[1]/2,s[0]/2]))
but I got the error TypeError: 'Symbol' object is not subscriptable, which make me think that some evaluation is performed on s.
Thanks for your patience, I'm just learning Sympy and I'm used to Maxima where this kind of construct is straightforward. To be more precise, with Maxima the full working code I'm trying to translate into Sympy is (in Maxima everything is a symbol, colon is the assignment operator, ev forces evaluation with custom values, the dot before diff is the vector scalar product):
A: [-s[2],s[1]]/2; /* define A in terms of subscripted symbols */
P1: [x1,y1];
P2: [x2,y2];
segment: P1+t*(P2-P1); /* --> [t*(x2-x1)+x1,t*(y2-y1)+y1] */
factor(integrate(ev(A,s=segment).diff(segment,t),t,0,1)); /* integrates the scalar product of A evaluated over segment and the derivative of segment */
Follow up
Thanks to Oscar answer I was able to come up with a working Sympy translation of the above Maxima code (improvements are welcomed!):
from sympy import *
def dotprod(*vectors): # scalar product, is there a built in better way?
return sum(Mul(*x) for x in zip(*vectors))
s = IndexedBase('s')
A = Array([-s[1]/2,s[0]/2])
t,x1,y1,x2,y2 = symbols('t x1 y1 x2 y2')
P1 = Array([x1,y1])
P2 = Array([x2,y2])
segment = P1 + t * (P2-P1)
dotprod(A.subs(s,segment),segment.diff(t)).integrate((t,0,1)).factor()
Apart from the IndexedBase magic the structure of the code in Maxima and Sympy is very similar.
I'm not sure I understand what you want. It's possible that your problem is better approached in a different way rather than using Array. In any case a direct answer to your question is that you can use IndexedBase to make a subscriptable symbol:
In [1]: s = IndexedBase('s')
In [2]: A = Array([-s[1]/2, s[0]/2])
In [3]: A
Out[3]:
⎡-s[1] s[0]⎤
⎢────── ────⎥
⎣ 2 2 ⎦

How to get a value from multiple functions in Pyomo

Let's suppose that the objective function is
max z(x,y) = f1(x) - f2(y)
where f1 is function of variables x and f2 is functions of variables y.
This could be written in Pyomo as
def z(model):
return f1(model) - f2(model)
def f1(model):
return [some summation of x variables with some coefficients]
def f2(model):
return [some summation of y variables with some coefficients]
model.objective = Objective(rule=z)
I know it is possible to get the numeric value of z(x,y) easily by calling (since it is the objective function) :
print(model.objective())
but is there a way to get the numeric value of any of these sub-functions separetedly after the optimization, even if they are not explicitly defined as objectives?
I'll answer your question in terms of a ConcreteModel, since rules in Pyomo, for the most part, are nothing more than a mechanism to delay building a ConcereteModel. For now, they are also required to define indexed objects, but that will likely change soon.
First, there is nothing stopping you from defining those "rules" as standard functions that take in some argument and return a value. E.g.,
def z(x, y):
return f1(x) - f2(y)
def f1(x):
return x + 1
def f2(x):
return y**2
Now if you call any of these functions with a built-in type (e.g., f(1,5)), you will get a number back. However, if you call them with Pyomo variables (or Pyomo expressions) you will get a Pyomo expression back, which you can assign to an objective or constraint. This works because Pyomo modeling components, such as variables, overload the standard algebraic operators like +, -, *, etc. Here is an example of how you can build an objective with these functions:
import pyomo.environ as aml
m = aml.ConcreteModel()
m.x = aml.Var()
m.y = aml.Var()
m.o = aml.Objective(expr= z(m.x, m.y))
Now if m.x and m.y have a value loaded into them (i.e., the .value attribute is something other than None), then you can call one of the sub-functions with them and evaluate the returned expression (slower)
aml.value(f1(m.x))
aml.value(f2(m.y))
or you can extract the value from them and pass that to the sub-functions (faster)
f1(m.x.value)
f2(m.y.value)
You can also use the Expression object to store sub-expressions that you want to evaluate on the fly or share inside multiple other expression on a model (all of which you can update by changing what expression is stored under the Expression object).

How do I display a full expression in sympy?

I am trying to use sympy in a Jupyter notebook to document and perform a series of mathematical cacluations in a reporducible way.
If I define the following:
from sympy import *
init_printing()
x, y, z = symbols("x y z")
x=y+z
x
then I can display the value of x (that is, y+z).
How do I display the full equation (x=y+z)?
Running Eq(x,y+z), even with evaluate=False) returns the expression with the value of x substituted (y+z=y+z).
I tried using Eq(S('x'),y+z), also Eq(S('x'),x) and sympy keep returning a boolean variable.
So I found a way to display it using the Ipython built-in functions:
from sympy import *
from IPython.display import display, Math
init_printing()
x, y, z = symbols("x y z")
x=y+z
display(Math('x = '+latex(x)))
I think that this is a more general solution to the problem.
Although you first declare x as a sympy.Symbol, once you perform the assignment x=y+z, x becomes an alias for y+z. Whenever you use x from that point after, x will be automatically translated by python as y+z.
If you insist on this workflow, you could use Eq(S('x'),y+z) to display the equation.
I know this isn't exactly the answer, but for those just looking for a neat print of the right-hand-side of a function f(x,y,z,...), you can just do f.subs(x,x) like so:
import sympy as sp
x,y,z=sp.symbols('x,y,z')
f=x+2*y+3*sp.exp(z)
f.subs(x,x)

Can you translate this debugging macro from C++ to python?

I use this very helpful macro when developing in C++:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
Could you help me implement the same idea in python? I don't know how the #a could be implemented with a python function...
As #Andrea Spadaccini and #adirau point out, it is not possible to reliably map values back to Python variable names. You could trawl through all namespaces looking for some variable name that references the given value, but that would be fighting the system and liable to return the wrong variable name.
Much easier it is to just pass the variable name:
import inspect
def pv(name):
frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
inspect.currentframe())[1]
# print(frame,filename,line_number,function_name,lines,index)
val=eval(name,frame.f_globals,frame.f_locals)
print('{0}: {1}'.format(name, val))
a=5
pv('a')
yields:
a: 5
You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable.
import inspect
import re
def dd(value):
calling_frame_record = inspect.stack()[1]
frame = inspect.getframeinfo(calling_frame_record[0])
m = re.search( "dd\((.+)\)", frame.code_context[0])
if m:
print "{0} = {1}".format(m.group(1), value)
def test():
a = 4
dd(a)
test()
Output
a = 4
I think that this cannot be done.
The debugging macro that you posted works because it is expanded before compilation, during pre-processing, when you know the variable name. It is like you write all those couts by yourself.
Python does not have a pre-processor (AFAIK), there are external tools that do a similar thing (pyp and others), but you can not define a macro with the standard language.
So you should do your trick at run-time. Well, at run-time you don't know the "name" of the variable because the variable is just a reference to an object, when you call a method you call it on the object, not on the "variable". There can be many variables that point to that object, how does the object know which variable was used to call the method?
You can't get a variable (well, object)'s name in python. But you can pass the object's name to get its value (kinda the opposite of what you do with that macro)
>>> a=4
>>> locals()['a']
4
EDIT: a detailed explanation may be found here
import sys
def DD(expr):
frame = sys._getframe(1)
print '%s = %s' % (expr, repr(eval(expr, frame.f_globals, frame.f_locals)))
GLOBAL_VAR = 10
def test():
local_var = 20
DD('GLOBAL_VAR + local_var')
>>> test()
GLOBAL_VAR + local_var = 30
The Rod solution is perfectly usable.
It could be even extended to handle many vars.
But you can get close to that with much less magic:
def dd(**kwargs):
print ", ".join(str(k) + "=" + str(v) for k, v in kwargs.iteritems())
a = 1
dd(a=a,b=3)
output:
a=1, b=3