本文整理汇总了Python中sage.symbolic.ring.SR类的典型用法代码示例。如果您正苦于以下问题:Python SR类的具体用法?Python SR怎么用?Python SR使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SR类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: length_rational_fraction
def length_rational_fraction(self, var='b'):
r"""
Return the generating series for the number of lengths with the given boundaries
"""
from sage.symbolic.ring import SR
F = SR.one()
for dart in range(self._total_darts):
if not self._active_darts[dart]:
continue
i = self._dart_to_edge_index[dart]
j1, j2 = self._edge_cycles[i]
if j1 == dart:
continue
else:
assert j2 == dart
f1 = self._dart_to_face_index[j1]
f2 = self._dart_to_face_index[j2]
b1 = SR.var('%s%d' %(var, f1))
b2 = SR.var('%s%d' %(var, f2))
F *= b1*b2 / (1 - b1*b2)
return F
示例2: __call__
def __call__(self, a, b, z, **kwargs):
"""
Return symbolic hypergeometric function expression.
INPUT:
- ``a`` -- a list or tuple of parameters
- ``b`` -- a list or tuple of parameters
- ``z`` -- a number or symbolic expression
EXAMPLES::
sage: hypergeometric([], [], 1)
hypergeometric((), (), 1)
sage: hypergeometric([], [1], 1)
hypergeometric((), (1,), 1)
sage: hypergeometric([2, 3], [1], 1)
hypergeometric((2, 3), (1,), 1)
sage: hypergeometric([], [], x)
hypergeometric((), (), x)
sage: hypergeometric([x], [], x^2)
hypergeometric((x,), (), x^2)
The only simplification that is done automatically is returning 1
if ``z`` is 0. For other simplifications use the
``simplify_hypergeometric`` method.
"""
return BuiltinFunction.__call__(self,
SR._force_pyobject(a),
SR._force_pyobject(b),
z, **kwargs)
示例3: mma_free_integrator
def mma_free_integrator(expression, v, a=None, b=None):
"""
sage: from sage.symbolic.integration.external import mma_free_integrator
sage: mma_free_integrator(sin(x), x) # optional - internet
-cos(x)
"""
import urllib, re
# We need to integrate against x
vars = [str(x) for x in expression.variables()]
if any(len(x)>1 for x in vars):
raise NotImplementedError("Mathematica online integrator can only handle single letter variables.")
x = SR.var('x')
if repr(v) != 'x':
for i in range(ord('a'), ord('z')+1):
if chr(i) not in vars:
shadow_x = SR.var(chr(i))
break
expression = expression.subs({x:shadow_x}).subs({dvar: x})
params = urllib.urlencode({'expr': expression._mathematica_init_(), 'random': 'false'})
page = urllib.urlopen("http://integrals.wolfram.com/index.jsp", params).read()
page = page[page.index('"inputForm"'):page.index('"outputForm"')]
page = re.sub("\s", "", page)
mexpr = re.match(r".*Integrate.*==</em><br/>(.*)</p>", page).groups()[0]
try:
ans = SR(mexpr.lower().replace('[', '(').replace(']', ')'))
if repr(v) != 'x':
ans = ans.subs({x:v}).subs({shadow_x:x})
return ans
except TypeError:
raise ValueError("Unable to parse: %s" % mexpr)
示例4: max_to_sr
def max_to_sr(expr):
r"""
Convert a Maxima object into a symbolic expression.
INPUT:
- ``expr`` - ECL object
OUTPUT: symbolic expression
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib, max_to_sr
sage: f = maxima_lib('f(x)')
sage: f.ecl()
<ECL: (($F SIMP) $X)>
sage: max_to_sr(f.ecl())
f(x)
TESTS::
sage: from sage.interfaces.maxima_lib import sr_to_max, max_to_sr
sage: f = function('f',x).diff()
sage: bool(max_to_sr(sr_to_max(f)) == f)
True
"""
if expr.consp():
op_max=caar(expr)
if op_max in special_max_to_sage:
return special_max_to_sage[op_max](expr)
if not(op_max in max_op_dict):
op_max_str=maxprint(op_max).python()[1:-1]
if op_max_str in max_to_pynac_table:
op = max_to_pynac_table[op_max_str]
else:
# This could be unsafe if the conversion to SR
# changes the structure of expr
sage_expr=SR(maxima(expr))
op=sage_expr.operator()
if op in sage_op_dict:
raise RuntimeError("Encountered operator mismatch in maxima-to-sr translation")
max_op_dict[op_max]=op
sage_op_dict[op]=op_max
else:
op=max_op_dict[op_max]
max_args=cdr(expr)
args=[max_to_sr(a) for a in max_args]
return op(*args)
elif expr.symbolp():
if not(expr in max_sym_dict):
sage_symbol=SR(maxima(expr))
sage_sym_dict[sage_symbol]=expr
max_sym_dict[expr]=sage_symbol
return max_sym_dict[expr]
else:
e=expr.python()
if isinstance(e,float):
return sage.rings.real_double.RealDoubleElement(e)
return e
示例5: laplace
def laplace(cls, self, parameters, variable, x='x', s='t'):
r"""
Returns the Laplace transform of self with respect to the variable
var.
INPUT:
- ``x`` - variable of self
- ``s`` - variable of Laplace transform.
We assume that a piecewise function is 0 outside of its domain and
that the left-most endpoint of the domain is 0.
EXAMPLES::
sage: x, s, w = var('x, s, w')
sage: f = piecewise([[(0,1),1],[[1,2], 1-x]])
sage: f.laplace(x, s)
-e^(-s)/s + (s + 1)*e^(-2*s)/s^2 + 1/s - e^(-s)/s^2
sage: f.laplace(x, w)
-e^(-w)/w + (w + 1)*e^(-2*w)/w^2 + 1/w - e^(-w)/w^2
::
sage: y, t = var('y, t')
sage: f = piecewise([[[1,2], 1-y]])
sage: f.laplace(y, t)
(t + 1)*e^(-2*t)/t^2 - e^(-t)/t^2
::
sage: s = var('s')
sage: t = var('t')
sage: f1(t) = -t
sage: f2(t) = 2
sage: f = piecewise([[[0,1],f1],[(1,infinity),f2]])
sage: f.laplace(t,s)
(s + 1)*e^(-s)/s^2 + 2*e^(-s)/s - 1/s^2
"""
from sage.all import assume, exp, forget
x = SR.var(x)
s = SR.var(s)
assume(s>0)
result = 0
for domain, f in parameters:
for interval in domain:
a = interval.lower()
b = interval.upper()
result += (SR(f)*exp(-s*x)).integral(x,a,b)
forget(s>0)
return result
示例6: simplify_sqrt_real
def simplify_sqrt_real(expr):
r"""
Simplify sqrt in symbolic expressions in the real domain.
EXAMPLES:
Simplifications of basic expressions::
sage: assume(x<0)
sage: simplify_sqrt_real( sqrt(x^2) )
-x
sage: simplify_sqrt_real( sqrt(x^2-2*x+1) )
-x + 1
sage: simplify_sqrt_real( sqrt(x^2) + sqrt(x^2-2*x+1) )
-2*x + 1
"""
from sage.symbolic.ring import SR
from sage.calculus.calculus import maxima
# 1/ Search for the sqrt's in expr
sexpr = str(expr)
if 'sqrt(' not in sexpr: # no sqrt to simplify
return expr
pos_sqrts = [] # positions of the sqrt's in sexpr
the_sqrts = [] # the sqrt sub-expressions in sexpr
for pos in range(len(sexpr)):
if sexpr[pos:pos+5] == 'sqrt(':
pos_sqrts.append(pos)
parenth = 1
scan = pos+5
while parenth != 0:
if sexpr[scan] == '(': parenth += 1
if sexpr[scan] == ')': parenth -= 1
scan += 1
the_sqrts.append( sexpr[pos:scan] )
# 2/ Simplifications of the sqrt's
new_expr = "" # will contain the result
pos0 = 0
for i, pos in enumerate(pos_sqrts):
# radcan is called on each sqrt:
x = SR(the_sqrts[i])
simpl = SR(x._maxima_().radcan())
# the absolute value of radcan's output is taken, the call to simplify()
# taking into account possible assumptions regarding the sign of simpl:
new_expr += sexpr[pos0:pos] + '(' + str(abs(simpl).simplify()) + ')'
pos0 = pos + len(the_sqrts[i])
new_expr += sexpr[pos0:]
return SR(new_expr)
示例7: spin_polynomial
def spin_polynomial(part, weight, length):
"""
Returns the spin polynomial associated to ``part``, ``weight``, and
``length``.
EXAMPLES::
sage: from sage.combinat.ribbon_tableau import spin_polynomial
sage: spin_polynomial([6,6,6],[4,2],3)
t^6 + t^5 + 2*t^4 + t^3 + t^2
sage: spin_polynomial([6,6,6],[4,1,1],3)
t^6 + 2*t^5 + 3*t^4 + 2*t^3 + t^2
sage: spin_polynomial([3,3,3,2,1], [2,2], 3)
t^(7/2) + t^(5/2)
sage: spin_polynomial([3,3,3,2,1], [2,1,1], 3)
2*t^(7/2) + 2*t^(5/2) + t^(3/2)
sage: spin_polynomial([3,3,3,2,1], [1,1,1,1], 3)
3*t^(7/2) + 5*t^(5/2) + 3*t^(3/2) + sqrt(t)
sage: spin_polynomial([5,4,3,2,1,1,1], [2,2,1], 3)
2*t^(9/2) + 6*t^(7/2) + 2*t^(5/2)
sage: spin_polynomial([[6]*6, [3,3]], [4,4,2], 3)
3*t^9 + 5*t^8 + 9*t^7 + 6*t^6 + 3*t^5
"""
from sage.symbolic.ring import SR
sp = spin_polynomial_square(part,weight,length)
t = SR.var('t')
c = sp.coefficients(sparse=False)
return sum([c[i]*t**(QQ(i)/2) for i in range(len(c))])
示例8: show
def show(self, show_hyperboloid=True, **graphics_options):
r"""
Plot ``self``.
EXAMPLES::
sage: from sage.geometry.hyperbolic_space.hyperbolic_geodesic import *
sage: g = HyperbolicPlane().HM().random_geodesic()
sage: g.show()
Graphics3d Object
"""
x = SR.var('x')
opts = self.graphics_options()
opts.update(graphics_options)
v1, u2 = [vector(k.coordinates()) for k in self.endpoints()]
# Lorentzian Gram Shmidt. The original vectors will be
# u1, u2 and the orthogonal ones will be v1, v2. Except
# v1 = u1, and I don't want to declare another variable,
# hence the odd naming convention above.
# We need the Lorentz dot product of v1 and u2.
v1_ldot_u2 = u2[0]*v1[0] + u2[1]*v1[1] - u2[2]*v1[2]
v2 = u2 + v1_ldot_u2 * v1
v2_norm = sqrt(v2[0]**2 + v2[1]**2 - v2[2]**2)
v2 = v2 / v2_norm
v2_ldot_u2 = u2[0]*v2[0] + u2[1]*v2[1] - u2[2]*v2[2]
# Now v1 and v2 are Lorentz orthogonal, and |v1| = -1, |v2|=1
# That is, v1 is unit timelike and v2 is unit spacelike.
# This means that cosh(x)*v1 + sinh(x)*v2 is unit timelike.
hyperbola = cosh(x)*v1 + sinh(x)*v2
endtime = arcsinh(v2_ldot_u2)
from sage.plot.plot3d.all import parametric_plot3d
pic = parametric_plot3d(hyperbola, (x, 0, endtime), **graphics_options)
if show_hyperboloid:
pic += self._model.get_background_graphic()
return pic
示例9: fourier_series_sine_coefficient
def fourier_series_sine_coefficient(cls, self, parameters, variable, n, L):
r"""
Returns the n-th Fourier series coefficient of
`\sin(n\pi x/L)`, `b_n`.
INPUT:
- ``self`` - the function f(x), defined over -L x L
- ``n`` - an integer n0
- ``L`` - (the period)/2
OUTPUT:
`b_n = \frac{1}{L}\int_{-L}^L f(x)\sin(n\pi x/L)dx`
EXAMPLES::
sage: f(x) = x^2
sage: f = piecewise([[(-1,1),f]])
sage: f.fourier_series_sine_coefficient(2,1) # L=1, n=2
0
"""
from sage.all import sin, pi
x = SR.var('x')
result = 0
for domain, f in parameters:
for interval in domain:
a = interval.lower()
b = interval.upper()
result += (f*sin(pi*x*n/L)/L).integrate(x, a, b)
return SR(result).simplify_trig()
示例10: random_expr
def random_expr(
size,
nvars=1,
ncoeffs=None,
var_frac=0.5,
internal=full_internal,
nullary=full_nullary,
nullary_frac=0.2,
coeff_generator=QQ.random_element,
verbose=False,
):
r"""
Produce a random symbolic expression of the given size. By
default, the expression involves (at most) one variable, an arbitrary
number of coefficients, and all of the symbolic functions and constants
(from the probability lists full_internal and full_nullary). It is
possible to adjust the ratio of leaves between symbolic constants,
variables, and coefficients (var_frac gives the fraction of variables,
and nullary_frac the fraction of symbolic constants; the remaining
leaves are coefficients).
The actual mix of symbolic constants and internal nodes can be modified
by specifying different probability lists.
To use a different type for coefficients, you can specify
coeff_generator, which should be a function that will return
a random coefficient every time it is called.
This function will often raise an error because it tries to create
an erroneous expression (such as a division by zero).
EXAMPLES::
sage: from sage.symbolic.random_tests import *
sage: set_random_seed(53)
sage: random_expr(50, nvars=3, coeff_generator=CDF.random_element) # random
(v1^(0.97134084277 + 0.195868299334*I)/csc(-pi + v1^2 + v3) + sgn(1/
((-v3 - 0.760455994772 - 0.554367254855*I)*erf(v3 + 0.982759757946 -
0.0352136502348*I)) + binomial(arccoth(v1^pi), 0.760455994772 +
0.554367254855*I) + arccosh(2*v2 - (v2 + 0.841911550437 -
0.303757179824*I)/sinh_integral(pi) + arccoth(v3 + 0.530133230474 +
0.532140303485*I))))/v2
sage: random_expr(5, verbose=True) # random
About to apply <built-in function inv> to [31]
About to apply sgn to [v1]
About to apply <built-in function add> to [1/31, sgn(v1)]
sgn(v1) + 1/31
"""
vars = [(1.0, SR.var("v%d" % (n + 1))) for n in range(nvars)]
if ncoeffs is None:
ncoeffs = size
coeffs = [(1.0, coeff_generator()) for _ in range(ncoeffs)]
leaves = [(var_frac, vars), (1.0 - var_frac - nullary_frac, coeffs), (nullary_frac, nullary)]
leaves = normalize_prob_list(leaves)
internal = normalize_prob_list(internal)
return random_expr_helper(size, internal, leaves, verbose)
示例11: test_issue_4023
def test_issue_4023():
from sage.symbolic.ring import SR
from sage.functions.all import log
from sympy import integrate, simplify
a,x = SR.var("a x")
i = integrate(log(x)/a, (x, a, a + 1))
i2 = simplify(i)
s = SR(i2)
assert s == (a*log(1 + a) - a*log(a) + log(1 + a) - 1)/a
示例12: _sympysage_symbol
def _sympysage_symbol(self):
"""
EXAMPLES::
sage: from sympy import Symbol
sage: assert x._sympy_() == Symbol('x')
sage: assert x == Symbol('x')._sage_()
"""
from sage.symbolic.ring import SR
return SR.var(self.name)
示例13: matrice_systeme
def matrice_systeme(systeme, variables):
"""
Renvoie une matrice par block représentant un programme linéaire sous forme standard.
INPUT::
- ``systeme`` -- Un programme linéaire sous forme standard
- ``variables`` -- La liste des variables du système
EXAMPLES::
sage: x = x1,x2,x3 = var('x1,x2,x3')
sage: Chvatal13 = [[2*x1 + 3*x2 + x3 <= 5,
....: 4*x1 + x2 + 2*x3 <= 11,
....: 3*x1 + 4*x2 + 2*x3 <= 8],
....: 5*x1 + 4*x2 + 3*x3]
sage: m = matrice_systeme(Chvatal13, x); m
[ z|s1 s2 s3|x1 x2 x3| 0]
[--+--------+--------+--]
[ 1| 0 0 0|-5 -4 -3| 0]
[--+--------+--------+--]
[ 0| 1 0 0| 2 3 1| 5]
[ 0| 0 1 0| 4 1 2|11]
[ 0| 0 0 1| 3 4 2| 8]
"""
def liste_coeffs(expression):
return [expression.coeff(v) for v in variables]
inequations = systeme[0]
m = matrix([liste_coeffs(ineq.lhs()) for ineq in inequations])
rhs = vector(ineq.rhs() for ineq in inequations).column()
slack = SR.var(",".join("s%s" % i for i in range(1, len(inequations) + 1)))
z = SR.var("z")
return block_matrix(
[
[z, matrix([slack]), matrix([variables]), ZZ(0)],
[ZZ(1), ZZ(0), -matrix([liste_coeffs(systeme[1])]), ZZ(0)],
[ZZ(0), ZZ(1), m, rhs],
]
)
示例14: fricas_integrator
def fricas_integrator(expression, v, a=None, b=None):
"""
Integration using FriCAS
EXAMPLES::
sage: from sage.symbolic.integration.external import fricas_integrator # optional - fricas
sage: fricas_integrator(sin(x), x) # optional - fricas
-cos(x)
sage: fricas_integrator(cos(x), x) # optional - fricas
sin(x)
sage: fricas_integrator(1/(x^2-2), x, 0, 1) # optional - fricas
1/4*(log(3*sqrt(2) - 4) - log(sqrt(2)))*sqrt(2)
sage: fricas_integrator(1/(x^2+6), x, -oo, oo) # optional - fricas
1/6*pi*sqrt(6)
"""
if not isinstance(expression, Expression):
expression = SR(expression)
if a is None:
result = expression._fricas_().integrate(v)
else:
import sage.rings.infinity
if a == sage.rings.infinity.PlusInfinity():
a = "%plusInfinity"
elif a == sage.rings.infinity.MinusInfinity():
a = "%minusInfinity"
if b == sage.rings.infinity.PlusInfinity():
b = "%plusInfinity"
elif b == sage.rings.infinity.MinusInfinity():
b = "%minusInfinity"
result = expression._fricas_().integrate("{}={}..{}".format(v, a, b))
locals = {str(v): v for v in expression.variables()}
if str(result) == "potentialPole":
raise ValueError("The integrand has a potential pole"
" in the integration interval")
parsed_result = result.unparsed_input_form()
import sage.misc.sage_eval
try:
return sage.misc.sage_eval.sage_eval(parsed_result, locals=locals)
except:
raise ValueError("Unable to parse: {}".format(parsed_result))
示例15: check_expression
def check_expression(expr, var_symbols, only_from_sympy=False):
"""
Does ``eval(expr)`` both in Sage and SymPy and does other checks.
EXAMPLES::
sage: from sage.interfaces.sympy import check_expression
sage: check_expression("1.123*x", "x")
"""
from sage import __dict__ as sagedict
from sage.symbolic.ring import SR
from sympy import (__dict__ as sympydict, Basic, S, var as svar)
# evaluate the expression in the context of Sage:
if var_symbols:
SR.var(var_symbols)
is_different = False
try:
e_sage = SR(expr)
assert not isinstance(e_sage, Basic)
except (NameError, TypeError):
is_different = True
pass
# evaluate the expression in the context of SymPy:
if var_symbols:
sympy_vars = svar(var_symbols)
b = globals().copy()
b.update(sympydict)
assert "sin" in b
b.update(sympydict)
e_sympy = eval(expr, b)
assert isinstance(e_sympy, Basic)
# Sympy func may have specific _sage_ method
if is_different:
_sage_method = getattr(e_sympy.func, "_sage_")
e_sage = _sage_method(S(e_sympy))
# Do the actual checks:
if not only_from_sympy:
assert S(e_sage) == e_sympy
assert e_sage == SR(e_sympy)