rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
AssertionError: morphims is not triangular on 1
AssertionError: morphism is not triangular on 1
def _test_triangular(self, **options): """ Tests that ``self`` is actually triangular
AssertionError: morphims is not untriangular on 1
AssertionError: morphism is not untriangular on 1
def _test_triangular(self, **options): """ Tests that ``self`` is actually triangular
LazyFormat("morphims is not untriangular on %s")%(x))
LazyFormat("morphism is not untriangular on %s")%(x))
def _test_triangular(self, **options): """ Tests that ``self`` is actually triangular
LazyFormat("morphims is not triangular on %s")%(x))
LazyFormat("morphism is not triangular on %s")%(x))
def _test_triangular(self, **options): """ Tests that ``self`` is actually triangular
depends = ["sage/libs/mwrank/wrap.h"],
depends = ["sage/libs/mwrank/wrap.h"] + [ SAGE_INC + "eclib/" + h for h in ["curve.h","egr.h","descent.h","points.h","isogs.h", "marith.h","htconst.h","interface.h"] ],
def uname_specific(name, value, alternative): if name in os.uname()[0]: return value else: return alternative
define_macros = [("NTL_ALL",None)]),
define_macros = [("NTL_ALL",None)], depends = [ SAGE_INC + "eclib/" + h for h in ["interface.h","bigrat.h","rat.h","curve.h", "moddata.h","symb.h","cusp.h","homspace.h","mat.h"] ]),
def uname_specific(name, value, alternative): if name in os.uname()[0]: return value else: return alternative
define_macros = [("NTL_ALL",None)]),
define_macros = [("NTL_ALL",None)], depends = [ SAGE_INC + "eclib/" + h for h in ["interface.h","bigrat.h","rat.h","curve.h", "moddata.h","symb.h","cusp.h","xsplit.h","method.h", "oldforms.h","homspace.h","cperiods.h","newforms.h"] ]),
def uname_specific(name, value, alternative): if name in os.uname()[0]: return value else: return alternative
basis = matrix( M.columns() + M.integer_kernel().basis() ).transpose() self._dual_embedding_scale = basis.det()
basis = M.columns() + M.integer_kernel().basis() basis = matrix(basis).transpose() self._dual_embedding_scale = abs(basis.det())
def _compute_dim(self, compute_vertices): r""" Compute the dimension of this polytope and its vertices, if necessary. If ``compute_vertices`` is ``True``, then ``self._vertices`` should contain points whose convex hull will be computed and placed back into ``self._vertices``. If the dimension of this polytope is not equal to its ambient dimension, auxiliary polytope will be created and stored for using PALP commands. TESTS:: sage: p = LatticePolytope(matrix([1, 2, 3]), compute_vertices=False) sage: p.vertices() # wrong, since these were not vertices [1 2 3] sage: hasattr(p, "_dim") False sage: p._compute_dim(compute_vertices=True) sage: p.vertices() [1 3] sage: p._dim 1 """ if hasattr(self, "_dim"): return if compute_vertices: points = [] for point in self._vertices.columns(copy=False): if not point in points: points.append(point) else: points = self._vertices.columns(copy=False) p0 = points[0] if p0 != 0: points = [point - p0 for point in points] N = ZZ**self.ambient_dim() H = N.submodule(points) self._dim = H.rank() if self._dim == 0: if compute_vertices: self._vertices = matrix(p0).transpose() elif self._dim == self.ambient_dim(): if compute_vertices: if len(points) < self._vertices.ncols(): # Repeated vertices if p0 != 0: points = [point + p0 for point in points] self._vertices = matrix(ZZ, points).transpose() self._vertices = read_palp_matrix(self.poly_x("v")) else: # Setup auxiliary polytope and maps H = H.saturation() H_points = [H.coordinates(point) for point in points] H_polytope = LatticePolytope(matrix(ZZ, H_points).transpose(), compute_vertices=True) self._sublattice = H self._sublattice_polytope = H_polytope self._embedding_matrix = H.basis_matrix().transpose() self._shift_vector = p0 if compute_vertices: self._vertices = self._embed(H_polytope.vertices())
A lattice polytope of strictly smaller dimension (=2) than the ambient dimension(=4):: sage: LatticePolytope(matrix([(1, -1, 0), (-1, -1, 0), (1, 1, 0), (3, 3, 0)]))
This is a 2-dimensional lattice polytope in a 4-dimensional space:: sage: m = matrix([(1,-1,1,3), (-1,-1,1,3), (0,0,0,0)]) sage: p = LatticePolytope(m.transpose()) sage: p
def facet_constant(self, i): r""" Return the constant in the ``i``-th facet inequality of this polytope. The i-th facet inequality is given by self.facet_normal(i) * X + self.facet_constant(i) >= 0. INPUT: - ``i`` - integer, the index of the facet OUTPUT: - integer -- the constant in the ``i``-th facet inequality. EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
sage: lp = LatticePolytope(matrix([(1, -1, 0), (-1, -1, 0), (1, 1, 0), (3, 3, 0)])) sage: lp.vertices()
sage: p.vertices()
def facet_constant(self, i): r""" Return the constant in the ``i``-th facet inequality of this polytope. The i-th facet inequality is given by self.facet_normal(i) * X + self.facet_constant(i) >= 0. INPUT: - ``i`` - integer, the index of the facet OUTPUT: - integer -- the constant in the ``i``-th facet inequality. EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
sage: matrix([[ lp.facet_normal(i)*lp.vertex(j) + lp.facet_constant(i) for i in range(0,3)] for j in range(0,3)]) [-22 0 0] [ 0 -22 0] [ 0 0 -11]
sage: fns = [p.facet_normal(i) for i in range(p.nfacets())] sage: fns [(11, -1, 1, 3), (-11, -1, 1, 3), (0, 1, -1, -3)] sage: fcs = [p.facet_constant(i) for i in range(p.nfacets())] sage: fcs [0, 0, 11] Now we manually compute the distance matrix of this polytope. Since it is a triangle, each line (corresponding to a facet) should have two zeros (vertices of the corresponding facet) and one positive number (since our normals are inner):: sage: matrix([[fns[i] * p.vertex(j) + fcs[i] ... for j in range(p.nvertices())] ... for i in range(p.nfacets())]) [22 0 0] [ 0 22 0] [ 0 0 11]
def facet_constant(self, i): r""" Return the constant in the ``i``-th facet inequality of this polytope. The i-th facet inequality is given by self.facet_normal(i) * X + self.facet_constant(i) >= 0. INPUT: - ``i`` - integer, the index of the facet OUTPUT: - integer -- the constant in the ``i``-th facet inequality. EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
parallel to the affine subspace spanned by this polytope.
orthogonal to the integer kernel of the affine subspace spanned by this polytope.
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``i``-th facet EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
Here is an example of a 3-dimensional polytope in 4d:: sage: lp = LatticePolytope(matrix([[1,1,-1,0],[1,-1,-1,0],[1,1,1,0],[3,3,3,0]])) sage: lp.vertices() [ 1 1 -1 0] [ 1 -1 -1 0] [ 1 1 1 0] [ 3 3 3 0] sage: ker = lp.vertices().integer_kernel().matrix()
Here is an example of a 3-dimensional polytope in a 4-dimensional space:: sage: m = matrix([(0,0,0,0), (1,1,1,3), (1,-1,1,3), (-1,-1,1,3)]) sage: p = LatticePolytope(m.transpose()) sage: p.vertices() [ 0 1 1 -1] [ 0 1 -1 -1] [ 0 1 1 1] [ 0 3 3 3] sage: ker = p.vertices().integer_kernel().matrix()
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``i``-th facet EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
sage: [ ker * lp.facet_normal(i) for i in range(0,4) ]
sage: [ker * p.facet_normal(i) for i in range(p.nfacets())]
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``i``-th facet EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
sage: matrix([lp.facet_normal(i) for i in range(0,4)]) * lp.vertices() [ 0 0 -20 0] [ 0 -20 0 0] [ 10 10 10 0] [-20 0 0 0] sage: matrix([[ lp.facet_normal(i)*lp.vertex(j) + lp.facet_constant(i) for i in range(0,4)] for j in range(0,4)]) [ 0 0 0 -20] [ 0 -20 0 0] [-20 0 0 0] [ 0 0 -10 0]
Now we manually compute the distance matrix of this polytope. Since it is a simplex, each line (corresponding to a facet) should consist of zeros (indicating generating vertices of the corresponding facet) and a single positive number (since our normals are inner):: sage: matrix([[p.facet_normal(i) * p.vertex(j) ... + p.facet_constant(i) ... for j in range(p.nvertices())] ... for i in range(p.nfacets())]) [ 0 0 0 20] [ 0 0 20 0] [ 0 20 0 0] [10 0 0 0]
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``i``-th facet EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1
Returns a list of the immediate super categories of self.
Returns a list of the immediate super categories of ``self``.
def super_categories(self): """ Returns a list of the immediate super categories of self.
- often uses self.one().
- often uses ``self.one()``.
def one(self): r""" Returns the one of the monoid, that is the unique neutral element for `*`.
Backward compatibility alias for :meth:`self.one()`.
Backward compatibility alias for :meth:`one`.
def one_element(self): r""" Backward compatibility alias for :meth:`self.one()`.
Returns the product of the elements in `args`, as an element of `self`. EXAMPLES:
Returns the product of the elements in ``args``, as an element of ``self``. EXAMPLES::
def prod(self, args): r""" n-ary product
Returns whether self is the one of the monoid
Returns whether ``self`` is the one of the monoid
def is_one(self): r""" Returns whether self is the one of the monoid
- n: a non negative integer
- ``n``: a non negative integer
def __pow__(self, n): r""" INPUTS: - n: a non negative integer
A naive implementation of __pow__
A naive implementation of ``__pow__``
def _pow_naive(self, n): r""" A naive implementation of __pow__
- n: a non negative integer
- ``n``: a non negative integer
def _pow_naive(self, n): r""" A naive implementation of __pow__
faster du to size explotion).
faster due to size explosion).
def _pow_naive(self, n): r""" A naive implementation of __pow__
sage: latex(maxima(derivative(ceil(x*y*d), d,x,x,y))) d^3\,\left({{{\it \partial}^4}\over{{\it \partial}\,d^4}}\, {\it ceil}\left(d , x , y\right)\right)\,x^2\,y^3+5\,d^2\,\left({{ {\it \partial}^3}\over{{\it \partial}\,d^3}}\,{\it ceil}\left(d , x , y\right)\right)\,x\,y^2+4\,d\,\left({{{\it \partial}^2}\over{ {\it \partial}\,d^2}}\,{\it ceil}\left(d , x , y\right)\right)\,y
sage: f = function('f') sage: latex(maxima(derivative(f(x*y*d), d,x,x,y))) Traceback (most recent call last): ... NotImplementedError: arguments must be distinct variables sage: latex(maxima(derivative(f(x,y,d), d,x,x,y))) {{{\it \partial}^4}\over{{\it \partial}\,d\,{\it \partial}\,x^2\, {\it \partial}\,y}}\,f\left(x , y , d\right)
def _latex_(self): """ Return Latex representation of this Maxima object. This calls the tex command in Maxima, then does a little post-processing to fix bugs in the resulting Maxima output. EXAMPLES:: sage: maxima('sqrt(2) + 1/3 + asin(5)')._latex_() '\\sin^{-1}\\cdot5+\\sqrt{2}+{{1}\\over{3}}'
nr_common = len(reduce(sets.Set.intersection, \ [sets.Set(c1[r]), sets.Set(c2[c]), sets.Set(c3[s])]))
nr_common = len(reduce(set.intersection, \ [set(c1[r]), set(c2[c]), set(c3[s])]))
def tau_to_bitrade(t1, t2, t3): """ Given permutations t1, t2, t3 that represent a latin bitrade, convert them to an explicit latin bitrade (T1, T2). The result is unique up to isotopism. EXAMPLE:: sage: from sage.combinat.matrices.latin import * sage: T1 = back_circulant(5) sage: x = isotopism( (0,1,2,3,4) ) sage: y = isotopism(5) # identity sage: z = isotopism(5) # identity sage: T2 = T1.apply_isotopism(x, y, z) sage: _, t1, t2, t3 = tau123(T1, T2) sage: U1, U2 = tau_to_bitrade(t1, t2, t3) sage: assert is_bitrade(U1, U2) sage: U1 [0 1 2 3 4] [1 2 3 4 0] [2 3 4 0 1] [3 4 0 1 2] [4 0 1 2 3] sage: U2 [4 0 1 2 3] [0 1 2 3 4] [1 2 3 4 0] [2 3 4 0 1] [3 4 0 1 2] """ c1 = t1.to_cycles() c2 = t2.to_cycles() c3 = t3.to_cycles() pt_to_cycle1 = {} pt_to_cycle2 = {} pt_to_cycle3 = {} for i in range(len(c1)): for j in range(len(c1[i])): pt_to_cycle1[c1[i][j]] = i for i in range(len(c2)): for j in range(len(c2[i])): pt_to_cycle2[c2[i][j]] = i for i in range(len(c3)): for j in range(len(c3[i])): pt_to_cycle3[c3[i][j]] = i n = max(len(c1), len(c2), len(c3)) T1 = LatinSquare(n) T2 = LatinSquare(n) for r in range(len(c1)): for c in range(len(c2)): for s in range(len(c3)): nr_common = len(reduce(sets.Set.intersection, \ [sets.Set(c1[r]), sets.Set(c2[c]), sets.Set(c3[s])])) assert nr_common in [0, 1] if nr_common == 1: T1[r, c] = s for cycle in c1: for pt1 in cycle: pt2 = t1[pt1 - 1] pt3 = t2[pt2 - 1] assert t3[pt3 - 1] == pt1 r = pt_to_cycle1[pt1] c = pt_to_cycle2[pt2] s = pt_to_cycle3[pt3] T2[r, c] = s return T1, T2
val1 = sets.Set(filter(lambda x: x >= 0, T1.row(r))) val2 = sets.Set(filter(lambda x: x >= 0, T2.row(r)))
val1 = set(filter(lambda x: x >= 0, T1.row(r))) val2 = set(filter(lambda x: x >= 0, T2.row(r)))
def is_row_and_col_balanced(T1, T2): """ Partial latin squares T1 and T2 are balanced if the symbols appearing in row r of T1 are the same as the symbols appearing in row r of T2, for each r, and if the same condition holds on columns. EXAMPLES:: sage: from sage.combinat.matrices.latin import * sage: T1 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: T2 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: is_row_and_col_balanced(T1, T2) True sage: T2 = matrix([[0,3,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: is_row_and_col_balanced(T1, T2) False """ for r in range(T1.nrows()): val1 = sets.Set(filter(lambda x: x >= 0, T1.row(r))) val2 = sets.Set(filter(lambda x: x >= 0, T2.row(r))) if val1 != val2: return False for c in range(T1.ncols()): val1 = sets.Set(filter(lambda x: x >= 0, T1.column(c))) val2 = sets.Set(filter(lambda x: x >= 0, T2.column(c))) if val1 != val2: return False return True
val1 = sets.Set(filter(lambda x: x >= 0, T1.column(c))) val2 = sets.Set(filter(lambda x: x >= 0, T2.column(c)))
val1 = set(filter(lambda x: x >= 0, T1.column(c))) val2 = set(filter(lambda x: x >= 0, T2.column(c)))
def is_row_and_col_balanced(T1, T2): """ Partial latin squares T1 and T2 are balanced if the symbols appearing in row r of T1 are the same as the symbols appearing in row r of T2, for each r, and if the same condition holds on columns. EXAMPLES:: sage: from sage.combinat.matrices.latin import * sage: T1 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: T2 = matrix([[0,1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: is_row_and_col_balanced(T1, T2) True sage: T2 = matrix([[0,3,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1], [-1,-1,-1,-1]]) sage: is_row_and_col_balanced(T1, T2) False """ for r in range(T1.nrows()): val1 = sets.Set(filter(lambda x: x >= 0, T1.row(r))) val2 = sets.Set(filter(lambda x: x >= 0, T2.row(r))) if val1 != val2: return False for c in range(T1.ncols()): val1 = sets.Set(filter(lambda x: x >= 0, T1.column(c))) val2 = sets.Set(filter(lambda x: x >= 0, T2.column(c))) if val1 != val2: return False return True
sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1)
sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1)
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean 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)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) for g in f]
f = [equify(g) for g in f]
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean 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)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (-1.1, 1.1), (-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] variables = reduce(lambda g1, g2: g1.union(g2), [set(g.variables()) for g in f], set([])) f = [equify(g, variables) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
def equify(f, variables = None):
def equify(f):
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
x |--> x^2 - 2
x^2 - 2
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
x |--> -x^2 + 2
-x^2 + 2
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
(x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y
-x*y + 1 sage: equify(y > 0) -y
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
if variables == None: variables = f.variables()
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s
return symbolic_expression(f.rhs() - f.lhs())
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
return symbolic_expression(f.lhs() - f.rhs())
def equify(f, variables = None): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x |--> x^2 - 2 sage: equify(x^2 > 2) x |--> -x^2 + 2 sage: equify(x*y > 1) (x, y) |--> -x*y + 1 sage: equify(y > 0, (x,y)) (x, y) |--> -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if variables == None: variables = f.variables() if op is operator.gt or op is operator.ge: s = symbolic_expression(f.rhs() - f.lhs()).function(*variables) return s else: s = symbolic_expression(f.lhs() - f.rhs()).function(*variables) return s
Returns the intermediate shape of the pm diagram (innner shape plus positions of plusses)
Returns the intermediate shape of the pm diagram (inner shape plus positions of plusses)
def intermediate_shape(self): """ Returns the intermediate shape of the pm diagram (innner shape plus positions of plusses)
p = p + [0,0]
p = p + [0 for i in range(self.n)]
def intermediate_shape(self): """ Returns the intermediate shape of the pm diagram (innner shape plus positions of plusses)
.. 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`. .. warning::
- ``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`. .. warning::
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`. .. warning::
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`. .. warning::
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`. .. warning::
X3 = singular.extcurve(1, X2) R = X3[1][5]
v = X2[3].sage_flattened_str_list() v = [ v[i].partition(',') for i in range(len(v)) ] pnts = [ ( int(v[i][0]), int(v[i][2])-1 ) for i in range(len(v))] R = X2[5][1][1]
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`. .. warning::
pnts = [self(int(v[3*i]), int(v[3*i+1]), int(v[3*i+2])) for i in range(len(v)/3)]
coords = [self(int(v[3*i]), int(v[3*i+1]), int(v[3*i+2])) for i in range(len(v)/3)]
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`. .. warning::
Dcoeffs.append(D.coefficient(x))
if x[0] == 1: Dcoeffs.append(D.coefficient(coords[x[1]])) else: Dcoeffs.append(0)
def riemann_roch_basis(self, D): r""" Return a basis for the Riemann-Roch space corresponding to `D`. .. warning::
"""
sage: def square_for_met(f): ... @sage_wraps(f) ... def new_f(self, x): ... return f(self,x)*f(self,x) ... return new_f sage: class T: ... @square_for_met ... def g(self, x): ... "My little method" ... return x sage: t = T() sage: t.g(2) 4 sage: t.g._sage_src_() ' @square_for_met...def g(self, x)...' sage: t.g.__doc__ 'My little method' """ assigned= set(assigned).intersection(set(dir(wrapped)))
'@square...def g(x)...'
0.85914091422952255
0.859140914229522...
def integral(f, *args, **kwds): r""" The integral of `f`. EXAMPLES:: sage: integral(sin(x), x) -cos(x) sage: integral(sin(x)^2, x, pi, 123*pi/2) 121/4*pi sage: integral( sin(x), x, 0, pi) 2 We integrate a symbolic function:: sage: f(x,y,z) = x*y/z + sin(z) sage: integral(f, z) (x, y, z) |--> x*y*log(z) - cos(z) :: sage: var('a,b') (a, b) sage: assume(b-a>0) sage: integral( sin(x), x, a, b) cos(a) - cos(b) sage: forget() :: sage: integral(x/(x^3-1), x) 1/3*sqrt(3)*arctan(1/3*(2*x + 1)*sqrt(3)) + 1/3*log(x - 1) - 1/6*log(x^2 + x + 1) :: sage: integral( exp(-x^2), x ) 1/2*sqrt(pi)*erf(x) We define the Gaussian, plot and integrate it numerically and symbolically:: sage: f(x) = 1/(sqrt(2*pi)) * e^(-x^2/2) sage: P = plot(f, -4, 4, hue=0.8, thickness=2) sage: P.show(ymin=0, ymax=0.4) sage: numerical_integral(f, -4, 4) # random output (0.99993665751633376, 1.1101527003413533e-14) sage: integrate(f, x) x |--> 1/2*erf(1/2*sqrt(2)*x) You can have Sage calculate multiple integrals. For example, consider the function `exp(y^2)` on the region between the lines `x=y`, `x=1`, and `y=0`. We find the value of the integral on this region using the command:: sage: area = integral(integral(exp(y^2),x,0,y),y,0,1); area 1/2*e - 1/2 sage: float(area) 0.85914091422952255 We compute the line integral of `\sin(x)` along the arc of the curve `x=y^4` from `(1,-1)` to `(1,1)`:: sage: t = var('t') sage: (x,y) = (t^4,t) sage: (dx,dy) = (diff(x,t), diff(y,t)) sage: integral(sin(x)*dx, t,-1, 1) 0 sage: restore('x,y') # restore the symbolic variables x and y Sage is unable to do anything with the following integral:: sage: integral( exp(-x^2)*log(x), x ) integrate(e^(-x^2)*log(x), x) Note, however, that:: sage: integral( exp(-x^2)*ln(x), x, 0, oo) -1/4*(euler_gamma + 2*log(2))*sqrt(pi) This definite integral is easy:: sage: integral( ln(x)/x, x, 1, 2) 1/2*log(2)^2 Sage can't do this elliptic integral (yet):: sage: integral(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) integrate(1/sqrt(2*t^4 - 3*t^2 - 2), t, 2, 3) A double integral:: sage: y = var('y') sage: integral(integral(x*y^2, x, 0, y), y, -2, 2) 32/5 This illustrates using assumptions:: sage: integral(abs(x), x, 0, 5) 25/2 sage: integral(abs(x), x, 0, a) integrate(abs(x), x, 0, a) sage: assume(a>0) sage: integral(abs(x), x, 0, a) 1/2*a^2 sage: forget() # forget the assumptions. We integrate and differentiate a huge mess:: sage: f = (x^2-1+3*(1+x^2)^(1/3))/(1+x^2)^(2/3)*x/(x^2+2)^2 sage: g = integral(f, x) sage: h = f - diff(g, x) :: sage: [float(h(i)) for i in range(5)] #random [0.0, -1.1102230246251565e-16, -5.5511151231257827e-17, -5.5511151231257827e-17, -6.9388939039072284e-17] sage: h.factor() 0 sage: bool(h == 0) True """ try: return f.integral(*args, **kwds) except AttributeError: pass if not isinstance(f, Expression): f = SR(f) return f.integral(*args, **kwds)
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]):
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=None):
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. Given a list of points, i.e. tuples of elements of ``self``'s base ring, this function returns the interpolation polynomial in the Lagrange form.
- ``previous_row`` -- (default: ``[]``) This option is only relevant
- ``previous_row`` -- (default: ``None``) This option is only relevant
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. Given a list of points, i.e. tuples of elements of ``self``'s base ring, this function returns the interpolation polynomial in the Lagrange form.
The return value should always be an element of ``self'', in the case of ``divided_difference'', or a list of elements of ``self'', in the case of ``neville''::
Make sure that ticket be an element of ``self`` in the case of ``divided_difference``, or a list of elements of ``self`` in the case of ``neville``. ::
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. Given a list of points, i.e. tuples of elements of ``self``'s base ring, this function returns the interpolation polynomial in the Lagrange form.
libraries=['polybori','pboriCudd', 'groebner', 'gd', 'png', 'm4ri'],
libraries=['polybori','pboriCudd', 'groebner', 'gd', 'png12', 'm4ri'],
def uname_specific(name, value, alternative): if name in os.uname()[0]: return value else: return alternative
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. EXAMPLES:: sage: S37=CuspForms(37,2) sage: S37.sturm_bound() 8 sage: M = ModularForms(11,2) sage: M.sturm_bound() 3 sage: ModularForms(Gamma1(15),2).sturm_bound() 33
from sage.rings.real_mpfr cimport RealField, RealNumber
from sage.rings.real_mpfr cimport RealField_class, RealNumber
cdef RealNumber result = domain(fn(*py_args))
/* Automatically generated. Do not edit! */ ...
/* Automatically generated by ext/gen_interpreters.py. Do not edit! */ ...
def write_interpreter(self, write): r""" Generate the code for the C interpreter.
/* Automatically generated. Do not edit! */
/* Automatically generated by ext/gen_interpreters.py. Do not edit! */
def write_interpreter(self, write): r""" Generate the code for the C interpreter.
/* Automatically generated. Do not edit! */
/* Automatically generated by ext/gen_interpreters.py. Do not edit! */
def get_interpreter(self): r""" Returns the code for the C interpreter.
from sage.rings.real_mpfr cimport RealField, RealNumber
from sage.rings.real_mpfr cimport RealField_class, RealNumber
def get_pxd(self): r""" Returns the code for the Cython .pxd file.
'/* Automatically generated. Do not edit! */\n'
'/* Automatically generated by ext/gen_interpreters.py. Do not edit! */\n'
def build_interp(interp_spec, dir): r""" Given an InterpreterSpec, writes the C interpreter and the Cython wrapper (generates a pyx and a pxd file). EXAMPLES: sage: from sage.ext.gen_interpreters import * sage: testdir = tmp_filename() sage: os.mkdir(testdir) sage: rdf_interp = RDFInterpreter() sage: build_interp(rdf_interp, testdir) sage: open(testdir + '/interp_rdf.c').readline() '/* Automatically generated. Do not edit! */\n' """ ig = InterpreterGenerator(interp_spec) interp_fn = '%s/interp_%s.c' % (dir, interp_spec.name) wrapper_fn = '%s/wrapper_%s.pyx' % (dir, interp_spec.name) pxd_fn = '%s/wrapper_%s.pxd' % (dir, interp_spec.name) interp = ig.get_interpreter() wrapper = ig.get_wrapper() pxd = ig.get_pxd() write_if_changed(interp_fn, interp) write_if_changed(wrapper_fn, wrapper) write_if_changed(pxd_fn, pxd)
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. EXAMPLES:
- ``legend_*`` - all the options valid for :meth:`set_legend_options` prefixed with 'legend_'
- ``legend_*`` - all the options valid for :meth:`set_legend_options` prefixed with ``legend_``
def show(self, **kwds): """ Show this graphics image with the default image viewer.
""" from sage.rings.all import ZZ
Check if sage: c.get_fake_div(1/pi/x) FakeExpression([1, FakeExpression([pi, x], <built-in function mul>)], <built-in function div>) """
def get_fake_div(self, ex): """ EXAMPLES::
if len(n) == 1:
if len(n) == 0: return FakeExpression([SR.one_element(), d], _operator.div) elif len(n) == 1:
def get_fake_div(self, ex): """ EXAMPLES::
from sage.rings.all import Rational
def arithmetic(self, ex, operator): r""" EXAMPLES::
'How big the point is.'
'How big the point is (i.e., area in points^2=(1/72 inch)^2).'
def _allowed_options(self): """ Return the allowed options for the Point class.
'size': 'How big the point is.',
'size': 'How big the point is (i.e., area in points^2=(1/72 inch)^2).',
def _allowed_options(self): """ Return the allowed options for the Point class.
""" g = self.division_points(m, poly_only=True) return len(g.roots(multiplicities=False)) > 0
A finite field example:: sage: E = EllipticCurve(GF(101),[23,34]) sage: E.cardinality().factor() 2 * 53 sage: Set([T.order() for T in E.points()]) {1, 106, 2, 53} sage: len([T for T in E.points() if T.is_divisible_by(2)]) 53 sage: len([T for T in E.points() if T.is_divisible_by(3)]) 106 TESTS: This shows that the bug reported at sage: K = QuadraticField(8,'a') sage: E = EllipticCurve([K(0),0,0,-1,0]) sage: P = E([-1,0]) sage: P.is_divisible_by(2) False sage: P.division_points(2) [] Note that it is not sufficient to test that ``self.division_points(m,poly_only=True)`` has roots:: sage: P.division_points(2, poly_only=True).roots() [(1/2*a - 1, 1), (-1/2*a - 1, 1)] sage: tor = E.torsion_points(); len(tor) 8 sage: [T.order() for T in tor] [2, 4, 4, 2, 4, 1, 4, 2] sage: all([T.is_divisible_by(3) for T in tor]) True sage: Set([T for T in tor if T.is_divisible_by(2)]) {(0 : 1 : 0), (1 : 0 : 1)} sage: Set([2*T for T in tor]) {(0 : 1 : 0), (1 : 0 : 1)} """ m = rings.Integer(m) if m == 1 or m == -1: return True if m == 0: return self == 0 m = m.abs() P = self try: n = P.order() if not n == oo: if m.gcd(n)==1: return True except NotImplementedError: pass P_is_2_torsion = (P==-P) g = P.division_points(m, poly_only=True) if not P_is_2_torsion: return len(g.roots())>0 if m%2==1: return True return len(self.division_points(m)) > 0
def is_divisible_by(self, m): """ Return True if there exists a point `Q` defined over the same field as self such that `mQ` == self.
sage: P5.homology()
The following computation can take a long time -- over half an hour -- with Sage's default computation of homology groups, but if you have CHomP installed, Sage will use that and the computation should only take a second or two. (You can download CHomP from http://chomp.rutgers.edu/, or you can install it as a Sage package using "sage -i chomp"). :: sage: P5.homology()
def RealProjectiveSpace(self, n): r""" A triangulation of `\Bold{R}P^n` for any `n \geq 0`.
non negative integer
non negative real number
def height(self): r""" Returns the height of self.
non negative integer
non negative real number
def width(self): r""" Returns the width of self.
We can also create spaces corresponding to the groups `\GammaH(N)` intermediate
We can also create spaces corresponding to the groups `\Gamma_H(N)` intermediate
def ModularForms(group = 1, weight = 2, base_ring = None, use_cache = True, prec = defaults.DEFAULT_PRECISION): r""" Create an ambient space of modular forms. INPUT: - ``group`` - A congruence subgroup or a Dirichlet character eps. - ``weight`` - int, the weight, which must be an integer = 1. - ``base_ring`` - the base ring (ignored if group is a Dirichlet character) Create using the command ModularForms(group, weight, base_ring) where group could be either a congruence subgroup or a Dirichlet character. EXAMPLES: First we create some spaces with trivial character:: sage: ModularForms(Gamma0(11),2).dimension() 2 sage: ModularForms(Gamma0(1),12).dimension() 2 If we give an integer N for the congruence subgroup, it defaults to `\Gamma_0(N)`:: sage: ModularForms(1,12).dimension() 2 sage: ModularForms(11,4) Modular Forms space of dimension 4 for Congruence Subgroup Gamma0(11) of weight 4 over Rational Field We create some spaces for `\Gamma_1(N)`. :: sage: ModularForms(Gamma1(13),2) Modular Forms space of dimension 13 for Congruence Subgroup Gamma1(13) of weight 2 over Rational Field sage: ModularForms(Gamma1(13),2).dimension() 13 sage: [ModularForms(Gamma1(7),k).dimension() for k in [2,3,4,5]] [5, 7, 9, 11] sage: ModularForms(Gamma1(5),11).dimension() 12 We create a space with character:: sage: e = (DirichletGroup(13).0)^2 sage: e.order() 6 sage: M = ModularForms(e, 2); M Modular Forms space of dimension 3, character [zeta6] and weight 2 over Cyclotomic Field of order 6 and degree 2 sage: f = M.T(2).charpoly('x'); f x^3 + (-2*zeta6 - 2)*x^2 - 2*zeta6*x + 14*zeta6 - 7 sage: f.factor() (x - 2*zeta6 - 1) * (x - zeta6 - 2) * (x + zeta6 + 1) We can also create spaces corresponding to the groups `\GammaH(N)` intermediate between `\Gamma_0(N)` and `\Gamma_1(N)`:: sage: G = GammaH(30, [11]) sage: M = ModularForms(G, 2); M Modular Forms space of dimension 20 for Congruence Subgroup Gamma_H(30) with H generated by [11] of weight 2 over Rational Field sage: M.T(7).charpoly().factor() (x + 4) * x^2 * (x - 6)^4 * (x + 6)^4 * (x - 8)^7 * (x^2 + 4) More examples of spaces with character:: sage: e = DirichletGroup(5, RationalField()).gen(); e Dirichlet character modulo 5 of conductor 5 mapping 2 |--> -1 sage: m = ModularForms(e, 2); m Modular Forms space of dimension 2, character [-1] and weight 2 over Rational Field sage: m == loads(dumps(m)) True sage: m.T(2).charpoly('x') x^2 - 1 sage: m = ModularForms(e, 6); m.dimension() 4 sage: m.T(2).charpoly('x') x^4 - 917*x^2 - 42284 This came up in a subtle bug (trac #5923):: sage: ModularForms(gp(1), gap(12)) Modular Forms space of dimension 2 for Modular Group SL(2,Z) of weight 12 over Rational Field This came up in another bug (related to trac #8630):: sage: chi = DirichletGroup(109, CyclotomicField(3)).0 sage: ModularForms(chi, 2, base_ring = CyclotomicField(15)) Modular Forms space of dimension 10, character [zeta3 + 1] and weight 2 over Cyclotomic Field of order 15 and degree 8 We create some weight 1 spaces. The first example works fine, since we can prove purely by Riemann surface theory that there are no weight 1 cusp forms:: sage: M = ModularForms(Gamma1(11), 1); M Modular Forms space of dimension 5 for Congruence Subgroup Gamma1(11) of weight 1 over Rational Field sage: M.basis() [ 1 + 22*q^5 + O(q^6), q + 4*q^5 + O(q^6), q^2 - 4*q^5 + O(q^6), q^3 - 5*q^5 + O(q^6), q^4 - 3*q^5 + O(q^6) ] sage: M.cuspidal_subspace().basis() [ ] sage: M == M.eisenstein_subspace() True This example doesn't work so well, because we can't calculate the cusp forms; but we can still work with the Eisenstein series. sage: M = ModularForms(Gamma1(57), 1); M Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: M.basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: M.cuspidal_subspace().basis() Traceback (most recent call last): ... NotImplementedError: Computation of dimensions of weight 1 cusp forms spaces not implemented in general sage: E = M.eisenstein_subspace(); E Eisenstein subspace of dimension 36 of Modular Forms space of dimension (unknown) for Congruence Subgroup Gamma1(57) of weight 1 over Rational Field sage: (E.0 + E.2).q_expansion(40) 1 + q^2 + 1473/2*q^36 - 1101/2*q^37 + q^38 - 373/2*q^39 + O(q^40) """ if isinstance(group, dirichlet.DirichletCharacter): if base_ring is None: base_ring = group.minimize_base_ring().base_ring() if base_ring is None: base_ring = rings.QQ if isinstance(group, dirichlet.DirichletCharacter) \ or arithgroup.is_CongruenceSubgroup(group): level = group.level() else: level = group key = canonical_parameters(group, level, weight, base_ring) if use_cache and _cache.has_key(key): M = _cache[key]() if not (M is None): M.set_precision(prec) return M (level, group, weight, base_ring) = key M = None if arithgroup.is_Gamma0(group): M = ambient_g0.ModularFormsAmbient_g0_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_Gamma1(group): M = ambient_g1.ModularFormsAmbient_g1_Q(group.level(), weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif arithgroup.is_GammaH(group): M = ambient_g1.ModularFormsAmbient_gH_Q(group, weight) if base_ring != rings.QQ: M = ambient_R.ModularFormsAmbient_R(M, base_ring) elif isinstance(group, dirichlet.DirichletCharacter): eps = group if eps.base_ring().characteristic() != 0: # TODO -- implement this # Need to add a lift_to_char_0 function for characters, # and need to still remember eps. raise NotImplementedError, "currently the character must be over a ring of characteristic 0." eps = eps.minimize_base_ring() if eps.is_trivial(): return ModularForms(eps.modulus(), weight, base_ring, use_cache = use_cache, prec = prec) M = ambient_eps.ModularFormsAmbient_eps(eps, weight) if base_ring != eps.base_ring(): M = M.base_extend(base_ring) # ambient_R.ModularFormsAmbient_R(M, base_ring) if M is None: raise NotImplementedError, \ "computation of requested space of modular forms not defined or implemented" M.set_precision(prec) _cache[key] = weakref.ref(M) return M
sage: f1(x) = 1 sage: f2(x) = 1-x sage: f = Piecewise([[(0,1),f1],[(1,2),f2]])
sage: f1(x) = 1-x sage: f = Piecewise([[(0,1),1],[(1,2),f1]])
def integral(self, x=None, a=None, b=None, definite=False): r""" By default, returns the indefinite integral of the function. If definite=True is given, returns the definite integral.
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. EXAMPLES:: sage: Q = Poset({5:[2,3], 1:[3,4], 2:[0], 3:[0], 4:[0]}) sage: Q.hasse_diagram() Digraph on 6 vertices
'ton_force':'Defined to be the magnitude of the force exerted on one ton of mass (2000 pounds) by a 9.80665 meter/second^2 gravitational field.\nApproximately equal to 8896.4432 newtons.'},
'ton_force':'Defined to be 2000 pounds of force.\nApproximately equal to 8896.4432 newtons.'},
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
{'candela':'SI base unit of luminous intensity.\nDefined to be the luminous intensity, in a given direction, of a source that emits monochromatic radiation of frequency 540*10^12 hertz and that has a radiant intensity in that direction of 1\xe2\x81\x84683 watt per steradian.',
{'candela':'SI base unit of luminous intensity.\nDefined to be the luminous intensity, in a given direction, of a source that emits monochromatic radiation of frequency 540*10^12 hertz and that has a radiant intensity in that direction of 1/683 watt per steradian.',
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
'solar_mass':'Defined to be the mass of the Sun.\nAbout 332,950 times the size of the Earth or 1,048 times the mass of Jupiter.\nApproximately equal to 1.98892*10^30 kilograms.',
'solar_mass':'Defined to be the mass of the Sun.\nAbout 332,950 times the mass of the Earth or 1,048 times the mass of Jupiter.\nApproximately equal to 1.98892*10^30 kilograms.',
def evalunitdict(): """ Replace all the string values of the unitdict variable by their evaluated forms, and builds some other tables for ease of use. This function is mainly used internally, for efficiency (and flexibility) purposes, making it easier to describe the units. EXAMPLES:: sage: sage.symbolic.units.evalunitdict() """ from sage.misc.all import sage_eval for key, value in unitdict.iteritems(): unitdict[key] = dict([(a,sage_eval(repr(b))) for a, b in value.iteritems()]) # FEATURE IDEA: create a function that would allow users to add # new entries to the table without having to know anything about # how the table is stored internally. # # Format the table for easier use. # for k, v in unitdict.iteritems(): for a in v: unit_to_type[a] = k for w in unitdict.iterkeys(): for j in unitdict[w].iterkeys(): if type(unitdict[w][j]) == tuple: unitdict[w][j] = unitdict[w][j][0] value_to_unit[w] = dict(zip(unitdict[w].itervalues(), unitdict[w].iterkeys()))
Collection power of units: cheval_vapeur horsepower watt
Collection of units of power: cheval_vapeur horsepower watt
def str_to_unit(name): """ Create the symbolic unit with given name. A symbolic unit is a class that derives from symbolic expression, and has a specialized docstring. INPUT: - ``name`` -- string OUTPUT: - UnitExpression EXAMPLES:: sage: sage.symbolic.units.str_to_unit('acre') acre sage: type(sage.symbolic.units.str_to_unit('acre')) <class 'sage.symbolic.units.UnitExpression'> """ return UnitExpression(SR, SR.var(name))
Collection all units of units: acceleration ... volume
Collection of units of all units: acceleration ... volume
def __init__(self, data, name=''): """ EXAMPLES::
Collection area of units: acre are barn hectare rood section square_chain square_meter township
Collection of units of area: acre are barn hectare rood section square_chain square_meter township
def __getattr__(self, name): """ Return the unit with the given name.
'Collection area of units: acre are barn hectare rood section square_chain square_meter township' """ name = self.__name + ' ' if self.__name else '' return "Collection %sof units: %s"%(name, ' '.join(sorted([str(x) for x in self.__data])))
'Collection of units of area: acre are barn hectare rood section square_chain square_meter township' """ name = ' of ' + self.__name if self.__name else '' return "Collection of units{0}: {1}".format(name, ' '.join(sorted([str(x) for x in self.__data])))
def __repr__(self): """ Return string representation of this collection of units.
- ``string`` -- a string EXAMPLE::
- ``string`` -- a string of symbols over some alphabet. OUTPUT: - A table of frequency of each unique symbol in ``string``. If ``string`` is an empty string, return an empty table. EXAMPLES: The frequency table of a non-empty string::
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2}
sage: str = "Stop counting my characters!" sage: T = sorted(frequency_table(str).items()) sage: for symbol, code in T: ... print symbol, code ... 3 ! 1 S 1 a 2 c 3 e 1 g 1 h 1 i 1 m 1 n 2 o 2 p 1 r 2 s 1 t 3 u 1 y 1 The frequency of an empty string:: sage: frequency_table("") {}
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
for l in string: d[l] = d.get(l,0) + 1
for s in string: d[s] = d.get(s, 0) + 1
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
class Huffman():
class Huffman(SageObject):
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
Huffman Encoding This class implements the basic functionalities of Huffman's encoding. It can build a Huffman code from a given string, or from the information of a dictionary associating to each key (the elements of the alphabet) a weight (most of the time, a probability value or a number of occurrences). For example ::
This class implements the basic functionalities of Huffman codes. It can build a Huffman code from a given string, or from the information of a dictionary associating to each key (the elements of the alphabet) a weight (most of the time, a probability value or a number of occurrences). INPUT: - ``string`` -- (default: ``None``) a string from which the Huffman encoding should be created. - ``table`` -- (default: ``None``) a dictionary that associates to each symbol of an alphabet a numeric value. If we consider the frequency of each alphabetic symbol, then ``table`` is considered as the frequency table of the alphabet with each numeric (non-negative integer) value being the number of occurrences of a symbol. The numeric values can also represent weights of the symbols. In that case, the numeric values are not necessarily integers, but can be real numbers. In general, we refer to ``table`` as a weight table. Exactly one of ``string`` and ``table`` cannot be ``None``. In order to construct a Huffman code for an alphabet, we use exactly one of the following methods: ``string`` to the constructor of this class. Based on the input string, a frequency table is constructed that contains the frequency of each unique symbol in ``string``. The alphabet in question is then all the unique symbols in ``string``. A significant implication of this is that any subsequent string that we want to encode must contain only symbols that can be found in ``string``. table to the constructor of this class. The table ``table`` can be a table of frequency or a table of weights. Examples::
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
We could have obtained the same result by "training" the Huffman code on the following table of frequency ::
We can obtain the same result by "training" the Huffman code with the following table of frequency::
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
sage: h2 = Huffman(frequencies = ft) Once ``h1`` has been trained, and hence possesses an encoding code,
sage: h2 = Huffman(table=ft) Once ``h1`` has been trained, and hence possesses an encoding table,
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
Which can be decoded the following way::
We can decode the above encoded string in the following way::
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
... precisely what we deserved :-) INPUT: One among the following: - ``string`` -- a string from which the Huffman encoding should be created - ``frequencies`` -- a dictionary associating its frequency or its number of occurrences to each letter of the alphabet.
This does not look like our original string. Instead of using frequency, we can assign weights to each alphabetic symbol:: sage: from sage.coding.source_coding.huffman import Huffman sage: T = {"a":45, "b":13, "c":12, "d":16, "e":9, "f":5} sage: H = Huffman(table=T) sage: L = ["deaf", "bead", "fab", "bee"] sage: E = [] sage: for e in L: ... E.append(H.encode(e)) ... print E[-1] ... 111110101100 10111010111 11000101 10111011101 sage: D = [] sage: for e in E: ... D.append(H.decode(e)) ... print D[-1] ... deaf bead fab bee sage: D == L True
def frequency_table(string): r""" Return the frequency table corresponding to the given string. INPUT: - ``string`` -- a string EXAMPLE:: sage: from sage.coding.source_coding.huffman import frequency_table sage: str = "Sage is my most favorite general purpose computer algebra system" sage: frequency_table(str) {'a': 5, ' ': 9, 'c': 1, 'b': 1, 'e': 8, 'g': 3, 'f': 1, 'i': 2, 'm': 4, 's': 5, 'o': 4, 'n': 1, 'p': 3, 'S': 1, 'r': 5, 'u': 2, 't': 4, 'v': 1, 'y': 2, 'l': 2} """ d = {} for l in string: d[l] = d.get(l,0) + 1 return d
def __init__(self, string = None, frequencies = None): r""" Constructor for Huffman INPUT: One among the following: - ``string`` -- a string from which the Huffman encoding should be created - ``frequencies`` -- a dictionary associating its frequency or its number of occurrences to each letter of the alphabet. EXAMPLE:: sage: from sage.coding.source_coding.huffman import Huffman sage: str = "Sage is my most favorite general purpose computer algebra system" sage: h = Huffman(str) If both arguments are supplied, an exception is raised :: sage: Huffman(string=str, frequencies={'a':8})
def __init__(self, string=None, table=None): r""" Constructor for Huffman. See the docstring of this class for full documentation. EXAMPLES:: sage: from sage.coding.source_coding.huffman import Huffman sage: str = "Sage is my most favorite general purpose computer algebra system" sage: h = Huffman(str) TESTS: If both arguments are supplied, an exception is raised:: sage: Huffman(string=str, table={'a':8})
def __init__(self, string = None, frequencies = None): r""" Constructor for Huffman
ValueError: Exactly one of `string` or `frequencies` parameters must be defined """
ValueError: Exactly one of 'string' and 'table' cannot be None. """ if (string is not None) and (table is not None): raise ValueError( "Exactly one of 'string' and 'table' cannot be None.")
def __init__(self, string = None, frequencies = None): r""" Constructor for Huffman
if sum([string is not None, frequencies is not None]) != 1: raise ValueError("Exactly one of `string` or `frequencies` parameters must be defined")
self._tree = None self._index = None
def __init__(self, string = None, frequencies = None): r""" Constructor for Huffman
elif frequencies is not None: self._build_code(frequencies) def _build_code_from_tree(self, tree, d, prefix=''): r""" Builds the code corresponding to a given tree and prefix
elif table is not None: self._build_code(table) def _build_code_from_tree(self, tree, d, prefix): r""" Builds the Huffman code corresponding to a given tree and prefix.
def __init__(self, string = None, frequencies = None): r""" Constructor for Huffman
EXAMPLE::
EXAMPLES::
def _build_code_from_tree(self, tree, d, prefix=''): r""" Builds the code corresponding to a given tree and prefix
sage: h._build_code_from_tree(h._tree, d) """
sage: h._build_code_from_tree(h._tree, d, prefix="") """
def _build_code_from_tree(self, tree, d, prefix=''): r""" Builds the code corresponding to a given tree and prefix
self._build_code_from_tree(tree[0], d, prefix=prefix+'0') self._build_code_from_tree(tree[1], d, prefix=prefix+'1')
self._build_code_from_tree(tree[0], d, prefix="".join([prefix, "0"])) self._build_code_from_tree(tree[1], d, prefix="".join([prefix, "1"]))
def _build_code_from_tree(self, tree, d, prefix=''): r""" Builds the code corresponding to a given tree and prefix
Returns a Huffman code for each one of the given elements. INPUT: - ``dic`` (dictionary) -- associates to each letter of the alphabet a frequency or a number of occurrences.
Constructs a Huffman code corresponding to an alphabet with the given weight table. INPUT: - ``dic`` -- a dictionary that associates to each symbol of an alphabet a numeric value. If we consider the frequency of each alphabetic symbol, then ``dic`` is considered as the frequency table of the alphabet with each numeric (non-negative integer) value being the number of occurrences of a symbol. The numeric values can also represent weights of the symbols. In that case, the numeric values are not necessarily integers, but can be real numbers. In general, we refer to ``dic`` as a weight table.
def _build_code(self, dic): r""" Returns a Huffman code for each one of the given elements. INPUT: - ``dic`` (dictionary) -- associates to each letter of the alphabet a frequency or a number of occurrences.
index = dic.items()
def _build_code(self, dic): r""" Returns a Huffman code for each one of the given elements. INPUT: - ``dic`` (dictionary) -- associates to each letter of the alphabet a frequency or a number of occurrences.
for i,(e,w) in enumerate(index): heappush(heap, (w, i) ) while len(heap)>=2: (w1, i1) = heappop(heap) (w2, i2) = heappop(heap) heappush(heap, (w1+w2,[i1,i2]))
for i, (s, w) in enumerate(dic.items()): heappush(heap, (w, i)) for i in range(1, len(dic)): weight_a, node_a = heappop(heap) weight_b, node_b = heappop(heap) heappush(heap, (weight_a + weight_b, [node_a, node_b]))
def _build_code(self, dic): r""" Returns a Huffman code for each one of the given elements. INPUT: - ``dic`` (dictionary) -- associates to each letter of the alphabet a frequency or a number of occurrences.