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

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