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

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