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

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