Skip to content

Commit

Permalink
lambdify adjustment, close JuliaPy#295
Browse files Browse the repository at this point in the history
  • Loading branch information
jverzani committed Jun 5, 2021
1 parent 7a2f451 commit 463628a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
16 changes: 12 additions & 4 deletions src/lambdify.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ end
__prod__(args...) = prod(args)
export __prod__

## Hide these away. Anonymous function definition is problematic
__SYMPY__ANY__(xs...) = any(xs)
__SYMPY__ALL__(xs...) = all(xs)
__SYMPY__ZERO__(xs...) = 0
__SYMPY__HEAVISIDE__ = (a...) -> (a[1] < 0 ? 0 : (a[1] > 0 ? 1 : (length(a) > 1 ? a[2] : NaN)))
export __SYMPY__ANY__, __SYMPY__ALL__, __SYMPY__ZERO__, __SYMPY__HEAVISIDE__

fn_map = Dict(
"Add" => :+,
"Sub" => :-,
Expand All @@ -50,9 +57,9 @@ fn_map = Dict(
"Max" => :max,
"Poly" => :identity,
"Piecewise" => :(_piecewise),
"Order" => :((xs...)->0),
"And" => :(&),
"Or" => :(|),
"Order" => :__SYMPY__ZERO__, # :(as...) -> 0,
"And" => :__SYMPY__ALL__, #:((as...) -> all(as)), #:(&),
"Or" => :__SYMPY__ANY__, #:((as...) -> any(as)), #:(|),
"Less" => :(<),
"LessThan" => :(<=),
"StrictLessThan" => :(<),
Expand All @@ -65,7 +72,7 @@ fn_map = Dict(
"conjugate" => :conj,
"atan2" => :atan,
# not quite a match; NaN not θ(0) when evaluated at 0 w/o second argument
"Heaviside" => :((a...) -> (a[1] < 0 ? 0.0 : (a[1] > 0 ? 1.0 : (length(a) > 1 ? a[2] : NaN))))
"Heaviside" => :__SYMPY__HEAVISIDE__
)

map_fn(key, fn_map) = haskey(fn_map, key) ? fn_map[key] : Symbol(key)
Expand Down Expand Up @@ -208,6 +215,7 @@ function lambdify(ex::Sym, vars=free_symbols(ex);
invoke_latest=true)

body = convert_expr(ex, fns=fns, values=values, use_julia_code=use_julia_code)
body = Meta.parse(string(body)) ## this seems stupid!
ex = expr_to_function(body, vars)
if invoke_latest
fn = eval(ex)
Expand Down
25 changes: 17 additions & 8 deletions test/tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,23 @@ end
@vars x
t = series(exp(x), x, 0, 2)
@test lambdify(t)(1/2) == 1 + 1/2

## issue #411 with Heaviside
@vars t
u = Heaviside(t)
λ = lambdify(u)
@test all((iszero(λ(-1)), isnan(λ(0)), isone(λ(1))))
u = Heaviside(t, 1)
λ = lambdify(u)
@test all((iszero(λ(-1)), isone(λ(0)), isone(λ(1))))

## issue #295 with piecewise function
@syms x
p = sympy.Piecewise((x,Gt(x,0)), (x^2, Le(x,0)))
@test lambdify(p)(2) == 2
@test lambdify(p)(-2) == (-2)^2


end

@testset "generic programming, issue 223" begin
Expand Down Expand Up @@ -784,13 +801,5 @@ end
A = sympy.MatrixSymbol("A", n, n)
@test inv(A) == A.I

## issue #411 with Heaviside
@vars t
u = Heaviside(t)
λ = lambdify(u)
@test all((iszero(λ(-1)), isnan(λ(0)), isone(λ(1))))
u = Heaviside(t, 1)
λ = lambdify(u)
@test all((iszero(λ(-1)), isone(λ(0)), isone(λ(1))))

end

0 comments on commit 463628a

Please sign in to comment.