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

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

* empty log message *

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