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

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