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

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

* empty log message *

File size: 18.4 KB
RevLine 
[3400]1;;----------------------------------------------------------------
[1201]2;;; -*- Mode: Lisp -*-
[77]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
[431]23(defpackage "POLYNOMIAL"
[3643]24 (:use :cl :utils :monom :copy)
[2596]25 (:export "POLY"
[3270]26 "POLY-DIMENSION"
[2596]27 "POLY-TERMLIST"
[3016]28 "POLY-TERM-ORDER"
[3509]29 "POLY-INSERT-TERM"
[3690]30 "SCALAR-MULTIPLY-BY"
31 "SCALAR-DIVIDE-BY"
[3642]32 "LEADING-TERM"
[3657]33 "LEADING-MONOMIAL"
[3642]34 "LEADING-COEFFICIENT"
[3657]35 "SECOND-LEADING-TERM"
36 "SECOND-LEADING-MONOMIAL"
37 "SECOND-LEADING-COEFFICIENT"
[3642]38 "ADD-TO"
[3646]39 "ADD"
[3642]40 "SUBTRACT-FROM"
[3646]41 "SUBTRACT"
[3071]42 "CHANGE-TERM-ORDER"
[3099]43 "STANDARD-EXTENSION"
[3101]44 "STANDARD-EXTENSION-1"
[3109]45 "STANDARD-SUM"
[3094]46 "SATURATION-EXTENSION"
[3655]47 "ALIST->POLY"
48 "UNIVERSAL-EZGCD"
[3678]49 "S-POLYNOMIAL"
[3686]50 "POLY-CONTENT"
[3692]51 "POLY-PRIMITIVE-PART"
[3714]52 "SATURATION-EXTENSION-1"
53 "UNIVERSAL-EXPT")
[3489]54 (:documentation "Implements polynomials. A polynomial is essentially
55a mapping of monomials of the same degree to coefficients. The
56momomials are ordered according to a monomial order."))
[143]57
[431]58(in-package :polynomial)
59
[1927]60(proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0)))
[52]61
[2442]62(defclass poly ()
[3253]63 ((dimension :initform nil
[3250]64 :initarg :dimension
65 :accessor poly-dimension
[3242]66 :documentation "Shared dimension of all terms, the number of variables")
[3250]67 (termlist :initform nil :initarg :termlist :accessor poly-termlist
[3619]68 :documentation "List of terms.")
[3250]69 (order :initform #'lex> :initarg :order :accessor poly-term-order
[2697]70 :documentation "Monomial/term order."))
[3262]71 (:default-initargs :dimension nil :termlist nil :order #'lex>)
[2695]72 (:documentation "A polynomial with a list of terms TERMLIST, ordered
[2696]73according to term order ORDER, which defaults to LEX>."))
[2442]74
[2471]75(defmethod print-object ((self poly) stream)
[3241]76 (print-unreadable-object (self stream :type t :identity t)
[3243]77 (with-accessors ((dimension poly-dimension)
78 (termlist poly-termlist)
79 (order poly-term-order))
[3237]80 self
[3244]81 (format stream "DIMENSION=~A TERMLIST=~A ORDER=~A"
82 dimension termlist order))))
[2469]83
[3015]84(defgeneric change-term-order (self other)
[3012]85 (:documentation "Change term order of SELF to the term order of OTHER.")
[3010]86 (:method ((self poly) (other poly))
87 (unless (eq (poly-term-order self) (poly-term-order other))
[3620]88 (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other))
[3010]89 (poly-term-order self) (poly-term-order other)))
[3012]90 self))
[3010]91
[3621]92(defgeneric poly-insert-term (self term)
[3622]93 (:documentation "Insert a term TERM into SELF before all other
[3621]94 terms. Order is not enforced.")
95 (:method ((self poly) (term term))
[3510]96 (cond ((null (poly-dimension self))
[3621]97 (setf (poly-dimension self) (monom-dimension term)))
98 (t (assert (= (poly-dimension self) (monom-dimension term)))))
99 (push term (poly-termlist self))
[3510]100 self))
101
[3622]102(defgeneric poly-append-term (self term)
103 (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.")
104 (:method ((self poly) (term term))
[3510]105 (cond ((null (poly-dimension self))
[3622]106 (setf (poly-dimension self) (monom-dimension term)))
107 (t (assert (= (poly-dimension self) (monom-dimension term)))))
108 (setf (cdr (last (poly-termlist self))) (list term))
[3510]109 self))
110
[3095]111(defun alist->poly (alist &aux (poly (make-instance 'poly)))
[3126]112 "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...).
113It can be used to enter simple polynomials by hand, e.g the polynomial
114in two variables, X and Y, given in standard notation as:
115
116 3*X^2*Y^3+2*Y+7
117
118can be entered as
119(ALIST->POLY '(((2 3) . 3) ((0 1) . 2) ((0 0) . 7))).
120
121NOTE: The primary use is for low-level debugging of the package."
[3099]122 (dolist (x alist poly)
[3705]123 (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x)))))
[3092]124
[3401]125(defmethod update-instance-for-different-class :after ((old monom) (new poly) &key)
126 "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST."
127 (reinitialize-instance new
128 :dimension (monom-dimension old)
[3511]129 :termlist (list (cons old 1))))
[3403]130
[3624]131(defmethod universal-equalp ((self poly) (other poly))
132 "Implements equality of polynomials."
133 (and (eql (poly-dimension self) (poly-dimension other))
134 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
135 (eq (poly-term-order self) (poly-term-order other))))
[2650]136
[3624]137(defgeneric leading-term (object)
[2442]138 (:method ((self poly))
[2525]139 (car (poly-termlist self)))
140 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
[52]141
[3625]142(defgeneric second-leading-term (object)
[2442]143 (:method ((self poly))
[2525]144 (cadar (poly-termlist self)))
145 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
[52]146
[3656]147(defgeneric leading-monomial (object)
148 (:method ((self poly))
149 (change-class (copy-instance (leading-term self)) 'monom))
150 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
151
152(defgeneric second-leading-monomial (object)
153 (:method ((self poly))
154 (change-class (copy-instance (second-leading-term self)) 'monom))
155 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
156
[3625]157(defgeneric leading-coefficient (object)
[2442]158 (:method ((self poly))
[3642]159 (term-coeff (leading-term self)))
[2545]160 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
[52]161
[2442]162(defgeneric second-leading-coefficient (object)
163 (:method ((self poly))
[3645]164 (term-coeff (second-leading-term self)))
[2906]165 (:documentation "The second leading coefficient of a polynomial. It
166 signals error for a polynomial with at most one term."))
[52]167
[3629]168(defmethod universal-zerop ((self poly))
169 "Return T iff SELF is a zero polynomial."
[3639]170 (null (poly-termlist self)))
[52]171
[3518]172(defgeneric poly-length (self)
[3630]173 (:documentation "Return the number of terms.")
[3518]174 (:method ((self poly))
175 (length (poly-termlist self))))
[52]176
[3689]177(defgeneric scalar-multiply-by (self other)
178 (:documentation "Multiply vector SELF by a scalar OTHER.")
179 (:method ((self poly) other)
180 (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other)))
181 (poly-termlist self))
182 self))
183
184(defgeneric scalar-divide-by (self other)
185 (:documentation "Divide vector SELF by a scalar OTHER.")
186 (:method ((self poly) other)
187 (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other)))
188 (poly-termlist self))
189 self))
190
[3663]191(defmethod multiply-by ((self poly) (other monom))
[3630]192 "Multiply a polynomial SELF by OTHER."
193 (mapc #'(lambda (term) (multiply-by term other))
194 (poly-termlist self))
195 self)
[2469]196
[3672]197(defmethod multiply-by ((self poly) (other term))
198 "Multiply a polynomial SELF by OTHER."
199 (mapc #'(lambda (term) (multiply-by term other))
200 (poly-termlist self))
201 self)
202
[2761]203(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
[2755]204 "Return an expression which will efficiently adds/subtracts two
205polynomials, P and Q. The addition/subtraction of coefficients is
206performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME
207is supplied, it is used to negate the coefficients of Q which do not
[2756]208have a corresponding coefficient in P. The code implements an
209efficient algorithm to add two polynomials represented as sorted lists
210of terms. The code destroys both arguments, reusing the terms to build
211the result."
[3631]212 `(macrolet ((lc (x) `(term-coeff (car ,x))))
[2742]213 (do ((p ,p)
214 (q ,q)
215 r)
216 ((or (endp p) (endp q))
217 ;; NOTE: R contains the result in reverse order. Can it
218 ;; be more efficient to produce the terms in correct order?
[2774]219 (unless (endp q)
[2776]220 ;; Upon subtraction, we must change the sign of
221 ;; all coefficients in q
[2774]222 ,@(when uminus-fn
[2775]223 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
[2774]224 (setf r (nreconc r q)))
[2742]225 r)
226 (multiple-value-bind
227 (greater-p equal-p)
[3632]228 (funcall ,order-fn (car p) (car q))
[2742]229 (cond
230 (greater-p
231 (rotatef (cdr p) r p)
232 )
233 (equal-p
[2766]234 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
[2742]235 (cond
[3640]236 ((universal-zerop s)
[2742]237 (setf p (cdr p))
238 )
239 (t
240 (setf (lc p) s)
241 (rotatef (cdr p) r p))))
242 (setf q (cdr q))
243 )
244 (t
[2743]245 ;;Negate the term of Q if UMINUS provided, signallig
246 ;;that we are doing subtraction
[2908]247 ,(when uminus-fn
248 `(setf (lc q) (funcall ,uminus-fn (lc q))))
[2743]249 (rotatef (cdr q) r q)))))))
[2585]250
[2655]251
[3647]252(defgeneric add-to (self other)
253 (:documentation "Add OTHER to SELF.")
254 (:method ((self number) (other number))
255 (+ self other)))
256
257(defgeneric subtract-from (self other)
[3648]258 (:documentation "Subtract OTHER from SELF.")
259 (:method ((self number) (other number))
260 (- self other)))
[3647]261
[2763]262(defmacro def-add/subtract-method (add/subtract-method-name
[2752]263 uminus-method-name
264 &optional
[2913]265 (doc-string nil doc-string-supplied-p))
[3647]266 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
[2749]267 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
[2615]268 ,@(when doc-string-supplied-p `(,doc-string))
[2769]269 ;; Ensure orders are compatible
[3015]270 (change-term-order other self)
[2772]271 (setf (poly-termlist self) (fast-add/subtract
272 (poly-termlist self) (poly-termlist other)
273 (poly-term-order self)
274 #',add/subtract-method-name
275 ,(when uminus-method-name `(function ,uminus-method-name))))
[2609]276 self))
[2487]277
[2916]278(eval-when (:compile-toplevel :load-toplevel :execute)
[2777]279
[3639]280 (def-add/subtract-method add-to nil
[2777]281 "Adds to polynomial SELF another polynomial OTHER.
[2610]282This operation destructively modifies both polynomials.
283The result is stored in SELF. This implementation does
[2752]284no consing, entirely reusing the sells of SELF and OTHER.")
[2609]285
[3639]286 (def-add/subtract-method subtract-from unary-minus
[2753]287 "Subtracts from polynomial SELF another polynomial OTHER.
[2610]288This operation destructively modifies both polynomials.
289The result is stored in SELF. This implementation does
[2752]290no consing, entirely reusing the sells of SELF and OTHER.")
[2916]291 )
[2777]292
[2691]293(defmethod unary-minus ((self poly))
[2694]294 "Destructively modifies the coefficients of the polynomial SELF,
295by changing their sign."
[2692]296 (mapc #'unary-minus (poly-termlist self))
[2683]297 self)
[52]298
[2795]299(defun add-termlists (p q order-fn)
[2794]300 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
[3639]301 (fast-add/subtract p q order-fn #'add-to nil))
[2794]302
[2800]303(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
[2927]304 &optional (reverse-arg-order-P nil))
[2799]305 "Multiplies term TERM by a list of term, TERMLIST.
[2792]306Takes into accound divisors of zero in the ring, by
[2927]307deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
[2928]308is T, change the order of arguments; this may be important
[2927]309if we extend the package to non-commutative rings."
[2800]310 `(mapcan #'(lambda (other-term)
[3633]311 (let ((prod (multiply
[2923]312 ,@(cond
[2930]313 (reverse-arg-order-p
[2925]314 `(other-term ,term))
315 (t
316 `(,term other-term))))))
[2800]317 (cond
[3633]318 ((universal-zerop prod) nil)
[2800]319 (t (list prod)))))
320 ,termlist))
[2790]321
[2796]322(defun multiply-termlists (p q order-fn)
[3127]323 "A version of polynomial multiplication, operating
324directly on termlists."
[2787]325 (cond
[2917]326 ((or (endp p) (endp q))
327 ;;p or q is 0 (represented by NIL)
328 nil)
[2789]329 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
[2787]330 ((endp (cdr p))
[2918]331 (multiply-term-by-termlist-dropping-zeros (car p) q))
332 ((endp (cdr q))
[2919]333 (multiply-term-by-termlist-dropping-zeros (car q) p t))
334 (t
[3633]335 (cons (multiply (car p) (car q))
[2949]336 (add-termlists
337 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
338 (multiply-termlists (cdr p) q order-fn)
339 order-fn)))))
[2793]340
[2803]341(defmethod multiply-by ((self poly) (other poly))
[3014]342 (change-term-order other self)
[2803]343 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
344 (poly-termlist other)
345 (poly-term-order self)))
346 self)
347
[3634]348(defun add (object1 object2)
[3374]349 "Non-destructively add POLY1 by POLY2."
[3634]350 (add-to (copy-instance object1) (copy-instance object2)))
[3374]351
[3634]352(defun subtract (minuend &rest subtrahends)
[3427]353 "Non-destructively subtract MINUEND and SUBTRAHENDS."
[3634]354 (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))
[3374]355
[3062]356(defmethod left-tensor-product-by ((self poly) (other monom))
357 (setf (poly-termlist self)
358 (mapcan #'(lambda (term)
359 (let ((prod (left-tensor-product-by term other)))
360 (cond
[3640]361 ((universal-zerop prod) nil)
[3062]362 (t (list prod)))))
363 (poly-termlist self)))
[3249]364 (incf (poly-dimension self) (monom-dimension other))
[3062]365 self)
[3044]366
[3062]367(defmethod right-tensor-product-by ((self poly) (other monom))
368 (setf (poly-termlist self)
369 (mapcan #'(lambda (term)
370 (let ((prod (right-tensor-product-by term other)))
371 (cond
[3640]372 ((universal-zerop prod) nil)
[3062]373 (t (list prod)))))
374 (poly-termlist self)))
[3249]375 (incf (poly-dimension self) (monom-dimension other))
[3062]376 self)
377
378
[3084]379(defun standard-extension (plist &aux (k (length plist)) (i 0))
[2716]380 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
[3060]381is a list of polynomials. Destructively modifies PLIST elements."
[3061]382 (mapc #'(lambda (poly)
[3085]383 (left-tensor-product-by
384 poly
385 (prog1
386 (make-monom-variable k i)
387 (incf i))))
[3061]388 plist))
[52]389
[3087]390(defun standard-extension-1 (plist
391 &aux
[3096]392 (plist (standard-extension plist))
[3087]393 (nvars (poly-dimension (car plist))))
[3081]394 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
[3087]395Firstly, new K variables U1, U2, ..., UK, are inserted into each
396polynomial. Subsequently, P1, P2, ..., PK are destructively modified
[3105]397tantamount to replacing PI with UI*PI-1. It assumes that all
[3106]398polynomials have the same dimension, and only the first polynomial
399is examined to determine this dimension."
[3089]400 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
401 ;; 1 from each polynomial; since UI*PI has no constant term,
402 ;; we just need to append the constant term at the end
403 ;; of each termlist.
[3064]404 (flet ((subtract-1 (p)
[3641]405 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
[3083]406 (setf plist (mapc #'subtract-1 plist)))
[3077]407 plist)
[52]408
409
[3107]410(defun standard-sum (plist
411 &aux
412 (plist (standard-extension plist))
413 (nvars (poly-dimension (car plist))))
[3087]414 "Calculate the polynomial U1*P1+U2*P2+...+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, and the resulting polynomials
[3117]418are added. Finally, 1 is subtracted. It should be noted that the term
419order is not modified, which is equivalent to using a lexicographic
420order on the first K variables."
[3107]421 (flet ((subtract-1 (p)
[3641]422 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
[3108]423 (subtract-1
424 (make-instance
425 'poly
[3115]426 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
[52]427
[3653]428(defgeneric universal-ezgcd (x y)
429 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
430C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
431the Euclidean algorithm.")
432 (:method ((x integer) (y integer)
433 &aux (c (gcd x y)))
434 (values c (/ x c) (/ y c)))
435 )
436
[3655]437(defgeneric s-polynomial (object1 object2)
[3651]438 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
439 (:method ((f poly) (g poly))
440 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
441 (mf (divide lcm (leading-monomial f)))
442 (mg (divide lcm (leading-monomial g))))
443 (multiple-value-bind (c cf cg)
[3652]444 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
[3651]445 (declare (ignore c))
446 (subtract
[3673]447 (multiply f (change-class mf 'term :coeff cg))
448 (multiply g (change-class mg 'term :coeff cf)))))))
[3651]449
[3676]450(defgeneric poly-content (object)
451 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
[3677]452 (:method ((self poly))
453 (reduce #'universal-gcd
[3679]454 (mapcar #'term-coeff (rest (poly-termlist self)))
455 :initial-value (leading-coefficient self))))
[3676]456
[3684]457(defun poly-primitive-part (object)
[3685]458 "Divide polynomial OBJECT by gcd of its
[3684]459coefficients. Return the resulting polynomial."
[3688]460 (scalar-divide-by object (poly-content object)))
[3682]461
[3700]462(defun poly-insert-variables (self k)
[3697]463 (left-tensor-product-by self (make-instance 'monom :dimension k)))
464
[3698]465(defun saturation-extension (f plist &aux (k (length plist)))
[3708]466 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
467PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
[3711]468as first K variables. It destructively modifies F and PLIST."
[3700]469 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
[3699]470 (standard-extension-1 plist)))
[3694]471
[3699]472(defun polysaturation-extension (f plist &aux (k (length plist)))
[3708]473 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
474and F' is F with variables U1,U2,...,UK inserted as first K
[3711]475variables. It destructively modifies F and PLIST."
[3700]476 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
[3703]477 (list (standard-sum plist))))
[3694]478
[3691]479(defun saturation-extension-1 (f p)
[3712]480 "Given family of polynomials F and a polynomial P, calculate [F',
481U*P-1], where F' is F with variable inserted as the first variable. It
482destructively modifies F and P."
[3693]483 (polysaturation-extension f (list p)))
[3713]484
[3717]485(defmethod multiply-by ((object1 number) (object2 poly))
[3720]486 (scalar-multiply-by (copy-instance object2) object1))
[3716]487
[3713]488(defgeneric universal-expt (x y)
[3721]489 (:documentation "Raises X to power Y.")
[3713]490 (:method ((x number) (y integer)) (expt x y))
491 (:method ((x t) (y integer))
492 (declare (type fixnum y))
493 (cond
494 ((minusp y) (error "universal-expt: Negative exponent."))
495 ((universal-zerop x) (if (zerop y) 1))
496 (t
497 (do ((k 1 (ash k 1))
498 (q x (multiply q q)) ;keep squaring
499 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
500 ((> k y) p)
[3721]501 (declare (fixnum k)))))))
Note: See TracBrowser for help on using the repository browser.