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

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

* empty log message *

File size: 18.5 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 (change-order other self)
171 (setf (poly-termlist self) (fast-add/subtract
172 (poly-termlist self) (poly-termlist other)
173 (poly-term-order self)
174 #',add/subtract-method-name
175 ,(when uminus-method-name `(function ,uminus-method-name))))
176 self))
177
178(eval-when (:compile-toplevel :load-toplevel :execute)
179
180 (def-add/subtract-method add-to nil
181 "Adds to polynomial SELF another polynomial OTHER.
182This operation destructively modifies both polynomials.
183The result is stored in SELF. This implementation does
184no consing, entirely reusing the sells of SELF and OTHER.")
185
186 (def-add/subtract-method subtract-from unary-minus
187 "Subtracts from polynomial SELF another polynomial OTHER.
188This operation destructively modifies both polynomials.
189The result is stored in SELF. This implementation does
190no consing, entirely reusing the sells of SELF and OTHER.")
191
192 )
193
194
195
196(defmethod unary-minus ((self poly))
197 "Destructively modifies the coefficients of the polynomial SELF,
198by changing their sign."
199 (mapc #'unary-minus (poly-termlist self))
200 self)
201
202(defun add-termlists (p q order-fn)
203 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
204 (fast-add/subtract p q order-fn #'add-to nil))
205
206(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
207 &optional (reverse-arg-order-P nil))
208 "Multiplies term TERM by a list of term, TERMLIST.
209Takes into accound divisors of zero in the ring, by
210deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
211is T, change the order of arguments; this may be important
212if we extend the package to non-commutative rings."
213 `(mapcan #'(lambda (other-term)
214 (let ((prod (r*
215 ,@(cond
216 (reverse-arg-order-p
217 `(other-term ,term))
218 (t
219 `(,term other-term))))))
220 (cond
221 ((r-zerop prod) nil)
222 (t (list prod)))))
223 ,termlist))
224
225(defun multiply-termlists (p q order-fn)
226 (cond
227 ((or (endp p) (endp q))
228 ;;p or q is 0 (represented by NIL)
229 nil)
230 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
231 ((endp (cdr p))
232 (multiply-term-by-termlist-dropping-zeros (car p) q))
233 ((endp (cdr q))
234 (multiply-term-by-termlist-dropping-zeros (car q) p t))
235 (t
236 (cons (r* (car p) (car q))
237 (add-termlists
238 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
239 (multiply-termlists (cdr p) q order-fn)
240 order-fn)))))
241
242
243
244(defmethod multiply-by ((self poly) (other poly))
245 (change-term-order other self)
246 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
247 (poly-termlist other)
248 (poly-term-order self)))
249 self)
250
251(defmethod r* ((poly1 poly) (poly2 poly))
252 "Non-destructively multiply POLY1 by POLY2."
253 (multiply-by (copy-instance POLY1) (copy-instance POLY2)))
254
255#|
256
257
258(defun poly-standard-extension (plist &aux (k (length plist)))
259 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
260is a list of polynomials."
261 (declare (list plist) (fixnum k))
262 (labels ((incf-power (g i)
263 (dolist (x (poly-termlist g))
264 (incf (monom-elt (term-monom x) i)))
265 (incf (poly-sugar g))))
266 (setf plist (poly-list-add-variables plist k))
267 (dotimes (i k plist)
268 (incf-power (nth i plist) i))))
269
270
271
272(defun saturation-extension (ring f plist
273 &aux
274 (k (length plist))
275 (d (monom-dimension (poly-lm (car plist))))
276 f-x plist-x)
277 "Calculate [F, U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK]."
278 (declare (type ring ring))
279 (setf f-x (poly-list-add-variables f k)
280 plist-x (mapcar #'(lambda (x)
281 (setf (poly-termlist x)
282 (nconc (poly-termlist x)
283 (list (make-term :monom (make-monom :dimension d)
284 :coeff (funcall (ring-uminus ring)
285 (funcall (ring-unit ring)))))))
286 x)
287 (poly-standard-extension plist)))
288 (append f-x plist-x))
289
290
291(defun polysaturation-extension (ring f plist
292 &aux
293 (k (length plist))
294 (d (+ k (monom-dimension (poly-lm (car plist)))))
295 ;; Add k variables to f
296 (f (poly-list-add-variables f k))
297 ;; Set PLIST to [U1*P1,U2*P2,...,UK*PK]
298 (plist (apply #'poly-append (poly-standard-extension plist))))
299 "Calculate [F, U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]. It destructively modifies F."
300 ;; Add -1 as the last term
301 (declare (type ring ring))
302 (setf (cdr (last (poly-termlist plist)))
303 (list (make-term :monom (make-monom :dimension d)
304 :coeff (funcall (ring-uminus ring) (funcall (ring-unit ring))))))
305 (append f (list plist)))
306
307(defun saturation-extension-1 (ring f p)
308 "Calculate [F, U*P-1]. It destructively modifies F."
309 (declare (type ring ring))
310 (polysaturation-extension ring f (list p)))
311
312;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
313;;
314;; Evaluation of polynomial (prefix) expressions
315;;
316;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
317
318(defun coerce-coeff (ring expr vars)
319 "Coerce an element of the coefficient ring to a constant polynomial."
320 ;; Modular arithmetic handler by rat
321 (declare (type ring ring))
322 (make-poly-from-termlist (list (make-term :monom (make-monom :dimension (length vars))
323 :coeff (funcall (ring-parse ring) expr)))
324 0))
325
326(defun poly-eval (expr vars
327 &optional
328 (ring +ring-of-integers+)
329 (order #'lex>)
330 (list-marker :[)
331 &aux
332 (ring-and-order (make-ring-and-order :ring ring :order order)))
333 "Evaluate Lisp form EXPR to a polynomial or a list of polynomials in
334variables VARS. Return the resulting polynomial or list of
335polynomials. Standard arithmetical operators in form EXPR are
336replaced with their analogues in the ring of polynomials, and the
337resulting expression is evaluated, resulting in a polynomial or a list
338of polynomials in internal form. A similar operation in another computer
339algebra system could be called 'expand' or so."
340 (declare (type ring ring))
341 (labels ((p-eval (arg) (poly-eval arg vars ring order))
342 (p-eval-scalar (arg) (poly-eval-scalar arg))
343 (p-eval-list (args) (mapcar #'p-eval args))
344 (p-add (x y) (poly-add ring-and-order x y)))
345 (cond
346 ((null expr) (error "Empty expression"))
347 ((eql expr 0) (make-poly-zero))
348 ((member expr vars :test #'equalp)
349 (let ((pos (position expr vars :test #'equalp)))
350 (make-poly-variable ring (length vars) pos)))
351 ((atom expr)
352 (coerce-coeff ring expr vars))
353 ((eq (car expr) list-marker)
354 (cons list-marker (p-eval-list (cdr expr))))
355 (t
356 (case (car expr)
357 (+ (reduce #'p-add (p-eval-list (cdr expr))))
358 (- (case (length expr)
359 (1 (make-poly-zero))
360 (2 (poly-uminus ring (p-eval (cadr expr))))
361 (3 (poly-sub ring-and-order (p-eval (cadr expr)) (p-eval (caddr expr))))
362 (otherwise (poly-sub ring-and-order (p-eval (cadr expr))
363 (reduce #'p-add (p-eval-list (cddr expr)))))))
364 (*
365 (if (endp (cddr expr)) ;unary
366 (p-eval (cdr expr))
367 (reduce #'(lambda (p q) (poly-mul ring-and-order p q)) (p-eval-list (cdr expr)))))
368 (/
369 ;; A polynomial can be divided by a scalar
370 (cond
371 ((endp (cddr expr))
372 ;; A special case (/ ?), the inverse
373 (coerce-coeff ring (apply (ring-div ring) (cdr expr)) vars))
374 (t
375 (let ((num (p-eval (cadr expr)))
376 (denom-inverse (apply (ring-div ring)
377 (cons (funcall (ring-unit ring))
378 (mapcar #'p-eval-scalar (cddr expr))))))
379 (scalar-times-poly ring denom-inverse num)))))
380 (expt
381 (cond
382 ((member (cadr expr) vars :test #'equalp)
383 ;;Special handling of (expt var pow)
384 (let ((pos (position (cadr expr) vars :test #'equalp)))
385 (make-poly-variable ring (length vars) pos (caddr expr))))
386 ((not (and (integerp (caddr expr)) (plusp (caddr expr))))
387 ;; Negative power means division in coefficient ring
388 ;; Non-integer power means non-polynomial coefficient
389 (coerce-coeff ring expr vars))
390 (t (poly-expt ring-and-order (p-eval (cadr expr)) (caddr expr)))))
391 (otherwise
392 (coerce-coeff ring expr vars)))))))
393
394(defun poly-eval-scalar (expr
395 &optional
396 (ring +ring-of-integers+)
397 &aux
398 (order #'lex>))
399 "Evaluate a scalar expression EXPR in ring RING."
400 (declare (type ring ring))
401 (poly-lc (poly-eval expr nil ring order)))
402
403(defun spoly (ring-and-order f g
404 &aux
405 (ring (ro-ring ring-and-order)))
406 "It yields the S-polynomial of polynomials F and G."
407 (declare (type ring-and-order ring-and-order) (type poly f g))
408 (let* ((lcm (monom-lcm (poly-lm f) (poly-lm g)))
409 (mf (monom-div lcm (poly-lm f)))
410 (mg (monom-div lcm (poly-lm g))))
411 (declare (type monom mf mg))
412 (multiple-value-bind (c cf cg)
413 (funcall (ring-ezgcd ring) (poly-lc f) (poly-lc g))
414 (declare (ignore c))
415 (poly-sub
416 ring-and-order
417 (scalar-times-poly ring cg (monom-times-poly mf f))
418 (scalar-times-poly ring cf (monom-times-poly mg g))))))
419
420
421(defun poly-primitive-part (ring p)
422 "Divide polynomial P with integer coefficients by gcd of its
423coefficients and return the result."
424 (declare (type ring ring) (type poly p))
425 (if (poly-zerop p)
426 (values p 1)
427 (let ((c (poly-content ring p)))
428 (values (make-poly-from-termlist
429 (mapcar
430 #'(lambda (x)
431 (make-term :monom (term-monom x)
432 :coeff (funcall (ring-div ring) (term-coeff x) c)))
433 (poly-termlist p))
434 (poly-sugar p))
435 c))))
436
437(defun poly-content (ring p)
438 "Greatest common divisor of the coefficients of the polynomial P. Use the RING structure
439to compute the greatest common divisor."
440 (declare (type ring ring) (type poly p))
441 (reduce (ring-gcd ring) (mapcar #'term-coeff (rest (poly-termlist p))) :initial-value (poly-lc p)))
442
443(defun read-infix-form (&key (stream t))
444 "Parser of infix expressions with integer/rational coefficients
445The parser will recognize two kinds of polynomial expressions:
446
447- polynomials in fully expanded forms with coefficients
448 written in front of symbolic expressions; constants can be optionally
449 enclosed in (); for example, the infix form
450 X^2-Y^2+(-4/3)*U^2*W^3-5
451 parses to
452 (+ (- (EXPT X 2) (EXPT Y 2)) (* (- (/ 4 3)) (EXPT U 2) (EXPT W 3)) (- 5))
453
454- lists of polynomials; for example
455 [X-Y, X^2+3*Z]
456 parses to
457 (:[ (- X Y) (+ (EXPT X 2) (* 3 Z)))
458 where the first symbol [ marks a list of polynomials.
459
460-other infix expressions, for example
461 [(X-Y)*(X+Y)/Z,(X+1)^2]
462parses to:
463 (:[ (/ (* (- X Y) (+ X Y)) Z) (EXPT (+ X 1) 2))
464Currently this function is implemented using M. Kantrowitz's INFIX package."
465 (read-from-string
466 (concatenate 'string
467 "#I("
468 (with-output-to-string (s)
469 (loop
470 (multiple-value-bind (line eof)
471 (read-line stream t)
472 (format s "~A" line)
473 (when eof (return)))))
474 ")")))
475
476(defun read-poly (vars &key
477 (stream t)
478 (ring +ring-of-integers+)
479 (order #'lex>))
480 "Reads an expression in prefix form from a stream STREAM.
481The expression read from the strem should represent a polynomial or a
482list of polynomials in variables VARS, over the ring RING. The
483polynomial or list of polynomials is returned, with terms in each
484polynomial ordered according to monomial order ORDER."
485 (poly-eval (read-infix-form :stream stream) vars ring order))
486
487(defun string->poly (str vars
488 &optional
489 (ring +ring-of-integers+)
490 (order #'lex>))
491 "Converts a string STR to a polynomial in variables VARS."
492 (with-input-from-string (s str)
493 (read-poly vars :stream s :ring ring :order order)))
494
495(defun poly->alist (p)
496 "Convert a polynomial P to an association list. Thus, the format of the
497returned value is ((MONOM[0] . COEFF[0]) (MONOM[1] . COEFF[1]) ...), where
498MONOM[I] is a list of exponents in the monomial and COEFF[I] is the
499corresponding coefficient in the ring."
500 (cond
501 ((poly-p p)
502 (mapcar #'term->cons (poly-termlist p)))
503 ((and (consp p) (eq (car p) :[))
504 (cons :[ (mapcar #'poly->alist (cdr p))))))
505
506(defun string->alist (str vars
507 &optional
508 (ring +ring-of-integers+)
509 (order #'lex>))
510 "Convert a string STR representing a polynomial or polynomial list to
511an association list (... (MONOM . COEFF) ...)."
512 (poly->alist (string->poly str vars ring order)))
513
514(defun poly-equal-no-sugar-p (p q)
515 "Compare polynomials for equality, ignoring sugar."
516 (declare (type poly p q))
517 (equalp (poly-termlist p) (poly-termlist q)))
518
519(defun poly-set-equal-no-sugar-p (p q)
520 "Compare polynomial sets P and Q for equality, ignoring sugar."
521 (null (set-exclusive-or p q :test #'poly-equal-no-sugar-p )))
522
523(defun poly-list-equal-no-sugar-p (p q)
524 "Compare polynomial lists P and Q for equality, ignoring sugar."
525 (every #'poly-equal-no-sugar-p p q))
526|#
Note: See TracBrowser for help on using the repository browser.