In SymPy, how might I build a function that alters an input expression? - expression

I'm brand new to sympy and to computer algebra systems. I'd like to create a function that can take in an expanded expression and return an expression in which powers are replaced by 1. For example, if the function is named unpower:
>>> unpower(x*y**3 + x**2)
x*y + x
Is it possible to do this? If so, where might I start in the documentation in order to learn how to do it? Tips/advice welcome!

This is a more advanced replacement exercise since you want to match exponents of any power. All SymPy objects have properties; the most basic property is args which tells you what the arguments of the object are.
>>> (x**y).args
(x, y)
Sometimes different args have names like base and exp for the args of Pow and you can query an object to find out what it is:
>>> (x**y).exp
y
>>> (1/x).is_Pow
True
The replace method -- see help(Basic.replace) -- is good for your needs because it can target only powers
>>> (x*y**3 + x**2).replace(lambda _: _.is_Pow, lambda _: _.base)
x*y + x
But you might want to keep the sign of the exponent, else
>>> (x/y).replace(lambda _: _.is_Pow, lambda _: _.base)
x*y
So maybe
>>> from sympy import sign
>>> unpow = lambda e: e.replace(lambda _: _.is_Pow, lambda _: _.base**sign(_.exp))
>>> unpow(x**3/y**2)
x/y

Related

Retrieve method content as an `Expr`ession

