/
maxima_lib.py
1678 lines (1334 loc) · 51.5 KB
/
maxima_lib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Library interface to Maxima
Maxima is a free GPL'd general purpose computer algebra system whose
development started in 1968 at MIT. It contains symbolic manipulation
algorithms, as well as implementations of special functions, including
elliptic functions and generalized hypergeometric functions. Moreover,
Maxima has implementations of many functions relating to the invariant
theory of the symmetric group `S_n`. (However, the commands for group
invariants, and the corresponding Maxima documentation, are in
French.) For many links to Maxima documentation, see
http://maxima.sourceforge.net/documentation.html.
AUTHORS:
- William Stein (2005-12): Initial version
- David Joyner: Improved documentation
- William Stein (2006-01-08): Fixed bug in parsing
- William Stein (2006-02-22): comparisons (following suggestion of
David Joyner)
- William Stein (2006-02-24): *greatly* improved robustness by adding
sequence numbers to IO bracketing in _eval_line
- Robert Bradshaw, Nils Bruin, Jean-Pierre Flori (2010,2011): Binary library
interface
For this interface, Maxima is loaded into ECL which is itself loaded
as a C library in Sage. Translations between Sage and Maxima objects
(which are nothing but wrappers to ECL objects) is made as much as possible
directly, but falls back to the string based conversion used by the
classical Maxima Pexpect interface in case no new implementation has been made.
This interface is the one used for calculus by Sage
and is accessible as `maxima_calculus`::
sage: maxima_calculus
Maxima_lib
Only one instance of this interface can be instantiated,
so the user should not try to instantiate another one,
which is anyway set to raise an error::
sage: from sage.interfaces.maxima_lib import MaximaLib
sage: MaximaLib()
Traceback (most recent call last):
...
RuntimeError: Maxima interface in library mode can only be instantiated once
"""
#*****************************************************************************
# Copyright (C) 2005 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
from sage.symbolic.ring import SR, var
from sage.libs.ecl import *
from maxima_abstract import (MaximaAbstract, MaximaAbstractFunction,
MaximaAbstractElement, MaximaAbstractFunctionElement,
MaximaAbstractElementFunction)
## We begin here by initializing Maxima in library mode
## i.e. loading it into ECL
ecl_eval("(setf *load-verbose* NIL)")
ecl_eval("(require 'maxima)")
ecl_eval("(in-package :maxima)")
ecl_eval("(setq $nolabels t))")
ecl_eval("(defvar *MAXIMA-LANG-SUBDIR* NIL)")
ecl_eval("(set-locale-subdir)")
ecl_eval("(set-pathnames)")
ecl_eval("(defun add-lineinfo (x) x)")
ecl_eval('(defun principal nil (cond ($noprincipal (diverg)) ((not pcprntd) (merror "Divergent Integral"))))')
ecl_eval("(remprop 'mfactorial 'grind)") # don't use ! for factorials (#11539)
ecl_eval("(setf $errormsg nil)")
# the following is a direct adaption of the definition of "retrieve"
# in the Maxima file macsys.lisp. This routine is normally responsible
# for displaying a question and returning the answer. We change it to
# throw an error in which the text of the question is included. We do
# this by running exactly the same code as in the original definition
# of "retrieve", but with *standard-output* redirected to a string.
ecl_eval(r"""
(defun retrieve (msg flag &aux (print? nil))
(declare (special msg flag print?))
(or (eq flag 'noprint) (setq print? t))
(error
(concatenate 'string "Maxima asks: "
(string-trim '(#\Newline)
(with-output-to-string (*standard-output*)
(cond ((not print?)
(setq print? t)
(princ *prompt-prefix*)
(princ *prompt-suffix*)
)
((null msg)
(princ *prompt-prefix*)
(princ *prompt-suffix*)
)
((atom msg)
(format t "~a~a~a" *prompt-prefix* msg *prompt-suffix*)
)
((eq flag t)
(princ *prompt-prefix*)
(mapc #'princ (cdr msg))
(princ *prompt-suffix*)
)
(t
(princ *prompt-prefix*)
(displa msg)
(princ *prompt-suffix*)
)
))))
)
)
""")
## Redirection of ECL and Maxima stdout to /dev/null
ecl_eval(r"""(defparameter *dev-null* (make-two-way-stream
(make-concatenated-stream) (make-broadcast-stream)))""")
ecl_eval("(setf original-standard-output *standard-output*)")
ecl_eval("(setf *standard-output* *dev-null*)")
#ecl_eval("(setf *error-output* *dev-null*)")
## Default options set in Maxima
# display2d -- no ascii art output
# keepfloat -- don't automatically convert floats to rationals
init_code = ['display2d : false', 'domain : complex', 'keepfloat : true',
'load(to_poly_solve)', 'load(simplify_sum)',
'load(abs_integrate)']
# Turn off the prompt labels, since computing them *very
# dramatically* slows down the maxima interpret after a while.
# See the function makelabel in suprv1.lisp.
# Many thanks to andrej.vodopivec@gmail.com and also
# Robert Dodier for figuring this out!
# See trac # 6818.
init_code.append('nolabels : true')
for l in init_code:
ecl_eval("#$%s$"%l)
## To get more debug information uncomment the next line
## should allow to do this through a method
#ecl_eval("(setf *standard-output* original-standard-output)")
## This is the main function (ECL object) used for evaluation
# This returns an EclObject
maxima_eval=ecl_eval("""
(defun maxima-eval( form )
(let ((result (catch 'macsyma-quit (cons 'maxima_eval (meval form)))))
;(princ (list "result=" result))
;(terpri)
;(princ (list "$error=" $error))
;(terpri)
(cond
((and (consp result) (eq (car result) 'maxima_eval)) (cdr result))
((eq result 'maxima-error)
(let ((the-jig (process-error-argl (cddr $error))))
(mapc #'set (car the-jig) (cadr the-jig))
(error (concatenate 'string
"Error executing code in Maxima: "
(with-output-to-string (stream)
(apply #'mformat stream (cadr $error)
(caddr the-jig)))))
))
(t
(let ((the-jig (process-error-argl (cddr $error))))
(mapc #'set (car the-jig) (cadr the-jig))
(error (concatenate 'string "Maxima condition. result:"
(princ-to-string result) "$error:"
(with-output-to-string (stream)
(apply #'mformat stream (cadr $error)
(caddr the-jig)))))
))
)
)
)
""")
## Number of instances of this interface
maxima_lib_instances = 0
## Here we define several useful ECL/Maxima objects
# The Maxima string function can change the structure of its input
#maxprint=EclObject("$STRING")
maxprint=EclObject(r"""(defun mstring-for-sage (form)
(coerce (mstring form) 'string))""").eval()
meval=EclObject("MEVAL")
msetq=EclObject("MSETQ")
mlist=EclObject("MLIST")
mequal=EclObject("MEQUAL")
cadadr=EclObject("CADADR")
max_integrate=EclObject("$INTEGRATE")
max_sum=EclObject("$SUM")
max_simplify_sum=EclObject("$SIMPLIFY_SUM")
max_ratsimp=EclObject("$RATSIMP")
max_limit=EclObject("$LIMIT")
max_tlimit=EclObject("$TLIMIT")
max_plus=EclObject("$PLUS")
max_minus=EclObject("$MINUS")
max_use_grobner=EclObject("$USE_GROBNER")
max_to_poly_solve=EclObject("$TO_POLY_SOLVE")
max_at=EclObject("%AT")
def stdout_to_string(s):
r"""
Evaluate command ``s`` and catch Maxima stdout
(not the result of the command!) into a string.
INPUT:
- ``s`` - string; command to evaluate
OUTPUT: string
This is currently used to implement :meth:`~MaximaLibElement.display2d`.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import stdout_to_string
sage: stdout_to_string('1+1')
''
sage: stdout_to_string('disp(1+1)')
'2\n\n'
"""
return ecl_eval(r"""(with-output-to-string (*standard-output*)
(maxima-eval #$%s$))"""%s).python()[1:-1]
def max_to_string(s):
r"""
Return the Maxima string corresponding to this ECL object.
INPUT:
- ``s`` - ECL object
OUTPUT: string
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_string
sage: ecl = maxima_lib(cos(x)).ecl()
sage: max_to_string(ecl)
'cos(_SAGE_VAR_x)'
"""
return maxprint(s).python()[1:-1]
my_mread=ecl_eval("""
(defun my-mread (cmd)
(caddr (mread (make-string-input-stream cmd))))
""")
def parse_max_string(s):
r"""
Evaluate string in Maxima without *any* further simplification.
INPUT:
- ``s`` - string
OUTPUT: ECL object
EXAMPLES::
sage: from sage.interfaces.maxima_lib import parse_max_string
sage: parse_max_string('1+1')
<ECL: ((MPLUS) 1 1)>
"""
return my_mread('"%s;"'%s)
class MaximaLib(MaximaAbstract):
"""
Interface to Maxima as a Library.
INPUT: none
OUTPUT: Maxima interface as a Library
EXAMPLES::
sage: from sage.interfaces.maxima_lib import MaximaLib, maxima_lib
sage: isinstance(maxima_lib,MaximaLib)
True
Only one such interface can be instantiated::
sage: MaximaLib()
Traceback (most recent call last):
...
RuntimeError: Maxima interface in library mode can only
be instantiated once
"""
def __init__(self):
"""
Create an instance of the Maxima interpreter.
See ``MaximaLib`` for full documentation.
TESTS::
sage: from sage.interfaces.maxima_lib import MaximaLib, maxima_lib
sage: MaximaLib == loads(dumps(MaximaLib))
True
sage: maxima_lib == loads(dumps(maxima_lib))
True
We make sure labels are turned off (see :trac:`6816`)::
sage: 'nolabels : true' in maxima_lib._MaximaLib__init_code
True
"""
global maxima_lib_instances
if maxima_lib_instances > 0:
raise RuntimeError("Maxima interface in library mode can only be instantiated once")
maxima_lib_instances += 1
global init_code
self.__init_code = init_code
MaximaAbstract.__init__(self,"maxima_lib")
self.__seq = 0
def _coerce_from_special_method(self, x):
r"""
Coerce ``x`` into self trying to call a special underscore method.
INPUT:
- ``x`` - object to coerce into self
OUTPUT: Maxima element equivalent to ``x``
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: xmax = maxima_lib._coerce_from_special_method(x)
sage: type(xmax)
<class 'sage.interfaces.maxima_lib.MaximaLibElement'>
"""
if isinstance(x, EclObject):
return MaximaLibElement(self,self._create(x))
else:
return MaximaAbstract._coerce_from_special_method(self,x)
def __reduce__(self):
r"""
Implement __reduce__ for ``MaximaLib``.
INPUT: none
OUTPUT:
A couple consisting of:
- the function to call for unpickling
- a tuple of arguments for the function
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.__reduce__()
(<function reduce_load_MaximaLib at 0x...>, ())
"""
return reduce_load_MaximaLib, tuple([])
# This outputs a string
def _eval_line(self, line, locals=None, reformat=True, **kwds):
r"""
Evaluate the line in Maxima.
INPUT:
- ``line`` - string; text to evaluate
- ``locals`` - None (ignored); this is used for compatibility with the
Sage notebook's generic system interface.
- ``reformat`` - boolean; whether to strip output or not
- ``**kwds`` - All other arguments are currently ignored.
OUTPUT: string representing Maxima output
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._eval_line('1+1')
'2'
sage: maxima_lib._eval_line('1+1;')
'2'
sage: maxima_lib._eval_line('1+1$')
''
sage: maxima_lib._eval_line('randvar : cos(x)+sin(y)$')
''
sage: maxima_lib._eval_line('randvar')
'sin(y)+cos(x)'
"""
result = ''
while line:
ind_dollar=line.find("$")
ind_semi=line.find(";")
if ind_dollar == -1 or (ind_semi >=0 and ind_dollar > ind_semi):
if ind_semi == -1:
statement = line
line = ''
else:
statement = line[:ind_semi]
line = line[ind_semi+1:]
if statement:
result = ((result + '\n') if result else '') + max_to_string(maxima_eval("#$%s$"%statement))
else:
statement = line[:ind_dollar]
line = line[ind_dollar+1:]
if statement:
_ = maxima_eval("#$%s$"%statement)
if not reformat:
return result
return ''.join([x.strip() for x in result.split()])
eval = _eval_line
###########################################
# Direct access to underlying lisp interpreter.
###########################################
def lisp(self, cmd):
"""
Send a lisp command to maxima.
INPUT:
- ``cmd`` - string
OUTPUT: ECL object
.. note::
The output of this command is very raw - not pretty.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.lisp("(+ 2 17)")
<ECL: 19>
"""
return ecl_eval(cmd)
def set(self, var, value):
"""
Set the variable var to the given value.
INPUT:
- ``var`` - string
- ``value`` - string
OUTPUT: none
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.set('xxxxx', '2')
sage: maxima_lib.get('xxxxx')
'2'
"""
if not isinstance(value, str):
raise TypeError
cmd = '%s : %s$'%(var, value.rstrip(';'))
self.eval(cmd)
def clear(self, var):
"""
Clear the variable named var.
INPUT:
- ``var`` - string
OUTPUT: none
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.set('xxxxx', '2')
sage: maxima_lib.get('xxxxx')
'2'
sage: maxima_lib.clear('xxxxx')
sage: maxima_lib.get('xxxxx')
'xxxxx'
"""
try:
self.eval('kill(%s)$'%var)
except (TypeError, AttributeError):
pass
def get(self, var):
"""
Get the string value of the variable ``var``.
INPUT:
- ``var`` - string
OUTPUT: string
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.set('xxxxx', '2')
sage: maxima_lib.get('xxxxx')
'2'
"""
s = self.eval('%s;'%var)
return s
def _create(self, value, name=None):
r"""
Create a variable with given value and name.
INPUT:
- ``value`` - string or ECL object
- ``name`` - string (default: None); name to use for the variable,
an automatically generated name is used if this is none
OUTPUT:
- string; the name of the created variable
EXAMPLES:
Creation from strings::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._create('3','var3')
'var3'
sage: maxima_lib.get('var3')
'3'
sage: s = maxima_lib._create('3')
sage: s # random output
'sage9'
sage: s[:4] == 'sage'
True
And from ECL object::
sage: c = maxima_lib(x+cos(19)).ecl()
sage: maxima_lib._create(c,'m')
'm'
sage: maxima_lib.get('m')
'_SAGE_VAR_x+cos(19)'
sage: maxima_lib.clear('m')
"""
name = self._next_var_name() if name is None else name
try:
if isinstance(value,EclObject):
maxima_eval([[msetq],cadadr("#$%s$#$"%name),value])
else:
self.set(name, value)
except RuntimeError as error:
s = str(error)
if "Is" in s: # Maxima asked for a condition
self._missing_assumption(s)
else:
raise
return name
def _function_class(self):
r"""
Return the Python class of Maxima functions.
INPUT: none
OUTPUT: type
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._function_class()
<class 'sage.interfaces.maxima_lib.MaximaLibFunction'>
"""
return MaximaLibFunction
def _object_class(self):
r"""
Return the Python class of Maxima elements.
INPUT: none
OUTPUT: type
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._object_class()
<class 'sage.interfaces.maxima_lib.MaximaLibElement'>
"""
return MaximaLibElement
def _function_element_class(self):
r"""
Return the Python class of Maxima functions of elements.
INPUT: none
OUTPUT: type
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._function_element_class()
<class 'sage.interfaces.maxima_lib.MaximaLibFunctionElement'>
"""
return MaximaLibFunctionElement
def _object_function_class(self):
r"""
Return the Python class of Maxima user-defined functions.
INPUT: none
OUTPUT: type
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._object_function_class()
<class 'sage.interfaces.maxima_lib.MaximaLibElementFunction'>
"""
return MaximaLibElementFunction
## some helper functions to wrap the calculus use of the maxima interface.
## these routines expect arguments living in the symbolic ring
## and return something that is hopefully coercible into the symbolic
## ring again.
def sr_integral(self,*args):
"""
Helper function to wrap calculus use of Maxima's integration.
TESTS::
sage: a,b=var('a,b')
sage: integrate(1/(x^3 *(a+b*x)^(1/3)),x)
Traceback (most recent call last):
...
ValueError: Computation failed since Maxima requested additional
constraints; using the 'assume' command before evaluation
*may* help (example of legal syntax is 'assume(a>0)', see
`assume?` for more details)
Is a positive or negative?
sage: assume(a>0)
sage: integrate(1/(x^3 *(a+b*x)^(1/3)),x)
2/9*sqrt(3)*b^2*arctan(1/3*sqrt(3)*(2*(b*x + a)^(1/3) + a^(1/3))/a^(1/3))/a^(7/3) - 1/9*b^2*log((b*x + a)^(2/3) + (b*x + a)^(1/3)*a^(1/3) + a^(2/3))/a^(7/3) + 2/9*b^2*log((b*x + a)^(1/3) - a^(1/3))/a^(7/3) + 1/6*(4*(b*x + a)^(5/3)*b^2 - 7*(b*x + a)^(2/3)*a*b^2)/((b*x + a)^2*a^2 - 2*(b*x + a)*a^3 + a^4)
sage: var('x, n')
(x, n)
sage: integral(x^n,x)
Traceback (most recent call last):
...
ValueError: Computation failed since Maxima requested additional
constraints; using the 'assume' command before evaluation
*may* help (example of legal syntax is 'assume(n>0)',
see `assume?` for more details)
Is n equal to -1?
sage: assume(n+1>0)
sage: integral(x^n,x)
x^(n + 1)/(n + 1)
sage: forget()
sage: assumptions() # Check the assumptions really were forgotten
[]
Make sure the abs_integrate package is being used,
:trac:`11483`. The following are examples from the Maxima
abs_integrate documentation::
sage: integrate(abs(x), x)
1/2*x*abs(x)
::
sage: integrate(sgn(x) - sgn(1-x), x)
abs(x - 1) + abs(x)
::
sage: integrate(1 / (1 + abs(x-5)), x, -5, 6)
log(11) + log(2)
::
sage: integrate(1/(1 + abs(x)), x)
1/2*(log(x + 1) + log(-x + 1))*sgn(x) + 1/2*log(x + 1) - 1/2*log(-x + 1)
::
sage: integrate(cos(x + abs(x)), x)
-1/4*(2*x - sin(2*x))*real_part(sgn(x)) + 1/2*x + 1/4*sin(2*x)
Note that the last example yielded the same answer in a
simpler form in earlier versions of Maxima (<= 5.29.1), namely
``-1/2*x*sgn(x) + 1/4*(sgn(x) + 1)*sin(2*x) + 1/2*x``. This
is because Maxima no longer simplifies ``realpart(signum(x))``
to ``signum(x)``::
sage: maxima("realpart(signum(x))")
'realpart(signum(x))
An example from sage-support thread e641001f8b8d1129::
sage: f = e^(-x^2/2)/sqrt(2*pi) * sgn(x-1)
sage: integrate(f, x, -Infinity, Infinity)
-erf(1/2*sqrt(2))
From :trac:`8624`::
sage: integral(abs(cos(x))*sin(x),(x,pi/2,pi))
1/2
::
sage: integrate(sqrt(x + sqrt(x)), x).simplify_radical()
1/12*((8*x - 3)*x^(1/4) + 2*x^(3/4))*sqrt(sqrt(x) + 1) + 1/8*log(sqrt(sqrt(x) + 1) + x^(1/4)) - 1/8*log(sqrt(sqrt(x) + 1) - x^(1/4))
And :trac:`11594`::
sage: integrate(abs(x^2 - 1), x, -2, 2)
4
This definite integral returned zero (incorrectly) in at least
Maxima 5.23. The correct answer is now given (:trac:`11591`)::
sage: f = (x^2)*exp(x) / (1+exp(x))^2
sage: integrate(f, (x, -infinity, infinity))
1/3*pi^2
Sometimes one needs different simplification settings, such as
``radexpand``, to compute an integral (see :trac:`10955`)::
sage: f = sqrt(x + 1/x^2)
sage: maxima = sage.calculus.calculus.maxima
sage: maxima('radexpand')
true
sage: integrate(f, x)
integrate(sqrt(x + 1/x^2), x)
sage: maxima('radexpand: all')
all
sage: g = integrate(f, x); g
2/3*sqrt(x^3 + 1) - 1/3*log(sqrt(x^3 + 1) + 1) + 1/3*log(sqrt(x^3 + 1) - 1)
sage: (f - g.diff(x)).simplify_radical()
0
sage: maxima('radexpand: true')
true
The following integral was computed incorrectly in versions of
Maxima before 5.27 (see :trac:`12947`)::
sage: a = integrate(x*cos(x^3),(x,0,1/2)).n()
sage: a.real()
0.124756040961038
sage: a.imag().abs() < 3e-17
True
"""
try:
return max_to_sr(maxima_eval(([max_integrate],[sr_to_max(SR(a)) for a in args])))
except RuntimeError as error:
s = str(error)
if "Divergent" in s or "divergent" in s:
# in pexpect interface, one looks for this - e.g. integrate(1/x^3,x,-1,3) gives a principal value
# if "divergent" in s or 'Principal Value' in s:
raise ValueError("Integral is divergent.")
elif "Is" in s: # Maxima asked for a condition
self._missing_assumption(s)
else:
raise
def sr_sum(self,*args):
"""
Helper function to wrap calculus use of Maxima's summation.
TESTS:
Check that :trac:`16224` is fixed::
sage: k = var('k')
sage: sum(x^(2*k)/factorial(2*k), k, 0, oo).simplify_radical()
cosh(x)
::
sage: x, y, k, n = var('x, y, k, n')
sage: sum(binomial(n,k) * x^k * y^(n-k), k, 0, n)
(x + y)^n
sage: q, a = var('q, a')
sage: sum(a*q^k, k, 0, oo)
Traceback (most recent call last):
...
ValueError: Computation failed since Maxima requested additional
constraints; using the 'assume' command before evaluation *may* help
(example of legal syntax is 'assume(abs(q)-1>0)', see `assume?`
for more details)
Is abs(q)-1 positive, negative or zero?
sage: assume(q > 1)
sage: sum(a*q^k, k, 0, oo)
Traceback (most recent call last):
...
ValueError: Sum is divergent.
sage: forget()
sage: assume(abs(q) < 1)
sage: sum(a*q^k, k, 0, oo)
-a/(q - 1)
sage: forget()
sage: assumptions() # check the assumptions were really forgotten
[]
Taking the sum of all natural numbers informs us that the sum
is divergent. Maxima (before 5.29.1) used to ask questions
about `m`, leading to a different error (see :trac:`11990`)::
sage: m = var('m')
sage: sum(m, m, 0, infinity)
Traceback (most recent call last):
...
ValueError: Sum is divergent.
An error with an infinite sum in Maxima (before 5.30.0,
see :trac:`13712`)::
sage: n = var('n')
sage: sum(1/((2*n-1)^2*(2*n+1)^2*(2*n+3)^2), n, 0, oo)
3/256*pi^2
Maxima correctly detects division by zero in a symbolic sum
(see :trac:`11894`)::
sage: sum(1/(m^4 + 2*m^3 + 3*m^2 + 2*m)^2, m, 0, infinity)
Traceback (most recent call last):
...
RuntimeError: ECL says: Error executing code in Maxima: Zero to negative power computed.
Similar situation for :trac:`12410`::
sage: x = var('x')
sage: sum(1/x*(-1)^x, x, 0, oo)
Traceback (most recent call last):
...
RuntimeError: ECL says: Error executing code in Maxima: Zero to negative power computed.
"""
try:
return max_to_sr(maxima_eval([[max_ratsimp],[[max_simplify_sum],([max_sum],[sr_to_max(SR(a)) for a in args])]]));
except RuntimeError as error:
s = str(error)
if "divergent" in s:
# in pexpect interface, one looks for this;
# could not find an example where 'Pole encountered' occurred, though
# if "divergent" in s or 'Pole encountered' in s:
raise ValueError("Sum is divergent.")
elif "Is" in s: # Maxima asked for a condition
self._missing_assumption(s)
else:
raise
def sr_limit(self,expr,v,a,dir=None):
"""
Helper function to wrap calculus use of Maxima's limits.
TESTS::
sage: f = (1+1/x)^x
sage: limit(f,x = oo)
e
sage: limit(f,x = 5)
7776/3125
sage: limit(f,x = 1.2)
2.06961575467...
sage: var('a')
a
sage: limit(x^a,x=0)
Traceback (most recent call last):
...
ValueError: Computation failed since Maxima requested additional
constraints; using the 'assume' command before evaluation
*may* help (example of legal syntax is 'assume(a>0)', see `assume?`
for more details)
Is a positive, negative or zero?
sage: assume(a>0)
sage: limit(x^a,x=0)
Traceback (most recent call last):
...
ValueError: Computation failed ...
Is a an integer?
sage: assume(a,'integer')
sage: assume(a,'even') # Yes, Maxima will ask this too
sage: limit(x^a,x=0)
0
sage: forget()
sage: assumptions() # check the assumptions were really forgotten
[]
The second limit below was computed incorrectly prior to
Maxima 5.24 (:trac:`10868`)::
sage: f(n) = 2 + 1/factorial(n)
sage: limit(f(n), n=infinity)
2
sage: limit(1/f(n), n=infinity)
1/2
The limit below was computed incorrectly prior to Maxima 5.30
(see :trac:`13526`)::
sage: n = var('n')
sage: l = (3^n + (-2)^n) / (3^(n+1) + (-2)^(n+1))
sage: l.limit(n=oo)
1/3
"""
try:
L=[sr_to_max(SR(a)) for a in [expr,v,a]]
if dir == "plus":
L.append(max_plus)
elif dir == "minus":
L.append(max_minus)
return max_to_sr(maxima_eval(([max_limit],L)))
except RuntimeError as error:
s = str(error)
if "Is" in s: # Maxima asked for a condition
self._missing_assumption(s)
else:
raise
def sr_tlimit(self,expr,v,a,dir=None):
"""
Helper function to wrap calculus use of Maxima's Taylor series limits.
TESTS::
sage: f = (1+1/x)^x
sage: limit(f, x = I, taylor=True)
(-I + 1)^I
"""
L=[sr_to_max(SR(a)) for a in [expr,v,a]]
if dir == "plus":
L.append(max_plus)
elif dir == "minus":
L.append(max_minus)
return max_to_sr(maxima_eval(([max_tlimit],L)))
def _missing_assumption(self,errstr):
"""
Helper function for unified handling of failed computation because an
assumption was missing.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib._missing_assumption('Is xyz a thing?')
Traceback (most recent call last):
...
ValueError: Computation failed ...
Is xyz a thing?
"""
j = errstr.find('Is ')
errstr = errstr[j:]
jj = 2
if errstr[3] == ' ':
jj = 3
k = errstr.find(' ',jj+1)
outstr = "Computation failed since Maxima requested additional constraints; using the 'assume' command before evaluation *may* help (example of legal syntax is 'assume("\
+ errstr[jj+1:k] +">0)', see `assume?` for more details)\n" + errstr
outstr = outstr.replace('_SAGE_VAR_','')
raise ValueError(outstr)
def is_MaximaLibElement(x):
r"""
Returns True if x is of type MaximaLibElement.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib, is_MaximaLibElement
sage: m = maxima_lib(1)
sage: is_MaximaLibElement(m)
True
sage: is_MaximaLibElement(1)