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

Last change on this file since 3010 was 3010, checked in by Marek Rychlik, 10 years ago

* empty log message *

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