Exemplo n.º 1
0
 def only_best_table(self, compare_to=None):
     counting = self._counting_tournaments
     #row_header = ["Pos", "Pts", "#Tourn", "Team name", "Region"]
     #row_header += ['Best', '2nd best', '3rd best', '4th best (does not count)']
     row_header = ["Pos"] 
     if compare_to:
         row_header += ['Official']
     row_header += ["Pts", "Team name"]
     row_header += ['Best', '2nd best', '3rd best', '4th best'][:counting]
     row_header += ['Provenance']
     rows = [row_header]
     L = self._equipes.values()
     L.sort(reverse=True)
     for i, e in enumerate(L):
         row = [i+1]
         if compare_to:
             pos = compare_to.index(e._nom)
             move = pos - i
             row.append("{} ({})".format(pos+1, move))
         row.append(e.total())
         #row.append(e.nb_tournois_participes())
         row.append(e._nom)
         bests = ["%s (%s) %s" % b for b in e.four_best()]
         if len(bests) < 4:
             bests += [""] * (4-len(bests))
         row.extend(bests[:counting])
         row.append(e.provenance())
         rows.append(row)
     return table(rows=rows,header_row=True)
Exemplo n.º 2
0
 def statistiques_participation_table(self):
     L = [e.nb_tournois_participes() for e in self._equipes.values()]
     M = max(L)
     rows = [("Number of tournaments played", "Number of teams")]
     for i in range(1, M+1):
         rows.append( (i, L.count(i)) )
     return table(rows=rows, header_row=True)
Exemplo n.º 3
0
def projection_graph(G, proj_fn, filename=None, verbose=False):
    r"""
    Return the image of a graph under a function on vertices.

    INPUT:

    - ``G`` -- graph
    - ``proj_fn`` -- function
    - ``filename`` -- integer (default:``None``), save the graph to this pdf
      filename if filename is not None
    - ``verbose`` -- bool (default:``False``), print a table of data about the
      projection

    EXAMPLES::

        sage: from slabbe.graph import projection_graph
        sage: g = graphs.PetersenGraph()
        sage: g.vertices()
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        sage: f = lambda i: i % 5
        sage: projection_graph(g, f)
        Looped multi-digraph on 5 vertices

    With verbose information::

        sage: projection_graph(g, lambda i:i%4, verbose=True)
          Number of vertices   Projected vertices
        +--------------------+--------------------+
          2                    3
          2                    2
          3                    1
          3                    0
        Looped multi-digraph on 4 vertices
    """
    edges = set((proj_fn(A),proj_fn(B)) for A,B,_ in G.edges())
    G_proj = DiGraph(edges, format='list_of_edges', loops=True, multiedges=True)
    if verbose:
        d = dict(Counter(proj_fn(s) for s in G.vertices()))
        rows = [(value, key) for key,value in d.iteritems()]
        rows.sort(reverse=True,key=lambda row:row[1])
        header_row = ['Number of vertices', 'Projected vertices']
        from sage.misc.table import table
        print table(rows=rows, header_row=header_row)
    if filename:
        from slabbe import TikzPicture
        print TikzPicture.from_graph(G_proj, prog='dot').pdf(filename)
    return G_proj
Exemplo n.º 4
0
def test_packages(packages, only_failures=False):
    """
    Return list of all installed packages.

    INPUT:

    - ``packages`` -- a list/tuple/iterable of strings. The names of
      GAP packages to try to import.

    - ``only_failures`` -- boolean, default ``False``. Whether to only
      include failures in the table.

    OUTPUT:

    A table of the installed packages and whether they load
    successfully.

    EXAMPLES::

        sage: from sage.tests.gap_packages import all_installed_packages, test_packages
        sage: test_packages(['GAPDoc'])
          Status   Package   GAP Output
        +--------+---------+------------+
                   GAPDoc    true

    All packages, including user-installed ones::

        sage: pkgs = all_installed_packages()
        sage: test_packages(pkgs)    # random output
          Status    Package      GAP Output
        +---------+------------+------------+
                    Alnuth       true
                    GAPDoc       true
          Failure   HAPcryst     fail
                    Hap          true
                    autpgrp      true
                    braid        true
                    crime        true
                    ctbllib      true
                    design       true
                    factint      true
                    grape        true
                    guava        true
                    laguna       true
                    polycyclic   true
                    polymaking   true
                    sonata       true
                    toric        true
    """
    rows = [['Status', 'Package', 'GAP Output']]
    for pkg in packages:
        output = libgap.eval('LoadPackage("{0}")'.format(pkg))
        ok = bool(output)
        status = '' if ok else 'Failure'
        if ok and only_failures:
            continue
        rows.append([status, pkg, str(output)])
    from sage.misc.table import table
    return table(rows, header_row=True)
