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

Last change on this file since 4050 was 4036, checked in by Marek Rychlik, 9 years ago

* empty log message *

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