@@ -92,6 +92,74 @@ function MA.operate_to!(
92
92
return output
93
93
end
94
94
95
+ """
96
+ _lowest_term_idx(p::Polynomial)
97
+
98
+ Return the index of the lowest term in `p` according to its monomial ordering.
99
+ """
100
+ _lowest_term_idx (p:: Polynomial{V, M, T} ) where {V, M <: Reverse , T} = lastindex (p. x)
101
+ _lowest_term_idx (p:: Polynomial ) = firstindex (p. x)
102
+
103
+ """
104
+ _insert_constant_term!(p::Polynomial)
105
+
106
+ Insert a constant (degree 0) term into polynomial `p` at the appropriate position for the
107
+ monomial ordering of `p`. Assume that a constant term does not already exists.
108
+ """
109
+ function _insert_constant_term! (p:: Polynomial{V, M, T} ) where {V, M <: Reverse , T}
110
+ push! (MP. coefficients (p), zero (T))
111
+ push! (MP. monomials (p). Z, zeros (Int, length (MP. variables (p))))
112
+ return p
113
+ end
114
+
115
+ function _insert_constant_term! (p:: Polynomial{V, M, T} ) where {V, M, T}
116
+ insert! (MP. coefficients (p), 1 , zero (T))
117
+ insert! (MP. monomials (p). Z, 1 , zeros (Int, length (MP. variables (p))))
118
+ return p
119
+ end
120
+
121
+ function MA. operate! (op:: Union{typeof(+), typeof(-)} , p:: Polynomial{V, M, T} , x:: T ) where {V, M, T}
122
+ c_idx = _lowest_term_idx (p)
123
+ if MP. nterms (p) == 0 || ! MP. isconstant (MP. terms (p)[c_idx])
124
+ _insert_constant_term! (p)
125
+ c_idx = _lowest_term_idx (p)
126
+ end
127
+ coeffs = MP. coefficients (p)
128
+ coeffs[c_idx] = op (coeffs[c_idx], x)
129
+ if iszero (coeffs[c_idx])
130
+ deleteat! (coeffs, c_idx)
131
+ deleteat! (MP. monomials (p), c_idx)
132
+ end
133
+ return p
134
+ end
135
+
136
+ function MA. operate! (op:: Union{typeof(+), typeof(-)} , p:: Polynomial{V, M, T} , x:: Variable{V, M} ) where {V, M, T}
137
+ vars = MP. variables (p)
138
+ idx = searchsortedfirst (vars, x; rev = true )
139
+ monos = MP. monomials (p)
140
+ if idx > length (vars) || ! isequal (vars[idx], x)
141
+ for mono in monos
142
+ insert! (MP. exponents (mono), idx, 0 )
143
+ end
144
+ insert! (vars, idx, x)
145
+ end
146
+ mono = Monomial {V, M} (vars, zeros (Int, length (vars)))
147
+ mono. z[idx] = 1
148
+ idx = searchsortedfirst (monos, mono)
149
+ coeffs = MP. coefficients (p)
150
+ N = MP. nterms (p)
151
+ if idx > N || ! isequal (monos[idx], mono)
152
+ insert! (monos. Z, idx, MP. exponents (mono))
153
+ insert! (coeffs, idx, zero (T))
154
+ end
155
+ coeffs[idx] = op (coeffs[idx], one (T))
156
+ if iszero (coeffs[idx])
157
+ deleteat! (coeffs, idx)
158
+ deleteat! (monos, idx)
159
+ end
160
+ return p
161
+ end
162
+
95
163
function MA. operate! (
96
164
op:: Union{typeof(+),typeof(-)} ,
97
165
p:: Polynomial ,
0 commit comments