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

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

* empty log message *

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