Exemplo n.º 5
0
def test_packages(packages, only_failures=False):
    """
    Return list of all installed packages.

    INPUT:

    - ``packages`` -- a list/tuple/iterable of strings. The names of
      GAP packages to try to import.

    - ``only_failures`` -- boolean, default ``False``. Whether to only
      include failures in the table.

    OUTPUT:

    A table of the installed packages and whether they load
    successfully.

    EXAMPLES::

        sage: from sage.tests.gap_packages import all_installed_packages, test_packages
        sage: test_packages(['GAPDoc'])
          Status   Package   GAP Output
        +--------+---------+------------+
                   GAPDoc    true

    All packages, including user-installed ones::

        sage: pkgs = all_installed_packages()
        sage: test_packages(pkgs)    # random output
          Status    Package      GAP Output
        +---------+------------+------------+
                    Alnuth       true
                    GAPDoc       true
          Failure   HAPcryst     fail
                    Hap          true
                    autpgrp      true
                    braid        true
                    crime        true
                    ctbllib      true
                    design       true
                    factint      true
                    grape        true
                    guava        true
                    laguna       true
                    polycyclic   true
                    polymaking   true
                    sonata       true
                    toric        true
    """
    rows = [['Status', 'Package', 'GAP Output']]
    for pkg in packages:
        output = libgap.eval('LoadPackage("{0}")'.format(pkg))
        ok = bool(output)
        status = '' if ok else 'Failure'
        if ok and only_failures:
            continue
        rows.append([status, pkg, str(output)])
    from sage.misc.table import table
    return table(rows, header_row=True)
Exemplo n.º 6
0
 def equipe_alphabetiquement_table(self):
     L = self._equipes.keys()
     rows = []
     for nom in sorted(L):
         equipe = self._equipes[nom]
         tournois = ", ".join([T.long_name() for T in equipe._positions.keys()])
         rows.append(( nom.ljust(40), equipe.provenance(), tournois))
     return table(rows=rows)
Exemplo n.º 7
0
 def tournaments_stat_table(self):
     rows = [("Tournaments considered", "Points for champion", "#teams getting points", 
              "#teams", "Strength")]
     for T in self._tournois:
         scale = self._scales[T._scale_id]
         rows.append( (T.long_name(), scale[1], len(scale)-1, 
                       self._tournament_size(T), 
                       "5/%s and %s/20"%(self._strength5(T), self._strength20(T))))
     return table(rows=rows,header_row=True)
Exemplo n.º 8
0
 def number_of_inversions_table(self, top=32):
     rows  = [("Tournoi", "Nombre d'inversions")]
     tot = 0
     for tournoi in self._tournois:
         move_list = self._moves[tournoi]
         #print tournoi, move_list[:top]
         moves = sum(abs(a) for a in move_list[:top])
         rows.append((tournoi, moves))
         tot += moves
     rows.append(('Total', tot))
     return table(rows=rows, header_row=True)
Exemplo n.º 9
0
def lyapunov_table(algo, n_orbits, n_iterations=1000):
    r"""
    Return a table of values of Lyapunov exponents for this algorithm.

    INPUT:

    - ``n_orbits`` -- integer, number of orbits
    - ``n_iterations`` -- integer, length of each orbit

    OUTPUT:

        table of liapounov exponents

    EXAMPLES::

        sage: from slabbe.mult_cont_frac import Brun
        sage: from slabbe.lyapunov import lyapunov_table
        sage: lyapunov_table(Brun(), 10, 1000000) # random
          10 succesfull orbits    min       mean      max       std
        +-----------------------+---------+---------+---------+---------+
          $\theta_1$              0.303     0.305     0.307     0.0013
          $\theta_2$              -0.1131   -0.1124   -0.1115   0.00051
          $1-\theta_2/\theta_1$   1.3678    1.3687    1.3691    0.00043
    """
    import numpy as np
    from sage.misc.functional import numerical_approx
    from sage.functions.other import abs, floor
    from sage.functions.log import log
    from sage.misc.table import table
    rep = lyapunov_sample(algo, n_orbits, n_iterations)

    def my_log(number):
        return floor(log(abs(number), 10.))

    def my_rounded(number, s):
        m = my_log(number)
        return numerical_approx(number, digits=m - s + 1)

    names = [r"$\theta_1$", r"$\theta_2$", r"$1-\theta_2/\theta_1$"]
    rows = []
    for i, data in enumerate(rep):
        data = np.array(data)
        s = my_log(data.std())
        row = [names[i]]
        row.append(my_rounded(data.min(), s))
        row.append(my_rounded(data.mean(), s))
        row.append(my_rounded(data.max(), s))
        row.append(my_rounded(data.std(), s))
        rows.append(row)
    header = [
        '{} succesfull orbits'.format(len(rep[0])), 'min', 'mean', 'max', 'std'
    ]
    return table(rows=rows, header_row=header)
