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

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

* empty log message *

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