This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
expression.pyx
12058 lines (9694 loc) · 380 KB
/
expression.pyx
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
# -*- coding: utf-8 -*-
"""
Symbolic Expressions
RELATIONAL EXPRESSIONS:
We create a relational expression::
sage: x = var('x')
sage: eqn = (x-1)^2 <= x^2 - 2*x + 3
sage: eqn.subs(x == 5)
16 <= 18
Notice that squaring the relation squares both sides.
::
sage: eqn^2
(x - 1)^4 <= (x^2 - 2*x + 3)^2
sage: eqn.expand()
x^2 - 2*x + 1 <= x^2 - 2*x + 3
This can transform a true relation into a false one::
sage: eqn = SR(-5) < SR(-3); eqn
-5 < -3
sage: bool(eqn)
True
sage: eqn^2
25 < 9
sage: bool(eqn^2)
False
We can do arithmetic with relations::
sage: e = x+1 <= x-2
sage: e + 2
x + 3 <= x
sage: e - 1
x <= x - 3
sage: e*(-1)
-x - 1 <= -x + 2
sage: (-2)*e
-2*x - 2 <= -2*x + 4
sage: e*5
5*x + 5 <= 5*x - 10
sage: e/5
1/5*x + 1/5 <= 1/5*x - 2/5
sage: 5/e
5/(x + 1) <= 5/(x - 2)
sage: e/(-2)
-1/2*x - 1/2 <= -1/2*x + 1
sage: -2/e
-2/(x + 1) <= -2/(x - 2)
We can even add together two relations, as long as the operators are
the same::
sage: (x^3 + x <= x - 17) + (-x <= x - 10)
x^3 <= 2*x - 27
Here they are not::
sage: (x^3 + x <= x - 17) + (-x >= x - 10)
Traceback (most recent call last):
...
TypeError: incompatible relations
ARBITRARY SAGE ELEMENTS:
You can work symbolically with any Sage data type. This can lead to
nonsense if the data type is strange, e.g., an element of a finite
field (at present).
We mix Singular variables with symbolic variables::
sage: R.<u,v> = QQ[]
sage: var('a,b,c')
(a, b, c)
sage: expand((u + v + a + b + c)^2)
a^2 + 2*a*b + b^2 + 2*a*c + 2*b*c + c^2 + 2*a*u + 2*b*u + 2*c*u + u^2 + 2*a*v + 2*b*v + 2*c*v + 2*u*v + v^2
TESTS:
Test Jacobian on Pynac expressions. (:trac:`5546`) ::
sage: var('x,y')
(x, y)
sage: f = x + y
sage: jacobian(f, [x,y])
[1 1]
Test if matrices work (:trac:`5546`) ::
sage: var('x,y,z')
(x, y, z)
sage: M = matrix(2,2,[x,y,z,x])
sage: v = vector([x,y])
sage: M * v
(x^2 + y^2, x*y + x*z)
sage: v*M
(x^2 + y*z, 2*x*y)
Test if comparison bugs from :trac:`6256` are fixed::
sage: t = exp(sqrt(x)); u = 1/t
sage: t*u
1
sage: t + u
e^(-sqrt(x)) + e^sqrt(x)
sage: t
e^sqrt(x)
Test if :trac:`9947` is fixed::
sage: real_part(1+2*(sqrt(2)+1)*(sqrt(2)-1))
3
sage: a=(sqrt(4*(sqrt(3) - 5)*(sqrt(3) + 5) + 48) + 4*sqrt(3))/ (sqrt(3) + 5)
sage: a.real_part()
4*sqrt(3)/(sqrt(3) + 5)
sage: a.imag_part()
2*sqrt(10)/(sqrt(3) + 5)
"""
#*****************************************************************************
# Copyright (C) 2008 William Stein <wstein@gmail.com>
# Copyright (C) 2008 Burcin Erocal <burcin@erocal.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function, absolute_import
include "cysignals/signals.pxi"
from inspect import ismethod
import operator
from . import ring
import sage.rings.integer
import sage.rings.rational
from cpython.object cimport Py_EQ, Py_NE, Py_LE, Py_GE, Py_LT, Py_GT
from sage.structure.element cimport ModuleElement, RingElement, Element
from sage.symbolic.comparison import mixed_order
from sage.symbolic.getitem cimport OperandsWrapper
from sage.symbolic.series cimport SymbolicSeries
from sage.symbolic.complexity_measures import string_length
from sage.symbolic.function import get_sfunction_from_serial, SymbolicFunction
cimport sage.symbolic.comparison
from sage.rings.rational import Rational # Used for sqrt.
from sage.misc.derivative import multi_derivative
from sage.misc.superseded import deprecated_function_alias
from sage.rings.infinity import AnInfinity, infinity, minus_infinity, unsigned_infinity
from sage.misc.decorators import rename_keyword
from sage.structure.dynamic_class import dynamic_class
from sage.symbolic.operators import FDerivativeOperator, add_vararg, mul_vararg
from sage.arith.numerical_approx cimport digits_to_bits
cpdef bint is_Expression(x):
"""
Return True if *x* is a symbolic Expression.
EXAMPLES::
sage: from sage.symbolic.expression import is_Expression
sage: is_Expression(x)
True
sage: is_Expression(2)
False
sage: is_Expression(SR(2))
True
"""
return isinstance(x, Expression)
cpdef bint is_SymbolicEquation(x):
"""
Return True if *x* is a symbolic equation.
EXAMPLES:
The following two examples are symbolic equations::
sage: from sage.symbolic.expression import is_SymbolicEquation
sage: is_SymbolicEquation(sin(x) == x)
True
sage: is_SymbolicEquation(sin(x) < x)
True
sage: is_SymbolicEquation(x)
False
This is not, since ``2==3`` evaluates to the boolean
``False``::
sage: is_SymbolicEquation(2 == 3)
False
However here since both 2 and 3 are coerced to be symbolic, we
obtain a symbolic equation::
sage: is_SymbolicEquation(SR(2) == SR(3))
True
"""
return isinstance(x, Expression) and is_a_relational((<Expression>x)._gobj)
def _dict_update_check_duplicate(dict d1, dict d2):
r"""
Merge the dictionary ``d2`` into ``d1`` and check for duplicates.
The two dictionaries must be of the form ``{expr: replacement}``. This
function throws a ``ValueError`` if any expressions are substituted
for twice.
EXAMPLES:
A normal merge with no conflicts::
sage: from sage.symbolic.expression import _dict_update_check_duplicate
sage: d1 = {'a': 1}
sage: d2 = {'b': 2}
sage: _dict_update_check_duplicate(d1, d2)
sage: d1 == {'a': 1, 'b': 2}
True
In this case, the variable ``a`` is substituted twice resulting in
an error::
sage: from sage.symbolic.expression import _dict_update_check_duplicate
sage: d1 = {'a': 1}
sage: d2 = {'a': 2}
sage: _dict_update_check_duplicate(d1, d2)
Traceback (most recent call last):
...
ValueError: duplicate substitution for a, got values 1 and 2
We report only the first conflict (according to the Python sort
order)::
sage: from sage.symbolic.expression import _dict_update_check_duplicate
sage: d1 = {'b': 1, 'a': 1}
sage: d2 = {'b': 2, 'a': 2}
sage: _dict_update_check_duplicate(d1, d2)
Traceback (most recent call last):
...
ValueError: duplicate substitution for a, got values 1 and 2
"""
# We need to check for duplicates in a predictable order so that
# errors are reported reliably. We only need to sort one of the
# dictionaries to achieve that, and we suspect that d2 will
# generally be smaller than d1, so we sort d2. This gives us a
# list of d2's keys.
#
# When sorting d2, we compare the string representations of its
# keys rather than the keys themselves. This is because comparison
# of symbolic expressions doesn't do what the sorted() function
# needs: `x <= y` is a symbolic inequality, and we need a
# True/False answer. The expression 'x' <= 'y' on the other hand
# is unambiguous.
#
for k in sorted(d2, key=str):
if k in d1:
msg = "duplicate substitution for {}, got values {} and {}"
raise ValueError(msg.format(k, d1[k], d2[k]))
d1.update(d2)
def _subs_make_dict(s):
r"""
There are a few ways we can represent a substitution. The first is
a symbolic equation. The second is a dictionary. The third would
be a list/tuple whose entries are expressions, dictionaries, or
lists/tuples themselves. This function converts all such
representations to dictionaries.
INPUT:
- ``s`` -- A representation of a substitution.
OUTPUT:
A dictionary of substitutions.
EXAMPLES:
An expression::
sage: from sage.symbolic.expression import _subs_make_dict
sage: _subs_make_dict(x == 1)
{x: 1}
And a dictionary (we just return it as-is)::
sage: _subs_make_dict({x: 1})
{x: 1}
And finally, a tuple or a list containing one of everything::
sage: w, x, y, z = SR.var('w, x, y, z')
sage: actual = _subs_make_dict([w == 1, {x: 1}, [y == 1], (z == 1,)])
sage: expected = {w: 1, y: 1, x: 1, z: 1}
sage: actual == expected
True
Note that it recursively calls itself so that the following does work::
sage: x, y, z = SR.var('x, y, z')
sage: actual = _subs_make_dict([[x == 1], [[y == 2], [z == 3]]])
sage: expected = {z: 3, y: 2, x: 1}
sage: actual == expected
True
Check that a ``TypeError`` is raised if the input is not valid::
sage: _subs_make_dict(1)
Traceback (most recent call last):
...
TypeError: not able to determine a substitution from 1
sage: _subs_make_dict(x)
Traceback (most recent call last):
...
TypeError: not able to determine a substitution from x
sage: _subs_make_dict(x <= 1)
Traceback (most recent call last):
...
TypeError: can only substitute equality, not inequalities; got x <= 1
"""
if isinstance(s, dict):
return s
elif is_SymbolicEquation(s):
if s.operator() is not operator.eq:
msg = "can only substitute equality, not inequalities; got {}"
raise TypeError(msg.format(s))
return {s.lhs(): s.rhs()}
elif isinstance(s, (tuple,list)):
result = {}
for d in s:
_dict_update_check_duplicate(result, _subs_make_dict(d))
return result
else:
msg = "not able to determine a substitution from {}"
raise TypeError(msg.format(s))
cdef class Expression(CommutativeRingElement):
cpdef object pyobject(self):
"""
Get the underlying Python object.
OUTPUT:
The Python object corresponding to this expression, assuming
this expression is a single numerical value or an infinity
representable in Python. Otherwise, a ``TypeError`` is raised.
EXAMPLES::
sage: var('x')
x
sage: b = -17.3
sage: a = SR(b)
sage: a.pyobject()
-17.3000000000000
sage: a.pyobject() is b
True
Integers and Rationals are converted internally though, so you
won't get back the same object::
sage: b = -17/3
sage: a = SR(b)
sage: a.pyobject()
-17/3
sage: a.pyobject() is b
False
TESTS::
sage: SR(oo).pyobject()
+Infinity
sage: SR(-oo).pyobject()
-Infinity
sage: SR(unsigned_infinity).pyobject()
Infinity
sage: SR(I*oo).pyobject()
Traceback (most recent call last):
...
TypeError: Python infinity cannot have complex phase.
"""
cdef GConstant* c
if is_a_constant(self._gobj):
from sage.symbolic.constants import constants_name_table
return constants_name_table[GEx_to_str(&self._gobj)]
if is_a_infinity(self._gobj):
if (ex_to_infinity(self._gobj).is_unsigned_infinity()): return unsigned_infinity
if (ex_to_infinity(self._gobj).is_plus_infinity()): return infinity
if (ex_to_infinity(self._gobj).is_minus_infinity()): return minus_infinity
raise TypeError('Python infinity cannot have complex phase.')
if not is_a_numeric(self._gobj):
raise TypeError("self must be a numeric expression")
return py_object_from_numeric(self._gobj)
def __init__(self, SR, x=0):
"""
Nearly all expressions are created by calling new_Expression_from_*,
but we need to make sure this at least does not leave self._gobj
uninitialized and segfault.
TESTS::
sage: sage.symbolic.expression.Expression(SR)
0
sage: sage.symbolic.expression.Expression(SR, 5)
5
We test subclassing ``Expression``::
sage: from sage.symbolic.expression import Expression
sage: class exp_sub(Expression): pass
sage: f = function('f')
sage: t = f(x)
sage: u = exp_sub(SR, t)
sage: u.operator()
f
"""
self._parent = SR
cdef Expression exp = self.coerce_in(x)
GEx_construct_ex(&self._gobj, exp._gobj)
def __dealloc__(self):
"""
Delete memory occupied by this expression.
"""
GEx_destruct(&self._gobj)
def __getstate__(self):
"""
Return a tuple describing the state of this expression for pickling.
This should return all information that will be required to unpickle
the object. The functionality for unpickling is implemented in
__setstate__().
In order to pickle Expression objects, we return a tuple containing
* 0 - as pickle version number
in case we decide to change the pickle format in the feature
* names of symbols of this expression
* a string representation of self stored in a Pynac archive.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: t = 2*x*y^z+3
sage: s = dumps(t)
sage: t.__getstate__()
(0,
['x', 'y', 'z'],
...)
"""
cdef GArchive ar
ar.archive_ex(self._gobj, "sage_ex")
ar_str = GArchive_to_str(&ar)
return (0, map(repr, self.variables()), ar_str)
def _dbgprint(self):
r"""
Print pynac debug output to ``stderr``.
EXAMPLES::
sage: (1+x)._dbgprint()
x + 1
"""
self._gobj.dbgprint()
def _dbgprinttree(self):
r"""
Print pynac expression tree debug output to ``stderr``.
EXAMPLES:
The expression tree is composed of Ginac primitives
and functions, organized by the tree, with various
other memory and hash information which will vary::
sage: (1+x+exp(x+1))._dbgprinttree() # not tested
add @0x65e5960, hash=0x4727e01a, flags=0x3, nops=3
x (symbol) @0x6209150, serial=6, hash=0x2057b15e, flags=0xf, domain=0
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
function exp @0x24835d0, hash=0x765c2165, flags=0xb, nops=1
add @0x65df570, hash=0x420740d2, flags=0xb, nops=2
x (symbol) @0x6209150, serial=6, hash=0x2057b15e, flags=0xf, domain=0
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
overall_coeff
1 (numeric) @0x65e4df0, hash=0x7fd3, flags=0x7
=====
=====
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
overall_coeff
1 (numeric) @0x663cc40, hash=0x7fd3, flags=0x7
=====
TESTS:
This test is just to make sure the function is working::
sage: (1+x+exp(x+1))._dbgprinttree()
add @...
x (symbol) ...
1 (numeric) ...
...
overall_coeff
1 (numeric) ...
=====
Check that user-defined functions get the same treatment (:trac:`19194`)::
sage: f=function('f')(x)
sage: f._dbgprinttree()
function f ...
x (symbol) ...
=====
"""
self._gobj.dbgprinttree();
def __setstate__(self, state):
"""
Initialize the state of the object from data saved in a pickle.
During unpickling __init__ methods of classes are not called, the saved
data is passed to the class via this function instead.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: t = 2*x*y^z+3
sage: u = loads(dumps(t)) # indirect doctest
sage: u
2*x*y^z + 3
sage: bool(t == u)
True
sage: u.subs(x=z)
2*y^z*z + 3
sage: loads(dumps(x.parent()(2)))
2
"""
# check input
if state[0] != 0 or len(state) != 3:
raise ValueError("unknown state information")
# set parent
self._set_parent(ring.SR)
# get variables
cdef GExList sym_lst
for name in state[1]:
sym_lst.append_sym(\
ex_to_symbol((<Expression>ring.SR.symbol(name))._gobj))
# initialize archive
cdef GArchive ar
GArchive_from_str(&ar, state[2], len(state[2]))
# extract the expression from the archive
GEx_construct_ex(&self._gobj, ar.unarchive_ex(sym_lst, <unsigned>0))
def __copy__(self):
"""
TESTS::
sage: copy(x)
x
"""
return new_Expression_from_GEx(self._parent, self._gobj)
def _repr_(self):
"""
Return string representation of this symbolic expression.
EXAMPLES::
sage: var("x y")
(x, y)
sage: repr(x+y)
'x + y'
TESTS::
# printing of modular number equal to -1 as coefficient
sage: k.<a> = GF(9); k(2)*x
2*x
sage: (x+1)*Mod(6,7)
6*x + 6
#printing rational functions
sage: x/y
x/y
sage: x/2/y
1/2*x/y
sage: .5*x/y
0.500000000000000*x/y
sage: x^(-1)
1/x
sage: x^(-5)
x^(-5)
sage: x^(-y)
x^(-y)
sage: 2*x^(-1)
2/x
sage: i*x
I*x
sage: -x.parent(i)
-I
sage: y + 3*(x^(-1))
y + 3/x
Printing the exp function::
sage: x.parent(1).exp()
e
sage: x.exp()
e^x
Powers::
sage: _ = var('A,B,n'); (A*B)^n
(A*B)^n
sage: (A/B)^n
(A/B)^n
sage: n*x^(n-1)
n*x^(n - 1)
sage: (A*B)^(n+1)
(A*B)^(n + 1)
sage: (A/B)^(n-1)
(A/B)^(n - 1)
sage: n*x^(n+1)
n*x^(n + 1)
sage: n*x^(n-1)
n*x^(n - 1)
sage: n*(A/B)^(n+1)
n*(A/B)^(n + 1)
sage: (n+A/B)^(n+1)
(n + A/B)^(n + 1)
Powers where the base or exponent is a Python object::
sage: (2/3)^x
(2/3)^x
sage: x^CDF(1,2)
x^(1.0 + 2.0*I)
sage: (2/3)^(2/3)
(2/3)^(2/3)
sage: (-x)^(1/4)
(-x)^(1/4)
sage: k.<a> = GF(9)
sage: SR(a+1)^x
(a + 1)^x
Check if :trac:`7876` is fixed::
sage: (1/2-1/2*I )*sqrt(2)
-(1/2*I - 1/2)*sqrt(2)
sage: latex((1/2-1/2*I )*sqrt(2))
-\left(\frac{1}{2} i - \frac{1}{2}\right) \, \sqrt{2}
Check if :trac:`9632` is fixed::
sage: zeta(x) + cos(x)
cos(x) + zeta(x)
sage: psi(1,1/3)*log(3)
log(3)*psi(1, 1/3)
"""
return self._parent._repr_element_(self)
def _sympy_character_art(self, use_unicode):
r"""
Create character art using Sympy
INPUT:
- ``use_unicode`` -- boolean. Whether to allow unicode instead
of 7-bit clean output.
OUTPUT:
String.
EXAMPLES::
sage: i = var('i')
sage: integral(exp(x + x^2)/(x+1), x)._sympy_character_art(False)
' / \n | \n | 2 \n | x + x \n | e...'
"""
from sympy import pretty, sympify
# FIXME:: when *sage* will use at least sympy >= 0.7.2
# we could use a nice splitting with respect of the AsciiArt module.
# from sage.typeset.ascii_art import AsciiArt, MAX_LENGTH ## for import
# num_columns = MAX_LENGTH ## option of pretty
try:
return pretty(sympify(self, evaluate=False), use_unicode=use_unicode)
except Exception:
return str(self)
def _ascii_art_(self):
"""
Ascii art magic method.
See :mod:`sage.typeset.ascii_art` for details.
EXAMPLES::
sage: i = var('i')
sage: ascii_art(sum(i^2/pi*x^i, i, 0, oo))
2
x + x
-------------------------------
3 2
- pi*x + 3*pi*x - 3*pi*x + pi
sage: ascii_art(integral(exp(x + x^2)/(x+1), x))
/
|
| 2
| x + x
| e
| ------- dx
| x + 1
|
/
"""
from sage.typeset.ascii_art import AsciiArt
return AsciiArt(self._sympy_character_art(False).splitlines())
def _unicode_art_(self):
u"""
Unicode art magic method.
See :mod:`sage.typeset.unicode_art` for details.
EXAMPLES::
sage: i = var('i')
sage: unicode_art(sum(i^2/pi*x^i, i, 0, oo))
2
x + x
───────────────────────────
3 2
- π⋅x + 3⋅π⋅x - 3⋅π⋅x + π
sage: unicode_art(integral(exp(x + x^2)/(x+1), x))
⌠
⎮ 2
⎮ x + x
⎮ ℯ
⎮ ─────── dx
⎮ x + 1
⌡
"""
from sage.typeset.unicode_art import UnicodeArt
return UnicodeArt(self._sympy_character_art(True).splitlines())
def _interface_(self, I):
"""
EXAMPLES::
sage: f = sin(e + 2)
sage: f._interface_(sage.calculus.calculus.maxima)
sin(%e+2)
"""
if is_a_constant(self._gobj):
return self.pyobject()._interface_(I)
return super(Expression, self)._interface_(I)
def _maxima_(self, session=None):
"""
EXAMPLES::
sage: f = sin(e + 2)
sage: f._maxima_()
sin(%e+2)
sage: _.parent() is sage.calculus.calculus.maxima
True
"""
if session is None:
# This chooses the Maxima interface used by calculus
# Maybe not such a great idea because the "default" interface is another one
from sage.calculus.calculus import maxima
return super(Expression, self)._interface_(maxima)
else:
return super(Expression, self)._interface_(session)
def _interface_init_(self, I):
"""
EXAMPLES::
sage: a = (pi + 2).sin()
sage: a._maxima_init_()
'sin((%pi)+(2))'
sage: a = (pi + 2).sin()
sage: a._maple_init_()
'sin((pi)+(2))'
sage: a = (pi + 2).sin()
sage: a._mathematica_init_()
'Sin[(Pi)+(2)]'
sage: f = pi + I*e
sage: f._pari_init_()
'(Pi)+((exp(1))*(I))'
TESTS:
Check if complex numbers are converted to Maxima correctly
:trac:`7557`::
sage: SR(1.5*I)._maxima_init_()
'1.5000000000000000*%i'
sage: SR(CC.0)._maxima_init_()
'1.0000000000000000*%i'
sage: SR(CDF.0)._maxima_init_()
'1.0000000000000000*%i'
"""
from sage.symbolic.expression_conversions import InterfaceInit
return InterfaceInit(I)(self)
def _gap_init_(self):
"""
Convert symbolic object to GAP string.
EXAMPLES::
sage: gap(e + pi^2 + x^3)
x^3 + pi^2 + e
"""
return '"%s"'%repr(self)
def _singular_init_(self):
"""
Conversion of a symbolic object to Singular string.
EXAMPLES::
sage: singular(e + pi^2 + x^3)
x^3 + pi^2 + e
"""
return '"%s"'%repr(self)
def _magma_init_(self, magma):
"""
Return string representation in Magma of this symbolic expression.
Since Magma has no notation of symbolic calculus, this simply
returns something that evaluates in Magma to a a Magma string.
EXAMPLES::
sage: x = var('x')
sage: f = sin(cos(x^2) + log(x))
sage: f._magma_init_(magma)
'"sin(cos(x^2) + log(x))"'
sage: magma(f) # optional - magma
sin(cos(x^2) + log(x))
sage: magma(f).Type() # optional - magma
MonStgElt
"""
return '"%s"'%repr(self)
def _latex_(self):
r"""
Return string representation of this symbolic expression.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: latex(y + 3*(x^(-1)))
y + \frac{3}{x}
sage: latex(x^(y+z^(1/y)))
x^{y + z^{\left(\frac{1}{y}\right)}}
sage: latex(1/sqrt(x+y))
\frac{1}{\sqrt{x + y}}
sage: latex(sin(x*(z+y)^x))
\sin\left(x {\left(y + z\right)}^{x}\right)
sage: latex(3/2*(x+y)/z/y)
\frac{3 \, {\left(x + y\right)}}{2 \, y z}
sage: latex((2^(x^y)))
2^{\left(x^{y}\right)}
sage: latex(abs(x))
{\left| x \right|}
sage: latex((x*y).conjugate())
\overline{x} \overline{y}
sage: latex(x*(1/(x^2)+sqrt(x^7)))
x {\left(\sqrt{x^{7}} + \frac{1}{x^{2}}\right)}
Check spacing of coefficients of mul expressions (:trac:`3202` and
:trac:`13356`)::
sage: latex(2*3^x)
2 \cdot 3^{x}
sage: latex(1/2/3^x)
\frac{1}{2 \cdot 3^{x}}
sage: latex(1/2*3^x)
\frac{1}{2} \cdot 3^{x}
Powers::
sage: _ = var('A,B,n')
sage: latex((n+A/B)^(n+1))
{\left(n + \frac{A}{B}\right)}^{n + 1}
sage: latex((A*B)^n)
\left(A B\right)^{n}
sage: latex((A*B)^(n-1))
\left(A B\right)^{n - 1}
Powers where the base or exponent is a Python object::
sage: latex((2/3)^x)
\left(\frac{2}{3}\right)^{x}
sage: latex(x^CDF(1,2))
x^{1.0 + 2.0i}
sage: latex((2/3)^(2/3))
\left(\frac{2}{3}\right)^{\frac{2}{3}}
sage: latex((-x)^(1/4))
\left(-x\right)^{\frac{1}{4}}
sage: k.<a> = GF(9)
sage: latex(SR(a+1)^x)
\left(a + 1\right)^{x}
More powers (:trac:`7406`)::
sage: latex((x^pi)^e)
{\left(x^{\pi}\right)}^{e}
sage: latex((x^(pi+1))^e)
{\left(x^{\pi + 1}\right)}^{e}
sage: a,b,c = var('a b c')
sage: latex(a^(b^c))
a^{\left(b^{c}\right)}
sage: latex((a^b)^c)
{\left(a^{b}\right)}^{c}
Separate coefficients to numerator and denominator (:trac:`7363`)::
sage: latex(2/(x+1))
\frac{2}{x + 1}
sage: latex(1/2/(x+1))
\frac{1}{2 \, {\left(x + 1\right)}}
Check if rational function coefficients without a ``numerator()`` method
are printed correctly. :trac:`8491`::
sage: latex(6.5/x)
\frac{6.50000000000000}{x}
sage: latex(Mod(2,7)/x)
\frac{2}{x}
Check if we avoid extra parenthesis in rational functions (:trac:`8688`)::
sage: latex((x+2)/(x^3+1))
\frac{x + 2}{x^{3} + 1}
sage: latex((x+2)*(x+1)/(x^3+1))
\frac{{\left(x + 2\right)} {\left(x + 1\right)}}{x^{3} + 1}
sage: latex((x+2)/(x^3+1)/(x+1))
\frac{x + 2}{{\left(x^{3} + 1\right)} {\left(x + 1\right)}}
Check that the sign is correct (:trac:`9086`)::
sage: latex(-1/x)
-\frac{1}{x}
sage: latex(1/-x)
-\frac{1}{x}
More tests for the sign (:trac:`9314`)::
sage: latex(-2/x)
-\frac{2}{x}
sage: latex(-x/y)
-\frac{x}{y}
sage: latex(-x*z/y)
-\frac{x z}{y}
sage: latex(-x/z/y)
-\frac{x}{y z}
Check if :trac:`9394` is fixed::
sage: var('n')
n
sage: latex( e^(2*I*pi*n*x - 2*I*pi*n) )