def test_prim_mst_edges_specify_weight(self):
     G=nx.Graph()
     G.add_edge(1,2,weight=1,color='red',distance=7)
     G.add_edge(1,3,weight=30,color='blue',distance=1)
     G.add_edge(2,3,weight=1,color='green',distance=1)
     G.add_node(13,color='purple')
     G.graph['foo']='bar'
     T=nx.prim_mst(G)
     assert_equal(sorted(T.nodes()),[1,2,3,13])
     assert_equal(sorted(T.edges()),[(1,2),(2,3)])
     T=nx.prim_mst(G,weight='distance')
     assert_equal(sorted(T.edges()),[(1,3),(2,3)])
     assert_equal(sorted(T.nodes()),[1,2,3,13])
Beispiel #2
0
 def test_prim_mst_edges_specify_weight(self):
     G = nx.Graph()
     G.add_edge(1, 2, weight=1, color='red', distance=7)
     G.add_edge(1, 3, weight=30, color='blue', distance=1)
     G.add_edge(2, 3, weight=1, color='green', distance=1)
     G.add_node(13, color='purple')
     G.graph['foo'] = 'bar'
     T = nx.prim_mst(G)
     assert_equal(sorted(T.nodes()), [1, 2, 3, 13])
     assert_equal(sorted(T.edges()), [(1, 2), (2, 3)])
     T = nx.prim_mst(G, weight='distance')
     assert_equal(sorted(T.edges()), [(1, 3), (2, 3)])
     assert_equal(sorted(T.nodes()), [1, 2, 3, 13])
 def test_prim_mst_disconnected(self):
     G=nx.Graph()
     G.add_path([1,2])
     G.add_path([10,20])
     T=nx.prim_mst(G)
     assert_equal(sorted(T.edges()),[(1, 2), (20, 10)])
     assert_equal(sorted(T.nodes()),[1, 2, 10, 20])
Beispiel #4
0
 def test_prim_mst_disconnected(self):
     G = nx.Graph()
     G.add_path([1, 2])
     G.add_path([10, 20])
     T = nx.prim_mst(G)
     assert_equal(sorted(T.edges()), [(1, 2), (20, 10)])
     assert_equal(sorted(T.nodes()), [1, 2, 10, 20])
 def test_prim_mst_attributes(self):
     G=nx.Graph()
     G.add_edge(1,2,weight=1,color='red',distance=7)
     G.add_edge(2,3,weight=1,color='green',distance=2)
     G.add_edge(1,3,weight=10,color='blue',distance=1)
     G.add_node(13,color='purple')
     G.graph['foo']='bar'
     T=nx.prim_mst(G)
     assert_equal(T.graph,G.graph)
     assert_equal(T.node[13],G.node[13])
     assert_equal(T.edge[1][2],G.edge[1][2])
Beispiel #6
0
 def test_prim_mst_attributes(self):
     G = nx.Graph()
     G.add_edge(1, 2, weight=1, color='red', distance=7)
     G.add_edge(2, 3, weight=1, color='green', distance=2)
     G.add_edge(1, 3, weight=10, color='blue', distance=1)
     G.add_node(13, color='purple')
     G.graph['foo'] = 'bar'
     T = nx.prim_mst(G)
     assert_equal(T.graph, G.graph)
     assert_equal(T.node[13], G.node[13])
     assert_equal(T.edge[1][2], G.edge[1][2])
 def test_prim_mst(self):
     T=nx.prim_mst(self.G)
     assert_equal(T.edges(data=True),self.tree_edgelist)
 def test_prim_mst_isolate(self):
     G=nx.Graph()
     G.add_nodes_from([1,2])
     T=nx.prim_mst(G)
     assert_equal(sorted(T.nodes()),[1, 2])
     assert_equal(sorted(T.edges()),[])
Beispiel #9
0
 def extract_mst(self, algorithm):
     if algorithm is TSP.MST.PRIM:
         return self._extract_prim_mst()
     elif algorithm is TSP.MST.NETWORKX:
         return nx.prim_mst(self.graph)
