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

Last change on this file since 3868 was 3868, 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#|
136(defmethod update-instance-for-different-class :before ((old monom) (new poly) &key)
137 "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST."
138 (reinitialize-instance new
139 :dimension (monom-dimension old)
140 :termlist (list (change-class old 'term))))
141|#
142
143(defmethod universal-equalp ((self poly) (other poly))
144 "Implements equality of polynomials."
145 (and (eql (poly-dimension self) (poly-dimension other))
146 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
147 (eq (poly-term-order self) (poly-term-order other))))
148
149(defgeneric leading-term (object)
150 (:method ((self poly))
151 (car (poly-termlist self)))
152 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
153
154(defgeneric second-leading-term (object)
155 (:method ((self poly))
156 (cadar (poly-termlist self)))
157 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
158
159(defgeneric leading-monomial (object)
160 (:method ((self poly))
161 (change-class (copy-instance (leading-term self)) 'monom))
162 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
163
164(defgeneric second-leading-monomial (object)
165 (:method ((self poly))
166 (change-class (copy-instance (second-leading-term self)) 'monom))
167 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
168
169(defgeneric leading-coefficient (object)
170 (:method ((self poly))
171 (term-coeff (leading-term self)))
172 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
173
174(defgeneric second-leading-coefficient (object)
175 (:method ((self poly))
176 (term-coeff (second-leading-term self)))
177 (:documentation "The second leading coefficient of a polynomial. It
178 signals error for a polynomial with at most one term."))
179
180(defmethod universal-zerop ((self poly))
181 "Return T iff SELF is a zero polynomial."
182 (null (poly-termlist self)))
183
184(defgeneric poly-length (self)
185 (:documentation "Return the number of terms.")
186 (:method ((self poly))
187 (length (poly-termlist self))))
188
189(defgeneric scalar-multiply-by (self other)
190 (:documentation "Multiply vector SELF by a scalar OTHER.")
191 (:method ((self poly) other)
192 (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other)))
193 (poly-termlist self))
194 self))
195
196(defgeneric scalar-divide-by (self other)
197 (:documentation "Divide vector SELF by a scalar OTHER.")
198 (:method ((self poly) other)
199 (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other)))
200 (poly-termlist self))
201 self))
202
203(defmethod multiply-by ((self poly) (other monom))
204 "Multiply a polynomial SELF by OTHER."
205 (mapc #'(lambda (term) (multiply-by term other))
206 (poly-termlist self))
207 self)
208
209(defmethod multiply-by ((self poly) (other term))
210 "Multiply a polynomial SELF by OTHER."
211 (mapc #'(lambda (term) (multiply-by term other))
212 (poly-termlist self))
213 self)
214
215(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
216 "Return an expression which will efficiently adds/subtracts two
217polynomials, P and Q. The addition/subtraction of coefficients is
218performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME
219is supplied, it is used to negate the coefficients of Q which do not
220have a corresponding coefficient in P. The code implements an
221efficient algorithm to add two polynomials represented as sorted lists
222of terms. The code destroys both arguments, reusing the terms to build
223the result."
224 `(macrolet ((lc (x) `(term-coeff (car ,x))))
225 (do ((p ,p)
226 (q ,q)
227 r)
228 ((or (endp p) (endp q))
229 ;; NOTE: R contains the result in reverse order. Can it
230 ;; be more efficient to produce the terms in correct order?
231 (unless (endp q)
232 ;; Upon subtraction, we must change the sign of
233 ;; all coefficients in q
234 ,@(when uminus-fn
235 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
236 (setf r (nreconc r q)))
237 r)
238 (multiple-value-bind
239 (greater-p equal-p)
240 (funcall ,order-fn (car p) (car q))
241 (cond
242 (greater-p
243 (rotatef (cdr p) r p)
244 )
245 (equal-p
246 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
247 (cond
248 ((universal-zerop s)
249 (setf p (cdr p))
250 )
251 (t
252 (setf (lc p) s)
253 (rotatef (cdr p) r p))))
254 (setf q (cdr q))
255 )
256 (t
257 ;;Negate the term of Q if UMINUS provided, signallig
258 ;;that we are doing subtraction
259 ,(when uminus-fn
260 `(setf (lc q) (funcall ,uminus-fn (lc q))))
261 (rotatef (cdr q) r q)))))))
262
263
264(defgeneric add-to (self other)
265 (:documentation "Add OTHER to SELF.")
266 (:method ((self number) (other number))
267 (+ self other))
268 (:method ((self poly) (other number))
269 (add-to self (make-poly-constant (poly-dimension self) other)))
270 (:method ((self number) (other poly))
271 (add-to (make-poly-constant (poly-dimension other) self) other)))
272
273
274(defgeneric subtract-from (self other)
275 (:documentation "Subtract OTHER from SELF.")
276 (:method ((self number) (other number))
277 (- self other))
278 (:method ((self poly) (other number))
279 (subtract-from self (make-poly-constant (poly-dimension self) other))))
280
281(defmacro def-add/subtract-method (add/subtract-method-name
282 uminus-method-name
283 &optional
284 (doc-string nil doc-string-supplied-p))
285 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
286 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
287 ,@(when doc-string-supplied-p `(,doc-string))
288 ;; Ensure orders are compatible
289 (change-term-order other self)
290 (setf (poly-termlist self) (fast-add/subtract
291 (poly-termlist self) (poly-termlist other)
292 (poly-term-order self)
293 #',add/subtract-method-name
294 ,(when uminus-method-name `(function ,uminus-method-name))))
295 self))
296
297(eval-when (:load-toplevel :execute)
298
299 (def-add/subtract-method add-to nil
300 "Adds to polynomial SELF another polynomial OTHER.
301This operation destructively modifies both polynomials.
302The result is stored in SELF. This implementation does
303no consing, entirely reusing the sells of SELF and OTHER.")
304
305 (def-add/subtract-method subtract-from unary-minus
306 "Subtracts from polynomial SELF another polynomial OTHER.
307This operation destructively modifies both polynomials.
308The result is stored in SELF. This implementation does
309no consing, entirely reusing the sells of SELF and OTHER.")
310 )
311
312(defmethod unary-minus ((self poly))
313 "Destructively modifies the coefficients of the polynomial SELF,
314by changing their sign."
315 (mapc #'unary-minus (poly-termlist self))
316 self)
317
318(defun add-termlists (p q order-fn)
319 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
320 (fast-add/subtract p q order-fn #'add-to nil))
321
322(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
323 &optional (reverse-arg-order-P nil))
324 "Multiplies term TERM by a list of term, TERMLIST.
325Takes into accound divisors of zero in the ring, by
326deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
327is T, change the order of arguments; this may be important
328if we extend the package to non-commutative rings."
329 `(mapcan #'(lambda (other-term)
330 (let ((prod (multiply
331 ,@(cond
332 (reverse-arg-order-p
333 `(other-term ,term))
334 (t
335 `(,term other-term))))))
336 (cond
337 ((universal-zerop prod) nil)
338 (t (list prod)))))
339 ,termlist))
340
341(defun multiply-termlists (p q order-fn)
342 "A version of polynomial multiplication, operating
343directly on termlists."
344 (cond
345 ((or (endp p) (endp q))
346 ;;p or q is 0 (represented by NIL)
347 nil)
348 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
349 ((endp (cdr p))
350 (multiply-term-by-termlist-dropping-zeros (car p) q))
351 ((endp (cdr q))
352 (multiply-term-by-termlist-dropping-zeros (car q) p t))
353 (t
354 (cons (multiply (car p) (car q))
355 (add-termlists
356 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
357 (multiply-termlists (cdr p) q order-fn)
358 order-fn)))))
359
360(defmethod multiply-by ((self poly) (other poly))
361 (change-term-order other self)
362 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
363 (poly-termlist other)
364 (poly-term-order self)))
365 self)
366
367(defgeneric add-2 (object1 object2)
368 (:documentation "Non-destructively add OBJECT1 to OBJECT2.")
369 (:method ((object1 t) (object2 t))
370 (add-to (copy-instance object1) (copy-instance object2))))
371
372(defun add (&rest summands)
373 "Non-destructively adds list SUMMANDS."
374 (cond ((endp summands) 0)
375 (t (reduce #'add-2 summands))))
376
377(defun subtract (minuend &rest subtrahends)
378 "Non-destructively subtract MINUEND and SUBTRAHENDS."
379 (cond ((endp subtrahends) (unary-minus minuend))
380 (t (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))))
381
382(defmethod left-tensor-product-by ((self poly) (other monom))
383 (setf (poly-termlist self)
384 (mapcan #'(lambda (term)
385 (let ((prod (left-tensor-product-by term other)))
386 (cond
387 ((universal-zerop prod) nil)
388 (t (list prod)))))
389 (poly-termlist self)))
390 (incf (poly-dimension self) (monom-dimension other))
391 self)
392
393(defmethod right-tensor-product-by ((self poly) (other monom))
394 (setf (poly-termlist self)
395 (mapcan #'(lambda (term)
396 (let ((prod (right-tensor-product-by term other)))
397 (cond
398 ((universal-zerop prod) nil)
399 (t (list prod)))))
400 (poly-termlist self)))
401 (incf (poly-dimension self) (monom-dimension other))
402 self)
403
404
405(defun standard-extension (plist &aux (k (length plist)) (i 0))
406 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
407is a list of polynomials. Destructively modifies PLIST elements."
408 (mapc #'(lambda (poly)
409 (left-tensor-product-by
410 poly
411 (prog1
412 (make-monom-variable k i)
413 (incf i))))
414 plist))
415
416(defun standard-extension-1 (plist
417 &aux
418 (plist (standard-extension plist))
419 (nvars (poly-dimension (car plist))))
420 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
421Firstly, new K variables U1, U2, ..., UK, are inserted into each
422polynomial. Subsequently, P1, P2, ..., PK are destructively modified
423tantamount to replacing PI with UI*PI-1. It assumes that all
424polynomials have the same dimension, and only the first polynomial
425is examined to determine this dimension."
426 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
427 ;; 1 from each polynomial; since UI*PI has no constant term,
428 ;; we just need to append the constant term at the end
429 ;; of each termlist.
430 (flet ((subtract-1 (p)
431 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
432 (setf plist (mapc #'subtract-1 plist)))
433 plist)
434
435
436(defun standard-sum (plist
437 &aux
438 (plist (standard-extension plist))
439 (nvars (poly-dimension (car plist))))
440 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
441Firstly, new K variables, U1, U2, ..., UK, are inserted into each
442polynomial. Subsequently, P1, P2, ..., PK are destructively modified
443tantamount to replacing PI with UI*PI, and the resulting polynomials
444are added. Finally, 1 is subtracted. It should be noted that the term
445order is not modified, which is equivalent to using a lexicographic
446order on the first K variables."
447 (flet ((subtract-1 (p)
448 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
449 (subtract-1
450 (make-instance
451 'poly
452 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
453
454(defgeneric universal-ezgcd (x y)
455 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
456C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
457the Euclidean algorithm.")
458 (:method ((x integer) (y integer)
459 &aux (c (gcd x y)))
460 (values c (/ x c) (/ y c)))
461 )
462
463(defgeneric s-polynomial (object1 object2)
464 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
465 (:method ((f poly) (g poly))
466 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
467 (mf (divide lcm (leading-monomial f)))
468 (mg (divide lcm (leading-monomial g))))
469 (multiple-value-bind (c cf cg)
470 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
471 (declare (ignore c))
472 (subtract
473 (multiply f (change-class mf 'term :coeff cg))
474 (multiply g (change-class mg 'term :coeff cf)))))))
475
476(defgeneric poly-content (object)
477 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
478 (:method ((self poly))
479 (reduce #'universal-gcd
480 (mapcar #'term-coeff (rest (poly-termlist self)))
481 :initial-value (leading-coefficient self))))
482
483(defun poly-primitive-part (object)
484 "Divide polynomial OBJECT by gcd of its
485coefficients. Return the resulting polynomial."
486 (scalar-divide-by object (poly-content object)))
487
488(defun poly-insert-variables (self k)
489 (left-tensor-product-by self (make-instance 'monom :dimension k)))
490
491(defun saturation-extension (f plist &aux (k (length plist)))
492 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
493PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
494as first K variables. It destructively modifies F and PLIST."
495 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
496 (standard-extension-1 plist)))
497
498(defun polysaturation-extension (f plist &aux (k (length plist)))
499 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
500and F' is F with variables U1,U2,...,UK inserted as first K
501variables. It destructively modifies F and PLIST."
502 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
503 (list (standard-sum plist))))
504
505(defun saturation-extension-1 (f p)
506 "Given family of polynomials F and a polynomial P, calculate [F',
507U*P-1], where F' is F with variable inserted as the first variable. It
508destructively modifies F and P."
509 (polysaturation-extension f (list p)))
510
511(defmethod multiply-by ((object1 number) (object2 poly))
512 (scalar-multiply-by (copy-instance object2) object1))
513
514(defun make-poly-variable (nvars pos &optional (power 1))
515 (change-class (make-monom-variable nvars pos power) 'poly))
516
517(defun make-poly-constant (nvars coeff)
518 (change-class (make-term-constant nvars coeff) 'poly))
519
520(defgeneric universal-expt (x y)
521 (:documentation "Raises X to power Y.")
522 (:method ((x number) (y integer)) (expt x y))
523 (:method ((x t) (y integer))
524 (declare (type fixnum y))
525 (cond
526 ((minusp y) (error "universal-expt: Negative exponent."))
527 ((universal-zerop x) (if (zerop y) 1))
528 (t
529 (do ((k 1 (ash k 1))
530 (q x (multiply q q)) ;keep squaring
531 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
532 ((> k y) p)
533 (declare (fixnum k)))))))
534
535(defgeneric poly-p (object)
536 (:documentation "Checks if an object is a polynomial.")
537 (:method ((self poly)) t)
538 (:method ((self t)) nil))
539
540(defmethod ->infix ((self poly) &optional vars)
541 (cons '+ (mapcar #'(lambda (x) (->infix x vars))
542 (poly-termlist self))))
543
Note: See TracBrowser for help on using the repository browser.