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

Last change on this file since 3346 was 3346, checked in by Marek Rychlik, 10 years ago

* empty log message *

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