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

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

* empty log message *

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