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

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

* empty log message *

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