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@ 3816

Last change on this file since 3816 was 3816, checked in by Marek Rychlik, 8 years ago

* empty log message *

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