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

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

* empty log message *

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