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

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

* empty log message *

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