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

Last change on this file since 2993 was 2949, checked in by Marek Rychlik, 10 years ago

* empty log message *

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