| 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='+') |
| 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 | |
| 502 | # We set maxima's configuration directory to $DOT_SAGE/maxima |
| 503 | # This avoids that sage's maxima inadvertently loads |
| 504 | # ~/.maxima/maxima-init.mac |
| 505 | # If you absolutely want maxima instances that are started by |
| 506 | # this interface to preload commands, put them in |
| 507 | # $DOT_SAGE/maxima/maxima-init.mac |
| 508 | # (we use the "--userdir" option in maxima for this) |
| 509 | import sage.misc.misc |
| 510 | SAGE_MAXIMA_DIR = os.path.join(sage.misc.misc.DOT_SAGE,"maxima") |
| 511 | |
| 512 | if not os.path.exists(STARTUP): |
| 513 | raise RuntimeError, 'You must get the file local/bin/sage-maxima.lisp' |
| 514 | if init_code is None: |
| 515 | # display2d -- no ascii art output |
| 516 | # keepfloat -- don't automatically convert floats to rationals |
| 517 | init_code = ['display2d : false', 'keepfloat : true'] |
| 518 | |
| 519 | # Turn off the prompt labels, since computing them *very |
| 520 | # dramatically* slows down the maxima interpret after a while. |
| 521 | # See the function makelabel in suprv1.lisp. |
| 522 | # Many thanks to andrej.vodopivec@gmail.com and also |
| 523 | # Robert Dodier for figuring this out! |
| 524 | # See trac # 6818. |
| 525 | init_code.append('nolabels:true') |
| 526 | |
| 527 | Expect.__init__(self, |
| 528 | name = 'maxima', |
| 529 | prompt = '\(\%i[0-9]+\)', |
| 530 | command = 'maxima-noreadline --userdir="%s" -p "%s"'%(SAGE_MAXIMA_DIR,STARTUP), |
| 531 | maxread = 10000, |
| 532 | script_subdirectory = script_subdirectory, |
| 533 | restart_on_ctrlc = False, |
| 534 | verbose_start = False, |
| 535 | init_code = init_code, |
| 536 | logfile = logfile, |
| 537 | eval_using_file_cutoff=eval_using_file_cutoff) |
| 538 | self._display_prompt = '<sage-display>' # must match what is in the file local/bin/sage-maxima.lisp!! |
| 539 | self._output_prompt_re = re.compile('\(\%o[0-9]+\)') |
| 540 | self._ask = ['zero or nonzero?', 'an integer?', 'positive, negative, or zero?', |
| 541 | 'positive or negative?', 'positive or zero?'] |
| 542 | self._prompt_wait = [self._prompt] + [re.compile(x) for x in self._ask] + \ |
| 543 | ['Break [0-9]+'] #note that you might need to change _expect_expr if you |
| 544 | #change this |
| 545 | self._error_re = re.compile('(Principal Value|debugmode|incorrect syntax|Maxima encountered a Lisp error)') |
| 546 | self._display2d = False |
| 547 | |
| 548 | def _quit_string(self): |
| 549 | """ |
| 550 | EXAMPLES:: |
| 551 | |
| 552 | sage: maxima._quit_string() |
| 553 | 'quit();' |
| 554 | """ |
| 555 | return 'quit();' |
| 556 | |
| 557 | def _crash_msg(self): |
| 558 | """ |
| 559 | EXAMPLES:: |
| 560 | |
| 561 | sage: maxima._crash_msg() |
| 562 | Maxima crashed -- automatically restarting. |
| 563 | """ |
| 564 | print "Maxima crashed -- automatically restarting." |
| 565 | |
| 566 | |
| 567 | def _batch(self, s, batchload=True): |
| 568 | filename = '%s-%s'%(self._local_tmpfile(),randrange(2147483647)) |
| 569 | F = open(filename, 'w') |
| 570 | F.write(s) |
| 571 | F.close() |
| 572 | if self.is_remote(): |
| 573 | self._send_tmpfile_to_server(local_file=filename) |
| 574 | tmp_to_use = self._remote_tmpfile() |
| 575 | tmp_to_use = filename |
| 576 | |
| 577 | if batchload: |
| 578 | cmd = 'batchload("%s");'%tmp_to_use |
| 579 | else: |
| 580 | cmd = 'batch("%s");'%tmp_to_use |
| 581 | |
| 582 | r = randrange(2147483647) |
| 583 | s = str(r+1) |
| 584 | cmd = "%s1+%s;\n"%(cmd,r) |
| 585 | |
| 586 | self._sendline(cmd) |
| 587 | self._expect_expr(s) |
| 588 | out = self._before() |
| 589 | self._error_check(str, out) |
| 590 | os.unlink(filename) |
| 591 | return out |
| 592 | |
| 593 | def _error_check(self, str, out): |
| 594 | r = self._error_re |
| 595 | m = r.search(out) |
| 596 | if not m is None: |
| 597 | self._error_msg(str, out) |
| 598 | |
| 599 | def _error_msg(self, str, out): |
| 600 | 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);','')) |
| 601 | |
| 602 | |
| 603 | ########################################### |
| 604 | # System -- change directory, etc |
| 605 | ########################################### |
| 606 | def chdir(self, dir): |
| 607 | """ |
| 608 | Change Maxima's current working directory. |
| 609 | |
| 610 | EXAMPLES:: |
| 611 | |
| 612 | sage: maxima.chdir('/') |
| 613 | """ |
| 614 | self.lisp('(ext::cd "%s")'%dir) |
| 615 | |
| 616 | ########################################### |
| 617 | # Interactive help |
| 618 | ########################################### |
| 619 | |
| 620 | |
| 621 | def help(self, s): |
| 622 | """ |
| 623 | EXAMPLES:: |
| 624 | |
| 625 | sage: maxima.help('gcd') |
| 626 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 627 | ... |
| 628 | """ |
| 629 | return self._command_runner("describe", s) |
| 630 | |
| 631 | def example(self, s): |
| 632 | """ |
| 633 | EXAMPLES:: |
| 634 | |
| 635 | sage: maxima.example('arrays') |
| 636 | a[n]:=n*a[n-1] |
| 637 | a := n a |
| 638 | n n - 1 |
| 639 | a[0]:1 |
| 640 | a[5] |
| 641 | 120 |
| 642 | a[n]:=n |
| 643 | a[6] |
| 644 | 6 |
| 645 | a[4] |
| 646 | 24 |
| 647 | done |
| 648 | """ |
| 649 | return self._command_runner("example", s) |
| 650 | |
| 651 | describe = help |
| 652 | |
| 653 | def demo(self, s): |
| 654 | """ |
| 655 | EXAMPLES:: |
| 656 | |
| 657 | sage: maxima.demo('array') # not tested |
| 658 | batching /opt/sage/local/share/maxima/5.16.3/demo/array.dem |
| 659 | |
| 660 | At the _ prompt, type ';' followed by enter to get next demo |
| 661 | subscrmap : true _ |
| 662 | """ |
| 663 | return self._command_runner("demo", s, redirect=False) |
| 664 | |
| 665 | def completions(self, s, verbose=True): |
| 666 | """ |
| 667 | Return all commands that complete the command starting with the |
| 668 | string s. This is like typing s[tab] in the Maxima interpreter. |
| 669 | |
| 670 | EXAMPLES:: |
| 671 | |
| 672 | sage: sorted(maxima.completions('gc', verbose=False)) |
| 673 | ['gcd', 'gcdex', 'gcfactor', 'gcprint', 'gctime'] |
| 674 | """ |
| 675 | if verbose: |
| 676 | print s, |
| 677 | sys.stdout.flush() |
| 678 | # in Maxima 5.19.1, apropos returns all commands that contain |
| 679 | # the given string, instead of all commands that start with |
| 680 | # the given string |
| 681 | cmd_list = self._eval_line('apropos("%s")'%s, error_check=False).replace('\\ - ','-') |
| 682 | cmd_list = [x for x in cmd_list[1:-1].split(',') if x[0] != '?'] |
| 683 | return [x for x in cmd_list if x.find(s) == 0] |
| 684 | |
| 685 | def _commands(self, verbose=True): |
| 686 | """ |
| 687 | Return list of all commands defined in Maxima. |
| 688 | |
| 689 | EXAMPLES:: |
| 690 | |
| 691 | sage: sorted(maxima._commands(verbose=False)) |
| 692 | ['Alpha', |
| 693 | 'Beta', |
| 694 | ... |
| 695 | 'zunderflow'] |
| 696 | """ |
| 697 | try: |
| 698 | return self.__commands |
| 699 | except AttributeError: |
| 700 | self.__commands = sum( |
| 701 | [self.completions(chr(65+n), verbose=verbose)+ |
| 702 | self.completions(chr(97+n), verbose=verbose) |
| 703 | for n in range(26)], []) |
| 704 | return self.__commands |
| 705 | |
| 706 | def trait_names(self, verbose=True, use_disk_cache=True): |
| 707 | """ |
| 708 | Return all Maxima commands, which is useful for tab completion. |
| 709 | |
| 710 | EXAMPLES:: |
| 711 | |
| 712 | sage: t = maxima.trait_names(verbose=False) |
| 713 | sage: 'gcd' in t |
| 714 | True |
| 715 | sage: len(t) # random output |
| 716 | 1840 |
| 717 | """ |
| 718 | try: |
| 719 | return self.__trait_names |
| 720 | except AttributeError: |
| 721 | import sage.misc.persist |
| 722 | if use_disk_cache: |
| 723 | try: |
| 724 | self.__trait_names = sage.misc.persist.load(COMMANDS_CACHE) |
| 725 | return self.__trait_names |
| 726 | except IOError: |
| 727 | pass |
| 728 | if verbose: |
| 729 | print "\nBuilding Maxima command completion list (this takes" |
| 730 | print "a few seconds only the first time you do it)." |
| 731 | print "To force rebuild later, delete %s."%COMMANDS_CACHE |
| 732 | v = self._commands(verbose=verbose) |
| 733 | if verbose: |
| 734 | print "\nDone!" |
| 735 | self.__trait_names = v |
| 736 | sage.misc.persist.save(v, COMMANDS_CACHE) |
| 737 | return v |
| 738 | |
| 739 | def _true_symbol(self): |
| 740 | """ |
| 741 | Return the true symbol in Maxima. |
| 742 | |
| 743 | EXAMPLES:: |
| 744 | |
| 745 | sage: maxima._true_symbol() |
| 746 | 'true' |
| 747 | sage: maxima.eval('is(2 = 2)') |
| 748 | 'true' |
| 749 | """ |
| 750 | return 'true' |
| 751 | |
| 752 | def _false_symbol(self): |
| 753 | """ |
| 754 | Return the false symbol in Maxima. |
| 755 | |
| 756 | EXAMPLES:: |
| 757 | |
| 758 | sage: maxima._false_symbol() |
| 759 | 'false' |
| 760 | sage: maxima.eval('is(2 = 4)') |
| 761 | 'false' |
| 762 | """ |
| 763 | return 'false' |
| 764 | |
| 765 | def _equality_symbol(self): |
| 766 | """ |
| 767 | Returns the equality symbol in Maxima. |
| 768 | |
| 769 | EXAMPLES:: |
| 770 | |
| 771 | sage: maxima._equality_symbol() |
| 772 | '=' |
| 773 | """ |
| 774 | return '=' |
| 775 | |
| 776 | def _inequality_symbol(self): |
| 777 | """ |
| 778 | Returns the equality symbol in Maxima. |
| 779 | |
| 780 | EXAMPLES:: |
| 781 | |
| 782 | sage: maxima._inequality_symbol() |
| 783 | '#' |
| 784 | sage: maxima((x != 1)) |
| 785 | x#1 |
| 786 | """ |
| 787 | return '#' |
| 788 | |
| 789 | def console(self): |
| 790 | r""" |
| 791 | Start the interactive Maxima console. This is a completely separate |
| 792 | maxima session from this interface. To interact with this session, |
| 793 | you should instead use ``maxima.interact()``. |
| 794 | |
| 795 | EXAMPLES:: |
| 796 | |
| 797 | sage: maxima.console() # not tested (since we can't) |
| 798 | Maxima 5.13.0 http://maxima.sourceforge.net |
| 799 | Using Lisp CLISP 2.41 (2006-10-13) |
| 800 | Distributed under the GNU Public License. See the file COPYING. |
| 801 | Dedicated to the memory of William Schelter. |
| 802 | This is a development version of Maxima. The function bug_report() |
| 803 | provides bug reporting information. |
| 804 | (%i1) |
| 805 | |
| 806 | :: |
| 807 | |
| 808 | sage: maxima.interact() # this is not tested either |
| 809 | --> Switching to Maxima <-- |
| 810 | maxima: 2+2 |
| 811 | 4 |
| 812 | maxima: |
| 813 | --> Exiting back to Sage <-- |
| 814 | """ |
| 815 | maxima_console() |
| 816 | |
| 817 | def cputime(self, t=None): |
| 818 | r""" |
| 819 | Returns the amount of CPU time that this Maxima session has used. |
| 820 | If \var{t} is not None, then it returns the difference between |
| 821 | the current CPU time and \var{t}. |
| 822 | |
| 823 | EXAMPLES: |
| 824 | sage: t = maxima.cputime() |
| 825 | sage: _ = maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1]) |
| 826 | sage: maxima.cputime(t) # output random |
| 827 | 0.568913 |
| 828 | """ |
| 829 | if t: |
| 830 | return float(self.eval('elapsed_run_time()')) - t |
| 831 | else: |
| 832 | return float(self.eval('elapsed_run_time()')) |
| 833 | |
| 834 | |
| 835 | ## def display2d(self, flag=True): |
| 836 | ## """ |
| 837 | ## Set the flag that determines whether Maxima objects are |
| 838 | ## printed using their 2-d ASCII art representation. When the |
| 839 | ## maxima interface starts the default is that objects are not |
| 840 | ## represented in 2-d. |
| 841 | |
| 842 | ## INPUT: |
| 843 | ## flag -- bool (default: True) |
| 844 | |
| 845 | ## EXAMPLES |
| 846 | ## sage: maxima('1/2') |
| 847 | ## 1/2 |
| 848 | ## sage: maxima.display2d(True) |
| 849 | ## sage: maxima('1/2') |
| 850 | ## 1 |
| 851 | ## - |
| 852 | ## 2 |
| 853 | ## sage: maxima.display2d(False) |
| 854 | ## """ |
| 855 | ## self._display2d = bool(flag) |
| 856 | |
| 857 | def plot2d(self, *args): |
| 858 | r""" |
| 859 | Plot a 2d graph using Maxima / gnuplot. |
| 860 | |
| 861 | maxima.plot2d(f, '[var, min, max]', options) |
| 862 | |
| 863 | INPUT: |
| 864 | |
| 865 | |
| 866 | - ``f`` - a string representing a function (such as |
| 867 | f="sin(x)") [var, xmin, xmax] |
| 868 | |
| 869 | - ``options`` - an optional string representing plot2d |
| 870 | options in gnuplot format |
| 871 | |
| 872 | |
| 873 | EXAMPLES:: |
| 874 | |
| 875 | sage: maxima.plot2d('sin(x)','[x,-5,5]') # not tested |
| 876 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-plot.eps"]' |
| 877 | sage: maxima.plot2d('sin(x)','[x,-5,5]',opts) # not tested |
| 878 | |
| 879 | The eps file is saved in the current directory. |
| 880 | """ |
| 881 | self('plot2d(%s)'%(','.join([str(x) for x in args]))) |
| 882 | |
| 883 | def plot2d_parametric(self, r, var, trange, nticks=50, options=None): |
| 884 | r""" |
| 885 | Plots r = [x(t), y(t)] for t = tmin...tmax using gnuplot with |
| 886 | options |
| 887 | |
| 888 | INPUT: |
| 889 | |
| 890 | |
| 891 | - ``r`` - a string representing a function (such as |
| 892 | r="[x(t),y(t)]") |
| 893 | |
| 894 | - ``var`` - a string representing the variable (such |
| 895 | as var = "t") |
| 896 | |
| 897 | - ``trange`` - [tmin, tmax] are numbers with tmintmax |
| 898 | |
| 899 | - ``nticks`` - int (default: 50) |
| 900 | |
| 901 | - ``options`` - an optional string representing plot2d |
| 902 | options in gnuplot format |
| 903 | |
| 904 | |
| 905 | EXAMPLES:: |
| 906 | |
| 907 | sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t",[-3.1,3.1]) # not tested |
| 908 | |
| 909 | :: |
| 910 | |
| 911 | sage: opts = '[gnuplot_preamble, "set nokey"], [gnuplot_term, ps], [gnuplot_out_file, "circle-plot.eps"]' |
| 912 | sage: maxima.plot2d_parametric(["sin(t)","cos(t)"], "t", [-3.1,3.1], options=opts) # not tested |
| 913 | |
| 914 | The eps file is saved to the current working directory. |
| 915 | |
| 916 | Here is another fun plot:: |
| 917 | |
| 918 | sage: maxima.plot2d_parametric(["sin(5*t)","cos(11*t)"], "t", [0,2*pi()], nticks=400) # not tested |
| 919 | """ |
| 920 | tmin = trange[0] |
| 921 | tmax = trange[1] |
| 922 | cmd = "plot2d([parametric, %s, %s, [%s, %s, %s], [nticks, %s]]"%( \ |
| 923 | r[0], r[1], var, tmin, tmax, nticks) |
| 924 | if options is None: |
| 925 | cmd += ")" |
| 926 | else: |
| 927 | cmd += ", %s)"%options |
| 928 | self(cmd) |
| 929 | |
| 930 | def plot3d(self, *args): |
| 931 | r""" |
| 932 | Plot a 3d graph using Maxima / gnuplot. |
| 933 | |
| 934 | maxima.plot3d(f, '[x, xmin, xmax]', '[y, ymin, ymax]', '[grid, nx, |
| 935 | ny]', options) |
| 936 | |
| 937 | INPUT: |
| 938 | |
| 939 | |
| 940 | - ``f`` - a string representing a function (such as |
| 941 | f="sin(x)") [var, min, max] |
| 942 | |
| 943 | |
| 944 | EXAMPLES:: |
| 945 | |
| 946 | sage: maxima.plot3d('1 + x^3 - y^2', '[x,-2,2]', '[y,-2,2]', '[grid,12,12]') # not tested |
| 947 | sage: maxima.plot3d('sin(x)*cos(y)', '[x,-2,2]', '[y,-2,2]', '[grid,30,30]') # not tested |
| 948 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-plot.eps"]' |
| 949 | sage: maxima.plot3d('sin(x+y)', '[x,-5,5]', '[y,-1,1]', opts) # not tested |
| 950 | |
| 951 | The eps file is saved in the current working directory. |
| 952 | """ |
| 953 | self('plot3d(%s)'%(','.join([str(x) for x in args]))) |
| 954 | |
| 955 | def plot3d_parametric(self, r, vars, urange, vrange, options=None): |
| 956 | r""" |
| 957 | Plot a 3d parametric graph with r=(x,y,z), x = x(u,v), y = y(u,v), |
| 958 | z = z(u,v), for u = umin...umax, v = vmin...vmax using gnuplot with |
| 959 | options. |
| 960 | |
| 961 | INPUT: |
| 962 | |
| 963 | |
| 964 | - ``x, y, z`` - a string representing a function (such |
| 965 | as ``x="u2+v2"``, ...) vars is a list or two strings |
| 966 | representing variables (such as vars = ["u","v"]) |
| 967 | |
| 968 | - ``urange`` - [umin, umax] |
| 969 | |
| 970 | - ``vrange`` - [vmin, vmax] are lists of numbers with |
| 971 | umin umax, vmin vmax |
| 972 | |
| 973 | - ``options`` - optional string representing plot2d |
| 974 | options in gnuplot format |
| 975 | |
| 976 | |
| 977 | OUTPUT: displays a plot on screen or saves to a file |
| 978 | |
| 979 | EXAMPLES:: |
| 980 | |
| 981 | sage: maxima.plot3d_parametric(["v*sin(u)","v*cos(u)","v"], ["u","v"],[-3.2,3.2],[0,3]) # not tested |
| 982 | sage: opts = '[gnuplot_term, ps], [gnuplot_out_file, "sin-cos-plot.eps"]' |
| 983 | sage: maxima.plot3d_parametric(["v*sin(u)","v*cos(u)","v"], ["u","v"],[-3.2,3.2],[0,3],opts) # not tested |
| 984 | |
| 985 | The eps file is saved in the current working directory. |
| 986 | |
| 987 | Here is a torus:: |
| 988 | |
| 989 | 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 |
| 990 | sage: maxima.plot3d_parametric(["expr_1","expr_2","expr_3"], ["x","y"],[0,6],[0,6]) # not tested |
| 991 | |
| 992 | Here is a Mobius strip:: |
| 993 | |
| 994 | sage: x = "cos(u)*(3 + v*cos(u/2))" |
| 995 | sage: y = "sin(u)*(3 + v*cos(u/2))" |
| 996 | sage: z = "v*sin(u/2)" |
| 997 | sage: maxima.plot3d_parametric([x,y,z],["u","v"],[-3.1,3.2],[-1/10,1/10]) # not tested |
| 998 | """ |
| 999 | umin = urange[0] |
| 1000 | umax = urange[1] |
| 1001 | vmin = vrange[0] |
| 1002 | vmax = vrange[1] |
| 1003 | cmd = 'plot3d([%s, %s, %s], [%s, %s, %s], [%s, %s, %s]'%( |
| 1004 | r[0], r[1], r[2], vars[0], umin, umax, vars[1], vmin, vmax) |
| 1005 | if options is None: |
| 1006 | cmd += ')' |
| 1007 | else: |
| 1008 | cmd += ', %s)'%options |
| 1009 | self(cmd) |
| 1010 | |
| 1011 | def de_solve(self, de, vars, ics=None): |
| 1012 | """ |
| 1013 | Solves a 1st or 2nd order ordinary differential equation (ODE) in |
| 1014 | two variables, possibly with initial conditions. |
| 1015 | |
| 1016 | INPUT: |
| 1017 | |
| 1018 | |
| 1019 | - ``de`` - a string representing the ODE |
| 1020 | |
| 1021 | - ``vars`` - a list of strings representing the two |
| 1022 | variables. |
| 1023 | |
| 1024 | - ``ics`` - a triple of numbers [a,b1,b2] representing |
| 1025 | y(a)=b1, y'(a)=b2 |
| 1026 | |
| 1027 | |
| 1028 | EXAMPLES:: |
| 1029 | |
| 1030 | sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y'], [1,1,1]) |
| 1031 | y=3*x-2*%e^(x-1) |
| 1032 | sage: maxima.de_solve('diff(y,x,2) + 3*x = y', ['x','y']) |
| 1033 | y=%k1*%e^x+%k2*%e^-x+3*x |
| 1034 | sage: maxima.de_solve('diff(y,x) + 3*x = y', ['x','y']) |
| 1035 | y=(%c-3*(-x-1)*%e^-x)*%e^x |
| 1036 | sage: maxima.de_solve('diff(y,x) + 3*x = y', ['x','y'],[1,1]) |
| 1037 | y=-%e^-1*(5*%e^x-3*%e*x-3*%e) |
| 1038 | """ |
| 1039 | if not isinstance(vars, str): |
| 1040 | str_vars = '%s, %s'%(vars[1], vars[0]) |
| 1041 | else: |
| 1042 | str_vars = vars |
| 1043 | self.eval('depends(%s)'%str_vars) |
| 1044 | m = self(de) |
| 1045 | a = 'ode2(%s, %s)'%(m.name(), str_vars) |
| 1046 | if ics != None: |
| 1047 | if len(ics) == 3: |
| 1048 | 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]) |
| 1049 | return self(cmd) |
| 1050 | if len(ics) == 2: |
| 1051 | return self("ic1("+a+",%s=%s,%s=%s);"%(vars[0],ics[0], vars[1],ics[1])) |
| 1052 | return self(a+";") |
| 1053 | |
| 1054 | def de_solve_laplace(self, de, vars, ics=None): |
| 1055 | """ |
| 1056 | Solves an ordinary differential equation (ODE) using Laplace |
| 1057 | transforms. |
| 1058 | |
| 1059 | INPUT: |
| 1060 | |
| 1061 | |
| 1062 | - ``de`` - a string representing the ODE (e.g., de = |
| 1063 | "diff(f(x),x,2)=diff(f(x),x)+sin(x)") |
| 1064 | |
| 1065 | - ``vars`` - a list of strings representing the |
| 1066 | variables (e.g., vars = ["x","f"]) |
| 1067 | |
| 1068 | - ``ics`` - a list of numbers representing initial |
| 1069 | conditions, with symbols allowed which are represented by strings |
| 1070 | (eg, f(0)=1, f'(0)=2 is ics = [0,1,2]) |
| 1071 | |
| 1072 | |
| 1073 | EXAMPLES:: |
| 1074 | |
| 1075 | sage: maxima.clear('x'); maxima.clear('f') |
| 1076 | sage: maxima.de_solve_laplace("diff(f(x),x,2) = 2*diff(f(x),x)-f(x)", ["x","f"], [0,1,2]) |
| 1077 | f(x)=x*%e^x+%e^x |
| 1078 | |
| 1079 | :: |
| 1080 | |
| 1081 | sage: maxima.clear('x'); maxima.clear('f') |
| 1082 | sage: f = maxima.de_solve_laplace("diff(f(x),x,2) = 2*diff(f(x),x)-f(x)", ["x","f"]) |
| 1083 | sage: f |
| 1084 | f(x)=x*%e^x*('at('diff(f(x),x,1),x=0))-f(0)*x*%e^x+f(0)*%e^x |
| 1085 | sage: print f |
| 1086 | ! |
| 1087 | x d ! x x |
| 1088 | f(x) = x %e (-- (f(x))! ) - f(0) x %e + f(0) %e |
| 1089 | dx ! |
| 1090 | !x = 0 |
| 1091 | |
| 1092 | .. note:: |
| 1093 | |
| 1094 | The second equation sets the values of `f(0)` and |
| 1095 | `f'(0)` in Maxima, so subsequent ODEs involving these |
| 1096 | variables will have these initial conditions automatically |
| 1097 | imposed. |
| 1098 | """ |
| 1099 | if not (ics is None): |
| 1100 | d = len(ics) |
| 1101 | for i in range(0,d-1): |
| 1102 | ic = 'atvalue(diff(%s(%s), %s, %s), %s = %s, %s)'%( |
| 1103 | vars[1], vars[0], vars[0], i, vars[0], ics[0], ics[1+i]) |
| 1104 | self.eval(ic) |
| 1105 | return self('desolve(%s, %s(%s))'%(de, vars[1], vars[0])) |
| 1106 | |
| 1107 | def solve_linear(self, eqns,vars): |
| 1108 | """ |
| 1109 | Wraps maxima's linsolve. |
| 1110 | |
| 1111 | INPUT: eqns is a list of m strings, each representing a linear |
| 1112 | question in m = n variables vars is a list of n strings, each |
| 1113 | representing a variable |
| 1114 | |
| 1115 | EXAMPLES:: |
| 1116 | |
| 1117 | sage: eqns = ["x + z = y","2*a*x - y = 2*a^2","y - 2*z = 2"] |
| 1118 | sage: vars = ["x","y","z"] |
| 1119 | sage: maxima.solve_linear(eqns, vars) |
| 1120 | [x=a+1,y=2*a,z=a-1] |
| 1121 | """ |
| 1122 | eqs = "[" |
| 1123 | for i in range(len(eqns)): |
| 1124 | if i<len(eqns)-1: |
| 1125 | eqs = eqs + eqns[i]+"," |
| 1126 | if i==len(eqns)-1: |
| 1127 | eqs = eqs + eqns[i]+"]" |
| 1128 | vrs = "[" |
| 1129 | for i in range(len(vars)): |
| 1130 | if i<len(vars)-1: |
| 1131 | vrs = vrs + vars[i]+"," |
| 1132 | if i==len(vars)-1: |
| 1133 | vrs = vrs + vars[i]+"]" |
| 1134 | return self('linsolve(%s, %s)'%(eqs, vrs)) |
| 1135 | |
| 1136 | def unit_quadratic_integer(self, n): |
| 1137 | r""" |
| 1138 | Finds a unit of the ring of integers of the quadratic number field |
| 1139 | `\QQ(\sqrt{n})`, `n>1`, using the qunit maxima |
| 1140 | command. |
| 1141 | |
| 1142 | EXAMPLES:: |
| 1143 | |
| 1144 | sage: u = maxima.unit_quadratic_integer(101); u |
| 1145 | a + 10 |
| 1146 | sage: u.parent() |
| 1147 | Number Field in a with defining polynomial x^2 - 101 |
| 1148 | sage: u = maxima.unit_quadratic_integer(13) |
| 1149 | sage: u |
| 1150 | 5*a + 18 |
| 1151 | sage: u.parent() |
| 1152 | Number Field in a with defining polynomial x^2 - 13 |
| 1153 | """ |
| 1154 | from sage.rings.all import QuadraticField, Integer |
| 1155 | # Take square-free part so sqrt(n) doesn't get simplified further by maxima |
| 1156 | # (The original version of this function would yield wrong answers if |
| 1157 | # n is not squarefree.) |
| 1158 | n = Integer(n).squarefree_part() |
| 1159 | if n < 1: |
| 1160 | raise ValueError, "n (=%s) must be >= 1"%n |
| 1161 | s = repr(self('qunit(%s)'%n)).lower() |
| 1162 | r = re.compile('sqrt\(.*\)') |
| 1163 | s = r.sub('a', s) |
| 1164 | a = QuadraticField(n, 'a').gen() |
| 1165 | return eval(s) |
| 1166 | |
| 1167 | def plot_list(self, ptsx, ptsy, options=None): |
| 1168 | r""" |
| 1169 | Plots a curve determined by a sequence of points. |
| 1170 | |
| 1171 | INPUT: |
| 1172 | |
| 1173 | |
| 1174 | - ``ptsx`` - [x1,...,xn], where the xi and yi are |
| 1175 | real, |
| 1176 | |
| 1177 | - ``ptsy`` - [y1,...,yn] |
| 1178 | |
| 1179 | - ``options`` - a string representing maxima plot2d |
| 1180 | options. |
| 1181 | |
| 1182 | |
| 1183 | The points are (x1,y1), (x2,y2), etc. |
| 1184 | |
| 1185 | This function requires maxima 5.9.2 or newer. |
| 1186 | |
| 1187 | .. note:: |
| 1188 | |
| 1189 | More that 150 points can sometimes lead to the program |
| 1190 | hanging. Why? |
| 1191 | |
| 1192 | EXAMPLES:: |
| 1193 | |
| 1194 | sage: zeta_ptsx = [ (pari(1/2 + i*I/10).zeta().real()).precision(1) for i in range (70,150)] |
| 1195 | sage: zeta_ptsy = [ (pari(1/2 + i*I/10).zeta().imag()).precision(1) for i in range (70,150)] |
| 1196 | sage: maxima.plot_list(zeta_ptsx, zeta_ptsy) # not tested |
| 1197 | sage: opts='[gnuplot_preamble, "set nokey"], [gnuplot_term, ps], [gnuplot_out_file, "zeta.eps"]' |
| 1198 | sage: maxima.plot_list(zeta_ptsx, zeta_ptsy, opts) # not tested |
| 1199 | """ |
| 1200 | cmd = 'plot2d([discrete,%s, %s]'%(ptsx, ptsy) |
| 1201 | if options is None: |
| 1202 | cmd += ')' |
| 1203 | else: |
| 1204 | cmd += ', %s)'%options |
| 1205 | self(cmd) |
| 1206 | |
| 1207 | |
| 1208 | def plot_multilist(self, pts_list, options=None): |
| 1209 | r""" |
| 1210 | Plots a list of list of points pts_list=[pts1,pts2,...,ptsn], |
| 1211 | where each ptsi is of the form [[x1,y1],...,[xn,yn]] x's must be |
| 1212 | integers and y's reals options is a string representing maxima |
| 1213 | plot2d options. |
| 1214 | |
| 1215 | Requires maxima 5.9.2 at least. |
| 1216 | |
| 1217 | .. note:: |
| 1218 | |
| 1219 | More that 150 points can sometimes lead to the program |
| 1220 | hanging. |
| 1221 | |
| 1222 | EXAMPLES:: |
| 1223 | |
| 1224 | sage: xx = [ i/10.0 for i in range (-10,10)] |
| 1225 | sage: yy = [ i/10.0 for i in range (-10,10)] |
| 1226 | sage: x0 = [ 0 for i in range (-10,10)] |
| 1227 | sage: y0 = [ 0 for i in range (-10,10)] |
| 1228 | sage: zeta_ptsx1 = [ (pari(1/2+i*I/10).zeta().real()).precision(1) for i in range (10)] |
| 1229 | sage: zeta_ptsy1 = [ (pari(1/2+i*I/10).zeta().imag()).precision(1) for i in range (10)] |
| 1230 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]]) # not tested |
| 1231 | sage: zeta_ptsx1 = [ (pari(1/2+i*I/10).zeta().real()).precision(1) for i in range (10,150)] |
| 1232 | sage: zeta_ptsy1 = [ (pari(1/2+i*I/10).zeta().imag()).precision(1) for i in range (10,150)] |
| 1233 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]]) # not tested |
| 1234 | sage: opts='[gnuplot_preamble, "set nokey"]' |
| 1235 | sage: maxima.plot_multilist([[zeta_ptsx1,zeta_ptsy1],[xx,y0],[x0,yy]],opts) # not tested |
| 1236 | """ |
| 1237 | n = len(pts_list) |
| 1238 | cmd = '[' |
| 1239 | for i in range(n): |
| 1240 | if i < n-1: |
| 1241 | cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+'],' |
| 1242 | if i==n-1: |
| 1243 | cmd = cmd+'[discrete,'+str(pts_list[i][0])+','+str(pts_list[i][1])+']]' |
| 1244 | #print cmd |
| 1245 | if options is None: |
| 1246 | self('plot2d('+cmd+')') |
| 1247 | else: |
| 1248 | self('plot2d('+cmd+','+options+')') |
| 1249 | |
| 1250 | |
| 1251 | class MaximaElement(ExpectElement): |
| 1252 | def __str__(self): |
| 1253 | """ |
| 1254 | Printing an object explicitly gives ASCII art: |
| 1255 | |
| 1256 | EXAMPLES:: |
| 1257 | |
| 1258 | sage: f = maxima('1/(x-1)^3'); f |
| 1259 | 1/(x-1)^3 |
| 1260 | sage: print f |
| 1261 | 1 |
| 1262 | -------- |
| 1263 | 3 |
| 1264 | (x - 1) |
| 1265 | """ |
| 1266 | return self.display2d(onscreen=False) |
| 1267 | |
| 1268 | def bool(self): |
| 1269 | """ |
| 1270 | EXAMPLES:: |
| 1271 | |
| 1272 | sage: maxima(0).bool() |
| 1273 | False |
| 1274 | sage: maxima(1).bool() |
| 1275 | True |
| 1276 | """ |
| 1277 | P = self._check_valid() |
| 1278 | 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 |
| 1279 | |
| 1280 | def __cmp__(self, other): |
| 1281 | """ |
| 1282 | EXAMPLES:: |
| 1283 | |
| 1284 | sage: a = maxima(1); b = maxima(2) |
| 1285 | sage: a == b |
| 1286 | False |
| 1287 | sage: a < b |
| 1288 | True |
| 1289 | sage: a > b |
| 1290 | False |
| 1291 | sage: b < a |
| 1292 | False |
| 1293 | sage: b > a |
| 1294 | True |
| 1295 | |
| 1296 | We can also compare more complicated object such as functions:: |
| 1297 | |
| 1298 | sage: f = maxima('sin(x)'); g = maxima('cos(x)') |
| 1299 | sage: -f == g.diff('x') |
| 1300 | True |
| 1301 | """ |
| 1302 | |
| 1303 | # thanks to David Joyner for telling me about using "is". |
| 1304 | # but be careful, since for relations things like is(equal(a,b)) are what Maxima needs |
| 1305 | P = self.parent() |
| 1306 | try: |
| 1307 | if P.eval("is (%s < %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1308 | return -1 |
| 1309 | elif P.eval("is (%s > %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1310 | return 1 |
| 1311 | elif P.eval("is (%s = %s)"%(self.name(), other.name())) == P._true_symbol(): |
| 1312 | return 0 |
| 1313 | except TypeError: |
| 1314 | pass |
| 1315 | return cmp(repr(self),repr(other)) |
| 1316 | # everything is supposed to be comparable in Python, so we define |
| 1317 | # the comparison thus when no comparable in interfaced system. |
| 1318 | |
| 1319 | def _sage_(self): |
| 1320 | """ |
| 1321 | Attempt to make a native Sage object out of this maxima object. |
| 1322 | This is useful for automatic coercions in addition to other |
| 1323 | things. |
| 1324 | |
| 1325 | EXAMPLES:: |
| 1326 | |
| 1327 | sage: a = maxima('sqrt(2) + 2.5'); a |
| 1328 | sqrt(2)+2.5 |
| 1329 | sage: b = a._sage_(); b |
| 1330 | sqrt(2) + 2.5 |
| 1331 | sage: type(b) |
| 1332 | <type 'sage.symbolic.expression.Expression'> |
| 1333 | |
| 1334 | We illustrate an automatic coercion:: |
| 1335 | |
| 1336 | sage: c = b + sqrt(3); c |
| 1337 | sqrt(2) + sqrt(3) + 2.5 |
| 1338 | sage: type(c) |
| 1339 | <type 'sage.symbolic.expression.Expression'> |
| 1340 | sage: d = sqrt(3) + b; d |
| 1341 | sqrt(2) + sqrt(3) + 2.5 |
| 1342 | sage: type(d) |
| 1343 | <type 'sage.symbolic.expression.Expression'> |
| 1344 | |
| 1345 | sage: a = sage.calculus.calculus.maxima('x^(sqrt(y)+%pi) + sin(%e + %pi)') |
| 1346 | sage: a._sage_() |
| 1347 | x^(pi + sqrt(y)) - sin(e) |
| 1348 | sage: var('x, y') |
| 1349 | (x, y) |
| 1350 | sage: v = sage.calculus.calculus.maxima.vandermonde_matrix([x, y, 1/2]) |
| 1351 | sage: v._sage_() |
| 1352 | [ 1 x x^2] |
| 1353 | [ 1 y y^2] |
| 1354 | [ 1 1/2 1/4] |
| 1355 | |
| 1356 | Check if #7661 is fixed:: |
| 1357 | |
| 1358 | sage: var('delta') |
| 1359 | delta |
| 1360 | sage: (2*delta).simplify() |
| 1361 | 2*delta |
| 1362 | """ |
| 1363 | import sage.calculus.calculus as calculus |
| 1364 | return calculus.symbolic_expression_from_maxima_string(self.name(), |
| 1365 | maxima=self.parent()) |
| 1366 | |
| 1367 | def _symbolic_(self, R): |
| 1368 | """ |
| 1369 | Return a symbolic expression equivalent to this maxima object. |
| 1370 | |
| 1371 | EXAMPLES:: |
| 1372 | |
| 1373 | sage: t = sqrt(2)._maxima_() |
| 1374 | sage: u = t._symbolic_(SR); u |
| 1375 | sqrt(2) |
| 1376 | sage: u.parent() |
| 1377 | Symbolic Ring |
| 1378 | |
| 1379 | This is used when converting maxima objects to the Symbolic Ring:: |
| 1380 | |
| 1381 | sage: SR(t) |
| 1382 | sqrt(2) |
| 1383 | """ |
| 1384 | return R(self._sage_()) |
| 1385 | |
| 1386 | def __complex__(self): |
| 1387 | """ |
| 1388 | EXAMPLES:: |
| 1389 | |
| 1390 | sage: complex(maxima('sqrt(-2)+1')) |
| 1391 | (1+1.4142135623730951j) |
| 1392 | """ |
| 1393 | return complex(self._sage_()) |
| 1394 | |
| 1395 | def _complex_mpfr_field_(self, C): |
| 1396 | """ |
| 1397 | EXAMPLES:: |
| 1398 | |
| 1399 | sage: CC(maxima('1+%i')) |
| 1400 | 1.00000000000000 + 1.00000000000000*I |
| 1401 | sage: CC(maxima('2342.23482943872+234*%i')) |
| 1402 | 2342.23482943872 + 234.000000000000*I |
| 1403 | sage: ComplexField(10)(maxima('2342.23482943872+234*%i')) |
| 1404 | 2300. + 230.*I |
| 1405 | sage: ComplexField(200)(maxima('1+%i')) |
| 1406 | 1.0000000000000000000000000000000000000000000000000000000000 + 1.0000000000000000000000000000000000000000000000000000000000*I |
| 1407 | sage: ComplexField(200)(maxima('sqrt(-2)')) |
| 1408 | 1.4142135623730950488016887242096980785696718753769480731767*I |
| 1409 | sage: N(sqrt(-2), 200) |
| 1410 | 8.0751148893563733350506651837615871941533119425962889089783e-62 + 1.4142135623730950488016887242096980785696718753769480731767*I |
| 1411 | """ |
| 1412 | return C(self._sage_()) |
| 1413 | |
| 1414 | def _mpfr_(self, R): |
| 1415 | """ |
| 1416 | EXAMPLES:: |
| 1417 | |
| 1418 | sage: RealField(100)(maxima('sqrt(2)+1')) |
| 1419 | 2.4142135623730950488016887242 |
| 1420 | """ |
| 1421 | return R(self._sage_()) |
| 1422 | |
| 1423 | def _complex_double_(self, C): |
| 1424 | """ |
| 1425 | EXAMPLES:: |
| 1426 | |
| 1427 | sage: CDF(maxima('sqrt(2)+1')) |
| 1428 | 2.41421356237 |
| 1429 | """ |
| 1430 | return C(self._sage_()) |
| 1431 | |
| 1432 | def _real_double_(self, R): |
| 1433 | """ |
| 1434 | EXAMPLES:: |
| 1435 | |
| 1436 | sage: RDF(maxima('sqrt(2)+1')) |
| 1437 | 2.41421356237 |
| 1438 | """ |
| 1439 | return R(self._sage_()) |
| 1440 | |
| 1441 | def real(self): |
| 1442 | """ |
| 1443 | Return the real part of this maxima element. |
| 1444 | |
| 1445 | EXAMPLES:: |
| 1446 | |
| 1447 | sage: maxima('2 + (2/3)*%i').real() |
| 1448 | 2 |
| 1449 | """ |
| 1450 | return self.realpart() |
| 1451 | |
| 1452 | def imag(self): |
| 1453 | """ |
| 1454 | Return the imaginary part of this maxima element. |
| 1455 | |
| 1456 | EXAMPLES:: |
| 1457 | |
| 1458 | sage: maxima('2 + (2/3)*%i').imag() |
| 1459 | 2/3 |
| 1460 | """ |
| 1461 | return self.imagpart() |
| 1462 | |
| 1463 | def numer(self): |
| 1464 | """ |
| 1465 | Return numerical approximation to self as a Maxima object. |
| 1466 | |
| 1467 | EXAMPLES:: |
| 1468 | |
| 1469 | sage: a = maxima('sqrt(2)').numer(); a |
| 1470 | 1.41421356237309... |
| 1471 | sage: type(a) |
| 1472 | <class 'sage.interfaces.maxima_abstract.MaximaElement'> |
| 1473 | """ |
| 1474 | return self.comma('numer') |
| 1475 | |
| 1476 | def str(self): |
| 1477 | """ |
| 1478 | Return string representation of this maxima object. |
| 1479 | |
| 1480 | EXAMPLES:: |
| 1481 | |
| 1482 | sage: maxima('sqrt(2) + 1/3').str() |
| 1483 | 'sqrt(2)+1/3' |
| 1484 | """ |
| 1485 | P = self._check_valid() |
| 1486 | return P.get(self._name) |
| 1487 | |
| 1488 | def __repr__(self): |
| 1489 | """ |
| 1490 | Return print representation of this object. |
| 1491 | |
| 1492 | EXAMPLES:: |
| 1493 | |
| 1494 | sage: maxima('sqrt(2) + 1/3').__repr__() |
| 1495 | 'sqrt(2)+1/3' |
| 1496 | """ |
| 1497 | P = self._check_valid() |
| 1498 | try: |
| 1499 | return self.__repr |
| 1500 | except AttributeError: |
| 1501 | pass |
| 1502 | r = P.get(self._name) |
| 1503 | self.__repr = r |
| 1504 | return r |
| 1505 | |
| 1506 | def display2d(self, onscreen=True): |
| 1507 | """ |
| 1508 | EXAMPLES:: |
| 1509 | |
| 1510 | sage: F = maxima('x^5 - y^5').factor() |
| 1511 | sage: F.display2d () |
| 1512 | 4 3 2 2 3 4 |
| 1513 | - (y - x) (y + x y + x y + x y + x ) |
| 1514 | """ |
| 1515 | self._check_valid() |
| 1516 | P = self.parent() |
| 1517 | with gc_disabled(): |
| 1518 | P._eval_line('display2d : true$') |
| 1519 | s = P._eval_line('disp(%s)$'%self.name(), reformat=False) |
| 1520 | P._eval_line('display2d: false$') |
| 1521 | |
| 1522 | s = s.strip('\r\n') |
| 1523 | |
| 1524 | # if ever want to dedent, see |
| 1525 | # http://mail.python.org/pipermail/python-list/2006-December/420033.html |
| 1526 | if onscreen: |
| 1527 | print s |
| 1528 | else: |
| 1529 | return s |
| 1530 | |
| 1531 | def diff(self, var='x', n=1): |
| 1532 | """ |
| 1533 | Return the n-th derivative of self. |
| 1534 | |
| 1535 | INPUT: |
| 1536 | |
| 1537 | |
| 1538 | - ``var`` - variable (default: 'x') |
| 1539 | |
| 1540 | - ``n`` - integer (default: 1) |
| 1541 | |
| 1542 | |
| 1543 | OUTPUT: n-th derivative of self with respect to the variable var |
| 1544 | |
| 1545 | EXAMPLES:: |
| 1546 | |
| 1547 | sage: f = maxima('x^2') |
| 1548 | sage: f.diff() |
| 1549 | 2*x |
| 1550 | sage: f.diff('x') |
| 1551 | 2*x |
| 1552 | sage: f.diff('x', 2) |
| 1553 | 2 |
| 1554 | sage: maxima('sin(x^2)').diff('x',4) |
| 1555 | 16*x^4*sin(x^2)-12*sin(x^2)-48*x^2*cos(x^2) |
| 1556 | |
| 1557 | :: |
| 1558 | |
| 1559 | sage: f = maxima('x^2 + 17*y^2') |
| 1560 | sage: f.diff('x') |
| 1561 | 34*y*'diff(y,x,1)+2*x |
| 1562 | sage: f.diff('y') |
| 1563 | 34*y |
| 1564 | """ |
| 1565 | return ExpectElement.__getattr__(self, 'diff')(var, n) |
| 1566 | |
| 1567 | derivative = diff |
| 1568 | |
| 1569 | def nintegral(self, var='x', a=0, b=1, |
| 1570 | desired_relative_error='1e-8', |
| 1571 | maximum_num_subintervals=200): |
| 1572 | r""" |
| 1573 | Return a numerical approximation to the integral of self from a to |
| 1574 | b. |
| 1575 | |
| 1576 | INPUT: |
| 1577 | |
| 1578 | |
| 1579 | - ``var`` - variable to integrate with respect to |
| 1580 | |
| 1581 | - ``a`` - lower endpoint of integration |
| 1582 | |
| 1583 | - ``b`` - upper endpoint of integration |
| 1584 | |
| 1585 | - ``desired_relative_error`` - (default: '1e-8') the |
| 1586 | desired relative error |
| 1587 | |
| 1588 | - ``maximum_num_subintervals`` - (default: 200) |
| 1589 | maxima number of subintervals |
| 1590 | |
| 1591 | |
| 1592 | OUTPUT: |
| 1593 | |
| 1594 | |
| 1595 | - approximation to the integral |
| 1596 | |
| 1597 | - estimated absolute error of the |
| 1598 | approximation |
| 1599 | |
| 1600 | - the number of integrand evaluations |
| 1601 | |
| 1602 | - an error code: |
| 1603 | |
| 1604 | - ``0`` - no problems were encountered |
| 1605 | |
| 1606 | - ``1`` - too many subintervals were done |
| 1607 | |
| 1608 | - ``2`` - excessive roundoff error |
| 1609 | |
| 1610 | - ``3`` - extremely bad integrand behavior |
| 1611 | |
| 1612 | - ``4`` - failed to converge |
| 1613 | |
| 1614 | - ``5`` - integral is probably divergent or slowly convergent |
| 1615 | |
| 1616 | - ``6`` - the input is invalid |
| 1617 | |
| 1618 | |
| 1619 | EXAMPLES:: |
| 1620 | |
| 1621 | sage: maxima('exp(-sqrt(x))').nintegral('x',0,1) |
| 1622 | (.5284822353142306, 4.16331413788384...e-11, 231, 0) |
| 1623 | |
| 1624 | Note that GP also does numerical integration, and can do so to very |
| 1625 | high precision very quickly:: |
| 1626 | |
| 1627 | sage: gp('intnum(x=0,1,exp(-sqrt(x)))') |
| 1628 | 0.5284822353142307136179049194 # 32-bit |
| 1629 | 0.52848223531423071361790491935415653022 # 64-bit |
| 1630 | sage: _ = gp.set_precision(80) |
| 1631 | sage: gp('intnum(x=0,1,exp(-sqrt(x)))') |
| 1632 | 0.52848223531423071361790491935415653021675547587292866196865279321015401702040079 |
| 1633 | """ |
| 1634 | from sage.rings.all import Integer |
| 1635 | v = self.quad_qags(var, a, b, epsrel=desired_relative_error, |
| 1636 | limit=maximum_num_subintervals) |
| 1637 | return v[0], v[1], Integer(v[2]), Integer(v[3]) |
| 1638 | |
| 1639 | def integral(self, var='x', min=None, max=None): |
| 1640 | r""" |
| 1641 | Return the integral of self with respect to the variable x. |
| 1642 | |
| 1643 | INPUT: |
| 1644 | |
| 1645 | |
| 1646 | - ``var`` - variable |
| 1647 | |
| 1648 | - ``min`` - default: None |
| 1649 | |
| 1650 | - ``max`` - default: None |
| 1651 | |
| 1652 | |
| 1653 | Returns the definite integral if xmin is not None, otherwise |
| 1654 | returns an indefinite integral. |
| 1655 | |
| 1656 | EXAMPLES:: |
| 1657 | |
| 1658 | sage: maxima('x^2+1').integral() |
| 1659 | x^3/3+x |
| 1660 | sage: maxima('x^2+ 1 + y^2').integral('y') |
| 1661 | y^3/3+x^2*y+y |
| 1662 | sage: maxima('x / (x^2+1)').integral() |
| 1663 | log(x^2+1)/2 |
| 1664 | sage: maxima('1/(x^2+1)').integral() |
| 1665 | atan(x) |
| 1666 | sage: maxima('1/(x^2+1)').integral('x', 0, infinity) |
| 1667 | %pi/2 |
| 1668 | sage: maxima('x/(x^2+1)').integral('x', -1, 1) |
| 1669 | 0 |
| 1670 | |
| 1671 | :: |
| 1672 | |
| 1673 | sage: f = maxima('exp(x^2)').integral('x',0,1); f |
| 1674 | -sqrt(%pi)*%i*erf(%i)/2 |
| 1675 | sage: f.numer() |
| 1676 | 1.46265174590718... |
| 1677 | """ |
| 1678 | I = ExpectElement.__getattr__(self, 'integrate') |
| 1679 | if min is None: |
| 1680 | return I(var) |
| 1681 | else: |
| 1682 | if max is None: |
| 1683 | raise ValueError, "neither or both of min/max must be specified." |
| 1684 | return I(var, min, max) |
| 1685 | |
| 1686 | integrate = integral |
| 1687 | |
| 1688 | def __float__(self): |
| 1689 | """ |
| 1690 | Return floating point version of this maxima element. |
| 1691 | |
| 1692 | EXAMPLES:: |
| 1693 | |
| 1694 | sage: float(maxima("3.14")) |
| 1695 | 3.1400000000000001 |
| 1696 | sage: float(maxima("1.7e+17")) |
| 1697 | 1.7e+17 |
| 1698 | sage: float(maxima("1.7e-17")) |
| 1699 | 1.6999999999999999e-17 |
| 1700 | """ |
| 1701 | try: |
| 1702 | return float(repr(self.numer())) |
| 1703 | except ValueError: |
| 1704 | raise TypeError, "unable to coerce '%s' to float"%repr(self) |
| 1705 | |
| 1706 | def __len__(self): |
| 1707 | """ |
| 1708 | Return the length of a list. |
| 1709 | |
| 1710 | EXAMPLES:: |
| 1711 | |
| 1712 | sage: v = maxima('create_list(x^i,i,0,5)') |
| 1713 | sage: len(v) |
| 1714 | 6 |
| 1715 | """ |
| 1716 | P = self._check_valid() |
| 1717 | return int(P.eval('length(%s)'%self.name())) |
| 1718 | |
| 1719 | def dot(self, other): |
| 1720 | """ |
| 1721 | Implements the notation self . other. |
| 1722 | |
| 1723 | EXAMPLES:: |
| 1724 | |
| 1725 | sage: A = maxima('matrix ([a1],[a2])') |
| 1726 | sage: B = maxima('matrix ([b1, b2])') |
| 1727 | sage: A.dot(B) |
| 1728 | matrix([a1*b1,a1*b2],[a2*b1,a2*b2]) |
| 1729 | """ |
| 1730 | P = self._check_valid() |
| 1731 | Q = P(other) |
| 1732 | return P('%s . %s'%(self.name(), Q.name())) |
| 1733 | |
| 1734 | def __getitem__(self, n): |
| 1735 | r""" |
| 1736 | Return the n-th element of this list. |
| 1737 | |
| 1738 | .. note:: |
| 1739 | |
| 1740 | Lists are 0-based when accessed via the Sage interface, not |
| 1741 | 1-based as they are in the Maxima interpreter. |
| 1742 | |
| 1743 | EXAMPLES:: |
| 1744 | |
| 1745 | sage: v = maxima('create_list(i*x^i,i,0,5)'); v |
| 1746 | [0,x,2*x^2,3*x^3,4*x^4,5*x^5] |
| 1747 | sage: v[3] |
| 1748 | 3*x^3 |
| 1749 | sage: v[0] |
| 1750 | 0 |
| 1751 | sage: v[10] |
| 1752 | Traceback (most recent call last): |
| 1753 | ... |
| 1754 | IndexError: n = (10) must be between 0 and 5 |
| 1755 | """ |
| 1756 | n = int(n) |
| 1757 | if n < 0 or n >= len(self): |
| 1758 | raise IndexError, "n = (%s) must be between %s and %s"%(n, 0, len(self)-1) |
| 1759 | # If you change the n+1 to n below, better change __iter__ as well. |
| 1760 | return ExpectElement.__getitem__(self, n+1) |
| 1761 | |
| 1762 | def __iter__(self): |
| 1763 | """ |
| 1764 | EXAMPLE:: |
| 1765 | |
| 1766 | sage: v = maxima('create_list(i*x^i,i,0,5)') |
| 1767 | sage: L = list(v) |
| 1768 | sage: [e._sage_() for e in L] |
| 1769 | [0, x, 2*x^2, 3*x^3, 4*x^4, 5*x^5] |
| 1770 | """ |
| 1771 | for i in range(len(self)): |
| 1772 | yield self[i] |
| 1773 | |
| 1774 | def subst(self, val): |
| 1775 | """ |
| 1776 | Substitute a value or several values into this Maxima object. |
| 1777 | |
| 1778 | EXAMPLES:: |
| 1779 | |
| 1780 | sage: maxima('a^2 + 3*a + b').subst('b=2') |
| 1781 | a^2+3*a+2 |
| 1782 | sage: maxima('a^2 + 3*a + b').subst('a=17') |
| 1783 | b+340 |
| 1784 | sage: maxima('a^2 + 3*a + b').subst('a=17, b=2') |
| 1785 | 342 |
| 1786 | """ |
| 1787 | return self.comma(val) |
| 1788 | |
| 1789 | def comma(self, args): |
| 1790 | """ |
| 1791 | Form the expression that would be written 'self, args' in Maxima. |
| 1792 | |
| 1793 | EXAMPLES:: |
| 1794 | |
| 1795 | sage: maxima('sqrt(2) + I').comma('numer') |
| 1796 | I+1.41421356237309... |
| 1797 | sage: maxima('sqrt(2) + I*a').comma('a=5') |
| 1798 | 5*I+sqrt(2) |
| 1799 | """ |
| 1800 | self._check_valid() |
| 1801 | P = self.parent() |
| 1802 | return P('%s, %s'%(self.name(), args)) |
| 1803 | |
| 1804 | def _latex_(self): |
| 1805 | """ |
| 1806 | Return Latex representation of this Maxima object. |
| 1807 | |
| 1808 | This calls the tex command in Maxima, then does a little |
| 1809 | post-processing to fix bugs in the resulting Maxima output. |
| 1810 | |
| 1811 | EXAMPLES:: |
| 1812 | |
| 1813 | sage: maxima('sqrt(2) + 1/3 + asin(5)')._latex_() |
| 1814 | '\\sin^{-1}\\cdot5+\\sqrt{2}+{{1}\\over{3}}' |
| 1815 | |
| 1816 | sage: y,d = var('y,d') |
| 1817 | sage: f = function('f') |
| 1818 | sage: latex(maxima(derivative(f(x*y*d), d,x,x,y))) |
| 1819 | Traceback (most recent call last): |
| 1820 | ... |
| 1821 | NotImplementedError: arguments must be distinct variables |
| 1822 | sage: latex(maxima(derivative(f(x,y,d), d,x,x,y))) |
| 1823 | {{{\it \partial}^4}\over{{\it \partial}\,d\,{\it \partial}\,x^2\, {\it \partial}\,y}}\,f\left(x , y , d\right) |
| 1824 | |
| 1825 | sage: latex(maxima(d/(d-2))) |
| 1826 | {{d}\over{d-2}} |
| 1827 | """ |
| 1828 | self._check_valid() |
| 1829 | P = self.parent() |
| 1830 | s = P._eval_line('tex(%s);'%self.name(), reformat=False) |
| 1831 | if not '$$' in s: |
| 1832 | raise RuntimeError, "Error texing maxima object." |
| 1833 | i = s.find('$$') |
| 1834 | j = s.rfind('$$') |
| 1835 | s = s[i+2:j] |
| 1836 | s = multiple_replace({'\r\n':' ', |
| 1837 | '\\%':'', |
| 1838 | '\\arcsin ':'\\sin^{-1} ', |
| 1839 | '\\arccos ':'\\cos^{-1} ', |
| 1840 | '\\arctan ':'\\tan^{-1} '}, s) |
| 1841 | |
| 1842 | # Fix a maxima bug, which gives a latex representation of multiplying |
| 1843 | # two numbers as a single space. This was really bad when 2*17^(1/3) |
| 1844 | # gets TeXed as '2 17^{\frac{1}{3}}' |
| 1845 | # |
| 1846 | # This regex matches a string of spaces preceded by either a '}', a |
| 1847 | # decimal digit, or a ')', and followed by a decimal digit. The spaces |
| 1848 | # get replaced by a '\cdot'. |
| 1849 | s = re.sub(r'(?<=[})\d]) +(?=\d)', '\cdot', s) |
| 1850 | |
| 1851 | return s |
| 1852 | |
| 1853 | def trait_names(self, verbose=False): |
| 1854 | """ |
| 1855 | Return all Maxima commands, which is useful for tab completion. |
| 1856 | |
| 1857 | EXAMPLES:: |
| 1858 | |
| 1859 | sage: m = maxima(2) |
| 1860 | sage: 'gcd' in m.trait_names() |
| 1861 | True |
| 1862 | """ |
| 1863 | return self.parent().trait_names(verbose=False) |
| 1864 | |
| 1865 | def _matrix_(self, R): |
| 1866 | r""" |
| 1867 | If self is a Maxima matrix, return the corresponding Sage matrix |
| 1868 | over the Sage ring `R`. |
| 1869 | |
| 1870 | This may or may not work depending in how complicated the entries |
| 1871 | of self are! It only works if the entries of self can be coerced as |
| 1872 | strings to produce meaningful elements of `R`. |
| 1873 | |
| 1874 | EXAMPLES:: |
| 1875 | |
| 1876 | sage: _ = maxima.eval("f[i,j] := i/j") |
| 1877 | sage: A = maxima('genmatrix(f,4,4)'); A |
| 1878 | 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]) |
| 1879 | sage: A._matrix_(QQ) |
| 1880 | [ 1 1/2 1/3 1/4] |
| 1881 | [ 2 1 2/3 1/2] |
| 1882 | [ 3 3/2 1 3/4] |
| 1883 | [ 4 2 4/3 1] |
| 1884 | |
| 1885 | You can also use the ``matrix`` command (which is |
| 1886 | defined in ``sage.misc.functional``):: |
| 1887 | |
| 1888 | sage: matrix(QQ, A) |
| 1889 | [ 1 1/2 1/3 1/4] |
| 1890 | [ 2 1 2/3 1/2] |
| 1891 | [ 3 3/2 1 3/4] |
| 1892 | [ 4 2 4/3 1] |
| 1893 | """ |
| 1894 | from sage.matrix.all import MatrixSpace |
| 1895 | self._check_valid() |
| 1896 | P = self.parent() |
| 1897 | nrows = int(P.eval('length(%s)'%self.name())) |
| 1898 | if nrows == 0: |
| 1899 | return MatrixSpace(R, 0, 0)(0) |
| 1900 | ncols = int(P.eval('length(%s[1])'%self.name())) |
| 1901 | M = MatrixSpace(R, nrows, ncols) |
| 1902 | s = self.str().replace('matrix','').replace(',',"','").\ |
| 1903 | replace("]','[","','").replace('([',"['").replace('])',"']") |
| 1904 | s = eval(s) |
| 1905 | return M([R(x) for x in s]) |
| 1906 | |
| 1907 | def partial_fraction_decomposition(self, var='x'): |
| 1908 | """ |
| 1909 | Return the partial fraction decomposition of self with respect to |
| 1910 | the variable var. |
| 1911 | |
| 1912 | EXAMPLES:: |
| 1913 | |
| 1914 | sage: f = maxima('1/((1+x)*(x-1))') |
| 1915 | sage: f.partial_fraction_decomposition('x') |
| 1916 | 1/(2*(x-1))-1/(2*(x+1)) |
| 1917 | sage: print f.partial_fraction_decomposition('x') |
| 1918 | 1 1 |
| 1919 | --------- - --------- |
| 1920 | 2 (x - 1) 2 (x + 1) |
| 1921 | """ |
| 1922 | return self.partfrac(var) |
| 1923 | |
| 1924 | def _operation(self, operation, right): |
| 1925 | r""" |
| 1926 | Note that right's parent should already be Maxima since this should |
| 1927 | be called after coercion has been performed. |
| 1928 | |
| 1929 | If right is a ``MaximaFunction``, then we convert |
| 1930 | ``self`` to a ``MaximaFunction`` that takes |
| 1931 | no arguments, and let the |
| 1932 | ``MaximaFunction._operation`` code handle everything |
| 1933 | from there. |
| 1934 | |
| 1935 | EXAMPLES:: |
| 1936 | |
| 1937 | sage: f = maxima.cos(x) |
| 1938 | sage: f._operation("+", f) |
| 1939 | 2*cos(x) |
| 1940 | """ |
| 1941 | P = self._check_valid() |
| 1942 | |
| 1943 | if isinstance(right, MaximaFunction): |
| 1944 | fself = P.function('', repr(self)) |
| 1945 | return fself._operation(operation, right) |
| 1946 | |
| 1947 | try: |
| 1948 | return P.new('%s %s %s'%(self._name, operation, right._name)) |
| 1949 | except Exception, msg: |
| 1950 | raise TypeError, msg |
| 1951 | |
| 1952 | |
| 1953 | |
| 1954 | class MaximaFunctionElement(FunctionElement): |
| 1955 | def _sage_doc_(self): |
| 1956 | """ |
| 1957 | EXAMPLES:: |
| 1958 | |
| 1959 | sage: m = maxima(4) |
| 1960 | sage: m.gcd._sage_doc_() |
| 1961 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 1962 | ... |
| 1963 | """ |
| 1964 | return self._obj.parent().help(self._name) |
| 1965 | |
| 1966 | class MaximaExpectFunction(ExpectFunction): |
| 1967 | def _sage_doc_(self): |
| 1968 | """ |
| 1969 | EXAMPLES:: |
| 1970 | |
| 1971 | sage: maxima.gcd._sage_doc_() |
| 1972 | -- Function: gcd (<p_1>, <p_2>, <x_1>, ...) |
| 1973 | ... |
| 1974 | """ |
| 1975 | M = self._parent |
| 1976 | return M.help(self._name) |
| 1977 | |
| 1978 | |
| 1979 | class MaximaFunction(MaximaElement): |
| 1980 | def __init__(self, parent, name, defn, args, latex): |
| 1981 | """ |
| 1982 | EXAMPLES:: |
| 1983 | |
| 1984 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1985 | sage: f == loads(dumps(f)) |
| 1986 | True |
| 1987 | """ |
| 1988 | MaximaElement.__init__(self, parent, name, is_name=True) |
| 1989 | self.__defn = defn |
| 1990 | self.__args = args |
| 1991 | self.__latex = latex |
| 1992 | |
| 1993 | def __reduce__(self): |
| 1994 | """ |
| 1995 | EXAMPLES:: |
| 1996 | |
| 1997 | sage: f = maxima.function('x,y','sin(x+y)') |
| 1998 | sage: f.__reduce__() |
| 1999 | (<function reduce_load_Maxima_function at 0x...>, |
| 2000 | (Maxima, 'sin(x+y)', 'x,y', None)) |
| 2001 | """ |
| 2002 | return reduce_load_Maxima_function, (self.parent(), self.__defn, self.__args, self.__latex) |
| 2003 | |
| 2004 | def __call__(self, *x): |
| 2005 | """ |
| 2006 | EXAMPLES:: |
| 2007 | |
| 2008 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2009 | sage: f(1,2) |
| 2010 | sin(3) |
| 2011 | sage: f(x,x) |
| 2012 | sin(2*x) |
| 2013 | """ |
| 2014 | P = self._check_valid() |
| 2015 | if len(x) == 1: |
| 2016 | x = '(%s)'%x |
| 2017 | return P('%s%s'%(self.name(), x)) |
| 2018 | |
| 2019 | def __repr__(self): |
| 2020 | """ |
| 2021 | EXAMPLES:: |
| 2022 | |
| 2023 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2024 | sage: repr(f) |
| 2025 | 'sin(x+y)' |
| 2026 | """ |
| 2027 | return self.definition() |
| 2028 | |
| 2029 | def _latex_(self): |
| 2030 | """ |
| 2031 | EXAMPLES:: |
| 2032 | |
| 2033 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2034 | sage: latex(f) |
| 2035 | \mathrm{sin(x+y)} |
| 2036 | """ |
| 2037 | if self.__latex is None: |
| 2038 | return r'\mathrm{%s}'%self.__defn |
| 2039 | else: |
| 2040 | return self.__latex |
| 2041 | |
| 2042 | def arguments(self, split=True): |
| 2043 | r""" |
| 2044 | Returns the arguments of this Maxima function. |
| 2045 | |
| 2046 | EXAMPLES:: |
| 2047 | |
| 2048 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2049 | sage: f.arguments() |
| 2050 | ['x', 'y'] |
| 2051 | sage: f.arguments(split=False) |
| 2052 | 'x,y' |
| 2053 | sage: f = maxima.function('', 'sin(x)') |
| 2054 | sage: f.arguments() |
| 2055 | [] |
| 2056 | """ |
| 2057 | if split: |
| 2058 | return self.__args.split(',') if self.__args != '' else [] |
| 2059 | else: |
| 2060 | return self.__args |
| 2061 | |
| 2062 | def definition(self): |
| 2063 | """ |
| 2064 | Returns the definition of this Maxima function as a string. |
| 2065 | |
| 2066 | EXAMPLES:: |
| 2067 | |
| 2068 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2069 | sage: f.definition() |
| 2070 | 'sin(x+y)' |
| 2071 | """ |
| 2072 | return self.__defn |
| 2073 | |
| 2074 | def integral(self, var): |
| 2075 | """ |
| 2076 | Returns the integral of self with respect to the variable var. |
| 2077 | |
| 2078 | Note that integrate is an alias of integral. |
| 2079 | |
| 2080 | EXAMPLES:: |
| 2081 | |
| 2082 | sage: x,y = var('x,y') |
| 2083 | sage: f = maxima.function('x','sin(x)') |
| 2084 | sage: f.integral(x) |
| 2085 | -cos(x) |
| 2086 | sage: f.integral(y) |
| 2087 | sin(x)*y |
| 2088 | """ |
| 2089 | var = str(var) |
| 2090 | P = self._check_valid() |
| 2091 | f = P('integrate(%s(%s), %s)'%(self.name(), self.arguments(split=False), var)) |
| 2092 | |
| 2093 | args = self.arguments() |
| 2094 | if var not in args: |
| 2095 | args.append(var) |
| 2096 | return P.function(",".join(args), repr(f)) |
| 2097 | |
| 2098 | integrate = integral |
| 2099 | |
| 2100 | def _operation(self, operation, f=None): |
| 2101 | r""" |
| 2102 | This is a utility function which factors out much of the |
| 2103 | commonality used in the arithmetic operations for |
| 2104 | ``MaximaFunctions``. |
| 2105 | |
| 2106 | INPUT: |
| 2107 | |
| 2108 | |
| 2109 | - ``operation`` - A string representing the operation |
| 2110 | being performed. For example, '\*', or '1/'. |
| 2111 | |
| 2112 | - ``f`` - The other operand. If f is |
| 2113 | ``None``, than the operation is assumed to be unary |
| 2114 | rather than binary. |
| 2115 | |
| 2116 | |
| 2117 | EXAMPLES:: |
| 2118 | |
| 2119 | sage: f = maxima.function('x,y','sin(x+y)') |
| 2120 | sage: f._operation("+", f) |
| 2121 | 2*sin(y+x) |
| 2122 | sage: f._operation("+", 2) |
| 2123 | sin(y+x)+2 |
| 2124 | sage: f._operation('-') |
| 2125 | -sin(y+x) |
| 2126 | sage: f._operation('1/') |
| 2127 | 1/sin(y+x) |
| 2128 | """ |
| 2129 | P = self._check_valid() |
| 2130 | if isinstance(f, MaximaFunction): |
| 2131 | tmp = list(sorted(set(self.arguments() + f.arguments()))) |
| 2132 | args = ','.join(tmp) |
| 2133 | defn = "(%s)%s(%s)"%(self.definition(), operation, f.definition()) |
| 2134 | elif f is None: |
| 2135 | args = self.arguments(split=False) |
| 2136 | defn = "%s(%s)"%(operation, self.definition()) |
| 2137 | else: |
| 2138 | args = self.arguments(split=False) |
| 2139 | defn = "(%s)%s(%s)"%(self.definition(), operation, repr(f)) |
| 2140 | |
| 2141 | return P.function(args,P.eval(defn)) |
| 2142 | |
| 2143 | def _add_(self, f): |
| 2144 | """ |
| 2145 | MaximaFunction as left summand. |
| 2146 | |
| 2147 | EXAMPLES:: |
| 2148 | |
| 2149 | sage: x,y = var('x,y') |
| 2150 | sage: f = maxima.function('x','sin(x)') |
| 2151 | sage: g = maxima.function('x','-cos(x)') |
| 2152 | sage: f+g |
| 2153 | sin(x)-cos(x) |
| 2154 | sage: f+3 |
| 2155 | sin(x)+3 |
| 2156 | |
| 2157 | :: |
| 2158 | |
| 2159 | sage: (f+maxima.cos(x))(2) |
| 2160 | sin(2)+cos(2) |
| 2161 | sage: (f+maxima.cos(y)) # This is a function with only ONE argument! |
| 2162 | cos(y)+sin(x) |
| 2163 | sage: (f+maxima.cos(y))(2) |
| 2164 | cos(y)+sin(2) |
| 2165 | |
| 2166 | :: |
| 2167 | |
| 2168 | sage: f = maxima.function('x','sin(x)') |
| 2169 | sage: g = -maxima.cos(x) |
| 2170 | sage: g+f |
| 2171 | sin(x)-cos(x) |
| 2172 | sage: (g+f)(2) # The sum IS a function |
| 2173 | sin(2)-cos(2) |
| 2174 | sage: 2+f |
| 2175 | sin(x)+2 |
| 2176 | """ |
| 2177 | return self._operation("+", f) |
| 2178 | |
| 2179 | def _sub_(self, f): |
| 2180 | r""" |
| 2181 | ``MaximaFunction`` as minuend. |
| 2182 | |
| 2183 | EXAMPLES:: |
| 2184 | |
| 2185 | sage: x,y = var('x,y') |
| 2186 | sage: f = maxima.function('x','sin(x)') |
| 2187 | sage: g = -maxima.cos(x) # not a function |
| 2188 | sage: f-g |
| 2189 | sin(x)+cos(x) |
| 2190 | sage: (f-g)(2) |
| 2191 | sin(2)+cos(2) |
| 2192 | sage: (f-maxima.cos(y)) # This function only has the argument x! |
| 2193 | sin(x)-cos(y) |
| 2194 | sage: _(2) |
| 2195 | sin(2)-cos(y) |
| 2196 | |
| 2197 | :: |
| 2198 | |
| 2199 | sage: g-f |
| 2200 | -sin(x)-cos(x) |
| 2201 | """ |
| 2202 | return self._operation("-", f) |
| 2203 | |
| 2204 | def _mul_(self, f): |
| 2205 | r""" |
| 2206 | ``MaximaFunction`` as left factor. |
| 2207 | |
| 2208 | EXAMPLES:: |
| 2209 | |
| 2210 | sage: f = maxima.function('x','sin(x)') |
| 2211 | sage: g = maxima('-cos(x)') # not a function! |
| 2212 | sage: f*g |
| 2213 | -cos(x)*sin(x) |
| 2214 | sage: _(2) |
| 2215 | -cos(2)*sin(2) |
| 2216 | |
| 2217 | :: |
| 2218 | |
| 2219 | sage: f = maxima.function('x','sin(x)') |
| 2220 | sage: g = maxima('-cos(x)') |
| 2221 | sage: g*f |
| 2222 | -cos(x)*sin(x) |
| 2223 | sage: _(2) |
| 2224 | -cos(2)*sin(2) |
| 2225 | sage: 2*f |
| 2226 | 2*sin(x) |
| 2227 | """ |
| 2228 | return self._operation("*", f) |
| 2229 | |
| 2230 | def _div_(self, f): |
| 2231 | r""" |
| 2232 | ``MaximaFunction`` as dividend. |
| 2233 | |
| 2234 | EXAMPLES:: |
| 2235 | |
| 2236 | sage: f=maxima.function('x','sin(x)') |
| 2237 | sage: g=maxima('-cos(x)') |
| 2238 | sage: f/g |
| 2239 | -sin(x)/cos(x) |
| 2240 | sage: _(2) |
| 2241 | -sin(2)/cos(2) |
| 2242 | |
| 2243 | :: |
| 2244 | |
| 2245 | sage: f=maxima.function('x','sin(x)') |
| 2246 | sage: g=maxima('-cos(x)') |
| 2247 | sage: g/f |
| 2248 | -cos(x)/sin(x) |
| 2249 | sage: _(2) |
| 2250 | -cos(2)/sin(2) |
| 2251 | sage: 2/f |
| 2252 | 2/sin(x) |
| 2253 | """ |
| 2254 | return self._operation("/", f) |
| 2255 | |
| 2256 | def __neg__(self): |
| 2257 | r""" |
| 2258 | Additive inverse of a ``MaximaFunction``. |
| 2259 | |
| 2260 | EXAMPLES:: |
| 2261 | |
| 2262 | sage: f=maxima.function('x','sin(x)') |
| 2263 | sage: -f |
| 2264 | -sin(x) |
| 2265 | """ |
| 2266 | return self._operation('-') |
| 2267 | |
| 2268 | def __inv__(self): |
| 2269 | r""" |
| 2270 | Multiplicative inverse of a ``MaximaFunction``. |
| 2271 | |
| 2272 | EXAMPLES:: |
| 2273 | |
| 2274 | sage: f = maxima.function('x','sin(x)') |
| 2275 | sage: ~f |
| 2276 | 1/sin(x) |
| 2277 | """ |
| 2278 | return self._operation('1/') |
| 2279 | |
| 2280 | def __pow__(self,f): |
| 2281 | r""" |
| 2282 | ``MaximaFunction`` raised to some power. |
| 2283 | |
| 2284 | EXAMPLES:: |
| 2285 | |
| 2286 | sage: f=maxima.function('x','sin(x)') |
| 2287 | sage: g=maxima('-cos(x)') |
| 2288 | sage: f^g |
| 2289 | 1/sin(x)^cos(x) |
| 2290 | |
| 2291 | :: |
| 2292 | |
| 2293 | sage: f=maxima.function('x','sin(x)') |
| 2294 | sage: g=maxima('-cos(x)') # not a function |
| 2295 | sage: g^f |
| 2296 | (-cos(x))^sin(x) |
| 2297 | """ |
| 2298 | return self._operation("^", f) |
| 2299 | |
| 2300 | |
| 2301 | def reduce_load_Maxima_function(parent, defn, args, latex): |
| 2302 | return parent.function(args, defn, defn, latex) |
| 2303 | |
| 2304 | |
| 2305 | import os |
| 2306 | def maxima_console(): |
| 2307 | """ |
| 2308 | Spawn a new Maxima command-line session. |
| 2309 | |
| 2310 | EXAMPLES:: |
| 2311 | |
| 2312 | sage: from sage.interfaces.maxima import maxima_console |
| 2313 | sage: maxima_console() # not tested |
| 2314 | Maxima 5.23.2 http://maxima.sourceforge.net |
| 2315 | ... |
| 2316 | """ |
| 2317 | os.system('maxima') |