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

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