Пример #1
0
 def test_enum_hops(self):
     g = Graph(nodes=EnumNodes(['x', 'y', 'z']),
               edges=EnumEdges(Hops.from_dict(x={'y', 'z'})))
     self.assertTrue(g.has_node('y'))
     self.assertFalse(g.has_node('a'))
     self.assertCountEqual(g.predecessors_of('y'), ['x'])
     self.assertCountEqual(g.predecessors_of('x'), [])
Пример #2
0
    def test_pons_asinorum(self):
        g0 = Graph.with_features(
            Equation.make_table(range(1, 20), range(1, 20),
                                [plus, minus, times]))
        g1 = Graph.augment(PrefixedGraph(1, g0), PrefixedGraph(2, g0))
        #        print('QQ')
        #        qq = list((x1, x1.with_prefix(2))
        #            for x1 in g1.query(WithPrefix(1, OfClass(After))))
        #        print(type(qq), type(qq[0]), len(qq[0]))
        #        pts(qq)
        g = g1.add_edges(
            EnumEdges(
                Hops.from_pairs(*(
                    (p_after, PrefixedNode(2, Before(p_after.unprefixed().x)))
                    for p_after in g1.query(WithPrefix(1, OfClass(After)))))))
        #pts(g.query(WithPrefix(1, OfClass(After))))
        #pts(g.query(WithPrefix(2, OfClass(Before))))
        #pts(g.successors_of(PrefixedNode(1, After(10))))
        #print()
        #pts(g.successors_of(PrefixedNode(1, After(63))))

        self.assertTrue(
            g.find_hop(PrefixedNode(1, After(10)), PrefixedNode(2,
                                                                Before(10))))
        self.assertFalse(
            g.find_hop(PrefixedNode(1, After(63)), PrefixedNode(2,
                                                                Before(63))))
Пример #3
0
def grafi_connessi():
    g = Graph()
    g2=Graph()

    dict_edge={}



    n=100
    g_seq=Graph_seq(n)
    for i in range(n):
        v0=g.insert_vertex(i)
        g2.insert_vertex(i)
        v0.connessioni=Array("i",n,lock=False)
        v0.pesi_condivisi=Array("i",n,lock=False)

    nodi=g.vertices()
    for i in range(len(nodi)):
        print(i)
        j=i+1
        for x in range(j,len(nodi)):
            while True:
                peso = randint( 1, 100000000 )
                if g.peso_unico(peso):
                        e=g.insert_edge( nodi[i], nodi[x], peso )
                        g_seq.addEdge(i,x,peso)
                        dict_edge[e.element()]=e
                        nodi[i].pesi_condivisi[nodi[x].element()]=peso
                        nodi[x].pesi_condivisi[nodi[i].element()]=peso

                        nodi[i].connessioni[len(nodi[i].listaArchi)-1]=nodi[x].element()
                        nodi[x].connessioni[len(nodi[x].listaArchi)-1]=nodi[i].element()
                        break
    lista_pesi_condivisi=[]
    lista_connessioni_condivise=[]

    for node in nodi:
        if len(node.listaArchi)<n:
            node.connessioni[len(node.listaArchi)]=-1

        lista_pesi_condivisi.append(node.pesi_condivisi)
        lista_connessioni_condivise.append(node.connessioni)

    return g,g_seq,lista_pesi_condivisi,lista_connessioni_condivise,dict_edge
Пример #4
0
    def test_doubled_graph(self):
        g0 = Graph(nodes=EnumNodes(['a', 'b', 'o']),
                   edges=EnumEdges(Hops.from_pairs(('a', 'b'), ('b', 'o'))))
        g = Graph.augment(PrefixedGraph(1, g0), PrefixedGraph(2, g0))

        self.assertTrue(g.has_node(PrefixedNode(1, 'a')))
        self.assertTrue(g.has_node(PrefixedNode(2, 'a')))
        self.assertFalse(g.has_node(PrefixedNode(3, 'a')))
        self.assertFalse(g.has_node('a'))
        self.assertEqual(
            g.find_hop(PrefixedNode(1, 'a'), PrefixedNode(1, 'b')),
            Hop(PrefixedNode(1, 'a'), PrefixedNode(1, 'b'), 1.0))
        self.assertEqual(
            g.find_hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b')),
            Hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b'), 1.0))
        self.assertEqual(
            g.find_hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'b')), None)
        self.assertEqual(g.find_hop('a', 'b'), None)

        # .add_edges() from one PrefixedGraph to the other

        g2 = g.add_edges(
            EnumEdges(
                Hops.from_pairs((PrefixedNode(1, 'a'), PrefixedNode(2, 'a')))))
        self.assertEqual(
            g2.find_hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'a')),
            Hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'a'), 1.0))

        self.assertCountEqual(g2.query(OfClass(str)), [
            PrefixedNode(1, 'a'),
            PrefixedNode(1, 'b'),
            PrefixedNode(1, 'o'),
            PrefixedNode(2, 'a'),
            PrefixedNode(2, 'b'),
            PrefixedNode(2, 'o')
        ])
        self.assertCountEqual(
            g2.query(WithPrefix(2, OfClass(str))),
            [PrefixedNode(2, 'a'),
             PrefixedNode(2, 'b'),
             PrefixedNode(2, 'o')])
        self.assertCountEqual(g0.query(WithPrefix(2, OfClass(str))), [])
