Rename *ll* and *ul* to ll and ul in method-by-limits
[maxima.git] / src / algsys.lisp
blob9b0560fd04863444c13f782d8f8c5eba4371f804
1 ;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; The data in this file contains enhancements. ;;;;;
4 ;;; ;;;;;
5 ;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
6 ;;; All rights reserved ;;;;;
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; (c) Copyright 1981 Massachusetts Institute of Technology ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11 (in-package :maxima)
13 (macsyma-module algsys)
15 (load-macsyma-macros ratmac)
17 ;;This is the algsys package.
19 ;;It solves systems of polynomial equations by straight-forward
20 ;;resultant hackery. Other possible methods seem worse:
21 ;;the Buchberger-Spear canonical ideal basis algorithm is slow,
22 ;;and the "resolvent" method (see van der Waerden, section 79)
23 ;;blows up in time and space. The "resultant"
24 ;;method (see the following sections of van der Waerden and
25 ;;Macaulay's book - Algebraic Theory of Modular Systems) looks
26 ;;good, but it requires the evaluation of large determinants.
27 ;;Unless some hack (such as prs's for evaluating resultants of
28 ;;two polynomials) is developed for multi-polynomial resultants,
29 ;;this method will remain impractical.
31 ;;Some other possible ideas: Keeping the total number of equations constant,
32 ;;in an effort to reduce extraneous solutions, or Reducing to a linear
33 ;;equation before taking resultants.
35 (declare-top (special $algdelta
36 *roots *failures $ratprint
37 *tvarxlist* *ivar* errset))
39 ;;note if $algepsilon is too large you may lose some roots.
41 (defmvar $algdelta 1e-5 )
43 (defmvar $realonly nil "If t only real solutions are returned.")
45 (defmvar realonlyratnum nil
46 "A REALROOTS hack for RWG. Causes ALGSYS to retain rational numbers
47 returned by REALROOTS when REALONLY is TRUE."
48 in-core)
50 (defmvar $algexact nil "If t ALGSYS always calls SOLVE to try to MAXIMA-FIND exact
51 solutions.")
53 (defmvar algnotexact nil
54 "A hack for RWG for univariate polys. Causes SOLVE not to get called
55 so that sqrts and cube roots will not be generated."
56 in-core)
58 (defmacro merrset (l)
59 `(let ((errset t) (unbind (cons bindlist loclist)) val)
60 (setq val (errset ,l))
61 (when (null val) (errlfun1 unbind))
62 val))
64 (defmfun $algsys (lhslist varxlist &aux varlist genvar)
65 ;; (declare (special varxlist)) ;;??
66 (setq $%rnum_list (list '(mlist)))
67 (cond ((not ($listp lhslist))
68 (merror (intl:gettext "algsys: first argument must be a list; found ~M") lhslist))
69 ((not ($listp varxlist))
70 (merror (intl:gettext "algsys: second argument must be a list; found ~M") varxlist)))
71 (let ((tlhslist nil) (*tvarxlist* nil) (solnlist nil) ($ratprint nil)
72 ($ratepsilon 1e-7)
73 ($keepfloat nil)
74 (varlist (reverse (cdr varxlist)))
75 (genvar nil) ($ratfac nil) ($breakup nil)
76 ($solvefactors nil) (*roots nil) (*failures nil)
77 (*ivar* nil) ($polyfactor nil) (varxl nil)
78 ($infeval nil) ($numer nil) ($float nil)
79 (numerflg $numer))
80 (dolist (var (cdr ($listofvars (list '(mlist simp) lhslist varxlist))))
81 (if (and (symbolp var) (not (constant var)))
82 (setq varxl (cons var varxl))))
83 (orderpointer varlist)
84 (setq tlhslist
85 (mapcar #'(lambda (q) (cadr (ratf (meqhk q))))
86 (cdr lhslist)))
87 (setq *ivar* (caadr (ratf '$%i)))
88 (setq *tvarxlist*
89 (mapcar #'(lambda (q)
90 (if (mnump q)
91 (merror (intl:gettext "algsys: variable cannot be a number; found ~M") q)
92 (caadr (ratf q))))
93 (cdr varxlist)))
94 (putorder *tvarxlist*)
95 (mbinding (varxl varxl)
96 (setq solnlist
97 (mapcar #'(lambda (q)
98 (addmlist
99 (bbsorteqns
100 (addparam (roundroots1 q) varxlist))))
101 (algsys tlhslist))))
102 (remorder *tvarxlist*)
103 (setq solnlist (addmlist solnlist))
104 (if numerflg
105 (let (($numer t) ($float t))
106 (resimplify solnlist))
107 solnlist)))
109 ;;; (CONDENSESOLNL TEMPSOLNL)
111 ;;; Condense a solution list, discarding any solution that is a special case of
112 ;;; another one. (For example, if the list contained [x=1, y=1] as a solution,
113 ;;; but also just [x=1], then the first solution would be discarded)
115 ;;; Destructively modifies TEMPSOLNL
116 (defun condensesolnl (tempsolnl)
117 (let (solnl)
118 (mapl (lambda (q)
119 (unless (subsetl (cdr q) (car q))
120 (push (car q) solnl)))
121 (stable-sort tempsolnl #'(lambda (a b) (> (length a) (length b)))));FIXME consider a total order function with #'sort
122 solnl))
124 ;;; (SUBSETL L1 S2)
126 ;;; Check whether some element of L1 is a subset of S2 (comparing elements with
127 ;;; ALIKE1). As a special case, if S2 is '(NIL) then return true.
128 (defun subsetl (l1 s2)
129 (or (equal s2 '(nil))
130 (member-if (lambda (x)
131 (subsetp x s2 :test #'alike1))
132 l1)))
134 (defun algsys (tlhslist)
135 (condensesolnl
136 (mapcan #'algsys0
137 (distrep (mapcar #'lofactors tlhslist)))))
139 (defun algsys0 (tlhslist)
140 (cond ((null tlhslist) (list nil))
141 ((equal tlhslist (list nil)) nil)
142 (t (algsys1 tlhslist))))
144 (defun algsys1 (tlhslist)
145 (destructuring-bind (resulteq . vartorid) (findleastvar tlhslist)
146 (bakalevel (algsys
147 (mapcar #'(lambda (q)
148 (if (among vartorid q)
149 (presultant q resulteq vartorid)
151 (remove resulteq tlhslist :test #'equal)))
152 tlhslist vartorid)))
154 (defun addmlist (l)
155 (cons '(mlist) l))
157 (defmacro what-the-$ev (&rest l)
158 ;; macro for calling $EV when you are not really
159 ;; sure why you are calling it, but you want the
160 ;; features of multiple evaluations and unpredictabiltiy
161 ;; anyway.
162 `(meval (list '($ev) ,@l)))
164 (defun rootsp (asolnset eqn) ;eqn is ((MLIST) eq deriv)
165 (let (rr ($keepfloat t) ($numer t) ($float t))
166 (setq rr (what-the-$ev eqn asolnset)) ; ratsimp?
167 (cond ((and (complexnump (cadr rr)) (complexnump (caddr rr)))
168 (< (cabs (cadr rr))
169 (* $algdelta (max 1 (cabs (caddr rr))))))
170 (t nil))))
172 (defun round1 (a)
173 (cond ((floatp a)
174 (setq a (maxima-rationalize a))
175 (fpcofrat1 (car a) (cdr a)))
176 (t a)))
178 (defun roundrhs (eqn)
179 (list (car eqn) (cadr eqn) (round1 (caddr eqn))))
181 (defun roundroots1 (lsoln)
182 (mapcar #'roundrhs lsoln))
184 (defun bbsorteqns (l)
185 (sort (copy-list l) #'orderlessp))
187 (defun putorder (tempvarl)
188 (do ((n 1 (1+ n))
189 (tempvarl tempvarl (cdr tempvarl)))
190 ((null tempvarl) nil)
191 (putprop (car tempvarl) n 'varorder)))
193 (defun remorder (gvarl)
194 (mapc #'(lambda (x) (remprop x 'varorder)) gvarl))
197 (defun orderlessp (eqn1 eqn2)
198 (< (get (caadr (ratf (cadr eqn1))) 'varorder)
199 (get (caadr (ratf (cadr eqn2))) 'varorder)))
201 (defun addparam (asolnsetl varxlist)
202 (cond ((= (length asolnsetl) (length *tvarxlist*))
203 asolnsetl)
205 (do ((tvarxl (cdr varxlist) (cdr tvarxl))
206 (defvar (mapcar #'cadr asolnsetl))
207 (var) (param))
208 ((null tvarxl) asolnsetl)
209 (setq var (car tvarxl))
210 (cond ((memalike var defvar) nil)
211 (t (setq param (make-param)
212 asolnsetl (cons (list '(mequal) var param)
213 (cdr (maxima-substitute
214 param var
215 (addmlist asolnsetl)))))))))))
217 ;; Do not remove this (and the unspecial below). While the functions
218 ;; that reference *vardegs* have special declarations for it,
219 ;; something is missing. If this is removed, then the testsuite fails
220 ;; where algsys produces the same solutions but in a different order.
221 ;; More troubling is that tests from rtest_odelin produces incorrect
222 ;; results and appears to hang somewhere after problem 57.
223 (declare-top (special *vardegs*))
225 ;;; (FINDLEASTVAR LHSL)
227 ;;; Iterate over the polynomials in LHSL, trying to find a "least var", which is
228 ;;; a variable that will hopefully be easiest to solve for. Variables from
229 ;;; *TVARXLIST* and their products are considered.
231 ;;; For example, if *TVARXLIST* contains x, y and we only considered the
232 ;;; polynomial x^3 + y^2 + x then we'd have a least var of y with degree 2. If c
233 ;;; is not in *TVARXLIST* then we'd get the same answer from x^3 + c*y^2 + x
234 ;;; because such variables are just ignored. However, x^3 + x^2*y^2 would yield
235 ;;; x with degree 3 because the mixed term x^2*y^2 has higher total degree.
237 ;;; The function returns the polynomial with the variable with minimal maximum
238 ;;; degree (as described above), together with that variable.
240 ;;; Mixed terms are mostly ignored, but consider this pair of polynomials:
241 ;;; [x*y+1, x^3+1]. In the first polynomial, the only non-constant term is
242 ;;; mixed. Its degree in the first polynomial is 2 which is less than 3, so that
243 ;;; first polynomial is returned along with its leading variable.
244 (defun findleastvar (lhsl)
245 (let ((*vardegs*)
246 (leasteq) (leastvar)
247 ;; most-positive-fixnum is larger than any polynomial degree, so we can
248 ;; initialise with this and be certain to replace it on the first
249 ;; iteration.
250 (leastdeg most-positive-fixnum))
251 (declare (special *vardegs*))
252 (loop
253 for teq in lhsl
254 for *vardegs* = (getvardegs teq)
255 for tdeg = (killvardegsc teq)
256 do (loop
257 for q in *vardegs*
258 if (<= (cdr q) leastdeg)
259 do (setq leastdeg (cdr q)
260 leasteq teq
261 leastvar (car q)))
262 if (< tdeg leastdeg)
263 do (setq leastdeg tdeg
264 leasteq teq
265 leastvar (car teq)))
266 (cons leasteq leastvar)))
268 ;;; DO-POLY-TERMS
270 ;;; Iterate over the terms in a polynomial, POLY, executing BODY with LE and LC
271 ;;; bound to the exponent and coefficient respectively of each term. If RESULT
272 ;;; is non-NIL, it is evaluated to give a result when the iteration finishes.
273 (defmacro do-poly-terms ((le lc poly &optional result) &body body)
274 (let ((pt (gensym)))
275 `(do ((,pt (p-terms ,poly) (pt-red ,pt)))
276 ((null ,pt) ,result)
277 (let ((,le (pt-le ,pt))
278 (,lc (pt-lc ,pt)))
279 ,@body))))
281 ;;; (KILLVARDEGSC POLY)
283 ;;; For each monomial in POLY that is mixed in the variables in *VARDEGS*
284 ;;; (i.e. has more than one variable from *VARDEGS* with positive exponent),
285 ;;; iterate over all but the first variable, checking to see whether its degree
286 ;;; in the monomial is at least as high as that in *VARDEGS*. If so, delete that
287 ;;; variable and its degree from *VARDEGS*.
289 ;;; Returns the maximum total degree of any term in the polynomial, summing
290 ;;; degrees over the variables in *VARDEGS*.
291 (defun killvardegsc (poly)
292 (if (pconstp poly)
294 (let ((tdeg 0))
295 (do-poly-terms (le lc poly tdeg)
296 (setf tdeg (max tdeg (+ le
297 (if (= le 0)
298 (killvardegsc lc)
299 (killvardegsn lc)))))))))
301 ;;; (KILLVARDEGSN POLY)
303 ;;; For each monomial in POLY, look at its degree in each variable in
304 ;;; *TVARXLIST*. If the degree is at least as high as that recorded in
305 ;;; *VARDEGS*, delete that variable and its degree from *VARDEGS*.
307 ;;; Returns the maximum total degree of any term in the polynomial, summing
308 ;;; degrees over the variables in *VARDEGS*.
309 (defun killvardegsn (poly)
310 (declare (special *vardegs*))
311 (cond
312 ((pconstp poly) 0)
314 (let ((x (assoc (p-var poly) *vardegs* :test #'eq)))
315 (when (and x (<= (cdr x) (p-le poly)))
316 (setq *vardegs* (delete x *vardegs* :test #'equal))))
317 (let ((tdeg 0))
318 (do-poly-terms (le lc poly tdeg)
319 (setf tdeg (max tdeg (+ le (killvardegsn lc)))))))))
321 ;;; (GETVARDEGS POLY)
323 ;;; Return degrees of POLY's monomials in the variables for which we're
324 ;;; solving. Ignores mixed terms (like x*y). Results are returned as an alist
325 ;;; with elements (VAR . DEGREE).
327 ;;; For example, if *TVARXLIST* is '(x y) and we are looking at the polynomial
328 ;;; x^2 + y^2, we have
330 ;;; (GETVARDEGS '(X 2 1 0 (Y 2 1))) => ((X . 2) (Y . 2))
332 ;;; Variables that aren't in *TVARXLIST* are assumed to come after those that
333 ;;; are. For example c*x^2 would look like
335 ;;; (GETVARDEGS '(X 2 (C 1 1))) => ((X . 2))
337 ;;; Mixed powers are ignored, so x*y + y looks like:
339 ;;; (GETVARDEGS '(X 1 (Y 1 1) 0 (Y 1 1))) => ((Y . 1))
341 (defun getvardegs (poly)
342 (cond ((pconstp poly) nil)
343 ((pconstp (caddr poly))
344 (cons (cons (car poly) (cadr poly))
345 (getvardegs (ptterm (cdr poly) 0))))
346 (t (getvardegs (ptterm (cdr poly) 0)))))
348 (declare-top (unspecial *vardegs*))
350 (defun pconstp (poly)
351 (or (atom poly) (not (member (car poly) *tvarxlist* :test #'eq))))
353 ;;; (PFREEOFMAINVARSP POLY)
355 ;;; If POLY isn't a polynomial in the variables for which we're solving,
356 ;;; disrep it and simplify appropriately.
357 (defun pfreeofmainvarsp (poly)
358 (if (or (atom poly)
359 (member (car poly) *tvarxlist* :test #'eq))
360 poly
361 (simplify-after-subst (pdis poly))))
363 ;;; (LOFACTORS POLY)
365 ;;; If POLY is a polynomial in one of the variables for which we're solving,
366 ;;; then factor it into a list of factors (where the result returns factors
367 ;;; alternating with their multiplicity in the same way as PFACTOR).
369 ;;; If POLY is not a polynomial in one of the solution variables, return NIL.
370 (defun lofactors (poly)
371 (let ((main-var-poly (pfreeofmainvarsp poly)))
372 (cond
373 ((pzerop main-var-poly) '(0))
375 ;; If POLY isn't a polynomial in our chosen variables, RADCAN will return
376 ;; something whose CAR is a cons. In that case, or if the polynomial is
377 ;; something like a number, there are no factors to extract.
378 ((or (atom main-var-poly)
379 (not (atom (car main-var-poly))))
380 nil)
383 (do ((tfactors (pfactor main-var-poly) (cddr tfactors))
384 (lfactors))
385 ((null tfactors) lfactors)
386 (let ((main-var-factor (pfreeofmainvarsp (car tfactors))))
387 (cond
388 ((pzerop main-var-factor)
389 (return (list 0)))
390 ((and (not (atom main-var-factor))
391 (atom (car main-var-factor)))
392 (push (pabs main-var-factor) lfactors)))))))))
394 ;;; (COMBINEY LISTOFL)
396 ;;; Combine "independent" lists in LISTOFL. If all the lists have empty pairwise
397 ;;; intersections, this returns all selections of items, one from each
398 ;;; list. Destructively modifies LISTOFL.
400 ;;; Selections are built up starting at the last list. When building, if there
401 ;;; would be a repeated element because the list we're about to select from has
402 ;;; nonempty intersection with an existing partial selections then elements from
403 ;;; the current list aren't added to this selection.
405 ;;; COMBINEY guarantees that no list in the result has two elements that are
406 ;;; ALIKE1 each other.
408 ;;; This is used to enumerate combinations of solutions from multiple
409 ;;; equations. Each entry in LISTOFL is a list of possible solutions for an
410 ;;; equation. A solution for the set of equations is found by looking at
411 ;;; (compatible) combinations of solutions.
413 ;;; (I don't know why the non-disjoint behaviour works like this. RJS 1/2015)
414 (defun combiney (listofl)
415 (unless (member nil listofl)
416 (combiney1 (delete '(0) listofl :test #'equal))))
418 ;;; DB (2016-09-13) Commit a158b1547 introduced a regression (SF bug 3210)
419 ;;; It: - restructured combiney
420 ;;; - used ":test #'alike1" in place of "test #'equal" in combiney1
421 ;;; Reverting the change to combiney1 restores previous behaviour.
422 ;;; I don't understand algsys internals and haven't analysed this further.
423 (defun combiney1 (listofl)
424 (cond ((null listofl) (list nil))
425 (t (mapcan #'(lambda (r)
426 (if (intersection (car listofl) r :test #'equal)
427 (list r)
428 (mapcar #'(lambda (q) (cons q r)) (car listofl))))
429 (combiney1 (cdr listofl))))))
431 (defun midpnt (l)
432 (rhalf (rplus* (car l) (cadr l))))
434 (defun rflot (l)
435 (let ((rr (midpnt l)))
436 (if realonlyratnum (list '(rat) (car rr) (cdr rr))
437 (/ (+ 0.0 (car rr)) (cdr rr)))))
439 (defun memberroot (a x eps)
440 (cond ((null x) nil)
441 ((< (abs (- a (car x)))
442 (/ (+ 0.0 (car eps)) (cdr eps)))
444 (t (memberroot a (cdr x) eps))))
446 (defun commonroots (eps solnl1 solnl2)
447 (cond ((null solnl1) nil)
448 ((memberroot (car solnl1) solnl2 eps)
449 (cons (car solnl1) (commonroots eps (cdr solnl1) solnl2)))
450 (t (commonroots eps (cdr solnl1) solnl2))))
452 ;; (REMOVE-MULT L)
454 ;; Return a copy of L with all elements in odd positions removed. This is so
455 ;; named because some code returns roots and multiplicities in the format
457 ;; (ROOT0 MULT0 ROOT1 MULT1 ... ROOTN MULTN)
459 ;; Calling REMOVE-MULT on such a list removes the multiplicities.
460 (defun remove-mult (l)
461 (and l (cons (car l) (remove-mult (cddr l)))))
463 (defun punivarp (poly)
464 ;; Check if called with the number zero, return nil.
465 ;; Related bugs: SF[609466], SF[1430379], SF[1663399]
466 (when (and (numberp poly) (= poly 0)) (return-from punivarp nil))
467 (do ((l (cdr poly) (cddr l)))
468 ((null l) t)
469 (or (numberp (cadr l))
470 (and (eq (caadr l) *ivar*)
471 (punivarp (cadr l)))
472 (return nil))))
474 ;; (REALONLY ROOTSL)
476 ;; Return only the elements of ROOTSL whose $IMAGPART simplifies to zero with
477 ;; SRATSIMP. (Note that this a subset of "the real roots", because SRATSIMP may
478 ;; not be able to check that a given expression is zero)
479 (defun realonly (rootsl)
480 (remove-if-not (lambda (root)
481 (equal 0 (sratsimp ($imagpart (caddr root)))))
482 rootsl))
485 (defun presultant (p1 p2 var)
486 (cadr (ratf (simplify ($resultant (pdis p1) (pdis p2) (pdis (list var 1 1)))))))
488 (defun ptimeftrs (l)
489 (prog (ll)
490 (setq ll (cddr l))
491 (cond ((null ll) (return (car l)))
492 (t (return (ptimes (car l) (ptimeftrs ll)))))))
494 ;; (EBAKSUBST SOLNL LHSL)
496 ;; Substitute a solution for one variable back into the "left hand side
497 ;; list". If the equation had to be solved for multiple variables, this allows
498 ;; us to use the solution for a first variable to feed in to the equation for
499 ;; the next one along.
501 ;; As well as doing the obvious substitution, EBAKSUBST also simplifies with
502 ;; $RADCAN (presumably, E stands for Exponential)
503 (defun ebaksubst (solnl lhsl)
504 (mapcar #'(lambda (q) (ebaksubst1 solnl q)) lhsl))
506 (defun ebaksubst1 (solnl q)
507 (let ((e ($substitute `((mlist) ,@solnl) (pdis q))))
508 (setq e (simplify-after-subst e))
509 (cadr (ratf e))))
511 (defun baksubst (solnl lhsl)
512 (setq lhsl (delete 't (mapcar #'(lambda (q) (car (merrset (baksubst1 solnl q))))
513 lhsl)
514 :test #'eq)) ;catches arith. ovfl
515 (if (member nil lhsl :test #'eq)
516 (list nil)
517 lhsl))
519 (defun baksubst1 (solnl poly)
520 (let* (($keepfloat (not $realonly)) ;sturm1 needs poly with
521 (poly1 ;integer coefs
522 (cdr (ratf (what-the-$ev (pdis poly)
523 (cons '(mlist) solnl)
524 '$numer)))))
525 (cond ((and (complexnump (pdis (car poly1)))
526 (numberp (cdr poly1)))
527 (rootsp (cons '(mlist) solnl)
528 (list '(mlist) (pdis poly) (tayapprox poly))))
529 (t (car poly1)))))
531 (defun complexnump (p)
532 (let ((p (cadr (ratf ($ratsimp p)))))
533 (or (numberp p)
534 (eq (pdis (pget (car p))) '$%i))))
536 ;; (SIMPLIFY-AFTER-SUBST EXPR)
538 ;; Simplify EXPR after substitution of a partial solution.
540 ;; Focus is on constant expressions:
541 ;; o failure to reduce a constant expression that is equivalent
542 ;; to zero causes solutions to be falsely rejected
543 ;; o some operations, such as the reduction of nested square roots,
544 ;; requires known sign and ordering of all terms
545 ;; o inappropriate simplification by $RADCAN introduced errors
546 ;; $radcan(sqrt(-1/(1+%i))) => exhausts heap
547 ;; $radcan(sqrt(6-3^(3/2))) > 0 => sqrt(sqrt(3)-2)*sqrt(3)*%i < 0
549 ;; Problems from bug reports showed that further simplification of
550 ;; non-constant terms, with incomplete information, could lead to
551 ;; missed roots or unwanted complexity.
553 ;; $ratsimp with algebraic:true can transform
554 ;; sqrt(2)*sqrt(-1/(sqrt(3)*%i+1)) => (sqrt(3)*%i)/2+1/2
555 ;; but $rectform is required for
556 ;; sqrt(sqrt(3)*%i-1)) => (sqrt(3)*%i)/sqrt(2)+1/sqrt(2)
557 ;; and $rootscontract is required for
558 ;; sqrt(34)-sqrt(2)*sqrt(17) => 0
559 (defun simplify-after-subst (expr)
560 "Simplify expression after substitution"
561 (let (($keepfloat t) ($algebraic t) (e expr)
562 e1 e2 tmp (growth-factor 1.2)
563 (genvar nil) (varlist nil)
564 ($rootsconmode t) ($radexpand t))
565 ;; Try two approaches
566 ;; 1) ratsimp
567 ;; 2) if $constantp(e) sqrtdenest + rectform + rootscontract + ratsimp
568 ;; take smallest expression
569 (setq e1 (sratsimp e))
570 (if ($constantp e)
571 (progn
572 (setq e ($sqrtdenest e))
573 ;; Rectform does more than is wanted. A function that denests and
574 ;; rationalizes nested complex radicals would be better.
575 ;; Limit expression growth. The factor is based on trials.
576 (setq tmp ($rectform e))
577 (when (< (conssize tmp) (* growth-factor (conssize e)))
578 (setq e tmp))
579 (setq e ($rootscontract e))
580 (setq e2 (sratsimp e))
581 (if (< (conssize e1) (conssize e2)) e1 e2))
582 e1)))
584 ;; (BAKALEVEL SOLNL LHSL VAR)
586 ;;; Recursively try to find a solution to the list of polynomials in LHSL. SOLNL
587 ;;; should be a non-empty list of partial solutions (for example, these might be
588 ;;; solutions we've already found for x when we're solving for x and y).
590 ;;; BAKALEVEL works over each partial solution. This should itself be a list. If
591 ;;; it is non-nil, it is a list of equations for the variables we're trying to
592 ;;; solve for ("x = 3 + y" etc.). In this case, BAKALEVEL substitutes these
593 ;;; solutions into the system of equations and then tries to solve the
594 ;;; result. On success, it merges the partial solutions in SOLNL with those it
595 ;;; gets recursively.
597 ;;; If a partial solution is nil, we don't yet have any partial information. If
598 ;;; there is only a single polynomial to solve in LHSL, we try to solve it in
599 ;;; the given variable, VAR. Otherwise we choose a variable of lowest degree
600 ;;; (with FINDLEASTVAR), solve for that (with CALLSOLVE) and then recurse.
601 (defun bakalevel (solnl lhsl var)
602 (loop for q in solnl nconcing (bakalevel1 q lhsl var)))
604 (defun bakalevel1 (solnl lhsl var)
605 (cond
606 ((not (exactonly solnl))
607 (mergesoln solnl (apprsys (baksubst solnl lhsl))))
608 (solnl
609 (mergesoln solnl (algsys (ebaksubst solnl lhsl))))
610 ((cdr lhsl)
611 (let ((poly-and-var (findleastvar lhsl)))
612 (bakalevel (callsolve poly-and-var)
613 (remove (car poly-and-var) lhsl :test #'equal)
614 var)))
615 ;; LHSL contains one polynomial and we try to solve in one variable VAR.
616 ;; CALLSOLVE can miss solutions when the coefficient of the highest order
617 ;; term in VAR contains other variables in *TVARXLIST**.
618 ;; BAKALEVELSOLVE looks for these missed solutions.
619 (t (nconc (callsolve (cons (car lhsl) var))
620 (bakalevelsolve (car lhsl) var)))))
623 ;; (EVERY-ATOM PRED X)
625 ;; Evaluates to true if (PRED Y) is true for every atom Y in the cons tree X.
626 (defun every-atom (pred x)
627 (if (atom x)
628 (funcall pred x)
629 (and (every-atom pred (car x))
630 (every-atom pred (cdr x)))))
632 ;; (EXACTONLY SOLNL)
634 ;; True if the list of solutions doesn't contain any terms that look inexact
635 ;; (just floating point numbers, unless realonlyratnum is true)
636 (defun exactonly (solnl)
637 (every-atom (lambda (x)
638 (and (not (floatp x))
639 (or (null realonlyratnum)
640 (not (eq x 'rat)))))
641 solnl))
643 ;; (MERGESOLN ASOLN SOLNL)
645 ;; For each solution S in SOLNL, evaluate each element of ASOLN in light of S
646 ;; and, collecting up the results and prepending them to S. If evaluating an
647 ;; element in light of S caused an error, ignore the combination of ASOLN and S.
648 (defun mergesoln (asoln solnl)
649 (let ((unbind (cons bindlist loclist))
650 (errorsw t))
651 (macrolet ((catch-error-t (&body body)
652 `(let ((result (catch 'errorsw ,@body)))
653 (when (eq result t)
654 (errlfun1 unbind))
655 result)))
656 (loop
657 for q in solnl
658 for result =
659 (catch-error-t
660 (append (mapcar (lambda (r)
661 (what-the-$ev r (cons '(mlist) q)))
662 asoln)
664 if (not (eq result t)) collect result))))
666 ;; (CALLSOLVE PV)
668 ;; Try to solve a polynomial with respect to the given variable. PV is a cons
669 ;; pair (POLY . VAR). On success, return a list of solutions. Each solution is
670 ;; itself a list, whose elements are equalities (one for each variable in the
671 ;; equation). If we determine that there aren't any solutions, return '(NIL).
673 ;; If POLY is in more than one variable or if it can clearly be solved by the
674 ;; quadratic formula (BIQUADRATICP), we always call SOLVE to try to get an exact
675 ;; solution. Similarly if the user has set the $ALGEXACT variable to true.
677 ;; Otherwise, or if SOLVE fails, we try to find an approximate solution with a
678 ;; call to CALLAPPRS.
680 ;; SOLVE introduces solutions with nested radicals, which causes problems
681 ;; in EBAKSUBST1. Try to clean up the solutions now.
682 (defun callsolve (pv)
683 (mapcar #'callsolve2 (callsolve1 pv)))
685 (defun callsolve1 (pv)
686 (let ((poly (car pv))
687 (var (cdr pv))
688 (varlist varlist)
689 (genvar genvar)
690 (*roots nil)
691 (*failures nil)
692 ($programmode t))
693 (cond ((or $algexact
694 (not (punivarp poly))
695 (biquadraticp poly))
696 ;; Call SOLVE to try to solve POLY. When it returns, the solutions it
697 ;; found end up in *ROOTS. *FAILURES contains expressions that, if
698 ;; solved, would lead to further solutions.
699 (solve (pdis poly) (pdis (list var 1 1)) 1)
700 (if (null (or *roots *failures))
701 ;; We're certain there are no solutions
702 (list nil)
703 ;; Try to find approximate solutions to the terms that SOLVE gave
704 ;; up on (in *FAILURES) and remove any roots from SOLVE that
705 ;; aren't known to be real if $REALONLY is true.
706 (append (mapcan (lambda (q)
707 (callapprs (cadr (ratf (meqhk q)))))
708 (remove-mult *failures))
709 (mapcar #'list
710 (if $realonly
711 (realonly (remove-mult *roots))
712 (remove-mult *roots))))))
713 (t (callapprs poly)))))
715 (defun callsolve2 (l)
716 "Simplify solution returned by callsolve1"
717 ;; l is a single element list '((mequal simp) var expr)
718 (let ((e (first l)))
719 `(((,(mop e)) ,(second e) ,(simplify-after-subst (third e))))))
721 ;;; (BIQUADRATICP POLY)
723 ;;; Check whether POLY is biquadratic in its main variable: either of degree at
724 ;;; most two or of degree four and with only even powers.
725 (defun biquadraticp (poly)
726 (or (atom poly)
727 (if algnotexact
728 (< (p-le poly) 2)
729 (or (< (p-le poly) 3)
730 (and (= (p-le poly) 4) (biquadp1 (p-red poly)))))))
732 (defun biquadp1 (terms)
733 (or (null terms)
734 (and (or (= (pt-le terms) 2) (= (pt-le terms) 0))
735 (biquadp1 (pt-red terms)))))
737 ;;; (CALLAPPRS POLY)
739 ;;; Try to find approximate solutions to POLY, which should be a polynomial in a
740 ;;; single variable. Uses STURM1 if we're only after real roots (because
741 ;;; $REALONLY is set). Otherwise, calls $ALLROOTS.
742 (defun callapprs (poly)
743 (unless (punivarp poly)
744 (merror (intl:gettext "algsys: Couldn't reduce system to a polynomial in one variable.")))
745 (let ($dispflag)
746 (if $realonly
747 (let ((dis-var (pdis (list (car poly) 1 1))))
748 (mapcar #'(lambda (q)
749 (list (list '(mequal) dis-var (rflot q))))
750 (sturm1 poly (cons 1 $algepsilon))))
751 (mapcar #'list
752 (let* (($programmode t)
753 (roots (cdr ($allroots (pdis poly)))))
754 (if (eq (caaar roots) 'mequal)
755 roots
756 (cdr roots)))))))
758 (defun apprsys (lhsl)
759 (cond ((null lhsl) (list nil))
761 (do ((tlhsl lhsl (cdr tlhsl))) (nil)
762 (cond ((null tlhsl)
763 ;; SHOULD TRY TO BE MORE SPECIFIC: "TOO COMPLICATED" IN WHAT SENSE??
764 (merror (intl:gettext "algsys: system too complicated; give up.")))
765 ((pconstp (car tlhsl)) (return nil))
766 ((punivarp (car tlhsl))
767 (return (bakalevel (callapprs (car tlhsl))
768 lhsl nil))))))))
770 (defun tayapprox (p)
771 (cons '(mplus)
772 (mapcar #'(lambda (x)
773 (list '(mycabs) (pdis (ptimes (list x 1 1)
774 (pderivative p x)))))
775 (listovars p))))
777 (defun mycabs (x)
778 (and (complexnump x) (cabs x)))
780 ;;; (DISTREP LOL)
782 ;;; Take selections from LOL, a list of lists, using COMBINEY. When used by
783 ;;; ALGSYS, the elements of the lists are per-equation solutions for some system
784 ;;; of equations. COMBINEY combines the per-equation solutions into prospective
785 ;;; solutions for the entire system.
787 ;;; These prospective solutions are then filtered with CONDENSESOLNL, which
788 ;;; discards special cases of more general solutions.
790 ;;; (I don't understand why this reversal has to be here, but we get properly
791 ;;; wrong solutions to some of the testsuite functions without it. Come back to
792 ;;; this... RJS 1/2015)
793 (defun distrep (lol)
794 (condensesolnl (mapcar #'reverse (combiney lol))))
796 (defun exclude (l1 l2)
797 (cond ((null l2)
798 nil)
799 ((member (car l2) l1 :test #'equal)
800 (exclude l1 (cdr l2)))
802 (cons (car l2) (exclude l1 (cdr l2))))))
804 ;;; (BAKALEVELSOLVE P VAR)
806 ;;; P is a polynomial in VAR. VAR may not be the main variable.
807 ;;; We are trying to solve P in terms of the single variable VAR, so
808 ;;; the other solution variables (in *TVARXLIST*) are treated as constants.
810 ;;; CALLSOLVE can miss solutions when the leading (highest order)
811 ;;; coefficient C of VAR contains other variables in *TVARXLIST*.
812 ;;; Apparently C is implicitly assumed to be non-zero.
814 ;;; Seek these missing solutions by:
815 ;;; - finding N, the highest power of VAR in P
816 ;;; - separating P into C*VAR^N + D (VAR may not be the main variable in P)
817 ;;; - look for solutions of form (C=0,D=0)
819 ;;; An example is solving a*b-c*d in terms of [a,b,c,d]
821 (defun bakalevelsolve (p var)
822 (let (n c d)
823 (cond
824 ;; a bare coefficient isn't an equation
825 ((pcoefp p) nil)
826 ;; N is highest power of VAR in polynomial P.
827 ;; No equation in VAR if N=0. No solution.
828 ((= (setq n (p-hipow-var p var)) 0) nil)
830 ;; express P as C*VAR^N + D
831 (setf (values c d) (p-coef-x p var n))
832 (if (p-allvars c) ; Does C contain any variables from *TVARXLIST*
833 (algsys `(,c ,d)) ; Try and solve C=0 and D=0 using algsys
834 nil))))) ; C is freeof of *TVARXLIST*. No solution.
836 ;;; De-duplicated list of variables in polynomial P
837 (defun p-allvars (p)
838 (unless (pcoefp p) (remove-duplicates (p-allvars1 p))))
840 ;;; List of variables in polynomial P. May contain duplicates.
841 (defun p-allvars1 (p)
842 (unless (pcoefp p)
843 (cons
844 (p-var p) ; the main variable of poly
845 (loop ; Recusively extract variables from coefficients.
846 for (nil ci) on (p-terms p) by #'cddr
847 if (not (pcoefp ci)) append (p-allvars1 ci)))))
849 ;;; Maximum degree of variable V in polynomial P
850 ;;; V may not be the main variable in P
851 (defun p-hipow-var (p v)
852 (cond
853 ((pcoefp p) 0) ; bare coefficient has degree 0
854 ((eq (p-var p) v) (p-le p)) ; V is main variable - return leading exponent
856 (loop ; Recusively search through coefficients of p
857 for (nil c) on (p-terms p) by #'cddr
858 maximize (p-hipow-var c v)))))
860 ;;; (P-COEF-X P X N)
862 ;;; Separate multivariable polynomial P with main variable V into C*x^n + D
863 ;;; where X may be different to V. Return (values C D)
864 ;;; Assumes terms of P are in decending order
865 (defun p-coef-x (p x n)
866 (cond
867 ((pcoefp p) ; p is a bare coefficient
868 (if (= n 0)
869 (values p (pzero)) ; c = bare coef, d = 0
870 (values (pzero) p))) ; c = 0, d = bare coef
871 ((eq (p-var p) x) ; main variable V in P is X
872 (p-coef-main p n))
874 ;; P is polynomial with main variable V other than X
875 ;; iterate over coefficients ai
876 ;; find (ci di) such that ai = ci*x^n + di
877 ;; C = ck*v^k + ... + c0*v^0, a polynomial in v
878 ;; D = dk*v^k + ... + d0*v^0, a polynomial in v
879 (loop
880 with terms = (p-terms p) with v = (p-var p) with ci with di
881 for (i ai) on terms by #'cddr
882 do (setf (values ci di) (p-coef-x ai x n))
883 unless (pzerop ci) append `(,i ,ci) into cterms
884 unless (pzerop di) append `(,i ,di) into dterms
885 finally (return (values (psimp v cterms) (psimp v dterms)))))))
888 ;;; (P-COEF-MAIN P N)
890 ;;; Separate multivariable polynomial P with main variable X into C*x^n + D
891 ;;; Return (values C D)
892 ;;; Assumes terms of P are in decending order
893 (defun p-coef-main (p n)
894 (if (pcoefp p) ; bare coefficient
895 (if (= n 0)
896 (values p 0) ; c = bare coef & d = 0
897 (values 0 p)) ; c = 0 & d = bare coef
898 (loop ; proper polynomial
899 with L = (p-terms p) ; list of terms in polynomial
900 with var = (p-var p) ; main variable
901 for i = (pop L) ; power of term
902 for ai = (pop L) ; coefficient of term x^i
903 while (>= i n) ; exit via finally if n-th power not present
904 if (> i n)
905 append `(,i ,ai) into terms ; accumulate higher order terms
906 else ; have i==n so C=ai. Construct D and return
907 do (return (values ai (psimp var (append terms L))))
908 while L ; exit via finally if all coefficients examined
909 finally (return (values 0 p)))))