;;---------------------------------------------------------------- ;;; -*- 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" "SCALAR-MULTIPLY-BY" "SCALAR-DIVIDE-BY" "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" "->INFIX" "UNIVERSAL-EZGCD" "S-POLYNOMIAL" "POLY-CONTENT" "POLY-PRIMITIVE-PART" "SATURATION-EXTENSION-1" "MAKE-POLY-VARIABLE" "MAKE-POLY-CONSTANT" "UNIVERSAL-EXPT" "UNIVERSAL-EQUALP" "POLY-LENGTH" "POLY-P" "+LIST-MARKER+" "POLY-EVAL") (: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 term) (new poly) &key) "Converts OLD of class TERM to a NEW of class POLY, by making it into a 1-element TERMLIST." (reinitialize-instance new :dimension (monom-dimension old) :termlist (list old))) (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 (change-class old 'term)))) (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)))) (defgeneric scalar-multiply-by (self other) (:documentation "Multiply vector SELF by a scalar OTHER.") (:method ((self poly) other) (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other))) (poly-termlist self)) self)) (defgeneric scalar-divide-by (self other) (:documentation "Divide vector SELF by a scalar OTHER.") (:method ((self poly) other) (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other))) (poly-termlist self)) self)) (defmethod unary-inverse :before ((self poly)) (with-slots (termlist) (assert (and (= (length termlist) 1) (zerop (total-degree (car termlist)) 0)) nil "To be invertible, the polynomial must have 1 term of total degree 0."))) (defmethod unary-inverse ((self poly)) (with-slots (termlist) self (setf (car termlist) (unary-inverse (car termlist))))) (defmethod multiply-by ((self poly) (other monom)) "Multiply a polynomial SELF by OTHER." (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) (defmethod multiply-by ((self poly) (other term)) "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-FN. If UMINUS-FN 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))) (unless (endp p) (setf r (nreconc r p))) 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)))) ;;(format t "P:~A~%" p) ;;(format t "Q:~A~%" q) ;;(format t "R:~A~%" r) ))) (defgeneric add-to (self other) (:documentation "Add OTHER to SELF.") (:method ((self number) (other number)) (+ self other)) (:method ((self poly) (other number)) (add-to self (make-poly-constant (poly-dimension self) other))) (:method ((self number) (other poly)) (add-to (make-poly-constant (poly-dimension other) self) other))) (defgeneric subtract-from (self other) (:documentation "Subtract OTHER from SELF.") (:method ((self number) (other number)) (- self other)) (:method ((self poly) (other number)) (subtract-from self (make-poly-constant (poly-dimension 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 (: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)) (defun subtract-termlists (p q order-fn) "Destructively subtracts two termlists P and Q ordered according to ORDER-FN." (fast-add/subtract p q order-fn #'subtract-from #'unary-minus)) (defmethod add-to ((self poly) (other poly)) "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." (change-term-order other self) (setf (poly-termlist self) (add-termlists (poly-termlist self) (poly-termlist other) (poly-term-order self))) self) (defmethod subtract-from ((self poly) (other poly)) "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." (change-term-order other self) (setf (poly-termlist self) (subtract-termlists (poly-termlist self) (poly-termlist other) (poly-term-order self))) self) (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) (defgeneric add-2 (object1 object2) (:documentation "Non-destructively add OBJECT1 to OBJECT2.") (:method ((object1 t) (object2 t)) (add-to (copy-instance object1) (copy-instance object2)))) (defun add (&rest summands) "Non-destructively adds list SUMMANDS." (cond ((endp summands) 0) (t (reduce #'add-2 summands)))) (defun subtract (minuend &rest subtrahends) "Non-destructively subtract MINUEND and SUBTRAHENDS." (cond ((endp subtrahends) (unary-minus minuend)) (t (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 f (change-class mf 'term :coeff cg)) (multiply g (change-class mg 'term :coeff cf))))))) (defgeneric poly-content (object) (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.") (:method ((self poly)) (reduce #'universal-gcd (mapcar #'term-coeff (rest (poly-termlist self))) :initial-value (leading-coefficient self)))) (defun poly-primitive-part (object) "Divide polynomial OBJECT by gcd of its coefficients. Return the resulting polynomial." (scalar-divide-by object (poly-content object))) (defun poly-insert-variables (self k) (left-tensor-product-by self (make-instance 'monom :dimension k))) (defun saturation-extension (f plist &aux (k (length plist))) "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted as first K variables. It destructively modifies F and PLIST." (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f) (standard-extension-1 plist))) (defun polysaturation-extension (f plist &aux (k (length plist))) "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted as first K variables. It destructively modifies F and PLIST." (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f) (list (standard-sum plist)))) (defun saturation-extension-1 (f p) "Given family of polynomials F and a polynomial P, calculate [F', U*P-1], where F' is F with variable inserted as the first variable. It destructively modifies F and P." (polysaturation-extension f (list p))) (defmethod multiply-by ((object1 number) (object2 poly)) (scalar-multiply-by (copy-instance object2) object1)) (defun make-poly-variable (nvars pos &optional (power 1)) (change-class (make-monom-variable nvars pos power) 'poly)) (defun make-poly-constant (nvars coeff) (change-class (make-term-constant nvars coeff) 'poly)) (defgeneric universal-expt (x y) (:documentation "Raises X to power Y.") (:method ((x number) (y integer)) (expt x y)) (:method ((x t) (y integer)) (declare (type fixnum y)) (cond ((minusp y) (error "universal-expt: Negative exponent.")) ((universal-zerop x) (if (zerop y) 1)) (t (do ((k 1 (ash k 1)) (q x (multiply q q)) ;keep squaring (p 1 (if (not (zerop (logand k y))) (multiply p q) p))) ((> k y) p) (declare (fixnum k))))))) (defgeneric poly-p (object) (:documentation "Checks if an object is a polynomial.") (:method ((self poly)) t) (:method ((self t)) nil)) (defmethod ->sexp :before ((self poly) &optional vars) "Ensures that the number of variables in VARS maches the polynomial dimension of the polynomial SELF." (with-slots (dimension) self (assert (= (length vars) dimension) nil "Number of variables ~S does not match the dimension ~S" vars dimension))) (defmethod ->sexp ((self poly) &optional vars) "Converts a polynomial SELF to a sexp." (cons '+ (mapcar #'(lambda (x) (->sexp x vars)) (poly-termlist self)))) (defparameter +list-marker+ :[ "A sexp with this head is considered a list of polynomials.") (defmethod ->sexp ((self cons) &optional vars) (assert (eql (car self) +list-marker+)) (cons +list-marker+ (mapcar #'(lambda (p) (->sexp p vars)) (cdr self)))) (defun poly-eval (expr vars order) "Evaluate Lisp form EXPR to a polynomial or a list of polynomials in variables VARS. Return the resulting polynomial or list of polynomials. Standard arithmetical operators in form EXPR are replaced with their analogues in the ring of polynomials, and the resulting expression is evaluated, resulting in a polynomial or a list of polynomials in internal form. A similar operation in another computer algebra system could be called 'expand' or so." (labels ((p-eval (p) (poly-eval p vars order)) (p-eval-list (plist) (mapcar #'p-eval plist))) (cond ((eq expr 0) (make-instance 'poly :dimension (length vars))) ((member expr vars :test #'equalp) (let ((pos (position expr vars :test #'equalp))) (make-poly-variable (length vars) pos))) ((atom expr) (make-poly-constant (length vars) expr)) ((eq (car expr) +list-marker+) (cons +list-marker+ (p-eval-list (cdr expr)))) (t (case (car expr) (+ (reduce #'add (p-eval-list (cdr expr)))) (- (apply #'subtract (p-eval-list (cdr expr)))) (* (if (endp (cddr expr)) ;unary (p-eval (cadr expr)) (reduce #'multiply (p-eval-list (cdr expr))))) (/ ;; A polynomial can be divided by a scalar (cond ((endp (cddr expr)) ;; A special case (/ ?), the inverse (divide (cadr expr))) (t (let ((num (p-eval (cadr expr))) (denom-inverse (apply #'divide (mapcar #'p-eval (cddr expr))))) (multiply denom-inverse num))))) (expt (cond ((member (cadr expr) vars :test #'equalp) ;;Special handling of (expt var pow) (let ((pos (position (cadr expr) vars :test #'equalp))) (make-poly-variable (length vars) pos (caddr expr)))) ((not (and (integerp (caddr expr)) (plusp (caddr expr)))) ;; Negative power means division in coefficient ring ;; Non-integer power means non-polynomial coefficient expr) (t (universal-expt (p-eval (cadr expr)) (caddr expr))))) (otherwise (error "Cannot evaluate as polynomial: ~A" expr)))))))