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

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