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

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

* empty log message *

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