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

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

* empty log message *

File size: 24.6 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 "MAKE-ZERO-FOR"
57 "MAKE-UNIT-FOR"
58 "UNIVERSAL-EXPT"
59 "UNIVERSAL-EQUALP"
60 "POLY-LENGTH"
61 "POLY-P"
62 "+LIST-MARKER+"
63 "POLY-EVAL")
64 (:documentation "Implements polynomials. A polynomial is essentially
65a mapping of monomials of the same degree to coefficients. The
66momomials are ordered according to a monomial order."))
67
68(in-package :polynomial)
69
70(proclaim '(optimize (speed 3) (space 0) (safety 0) (debug 0)))
71
72(defclass poly ()
73 ((dimension :initform nil
74 :initarg :dimension
75 :accessor poly-dimension
76 :documentation "Shared dimension of all terms, the number of variables")
77 (termlist :initform nil :initarg :termlist :accessor poly-termlist
78 :documentation "List of terms.")
79 (order :initform #'lex> :initarg :order :accessor poly-term-order
80 :documentation "Monomial/term order."))
81 (:default-initargs :dimension nil :termlist nil :order #'lex>)
82 (:documentation "A polynomial with a list of terms TERMLIST, ordered
83according to term order ORDER, which defaults to LEX>."))
84
85(defmethod print-object ((self poly) stream)
86 (print-unreadable-object (self stream :type t :identity t)
87 (with-accessors ((dimension poly-dimension)
88 (termlist poly-termlist)
89 (order poly-term-order))
90 self
91 (format stream "DIMENSION=~A TERMLIST=~A ORDER=~A"
92 dimension termlist order))))
93
94(defgeneric change-term-order (self other)
95 (:documentation "Change term order of SELF to the term order of OTHER.")
96 (:method ((self poly) (other poly))
97 (unless (eq (poly-term-order self) (poly-term-order other))
98 (setf (poly-termlist self) (sort (poly-termlist self) (poly-term-order other))
99 (poly-term-order self) (poly-term-order other)))
100 self))
101
102(defgeneric poly-insert-term (self term)
103 (:documentation "Insert a term TERM into SELF before all other
104 terms. Order is not enforced.")
105 (:method ((self poly) (term term))
106 (cond ((null (poly-dimension self))
107 (setf (poly-dimension self) (monom-dimension term)))
108 (t (assert (= (poly-dimension self) (monom-dimension term)))))
109 (push term (poly-termlist self))
110 self))
111
112(defgeneric poly-append-term (self term)
113 (:documentation "Append a term TERM to SELF after all other terms. Order is not enforced.")
114 (:method ((self poly) (term term))
115 (cond ((null (poly-dimension self))
116 (setf (poly-dimension self) (monom-dimension term)))
117 (t (assert (= (poly-dimension self) (monom-dimension term)))))
118 (setf (cdr (last (poly-termlist self))) (list term))
119 self))
120
121(defun alist->poly (alist &aux (poly (make-instance 'poly)))
122 "It reads polynomial from an alist formatted as ( ... (exponents . coeff) ...).
123It can be used to enter simple polynomials by hand, e.g the polynomial
124in two variables, X and Y, given in standard notation as:
125
126 3*X^2*Y^3+2*Y+7
127
128can be entered as
129(ALIST->POLY '(((2 3) . 3) ((0 1) . 2) ((0 0) . 7))).
130
131NOTE: The primary use is for low-level debugging of the package."
132 (dolist (x alist poly)
133 (poly-insert-term poly (make-instance 'term :exponents (car x) :coeff (cdr x)))))
134
135(defmethod update-instance-for-different-class :after ((old term) (new poly) &key)
136 "Converts OLD of class TERM 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 old)))
140
141(defmethod update-instance-for-different-class :after ((old monom) (new poly) &key)
142 "Converts OLD of class MONOM to a NEW of class POLY, by making it into a 1-element TERMLIST."
143 (reinitialize-instance new
144 :dimension (monom-dimension old)
145 :termlist (list (change-class old 'term))))
146
147(defmethod universal-equalp ((self poly) (other poly))
148 "Implements equality of polynomials."
149 (and (eql (poly-dimension self) (poly-dimension other))
150 (every #'universal-equalp (poly-termlist self) (poly-termlist other))
151 (eq (poly-term-order self) (poly-term-order other))))
152
153(defgeneric leading-term (object)
154 (:method ((self poly))
155 (car (poly-termlist self)))
156 (:documentation "The leading term of a polynomial, or NIL for zero polynomial."))
157
158(defgeneric second-leading-term (object)
159 (:method ((self poly))
160 (cadar (poly-termlist self)))
161 (:documentation "The second leading term of a polynomial, or NIL for a polynomial with at most one term."))
162
163(defgeneric leading-monomial (object)
164 (:method ((self poly))
165 (change-class (copy-instance (leading-term self)) 'monom))
166 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
167
168(defgeneric second-leading-monomial (object)
169 (:method ((self poly))
170 (change-class (copy-instance (second-leading-term self)) 'monom))
171 (:documentation "The leading monomial of a polynomial, or NIL for zero polynomial."))
172
173(defgeneric leading-coefficient (object)
174 (:method ((self poly))
175 (term-coeff (leading-term self)))
176 (:documentation "The leading coefficient of a polynomial. It signals error for a zero polynomial."))
177
178(defgeneric second-leading-coefficient (object)
179 (:method ((self poly))
180 (term-coeff (second-leading-term self)))
181 (:documentation "The second leading coefficient of a polynomial. It
182 signals error for a polynomial with at most one term."))
183
184(defmethod universal-zerop ((self poly))
185 "Return T iff SELF is a zero polynomial."
186 (null (poly-termlist self)))
187
188(defgeneric poly-length (self)
189 (:documentation "Return the number of terms.")
190 (:method ((self poly))
191 (length (poly-termlist self))))
192
193(defgeneric scalar-multiply-by (self other)
194 (:documentation "Multiply vector SELF by a scalar OTHER.")
195 (:method ((self poly) other)
196 (mapc #'(lambda (term) (setf (term-coeff term) (multiply (term-coeff term) other)))
197 (poly-termlist self))
198 self))
199
200(defgeneric scalar-divide-by (self other)
201 (:documentation "Divide vector SELF by a scalar OTHER.")
202 (:method ((self poly) other)
203 (mapc #'(lambda (term) (setf (term-coeff term) (divide (term-coeff term) other)))
204 (poly-termlist self))
205 self))
206
207(defmethod unary-inverse :before ((self poly))
208 "Checks invertibility of a polynomial SELF. To be invertable, the
209polynomial must be an invertible, constant polynomial."
210 (with-slots (termlist)
211 self
212 (assert (and (= (length termlist) 1) (zerop (total-degree (car termlist))))
213 nil
214 "To be invertible, the polynomial must have 1 term of total degree 0.")))
215
216(defmethod unary-inverse ((self poly))
217 "Returns the unary inverse of a polynomial SELF."
218 (with-slots (termlist)
219 self
220 (setf (car termlist) (unary-inverse (car termlist)))
221 self))
222
223(defmethod multiply-by ((self poly) (other monom))
224 "Multiply a polynomial SELF by OTHER."
225 (mapc #'(lambda (term) (multiply-by term other))
226 (poly-termlist self))
227 self)
228
229(defmethod multiply-by ((self poly) (other term))
230 "Multiply a polynomial SELF by OTHER."
231 (mapc #'(lambda (term) (multiply-by term other))
232 (poly-termlist self))
233 self)
234
235(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
236 "Return an expression which will efficiently adds/subtracts two
237polynomials, P and Q. The addition/subtraction of coefficients is
238performed by calling ADD/SUBTRACT-FN. If UMINUS-FN is supplied, it is
239used to negate the coefficients of Q which do not have a corresponding
240coefficient in P. The code implements an efficient algorithm to add
241two polynomials represented as sorted lists of terms. The code
242destroys both arguments, reusing the terms to build the result."
243 `(macrolet ((lc (x) `(term-coeff (car ,x))))
244 (do ((p ,p)
245 (q ,q)
246 r)
247 ((or (endp p) (endp q))
248 ;; NOTE: R contains the result in reverse order. Can it
249 ;; be more efficient to produce the terms in correct order?
250 (unless (endp q)
251 ;; Upon subtraction, we must change the sign of
252 ;; all coefficients in q
253 ,@(when uminus-fn
254 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
255 (setf r (nreconc r q)))
256 (unless (endp p)
257 (setf r (nreconc r p)))
258 r)
259 (multiple-value-bind
260 (greater-p equal-p)
261 (funcall ,order-fn (car p) (car q))
262 (cond
263 (greater-p
264 (rotatef (cdr p) r p)
265 )
266 (equal-p
267 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
268 (cond
269 ((universal-zerop s)
270 (setf p (cdr p))
271 )
272 (t
273 (setf (lc p) s)
274 (rotatef (cdr p) r p))))
275 (setf q (cdr q))
276 )
277 (t
278 ;;Negate the term of Q if UMINUS provided, signallig
279 ;;that we are doing subtraction
280 ,(when uminus-fn
281 `(setf (lc q) (funcall ,uminus-fn (lc q))))
282 (rotatef (cdr q) r q))))
283 ;;(format t "P:~A~%" p)
284 ;;(format t "Q:~A~%" q)
285 ;;(format t "R:~A~%" r)
286 )))
287
288
289
290(defgeneric add-to (self other)
291 (:documentation "Add OTHER to SELF.")
292 (:method ((self number) (other number))
293 (+ self other))
294 (:method ((self poly) (other number))
295 (add-to self (make-poly-constant (poly-dimension self) other)))
296 (:method ((self number) (other poly))
297 (add-to (make-poly-constant (poly-dimension other) self) other)))
298
299
300(defgeneric subtract-from (self other)
301 (:documentation "Subtract OTHER from SELF.")
302 (:method ((self number) (other number))
303 (- self other))
304 (:method ((self poly) (other number))
305 (subtract-from self (make-poly-constant (poly-dimension self) other))))
306
307
308#|
309(defmacro def-add/subtract-method (add/subtract-method-name
310 uminus-method-name
311 &optional
312 (doc-string nil doc-string-supplied-p))
313 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
314 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
315 ,@(when doc-string-supplied-p `(,doc-string))
316 ;; Ensure orders are compatible
317 (change-term-order other self)
318 (setf (poly-termlist self) (fast-add/subtract
319 (poly-termlist self) (poly-termlist other)
320 (poly-term-order self)
321 #',add/subtract-method-name
322 ,(when uminus-method-name `(function ,uminus-method-name))))
323 self))
324
325(eval-when (:load-toplevel :execute)
326
327 (def-add/subtract-method add-to nil
328 "Adds to polynomial SELF another polynomial OTHER.
329This operation destructively modifies both polynomials.
330The result is stored in SELF. This implementation does
331no consing, entirely reusing the sells of SELF and OTHER.")
332
333 (def-add/subtract-method subtract-from unary-minus
334 "Subtracts from polynomial SELF another polynomial OTHER.
335This operation destructively modifies both polynomials.
336The result is stored in SELF. This implementation does
337no consing, entirely reusing the sells of SELF and OTHER.")
338 )
339
340|#
341
342(defmethod unary-minus ((self poly))
343 "Destructively modifies the coefficients of the polynomial SELF,
344by changing their sign."
345 (mapc #'unary-minus (poly-termlist self))
346 self)
347
348(defun add-termlists (p q order-fn)
349 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
350 (fast-add/subtract p q order-fn #'add-to nil))
351
352(defun subtract-termlists (p q order-fn)
353 "Destructively subtracts two termlists P and Q ordered according to ORDER-FN."
354 (fast-add/subtract p q order-fn #'subtract-from #'unary-minus))
355
356(defmethod add-to ((self poly) (other poly))
357 "Adds to polynomial SELF another polynomial OTHER.
358This operation destructively modifies both polynomials.
359The result is stored in SELF. This implementation does
360no consing, entirely reusing the sells of SELF and OTHER."
361 (change-term-order other self)
362 (setf (poly-termlist self) (add-termlists
363 (poly-termlist self) (poly-termlist other)
364 (poly-term-order self)))
365 self)
366
367
368(defmethod subtract-from ((self poly) (other poly))
369 "Subtracts from polynomial SELF another polynomial OTHER.
370This operation destructively modifies both polynomials.
371The result is stored in SELF. This implementation does
372no consing, entirely reusing the sells of SELF and OTHER."
373 (change-term-order other self)
374 (setf (poly-termlist self) (subtract-termlists
375 (poly-termlist self) (poly-termlist other)
376 (poly-term-order self)))
377 self)
378
379(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
380 &optional (reverse-arg-order-P nil))
381 "Multiplies term TERM by a list of term, TERMLIST.
382Takes into accound divisors of zero in the ring, by
383deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
384is T, change the order of arguments; this may be important
385if we extend the package to non-commutative rings."
386 `(mapcan #'(lambda (other-term)
387 (let ((prod (multiply
388 ,@(cond
389 (reverse-arg-order-p
390 `(other-term ,term))
391 (t
392 `(,term other-term))))))
393 (cond
394 ((universal-zerop prod) nil)
395 (t (list prod)))))
396 ,termlist))
397
398(defun multiply-termlists (p q order-fn)
399 "A version of polynomial multiplication, operating
400directly on termlists."
401 (cond
402 ((or (endp p) (endp q))
403 ;;p or q is 0 (represented by NIL)
404 nil)
405 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
406 ((endp (cdr p))
407 (multiply-term-by-termlist-dropping-zeros (car p) q))
408 ((endp (cdr q))
409 (multiply-term-by-termlist-dropping-zeros (car q) p t))
410 (t
411 (cons (multiply (car p) (car q))
412 (add-termlists
413 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
414 (multiply-termlists (cdr p) q order-fn)
415 order-fn)))))
416
417(defmethod multiply-by ((self poly) (other poly))
418 (change-term-order other self)
419 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
420 (poly-termlist other)
421 (poly-term-order self)))
422 self)
423
424(defgeneric add-2 (object1 object2)
425 (:documentation "Non-destructively add OBJECT1 to OBJECT2.")
426 (:method ((object1 t) (object2 t))
427 (add-to (copy-instance object1) (copy-instance object2))))
428
429(defun add (&rest summands)
430 "Non-destructively adds list SUMMANDS."
431 (cond ((endp summands) 0)
432 (t (reduce #'add-2 summands))))
433
434(defun subtract (minuend &rest subtrahends)
435 "Non-destructively subtract MINUEND and SUBTRAHENDS."
436 (cond ((endp subtrahends) (unary-minus minuend))
437 (t (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))))
438
439(defmethod left-tensor-product-by ((self poly) (other monom))
440 (setf (poly-termlist self)
441 (mapcan #'(lambda (term)
442 (let ((prod (left-tensor-product-by term other)))
443 (cond
444 ((universal-zerop prod) nil)
445 (t (list prod)))))
446 (poly-termlist self)))
447 (incf (poly-dimension self) (monom-dimension other))
448 self)
449
450(defmethod right-tensor-product-by ((self poly) (other monom))
451 (setf (poly-termlist self)
452 (mapcan #'(lambda (term)
453 (let ((prod (right-tensor-product-by term other)))
454 (cond
455 ((universal-zerop prod) nil)
456 (t (list prod)))))
457 (poly-termlist self)))
458 (incf (poly-dimension self) (monom-dimension other))
459 self)
460
461
462(defun standard-extension (plist &aux (k (length plist)) (i 0))
463 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
464is a list of polynomials. Destructively modifies PLIST elements."
465 (mapc #'(lambda (poly)
466 (left-tensor-product-by
467 poly
468 (prog1
469 (make-monom-variable k i)
470 (incf i))))
471 plist))
472
473(defun standard-extension-1 (plist
474 &aux
475 (plist (standard-extension plist))
476 (nvars (poly-dimension (car plist))))
477 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
478Firstly, new K variables U1, U2, ..., UK, are inserted into each
479polynomial. Subsequently, P1, P2, ..., PK are destructively modified
480tantamount to replacing PI with UI*PI-1. It assumes that all
481polynomials have the same dimension, and only the first polynomial
482is examined to determine this dimension."
483 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
484 ;; 1 from each polynomial; since UI*PI has no constant term,
485 ;; we just need to append the constant term at the end
486 ;; of each termlist.
487 (flet ((subtract-1 (p)
488 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
489 (setf plist (mapc #'subtract-1 plist)))
490 plist)
491
492
493(defun standard-sum (plist
494 &aux
495 (plist (standard-extension plist))
496 (nvars (poly-dimension (car plist))))
497 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
498Firstly, new K variables, U1, U2, ..., UK, are inserted into each
499polynomial. Subsequently, P1, P2, ..., PK are destructively modified
500tantamount to replacing PI with UI*PI, and the resulting polynomials
501are added. Finally, 1 is subtracted. It should be noted that the term
502order is not modified, which is equivalent to using a lexicographic
503order on the first K variables."
504 (flet ((subtract-1 (p)
505 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
506 (subtract-1
507 (make-instance
508 'poly
509 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
510
511(defgeneric universal-ezgcd (x y)
512 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
513C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
514the Euclidean algorithm.")
515 (:method ((x integer) (y integer)
516 &aux (c (gcd x y)))
517 (values c (/ x c) (/ y c)))
518 )
519
520(defgeneric s-polynomial (object1 object2)
521 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
522 (:method ((f poly) (g poly))
523 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
524 (mf (divide lcm (leading-monomial f)))
525 (mg (divide lcm (leading-monomial g))))
526 (multiple-value-bind (c cf cg)
527 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
528 (declare (ignore c))
529 (subtract
530 (multiply f (change-class mf 'term :coeff cg))
531 (multiply g (change-class mg 'term :coeff cf)))))))
532
533(defgeneric poly-content (object)
534 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
535 (:method ((self poly))
536 (reduce #'universal-gcd
537 (mapcar #'term-coeff (rest (poly-termlist self)))
538 :initial-value (leading-coefficient self))))
539
540(defun poly-primitive-part (object)
541 "Divide polynomial OBJECT by gcd of its
542coefficients. Return the resulting polynomial."
543 (scalar-divide-by object (poly-content object)))
544
545(defun poly-insert-variables (self k)
546 (left-tensor-product-by self (make-instance 'monom :dimension k)))
547
548(defun saturation-extension (f plist &aux (k (length plist)))
549 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
550PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
551as first K variables. It destructively modifies F and PLIST."
552 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
553 (standard-extension-1 plist)))
554
555(defun polysaturation-extension (f plist &aux (k (length plist)))
556 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
557and F' is F with variables U1,U2,...,UK inserted as first K
558variables. It destructively modifies F and PLIST."
559 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
560 (list (standard-sum plist))))
561
562(defun saturation-extension-1 (f p)
563 "Given family of polynomials F and a polynomial P, calculate [F',
564U*P-1], where F' is F with variable inserted as the first variable. It
565destructively modifies F and P."
566 (polysaturation-extension f (list p)))
567
568(defmethod multiply-by ((object1 number) (object2 poly))
569 (scalar-multiply-by (copy-instance object2) object1))
570
571(defun make-poly-variable (nvars pos &optional (power 1))
572 (change-class (make-monom-variable nvars pos power) 'poly))
573
574(defun make-poly-constant (nvars coeff)
575 (change-class (make-term-constant nvars coeff) 'poly))
576
577(defgeneric universal-expt (x y)
578 (:documentation "Raises X to power Y.")
579 (:method ((x number) (y integer)) (expt x y))
580 (:method ((x t) (y integer))
581 (declare (type fixnum y))
582 (cond
583 ((minusp y) (error "universal-expt: Negative exponent."))
584 ((universal-zerop x) (if (zerop y) 1))
585 (t
586 (do ((k 1 (ash k 1))
587 (q x (multiply q q)) ;keep squaring
588 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
589 ((> k y) p)
590 (declare (fixnum k)))))))
591
592(defgeneric poly-p (object)
593 (:documentation "Checks if an object is a polynomial.")
594 (:method ((self poly)) t)
595 (:method ((self t)) nil))
596
597(defmethod ->sexp :before ((self poly) &optional vars)
598 "Ensures that the number of variables in VARS maches the polynomial dimension of the
599polynomial SELF."
600 (with-slots (dimension)
601 self
602 (assert (= (length vars) dimension)
603 nil
604 "Number of variables ~S does not match the dimension ~S"
605 vars dimension)))
606
607(defmethod ->sexp ((self poly) &optional vars)
608 "Converts a polynomial SELF to a sexp."
609 (let ((m (mapcar #'(lambda (x) (->sexp x vars))
610 (poly-termlist self))))
611 (cond ((endp m) 0)
612 ((endp (cdr m)) (car m))
613 (t (cons '+ m)))))
614
615(defparameter +list-marker+ :[
616 "A sexp with this head is considered a list of polynomials.")
617
618(defmethod ->sexp ((self cons) &optional vars)
619 (assert (eql (car self) +list-marker+))
620 (cons +list-marker+ (mapcar #'(lambda (p) (->sexp p vars)) (cdr self))))
621
622
623(defun poly-eval (expr vars order)
624 "Evaluate Lisp form EXPR to a polynomial or a list of polynomials in
625variables VARS. Return the resulting polynomial or list of
626polynomials. Standard arithmetical operators in form EXPR are
627replaced with their analogues in the ring of polynomials, and the
628resulting expression is evaluated, resulting in a polynomial or a list
629of polynomials in internal form. A similar operation in another computer
630algebra system could be called 'expand' or so."
631 (labels ((p-eval (p) (poly-eval p vars order))
632 (p-eval-list (plist) (mapcar #'p-eval plist)))
633 (cond
634 ((eq expr 0)
635 (make-instance 'poly :dimension (length vars)))
636 ((member expr vars :test #'equalp)
637 (let ((pos (position expr vars :test #'equalp)))
638 (make-poly-variable (length vars) pos)))
639 ((atom expr)
640 (make-poly-constant (length vars) expr))
641 ((eq (car expr) +list-marker+)
642 (cons +list-marker+ (p-eval-list (cdr expr))))
643 (t
644 (case (car expr)
645 (+ (reduce #'add (p-eval-list (cdr expr))))
646 (- (apply #'subtract (p-eval-list (cdr expr))))
647 (*
648 (if (endp (cddr expr)) ;unary
649 (p-eval (cadr expr))
650 (reduce #'multiply (p-eval-list (cdr expr)))))
651 (/
652 ;; A polynomial can be divided by a scalar
653 (cond
654 ((endp (cddr expr))
655 ;; A special case (/ ?), the inverse
656 (divide (cadr expr)))
657 (t
658 (let ((num (p-eval (cadr expr)))
659 (denom-inverse (apply #'divide (mapcar #'p-eval (cddr expr)))))
660 (multiply denom-inverse num)))))
661 (expt
662 (cond
663 ((member (cadr expr) vars :test #'equalp)
664 ;;Special handling of (expt var pow)
665 (let ((pos (position (cadr expr) vars :test #'equalp)))
666 (make-poly-variable (length vars) pos (caddr expr))))
667 ((not (and (integerp (caddr expr)) (plusp (caddr expr))))
668 ;; Negative power means division in coefficient ring
669 ;; Non-integer power means non-polynomial coefficient
670 expr)
671 (t (universal-expt (p-eval (cadr expr)) (caddr expr)))))
672 (otherwise
673 (error "Cannot evaluate as polynomial: ~A" expr)))))))
674
675(defgeneric make-zero-for (self)
676 (:method ((self poly))
677 (make-instance 'poly :dimension (poly-dimension self))))
678
679(defgeneric make-unit-for (self)
680 (:method ((self poly))
681 (make-poly-constant (poly-dimension self) 1)))
682
Note: See TracBrowser for help on using the repository browser.