;;---------------------------------------------------------------- ;; File: polynomial.lisp ;;---------------------------------------------------------------- ;; ;; Author: Marek Rychlik (rychlik@u.arizona.edu) ;; Date: Thu Aug 27 09:41:24 2015 ;; Copying: (C) Marek Rychlik, 2010. All rights reserved. ;; ;;---------------------------------------------------------------- ;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Copyright (C) 1999, 2002, 2009, 2015 Marek Rychlik ;;; ;;; This program is free software; you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 2 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program; if not, write to the Free Software ;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage "POLYNOMIAL" (:use :cl :utils :monom :copy) (:export "POLY" "POLY-DIMENSION" "POLY-TERMLIST" "POLY-TERM-ORDER" "POLY-INSERT-TERM" "LEADING-TERM" "LEADING-MONOMIAL" "LEADING-COEFFICIENT" "SECOND-LEADING-TERM" "SECOND-LEADING-MONOMIAL" "SECOND-LEADING-COEFFICIENT" "ADD-TO" "ADD" "SUBTRACT-FROM" "SUBTRACT" "CHANGE-TERM-ORDER" "STANDARD-EXTENSION" "STANDARD-EXTENSION-1" "STANDARD-SUM" "SATURATION-EXTENSION" "ALIST->POLY" "UNIVERSAL-EZGCD" "S-POLYNOMIAL") (:documentation "Implements polynomials. A polynomial is essentially a mapping of monomials of the same degree to coefficients. The momomials are ordered according to a monomial order.")) (in-package :polynomial) (proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0))) (defclass poly () ((dimension :initform nil :initarg :dimension :accessor poly-dimension :documentation "Shared dimension of all terms, the number of variables") (termlist :initform nil :initarg :termlist :accessor poly-termlist :documentation "List of terms.") (order :initform #'lex> :initarg :order :accessor poly-term-order :documentation "Monomial/term order.")) (:default-initargs :dimension nil :termlist nil :order #'lex>) (:documentation "A polynomial with a list of terms TERMLIST, ordered according to term order ORDER, which defaults to LEX>.")) (defmethod print-object ((self poly) stream) (print-unreadable-object (self stream :type t :identity t) (with-accessors ((dimension poly-dimension) (termlist poly-termlist) (order poly-term-order)) self (format stream "DIMENSION=~A TERMLIST=~A ORDER=~A" dimension termlist order)))) (defgeneric change-term-order (self other) (:documentation "Change term order of SELF to the term order of OTHER.") (:method ((self poly) (other poly)) (unless (eq (poly-term-order self) (poly-term-order other)) (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other)) (poly-term-order self) (poly-term-order other))) self)) (defgeneric poly-insert-term (self term) (:documentation "Insert a term TERM into SELF before all other terms. Order is not enforced.") (:method ((self poly) (term term)) (cond ((null (poly-dimension self)) (setf (poly-dimension self) (monom-dimension term))) (t (assert (= (poly-dimension self) (monom-dimension term))))) (push term (poly-termlist self)) self)) (defgeneric poly-append-term (self term) (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.") (:method ((self poly) (term term)) (cond ((null (poly-dimension self)) (setf (poly-dimension self) (monom-dimension term))) (t (assert (= (poly-dimension self) (monom-dimension term))))) (setf (cdr (last (poly-termlist self))) (list term)) self)) (defun alist->poly (alist &aux (poly (make-instance 'poly))) "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...). It can be used to enter simple polynomials by hand, e.g the polynomial in two variables, X and Y, given in standard notation as: 3*X^2*Y^3+2*Y+7 can be entered as (ALIST->POLY '(((2 3) . 3) ((0 1) . 2) ((0 0) . 7))). NOTE: The primary use is for low-level debugging of the package." (dolist (x alist poly) (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x))))) (defmethod update-instance-for-different-class :after ((old monom) (new poly) &key) "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST." (reinitialize-instance new :dimension (monom-dimension old) :termlist (list (cons old 1)))) (defmethod universal-equalp ((self poly) (other poly)) "Implements equality of polynomials." (and (eql (poly-dimension self) (poly-dimension other)) (every #'universal-equalp (poly-termlist self) (poly-termlist other)) (eq (poly-term-order self) (poly-term-order other)))) (defgeneric leading-term (object) (:method ((self poly)) (car (poly-termlist self))) (:documentation "The leading term of a polynomial, or NIL for zero polynomial.")) (defgeneric second-leading-term (object) (:method ((self poly)) (cadar (poly-termlist self))) (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term.")) (defgeneric leading-monomial (object) (:method ((self poly)) (change-class (copy-instance (leading-term self)) 'monom)) (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial.")) (defgeneric second-leading-monomial (object) (:method ((self poly)) (change-class (copy-instance (second-leading-term self)) 'monom)) (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial.")) (defgeneric leading-coefficient (object) (:method ((self poly)) (term-coeff (leading-term self))) (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial.")) (defgeneric second-leading-coefficient (object) (:method ((self poly)) (term-coeff (second-leading-term self))) (:documentation "The second leading coefficient of a polynomial. It signals error for a polynomial with at most one term.")) (defmethod universal-zerop ((self poly)) "Return T iff SELF is a zero polynomial." (null (poly-termlist self))) (defgeneric poly-length (self) (:documentation "Return the number of terms.") (:method ((self poly)) (length (poly-termlist self)))) (defmethod multiply-by ((self poly) (other monom)) "Multiply a polynomial SELF by OTHER." (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) (defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn) "Return an expression which will efficiently adds/subtracts two polynomials, P and Q. The addition/subtraction of coefficients is performed by calling ADD/SUBTRACT-METHOD-NAME. If UMINUS-METHOD-NAME is supplied, it is used to negate the coefficients of Q which do not have a corresponding coefficient in P. The code implements an efficient algorithm to add two polynomials represented as sorted lists of terms. The code destroys both arguments, reusing the terms to build the result." `(macrolet ((lc (x) `(term-coeff (car ,x)))) (do ((p ,p) (q ,q) r) ((or (endp p) (endp q)) ;; NOTE: R contains the result in reverse order. Can it ;; be more efficient to produce the terms in correct order? (unless (endp q) ;; Upon subtraction, we must change the sign of ;; all coefficients in q ,@(when uminus-fn `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q))) (setf r (nreconc r q))) r) (multiple-value-bind (greater-p equal-p) (funcall ,order-fn (car p) (car q)) (cond (greater-p (rotatef (cdr p) r p) ) (equal-p (let ((s (funcall ,add/subtract-fn (lc p) (lc q)))) (cond ((universal-zerop s) (setf p (cdr p)) ) (t (setf (lc p) s) (rotatef (cdr p) r p)))) (setf q (cdr q)) ) (t ;;Negate the term of Q if UMINUS provided, signallig ;;that we are doing subtraction ,(when uminus-fn `(setf (lc q) (funcall ,uminus-fn (lc q)))) (rotatef (cdr q) r q))))))) (defgeneric add-to (self other) (:documentation "Add OTHER to SELF.") (:method ((self number) (other number)) (+ self other))) (defgeneric subtract-from (self other) (:documentation "Subtract OTHER from SELF.") (:method ((self number) (other number)) (- self other))) (defmacro def-add/subtract-method (add/subtract-method-name uminus-method-name &optional (doc-string nil doc-string-supplied-p)) "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM." `(defmethod ,add/subtract-method-name ((self poly) (other poly)) ,@(when doc-string-supplied-p `(,doc-string)) ;; Ensure orders are compatible (change-term-order other self) (setf (poly-termlist self) (fast-add/subtract (poly-termlist self) (poly-termlist other) (poly-term-order self) #',add/subtract-method-name ,(when uminus-method-name `(function ,uminus-method-name)))) self)) (eval-when (:compile-toplevel :load-toplevel :execute) (def-add/subtract-method add-to nil "Adds to polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER.") (def-add/subtract-method subtract-from unary-minus "Subtracts from polynomial SELF another polynomial OTHER. This operation destructively modifies both polynomials. The result is stored in SELF. This implementation does no consing, entirely reusing the sells of SELF and OTHER.") ) (defmethod unary-minus ((self poly)) "Destructively modifies the coefficients of the polynomial SELF, by changing their sign." (mapc #'unary-minus (poly-termlist self)) self) (defun add-termlists (p q order-fn) "Destructively adds two termlists P and Q ordered according to ORDER-FN." (fast-add/subtract p q order-fn #'add-to nil)) (defmacro multiply-term-by-termlist-dropping-zeros (term termlist &optional (reverse-arg-order-P nil)) "Multiplies term TERM by a list of term, TERMLIST. Takes into accound divisors of zero in the ring, by deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P is T, change the order of arguments; this may be important if we extend the package to non-commutative rings." `(mapcan #'(lambda (other-term) (let ((prod (multiply ,@(cond (reverse-arg-order-p `(other-term ,term)) (t `(,term other-term)))))) (cond ((universal-zerop prod) nil) (t (list prod))))) ,termlist)) (defun multiply-termlists (p q order-fn) "A version of polynomial multiplication, operating directly on termlists." (cond ((or (endp p) (endp q)) ;;p or q is 0 (represented by NIL) nil) ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q ((endp (cdr p)) (multiply-term-by-termlist-dropping-zeros (car p) q)) ((endp (cdr q)) (multiply-term-by-termlist-dropping-zeros (car q) p t)) (t (cons (multiply (car p) (car q)) (add-termlists (multiply-term-by-termlist-dropping-zeros (car p) (cdr q)) (multiply-termlists (cdr p) q order-fn) order-fn))))) (defmethod multiply-by ((self poly) (other poly)) (change-term-order other self) (setf (poly-termlist self) (multiply-termlists (poly-termlist self) (poly-termlist other) (poly-term-order self))) self) (defun add (object1 object2) "Non-destructively add POLY1 by POLY2." (add-to (copy-instance object1) (copy-instance object2))) (defun subtract (minuend &rest subtrahends) "Non-destructively subtract MINUEND and SUBTRAHENDS." (subtract-from (copy-instance minuend) (reduce #'add subtrahends))) (defmethod left-tensor-product-by ((self poly) (other monom)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (left-tensor-product-by term other))) (cond ((universal-zerop prod) nil) (t (list prod))))) (poly-termlist self))) (incf (poly-dimension self) (monom-dimension other)) self) (defmethod right-tensor-product-by ((self poly) (other monom)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (right-tensor-product-by term other))) (cond ((universal-zerop prod) nil) (t (list prod))))) (poly-termlist self))) (incf (poly-dimension self) (monom-dimension other)) self) (defun standard-extension (plist &aux (k (length plist)) (i 0)) "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK] is a list of polynomials. Destructively modifies PLIST elements." (mapc #'(lambda (poly) (left-tensor-product-by poly (prog1 (make-monom-variable k i) (incf i)))) plist)) (defun standard-extension-1 (plist &aux (plist (standard-extension plist)) (nvars (poly-dimension (car plist)))) "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK]. Firstly, new K variables U1, U2, ..., UK, are inserted into each polynomial. Subsequently, P1, P2, ..., PK are destructively modified tantamount to replacing PI with UI*PI-1. It assumes that all polynomials have the same dimension, and only the first polynomial is examined to determine this dimension." ;; Implementation note: we use STANDARD-EXTENSION and then subtract ;; 1 from each polynomial; since UI*PI has no constant term, ;; we just need to append the constant term at the end ;; of each termlist. (flet ((subtract-1 (p) (poly-append-term p (make-instance 'term :dimension nvars :coeff -1)))) (setf plist (mapc #'subtract-1 plist))) plist) (defun standard-sum (plist &aux (plist (standard-extension plist)) (nvars (poly-dimension (car plist)))) "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK]. Firstly, new K variables, U1, U2, ..., UK, are inserted into each polynomial. Subsequently, P1, P2, ..., PK are destructively modified tantamount to replacing PI with UI*PI, and the resulting polynomials are added. Finally, 1 is subtracted. It should be noted that the term order is not modified, which is equivalent to using a lexicographic order on the first K variables." (flet ((subtract-1 (p) (poly-append-term p (make-instance 'term :dimension nvars :coeff -1)))) (subtract-1 (make-instance 'poly :termlist (apply #'nconc (mapcar #'poly-termlist plist)))))) (defgeneric universal-ezgcd (x y) (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2, C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by the Euclidean algorithm.") (:method ((x integer) (y integer) &aux (c (gcd x y))) (values c (/ x c) (/ y c))) ) (defgeneric s-polynomial (object1 object2) (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.") (:method ((f poly) (g poly)) (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g))) (mf (divide lcm (leading-monomial f))) (mg (divide lcm (leading-monomial g)))) (multiple-value-bind (c cf cg) (universal-ezgcd (leading-coefficient f) (leading-coefficient g)) (declare (ignore c)) (subtract (multiply cg (multiply mf f)) (multiply cf (multiply mg g))))))) #| (defun saturation-extension-1 (ring f p) "Calculate [F, U*P-1]. It destructively modifies F." (declare (type ring ring)) (polysaturation-extension ring f (list p))) (defun poly-primitive-part (ring p) "Divide polynomial P with integer coefficients by gcd of its coefficients and return the result." (declare (type ring ring) (type poly p)) (if (poly-zerop p) (values p 1) (let ((c (poly-content ring p))) (values (make-poly-from-termlist (mapcar #'(lambda (x) (make-term :monom (term-monom x) :coeff (funcall (ring-div ring) (term-coeff x) c))) (poly-termlist p)) (poly-sugar p)) c)))) (defun poly-content (ring p) "Greatest common divisor of the coefficients of the polynomial P. Use the RING structure to compute the greatest common divisor." (declare (type ring ring) (type poly p)) (reduce (ring-gcd ring) (mapcar #'term-coeff (rest (poly-termlist p))) :initial-value (poly-lc p))) |#