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

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

* empty log message *

File size: 15.6 KB
Line 
1;;; -*- Mode: Lisp -*-
2;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3;;;
4;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik <rychlik@u.arizona.edu>
5;;;
6;;; This program is free software; you can redistribute it and/or modify
7;;; it under the terms of the GNU General Public License as published by
8;;; the Free Software Foundation; either version 2 of the License, or
9;;; (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19;;;
20;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
21
22(defpackage "POLYNOMIAL"
23 (:use :cl :ring :monom :order :term #| :infix |# )
24 (:export "POLY"
25 "POLY-TERMLIST"
26 "POLY-TERM-ORDER")
27 (:documentation "Implements polynomials"))
28
29(in-package :polynomial)
30
31(proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0)))
32
33(defclass poly ()
34 ((termlist :initarg :termlist :accessor poly-termlist)
35 (order :initarg :order :accessor poly-term-order))
36 (:default-initargs :termlist nil :order #'lex>)
37 (:documentation "A polynomial with a list of terms TERMLIST, ordered
38according to term order ORDER, which defaults to LEX>."))
39
40(defmethod print-object ((self poly) stream)
41 (format stream "#<POLY TERMLIST=~A ORDER=~A>"
42 (poly-termlist self)
43 (poly-term-order self)))
44
45(defmethod r-equalp ((self poly) (other poly))
46 "POLY instances are R-EQUALP if they have the same
47order and if all terms are R-EQUALP."
48 (and (every #'r-equalp (poly-termlist self) (poly-termlist other))
49 (eq (poly-term-order self) (poly-term-order other))))
50
51(defmethod insert-item ((self poly) (item term))
52 (push item (poly-termlist self))
53 self)
54
55(defmethod append-item ((self poly) (item term))
56 (setf (cdr (last (poly-termlist self))) (list item))
57 self)
58
59;; Leading term
60(defgeneric leading-term (object)
61 (:method ((self poly))
62 (car (poly-termlist self)))
63 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
64
65;; Second term
66(defgeneric second-leading-term (object)
67 (:method ((self poly))
68 (cadar (poly-termlist self)))
69 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
70
71;; Leading coefficient
72(defgeneric leading-coefficient (object)
73 (:method ((self poly))
74 (r-coeff (leading-term self)))
75 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
76
77;; Second coefficient
78(defgeneric second-leading-coefficient (object)
79 (:method ((self poly))
80 (r-coeff (second-leading-term self)))
81 (:documentation "The second leading coefficient of a polynomial. It signals error for a polynomial with at most one term."))
82
83;; Testing for a zero polynomial
84(defmethod r-zerop ((self poly))
85 (null (poly-termlist self)))
86
87;; The number of terms
88(defmethod r-length ((self poly))
89 (length (poly-termlist self)))
90
91(defmethod multiply-by ((self poly) (other monom))
92 (mapc #'(lambda (term) (multiply-by term other))
93 (poly-termlist self))
94 self)
95
96(defmethod multiply-by ((self poly) (other scalar))
97 (mapc #'(lambda (term) (multiply-by term other))
98 (poly-termlist self))
99 self)
100
101
102(defun fast-addition (p q order-fn add-fun)
103 "Returns the sum of two polynomials. Implements an efficient
104algorithm to add two polynomials represented as sorted lists of
105terms. This function destroys both arguments, reusing the terms to
106build the result."
107 (macrolet ((lc (x) `(r-coeff (car ,x))))
108 (do ((p p)
109 (q q)
110 r)
111 ((or (endp p) (endp q))
112 ;; NOTE: R contains the result in reverse order. Can it
113 ;; be more efficient to produce the terms in correct order?
114 (unless (endp q) (setf r (nreconc r q)))
115 r)
116 (multiple-value-bind
117 (greater-p equal-p)
118 (funcall order-fn (car p) (car q))
119 (cond
120 (greater-p
121 (rotatef (cdr p) r p)
122 )
123 (equal-p
124 (let ((s (funcall add-fun (lc p) (lc q))))
125 (cond
126 ((r-zerop s)
127 (setf p (cdr p))
128 )
129 (t
130 (setf (lc p) s)
131 (rotatef (cdr p) r p))))
132 (setf q (cdr q))
133 )
134 (t
135 (rotatef (cdr q) r q)))))))
136
137
138(defmacro def-additive-operation-method (method-name &optional (doc-string nil doc-string-supplied-p))
139 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
140 `(defmethod ,method-name ((self poly) (other poly))
141 ,@(when doc-string-supplied-p `(,doc-string))
142 (with-slots ((termlist1 termlist) (order1 order))
143 self
144 (with-slots ((termlist2 termlist) (order2 order))
145 other
146 ;; Ensure orders are compatible
147 (unless (eq order1 order2)
148 (setf termlist2 (sort termlist2 order1)
149 order2 order1))
150 (setf termlist1 (fast-addition termlist1 termlist2 order1 #',method-name))))
151 self))
152
153(def-additive-operation-method add-to
154 "Adds to polynomial SELF another polynomial OTHER.
155This operation destructively modifies both polynomials.
156The result is stored in SELF. This implementation does
157no consing, entirely reusing the sells of SELF and OTHER.")
158
159(def-additive-operation-method subtract-from
160 "Subtracts from polynomial SELF another polynomial OTHER.
161This operation destructively modifies both polynomials.
162The result is stored in SELF. This implementation does
163no consing, entirely reusing the sells of SELF and OTHER.")
164
165(defmethod unary-minus ((self poly))
166 "Destructively modifies the coefficients of the polynomial SELF,
167by changing their sign."
168 (mapc #'unary-minus (poly-termlist self))
169 self)
170
171#|
172
173(defun poly-standard-extension (plist &aux (k (length plist)))
174 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]."
175 (declare (list plist) (fixnum k))
176 (labels ((incf-power (g i)
177 (dolist (x (poly-termlist g))
178 (incf (monom-elt (term-monom x) i)))
179 (incf (poly-sugar g))))
180 (setf plist (poly-list-add-variables plist k))
181 (dotimes (i k plist)
182 (incf-power (nth i plist) i))))
183
184(defun saturation-extension (ring f plist
185 &aux
186 (k (length plist))
187 (d (monom-dimension (poly-lm (car plist))))
188 f-x plist-x)
189 "Calculate [F, U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK]."
190 (declare (type ring ring))
191 (setf f-x (poly-list-add-variables f k)
192 plist-x (mapcar #'(lambda (x)
193 (setf (poly-termlist x)
194 (nconc (poly-termlist x)
195 (list (make-term :monom (make-monom :dimension d)
196 :coeff (funcall (ring-uminus ring)
197 (funcall (ring-unit ring)))))))
198 x)
199 (poly-standard-extension plist)))
200 (append f-x plist-x))
201
202
203(defun polysaturation-extension (ring f plist
204 &aux
205 (k (length plist))
206 (d (+ k (monom-dimension (poly-lm (car plist)))))
207 ;; Add k variables to f
208 (f (poly-list-add-variables f k))
209 ;; Set PLIST to [U1*P1,U2*P2,...,UK*PK]
210 (plist (apply #'poly-append (poly-standard-extension plist))))
211 "Calculate [F, U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]. It destructively modifies F."
212 ;; Add -1 as the last term
213 (declare (type ring ring))
214 (setf (cdr (last (poly-termlist plist)))
215 (list (make-term :monom (make-monom :dimension d)
216 :coeff (funcall (ring-uminus ring) (funcall (ring-unit ring))))))
217 (append f (list plist)))
218
219(defun saturation-extension-1 (ring f p)
220 "Calculate [F, U*P-1]. It destructively modifies F."
221 (declare (type ring ring))
222 (polysaturation-extension ring f (list p)))
223
224;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
225;;
226;; Evaluation of polynomial (prefix) expressions
227;;
228;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
229
230(defun coerce-coeff (ring expr vars)
231 "Coerce an element of the coefficient ring to a constant polynomial."
232 ;; Modular arithmetic handler by rat
233 (declare (type ring ring))
234 (make-poly-from-termlist (list (make-term :monom (make-monom :dimension (length vars))
235 :coeff (funcall (ring-parse ring) expr)))
236 0))
237
238(defun poly-eval (expr vars
239 &optional
240 (ring +ring-of-integers+)
241 (order #'lex>)
242 (list-marker :[)
243 &aux
244 (ring-and-order (make-ring-and-order :ring ring :order order)))
245 "Evaluate Lisp form EXPR to a polynomial or a list of polynomials in
246variables VARS. Return the resulting polynomial or list of
247polynomials. Standard arithmetical operators in form EXPR are
248replaced with their analogues in the ring of polynomials, and the
249resulting expression is evaluated, resulting in a polynomial or a list
250of polynomials in internal form. A similar operation in another computer
251algebra system could be called 'expand' or so."
252 (declare (type ring ring))
253 (labels ((p-eval (arg) (poly-eval arg vars ring order))
254 (p-eval-scalar (arg) (poly-eval-scalar arg))
255 (p-eval-list (args) (mapcar #'p-eval args))
256 (p-add (x y) (poly-add ring-and-order x y)))
257 (cond
258 ((null expr) (error "Empty expression"))
259 ((eql expr 0) (make-poly-zero))
260 ((member expr vars :test #'equalp)
261 (let ((pos (position expr vars :test #'equalp)))
262 (make-poly-variable ring (length vars) pos)))
263 ((atom expr)
264 (coerce-coeff ring expr vars))
265 ((eq (car expr) list-marker)
266 (cons list-marker (p-eval-list (cdr expr))))
267 (t
268 (case (car expr)
269 (+ (reduce #'p-add (p-eval-list (cdr expr))))
270 (- (case (length expr)
271 (1 (make-poly-zero))
272 (2 (poly-uminus ring (p-eval (cadr expr))))
273 (3 (poly-sub ring-and-order (p-eval (cadr expr)) (p-eval (caddr expr))))
274 (otherwise (poly-sub ring-and-order (p-eval (cadr expr))
275 (reduce #'p-add (p-eval-list (cddr expr)))))))
276 (*
277 (if (endp (cddr expr)) ;unary
278 (p-eval (cdr expr))
279 (reduce #'(lambda (p q) (poly-mul ring-and-order p q)) (p-eval-list (cdr expr)))))
280 (/
281 ;; A polynomial can be divided by a scalar
282 (cond
283 ((endp (cddr expr))
284 ;; A special case (/ ?), the inverse
285 (coerce-coeff ring (apply (ring-div ring) (cdr expr)) vars))
286 (t
287 (let ((num (p-eval (cadr expr)))
288 (denom-inverse (apply (ring-div ring)
289 (cons (funcall (ring-unit ring))
290 (mapcar #'p-eval-scalar (cddr expr))))))
291 (scalar-times-poly ring denom-inverse num)))))
292 (expt
293 (cond
294 ((member (cadr expr) vars :test #'equalp)
295 ;;Special handling of (expt var pow)
296 (let ((pos (position (cadr expr) vars :test #'equalp)))
297 (make-poly-variable ring (length vars) pos (caddr expr))))
298 ((not (and (integerp (caddr expr)) (plusp (caddr expr))))
299 ;; Negative power means division in coefficient ring
300 ;; Non-integer power means non-polynomial coefficient
301 (coerce-coeff ring expr vars))
302 (t (poly-expt ring-and-order (p-eval (cadr expr)) (caddr expr)))))
303 (otherwise
304 (coerce-coeff ring expr vars)))))))
305
306(defun poly-eval-scalar (expr
307 &optional
308 (ring +ring-of-integers+)
309 &aux
310 (order #'lex>))
311 "Evaluate a scalar expression EXPR in ring RING."
312 (declare (type ring ring))
313 (poly-lc (poly-eval expr nil ring order)))
314
315(defun spoly (ring-and-order f g
316 &aux
317 (ring (ro-ring ring-and-order)))
318 "It yields the S-polynomial of polynomials F and G."
319 (declare (type ring-and-order ring-and-order) (type poly f g))
320 (let* ((lcm (monom-lcm (poly-lm f) (poly-lm g)))
321 (mf (monom-div lcm (poly-lm f)))
322 (mg (monom-div lcm (poly-lm g))))
323 (declare (type monom mf mg))
324 (multiple-value-bind (c cf cg)
325 (funcall (ring-ezgcd ring) (poly-lc f) (poly-lc g))
326 (declare (ignore c))
327 (poly-sub
328 ring-and-order
329 (scalar-times-poly ring cg (monom-times-poly mf f))
330 (scalar-times-poly ring cf (monom-times-poly mg g))))))
331
332
333(defun poly-primitive-part (ring p)
334 "Divide polynomial P with integer coefficients by gcd of its
335coefficients and return the result."
336 (declare (type ring ring) (type poly p))
337 (if (poly-zerop p)
338 (values p 1)
339 (let ((c (poly-content ring p)))
340 (values (make-poly-from-termlist
341 (mapcar
342 #'(lambda (x)
343 (make-term :monom (term-monom x)
344 :coeff (funcall (ring-div ring) (term-coeff x) c)))
345 (poly-termlist p))
346 (poly-sugar p))
347 c))))
348
349(defun poly-content (ring p)
350 "Greatest common divisor of the coefficients of the polynomial P. Use the RING structure
351to compute the greatest common divisor."
352 (declare (type ring ring) (type poly p))
353 (reduce (ring-gcd ring) (mapcar #'term-coeff (rest (poly-termlist p))) :initial-value (poly-lc p)))
354
355(defun read-infix-form (&key (stream t))
356 "Parser of infix expressions with integer/rational coefficients
357The parser will recognize two kinds of polynomial expressions:
358
359- polynomials in fully expanded forms with coefficients
360 written in front of symbolic expressions; constants can be optionally
361 enclosed in (); for example, the infix form
362 X^2-Y^2+(-4/3)*U^2*W^3-5
363 parses to
364 (+ (- (EXPT X 2) (EXPT Y 2)) (* (- (/ 4 3)) (EXPT U 2) (EXPT W 3)) (- 5))
365
366- lists of polynomials; for example
367 [X-Y, X^2+3*Z]
368 parses to
369 (:[ (- X Y) (+ (EXPT X 2) (* 3 Z)))
370 where the first symbol [ marks a list of polynomials.
371
372-other infix expressions, for example
373 [(X-Y)*(X+Y)/Z,(X+1)^2]
374parses to:
375 (:[ (/ (* (- X Y) (+ X Y)) Z) (EXPT (+ X 1) 2))
376Currently this function is implemented using M. Kantrowitz's INFIX package."
377 (read-from-string
378 (concatenate 'string
379 "#I("
380 (with-output-to-string (s)
381 (loop
382 (multiple-value-bind (line eof)
383 (read-line stream t)
384 (format s "~A" line)
385 (when eof (return)))))
386 ")")))
387
388(defun read-poly (vars &key
389 (stream t)
390 (ring +ring-of-integers+)
391 (order #'lex>))
392 "Reads an expression in prefix form from a stream STREAM.
393The expression read from the strem should represent a polynomial or a
394list of polynomials in variables VARS, over the ring RING. The
395polynomial or list of polynomials is returned, with terms in each
396polynomial ordered according to monomial order ORDER."
397 (poly-eval (read-infix-form :stream stream) vars ring order))
398
399(defun string->poly (str vars
400 &optional
401 (ring +ring-of-integers+)
402 (order #'lex>))
403 "Converts a string STR to a polynomial in variables VARS."
404 (with-input-from-string (s str)
405 (read-poly vars :stream s :ring ring :order order)))
406
407(defun poly->alist (p)
408 "Convert a polynomial P to an association list. Thus, the format of the
409returned value is ((MONOM[0] . COEFF[0]) (MONOM[1] . COEFF[1]) ...), where
410MONOM[I] is a list of exponents in the monomial and COEFF[I] is the
411corresponding coefficient in the ring."
412 (cond
413 ((poly-p p)
414 (mapcar #'term->cons (poly-termlist p)))
415 ((and (consp p) (eq (car p) :[))
416 (cons :[ (mapcar #'poly->alist (cdr p))))))
417
418(defun string->alist (str vars
419 &optional
420 (ring +ring-of-integers+)
421 (order #'lex>))
422 "Convert a string STR representing a polynomial or polynomial list to
423an association list (... (MONOM . COEFF) ...)."
424 (poly->alist (string->poly str vars ring order)))
425
426(defun poly-equal-no-sugar-p (p q)
427 "Compare polynomials for equality, ignoring sugar."
428 (declare (type poly p q))
429 (equalp (poly-termlist p) (poly-termlist q)))
430
431(defun poly-set-equal-no-sugar-p (p q)
432 "Compare polynomial sets P and Q for equality, ignoring sugar."
433 (null (set-exclusive-or p q :test #'poly-equal-no-sugar-p )))
434
435(defun poly-list-equal-no-sugar-p (p q)
436 "Compare polynomial lists P and Q for equality, ignoring sugar."
437 (every #'poly-equal-no-sugar-p p q))
438|#
Note: See TracBrowser for help on using the repository browser.