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

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