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

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

* empty log message *

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