Пример #5
0
    def test_features_graph(self):
        e = Equation.make([3, 4], plus)
        g = Graph.with_features([e])
        #print(type(g.edges))
        #pr(g.edges)
        self.assertTrue(g.has_node(NumOperands(2)))
        self.assertTrue(g.has_node(2))

        self.assertEqual(g.hop_weight(e, plus), 1.0)
        self.assertEqual(g.hop_weight(plus, e), 1.0)
        self.assertEqual(g.hop_weight(e, 2), 0.0)
Пример #6
0
 def test_graph_propagator_incoming(self):
     g = Graph(nodes=EnumNodes(['a', 'b', 'o']),
               edges=EnumEdges(Hops.from_pairs(('a', 'b'), ('b', 'o'))))
     p = GraphPropagatorIncoming(positive_feedback_rate=0.2,
                                 alpha=0.9,
                                 max_total=1.0,
                                 noise=0.0)
     in_d = dict(a=1.0, b=0.5, o=0.0)
     out_d = p.propagate(g, in_d)
     self.assertAlmostEqual(out_d['a'], 0.569072143062159)
     self.assertAlmostEqual(out_d['b'], 0.319848331226608)
     self.assertAlmostEqual(out_d['o'], 0.11107952571123292)
Пример #7
0
def HamTourGadget(Hint):
    edgeList = [(0, 5), (0, 2), (0, 6), (1, 2), (1, 5), (2, 3), (4, 5), (5, 6)]
    Graph = UndirectedGraph(7, edgeList)
  
    #Ensure no duplicates in the list
    Hint2 = list(set(Hint))
    if len(Hint2) != len(Hint): return False

    for i in Hint:
	if Hint[(i+1)%7] in Graph.neighbors(Hint[i]):continue
	else: return False
    print Hint
    return True	 
Пример #8
0
    def test_augment(self):
        g1 = AlphabetGraph()
        g2 = Graph(nodes=EnumNodes(range(1, 4)),
                   edges=EnumEdges(
                       Hops.from_pairs((1, 'a'), (2, 'b'), (3, 'c'))))
        g = Graph.augment(g2, g1)

        self.assertTrue(g2.has_node(1))
        self.assertFalse(g2.has_node('a'))
        self.assertFalse(g2.find_hop(1, 'a'))
        self.assertCountEqual(g2.successors_of(2), [])
        self.assertCountEqual(g2.predecessors_of('c'), [])

        self.assertTrue(g.has_node(1))
        self.assertTrue(g.has_node('a'))
        self.assertTrue(g.find_hop(1, 'a'))
        self.assertCountEqual(g.successors_of(2), ['b'])
        self.assertCountEqual(g.predecessors_of('b'), [2, 'a'])
Пример #9
0
    def test_features(self):
        @dataclass(frozen=True)
        class Parity(Feature):
            name: str

        Even = Parity('Even')
        Odd = Parity('Odd')

        @dataclass(frozen=True)
        class BaseNode:
            n: int

            def features_of(self):
                if self.n & 1:
                    yield Odd
                else:
                    yield Even
                yield self.n

        g = Graph.with_features([BaseNode(1), BaseNode(2), BaseNode(3)])

        self.assertCountEqual(g.query(OfClass(Parity)), [Odd, Even])
        self.assertCountEqual(g.hops_to_node(BaseNode(1)), [
            Hop(Odd, BaseNode(1), 1.0),
            Hop(1, BaseNode(1), 1.0),
            Hop(BaseNode, BaseNode(1), 1.0)
        ])
        self.assertCountEqual(g.hops_from_node(Odd), [
            Hop(Odd, BaseNode(1), 1.0),
            Hop(Odd, BaseNode(3), 1.0),
            Hop(Odd, Parity, 1.0)
        ])
        self.assertEqual(g.find_hop(BaseNode(2), Even),
                         Hop(BaseNode(2), Even, 1.0))
        self.assertEqual(g.find_hop(Even, Odd), None)

        # Now add mutual inhibition
        g = g.add_edges(MutualInhibition((Feature, int)))

        self.assertEqual(g.find_hop(Even, Odd), Hop(Even, Odd, -0.2))
        self.assertEqual(g.find_hop(Odd, Even), Hop(Odd, Even, -0.2))
        self.assertEqual(g.find_hop(1, 2), Hop(1, 2, -0.2))
