Skip to content

Commit 278bd5d

Browse files
Copilotoameye
andcommitted
Add BasicSymbolic support for drop_powers and max_power
Co-authored-by: oameye <57623933+oameye@users.noreply.github.com>
1 parent 0aad2dc commit 278bd5d

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

src/Symbolics/drop_powers.jl

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ julia>drop_powers((x+y)^2 + (x+y)^3, [x,y], 3)
1313
x^2 + y^2 + 2*x*y
1414
```
1515
"""
16+
function drop_powers(expr::BasicSymbolic, vars::Vector{<:BasicSymbolic}, deg::Int)
17+
return unwrap(drop_powers(Num(expr), Num.(vars), deg))
18+
end
19+
20+
# Num fallback: the actual implementation
1621
function drop_powers(expr::Num, vars::Vector{Num}, deg::Int)
1722
Symbolics.@variables ϵ
1823
subs_expr = deepcopy(expr)
@@ -43,17 +48,19 @@ function drop_powers(eqs::Vector{Equation}, var::Vector{Num}, deg::Int)
4348
Equation(drop_powers(eq.lhs, var, deg), drop_powers(eq.rhs, var, deg)) for eq in eqs
4449
]
4550
end
51+
drop_powers(expr::BasicSymbolic, var::BasicSymbolic, deg::Int) = drop_powers(expr, [var], deg)
4652
drop_powers(expr, var::Num, deg::Int) = drop_powers(expr, [var], deg)
47-
drop_powers(x, vars, deg::Int) = drop_powers(wrap(x), vars, deg)
48-
# ^ TODO: in principle `drop_powers` should get in BasicSymbolic and have a fallback for Num
53+
drop_powers(x, vars, deg::Int) = drop_powers(Num(x), Num.(vars), deg)
4954

5055
"Return the highest power of `y` occurring in the term `x`."
51-
function max_power(x::Num, y::Num)
56+
function max_power(x::BasicSymbolic, y::BasicSymbolic)
5257
terms = get_all_terms(x)
5358
powers = power_of.(terms, y)
5459
return maximum(powers)
5560
end
5661

62+
# Num fallback: unwrap to BasicSymbolic
63+
max_power(x::Num, y::Num) = max_power(unwrap(x), unwrap(y))
5764
max_power(x::Vector{Num}, y::Num) = maximum(max_power.(x, y))
5865
max_power(x::Complex, y::Num) = maximum(max_power.([x.re, x.im], y))
5966
max_power(x, t) = max_power(wrap(x), wrap(t))

test/symbolics.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ end
5959

6060
@eqtest drop_powers([a^2 + a + b, b], a, 2) == [a + b, b]
6161
@eqtest drop_powers([a^2 + a + b, b], [a, b], 2) == [a + b, b]
62+
63+
@testset "BasicSymbolic" begin
64+
using SymbolicUtils: @syms
65+
66+
@syms a_bs b_bs
67+
68+
@test max_power(a_bs^2 + b_bs, a_bs) == 2
69+
@test max_power(a_bs * ((a_bs + b_bs)^4)^2 + a_bs, a_bs) == 9
70+
71+
@test isequal(drop_powers(a_bs^2 + b_bs, a_bs, 2), b_bs)
72+
@test isequal(drop_powers((a_bs + b_bs)^2, a_bs, 1), b_bs^2)
73+
@test isequal(drop_powers((a_bs + b_bs)^2, [a_bs, b_bs], 2), unwrap(Num(0)))
74+
@test drop_powers(a_bs^2 + b_bs, a_bs, 2) isa BasicSymbolic
75+
end
6276
end
6377

6478
@testset "trig_to_exp and exp_to_trig" begin

0 commit comments

Comments
 (0)