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

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