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

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