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

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

* empty log message *

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