Esempio n. 1
0
    def test_congruence_groups(self):
        r"""
        Check whether the different implementations of methods for congruence
        groups and generic arithmetic group by permutations return the same
        results.

        EXAMPLES::

            sage: from sage.modular.arithgroup.tests import Test
            sage: Test().test_congruence_groups() #random
        """
        G = prandom.choice(self.congroups)
        GG = G.as_permutation_group()

        if not GG.is_congruence():
            raise AssertionError, "Hsu congruence test failed"

        methods = [
            'index', 'is_odd', 'is_even', 'is_normal', 'ncusps', 'nregcusps',
            'nirregcusps', 'nu2', 'nu3', 'generalised_level'
        ]

        for f in methods:
            if getattr(G, f)() != getattr(GG, f)():
                raise AssertionError, "results of %s does not coincide for %s" % (
                    f, G)

        if sorted((G.cusp_width(c) for c in G.cusps())) != GG.cusp_widths():
            raise AssertionError, "Cusps widths are different for %s" % G

        for _ in xrange(20):
            m = GG.random_element()
            if m not in G:
                raise AssertionError, "random element generated by perm. group not in %s" % (
                    str(m), str(G))
Esempio n. 2
0
    def random_element(self):
        """
        Returns a random element from the cartesian product of \*iters.

        EXAMPLES::

            sage: CartesianProduct('dog', 'cat').random_element()
            ['d', 'a']
        """
        return [rnd.choice(_) for _ in self.iters]
Esempio n. 3
0
    def random_element(self):
        """
        Returns a random element from the cartesian product of \*iters.

        EXAMPLES::

            sage: CartesianProduct('dog', 'cat').random_element()
            ['d', 'a']
        """
        return [rnd.choice(_) for _ in self.iters]
Esempio n. 4
0
    def random_element(self):
        r"""
        Returns a random element from the Cartesian product of \*iters.

        EXAMPLES::

            sage: from sage.combinat.cartesian_product import CartesianProduct_iters
            sage: CartesianProduct_iters('dog', 'cat').random_element()
            ['d', 'a']
        """
        return [rnd.choice(_) for _ in self.iters]
Esempio n. 5
0
    def random_element(self):
        r"""
        Returns a random element from the Cartesian product of \*iters.

        EXAMPLES::

            sage: from sage.combinat.cartesian_product import CartesianProduct_iters
            sage: CartesianProduct_iters('dog', 'cat').random_element()
            ['d', 'a']
        """
        return [rnd.choice(_) for _ in self.iters]
Esempio n. 6
0
def random_rings(level=MAX_LEVEL):
    """
    Return an iterator over random rings up to the given "level" of complexity.

    EXAMPLES:
        sage: type(sage.rings.tests.random_rings())
        <type 'generator'>
    """
    v = rings0()
    if level >= 1:
        v += rings1()
    while True:
        yield random.choice(v)[0]()
Esempio n. 7
0
def random_rings(level=MAX_LEVEL):
    """
    Return an iterator over random rings up to the given "level" of complexity.

    EXAMPLES:
        sage: type(sage.rings.tests.random_rings())
        <type 'generator'>
    """
    v = rings0()
    if level >= 1:
        v += rings1()
    while True:
        yield random.choice(v)[0]()
Esempio n. 8
0
    def random_element(self):
        r"""
        Return a random element.

        EXAMPLES::

            sage: S = FiniteEnumeratedSet('abc')
            sage: S.random_element()   # random
            'b'
        """
        if not self._elements:
            raise EmptySetError
        from sage.misc.prandom import choice
        return choice(self._elements)
Esempio n. 9
0
File: set.py Progetto: shalec/sage
    def random_element(self):
        r"""
        Return a random element in this set.

        EXAMPLES::

            sage: Set([1,2,3]).random_element() # random
            2
        """
        try:
            return self.object().random_element()
        except AttributeError:
            # TODO: this very slow!
            return choice(self.list())
