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

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