Пример #10
0
from Equation import Equation, Operator, plus, times, minus
from Equation import IncreaseOrDecrease, Increase, Decrease, NumOperands, \
    Before, After, MaxBefore, MinBefore
from Graph2 import Graph, Node, Hop, Hops, Nodes, Edges, EnumNodes, EnumEdges, \
    OfClass, MutualInhibition, Feature, features_of, GraphPropagatorOutgoing, \
    PrefixedGraph, PrefixedNode, WithPrefix
from Slipnet2 import Slipnet, NodeA, TyrrellPropagator, \
    default_tyrrell_propagator
from FMTypes import epsilon
from util import as_iter, as_dict, union, pts, pr


eqn_graph = Graph.with_features(
    Equation.make_table(
        range(1, 11), range(1, 11), [plus, minus, times]
    )
) #.add_edges(MutualInhibition((Feature, Operator, Equation, int), weight=-5.0))
p = TyrrellPropagator(
    max_total=10.0,
    noise=0.0,
    positive_feedback_rate=0.0, #1.5,  # higher -> initial features matter more
    sigmoid_p=1.2,  #1.5 higher -> sharper distinctions, more salience
    num_iterations=10,
    alpha=0.95,
    tyrrell_alpha=0.05,  # 0.2
    tyrrell_beta=0.1
)
p1a = TyrrellPropagator(  # Makes 6+4=10 just barely win
    max_total=10.0,
    noise=0.0,
Пример #11
0
def creaRandom():
    # CREAZIONE RANDOM DEL GRAFO

    g = Graph()
    g2=Graph()

    dict_edge={}



    n=100
    g_seq=Graph_seq(n)
    for i in range(n):
        v0=g.insert_vertex(i)
        g2.insert_vertex(i)
        v0.connessioni=Array("i",n,lock=False)
        v0.pesi_condivisi=Array("i",n,lock=False)
        #print(i)
        #v0.archi_condivisi=m.list([0 for x in range(n-1)])

    nodi=g.vertices()
    nodi2=g2.vertices()


    for i in range(0,len(nodi)):
        while True:
            peso = randint( 1, 100000000 )
            if g.peso_unico(peso):
                if i+1==len(nodi):
                    e=g.insert_edge( nodi[i], nodi[0], peso )
                    g_seq.addEdge(i,0,peso)
                    dict_edge[e.element()]=e
                    nodi[i].pesi_condivisi[nodi[0].element()]=peso
                    nodi[0].pesi_condivisi[nodi[i].element()]=peso

                    nodi[i].connessioni[len(nodi[i].listaArchi)-1]=nodi[0].element()
                    nodi[0].connessioni[len(nodi[0].listaArchi)-1]=nodi[i].element()


                    g2.insert_edge( nodi2[i], nodi2[0], peso )
                    break
                else:
                    e=g.insert_edge( nodi[i], nodi[i+1], peso )
                    dict_edge[e.element()]=e
                    g_seq.addEdge(i,i+1,peso)
                    nodi[i].pesi_condivisi[nodi[i+1].element()]=peso
                    nodi[i+1].pesi_condivisi[nodi[i].element()]=peso
                    nodi[i].connessioni[len(nodi[i].listaArchi)-1]=nodi[i+1].element()
                    nodi[i+1].connessioni[len(nodi[i+1].listaArchi)-1]=nodi[i].element()

                    g2.insert_edge( nodi2[i], nodi2[i+1], peso )
                    break


    lista_archi_condivisi=[]
    for node in nodi:
        i=0
        #print(node,flush=True)
        print("node",node,flush=True)
        while i<1:
            peso = randint( 1, 100000000 )
            # NUMERO MOLTO GRANDE PER AVERE QUASI LA CERTEZZA DI NON AVERE ARCHI CON LO STESSO PESO
            # LA FUNZIONE PER IL CONTROLLO è PRESENTE NELA CLASSE DEL GRAFO MA IMPIEGA MOLTO TEMPO
            nodo2 = randint(0, n-1)
            if nodo2 != node.element() and g.get_edge(node,nodi[nodo2]) is None and g.peso_unico(peso):

                e=g.insert_edge( node, nodi[nodo2], peso )
                g_seq.addEdge(node.element(),nodo2,peso)
                dict_edge[e.element()]=e
                g2.insert_edge( nodi2[node.element()], nodi2[nodo2], peso )

                node.pesi_condivisi[nodi[nodo2].element()]=peso
                nodi[nodo2].pesi_condivisi[node.element()]=peso
                node.connessioni[len(node.listaArchi)-1]=nodi[nodo2].element()
                nodi[nodo2].connessioni[len( nodi[nodo2].listaArchi)-1]=node.element()
                i=i+1

    lista_pesi_condivisi=[]
    lista_connessioni_condivise=[]

    for node in nodi:
        if len(node.listaArchi)<n:
            node.connessioni[len(node.listaArchi)]=-1

        lista_pesi_condivisi.append(node.pesi_condivisi)
        lista_connessioni_condivise.append(node.connessioni)





    return g,g_seq,lista_pesi_condivisi,lista_connessioni_condivise,dict_edge
Пример #12
0
def Boruvka_parallel_array(g,lista_pesi_condivisi,lista_connessioni,dict_edge):
    grafoB = Graph()

    lista_nodi = g.vertices()

    for node in lista_nodi:
        grafoB.insert_vertex( node.element() )

    peso_albero=0
    parent = Array( "i", g.vertex_count(), lock=False )
    successor_next =Array( "i",g.vertex_count(), lock=False )


    result=Array("i",g.vertex_count(),lock=False)

    jobs_min=JoinableQueue()

    processes_minimo=minimo_paralelo(parent,successor_next,lista_pesi_condivisi,lista_connessioni,jobs_min,result)
    lista_nodi_boruvka=grafoB.vertices()






    t66=time()
    while len( lista_nodi ) > 1:
        lista_divisa_interi=dividi_gruppi(lista_nodi,8)
        t2=time()
        add_jobs(jobs_min,lista_divisa_interi,0)
        jobs_min.join()


        for node in lista_nodi:
            edge=dict_edge[result[node.element()]]

            n1,n2=edge.endpoints_posizione()
            e=grafoB.insert_edge(lista_nodi_boruvka[n1],lista_nodi_boruvka[n2]
                                 ,edge.element())
            if e is not None:
                peso_albero+=edge.element()


        for node in lista_nodi:
            i=node.element()
            parent_opposto = parent[parent[i]]
            if i == parent_opposto:
                if i < parent[i]:
                    parent[i] = i
                else:
                    parent[parent[i]] = parent[i]

        while True:
            bool = True

            add_jobs(jobs_min,lista_divisa_interi,1)
            jobs_min.join()

            for x, y in zip( parent, successor_next ):
                if x != y:

                    bool = False
                    break

            if bool:
                break

            add_jobs(jobs_min,lista_divisa_interi,2)
            jobs_min.join()



        for node in lista_nodi:
            node.root =parent[node.element()]
            node.setElement( node.root )



        dict_merge={}


        for node in lista_nodi:
            if node.root==node.posizione:
                dict_merge[node.root]=[]


        add_jobs(jobs_min,lista_divisa_interi,3)
        jobs_min.join()


        lista=[x for x in lista_nodi]
        lista_nodi=[]
        for node in lista:
            if node.posizione!=node.root:
                dict_merge[node.root].append(node.posizione)
            else:
                lista_nodi.append(node)



        if len(lista_nodi)<=1:
            break





        add_jobs(jobs_min,dict_merge,4)
        jobs_min.join()





    for pr in processes_minimo:
        pr.terminate()





    return (grafoB,peso_albero)
Пример #13
0
        # .add_edges() from one PrefixedGraph to the other

        g2 = g.add_edges(
            EnumEdges(
                Hops.from_pairs((PrefixedNode(1, 'a'), PrefixedNode(2, 'a')))))
        self.assertEqual(
            g2.find_hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'a')),
            Hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'a'), 1.0))

        self.assertCountEqual(g2.query(OfClass(str)), [
            PrefixedNode(1, 'a'),
            PrefixedNode(1, 'b'),
            PrefixedNode(1, 'o'),
            PrefixedNode(2, 'a'),
            PrefixedNode(2, 'b'),
            PrefixedNode(2, 'o')
        ])
        self.assertCountEqual(
            g2.query(WithPrefix(2, OfClass(str))),
            [PrefixedNode(2, 'a'),
             PrefixedNode(2, 'b'),
             PrefixedNode(2, 'o')])
        self.assertCountEqual(g0.query(WithPrefix(2, OfClass(str))), [])


