Skip to content

added complex sum to the function _linear_expansion #1492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/linear_algebra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,13 @@ function _linear_expansion(t::Equation, x)
# t.rhs - t.lhs = 0
return (a₂ - a₁, b₂ - b₁, islinear)
end

"""
works with t of two types:
x (variable, type Num)
or
b (constant)
"""
trivial_linear_expansion(t, x) = isequal(t, x) ? (1, 0, true) : (0, t, true)

is_expansion_leaf(t) = !iscall(t) || (operation(t) isa Operator)
Expand Down Expand Up @@ -294,6 +301,12 @@ function _linear_expansion(t, x)
b₁ += b₂
end
return (a₁, b₁, true)
elseif op === Complex{Real}
# x+2im is interpreted as Complex{Real}(x, 2)
real_part, im_part = arguments(t)
a_real, b_real, islinear_real = linear_expansion(real_part, x)
a_im, b_im, islinear_im = linear_expansion(im_part, x)
return (a_real + a_im * im, b_real + b_im * im, islinear_real && islinear_im)
elseif op === (-)
@assert length(args) == 1
a, b, islinear = linear_expansion(args[1], x)
Expand Down
19 changes: 19 additions & 0 deletions test/linear_solver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,22 @@ a, b, islinear = Symbolics.linear_expansion(D(x) - x, x)
@variables x y
@test !Symbolics.linear_expansion(x + z([x, y]), y)[3]
end

@testset "linear_expansion with imaginary numbers" begin
@variables x y

a, b, islin = Symbolics.linear_expansion(1im*x^2 + 1im*x, x)
@test !islin
a, b, islin = Symbolics.linear_expansion(2im*x + 1im, x)
@test islin && isequal(a, 2im) && isequal(b, 1im)
a, b, islin = Symbolics.linear_expansion(1im*x + 1im*y, x)
@test islin && isequal(a, 1im) #&& isequal(b, 1im*y)
a, b, islin = Symbolics.linear_expansion(1im*x - y,x)
@test islin && isequal(a, 1im) && isequal(b, -y)

@variables xx[1:2] yy[1:2] zz(..)
a, b, islin = Symbolics.linear_expansion(zz(1im * xx[2]) + 1im*xx[1], xx[1])
@test islin && isequal(a, im) && isequal(b, zz(1im * xx[2]))
a, b, islin = Symbolics.linear_expansion(1im * yy[1], xx[1])
@test islin && isequal(a, 0) # && isequal(b, yy[1])
end
Loading