Esempio n. 10
0
    def random_element(self):
        r"""
        Return a random element in this set.

        EXAMPLES::

            sage: Set([1,2,3]).random_element() # random
            2
        """
        try:
            return self.object().random_element()
        except AttributeError:
            # TODO: this very slow!
            return choice(self.list())
Esempio n. 11
0
    def test_random(self):
        """
        Do a random test from all the possible tests.

        EXAMPLES::

            sage: from sage.modular.arithgroup.tests import Test
            sage: Test().test_random() #random
            Doing random test
        """
        tests = [a for a in Test.__dict__.keys() if a[:5] == "test_" and a != "test_random"]
        name = prandom.choice(tests)
        print "Doing random test %s"%name
        Test.__dict__[name](self)
Esempio n. 12
0
    def random_element(self):
        r"""
        Return a random element.

        EXAMPLES::

            sage: S = FiniteEnumeratedSet('abc')
            sage: S.random_element()   # random
            'b'
        """
        if not self._elements:
            raise EmptySetError
        from sage.misc.prandom import choice
        return choice(self._elements)
Esempio n. 13
0
File: tests.py Progetto: yjjcc/sage
    def test_random(self):
        """
        Do a random test from all the possible tests.

        EXAMPLES::

            sage: from sage.modular.arithgroup.tests import Test
            sage: Test().test_random() #random
            Doing random test
        """
        tests = [
            a for a in Test.__dict__ if a[:5] == "test_" and a != "test_random"
        ]
        name = prandom.choice(tests)
        print("Doing random test %s" % name)
        Test.__dict__[name](self)
Esempio n. 14
0
    def random_element(self):
        """
        Returns a random multichoice of k things from range(n).

        EXAMPLES::

            sage: MultichooseNK(5,2).random_element()
            [0, 2]
            sage: MultichooseNK(5,2).random_element()
            [0, 1]
        """
        n, k = self._n, self._k
        rng = list(range(n))
        r = []
        for i in range(k):
            r.append(rnd.choice(rng))
        r.sort()
        return r
Esempio n. 15
0
    def random_component(self):
        r"""
        Returns a random connected component of this stratum.

        EXAMPLES::

            sage: from surface_dynamics.all import *

            sage: Q = QuadraticStratum(6,6)
            sage: Q.random_component()
            Q_4(6^2)^hyp
            sage: Q.random_component()
            Q_4(6^2)^reg
        """
        if self.components():
            from sage.misc.prandom import choice
            return choice(self.components())
        from sage.categories.sets_cat import EmptySetError
        raise EmptySetError("The stratum is empty")
Esempio n. 16
0
    def random_component(self):
        r"""
        Returns a random connected component of this stratum.

        EXAMPLES::

            sage: from surface_dynamics.all import *

            sage: Q = QuadraticStratum(6,6)
            sage: Q.random_component()
            Q_4(6^2)^hyp
            sage: Q.random_component()
            Q_4(6^2)^reg
        """
        if self.components():
            from sage.misc.prandom import choice
            return choice(self.components())
        from sage.categories.sets_cat import EmptySetError
        raise EmptySetError("The stratum is empty")
Esempio n. 17
0
    def random_element(self):
        """
        Returns a random multichoice of k things from range(n).

        EXAMPLES::

            sage: MultichooseNK(5,2).random_element()
            doctest:...: DeprecationWarning: MultichooseNK should be
            replaced by itertools.combinations_with_replacement
            See http://trac.sagemath.org/16473 for details.
            [0, 2]
            sage: MultichooseNK(5,2).random_element()
            [0, 1]
        """
        n, k = self._n, self._k
        rng = list(range(n))
        r = []
        for i in range(k):
            r.append(rnd.choice(rng))
        r.sort()
        return r