if __name__ == '__main__':
    # TODO mv this someplace where make_equations() is defined
    g = Graph.with_features(make_equations(1, 20, {plus, minus, times})) \
             .add_edges(MutualInhibition(Feature))
Пример #14
0
 def test_equation_table(self):
     g = Graph.with_features(
         Equation.make_table(range(1, 11), range(1, 11),
                             [plus, minus, times])).add_edges(
                                 MutualInhibition(Feature))
     self.assertEqual(g.hop_weight(Before(2), Before(3)), -0.2)
Пример #15
0
def creaRandom():
    # CREAZIONE RANDOM DEL GRAFO

    g = Graph()
    g_sequenziale = Graph()
    g_parallel_array = Graph()
    g_parallel_queue = Graph()
    g_prim = Graph2()
    dict_edge = {}

    n = 10000
    for i in range(n):

        g_sequenziale.insert_vertex(i)
        v1 = g_parallel_queue.insert_vertex(i)
        v2 = g_parallel_array.insert_vertex(i)
        v1.connessioni = Array("i", n, lock=False)
        v1.pesi_condivisi = Array("i", n, lock=False)
        v2.connessioni = Array("i", n, lock=False)
        v2.pesi_condivisi = Array("i", n, lock=False)
        g_prim.insert_vertex(i)
        g.insert_vertex(i)

    nodi = g.vertices()
    nodi_sequenziale = g_sequenziale.vertices()
    nodi_array = g_parallel_array.vertices()
    nodi_queue = g_parallel_queue.vertices()
    nodi_prim = g_prim.vertices()

    for i in range(0, len(nodi)):
        while True:
            peso = randint(1, 100000000)
            if g.peso_unico(peso):
                if i + 1 == len(nodi):
                    e = g.insert_edge(nodi[i], nodi[0], peso)
                    dict_edge[e.element()] = e
                    g_prim.insert_edge(nodi_prim[i], nodi_prim[0], peso)
                    g_sequenziale.insert_edge(nodi_sequenziale[i],
                                              nodi_sequenziale[0], peso)

                    g_parallel_array.insert_edge(nodi_array[i], nodi_array[0],
                                                 peso)
                    g_parallel_queue.insert_edge(nodi_queue[i], nodi_queue[0],
                                                 peso)
                    nodi_queue[i].pesi_condivisi[
                        nodi_queue[0].element()] = peso
                    nodi_queue[0].pesi_condivisi[
                        nodi_queue[i].element()] = peso

                    nodi_queue[i].connessioni[len(nodi_queue[i].listaArchi) -
                                              1] = nodi_queue[0].element()
                    nodi_queue[0].connessioni[len(nodi_queue[0].listaArchi) -
                                              1] = nodi_queue[i].element()

                    nodi_array[i].pesi_condivisi[
                        nodi_array[0].element()] = peso
                    nodi_array[0].pesi_condivisi[
                        nodi_array[i].element()] = peso

                    nodi_array[i].connessioni[len(nodi_array[i].listaArchi) -
                                              1] = nodi_array[0].element()
                    nodi_array[0].connessioni[len(nodi_array[0].listaArchi) -
                                              1] = nodi_array[i].element()
                    break

                else:
                    e = g.insert_edge(nodi[i], nodi[i + 1], peso)
                    dict_edge[e.element()] = e
                    g_prim.insert_edge(nodi_prim[i], nodi_prim[i + 1], peso)
                    g_sequenziale.insert_edge(nodi_sequenziale[i],
                                              nodi_sequenziale[i + 1], peso)
                    g_parallel_array.insert_edge(nodi_array[i],
                                                 nodi_array[i + 1], peso)
                    g_parallel_queue.insert_edge(nodi_queue[i],
                                                 nodi_queue[i + 1], peso)

                    nodi_queue[i].pesi_condivisi[nodi_queue[
                        i + 1].element()] = peso
                    nodi_queue[i + 1].pesi_condivisi[
                        nodi_queue[i].element()] = peso
                    nodi_queue[i].connessioni[len(nodi_queue[i].listaArchi) -
                                              1] = nodi_queue[i + 1].element()
                    nodi_queue[i +
                               1].connessioni[len(nodi_queue[i + 1].listaArchi)
                                              - 1] = nodi_queue[i].element()

                    nodi_array[i].pesi_condivisi[nodi_array[
                        i + 1].element()] = peso
                    nodi_array[i + 1].pesi_condivisi[
                        nodi_array[i].element()] = peso
                    nodi_array[i].connessioni[len(nodi_array[i].listaArchi) -
                                              1] = nodi_array[i + 1].element()
                    nodi_array[i +
                               1].connessioni[len(nodi_array[i + 1].listaArchi)
                                              - 1] = nodi_array[i].element()
                    break

    for node in nodi:
        i = 0
        while i < 99:
            peso = randint(1, 100000000)
            # NUMERO MOLTO GRANDE PER AVERE QUASI LA CERTEZZA DI NON AVERE ARCHI CON LO STESSO PESO
            # LA FUNZIONE PER IL CONTROLLO è PRESENTE NELA CLASSE DEL GRAFO MA IMPIEGA MOLTO TEMPO
            nodo2 = randint(0, n - 1)
            if nodo2 != node.element() and g.get_edge(
                    node, nodi[nodo2]) is None and g.peso_unico(peso):

                e = g.insert_edge(node, nodi[nodo2], peso)
                dict_edge[e.element()] = e
                g_sequenziale.insert_edge(nodi_sequenziale[node.element()],
                                          nodi_sequenziale[nodo2], peso)
                g_parallel_array.insert_edge(nodi_array[node.element()],
                                             nodi_array[nodo2], peso)
                g_parallel_queue.insert_edge(nodi_queue[node.element()],
                                             nodi_queue[nodo2], peso)
                g_prim.insert_edge(nodi_prim[node.element()], nodi_prim[nodo2],
                                   peso)

                nodi_queue[node.element()].pesi_condivisi[
                    nodi_queue[nodo2].element()] = peso
                nodi_queue[nodo2].pesi_condivisi[nodi_queue[
                    node.element()].element()] = peso
                nodi_queue[node.element()].connessioni[
                    len(nodi_queue[node.element()].listaArchi) -
                    1] = nodi_queue[nodo2].element()
                nodi_queue[nodo2].connessioni[
                    len(nodi_queue[nodo2].listaArchi) -
                    1] = nodi_queue[node.element()].element()

                nodi_array[node.element()].pesi_condivisi[
                    nodi_array[nodo2].element()] = peso
                nodi_array[nodo2].pesi_condivisi[nodi_array[
                    node.element()].element()] = peso
                nodi_array[node.element()].connessioni[
                    len(nodi_array[node.element()].listaArchi) -
                    1] = nodi_array[nodo2].element()
                nodi_array[nodo2].connessioni[
                    len(nodi_array[nodo2].listaArchi) -
                    1] = nodi_array[node.element()].element()
                i = i + 1

    lista_pesi_condivisi_queue = []
    lista_connessioni_condivise_queue = []
    lista_connessioni_condivise_array = []
    lista_pesi_condivisi_array = []
    for node in nodi_array:
        if len(node.listaArchi) < n:
            node.connessioni[len(node.listaArchi)] = -1

        lista_pesi_condivisi_array.append(node.pesi_condivisi)
        lista_connessioni_condivise_array.append(node.connessioni)

    for node in nodi_queue:
        if len(node.listaArchi) < n:
            node.connessioni[len(node.listaArchi)] = -1

        lista_pesi_condivisi_queue.append(node.pesi_condivisi)
        lista_connessioni_condivise_queue.append(node.connessioni)

    return g,g_sequenziale,g_parallel_array,g_parallel_queue,\
           g_prim,lista_pesi_condivisi_array,\
           lista_connessioni_condivise_array,lista_pesi_condivisi_queue,lista_connessioni_condivise_queue,dict_edge
