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

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

* empty log message *

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