Exemplo n.º 10
0
def mult_cont_frac_vs_dirichlet(v, dirichlet, algos):
    r"""
    Returns the indices i such that dirichlet approximations appears as columns
    of the i-th matrix obtained from mult. dim. cont. frac. algorithms.

    INPUT:

    - ``v`` -- list of real numbers
    - ``dirichlet`` -- list, first dirichlet approximations
    - ``algos`` -- list, list of mult. cont. frac. algorithms

    OUTPUT:

    table

    EXAMPLES::

        sage: from slabbe.diophantine_approx import best_simultaneous_convergents
        sage: from slabbe.diophantine_approx import mult_cont_frac_vs_dirichlet
        sage: from slabbe.mult_cont_frac import Brun,ARP,Reverse,Selmer,Cassaigne
        sage: v = [e, pi]
        sage: it = best_simultaneous_convergents(v)
        sage: dirichlet = [next(it) for _ in range(10)]
        sage: algos = [Brun(), ARP(), Reverse(), Selmer(),Cassaigne()]
        sage: mult_cont_frac_vs_dirichlet(v, dirichlet, algos)
          Dirichlet                     Brun       ARP        Reverse   Selmer     Cassaigne
        +-----------------------------+----------+----------+---------+----------+-----------+
          (3, 3, 1)                     [4, 5]     [3]        []        [8, 12]    []
          (19, 22, 7)                   [9, 16]    [6, 11]    [7, 33]   [32]       [15, 25]
          (1843, 2130, 678)             [22, 27]   [16, 17]   []        [44, 48]   [36, 39]
          (51892, 59973, 19090)         []         []         []        [56]       []
          (113018, 130618, 41577)       []         []         []        []         []
          (114861, 132748, 42255)       [33, 35]   [22, 24]   []        [62, 66]   [51, 53]
          (166753, 192721, 61345)       []         []         []        []         []
          (446524, 516060, 164267)      [36]       [25]       []        []         [56, 57]
          (1174662, 1357589, 432134)    [39, 44]   [26, 29]   []        [68]       [61, 66]
          (3970510, 4588827, 1460669)   []         [28]       []        []         []
    """
    D = mult_cont_frac_vs_dirichlet_dict(v, dirichlet, algos)
    rows = []
    for v in dirichlet:
        v = tuple(v)
        row = [v]
        for algo in algos:
            indices = D[algo][v]
            if len(indices) > 1:
                row.append([min(indices), max(indices)])
            else:
                row.append(indices)
        rows.append(row)
    header_row = ['Dirichlet'] + [algo.class_name() for algo in algos]
    from sage.misc.table import table
    return table(rows=rows, header_row=header_row)
Exemplo n.º 11
0
 def full_table(self):
     L = self.sorted_team_list()
     title = ["Division", "Position", "Équipe", "Provenance"]
     title += ["Pos", "Pts", 'ES'] * len(self._tournois)
     title += ["Total", "Variation"]
     rows = []
     rows.append(title)
     for i, e in enumerate(L):
         row = [self.division(i+1), i+1, e._nom, e.provenance()]
         row += e.pos_pts_es_ordonnes(self._tournois)
         row += [e.total(), self.get_move_str(e)]
         rows.append(row)
     return table(rows=rows,header_row=True)
Exemplo n.º 12
0
def projection_graph(G, proj_fn, filename=None, verbose=False):
    r"""
    Return the image of a graph under a function on vertices.

    INPUT:

    - ``G`` -- graph
    - ``proj_fn`` -- function
    - ``filename`` -- integer (default:``None``), save the graph to this pdf
      filename if filename is not None
    - ``verbose`` -- bool (default:``False``), print a table of data about the
      projection

    EXAMPLES::

        sage: from slabbe.graph import projection_graph
        sage: g = graphs.PetersenGraph()
        sage: g.vertices()
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        sage: f = lambda i: i % 5
        sage: projection_graph(g, f)
        Looped multi-digraph on 5 vertices

    With verbose information::

        sage: projection_graph(g, lambda i:i%4, verbose=True)
          Number of vertices   Projected vertices
        +--------------------+--------------------+
          2                    3
          2                    2
          3                    1
          3                    0
        Looped multi-digraph on 4 vertices
    """
    edges = set((proj_fn(A),proj_fn(B)) for A,B,_ in G.edges())
    G_proj = DiGraph(edges, format='list_of_edges', loops=True, multiedges=True)
    if verbose:
        d = dict(Counter(proj_fn(s) for s in G.vertices()))
        rows = [(value, key) for key,value in d.iteritems()]
        rows.sort(reverse=True,key=lambda row:row[1])
        header_row = ['Number of vertices', 'Projected vertices']
        from sage.misc.table import table
        print(table(rows=rows, header_row=header_row))
    if filename:
        from slabbe import TikzPicture
        print(TikzPicture.from_graph(G_proj, prog='dot').pdf(filename))
    return G_proj