Пример #16
0
    return costo_mst


if __name__ == "__main__":
    g,g_sequenziale,g_parallel_array,g_parallel_queue,g_prim\
        ,lista_pesi_condivisi_array,lista_connessioni_condivise_array,\
    lista_pesi_condivisi_queue,lista_connessioni_condivise_queue,edge_dict=creaRandom()
    print("NUMERO DI NODI: {}, NUMERO DI ARCHI: {}".format(
        g.vertex_count(), g.edges_count()),
          flush=True)

    lista_nodi_originale = g.vertices()

    parent = [0 for node in g.vertices()]
    successor_next = [0 for node in g.vertices()]
    mst = Graph()

    for node in g.vertices():
        mst.insert_vertex(node.element())

    costo_mst = 0

    lista_nodi_mst = mst.vertices()
    nodi_rimanenti = g.vertices()
    n_process = 8
    comm = MPI.COMM_SELF.Spawn(
        sys.executable,
        args=[os.path.dirname(sys.argv[0]) + "\child_processes.py"],
        maxprocs=n_process)

    tempo_parallelo = time()
Пример #17
0
 def fill_slipnet(self):
     #self.slipnet = eqn_graph
     self.slipnet.base_graph = \
         Graph.augment(self.slipnet.base_graph, eqn_graph)
