| 1 | r""" |
| 2 | Interface to Maxima |
| 3 | |
| 4 | Maxima is a free GPL'd general purpose computer algebra system |
| 5 | whose development started in 1968 at MIT. It contains symbolic |
| 6 | manipulation algorithms, as well as implementations of special |
| 7 | functions, including elliptic functions and generalized |
| 8 | hypergeometric functions. Moreover, Maxima has implementations of |
| 9 | many functions relating to the invariant theory of the symmetric |
| 10 | group `S_n`. (However, the commands for group invariants, |
| 11 | and the corresponding Maxima documentation, are in French.) For many |
| 12 | links to Maxima documentation see |
| 13 | http://maxima.sourceforge.net/docs.shtml/. |
| 14 | |
| 15 | AUTHORS: |
| 16 | |
| 17 | - William Stein (2005-12): Initial version |
| 18 | |
| 19 | - David Joyner: Improved documentation |
| 20 | |
| 21 | - William Stein (2006-01-08): Fixed bug in parsing |
| 22 | |
| 23 | - William Stein (2006-02-22): comparisons (following suggestion of |
| 24 | David Joyner) |
| 25 | |
| 26 | - William Stein (2006-02-24): *greatly* improved robustness by adding |
| 27 | sequence numbers to IO bracketing in _eval_line |
| 28 | |
| 29 | If the string "error" (case insensitive) occurs in the output of |
| 30 | anything from Maxima, a RuntimeError exception is raised. |
| 31 | |
| 32 | EXAMPLES: We evaluate a very simple expression in Maxima. |
| 33 | |
| 34 | :: |
| 35 | |
| 36 | sage: maxima('3 * 5') |
| 37 | 15 |
| 38 | |
| 39 | We factor `x^5 - y^5` in Maxima in several different ways. |
| 40 | The first way yields a Maxima object. |
| 41 | |
| 42 | :: |
| 43 | |
| 44 | sage: F = maxima.factor('x^5 - y^5') |
| 45 | sage: F |
| 46 | -(y-x)*(y^4+x*y^3+x^2*y^2+x^3*y+x^4) |
| 47 | sage: type(F) |
| 48 | <class 'sage.interfaces.maxima_abstract.MaximaElement'> |
| 49 | |
| 50 | Note that Maxima objects can also be displayed using "ASCII art"; |
| 51 | to see a normal linear representation of any Maxima object x. Just |
| 52 | use the print command: use ``str(x)``. |
| 53 | |
| 54 | :: |
| 55 | |
| 56 | sage: print F |
| 57 | 4 3 2 2 3 4 |
| 58 | - (y - x) (y + x y + x y + x y + x ) |
| 59 | |
| 60 | You can always use ``repr(x)`` to obtain the linear |
| 61 | representation of an object. This can be useful for moving maxima |
| 62 | data to other systems. |
| 63 | |
| 64 | :: |
| 65 | |
| 66 | sage: repr(F) |
| 67 | '-(y-x)*(y^4+x*y^3+x^2*y^2+x^3*y+x^4)' |
| 68 | sage: F.str() |
| 69 | '-(y-x)*(y^4+x*y^3+x^2*y^2+x^3*y+x^4)' |
| 70 | |
| 71 | The ``maxima.eval`` command evaluates an expression in |
| 72 | maxima and returns the result as a *string* not a maxima object. |
| 73 | |
| 74 | :: |
| 75 | |
| 76 | sage: print maxima.eval('factor(x^5 - y^5)') |
| 77 | -(y-x)*(y^4+x*y^3+x^2*y^2+x^3*y+x^4) |
| 78 | |
| 79 | We can create the polynomial `f` as a Maxima polynomial, |
| 80 | then call the factor method on it. Notice that the notation |
| 81 | ``f.factor()`` is consistent with how the rest of Sage |
| 82 | works. |
| 83 | |
| 84 | :: |
| 85 | |
| 86 | sage: f = maxima('x^5 - y^5') |
| 87 | sage: f^2 |
| 88 | (x^5-y^5)^2 |
| 89 | sage: f.factor() |
| 90 | -(y-x)*(y^4+x*y^3+x^2*y^2+x^3*y+x^4) |
| 91 | |
| 92 | Control-C interruption works well with the maxima interface, |
| 93 | because of the excellent implementation of maxima. For example, try |
| 94 | the following sum but with a much bigger range, and hit control-C. |
| 95 | |
| 96 | :: |
| 97 | |
| 98 | sage: maxima('sum(1/x^2, x, 1, 10)') |
| 99 | 1968329/1270080 |
| 100 | |
| 101 | Tutorial |
| 102 | -------- |
| 103 | |
| 104 | We follow the tutorial at |
| 105 | http://maxima.sourceforge.net/docs/intromax/. |
| 106 | |
| 107 | :: |
| 108 | |
| 109 | sage: maxima('1/100 + 1/101') |
| 110 | 201/10100 |
| 111 | |
| 112 | :: |
| 113 | |
| 114 | sage: a = maxima('(1 + sqrt(2))^5'); a |
| 115 | (sqrt(2)+1)^5 |
| 116 | sage: a.expand() |
| 117 | 3*2^(7/2)+5*sqrt(2)+41 |
| 118 | |
| 119 | :: |
| 120 | |
| 121 | sage: a = maxima('(1 + sqrt(2))^5') |
| 122 | sage: float(a) |
| 123 | 82.012193308819747 |
| 124 | sage: a.numer() |
| 125 | 82.01219330881975 |
| 126 | |
| 127 | :: |
| 128 | |
| 129 | sage: maxima.eval('fpprec : 100') |
| 130 | '100' |
| 131 | sage: a.bfloat() |
| 132 | 8.20121933088197564152489730020812442785204843859314941221237124017312418754011041266612384955016056b1 |
| 133 | |
| 134 | :: |
| 135 | |
| 136 | sage: maxima('100!') |
| 137 | 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 |
| 138 | |
| 139 | :: |
| 140 | |
| 141 | sage: f = maxima('(x + 3*y + x^2*y)^3') |
| 142 | sage: f.expand() |
| 143 | x^6*y^3+9*x^4*y^3+27*x^2*y^3+27*y^3+3*x^5*y^2+18*x^3*y^2+27*x*y^2+3*x^4*y+9*x^2*y+x^3 |
| 144 | sage: f.subst('x=5/z') |
| 145 | (5/z+25*y/z^2+3*y)^3 |
| 146 | sage: g = f.subst('x=5/z') |
| 147 | sage: h = g.ratsimp(); h |
| 148 | (27*y^3*z^6+135*y^2*z^5+(675*y^3+225*y)*z^4+(2250*y^2+125)*z^3+(5625*y^3+1875*y)*z^2+9375*y^2*z+15625*y^3)/z^6 |
| 149 | sage: h.factor() |
| 150 | (3*y*z^2+5*z+25*y)^3/z^6 |
| 151 | |
| 152 | :: |
| 153 | |
| 154 | sage: eqn = maxima(['a+b*c=1', 'b-a*c=0', 'a+b=5']) |
| 155 | sage: s = eqn.solve('[a,b,c]'); s |
| 156 | [[a=(25*sqrt(79)*%i+25)/(6*sqrt(79)*%i-34),b=(5*sqrt(79)*%i+5)/(sqrt(79)*%i+11),c=(sqrt(79)*%i+1)/10],[a=(25*sqrt(79)*%i-25)/(6*sqrt(79)*%i+34),b=(5*sqrt(79)*%i-5)/(sqrt(79)*%i-11),c=-(sqrt(79)*%i-1)/10]] |
| 157 | |
| 158 | Here is an example of solving an algebraic equation:: |
| 159 | |
| 160 | sage: maxima('x^2+y^2=1').solve('y') |
| 161 | [y=-sqrt(1-x^2),y=sqrt(1-x^2)] |
| 162 | sage: maxima('x^2 + y^2 = (x^2 - y^2)/sqrt(x^2 + y^2)').solve('y') |
| 163 | [y=-sqrt((-y^2-x^2)*sqrt(y^2+x^2)+x^2),y=sqrt((-y^2-x^2)*sqrt(y^2+x^2)+x^2)] |
| 164 | |
| 165 | You can even nicely typeset the solution in latex:: |
| 166 | |
| 167 | sage: latex(s) |
| 168 | \left[ \left[ a={{25\,\sqrt{79}\,i+25}\over{6\,\sqrt{79}\,i-34}} , b={{5\,\sqrt{79}\,i+5}\over{\sqrt{79}\,i+11}} , c={{\sqrt{79}\,i+1 }\over{10}} \right] , \left[ a={{25\,\sqrt{79}\,i-25}\over{6\, \sqrt{79}\,i+34}} , b={{5\,\sqrt{79}\,i-5}\over{\sqrt{79}\,i-11}} , c=-{{\sqrt{79}\,i-1}\over{10}} \right] \right] |
| 169 | |
| 170 | To have the above appear onscreen via ``xdvi``, type |
| 171 | ``view(s)``. (TODO: For OS X should create pdf output |
| 172 | and use preview instead?) |
| 173 | |
| 174 | :: |
| 175 | |
| 176 | sage: e = maxima('sin(u + v) * cos(u)^3'); e |
| 177 | cos(u)^3*sin(v+u) |
| 178 | sage: f = e.trigexpand(); f |
| 179 | cos(u)^3*(cos(u)*sin(v)+sin(u)*cos(v)) |
| 180 | sage: f.trigreduce() |
| 181 | (sin(v+4*u)+sin(v-2*u))/8+(3*sin(v+2*u)+3*sin(v))/8 |
| 182 | sage: w = maxima('3 + k*%i') |
| 183 | sage: f = w^2 + maxima('%e')^w |
| 184 | sage: f.realpart() |
| 185 | %e^3*cos(k)-k^2+9 |
| 186 | |
| 187 | :: |
| 188 | |
| 189 | sage: f = maxima('x^3 * %e^(k*x) * sin(w*x)'); f |
| 190 | x^3*%e^(k*x)*sin(w*x) |
| 191 | sage: f.diff('x') |
| 192 | k*x^3*%e^(k*x)*sin(w*x)+3*x^2*%e^(k*x)*sin(w*x)+w*x^3*%e^(k*x)*cos(w*x) |
| 193 | sage: f.integrate('x') |
| 194 | (((k*w^6+3*k^3*w^4+3*k^5*w^2+k^7)*x^3+(3*w^6+3*k^2*w^4-3*k^4*w^2-3*k^6)*x^2+(-18*k*w^4-12*k^3*w^2+6*k^5)*x-6*w^4+36*k^2*w^2-6*k^4)*%e^(k*x)*sin(w*x)+((-w^7-3*k^2*w^5-3*k^4*w^3-k^6*w)*x^3+(6*k*w^5+12*k^3*w^3+6*k^5*w)*x^2+(6*w^5-12*k^2*w^3-18*k^4*w)*x-24*k*w^3+24*k^3*w)*%e^(k*x)*cos(w*x))/(w^8+4*k^2*w^6+6*k^4*w^4+4*k^6*w^2+k^8) |
| 195 | |
| 196 | :: |
| 197 | |
| 198 | sage: f = maxima('1/x^2') |
| 199 | sage: f.integrate('x', 1, 'inf') |
| 200 | 1 |
| 201 | sage: g = maxima('f/sinh(k*x)^4') |
| 202 | sage: g.taylor('x', 0, 3) |
| 203 | f/(k^4*x^4)-2*f/(3*k^2*x^2)+11*f/45-62*k^2*f*x^2/945 |
| 204 | |
| 205 | :: |
| 206 | |
| 207 | sage: maxima.taylor('asin(x)','x',0, 10) |
| 208 | x+x^3/6+3*x^5/40+5*x^7/112+35*x^9/1152 |
| 209 | |
| 210 | Examples involving matrices |
| 211 | --------------------------- |
| 212 | |
| 213 | We illustrate computing with the matrix whose `i,j` entry |
| 214 | is `i/j`, for `i,j=1,\ldots,4`. |
| 215 | |
| 216 | :: |
| 217 | |
| 218 | sage: f = maxima.eval('f[i,j] := i/j') |
| 219 | sage: A = maxima('genmatrix(f,4,4)'); A |
| 220 | matrix([1,1/2,1/3,1/4],[2,1,2/3,1/2],[3,3/2,1,3/4],[4,2,4/3,1]) |
| 221 | sage: A.determinant() |
| 222 | 0 |
| 223 | sage: A.echelon() |
| 224 | matrix([1,1/2,1/3,1/4],[0,0,0,0],[0,0,0,0],[0,0,0,0]) |
| 225 | sage: A.eigenvalues() |
| 226 | [[0,4],[3,1]] |
| 227 | sage: A.eigenvectors() |
| 228 | [[[0,4],[3,1]],[[[1,0,0,-4],[0,1,0,-2],[0,0,1,-4/3]],[[1,2,3,4]]]] |
| 229 | |
| 230 | We can also compute the echelon form in Sage:: |
| 231 | |
| 232 | sage: B = matrix(QQ, A) |
| 233 | sage: B.echelon_form() |
| 234 | [ 1 1/2 1/3 1/4] |
| 235 | [ 0 0 0 0] |
| 236 | [ 0 0 0 0] |
| 237 | [ 0 0 0 0] |
| 238 | sage: B.charpoly('x').factor() |
| 239 | (x - 4) * x^3 |
| 240 | |
| 241 | Laplace Transforms |
| 242 | ------------------ |
| 243 | |
| 244 | We illustrate Laplace transforms:: |
| 245 | |
| 246 | sage: _ = maxima.eval("f(t) := t*sin(t)") |
| 247 | sage: maxima("laplace(f(t),t,s)") |
| 248 | 2*s/(s^2+1)^2 |
| 249 | |
| 250 | :: |
| 251 | |
| 252 | sage: maxima("laplace(delta(t-3),t,s)") #Dirac delta function |
| 253 | %e^-(3*s) |
| 254 | |
| 255 | :: |
| 256 | |
| 257 | sage: _ = maxima.eval("f(t) := exp(t)*sin(t)") |
| 258 | sage: maxima("laplace(f(t),t,s)") |
| 259 | 1/(s^2-2*s+2) |
| 260 | |
| 261 | :: |
| 262 | |
| 263 | sage: _ = maxima.eval("f(t) := t^5*exp(t)*sin(t)") |
| 264 | sage: maxima("laplace(f(t),t,s)") |
| 265 | 360*(2*s-2)/(s^2-2*s+2)^4-480*(2*s-2)^3/(s^2-2*s+2)^5+120*(2*s-2)^5/(s^2-2*s+2)^6 |
| 266 | sage: print maxima("laplace(f(t),t,s)") |
| 267 | 3 5 |
| 268 | 360 (2 s - 2) 480 (2 s - 2) 120 (2 s - 2) |
| 269 | --------------- - --------------- + --------------- |
| 270 | 2 4 2 5 2 6 |
| 271 | (s - 2 s + 2) (s - 2 s + 2) (s - 2 s + 2) |
| 272 | |
| 273 | :: |
| 274 | |
| 275 | sage: maxima("laplace(diff(x(t),t),t,s)") |
| 276 | s*'laplace(x(t),t,s)-x(0) |
| 277 | |
| 278 | :: |
| 279 | |
| 280 | sage: maxima("laplace(diff(x(t),t,2),t,s)") |
| 281 | -?%at('diff(x(t),t,1),t=0)+s^2*'laplace(x(t),t,s)-x(0)*s |
| 282 | |
| 283 | It is difficult to read some of these without the 2d |
| 284 | representation:: |
| 285 | |
| 286 | sage: print maxima("laplace(diff(x(t),t,2),t,s)") |
| 287 | ! |
| 288 | d ! 2 |
| 289 | - -- (x(t))! + s laplace(x(t), t, s) - x(0) s |
| 290 | dt ! |
| 291 | !t = 0 |
| 292 | |
| 293 | Even better, use |
| 294 | ``view(maxima("laplace(diff(x(t),t,2),t,s)"))`` to see |
| 295 | a typeset version. |
| 296 | |
| 297 | Continued Fractions |
| 298 | ------------------- |
| 299 | |
| 300 | A continued fraction `a + 1/(b + 1/(c + \cdots))` is |
| 301 | represented in maxima by the list `[a, b, c, \ldots]`. |
| 302 | |
| 303 | :: |
| 304 | |
| 305 | sage: maxima("cf((1 + sqrt(5))/2)") |
| 306 | [1,1,1,1,2] |
| 307 | sage: maxima("cf ((1 + sqrt(341))/2)") |
| 308 | [9,1,2,1,2,1,17,1,2,1,2,1,17,1,2,1,2,1,17,2] |
| 309 | |
| 310 | Special examples |
| 311 | ---------------- |
| 312 | |
| 313 | In this section we illustrate calculations that would be awkward to |
| 314 | do (as far as I know) in non-symbolic computer algebra systems like |
| 315 | MAGMA or GAP. |
| 316 | |
| 317 | We compute the gcd of `2x^{n+4} - x^{n+2}` and |
| 318 | `4x^{n+1} + 3x^n` for arbitrary `n`. |
| 319 | |
| 320 | :: |
| 321 | |
| 322 | sage: f = maxima('2*x^(n+4) - x^(n+2)') |
| 323 | sage: g = maxima('4*x^(n+1) + 3*x^n') |
| 324 | sage: f.gcd(g) |
| 325 | x^n |
| 326 | |
| 327 | You can plot 3d graphs (via gnuplot):: |
| 328 | |
| 329 | sage: maxima('plot3d(x^2-y^2, [x,-2,2], [y,-2,2], [grid,12,12])') # not tested |
| 330 | [displays a 3 dimensional graph] |
| 331 | |
| 332 | You can formally evaluate sums (note the ``nusum`` |
| 333 | command):: |
| 334 | |
| 335 | sage: S = maxima('nusum(exp(1+2*i/n),i,1,n)') |
| 336 | sage: print S |
| 337 | 2/n + 3 2/n + 1 |
| 338 | %e %e |
| 339 | ----------------------- - ----------------------- |
| 340 | 1/n 1/n 1/n 1/n |
| 341 | (%e - 1) (%e + 1) (%e - 1) (%e + 1) |
| 342 | |
| 343 | We formally compute the limit as `n\to\infty` of |
| 344 | `2S/n` as follows:: |
| 345 | |
| 346 | sage: T = S*maxima('2/n') |
| 347 | sage: T.tlimit('n','inf') |
| 348 | %e^3-%e |
| 349 | |
| 350 | Miscellaneous |
| 351 | ------------- |
| 352 | |
| 353 | Obtaining digits of `\pi`:: |
| 354 | |
| 355 | sage: maxima.eval('fpprec : 100') |
| 356 | '100' |
| 357 | sage: maxima(pi).bfloat() |
| 358 | 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068b0 |
| 359 | |
| 360 | Defining functions in maxima:: |
| 361 | |
| 362 | sage: maxima.eval('fun[a] := a^2') |
| 363 | 'fun[a]:=a^2' |
| 364 | sage: maxima('fun[10]') |
| 365 | 100 |
| 366 | |
| 367 | Interactivity |
| 368 | ------------- |
| 369 | |
| 370 | Unfortunately maxima doesn't seem to have a non-interactive mode, |
| 371 | which is needed for the Sage interface. If any Sage call leads to |
| 372 | maxima interactively answering questions, then the questions can't be |
| 373 | answered and the maxima session may hang. See the discussion at |
| 374 | http://www.ma.utexas.edu/pipermail/maxima/2005/011061.html for some |
| 375 | ideas about how to fix this problem. An example that illustrates this |
| 376 | problem is ``maxima.eval('integrate (exp(a*x), x, 0, inf)')``. |
| 377 | |
| 378 | Latex Output |
| 379 | ------------ |
| 380 | |
| 381 | To TeX a maxima object do this:: |
| 382 | |
| 383 | sage: latex(maxima('sin(u) + sinh(v^2)')) |
| 384 | \sinh v^2+\sin u |
| 385 | |
| 386 | Here's another example:: |
| 387 | |
| 388 | sage: g = maxima('exp(3*%i*x)/(6*%i) + exp(%i*x)/(2*%i) + c') |
| 389 | sage: latex(g) |
| 390 | -{{i\,e^{3\,i\,x}}\over{6}}-{{i\,e^{i\,x}}\over{2}}+c |
| 391 | |
| 392 | Long Input |
| 393 | ---------- |
| 394 | |
| 395 | The MAXIMA interface reads in even very long input (using files) in |
| 396 | a robust manner, as long as you are creating a new object. |
| 397 | |
| 398 | .. note:: |
| 399 | |
| 400 | Using ``maxima.eval`` for long input is much less robust, and is |
| 401 | not recommended. |
| 402 | |
| 403 | :: |
| 404 | |
| 405 | sage: t = '"%s"'%10^10000 # ten thousand character string. |
| 406 | sage: a = maxima(t) |
| 407 | |
| 408 | TESTS: This working tests that a subtle bug has been fixed:: |
| 409 | |
| 410 | sage: f = maxima.function('x','gamma(x)') |
| 411 | sage: g = f(1/7) |
| 412 | sage: g |
| 413 | gamma(1/7) |
| 414 | sage: del f |
| 415 | sage: maxima(sin(x)) |
| 416 | sin(x) |
| 417 | |
| 418 | This tests to make sure we handle the case where Maxima asks if an |
| 419 | expression is positive or zero. |
| 420 | |
| 421 | :: |
| 422 | |
| 423 | sage: var('Ax,Bx,By') |
| 424 | (Ax, Bx, By) |
| 425 | sage: t = -Ax*sin(sqrt(Ax^2)/2)/(sqrt(Ax^2)*sqrt(By^2 + Bx^2)) |
| 426 | sage: t.limit(Ax=0,dir='above') |
| 427 | 0 |
| 428 | |
| 429 | A long complicated input expression:: |
| 430 | |
| 431 | sage: maxima._eval_line('((((((((((0) + ((1) / ((n0) ^ (0)))) + ((1) / ((n1) ^ (1)))) + ((1) / ((n2) ^ (2)))) + ((1) / ((n3) ^ (3)))) + ((1) / ((n4) ^ (4)))) + ((1) / ((n5) ^ (5)))) + ((1) / ((n6) ^ (6)))) + ((1) / ((n7) ^ (7)))) + ((1) / ((n8) ^ (8)))) + ((1) / ((n9) ^ (9)));') |
| 432 | '1/n9^9+1/n8^8+1/n7^7+1/n6^6+1/n5^5+1/n4^4+1/n3^3+1/n2^2+1/n1+1' |
| 433 | """ |
| 434 | |
| 435 | #***************************************************************************** |
| 436 | # Copyright (C) 2005 William Stein <wstein@gmail.com> |
| 437 | # |
| 438 | # Distributed under the terms of the GNU General Public License (GPL) |
| 439 | # |
| 440 | # This code is distributed in the hope that it will be useful, |
| 441 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 442 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 443 | # General Public License for more details. |
| 444 | # |
| 445 | # The full text of the GPL is available at: |
| 446 | # |
| 447 | # http://www.gnu.org/licenses/ |
| 448 | #***************************************************************************** |
| 449 | |
| 450 | from __future__ import with_statement |
| 451 | |
| 452 | import os, re, sys, subprocess |
| 453 | import pexpect |
| 454 | cygwin = os.uname()[0][:6]=="CYGWIN" |
| 455 | |
| 456 | from expect import Expect, ExpectElement, FunctionElement, ExpectFunction, gc_disabled, AsciiArtString |
| 457 | from pexpect import EOF |
| 458 | |
| 459 | from random import randrange |
| 460 | |
| 461 | ##import sage.rings.all |
| 462 | import sage.rings.complex_number |
| 463 | |
| 464 | from sage.misc.misc import verbose, DOT_SAGE, SAGE_ROOT |
| 465 | |
| 466 | from sage.misc.multireplace import multiple_replace |
| 467 | |
| 468 | COMMANDS_CACHE = '%s/maxima_commandlist_cache.sobj'%DOT_SAGE |
| 469 | |
| 470 | import sage.server.support |
| 471 | |
| 472 | # The Maxima "apropos" command, e.g., apropos(det) gives a list |
| 473 | # of all identifiers that begin in a certain way. This could |
| 474 | # maybe be useful somehow... (?) Also maxima has a lot for getting |
| 475 | # documentation from the system -- this could also be useful. |
| 476 | |
| 477 | class Maxima(Expect): |
| 478 | """ |
| 479 | Interface to the Maxima interpreter. |
| 480 | """ |
| 481 | def __init__(self, script_subdirectory=None, logfile=None, server=None, |
| 482 | init_code = None): |
| 483 | """ |
| 484 | Create an instance of the Maxima interpreter. |
| 485 | |
| 486 | TESTS:: |
| 487 | |
| 488 | sage: maxima == loads(dumps(maxima)) |
| 489 | True |
| 490 | |
| 491 | We make sure labels are turned off (see trac 6816):: |
| 492 | |
| 493 | sage: 'nolabels:true' in maxima._Expect__init_code |
| 494 | True |
| 495 | """ |
| 496 | # TODO: Input and output prompts in maxima can be changed by |
| 497 | # setting inchar and outchar.. |
| 498 | eval_using_file_cutoff = 256 |
| 499 | self.__eval_using_file_cutoff = eval_using_file_cutoff |
| 500 | STARTUP = '%s/local/bin/sage-maxima.lisp'%SAGE_ROOT |
| 501 | if not os.path.exists(STARTUP): |
| 502 | raise RuntimeError, 'You must get the file local/bin/sage-maxima.lisp' |
| 503 | if init_code is None: |
| 504 | # display2d -- no ascii art output |
| 505 | # keepfloat -- don't automatically convert floats to rationals |
| 506 | init_code = ['display2d : false', 'keepfloat : true'] |
| 507 | |
| 508 | # Turn off the prompt labels, since computing them *very |
| 509 | # dramatically* slows down the maxima interpret after a while. |
| 510 | # See the function makelabel in suprv1.lisp. |
| 511 | # Many thanks to andrej.vodopivec@gmail.com and also |
| 512 | # Robert Dodier for figuring this out! |
| 513 | # See trac # 6818. |
| 514 | init_code.append('nolabels:true') |
| 515 | |
| 516 | Expect.__init__(self, |
| 517 | name = 'maxima', |
| 518 | prompt = '\(\%i[0-9]+\)', |
| 519 | command = 'maxima-noreadline -p "%s"'%STARTUP, |
| 520 | maxread = 10000, |
| 521 | script_subdirectory = script_subdirectory, |
| 522 | restart_on_ctrlc = False, |
| 523 | verbose_start = False, |
| 524 | init_code = init_code, |
| 525 | logfile = logfile, |
| 526 | eval_using_file_cutoff=eval_using_file_cutoff) |
| 527 | self._display_prompt = '<sage-display>' # must match what is in the file local/ibn/sage-maxima.lisp!! |
| 528 | self._output_prompt_re = re.compile('\(\%o[0-9]+\)') |
| 529 | self._ask = ['zero or nonzero?', 'an integer?', 'positive, negative, or zero?', |
| 530 | 'positive or negative?', 'positive or zero?'] |
| 531 | self._prompt_wait = [self._prompt] + [re.compile(x) for x in self._ask] + \ |
| 532 | ['Break [0-9]+'] #note that you might need to change _expect_expr if you |
| 533 | #change this |
| 534 | self._error_re = re.compile('(Principal Value|debugmode|Incorrect syntax|Maxima encountered a Lisp error)') |
| 535 | self._display2d = False |
| 536 | |
| 537 | def _quit_string(self): |
| 538 | """ |
| 539 | EXAMPLES:: |
| 540 | |
| 541 | sage: maxima._quit_string() |
| 542 | 'quit();' |
| 543 | """ |
| 544 | return 'quit();' |
| 545 | |
| 546 | def _crash_msg(self): |
| 547 | """ |
| 548 | EXAMPLES:: |
| 549 | |
| 550 | sage: maxima._crash_msg() |
| 551 | Maxima crashed -- automatically restarting. |
| 552 | """ |
| 553 | print "Maxima crashed -- automatically restarting." |
| 554 | |
| 555 | |
| 556 | def _batch(self, s, batchload=True): |
| 557 | filename = '%s-%s'%(self._local_tmpfile(),randrange(2147483647)) |
| 558 | F = open(filename, 'w') |
| 559 | F.write(s) |
| 560 | F.close() |
| 561 | if self.is_remote(): |
| 562 | self._send_tmpfile_to_server(local_file=filename) |
| 563 | tmp_to_use = self._remote_tmpfile() |
| 564 | tmp_to_use = filename |
| 565 | |
| 566 | if batchload: |
| 567 | cmd = 'batchload("%s");'%tmp_to_use |
| 568 | else: |
| 569 | cmd = 'batch("%s");'%tmp_to_use |
| 570 | |
| 571 | r = randrange(2147483647) |
| 572 | s = str(r+1) |
| 573 | cmd = "%s1+%s;\n"%(cmd,r) |
| 574 | |
| 575 | self._sendline(cmd) |
| 576 | self._expect_expr(s) |
| 577 | out = self._before() |
| 578 | self._error_check(str, out) |
| 579 | os.unlink(filename) |
| 580 | return out |
| 581 | |
| 582 | def _error_check(self, str, out): |
| 583 | r = self._error_re |
| 584 | m = r.search(out) |
| 585 | if not m is None: |
| 586 | self._error_msg(str, out) |
| 587 | |
| 588 | def _error_msg(self, str, out): |
| 589 | raise TypeError, "Error executing code in Maxima\nCODE:\n\t%s\nMaxima ERROR:\n\t%s"%(str, out.replace('-- an error. To debug this try debugmode(true);','')) |
| 590 | |
| 591 | |
| 592 | ########################################### |
| 593 | # System -- change directory, etc |
| 594 | ########################################### |
| 595 | def chdir(self, dir): |
| 596 | """ |
| 597 | Change Maxima's current working directory. |
| 598 | |
| 599 | EXAMPLES:: |
| 600 | |
| 601 | sage: maxima.chdir('/') |
| 602 | """ |
| 603 | self.lisp('(ext::cd "%s")'%dir) |
| 604 | |
| 605 | ########################################### |
| 606 | # Interactive help |
| 607 | ########################################### |
| 608 | |
| 609 | |
| 610 | def help(self, s): |
| 611 | """ |
| 612 | EXAMPLES:: |
| 613 | |
| 614 | sage: maxima.help('gcd') |
| 615 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 616 | ... |
| 617 | """ |
| 618 | return self._command_runner("describe", s) |
| 619 | |
| 620 | def example(self, s): |
| 621 | """ |
| 622 | EXAMPLES:: |
| 623 | |
| 624 | sage: maxima.example('arrays') |
| 625 | a[n]:=n*a[n-1] |
| 626 | a := n a |
| 627 | n n - 1 |
| 628 | a[0]:1 |
| 629 | a[5] |
| 630 | 120 |
| 631 | a[n]:=n |
| 632 | a[6] |
| 633 | 6 |
| 634 | a[4] |
| 635 | 24 |
| 636 | done |
| 637 | """ |
| 638 | return self._command_runner("example", s) |
| 639 | |
| 640 | describe = help |
| 641 | |
| 642 | def demo(self, s): |
| 643 | """ |
| 644 | EXAMPLES:: |
| 645 | |
| 646 | sage: maxima.demo('array') # not tested |
| 647 | batching /opt/sage/local/share/maxima/5.16.3/demo/array.dem |
| 648 | |
| 649 | At the _ prompt, type ';' followed by enter to get next demo |
| 650 | subscrmap : true _ |
| 651 | """ |
| 652 | return self._command_runner("demo", s, redirect=False) |
| 653 | |
| 654 | def completions(self, s, verbose=True): |
| 655 | """ |
| 656 | Return all commands that complete the command starting with the |
| 657 | string s. This is like typing s[tab] in the Maxima interpreter. |
| 658 | |
| 659 | EXAMPLES:: |
| 660 | |
| 661 | sage: sorted(maxima.completions('gc', verbose=False)) |
| 662 | ['gcd', 'gcdex', 'gcfactor', 'gcprint', 'gctime'] |
| 663 | """ |
| 664 | if verbose: |
| 665 | print s, |
| 666 | sys.stdout.flush() |
| 667 | # in Maxima 5.19.1, apropos returns all commands that contain |
| 668 | # the given string, instead of all commands that start with |
| 669 | # the given string |
| 670 | cmd_list = self._eval_line('apropos("%s")'%s, error_check=False).replace('\\ - ','-') |
| 671 | cmd_list = [x for x in cmd_list[1:-1].split(',') if x[0] != '?'] |
| 672 | return [x for x in cmd_list if x.find(s) == 0] |
| 673 | |
| 674 | def _commands(self, verbose=True): |
| 675 | """ |
| 676 | Return list of all commands defined in Maxima. |
| 677 | |
| 678 | EXAMPLES:: |
| 679 | |
| 680 | sage: sorted(maxima._commands(verbose=False)) |
| 681 | ['Alpha', |
| 682 | 'Beta', |
| 683 | ... |
| 684 | 'zunderflow'] |
| 685 | """ |
| 686 | try: |
| 687 | return self.__commands |
| 688 | except AttributeError: |
| 689 | self.__commands = sum( |
| 690 | [self.completions(chr(65+n), verbose=verbose)+ |
| 691 | self.completions(chr(97+n), verbose=verbose) |
| 692 | for n in range(26)], []) |
| 693 | return self.__commands |
| 694 | |
| 695 | def trait_names(self, verbose=True, use_disk_cache=True): |
| 696 | """ |
| 697 | Return all Maxima commands, which is useful for tab completion. |
| 698 | |
| 699 | EXAMPLES:: |
| 700 | |
| 701 | sage: t = maxima.trait_names(verbose=False) |
| 702 | sage: 'gcd' in t |
| 703 | True |
| 704 | sage: len(t) # random output |
| 705 | 1840 |
| 706 | """ |
| 707 | try: |
| 708 | return self.__trait_names |
| 709 | except AttributeError: |
| 710 | import sage.misc.persist |
| 711 | if use_disk_cache: |
| 712 | try: |
| 713 | self.__trait_names = sage.misc.persist.load(COMMANDS_CACHE) |
| 714 | return self.__trait_names |
| 715 | except IOError: |
| 716 | pass |
| 717 | if verbose: |
| 718 | print "\nBuilding Maxima command completion list (this takes" |
| 719 | print "a few seconds only the first time you do it)." |
| 720 | print "To force rebuild later, delete %s."%COMMANDS_CACHE |
| 721 | v = self._commands(verbose=verbose) |
| 722 | if verbose: |
| 723 | print "\nDone!" |
| 724 | self.__trait_names = v |
| 725 | sage.misc.persist.save(v, COMMANDS_CACHE) |
| 726 | return v |
| 727 | |
| 728 | def _true_symbol(self): |
| 729 | """ |
| 730 | Return the true symbol in Maxima. |
| 731 | |
| 732 | EXAMPLES:: |
| 733 | |
| 734 | sage: maxima._true_symbol() |
| 735 | 'true' |
| 736 | sage: maxima.eval('is(2 = 2)') |
| 737 | 'true' |
| 738 | """ |
| 739 | return 'true' |
| 740 | |
| 741 | def _false_symbol(self): |
| 742 | """ |
| 743 | Return the false symbol in Maxima. |
| 744 | |
| 745 | EXAMPLES:: |
| 746 | |
| 747 | sage: maxima._false_symbol() |
| 748 | 'false' |
| 749 | sage: maxima.eval('is(2 = 4)') |
| 750 | 'false' |
| 751 | """ |
| 752 | return 'false' |
| 753 | |
| 754 | def _equality_symbol(self): |
| 755 | """ |
| 756 | Returns the equality symbol in Maxima. |
| 757 | |
| 758 | EXAMPLES:: |
| 759 | |
| 760 | sage: maxima._equality_symbol() |
| 761 | '=' |
| 762 | """ |
| 763 | return '=' |
| 764 | |
| 765 | def _inequality_symbol(self): |
| 766 | """ |
| 767 | Returns the equality symbol in Maxima. |
| 768 | |
| 769 | EXAMPLES:: |
| 770 | |
| 771 | sage: maxima._inequality_symbol() |
| 772 | '#' |
| 773 | sage: maxima((x != 1)) |
| 774 | x#1 |
| 775 | """ |
| 776 | return '#' |
| 777 | |
| 778 | def console(self): |
| 779 | r""" |
| 780 | Start the interactive Maxima console. This is a completely separate |
| 781 | maxima session from this interface. To interact with this session, |
| 782 | you should instead use ``maxima.interact()``. |
| 783 | |
| 784 | EXAMPLES:: |
| 785 | |
| 786 | sage: maxima.console() # not tested (since we can't) |
| 787 | Maxima 5.13.0 http://maxima.sourceforge.net |
| 788 | Using Lisp CLISP 2.41 (2006-10-13) |
| 789 | Distributed under the GNU Public License. See the file COPYING. |
| 790 | Dedicated to the memory of William Schelter. |
| 791 | This is a development version of Maxima. The function bug_report() |
| 792 | provides bug reporting information. |
| 793 | (%i1) |
| 794 | |
| 795 | :: |
| 796 | |
| 797 | sage: maxima.interact() # this is not tested either |
| 798 | --> Switching to Maxima <-- |
| 799 | maxima: 2+2 |
| 800 | 4 |
| 801 | maxima: |
| 802 | --> Exiting back to Sage <-- |
| 803 | """ |
| 804 | maxima_console() |
| 805 | |
| 806 | def cputime(self, t=None): |
| 807 | r""" |
| 808 | Returns the amount of CPU time that this Maxima session has used. |
| 809 | If \var{t} is not None, then it returns the difference between |
| 810 | the current CPU time and \var{t}. |
| 811 | |
| 812 | EXAMPLES: |
| 813 | sage: t = maxima.cputime() |
| 814 | sage: _ = maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1]) |
| 815 | sage: maxima.cputime(t) # output random |
| 816 | 0.568913 |
| 817 | """ |
| 818 | if t: |
| 819 | return float(self.eval('elapsed_run_time()')) - t |
| 820 | else: |
| 821 | return float(self.eval('elapsed_run_time()')) |
| 822 | |
| 823 | |
| 824 | ## def display2d(self, flag=True): |
| 825 | ## """ |
| 826 | ## Set the flag that determines whether Maxima objects are |
| 827 | ## printed using their 2-d ASCII art representation. When the |
| 828 | ## maxima interface starts the default is that objects are not |
| 829 | ## represented in 2-d. |
| 830 | |
| 831 | ## INPUT: |
| 832 | ## flag -- bool (default: True) |
| 833 | |
| 834 | ## EXAMPLES |
| 835 | ## sage: maxima('1/2') |
| 836 | ## 1/2 |
| 837 | ## sage: maxima.display2d(True) |
| 838 | ## sage: maxima('1/2') |
| 839 | ## 1 |
| 840 | ## - |
| 841 | ## 2 |
| 842 | ## sage: maxima.display2d(False) |
| 843 | ## """ |
| 844 | ## self._display2d = bool(flag) |
| 845 | |
| 846 | def plot2d(self, *args): |
| 847 | r""" |
| 848 | Plot a 2d graph using Maxima / gnuplot. |
| 849 | |
| 850 | maxima.plot2d(f, '[var, min, max]', options) |
| 851 | |
| 852 | INPUT: |
| 853 | |
| 854 | |
| 855 | - ``f`` - a string representing a function (such as |
| 856 | f="sin(x)") [var, xmin, xmax] |
| 857 | |
| 858 | - ``options`` - an optional string representing plot2d |
| 859 | options in gnuplot format |
| 860 | |
| 861 | |
| 862 | EXAMPLES:: |
| 863 | |
| 864 | sage: maxima.plot2d('sin(x)','[x,-5,5]') # not tested |
| 865 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-plot.eps"]' |
| 866 | sage: maxima.plot2d('sin(x)','[x,-5,5]',opts) # not tested |
| 867 | |
| 868 | The eps file is saved in the current directory. |
| 869 | """ |
| 870 | self('plot2d(%s)'%(','.join([str(x) for x in args]))) |
| 871 | |
| 872 | def plot2d_parametric(self, r, var, trange, nticks=50, options=None): |
| 873 | r""" |
| 874 | Plots r = [x(t), y(t)] for t = tmin...tmax using gnuplot with |
| 875 | options |
| 876 | |
| 877 | INPUT: |
| 878 | |
| 879 | |
| 880 | - ``r`` - a string representing a function (such as |
| 881 | r="[x(t),y(t)]") |
| 882 | |
| 883 | - ``var`` - a string representing the variable (such |
| 884 | as var = "t") |
| 885 | |
| 886 | - ``trange`` - [tmin, tmax] are numbers with tmintmax |
| 887 | |
| 888 | - ``nticks`` - int (default: 50) |
| 889 | |
| 890 | - ``options`` - an optional string representing plot2d |
| 891 | options in gnuplot format |
| 892 | |
| 893 | |
| 894 | EXAMPLES:: |
| 895 | |
| 896 | sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t",[-3.1,3.1]) # not tested |
| 897 | |
| 898 | :: |
| 899 | |
| 900 | sage: opts = '[gnuplot_preamble, "set nokey"], [gnuplot_term, ps], [gnuplot_out_file, "circle-plot.eps"]' |
| 901 | sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t", [-3.1,3.1], options=opts) # not tested |
| 902 | |
| 903 | The eps file is saved to the current working directory. |
| 904 | |
| 905 | Here is another fun plot:: |
| 906 | |
| 907 | sage: maxima.plot2d_parametric(["sin(5*t)","cos(11*t)"], "t", [0,2*pi()], nticks=400) # not tested |
| 908 | """ |
| 909 | tmin = trange[0] |
| 910 | tmax = trange[1] |
| 911 | cmd = "plot2d([parametric, %s, %s, [%s, %s, %s], [nticks, %s]]"%( \ |
| 912 | r[0], r[1], var, tmin, tmax, nticks) |
| 913 | if options is None: |
| 914 | cmd += ")" |
| 915 | else: |
| 916 | cmd += ", %s)"%options |
| 917 | self(cmd) |
| 918 | |
| 919 | def plot3d(self, *args): |
| 920 | r""" |
| 921 | Plot a 3d graph using Maxima / gnuplot. |
| 922 | |
| 923 | maxima.plot3d(f, '[x, xmin, xmax]', '[y, ymin, ymax]', '[grid, nx, |
| 924 | ny]', options) |
| 925 | |
| 926 | INPUT: |
| 927 | |
| 928 | |
| 929 | - ``f`` - a string representing a function (such as |
| 930 | f="sin(x)") [var, min, max] |
| 931 | |
| 932 | |
| 933 | EXAMPLES:: |
| 934 | |
| 935 | sage: maxima.plot3d('1 + x^3 - y^2', '[x,-2,2]', '[y,-2,2]', '[grid,12,12]') # not tested |
| 936 | sage: maxima.plot3d('sin(x)*cos(y)', '[x,-2,2]', '[y,-2,2]', '[grid,30,30]') # not tested |
| 937 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-plot.eps"]' |
| 938 | sage: maxima.plot3d('sin(x+y)', '[x,-5,5]', '[y,-1,1]', opts) # not tested |
| 939 | |
| 940 | The eps file is saved in the current working directory. |
| 941 | """ |
| 942 | self('plot3d(%s)'%(','.join([str(x) for x in args]))) |
| 943 | |
| 944 | def plot3d_parametric(self, r, vars, urange, vrange, options=None): |
| 945 | r""" |
| 946 | Plot a 3d parametric graph with r=(x,y,z), x = x(u,v), y = y(u,v), |
| 947 | z = z(u,v), for u = umin...umax, v = vmin...vmax using gnuplot with |
| 948 | options. |
| 949 | |
| 950 | INPUT: |
| 951 | |
| 952 | |
| 953 | - ``x, y, z`` - a string representing a function (such |
| 954 | as ``x="u2+v2"``, ...) vars is a list or two strings |
| 955 | representing variables (such as vars = ["u","v"]) |
| 956 | |
| 957 | - ``urange`` - [umin, umax] |
| 958 | |
| 959 | - ``vrange`` - [vmin, vmax] are lists of numbers with |
| 960 | umin umax, vmin vmax |
| 961 | |
| 962 | - ``options`` - optional string representing plot2d |
| 963 | options in gnuplot format |
| 964 | |
| 965 | |
| 966 | OUTPUT: displays a plot on screen or saves to a file |
| 967 | |
| 968 | EXAMPLES:: |
| 969 | |
| 970 | sage: maxima.plot3d_parametric(["v*sin(u)","v*cos(u)","v"], ["u","v"],[-3.2,3.2],[0,3]) # not tested |
| 971 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-cos-plot.eps"]' |
| 972 | sage: maxima.plot3d_parametric(["v*sin(u)","v*cos(u)","v"], ["u","v"],[-3.2,3.2],[0,3],opts) # not tested |
| 973 | |
| 974 | The eps file is saved in the current working directory. |
| 975 | |
| 976 | Here is a torus:: |
| 977 | |
| 978 | sage: _ = maxima.eval("expr_1: cos(y)*(10.0+6*cos(x)); expr_2: sin(y)*(10.0+6*cos(x)); expr_3: -6*sin(x);") # optional |
| 979 | sage: maxima.plot3d_parametric(["expr_1","expr_2","expr_3"], ["x","y"],[0,6],[0,6]) # not tested |
| 980 | |
| 981 | Here is a Mobius strip:: |
| 982 | |
| 983 | sage: x = "cos(u)*(3 + v*cos(u/2))" |
| 984 | sage: y = "sin(u)*(3 + v*cos(u/2))" |
| 985 | sage: z = "v*sin(u/2)" |
| 986 | sage: maxima.plot3d_parametric([x,y,z],["u","v"],[-3.1,3.2],[-1/10,1/10]) # not tested |
| 987 | """ |
| 988 | umin = urange[0] |
| 989 | umax = urange[1] |
| 990 | vmin = vrange[0] |
| 991 | vmax = vrange[1] |
| 992 | cmd = 'plot3d([%s, %s, %s], [%s, %s, %s], [%s, %s, %s]'%( |
| 993 | r[0], r[1], r[2], vars[0], umin, umax, vars[1], vmin, vmax) |
| 994 | if options is None: |
| 995 | cmd += ')' |
| 996 | else: |
| 997 | cmd += ', %s)'%options |
| 998 | self(cmd) |
| 999 | |
| 1000 | def de_solve(self, de, vars, ics=None): |
| 1001 | """ |
| 1002 | Solves a 1st or 2nd order ordinary differential equation (ODE) in |
| 1003 | two variables, possibly with initial conditions. |
| 1004 | |
| 1005 | INPUT: |
| 1006 | |
| 1007 | |
| 1008 | - ``de`` - a string representing the ODE |
| 1009 | |
| 1010 | - ``vars`` - a list of strings representing the two |
| 1011 | variables. |
| 1012 | |
| 1013 | - ``ics`` - a triple of numbers [a,b1,b2] representing |
| 1014 | y(a)=b1, y'(a)=b2 |
| 1015 | |
| 1016 | |
| 1017 | EXAMPLES:: |
| 1018 | |
| 1019 | sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1]) |
| 1020 | y=3*x-2*%e^(x-1) |
| 1021 | sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y']) |
| 1022 | y=%k1*%e^x+%k2*%e^-x+3*x |
| 1023 | sage: maxima.de_solve('diff(y,x) + 3*x = y', ['x','y']) |
| 1024 | y=(%c-3*(-x-1)*%e^-x)*%e^x |
| 1025 | sage: maxima.de_solve('diff(y,x) + 3*x = y', ['x','y'],[1,1]) |
| 1026 | y=-%e^-1*(5*%e^x-3*%e*x-3*%e) |
| 1027 | """ |
| 1028 | if not isinstance(vars, str): |
| 1029 | str_vars = '%s, %s'%(vars[1], vars[0]) |
| 1030 | else: |
| 1031 | str_vars = vars |
| 1032 | self.eval('depends(%s)'%str_vars) |
| 1033 | m = self(de) |
| 1034 | a = 'ode2(%s, %s)'%(m.name(), str_vars) |
| 1035 | if ics != None: |
| 1036 | if len(ics) == 3: |
| 1037 | cmd = "ic2("+a+",%s=%s,%s=%s,diff(%s,%s)=%s);"%(vars[0],ics[0], vars[1],ics[1], vars[1], vars[0], ics[2]) |
| 1038 | return self(cmd) |
| 1039 | if len(ics) == 2: |
| 1040 | return self("ic1("+a+",%s=%s,%s=%s);"%(vars[0],ics[0], vars[1],ics[1])) |
| 1041 | return self(a+";") |
| 1042 | |
| 1043 | def de_solve_laplace(self, de, vars, ics=None): |
| 1044 | """ |
| 1045 | Solves an ordinary differential equation (ODE) using Laplace |
| 1046 | transforms. |
| 1047 | |
| 1048 | INPUT: |
| 1049 | |
| 1050 | |
| 1051 | - ``de`` - a string representing the ODE (e.g., de = |
| 1052 | "diff(f(x),x,2)=diff(f(x),x)+sin(x)") |
| 1053 | |
| 1054 | - ``vars`` - a list of strings representing the |
| 1055 | variables (e.g., vars = ["x","f"]) |
| 1056 | |
| 1057 | - ``ics`` - a list of numbers representing initial |
| 1058 | conditions, with symbols allowed which are represented by strings |
| 1059 | (eg, f(0)=1, f'(0)=2 is ics = [0,1,2]) |
| 1060 | |
| 1061 | |
| 1062 | EXAMPLES:: |
| 1063 | |
| 1064 | sage: maxima.clear('x'); maxima.clear('f') |
| 1065 | sage: maxima.de_solve_laplace("diff(f(x),x,2) = 2*diff(f(x),x)-f(x)", ["x","f"], [0,1,2]) |
| 1066 | f(x)=x*%e^x+%e^x |
| 1067 | |
| 1068 | :: |
| 1069 | |
| 1070 | sage: maxima.clear('x'); maxima.clear('f') |
| 1071 | sage: f = maxima.de_solve_laplace("diff(f(x),x,2) = 2*diff(f(x),x)-f(x)", ["x","f"]) |
| 1072 | sage: f |
| 1073 | f(x)=x*%e^x*('at('diff(f(x),x,1),x=0))-f(0)*x*%e^x+f(0)*%e^x |
| 1074 | sage: print f |
| 1075 | ! |
| 1076 | x d ! x x |
| 1077 | f(x) = x %e (-- (f(x))! ) - f(0) x %e + f(0) %e |
| 1078 | dx ! |
| 1079 | !x = 0 |
| 1080 | |
| 1081 | .. note:: |
| 1082 | |
| 1083 | The second equation sets the values of `f(0)` and |
| 1084 | `f'(0)` in Maxima, so subsequent ODEs involving these |
| 1085 | variables will have these initial conditions automatically |
| 1086 | imposed. |
| 1087 | """ |
| 1088 | if not (ics is None): |
| 1089 | d = len(ics) |
| 1090 | for i in range(0,d-1): |
| 1091 | ic = 'atvalue(diff(%s(%s), %s, %s), %s = %s, %s)'%( |
| 1092 | vars[1], vars[0], vars[0], i, vars[0], ics[0], ics[1+i]) |
| 1093 | self.eval(ic) |
| 1094 | return self('desolve(%s, %s(%s))'%(de, vars[1], vars[0])) |
| 1095 | |
| 1096 | def solve_linear(self, eqns,vars): |
| 1097 | """ |
| 1098 | Wraps maxima's linsolve. |
| 1099 | |
| 1100 | INPUT: eqns is a list of m strings, each representing a linear |
| 1101 | question in m = n variables vars is a list of n strings, each |
| 1102 | representing a variable |
| 1103 | |
| 1104 | EXAMPLES:: |
| 1105 | |
| 1106 | sage: eqns = ["x + z = y","2*a*x - y = 2*a^2","y - 2*z = 2"] |
| 1107 | sage: vars = ["x","y","z"] |
| 1108 | sage: maxima.solve_linear(eqns, vars) |
| 1109 | [x=a+1,y=2*a,z=a-1] |
| 1110 | """ |
| 1111 | eqs = "[" |
| 1112 | for i in range(len(eqns)): |
| 1113 | if i<len(eqns)-1: |
| 1114 | eqs = eqs + eqns[i]+"," |
| 1115 | if i==len(eqns)-1: |
| 1116 | eqs = eqs + eqns[i]+"]" |
| 1117 | vrs = "[" |
| 1118 | for i in range(len(vars)): |
| 1119 | if i<len(vars)-1: |
| 1120 | vrs = vrs + vars[i]+"," |
| 1121 | if i==len(vars)-1: |
| 1122 | vrs = vrs + vars[i]+"]" |
| 1123 | return self('linsolve(%s, %s)'%(eqs, vrs)) |
| 1124 | |
| 1125 | def unit_quadratic_integer(self, n): |
| 1126 | r""" |
| 1127 | Finds a unit of the ring of integers of the quadratic number field |
| 1128 | `\QQ(\sqrt{n})`, `n>1`, using the qunit maxima |
| 1129 | command. |
| 1130 | |
| 1131 | EXAMPLES:: |
| 1132 | |
| 1133 | sage: u = maxima.unit_quadratic_integer(101); u |
| 1134 | a + 10 |
| 1135 | sage: u.parent() |
| 1136 | Number Field in a with defining polynomial x^2 - 101 |
| 1137 | sage: u = maxima.unit_quadratic_integer(13) |
| 1138 | sage: u |
| 1139 | 5*a + 18 |
| 1140 | sage: u.parent() |
| 1141 | Number Field in a with defining polynomial x^2 - 13 |
| 1142 | """ |
| 1143 | from sage.rings.all import QuadraticField, Integer |
| 1144 | # Take square-free part so sqrt(n) doesn't get simplified further by maxima |
| 1145 | # (The original version of this function would yield wrong answers if |
| 1146 | # n is not squarefree.) |
| 1147 | n = Integer(n).squarefree_part() |
| 1148 | if n < 1: |
| 1149 | raise ValueError, "n (=%s) must be >= 1"%n |
| 1150 | s = repr(self('qunit(%s)'%n)).lower() |
| 1151 | r = re.compile('sqrt\(.*\)') |
| 1152 | s = r.sub('a', s) |
| 1153 | a = QuadraticField(n, 'a').gen() |
| 1154 | return eval(s) |
| 1155 | |
| 1156 | def plot_list(self, ptsx, ptsy, options=None): |
| 1157 | r""" |
| 1158 | Plots a curve determined by a sequence of points. |
| 1159 | |
| 1160 | INPUT: |
| 1161 | |
| 1162 | |
| 1163 | - ``ptsx`` - [x1,...,xn], where the xi and yi are |
| 1164 | real, |
| 1165 | |
| 1166 | - ``ptsy`` - [y1,...,yn] |
| 1167 | |
| 1168 | - ``options`` - a string representing maxima plot2d |
| 1169 | options. |
| 1170 | |
| 1171 | |
| 1172 | The points are (x1,y1), (x2,y2), etc. |
| 1173 | |
| 1174 | This function requires maxima 5.9.2 or newer. |
| 1175 | |
| 1176 | .. note:: |
| 1177 | |
| 1178 | More that 150 points can sometimes lead to the program |
| 1179 | hanging. Why? |
| 1180 | |
| 1181 | EXAMPLES:: |
| 1182 | |
| 1183 | sage: zeta_ptsx = [ (pari(1/2 + i*I/10).zeta().real()).precision(1) for i in range (70,150)] |
| 1184 | sage: zeta_ptsy = [ (pari(1/2 + i*I/10).zeta().imag()).precision(1) for i in range (70,150)] |
| 1185 | sage: maxima.plot_list(zeta_ptsx, zeta_ptsy) # not tested |
| 1186 | sage: opts='[gnuplot_preamble, "set nokey"], [gnuplot_term, ps], [gnuplot_out_file, "zeta.eps"]' |
| 1187 | sage: maxima.plot_list(zeta_ptsx, zeta_ptsy, opts) # not tested |
| 1188 | """ |
| 1189 | cmd = 'plot2d([discrete,%s, %s]'%(ptsx, ptsy) |
| 1190 | if options is None: |
| 1191 | cmd += ')' |
| 1192 | else: |
| 1193 | cmd += ', %s)'%options |
| 1194 | self(cmd) |
| 1195 | |
| 1196 | |
| 1197 | def plot_multilist(self, pts_list, options=None): |
| 1198 | r""" |
| 1199 | Plots a list of list of points pts_list=[pts1,pts2,...,ptsn], |
| 1200 | where each ptsi is of the form [[x1,y1],...,[xn,yn]] x's must be |
| 1201 | integers and y's reals options is a string representing maxima |
| 1202 | plot2d options. |
| 1203 | |
| 1204 | Requires maxima 5.9.2 at least. |
| 1205 | |
| 1206 | .. note:: |
| 1207 | |
| 1208 | More that 150 points can sometimes lead to the program |
| 1209 | hanging. |
| 1210 | |
| 1211 | EXAMPLES:: |
| 1212 | |
| 1213 | sage: xx = [ i/10.0 for i in range (-10,10)] |
| 1214 | sage: yy = [ i/10.0 for i in range (-10,10)] |
| 1215 | sage: x0 = [ 0 for i in range (-10,10)] |
| 1216 | sage: y0 = [ 0 for i in range (-10,10)] |
| 1217 | sage: zeta_ptsx1 = [ (pari(1/2+i*I/10).zeta().real()).precision(1) for i in range (10)] |
| 1218 | sage: zeta_ptsy1 = [ (pari(1/2+i*I/10).zeta().imag()).precision(1) for i in range (10)] |
| 1219 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]]) # not tested |
| 1220 | sage: zeta_ptsx1 = [ (pari(1/2+i*I/10).zeta().real()).precision(1) for i in range (10,150)] |
| 1221 | sage: zeta_ptsy1 = [ (pari(1/2+i*I/10).zeta().imag()).precision(1) for i in range (10,150)] |
| 1222 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]]) # not tested |
| 1223 | sage: opts='[gnuplot_preamble, "set nokey"]' |
| 1224 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]],opts) # not tested |
| 1225 | """ |
| 1226 | n = len(pts_list) |
| 1227 | cmd = '[' |
| 1228 | for i in range(n): |
| 1229 | if i < n-1: |
| 1230 | cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+'],' |
| 1231 | if i==n-1: |
| 1232 | cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+']]' |
| 1233 | #print cmd |
| 1234 | if options is None: |
| 1235 | self('plot2d('+cmd+')') |
| 1236 | else: |
| 1237 | self('plot2d('+cmd+','+options+')') |
| 1238 | |
| 1239 | |
| 1240 | class MaximaElement(ExpectElement): |
| 1241 | def __str__(self): |
| 1242 | """ |
| 1243 | Printing an object explicitly gives ASCII art: |
| 1244 | |
| 1245 | EXAMPLES:: |
| 1246 | |
| 1247 | sage: f = maxima('1/(x-1)^3'); f |
| 1248 | 1/(x-1)^3 |
| 1249 | sage: print f |
| 1250 | 1 |
| 1251 | -------- |
| 1252 | 3 |
| 1253 | (x - 1) |
| 1254 | """ |
| 1255 | return self.display2d(onscreen=False) |
| 1256 | |
| 1257 | def bool(self): |
| 1258 | """ |
| 1259 | EXAMPLES:: |
| 1260 | |
| 1261 | sage: maxima(0).bool() |
| 1262 | False |
| 1263 | sage: maxima(1).bool() |
| 1264 | True |
| 1265 | """ |
| 1266 | P = self._check_valid() |
| 1267 | return P.eval('is(%s = 0);'%self.name()) == P._false_symbol() # but be careful, since for relations things like is(equal(a,b)) are what Maxima needs |
| 1268 | |
| 1269 | def __cmp__(self, other): |
| 1270 | """ |
| 1271 | EXAMPLES:: |
| 1272 | |
| 1273 | sage: a = maxima(1); b = maxima(2) |
| 1274 | sage: a == b |
| 1275 | False |
| 1276 | sage: a < b |
| 1277 | True |
| 1278 | sage: a > b |
| 1279 | False |
| 1280 | sage: b < a |
| 1281 | False |
| 1282 | sage: b > a |
| 1283 | True |
| 1284 | |
| 1285 | We can also compare more complicated object such as functions:: |
| 1286 | |
| 1287 | sage: f = maxima('sin(x)'); g = maxima('cos(x)') |
| 1288 | sage: -f == g.diff('x') |
| 1289 | True |
| 1290 | """ |
| 1291 | |
| 1292 | # thanks to David Joyner for telling me about using "is". |
| 1293 | # but be careful, since for relations things like is(equal(a,b)) are what Maxima needs |
| 1294 | P = self.parent() |
| 1295 | try: |
| 1296 | if P.eval("is (%s < %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1297 | return -1 |
| 1298 | elif P.eval("is (%s > %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1299 | return 1 |
| 1300 | elif P.eval("is (%s = %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1301 | return 0 |
| 1302 | except TypeError: |
| 1303 | pass |
| 1304 | return cmp(repr(self),repr(other)) |
| 1305 | # everything is supposed to be comparable in Python, so we define |
| 1306 | # the comparison thus when no comparable in interfaced system. |
| 1307 | |
| 1308 | def _sage_(self): |
| 1309 | """ |
| 1310 | Attempt to make a native Sage object out of this maxima object. |
| 1311 | This is useful for automatic coercions in addition to other |
| 1312 | things. |
| 1313 | |
| 1314 | EXAMPLES:: |
| 1315 | |
| 1316 | sage: a = maxima('sqrt(2) + 2.5'); a |
| 1317 | sqrt(2)+2.5 |
| 1318 | sage: b = a._sage_(); b |
| 1319 | sqrt(2) + 2.5 |
| 1320 | sage: type(b) |
| 1321 | <type 'sage.symbolic.expression.Expression'> |
| 1322 | |
| 1323 | We illustrate an automatic coercion:: |
| 1324 | |
| 1325 | sage: c = b + sqrt(3); c |
| 1326 | sqrt(2) + sqrt(3) + 2.5 |
| 1327 | sage: type(c) |
| 1328 | <type 'sage.symbolic.expression.Expression'> |
| 1329 | sage: d = sqrt(3) + b; d |
| 1330 | sqrt(2) + sqrt(3) + 2.5 |
| 1331 | sage: type(d) |
| 1332 | <type 'sage.symbolic.expression.Expression'> |
| 1333 | """ |
| 1334 | from sage.calculus.calculus import symbolic_expression_from_maxima_string |
| 1335 | #return symbolic_expression_from_maxima_string(self.name(), maxima=self.parent()) |
| 1336 | return symbolic_expression_from_maxima_string(repr(self)) |
| 1337 | |
| 1338 | def _symbolic_(self, R): |
| 1339 | """ |
| 1340 | Return a symbolic expression equivalent to this maxima object. |
| 1341 | |
| 1342 | EXAMPLES:: |
| 1343 | |
| 1344 | sage: t = sqrt(2)._maxima_() |
| 1345 | sage: u = t._symbolic_(SR); u |
| 1346 | sqrt(2) |
| 1347 | sage: u.parent() |
| 1348 | Symbolic Ring |
| 1349 | |
| 1350 | This is used when converting maxima objects to the Symbolic Ring:: |
| 1351 | |
| 1352 | sage: SR(t) |
| 1353 | sqrt(2) |
| 1354 | """ |
| 1355 | return R(self._sage_()) |
| 1356 | |
| 1357 | def __complex__(self): |
| 1358 | """ |
| 1359 | EXAMPLES:: |
| 1360 | |
| 1361 | sage: complex(maxima('sqrt(-2)+1')) |
| 1362 | (1+1.4142135623730951j) |
| 1363 | """ |
| 1364 | return complex(self._sage_()) |
| 1365 | |
| 1366 | def _complex_mpfr_field_(self, C): |
| 1367 | """ |
| 1368 | EXAMPLES:: |
| 1369 | |
| 1370 | sage: CC(maxima('1+%i')) |
| 1371 | 1.00000000000000 + 1.00000000000000*I |
| 1372 | sage: CC(maxima('2342.23482943872+234*%i')) |
| 1373 | 2342.23482943872 + 234.000000000000*I |
| 1374 | sage: ComplexField(10)(maxima('2342.23482943872+234*%i')) |
| 1375 | 2300. + 230.*I |
| 1376 | sage: ComplexField(200)(maxima('1+%i')) |
| 1377 | 1.0000000000000000000000000000000000000000000000000000000000 + 1.0000000000000000000000000000000000000000000000000000000000*I |
| 1378 | sage: ComplexField(200)(maxima('sqrt(-2)')) |
| 1379 | 1.4142135623730950488016887242096980785696718753769480731767*I |
| 1380 | sage: N(sqrt(-2), 200) |
| 1381 | 8.0751148893563733350506651837615871941533119425962889089783e-62 + 1.4142135623730950488016887242096980785696718753769480731767*I |
| 1382 | """ |
| 1383 | return C(self._sage_()) |
| 1384 | |
| 1385 | def _mpfr_(self, R): |
| 1386 | """ |
| 1387 | EXAMPLES:: |
| 1388 | |
| 1389 | sage: RealField(100)(maxima('sqrt(2)+1')) |
| 1390 | 2.4142135623730950488016887242 |
| 1391 | """ |
| 1392 | return R(self._sage_()) |
| 1393 | |
| 1394 | def _complex_double_(self, C): |
| 1395 | """ |
| 1396 | EXAMPLES:: |
| 1397 | |
| 1398 | sage: CDF(maxima('sqrt(2)+1')) |
| 1399 | 2.41421356237 |
| 1400 | """ |
| 1401 | return C(self._sage_()) |
| 1402 | |
| 1403 | def _real_double_(self, R): |
| 1404 | """ |
| 1405 | EXAMPLES:: |
| 1406 | |
| 1407 | sage: RDF(maxima('sqrt(2)+1')) |
| 1408 | 2.41421356237 |
| 1409 | """ |
| 1410 | return R(self._sage_()) |
| 1411 | |
| 1412 | def real(self): |
| 1413 | """ |
| 1414 | Return the real part of this maxima element. |
| 1415 | |
| 1416 | EXAMPLES:: |
| 1417 | |
| 1418 | sage: maxima('2 + (2/3)*%i').real() |
| 1419 | 2 |
| 1420 | """ |
| 1421 | return self.realpart() |
| 1422 | |
| 1423 | def imag(self): |
| 1424 | """ |
| 1425 | Return the imaginary part of this maxima element. |
| 1426 | |
| 1427 | EXAMPLES:: |
| 1428 | |
| 1429 | sage: maxima('2 + (2/3)*%i').imag() |
| 1430 | 2/3 |
| 1431 | """ |
| 1432 | return self.imagpart() |
| 1433 | |
| 1434 | def numer(self): |
| 1435 | """ |
| 1436 | Return numerical approximation to self as a Maxima object. |
| 1437 | |
| 1438 | EXAMPLES:: |
| 1439 | |
| 1440 | sage: a = maxima('sqrt(2)').numer(); a |
| 1441 | 1.414213562373095 |
| 1442 | sage: type(a) |
| 1443 | <class 'sage.interfaces.maxima_abstract.MaximaElement'> |
| 1444 | """ |
| 1445 | return self.comma('numer') |
| 1446 | |
| 1447 | def str(self): |
| 1448 | """ |
| 1449 | Return string representation of this maxima object. |
| 1450 | |
| 1451 | EXAMPLES:: |
| 1452 | |
| 1453 | sage: maxima('sqrt(2) + 1/3').str() |
| 1454 | 'sqrt(2)+1/3' |
| 1455 | """ |
| 1456 | P = self._check_valid() |
| 1457 | return P.get(self._name) |
| 1458 | |
| 1459 | def __repr__(self): |
| 1460 | """ |
| 1461 | Return print representation of this object. |
| 1462 | |
| 1463 | EXAMPLES:: |
| 1464 | |
| 1465 | sage: maxima('sqrt(2) + 1/3').__repr__() |
| 1466 | 'sqrt(2)+1/3' |
| 1467 | """ |
| 1468 | P = self._check_valid() |
| 1469 | try: |
| 1470 | return self.__repr |
| 1471 | except AttributeError: |
| 1472 | pass |
| 1473 | r = P.get(self._name) |
| 1474 | self.__repr = r |
| 1475 | return r |
| 1476 | |
| 1477 | def display2d(self, onscreen=True): |
| 1478 | """ |
| 1479 | EXAMPLES:: |
| 1480 | |
| 1481 | sage: F = maxima('x^5 - y^5').factor() |
| 1482 | sage: F.display2d () |
| 1483 | 4 3 2 2 3 4 |
| 1484 | - (y - x) (y + x y + x y + x y + x ) |
| 1485 | """ |
| 1486 | self._check_valid() |
| 1487 | P = self.parent() |
| 1488 | with gc_disabled(): |
| 1489 | P._eval_line('display2d : true$') |
| 1490 | s = P._eval_line('disp(%s)$'%self.name(), reformat=False) |
| 1491 | P._eval_line('display2d: false$') |
| 1492 | |
| 1493 | s = s.strip('\r\n') |
| 1494 | |
| 1495 | # if ever want to dedent, see |
| 1496 | # http://mail.python.org/pipermail/python-list/2006-December/420033.html |
| 1497 | if onscreen: |
| 1498 | print s |
| 1499 | else: |
| 1500 | return s |
| 1501 | |
| 1502 | def diff(self, var='x', n=1): |
| 1503 | """ |
| 1504 | Return the n-th derivative of self. |
| 1505 | |
| 1506 | INPUT: |
| 1507 | |
| 1508 | |
| 1509 | - ``var`` - variable (default: 'x') |
| 1510 | |
| 1511 | - ``n`` - integer (default: 1) |
| 1512 | |
| 1513 | |
| 1514 | OUTPUT: n-th derivative of self with respect to the variable var |
| 1515 | |
| 1516 | EXAMPLES:: |
| 1517 | |
| 1518 | sage: f = maxima('x^2') |
| 1519 | sage: f.diff() |
| 1520 | 2*x |
| 1521 | sage: f.diff('x') |
| 1522 | 2*x |
| 1523 | sage: f.diff('x', 2) |
| 1524 | 2 |
| 1525 | sage: maxima('sin(x^2)').diff('x',4) |
| 1526 | 16*x^4*sin(x^2)-12*sin(x^2)-48*x^2*cos(x^2) |
| 1527 | |
| 1528 | :: |
| 1529 | |
| 1530 | sage: f = maxima('x^2 + 17*y^2') |
| 1531 | sage: f.diff('x') |
| 1532 | 34*y*'diff(y,x,1)+2*x |
| 1533 | sage: f.diff('y') |
| 1534 | 34*y |
| 1535 | """ |
| 1536 | return ExpectElement.__getattr__(self, 'diff')(var, n) |
| 1537 | |
| 1538 | derivative = diff |
| 1539 | |
| 1540 | def nintegral(self, var='x', a=0, b=1, |
| 1541 | desired_relative_error='1e-8', |
| 1542 | maximum_num_subintervals=200): |
| 1543 | r""" |
| 1544 | Return a numerical approximation to the integral of self from a to |
| 1545 | b. |
| 1546 | |
| 1547 | INPUT: |
| 1548 | |
| 1549 | |
| 1550 | - ``var`` - variable to integrate with respect to |
| 1551 | |
| 1552 | - ``a`` - lower endpoint of integration |
| 1553 | |
| 1554 | - ``b`` - upper endpoint of integration |
| 1555 | |
| 1556 | - ``desired_relative_error`` - (default: '1e-8') the |
| 1557 | desired relative error |
| 1558 | |
| 1559 | - ``maximum_num_subintervals`` - (default: 200) |
| 1560 | maxima number of subintervals |
| 1561 | |
| 1562 | |
| 1563 | OUTPUT: |
| 1564 | |
| 1565 | |
| 1566 | - approximation to the integral |
| 1567 | |
| 1568 | - estimated absolute error of the |
| 1569 | approximation |
| 1570 | |
| 1571 | - the number of integrand evaluations |
| 1572 | |
| 1573 | - an error code: |
| 1574 | |
| 1575 | - ``0`` - no problems were encountered |
| 1576 | |
| 1577 | - ``1`` - too many subintervals were done |
| 1578 | |
| 1579 | - ``2`` - excessive roundoff error |
| 1580 | |
| 1581 | - ``3`` - extremely bad integrand behavior |
| 1582 | |
| 1583 | - ``4`` - failed to converge |
| 1584 | |
| 1585 | - ``5`` - integral is probably divergent or slowly convergent |
| 1586 | |
| 1587 | - ``6`` - the input is invalid |
| 1588 | |
| 1589 | |
| 1590 | EXAMPLES:: |
| 1591 | |
| 1592 | sage: maxima('exp(-sqrt(x))').nintegral('x',0,1) |
| 1593 | (.5284822353142306, 4.163314137883845e-11, 231, 0) |
| 1594 | |
| 1595 | Note that GP also does numerical integration, and can do so to very |
| 1596 | high precision very quickly:: |
| 1597 | |
| 1598 | sage: gp('intnum(x=0,1,exp(-sqrt(x)))') |
| 1599 | 0.5284822353142307136179049194 # 32-bit |
| 1600 | 0.52848223531423071361790491935415653021 # 64-bit |
| 1601 | sage: _ = gp.set_precision(80) |
| 1602 | sage: gp('intnum(x=0,1,exp(-sqrt(x)))') |
| 1603 | 0.52848223531423071361790491935415653021675547587292866196865279321015401702040079 |
| 1604 | """ |
| 1605 | from sage.rings.all import Integer |
| 1606 | v = self.quad_qags(var, a, b, epsrel=desired_relative_error, |
| 1607 | limit=maximum_num_subintervals) |
| 1608 | return v[0], v[1], Integer(v[2]), Integer(v[3]) |
| 1609 | |
| 1610 | def integral(self, var='x', min=None, max=None): |
| 1611 | r""" |
| 1612 | Return the integral of self with respect to the variable x. |
| 1613 | |
| 1614 | INPUT: |
| 1615 | |
| 1616 | |
| 1617 | - ``var`` - variable |
| 1618 | |
| 1619 | - ``min`` - default: None |
| 1620 | |
| 1621 | - ``max`` - default: None |
| 1622 | |
| 1623 | |
| 1624 | Returns the definite integral if xmin is not None, otherwise |
| 1625 | returns an indefinite integral. |
| 1626 | |
| 1627 | EXAMPLES:: |
| 1628 | |
| 1629 | sage: maxima('x^2+1').integral() |
| 1630 | x^3/3+x |
| 1631 | sage: maxima('x^2+ 1 + y^2').integral('y') |
| 1632 | y^3/3+x^2*y+y |
| 1633 | sage: maxima('x / (x^2+1)').integral() |
| 1634 | log(x^2+1)/2 |
| 1635 | sage: maxima('1/(x^2+1)').integral() |
| 1636 | atan(x) |
| 1637 | sage: maxima('1/(x^2+1)').integral('x', 0, infinity) |
| 1638 | %pi/2 |
| 1639 | sage: maxima('x/(x^2+1)').integral('x', -1, 1) |
| 1640 | 0 |
| 1641 | |
| 1642 | :: |
| 1643 | |
| 1644 | sage: f = maxima('exp(x^2)').integral('x',0,1); f |
| 1645 | -sqrt(%pi)*%i*erf(%i)/2 |
| 1646 | sage: f.numer() |
| 1647 | 1.462651745907182 |
| 1648 | """ |
| 1649 | I = ExpectElement.__getattr__(self, 'integrate') |
| 1650 | if min is None: |
| 1651 | return I(var) |
| 1652 | else: |
| 1653 | if max is None: |
| 1654 | raise ValueError, "neither or both of min/max must be specified." |
| 1655 | return I(var, min, max) |
| 1656 | |
| 1657 | integrate = integral |
| 1658 | |
| 1659 | def __float__(self): |
| 1660 | """ |
| 1661 | Return floating point version of this maxima element. |
| 1662 | |
| 1663 | EXAMPLES:: |
| 1664 | |
| 1665 | sage: float(maxima("3.14")) |
| 1666 | 3.1400000000000001 |
| 1667 | sage: float(maxima("1.7e+17")) |
| 1668 | 1.7e+17 |
| 1669 | sage: float(maxima("1.7e-17")) |
| 1670 | 1.6999999999999999e-17 |
| 1671 | """ |
| 1672 | try: |
| 1673 | return float(repr(self.numer())) |
| 1674 | except ValueError: |
| 1675 | raise TypeError, "unable to coerce '%s' to float"%repr(self) |
| 1676 | |
| 1677 | def __len__(self): |
| 1678 | """ |
| 1679 | Return the length of a list. |
| 1680 | |
| 1681 | EXAMPLES:: |
| 1682 | |
| 1683 | sage: v = maxima('create_list(x^i,i,0,5)') |
| 1684 | sage: len(v) |
| 1685 | 6 |
| 1686 | """ |
| 1687 | P = self._check_valid() |
| 1688 | return int(P.eval('length(%s)'%self.name())) |
| 1689 | |
| 1690 | def dot(self, other): |
| 1691 | """ |
| 1692 | Implements the notation self . other. |
| 1693 | |
| 1694 | EXAMPLES:: |
| 1695 | |
| 1696 | sage: A = maxima('matrix ([a1],[a2])') |
| 1697 | sage: B = maxima('matrix ([b1, b2])') |
| 1698 | sage: A.dot(B) |
| 1699 | matrix([a1*b1,a1*b2],[a2*b1,a2*b2]) |
| 1700 | """ |
| 1701 | P = self._check_valid() |
| 1702 | Q = P(other) |
| 1703 | return P('%s . %s'%(self.name(), Q.name())) |
| 1704 | |
| 1705 | def __getitem__(self, n): |
| 1706 | r""" |
| 1707 | Return the n-th element of this list. |
| 1708 | |
| 1709 | .. note:: |
| 1710 | |
| 1711 | Lists are 0-based when accessed via the Sage interface, not |
| 1712 | 1-based as they are in the Maxima interpreter. |
| 1713 | |
| 1714 | EXAMPLES:: |
| 1715 | |
| 1716 | sage: v = maxima('create_list(i*x^i,i,0,5)'); v |
| 1717 | [0,x,2*x^2,3*x^3,4*x^4,5*x^5] |
| 1718 | sage: v[3] |
| 1719 | 3*x^3 |
| 1720 | sage: v[0] |
| 1721 | 0 |
| 1722 | sage: v[10] |
| 1723 | Traceback (most recent call last): |
| 1724 | ... |
| 1725 | IndexError: n = (10) must be between 0 and 5 |
| 1726 | """ |
| 1727 | n = int(n) |
| 1728 | if n < 0 or n >= len(self): |
| 1729 | raise IndexError, "n = (%s) must be between %s and %s"%(n, 0, len(self)-1) |
| 1730 | # If you change the n+1 to n below, better change __iter__ as well. |
| 1731 | return ExpectElement.__getitem__(self, n+1) |
| 1732 | |
| 1733 | def __iter__(self): |
| 1734 | """ |
| 1735 | EXAMPLE:: |
| 1736 | |
| 1737 | sage: v = maxima('create_list(i*x^i,i,0,5)') |
| 1738 | sage: L = list(v) |
| 1739 | sage: [e._sage_() for e in L] |
| 1740 | [0, x, 2*x^2, 3*x^3, 4*x^4, 5*x^5] |
| 1741 | """ |
| 1742 | for i in range(len(self)): |
| 1743 | yield self[i] |
| 1744 | |
| 1745 | def subst(self, val): |
| 1746 | """ |
| 1747 | Substitute a value or several values into this Maxima object. |
| 1748 | |
| 1749 | EXAMPLES:: |
| 1750 | |
| 1751 | sage: maxima('a^2 + 3*a + b').subst('b=2') |
| 1752 | a^2+3*a+2 |
| 1753 | sage: maxima('a^2 + 3*a + b').subst('a=17') |
| 1754 | b+340 |
| 1755 | sage: maxima('a^2 + 3*a + b').subst('a=17, b=2') |
| 1756 | 342 |
| 1757 | """ |
| 1758 | return self.comma(val) |
| 1759 | |
| 1760 | def comma(self, args): |
| 1761 | """ |
| 1762 | Form the expression that would be written 'self, args' in Maxima. |
| 1763 | |
| 1764 | EXAMPLES:: |
| 1765 | |
| 1766 | sage: maxima('sqrt(2) + I').comma('numer') |
| 1767 | I+1.414213562373095 |
| 1768 | sage: maxima('sqrt(2) + I*a').comma('a=5') |
| 1769 | 5*I+sqrt(2) |
| 1770 | """ |
| 1771 | self._check_valid() |
| 1772 | P = self.parent() |
| 1773 | return P('%s, %s'%(self.name(), args)) |
| 1774 | |
| 1775 | def _latex_(self): |
| 1776 | """ |
| 1777 | Return Latex representation of this Maxima object. |
| 1778 | |
| 1779 | This calls the tex command in Maxima, then does a little |
| 1780 | post-processing to fix bugs in the resulting Maxima output. |
| 1781 | |
| 1782 | EXAMPLES:: |
| 1783 | |
| 1784 | sage: maxima('sqrt(2) + 1/3 + asin(5)')._latex_() |
| 1785 | '\\sin^{-1}\\cdot5+\\sqrt{2}+{{1}\\over{3}}' |
| 1786 | |
| 1787 | sage: y,d = var('y,d') |
| 1788 | sage: latex(maxima(derivative(ceil(x*y*d), d,x,x,y))) |
| 1789 | d^3\,\left({{{\it \partial}^4}\over{{\it \partial}\,d^4}}\, {\it ceil}\left(d , x , y\right)\right)\,x^2\,y^3+5\,d^2\,\left({{ {\it \partial}^3}\over{{\it \partial}\,d^3}}\,{\it ceil}\left(d , x , y\right)\right)\,x\,y^2+4\,d\,\left({{{\it \partial}^2}\over{ {\it \partial}\,d^2}}\,{\it ceil}\left(d , x , y\right)\right)\,y |
| 1790 | |
| 1791 | |
| 1792 | sage: latex(maxima(d/(d-2))) |
| 1793 | {{d}\over{d-2}} |
| 1794 | """ |
| 1795 | self._check_valid() |
| 1796 | P = self.parent() |
| 1797 | s = P._eval_line('tex(%s);'%self.name(), reformat=False) |
| 1798 | if not '$$' in s: |
| 1799 | raise RuntimeError, "Error texing maxima object." |
| 1800 | i = s.find('$$') |
| 1801 | j = s.rfind('$$') |
| 1802 | s = s[i+2:j] |
| 1803 | s = multiple_replace({'\r\n':' ', |
| 1804 | '\\%':'', |
| 1805 | '\\arcsin ':'\\sin^{-1} ', |
| 1806 | '\\arccos ':'\\cos^{-1} ', |
| 1807 | '\\arctan ':'\\tan^{-1} '}, s) |
| 1808 | |
| 1809 | # Fix a maxima bug, which gives a latex representation of multiplying |
| 1810 | # two numbers as a single space. This was really bad when 2*17^(1/3) |
| 1811 | # gets TeXed as '2 17^{\frac{1}{3}}' |
| 1812 | # |
| 1813 | # This regex matches a string of spaces preceded by either a '}', a |
| 1814 | # decimal digit, or a ')', and followed by a decimal digit. The spaces |
| 1815 | # get replaced by a '\cdot'. |
| 1816 | s = re.sub(r'(?<=[})\d]) +(?=\d)', '\cdot', s) |
| 1817 | |
| 1818 | return s |
| 1819 | |
| 1820 | def trait_names(self, verbose=False): |
| 1821 | """ |
| 1822 | Return all Maxima commands, which is useful for tab completion. |
| 1823 | |
| 1824 | EXAMPLES:: |
| 1825 | |
| 1826 | sage: m = maxima(2) |
| 1827 | sage: 'gcd' in m.trait_names() |
| 1828 | True |
| 1829 | """ |
| 1830 | return self.parent().trait_names(verbose=False) |
| 1831 | |
| 1832 | def _matrix_(self, R): |
| 1833 | r""" |
| 1834 | If self is a Maxima matrix, return the corresponding Sage matrix |
| 1835 | over the Sage ring `R`. |
| 1836 | |
| 1837 | This may or may not work depending in how complicated the entries |
| 1838 | of self are! It only works if the entries of self can be coerced as |
| 1839 | strings to produce meaningful elements of `R`. |
| 1840 | |
| 1841 | EXAMPLES:: |
| 1842 | |
| 1843 | sage: _ = maxima.eval("f[i,j] := i/j") |
| 1844 | sage: A = maxima('genmatrix(f,4,4)'); A |
| 1845 | matrix([1,1/2,1/3,1/4],[2,1,2/3,1/2],[3,3/2,1,3/4],[4,2,4/3,1]) |
| 1846 | sage: A._matrix_(QQ) |
| 1847 | [ 1 1/2 1/3 1/4] |
| 1848 | [ 2 1 2/3 1/2] |
| 1849 | [ 3 3/2 1 3/4] |
| 1850 | [ 4 2 4/3 1] |
| 1851 | |
| 1852 | You can also use the ``matrix`` command (which is |
| 1853 | defined in ``sage.misc.functional``):: |
| 1854 | |
| 1855 | sage: matrix(QQ, A) |
| 1856 | [ 1 1/2 1/3 1/4] |
| 1857 | [ 2 1 2/3 1/2] |
| 1858 | [ 3 3/2 1 3/4] |
| 1859 | [ 4 2 4/3 1] |
| 1860 | """ |
| 1861 | from sage.matrix.all import MatrixSpace |
| 1862 | self._check_valid() |
| 1863 | P = self.parent() |
| 1864 | nrows = int(P.eval('length(%s)'%self.name())) |
| 1865 | if nrows == 0: |
| 1866 | return MatrixSpace(R, 0, 0)(0) |
| 1867 | ncols = int(P.eval('length(%s[1])'%self.name())) |
| 1868 | M = MatrixSpace(R, nrows, ncols) |
| 1869 | s = self.str().replace('matrix','').replace(',',"','").\ |
| 1870 | replace("]','[","','").replace('([',"['").replace('])',"']") |
| 1871 | s = eval(s) |
| 1872 | return M([R(x) for x in s]) |
| 1873 | |
| 1874 | def partial_fraction_decomposition(self, var='x'): |
| 1875 | """ |
| 1876 | Return the partial fraction decomposition of self with respect to |
| 1877 | the variable var. |
| 1878 | |
| 1879 | EXAMPLES:: |
| 1880 | |
| 1881 | sage: f = maxima('1/((1+x)*(x-1))') |
| 1882 | sage: f.partial_fraction_decomposition('x') |
| 1883 | 1/(2*(x-1))-1/(2*(x+1)) |
| 1884 | sage: print f.partial_fraction_decomposition('x') |
| 1885 | 1 1 |
| 1886 | --------- - --------- |
| 1887 | 2 (x - 1) 2 (x + 1) |
| 1888 | """ |
| 1889 | return self.partfrac(var) |
| 1890 | |
| 1891 | def _operation(self, operation, right): |
| 1892 | r""" |
| 1893 | Note that right's parent should already be Maxima since this should |
| 1894 | be called after coercion has been performed. |
| 1895 | |
| 1896 | If right is a ``MaximaFunction``, then we convert |
| 1897 | ``self`` to a ``MaximaFunction`` that takes |
| 1898 | no arguments, and let the |
| 1899 | ``MaximaFunction._operation`` code handle everything |
| 1900 | from there. |
| 1901 | |
| 1902 | EXAMPLES:: |
| 1903 | |
| 1904 | sage: f = maxima.cos(x) |
| 1905 | sage: f._operation("+", f) |
| 1906 | 2*cos(x) |
| 1907 | """ |
| 1908 | P = self._check_valid() |
| 1909 | |
| 1910 | if isinstance(right, MaximaFunction): |
| 1911 | fself = P.function('', repr(self)) |
| 1912 | return fself._operation(operation, right) |
| 1913 | |
| 1914 | try: |
| 1915 | return P.new('%s %s %s'%(self._name, operation, right._name)) |
| 1916 | except Exception, msg: |
| 1917 | raise TypeError, msg |
| 1918 | |
| 1919 | |
| 1920 | |
| 1921 | class MaximaFunctionElement(FunctionElement): |
| 1922 | def _sage_doc_(self): |
| 1923 | """ |
| 1924 | EXAMPLES:: |
| 1925 | |
| 1926 | sage: m = maxima(4) |
| 1927 | sage: m.gcd._sage_doc_() |
| 1928 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 1929 | ... |
| 1930 | """ |
| 1931 | return self._obj.parent().help(self._name) |
| 1932 | |
| 1933 | class MaximaExpectFunction(ExpectFunction): |
| 1934 | def _sage_doc_(self): |
| 1935 | """ |
| 1936 | EXAMPLES:: |
| 1937 | |
| 1938 | sage: maxima.gcd._sage_doc_() |
| 1939 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 1940 | ... |
| 1941 | """ |
| 1942 | M = self._parent |
| 1943 | return M.help(self._name) |
| 1944 | |
| 1945 | |
| 1946 | class MaximaFunction(MaximaElement): |
| 1947 | def __init__(self, parent, name, defn, args, latex): |
| 1948 | """ |
| 1949 | EXAMPLES:: |
| 1950 | |
| 1951 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1952 | sage: f == loads(dumps(f)) |
| 1953 | True |
| 1954 | """ |
| 1955 | MaximaElement.__init__(self, parent, name, is_name=True) |
| 1956 | self.__defn = defn |
| 1957 | self.__args = args |
| 1958 | self.__latex = latex |
| 1959 | |
| 1960 | def __reduce__(self): |
| 1961 | """ |
| 1962 | EXAMPLES:: |
| 1963 | |
| 1964 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1965 | sage: f.__reduce__() |
| 1966 | (<function reduce_load_Maxima_function at 0x...>, |
| 1967 | (Maxima, 'sin(x+y)', 'x,y', None)) |
| 1968 | """ |
| 1969 | return reduce_load_Maxima_function, (self.parent(), self.__defn, self.__args, self.__latex) |
| 1970 | |
| 1971 | def __call__(self, *x): |
| 1972 | """ |
| 1973 | EXAMPLES:: |
| 1974 | |
| 1975 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1976 | sage: f(1,2) |
| 1977 | sin(3) |
| 1978 | sage: f(x,x) |
| 1979 | sin(2*x) |
| 1980 | """ |
| 1981 | P = self._check_valid() |
| 1982 | if len(x) == 1: |
| 1983 | x = '(%s)'%x |
| 1984 | return P('%s%s'%(self.name(), x)) |
| 1985 | |
| 1986 | def __repr__(self): |
| 1987 | """ |
| 1988 | EXAMPLES:: |
| 1989 | |
| 1990 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1991 | sage: repr(f) |
| 1992 | 'sin(x+y)' |
| 1993 | """ |
| 1994 | return self.definition() |
| 1995 | |
| 1996 | def _latex_(self): |
| 1997 | """ |
| 1998 | EXAMPLES:: |
| 1999 | |
| 2000 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2001 | sage: latex(f) |
| 2002 | \mathrm{sin(x+y)} |
| 2003 | """ |
| 2004 | if self.__latex is None: |
| 2005 | return r'\mathrm{%s}'%self.__defn |
| 2006 | else: |
| 2007 | return self.__latex |
| 2008 | |
| 2009 | def arguments(self, split=True): |
| 2010 | r""" |
| 2011 | Returns the arguments of this Maxima function. |
| 2012 | |
| 2013 | EXAMPLES:: |
| 2014 | |
| 2015 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2016 | sage: f.arguments() |
| 2017 | ['x', 'y'] |
| 2018 | sage: f.arguments(split=False) |
| 2019 | 'x,y' |
| 2020 | sage: f = maxima.function('', 'sin(x)') |
| 2021 | sage: f.arguments() |
| 2022 | [] |
| 2023 | """ |
| 2024 | if split: |
| 2025 | return self.__args.split(',') if self.__args != '' else [] |
| 2026 | else: |
| 2027 | return self.__args |
| 2028 | |
| 2029 | def definition(self): |
| 2030 | """ |
| 2031 | Returns the definition of this Maxima function as a string. |
| 2032 | |
| 2033 | EXAMPLES:: |
| 2034 | |
| 2035 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2036 | sage: f.definition() |
| 2037 | 'sin(x+y)' |
| 2038 | """ |
| 2039 | return self.__defn |
| 2040 | |
| 2041 | def integral(self, var): |
| 2042 | """ |
| 2043 | Returns the integral of self with respect to the variable var. |
| 2044 | |
| 2045 | Note that integrate is an alias of integral. |
| 2046 | |
| 2047 | EXAMPLES:: |
| 2048 | |
| 2049 | sage: x,y = var('x,y') |
| 2050 | sage: f = maxima.function('x','sin(x)') |
| 2051 | sage: f.integral(x) |
| 2052 | -cos(x) |
| 2053 | sage: f.integral(y) |
| 2054 | sin(x)*y |
| 2055 | """ |
| 2056 | var = str(var) |
| 2057 | P = self._check_valid() |
| 2058 | f = P('integrate(%s(%s), %s)'%(self.name(), self.arguments(split=False), var)) |
| 2059 | |
| 2060 | args = self.arguments() |
| 2061 | if var not in args: |
| 2062 | args.append(var) |
| 2063 | return P.function(",".join(args), repr(f)) |
| 2064 | |
| 2065 | integrate = integral |
| 2066 | |
| 2067 | def _operation(self, operation, f=None): |
| 2068 | r""" |
| 2069 | This is a utility function which factors out much of the |
| 2070 | commonality used in the arithmetic operations for |
| 2071 | ``MaximaFunctions``. |
| 2072 | |
| 2073 | INPUT: |
| 2074 | |
| 2075 | |
| 2076 | - ``operation`` - A string representing the operation |
| 2077 | being performed. For example, '\*', or '1/'. |
| 2078 | |
| 2079 | - ``f`` - The other operand. If f is |
| 2080 | ``None``, than the operation is assumed to be unary |
| 2081 | rather than binary. |
| 2082 | |
| 2083 | |
| 2084 | EXAMPLES:: |
| 2085 | |
| 2086 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2087 | sage: f._operation("+", f) |
| 2088 | 2*sin(y+x) |
| 2089 | sage: f._operation("+", 2) |
| 2090 | sin(y+x)+2 |
| 2091 | sage: f._operation('-') |
| 2092 | -sin(y+x) |
| 2093 | sage: f._operation('1/') |
| 2094 | 1/sin(y+x) |
| 2095 | """ |
| 2096 | P = self._check_valid() |
| 2097 | if isinstance(f, MaximaFunction): |
| 2098 | tmp = list(sorted(set(self.arguments() + f.arguments()))) |
| 2099 | args = ','.join(tmp) |
| 2100 | defn = "(%s)%s(%s)"%(self.definition(), operation, f.definition()) |
| 2101 | elif f is None: |
| 2102 | args = self.arguments(split=False) |
| 2103 | defn = "%s(%s)"%(operation, self.definition()) |
| 2104 | else: |
| 2105 | args = self.arguments(split=False) |
| 2106 | defn = "(%s)%s(%s)"%(self.definition(), operation, repr(f)) |
| 2107 | |
| 2108 | return P.function(args,P.eval(defn)) |
| 2109 | |
| 2110 | def _add_(self, f): |
| 2111 | """ |
| 2112 | MaximaFunction as left summand. |
| 2113 | |
| 2114 | EXAMPLES:: |
| 2115 | |
| 2116 | sage: x,y = var('x,y') |
| 2117 | sage: f = maxima.function('x','sin(x)') |
| 2118 | sage: g = maxima.function('x','-cos(x)') |
| 2119 | sage: f+g |
| 2120 | sin(x)-cos(x) |
| 2121 | sage: f+3 |
| 2122 | sin(x)+3 |
| 2123 | |
| 2124 | :: |
| 2125 | |
| 2126 | sage: (f+maxima.cos(x))(2) |
| 2127 | sin(2)+cos(2) |
| 2128 | sage: (f+maxima.cos(y)) # This is a function with only ONE argument! |
| 2129 | cos(y)+sin(x) |
| 2130 | sage: (f+maxima.cos(y))(2) |
| 2131 | cos(y)+sin(2) |
| 2132 | |
| 2133 | :: |
| 2134 | |
| 2135 | sage: f = maxima.function('x','sin(x)') |
| 2136 | sage: g = -maxima.cos(x) |
| 2137 | sage: g+f |
| 2138 | sin(x)-cos(x) |
| 2139 | sage: (g+f)(2) # The sum IS a function |
| 2140 | sin(2)-cos(2) |
| 2141 | sage: 2+f |
| 2142 | sin(x)+2 |
| 2143 | """ |
| 2144 | return self._operation("+", f) |
| 2145 | |
| 2146 | def _sub_(self, f): |
| 2147 | r""" |
| 2148 | ``MaximaFunction`` as minuend. |
| 2149 | |
| 2150 | EXAMPLES:: |
| 2151 | |
| 2152 | sage: x,y = var('x,y') |
| 2153 | sage: f = maxima.function('x','sin(x)') |
| 2154 | sage: g = -maxima.cos(x) # not a function |
| 2155 | sage: f-g |
| 2156 | sin(x)+cos(x) |
| 2157 | sage: (f-g)(2) |
| 2158 | sin(2)+cos(2) |
| 2159 | sage: (f-maxima.cos(y)) # This function only has the argument x! |
| 2160 | sin(x)-cos(y) |
| 2161 | sage: _(2) |
| 2162 | sin(2)-cos(y) |
| 2163 | |
| 2164 | :: |
| 2165 | |
| 2166 | sage: g-f |
| 2167 | -sin(x)-cos(x) |
| 2168 | """ |
| 2169 | return self._operation("-", f) |
| 2170 | |
| 2171 | def _mul_(self, f): |
| 2172 | r""" |
| 2173 | ``MaximaFunction`` as left factor. |
| 2174 | |
| 2175 | EXAMPLES:: |
| 2176 | |
| 2177 | sage: f = maxima.function('x','sin(x)') |
| 2178 | sage: g = maxima('-cos(x)') # not a function! |
| 2179 | sage: f*g |
| 2180 | -cos(x)*sin(x) |
| 2181 | sage: _(2) |
| 2182 | -cos(2)*sin(2) |
| 2183 | |
| 2184 | :: |
| 2185 | |
| 2186 | sage: f = maxima.function('x','sin(x)') |
| 2187 | sage: g = maxima('-cos(x)') |
| 2188 | sage: g*f |
| 2189 | -cos(x)*sin(x) |
| 2190 | sage: _(2) |
| 2191 | -cos(2)*sin(2) |
| 2192 | sage: 2*f |
| 2193 | 2*sin(x) |
| 2194 | """ |
| 2195 | return self._operation("*", f) |
| 2196 | |
| 2197 | def _div_(self, f): |
| 2198 | r""" |
| 2199 | ``MaximaFunction`` as dividend. |
| 2200 | |
| 2201 | EXAMPLES:: |
| 2202 | |
| 2203 | sage: f=maxima.function('x','sin(x)') |
| 2204 | sage: g=maxima('-cos(x)') |
| 2205 | sage: f/g |
| 2206 | -sin(x)/cos(x) |
| 2207 | sage: _(2) |
| 2208 | -sin(2)/cos(2) |
| 2209 | |
| 2210 | :: |
| 2211 | |
| 2212 | sage: f=maxima.function('x','sin(x)') |
| 2213 | sage: g=maxima('-cos(x)') |
| 2214 | sage: g/f |
| 2215 | -cos(x)/sin(x) |
| 2216 | sage: _(2) |
| 2217 | -cos(2)/sin(2) |
| 2218 | sage: 2/f |
| 2219 | 2/sin(x) |
| 2220 | """ |
| 2221 | return self._operation("/", f) |
| 2222 | |
| 2223 | def __neg__(self): |
| 2224 | r""" |
| 2225 | Additive inverse of a ``MaximaFunction``. |
| 2226 | |
| 2227 | EXAMPLES:: |
| 2228 | |
| 2229 | sage: f=maxima.function('x','sin(x)') |
| 2230 | sage: -f |
| 2231 | -sin(x) |
| 2232 | """ |
| 2233 | return self._operation('-') |
| 2234 | |
| 2235 | def __inv__(self): |
| 2236 | r""" |
| 2237 | Multiplicative inverse of a ``MaximaFunction``. |
| 2238 | |
| 2239 | EXAMPLES:: |
| 2240 | |
| 2241 | sage: f = maxima.function('x','sin(x)') |
| 2242 | sage: ~f |
| 2243 | 1/sin(x) |
| 2244 | """ |
| 2245 | return self._operation('1/') |
| 2246 | |
| 2247 | def __pow__(self,f): |
| 2248 | r""" |
| 2249 | ``MaximaFunction`` raised to some power. |
| 2250 | |
| 2251 | EXAMPLES:: |
| 2252 | |
| 2253 | sage: f=maxima.function('x','sin(x)') |
| 2254 | sage: g=maxima('-cos(x)') |
| 2255 | sage: f^g |
| 2256 | 1/sin(x)^cos(x) |
| 2257 | |
| 2258 | :: |
| 2259 | |
| 2260 | sage: f=maxima.function('x','sin(x)') |
| 2261 | sage: g=maxima('-cos(x)') # not a function |
| 2262 | sage: g^f |
| 2263 | (-cos(x))^sin(x) |
| 2264 | """ |
| 2265 | return self._operation("^", f) |
| 2266 | |
| 2267 | |
| 2268 | |
| 2269 | def reduce_load_Maxima_function(parent, defn, args, latex): |
| 2270 | return parent.function(args, defn, defn, latex) |
| 2271 | |
| 2272 | |
| 2273 | import os |
| 2274 | def maxima_console(): |
| 2275 | """ |
| 2276 | Spawn a new Maxima command-line session. |
| 2277 | |
| 2278 | EXAMPLES:: |
| 2279 | |
| 2280 | sage: from sage.interfaces.maxima import maxima_console |
| 2281 | sage: maxima_console() # not tested |
| 2282 | Maxima 5.16.3 http://maxima.sourceforge.net |
| 2283 | ... |
| 2284 | """ |
| 2285 | os.system('maxima') |