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

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

* empty log message *

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