Skip to content

Commit 39fcd53

Browse files
authored
Merge pull request #384 from JuliaSymbolics/s/as_polynomial
as_polynomial
2 parents 62b949a + 741d72e commit 39fcd53

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/polyform.jl

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export PolyForm, simplify_fractions, quick_cancel, flatten_fractions
1+
export PolyForm, simplify_fractions, quick_cancel, flatten_fractions, as_polynomial
22
using Bijections
33
using DynamicPolynomials: PolyVar
44

@@ -43,6 +43,34 @@ end
4343
Base.hash(p::PolyForm, u::UInt64) = xor(hash(p.p, u), trunc(UInt, 0xbabacacababacaca))
4444
Base.isequal(x::PolyForm, y::PolyForm) = isequal(x.p, y.p)
4545

46+
47+
function as_polynomial(f, exprs...; polyform=false, T=Real)
48+
@assert length(exprs) >= 1 "At least one expression must be passed to `multivariatepolynomial`."
49+
50+
pvar2sym, sym2term = get_pvar2sym(), get_sym2term()
51+
ps = map(exprs) do x
52+
if istree(x) && operation(x) == (/)
53+
num, den = arguments(x)
54+
PolyForm(num, pvar2sym, sym2term).p /
55+
PolyForm(den, pvar2sym, sym2term).p
56+
else
57+
PolyForm(x, pvar2sym, sym2term).p
58+
end
59+
end
60+
61+
convert_back_f = function (x)
62+
if x isa MultivariatePolynomials.RationalPoly
63+
PolyForm{T}(numerator(x), pvar2sym, sym2term) /
64+
PolyForm{T}(denominator(x), pvar2sym, sym2term)
65+
else
66+
PolyForm{T}(x, pvar2sym, sym2term)
67+
end
68+
end
69+
70+
convert_back = polyform ? convert_back_f : unpolyize convert_back_f
71+
res = f(convert_back, ps...)
72+
end
73+
4674
# We use the same PVAR2SYM bijection to maintain the PolyVar <-> Sym mapping,
4775
# When all PolyForms go out of scope in a session, we allow it to free up memory and
4876
# start over if necessary

test/polyform.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,17 @@ end
7676
@test !SymbolicUtils.fraction_isone(x)
7777
@test SymbolicUtils.fraction_isone(o)
7878
end
79+
80+
81+
@testset "as_polynomial" begin
82+
83+
@syms x y z
84+
@eqtest as_polynomial((f, x, y) -> f(gcd(x, y)), 10x+10y, 5*(x^2-y^2)) == 5x + 5y
85+
@test as_polynomial((f, x, y) -> f(gcd(x, y)), 10x+10y, 5*(x^2-y^2), polyform=true) isa PolyForm
86+
@test repr(as_polynomial((f, x, y) -> f(gcd(x, y)), 10x+10y, 5*(x^2-y^2), polyform=true)) == repr(5x + 5y)
87+
88+
89+
@test as_polynomial(x, y/z) do g, x, y
90+
g(x+y)
91+
end |> repr == "(y + x*z) / z"
92+
end

0 commit comments

Comments
 (0)