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

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

* empty log message *

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