Пример #18
0
    NewType, Type, ClassVar, Sequence, Callable, Hashable, Collection, \
    Sequence, Literal

import matplotlib.pyplot as plt  # type: ignore[import]
import numpy as np  # type: ignore[import]

from FARGModel import FARGModel, SeqCanvas, SeqState, CellRef, Want, Consume, \
    Before, After
from FMTypes import epsilon, Elem, Elems, Value, Addr, FMPred
from Graph2 import Graph, MutualInhibition
from Equation import Equation, Operator, plus, times, minus, EqnConsume
from util import pts, pl, pr

eqn_graph = Graph.with_features(
    EqnConsume.make(eqn)
        for eqn in Equation.make_table(
            range(1, 11), range(1, 11), [plus, minus, times]
        )
) #.add_edges(MutualInhibition((Feature, Equation, int), weight=-0.02))

class Numbo(FARGModel):

    def fill_slipnet(self):
        #self.slipnet = eqn_graph
        self.slipnet.base_graph = \
            Graph.augment(self.slipnet.base_graph, eqn_graph)

def r4_5_6__15(*args, **kwargs):
    global fm, ca, wa
    fm = Numbo(*args, **kwargs)
    ca = fm.build(SeqCanvas([SeqState((4, 5, 6), None)]))
    wa = fm.build(Want(15, CellRef(ca, 0)))
