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

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

* empty log message *

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