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

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

* empty log message *

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