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

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

* empty log message *

File size: 24.1 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 (with-slots (termlist)
207 (assert (and (= (length termlist) 1) (zerop (total-degree (car termlist)) 0))
208 nil
209 "To be invertible, the polynomial must have 1 term of total degree 0.")))
210
211(defmethod unary-inverse ((self poly))
212 (with-slots (termlist)
213 self
214 (setf (car termlist) (unary-inverse (car termlist)))))
215
216(defmethod multiply-by ((self poly) (other monom))
217 "Multiply a polynomial SELF by OTHER."
218 (mapc #'(lambda (term) (multiply-by term other))
219 (poly-termlist self))
220 self)
221
222(defmethod multiply-by ((self poly) (other term))
223 "Multiply a polynomial SELF by OTHER."
224 (mapc #'(lambda (term) (multiply-by term other))
225 (poly-termlist self))
226 self)
227
228(defmacro fast-add/subtract (p q order-fn add/subtract-fn uminus-fn)
229 "Return an expression which will efficiently adds/subtracts two
230polynomials, P and Q. The addition/subtraction of coefficients is
231performed by calling ADD/SUBTRACT-FN. If UMINUS-FN is supplied, it is
232used to negate the coefficients of Q which do not have a corresponding
233coefficient in P. The code implements an efficient algorithm to add
234two polynomials represented as sorted lists of terms. The code
235destroys both arguments, reusing the terms to build the result."
236 `(macrolet ((lc (x) `(term-coeff (car ,x))))
237 (do ((p ,p)
238 (q ,q)
239 r)
240 ((or (endp p) (endp q))
241 ;; NOTE: R contains the result in reverse order. Can it
242 ;; be more efficient to produce the terms in correct order?
243 (unless (endp q)
244 ;; Upon subtraction, we must change the sign of
245 ;; all coefficients in q
246 ,@(when uminus-fn
247 `((mapc #'(lambda (x) (setf x (funcall ,uminus-fn x))) q)))
248 (setf r (nreconc r q)))
249 (unless (endp p)
250 (setf r (nreconc r p)))
251 r)
252 (multiple-value-bind
253 (greater-p equal-p)
254 (funcall ,order-fn (car p) (car q))
255 (cond
256 (greater-p
257 (rotatef (cdr p) r p)
258 )
259 (equal-p
260 (let ((s (funcall ,add/subtract-fn (lc p) (lc q))))
261 (cond
262 ((universal-zerop s)
263 (setf p (cdr p))
264 )
265 (t
266 (setf (lc p) s)
267 (rotatef (cdr p) r p))))
268 (setf q (cdr q))
269 )
270 (t
271 ;;Negate the term of Q if UMINUS provided, signallig
272 ;;that we are doing subtraction
273 ,(when uminus-fn
274 `(setf (lc q) (funcall ,uminus-fn (lc q))))
275 (rotatef (cdr q) r q))))
276 ;;(format t "P:~A~%" p)
277 ;;(format t "Q:~A~%" q)
278 ;;(format t "R:~A~%" r)
279 )))
280
281
282
283(defgeneric add-to (self other)
284 (:documentation "Add OTHER to SELF.")
285 (:method ((self number) (other number))
286 (+ self other))
287 (:method ((self poly) (other number))
288 (add-to self (make-poly-constant (poly-dimension self) other)))
289 (:method ((self number) (other poly))
290 (add-to (make-poly-constant (poly-dimension other) self) other)))
291
292
293(defgeneric subtract-from (self other)
294 (:documentation "Subtract OTHER from SELF.")
295 (:method ((self number) (other number))
296 (- self other))
297 (:method ((self poly) (other number))
298 (subtract-from self (make-poly-constant (poly-dimension self) other))))
299
300
301#|
302(defmacro def-add/subtract-method (add/subtract-method-name
303 uminus-method-name
304 &optional
305 (doc-string nil doc-string-supplied-p))
306 "This macro avoids code duplication for two similar operations: ADD-TO and SUBTRACT-FROM."
307 `(defmethod ,add/subtract-method-name ((self poly) (other poly))
308 ,@(when doc-string-supplied-p `(,doc-string))
309 ;; Ensure orders are compatible
310 (change-term-order other self)
311 (setf (poly-termlist self) (fast-add/subtract
312 (poly-termlist self) (poly-termlist other)
313 (poly-term-order self)
314 #',add/subtract-method-name
315 ,(when uminus-method-name `(function ,uminus-method-name))))
316 self))
317
318(eval-when (:load-toplevel :execute)
319
320 (def-add/subtract-method add-to nil
321 "Adds to polynomial SELF another polynomial OTHER.
322This operation destructively modifies both polynomials.
323The result is stored in SELF. This implementation does
324no consing, entirely reusing the sells of SELF and OTHER.")
325
326 (def-add/subtract-method subtract-from unary-minus
327 "Subtracts from polynomial SELF another polynomial OTHER.
328This operation destructively modifies both polynomials.
329The result is stored in SELF. This implementation does
330no consing, entirely reusing the sells of SELF and OTHER.")
331 )
332
333|#
334
335(defmethod unary-minus ((self poly))
336 "Destructively modifies the coefficients of the polynomial SELF,
337by changing their sign."
338 (mapc #'unary-minus (poly-termlist self))
339 self)
340
341(defun add-termlists (p q order-fn)
342 "Destructively adds two termlists P and Q ordered according to ORDER-FN."
343 (fast-add/subtract p q order-fn #'add-to nil))
344
345(defun subtract-termlists (p q order-fn)
346 "Destructively subtracts two termlists P and Q ordered according to ORDER-FN."
347 (fast-add/subtract p q order-fn #'subtract-from #'unary-minus))
348
349(defmethod add-to ((self poly) (other poly))
350 "Adds to polynomial SELF another polynomial OTHER.
351This operation destructively modifies both polynomials.
352The result is stored in SELF. This implementation does
353no consing, entirely reusing the sells of SELF and OTHER."
354 (change-term-order other self)
355 (setf (poly-termlist self) (add-termlists
356 (poly-termlist self) (poly-termlist other)
357 (poly-term-order self)))
358 self)
359
360
361(defmethod subtract-from ((self poly) (other poly))
362 "Subtracts from polynomial SELF another polynomial OTHER.
363This operation destructively modifies both polynomials.
364The result is stored in SELF. This implementation does
365no consing, entirely reusing the sells of SELF and OTHER."
366 (change-term-order other self)
367 (setf (poly-termlist self) (subtract-termlists
368 (poly-termlist self) (poly-termlist other)
369 (poly-term-order self)))
370 self)
371
372(defmacro multiply-term-by-termlist-dropping-zeros (term termlist
373 &optional (reverse-arg-order-P nil))
374 "Multiplies term TERM by a list of term, TERMLIST.
375Takes into accound divisors of zero in the ring, by
376deleting zero terms. Optionally, if REVERSE-ARG-ORDER-P
377is T, change the order of arguments; this may be important
378if we extend the package to non-commutative rings."
379 `(mapcan #'(lambda (other-term)
380 (let ((prod (multiply
381 ,@(cond
382 (reverse-arg-order-p
383 `(other-term ,term))
384 (t
385 `(,term other-term))))))
386 (cond
387 ((universal-zerop prod) nil)
388 (t (list prod)))))
389 ,termlist))
390
391(defun multiply-termlists (p q order-fn)
392 "A version of polynomial multiplication, operating
393directly on termlists."
394 (cond
395 ((or (endp p) (endp q))
396 ;;p or q is 0 (represented by NIL)
397 nil)
398 ;; If p= p0+p1 and q=q0+q1 then p*q=p0*q0+p0*q1+p1*q
399 ((endp (cdr p))
400 (multiply-term-by-termlist-dropping-zeros (car p) q))
401 ((endp (cdr q))
402 (multiply-term-by-termlist-dropping-zeros (car q) p t))
403 (t
404 (cons (multiply (car p) (car q))
405 (add-termlists
406 (multiply-term-by-termlist-dropping-zeros (car p) (cdr q))
407 (multiply-termlists (cdr p) q order-fn)
408 order-fn)))))
409
410(defmethod multiply-by ((self poly) (other poly))
411 (change-term-order other self)
412 (setf (poly-termlist self) (multiply-termlists (poly-termlist self)
413 (poly-termlist other)
414 (poly-term-order self)))
415 self)
416
417(defgeneric add-2 (object1 object2)
418 (:documentation "Non-destructively add OBJECT1 to OBJECT2.")
419 (:method ((object1 t) (object2 t))
420 (add-to (copy-instance object1) (copy-instance object2))))
421
422(defun add (&rest summands)
423 "Non-destructively adds list SUMMANDS."
424 (cond ((endp summands) 0)
425 (t (reduce #'add-2 summands))))
426
427(defun subtract (minuend &rest subtrahends)
428 "Non-destructively subtract MINUEND and SUBTRAHENDS."
429 (cond ((endp subtrahends) (unary-minus minuend))
430 (t (subtract-from (copy-instance minuend) (reduce #'add subtrahends)))))
431
432(defmethod left-tensor-product-by ((self poly) (other monom))
433 (setf (poly-termlist self)
434 (mapcan #'(lambda (term)
435 (let ((prod (left-tensor-product-by term other)))
436 (cond
437 ((universal-zerop prod) nil)
438 (t (list prod)))))
439 (poly-termlist self)))
440 (incf (poly-dimension self) (monom-dimension other))
441 self)
442
443(defmethod right-tensor-product-by ((self poly) (other monom))
444 (setf (poly-termlist self)
445 (mapcan #'(lambda (term)
446 (let ((prod (right-tensor-product-by term other)))
447 (cond
448 ((universal-zerop prod) nil)
449 (t (list prod)))))
450 (poly-termlist self)))
451 (incf (poly-dimension self) (monom-dimension other))
452 self)
453
454
455(defun standard-extension (plist &aux (k (length plist)) (i 0))
456 "Calculate [U1*P1,U2*P2,...,UK*PK], where PLIST=[P1,P2,...,PK]
457is a list of polynomials. Destructively modifies PLIST elements."
458 (mapc #'(lambda (poly)
459 (left-tensor-product-by
460 poly
461 (prog1
462 (make-monom-variable k i)
463 (incf i))))
464 plist))
465
466(defun standard-extension-1 (plist
467 &aux
468 (plist (standard-extension plist))
469 (nvars (poly-dimension (car plist))))
470 "Calculate [U1*P1-1,U2*P2-1,...,UK*PK-1], where PLIST=[P1,P2,...,PK].
471Firstly, new K variables U1, U2, ..., UK, are inserted into each
472polynomial. Subsequently, P1, P2, ..., PK are destructively modified
473tantamount to replacing PI with UI*PI-1. It assumes that all
474polynomials have the same dimension, and only the first polynomial
475is examined to determine this dimension."
476 ;; Implementation note: we use STANDARD-EXTENSION and then subtract
477 ;; 1 from each polynomial; since UI*PI has no constant term,
478 ;; we just need to append the constant term at the end
479 ;; of each termlist.
480 (flet ((subtract-1 (p)
481 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
482 (setf plist (mapc #'subtract-1 plist)))
483 plist)
484
485
486(defun standard-sum (plist
487 &aux
488 (plist (standard-extension plist))
489 (nvars (poly-dimension (car plist))))
490 "Calculate the polynomial U1*P1+U2*P2+...+UK*PK-1, where PLIST=[P1,P2,...,PK].
491Firstly, new K variables, U1, U2, ..., UK, are inserted into each
492polynomial. Subsequently, P1, P2, ..., PK are destructively modified
493tantamount to replacing PI with UI*PI, and the resulting polynomials
494are added. Finally, 1 is subtracted. It should be noted that the term
495order is not modified, which is equivalent to using a lexicographic
496order on the first K variables."
497 (flet ((subtract-1 (p)
498 (poly-append-term p (make-instance 'term :dimension nvars :coeff -1))))
499 (subtract-1
500 (make-instance
501 'poly
502 :termlist (apply #'nconc (mapcar #'poly-termlist plist))))))
503
504(defgeneric universal-ezgcd (x y)
505 (:documentation "Solves the diophantine system: X=C*X1, Y=C*X2,
506C=GCD(X,Y). It returns C, X1 and Y1. The result may be obtained by
507the Euclidean algorithm.")
508 (:method ((x integer) (y integer)
509 &aux (c (gcd x y)))
510 (values c (/ x c) (/ y c)))
511 )
512
513(defgeneric s-polynomial (object1 object2)
514 (:documentation "Yields the S-polynomial of OBJECT1 and OBJECT2.")
515 (:method ((f poly) (g poly))
516 (let* ((lcm (universal-lcm (leading-monomial f) (leading-monomial g)))
517 (mf (divide lcm (leading-monomial f)))
518 (mg (divide lcm (leading-monomial g))))
519 (multiple-value-bind (c cf cg)
520 (universal-ezgcd (leading-coefficient f) (leading-coefficient g))
521 (declare (ignore c))
522 (subtract
523 (multiply f (change-class mf 'term :coeff cg))
524 (multiply g (change-class mg 'term :coeff cf)))))))
525
526(defgeneric poly-content (object)
527 (:documentation "Greatest common divisor of the coefficients of the polynomial object OBJECT.")
528 (:method ((self poly))
529 (reduce #'universal-gcd
530 (mapcar #'term-coeff (rest (poly-termlist self)))
531 :initial-value (leading-coefficient self))))
532
533(defun poly-primitive-part (object)
534 "Divide polynomial OBJECT by gcd of its
535coefficients. Return the resulting polynomial."
536 (scalar-divide-by object (poly-content object)))
537
538(defun poly-insert-variables (self k)
539 (left-tensor-product-by self (make-instance 'monom :dimension k)))
540
541(defun saturation-extension (f plist &aux (k (length plist)))
542 "Calculate [F', U1*P1-1,U2*P2-1,...,UK*PK-1], where
543PLIST=[P1,P2,...,PK] and F' is F with variables U1,U2,...,UK inserted
544as first K variables. It destructively modifies F and PLIST."
545 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
546 (standard-extension-1 plist)))
547
548(defun polysaturation-extension (f plist &aux (k (length plist)))
549 "Calculate [F', U1*P1+U2*P2+...+UK*PK-1], where PLIST=[P1,P2,...,PK]
550and F' is F with variables U1,U2,...,UK inserted as first K
551variables. It destructively modifies F and PLIST."
552 (nconc (mapc #'(lambda (x) (poly-insert-variables x k)) f)
553 (list (standard-sum plist))))
554
555(defun saturation-extension-1 (f p)
556 "Given family of polynomials F and a polynomial P, calculate [F',
557U*P-1], where F' is F with variable inserted as the first variable. It
558destructively modifies F and P."
559 (polysaturation-extension f (list p)))
560
561(defmethod multiply-by ((object1 number) (object2 poly))
562 (scalar-multiply-by (copy-instance object2) object1))
563
564(defun make-poly-variable (nvars pos &optional (power 1))
565 (change-class (make-monom-variable nvars pos power) 'poly))
566
567(defun make-poly-constant (nvars coeff)
568 (change-class (make-term-constant nvars coeff) 'poly))
569
570(defgeneric universal-expt (x y)
571 (:documentation "Raises X to power Y.")
572 (:method ((x number) (y integer)) (expt x y))
573 (:method ((x t) (y integer))
574 (declare (type fixnum y))
575 (cond
576 ((minusp y) (error "universal-expt: Negative exponent."))
577 ((universal-zerop x) (if (zerop y) 1))
578 (t
579 (do ((k 1 (ash k 1))
580 (q x (multiply q q)) ;keep squaring
581 (p 1 (if (not (zerop (logand k y))) (multiply p q) p)))
582 ((> k y) p)
583 (declare (fixnum k)))))))
584
585(defgeneric poly-p (object)
586 (:documentation "Checks if an object is a polynomial.")
587 (:method ((self poly)) t)
588 (:method ((self t)) nil))
589
590(defmethod ->sexp :before ((self poly) &optional vars)
591 "Ensures that the number of variables in VARS maches the polynomial dimension of the
592polynomial SELF."
593 (with-slots (dimension)
594 self
595 (assert (= (length vars) dimension)
596 nil
597 "Number of variables ~S does not match the dimension ~S"
598 vars dimension)))
599
600(defmethod ->sexp ((self poly) &optional vars)
601 "Converts a polynomial SELF to a sexp."
602 (cons '+ (mapcar #'(lambda (x) (->sexp x vars))
603 (poly-termlist self))))
604
605(defparameter +list-marker+ :[
606 "A sexp with this head is considered a list of polynomials.")
607
608(defmethod ->sexp ((self cons) &optional vars)
609 (assert (eql (car self) +list-marker+))
610 (cons +list-marker+ (mapcar #'(lambda (p) (->sexp p vars)) (cdr self))))
611
612
613(defun poly-eval (expr vars order)
614 "Evaluate Lisp form EXPR to a polynomial or a list of polynomials in
615variables VARS. Return the resulting polynomial or list of
616polynomials. Standard arithmetical operators in form EXPR are
617replaced with their analogues in the ring of polynomials, and the
618resulting expression is evaluated, resulting in a polynomial or a list
619of polynomials in internal form. A similar operation in another computer
620algebra system could be called 'expand' or so."
621 (labels ((p-eval (p) (poly-eval p vars order))
622 (p-eval-list (plist) (mapcar #'p-eval plist)))
623 (cond
624 ((eq expr 0)
625 (make-instance 'poly :dimension (length vars)))
626 ((member expr vars :test #'equalp)
627 (let ((pos (position expr vars :test #'equalp)))
628 (make-poly-variable (length vars) pos)))
629 ((atom expr)
630 (make-poly-constant (length vars) expr))
631 ((eq (car expr) +list-marker+)
632 (cons +list-marker+ (p-eval-list (cdr expr))))
633 (t
634 (case (car expr)
635 (+ (reduce #'add (p-eval-list (cdr expr))))
636 (- (apply #'subtract (p-eval-list (cdr expr))))
637 (*
638 (if (endp (cddr expr)) ;unary
639 (p-eval (cadr expr))
640 (reduce #'multiply (p-eval-list (cdr expr)))))
641 (/
642 ;; A polynomial can be divided by a scalar
643 (cond
644 ((endp (cddr expr))
645 ;; A special case (/ ?), the inverse
646 (divide (cadr expr)))
647 (t
648 (let ((num (p-eval (cadr expr)))
649 (denom-inverse (apply #'divide (mapcar #'p-eval (cddr expr)))))
650 (multiply denom-inverse num)))))
651 (expt
652 (cond
653 ((member (cadr expr) vars :test #'equalp)
654 ;;Special handling of (expt var pow)
655 (let ((pos (position (cadr expr) vars :test #'equalp)))
656 (make-poly-variable (length vars) pos (caddr expr))))
657 ((not (and (integerp (caddr expr)) (plusp (caddr expr))))
658 ;; Negative power means division in coefficient ring
659 ;; Non-integer power means non-polynomial coefficient
660 expr)
661 (t (universal-expt (p-eval (cadr expr)) (caddr expr)))))
662 (otherwise
663 (error "Cannot evaluate as polynomial: ~A" expr)))))))
Note: See TracBrowser for help on using the repository browser.