Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/calculus/var.pyx
8815 views
1
from sage.symbolic.function_factory import function as new_function
2
from sage.symbolic.ring import SR
3
4
def var(*args, **kwds):
5
r"""
6
Create a symbolic variable with the name *s*.
7
8
INPUT:
9
10
- ``args`` - A single string ``var('x y')``, a list of strings
11
``var(['x','y'])``, or multiple strings ``var('x', 'y')``. A
12
single string can be either a single variable name, or a space
13
or comma separated list of variable names. In a list or tuple of
14
strings, each entry is one variable. If multiple arguments are
15
specified, each argument is taken to be one variable. Spaces
16
before or after variable names are ignored.
17
18
- ``kwds`` - keyword arguments can be given to specify domain and
19
custom latex_name for variables. See EXAMPLES for usage.
20
21
.. note::
22
23
The new variable is both returned and automatically injected
24
into the global namespace. If you need symbolic variable in
25
library code, it is better to use either SR.var() or SR.symbol().
26
27
OUTPUT:
28
29
If a single symbolic variable was created, the variable
30
itself. Otherwise, a tuple of symbolic variables. The variable
31
names are checked to be valid Python identifiers and a
32
``ValueError`` is raised otherwise.
33
34
EXAMPLES:
35
36
Here are the different ways to define three variables ``x``, ``y``,
37
and ``z`` in a single line::
38
39
sage: var('x y z')
40
(x, y, z)
41
sage: var('x, y, z')
42
(x, y, z)
43
sage: var(['x', 'y', 'z'])
44
(x, y, z)
45
sage: var('x', 'y', 'z')
46
(x, y, z)
47
sage: var('x'), var('y'), var(z)
48
(x, y, z)
49
50
We define some symbolic variables::
51
52
sage: var('n xx yy zz')
53
(n, xx, yy, zz)
54
55
Then we make an algebraic expression out of them::
56
57
sage: f = xx^n + yy^n + zz^n; f
58
xx^n + yy^n + zz^n
59
60
By default, var returns a complex variable. To define real or positive
61
variables we can specify the domain as::
62
63
sage: x = var('x', domain=RR); x; x.conjugate()
64
x
65
x
66
sage: y = var('y', domain='real'); y.conjugate()
67
y
68
sage: y = var('y', domain='positive'); y.abs()
69
y
70
71
Custom latex expression can be assigned to variable::
72
73
sage: x = var('sui', latex_name="s_{u,i}"); x._latex_()
74
's_{u,i}'
75
76
In notebook, we can also colorize latex expression::
77
78
sage: x = var('sui', latex_name="\\color{red}{s_{u,i}}"); x._latex_()
79
'\\color{red}{s_{u,i}}'
80
81
We can substitute a new variable name for n::
82
83
sage: f(n = var('sigma'))
84
xx^sigma + yy^sigma + zz^sigma
85
86
If you make an important built-in variable into a symbolic variable,
87
you can get back the original value using restore::
88
89
sage: var('QQ RR')
90
(QQ, RR)
91
sage: QQ
92
QQ
93
sage: restore('QQ')
94
sage: QQ
95
Rational Field
96
97
We make two new variables separated by commas::
98
99
sage: var('theta, gamma')
100
(theta, gamma)
101
sage: theta^2 + gamma^3
102
gamma^3 + theta^2
103
104
The new variables are of type Expression, and belong
105
to the symbolic expression ring::
106
107
sage: type(theta)
108
<type 'sage.symbolic.expression.Expression'>
109
sage: parent(theta)
110
Symbolic Ring
111
112
TESTS::
113
114
sage: var('q',ns=False)
115
Traceback (most recent call last):
116
...
117
NotImplementedError: The new (Pynac) symbolics are now the only symbolics; please do not use keyword `ns` any longer.
118
sage: q
119
Traceback (most recent call last):
120
...
121
NameError: name 'q' is not defined
122
sage: var('q',ns=1)
123
doctest:...: DeprecationWarning: The new (Pynac) symbolics are now the only symbolics; please do not use keyword 'ns' any longer.
124
See http://trac.sagemath.org/6559 for details.
125
q
126
"""
127
if len(args)==1:
128
name = args[0]
129
else:
130
name = args
131
G = globals() # this is the reason the code must be in Cython.
132
if 'ns' in kwds:
133
if kwds['ns']:
134
from sage.misc.superseded import deprecation
135
deprecation(6559, "The new (Pynac) symbolics are now the only symbolics; please do not use keyword 'ns' any longer.")
136
else:
137
raise NotImplementedError("The new (Pynac) symbolics are now the only symbolics; please do not use keyword `ns` any longer.")
138
kwds.pop('ns')
139
v = SR.var(name, **kwds)
140
if isinstance(v, tuple):
141
for x in v:
142
G[repr(x)] = x
143
else:
144
G[repr(v)] = v
145
return v
146
147
def function(s, *args, **kwds):
148
r"""
149
Create a formal symbolic function with the name *s*.
150
151
INPUT:
152
153
- ``s`` - a string, either a single variable name, or a space or
154
comma separated list of variable names.
155
156
- ``**kwds`` - keyword arguments. Either one of the following two
157
keywords can be used to customize latex representation of
158
symbolic functions:
159
160
(1) latex_name=LaTeX
161
where ``LaTeX`` is any valid latex expression.
162
Ex: f = function('f', x, latex_name="\\mathcal{F}")
163
See EXAMPLES for more.
164
165
(2) print_latex_func=my_latex_print
166
where ``my_latex_print`` is any callable function
167
that returns a valid latex expression.
168
Ex: f = function('f', x, print_latex_func=my_latex_print)
169
See EXAMPLES for an explicit usage.
170
171
.. note::
172
173
The new function is both returned and automatically injected
174
into the global namespace. If you use this function in library
175
code, it is better to use sage.symbolic.function_factory.function,
176
since it won't touch the global namespace.
177
178
EXAMPLES::
179
180
We create a formal function called supersin::
181
182
sage: f = function('supersin', x)
183
sage: f
184
supersin(x)
185
186
We can immediately use supersin in symbolic expressions::
187
188
sage: y, z, A = var('y z A')
189
sage: supersin(y+z) + A^3
190
A^3 + supersin(y + z)
191
192
We can define other functions in terms of supersin::
193
194
sage: g(x,y) = supersin(x)^2 + sin(y/2)
195
sage: g
196
(x, y) |--> supersin(x)^2 + sin(1/2*y)
197
sage: g.diff(y)
198
(x, y) |--> 1/2*cos(1/2*y)
199
sage: k = g.diff(x); k
200
(x, y) |--> 2*supersin(x)*D[0](supersin)(x)
201
202
Custom typesetting of symbolic functions in LaTeX::
203
204
(1) Either using latex_name keyword::
205
206
sage: riemann(x) = function('riemann', x, latex_name="\\mathcal{R}")
207
sage: latex(riemann(x))
208
\mathcal{R}\left(x\right)
209
210
(2) Or passing a custom callable function that returns a
211
latex expression::
212
213
sage: mu,nu = var('mu,nu')
214
sage: def my_latex_print(self, *args): return "\\psi_{%s}"%(', '.join(map(latex, args)))
215
sage: psi(mu,nu) = function('psi', mu, nu, print_latex_func=my_latex_print)
216
sage: latex(psi(mu,nu))
217
\psi_{\mu, \nu}
218
219
In Sage 4.0, you must now use the :meth:`substitute_function`
220
method to replace functions::
221
222
sage: k.substitute_function(supersin, sin)
223
2*cos(x)*sin(x)
224
"""
225
if len(args) > 0:
226
return function(s, **kwds)(*args)
227
228
G = globals() # this is the reason the code must be in Cython.
229
v = new_function(s, **kwds)
230
if isinstance(v, tuple):
231
for x in v:
232
G[repr(x)] = x
233
else:
234
G[repr(v)] = v
235
return v
236
237
238
def clear_vars():
239
"""
240
Delete all 1-letter symbolic variables that are predefined at
241
startup of Sage. Any one-letter global variables that are not
242
symbolic variables are not cleared.
243
244
EXAMPLES::
245
246
sage: var('x y z')
247
(x, y, z)
248
sage: (x+y)^z
249
(x + y)^z
250
sage: k = 15
251
sage: clear_vars()
252
sage: (x+y)^z
253
Traceback (most recent call last):
254
...
255
NameError: name 'x' is not defined
256
sage: expand((e + i)^2)
257
e^2 + 2*I*e - 1
258
sage: k
259
15
260
"""
261
G = globals()
262
from sage.symbolic.ring import is_SymbolicVariable
263
for i in range(65,65+26) + range(97,97+26):
264
if chr(i) in G and is_SymbolicVariable(G[chr(i)]):
265
# We check to see if there is a corresponding pyobject
266
# associated with the expression. This will work for
267
# constants which we want to keep, but will fail for
268
# variables that we want to delete.
269
try:
270
G[chr(i)].pyobject()
271
except TypeError:
272
del G[chr(i)]
273
274
275
276
277