Exemplo n.º 13
0
def lyapunov_table(algo, n_orbits, n_iterations=1000):
    r"""
    Return a table of values of Lyapunov exponents for this algorithm.

    INPUT:

    - ``n_orbits`` -- integer, number of orbits
    - ``n_iterations`` -- integer, length of each orbit

    OUTPUT:

        table of liapounov exponents

    EXAMPLES::

        sage: from slabbe.mult_cont_frac import Brun
        sage: from slabbe.lyapunov import lyapunov_table
        sage: lyapunov_table(Brun(), 10, 1000000) # random
          10 succesfull orbits    min       mean      max       std
        +-----------------------+---------+---------+---------+---------+
          $\theta_1$              0.303     0.305     0.307     0.0013
          $\theta_2$              -0.1131   -0.1124   -0.1115   0.00051
          $1-\theta_2/\theta_1$   1.3678    1.3687    1.3691    0.00043
    """
    import numpy as np
    from sage.misc.functional import numerical_approx
    from sage.rings.real_mpfr import RR
    from sage.misc.table import table
    rep = lyapunov_sample(algo, n_orbits, n_iterations)
    def floor_log(number):
        return RR(number).abs().log10().floor()
    def my_rounded(number, s):
        m = floor_log(number)
        return numerical_approx(number, digits=m-s+1)
    names = [r"$\theta_1$", r"$\theta_2$", r"$1-\theta_2/\theta_1$"]
    rows = []
    for i, data in enumerate(rep):
        data = np.array(data)
        s = floor_log(data.std())
        row = [names[i]]
        row.append(my_rounded(data.min(),s))
        row.append(my_rounded(data.mean(),s))
        row.append(my_rounded(data.max(),s))
        row.append(my_rounded(data.std(),s))
        rows.append(row)
    header = ['{} succesfull orbits'.format(len(rep[0])), 'min','mean','max','std']
    return table(rows=rows,header_row=header)
    def _repr_(self):
        r"""
        Return as string representation of ``self``.

        OUTPUT:

        A string.

        EXAMPLES::

            sage: rays = [(1,0), (1,1), (1,2), (-1,-1)]
            sage: F1 = FilteredVectorSpace(rays, {0:[1, 2], 2:[3]})
            sage: F2 = FilteredVectorSpace(rays, {0:[1, 2], oo:[3]})
            sage: F3 = FilteredVectorSpace(rays, {oo:[3]})
            sage: F4 = FilteredVectorSpace(rays, {0:[3]})
            sage: MultiFilteredVectorSpace({'a':F1, 'b':F2, 'c': F3, 'd': F4})
            Filtrations
                a: QQ^2 >= QQ^1 >= QQ^1 >=  0
                b: QQ^2 >= QQ^1 >= QQ^1 >= QQ^1
                c: QQ^1 >= QQ^1 >= QQ^1 >= QQ^1
                d: QQ^1 >=  0   >=  0   >=  0

            sage: MultiFilteredVectorSpace(123, base_ring=RR)
            Unfiltered RR^123
        """
        if not self._filt:
            F = FilteredVectorSpace(self.dimension(),
                                    base_ring=self.base_ring())
            return 'Unfiltered ' + repr(F)
        rows = []
        support = self.support()
        min_deg, max_deg = self.min_degree(), self.max_degree()
        for key in sorted(self.index_set()):
            F = self.get_filtration(key)
            r = [str(key)] + F._repr_degrees(min_deg, max_deg-1)
            rows.append(r)
        from sage.misc.table import table
        t = table(rows)
        w = t._widths()
        lines = ['Filtrations']
        for r in rows:
            s = '    '
            s += r[0].rjust(w[0]) + ': '
            s += ' >= '.join(r[i].center(w[i]) for i in range(1, len(w)))
            lines.append(s)
        return '\n'.join(lines)
