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

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

* empty log message *

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