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

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

* empty log message *

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