Exemplo n.º 15
0
    def _repr_(self):
        r"""
        Return as string representation of ``self``.

        OUTPUT:

        A string.

        EXAMPLES::

            sage: rays = [(1,0), (1,1), (1,2), (-1,-1)]
            sage: F1 = FilteredVectorSpace(rays, {0:[1, 2], 2:[3]})
            sage: F2 = FilteredVectorSpace(rays, {0:[1, 2], oo:[3]})
            sage: F3 = FilteredVectorSpace(rays, {oo:[3]})
            sage: F4 = FilteredVectorSpace(rays, {0:[3]})
            sage: MultiFilteredVectorSpace({'a':F1, 'b':F2, 'c': F3, 'd': F4})
            Filtrations
                a: QQ^2 >= QQ^1 >= QQ^1 >=  0
                b: QQ^2 >= QQ^1 >= QQ^1 >= QQ^1
                c: QQ^1 >= QQ^1 >= QQ^1 >= QQ^1
                d: QQ^1 >=  0   >=  0   >=  0

            sage: MultiFilteredVectorSpace(123, base_ring=RR)
            Unfiltered RR^123
        """
        if not self._filt:
            F = FilteredVectorSpace(self.dimension(),
                                    base_ring=self.base_ring())
            return 'Unfiltered ' + repr(F)
        rows = []
        support = self.support()
        min_deg, max_deg = self.min_degree(), self.max_degree()
        for key in sorted(self.index_set()):
            F = self.get_filtration(key)
            r = [str(key)] + F._repr_degrees(min_deg, max_deg - 1)
            rows.append(r)
        from sage.misc.table import table
        t = table(rows)
        w = t._widths()
        lines = ['Filtrations']
        for r in rows:
            s = '    '
            s += r[0].rjust(w[0]) + ': '
            s += ' >= '.join(r[i].center(w[i]) for i in range(1, len(w)))
            lines.append(s)
        return '\n'.join(lines)
Exemplo n.º 16
0
    def check_integrals_of_motion(self, affine_parameter, solution_key=None):
        r"""
        Check the constancy of the four integrals of motion

        INPUT:

        - ``affine_parameter`` -- value of the affine parameter `\lambda`
        - ``solution_key`` -- (default: ``None``) string denoting the numerical
          solution to use for evaluating the various integrals of motion;
          if ``None``, the latest solution computed by :meth:`integrate` is
          used.

        OUTPUT:

        - a `SageMath table <https://doc.sagemath.org/html/en/reference/misc/sage/misc/table.html>`_
          with the absolute and relative differences with respect to the
          initial values.

        """
        CF = ComplexField(16)
        lambda_min = self.domain().lower_bound()
        res = [[
            "quantity", "value", "initial value", "diff.", "relative diff."
        ]]
        mu = self.evaluate_mu(affine_parameter, solution_key=solution_key)
        mu0 = self.evaluate_mu(lambda_min, solution_key=solution_key)
        diff = mu - mu0
        rel_diff = CF(diff / mu0) if mu0 != 0 else "-"
        res.append([r"$\mu$", mu, mu0, CF(diff), rel_diff])
        E = self.evaluate_E(affine_parameter, solution_key=solution_key)
        E0 = self.evaluate_E(lambda_min, solution_key=solution_key)
        diff = E - E0
        rel_diff = CF(diff / E0) if E0 != 0 else "-"
        res.append([r"$E$", E, E0, CF(diff), rel_diff])
        L = self.evaluate_L(affine_parameter, solution_key=solution_key)
        L0 = self.evaluate_L(lambda_min, solution_key=solution_key)
        diff = L - L0
        rel_diff = CF(diff / L0) if L0 != 0 else "-"
        res.append([r"$L$", L, L0, CF(diff), rel_diff])
        Q = self.evaluate_Q(affine_parameter, solution_key=solution_key)
        Q0 = self.evaluate_Q(lambda_min, solution_key=solution_key)
        diff = Q - Q0
        rel_diff = CF(diff / Q0) if Q0 != 0 else "-"
        res.append([r"$Q$", Q, Q0, CF(diff), rel_diff])
        return table(res, align="center")
