Example #1
0
    def __init__(self, graph, world):
        self._batch = pyglet.graphics.Batch()
        self._node_shapes = [[None] * world.grid_width
                             for y in range(world.grid_height)]
        self._conn_shapes = []

        cell = world.cell
        half_cell = world.cell / 2
        color = ('c4B', (150, 150, 150, 100))

        # create nodes
        for node in graph.get_nodes():
            x, y = node
            shape = shapes.Circle(4,
                                  cell * x + half_cell,
                                  cell * y + half_cell,
                                  color=color)
            shape.add_to_batch(self._batch)
            self._node_shapes[y][x] = shape

        # create connections
        for node in graph.get_nodes():
            x1, y1 = node
            for dest in graph.get_connections(node):
                x2, y2 = dest[0]
                shape = shapes.Line(cell * x1 + half_cell,
                                    cell * y1 + half_cell,
                                    cell * x2 + half_cell,
                                    cell * y2 + half_cell,
                                    color=color)
                shape.add_to_batch(self._batch)
                self._conn_shapes.append(shape)
Example #2
0
def connected_components(graph):
	"""
	Connected components.

	@attention: Indentification of connected components is meaningful only for non-directed graphs.

	@type  graph: graph
	@param graph: Graph.

	@rtype:  list
	@return: List that associates each node to its connected component.
	"""
	visited = []
	count = 1

	# Initialization
	for each in graph.get_nodes():
		visited.append(0)

	# For 'each' node not found to belong to a connected component, find its connected component.
	for each in graph.get_nodes():
		if (not visited[each]):
			_dfs(graph, visited, count, each)
			count = count + 1
	
	return visited
Example #3
0
def process_reentrancy(graph):
	for node_var in graph.get_nodes():
		if re.match("^[a-z][^ ]*$", node_var): # is variable 
			for node in graph.get_nodes():
				if re.match( "^{} / .*".format(node_var), node):
					graph.remove_node(node_var)
					graph.update_destination(node_var, node)
Example #4
0
def depth_first_search(graph):
	"""
	Depth-first search.

	@type  graph: graph
	@param graph: Graph.

	@rtype:  tuple
	@return: A tupple containing tree lists:
		1. Generated spanning tree
		2. Graph's preordering
		3. Graph's postordering
	"""
	visited = []			# List for marking visited and non-visited nodes
	spanning_tree = []		# Spanning tree
	pre = []				# Graph's preordering
	post = []				# Graph's postordering

	# Initialization
	for each in graph.get_nodes():
		visited.append(0)
		spanning_tree.append(-1)
	
	# Algorithm loop
	for each in graph.get_nodes():
		if (not visited[each]):							# Select a non-visited node
			_dfs(graph, visited, spanning_tree, pre, post, each)	# Explore node's connected component

	return spanning_tree, pre, post
Example #5
0
def breadth_first_search(graph):
	"""
	Breadth-first search.

	@type  graph: graph
	@param graph: Graph.

	@rtype:  list
	@return: Generated spanning_tree
	"""
	queue = []			# Visiting queue
	spanning_tree = []	# Spanning tree

	# Initialization
	for each in graph.get_nodes():
		spanning_tree.append(-2)	# -2 in spanning_tree means a non-visited node

	# Algorithm
	for each in graph.get_nodes():
		if (spanning_tree[each] == -2):
			queue.append(each)
			spanning_tree[each] = -1	# -1 means that the node is the root of a tree

			while (queue != []):
				node = queue.pop(0)

				for other in graph.get_node(node):
					if (spanning_tree[other] == -2):
						queue.append(other)
						spanning_tree[other] = node

	return spanning_tree
Example #6
0
def accessibility(graph):
	"""
	Accessibility matrix (transitive closure).

	@type  graph: graph
	@param graph: Graph.

	@rtype:  list
	@return: Accessibility matrix
	"""
	accessibility = []	# Accessibility matrix

	# For each node i, mark each node j so that exists a path from i to j.
	for i in graph.get_nodes():
		access = []
		for j in graph.get_nodes():
			access.append(0)
		_dfs(graph, access, 1, i)	# Perform DFS to explore all reachable nodes
		accessibility.append(access)
	return accessibility