def run():
    t0 = time.time()
    numsolved = 0
    nodeslist = []
    distlist = []
    timelist = []
    while ((time.time() - t0) < 600):
        t0 = time.time()
        for i in range(100):  #CHANGE TO 100
            temptime = time.time()
            fileobj = open('test' + str(i) + '.txt',
                           'r')  #CHANGE TEST0 TO A VAR, SO IT CYCLES ALL FILES
            if ((time.time() - t0) > 600):
                break
            #fileobj=open('test78.txt','r')
            numcities = fileobj.readline()
            cities = []
            closed = []
            notclosed = []
            dist = 0
            nodes = 0

            #this reads the files, turns all the cities into nodes, and puts them in the notclosed list
            for d in range(int(float(numcities))):
                tmp = fileobj.readline()
                firstspace = tmp.index(" ")
                secondspace = tmp.index(' ', firstspace + 1)
                cities.append((tmp[firstspace + 1:secondspace],
                               tmp[secondspace + 1:len(tmp) - 1]))
                tmpNode = Node()
                tmpNode.x = float(tmp[firstspace + 1:secondspace])
                tmpNode.y = float(tmp[secondspace + 1:len(tmp) - 1])
                tmpNode.num = float(tmp[:firstspace])
                nodes += 1
                notclosed.append(tmpNode)

            closed.append(notclosed[0])
            notclosed.remove(closed[0])
            start = closed[0]
            curr = start
            tmpcity = closed[0]
            distances = []
            if ((time.time() - t0) > 600):
                break
            while (notclosed and (time.time() - t0 < 600)):
                #while(notclosed):
                maxdist = 999999
                maxnode = None
                for a in notclosed:  #iterates through all the nodes, to see which one to add next

                    graph = nx.Graph()
                    hn = 0
                    hn = dist + hn + findDistance(a, curr)
                    for g in range(len(notclosed)):
                        if (notclosed[g] != a):
                            distances.append(findDistance(a, notclosed[g]))
                        for e in range(len(notclosed) + 1):
                            if (g != len(notclosed)):
                                if (e == len(notclosed)):
                                    if (notclosed[g].x != a.x
                                            and notclosed[g].y != a.y):
                                        dist1 = findDistance(
                                            notclosed[g], start)
                                        graph.add_edge(g, 'c', weight=dist1)
                                        nodes += 1
                                    if ((time.time() - t0) > 600):
                                        break
                                else:
                                    if ((notclosed[g].x != a.x
                                         and notclosed[g].y != a.y)
                                            and (notclosed[e].x != a.x
                                                 and notclosed[e].y != a.y)):
                                        dist1 = findDistance(
                                            notclosed[g], notclosed[e])
                                        graph.add_edge(g, e, weight=dist1)
                                        nodes += 1
                                    if ((time.time() - t0) > 600):
                                        break
                    adddist = 0
                    for c in notclosed:
                        if (a != c):
                            adddist += findDistance(c, start)
                    hn += adddist
                    mst = nx.prim_mst(graph)  #changed tree to edges
                    for node in mst.edges(data=True):
                        hn += node[2][
                            'weight']  #adds up the distances from the mst
                    hn += findDistance(a, start) + min(
                        distances
                    )  #adds the distance from the a node to start node
                    if (hn < maxdist):
                        maxdist = hn
                        maxnode = a
                    if ((time.time() - t0) > 600):
                        break
                closed.append(maxnode)
                notclosed.remove(maxnode)
                dist += findDistance(maxnode, curr)
                curr = maxnode
            distlist.append(dist)
            nodeslist.append(nodes)
            print(time.time() - temptime)
            print("iter: " + str(i) + " dist: " + str(dist))
            timelist.append(time.time() - temptime)
            numsolved += 1

    print(time.time() - t0)
    print(numsolved)
    print(dist)
    counter1 = 0
    counter2 = 0
    counter3 = 0
    counter4 = 0
    nodesavg1 = 0
    nodesavg2 = 0
    nodesavg3 = 0
    nodesavg4 = 0
    timeavg1 = 0
    timeavg2 = 0
    timeavg3 = 0
    timeavg4 = 0
    distavg1 = 0
    distavg2 = 0
    distavg3 = 0
    distavg4 = 0

    for i in range(numsolved):
        if (i < 25):
            nodesavg1 += nodeslist[i]
            timeavg1 += timelist[i]
            distavg1 += distlist[i]
            counter1 += 1
        elif (i < 50):
            nodesavg2 += nodeslist[i]
            timeavg2 += timelist[i]
            distavg2 += distlist[i]
            counter2 += 1
        elif (i < 75):
            nodesavg3 += nodeslist[i]
            timeavg3 += timelist[i]
            distavg3 += distlist[i]
            counter3 += 1
        else:
            nodesavg4 += nodeslist[i]
            timeavg4 += timelist[i]
            distavg4 += distlist[i]
            counter4 += 1

    print("avgnode1: " + str(nodesavg1 / counter1) + " avgtime1: " +
          str(timeavg1 / counter1) + " avgdist1: " + str(distavg1 / counter1))
    print("avgnode2: " + str(nodesavg2 / counter2) + " avgtime2: " +
          str(timeavg2 / counter2) + " avgdist2: " + str(distavg2 / counter2))
    print("avgnode3: " + str(nodesavg3 / counter3) + " avgtime3: " +
          str(timeavg3 / counter3) + " avgdist3: " + str(distavg3 / counter3))
    print("avgnode4: " + str(nodesavg4 / counter4) + " avgtime4: " +
          str(timeavg4 / counter4) + " avgdist4: " + str(distavg4 / counter4))
net.show()


net.algorithms = (MegaMerger,)
write_pickle(net, 'RandomSAlg.tar.gz')
#write_pickle(net, 'WorstCaseSAlg.tar.gz')
##s ovom mrezom pokretati GUI simulator

g = Graph()
g.adj=net.adj

