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

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

* empty log message *

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