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

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

* empty log message *

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