Exemplo n.º 17
0
    def table(self):
        r"""
        EXAMPLES::

            sage: from slabbe.ranking_scale import RankingScale_CQU4_2011
            sage: R = RankingScale_CQU4_2011()
            sage: R.table()
              Position   Grand Chelem   Mars Attaque   La Flotte   Petit Chelem
              1          1000           1000           800         400
              2          938            938            728         355
              3          884            884            668         317
              4          835            835            614         285
              5          791            791            566         256
              6          750            750            522         230
              7          711            711            482         206
              8          675            675            444         184
              9          641            641            409         164
              10         609            609            377         146
            ...
              95         0              11             0           0
              96         0              10             0           0
              97         0              9              0           0
              98         0              8              0           0
              99         0              7              0           0
              100        0              6              0           0
              101        0              4              0           0
              102        0              3              0           0
              103        0              2              0           0
              104        0              1              0           0
        """
        from sage.misc.table import table
        rows = []
        M = self.length()
        names = ('Position',) + self._scale_names
        scales = (range(M),) + self._scales
        rows.append(names)
        Z = itertools.izip_longest(*scales, fillvalue=0)
        Z.next() # enlever la premiere ligne de zeros
        rows.extend(Z)
        return table(rows)
Exemplo n.º 18
0
    def table(self, p, i1, i2, j1, j2):
        r"""
        Return a table printing the groups in the ``p`` page.

        INPUT:

        - ``p`` -- the page to print.

        -- ``i1`` -- the first column to print.

        -- ``i2`` -- the last column to print.

        -- ``j1`` -- the first row to print.

        -- ``j2`` -- the last row to print.

        EXAMPLES::

            sage: from sage.interfaces.kenzo import Sphere # optional -- kenzo
            sage: S2 = Sphere(2)                           # optional -- kenzo
            sage: EMS = S2.em_spectral_sequence()          # optional -- kenzo
            sage: EMS.table(0, -2, 2, -2, 2)               # optional -- kenzo
              0   Z   0   0   0
              0   0   0   0   0
              0   0   Z   0   0
              0   0   0   0   0
              0   0   0   0   0
        """
        from sage.misc.table import table
        groups = []
        for j in range(j2 - j1 + 1):
            row = []
            for i in range(i1, i2 + 1):
                group = self.group(p, i, j2 - j)
                if group.invariants():
                    row.append(group.short_name())
                else:
                    row.append('0')
            groups.append(row)
        return table(groups)
Exemplo n.º 19
0
    def table(self):
        r"""
        EXAMPLES::

            sage: from slabbe.ranking_scale import RankingScale_CQU4_2011
            sage: R = RankingScale_CQU4_2011()
            sage: R.table()
              Position   Grand Chelem   Mars Attaque   La Flotte   Petit Chelem
              1          1000           1000           800         400
              2          938            938            728         355
              3          884            884            668         317
              4          835            835            614         285
              5          791            791            566         256
              6          750            750            522         230
              7          711            711            482         206
              8          675            675            444         184
              9          641            641            409         164
              10         609            609            377         146
            ...
              95         0              11             0           0
              96         0              10             0           0
              97         0              9              0           0
              98         0              8              0           0
              99         0              7              0           0
              100        0              6              0           0
              101        0              4              0           0
              102        0              3              0           0
              103        0              2              0           0
              104        0              1              0           0
        """
        from sage.misc.table import table
        rows = []
        M = self.length()
        names = ('Position', ) + self._scale_names
        scales = (range(M), ) + self._scales
        rows.append(names)
        Z = itertools.izip_longest(*scales, fillvalue=0)
        Z.next()  # enlever la premiere ligne de zeros
        rows.extend(Z)
        return table(rows)
Exemplo n.º 20
0
def lyapunov_comparison_table(L, n_orbits=100, n_iterations=10000):
    r"""
    Return a table of values of Lyapunov exponents for many algorithm.

    INPUT:

    - ``L`` -- list of algorithms
    - ``n_orbits`` -- integer
    - ``n_iterations`` -- integer

    OUTPUT:

        table

    EXAMPLES::

        sage: import slabbe.mult_cont_frac as mcf
        sage: from slabbe.lyapunov import lyapunov_comparison_table
        sage: algos = [mcf.Brun(), mcf.ARP()]
        sage: lyapunov_comparison_table(algos)    # abs tol 0.01
          Algorithm                 \#Orbits   $\theta_1$ (std)   $\theta_2$ (std)   $1-\theta_2/\theta_1$ (std)
        +-------------------------+----------+------------------+------------------+-----------------------------+
          Arnoux-Rauzy-Poincar\'e   100        0.44 (0.012)       -0.172 (0.0060)    1.388 (0.0054)
          Brun                      100        0.30 (0.011)       -0.113 (0.0049)    1.370 (0.0070)
    """
    rows = []
    for algo in L:
        try:
            row = _lyapunov_row(algo, n_orbits, n_iterations)
        except Exception as err:
            s = "{}: {}".format(err.__class__.__name__, err)
            print("Ignoring {} in Lyapunov table. {}".format(
                algo.class_name(), s))
        else:
            rows.append(row)
    rows.sort(key=lambda d: d[4], reverse=True)
    header = ("Algorithm", r"\#Orbits", r"$\theta_1$ (std)",
              r"$\theta_2$ (std)", r"$1-\theta_2/\theta_1$ (std)")
    return table(rows=rows, header_row=header)