def test_graph():
    # check for successful input
    graph = Graph()
    a = graph.add_node('a')
    assert a.value == 'a'
    b = graph.add_node('b')
    c = graph.add_node('c')
    d = graph.add_node('d')
    e = graph.add_node('e')
    f = graph.add_node('f')
    # check the get_nodes function
    assert graph.get_nodes()[0].value == 'a'
    assert graph.get_nodes()[1].value == 'b'
    assert graph.get_nodes()[5].value == 'f'
    # check if the add_edges and get_neighbors are working properly
    graph.add_edge(a, c)
    graph.add_edge(a, d)
    graph.add_edge(b, c)
    graph.add_edge(b, f)
    graph.add_edge(c, a)
    graph.add_edge(c, b)
    graph.add_edge(c, e)
    graph.add_edge(d, a)
    graph.add_edge(d, e)
    graph.add_edge(e, c)
    graph.add_edge(e, d)
    graph.add_edge(e, f)
    graph.add_edge(f, b)
    graph.add_edge(f, e)
    assert graph.get_neighbors(a)[0].node.value == 'c'
    assert graph.get_neighbors(a)[1].node.value == 'd'
    # testing the size method
    assert graph.size()==6
    # check for empty graph
    graph2 = Graph()
    assert graph2.get_nodes() == None
Example #8
0
# G = nx.gnp_random_graph(100,0.5)
# cc = calculate_local_clustering_coefficients(network)
# cc_list=list(cc.values())
# cc[] = cc
# cc = sorted(cc)
#graph2 = graph.__init__("csv/amazon.csv")

# get_data_frame("p2network")

# graph = graph.Graph("p2network")
# graph = graph.Graph("p2networktestneg")
# graph = graph.Graph("p2networktrain")
graph = graph.Graph("facebook_train")
# graph = graph.Graph("csv/graph.txt")

print(graph.get_nodes())
# print(graph.neighbor_of_node(1))

analyzer = GraphAnalyzer(graph)
save_dir = "csv"

k = 1
plt.rcParams["figure.figsize"] = (11, 7)
nx_graph = nx.Graph()
# own_graph = graph.Graph("csv/amazon.txt")
# own_graph = graph.Graph("csv/amazon")
# print(own_graph.get_vertices())
# own_graph = graph.Graph(sys.argv[1])
degrees = graph.get_each_node_degree()
# print(own_graph.get_degrees())
hubs = []
Example #9
0
import graph
from collections import namedtuple
import re, sys

infile = sys.argv[1]
infile = open(infile, "r")

graph = graph.Graph()

for i, line in enumerate(infile):
    if i == 1:
        s = line.split(', ')
    if i > 2:
        nodes = graph.get_nodes()
        words = line.split()
        if words[0] not in graph.get_nodes():
            graph.add_node(words[0])
        elif words[1] not in graph.get_nodes():
            graph.add_node(words[1])
        graph.add_edge(int(words[0]), int(words[1]), int(words[2]))
print(graph.get_nodes())
graph.dijkstra(1, 10)
Example #10
0
from graph import Node, get_nodes, get_best_F

import time

start = time.time()

nodes = get_nodes()

meta = nodes[-1]
init_node = nodes[0]
solution_found = False

# print('init_node', init_node)
# print('meta', meta, '\n')

open_list = [nodes[0]]
close_list = []
nodes = Node.del_node(nodes[0], nodes)

for node in nodes:
    open_list.append(node)

start_g = 0.0
start_f = start_g + Node.distanceToCity(init_node, meta)  # g+h

while open_list != []:
    best_node = get_best_F(close_list, open_list)  # get node with best f(x)

    if best_node.get_id() == meta.get_id():
        solution_found = True
Example #11
0
                    help='\t\tOutput file for the solution.',
                    type=str,
                    required=True)
parser.add_argument('-t',
                    '--time',
                    help='\t\tTime to run the application.',
                    type=int,
                    required=True)
args = parser.parse_args()

start, time_to_complete = time.time(), args.time
file_in, file_out = args.input, args.output
graph = Graph()
graph.populate_from_file(file_in)

tour = graph.get_nodes()
tour.append(tour[0])

print(f'Distance of beginning tour: {calculate_tour_dist(graph, tour)}')

h_time = time_to_complete / 2
critical_time = 1.5
q_time = (h_time - critical_time)
stop_time = start + time_to_complete - critical_time
tour = tsp_simulated_annelling(graph, tour, 200, time.time() + h_time)
print(f'Distance of tour: {calculate_tour_dist(graph, tour)}')
gc.collect()

tour = tsp_2opt(graph, tour, time.time() + q_time)
print(f'Distance of tour: {calculate_tour_dist(graph, tour)}')
gc.collect()