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

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