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

Last change on this file since 3663 was 3663, 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 (: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 :after ((old monom) (new poly) &key)
128 "Converts OLD of class MONOM 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 (cons old 1))))
132
133(defmethod universal-equalp ((self poly) (other poly))
134 "Implements equality of polynomials."
135 (and (eql (poly-dimension self) (poly-dimension other))
136 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
137 (eq (poly-term-order self) (poly-term-order other))))
138
139(defgeneric leading-term (object)
140 (:method ((self poly))
141 (car (poly-termlist self)))
142 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
143
144(defgeneric second-leading-term (object)
145 (:method ((self poly))
146 (cadar (poly-termlist self)))
147 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
148
149(defgeneric leading-monomial (object)
150 (:method ((self poly))
151 (change-class (copy-instance (leading-term self)) 'monom))
152 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
153
154(defgeneric second-leading-monomial (object)
155 (:method ((self poly))
156 (change-class (copy-instance (second-leading-term self)) 'monom))
157 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
158
159(defgeneric leading-coefficient (object)
160 (:method ((self poly))
161 (term-coeff (leading-term self)))
162 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
163
164(defgeneric second-leading-coefficient (object)
165 (:method ((self poly))
166 (term-coeff (second-leading-term self)))
167 (:documentation "The second leading coefficient of a polynomial. It
168 signals error for a polynomial with at most one term."))
169
170(defmethod universal-zerop ((self poly))
171 "Return T iff SELF is a zero polynomial."
172 (null (poly-termlist self)))
173
174(defgeneric poly-length (self)
175 (:documentation "Return the number of terms.")
176 (:method ((self poly))
177 (length (poly-termlist self))))
178
179(defmethod multiply-by ((self poly) (other monom))
180 "Multiply a polynomial SELF by OTHER."
181 (mapc #'(lambda (term) (multiply-by term other))
182 (poly-termlist self))
183 self)
184
185(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
186 "Return an expression which will efficiently adds/subtracts two
187polynomials, P and Q. The addition/subtraction of coefficients is
188performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME
189is supplied, it is used to negate the coefficients of Q which do not
190have a corresponding coefficient in P. The code implements an
191efficient algorithm to add two polynomials represented as sorted lists
192of terms. The code destroys both arguments, reusing the terms to build
193the result."
194 `(macrolet ((lc (x) `(term-coeff (car ,x))))
195 (do ((p ,p)
196 (q ,q)
197 r)
198 ((or (endp p) (endp q))
199 ;; NOTE: R contains the result in reverse order. Can it
200 ;; be more efficient to produce the terms in correct order?
201 (unless (endp q)
202 ;; Upon subtraction, we must change the sign of
203 ;; all coefficients in q
204 ,@(when uminus-fn
205 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
206 (setf r (nreconc r q)))
207 r)
208 (multiple-value-bind
209 (greater-p equal-p)
210 (funcall ,order-fn (car p) (car q))
211 (cond
212 (greater-p
213 (rotatef (cdr p) r p)
214 )
215 (equal-p
216 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
217 (cond
218 ((universal-zerop s)
219 (setf p (cdr p))
220 )
221 (t
222 (setf (lc p) s)
223 (rotatef (cdr p) r p))))
224 (setf q (cdr q))
225 )
226 (t
227 ;;Negate the term of Q if UMINUS provided, signallig
228 ;;that we are doing subtraction
229 ,(when uminus-fn
230 `(setf (lc q) (funcall ,uminus-fn (lc q))))
231 (rotatef (cdr q) r q)))))))
232
233
234(defgeneric add-to (self other)
235 (:documentation "Add OTHER to SELF.")
236 (:method ((self number) (other number))
237 (+ self other)))
238
239(defgeneric subtract-from (self other)
240 (:documentation "Subtract OTHER from SELF.")
241 (:method ((self number) (other number))
242 (- self other)))
243
244(defmacro def-add/subtract-method (add/subtract-method-name
245 uminus-method-name
246 &optional
247 (doc-string nil doc-string-supplied-p))
248 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
249 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
250 ,@(when doc-string-supplied-p `(,doc-string))
251 ;; Ensure orders are compatible
252 (change-term-order other self)
253 (setf (poly-termlist self) (fast-add/subtract
254 (poly-termlist self) (poly-termlist other)
255 (poly-term-order self)
256 #',add/subtract-method-name
257 ,(when uminus-method-name `(function ,uminus-method-name))))
258 self))
259
260(eval-when (:compile-toplevel :load-toplevel :execute)
261
262 (def-add/subtract-method add-to nil
263 "Adds to polynomial SELF another polynomial OTHER.
264This operation destructively modifies both polynomials.
265The result is stored in SELF. This implementation does
266no consing, entirely reusing the sells of SELF and OTHER.")
267
268 (def-add/subtract-method subtract-from unary-minus
269 "Subtracts from polynomial SELF another polynomial OTHER.
270This operation destructively modifies both polynomials.
271The result is stored in SELF. This implementation does
272no consing, entirely reusing the sells of SELF and OTHER.")
273 )
274
275(defmethod unary-minus ((self poly))
276 "Destructively modifies the coefficients of the polynomial SELF,
277by changing their sign."
278 (mapc #'unary-minus (poly-termlist self))
279 self)
280
281(defun add-termlists (p q order-fn)
282 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
283 (fast-add/subtract p q order-fn #'add-to nil))
284
285(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
286 &optional (reverse-arg-order-P nil))
287 "Multiplies term TERM by a list of term, TERMLIST.
288Takes into accound divisors of zero in the ring, by
289deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
290is T, change the order of arguments; this may be important
291if we extend the package to non-commutative rings."
292 `(mapcan #'(lambda (other-term)
293 (let ((prod (multiply
294 ,@(cond
295 (reverse-arg-order-p
296 `(other-term ,term))
297 (t
298 `(,term other-term))))))
299 (cond
300 ((universal-zerop prod) nil)
301 (t (list prod)))))
302 ,termlist))
303
304(defun multiply-termlists (p q order-fn)
305 "A version of polynomial multiplication, operating
306directly on termlists."
307 (cond
308 ((or (endp p) (endp q))
309 ;;p or q is 0 (represented by NIL)
310 nil)
311 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
312 ((endp (cdr p))
313 (multiply-term-by-termlist-dropping-zeros (car p) q))
314 ((endp (cdr q))
315 (multiply-term-by-termlist-dropping-zeros (car q) p t))
316 (t
317 (cons (multiply (car p) (car q))
318 (add-termlists
319 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
320 (multiply-termlists (cdr p) q order-fn)
321 order-fn)))))
322
323(defmethod multiply-by ((self poly) (other poly))
324 (change-term-order other self)
325 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
326 (poly-termlist other)
327 (poly-term-order self)))
328 self)
329
330(defun add (object1 object2)
331 "Non-destructively add POLY1 by POLY2."
332 (add-to (copy-instance object1) (copy-instance object2)))
333
334(defun subtract (minuend &rest subtrahends)
335 "Non-destructively subtract MINUEND and SUBTRAHENDS."
336 (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))
337
338(defmethod left-tensor-product-by ((self poly) (other monom))
339 (setf (poly-termlist self)
340 (mapcan #'(lambda (term)
341 (let ((prod (left-tensor-product-by term other)))
342 (cond
343 ((universal-zerop prod) nil)
344 (t (list prod)))))
345 (poly-termlist self)))
346 (incf (poly-dimension self) (monom-dimension other))
347 self)
348
349(defmethod right-tensor-product-by ((self poly) (other monom))
350 (setf (poly-termlist self)
351 (mapcan #'(lambda (term)
352 (let ((prod (right-tensor-product-by term other)))
353 (cond
354 ((universal-zerop prod) nil)
355 (t (list prod)))))
356 (poly-termlist self)))
357 (incf (poly-dimension self) (monom-dimension other))
358 self)
359
360
361(defun standard-extension (plist &aux (k (length plist)) (i 0))
362 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
363is a list of polynomials. Destructively modifies PLIST elements."
364 (mapc #'(lambda (poly)
365 (left-tensor-product-by
366 poly
367 (prog1
368 (make-monom-variable k i)
369 (incf i))))
370 plist))
371
372(defun standard-extension-1 (plist
373 &aux
374 (plist (standard-extension plist))
375 (nvars (poly-dimension (car plist))))
376 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
377Firstly, new K variables U1, U2, ..., UK, are inserted into each
378polynomial. Subsequently, P1, P2, ..., PK are destructively modified
379tantamount to replacing PI with UI*PI-1. It assumes that all
380polynomials have the same dimension, and only the first polynomial
381is examined to determine this dimension."
382 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
383 ;; 1 from each polynomial; since UI*PI has no constant term,
384 ;; we just need to append the constant term at the end
385 ;; of each termlist.
386 (flet ((subtract-1 (p)
387 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
388 (setf plist (mapc #'subtract-1 plist)))
389 plist)
390
391
392(defun standard-sum (plist
393 &aux
394 (plist (standard-extension plist))
395 (nvars (poly-dimension (car plist))))
396 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
397Firstly, new K variables, U1, U2, ..., UK, are inserted into each
398polynomial. Subsequently, P1, P2, ..., PK are destructively modified
399tantamount to replacing PI with UI*PI, and the resulting polynomials
400are added. Finally, 1 is subtracted. It should be noted that the term
401order is not modified, which is equivalent to using a lexicographic
402order on the first K variables."
403 (flet ((subtract-1 (p)
404 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
405 (subtract-1
406 (make-instance
407 'poly
408 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
409
410(defgeneric universal-ezgcd (x y)
411 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
412C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
413the Euclidean algorithm.")
414 (:method ((x integer) (y integer)
415 &aux (c (gcd x y)))
416 (values c (/ x c) (/ y c)))
417 )
418
419(defgeneric s-polynomial (object1 object2)
420 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
421 (:method ((f poly) (g poly))
422 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
423 (mf (divide lcm (leading-monomial f)))
424 (mg (divide lcm (leading-monomial g))))
425 (multiple-value-bind (c cf cg)
426 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
427 (declare (ignore c))
428 (subtract
429 (multiply (multiply f mf) cg)
430 (multiply (multiply g mg) cf))))))
431
432#|
433
434(defun saturation-extension-1 (ring f p)
435 "Calculate [F, U*P-1]. It destructively modifies F."
436 (declare (type ring ring))
437 (polysaturation-extension ring f (list p)))
438
439
440
441
442
443
444(defun poly-primitive-part (ring p)
445 "Divide polynomial P with integer coefficients by gcd of its
446coefficients and return the result."
447 (declare (type ring ring) (type poly p))
448 (if (poly-zerop p)
449 (values p 1)
450 (let ((c (poly-content ring p)))
451 (values (make-poly-from-termlist
452 (mapcar
453 #'(lambda (x)
454 (make-term :monom (term-monom x)
455 :coeff (funcall (ring-div ring) (term-coeff x) c)))
456 (poly-termlist p))
457 (poly-sugar p))
458 c))))
459
460(defun poly-content (ring p)
461 "Greatest common divisor of the coefficients of the polynomial P. Use the RING structure
462to compute the greatest common divisor."
463 (declare (type ring ring) (type poly p))
464 (reduce (ring-gcd ring) (mapcar #'term-coeff (rest (poly-termlist p))) :initial-value (poly-lc p)))
465
466|#
Note: See TracBrowser for help on using the repository browser.