Esempio n. 18
0
    def test_congruence_groups(self):
        r"""
        Check whether the different implementations of methods for congruence
        groups and generic arithmetic group by permutations return the same
        results.

        EXAMPLES::

            sage: from sage.modular.arithgroup.tests import Test
            sage: Test().test_congruence_groups() #random
        """
        G = prandom.choice(self.congroups)
        GG = G.as_permutation_group()

        if not GG.is_congruence():
            raise AssertionError("Hsu congruence test failed")

        methods = [
            'index',
            'is_odd',
            'is_even',
            'is_normal',
            'ncusps',
            'nregcusps',
            'nirregcusps',
            'nu2',
            'nu3',
            'generalised_level']

        for f in methods:
            if getattr(G,f)() != getattr(GG,f)():
                raise AssertionError("results of %s does not coincide for %s" %(f,G))

        if sorted((G.cusp_width(c) for c in G.cusps())) != GG.cusp_widths():
            raise AssertionError("Cusps widths are different for %s" %G)

        for _ in xrange(20):
            m = GG.random_element()
            if m not in G:
                raise AssertionError("random element generated by perm. group not in %s" %(str(m),str(G)))
Esempio n. 19
0
def RandomBlockGraph(m, k, kmax=None, incidence_structure=False):
    r"""
    Return a Random Block Graph.

    A block graph is a connected graph in which every biconnected component
    (block) is a clique.

    .. SEEALSO::

        - :wikipedia:`Block_graph` for more details on these graphs
        - :meth:`~sage.graphs.graph.Graph.is_block_graph` -- test if a graph is a block graph
        - :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cut_vertices`
        - :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cuts_tree`
        - :meth:`~sage.combinat.designs.incidence_structures.IncidenceStructure` 

    INPUT:

    - ``m`` -- integer; number of blocks (at least one).

    - ``k`` -- integer; minimum number of vertices of a block (at least two).

    - ``kmax`` -- integer (default: ``None``) By default, each block has `k`
      vertices. When the parameter `kmax` is specified (with `kmax \geq k`), the
      number of vertices of each block is randomly chosen between `k` and
      `kmax`.

    - ``incidence_structure`` -- boolean (default: ``False``) when set to
      ``True``, the incidence structure of the graphs is returned instead of the
      graph itself, that is the list of the lists of vertices in each
      block. This is useful for the creation of some hypergraphs.

    OUTPUT:

    A Graph when ``incidence_structure==False`` (default), and otherwise an
    incidence structure.

    EXAMPLES:

    A block graph with a single block is a clique::

        sage: B = graphs.RandomBlockGraph(1, 4)
        sage: B.is_clique()
        True

    A block graph with blocks of order 2 is a tree::

        sage: B = graphs.RandomBlockGraph(10, 2)
        sage: B.is_tree()
        True

    Every biconnected component of a block graph is a clique::

        sage: B = graphs.RandomBlockGraph(5, 3, kmax=6)
        sage: blocks,cuts = B.blocks_and_cut_vertices()
        sage: all(B.is_clique(block) for block in blocks)
        True

    A block graph with blocks of order `k` has `m*(k-1)+1` vertices::

        sage: m, k = 6, 4
        sage: B = graphs.RandomBlockGraph(m, k)
        sage: B.order() == m*(k-1)+1
        True

    Test recognition methods::

        sage: B = graphs.RandomBlockGraph(6, 2, kmax=6)
        sage: B.is_block_graph()
        True
        sage: B in graph_classes.Block
        True

    Asking for the incidence structure::

        sage: m, k = 6, 4
        sage: IS = graphs.RandomBlockGraph(m, k, incidence_structure=True)
        sage: from sage.combinat.designs.incidence_structures import IncidenceStructure
        sage: IncidenceStructure(IS)
        Incidence structure with 19 points and 6 blocks
        sage: m*(k-1)+1
        19

    TESTS:

    A block graph has at least one block, so `m\geq 1`::

        sage: B = graphs.RandomBlockGraph(0, 1)
        Traceback (most recent call last):
        ...
        ValueError: the number `m` of blocks must be >= 1

    A block has at least 2 vertices, so `k\geq 2`::

        sage: B = graphs.RandomBlockGraph(1, 1)
        Traceback (most recent call last):
        ...
        ValueError: the minimum number `k` of vertices in a block must be >= 2

    The maximum size of a block is at least its minimum size, so `k\leq kmax`::

        sage: B = graphs.RandomBlockGraph(1, 3, kmax=2)
        Traceback (most recent call last):
        ...
        ValueError: the maximum number `kmax` of vertices in a block must be >= `k`
    """
    import itertools
    from sage.misc.prandom import choice
    from sage.sets.disjoint_set import DisjointSet

    if m < 1:
        raise ValueError("the number `m` of blocks must be >= 1")
    if k < 2:
        raise ValueError("the minimum number `k` of vertices in a block must be >= 2")
    if kmax is None:
        kmax = k
    elif kmax < k:
        raise ValueError("the maximum number `kmax` of vertices in a block must be >= `k`")

    if m == 1:
        # A block graph with a single block is a clique
        IS = [ list(range(randint(k, kmax))) ]
        
    elif kmax == 2:
        # A block graph with blocks of order 2 is a tree
        IS = [ list(e) for e in RandomTree(m+1).edges(labels=False) ]

    else:
        # We start with a random tree of order m
        T = RandomTree(m)

        # We create a block of order in range [k,kmax] per vertex of the tree
        B = {u:[(u,i) for i in range(randint(k, kmax))] for u in T}

        # For each edge of the tree, we choose 1 vertex in each of the
        # corresponding blocks and we merge them. We use a disjoint set data
        # structure to keep a unique identifier per merged vertices
        DS = DisjointSet([i for u in B for i in B[u]])
        for u,v in T.edges(labels=0):
            DS.union(choice(B[u]), choice(B[v]))

        # We relabel vertices in the range [0, m*(k-1)] and build the incidence
        # structure
        new_label = {root:i for i,root in enumerate(DS.root_to_elements_dict())}
        IS = [ [new_label[DS.find(v)] for v in B[u]] for u in B ]

    if incidence_structure:
        return IS
    
    # We finally build the block graph
    if k == kmax:
        BG = Graph(name = "Random Block Graph with {} blocks of order {}".format(m, k))
    else:
        BG = Graph(name = "Random Block Graph with {} blocks of order {} to {}".format(m, k, kmax))
    for block in IS:
        BG.add_clique( block )
    return BG