I have a function f defined as follows.
f(x, y) = 3x^2 + x*y - 2y + 1
How can I retrieve the following quote block for this method, which includes the function contents?
quote # REPL[0], line 2:
((3 * x ^ 2 + x * y) - 2y) + 1
end
As folks have mentioned in the comments, digging through the fields of the methods like this isn't a stable or officially supported API. Further, your simple example is deceiving. This isn't, in general, representative of the original code you wrote for the method. It's a simplified intermediate AST representation with single-assignment variables and drastically simplified control flow. In general, the AST it returns isn't valid top-level Julia code. It just so happens that for your simple example, it is.
That said, there is a documented way to do this. You can use code_lowered() to get access to this intermediate representation without digging through undocumented fields. This will work across Julia versions, but I don't think there are official guarantees on the stability of the intermediate representation yet. Here's a slightly more complicated example:
julia> f(X) = for elt in X; println(elt); end
f (generic function with 1 method)
julia> code_lowered(f)[1]
LambdaInfo template for f(X) at REPL[17]:1
:(begin
nothing
SSAValue(0) = X
#temp# = (Base.start)(SSAValue(0))
4:
unless !((Base.done)(SSAValue(0),#temp#)) goto 13
SSAValue(1) = (Base.next)(SSAValue(0),#temp#)
elt = (Core.getfield)(SSAValue(1),1)
#temp# = (Core.getfield)(SSAValue(1),2) # line 1:
(Main.println)(elt)
11:
goto 4
13:
return
end)
julia> code_lowered(f)[1] == methods(f).ms[1].lambda_template
true
If you really want to see the code exactly as it was written, the best way is to use the embedded file and line information and refer to the original source. Note that this is precisely the manner in which Gallium.jl (Julia's debugger) finds the source to display as it steps through functions. It's undocumented, but you can even access the REPL history for functions defined interactively. See how Gallium does it through here.
First, retrieve the method using methods(f).
julia> methods(f)
# 1 method for generic function "f":
f(x, y) at REPL[1]:1
julia> methods(f).ms
1-element Array{Method,1}:
f(x, y) at REPL[1]:1
julia> method = methods(f).ms[1]
f(x, y) at REPL[1]:1
From here, retrieving the Expression is straightforward; simply use the lambda_template attribute of the method.
julia> method.lambda_template
LambdaInfo template for f(x, y) at REPL[1]:1
:(begin
nothing
return ((3 * x ^ 2 + x * y) - 2 * y) + 1
end)
Edit: This does not work in Julia v0.6+!

Differentiate an infix formal language functions

I have a source file like (without loss of generality (only to image a possible syntax)):
function a()
return g // global variable without any internal structure exactly
end
function b(x, y)
local z = x * y
return z + 1
end
function c(z, t)
return b(z * z, a())
end
// ...etc
I want to defferentiate any function WRT to some variable.
All the formal parametres we can treat as a functions with unknown at derive time internal structure.
If I stand correct further, then the following is truth (for depending symbols ' is part of symbol, for global variables is operator during substitute time stage (def: g{g} is one, but g{y} is zero)):
function a'()
return g';
end
function b'(x, y, x', y')
local z' = x' * y + x * y'
return z' + 0
end
But what to do with last function? Namely, with actual parameters in substitution of function b?
Is there any ready to use implementations of general algorithm to work with the above? What to do with higher order derivatives (especially interesting, how to handle the formal parameters)? Are there any other possible unclear cases?
I would suggest having your parameters be symbolic expressions that know how to respond to derivatives, and having all operations take functions and return functions. Then you will get a final expression that knows how to be represented as a derivative. Furthermore you can do things like partial derivatives at a later point because you have the symbolic expression.
For a real example of what I mean, see http://www.elem.com/~btilly/kelly-criterion/js/advanced-math.js for a library that I wrote to solve a calculus problem in JavaScript, and search for "Optimize if requested" in the source for http://www.elem.com/~btilly/kelly-criterion/betting-returns2.html to see how I used it. See http://www.elem.com/~btilly/kelly-criterion/ for an explanation of why I was writing that code.
In that example I, of course, was not working from infix notation. But that is a standard parsing problem that I think you know how to solve.

Julia: Passing Multiple Arguments to Anonymous Functions

In the Julia Manual under the Anonymous Functions section one of the examples that is offered is (x,y,z)->2x+y-z.
Could someone please show me how one would pass a set of arguments to this function?
Say x=(1,2,3); y=(2,3,4); z=(1,3,5).
If you define x,y and z to be arrays then you can just call the function and pass them in:
fun = (x,y,z)->2x+y-z
x=[1,2,3]
y=[2,3,4]
z=[1,3,5]
fun(x, y, z)
giving the result:
3-element Array{Int64,1}:
3
4
5
But if you want to do this with tuples, as per your example, you will need to use map:
x=(1,2,3)
y=(2,3,4)
z=(1,3,5)
map(fun, x, y, z)
this gives the same result, but this time as a tuple:
(3, 4, 5)
This is because the *, + and - operators are not defined for tuples so the formula 2x+y-z can't work. Using map gets around this by calling the function multiple times passing in scalars.
You have to assign the anonymous function to a variable, in order to call it.
julia> fun = (x,y,z)->2x+y-z
(anonymous function)
julia> fun((1,2,3),(2,3,4),(1,3,5))
ERROR: no method *(Int64, (Int64,Int64,Int64))
in anonymous at none:1
It does not work, because the tuples you set for x, does not implement the * function.

Higher order function to apply many functions to one argument

I want the common name of a higher order function that applies a list of functions onto a single argument.
In this sense it is a converse of map. map takes a function and a list of arguments and applies that function to the entire list. In Python it might look like this
map = lambda fn, args: [fn(arg) for arg in args]
I'm thinking of the function that does the same but has the alternate argument as a list type
??? = lambda fns, arg: [fn(arg) for fn in fns]
I suspect that this function exists and has a common name. What is it?
Actually, what you describe is not the converse of map, but just map applied in another way. Consider, e.g.,
map(lambda f: f(2), [lambda x: x + 1, lambda x: x, lambda x: x * x])
which in effect applies three functions (plus 1, identity, and squaring) to the argument 2. So what you wanted is just
alt_map = lambda x, fns: map(lambda f: f(x), fns)
which is still an ordinary map.

symbolic mathematics in algorithms

I am going throgh algorithms. It is mentioned that one of the application of algorithms is symbolic mathematics. And I found following defintion from dictionary as below.
The use of computers to manipulate mathematical equations and
expressions in symbolic form, as opposed to manipulating the numerical
quantities represented by those symbols. Such a system might be used
for symbolic integration or differentiation, substitution of one
expression into another, simplification of an expression, change of
subject etc. One of the best known symbolic mathematics software
packages is Mathematica.
My question what does statement "equations and expressions in symbolic form, as opposed to manipulating the numerical quantities represented by those symbols." mean?
Thanks!
My question what does statement "equations and expressions in symbolic
form, as opposed to manipulating the numerical quantities represented
by those symbols." mean?
By the second, something like this is meant:
>>> x = 2.3
>>> y = 9.8
>>> z = x+2*y
>>> z
21.900000000000002
>>> type(z)
<type 'float'>
where you're treating x, y, and z as names for numbers. You're using the computer as an old-fashioned calculator, where it only does arithmetic. z = x+2*y performs the arithmetic operations described on the right and associates the resulting number to z.
By the "symbolic form", something more like this is meant:
sage: x, y, z = var("x y z")
sage: z == x+2*y
z == x + 2*y
sage: eq = z == x+2*y
sage: eq
z == x + 2*y
sage: type(z)
<type 'sage.symbolic.expression.Expression'>
sage: parent(eq)
Symbolic Ring
sage: eq.solve(y)
[y == -1/2*x + 1/2*z]
where x,y, and z can be expressions, or variables in some structure, rather than merely names for specific numbers, and higher-level operations can be performed.

Resources