Exemplo n.º 21
0
def lyapunov_comparison_table(L, n_orbits=100, n_iterations=10000):
    r"""
    Return a table of values of Lyapunov exponents for many algorithm.

    INPUT:

    - ``L`` -- list of algorithms
    - ``n_orbits`` -- integer
    - ``n_iterations`` -- integer

    OUTPUT:

        table

    EXAMPLES::

        sage: import slabbe.mult_cont_frac as mcf
        sage: from slabbe.lyapunov import lyapunov_comparison_table
        sage: algos = [mcf.Brun(), mcf.ARP()]
        sage: lyapunov_comparison_table(algos)    # abs tol 0.01
          Algorithm                 \#Orbits   $\theta_1$ (std)   $\theta_2$ (std)   $1-\theta_2/\theta_1$ (std)
        +-------------------------+----------+------------------+------------------+-----------------------------+
          Arnoux-Rauzy-Poincar\'e   100        0.44 (0.012)       -0.172 (0.0060)    1.388 (0.0054)
          Brun                      100        0.30 (0.011)       -0.113 (0.0049)    1.370 (0.0070)
    """
    rows = []
    for algo in L:
        try:
            row = _lyapunov_row(algo, n_orbits, n_iterations)
        except Exception as err:
            s = "{}: {}".format(err.__class__.__name__, err)
            print("Ignoring {} in Lyapunov table. {}".format(algo.class_name(), s))
        else:
            rows.append(row)
    rows.sort(key=lambda d:d[4], reverse=True)
    header = ("Algorithm", r"\#Orbits", r"$\theta_1$ (std)", r"$\theta_2$ (std)",
               r"$1-\theta_2/\theta_1$ (std)")
    return table(rows=rows, header_row=header)
Exemplo n.º 22
0
def test_packages(packages, only_failures=False):
    """
    Return list of all installed packages.

    INPUT:

    - ``packages`` -- a list/tuple/iterable of strings. The names of
      GAP packages to try to import.

    - ``only_failures`` -- boolean, default ``False``. Whether to only
      include failures in the table.

    OUTPUT:

    A table of the installed packages and whether they load
    successfully.

    EXAMPLES::

        sage: from sage.tests.gap_packages import all_installed_packages, test_packages
        sage: test_packages(['GAPDoc'])
          Status   Package   GAP Output
        +--------+---------+------------+
                   GAPDoc    true

    All packages, including user-installed ones::

        sage: pkgs = all_installed_packages()
        sage: test_packages(pkgs)    # random output
          Status    Package      GAP Output
        +---------+------------+------------+
                   Alnuth       true
                   GAPDoc       true
                   HAPcryst     true
                   Hap          true
                   QPA          true
                   aclib        true
                   atlasrep     true
                   autpgrp      true
                   cohomolo     true
                   corelg       true
                   crime        true
                   cryst        true
                   crystcat     true
                   ctbllib      true
                   design       true
                   factint      true
                   gbnp         true
                   grape        true
                   guava        true
                   happrime     true
                   hecke        true
                   laguna       true
                   liealgdb     true
                   liepring     true
                   liering      true
                   loops        true
                   mapclass     true
                   polycyclic   true
                   polymaking   true
                   quagroup     true
                   repsn        true
                   sla          true
                   sonata       true
                   tomlib       true
                   toric        true
    """
    rows = [['Status', 'Package', 'GAP Output']]
    for pkgdir in packages:
        # to allow weird suffixes e.g. 'qpa-version'
        pkg = pkgdir.split('-')[0]
        orig_warning_level = libgap.InfoLevel(libgap.InfoWarning)
        # Silence warnings about missing optional packages that might occur
        # when loading packages; they're not important for the purposes of this
        # test code
        libgap.SetInfoLevel(libgap.InfoWarning, 0)
        try:
            output = libgap.LoadPackage(pkg)
        finally:
            # Restore the original warning level
            libgap.SetInfoLevel(libgap.InfoWarning, orig_warning_level)

        ok = bool(output)
        status = '' if ok else 'Failure'
        if ok and only_failures:
            continue
        rows.append([status, pkg, str(output)])
    from sage.misc.table import table
    return table(rows, header_row=True)