Пример #19
0
def creaRandom():
    # CREAZIONE RANDOM DEL GRAFO

    g = Graph()

    for i in range(100):
        g.insert_vertex(i)

    nodi = g.vertices()

    for i in range(0, len(nodi)):
        while True:
            peso = randint(1, 1000000000)
            if g.peso_unico(peso):
                if i + 1 == len(nodi):
                    g.insert_edge(nodi[i], nodi[0], peso)
                    break
                else:
                    g.insert_edge(nodi[i], nodi[i + 1], peso)
                    break

    for node in nodi:
        i = 0
        while i < 3:
            peso = randint(1, 1000000000)
            # NUMERO MOLTO GRANDE PER AVERE QUASI LA CERTEZZA DI NON AVERE ARCHI CON LO STESSO PESO
            # LA FUNZIONE PER IL CONTROLLO è PRESENTE NELA CLASSE DEL GRAFO MA IMPIEGA MOLTO TEMPO
            nodo2 = randint(0, 9999)
            if nodo2 != node.element() and g.get_edge(
                    node, nodi[nodo2]) is None and g.peso_unico(peso):
                i = i + 1
                g.insert_edge(node, nodi[nodo2], peso)

    return g
Пример #20
0
 def __init__ (self, numVerts, edgeList):
   Graph.__init__(self, numVerts, [])
   for x,y in edgeList:
       self.addEdge(x,y)
Пример #21
0
 def test_enum_graph(self):
     g = Graph(nodes=EnumNodes(['x', 'y', 'z']), edges=EnumEdges())
     self.assertTrue(g.has_node('y'))
     self.assertFalse(g.has_node('a'))
     self.assertCountEqual(g.predecessors_of('y'), [])
Пример #22
0
def AlphabetGraph():
    '''A graph consisting of nodes for 'a'..'z', with an edge from each letter
    to its immediate successor. Illustrates how to make a virtual graph,
    where every node and edge as computed as it searched for, rather than
    each being represented explicitly by a separate object.'''
    return Graph(nodes=AlphabetNodes(), edges=AlphabetEdges())
