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

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