#Uses Kruskal’s algorithm.
#If the graph edges do not have a weight attribute 
#a default weight of 1 will be used.
#test_graph = minimum_spanning_tree(net)
test_graph=prim_mst(net)
test_net.adj=test_graph.adj
test_net.show()
test_sum= test_net.size(weight='weight')


#sim = Simulation(net)
#sim.run()

exclude = list()
exclude.append('Neighbors')

print "banana"
print("banana")
for node in net.nodes():
Beispiel #12
0
 def test_prim_mst(self):
     T = nx.prim_mst(self.G)
     assert_equal(T.edges(data=True), self.tree_edgelist)
Beispiel #13
0
 def test_prim_mst_isolate(self):
     G = nx.Graph()
     G.add_nodes_from([1, 2])
     T = nx.prim_mst(G)
     assert_equal(sorted(T.nodes()), [1, 2])
     assert_equal(sorted(T.edges()), [])
Beispiel #14
0
		print "|Original Algorithm|"
		
		print "Nodes of MST is: ",mst.nodes()
		print "Edges of MST is: ",
		print_edges(mst)

		print "Total Cost is: ",total_cost
		print "Time Elapsed (in seconds): ", time_consumed
		print "Number of Iterations: ",qty_of_iterations
		print ""

		#run the networkx algorithm
		time_consumed = 0
		start_time = 0
		start_time = timeit.default_timer()
		T = nx.prim_mst(G)        
		time_consumed = timeit.default_timer() - start_time        
		
		print "|Networkx Algorithm|"

		print "Nodes of MST is: ",T.nodes()
		print "Edges of MST is: "
		print_edges(T)

		total_cost = 0
		for edge in T.edges(data='weight'):
			total_cost += getWeight(edge)

		print "Total Cost is: ",total_cost
		print "Time Elapsed (in seconds): ", time_consumed        
		print ""
Beispiel #15
0
def isum(wlist):
	ctr = 0
	for weight in wlist:
		ctr+= (0 if weight == sys.maxint else weight)
	return ctr
	
for line in fp:
	adj = map(convert, line.rstrip('\r\n').split(','))
	for j in range(nov):
		G.add_edge(i,j,weight=adj[j])
	i+=1

# total_weight = sum([weight for edge, weight, in nx.get_edge_attributes(G, 'weight')])

weight_list = (G[a][b]['weight'] for a,b in nx.get_edge_attributes(G, 'weight'))

total_weight = isum(weight_list)

print total_weight

T =nx.prim_mst(G)
new_weight_list = (T[a][b]['weight'] for a,b in nx.get_edge_attributes(T, 'weight')) 
new_weight = isum(new_weight_list)

print new_weight

print "Savings %ld" % (total_weight - new_weight)

#set root's key to zero
Beispiel #16
0
 def _generate_spanning_graph(self):
     return nx.prim_mst(self.complete_graph)
 def extract_mst(self, algorithm):
     if algorithm is MSTGrouping.MST.PRIM:
         return self._extract_prim_mst()
     elif algorithm is MSTGrouping.MST.NETWORKX:
         return nx.prim_mst(self.graph)
 def _generate_spanning_graph(self):
     return nx.prim_mst(self.complete_graph)
Beispiel #19
0
		src = random.choice(network.nodes())
		dst = random.choice(network.nodes())
	paths.append((src, dst))

for path in paths:
    src, dst = path
    print("\nSource: ", src, " Destination: ", dst)
    dijkstra_shortest_paths = nx.single_source_dijkstra_path(network.copy(), src, weight='distance')
    dijkstra_shortest_path = dijkstra_shortest_paths[dst]
    dsp_edges = list(zip(dijkstra_shortest_path[0:], dijkstra_shortest_path[1:]))
    print("\n\tDijkstra\n\t\tPath: ", dijkstra_shortest_path)
    dijkstra_throughput = select_channels(network, dsp_edges)
    print("\t\tThroughput = ", dijkstra_throughput)
    dijkstra_greedy_throughput = select_channels_greedy(network, dsp_edges)
    print("\t\tThroughput Greedy = ", dijkstra_greedy_throughput)
    prim_tree = nx.prim_mst(network, weight='bottleneck_weight')
    prim_path = nx.shortest_path(prim_tree, src, dst)
    prim_edges = list(zip(prim_path[0:], prim_path[1:]))
    print("\tPrim\n\t\tPath: ", prim_path)
    prim_throughput = select_channels(network, prim_edges)
    print("\t\tThroughput = ", prim_throughput)
    prim_greedy_throughput = select_channels_greedy(network, prim_edges)
    print("\t\tThroughput Greedy = ", prim_greedy_throughput)
    rcs_path = rcs_path(network, src, dst)
    print("\tRCS")
    if rcs_path is not None:
        print("\t\tPath: ", list(vertices_for_path(rcs_path.path)))
        rcs_throughput = select_channels(network, rcs_path.path)
        print("\t\tThroughput: ", rcs_throughput)
        rcs_greedy_throughput = select_channels_greedy(network, rcs_path.path)
        print("\t\tThroughput Greedy: ", rcs_greedy_throughput)