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

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

* empty log message *

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