Exemplo n.º 23
0
def dirichlet_convergents_dependance(v, n, verbose=False):
    r"""
    INPUT:

    - ``v`` -- list of real numbers
    - ``n`` -- integer, number of iterations
    - ``verbose`` -- bool (default: ``False``),

    OUTPUT:

    - table of linear combinaisons of dirichlet approximations in terms of
      previous dirichlet approximations

    EXAMPLES::

        sage: from slabbe.diophantine_approx import dirichlet_convergents_dependance
        sage: dirichlet_convergents_dependance([e,pi], 4)
          i   vi                      lin. rec.     remainder
        +---+-----------------------+-------------+-----------+
          0   (3, 3, 1)               []            (3, 3, 1)
          1   (19, 22, 7)             [6]           (1, 4, 1)
          2   (1843, 2130, 678)       [96, 6]       (1, 0, 0)
          3   (51892, 59973, 19090)   [28, 15, 1]   (0, 0, 0)

    The last 3 seems enough::

        sage: dirichlet_convergents_dependance([e,pi], 8)
          i   vi                         lin. rec.     remainder
        +---+--------------------------+-------------+-----------+
          0   (3, 3, 1)                  []            (3, 3, 1)
          1   (19, 22, 7)                [6]           (1, 4, 1)
          2   (1843, 2130, 678)          [96, 6]       (1, 0, 0)
          3   (51892, 59973, 19090)      [28, 15, 1]   (0, 0, 0)
          4   (113018, 130618, 41577)    [2, 5, 1]     (0, 0, 0)
          5   (114861, 132748, 42255)    [1, 0, 1]     (0, 0, 0)
          6   (166753, 192721, 61345)    [1, 0, 1]     (0, 0, 0)
          7   (446524, 516060, 164267)   [2, 0, 1]     (0, 0, 0)

    But not in this case::

        sage: dirichlet_convergents_dependance([pi,sqrt(3)], 12)
          i    vi                      lin. rec.                  remainder
        +----+-----------------------+--------------------------+-----------+
          0    (3, 2, 1)               []                         (3, 2, 1)
          1    (22, 12, 7)             [6]                        (4, 0, 1)
          2    (47, 26, 15)            [2, 1]                     (0, 0, 0)
          3    (69, 38, 22)            [1, 1]                     (0, 0, 0)
          4    (176, 97, 56)           [2, 0, 1, 4]               (4, 1, 1)
          5    (223, 123, 71)          [1, 0, 1]                  (0, 0, 0)
          6    (399, 220, 127)         [1, 1]                     (0, 0, 0)
          7    (1442, 795, 459)        [3, 1, 0, 0, 0, 1]         (0, 0, 0)
          8    (6390, 3523, 2034)      [4, 1, 1]                  (0, 0, 0)
          9    (26603, 14667, 8468)    [4, 0, 2, 1, 0, 0, 0, 1]   (0, 0, 0)
          10   (32993, 18190, 10502)   [1, 1]                     (0, 0, 0)
          11   (40825, 22508, 12995)   [1, 0, 1, 1]               (0, 0, 0)

    The v4 is not a lin. comb. of the previous four::

        sage: dirichlet_convergents_dependance([e,pi,sqrt(3)], 5)
          i   vi                                lin. rec.        remainder
        +---+---------------------------------+----------------+--------------+
          0   (3, 3, 2, 1)                      []               (3, 3, 2, 1)
          1   (19, 22, 12, 7)                   [6]              (1, 4, 0, 1)
          2   (193, 223, 123, 71)               [10, 1]          (0, 0, 1, 0)
          3   (5529, 6390, 3523, 2034)          [28, 6, 3]       (2, 5, 1, 1)
          4   (163067, 188461, 103904, 59989)   [29, 14, 1, 1]   (2, 4, 1, 1)
    """
    L = []
    it = best_simultaneous_convergents(v)
    rows = []
    for i in range(n):
        vi = vector(next(it))
        t = vi
        M = []
        for u in reversed(L):
            m = floor(min(a / b for a, b in zip(t, u)))
            M.append(m)
            t -= m * u
            if t == 0:
                if verbose:
                    c = ','.join("v{}".format(len(L) - j)
                                 for j in range(len(M)))
                    print "v{} = {} = <{}>.<{}>".format(i, vi, M, c)
                break
        else:
            if verbose:
                print "v{} = {} = <{}>.<v{}, ..., v0> + {}".format(
                    i, vi, M, i - 1, t)
        L.append(vi)
        row = [i, vi, M, t]
        rows.append(row)
    header_row = ['i', 'vi', 'lin. rec.', 'remainder']
    from sage.misc.table import table
    return table(rows=rows, header_row=header_row)