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

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

* empty log message *

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