rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
suff = suff[1:]
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
sage: W = Words('012') sage: W('012012012').is_cube() True sage: W('01010101').is_cube() False sage: W().is_cube() True sage: W('012012').is_cube()
sage: Word('012012012').is_cube() True sage: Word('01010101').is_cube() False sage: Word().is_cube() True sage: Word('012012').is_cube()
def is_cube(self): r""" Returns True if self is a cube, and False otherwise.
sage: W = Words('123') sage: W('12312').is_cube_free() True sage: W('32221').is_cube_free() False sage: W().is_cube_free() True """ l = self.length() if l < 3:
sage: Word('12312').is_cube_free() True sage: Word('32221').is_cube_free() False sage: Word().is_cube_free() True TESTS: We make sure that sage: Word('111').is_cube_free() False sage: Word('2111').is_cube_free() False sage: Word('32111').is_cube_free() False """ L = self.length() if L < 3:
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
suff = self for i in xrange(0, l - 3): for ll in xrange(3, l-i+1, 3): if suff[:ll].is_cube():
for start in xrange(0, L - 2): for end in xrange(start+3, L+1, 3): if self[start:end].is_cube():
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
suff = suff[1:]
def is_cube_free(self): r""" Returns True if self does not contain cubes, and False otherwise.
Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Return an iterator through all curves in the database with given conductors.
def iter(self, conductors): """ Returns an iterator through all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
Return an iterator through all optimal curves in the database with given conductors.
def iter_optimal(self, conductors): """ Returns an iterator through all optimal curves with conductor between Nmin and Nmax-1 in the database.
Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns a list of all curves with given conductors.
def list(self, conductors): """ Returns a list of all curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
Returns a list of all optimal curves with given conductors.
def list_optimal(self, conductors): """ Returns a list of all optimal curves with conductor between Nmin and Nmax-1, inclusive, in the database.
The smallest conductor for which the database is complete. (Always 1.)
The smallest conductor for which the database is complete: always 1.
def smallest_conductor(self): """ The smallest conductor for which the database is complete. (Always 1.)
OUTPUT: - ``int`` - smallest cond - ``int`` - largest conductor plus one
OUTPUT: tuple of ints (N1,N2+1) where N1 is the smallest and N2 the largest conductor for which the database is complete.
def conductor_range(self): """ Return the range of conductors that are covered by the database.
and coefficients bounded above by 10. ::
and coefficients bounded above by 10::
def algdep(z, degree, known_bits=None, use_bits=None, known_digits=None, use_digits=None, height_bound=None, proof=False): """ Returns a polynomial of degree at most `degree` which is approximately satisfied by the number `z`. Note that the returned polynomial need not be irreducible, and indeed usually won't be if `z` is a good approximation to an algebraic number of degree less than `degree`. You can specify the number of known bits or digits with ``known_bits=k`` or ``known_digits=k``; Pari is then told to compute the result using `0.8k` of these bits/digits. (The Pari documentation recommends using a factor between .6 and .9, but internally defaults to .8.) Or, you can specify the precision to use directly with ``use_bits=k`` or ``use_digits=k``. If none of these are specified, then the precision is taken from the input value. A height bound may specified to indicate the maximum coefficient size of the returned polynomial; if a sufficiently small polyomial is not found then ``None`` wil be returned. If ``proof=True`` then the result is returned only if it can be proved correct (i.e. the only possible minimal polynomial satisfying the height bound, or no such polynomial exists). Otherwise a ``ValueError`` is raised indicating that higher precision is required. ALGORITHM: Uses LLL for real/complex inputs, PARI C-library algdep command otherwise. Note that ``algebraic_dependency`` is a synonym for ``algdep``. INPUT: - ``z`` - real, complex, or `p`-adic number - ``degree`` - an integer - ``height_bound`` - an integer (default ``None``) specifying the maximum coefficient size for the returned polynomial - ``proof`` - a boolean (default ``False``), requres height_bound to be set EXAMPLES:: sage: algdep(1.888888888888888, 1) 9*x - 17 sage: algdep(0.12121212121212,1) 33*x - 4 sage: algdep(sqrt(2),2) x^2 - 2 This example involves a complex number. :: sage: z = (1/2)*(1 + RDF(sqrt(3)) *CC.0); z 0.500000000000000 + 0.866025403784439*I sage: p = algdep(z, 6); p x^3 + 1 sage: p.factor() (x + 1) * (x^2 - x + 1) sage: z^2 - z + 1 0 This example involves a `p`-adic number. :: sage: K = Qp(3, print_mode = 'series') sage: a = K(7/19); a 1 + 2*3 + 3^2 + 3^3 + 2*3^4 + 2*3^5 + 3^8 + 2*3^9 + 3^11 + 3^12 + 2*3^15 + 2*3^16 + 3^17 + 2*3^19 + O(3^20) sage: algdep(a, 1) 19*x - 7 These examples show the importance of proper precision control. We compute a 200-bit approximation to sqrt(2) which is wrong in the 33'rd bit. :: sage: z = sqrt(RealField(200)(2)) + (1/2)^33 sage: p = algdep(z, 4); p 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: factor(p) 227004321085*x^4 - 216947902586*x^3 - 99411220986*x^2 + 82234881648*x - 211871195088 sage: algdep(z, 4, known_bits=32) x^2 - 2 sage: algdep(z, 4, known_digits=10) x^2 - 2 sage: algdep(z, 4, use_bits=25) x^2 - 2 sage: algdep(z, 4, use_digits=8) x^2 - 2 Using the ``height_bound`` and ``proof`` parameters, we can see that `pi` is not the root of an integer polynomial of degree at most 5 and coefficients bounded above by 10. :: sage: algdep(pi.n(), 5, height_bound=10, proof=True) is None True For stronger results, we need more precicion. :: sage: algdep(pi.n(), 5, height_bound=100, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 5, height_bound=100, proof=True) is None True sage: algdep(pi.n(), 10, height_bound=10, proof=True) is None Traceback (most recent call last): ... ValueError: insufficient precision for non-existence proof sage: algdep(pi.n(200), 10, height_bound=10, proof=True) is None True We can also use ``proof=True`` to get positive results. :: sage: a = sqrt(2) + sqrt(3) + sqrt(5) sage: algdep(a.n(), 8, height_bound=1000, proof=True) Traceback (most recent call last): ... ValueError: insufficient precision for uniqueness proof sage: f = algdep(a.n(1000), 8, height_bound=1000, proof=True); f x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 sage: f(a).expand() 0 """ if proof and not height_bound: raise ValueError, "height_bound must be given for proof=True" x = ZZ['x'].gen() if isinstance(z, (int, long, integer.Integer)): if height_bound and abs(z) >= height_bound: return None return x - ZZ(z) degree = ZZ(degree) if isinstance(z, (sage.rings.rational.Rational)): if height_bound and max(abs(z.denominator()), abs(z.numerator())) >= height_bound: return None return z.denominator()*x - z.numerator() if isinstance(z, float): z = sage.rings.real_mpfr.RR(z) elif isinstance(z, complex): z = sage.rings.complex_field.CC(z) if isinstance(z, (sage.rings.real_mpfr.RealNumber, sage.rings.complex_number.ComplexNumber)): log2_10 = 3.32192809488736 prec = z.prec() - 6 if known_digits is not None: known_bits = known_digits * log2_10 if known_bits is not None: use_bits = known_bits * 0.8 if use_digits is not None: use_bits = use_digits * log2_10 if use_bits is not None: prec = int(use_bits) is_complex = isinstance(z, sage.rings.complex_number.ComplexNumber) n = degree+1 from sage.matrix.all import matrix M = matrix(ZZ, n, n+1+int(is_complex)) r = ZZ(1) << prec M[0, 0] = 1 M[0,-1] = r for k in range(1, degree+1): M[k,k] = 1 r *= z if is_complex: M[k, -1] = r.real().round() M[k, -2] = r.imag().round() else: M[k, -1] = r.round() LLL = M.LLL(delta=.75) coeffs = LLL[0][:n] if height_bound: def norm(v): # norm on an integer vector invokes Integer.sqrt() which tries to factor... from sage.rings.real_mpfi import RIF return v.change_ring(RIF).norm() if max(abs(a) for a in coeffs) > height_bound: if proof: # Given an LLL reduced basis $b_1, ..., b_n$, we only # know that $|b_1| <= 2^((n-1)/2) |x|$ for non-zero $x \in L$. if norm(LLL[0]) <= 2**((n-1)/2) * n.sqrt() * height_bound: raise ValueError, "insufficient precision for non-existence proof" return None elif proof and norm(LLL[1]) < 2**((n-1)/2) * max(norm(LLL[0]), n.sqrt()*height_bound): raise ValueError, "insufficient precision for uniqueness proof" if coeffs[degree] < 0: coeffs = -coeffs f = list(coeffs) elif proof or height_bound: raise NotImplementedError, "proof and height bound only implemented for real and complex numbers" else: y = pari(z) f = y.algdep(degree) return x.parent()(f)
Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007)
Now type show(P1), show(P2) to view these. AUTHORS: - David Joyner (3-2006, 8-2007)
def desolve_system_strings(des,vars,ics=None): """ Solves any size system of 1st order ODE's. Initials conditions are optional. INPUT: de -- a list of strings representing the ODEs in maxima notation (eg, de = "diff(f(x),x,2)=diff(f(x),x)+sin(x)") vars -- a list of strings representing the variables (eg, vars = ["s","x","y"], where s is the independent variable and x,y the dependent variables) ics -- a list of numbers representing initial conditions (eg, x(0)=1, y(0)=2 is ics = [0,1,2]) WARNING: The given ics sets the initial values of the dependent vars in maxima, so subsequent ODEs involving these variables will have these initial conditions automatically imposed. EXAMPLES: sage: from sage.calculus.desolvers import desolve_system_strings sage: s = var('s') sage: function('x', s) x(s) sage: function('y', s) y(s) sage: de1 = lambda z: diff(z[0],s) + z[1] - 1 sage: de2 = lambda z: diff(z[1],s) - z[0] + 1 sage: des = [de1([x(s),y(s)]),de2([x(s),y(s)])] sage: vars = ["s","x","y"] sage: desolve_system_strings(des,vars) ["(1-'y(0))*sin(s)+('x(0)-1)*cos(s)+1", "('x(0)-1)*sin(s)+('y(0)-1)*cos(s)+1"] sage: ics = [0,1,-1] sage: soln = desolve_system_strings(des,vars,ics); soln ['2*sin(s)+1', '1-2*cos(s)'] sage: solnx, solny = map(SR, soln) sage: RR(solnx(s=3)) 1.28224001611973 sage: P1 = plot([solnx,solny],(0,1)) sage: P2 = parametric_plot((solnx,solny),(0,1)) Now type show(P1), show(P2) to view these. AUTHORS: David Joyner (3-2006, 8-2007) """ d = len(des) dess = [de._maxima_init_() + "=0" for de in des] for i in range(d): cmd="de:" + dess[int(i)] + ";" maxima.eval(cmd) desstr = "[" + ",".join(dess) + "]" d = len(vars) varss = list("'" + vars[i] + "(" + vars[0] + ")" for i in range(1,d)) varstr = "[" + ",".join(varss) + "]" if ics is not None: #d = len(ics) ## must be same as len(des) for i in range(1,d): ic = "atvalue('" + vars[i] + "("+vars[0] + ")," + str(vars[0]) + "=" + str(ics[0]) + "," + str(ics[i]) + ")" maxima.eval(ic) cmd = "desolve(" + desstr + "," + varstr + ");" soln = maxima(cmd) return [f.rhs()._maxima_init_() for f in soln]
self._read_faces(self.poly_x("i"))
self._read_faces(self.poly_x("i", reduce_dimension=True))
def _compute_faces(self): r""" Compute and cache faces of this polytope.
Return the sequence of faces of this polytope.
Return the sequence of proper faces of this polytope.
def faces(self, dim=None, codim=None): r""" Return the sequence of faces of this polytope.
self._points = self._embed(read_palp_matrix( self.poly_x("p", reduce_dimension=True))) self._points.set_immutable()
if self.dim() == 0: self._points = self._vertices else: self._points = self._embed(read_palp_matrix( self.poly_x("p", reduce_dimension=True))) self._points.set_immutable()
def points(self): r""" Return all lattice points of this polytope as columns of a matrix.
Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
Return a new Weierstrass model of self under the standard transformation `(u,r,s,t)`
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
(x,y) \mapsto (x',y') = (u^2xr , u^3y + su^2x' + t).
(x,y) \mapsto (x',y') = (u^2x + r , u^3y + su^2x + t).
def change_weierstrass_model(self, *urst): r""" Return a new Weierstrass model of self under the standard transformation `(u,r,s,,t)`
P1 = P[0]; P2 = P[1]
P1 = P[0] P2 = P[1] if is_Integer(P1) and is_Integer(P2): R = PolynomialRing(self.value_ring(), 'x') P1 = R(P1) P2 = R(P2) return JacobianMorphism_divisor_class_field(self, tuple([P1,P2])) if is_Integer(P1) and is_Polynomial(P2): R = PolynomialRing(self.value_ring(), 'x') P1 = R(P1) return JacobianMorphism_divisor_class_field(self, tuple([P1,P2])) if is_Integer(P2) and is_Polynomial(P1): R = PolynomialRing(self.value_ring(), 'x') P2 = R(P2) return JacobianMorphism_divisor_class_field(self, tuple([P1,P2]))
def __call__(self, P): r""" Returns a rational point P in the abstract Homset J(K), given:
NOTE::
NOTE:
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def tamagawa_product(self):
def tamagawa_product_bsd(self):
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
sage: E.tamagawa_product()
sage: E.tamagawa_product_bsd()
def tamagawa_product(self): r""" Given an elliptic curve `E` over a number field `K`, this function returns the integer `C(E/K)` that appears in the Birch and Swinnerton-Dyer conjecture accounting for the local information at finite places. If the model is a global minimal model then `C(E/K)` is simply the product of the Tamagawa numbers `c_v` where `v` runs over all prime ideals of `K`. Otherwise, if the model has to be changed at a place `v` a correction factor appears. The definition is such that `C(E/K)` times the periods at the infinite places is invariant under change of the Weierstrass model. See [Ta2] and [Do] for details.
sage: E2 Elliptic Curve defined by y^2 + a*x*y + (a+1)*y = x^3 + (a+1)*x^2 + (12289755603565800754*a-75759141535687466985)*x + (51556320144761417221790307379*a-317814501841918807353201512829) over Number Field in a with defining polynomial x^2 - 38
sage: E2 Elliptic Curve defined by y^2 + a*x*y + (a+1)*y = x^3 + (a+1)*x^2 + (368258520200522046806318444*a-2270097978636731786720859345)*x + (8456608930173478039472018047583706316424*a-52130038506793883217874390501829588391299) over Number Field in a with defining polynomial x^2 - 38
def global_minimal_model(self, proof = None): r""" Returns a model of self that is integral, minimal at all primes.
_vars = str(self.gen())
_vars = '(%s)'%self.gen()
def _singular_init_(self, singular=singular_default): """ Return a newly created Singular ring matching this ring. """ if not can_convert_to_singular(self): raise TypeError, "no conversion of this ring to a Singular ring defined"
Digraph on 6 vertices
Hasse diagram of a poset containing 6 elements
def hasse_diagram(self): """ Returns the Hasse_diagram of the poset as a Sage DiGraph object.
sage: m._scaling -2
Warning : Could not normalize the modular symbols, maybe all further results will be multiplied by -1, 2 or -2. sage: m._scaling 1
def _find_scaling_L_ratio(self): r""" This function is use to set ``_scaling``, the factor used to adjust the scalar multiple of the modular symbol. If `[0]`, the modular symbol evaluated at 0, is non-zero, we can just scale it with respect to the approximation of the L-value. It is known that the quotient is a rational number with small denominator. Otherwise we try to scale using quadratic twists.
.. note:: Reference for the Sturm bound that we use in the definition of of this function: J. Sturm, On the congruence of modular forms, Number theory (New York, 1984-1985), Springer, Berlin, 1987, pp. 275-280. Useful Remark:
sage: CuspForms(Gamma1(144), 3).sturm_bound() 3457 sage: CuspForms(DirichletGroup(144).1^2, 3).sturm_bound() 73 sage: CuspForms(Gamma0(144), 3).sturm_bound() 73 REFERENCE: - [Sturm] J. Sturm, On the congruence of modular forms, Number theory (New York, 1984-1985), Springer, Berlin, 1987, pp. 275-280. NOTE::
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
`s \geq` the sturm bound for `\Gamma_0` at
`s \geq` the Sturm bound for `\Gamma_0` at
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
self.__sturm_bound = self.group().sturm_bound(self.weight())+1
self.__sturm_bound = G.sturm_bound(self.weight())+1
def sturm_bound(self, M=None): r""" For a space M of modular forms, this function returns an integer B such that two modular forms in either self or M are equal if and only if their q-expansions are equal to precision B (note that this is 1+ the usual Sturm bound, since `O(q^\mathrm{prec})` has precision prec). If M is none, then M is set equal to self.
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.)
def valuation(m,*args1, **args2): """
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
If m is 0, this function returns rings.infinity.
See the documentation of m.valuation() for a more precise description. Use of this function by developers is discouraged. Use m.valuation() instead. .. NOTE:: This is not always a valuation in the mathematical sense. For more information see: sage.rings.finite_rings.integer_mod.IntegerMod_int.valuation
def valuation(m, p): """ The exact power of p that divides m. m should be an integer or rational (but maybe other types work too.) This actually just calls the m.valuation() method. If m is 0, this function returns rings.infinity. EXAMPLES:: sage: valuation(512,2) 9 sage: valuation(1,2) 0 sage: valuation(5/9, 3) -2 Valuation of 0 is defined, but valuation with respect to 0 is not:: sage: valuation(0,7) +Infinity sage: valuation(3,0) Traceback (most recent call last): ... ValueError: You can only compute the valuation with respect to a integer larger than 1. Here are some other examples:: sage: valuation(100,10) 2 sage: valuation(200,10) 2 sage: valuation(243,3) 5 sage: valuation(243*10007,3) 5 sage: valuation(243*10007,10007) 1 """ if hasattr(m, 'valuation'): return m.valuation(p) if m == 0: import sage.rings.all return sage.rings.all.infinity if is_FractionFieldElement(m): return valuation(m.numerator()) - valuation(m.denominator()) r = 0 power = p while not (m % power): # m % power == 0 r += 1 power *= p return r
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.
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.
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.
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.
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.
if self._style == "coroots" and all(xv in ZZ for xv in x):
if self._style == "coroots" and isinstance(x, tuple) and all(xv in ZZ for xv in x):
def __call__(self, *args): """ Coerces the element into the ring. You may pass a vector in the ambient space, an element of the base_ring, or an argument list of integers (or half-integers for the spin types) which are the components of a vector in the ambient space.
return QuotientRingElement(self.parent(), -self.__rep)
return self.parent()(-self.__rep)
def __neg__(self): """ EXAMPLES::
return QuotientRingElement(self.parent(), inv)
return self.parent()(inv)
def __invert__(self): """ EXAMPLES::
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.
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.
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::
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::
return QuotientRingElement(self.parent(), self.__rep.reduce(G))
return self.parent()(self.__rep.reduce(G))
def reduce(self, G): r""" Reduce this quotient ring element by a set of quotient ring elements ``G``.
def __init__(self, polynomial, name=None, check=True, embedding=None, latex_name=None):
def __init__(self, polynomial, name=None, latex_name=None, check=True, embedding=None):
def __init__(self, polynomial, name=None, check=True, embedding=None, latex_name=None): """ Create a quadratic number field.
sage: cmp(c1, 1)
sage: cmp(c1, 1) * cmp(1, c1)
def __cmp__(self, right): r""" Compare ``self`` and ``right``.
if len(value) > parent.degree(): raise ValueError, "list too long" self.__value = pari(0).Mod(parent._pari_modulus())*parent._pari_one() for i in range(len(value)): self.__value = self.__value + pari(int(value[i])).Mod(parent._pari_modulus())*pari("a^%s"%i)
self.__value = (pari(value).Polrev("a") * parent._pari_one()).Mod(parent._pari_modulus())
def __init__(self, parent, value, check=True): """ Create element of a finite field.
more planar areas get fewer triangles, and areas with higher curvature get more triangles
more planar areas get fewer triangles, and areas with higher curvature get more triangles.
def get_colors(self, list): """ Parameters: list: an iterable collection of values which can be cast into colors -- typically an RGB triple, or an RGBA 4-tuple
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.
- ``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.
- ``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.
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.
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.
""" return Vobj.evaluated_on(self)
If you pass a vector, it is assumed to be the coordinate vector of a point:: sage: ineq.eval( vector(ZZ, [3,2]) ) -4 """ try: return Vobj.evaluated_on(self) except AttributeError: return self.A() * Vobj + self.b()
def eval(self, Vobj): r""" Evaluates the left hand side `A\vec{x}+b` on the given vertex/ray/line.
- ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function
- ``algorithm`` - string (default: 'gmp'): - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function
def factorial(n, algorithm='gmp'): r""" Compute the factorial of `n`, which is the product `1\cdot 2\cdot 3 \cdots (n-1)\cdot n`. INPUT: - ``n`` - an integer - ``algorithm`` - string (default: 'gmp') - ``'gmp'`` - use the GMP C-library factorial function - ``'pari'`` - use PARI's factorial function OUTPUT: an integer EXAMPLES:: sage: from sage.rings.arith import factorial sage: factorial(0) 1 sage: factorial(4) 24 sage: factorial(10) 3628800 sage: factorial(1) == factorial(0) True sage: factorial(6) == 6*5*4*3*2 True sage: factorial(1) == factorial(0) True sage: factorial(71) == 71* factorial(70) True sage: factorial(-32) Traceback (most recent call last): ... ValueError: factorial -- must be nonnegative PERFORMANCE: This discussion is valid as of April 2006. All timings below are on a Pentium Core Duo 2Ghz MacBook Pro running Linux with a 2.6.16.1 kernel. - It takes less than a minute to compute the factorial of `10^7` using the GMP algorithm, and the factorial of `10^6` takes less than 4 seconds. - The GMP algorithm is faster and more memory efficient than the PARI algorithm. E.g., PARI computes `10^7` factorial in 100 seconds on the core duo 2Ghz. - For comparison, computation in Magma `\leq` 2.12-10 of `n!` is best done using ``*[1..n]``. It takes 113 seconds to compute the factorial of `10^7` and 6 seconds to compute the factorial of `10^6`. Mathematica V5.2 compute the factorial of `10^7` in 136 seconds and the factorial of `10^6` in 7 seconds. (Mathematica is notably very efficient at memory usage when doing factorial calculations.) """ if n < 0: raise ValueError, "factorial -- must be nonnegative" if algorithm == 'gmp': return ZZ(n).factorial() elif algorithm == 'pari': return pari.factorial(n) else: raise ValueError, 'unknown algorithm'
sage: T = _ArbCoordTrans((x + y, x - y, z), z) sage: f(x, y) = x * y
sage: T = _ArbitraryCoordinates((x + y, x - y, z), z,[x,y]) sage: f(x, y) = 2*x+y
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
[x + y, x - y, x*y] """
(x + y, x - y, 2*x + y) sage: [h(1,2) for h in T.to_cartesian(lambda x,y: 2*x+y)] [3, -1, 4] """
def to_cartesian(self, func, params): """ Returns a 3-tuple of functions, parameterized over ``params``, that represents the cartesian coordinates of the value of ``func``.
sage: from sage.plot.plot3d.plot3d import _ArbCoordTrans
sage: from sage.plot.plot3d.plot3d import _ArbitraryCoordinates
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
sage: T = _ArbCoordTrans((x + y, x - y, z), x) The independent and dependent variables don't really matter in the case of an arbitrary transformation (since it is already in terms of its own variables), so default values are provided:: sage: T.indep_var 'f' sage: T.dep_vars ['u', 'v'] Finally, an example of gen_transform():: sage: T.gen_transform(f=z) [y + z, -y + z, z] """ return [t.subs({self.fvar: f}) for t in self.custom_trans] class Spherical(_CoordTrans):
sage: T = _ArbitraryCoordinates((x + y, x - y, z), x,[y,z]) sage: T.transform(x=z,y=1) (z + 1, z - 1, z) """ return tuple(t.subs(**kwds) for t in self.custom_trans) class Spherical(_Coordinates):
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
- the *radial distance* (``r``), - the *elevation angle* (``theta``), - and the *azimuth angle* (``phi``).
- the *radial distance* (``radius``) from the origin - the *azimuth angle* (``azimuth``) from the positive `x`-axis - the *inclination angle* (``inclination``) from the positive `z`-axis
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
Construct a spherical transformation for a function ``r`` in terms of ``theta`` and ``phi``:: sage: T = Spherical('r', ['phi', 'theta']) If we construct some concrete variables, we can get a transformation::
Construct a spherical transformation for a function for the radius in terms of the azimuth and inclination:: sage: T = Spherical('radius', ['azimuth', 'inclination']) If we construct some concrete variables, we can get a transformation in terms of those variables::
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
sage: T.gen_transform(r=r, theta=theta, phi=phi) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) Use with plot3d on a made-up function:: sage: plot3d(phi * theta, (phi, 0, 1), (theta, 0, 1), transformation=T) To graph a function ``theta`` in terms of ``r`` and ``phi``, you would use:: sage: Spherical('theta', ['r', 'phi']) Spherical coordinate system (theta in terms of r, phi) See also ``spherical_plot3d`` for more examples of plotting in spherical
sage: T.transform(radius=r, azimuth=theta, inclination=phi) (r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)) We can plot with this transform. Remember that the independent variable is the radius, and the dependent variables are the azimuth and the inclination (in that order):: sage: plot3d(phi * theta, (theta, 0, pi), (phi, 0, 1), transformation=T) We next graph the function where the inclination angle is constant:: sage: S=Spherical('inclination', ['radius', 'azimuth']) sage: r,theta=var('r,theta') sage: plot3d(3, (r,0,3), (theta, 0, 2*pi), transformation=S) See also :func:`spherical_plot3d` for more examples of plotting in spherical
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
all_vars = ['r', 'theta', 'phi'] _name = 'Spherical coordinate system' def gen_transform(self, r=None, theta=None, phi=None): """
def transform(self, radius=None, azimuth=None, inclination=None): """ A spherical coordinates transform.
def gen_transform(self, f=None, u=None, v=None): """ EXAMPLE::
sage: T = Spherical('r', ['theta', 'phi']) sage: T.gen_transform(r=var('r'), theta=var('theta'), phi=var('phi')) (r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta)) """ return (r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta)) class Cylindrical(_CoordTrans):
sage: T = Spherical('radius', ['azimuth', 'inclination']) sage: T.transform(radius=var('r'), azimuth=var('theta'), inclination=var('phi')) (r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)) """ return (radius * sin(inclination) * cos(azimuth), radius * sin(inclination) * sin(azimuth), radius * cos(inclination)) class Cylindrical(_Coordinates):
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
- the *radial distance* (``rho``), - the *angular position* or *azimuth* (``phi``), - and the *height* or *altitude* (``z``).
- the *radial distance* (``radius``) from the `z`-axis - the *azimuth angle* (``azimuth``) from the positive `x`-axis - the *height* or *altitude* (``height``) above the `xy`-plane
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
Construct a cylindrical transformation for a function ``rho`` in terms of ``phi`` and ``z``:: sage: T = Cylindrical('rho', ['phi', 'z'])
Construct a cylindrical transformation for a function for ``height`` in terms of ``radius`` and ``azimuth``:: sage: T = Cylindrical('height', ['radius', 'azimuth'])
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
sage: rho, phi, z = var('rho phi z') sage: T.gen_transform(rho=rho, phi=phi, z=z) (rho*cos(phi), rho*sin(phi), z) Use with plot3d on a made-up function:: sage: plot3d(phi * z, (phi, 0, 1), (z, 0, 1), transformation=T) To graph a function ``z`` in terms of ``phi`` and ``rho`` you would use:: sage: Cylindrical('z', ['phi', 'rho']) Cylindrical coordinate system (z in terms of phi, rho) See also ``cylindrical_plot3d`` for more examples of plotting in cylindrical
sage: r, theta, z = var('r theta z') sage: T.transform(radius=r, azimuth=theta, height=z) (r*cos(theta), r*sin(theta), z) We can plot with this transform. Remember that the independent variable is the height, and the dependent variables are the radius and the azimuth (in that order):: sage: plot3d(9-r^2, (r, 0, 3), (theta, 0, pi), transformation=T) We next graph the function where the radius is constant:: sage: S=Cylindrical('radius', ['azimuth', 'height']) sage: theta,z=var('theta, z') sage: plot3d(3, (theta,0,2*pi), (z, -2, 2), transformation=S) See also :func:`cylindrical_plot3d` for more examples of plotting in cylindrical
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
_name = 'Cylindrical coordinate system' all_vars = ['rho', 'phi', 'z'] def gen_transform(self, rho=None, phi=None, z=None): """
def transform(self, radius=None, azimuth=None, height=None): """ A cylindrical coordinates transform.
def gen_transform(self, r=None, theta=None, phi=None): """ EXAMPLE::
"""
r"""
def selmer_group(self, S, m, proof=True): """ Compute the Selmer group `K(S,m)`, which is defined to be the subgroup of `K^\times/(K^\times)^m` consisting of elements `a` such that `K(\sqrt[m]{a})/K` is unramified at all primes of `K` lying above a place outside of `S`.
out = copy.deepcopy(_pik.loads(self._check_types)) return out def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = _pik.dumps(out)
body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs: seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to libraru_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionay, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) body.append(" for func in funcs: body.append(" body.append(" body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f)
def check_types(self, *a, **kw): if self._check_types is None: out = check_types(*a, **kw) self._check_types = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_types)) return out
out = copy.deepcopy(_pik.loads(self._check_ieee_macros)) return out def check_complex(self, *a, **kw): if self._check_complex is None: out = check_complex(*a, **kw) self._check_complex = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_complex)) return out PYTHON_HAS_UNICODE_WIDE = True def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR') def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32' def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" if sys.version[:5] < '2.4.2': nosmp = 1 else:
for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of get_output is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) from distutils.ccompiler import CompileError, LinkError self._check_compiler() exitcode, output = 255, ''
def check_ieee_macros(self, *a, **kw): if self._check_ieee_macros is None: out = check_ieee_macros(*a, **kw) self._check_ieee_macros = _pik.dumps(out) else: out = copy.deepcopy(_pik.loads(self._check_ieee_macros)) return out
nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 return nosmp == 1 def win32_checks(deflist): from numpy.distutils.misc_util import get_build_architecture a = get_build_architecture() print('BUILD_ARCHITECTURE: %r, os.name=%r, sys.platform=%r' % \ (a, os.name, sys.platform)) if a == 'AMD64': deflist.append('DISTUTILS_USE_SDK') if a == "Intel" or a == "AMD64": deflist.append('FORCE_NO_LONG_DOUBLE_FORMATTING') def check_math_capabilities(config, moredefs, mathlibs): def check_func(func_name): return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) def check_funcs_once(funcs_name): decl = dict([(f, True) for f in funcs_name]) st = config.check_funcs_once(funcs_name, libraries=mathlibs, decl=decl, call=decl) if st: moredefs.extend([fname2def(f) for f in funcs_name]) return st def check_funcs(funcs_name): if not check_funcs_once(funcs_name): for f in funcs_name: if check_func(f): moredefs.append(fname2def(f)) return 0 else: return 1 if not check_funcs_once(MANDATORY_FUNCS): raise SystemError("One of the required function to build numpy is not" " available (the list is %s)." % str(MANDATORY_FUNCS)) if sys.version_info[:2] >= (2, 5): for f in OPTIONAL_STDFUNCS_MAYBE: if config.check_decl(fname2def(f), headers=["Python.h", "math.h"]): OPTIONAL_STDFUNCS.remove(f) check_funcs(OPTIONAL_STDFUNCS) check_funcs(C99_FUNCS_SINGLE) check_funcs(C99_FUNCS_EXTENDED) def check_complex(config, mathlibs): priv = [] pub = [] st = config.check_header('complex.h') if st: priv.append('HAVE_COMPLEX_H') pub.append('NPY_USE_C99_COMPLEX') for t in C99_COMPLEX_TYPES: st = config.check_type(t, headers=["complex.h"]) if st: pub.append(('NPY_HAVE_%s' % type2def(t), 1)) def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append(fname2def(f))
src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.') if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: raise KeyboardInterrupt
def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Python 2.3 causes a segfault when # trying to re-acquire the thread-state # which is done in error-handling # ufunc code. NPY_ALLOW_C_API and friends # cause the segfault. So, we disable threading # for now. if sys.version[:5] < '2.4.2': nosmp = 1 else: # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't # block. try: nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 return nosmp == 1
priv.extend([fname2def(f) for f in flist]) check_prec('') check_prec('f') check_prec('l') return priv, pub def check_ieee_macros(config): priv = [] pub = [] macros = [] def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) _macros = ["isnan", "isinf", "signbit", "isfinite"] if sys.version_info[:2] >= (2, 6): for f in _macros: py_symbol = fname2def("decl_%s" % f) already_declared = config.check_decl(py_symbol, headers=["Python.h", "math.h"]) if already_declared: if config.check_macro_true(py_symbol, headers=["Python.h", "math.h"]): pub.append('NPY_%s' % fname2def("decl_%s" % f)) else: macros.append(f) else: macros = _macros[:] for f in macros: st = config.check_decl(f, headers = ["Python.h", "math.h"]) if st: _add_decl(f) return priv, pub def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] expected = {} expected['short'] = [2] expected['int'] = [4] expected['long'] = [8, 4] expected['float'] = [4] expected['double'] = [8] expected['long double'] = [8, 12, 16] expected['Py_intptr_t'] = [4, 8] expected['PY_LONG_LONG'] = [8] expected['long long'] = [8] result = config_cmd.check_header('Python.h') if not result: raise SystemError( "Cannot compile 'Python.h'. Perhaps you need to "\ "install python-dev|python-devel.") res = config_cmd.check_header("endian.h") if res: private_defines.append(('HAVE_ENDIAN_H', 1)) public_defines.append(('NPY_HAVE_ENDIAN_H', 1)) for type in ('short', 'int', 'long'): res = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) if res: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), "SIZEOF_%s" % sym2def(type))) else: res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) for type in ('float', 'double', 'long double'): already_declared = config_cmd.check_decl("SIZEOF_%s" % sym2def(type), headers = ["Python.h"]) res = config_cmd.check_type_size(type, expected=expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) if not already_declared and not type == 'long double': private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) complex_def = "struct {%s __x; %s __y;}" % (type, type) res = config_cmd.check_type_size(complex_def, expected=2*expected[type]) if res >= 0: public_defines.append(('NPY_SIZEOF_COMPLEX_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % complex_def) for type in ('Py_intptr_t',): res = config_cmd.check_type_size(type, headers=["Python.h"], library_dirs=[pythonlib_dir()], expected=expected[type]) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def(type), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def(type), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % type) if config_cmd.check_decl('PY_LONG_LONG', headers=['Python.h']): res = config_cmd.check_type_size('PY_LONG_LONG', headers=['Python.h'], library_dirs=[pythonlib_dir()], expected=expected['PY_LONG_LONG']) if res >= 0: private_defines.append(('SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) public_defines.append(('NPY_SIZEOF_%s' % sym2def('PY_LONG_LONG'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'PY_LONG_LONG') res = config_cmd.check_type_size('long long', expected=expected['long long']) if res >= 0: public_defines.append(('NPY_SIZEOF_%s' % sym2def('long long'), '%d' % res)) else: raise SystemError("Checking sizeof (%s) failed !" % 'long long') if not config_cmd.check_decl('CHAR_BIT', headers=['Python.h']): raise RuntimeError( "Config wo CHAR_BIT is not supported"\ ", please contact the maintainers") return private_defines, public_defines def check_mathlib(config_cmd): mathlibs = [] mathlibs_choices = [[],['m'],['cpml']] mathlib = os.environ.get('MATHLIB') if mathlib: mathlibs_choices.insert(0,mathlib.split(',')) for libs in mathlibs_choices: if config_cmd.check_func("exp", libraries=libs, decl=True, call=True): mathlibs = libs break else: raise EnvironmentError("math library missing; rerun " "setup.py after setting the " "MATHLIB env variable") return mathlibs def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" if config.check_compiler_gcc4(): return '__attribute__((visibility("hidden")))' else: return '' def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs config = Configuration('core',parent_package,top_path) local_dir = config.local_path codegen_dir = join(local_dir,'code_generators') if is_released(config): warnings.simplefilter('error', MismatchCAPIWarning) check_api_version(C_API_VERSION, codegen_dir) generate_umath_py = join(codegen_dir,'generate_umath.py') n = dot_join(config.name,'generate_umath') generate_umath = imp.load_module('_'.join(n.split('.')), open(generate_umath_py,'U'),generate_umath_py, ('.py','U',1)) header_dir = 'include/numpy' cocache = CallOnceOnly() def generate_config_h(ext, build_dir): target = join(build_dir,header_dir,'config.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__,target): config_cmd = config.get_config_cmd() log.info('Generating %s',target) moredefs, ignored = cocache.check_types(config_cmd, ext, build_dir) mathlibs = check_mathlib(config_cmd) moredefs.append(('MATHLIB',','.join(mathlibs))) check_math_capabilities(config_cmd, moredefs, mathlibs) moredefs.extend(cocache.check_ieee_macros(config_cmd)[0]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[0]) if is_npy_no_signal(): moredefs.append('__NPY_PRIVATE_NO_SIGNAL') if sys.platform=='win32' or os.name=='nt': win32_checks(moredefs) inline = config_cmd.check_inline() if not config_cmd.check_decl('Py_UNICODE_WIDE', headers=['Python.h']): PYTHON_HAS_UNICODE_WIDE = True else: PYTHON_HAS_UNICODE_WIDE = False if ENABLE_SEPARATE_COMPILATION: moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1)) if sys.platform != 'darwin': rep = check_long_double_representation(config_cmd) if rep in ['INTEL_EXTENDED_12_BYTES_LE', 'INTEL_EXTENDED_16_BYTES_LE', 'IEEE_QUAD_LE', 'IEEE_QUAD_BE', 'IEEE_DOUBLE_LE', 'IEEE_DOUBLE_BE', 'DOUBLE_DOUBLE_BE']: moredefs.append(('HAVE_LDOUBLE_%s' % rep, 1)) else: raise ValueError("Unrecognized long double format: %s" % rep) if sys.version_info[0] == 3: moredefs.append(('NPY_PY3K', 1)) target_f = open(target, 'w') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' target_f.write(' if inline == 'inline': target_f.write('/* else: target_f.write(' target_f.write(' target_f.write(""" """) target_f.close() print('File:',target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') else: mathlibs = [] target_f = open(target) for line in target_f.readlines(): s = ' if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) target_f.close() if hasattr(ext, 'libraries'): ext.libraries.extend(mathlibs) incl_dir = os.path.dirname(target) if incl_dir not in config.numpy_include_dirs: config.numpy_include_dirs.append(incl_dir) return target def generate_numpyconfig_h(ext, build_dir): """Depends on config.h: generate_config_h has to be called before !""" target = join(build_dir,header_dir,'_numpyconfig.h') d = os.path.dirname(target) if not os.path.exists(d): os.makedirs(d) if newer(__file__,target): config_cmd = config.get_config_cmd() log.info('Generating %s',target) ignored, moredefs = cocache.check_types(config_cmd, ext, build_dir) if is_npy_no_signal(): moredefs.append(('NPY_NO_SIGNAL', 1)) if is_npy_no_smp(): moredefs.append(('NPY_NO_SMP', 1)) else: moredefs.append(('NPY_NO_SMP', 0)) mathlibs = check_mathlib(config_cmd) moredefs.extend(cocache.check_ieee_macros(config_cmd)[1]) moredefs.extend(cocache.check_complex(config_cmd, mathlibs)[1]) if ENABLE_SEPARATE_COMPILATION: moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1)) if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']): moredefs.append(('NPY_USE_C99_FORMATS', 1)) hidden_visibility = visibility_define(config_cmd) moredefs.append(('NPY_VISIBILITY_HIDDEN', hidden_visibility)) moredefs.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION)) moredefs.append(('NPY_API_VERSION', '0x%.8X' % C_API_VERSION)) target_f = open(target, 'w') for d in moredefs: if isinstance(d,str): target_f.write(' else: target_f.write(' target_f.write(""" """) target_f.close() print('File: %s' % target) target_f = open(target) print(target_f.read()) target_f.close() print('EOF') config.add_data_files((header_dir, target)) return target def generate_api_func(module_name): def generate_api(ext, build_dir): script = join(codegen_dir, module_name + '.py') sys.path.insert(0, codegen_dir) try: m = __import__(module_name) log.info('executing %s', script) h_file, c_file, doc_file = m.generate_api(os.path.join(build_dir, header_dir)) finally: del sys.path[0] config.add_data_files((header_dir, h_file), (header_dir, doc_file)) return (h_file,) return generate_api generate_numpy_api = generate_api_func('generate_numpy_api') generate_ufunc_api = generate_api_func('generate_ufunc_api') config.add_include_dirs(join(local_dir, "src", "private")) config.add_include_dirs(join(local_dir, "src")) config.add_include_dirs(join(local_dir)) def generate_multiarray_templated_sources(ext, build_dir): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'multiarray') sources = [join(local_dir, subpath, 'scalartypes.c.src'), join(local_dir, subpath, 'arraytypes.c.src')] config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) def generate_umath_templated_sources(ext, build_dir): from numpy.distutils.misc_util import get_cmd subpath = join('src', 'umath') sources = [join(local_dir, subpath, 'loops.c.src'), join(local_dir, subpath, 'umathmodule.c.src')] config.add_include_dirs(join(build_dir, subpath)) cmd = get_cmd('build_src') cmd.ensure_finalized() cmd.template_sources(sources, ext) def generate_umath_c(ext,build_dir): target = join(build_dir,header_dir,'__umath_generated.c') dir = os.path.dirname(target) if not os.path.exists(dir): os.makedirs(dir) script = generate_umath_py if newer(script,target): f = open(target,'w') f.write(generate_umath.make_code(generate_umath.defdict, generate_umath.__file__)) f.close() return [] config.add_data_files('include/numpy/*.h') config.add_include_dirs(join('src', 'npymath')) config.add_include_dirs(join('src', 'multiarray')) config.add_include_dirs(join('src', 'umath')) config.numpy_include_dirs.extend(config.paths('include')) deps = [join('src','npymath','_signbit.c'), join('include','numpy','*object.h'), 'include/numpy/fenv/fenv.c', 'include/numpy/fenv/fenv.h', join(codegen_dir,'genapi.py'), ] if sys.platform == 'cygwin': config.add_data_dir('include/numpy/fenv') config.add_extension('_sort', sources=[join('src','_sortmodule.c.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, ], ) subst_dict = dict([("sep", os.path.sep), ("pkgname", "numpy.core")]) def get_mathlib_info(*args): config_cmd = config.get_config_cmd() st = config_cmd.try_link('int main(void) { return 0;}') if not st: raise RuntimeError("Broken toolchain: cannot link a simple C program") mlibs = check_mathlib(config_cmd) posix_mlib = ' '.join(['-l%s' % l for l in mlibs]) msvc_mlib = ' '.join(['%s.lib' % l for l in mlibs]) subst_dict["posix_mathlib"] = posix_mlib subst_dict["msvc_mathlib"] = msvc_mlib config.add_installed_library('npymath', sources=[join('src', 'npymath', 'npy_math.c.src'), join('src', 'npymath', 'ieee754.c.src'), join('src', 'npymath', 'npy_math_complex.c.src'), get_mathlib_info], install_dir='lib') config.add_npy_pkg_config("npymath.ini.in", "lib/npy-pkg-config", subst_dict) config.add_npy_pkg_config("mlib.ini.in", "lib/npy-pkg-config", subst_dict) multiarray_deps = [ join('src', 'multiarray', 'arrayobject.h'), join('src', 'multiarray', 'arraytypes.h'), join('src', 'multiarray', 'buffer.h'), join('src', 'multiarray', 'calculation.h'), join('src', 'multiarray', 'common.h'), join('src', 'multiarray', 'convert_datatype.h'), join('src', 'multiarray', 'convert.h'), join('src', 'multiarray', 'conversion_utils.h'), join('src', 'multiarray', 'ctors.h'), join('src', 'multiarray', 'descriptor.h'), join('src', 'multiarray', 'getset.h'), join('src', 'multiarray', 'hashdescr.h'), join('src', 'multiarray', 'iterators.h'), join('src', 'multiarray', 'mapping.h'), join('src', 'multiarray', 'methods.h'), join('src', 'multiarray', 'multiarraymodule.h'), join('src', 'multiarray', 'numpymemoryview.h'), join('src', 'multiarray', 'number.h'), join('src', 'multiarray', 'numpyos.h'), join('src', 'multiarray', 'refcount.h'), join('src', 'multiarray', 'scalartypes.h'), join('src', 'multiarray', 'sequence.h'), join('src', 'multiarray', 'shape.h'), join('src', 'multiarray', 'ucsnarrow.h'), join('src', 'multiarray', 'usertypes.h')] multiarray_src = [join('src', 'multiarray', 'multiarraymodule.c'), join('src', 'multiarray', 'hashdescr.c'), join('src', 'multiarray', 'arrayobject.c'), join('src', 'multiarray', 'numpymemoryview.c'), join('src', 'multiarray', 'buffer.c'), join('src', 'multiarray', 'numpyos.c'), join('src', 'multiarray', 'conversion_utils.c'), join('src', 'multiarray', 'flagsobject.c'), join('src', 'multiarray', 'descriptor.c'), join('src', 'multiarray', 'iterators.c'), join('src', 'multiarray', 'mapping.c'), join('src', 'multiarray', 'number.c'), join('src', 'multiarray', 'getset.c'), join('src', 'multiarray', 'sequence.c'), join('src', 'multiarray', 'methods.c'), join('src', 'multiarray', 'ctors.c'), join('src', 'multiarray', 'convert_datatype.c'), join('src', 'multiarray', 'convert.c'), join('src', 'multiarray', 'shape.c'), join('src', 'multiarray', 'item_selection.c'), join('src', 'multiarray', 'calculation.c'), join('src', 'multiarray', 'common.c'), join('src', 'multiarray', 'usertypes.c'), join('src', 'multiarray', 'scalarapi.c'), join('src', 'multiarray', 'refcount.c'), join('src', 'multiarray', 'arraytypes.c.src'), join('src', 'multiarray', 'scalartypes.c.src')] if PYTHON_HAS_UNICODE_WIDE: multiarray_src.append(join('src', 'multiarray', 'ucsnarrow.c')) umath_src = [join('src', 'umath', 'umathmodule.c.src'), join('src', 'umath', 'funcs.inc.src'), join('src', 'umath', 'loops.c.src'), join('src', 'umath', 'ufunc_object.c')] umath_deps = [generate_umath_py, join(codegen_dir,'generate_ufunc_api.py')] if not ENABLE_SEPARATE_COMPILATION: multiarray_deps.extend(multiarray_src) multiarray_src = [join('src', 'multiarray', 'multiarraymodule_onefile.c')] multiarray_src.append(generate_multiarray_templated_sources) umath_deps.extend(umath_src) umath_src = [join('src', 'umath', 'umathmodule_onefile.c')] umath_src.append(generate_umath_templated_sources) umath_src.append(join('src', 'umath', 'funcs.inc.src')) config.add_extension('multiarray', sources = multiarray_src + [generate_config_h, generate_numpyconfig_h, generate_numpy_api, join(codegen_dir,'generate_numpy_api.py'), join('*.py')], depends = deps + multiarray_deps, libraries=['npymath']) config.add_extension('umath', sources = [generate_config_h, generate_numpyconfig_h, generate_umath_c, generate_ufunc_api, ] + umath_src, depends = deps + umath_deps, libraries=['npymath'], ) config.add_extension('scalarmath', sources=[join('src','scalarmathmodule.c.src'), generate_config_h, generate_numpyconfig_h, generate_numpy_api, generate_ufunc_api], ) blas_info = get_info('blas_opt',0) def get_dotblas_sources(ext, build_dir): if blas_info: if ('NO_ATLAS_INFO',1) in blas_info.get('define_macros',[]): return None return ext.depends[:1] return None config.add_extension('_dotblas', sources = [get_dotblas_sources], depends=[join('blasdot','_dotblas.c'), join('blasdot','cblas.h'), ], include_dirs = ['blasdot'], extra_info = blas_info ) config.add_extension('umath_tests', sources = [join('src','umath', 'umath_tests.c.src')]) config.add_extension('multiarray_tests', sources = [join('src', 'multiarray', 'multiarray_tests.c.src')]) config.add_data_dir('tests') config.add_data_dir('tests/data') config.make_svn_version_py() return config if __name__=='__main__': from numpy.distutils.core import setup setup(configuration=configuration)
exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output
def check_prec(prec): flist = [f + prec for f in C99_COMPLEX_FUNCS] decl = dict([(f, True) for f in flist]) if not config.check_funcs_once(flist, call=decl, decl=decl, libraries=mathlibs): for f in flist: if config.check_func(f, call=True, decl=True, libraries=mathlibs): priv.append(fname2def(f)) else: priv.extend([fname2def(f) for f in flist])
sage: maxima.eval('sage0: x == x;')
sage: maxima._eval_line('sage0: x == x;')
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
TypeError: error evaluating "sage0: x == x;":...
TypeError: Error executing code in Maxima...
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
pre_out = self._before() self._expect_expr() out = self._before()
out = self._before()
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
self._error_check(line, pre_out)
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
i = o.rfind('(%o') return o[:i]
def _eval_line(self, line, allow_use_file=False, wait_for_prompt=True, reformat=True, error_check=True): """ EXAMPLES:
for _ in range(3):
for _ in range(5):
def _command_runner(self, command, s, redirect=True): """ Run ``command`` in a new Maxima session and return its output as an ``AsciiArtString``.
'5.20.1'
'5.22.1'
def version(self): """ Return the version of Maxima that Sage includes.
sage: f = attrcall('core', 3) sage: loads(dumps(f))
sage: f = attrcall('core', 3); f
def __init__(self, name, args, kwds): """ TESTS::
- ``algorithm`` - string (default: 'recursive') specifying which algorithm to be used when computing the iterated palindromic closure. It must be one of the two following values: - ``'definition'`` means that the iterated right palindromic closure is computed using the definition. - ``'recursive'`` is based on an efficient formula that recursively computes the iterated right palindromic closure without having to recompute the longest `f`-palindromic suffix at each iteration [2].
- ``algorithm`` - string (default: ``'recursive'``) specifying which algorithm to be used when computing the iterated palindromic closure. It must be one of the two following values: - ``'definition'`` - computed using the definition - ``'recursive'`` - computation based on an efficient formula that recursively computes the iterated right palindromic closure without having to recompute the longest `f`-palindromic suffix at each iteration [2].
def iterated_right_palindromic_closure(self, f=None, algorithm='recursive'): r""" Returns the iterated (`f`-)palindromic closure of self.
l = len(sub)
L = len(sub)
def find(self, sub, start=0, end=None): r""" Returns the index of the first occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
i = len(self) - l
i = len(self) - L
def find(self, sub, start=0, end=None): r""" Returns the index of the first occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
i = start - l
i = start - L
def find(self, sub, start=0, end=None): r""" Returns the index of the first occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
if self[i:i+l] == sub: return i
if self[i:i+L] == sub: return i
def find(self, sub, start=0, end=None): r""" Returns the index of the first occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
l = len(sub)
L = len(sub)
def rfind(self, sub, start=0, end=None): r""" Returns the index of the last occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
i = len(self) - l
i = len(self) - L
def rfind(self, sub, start=0, end=None): r""" Returns the index of the last occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
i = end - l
i = end - L
def rfind(self, sub, start=0, end=None): r""" Returns the index of the last occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
if self[i:i+l] == sub: return i
if self[i:i+L] == sub: return i
def rfind(self, sub, start=0, end=None): r""" Returns the index of the last occurrence of sub in self, such that sub is contained within self[start:end]. Returns -1 on failure.
if order is Infinity:
if order == 1: if isinstance(w, (tuple,str,list)): length = 'finite' elif isinstance(w, FiniteWord_class): length = sum(self._morph[a].length() * b for (a,b) in w.evaluation_dict().iteritems()) elif hasattr(w, '__iter__'): length = Infinity datatype = 'iter' elif w in self._domain.alphabet(): return self._morph[w] else: raise TypeError, "Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w return self.codomain()((x for y in w for x in self._morph[y]), length=length, datatype=datatype) elif order is Infinity:
def __call__(self, w, order=1, datatype='iter'): r""" Returns the image of ``w`` under self to the given order.
if not isinstance(order, (int,Integer)) or order < 0 : raise TypeError, "order (%s) must be a positive integer or plus Infinity" % order
elif isinstance(order, (int,Integer)) and order > 1: return self(self(w, order-1),datatype=datatype)
def __call__(self, w, order=1, datatype='iter'): r""" Returns the image of ``w`` under self to the given order.
elif order == 1: if isinstance(w, (tuple,str,list)): length = 'finite' elif isinstance(w, FiniteWord_class): length = sum(self._morph[a].length() * b for (a,b) in w.evaluation_dict().iteritems()) elif hasattr(w, '__iter__'): length = Infinity datatype = 'iter' elif w in self._domain.alphabet(): w = [w] length = 'finite' else: raise TypeError, "Don't know how to handle an input (=%s) that is not iterable or not in the domain alphabet."%w return self.codomain()((x for y in w for x in self._morph[y]), length=length, datatype=datatype) elif order > 1: return self(self(w, order-1),datatype=datatype)
else: raise TypeError, "order (%s) must be a positive integer or plus Infinity" % order
def __call__(self, w, order=1, datatype='iter'): r""" Returns the image of ``w`` under self to the given order.
image = self(letter)
image = self.image(letter)
def is_prolongable(self, letter): r""" Returns ``True`` if ``self`` is prolongable on ``letter``.
return sage_eval(x, self.gens_dict())
return self(sage_eval(x, self.gens_dict()))
def __call__(self, x, check=True): """ Convert ``x`` to an element of this multivariate polynomial ring, possibly non-canonically.
.. warning:: This function calls a Singular function that appears to be very buggy and should not be trusted.
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`.
- ``sort`` - bool (default: True), if True return the point list sorted. If False, returns the points in the order computed by Singular.
- ``D`` - a divisor OUTPUT: A list of function field elements that form a basis of the Riemann-Roch space
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`.
sage: D = C.divisor([ (4, pts[0]), (0,pts[1]), (4, pts[2]) ])
sage: D = C.divisor([ (4, pts[0]), (4, pts[2]) ])
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`.
The following example illustrates that the Riemann-Roch space function in Singular doesn't *not* work correctly.
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`.
sage: C.riemann_roch_basis(D) [x/(y + x), (z + y)/(y + x)] The answer has dimension 2 (confirmed via Magma). But it varies between 1 and quite large with Singular.
sage: C.riemann_roch_basis(D) [(-2*x + y)/(x + y), (-x + z)/(x + y)] .. NOTE:: Currently this only works over prime field and divisors supported on rational points.
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`.