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

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

* empty log message *

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