close Warning: Can't synchronize with repository "(default)" (The repository directory has changed, you should resynchronize the repository with: trac-admin $ENV repository resync '(default)'). Look in the Trac log for more information.

source: branches/f4grobner/polynomial.lisp@ 3743

Last change on this file since 3743 was 3741, checked in by Marek Rychlik, 9 years ago

* empty log message *

File size: 18.5 KB
Line 
1;;----------------------------------------------------------------
2;;; -*- Mode: Lisp -*-
3;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4;;;
5;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik <rychlik@u.arizona.edu>
6;;;
7;;; This program is free software; you can redistribute it and/or modify
8;;; it under the terms of the GNU General Public License as published by
9;;; the Free Software Foundation; either version 2 of the License, or
10;;; (at your option) any later version.
11;;;
12;;; This program is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with this program; if not, write to the Free Software
19;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20;;;
21;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22
23(defpackage "POLYNOMIAL"
24 (:use :cl :utils :monom :copy)
25 (:export "POLY"
26 "POLY-DIMENSION"
27 "POLY-TERMLIST"
28 "POLY-TERM-ORDER"
29 "POLY-INSERT-TERM"
30 "SCALAR-MULTIPLY-BY"
31 "SCALAR-DIVIDE-BY"
32 "LEADING-TERM"
33 "LEADING-MONOMIAL"
34 "LEADING-COEFFICIENT"
35 "SECOND-LEADING-TERM"
36 "SECOND-LEADING-MONOMIAL"
37 "SECOND-LEADING-COEFFICIENT"
38 "ADD-TO"
39 "ADD"
40 "SUBTRACT-FROM"
41 "SUBTRACT"
42 "CHANGE-TERM-ORDER"
43 "STANDARD-EXTENSION"
44 "STANDARD-EXTENSION-1"
45 "STANDARD-SUM"
46 "SATURATION-EXTENSION"
47 "ALIST->POLY"
48 "UNIVERSAL-EZGCD"
49 "S-POLYNOMIAL"
50 "POLY-CONTENT"
51 "POLY-PRIMITIVE-PART"
52 "SATURATION-EXTENSION-1"
53 "MAKE-POLY-VARIABLE"
54 "UNIVERSAL-EXPT")
55 (:documentation "Implements polynomials. A polynomial is essentially
56a mapping of monomials of the same degree to coefficients. The
57momomials are ordered according to a monomial order."))
58
59(in-package :polynomial)
60
61(proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0)))
62
63(defclass poly ()
64 ((dimension :initform nil
65 :initarg :dimension
66 :accessor poly-dimension
67 :documentation "Shared dimension of all terms, the number of variables")
68 (termlist :initform nil :initarg :termlist :accessor poly-termlist
69 :documentation "List of terms.")
70 (order :initform #'lex> :initarg :order :accessor poly-term-order
71 :documentation "Monomial/term order."))
72 (:default-initargs :dimension nil :termlist nil :order #'lex>)
73 (:documentation "A polynomial with a list of terms TERMLIST, ordered
74according to term order ORDER, which defaults to LEX>."))
75
76(defmethod print-object ((self poly) stream)
77 (print-unreadable-object (self stream :type t :identity t)
78 (with-accessors ((dimension poly-dimension)
79 (termlist poly-termlist)
80 (order poly-term-order))
81 self
82 (format stream "DIMENSION=~A TERMLIST=~A ORDER=~A"
83 dimension termlist order))))
84
85(defgeneric change-term-order (self other)
86 (:documentation "Change term order of SELF to the term order of OTHER.")
87 (:method ((self poly) (other poly))
88 (unless (eq (poly-term-order self) (poly-term-order other))
89 (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other))
90 (poly-term-order self) (poly-term-order other)))
91 self))
92
93(defgeneric poly-insert-term (self term)
94 (:documentation "Insert a term TERM into SELF before all other
95 terms. Order is not enforced.")
96 (:method ((self poly) (term term))
97 (cond ((null (poly-dimension self))
98 (setf (poly-dimension self) (monom-dimension term)))
99 (t (assert (= (poly-dimension self) (monom-dimension term)))))
100 (push term (poly-termlist self))
101 self))
102
103(defgeneric poly-append-term (self term)
104 (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.")
105 (:method ((self poly) (term term))
106 (cond ((null (poly-dimension self))
107 (setf (poly-dimension self) (monom-dimension term)))
108 (t (assert (= (poly-dimension self) (monom-dimension term)))))
109 (setf (cdr (last (poly-termlist self))) (list term))
110 self))
111
112(defun alist->poly (alist &aux (poly (make-instance 'poly)))
113 "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...).
114It can be used to enter simple polynomials by hand, e.g the polynomial
115in two variables, X and Y, given in standard notation as:
116
117 3*X^2*Y^3+2*Y+7
118
119can be entered as
120(ALIST->POLY '(((2 3) . 3) ((0 1) . 2) ((0 0) . 7))).
121
122NOTE: The primary use is for low-level debugging of the package."
123 (dolist (x alist poly)
124 (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x)))))
125
126(defmethod update-instance-for-different-class :after ((old monom) (new poly) &key)
127 "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST."
128 (reinitialize-instance new
129 :dimension (monom-dimension old)
130 :termlist (list (cons old 1))))
131
132(defmethod universal-equalp ((self poly) (other poly))
133 "Implements equality of polynomials."
134 (and (eql (poly-dimension self) (poly-dimension other))
135 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
136 (eq (poly-term-order self) (poly-term-order other))))
137
138(defgeneric leading-term (object)
139 (:method ((self poly))
140 (car (poly-termlist self)))
141 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
142
143(defgeneric second-leading-term (object)
144 (:method ((self poly))
145 (cadar (poly-termlist self)))
146 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
147
148(defgeneric leading-monomial (object)
149 (:method ((self poly))
150 (change-class (copy-instance (leading-term self)) 'monom))
151 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
152
153(defgeneric second-leading-monomial (object)
154 (:method ((self poly))
155 (change-class (copy-instance (second-leading-term self)) 'monom))
156 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
157
158(defgeneric leading-coefficient (object)
159 (:method ((self poly))
160 (term-coeff (leading-term self)))
161 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
162
163(defgeneric second-leading-coefficient (object)
164 (:method ((self poly))
165 (term-coeff (second-leading-term self)))
166 (:documentation "The second leading coefficient of a polynomial. It
167 signals error for a polynomial with at most one term."))
168
169(defmethod universal-zerop ((self poly))
170 "Return T iff SELF is a zero polynomial."
171 (null (poly-termlist self)))
172
173(defgeneric poly-length (self)
174 (:documentation "Return the number of terms.")
175 (:method ((self poly))
176 (length (poly-termlist self))))
177
178(defgeneric scalar-multiply-by (self other)
179 (:documentation "Multiply vector SELF by a scalar OTHER.")
180 (:method ((self poly) other)
181 (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other)))
182 (poly-termlist self))
183 self))
184
185(defgeneric scalar-divide-by (self other)
186 (:documentation "Divide vector SELF by a scalar OTHER.")
187 (:method ((self poly) other)
188 (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other)))
189 (poly-termlist self))
190 self))
191
192(defmethod multiply-by ((self poly) (other monom))
193 "Multiply a polynomial SELF by OTHER."
194 (mapc #'(lambda (term) (multiply-by term other))
195 (poly-termlist self))
196 self)
197
198(defmethod multiply-by ((self poly) (other term))
199 "Multiply a polynomial SELF by OTHER."
200 (mapc #'(lambda (term) (multiply-by term other))
201 (poly-termlist self))
202 self)
203
204(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
205 "Return an expression which will efficiently adds/subtracts two
206polynomials, P and Q. The addition/subtraction of coefficients is
207performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME
208is supplied, it is used to negate the coefficients of Q which do not
209have a corresponding coefficient in P. The code implements an
210efficient algorithm to add two polynomials represented as sorted lists
211of terms. The code destroys both arguments, reusing the terms to build
212the result."
213 `(macrolet ((lc (x) `(term-coeff (car ,x))))
214 (do ((p ,p)
215 (q ,q)
216 r)
217 ((or (endp p) (endp q))
218 ;; NOTE: R contains the result in reverse order. Can it
219 ;; be more efficient to produce the terms in correct order?
220 (unless (endp q)
221 ;; Upon subtraction, we must change the sign of
222 ;; all coefficients in q
223 ,@(when uminus-fn
224 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
225 (setf r (nreconc r q)))
226 r)
227 (multiple-value-bind
228 (greater-p equal-p)
229 (funcall ,order-fn (car p) (car q))
230 (cond
231 (greater-p
232 (rotatef (cdr p) r p)
233 )
234 (equal-p
235 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
236 (cond
237 ((universal-zerop s)
238 (setf p (cdr p))
239 )
240 (t
241 (setf (lc p) s)
242 (rotatef (cdr p) r p))))
243 (setf q (cdr q))
244 )
245 (t
246 ;;Negate the term of Q if UMINUS provided, signallig
247 ;;that we are doing subtraction
248 ,(when uminus-fn
249 `(setf (lc q) (funcall ,uminus-fn (lc q))))
250 (rotatef (cdr q) r q)))))))
251
252
253(defgeneric add-to (self other)
254 (:documentation "Add OTHER to SELF.")
255 (:method ((self number) (other number))
256 (+ self other)))
257
258(defgeneric subtract-from (self other)
259 (:documentation "Subtract OTHER from SELF.")
260 (:method ((self number) (other number))
261 (- self other)))
262
263(defmacro def-add/subtract-method (add/subtract-method-name
264 uminus-method-name
265 &optional
266 (doc-string nil doc-string-supplied-p))
267 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
268 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
269 ,@(when doc-string-supplied-p `(,doc-string))
270 ;; Ensure orders are compatible
271 (change-term-order other self)
272 (setf (poly-termlist self) (fast-add/subtract
273 (poly-termlist self) (poly-termlist other)
274 (poly-term-order self)
275 #',add/subtract-method-name
276 ,(when uminus-method-name `(function ,uminus-method-name))))
277 self))
278
279(eval-when (:compile-toplevel :load-toplevel :execute)
280
281 (def-add/subtract-method add-to nil
282 "Adds to polynomial SELF another polynomial OTHER.
283This operation destructively modifies both polynomials.
284The result is stored in SELF. This implementation does
285no consing, entirely reusing the sells of SELF and OTHER.")
286
287 (def-add/subtract-method subtract-from unary-minus
288 "Subtracts from polynomial SELF another polynomial OTHER.
289This operation destructively modifies both polynomials.
290The result is stored in SELF. This implementation does
291no consing, entirely reusing the sells of SELF and OTHER.")
292 )
293
294(defmethod unary-minus ((self poly))
295 "Destructively modifies the coefficients of the polynomial SELF,
296by changing their sign."
297 (mapc #'unary-minus (poly-termlist self))
298 self)
299
300(defun add-termlists (p q order-fn)
301 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
302 (fast-add/subtract p q order-fn #'add-to nil))
303
304(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
305 &optional (reverse-arg-order-P nil))
306 "Multiplies term TERM by a list of term, TERMLIST.
307Takes into accound divisors of zero in the ring, by
308deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
309is T, change the order of arguments; this may be important
310if we extend the package to non-commutative rings."
311 `(mapcan #'(lambda (other-term)
312 (let ((prod (multiply
313 ,@(cond
314 (reverse-arg-order-p
315 `(other-term ,term))
316 (t
317 `(,term other-term))))))
318 (cond
319 ((universal-zerop prod) nil)
320 (t (list prod)))))
321 ,termlist))
322
323(defun multiply-termlists (p q order-fn)
324 "A version of polynomial multiplication, operating
325directly on termlists."
326 (cond
327 ((or (endp p) (endp q))
328 ;;p or q is 0 (represented by NIL)
329 nil)
330 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
331 ((endp (cdr p))
332 (multiply-term-by-termlist-dropping-zeros (car p) q))
333 ((endp (cdr q))
334 (multiply-term-by-termlist-dropping-zeros (car q) p t))
335 (t
336 (cons (multiply (car p) (car q))
337 (add-termlists
338 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
339 (multiply-termlists (cdr p) q order-fn)
340 order-fn)))))
341
342(defmethod multiply-by ((self poly) (other poly))
343 (change-term-order other self)
344 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
345 (poly-termlist other)
346 (poly-term-order self)))
347 self)
348
349(defun add (object1 object2)
350 "Non-destructively add POLY1 by POLY2."
351 (add-to (copy-instance object1) (copy-instance object2)))
352
353(defun subtract (minuend &rest subtrahends)
354 "Non-destructively subtract MINUEND and SUBTRAHENDS."
355 (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))
356
357(defmethod left-tensor-product-by ((self poly) (other monom))
358 (setf (poly-termlist self)
359 (mapcan #'(lambda (term)
360 (let ((prod (left-tensor-product-by term other)))
361 (cond
362 ((universal-zerop prod) nil)
363 (t (list prod)))))
364 (poly-termlist self)))
365 (incf (poly-dimension self) (monom-dimension other))
366 self)
367
368(defmethod right-tensor-product-by ((self poly) (other monom))
369 (setf (poly-termlist self)
370 (mapcan #'(lambda (term)
371 (let ((prod (right-tensor-product-by term other)))
372 (cond
373 ((universal-zerop prod) nil)
374 (t (list prod)))))
375 (poly-termlist self)))
376 (incf (poly-dimension self) (monom-dimension other))
377 self)
378
379
380(defun standard-extension (plist &aux (k (length plist)) (i 0))
381 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
382is a list of polynomials. Destructively modifies PLIST elements."
383 (mapc #'(lambda (poly)
384 (left-tensor-product-by
385 poly
386 (prog1
387 (make-monom-variable k i)
388 (incf i))))
389 plist))
390
391(defun standard-extension-1 (plist
392 &aux
393 (plist (standard-extension plist))
394 (nvars (poly-dimension (car plist))))
395 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
396Firstly, new K variables U1, U2, ..., UK, are inserted into each
397polynomial. Subsequently, P1, P2, ..., PK are destructively modified
398tantamount to replacing PI with UI*PI-1. It assumes that all
399polynomials have the same dimension, and only the first polynomial
400is examined to determine this dimension."
401 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
402 ;; 1 from each polynomial; since UI*PI has no constant term,
403 ;; we just need to append the constant term at the end
404 ;; of each termlist.
405 (flet ((subtract-1 (p)
406 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
407 (setf plist (mapc #'subtract-1 plist)))
408 plist)
409
410
411(defun standard-sum (plist
412 &aux
413 (plist (standard-extension plist))
414 (nvars (poly-dimension (car plist))))
415 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
416Firstly, new K variables, U1, U2, ..., UK, are inserted into each
417polynomial. Subsequently, P1, P2, ..., PK are destructively modified
418tantamount to replacing PI with UI*PI, and the resulting polynomials
419are added. Finally, 1 is subtracted. It should be noted that the term
420order is not modified, which is equivalent to using a lexicographic
421order on the first K variables."
422 (flet ((subtract-1 (p)
423 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
424 (subtract-1
425 (make-instance
426 'poly
427 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
428
429(defgeneric universal-ezgcd (x y)
430 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
431C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
432the Euclidean algorithm.")
433 (:method ((x integer) (y integer)
434 &aux (c (gcd x y)))
435 (values c (/ x c) (/ y c)))
436 )
437
438(defgeneric s-polynomial (object1 object2)
439 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
440 (:method ((f poly) (g poly))
441 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
442 (mf (divide lcm (leading-monomial f)))
443 (mg (divide lcm (leading-monomial g))))
444 (multiple-value-bind (c cf cg)
445 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
446 (declare (ignore c))
447 (subtract
448 (multiply f (change-class mf 'term :coeff cg))
449 (multiply g (change-class mg 'term :coeff cf)))))))
450
451(defgeneric poly-content (object)
452 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
453 (:method ((self poly))
454 (reduce #'universal-gcd
455 (mapcar #'term-coeff (rest (poly-termlist self)))
456 :initial-value (leading-coefficient self))))
457
458(defun poly-primitive-part (object)
459 "Divide polynomial OBJECT by gcd of its
460coefficients. Return the resulting polynomial."
461 (scalar-divide-by object (poly-content object)))
462
463(defun poly-insert-variables (self k)
464 (left-tensor-product-by self (make-instance 'monom :dimension k)))
465
466(defun saturation-extension (f plist &aux (k (length plist)))
467 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
468PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
469as first K variables. It destructively modifies F and PLIST."
470 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
471 (standard-extension-1 plist)))
472
473(defun polysaturation-extension (f plist &aux (k (length plist)))
474 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
475and F' is F with variables U1,U2,...,UK inserted as first K
476variables. It destructively modifies F and PLIST."
477 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
478 (list (standard-sum plist))))
479
480(defun saturation-extension-1 (f p)
481 "Given family of polynomials F and a polynomial P, calculate [F',
482U*P-1], where F' is F with variable inserted as the first variable. It
483destructively modifies F and P."
484 (polysaturation-extension f (list p)))
485
486(defmethod multiply-by ((object1 number) (object2 poly))
487 (scalar-multiply-by (copy-instance object2) object1))
488
489(defun make-poly-variable (nvars pos)
490 (change-class (make-monom-variable nvars pos) 'poly))
491
492
493(defgeneric universal-expt (x y)
494 (:documentation "Raises X to power Y.")
495 (:method ((x number) (y integer)) (expt x y))
496 (:method ((x t) (y integer))
497 (declare (type fixnum y))
498 (cond
499 ((minusp y) (error "universal-expt: Negative exponent."))
500 ((universal-zerop x) (if (zerop y) 1))
501 (t
502 (do ((k 1 (ash k 1))
503 (q x (multiply q q)) ;keep squaring
504 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
505 ((> k y) p)
506 (declare (fixnum k)))))))
Note: See TracBrowser for help on using the repository browser.