Esempio n. 20
0
def RandomBlockGraph(m, k, kmax=None, incidence_structure=False):
    r"""
    Return a Random Block Graph.

    A block graph is a connected graph in which every biconnected component
    (block) is a clique.

    .. SEEALSO::

        - :wikipedia:`Block_graph` for more details on these graphs
        - :meth:`~sage.graphs.graph.Graph.is_block_graph` -- test if a graph is a block graph
        - :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cut_vertices`
        - :meth:`~sage.graphs.generic_graph.GenericGraph.blocks_and_cuts_tree`
        - :meth:`~sage.combinat.designs.incidence_structures.IncidenceStructure` 

    INPUT:

    - ``m`` -- integer; number of blocks (at least one).

    - ``k`` -- integer; minimum number of vertices of a block (at least two).

    - ``kmax`` -- integer (default: ``None``) By default, each block has `k`
      vertices. When the parameter `kmax` is specified (with `kmax \geq k`), the
      number of vertices of each block is randomly chosen between `k` and
      `kmax`.

    - ``incidence_structure`` -- boolean (default: ``False``) when set to
      ``True``, the incidence structure of the graphs is returned instead of the
      graph itself, that is the list of the lists of vertices in each
      block. This is useful for the creation of some hypergraphs.

    OUTPUT:

    A Graph when ``incidence_structure==False`` (default), and otherwise an
    incidence structure.

    EXAMPLES:

    A block graph with a single block is a clique::

        sage: B = graphs.RandomBlockGraph(1, 4)
        sage: B.is_clique()
        True

    A block graph with blocks of order 2 is a tree::

        sage: B = graphs.RandomBlockGraph(10, 2)
        sage: B.is_tree()
        True

    Every biconnected component of a block graph is a clique::

        sage: B = graphs.RandomBlockGraph(5, 3, kmax=6)
        sage: blocks,cuts = B.blocks_and_cut_vertices()
        sage: all(B.is_clique(block) for block in blocks)
        True

    A block graph with blocks of order `k` has `m*(k-1)+1` vertices::

        sage: m, k = 6, 4
        sage: B = graphs.RandomBlockGraph(m, k)
        sage: B.order() == m*(k-1)+1
        True

    Test recognition methods::

        sage: B = graphs.RandomBlockGraph(6, 2, kmax=6)
        sage: B.is_block_graph()
        True
        sage: B in graph_classes.Block
        True

    Asking for the incidence structure::

        sage: m, k = 6, 4
        sage: IS = graphs.RandomBlockGraph(m, k, incidence_structure=True)
        sage: from sage.combinat.designs.incidence_structures import IncidenceStructure
        sage: IncidenceStructure(IS)
        Incidence structure with 19 points and 6 blocks
        sage: m*(k-1)+1
        19

    TESTS:

    A block graph has at least one block, so `m\geq 1`::

        sage: B = graphs.RandomBlockGraph(0, 1)
        Traceback (most recent call last):
        ...
        ValueError: the number `m` of blocks must be >= 1

    A block has at least 2 vertices, so `k\geq 2`::

        sage: B = graphs.RandomBlockGraph(1, 1)
        Traceback (most recent call last):
        ...
        ValueError: the minimum number `k` of vertices in a block must be >= 2

    The maximum size of a block is at least its minimum size, so `k\leq kmax`::

        sage: B = graphs.RandomBlockGraph(1, 3, kmax=2)
        Traceback (most recent call last):
        ...
        ValueError: the maximum number `kmax` of vertices in a block must be >= `k`
    """
    import itertools
    from sage.misc.prandom import choice
    from sage.sets.disjoint_set import DisjointSet

    if m < 1:
        raise ValueError("the number `m` of blocks must be >= 1")
    if k < 2:
        raise ValueError(
            "the minimum number `k` of vertices in a block must be >= 2")
    if kmax is None:
        kmax = k
    elif kmax < k:
        raise ValueError(
            "the maximum number `kmax` of vertices in a block must be >= `k`")

    if m == 1:
        # A block graph with a single block is a clique
        IS = [list(range(randint(k, kmax)))]

    elif kmax == 2:
        # A block graph with blocks of order 2 is a tree
        IS = [list(e) for e in RandomTree(m + 1).edges(labels=False)]

    else:
        # We start with a random tree of order m
        T = RandomTree(m)

        # We create a block of order in range [k,kmax] per vertex of the tree
        B = {u: [(u, i) for i in range(randint(k, kmax))] for u in T}

        # For each edge of the tree, we choose 1 vertex in each of the
        # corresponding blocks and we merge them. We use a disjoint set data
        # structure to keep a unique identifier per merged vertices
        DS = DisjointSet([i for u in B for i in B[u]])
        for u, v in T.edges(labels=0):
            DS.union(choice(B[u]), choice(B[v]))

        # We relabel vertices in the range [0, m*(k-1)] and build the incidence
        # structure
        new_label = {
            root: i
            for i, root in enumerate(DS.root_to_elements_dict())
        }
        IS = [[new_label[DS.find(v)] for v in B[u]] for u in B]

    if incidence_structure:
        return IS

    # We finally build the block graph
    if k == kmax:
        BG = Graph(
            name="Random Block Graph with {} blocks of order {}".format(m, k))
    else:
        BG = Graph(
            name="Random Block Graph with {} blocks of order {} to {}".format(
                m, k, kmax))
    for block in IS:
        BG.add_clique(block)
    return BG