本文整理汇总了Python中sage.symbolic.ring.SR.var方法的典型用法代码示例。如果您正苦于以下问题:Python SR.var方法的具体用法?Python SR.var怎么用?Python SR.var使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sage.symbolic.ring.SR
的用法示例。
在下文中一共展示了SR.var方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: length_rational_fraction
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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: mma_free_integrator
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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)
示例3: laplace
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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
示例4: spin_polynomial
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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))])
示例5: show
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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
示例6: fourier_series_sine_coefficient
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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()
示例7: random_expr
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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)
示例8: test_issue_4023
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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
示例9: _sympysage_symbol
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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)
示例10: check_expression
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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)
示例11: matrice_systeme
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
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],
]
)
示例12: test_undefined_function
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
def test_undefined_function():
from sage.symbolic.ring import SR
from sage.calculus.var import function
from sympy import Symbol, Function
f = function('f')
sf = Function('f')
x,y = SR.var('x y')
sx = Symbol('x')
sy = Symbol('y')
assert f(x)._sympy_() == sf(sx)
assert f(x) == sf(sx)._sage_()
assert f(x,y)._sympy_() == sf(sx, sy)
assert f(x,y) == sf(sx, sy)._sage_()
assert f._sympy_() == sf
assert f == sf._sage_()
示例13: weight_integrand
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
def weight_integrand(self, simplify_factor=True):
"""
Weight integrand as a rational function.
The Jacobian determinant of some coordinate transformation.
"""
def arg(x,y):
return arctan(y/x) # up to a constant, but it doesn't matter
def phi(x,y,a,b):
z = (a+I*b-x-I*y)*(a - I*b - x - I*y)
w = z.real()
q = z.imag()
return arg(w,q).full_simplify()
n = len(self.internal_vertices())
coordinates = lambda v: SR.var(chr(97+2*(v-1)) + ',' + chr(97+2*(v-1)+1)) \
if v in self.internal_vertices() else \
[(0,0), (1,0)][self.ground_vertices().index(v)]
internal_coordinates = sum((list(coordinates(v)) for v in
sorted(self.internal_vertices())), [])
U = CoordinatePatch(internal_coordinates)
F = DifferentialForms(U)
psi = 0
two_forms = []
for v in self.internal_vertices():
x,y = coordinates(v)
outgoing_edges = self.outgoing_edges([v])
left_target = filter(lambda (x, y, z): z == 'L', outgoing_edges)[0][1]
right_target = filter(lambda (x, y, z): z == 'R', outgoing_edges)[0][1]
one_forms = []
for target in [left_target, right_target]:
a,b = coordinates(target)
one_form = DifferentialForm(F, 1)
for v in internal_coordinates:
index = internal_coordinates.index(v)
one_form[index] = phi(x,y,a,b).diff(v)
if simplify_factor:
one_form[index] = SR(one_form[index]).full_simplify()
one_forms.append(one_form)
two_form = one_forms[0]*one_forms[1]
two_forms.append(two_form)
import operator
two_n_form = reduce(operator.mul, two_forms, 1)
return two_n_form[range(0,2*n)]
示例14: fourier_series_cosine_coefficient
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
def fourier_series_cosine_coefficient(cls, self, parameters, variable, n, L):
r"""
Returns the n-th Fourier series coefficient of
`\cos(n\pi x/L)`, `a_n`.
INPUT:
- ``self`` - the function f(x), defined over -L x L
- ``n`` - an integer n=0
- ``L`` - (the period)/2
OUTPUT:
`a_n = \frac{1}{L}\int_{-L}^L f(x)\cos(n\pi x/L)dx`
EXAMPLES::
sage: f(x) = x^2
sage: f = piecewise([[(-1,1),f]])
sage: f.fourier_series_cosine_coefficient(2,1)
pi^(-2)
sage: f(x) = x^2
sage: f = piecewise([[(-pi,pi),f]])
sage: f.fourier_series_cosine_coefficient(2,pi)
1
sage: f1(x) = -1
sage: f2(x) = 2
sage: f = piecewise([[(-pi,pi/2),f1],[(pi/2,pi),f2]])
sage: f.fourier_series_cosine_coefficient(5,pi)
-3/5/pi
"""
from sage.all import cos, pi
x = SR.var('x')
result = 0
for domain, f in parameters:
for interval in domain:
a = interval.lower()
b = interval.upper()
result += (f*cos(pi*x*n/L)/L).integrate(x, a, b)
return SR(result).simplify_trig()
示例15: __init__
# 需要导入模块: from sage.symbolic.ring import SR [as 别名]
# 或者: from sage.symbolic.ring.SR import var [as 别名]
def __init__(self, n, delta=0.01, m=None):
"""
Construct LWE instance parameterised by security parameter ``n`` where
the modulus ``q`` and the ``stddev`` of the noise is chosen as in
[LP2011]_.
INPUT:
- ``n`` - security parameter (integer > 0)
- ``delta`` - error probability per symbol (default: 0.01)
- ``m`` - number of allowed samples or ``None`` in which case ``m=2*n +
128`` as in [LP2011]_ (default: ``None``)
EXAMPLES::
sage: from sage.crypto.lwe import LindnerPeikert
sage: LindnerPeikert(n=20)
LWE(20, 2053, Discrete Gaussian sampler over the Integers with sigma = 3.600954 and c = 0, 'noise', 168)
"""
if m is None:
m = 2*n + 128
# Find c>=1 such that c*exp((1-c**2)/2))**(2*n) == 2**-40
# (c*exp((1-c**2)/2))**(2*n) == 2**-40
# log((c*exp((1-c**2)/2))**(2*n)) == -40*log(2)
# (2*n)*log(c*exp((1-c**2)/2)) == -40*log(2)
# 2*n*(log(c)+log(exp((1-c**2)/2))) == -40*log(2)
# 2*n*(log(c)+(1-c**2)/2) == -40*log(2)
# 2*n*log(c)+n*(1-c**2) == -40*log(2)
# 2*n*log(c)+n*(1-c**2) + 40*log(2) == 0
c = SR.var('c')
c = find_root(2*n*log(c)+n*(1-c**2) + 40*log(2) == 0, 1, 10)
# Upper bound on s**2/t
s_t_bound = (sqrt(2) * pi / c / sqrt(2*n*log(2/delta))).n()
# Interpretation of "choose q just large enough to allow for a Gaussian parameter s>=8" in [LP2011]_
q = next_prime(floor(2**round(log(256 / s_t_bound, 2))))
# Gaussian parameter as defined in [LP2011]_
s = sqrt(s_t_bound*floor(q/4))
# Transform s into stddev
stddev = s/sqrt(2*pi.n())
D = DiscreteGaussianDistributionIntegerSampler(stddev)
LWE.__init__(self, n=n, q=q, D=D, secret_dist='noise', m=m)