Пример #23
0
    def test_prefix(self):
        g0 = Graph(nodes=EnumNodes(['a', 'b', 'o']),
                   edges=EnumEdges(Hops.from_pairs(('a', 'b'), ('b', 'o'))))
        g = PrefixedGraph(2, g0)

        # methods that go to Nodes

        self.assertFalse(g.has_node('a'))
        self.assertTrue(g.has_node(PrefixedNode(2, 'a')))
        self.assertFalse(g.has_node(PrefixedNode(1, 'a')))

        self.assertCountEqual(
            g.query(OfClass(str)),
            [PrefixedNode(2, 'a'),
             PrefixedNode(2, 'b'),
             PrefixedNode(2, 'o')])

        # methods that go to Edges

        # .hops_from_node()
        self.assertCountEqual(g.hops_from_node('a'), [])
        self.assertCountEqual(g.hops_from_node(PrefixedNode(
            2, 'a')), [Hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b'), 1.0)])
        self.assertCountEqual(g.hops_from_node(PrefixedNode(1, 'a')), [])

        # .hops_to_node()
        self.assertCountEqual(g.hops_to_node('b'), [])
        self.assertCountEqual(g.hops_to_node(PrefixedNode(
            2, 'b')), [Hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b'), 1.0)])
        self.assertCountEqual(g.hops_to_node(PrefixedNode(1, 'b')), [])

        # .find_hop()
        self.assertIsNone(g.find_hop('a', 'b'))
        self.assertEqual(
            g.find_hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b')),
            Hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'b'), 1.0))
        self.assertEqual(
            g.find_hop(PrefixedNode(1, 'a'), PrefixedNode(2, 'b')), None)
        self.assertEqual(
            g.find_hop(PrefixedNode(2, 'a'), PrefixedNode(1, 'b')), None)

        # .degree_out() and .degree_in()
        self.assertEqual(g.degree_out('a'), 0)
        self.assertEqual(g.degree_out(PrefixedNode(1, 'a')), 0)
        self.assertEqual(g.degree_out(PrefixedNode(2, 'a')), 1)
        self.assertEqual(g.degree_in('b'), 0)
        self.assertEqual(g.degree_in(PrefixedNode(1, 'b')), 0)
        self.assertEqual(g.degree_in(PrefixedNode(2, 'b')), 1)

        # .successors_of() and .predecessors_of()
        self.assertCountEqual(g.successors_of('a'), [])
        self.assertCountEqual(g.successors_of(PrefixedNode(1, 'a')), [])
        self.assertCountEqual(g.successors_of(PrefixedNode(2, 'a')),
                              [PrefixedNode(2, 'b')])
        self.assertCountEqual(g.predecessors_of(PrefixedNode(2, 'b')),
                              [PrefixedNode(2, 'a')])

        # .hop_weight()
        self.assertEqual(
            g.hop_weight(PrefixedNode(2, 'a'), PrefixedNode(2, 'b')), 1.0)
        self.assertEqual(
            g.hop_weight(PrefixedNode(1, 'a'), PrefixedNode(2, 'b')), 0.0)
        self.assertEqual(
            g.hop_weight(PrefixedNode(2, 'a'), PrefixedNode(1, 'b')), 0.0)

        # .add_edges()

        g2 = g.add_edges(
            EnumEdges(
                Hops.from_pairs((PrefixedNode(2, 'a'), PrefixedNode(2, 'o')))))
        self.assertEqual(
            g2.find_hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'o')),
            Hop(PrefixedNode(2, 'a'), PrefixedNode(2, 'o'), 1.0))
        self.assertEqual(g2.find_hop('a', 'o'), None)
Пример #24
0
 def empty(cls, propagator: Propagator=default_tyrrell_propagator) \
 -> 'Slipnet':
     return Slipnet(Graph.empty(), propagator)
Пример #25
0
def Boruvka_seq(g):
    lista_nodi = g.vertices()
    peso_albero = 0
    mst = Graph()
    for node in g.vertices():
        mst.insert_vertex(node.element())

    parent = [-1] * g.vertex_count()

    tempo_ricerca = 0
    tempo_pointer = 0
    tempo_merge = 0

    while len(lista_nodi) > 1:

        tempo_ricerca_parziale = time()
        for node in lista_nodi:
            minedge = None
            for edge in node.incident_edges():

                if minedge == None or minedge.element() > edge.element():
                    minedge = edge
                    n1, n2 = edge.endpoints()
                    if n1 == node.element():
                        parent[node.element()] = n2
                    else:
                        parent[node.element()] = n1

            if minedge is not None:
                n1, n2 = minedge.endpoints_posizione()
                e = mst.insert_edge(mst.vertices()[n1],
                                    mst.vertices()[n2], minedge.element())
                if e is not None:
                    peso_albero += minedge.element()
                    #print(e,flush=True)
        tempo_ricerca += (time() - tempo_ricerca_parziale)

        for node in lista_nodi:
            node_parent = parent[node.element()]
            parent_parent = parent[parent[node.element()]]

            if node.element() == parent_parent:

                if node.element() < node_parent:
                    parent[node.element()] = node.element()

                else:
                    parent[node_parent] = node_parent

        tempo_pointer_parziale = time()
        findRoot(parent)
        tempo_pointer += (time() - tempo_pointer_parziale)

        for nodo in lista_nodi:
            nodo.root = g.vertices()[parent[nodo.element()]]
            nodo.setElement(nodo.root.element())
            for edge in nodo.incident_edges():
                n1, n2 = edge.endpoints()
                edge.setElement(parent[n1], parent[n2])

        i = 0
        tempo_merge_parziale = time()
        while i < len(lista_nodi):
            node = lista_nodi[i]
            if node.root != node:
                merge(node, node.root)
                lista_nodi.pop(i)
            else:
                i = i + 1
        delete_multi_edges(lista_nodi)
        tempo_merge += (time() - tempo_merge_parziale)
    print(
        "TEMPO RICERCA ARCHI MINIMI :{}, TEMPO POINTER JUMPING:{}, TEMPO MERGE:{}"
        .format(tempo_ricerca, tempo_pointer, tempo_merge))

    return (mst, peso_albero)