rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
(list) a list of lists of length 3, each holding the
(list) A list of lists of length 3, each holding the
def points(self): """ Return a list of the generating points in this Mordell-Weil group.
9932a677a12413086a59217c4c0d425b0543b6eb /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/9932a677a12413086a59217c4c0d425b0543b6eb/interface.py
sage: latex(maxima(derivative(ceil(x*y*d), d,x,x,y))) d^3\,\left({{{\it \partial}^4}\over{{\it \partial}\,d^4}}\, {\it ceil}\left(d , x , y\right)\right)\,x^2\,y^3+5\,d^2\,\left({{ {\it \partial}^3}\over{{\it \partial}\,d^3}}\,{\it ceil}\left(d , x , y\right)\right)\,x\,y^2+4\,d\,\left({{{\it \partial}^2}\over{ {\it \partial}\,d^2}}\,{\it ceil}\left(d , x , y\right)\right)\,y
sage: f = function('f') sage: latex(maxima(derivative(f(x*y*d), d,x,x,y))) Traceback (most recent call last): ... NotImplementedError: arguments must be distinct variables sage: latex(maxima(derivative(f(x,y,d), d,x,x,y))) {{{\it \partial}^4}\over{{\it \partial}\,d\,{\it \partial}\,x^2\, {\it \partial}\,y}}\,f\left(x , y , d\right)
def _latex_(self): """ Return Latex representation of this Maxima object.
410199b0200806c2e676aa962b35ac96bb5d88f3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/410199b0200806c2e676aa962b35ac96bb5d88f3/maxima.py
Construct a module with basis from the data in ``x``
Construct a module with basis from the data in ``x``.
def _call_(self, x): """ Construct a module with basis from the data in ``x``
5e77b431e0bbe5251f2f32e3a2fe9539007540b3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5e77b431e0bbe5251f2f32e3a2fe9539007540b3/modules_with_basis.py
Returns whether this category is abelian
Returns whether this category is abelian.
def is_abelian(self): """ Returns whether this category is abelian
5e77b431e0bbe5251f2f32e3a2fe9539007540b3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5e77b431e0bbe5251f2f32e3a2fe9539007540b3/modules_with_basis.py
With the ``zero`` argument, one can define affine morphisms:
With the ``zero`` argument, one can define affine morphisms::
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
5e77b431e0bbe5251f2f32e3a2fe9539007540b3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5e77b431e0bbe5251f2f32e3a2fe9539007540b3/modules_with_basis.py
Or more generaly any ring admitting a coercion map from the base ring:
Or more generaly any ring admitting a coercion map from the base ring::
def module_morphism(self, on_basis = None, diagonal = None, triangular = None, **keywords): r""" Constructs morphisms by linearity
5e77b431e0bbe5251f2f32e3a2fe9539007540b3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5e77b431e0bbe5251f2f32e3a2fe9539007540b3/modules_with_basis.py
We can also create spaces corresponding to the groups `\GammaH(N)` intermediate
We can also create spaces corresponding to the groups `\Gamma_H(N)` intermediate
def ModularForms(group = 1, weight = 2, base_ring = None, use_cache = True, prec = defaults.DEFAULT_PRECISION): r""" Create an ambient space of modular forms. INPUT: - ``group`` - A congruence subgroup or a Dirichlet character eps. - ``weight`` - int, the weight, which must be an integer = 1. - ``base_ring`` - the base ring (ignored if group is a Dirichlet character) Create using the command ModularForms(group, weight, base_ring) where group could be either a congruence subgroup or a Dirichlet character. EXAMPLES: First we create some spaces with trivial character:: sage: ModularForms(Gamma0(11),2).dimension() 2 sage: ModularForms(Gamma0(1),12).dimension() 2 If we give an integer N for the congruence subgroup, it defaults to `\Gamma_0(N)`:: sage: ModularForms(1,12).dimension() 2 sage: ModularForms(11,4) Modular Forms space of dimension 4 for Congruence Subgroup Gamma0(11) of weight 4 over Rational Field We create some spaces for `\Gamma_1(N)`. :: sage: ModularForms(Gamma1(13),2) Modular Forms space of dimension 13 for Congruence Subgroup Gamma1(13) of weight 2 over Rational Field sage: ModularForms(Gamma1(13),2).dimension() 13 sage: [ModularForms(Gamma1(7),k).dimension() for k in [2,3,4,5]] [5, 7, 9, 11] sage: ModularForms(Gamma1(5),11).dimension() 12 We create a space with character:: sage: e = (DirichletGroup(13).0)^2 sage: e.order() 6 sage: M = ModularForms(e, 2); M Modular Forms space of dimension 3, character [zeta6] and weight 2 over Cyclotomic Field of order 6 and degree 2 sage: f = M.T(2).charpoly('x'); f x^3 + (-2*zeta6 - 2)*x^2 - 2*zeta6*x + 14*zeta6 - 7 sage: f.factor() (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1) We can also create spaces corresponding to the groups `\GammaH(N)` intermediate between `\Gamma_0(N)` and `\Gamma_1(N)`:: sage: G = GammaH(30, [11]) sage: M = ModularForms(G, 2); M Modular Forms space of dimension 20 for Congruence Subgroup Gamma_H(30) with H generated by [11] of weight 2 over Rational Field sage: M.T(7).charpoly().factor() (x + 4) * x^2 * (x - 6)^4 * (x + 6)^4 * (x - 8)^7 * (x^2 + 4) More examples of spaces with character:: sage: e = DirichletGroup(5, RationalField()).gen(); e Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1 sage: m = ModularForms(e, 2); m Modular Forms space of dimension 2, character [-1] and weight 2 over Rational Field sage: m == loads(dumps(m)) True sage: m.T(2).charpoly('x') x^2 - 1 sage: m = ModularForms(e, 6); m.dimension() 4 sage: m.T(2).charpoly('x') x^4 - 917*x^2 - 42284 This came up in a subtle bug (trac #5923):: sage: ModularForms(gp(1), gap(12)) Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field This came up in another bug (related to trac #8630):: sage: chi = DirichletGroup(109, CyclotomicField(3)).0 sage: ModularForms(chi, 2, base_ring = CyclotomicField(15)) Modular Forms space of dimension 10, character [zeta3 + 1] and weight 2 over Cyclotomic Field of order 15 and degree 8 We create some weight 1 spaces. The first example works fine, since we can prove purely by Riemann surface theory that there are no weight 1 cusp forms:: sage: M = ModularForms(Gamma1(11), 1); M Modular Forms space of dimension 5 for Congruence Subgroup Gamma1(11) of weight 1 over Rational Field sage: M.basis() [ 1 + 22*q^5 + O(q^6), q + 4*q^5 + O(q^6), q^2 - 4*q^5 + O(q^6), q^3 - 5*q^5 + O(q^6), q^4 - 3*q^5 + O(q^6) ] sage: M.cuspidal_subspace().basis() [ ] sage: M == M.eisenstein_subspace() True This example doesn't work so well, because we can't calculate the cusp forms; but we can still work with the Eisenstein series. sage: M = ModularForms(Gamma1(57), 1); M Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: M.basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: M.cuspidal_subspace().basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: E = M.eisenstein_subspace(); E Eisenstein subspace of dimension 36 of Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: (E.0 + E.2).q_expansion(40) 1 + q^2 + 1473/2*q^36 - 1101/2*q^37 + q^38 - 373/2*q^39 + O(q^40) """ if isinstance(group, dirichlet.DirichletCharacter): if base_ring is None: base_ring = group.minimize_base_ring().base_ring() if base_ring is None: base_ring = rings.QQ if isinstance(group, dirichlet.DirichletCharacter) \ or arithgroup.is_CongruenceSubgroup(group): level = group.level() else: level = group key = canonical_parameters(group, level, weight, base_ring) if use_cache and _cache.has_key(key): M = _cache[key]() if not (M is None): M.set_precision(prec) return M (level, group, weight, base_ring) = key M = None if arithgroup.is_Gamma0(group): M = ambient_g0.ModularFormsAmbient_g0_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_Gamma1(group): M = ambient_g1.ModularFormsAmbient_g1_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_GammaH(group): M = ambient_g1.ModularFormsAmbient_gH_Q(group, weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif isinstance(group, dirichlet.DirichletCharacter): eps = group if eps.base_ring().characteristic() != 0: # TODO -- implement this # Need to add a lift_to_char_0 function for characters, # and need to still remember eps. raise NotImplementedError, "currently the character must be over a ring of characteristic 0." eps = eps.minimize_base_ring() if eps.is_trivial(): return ModularForms(eps.modulus(), weight, base_ring, use_cache = use_cache, prec = prec) M = ambient_eps.ModularFormsAmbient_eps(eps, weight) if base_ring != eps.base_ring(): M = M.base_extend(base_ring) # ambient_R.ModularFormsAmbient_R(M, base_ring) if M is None: raise NotImplementedError, \ "computation of requested space of modular forms not defined or implemented" M.set_precision(prec) _cache[key] = weakref.ref(M) return M
6eb3e644186e44f7fb98ea0dcfe24aeebce503c5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/6eb3e644186e44f7fb98ea0dcfe24aeebce503c5/constructor.py
def rational_points(self, algorithm="enum", sort=True):
def rational_points_iterator(self):
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
Return the rational points on this curve computed via enumeration.
Return a generator object for the rational points on this curve.
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
- ``algorithm`` (string, default: 'enum') -- the algorithm to use. Currently this is ignored. - ``sort`` (boolean, default ``True``) -- whether the output points should be sorted. If False, the order of the output is non-deterministic.
- ``self`` -- a projective curve
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
A list of all the rational points on the curve defined over its base field, possibly sorted. .. note:: This is a slow Python-level implementation. EXAMPLES:: sage: F = GF(5)
A generator of all the rational points on the curve defined over its base field. EXAMPLE:: sage: F = GF(37)
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
sage: C = Curve(X^3+Y^3-Z^3) sage: C.rational_points() [(0 : 1 : 1), (1 : 0 : 1), (2 : 2 : 1), (3 : 4 : 1), (4 : 1 : 0), (4 : 3 : 1)] sage: C.rational_points(sort=False) [(4 : 1 : 0), (1 : 0 : 1), (0 : 1 : 1), (2 : 2 : 1), (4 : 3 : 1), (3 : 4 : 1)]
sage: C = Curve(X^7+Y*X*Z^5*55+Y^7*12) sage: len(list(C.rational_points_iterator())) 37
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
sage: F = GF(1009)
sage: F = GF(2)
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
sage: C = Curve(X^5+12*X*Y*Z^3 + X^2*Y^3 - 13*Y^2*Z^3) sage: len(C.rational_points()) 1043
sage: C = Curve(X*Y*Z) sage: a = C.rational_points_iterator() sage: a.next() (1 : 0 : 0) sage: a.next() (0 : 1 : 0) sage: a.next() (1 : 1 : 0) sage: a.next() (0 : 0 : 1) sage: a.next() (1 : 0 : 1) sage: a.next() (0 : 1 : 1) sage: a.next() Traceback (most recent call last): ... StopIteration
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
sage: F = GF(2^6,'a')
sage: F = GF(3^2,'a')
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
sage: C = Curve(X^5+11*X*Y*Z^3 + X^2*Y^3 - 13*Y^2*Z^3) sage: len(C.rational_points()) 104 :: sage: R.<x,y,z> = GF(2)[] sage: f = x^3*y + y^3*z + x*z^3 sage: C = Curve(f); pts = C.rational_points() sage: pts [(0 : 0 : 1), (0 : 1 : 0), (1 : 0 : 0)]
sage: C = Curve(X^3+5*Y^2*Z-33*X*Y*X) sage: b = C.rational_points_iterator() sage: b.next() (0 : 1 : 0) sage: b.next() (0 : 0 : 1) sage: b.next() (2*a + 2 : 2*a : 1) sage: b.next() (2 : a + 1 : 1) sage: b.next() (a + 1 : a + 2 : 1) sage: b.next() (1 : 2 : 1) sage: b.next() (2*a + 2 : a : 1) sage: b.next() (2 : 2*a + 2 : 1) sage: b.next() (a + 1 : 2*a + 1 : 1) sage: b.next() (1 : 1 : 1) sage: b.next() Traceback (most recent call last): ... StopIteration
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
points = []
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
points.append(self.point([one,zero,zero]))
t = self.point([one,zero,zero]) yield(t)
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
for x in R(g((X,one,zero))).roots(multiplicities=False): points.append(self.point([x,one,zero]))
g10 = R(g(X,one,zero)) if g10.is_zero(): for x in K: yield(self.point([x,one,zero])) else: for x in g10.roots(multiplicities=False): yield(self.point([x,one,zero]))
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
for x in R(g((X,y,one))).roots(multiplicities=False): points.append(self.point([x,y,one]))
gy1 = R(g(X,y,one)) if gy1.is_zero(): for x in K: yield(self.point([x,y,one])) else: for x in gy1.roots(multiplicities=False): yield(self.point([x,y,one])) def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. INPUT: - ``algorithm`` (string, default: 'enum') -- the algorithm to use. Currently this is ignored. - ``sort`` (boolean, default ``True``) -- whether the output points should be sorted. If False, the order of the output is non-deterministic. OUTPUT: A list of all the rational points on the curve defined over its base field, possibly sorted. .. note:: This is a slow Python-level implementation. EXAMPLES:: sage: F = GF(7) sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) sage: C = Curve(X^3+Y^3-Z^3) sage: C.rational_points() [(0 : 1 : 1), (0 : 2 : 1), (0 : 4 : 1), (1 : 0 : 1), (2 : 0 : 1), (3 : 1 : 0), (4 : 0 : 1), (5 : 1 : 0), (6 : 1 : 0)] :: sage: F = GF(1237) sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) sage: C = Curve(X^7+7*Y^6*Z+Z^4*X^2*Y*89) sage: len(C.rational_points()) 1237 :: sage: F = GF(2^6,'a') sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) sage: C = Curve(X^5+11*X*Y*Z^3 + X^2*Y^3 - 13*Y^2*Z^3) sage: len(C.rational_points()) 104 :: sage: R.<x,y,z> = GF(2)[] sage: f = x^3*y + y^3*z + x*z^3 sage: C = Curve(f); pts = C.rational_points() sage: pts [(0 : 0 : 1), (0 : 1 : 0), (1 : 0 : 0)] """ points = list(self.rational_points_iterator())
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
05c8eef04e5f3195edea5753cb5866da744515e5 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/05c8eef04e5f3195edea5753cb5866da744515e5/projective_curve.py
summing the sizes of the enumerated sets:
summing the sizes of the enumerated sets::
def cardinality(self): """ Returns the cardinality of this disjoint union.
84bb818f9eb80986f707ee05f4a8c9cee703c55e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/84bb818f9eb80986f707ee05f4a8c9cee703c55e/disjoint_union_enumerated_sets.py
'How big the point is.'
'How big the point is (i.e., area in points^2=(1/72 inch)^2).'
def _allowed_options(self): """ Return the allowed options for the Point class.
cf6eff7e0130e9212149458ca56db0aeed58d5d4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/cf6eff7e0130e9212149458ca56db0aeed58d5d4/point.py
'size': 'How big the point is.',
'size': 'How big the point is (i.e., area in points^2=(1/72 inch)^2).',
def _allowed_options(self): """ Return the allowed options for the Point class.
cf6eff7e0130e9212149458ca56db0aeed58d5d4 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/cf6eff7e0130e9212149458ca56db0aeed58d5d4/point.py
return []
return
def upgrade(): """ Download and build the latest version of Sage. You must have an internet connection. Also, you will have to restart Sage for the changes to take affect. This upgrades to the latest version of core packages (optional packages are not automatically upgraded). This will not work on systems that don't have a C compiler. .. seealso:: :func:`install_package`, :func:`optional_packages` """ global __installed_packages if os.uname()[0][:6] == 'CYGWIN': print "Upgrade may not work correctly under Microsoft Windows" print "since you can't change an opened file. Quit all" print "instances of Sage and use 'sage -upgrade' instead." return [] os.system('sage -upgrade') __installed_packages = None print "You should quit and restart Sage now."
8a37bc0c19467908de299f9f25078a11e077fc54 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8a37bc0c19467908de299f9f25078a11e077fc54/package.py
This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) sage: assume(y>0) sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True)
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): r""" Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx``, i.e. write `[x_0, y(x_0), y'(x_0)]` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` boundary conditions, i.e. write `[x_0, y(x_0), x_1, y(x_1)]`. - gives an error if the solution is not SymbolicEquation (as happens for example for Clairaut equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairaut, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) :: sage: f(x=10) 2 :: sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) :: sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) :: sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] :: sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] :: sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) :: sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] :: sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) :: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 Trac #9835 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x,2)+y*(1-y^2)==0,y,[0,-1,1,1]) Traceback (most recent call last): ... NotImplementedError: Unable to use initial condition for this equation (freeofx). AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) de00 = de._maxima_() P = de00.parent() dvar_str=P(dvar.operator()).str() ivar_str=P(ivar).str() de00 = de00.str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = P(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" P("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=P("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): if not show_method: maxima_method=P("method") raise NotImplementedError, "Unable to use initial condition for this equation (%s)."%(str(maxima_method).strip()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=P(ivar==ics[0]).str() tempic=tempic+","+P(dvar==ics[1]).str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+P(ics[2]).str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial condition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima P("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,P(ivar==ics[0]).str(),dvar_str,P(ics[1]).str(),P(ivar==ics[2]).str(),dvar_str,P(ics[3]).str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=P(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial condition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
e4366b45405e2291636c4e78ad37fb6df072b317 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/e4366b45405e2291636c4e78ad37fb6df072b317/desolvers.py
Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
Return a list of the associated primes of primary ideals of which the intersection is `I` = ``self``.
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
909ce5c943b9a9979f373d3a4e76baccb4d24a6e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/909ce5c943b9a9979f373d3a4e76baccb4d24a6e/multi_polynomial_ideal.py
- ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...]
- ``list`` - a list of associated primes
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
909ce5c943b9a9979f373d3a4e76baccb4d24a6e /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/909ce5c943b9a9979f373d3a4e76baccb4d24a6e/multi_polynomial_ideal.py
def iter_morphisms(self, l=None, codomain=None, min_length=1):
@rename_keyword(deprecated='Sage version 4.6.1', l='arg') def iter_morphisms(self, arg=None, codomain=None, min_length=1):
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
- ``l`` - (optional, default: None) It can be one of the following :
- ``arg`` - (optional, default: None) It can be one of the following :
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
- list of nonnegative integers - The length of the list must be the number of letters in the alphabet, and the `i`-th integer of ``l`` determines the length of the word mapped to by the `i`-th letter of the (ordered) alphabet.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
- ``min_length`` - (default: 1) nonnegative integer. If ``l`` is
- ``min_length`` - (default: 1) nonnegative integer. If ``arg`` is
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
``min_length``. This is ignored if ``l`` is a list.
``min_length``. This is ignored if ``arg`` is a list.
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
TypeError: l (=[0, 1, 2]) must be an iterable of 2 integers
TypeError: arg (=[0, 1, 2]) must be an iterable of 2 integers
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
TypeError: l (=[0, 'a']) must be an iterable of 2 integers
TypeError: arg (=[0, 'a']) must be an iterable of 2 integers
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
if l is None:
if arg is None:
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
elif isinstance(l, tuple): if not len(l) == 2 or not all(isinstance(a, (int,Integer)) for a in l): raise TypeError("l (=%s) must be a tuple of 2 integers" %l)
elif isinstance(arg, tuple): if not len(arg) == 2 or not all(isinstance(a, (int,Integer)) for a in arg): raise TypeError("arg (=%s) must be a tuple of 2 integers" %arg)
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
compositions = IntegerListsLex(range(*l),
compositions = IntegerListsLex(range(*arg),
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
l = list(l) if (not len(l) == n or not all(isinstance(a, (int,Integer)) for a in l)):
arg = list(arg) if (not len(arg) == n or not all(isinstance(a, (int,Integer)) for a in arg)):
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
"l (=%s) must be an iterable of %s integers" %(l, n)) compositions = [l]
"arg (=%s) must be an iterable of %s integers" %(arg, n)) compositions = [arg]
def iter_morphisms(self, l=None, codomain=None, min_length=1): r""" Iterate over all morphisms with domain ``self`` and the given codmain.
564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/564ffdb70e6edfcbc0b0fa7b79a0926d1d565df3/words.py
"""
r"""
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
7fb9685cca7c6df4ae0cab0c8237d0a0834f0892 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7fb9685cca7c6df4ae0cab0c8237d0a0834f0892/graph_generators.py
cospectral graphs.
cospectral graphs (lists of cadinality 1 being omitted).
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
7fb9685cca7c6df4ae0cab0c8237d0a0834f0892 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7fb9685cca7c6df4ae0cab0c8237d0a0834f0892/graph_generators.py
is enough to check the spectrum of the matrix `D^{-1}A`, where D
is enough to check the spectrum of the matrix `D^{-1}A`, where `D`
def cospectral_graphs(self, vertices, matrix_function=lambda g: g.adjacency_matrix(), graphs=None): """ Find all sets of graphs on ``vertices`` vertices (with possible restrictions) which are cospectral with respect to a constructed matrix.
7fb9685cca7c6df4ae0cab0c8237d0a0834f0892 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7fb9685cca7c6df4ae0cab0c8237d0a0834f0892/graph_generators.py
sage: browse_sage_doc(identity_matrix, 'rst')[:9] '**File:**' sage: browse_sage_doc(identity_matrix, 'rst')[-60:] 'MatrixSpace of 3 by 3 sparse matrices over Integer Ring\n ' sage: browse_sage_doc(identity_matrix, 'html', False)[:59] '<div class="docstring">\n \n <p><strong>File:</strong> /v'
sage: browse_sage_doc(identity_matrix, 'rst') "...**File:**...**Type:**...**Definition:** identity_matrix..." sage: identity_matrix.__doc__.replace('\\','\\\\') in browse_sage_doc(identity_matrix, 'rst') True sage: browse_sage_doc(identity_matrix, 'html', False) '...div...File:...Type:...Definition:...identity_matrix...'
def __call__(self, obj, output='html', view=True): r""" Return the documentation for ``obj``.
6a7a8d2dcf4f778c061b1f6c8f4d142c873499cd /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/6a7a8d2dcf4f778c061b1f6c8f4d142c873499cd/sagedoc.py
sage: W = Words('123') sage: W('1212').is_square() True sage: W('1213').is_square() False sage: W('12123').is_square() False sage: W().is_square()
sage: Word('1212').is_square() True sage: Word('1213').is_square() False sage: Word('12123').is_square() False sage: Word().is_square()
def is_square(self): r""" Returns True if self is a square, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True TESTS:: sage: W = Words('123') sage: W('11').is_square_free() False sage: W('211').is_square_free() False sage: W('3211').is_square_free() False """ l = self.length() if l < 2:
sage: Word('12312').is_square_free() True sage: Word('31212').is_square_free() False sage: Word().is_square_free() True TESTS: We make sure that sage: Word('11').is_square_free() False sage: Word('211').is_square_free() False sage: Word('3211').is_square_free() False """ L = self.length() if L < 2:
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
suff = self for i in xrange(0, l-1): for ll in xrange(2, l-i+1, 2): if suff[:ll].is_square():
for start in xrange(0, L-1): for end in xrange(start+2, L+1, 2): if self[start:end].is_square():
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
suff = suff[1:]
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
sage: W = Words('012') sage: W('012012012').is_cube() True sage: W('01010101').is_cube() False sage: W().is_cube() True sage: W('012012').is_cube()
sage: Word('012012012').is_cube() True sage: Word('01010101').is_cube() False sage: Word().is_cube() True sage: Word('012012').is_cube()
def is_cube(self): r""" Returns True if self is a cube, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
sage: W = Words('123') sage: W('12312').is_cube_free() True sage: W('32221').is_cube_free() False sage: W().is_cube_free() True """ l = self.length() if l < 3:
sage: Word('12312').is_cube_free() True sage: Word('32221').is_cube_free() False sage: Word().is_cube_free() True TESTS: We make sure that sage: Word('111').is_cube_free() False sage: Word('2111').is_cube_free() False sage: Word('32111').is_cube_free() False """ L = self.length() if L < 3:
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
suff = self for i in xrange(0, l - 3): for ll in xrange(3, l-i+1, 3): if suff[:ll].is_cube():
for start in xrange(0, L - 2): for end in xrange(start+3, L+1, 3): if self[start:end].is_cube():
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
suff = suff[1:]
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
65e004c0d1f96d960ea72ba590c71bc975cf9627 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/65e004c0d1f96d960ea72ba590c71bc975cf9627/finite_word.py
For example, ::
For example::
def old_cremona_letter_code(n): r""" Returns the *old* Cremona letter code corresponding to an integer. integer. For example, :: 1 --> A 26 --> Z 27 --> AA 52 --> ZZ 53 --> AAA etc. INPUT: - ``n`` - int OUTPUT: str EXAMPLES:: sage: old_cremona_letter_code(1) 'A' sage: old_cremona_letter_code(26) 'Z' sage: old_cremona_letter_code(27) 'AA' sage: old_cremona_letter_code(521) 'AAAAAAAAAAAAAAAAAAAAA' sage: old_cremona_letter_code(53) 'AAA' sage: old_cremona_letter_code(2005) 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC' """ n -= 1 k = n%26 + 65 label = chr(k)*int(n//26 + 1) return label
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
sage: it.next() Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field sage: it.next() Elliptic Curve defined by y^2 + y = x^3 - x^2 - 7820*x - 263580 over Rational Field """ return self.iter([11, self.largest_conductor()+1])
sage: it.next().label() '11a1' sage: it.next().label() '11a2' sage: it.next().label() '11a3' sage: it.next().label() '14a1' sage: skip = [it.next() for _ in range(100)] sage: it.next().label() '45a3' """ return self.iter(xsrange(11,self.largest_conductor()+1))
def __iter__(self): """ Returns an iterator through all EllipticCurve objects in the Cremona database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Return an iterator through all curves in the database with given conductors.
def iter(self, conductors): """ Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
Return an iterator through all optimal curves in the database with given conductors.
def iter_optimal(self, conductors): """ Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns a list of all curves with given conductors.
def list(self, conductors): """ Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns a list of all optimal curves with given conductors.
def list_optimal(self, conductors): """ Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
The smallest conductor for which the database is complete. (Always 1.)
The smallest conductor for which the database is complete: always 1.
def smallest_conductor(self): """ The smallest conductor for which the database is complete. (Always 1.)
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
OUTPUT: - ``int`` - smallest cond - ``int`` - largest conductor plus one
OUTPUT: tuple of ints (N1,N2+1) where N1 is the smallest and N2 the largest conductor for which the database is complete.
def conductor_range(self): """ Return the range of conductors that are covered by the database.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
TESTS::
TESTS:
def _init_allgens(self, ftpdata, largest_conductor=0): """ Initialize the allgens table by reading the corresponding ftpdata files and importing them into the database. """ if self.read_only: raise RuntimeError, "The database must not be read_only." files = os.listdir(ftpdata) files.sort() name = "allgens" c = _map[name] print "Deleting old data" for N in range(1,largest_conductor+1): self[N][c] = {} self[N] = self[N] # so database knows that self[N] changed. print "Reading new data" for F in files: if not F[:len(name)] == name: continue print F for L in gzip.GzipFile(ftpdata + "/" + F).readlines(): print L v = L.split() N = int(v[0]) if largest_conductor and N > largest_conductor: self.commit() return id = v[1] + v[2] dat = [eval(s.replace(':',',')) for s in v[5:]] if not self[N].has_key(c): self[N][c] = {} self[N][c][id] = dat self[N] = self[N] # so database knows that self[N] changed.
3c1b27bc91a3712f6058f9620a30ed25509047e2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/3c1b27bc91a3712f6058f9620a30ed25509047e2/cremona.py
sage: for lset in polytopes.cross_polytope(2).face_lattice().level_sets(): print lset[0] (None, (0, 1, 2, 3)) ((1,), (2, 3)) ((1, 2), (3,)) ((0, 1, 2, 3), None)
sage: level_sets = polytopes.cross_polytope(2).face_lattice().level_sets() sage: print level_sets[0], level_sets[-1] [(None, (0, 1, 2, 3))] [((0, 1, 2, 3), None)]
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
5b19bc41e9ed7f05434df1ef214d5e2da019260c /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/5b19bc41e9ed7f05434df1ef214d5e2da019260c/polyhedra.py
sage: @interacts.decorator.library_interact
sage: @interacts.library.library_interact
def library_interact(f): """ This is a decorator for using interacts in the Sage library. EXAMPLES:: sage: @interacts.decorator.library_interact ... def f(n=5): print n ... sage: f() # an interact appears <html>...</html> """ @sage_wraps(f) def library_wrapper(): # Maybe program around bug (?) in the notebook: html("</pre>") # This prints out the relevant html code to make # the interact appear: interact(f) return library_wrapper
8c25e9ca470abe52dc3ac0c498cdff091b20a257 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8c25e9ca470abe52dc3ac0c498cdff091b20a257/library.py
sage: interacts.decorator.demo()
sage: interacts.library.demo()
def demo(n=tuple(range(10)), m=tuple(range(10))): """ This is a demo interact that sums two numbers. INPUT: - `n` -- integer slider - `m` -- integer slider EXAMPLES:: sage: interacts.decorator.demo() <html>...</html> """ print n+m
8c25e9ca470abe52dc3ac0c498cdff091b20a257 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/8c25e9ca470abe52dc3ac0c498cdff091b20a257/library.py
The performance issue from
The performance issue from
... def variance(self, bias = False):
d868e3d99c0565bfa6cb057a2325bd9a9e7b1625 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/d868e3d99c0565bfa6cb057a2325bd9a9e7b1625/basic_stats.py
sage: homchain(C2, generators=True, base_ring=GF(2))[2]
sage: homchain(C2, generators=True, base_ring=GF(2))[2]
def homchain(complex=None, **kwds): r""" Compute the homology of a chain complex using the CHomP program ``homchain``. :param complex: a chain complex :param generators: if True, also return list of generators :type generators: boolean; optional, default False :param verbose: if True, print helpful messages as the computation progresses :type verbose: boolean; optional, default False :param help: if True, just print a help message and exit :type help: boolean; optional, default False :param extra_opts: options passed directly to ``homchain`` :type extra_opts: string :return: homology groups as a dictionary indexed by dimension EXAMPLES:: sage: from sage.interfaces.chomp import homchain sage: C = cubical_complexes.Sphere(3).chain_complex() sage: homchain(C)[3] # optional: need CHomP Z Generators: these are given as a list after the homology group. Each generator is specified as a cycle, an element in the appropriate free module over the base ring:: sage: C2 = delta_complexes.Sphere(2).chain_complex() sage: homchain(C2, generators=True)[2] # optional: need CHomP (Z, [(1, -1)]) sage: homchain(C2, generators=True, base_ring=GF(2))[2] (Vector space of dimension 1 over Finite Field of size 2, [(1, 1)]) TESTS: Chain complexes concentrated in negative dimensions, cochain complexes, etc.:: sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=-1) sage: homchain(C) # optional: need CHomP {-6: C4 x C4} sage: C = ChainComplex({-5: 4 * identity_matrix(ZZ, 2)}, degree=1) sage: homchain(C, generators=True) # optional: need CHomP {-4: (C4 x C4, [(1, 0), (0, 1)])} """ from sage.homology.all import ChainComplex help = kwds.get('help', False) if help: return CHomP().help('homchain') # Type-checking just in case. if isinstance(complex, ChainComplex): return CHomP()('homchain', complex, **kwds) else: raise TypeError, "Complex is not a chain complex."
10fd085a77bef57fa7361816e347209fc768b29a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/10fd085a77bef57fa7361816e347209fc768b29a/chomp.py
sage: cmp(P1xP1, 1)
sage: cmp(P1xP1, 1) * cmp(1, P1xP1)
def __cmp__(self, right): r""" Compare ``self`` and ``right``.
1312749ae504505c480e693c47b6d47f6e4a0bf0 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/1312749ae504505c480e693c47b6d47f6e4a0bf0/toric_variety.py
THEOREM (Kato): Suppose `p \geq 5` is a prime so the `p`-adic representation `\rho_{E,p}` is surjective and `L(E,1) \neq 0`. Then `{ord}_p(\
THEOREM (Kato): Suppose `L(E,1) \neq 0` and `p \neq 2, 3` is a prime such that - `E` does not have additive reduction at `p`, - the mod-`p` representation is surjective. Then `{ord}_p(\
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
a65589b424a4f170a5aece0d1b80690d7bdd7d29 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/a65589b424a4f170a5aece0d1b80690d7bdd7d29/sha_tate.py
[2, 3, 5]
[2, 3, 5, 23]
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
a65589b424a4f170a5aece0d1b80690d7bdd7d29 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/a65589b424a4f170a5aece0d1b80690d7bdd7d29/sha_tate.py
[2, 3, 7]
[2, 3, 7, 29]
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
a65589b424a4f170a5aece0d1b80690d7bdd7d29 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/a65589b424a4f170a5aece0d1b80690d7bdd7d29/sha_tate.py
B = [2,3] for p in self.E.galois_representation().non_surjective():
B = [2, 3] for p in self.E.galois_representation().non_surjective():
def bound_kato(self): r""" Returns a list `p` of primes such that the theorems of Kato's [Ka] and others (e.g., as explained in a paper/thesis of Grigor Grigorov [Gri]) imply that if `p` divides the order of Sha(E) then `p` is in the list.
a65589b424a4f170a5aece0d1b80690d7bdd7d29 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/a65589b424a4f170a5aece0d1b80690d7bdd7d29/sha_tate.py
``obj``, return a list of those names. If
``obj``, return a sorted list of those names. If
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return result
125f8a6e4b9ecacb479405e4c6d70b9a85d59547 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/125f8a6e4b9ecacb479405e4c6d70b9a85d59547/sageinspect.py
return result
return sorted(result)
def sage_getvariablename(obj, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``obj`` - an object - ``omit_underscore_names`` (optional, default True) If the user has assigned an object ``obj`` to a variable name, then return that variable name. If several variables point to ``obj``, return a list of those names. If ``omit_underscore_names`` is True (the default) then omit names starting with an underscore "_". This is a modified version of code taken from http://pythonic.pocoo.org/2009/5/30/finding-objects-names, written by Georg Brandl. EXAMPLES:: sage: from sage.misc.sageinspect import sage_getvariablename sage: A = random_matrix(ZZ, 100) sage: sage_getvariablename(A) 'A' sage: B = A sage: sage_getvariablename(A) ['A', 'B'] If an object is not assigned to a variable, an empty list is returned:: sage: sage_getvariablename(random_matrix(ZZ, 60)) [] """ import gc result = [] for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for k, v in referrer.iteritems(): if v is obj: if isinstance(k, str): if (not omit_underscore_names) or not k.startswith('_'): result.append(k) if len(result) == 1: return result[0] else: return result
125f8a6e4b9ecacb479405e4c6d70b9a85d59547 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/125f8a6e4b9ecacb479405e4c6d70b9a85d59547/sageinspect.py
approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise.
approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits of `z` with ``known_bits=k`` or ``known_digits=k``. PARI is then told to compute the result using `0.8k` of these bits/digits. Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may be specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polynomial is not found, then ``None`` will be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library ``algdep`` command otherwise.
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
- ``height_bound`` - an integer (default ``None``) specifying the maximum
- ``height_bound`` - an integer (default: ``None``) specifying the maximum
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
- ``proof`` - a boolean (default ``False``), requres height_bound to be set
- ``proof`` - a boolean (default: ``False``), requires height_bound to be set
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
This example involves a complex number. ::
This example involves a complex number::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
This example involves a `p`-adic number. ::
This example involves a `p`-adic number::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. ::
compute a 200-bit approximation to `sqrt(2)` which is wrong in the 33'rd bit::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
and coefficients bounded above by 10. ::
and coefficients bounded above by 10::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
For stronger results, we need more precicion. ::
For stronger results, we need more precicion::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
We can also use ``proof=True`` to get positive results. ::
We can also use ``proof=True`` to get positive results::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
- ``bound (default 1024)`` - int: highest power to test.
- ``bound (default: 1024)`` - int: highest power to test.
def is_pseudoprime_small_power(n, bound=1024, get_data=False): r""" Return True if `n` is a small power of a pseudoprime, and False otherwise. The result is *NOT* proven correct - *this IS a pseudo-primality test!*. If `get_data` is set to true and `n = p^d`, for a pseudoprime `p` and power `d`, return [(p, d)]. INPUT: - ``n`` - an integer - ``bound (default 1024)`` - int: highest power to test. - ``get_data`` - boolean: return small pseudoprime and the power. EXAMPLES:: sage: is_pseudoprime_small_power(389) True sage: is_pseudoprime_small_power(2000) False sage: is_pseudoprime_small_power(2) True sage: is_pseudoprime_small_power(1024) True sage: is_pseudoprime_small_power(-1) False sage: is_pseudoprime_small_power(1) True sage: is_pseudoprime_small_power(997^100) True The default bound is 1024:: sage: is_pseudoprime_small_power(3^1024) True sage: is_pseudoprime_small_power(3^1025) False But it can be set higher or lower:: sage: is_pseudoprime_small_power(3^1025, bound=2000) True sage: is_pseudoprime_small_power(3^100, bound=20) False Use of the get_data keyword:: sage: is_pseudoprime_small_power(3^1024, get_data=True) [(3, 1024)] sage: is_pseudoprime_small_power(2^256, get_data=True) [(2, 256)] sage: is_pseudoprime_small_power(15, get_data=True) False """ n = ZZ(n) if n.is_pseudoprime() or n == 1: return True if n < 0: return False for i in range(2, bound + 1): p, boo = n.nth_root(i, truncate_mode=True) if boo: if p.is_pseudoprime(): if get_data == True: return [(p, i)] else: return True return False
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
- ``verbose`` - integer (default 0); pari's debug
- ``verbose`` - integer (default: 0); PARI's debug
def factor(n, proof=None, int_=False, algorithm='pari', verbose=0, **kwds): """ Returns the factorization of n. The result depends on the type of n. If n is an integer, factor returns the factorization of the integer n as an object of type Factorization. If n is not an integer, ``n.factor(proof=proof, **kwds)`` gets called. See ``n.factor??`` for more documentation in this case. .. warning:: This means that applying factor to an integer result of a symbolic computation will not factor the integer, because it is considered as an element of a larger symbolic ring. EXAMPLE:: sage: f(n)=n^2 sage: is_prime(f(3)) False sage: factor(f(3)) 9 INPUT: - ``n`` - an nonzero integer - ``proof`` - bool or None (default: None) - ``int_`` - bool (default: False) whether to return answers as Python ints - ``algorithm`` - string - ``'pari'`` - (default) use the PARI c library - ``'kash'`` - use KASH computer algebra system (requires the optional kash package be installed) - ``'magma'`` - use Magma (requires magma be installed) - ``verbose`` - integer (default 0); pari's debug variable is set to this; e.g., set to 4 or 8 to see lots of output during factorization. OUTPUT: factorization of n The qsieve and ecm commands give access to highly optimized implementations of algorithms for doing certain integer factorization problems. These implementations are not used by the generic factor command, which currently just calls PARI (note that PARI also implements sieve and ecm algorithms, but they aren't as optimized). Thus you might consider using them instead for certain numbers. The factorization returned is an element of the class :class:`~sage.structure.factorization.Factorization`; see Factorization?? for more details, and examples below for usage. A Factorization contains both the unit factor (+1 or -1) and a sorted list of (prime, exponent) pairs. The factorization displays in pretty-print format but it is easy to obtain access to the (prime,exponent) pairs and the unit, to recover the number from its factorization, and even to multiply two factorizations. See examples below. EXAMPLES:: sage: factor(500) 2^2 * 5^3 sage: factor(-20) -1 * 2^2 * 5 sage: f=factor(-20) sage: list(f) [(2, 2), (5, 1)] sage: f.unit() -1 sage: f.value() -20 sage: factor( -next_prime(10^2) * next_prime(10^7) ) -1 * 101 * 10000019 :: sage: factor(-500, algorithm='kash') # optional - kash -1 * 2^2 * 5^3 :: sage: factor(-500, algorithm='magma') # optional - magma -1 * 2^2 * 5^3 :: sage: factor(0) Traceback (most recent call last): ... ArithmeticError: Prime factorization of 0 not defined. sage: factor(1) 1 sage: factor(-1) -1 sage: factor(2^(2^7)+1) 59649589127497217 * 5704689200685129054721 Sage calls PARI's factor, which has proof False by default. Sage has a global proof flag, set to True by default (see :mod:`sage.structure.proof.proof`, or proof.[tab]). To override the default, call this function with proof=False. :: sage: factor(3^89-1, proof=False) 2 * 179 * 1611479891519807 * 5042939439565996049162197 :: sage: factor(2^197 + 1) # takes a long time (e.g., 3 seconds!) 3 * 197002597249 * 1348959352853811313 * 251951573867253012259144010843 Any object which has a factor method can be factored like this:: sage: K.<i> = QuadraticField(-1) sage: factor(122+454*i) (-1) * (-2*i - 3) * (-i + 4) * (i + 1)^3 * (-i + 2)^3 To access the data in a factorization:: sage: f = factor(420); f 2^2 * 3 * 5 * 7 sage: [x for x in f] [(2, 2), (3, 1), (5, 1), (7, 1)] sage: [p for p,e in f] [2, 3, 5, 7] sage: [e for p,e in f] [2, 1, 1, 1] sage: [p^e for p,e in f] [4, 3, 5, 7] """ if not isinstance(n, (int,long, integer.Integer)): # this happens for example if n = x**2 + y**2 + 2*x*y try: return n.factor(proof=proof, **kwds) except AttributeError: raise TypeError, "unable to factor n" except TypeError: # just in case factor method doesn't have a proof option. try: return n.factor(**kwds) except AttributeError: raise TypeError, "unable to factor n" #n = abs(n) n = ZZ(n) if n < 0: unit = ZZ(-1) n = -n else: unit = ZZ(1) if n == 0: raise ArithmeticError, "Prime factorization of 0 not defined." if n == 1: return factorization.Factorization([], unit) if n < 10000000000000: return factorization.Factorization(__factor_using_trial_division(n), unit) if algorithm == 'pari': return factorization.Factorization(__factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof), unit) elif algorithm in ['kash', 'magma']: if algorithm == 'kash': from sage.interfaces.all import kash as I else: from sage.interfaces.all import magma as I F = I.eval('Factorization(%s)'%n) i = F.rfind(']') + 1 F = F[:i] F = F.replace("<","(").replace(">",")") F = eval(F) if not int_: F = [(ZZ(a), ZZ(b)) for a,b in F] return factorization.Factorization(F, unit) else: raise ValueError, "Algorithm is not known"
2a5f9f192675580f8a03d5205bd9793259ee204a /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/2a5f9f192675580f8a03d5205bd9793259ee204a/arith.py
solution is not SymbolisEquation (as happens for example for
solution is not SymbolicEquation (as happens for example for
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
- ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation.
- ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation.
def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False): """ Solves a 1st or 2nd order linear ODE via maxima. Including IVP and BVP. *Use* ``desolve? <tab>`` *if the output in truncated in notebook.* INPUT: - ``de`` - an expression or equation representing the ODE - ``dvar`` - the dependent variable (hereafter called ``y``) - ``ics`` - (optional) the initial or boundary conditions - for a first-order equation, specify the initial ``x`` and ``y`` - for a second-order equation, specify the initial ``x``, ``y``, and ``dy/dx`` - for a second-order boundary solution, specify initial and final ``x`` and ``y`` initial conditions gives error if the solution is not SymbolisEquation (as happens for example for clairot equation) - ``ivar`` - (optional) the independent variable (hereafter called x), which must be specified if there is more than one independent variable in the equation. - ``show_method`` - (optional) if true, then Sage returns pair ``[solution, method]``, where method is the string describing method which has been used to get solution (Maxima uses the following order for first order equations: linear, separable, exact (including exact with integrating factor), homogeneous, bernoulli, generalized homogeneous) - use carefully in class, see below for the example of the equation which is separable but this property is not recognized by Maxima and equation is solved as exact. - ``contrib_ode`` - (optional) if true, desolve allows to solve clairot, lagrange, riccati and some other equations. May take a long time and thus turned off by default. Initial conditions can be used only if the result is one SymbolicEquation (does not contain singular solution, for example) OUTPUT: In most cases returns SymbolicEquation which defines the solution implicitly. If the result is in the form y(x)=... (happens for linear eqs.), returns the right-hand side only. The possible constant solutions of separable ODE's are omitted. EXAMPLES:: sage: x = var('x') sage: y = function('y', x) sage: desolve(diff(y,x) + y - 1, y) (c + e^x)*e^(-x) :: sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f (e^10 + e^x)*e^(-x) :: sage: plot(f) We can also solve second-order differential equations.:: sage: x = var('x') sage: y = function('y', x) sage: de = diff(y,x,2) - y == x sage: desolve(de, y) k1*e^x + k2*e^(-x) - x :: sage: f = desolve(de, y, [10,2,1]); f -x + 5*e^(-x + 10) + 7*e^(x - 10) sage: f(x=10) 2 sage: diff(f,x)(x=10) 1 :: sage: de = diff(y,x,2) + y == 0 sage: desolve(de, y) k1*sin(x) + k2*cos(x) sage: desolve(de, y, [0,1,pi/2,4]) 4*sin(x) + cos(x) sage: desolve(y*diff(y,x)+sin(x)==0,y) -1/2*y(x)^2 == c - cos(x) Clairot equation: general and singular solutions:: sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True) [[y(x) == c^2 + c*x, y(x) == -1/4*x^2], 'clairault'] For equations involving more variables we specify independent variable:: sage: a,b,c,n=var('a b c n') sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True) [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]] sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True) [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati'] Higher orded, not involving independent variable:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand() 1/6*y(x)^3 + k1*y(x) == k2 + x sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand() 1/6*y(x)^3 - 5/3*y(x) == x - 3/2 sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True) [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx'] Separable equations - Sage returns solution in implicit form:: sage: desolve(diff(y,x)*sin(y) == cos(x),y) -cos(y(x)) == c + sin(x) sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True) [-cos(y(x)) == c + sin(x), 'separable'] sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1]) -cos(y(x)) == sin(x) - cos(1) - 1 Linear equation - Sage returns the expression on the right hand side only:: sage: desolve(diff(y,x)+(y) == cos(x),y) 1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x) sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True) [1/2*((sin(x) + cos(x))*e^x + 2*c)*e^(-x), 'linear'] sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1]) 1/2*(e^x*sin(x) + e^x*cos(x) + 1)*e^(-x) This ODE with separated variables is solved as exact. Explanation - factor does not split `e^{x-y}` in Maxima into `e^{x}e^{y}`:: sage: desolve(diff(y,x)==exp(x-y),y,show_method=True) [-e^x + e^y(x) == c, 'exact'] You can solve Bessel equations. You can also use initial conditions, but you cannot put (sometimes desired) initial condition at x=0, since this point is singlar point of the equation. Anyway, if the solution should be bounded at x=0, then k2=0.:: sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y) k1*bessel_j(2, x) + k2*bessel_y(2, x) Difficult ODE produces error:: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Difficult ODE produces error - moreover, takes a long time :: sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested Some more types od ODE's:: sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True) [[y(x) == c + log(x), y(x) == c*e^x], 'factor'] :: sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True) [[[x == c - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == c + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange'] These two examples produce error (as expected, Maxima 5.18 cannot solve equations from initial conditions). Current Maxima 5.18 returns false answer in this case!:: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." :: sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested Traceback (click to the left for traceback) ... NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." Second order linear ODE:: sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y) (k2*x + k1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True) [(k2*x + k1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1]) 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True) [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2]) 3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True) [3*((e^(1/2*pi) - 2)*x/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y) (k2*x + k1)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True) [(k2*x + k1)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1]) (4*x + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True) [(4*x + 3)*e^(-x), 'constcoeff'] sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2]) (2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x) sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True) [(2*(2*e^(1/2*pi) - 3)*x/pi + 3)*e^(-x), 'constcoeff'] This equation can be solved within Maxima but not within Sage. It needs assumptions assume(x>0,y>0) and works in Maxima, but not in Sage:: sage: assume(x>0) # not tested sage: assume(y>0) # not tested sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y,y,show_method=True) # not tested TESTS: Trac #6479 fixed:: sage: x = var('x') sage: y = function('y', x) sage: desolve( diff(y,x,x) == 0, y, [0,0,1]) x :: sage: desolve( diff(y,x,x) == 0, y, [0,1,1]) x + 1 AUTHORS: - David Joyner (1-2006) - Robert Bradshaw (10-2008) - Robert Marik (10-2009) """ if is_SymbolicEquation(de): de = de.lhs() - de.rhs() if is_SymbolicVariable(dvar): raise ValueError, "You have to declare dependent variable as a function, eg. y=function('y',x)" # for backwards compatibility if isinstance(dvar, list): dvar, ivar = dvar elif ivar is None: ivars = de.variables() ivars = [t for t in ivars if t is not dvar] if len(ivars) != 1: raise ValueError, "Unable to determine independent variable, please specify." ivar = ivars[0] def sanitize_var(exprs): return exprs.replace("'"+dvar_str+"("+ivar_str+")",dvar_str) dvar_str=dvar.operator()._maxima_().str() ivar_str=ivar._maxima_().str() de00 = de._maxima_().str() de0 = sanitize_var(de00) ode_solver="ode2" cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x) soln = maxima(cmd) if str(soln).strip() == 'false': if contrib_ode: ode_solver="contrib_ode" maxima("load('contrib_ode)") cmd="(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))"%(ode_solver,de0,dvar_str,ivar_str,dvar_str,dvar_str,ivar_str) # we produce string like this # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP)) soln = maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this ODE." else: raise NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True." if show_method: maxima_method=maxima("method") if (ics is not None): if not is_SymbolicEquation(soln.sage()): raise NotImplementedError, "Maxima was unable to use initial condition for this equation (%s)"%(maxima_method.str()) if len(ics) == 2: tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() cmd="(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if len(ics) == 3: #fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \ temp: lhs(soln) - rhs(soln), \ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") tempic=(ivar==ics[0])._maxima_().str() tempic=tempic+","+(dvar==ics[1])._maxima_().str() tempic=tempic+",'diff("+dvar_str+","+ivar_str+")="+(ics[2])._maxima_().str() cmd="(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))"%(ode_solver,de00,dvar_str,ivar_str,tempic,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this IVP. Remove the initial contition to get the general solution." if len(ics) == 4: #fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima maxima("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \ if length(temp)=1 then return(first(temp)) else return(temp))") cmd="bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)"%(ode_solver,de00,dvar_str,ivar_str,(ivar==ics[0])._maxima_().str(),dvar_str,(ics[1])._maxima_().str(),(ivar==ics[2])._maxima_().str(),dvar_str,(ics[3])._maxima_().str()) cmd="(TEMP:%s,substitute(%s=%s(%s),TEMP))"%(cmd,dvar_str,dvar_str,ivar_str) cmd=sanitize_var(cmd) # we produce string like this # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP)) soln=maxima(cmd) if str(soln).strip() == 'false': raise NotImplementedError, "Maxima was unable to solve this BVP. Remove the initial contition to get the general solution." soln=soln.sage() if is_SymbolicEquation(soln) and soln.lhs() == dvar: # Remark: Here we do not check that the right hand side does not depend on dvar. # This probably will not hapen for soutions obtained via ode2, anyway. soln = soln.rhs() if show_method: return [soln,maxima_method.str()] else: return soln
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
"""
r"""
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2])
- ``de`` - a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") - ``vars`` - a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) - ``ics`` - a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2])
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES:
The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES::
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007)
Now type show(P1), show(P2) to view these. AUTHORS: - David Joyner (3-2006, 8-2007)
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
"""
r"""
def eulers_method(f,x0,y0,h,x1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order ODE ``y' = f(x,y)``, ``y(a)=c``. The "x" column of the table increments from ``x0`` to ``x1`` by ``h`` (so ``(x1-x0)/h`` must be an integer). In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the last column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2 1/2 -1 -7/4 1 -11/4 -11/8 :: sage: x,y = PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y = PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1,method="None") [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]] :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: x,y=PolynomialRing(RR,2,"xy").gens() sage: eulers_method(5*x+y-5,0,1,1/2,1) x y h*f(x,y) 0 1 -2.0 1/2 -1.0 -1.7 1 -2.7 -1.3 :: sage: x,y=PolynomialRing(QQ,2,"xy").gens() sage: eulers_method(5*x+y-5,1,1,1/3,2) x y h*f(x,y) 1 1 1/3 4/3 4/3 1 5/3 7/3 17/9 2 38/9 83/27 :: sage: eulers_method(5*x+y-5,0,1,1/2,1,method="none") [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]] :: sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,method="none") sage: P1 = list_plot(pts) sage: P2 = line(pts) sage: (P1+P2).show() AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s"%("x","y","h*f(x,y)") n=int((1.0)*(x1-x0)/h) x00=x0; y00=y0 soln = [[x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %20r"%(x00,y00,h*f(x00,y00)) y00 = y00+h*f(x00,y00) x00=x00+h soln.append([x00,y00]) if method!="table": return soln
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
"""
r"""
def eulers_method_2x2(f,g, t0, x0, y0, h, t1,method="table"): """ This implements Euler's method for finding numerically the solution of the 1st order system of two ODEs ``x' = f(t, x, y), x(t0)=x0.`` ``y' = g(t, x, y), y(t0)=y0.`` The "t" column of the table increments from `t_0` to `t_1` by `h` (so `\\frac{t_1-t_0}{h}` must be an integer). In the "x" column, the new x-value equals the old x-value plus the corresponding entry in the next (third) column. In the "y" column, the new y-value equals the old y-value plus the corresponding entry in the next (last) column. *For pedagogical purposes only.* EXAMPLES:: sage: from sage.calculus.desolvers import eulers_method_2x2 sage: t, x, y = PolynomialRing(QQ,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,method="none") [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]] :: sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0 0 0 1/3 0 1/9 0 0 2/3 1/9 7/27 0 1/27 1 10/27 38/81 1/27 1/9 :: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = x+y+t; g = x-y sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 0 0.00 0 0.00 1/3 0.00 0.13 0.00 0.00 2/3 0.13 0.29 0.00 0.043 1 0.41 0.57 0.043 0.15 To numerically approximate `y(1)`, where `(1+t^2)y''+y'-y=0`, `y(0)=1`, `y'(0)=-1`, using 4 steps of Euler's method, first convert to a system: `y_1' = y_2`, `y_1(0)=1`; `y_2' = \\frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.:: sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU') sage: t, x, y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = (x-y)/(1+t^2) sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 -0.25 -1 0.50 1/4 0.75 -0.12 -0.50 0.29 1/2 0.63 -0.054 -0.21 0.19 3/4 0.63 -0.0078 -0.031 0.11 1 0.63 0.020 0.079 0.071 To numerically approximate y(1), where `y''+ty'+y=0`, `y(0)=1`, `y'(0)=0`:: sage: t,x,y=PolynomialRing(RR,3,"txy").gens() sage: f = y; g = -x-y*t sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1) t x h*f(t,x,y) y h*g(t,x,y) 0 1 0.00 0 -0.25 1/4 1.0 -0.062 -0.25 -0.23 1/2 0.94 -0.11 -0.46 -0.17 3/4 0.88 -0.15 -0.62 -0.10 1 0.75 -0.17 -0.68 -0.015 AUTHORS: - David Joyner """ if method=="table": print "%10s %20s %25s %20s %20s"%("t", "x","h*f(t,x,y)","y", "h*g(t,x,y)") n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): if method=="table": print "%10r %20r %25r %20r %20r"%(t00,x00,h*f(t00,x00,y00),y00,h*g(t00,x00,y00)) x01 = x00 + h*f(t00,x00,y00) y00 = y00 + h*g(t00,x00,y00) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) if method!="table": return soln
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
"""
r""" Plots solution of ODE
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
`\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) =
`\theta''+\sin(\theta)=0`, `\theta(0)=\frac 34`, `\theta'(0) =
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot
``(P[0]+P[1]).show()`` to plot `(t,\theta(t))` and `(t,\theta'(t))`::
def eulers_method_2x2_plot(f,g, t0, x0, y0, h, t1): """ This plots the soln in the rectangle ``(xrange[0],xrange[1]) x (yrange[0],yrange[1])`` and plots using Euler's method the numerical solution of the 1st order ODEs `x' = f(t,x,y)`, `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`. *For pedagogical purposes only.* EXAMPLES:: The following example plots the solution to `\\theta''+\\sin(\\theta)=0`, `\\theta(0)=\\frac 34`, `\\theta'(0) = 0`. Type ``P[0].show()`` to plot the solution, ``(P[0]+P[1]).show()`` to plot `(t,\\theta(t))` and `(t,\\theta'(t))`:: sage: from sage.calculus.desolvers import eulers_method_2x2_plot sage: f = lambda z : z[2]; g = lambda z : -sin(z[1]) sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) """ n=int((1.0)*(t1-t0)/h) t00 = t0; x00 = x0; y00 = y0 soln = [[t00,x00,y00]] for i in range(n+1): x01 = x00 + h*f([t00,x00,y00]) y00 = y00 + h*g([t00,x00,y00]) x00 = x01 t00 = t00 + h soln.append([t00,x00,y00]) Q1 = line([[x[0],x[1]] for x in soln], rgbcolor=(1/4,1/8,3/4)) Q2 = line([[x[0],x[2]] for x in soln], rgbcolor=(1/2,1/8,1/4)) return [Q1,Q2]
7f133a6744923b72b06980a1787657382d80133b /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/7f133a6744923b72b06980a1787657382d80133b/desolvers.py
self._read_faces(self.poly_x("i"))
self._read_faces(self.poly_x("i", reduce_dimension=True))
def _compute_faces(self): r""" Compute and cache faces of this polytope.
0c437a9fd38c44ead21aca785cc5469bac656ae2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0c437a9fd38c44ead21aca785cc5469bac656ae2/lattice_polytope.py
Return the sequence of faces of this polytope.
Return the sequence of proper faces of this polytope.
def faces(self, dim=None, codim=None): r""" Return the sequence of faces of this polytope.
0c437a9fd38c44ead21aca785cc5469bac656ae2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0c437a9fd38c44ead21aca785cc5469bac656ae2/lattice_polytope.py
self._points = self._embed(read_palp_matrix( self.poly_x("p", reduce_dimension=True))) self._points.set_immutable()
if self.dim() == 0: self._points = self._vertices else: self._points = self._embed(read_palp_matrix( self.poly_x("p", reduce_dimension=True))) self._points.set_immutable()
def points(self): r""" Return all lattice points of this polytope as columns of a matrix.
0c437a9fd38c44ead21aca785cc5469bac656ae2 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/0c437a9fd38c44ead21aca785cc5469bac656ae2/lattice_polytope.py
sage: f1(x) = 1 sage: f2(x) = 1-x sage: f = Piecewise([[(0,1),f1],[(1,2),f2]])
sage: f1(x) = 1-x sage: f = Piecewise([[(0,1),1],[(1,2),f1]])
def integral(self, x=None, a=None, b=None, definite=False): r""" By default, returns the indefinite integral of the function. If definite=True is given, returns the definite integral.
e8ef019171ad607aab4ce833d63168ff9b0ef837 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/e8ef019171ad607aab4ce833d63168ff9b0ef837/piecewise.py
Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
Return a new Weierstrass model of self under the standard transformation `(u,r,s,t)`
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
60581bf6d640bfa4b7f71a19999bd0feb09d2c88 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/60581bf6d640bfa4b7f71a19999bd0feb09d2c88/ell_generic.py
(x,y) \mapsto (x',y') = (u^2xr , u^3y + su^2x' + t).
(x,y) \mapsto (x',y') = (u^2x + r , u^3y + su^2x + t).
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
60581bf6d640bfa4b7f71a19999bd0feb09d2c88 /local1/tlutelli/issta_data/temp/all_python//python/2010_temp/2010/9417/60581bf6d640bfa4b7f71a19999bd0feb09d2c88/ell_generic.py