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

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