rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
through `(x - a)^n`.
|
through `(x - a)^n`. Functions in more variables are also supported.
|
def taylor(f, v, a, n): """ Expands self in a truncated Taylor or Laurent series in the variable `v` around the point `a`, containing terms through `(x - a)^n`. INPUT: - ``v`` - variable - ``a`` - number - ``n`` - integer EXAMPLES:: sage: var('x,k,n') (x, k, n) sage: taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6) -1/720*(45*k^6 - 60*k^4 + 16*k^2)*x^6 - 1/24*(3*k^4 - 4*k^2)*x^4 - 1/2*k^2*x^2 + 1 sage: taylor ((x + 1)^n, x, 0, 4) 1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1 """ if not isinstance(f, Expression): f = SR(f) return f.taylor(v=v,a=a,n=n)
|
- ``v`` - variable - ``a`` - number - ``n`` - integer
|
- ``*args`` - the following notation is supported - ``x, a, n`` - variable, point, degree - ``(x, a), (y, b), ..., n`` - variables with points, degree of polynomial
|
def taylor(f, v, a, n): """ Expands self in a truncated Taylor or Laurent series in the variable `v` around the point `a`, containing terms through `(x - a)^n`. INPUT: - ``v`` - variable - ``a`` - number - ``n`` - integer EXAMPLES:: sage: var('x,k,n') (x, k, n) sage: taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6) -1/720*(45*k^6 - 60*k^4 + 16*k^2)*x^6 - 1/24*(3*k^4 - 4*k^2)*x^4 - 1/2*k^2*x^2 + 1 sage: taylor ((x + 1)^n, x, 0, 4) 1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1 """ if not isinstance(f, Expression): f = SR(f) return f.taylor(v=v,a=a,n=n)
|
return f.taylor(v=v,a=a,n=n)
|
return f.taylor(*args)
|
def taylor(f, v, a, n): """ Expands self in a truncated Taylor or Laurent series in the variable `v` around the point `a`, containing terms through `(x - a)^n`. INPUT: - ``v`` - variable - ``a`` - number - ``n`` - integer EXAMPLES:: sage: var('x,k,n') (x, k, n) sage: taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6) -1/720*(45*k^6 - 60*k^4 + 16*k^2)*x^6 - 1/24*(3*k^4 - 4*k^2)*x^4 - 1/2*k^2*x^2 + 1 sage: taylor ((x + 1)^n, x, 0, 4) 1/24*(n^4 - 6*n^3 + 11*n^2 - 6*n)*x^4 + 1/6*(n^3 - 3*n^2 + 2*n)*x^3 + 1/2*(n^2 - n)*x^2 + n*x + 1 """ if not isinstance(f, Expression): f = SR(f) return f.taylor(v=v,a=a,n=n)
|
return QuotientRingElement(self.parent(), self.__rep + right.__rep)
|
return self.parent()(self.__rep + right.__rep)
|
def _add_(self, right): """ Add quotient ring element ``self`` to another quotient ring element, ``right``. If the quotient is `R/I`, the addition is carried out in `R` and then reduced to `R/I`.
|
return QuotientRingElement(self.parent(), self.__rep - right.__rep)
|
return self.parent()(self.__rep - right.__rep)
|
def _sub_(self, right): """ Subtract quotient ring element ``right`` from quotient ring element ``self``. If the quotient is `R/I`, the subtraction is carried out in `R` and then reduced to `R/I`.
|
return QuotientRingElement(self.parent(), self.__rep * right.__rep)
|
return self.parent()(self.__rep * right.__rep)
|
def _mul_(self, right): """ Multiply quotient ring element ``self`` by another quotient ring element, ``right``. If the quotient is `R/I`, the multiplication is carried out in `R` and then reduced to `R/I`.
|
return QuotientRingElement(self.parent(), -self.__rep)
|
return self.parent()(-self.__rep)
|
def __neg__(self): """ EXAMPLES:: sage: R.<x,y> = QQ[]; S.<a,b> = R.quo(x^2 + y^2); type(a) <class 'sage.rings.quotient_ring_element.QuotientRingElement'> sage: -a # indirect doctest -a sage: -(a+b) -a - b """ return QuotientRingElement(self.parent(), -self.__rep)
|
return QuotientRingElement(self.parent(), inv)
|
return self.parent()(inv)
|
def __invert__(self): """ EXAMPLES:: sage: R.<x,y> = QQ[]; S.<a,b> = R.quo(x^2 + y^2); type(a) <class 'sage.rings.quotient_ring_element.QuotientRingElement'> sage: ~S(2/3) 3/2
|
return QuotientRingElement(self.parent(),self.__rep.lt())
|
return self.parent()(self.__rep.lt())
|
def lt(self): """ Return the leading term of this quotient ring element. EXAMPLE:: sage: R.<x,y,z>=PolynomialRing(GF(7),3,order='lex') sage: I = sage.rings.ideal.FieldIdeal(R) sage: Q = R.quo( I ) sage: f = Q( z*y + 2*x ) sage: f.lt() 2*xbar
|
return QuotientRingElement(self.parent(),self.__rep.lm())
|
return self.parent()(self.__rep.lm())
|
def lm(self): """ Return the leading monomial of this quotient ring element. EXAMPLE:: sage: R.<x,y,z>=PolynomialRing(GF(7),3,order='lex') sage: I = sage.rings.ideal.FieldIdeal(R) sage: Q = R.quo( I ) sage: f = Q( z*y + 2*x ) sage: f.lm() xbar TESTS:: sage: R.<x,y> = QQ[]; S.<a,b> = R.quo(x^2 + y^2); type(a) <class 'sage.rings.quotient_ring_element.QuotientRingElement'> sage: (a+3*a*b+b).lm() a*b """ return QuotientRingElement(self.parent(),self.__rep.lm())
|
return tuple([QuotientRingElement(self.parent(),v) for v in self.__rep.variables()])
|
return tuple([self.parent()(v) for v in self.__rep.variables()])
|
def variables(self): """ EXAMPLES:: sage: R.<x,y> = QQ[]; S.<a,b> = R.quo(x^2 + y^2); type(a) <class 'sage.rings.quotient_ring_element.QuotientRingElement'> sage: a.variables() (a,) sage: b.variables() (b,) sage: s = a^2 + b^2 + 1; s 1 sage: s.variables() () sage: (a+b).variables() (a, b) """ return tuple([QuotientRingElement(self.parent(),v) for v in self.__rep.variables()])
|
return [QuotientRingElement(self.parent(),m) for m in self.__rep.monomials()]
|
return [self.parent()(m) for m in self.__rep.monomials()]
|
def monomials(self): """ EXAMPLES:: sage: R.<x,y> = QQ[]; S.<a,b> = R.quo(x^2 + y^2); type(a) <class 'sage.rings.quotient_ring_element.QuotientRingElement'> sage: a.monomials() [a] sage: (a+a*b).monomials() [a*b, a] """ return [QuotientRingElement(self.parent(),m) for m in self.__rep.monomials()]
|
sage: cmp(c1, 1)
|
sage: cmp(c1, 1) * cmp(1, c1)
|
def __cmp__(self, right): r""" Compare ``self`` and ``right``. INPUT: - ``right`` -- anything. OUTPUT: - 0 if ``right`` is of the same type as ``self`` and their rays are the same and listed in the same order. 1 or -1 otherwise. TESTS:: sage: c1 = Cone([(1,0), (0,1)]) sage: c2 = Cone([(0,1), (1,0)]) sage: c3 = Cone([(0,1), (1,0)]) sage: cmp(c1, c2) 1 sage: cmp(c2, c1) -1 sage: cmp(c2, c3) 0 sage: c2 is c3 False sage: cmp(c1, 1) -1 """ c = cmp(type(self), type(right)) if c: return c return cmp((self.lattice(), self.rays()), (right.lattice(), right.rays()))
|
def _limit_latex_(*args):
|
def _limit_latex_(self, f, x, a):
|
def _limit_latex_(*args): r""" Return latex expression for limit of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _limit_latex_ sage: var('x,a') (x, a) sage: f(x) = function('f',x) sage: _limit_latex_(f(x), x, a) '\\lim_{x \\to a}\\, f\\left(x\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-15) """ # Read f,x,a from arguments f = args[0] x = args[1] a = args[2] return "\\lim_{%s \\to %s}\\, %s"%(latex(x), latex(a), latex(f))
|
sage: f(x) = function('f',x) sage: _limit_latex_(f(x), x, a)
|
sage: f = function('f',x) sage: _limit_latex_(0, f, x, a)
|
def _limit_latex_(*args): r""" Return latex expression for limit of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _limit_latex_ sage: var('x,a') (x, a) sage: f(x) = function('f',x) sage: _limit_latex_(f(x), x, a) '\\lim_{x \\to a}\\, f\\left(x\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-15) """ # Read f,x,a from arguments f = args[0] x = args[1] a = args[2] return "\\lim_{%s \\to %s}\\, %s"%(latex(x), latex(a), latex(f))
|
f = args[0] x = args[1] a = args[2]
|
def _limit_latex_(*args): r""" Return latex expression for limit of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _limit_latex_ sage: var('x,a') (x, a) sage: f(x) = function('f',x) sage: _limit_latex_(f(x), x, a) '\\lim_{x \\to a}\\, f\\left(x\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-15) """ # Read f,x,a from arguments f = args[0] x = args[1] a = args[2] return "\\lim_{%s \\to %s}\\, %s"%(latex(x), latex(a), latex(f))
|
|
def _integrate_latex_(*args):
|
def _integrate_latex_(self, f, x, *args):
|
def _integrate_latex_(*args): r""" Return LaTeX expression for integration of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _integrate_latex_ sage: var('x,a,b') (x, a, b) sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x) '\\int f\\left(x\\right)\\,{d x}' sage: _integrate_latex_(f(x),x,a,b) '\\int_{a}^{b} f\\left(x\\right)\\,{d x}' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ f = args[0] x = args[1] # Check whether its a definite integral if len(args) == 4: a = args[2] b = args[3] return "\\int_{%s}^{%s} %s\\,{d %s}"%(latex(a), latex(b), latex(f), latex(x)) # Typeset as indefinite integral return "\\int %s\\,{d %s}"%(latex(f), latex(x))
|
sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x)
|
sage: f = function('f',x) sage: _integrate_latex_(0,f,x)
|
def _integrate_latex_(*args): r""" Return LaTeX expression for integration of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _integrate_latex_ sage: var('x,a,b') (x, a, b) sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x) '\\int f\\left(x\\right)\\,{d x}' sage: _integrate_latex_(f(x),x,a,b) '\\int_{a}^{b} f\\left(x\\right)\\,{d x}' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ f = args[0] x = args[1] # Check whether its a definite integral if len(args) == 4: a = args[2] b = args[3] return "\\int_{%s}^{%s} %s\\,{d %s}"%(latex(a), latex(b), latex(f), latex(x)) # Typeset as indefinite integral return "\\int %s\\,{d %s}"%(latex(f), latex(x))
|
sage: _integrate_latex_(f(x),x,a,b)
|
sage: _integrate_latex_(0,f,x,a,b)
|
def _integrate_latex_(*args): r""" Return LaTeX expression for integration of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _integrate_latex_ sage: var('x,a,b') (x, a, b) sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x) '\\int f\\left(x\\right)\\,{d x}' sage: _integrate_latex_(f(x),x,a,b) '\\int_{a}^{b} f\\left(x\\right)\\,{d x}' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ f = args[0] x = args[1] # Check whether its a definite integral if len(args) == 4: a = args[2] b = args[3] return "\\int_{%s}^{%s} %s\\,{d %s}"%(latex(a), latex(b), latex(f), latex(x)) # Typeset as indefinite integral return "\\int %s\\,{d %s}"%(latex(f), latex(x))
|
f = args[0] x = args[1]
|
def _integrate_latex_(*args): r""" Return LaTeX expression for integration of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _integrate_latex_ sage: var('x,a,b') (x, a, b) sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x) '\\int f\\left(x\\right)\\,{d x}' sage: _integrate_latex_(f(x),x,a,b) '\\int_{a}^{b} f\\left(x\\right)\\,{d x}' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ f = args[0] x = args[1] # Check whether its a definite integral if len(args) == 4: a = args[2] b = args[3] return "\\int_{%s}^{%s} %s\\,{d %s}"%(latex(a), latex(b), latex(f), latex(x)) # Typeset as indefinite integral return "\\int %s\\,{d %s}"%(latex(f), latex(x))
|
|
if len(args) == 4: a = args[2] b = args[3]
|
if len(args) == 2: a, b = args
|
def _integrate_latex_(*args): r""" Return LaTeX expression for integration of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _integrate_latex_ sage: var('x,a,b') (x, a, b) sage: f(x) = function('f',x) sage: _integrate_latex_(f(x),x) '\\int f\\left(x\\right)\\,{d x}' sage: _integrate_latex_(f(x),x,a,b) '\\int_{a}^{b} f\\left(x\\right)\\,{d x}' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ f = args[0] x = args[1] # Check whether its a definite integral if len(args) == 4: a = args[2] b = args[3] return "\\int_{%s}^{%s} %s\\,{d %s}"%(latex(a), latex(b), latex(f), latex(x)) # Typeset as indefinite integral return "\\int %s\\,{d %s}"%(latex(f), latex(x))
|
def _laplace_latex_(*args):
|
def _laplace_latex_(self, *args):
|
def _laplace_latex_(*args): r""" Return LaTeX expression for Laplace transform of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _laplace_latex_ sage: var('s,t') (s, t) sage: f(t) = function('f',t) sage: _laplace_latex_(f(t),t,s) '\\mathcal{L}\\left(f\\left(t\\right), t, s\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ return "\\mathcal{L}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
|
sage: f(t) = function('f',t) sage: _laplace_latex_(f(t),t,s)
|
sage: f = function('f',t) sage: _laplace_latex_(0,f,t,s)
|
def _laplace_latex_(*args): r""" Return LaTeX expression for Laplace transform of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _laplace_latex_ sage: var('s,t') (s, t) sage: f(t) = function('f',t) sage: _laplace_latex_(f(t),t,s) '\\mathcal{L}\\left(f\\left(t\\right), t, s\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ return "\\mathcal{L}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
|
def _inverse_laplace_latex_(*args):
|
def _inverse_laplace_latex_(self, *args):
|
def _inverse_laplace_latex_(*args): r""" Return LaTeX expression for inverse Laplace transform of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _inverse_laplace_latex_ sage: var('s,t') (s, t) sage: F(s) = function('F',s) sage: _inverse_laplace_latex_(F(s),s,t) '\\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ return "\\mathcal{L}^{-1}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
|
sage: F(s) = function('F',s) sage: _inverse_laplace_latex_(F(s),s,t)
|
sage: F = function('F',s) sage: _inverse_laplace_latex_(0,F,s,t)
|
def _inverse_laplace_latex_(*args): r""" Return LaTeX expression for inverse Laplace transform of a symbolic function. EXAMPLES:: sage: from sage.calculus.calculus import _inverse_laplace_latex_ sage: var('s,t') (s, t) sage: F(s) = function('F',s) sage: _inverse_laplace_latex_(F(s),s,t) '\\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)' AUTHORS: - Golam Mortuza Hossain (2009-06-22) """ return "\\mathcal{L}^{-1}\\left(%s\\right)"%(', '.join([latex(x) for x in args]))
|
TypeError, "No lookup table provided."
|
raise TypeError("No lookup table provided.")
|
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
|
if not ZZ(len(S)).is_power_of(2): raise TypeError("Lookup table length is not a power of 2.")
|
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
|
|
length = ZZ(len(S)).exact_log(2) if length != int(length): TypeError, "lookup table length is not a power of 2." self.m = int(length)
|
self.m = ZZ(len(S)).exact_log(2)
|
def __init__(self, *args, **kwargs): """ Construct a substitution box (S-box) for a given lookup table `S`.
|
def random_element(self, prec, bound=None):
|
def random_element(self, prec=None, *args, **kwds):
|
def random_element(self, prec, bound=None): r""" Return a random power series. INPUT: - ``prec`` - an integer - ``bound`` - an integer (default: None, which tries to spread choice across ring, if implemented) OUTPUT: - ``power series`` - a power series such that the coefficient of `x^i`, for `i` up to ``degree``, are coercions to the base ring of random integers between -``bound`` and ``bound``. IMPLEMENTATION: Call the random_element method on the underlying polynomial ring. EXAMPLES:: sage: R.<t> = PowerSeriesRing(QQ) sage: R.random_element(5) -4 - 1/2*t^2 - 1/95*t^3 + 1/2*t^4 + O(t^5) sage: R.random_element(5,20) 1/15 + 19/17*t + 10/3*t^2 + 5/2*t^3 + 1/2*t^4 + O(t^5) """ return self(self.__poly_ring.random_element(prec, bound), prec)
|
- ``prec`` - an integer - ``bound`` - an integer (default: None, which tries to spread choice across ring, if implemented)
|
- ``prec`` - Integer specifying precision of output (default: default precision of self) - ``*args, **kwds`` - Passed on to the ``random_element`` method for the base ring
|
def random_element(self, prec, bound=None): r""" Return a random power series. INPUT: - ``prec`` - an integer - ``bound`` - an integer (default: None, which tries to spread choice across ring, if implemented) OUTPUT: - ``power series`` - a power series such that the coefficient of `x^i`, for `i` up to ``degree``, are coercions to the base ring of random integers between -``bound`` and ``bound``. IMPLEMENTATION: Call the random_element method on the underlying polynomial ring. EXAMPLES:: sage: R.<t> = PowerSeriesRing(QQ) sage: R.random_element(5) -4 - 1/2*t^2 - 1/95*t^3 + 1/2*t^4 + O(t^5) sage: R.random_element(5,20) 1/15 + 19/17*t + 10/3*t^2 + 5/2*t^3 + 1/2*t^4 + O(t^5) """ return self(self.__poly_ring.random_element(prec, bound), prec)
|
- ``power series`` - a power series such that the coefficient of `x^i`, for `i` up to ``degree``, are coercions to the base ring of random integers between -``bound`` and ``bound``. IMPLEMENTATION: Call the random_element method on the underlying
|
- Power series with precision ``prec`` whose coefficients are random elements from the base ring, randomized subject to the arguments ``*args`` and ``**kwds`` IMPLEMENTATION:: Call the ``random_element`` method on the underlying
|
def random_element(self, prec, bound=None): r""" Return a random power series. INPUT: - ``prec`` - an integer - ``bound`` - an integer (default: None, which tries to spread choice across ring, if implemented) OUTPUT: - ``power series`` - a power series such that the coefficient of `x^i`, for `i` up to ``degree``, are coercions to the base ring of random integers between -``bound`` and ``bound``. IMPLEMENTATION: Call the random_element method on the underlying polynomial ring. EXAMPLES:: sage: R.<t> = PowerSeriesRing(QQ) sage: R.random_element(5) -4 - 1/2*t^2 - 1/95*t^3 + 1/2*t^4 + O(t^5) sage: R.random_element(5,20) 1/15 + 19/17*t + 10/3*t^2 + 5/2*t^3 + 1/2*t^4 + O(t^5) """ return self(self.__poly_ring.random_element(prec, bound), prec)
|
sage: R.random_element(5,20) 1/15 + 19/17*t + 10/3*t^2 + 5/2*t^3 + 1/2*t^4 + O(t^5) """ return self(self.__poly_ring.random_element(prec, bound), prec)
|
sage: R.random_element(10) -1/2 + 2*t - 2/7*t^2 - 25*t^3 - t^4 + 2*t^5 - 4*t^7 - 1/3*t^8 - t^9 + O(t^10) If given no argument, random_element uses default precision of self:: sage: T = PowerSeriesRing(ZZ,'t') sage: T.default_prec() 20 sage: T.random_element() 4 + 2*t - t^2 - t^3 + 2*t^4 + t^5 + t^6 - 2*t^7 - t^8 - t^9 + t^11 - 6*t^12 + 2*t^14 + 2*t^16 - t^17 - 3*t^18 + O(t^20) sage: S = PowerSeriesRing(ZZ,'t', default_prec=4) sage: S.random_element() 2 - t - 5*t^2 + t^3 + O(t^4) Further arguments are passed to the underlying base ring (ticket sage: SZ = PowerSeriesRing(ZZ,'v') sage: SQ = PowerSeriesRing(QQ,'v') sage: SR = PowerSeriesRing(RR,'v') sage: SZ.random_element(x=4, y=6) 4 + 5*v + 5*v^2 + 5*v^3 + 4*v^4 + 5*v^5 + 5*v^6 + 5*v^7 + 4*v^8 + 5*v^9 + 4*v^10 + 4*v^11 + 5*v^12 + 5*v^13 + 5*v^14 + 5*v^15 + 5*v^16 + 5*v^17 + 4*v^18 + 5*v^19 + O(v^20) sage: SZ.random_element(3, x=4, y=6) 5 + 4*v + 5*v^2 + O(v^3) sage: SQ.random_element(3, num_bound=3, den_bound=100) 1/87 - 3/70*v - 3/44*v^2 + O(v^3) sage: SR.random_element(3, max=10, min=-10) 2.85948321262904 - 9.73071330911226*v - 6.60414378519265*v^2 + O(v^3) """ if prec is None: prec = self.default_prec() return self(self.__poly_ring.random_element(prec-1, *args, **kwds), prec)
|
def random_element(self, prec, bound=None): r""" Return a random power series. INPUT: - ``prec`` - an integer - ``bound`` - an integer (default: None, which tries to spread choice across ring, if implemented) OUTPUT: - ``power series`` - a power series such that the coefficient of `x^i`, for `i` up to ``degree``, are coercions to the base ring of random integers between -``bound`` and ``bound``. IMPLEMENTATION: Call the random_element method on the underlying polynomial ring. EXAMPLES:: sage: R.<t> = PowerSeriesRing(QQ) sage: R.random_element(5) -4 - 1/2*t^2 - 1/95*t^3 + 1/2*t^4 + O(t^5) sage: R.random_element(5,20) 1/15 + 19/17*t + 10/3*t^2 + 5/2*t^3 + 1/2*t^4 + O(t^5) """ return self(self.__poly_ring.random_element(prec, bound), prec)
|
sage: phi,theta=var('phi theta') sage: Y=spherical_harmonic(2,1,theta,phi) sage: rea=spherical_plot3d(abs(real(Y)),(phi,0,2*pi),(theta,0,pi),color='blue',opacity=0.6) sage: ima=spherical_plot3d(abs(imag(Y)),(phi,0,2*pi),(theta,0,pi),color='red' ,opacity=0.6) sage: (rea+ima).show(aspect_ratio=1)
|
sage: phi, theta = var('phi, theta') sage: Y = spherical_harmonic(2, 1, theta, phi) sage: rea = spherical_plot3d(abs(real(Y)), (phi,0,2*pi), (theta,0,pi), color='blue', opacity=0.6) sage: ima = spherical_plot3d(abs(imag(Y)), (phi,0,2*pi), (theta,0,pi), color='red', opacity=0.6) sage: (rea + ima).show(aspect_ratio=1)
|
def spherical_plot3d(f, urange, vrange, **kwds): """ Plots a function in spherical coordinates. This function is equivalent to:: sage: r,u,v=var('r,u,v') sage: f=u*v; urange=(u,0,pi); vrange=(v,0,pi) sage: T = (r*cos(u)*sin(v), r*sin(u)*sin(v), r*cos(v), [u,v]) sage: plot3d(f, urange, vrange, transformation=T) or equivalently:: sage: T = Spherical('radius', ['azimuth', 'inclination']) sage: f=lambda u,v: u*v; urange=(u,0,pi); vrange=(v,0,pi) sage: plot3d(f, urange, vrange, transformation=T) INPUT: - ``f`` - a symbolic expression or function of two variables. - ``urange`` - a 3-tuple (u, u_min, u_max), the domain of the azimuth variable. - ``vrange`` - a 3-tuple (v, v_min, v_max), the domain of the inclination variable. EXAMPLES: A sphere of radius 2:: sage: x,y=var('x,y') sage: spherical_plot3d(2,(x,0,2*pi),(y,0,pi)) The real and imaginary parts of a spherical harmonic with `l=2` and `m=1`:: sage: phi,theta=var('phi theta') sage: Y=spherical_harmonic(2,1,theta,phi) sage: rea=spherical_plot3d(abs(real(Y)),(phi,0,2*pi),(theta,0,pi),color='blue',opacity=0.6) sage: ima=spherical_plot3d(abs(imag(Y)),(phi,0,2*pi),(theta,0,pi),color='red' ,opacity=0.6) sage: (rea+ima).show(aspect_ratio=1) A drop of water:: sage: x,y=var('x,y') sage: spherical_plot3d(e^-y,(x,0,2*pi),(y,0,pi),opacity=0.5).show(frame=False) An object similar to a heart:: sage: x,y=var('x,y') sage: spherical_plot3d((2+cos(2*x))*(y+1),(x,0,2*pi),(y,0,pi),rgbcolor=(1,.1,.1)) Some random figures: :: sage: x,y=var('x,y') sage: spherical_plot3d(1+sin(5*x)/5,(x,0,2*pi),(y,0,pi),rgbcolor=(1,0.5,0),plot_points=(80,80),opacity=0.7) :: sage: x,y=var('x,y') sage: spherical_plot3d(1+2*cos(2*y),(x,0,3*pi/2),(y,0,pi)).show(aspect_ratio=(1,1,1)) """ return plot3d(f, urange, vrange, transformation=Spherical('radius', ['azimuth', 'inclination']), **kwds)
|
sage: m = matrix(3, lambda i,j: i-j)
|
sage: m = matrix(3, lambda i,j: i-j); m
|
def matrix(*args, **kwds): """ Create a matrix. INPUT: The matrix command takes the entries of a matrix, optionally preceded by a ring and the dimensions of the matrix, and returns a matrix. The entries of a matrix can be specified as a flat list of elements, a list of lists (i.e., a list of rows), a list of Sage vectors, a callable object, or a dictionary having positions as keys and matrix entries as values (see the examples). If you pass in a callable object, then you must specify the number of rows and columns. You can create a matrix of zeros by passing an empty list or the integer zero for the entries. To construct a multiple of the identity (`cI`), you can specify square dimensions and pass in `c`. Calling matrix() with a Sage object may return something that makes sense. Calling matrix() with a NumPy array will convert the array to a matrix. The ring, number of rows, and number of columns of the matrix can be specified by setting the ring, nrows, or ncols parameters or by passing them as the first arguments to the function in the order ring, nrows, ncols. The ring defaults to ZZ if it is not specified or cannot be determined from the entries. If the numbers of rows and columns are not specified and cannot be determined, then an empty 0x0 matrix is returned. - ``ring`` - the base ring for the entries of the matrix. - ``nrows`` - the number of rows in the matrix. - ``ncols`` - the number of columns in the matrix. - ``sparse`` - create a sparse matrix. This defaults to True when the entries are given as a dictionary, otherwise defaults to False. OUTPUT: a matrix EXAMPLES:: sage: m=matrix(2); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring :: sage: m=matrix(2,3); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring :: sage: m=matrix(QQ,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m = matrix(QQ, 3, 3, lambda i, j: i+j); m [0 1 2] [1 2 3] [2 3 4] sage: m = matrix(3, lambda i,j: i-j) [ 0 -1 -2] [ 1 0 -1] [ 2 1 0] :: sage: v1=vector((1,2,3)) sage: v2=vector((4,5,6)) sage: m=matrix([v1,v2]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring :: sage: m=matrix(QQ,2,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m=matrix(QQ,2,3,[1,2,3,4,5,6]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field :: sage: m=matrix({(0,1): 2, (1,1):2/5}); m; m.parent() [ 0 2] [ 0 2/5] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field :: sage: m=matrix(QQ,2,3,{(1,1): 2}); m; m.parent() [0 0 0] [0 2 0] Full MatrixSpace of 2 by 3 sparse matrices over Rational Field :: sage: import numpy sage: n=numpy.array([[1,2],[3,4]],float) sage: m=matrix(n); m; m.parent() [1.0 2.0] [3.0 4.0] Full MatrixSpace of 2 by 2 dense matrices over Real Double Field :: sage: v = vector(ZZ, [1, 10, 100]) sage: m=matrix(v); m; m.parent() [ 1 10 100] Full MatrixSpace of 1 by 3 dense matrices over Integer Ring sage: m=matrix(GF(7), v); m; m.parent() [1 3 2] Full MatrixSpace of 1 by 3 dense matrices over Finite Field of size 7 :: sage: g = graphs.PetersenGraph() sage: m = matrix(g); m; m.parent() [0 1 0 0 1 1 0 0 0 0] [1 0 1 0 0 0 1 0 0 0] [0 1 0 1 0 0 0 1 0 0] [0 0 1 0 1 0 0 0 1 0] [1 0 0 1 0 0 0 0 0 1] [1 0 0 0 0 0 0 1 1 0] [0 1 0 0 0 0 0 0 1 1] [0 0 1 0 0 1 0 0 0 1] [0 0 0 1 0 1 1 0 0 0] [0 0 0 0 1 0 1 1 0 0] Full MatrixSpace of 10 by 10 dense matrices over Integer Ring :: sage: matrix(ZZ, 10, 10, range(100), sparse=True).parent() Full MatrixSpace of 10 by 10 sparse matrices over Integer Ring :: sage: R = PolynomialRing(QQ, 9, 'x') sage: A = matrix(R, 3, 3, R.gens()); A [x0 x1 x2] [x3 x4 x5] [x6 x7 x8] sage: det(A) -x2*x4*x6 + x1*x5*x6 + x2*x3*x7 - x0*x5*x7 - x1*x3*x8 + x0*x4*x8 TESTS:: sage: m=matrix(); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(QQ); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Rational Field sage: m=matrix(QQ,2); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 dense matrices over Rational Field sage: m=matrix(QQ,2,3); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix([]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(QQ,[]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Rational Field sage: m=matrix(2,2,1); m; m.parent() [1 0] [0 1] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring sage: m=matrix(QQ,2,2,1); m; m.parent() [1 0] [0 1] Full MatrixSpace of 2 by 2 dense matrices over Rational Field sage: m=matrix(2,3,0); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix(QQ,2,3,0); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix([[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix(QQ,2,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix(QQ,3,[[1,2,3],[4,5,6]]); m; m.parent() Traceback (most recent call last): ... ValueError: Number of rows does not match up with specified number. sage: m=matrix(QQ,2,3,[[1,2,3],[4,5,6]]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Rational Field sage: m=matrix(QQ,2,4,[[1,2,3],[4,5,6]]); m; m.parent() Traceback (most recent call last): ... ValueError: Number of columns does not match up with specified number. sage: m=matrix([(1,2,3),(4,5,6)]); m; m.parent() [1 2 3] [4 5 6] Full MatrixSpace of 2 by 3 dense matrices over Integer Ring sage: m=matrix([1,2,3,4,5,6]); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Integer Ring sage: m=matrix((1,2,3,4,5,6)); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Integer Ring sage: m=matrix(QQ,[1,2,3,4,5,6]); m; m.parent() [1 2 3 4 5 6] Full MatrixSpace of 1 by 6 dense matrices over Rational Field sage: m=matrix(QQ,3,2,[1,2,3,4,5,6]); m; m.parent() [1 2] [3 4] [5 6] Full MatrixSpace of 3 by 2 dense matrices over Rational Field sage: m=matrix(QQ,2,4,[1,2,3,4,5,6]); m; m.parent() Traceback (most recent call last): ... ValueError: entries has the wrong length sage: m=matrix(QQ,5,[1,2,3,4,5,6]); m; m.parent() Traceback (most recent call last): ... TypeError: entries has the wrong length sage: m=matrix({(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Integer Ring sage: m=matrix(QQ,{(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,3,{(1,1): 2}); m; m.parent() [0 0 0] [0 2 0] [0 0 0] Full MatrixSpace of 3 by 3 sparse matrices over Rational Field sage: m=matrix(QQ,3,4,{(1,1): 2}); m; m.parent() [0 0 0 0] [0 2 0 0] [0 0 0 0] Full MatrixSpace of 3 by 4 sparse matrices over Rational Field sage: m=matrix(QQ,2,{(1,1): 2}); m; m.parent() [0 0] [0 2] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,1,{(1,1): 2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: m=matrix({}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Integer Ring sage: m=matrix(QQ,{}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Rational Field sage: m=matrix(QQ,2,{}); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 sparse matrices over Rational Field sage: m=matrix(QQ,2,3,{}); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 sparse matrices over Rational Field sage: m=matrix(2,{}); m; m.parent() [0 0] [0 0] Full MatrixSpace of 2 by 2 sparse matrices over Integer Ring sage: m=matrix(2,3,{}); m; m.parent() [0 0 0] [0 0 0] Full MatrixSpace of 2 by 3 sparse matrices over Integer Ring sage: m=matrix(0); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(0,2); m; m.parent() [] Full MatrixSpace of 0 by 2 dense matrices over Integer Ring sage: m=matrix(2,0); m; m.parent() [] Full MatrixSpace of 2 by 0 dense matrices over Integer Ring sage: m=matrix(0,[1]); m; m.parent() Traceback (most recent call last): ... ValueError: entries has the wrong length sage: m=matrix(1,0,[]); m; m.parent() [] Full MatrixSpace of 1 by 0 dense matrices over Integer Ring sage: m=matrix(0,1,[]); m; m.parent() [] Full MatrixSpace of 0 by 1 dense matrices over Integer Ring sage: m=matrix(0,[]); m; m.parent() [] Full MatrixSpace of 0 by 0 dense matrices over Integer Ring sage: m=matrix(0,{}); m; m.parent() [] Full MatrixSpace of 0 by 0 sparse matrices over Integer Ring sage: m=matrix(0,{(1,1):2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: m=matrix(2,0,{(1,1):2}); m; m.parent() Traceback (most recent call last): ... IndexError: invalid entries list sage: import numpy sage: n=numpy.array([[numpy.complex(0,1),numpy.complex(0,2)],[3,4]],complex) sage: m=matrix(n); m; m.parent() [1.0*I 2.0*I] [ 3.0 4.0] Full MatrixSpace of 2 by 2 dense matrices over Complex Double Field sage: n=numpy.array([[1,2],[3,4]],'int32') sage: m=matrix(n); m; m.parent() [1 2] [3 4] Full MatrixSpace of 2 by 2 dense matrices over Integer Ring sage: n = numpy.array([[1,2,3],[4,5,6],[7,8,9]],'float32') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Real Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'float64') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Real Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'complex64') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Complex Double Field sage: n=numpy.array([[1,2,3],[4,5,6],[7,8,9]],'complex128') sage: m=matrix(n); m; m.parent() [1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0] Full MatrixSpace of 3 by 3 dense matrices over Complex Double Field sage: a = matrix([[1,2],[3,4]]) sage: b = matrix(a.numpy()); b [1 2] [3 4] sage: a == b True sage: c = matrix(a.numpy('float32')); c [1.0 2.0] [3.0 4.0] sage: matrix(numpy.array([[5]])) [5] sage: v = vector(ZZ, [1, 10, 100]) sage: m=matrix(ZZ['x'], v); m; m.parent() [ 1 10 100] Full MatrixSpace of 1 by 3 dense matrices over Univariate Polynomial Ring in x over Integer Ring sage: matrix(ZZ, 10, 10, range(100)).parent() Full MatrixSpace of 10 by 10 dense matrices over Integer Ring sage: m = matrix(GF(7), [[1/3,2/3,1/2], [3/4,4/5,7]]); m; m.parent() [5 3 4] [6 5 0] Full MatrixSpace of 2 by 3 dense matrices over Finite Field of size 7 sage: m = matrix([[1,2,3], [RDF(2), CDF(1,2), 3]]); m; m.parent() [ 1.0 2.0 3.0] [ 2.0 1.0 + 2.0*I 3.0] Full MatrixSpace of 2 by 3 dense matrices over Complex Double Field sage: m=matrix(3,3,1/2); m; m.parent() [1/2 0 0] [ 0 1/2 0] [ 0 0 1/2] Full MatrixSpace of 3 by 3 dense matrices over Rational Field sage: matrix([[1],[2,3]]) Traceback (most recent call last): ... ValueError: List of rows is not valid (rows are wrong types or lengths) sage: matrix([[1],2]) Traceback (most recent call last): ... ValueError: List of rows is not valid (rows are wrong types or lengths) sage: matrix(vector(RR,[1,2,3])).parent() Full MatrixSpace of 1 by 3 dense matrices over Real Field with 53 bits of precision AUTHORS: - ??: Initial implementation - Jason Grout (2008-03): almost a complete rewrite, with bits and pieces from the original implementation """ args = list(args) sparse = kwds.get('sparse',False) # if the first object already knows how to make itself into a # matrix, try that, defaulting to a matrix over the integers. if len(args) == 1 and hasattr(args[0], '_matrix_'): try: return args[0]._matrix_(sparse=sparse) except TypeError: return args[0]._matrix_() elif len(args) == 2: if hasattr(args[0], '_matrix_'): try: return args[0]._matrix_(args[1], sparse=sparse) except TypeError: return args[0]._matrix_(args[1]) elif hasattr(args[1], '_matrix_'): try: return args[1]._matrix_(args[0], sparse=sparse) except TypeError: return args[1]._matrix_(args[0]) if len(args) == 0: # if nothing was passed return the empty matrix over the # integer ring. return matrix_space.MatrixSpace(rings.ZZ, 0, 0, sparse=sparse)([]) if len(args) >= 1 and rings.is_Ring(args[0]): # A ring is specified if kwds.get('ring', args[0]) != args[0]: raise ValueError, "Specified rings are not the same" else: ring = args[0] args.pop(0) else: ring = kwds.get('ring', None) if len(args) >= 1: # check to see if the number of rows is specified try: import numpy if isinstance(args[0], numpy.ndarray): raise TypeError nrows = int(args[0]) args.pop(0) if kwds.get('nrows', nrows) != nrows: raise ValueError, "Number of rows specified in two places and they are not the same" except TypeError: nrows = kwds.get('nrows', None) else: nrows = kwds.get('nrows', None) if len(args) >= 1: # check to see if additionally, the number of columns is specified try: import numpy if isinstance(args[0], numpy.ndarray): raise TypeError ncols = int(args[0]) args.pop(0) if kwds.get('ncols', ncols) != ncols: raise ValueError, "Number of columns specified in two places and they are not the same" except TypeError: ncols = kwds.get('ncols', None) else: ncols = kwds.get('ncols', None) # Now we've taken care of initial ring, nrows, and ncols arguments. # We've also taken care of the Sage object case. # Now the rest of the arguments are a list of rows, a flat list of # entries, a callable, a dict, a numpy array, or a single value. if len(args) == 0: # If no entries are specified, pass back a zero matrix entries = 0 entry_ring = rings.ZZ elif len(args) == 1: if isinstance(args[0], (types.FunctionType, types.LambdaType, types.MethodType)): if ncols is None and nrows is None: raise ValueError, "When passing in a callable, the dimensions of the matrix must be specified" if ncols is None: ncols = nrows else: nrows = ncols f = args[0] args[0] = [[f(i,j) for j in range(ncols)] for i in range(nrows)] if isinstance(args[0], (list, tuple)): if len(args[0]) == 0: # no entries are specified, pass back the zero matrix entries = 0 entry_ring = rings.ZZ elif isinstance(args[0][0], (list, tuple)) or is_Vector(args[0][0]): # Ensure we have a list of lists, each inner list having the same number of elements first_len = len(args[0][0]) if not all( (isinstance(v, (list, tuple)) or is_Vector(v)) and len(v) == first_len for v in args[0]): raise ValueError, "List of rows is not valid (rows are wrong types or lengths)" # We have a list of rows or vectors if nrows is None: nrows = len(args[0]) elif nrows != len(args[0]): raise ValueError, "Number of rows does not match up with specified number." if ncols is None: ncols = len(args[0][0]) elif ncols != len(args[0][0]): raise ValueError, "Number of columns does not match up with specified number." entries = sum([list(v) for v in args[0]], []) else: # We have a flat list; figure out nrows and ncols if nrows is None: nrows = 1 if nrows > 0: if ncols is None: ncols = len(args[0]) // nrows elif ncols != len(args[0]) // nrows: raise ValueError, "entries has the wrong length" elif len(args[0]) > 0: raise ValueError, "entries has the wrong length" entries = args[0] if nrows > 0 and ncols > 0 and ring is None: entries, ring = prepare(entries) elif isinstance(args[0], dict): # We have a dictionary # default to sparse sparse = kwds.get('sparse', True) if len(args[0]) == 0: # no entries are specified, pass back the zero matrix entries = 0 else: entries, entry_ring = prepare_dict(args[0]) if nrows is None: nrows = nrows_from_dict(entries) ncols = ncols_from_dict(entries) # note that ncols can still be None if nrows is set -- # it will be assigned nrows down below. # See the construction after the numpy case below. else: import numpy if isinstance(args[0], numpy.ndarray): num_array = args[0] str_dtype = str(num_array.dtype) if not( num_array.flags.c_contiguous is True or num_array.flags.f_contiguous is True): raise TypeError('numpy matrix must be either c_contiguous or f_contiguous') if str_dtype.count('float32')==1: m=matrix(RDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy32(num_array) elif str_dtype.count('float64')==1: m=matrix(RDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy(num_array) elif str_dtype.count('complex64')==1: m=matrix(CDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy32(num_array) elif str_dtype.count('complex128')==1: m=matrix(CDF,num_array.shape[0],num_array.shape[1],0) m._replace_self_with_numpy(num_array) elif str_dtype.count('int') == 1: m = matrix(ZZ, [list(row) for row in list(num_array)]) elif str_dtype.count('object') == 1: #Get the raw nested list from the numpy array #and feed it back into matrix try: return matrix( [list(row) for row in list(num_array)]) except TypeError: raise TypeError("cannot convert NumPy matrix to Sage matrix") else: raise TypeError("cannot convert NumPy matrix to Sage matrix") return m elif nrows is not None and ncols is not None: # assume that we should just pass the thing into the # MatrixSpace constructor and hope for the best # This is not documented, but it is doctested if ring is None: entry_ring = args[0].parent() entries = args[0] else: raise ValueError, "Invalid matrix constructor. Type matrix? for help" else: raise ValueError, "Invalid matrix constructor. Type matrix? for help" if nrows is None: nrows = 0 if ncols is None: ncols = nrows if ring is None: try: ring = entry_ring except NameError: ring = rings.ZZ return matrix_space.MatrixSpace(ring, nrows, ncols, sparse=sparse)(entries)
|
if self.ambient_vector_space() != other.ambient_vector_space(): return False if other == other.ambient_vector_space(): return True
|
try: if self.ambient_vector_space() != other.ambient_vector_space(): return False if other == other.ambient_vector_space(): return True except AttributeError: pass
|
def is_submodule(self, other): """ Return True if self is a submodule of other. EXAMPLES:: sage: M = FreeModule(ZZ,3) sage: V = M.ambient_vector_space() sage: X = V.span([[1/2,1/2,0],[1/2,0,1/2]], ZZ) sage: Y = V.span([[1,1,1]], ZZ) sage: N = X + Y sage: M.is_submodule(X) False sage: M.is_submodule(Y) False sage: Y.is_submodule(M) True sage: N.is_submodule(M) False sage: M.is_submodule(N) True Since basis() is not implemented in general, submodule testing does not work for all PID's. However, trivial cases are already used (and useful) for coercion, e.g. :: sage: QQ(1/2) * vector(ZZ['x']['y'],[1,2,3,4]) (1/2, 1, 3/2, 2) sage: vector(ZZ['x']['y'],[1,2,3,4]) * QQ(1/2) (1/2, 1, 3/2, 2) """ if not isinstance(other, FreeModule_generic): return False if self.ambient_vector_space() != other.ambient_vector_space(): return False if other == other.ambient_vector_space(): return True if other.rank() < self.rank(): return False if self.base_ring() != other.base_ring(): try: if not self.base_ring().is_subring(other.base_ring()): return False except NotImplementedError: return False for b in self.basis(): if not (b in other): return False return True
|
"""
|
Multi-edged and looped graphs are partially supported:: sage: G = Graph({0:[1,1]}, multiedges=True) sage: G.is_planar() True sage: G.is_planar(on_embedding={}) Traceback (most recent call last): ... NotImplementedError: Cannot compute with embeddings of multiple-edged or looped graphs. sage: G.is_planar(set_pos=True) Traceback (most recent call last): ... NotImplementedError: Cannot compute with embeddings of multiple-edged or looped graphs. sage: G.is_planar(set_embedding=True) Traceback (most recent call last): ... NotImplementedError: Cannot compute with embeddings of multiple-edged or looped graphs. sage: G.is_planar(kuratowski=True) (True, None) :: sage: G = graphs.CompleteGraph(5) sage: G = Graph(G, multiedges=True) sage: G.add_edge(0,1) sage: G.is_planar() False sage: b,k = G.is_planar(kuratowski=True) sage: b False sage: k.vertices() [0, 1, 2, 3, 4] """ if self.has_multiple_edges() or self.has_loops(): if set_embedding or (on_embedding is not None) or set_pos: raise NotImplementedError("Cannot compute with embeddings of multiple-edged or looped graphs.") else: return self.to_simple().is_planar(kuratowski=kuratowski)
|
def is_planar(self, on_embedding=None, kuratowski=False, set_embedding=False, set_pos=False): """ Returns True if the graph is planar, and False otherwise. This wraps the reference implementation provided by John Boyer of the linear time planarity algorithm by edge addition due to Boyer Myrvold. (See reference code in graphs.planarity). Note - the argument on_embedding takes precedence over set_embedding. This means that only the on_embedding combinatorial embedding will be tested for planarity and no _embedding attribute will be set as a result of this function call, unless on_embedding is None. REFERENCE:
|
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.
|
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.
|
Return a generator object for the rational points on this curve. INPUT: - ``self`` -- a projective curve
|
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
|
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) sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) sage: C = Curve(X^7+Y*X*Z^5*55+Y^7*12) sage: len(list(C.rational_points_iterator())) 37 :: sage: F = GF(2)
|
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
|
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: F = GF(1009) sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) 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.
|
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)]
|
sage: F = GF(3^2,'a') sage: P2.<X,Y,Z> = ProjectiveSpace(F,2) 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.
|
points = []
|
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
|
|
points.append(self.point([one,zero,zero])) except TypeError:
|
t = self.point([one,zero,zero]) yield(t) except TypeError:
|
def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration.
|
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.
|
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.
|
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.
|
[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.
|
[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.
|
variables x,y::
|
variables `x`, `y`::
|
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
|
sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'])
|
:: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: P :: sage: P=contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],\ ... linewidths=[1,5],linestyles=['solid','dashed']) sage: P
|
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
|
sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False)
|
sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',\ ... labels=True, label_fmt="%1.0f", label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv',labels=True,\ ... contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: P :: sage: P=contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: P :: sage: P= contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), \ ... fill=False, cmap='hsv', labels=True, label_inline=False) sage: P
|
def contour_plot(f, xrange, yrange, **options): r""" ``contour_plot`` takes a function of two variables, `f(x,y)` and plots contour lines of the function over the specified ``xrange`` and ``yrange`` as demonstrated below. ``contour_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` The following inputs must all be passed in as named parameters: - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid. For old computers, 25 is fine, but should not be used to verify specific intersection points. - ``fill`` -- bool (default: ``True``), whether to color in the area between contour lines - ``cmap`` -- a colormap (default: ``'gray'``), the name of a predefined colormap, a list of colors or an instance of a matplotlib Colormap. Type: ``import matplotlib.cm; matplotlib.cm.datad.keys()`` for available colormap names. - ``contours`` -- integer or list of numbers (default: ``None``): If a list of numbers is given, then this specifies the contour levels to use. If an integer is given, then this many contour lines are used, but the exact levels are determined automatically. If ``None`` is passed (or the option is not given), then the number of contour lines is determined automatically, and is usually about 5. - ``linewidths`` -- integer or list of integer (default: None), if a single integer all levels will be of the width given, otherwise the levels will be plotted with the width in the order given. If the list is shorter than the number of contours, then the widths will be repeated cyclically. - ``linestyles`` -- string or list of strings (default: None), the style of the lines to be plotted, one of: solid, dashed, dashdot, or dotted. If the list is shorter than the number of contours, then the styles will be repeated cyclically. - ``labels`` -- boolean (default: False) Show level labels or not. The following options are to adjust the style and placement of labels, they have no effect if no labels are shown. - ``label_fontsize`` -- integer (default: 9), the font size of the labels. - ``label_colors`` -- string or sequence of colors (default: None) If a string, gives the name of a single color with which to draw all labels. If a sequence, gives the colors of the labels. A color is a string giving the name of one or a 3-tuple of floats. - ``label_inline`` -- boolean (default: False if fill is True, otherwise True), controls whether the underlying contour is removed or not. - ``label_inline_spacing`` -- integer (default: 3), When inline, this is the amount of contour that is removed from each side, in pixels. - ``label_fmt`` -- a format string (default: "%1.2f"), this is used to get the label text from the level. This can also be a dictionary with the contour levels as keys and corresponding text string labels as values. EXAMPLES: Here we plot a simple function of two variables. Note that since the input function is an expression, we need to explicitly declare the variables in 3-tuples for the range:: sage: x,y = var('x,y') sage: contour_plot(cos(x^2+y^2), (x, -4, 4), (y, -4, 4)) Here we change the ranges and add some options:: sage: x,y = var('x,y') sage: contour_plot((x^2)*cos(x*y), (x, -10, 5), (y, -5, 5), fill=False, plot_points=150) An even more complicated plot:: sage: x,y = var('x,y') sage: contour_plot(sin(x^2 + y^2)*cos(x)*sin(y), (x, -4, 4), (y, -4, 4),plot_points=150) Some elliptic curves, but with symbolic endpoints. In the first example, the plot is rotated 90 degrees because we switch the variables x,y:: sage: x,y = var('x,y') sage: contour_plot(y^2 + 1 - x^3 - x, (y,-pi,pi), (x,-pi,pi)) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi)) We can play with the contour levels:: sage: x,y = var('x,y') sage: f(x,y) = x^2 + y^2 sage: contour_plot(f, (-2, 2), (-2, 2)) sage: contour_plot(f, (-2, 2), (-2, 2), contours=2, cmap=[(1,0,0), (0,1,0), (0,0,1)]) sage: contour_plot(f, (-2, 2), (-2, 2), contours=(0.1, 1.0, 1.2, 1.4), cmap='hsv') sage: contour_plot(f, (-2, 2), (-2, 2), contours=(1.0,), fill=False, aspect_ratio=1) sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,0,1]) We can change the style of the lines:: sage: contour_plot(f, (-2,2), (-2,2), fill=False, linewidths=10) sage: contour_plot(f, (-2,2), (-2,2), fill=False, linestyles='dashdot') sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed'],fill=False) sage: contour_plot(x^2-y^2,(x,-3,3),(y,-3,3),contours=[0,1,2,3,4],linewidths=[1,5],linestyles=['solid','dashed']) We can add labels and play with them:: sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fmt="%1.0f", label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, contours=[-4,0,4], label_fmt={-4:"low", 0:"medium", 4: "hi"}, label_colors='black') sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_fontsize=18) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline_spacing=1) sage: contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), fill=False, cmap='hsv', labels=True, label_inline=False) If fill is True (the default), then we may have to color the labels so that we can see them:: sage: contour_plot(f, (-2,2), (-2,2), labels=True, label_colors='red') This should plot concentric circles centered at the origin:: sage: x,y = var('x,y') sage: contour_plot(x^2+y^2-2,(x,-1,1), (y,-1,1)).show(aspect_ratio=1) Extra options will get passed on to show(), as long as they are valid:: sage: f(x, y) = cos(x) + sin(y) sage: contour_plot(f, (0, pi), (0, pi), axes=True) sage: contour_plot(f, (0, pi), (0, pi)).show(axes=True) # These are equivalent Note that with ``fill=False`` and grayscale contours, there is the possibility of confusion between the contours and the axes, so use ``fill=False`` together with ``axes=True`` with caution:: sage: contour_plot(f, (-pi, pi), (-pi, pi), fill=False, axes=True) TESTS: To check that ticket 5221 is fixed, note that this has three curves, not two:: sage: x,y = var('x,y') sage: contour_plot(x-y^2,(x,-5,5),(y,-3,3),contours=[-4,-2,0], fill=False) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid g, ranges = setup_for_eval_on_grid([f], [xrange, yrange], options['plot_points']) g = g[0] xrange,yrange=[r[:2] for r in ranges] xy_data_array = [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, options)) return g
|
This function is an automatic generated pexpect wrapper around the Singular
|
This function is an automatically generated pexpect wrapper around the Singular
|
def _sage_doc_(self): """ EXAMPLES:: sage: 'groebner' in singular.groebner._sage_doc_() True """ if not nodes: generate_docstring_dictionary()
|
sage: F = e.formal_group().group_law(5); F t1 + O(t1^5) + (1 - 2*t1^4 + O(t1^5))*t2 + (-4*t1^3 + O(t1^5))*t2^2 + (-4*t1^2 - 30*t1^4 + O(t1^5))*t2^3 + (-2*t1 - 30*t1^3 + O(t1^5))*t2^4 + O(t2^5) sage: i = e.formal_group().inverse(5)
|
sage: e.formal_group().group_law(5) t1 + O(t1^5) + (1 - 2*t1^4 + O(t1^5))*t2 + (-4*t1^3 + O(t1^5))*t2^2 + (-4*t1^2 - 30*t1^4 + O(t1^5))*t2^3 + (-2*t1 - 30*t1^3 + O(t1^5))*t2^4 + O(t2^5) sage: e = EllipticCurve('14a1') sage: ehat = e.formal() sage: ehat.group_law(3) t1 + O(t1^3) + (1 - t1 - 4*t1^2 + O(t1^3))*t2 + (-4*t1 + O(t1^3))*t2^2 + O(t2^3) sage: ehat.group_law(5) t1 + O(t1^5) + (1 - t1 - 2*t1^3 - 32*t1^4 + O(t1^5))*t2 + (-3*t1^2 - 59*t1^3 - 120*t1^4 + O(t1^5))*t2^2 + (-2*t1 - 59*t1^2 - 141*t1^3 - 347*t1^4 + O(t1^5))*t2^3 + (-32*t1 - 120*t1^2 - 347*t1^3 - 951*t1^4 + O(t1^5))*t2^4 + O(t2^5) sage: e = EllipticCurve(GF(7),[3,4]) sage: ehat = e.formal() sage: ehat.group_law(3) t1 + O(t1^3) + (1 + O(t1^3))*t2 + O(t2^3) sage: F = ehat.group_law(7); F t1 + O(t1^7) + (1 + t1^4 + 2*t1^6 + O(t1^7))*t2 + (2*t1^3 + 6*t1^5 + O(t1^7))*t2^2 + (2*t1^2 + 3*t1^4 + 2*t1^6 + O(t1^7))*t2^3 + (t1 + 3*t1^3 + 4*t1^5 + O(t1^7))*t2^4 + (6*t1^2 + 4*t1^4 + O(t1^7))*t2^5 + (2*t1 + 2*t1^3 + O(t1^7))*t2^6 + O(t2^7) TESTS:: sage: i = e.formal_group().inverse(7)
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
O(t^5)
|
O(t^7)
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
t1 + O(t1^4) + (1 + O(t1^4))*t2 + (-4*t1^3 + O(t1^4))*t2^2 + (-4*t1^2 + O(t1^4))*t2^3 + O(t2^4)
|
t1 + O(t1^4) + (1 + O(t1^4))*t2 + (2*t1^3 + O(t1^4))*t2^2 + (2*t1^2 + O(t1^4))*t2^3 + O(t2^4) Test for trac ticket 9646:: sage: P.<a1, a2, a3, a4, a6> = PolynomialRing(ZZ, 5) sage: E = EllipticCurve(list(P.gens())) sage: F = E.formal().group_law(prec = 4) sage: t2 = F.parent().gen() sage: t1 = F.parent().base_ring().gen() sage: F(t1, 0) t1 sage: F(0, t2) t2 sage: F[2][1] -a2
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
if prec == 1: return R2(O(t2)) elif prec == 2: return R2(t1+t2 - self.curve().a1()*t1*t2)
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
|
w = self.w(prec)
|
w = self.w(prec+1)
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
lam = sum([tsum(n)*w[n] for n in range(3,prec)]) w1 = R1(w, prec)
|
lam = sum([tsum(n)*w[n] for n in range(3,prec+1)]) w1 = R1(w, prec+1)
|
def group_law(self, prec=10): r""" The formal group law. INPUT: - ``prec`` - integer (default 10) OUTPUT: a power series with given precision in ZZ[[ ZZ[['t1']],'t2']] DETAILS: Return the formal power series .. math:: F(t_1, t_2) = t_1 + t_2 - a_1 t_1 t_2 - \cdots to precision `O(t^{prec})` of page 115 of [Silverman AEC1]. The result is cached, and a cached version is returned if possible. .. warning::
|
occured. Please put there the version of sageq at the time of deprecation.
|
occurred. Please put there the version of sage at the time of deprecation.
|
def deprecation(message, version=None): r""" Issue a deprecation warning. INPUT: - ``message`` - an explanation why things are deprecated and by what it should be replaced. - ``version`` - (optional) on which version and when the deprecation occured. Please put there the version of sageq at the time of deprecation. EXAMPLES:: sage: def foo(): ... sage.misc.misc.deprecation("The function foo is replaced by bar.") sage: foo() doctest:...: DeprecationWarning: The function foo is replaced by bar. sage: def bar(): ... sage.misc.misc.deprecation("The function bar is removed.", ... 'Sage Version 4.2') sage: bar() doctest:...: DeprecationWarning: (Since Sage Version 4.2) The function bar is removed. """ # Stack level 3 to get the line number of the code which called # the deprecated function which called this function. if version is not None: message = "(Since " + version + ") " + message warn(message, DeprecationWarning, stacklevel=3)
|
A wrapper around methods or functions wich automatically print the correct
|
A wrapper around methods or functions which automatically print the correct
|
sage: def bar():
|
Please note that for more extensive use of R's plotting capabilities (such as the lattices package), it is advisable to either use an interactive plotting device or to use the notebook. The following examples are not tested, because they differ depending on operating system.
|
Please note that for more extensive use of R's plotting capabilities (such as the lattices package), it is advisable to either use an interactive plotting device or to use the notebook. The following examples are not tested, because they differ depending on operating system::
|
def plot(self, *args, **kwds): """ The R plot function. Type r.help('plot') for much more extensive documentation about this function. See also below for a brief introduction to more plotting with R.
|
In the notebook, one can use r.png() to open the device, but would need to use the following since R lattice graphics do not automatically print away from the command line.
|
In the notebook, one can use r.png() to open the device, but would need to use the following since R lattice graphics do not automatically print away from the command line::
|
def plot(self, *args, **kwds): """ The R plot function. Type r.help('plot') for much more extensive documentation about this function. See also below for a brief introduction to more plotting with R.
|
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
|
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
|
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."
|
if n == 1: return 1 for p in [2, 3, 5]: if n%p == 0: return p if bound == None: bound = n dif = [6, 4, 2, 4, 2, 4, 6, 2] m = 7; i = 1 while m <= bound and m*m <= n: if n%m == 0: return m m += dif[i%8] i += 1 return n
|
if bound is None: return ZZ(n).trial_division() else: return ZZ(n).trial_division(bound)
|
def trial_division(n, bound=None): """ Return the smallest prime divisor <= bound of the positive integer n, or n if there is no such prime. If the optional argument bound is omitted, then bound <= n. INPUT: - ``n`` - a positive integer - ``bound`` - (optional) a positive integer OUTPUT: - ``int`` - a prime p=bound that divides n, or n if there is no such prime. EXAMPLES:: sage: trial_division(15) 3 sage: trial_division(91) 7 sage: trial_division(11) 11 sage: trial_division(387833, 300) 387833 sage: # 300 is not big enough to split off a sage: # factor, but 400 is. sage: trial_division(387833, 400) 389 """ if n == 1: return 1 for p in [2, 3, 5]: if n%p == 0: return p if bound == None: bound = n dif = [6, 4, 2, 4, 2, 4, 6, 2] m = 7; i = 1 while m <= bound and m*m <= n: if n%m == 0: return m m += dif[i%8] i += 1 return n
|
if n < 10000000000000: return factorization.Factorization(__factor_using_trial_division(n), unit)
|
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(-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) (-i) * (3*i - 2) * (4*i + 1) * (i + 1)^3 * (2*i + 1)^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 < 10000000000: return __factor_using_trial_division(n) 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"
|
|
Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition.
|
Returns the unique graph on \{0,1,...,n-1\} ( n = self.order() ) which - is isomorphic to self, - has canonical vertex labels, - allows only permutations of vertices respecting the input set partition (if given). Canonical here means that all graphs isomorphic to self (and respecting the input set partition) have the same canonical vertex labels.
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition. INPUT: - ``partition`` - if given, the canonical label with respect to this partition will be computed. The default is the unit partition. - ``certify`` - if True, a dictionary mapping from the (di)graph to its canonical label will be given. - ``verbosity`` - gets passed to nice: prints helpful output. - ``edge_labels`` - default False, otherwise allows only permutations respecting edge labels. EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: E = D.canonical_label(); E Dodecahedron: Graph on 20 vertices sage: D.canonical_label(certify=True) (Dodecahedron: Graph on 20 vertices, {0: 0, 1: 19, 2: 16, 3: 15, 4: 9, 5: 1, 6: 10, 7: 8, 8: 14, 9: 12, 10: 17, 11: 11, 12: 5, 13: 6, 14: 2, 15: 4, 16: 3, 17: 7, 18: 13, 19: 18}) sage: D.is_isomorphic(E) True Multigraphs:: sage: G = Graph(multiedges=True,sparse=True) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.canonical_label() Multi-graph on 2 vertices sage: Graph('A?', implementation='c_graph').canonical_label() Graph on 2 vertices
|
respect to this partition will be computed. The default is the unit partition.
|
respect to this set partition will be computed. The default is the unit set partition.
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition. INPUT: - ``partition`` - if given, the canonical label with respect to this partition will be computed. The default is the unit partition. - ``certify`` - if True, a dictionary mapping from the (di)graph to its canonical label will be given. - ``verbosity`` - gets passed to nice: prints helpful output. - ``edge_labels`` - default False, otherwise allows only permutations respecting edge labels. EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: E = D.canonical_label(); E Dodecahedron: Graph on 20 vertices sage: D.canonical_label(certify=True) (Dodecahedron: Graph on 20 vertices, {0: 0, 1: 19, 2: 16, 3: 15, 4: 9, 5: 1, 6: 10, 7: 8, 8: 14, 9: 12, 10: 17, 11: 11, 12: 5, 13: 6, 14: 2, 15: 4, 16: 3, 17: 7, 18: 13, 19: 18}) sage: D.is_isomorphic(E) True Multigraphs:: sage: G = Graph(multiedges=True,sparse=True) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.canonical_label() Multi-graph on 2 vertices sage: Graph('A?', implementation='c_graph').canonical_label() Graph on 2 vertices
|
b_new = {}
|
c_new = {}
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition. INPUT: - ``partition`` - if given, the canonical label with respect to this partition will be computed. The default is the unit partition. - ``certify`` - if True, a dictionary mapping from the (di)graph to its canonical label will be given. - ``verbosity`` - gets passed to nice: prints helpful output. - ``edge_labels`` - default False, otherwise allows only permutations respecting edge labels. EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: E = D.canonical_label(); E Dodecahedron: Graph on 20 vertices sage: D.canonical_label(certify=True) (Dodecahedron: Graph on 20 vertices, {0: 0, 1: 19, 2: 16, 3: 15, 4: 9, 5: 1, 6: 10, 7: 8, 8: 14, 9: 12, 10: 17, 11: 11, 12: 5, 13: 6, 14: 2, 15: 4, 16: 3, 17: 7, 18: 13, 19: 18}) sage: D.is_isomorphic(E) True Multigraphs:: sage: G = Graph(multiedges=True,sparse=True) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.canonical_label() Multi-graph on 2 vertices sage: Graph('A?', implementation='c_graph').canonical_label() Graph on 2 vertices
|
b_new[v] = c[G_to[('o',v)]] H.relabel(b_new)
|
c_new[v] = c[G_to[('o',v)]] H.relabel(c_new)
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition. INPUT: - ``partition`` - if given, the canonical label with respect to this partition will be computed. The default is the unit partition. - ``certify`` - if True, a dictionary mapping from the (di)graph to its canonical label will be given. - ``verbosity`` - gets passed to nice: prints helpful output. - ``edge_labels`` - default False, otherwise allows only permutations respecting edge labels. EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: E = D.canonical_label(); E Dodecahedron: Graph on 20 vertices sage: D.canonical_label(certify=True) (Dodecahedron: Graph on 20 vertices, {0: 0, 1: 19, 2: 16, 3: 15, 4: 9, 5: 1, 6: 10, 7: 8, 8: 14, 9: 12, 10: 17, 11: 11, 12: 5, 13: 6, 14: 2, 15: 4, 16: 3, 17: 7, 18: 13, 19: 18}) sage: D.is_isomorphic(E) True Multigraphs:: sage: G = Graph(multiedges=True,sparse=True) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.canonical_label() Multi-graph on 2 vertices sage: Graph('A?', implementation='c_graph').canonical_label() Graph on 2 vertices
|
return H, relabeling
|
return H, c_new
|
def canonical_label(self, partition=None, certify=False, verbosity=0, edge_labels=False): """ Returns the canonical label with respect to the partition. If no partition is given, uses the unit partition. INPUT: - ``partition`` - if given, the canonical label with respect to this partition will be computed. The default is the unit partition. - ``certify`` - if True, a dictionary mapping from the (di)graph to its canonical label will be given. - ``verbosity`` - gets passed to nice: prints helpful output. - ``edge_labels`` - default False, otherwise allows only permutations respecting edge labels. EXAMPLES:: sage: D = graphs.DodecahedralGraph() sage: E = D.canonical_label(); E Dodecahedron: Graph on 20 vertices sage: D.canonical_label(certify=True) (Dodecahedron: Graph on 20 vertices, {0: 0, 1: 19, 2: 16, 3: 15, 4: 9, 5: 1, 6: 10, 7: 8, 8: 14, 9: 12, 10: 17, 11: 11, 12: 5, 13: 6, 14: 2, 15: 4, 16: 3, 17: 7, 18: 13, 19: 18}) sage: D.is_isomorphic(E) True Multigraphs:: sage: G = Graph(multiedges=True,sparse=True) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.add_edge((0,1)) sage: G.canonical_label() Multi-graph on 2 vertices sage: Graph('A?', implementation='c_graph').canonical_label() Graph on 2 vertices
|
Return the number of the `n`-th partial convergent, computed
|
Return the numerator of the `n`-th partial convergent, computed
|
def pn(self, n): """ Return the number of the `n`-th partial convergent, computed using the recurrence. EXAMPLES:: sage: c = continued_fraction(pi); c [3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3] sage: c.pn(0), c.qn(0) (3, 1) sage: len(c) 14 sage: c.pn(13), c.qn(13) (245850922, 78256779) """ if n < -2: raise ValueError, "n must be at least -2" if n > len(self._x): raise ValueError, "n must be at most %s"%len(self._x) try: return self.__pn[n+2] except AttributeError: self.__pn = [0, 1, self._x[0]] self.__qn = [1, 0, 1] except IndexError: pass for k in range(len(self.__pn), n+3): self.__pn.append(self._x[k-2]*self.__pn[k-1] + self.__pn[k-2]) self.__qn.append(self._x[k-2]*self.__qn[k-1] + self.__qn[k-2]) return self.__pn[n+2]
|
Return the (unique) field of all contiued fractions.
|
Return the (unique) field of all continued fractions.
|
def ContinuedFractionField(): """ Return the (unique) field of all contiued fractions. EXAMPLES:: sage: ContinuedFractionField() Field of all continued fractions """ return CFF
|
Return a list of the edges of the graph as triples (u,v,l) where u and v are vertices and l is a label.
|
Return a list of edges. Each edge is a triple (u,v,l) where u and v are vertices and l is a label. If the parameter ``labels`` is False then a list of couple (u,v) is returned where u and v are vertices.
|
def edges(self, labels=True, sort=True, key=None): r""" Return a list of the edges of the graph as triples (u,v,l) where u and v are vertices and l is a label.
|
def edge_boundary(self, vertices1, vertices2=None, labels=True):
|
def edge_boundary(self, vertices1, vertices2=None, labels=True, sort=True):
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
sage: G = graphs.PetersenGraph()
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
|
""" vertices1 = [v for v in vertices1 if v in self] output = []
|
sage: G.edge_boundary([2], [0]) [(0, 2, {})] """ vertices1 = set([v for v in vertices1 if v in self])
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
output.extend(self.outgoing_edge_iterator(vertices1,labels=labels))
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
|
output = [e for e in output if e[1] in vertices2]
|
vertices2 = set([v for v in vertices2 if v in self]) output = [e for e in self.outgoing_edge_iterator(vertices1,labels=labels) if e[1] in vertices2]
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
output = [e for e in output if e[1] not in vertices1] return output
|
output = [e for e in self.outgoing_edge_iterator(vertices1,labels=labels) if e[1] not in vertices1]
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
output.extend(self.edge_iterator(vertices1,labels=labels)) output2 = []
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
|
for e in output: if e[0] in vertices1: if e[1] in vertices2: output2.append(e) elif e[0] in vertices2: output2.append(e)
|
vertices2 = set([v for v in vertices2 if v in self]) output = [e for e in self.edge_iterator(vertices1,labels=labels) if (e[0] in vertices1 and e[1] in vertices2) or (e[1] in vertices1 and e[0] in vertices2)]
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
for e in output: if e[0] in vertices1: if e[1] not in vertices1: output2.append(e) elif e[0] not in vertices1: output2.append(e) return output2
|
output = [e for e in self.edge_iterator(vertices1,labels=labels) if e[1] not in vertices1 or e[0] not in vertices1] if sort: output.sort() return output
|
def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. In a digraph, the external boundary of a vertex `v` are those vertices `u` with an arc `(v, u)`. INPUT: - ``labels`` - if ``False``, each edge is a tuple `(u,v)` of vertices. EXAMPLES:: sage: K = graphs.CompleteBipartiteGraph(9,3) sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 27 Note that the edge boundary preserves direction:: sage: K = graphs.CompleteBipartiteGraph(9,3).to_directed() sage: len(K.edge_boundary( [0,1,2,3,4,5,6,7,8], [9,10,11] )) 27 sage: K.size() 54 :: sage: D = DiGraph({0:[1,2], 3:[0]}) sage: D.edge_boundary([0]) [(0, 1, None), (0, 2, None)] sage: D.edge_boundary([0], labels=False) [(0, 1), (0, 2)]
|
Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
Returns an iterator over edges. The iterator returned is over the edges incident with any vertex given in the parameter ``vertices``. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only.
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
- ``vertices`` - (default: None) a vertex, a list of vertices or None
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
|
- ``ignore_direction`` - (default False) only applies
|
- ``ignore_direction`` - bool (default: False) - only applies
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e
|
from itertools import chain return chain(self._backend.iterator_out_edges(vertices, labels), self._backend.iterator_in_edges(vertices, labels))
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
for e in self._backend.iterator_out_edges(vertices, labels): yield e
|
return self._backend.iterator_out_edges(vertices, labels)
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
for e in self._backend.iterator_edges(vertices, labels): yield e def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices
|
return self._backend.iterator_edges(vertices, labels) def edges_incident(self, vertices=None, labels=True, sort=True): """ Returns incident edges to some vertices. If ``vertices` is a vertex, then it returns the list of edges incident to that vertex. If ``vertices`` is a list of vertices then it returns the list of all edges adjacent to those vertices. If ``vertices``
|
def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. INPUT: - ``labels`` - if False, each edge is a tuple (u,v) of vertices. - ``ignore_direction`` - (default False) only applies to directed graphs. If True, searches across edges in either direction. EXAMPLES:: sage: for i in graphs.PetersenGraph().edge_iterator([0]): ... print i (0, 1, None) (0, 4, None) (0, 5, None) sage: D = DiGraph( { 0 : [1,2], 1: [0] } ) sage: for i in D.edge_iterator([0]): ... print i (0, 1, None) (0, 2, None) :: sage: G = graphs.TetrahedralGraph() sage: list(G.edge_iterator(labels=False)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] :: sage: D = DiGraph({1:[0], 2:[0]}) sage: list(D.edge_iterator(0)) [] sage: list(D.edge_iterator(0, ignore_direction=True)) [(1, 0, None), (2, 0, None)] """ if vertices is None: vertices = self elif vertices in self: vertices = [vertices] else: vertices = [v for v in vertices if v in self] if ignore_direction and self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e elif self._directed: for e in self._backend.iterator_out_edges(vertices, labels): yield e else: for e in self._backend.iterator_edges(vertices, labels): yield e
|
- ``label`` - if False, each edge is a tuple (u,v) of vertices.
|
- ``vertices`` - object (default: None) - a vertex, a list of vertices or None. - ``labels`` - bool (default: True) - if False, each edge is a tuple (u,v) of vertices. - ``sort`` - bool (default: True) - if True the returned list is sorted.
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges. INPUT: - ``label`` - if False, each edge is a tuple (u,v) of vertices. EXAMPLES:: sage: graphs.PetersenGraph().edges_incident([0,9], labels=False) [(0, 1), (0, 4), (0, 5), (4, 9), (6, 9), (7, 9)] sage: D = DiGraph({0:[1]}) sage: D.edges_incident([0]) [(0, 1, None)] sage: D.edges_incident([1]) [] """ if vertices in self: vertices = [vertices] v = list(self.edge_boundary(vertices, labels=labels)) v.sort() return v
|
v = list(self.edge_boundary(vertices, labels=labels)) v.sort() return v
|
if sort: return sorted(self.edge_iterator(vertices=vertices,labels=labels)) return list(self.edge_iterator(vertices=vertices,labels=labels))
|
def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges. INPUT: - ``label`` - if False, each edge is a tuple (u,v) of vertices. EXAMPLES:: sage: graphs.PetersenGraph().edges_incident([0,9], labels=False) [(0, 1), (0, 4), (0, 5), (4, 9), (6, 9), (7, 9)] sage: D = DiGraph({0:[1]}) sage: D.edges_incident([0]) [(0, 1, None)] sage: D.edges_incident([1]) [] """ if vertices in self: vertices = [vertices] v = list(self.edge_boundary(vertices, labels=labels)) v.sort() return v
|
if polynomial not in self.coordinate_ring():
|
S = self.coordinate_ring() try: polynomial = S(polynomial) except TypeError:
|
def is_homogeneous(self, polynomial): r""" Check if ``polynomial`` is homogeneous.
|
polynomial = polynomial.lift()
|
polynomial = S(polynomial.lift())
|
def is_homogeneous(self, polynomial): r""" Check if ``polynomial`` is homogeneous.
|
pass
|
def cycle_index(self, parent = None): r""" INPUT: - ``self`` - a permutation group `G` - ``parent`` -- a free module with basis indexed by partitions, or behave as such, with a ``term`` and ``sum`` method (default: the symmetric functions over the rational field in the p basis) Returns the *cycle index* of `G`, which is a gadget counting the elements of `G` by cycle type, averaged over the group: .. math:: P = \frac{1}{|G|} \sum_{g\in G} p_{ \operatorname{cycle\ type}(g) } EXAMPLES: Among the permutations of the symmetric group `S_4`, there is the identity, 6 cycles of length 2, 3 products of two cycles of length 2, 8 cycles of length 3, and 6 cycles of length 4:: sage: S4 = SymmetricGroup(4) sage: P = S4.cycle_index() sage: 24 * P p[1, 1, 1, 1] + 6*p[2, 1, 1] + 3*p[2, 2] + 8*p[3, 1] + 6*p[4] If `l = (l_1,\dots,l_k)` is a partition, ``|G| P[l]`` is the number of elements of `G` with cycles of length `(p_1,\dots,p_k)`:: sage: 24 * P[ Partition([3,1]) ] 8 The cycle index plays an important role in the enumeration of objects modulo the action of a group (Polya enumeration), via the use of symmetric functions and plethysms. It is therefore encoded as a symmetric function, expressed in the powersum basis:: sage: P.parent() Symmetric Function Algebra over Rational Field, Power symmetric functions as basis This symmetric function can have some nice properties; for example, for the symmetric group `S_n`, we get the complete symmetric function `h_n`:: sage: S = SymmetricFunctions(QQ); h = S.h() sage: h( P ) h[4] TODO: add some simple examples of Polya enumeration, once it will be easy to expand symmetric functions on any alphabet. Here are the cycle indices of some permutation groups:: sage: 6 * CyclicPermutationGroup(6).cycle_index() p[1, 1, 1, 1, 1, 1] + p[2, 2, 2] + 2*p[3, 3] + 2*p[6] sage: 60 * AlternatingGroup(5).cycle_index() p[1, 1, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 24*p[5] sage: for G in TransitiveGroups(5): ... G.cardinality() * G.cycle_index() p[1, 1, 1, 1, 1] + 4*p[5] p[1, 1, 1, 1, 1] + 5*p[2, 2, 1] + 4*p[5] p[1, 1, 1, 1, 1] + 5*p[2, 2, 1] + 10*p[4, 1] + 4*p[5] p[1, 1, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 24*p[5] p[1, 1, 1, 1, 1] + 10*p[2, 1, 1, 1] + 15*p[2, 2, 1] + 20*p[3, 1, 1] + 20*p[3, 2] + 30*p[4, 1] + 24*p[5] One may specify another parent for the result:: sage: F = CombinatorialFreeModule(QQ, Partitions()) sage: P = CyclicPermutationGroup(6).cycle_index(parent = F) sage: 6 * P B[[1, 1, 1, 1, 1, 1]] + B[[2, 2, 2]] + 2*B[[3, 3]] + 2*B[[6]] sage: P.parent() is F True This parent should have a ``term`` and ``sum`` method:: sage: CyclicPermutationGroup(6).cycle_index(parent = QQ) Traceback (most recent call last): ... AssertionError: `parent` should be (or behave as) a free module with basis indexed by partitions REFERENCES: .. [Ker1991] A. Kerber. Algebraic combinatorics via finite group actions, 2.2 p. 70. BI-Wissenschaftsverlag, Mannheim, 1991. AUTHORS: - Nicolas Borie and Nicolas M. Thiery TESTS:: sage: P = PermutationGroup([]); P Permutation Group with generators [()] sage: P.cycle_index() p[1] sage: P = PermutationGroup([[(1)]]); P Permutation Group with generators [()] sage: P.cycle_index() p[1] """ from sage.combinat.permutation import Permutation if parent is None: from sage.rings.rational_field import QQ from sage.combinat.sf.sf import SymmetricFunctions parent = SymmetricFunctions(QQ).powersum() else: assert hasattr(parent, "term") and hasattr(parent, "sum"), \ "`parent` should be (or behave as) a free module with basis indexed by partitions" base_ring = parent.base_ring() from sage.interfaces.gap import gap CC = ([Permutation(self(C.Representative())).cycle_type(), base_ring(C.Size())] for C in gap(self).ConjugacyClasses()) return parent.sum( parent.term( partition, coeff ) for (partition, coeff) in CC)/self.cardinality()
|
def example(self): """ Returns an example of finite permutation group, as per :meth:`Category.example`.
|
-0.530637530952518 + 1.11851787964371*I
|
0.530637530952518 - 1.11851787964371*I
|
def __init__(self): r""" The inverse of the hyperbolic secant function.
|
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. EXAMPLES:: sage: Word([1,0,0,1]).is_square() False 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() True """ if self.length() % 2 != 0: return False else: l = self.length() / 2 return self[:l] == self[l:]
|
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. EXAMPLES:: sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True
|
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. EXAMPLES:: sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True
|
suff = suff[1:]
|
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. EXAMPLES:: sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.