;;---------------------------------------------------------------- ;; 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) (:export "POLY" "POLY-DIMENSION" "POLY-TERMLIST" "POLY-TERM-ORDER" "CHANGE-TERM-ORDER" "STANDARD-EXTENSION" "STANDARD-EXTENSION-1" "STANDARD-SUM" "SATURATION-EXTENSION" "ALIST->POLY") (: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)) (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 'monom :exponents (car x)) (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 (cons monom 1)))) (defmethod r-equalp ((self poly) (other poly)) "POLY instances are R-EQUALP if they have the same order and if all terms are R-EQUALP." (and (every #'r-equalp (poly-termlist self) (poly-termlist other)) (eq (poly-term-order self) (poly-term-order other)))) (defgeneric poly-insert-term (self monom coeff) (:method ((self poly) (monom monom) coeff) (cond ((null (poly-dimension self)) (setf (poly-dimension self) (monom-dimension monom))) (t (assert (= (poly-dimension self) (monom-dimension monom))))) (push (cons monom coeff) (poly-termlist self)) self)) (defgeneric poly-append-term (self monom coeff) (:method ((self poly) (monom monom) coeff) (cond ((null (poly-dimension self)) (setf (poly-dimension self) (monom-dimension monom))) (t (assert (= (poly-dimension self) (monom-dimension monom))))) (setf (cdr (last (poly-termlist self))) (list (cons monom coeff))) self)) ;; Leading term (defgeneric leading-term (object) (:method ((self poly)) (car (poly-termlist self))) (:documentation "The leading term of a polynomial, or NIL for zero polynomial.")) ;; Second term (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.")) ;; Leading coefficient (defgeneric leading-coefficient (object) (:method ((self poly)) (scalar-coeff (leading-term self))) (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial.")) ;; Second coefficient (defgeneric second-leading-coefficient (object) (:method ((self poly)) (scalar-coeff (second-leading-term self))) (:documentation "The second leading coefficient of a polynomial. It signals error for a polynomial with at most one term.")) ;; Testing for a zero polynomial (defmethod r-zerop ((self poly)) (null (poly-termlist self))) ;; The number of terms (defmethod r-length ((self poly)) (length (poly-termlist self))) (defmethod multiply-by ((self poly) (other monom)) (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) (defmethod multiply-by ((self poly) (other term)) (mapc #'(lambda (term) (multiply-by term other)) (poly-termlist self)) self) (defmethod multiply-by ((self poly) (other scalar)) (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) `(scalar-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 ((r-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))))))) (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 (r* ,@(cond (reverse-arg-order-p `(other-term ,term)) (t `(,term other-term)))))) (cond ((r-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 (r* (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) (defmethod r+ ((poly1 poly) poly2) "Non-destructively add POLY1 by POLY2." (add-to (copy-instance POLY1) (change-class (copy-instance POLY2) 'poly))) (defmethod r- ((minuend poly) &rest subtrahends) "Non-destructively subtract MINUEND and SUBTRAHENDS." (subtract-from (copy-instance minuend) (change-class (reduce #'r+ subtrahends) 'poly))) (defmethod r+ ((poly1 term) poly2) "Non-destructively add POLY1 by POLY2." (add-to (change-class (copy-instance poly1) 'poly) (change-class (copy-instance poly2) 'poly))) (defmethod r- ((minuend term) &rest subtrahends) "Non-destructively subtract MINUEND and SUBTRAHENDS." (subtract-from (change-class (copy-instance minuend) 'poly) (change-class (reduce #'r+ subtrahends) 'poly))) (defmethod r+ ((poly1 monom) poly2) "Non-destructively add POLY1 by POLY2." (add-to (change-class (copy-instance poly1) 'poly) (change-class (copy-instance poly2) 'poly))) (defmethod r- ((minuend monom) &rest subtrahends) "Non-destructively subtract MINUEND and SUBTRAHENDS." (subtract-from (change-class (copy-instance minuend) 'poly) (change-class (reduce #'r+ subtrahends) 'poly))) (defmethod r* ((poly1 poly) (poly2 poly)) "Non-destructively multiply POLY1 by POLY2." (multiply-by (copy-instance poly1) (copy-instance poly2))) (defmethod left-tensor-product-by ((self poly) (other term)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (left-tensor-product-by term other))) (cond ((r-zerop prod) nil) (t (list prod))))) (poly-termlist self))) self) (defmethod right-tensor-product-by ((self poly) (other term)) (setf (poly-termlist self) (mapcan #'(lambda (term) (let ((prod (right-tensor-product-by term other))) (cond ((r-zerop prod) nil) (t (list prod))))) (poly-termlist self))) self) (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 ((r-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 ((r-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 'monom :dimension nvars) -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) (append-item p (make-instance 'term :coeff -1 :dimension nvars)))) (subtract-1 (make-instance 'poly :termlist (apply #'nconc (mapcar #'poly-termlist plist)))))) #| (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 spoly (ring-and-order f g &aux (ring (ro-ring ring-and-order))) "It yields the S-polynomial of polynomials F and G." (declare (type ring-and-order ring-and-order) (type poly f g)) (let* ((lcm (monom-lcm (poly-lm f) (poly-lm g))) (mf (monom-div lcm (poly-lm f))) (mg (monom-div lcm (poly-lm g)))) (declare (type monom mf mg)) (multiple-value-bind (c cf cg) (funcall (ring-ezgcd ring) (poly-lc f) (poly-lc g)) (declare (ignore c)) (poly-sub ring-and-order (scalar-times-poly ring cg (monom-times-poly mf f)) (scalar-times-poly ring cf (monom-times-poly mg g)))))) (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))) |#