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

Last change on this file since 3869 was 3869, checked in by Marek Rychlik, 8 years ago

* empty log message *

File size: 19.8 KB
Line 
1;;----------------------------------------------------------------
2;;; -*- Mode: Lisp -*-
3;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4;;;
5;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik <rychlik@u.arizona.edu>
6;;;
7;;; This program is free software; you can redistribute it and/or modify
8;;; it under the terms of the GNU General Public License as published by
9;;; the Free Software Foundation; either version 2 of the License, or
10;;; (at your option) any later version.
11;;;
12;;; This program is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with this program; if not, write to the Free Software
19;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20;;;
21;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22
23(defpackage "POLYNOMIAL"
24 (:use :cl :utils :monom :copy)
25 (:export "POLY"
26 "POLY-DIMENSION"
27 "POLY-TERMLIST"
28 "POLY-TERM-ORDER"
29 "POLY-INSERT-TERM"
30 "SCALAR-MULTIPLY-BY"
31 "SCALAR-DIVIDE-BY"
32 "LEADING-TERM"
33 "LEADING-MONOMIAL"
34 "LEADING-COEFFICIENT"
35 "SECOND-LEADING-TERM"
36 "SECOND-LEADING-MONOMIAL"
37 "SECOND-LEADING-COEFFICIENT"
38 "ADD-TO"
39 "ADD"
40 "SUBTRACT-FROM"
41 "SUBTRACT"
42 "CHANGE-TERM-ORDER"
43 "STANDARD-EXTENSION"
44 "STANDARD-EXTENSION-1"
45 "STANDARD-SUM"
46 "SATURATION-EXTENSION"
47 "ALIST->POLY"
48 "->INFIX"
49 "UNIVERSAL-EZGCD"
50 "S-POLYNOMIAL"
51 "POLY-CONTENT"
52 "POLY-PRIMITIVE-PART"
53 "SATURATION-EXTENSION-1"
54 "MAKE-POLY-VARIABLE"
55 "MAKE-POLY-CONSTANT"
56 "UNIVERSAL-EXPT"
57 "POLY-P")
58 (:documentation "Implements polynomials. A polynomial is essentially
59a mapping of monomials of the same degree to coefficients. The
60momomials are ordered according to a monomial order."))
61
62(in-package :polynomial)
63
64(proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0)))
65
66(defclass poly ()
67 ((dimension :initform nil
68 :initarg :dimension
69 :accessor poly-dimension
70 :documentation "Shared dimension of all terms, the number of variables")
71 (termlist :initform nil :initarg :termlist :accessor poly-termlist
72 :documentation "List of terms.")
73 (order :initform #'lex> :initarg :order :accessor poly-term-order
74 :documentation "Monomial/term order."))
75 (:default-initargs :dimension nil :termlist nil :order #'lex>)
76 (:documentation "A polynomial with a list of terms TERMLIST, ordered
77according to term order ORDER, which defaults to LEX>."))
78
79(defmethod print-object ((self poly) stream)
80 (print-unreadable-object (self stream :type t :identity t)
81 (with-accessors ((dimension poly-dimension)
82 (termlist poly-termlist)
83 (order poly-term-order))
84 self
85 (format stream "DIMENSION=~A TERMLIST=~A ORDER=~A"
86 dimension termlist order))))
87
88(defgeneric change-term-order (self other)
89 (:documentation "Change term order of SELF to the term order of OTHER.")
90 (:method ((self poly) (other poly))
91 (unless (eq (poly-term-order self) (poly-term-order other))
92 (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other))
93 (poly-term-order self) (poly-term-order other)))
94 self))
95
96(defgeneric poly-insert-term (self term)
97 (:documentation "Insert a term TERM into SELF before all other
98 terms. Order is not enforced.")
99 (:method ((self poly) (term term))
100 (cond ((null (poly-dimension self))
101 (setf (poly-dimension self) (monom-dimension term)))
102 (t (assert (= (poly-dimension self) (monom-dimension term)))))
103 (push term (poly-termlist self))
104 self))
105
106(defgeneric poly-append-term (self term)
107 (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.")
108 (:method ((self poly) (term term))
109 (cond ((null (poly-dimension self))
110 (setf (poly-dimension self) (monom-dimension term)))
111 (t (assert (= (poly-dimension self) (monom-dimension term)))))
112 (setf (cdr (last (poly-termlist self))) (list term))
113 self))
114
115(defun alist->poly (alist &aux (poly (make-instance 'poly)))
116 "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...).
117It can be used to enter simple polynomials by hand, e.g the polynomial
118in two variables, X and Y, given in standard notation as:
119
120 3*X^2*Y^3+2*Y+7
121
122can be entered as
123(ALIST->POLY '(((2 3) . 3) ((0 1) . 2) ((0 0) . 7))).
124
125NOTE: The primary use is for low-level debugging of the package."
126 (dolist (x alist poly)
127 (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x)))))
128
129(defmethod update-instance-for-different-class :before ((old term) (new poly) &key)
130 "Converts OLD of class TERM to a NEW of class POLY, by making it into a 1-element TERMLIST."
131 (reinitialize-instance new
132 :dimension (monom-dimension old)
133 :termlist (list old)))
134
135(defmethod update-instance-for-different-class :before ((old monom) (new poly) &key)
136 "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST."
137 (reinitialize-instance new
138 :dimension (monom-dimension old)
139 :termlist (list (change-class old 'term))))
140
141(defmethod universal-equalp ((self poly) (other poly))
142 "Implements equality of polynomials."
143 (and (eql (poly-dimension self) (poly-dimension other))
144 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
145 (eq (poly-term-order self) (poly-term-order other))))
146
147(defgeneric leading-term (object)
148 (:method ((self poly))
149 (car (poly-termlist self)))
150 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
151
152(defgeneric second-leading-term (object)
153 (:method ((self poly))
154 (cadar (poly-termlist self)))
155 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
156
157(defgeneric leading-monomial (object)
158 (:method ((self poly))
159 (change-class (copy-instance (leading-term self)) 'monom))
160 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
161
162(defgeneric second-leading-monomial (object)
163 (:method ((self poly))
164 (change-class (copy-instance (second-leading-term self)) 'monom))
165 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
166
167(defgeneric leading-coefficient (object)
168 (:method ((self poly))
169 (term-coeff (leading-term self)))
170 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
171
172(defgeneric second-leading-coefficient (object)
173 (:method ((self poly))
174 (term-coeff (second-leading-term self)))
175 (:documentation "The second leading coefficient of a polynomial. It
176 signals error for a polynomial with at most one term."))
177
178(defmethod universal-zerop ((self poly))
179 "Return T iff SELF is a zero polynomial."
180 (null (poly-termlist self)))
181
182(defgeneric poly-length (self)
183 (:documentation "Return the number of terms.")
184 (:method ((self poly))
185 (length (poly-termlist self))))
186
187(defgeneric scalar-multiply-by (self other)
188 (:documentation "Multiply vector SELF by a scalar OTHER.")
189 (:method ((self poly) other)
190 (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other)))
191 (poly-termlist self))
192 self))
193
194(defgeneric scalar-divide-by (self other)
195 (:documentation "Divide vector SELF by a scalar OTHER.")
196 (:method ((self poly) other)
197 (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other)))
198 (poly-termlist self))
199 self))
200
201(defmethod multiply-by ((self poly) (other monom))
202 "Multiply a polynomial SELF by OTHER."
203 (mapc #'(lambda (term) (multiply-by term other))
204 (poly-termlist self))
205 self)
206
207(defmethod multiply-by ((self poly) (other term))
208 "Multiply a polynomial SELF by OTHER."
209 (mapc #'(lambda (term) (multiply-by term other))
210 (poly-termlist self))
211 self)
212
213(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
214 "Return an expression which will efficiently adds/subtracts two
215polynomials, P and Q. The addition/subtraction of coefficients is
216performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME
217is supplied, it is used to negate the coefficients of Q which do not
218have a corresponding coefficient in P. The code implements an
219efficient algorithm to add two polynomials represented as sorted lists
220of terms. The code destroys both arguments, reusing the terms to build
221the result."
222 `(macrolet ((lc (x) `(term-coeff (car ,x))))
223 (do ((p ,p)
224 (q ,q)
225 r)
226 ((or (endp p) (endp q))
227 ;; NOTE: R contains the result in reverse order. Can it
228 ;; be more efficient to produce the terms in correct order?
229 (unless (endp q)
230 ;; Upon subtraction, we must change the sign of
231 ;; all coefficients in q
232 ,@(when uminus-fn
233 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
234 (setf r (nreconc r q)))
235 r)
236 (multiple-value-bind
237 (greater-p equal-p)
238 (funcall ,order-fn (car p) (car q))
239 (cond
240 (greater-p
241 (rotatef (cdr p) r p)
242 )
243 (equal-p
244 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
245 (cond
246 ((universal-zerop s)
247 (setf p (cdr p))
248 )
249 (t
250 (setf (lc p) s)
251 (rotatef (cdr p) r p))))
252 (setf q (cdr q))
253 )
254 (t
255 ;;Negate the term of Q if UMINUS provided, signallig
256 ;;that we are doing subtraction
257 ,(when uminus-fn
258 `(setf (lc q) (funcall ,uminus-fn (lc q))))
259 (rotatef (cdr q) r q)))))))
260
261
262(defgeneric add-to (self other)
263 (:documentation "Add OTHER to SELF.")
264 (:method ((self number) (other number))
265 (+ self other))
266 (:method ((self poly) (other number))
267 (add-to self (make-poly-constant (poly-dimension self) other)))
268 (:method ((self number) (other poly))
269 (add-to (make-poly-constant (poly-dimension other) self) other)))
270
271
272(defgeneric subtract-from (self other)
273 (:documentation "Subtract OTHER from SELF.")
274 (:method ((self number) (other number))
275 (- self other))
276 (:method ((self poly) (other number))
277 (subtract-from self (make-poly-constant (poly-dimension self) other))))
278
279(defmacro def-add/subtract-method (add/subtract-method-name
280 uminus-method-name
281 &optional
282 (doc-string nil doc-string-supplied-p))
283 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
284 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
285 ,@(when doc-string-supplied-p `(,doc-string))
286 ;; Ensure orders are compatible
287 (change-term-order other self)
288 (setf (poly-termlist self) (fast-add/subtract
289 (poly-termlist self) (poly-termlist other)
290 (poly-term-order self)
291 #',add/subtract-method-name
292 ,(when uminus-method-name `(function ,uminus-method-name))))
293 self))
294
295(eval-when (:load-toplevel :execute)
296
297 (def-add/subtract-method add-to nil
298 "Adds to polynomial SELF another polynomial OTHER.
299This operation destructively modifies both polynomials.
300The result is stored in SELF. This implementation does
301no consing, entirely reusing the sells of SELF and OTHER.")
302
303 (def-add/subtract-method subtract-from unary-minus
304 "Subtracts from polynomial SELF another polynomial OTHER.
305This operation destructively modifies both polynomials.
306The result is stored in SELF. This implementation does
307no consing, entirely reusing the sells of SELF and OTHER.")
308 )
309
310(defmethod unary-minus ((self poly))
311 "Destructively modifies the coefficients of the polynomial SELF,
312by changing their sign."
313 (mapc #'unary-minus (poly-termlist self))
314 self)
315
316(defun add-termlists (p q order-fn)
317 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
318 (fast-add/subtract p q order-fn #'add-to nil))
319
320(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
321 &optional (reverse-arg-order-P nil))
322 "Multiplies term TERM by a list of term, TERMLIST.
323Takes into accound divisors of zero in the ring, by
324deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
325is T, change the order of arguments; this may be important
326if we extend the package to non-commutative rings."
327 `(mapcan #'(lambda (other-term)
328 (let ((prod (multiply
329 ,@(cond
330 (reverse-arg-order-p
331 `(other-term ,term))
332 (t
333 `(,term other-term))))))
334 (cond
335 ((universal-zerop prod) nil)
336 (t (list prod)))))
337 ,termlist))
338
339(defun multiply-termlists (p q order-fn)
340 "A version of polynomial multiplication, operating
341directly on termlists."
342 (cond
343 ((or (endp p) (endp q))
344 ;;p or q is 0 (represented by NIL)
345 nil)
346 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
347 ((endp (cdr p))
348 (multiply-term-by-termlist-dropping-zeros (car p) q))
349 ((endp (cdr q))
350 (multiply-term-by-termlist-dropping-zeros (car q) p t))
351 (t
352 (cons (multiply (car p) (car q))
353 (add-termlists
354 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
355 (multiply-termlists (cdr p) q order-fn)
356 order-fn)))))
357
358(defmethod multiply-by ((self poly) (other poly))
359 (change-term-order other self)
360 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
361 (poly-termlist other)
362 (poly-term-order self)))
363 self)
364
365(defgeneric add-2 (object1 object2)
366 (:documentation "Non-destructively add OBJECT1 to OBJECT2.")
367 (:method ((object1 t) (object2 t))
368 (add-to (copy-instance object1) (copy-instance object2))))
369
370(defun add (&rest summands)
371 "Non-destructively adds list SUMMANDS."
372 (cond ((endp summands) 0)
373 (t (reduce #'add-2 summands))))
374
375(defun subtract (minuend &rest subtrahends)
376 "Non-destructively subtract MINUEND and SUBTRAHENDS."
377 (cond ((endp subtrahends) (unary-minus minuend))
378 (t (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))))
379
380(defmethod left-tensor-product-by ((self poly) (other monom))
381 (setf (poly-termlist self)
382 (mapcan #'(lambda (term)
383 (let ((prod (left-tensor-product-by term other)))
384 (cond
385 ((universal-zerop prod) nil)
386 (t (list prod)))))
387 (poly-termlist self)))
388 (incf (poly-dimension self) (monom-dimension other))
389 self)
390
391(defmethod right-tensor-product-by ((self poly) (other monom))
392 (setf (poly-termlist self)
393 (mapcan #'(lambda (term)
394 (let ((prod (right-tensor-product-by term other)))
395 (cond
396 ((universal-zerop prod) nil)
397 (t (list prod)))))
398 (poly-termlist self)))
399 (incf (poly-dimension self) (monom-dimension other))
400 self)
401
402
403(defun standard-extension (plist &aux (k (length plist)) (i 0))
404 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
405is a list of polynomials. Destructively modifies PLIST elements."
406 (mapc #'(lambda (poly)
407 (left-tensor-product-by
408 poly
409 (prog1
410 (make-monom-variable k i)
411 (incf i))))
412 plist))
413
414(defun standard-extension-1 (plist
415 &aux
416 (plist (standard-extension plist))
417 (nvars (poly-dimension (car plist))))
418 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
419Firstly, new K variables U1, U2, ..., UK, are inserted into each
420polynomial. Subsequently, P1, P2, ..., PK are destructively modified
421tantamount to replacing PI with UI*PI-1. It assumes that all
422polynomials have the same dimension, and only the first polynomial
423is examined to determine this dimension."
424 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
425 ;; 1 from each polynomial; since UI*PI has no constant term,
426 ;; we just need to append the constant term at the end
427 ;; of each termlist.
428 (flet ((subtract-1 (p)
429 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
430 (setf plist (mapc #'subtract-1 plist)))
431 plist)
432
433
434(defun standard-sum (plist
435 &aux
436 (plist (standard-extension plist))
437 (nvars (poly-dimension (car plist))))
438 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
439Firstly, new K variables, U1, U2, ..., UK, are inserted into each
440polynomial. Subsequently, P1, P2, ..., PK are destructively modified
441tantamount to replacing PI with UI*PI, and the resulting polynomials
442are added. Finally, 1 is subtracted. It should be noted that the term
443order is not modified, which is equivalent to using a lexicographic
444order on the first K variables."
445 (flet ((subtract-1 (p)
446 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
447 (subtract-1
448 (make-instance
449 'poly
450 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
451
452(defgeneric universal-ezgcd (x y)
453 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
454C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
455the Euclidean algorithm.")
456 (:method ((x integer) (y integer)
457 &aux (c (gcd x y)))
458 (values c (/ x c) (/ y c)))
459 )
460
461(defgeneric s-polynomial (object1 object2)
462 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
463 (:method ((f poly) (g poly))
464 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
465 (mf (divide lcm (leading-monomial f)))
466 (mg (divide lcm (leading-monomial g))))
467 (multiple-value-bind (c cf cg)
468 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
469 (declare (ignore c))
470 (subtract
471 (multiply f (change-class mf 'term :coeff cg))
472 (multiply g (change-class mg 'term :coeff cf)))))))
473
474(defgeneric poly-content (object)
475 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
476 (:method ((self poly))
477 (reduce #'universal-gcd
478 (mapcar #'term-coeff (rest (poly-termlist self)))
479 :initial-value (leading-coefficient self))))
480
481(defun poly-primitive-part (object)
482 "Divide polynomial OBJECT by gcd of its
483coefficients. Return the resulting polynomial."
484 (scalar-divide-by object (poly-content object)))
485
486(defun poly-insert-variables (self k)
487 (left-tensor-product-by self (make-instance 'monom :dimension k)))
488
489(defun saturation-extension (f plist &aux (k (length plist)))
490 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
491PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
492as first K variables. It destructively modifies F and PLIST."
493 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
494 (standard-extension-1 plist)))
495
496(defun polysaturation-extension (f plist &aux (k (length plist)))
497 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
498and F' is F with variables U1,U2,...,UK inserted as first K
499variables. It destructively modifies F and PLIST."
500 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
501 (list (standard-sum plist))))
502
503(defun saturation-extension-1 (f p)
504 "Given family of polynomials F and a polynomial P, calculate [F',
505U*P-1], where F' is F with variable inserted as the first variable. It
506destructively modifies F and P."
507 (polysaturation-extension f (list p)))
508
509(defmethod multiply-by ((object1 number) (object2 poly))
510 (scalar-multiply-by (copy-instance object2) object1))
511
512(defun make-poly-variable (nvars pos &optional (power 1))
513 (change-class (make-monom-variable nvars pos power) 'poly))
514
515(defun make-poly-constant (nvars coeff)
516 (change-class (make-term-constant nvars coeff) 'poly))
517
518(defgeneric universal-expt (x y)
519 (:documentation "Raises X to power Y.")
520 (:method ((x number) (y integer)) (expt x y))
521 (:method ((x t) (y integer))
522 (declare (type fixnum y))
523 (cond
524 ((minusp y) (error "universal-expt: Negative exponent."))
525 ((universal-zerop x) (if (zerop y) 1))
526 (t
527 (do ((k 1 (ash k 1))
528 (q x (multiply q q)) ;keep squaring
529 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
530 ((> k y) p)
531 (declare (fixnum k)))))))
532
533(defgeneric poly-p (object)
534 (:documentation "Checks if an object is a polynomial.")
535 (:method ((self poly)) t)
536 (:method ((self t)) nil))
537
538(defmethod ->infix ((self poly) &optional vars)
539 (cons '+ (mapcar #'(lambda (x) (->infix x vars))
540 (poly-termlist self))))
541
Note: See TracBrowser for help on using the repository browser.