def test_get_edges(self): graph = Graph() # Create test Verticies v1,v2,v3 = Vertex("a"), Vertex("b"), Vertex("c") # Add verticies graph.add_vertex(v1) graph.add_vertex(v2) graph.add_vertex(v3) self.assertEqual(graph.num_verticies, 3) self.assertEqual(graph.num_edges, 0) # Create edges edges = [ ("a", "b", 10), ("b", "c", 10), ("c", "a", 4) ] # Iterate through edges for edge in edges: fromVert, toVert, weight = edge graph.add_edge(fromVert, toVert, weight) self.assertEqual(graph.num_edges, 3)
def test_add_neighbor(self): v1 = "a" vertex = Vertex(v1) vertex.add_neighbor("b", 0) self.assertTrue(any(vertex.neighbors)) self.assertDictEqual(vertex.neighbors, {"b":0})
def add_edge(self, from_vertex_id, to_vertex_id, weight=None): if from_vertex_id not in self.vertices: self.vertices[from_vertex_id] = Vertex(from_vertex_id) self.no_of_vertices += 1 if to_vertex_id not in self.vertices: self.vertices[to_vertex_id] = Vertex(to_vertex_id) self.no_of_vertices += 1 self.vertices[from_vertex_id].add_nbr(to_vertex_id, weight) if self.is_undirected: self.vertices[to_vertex_id].add_nbr(from_vertex_id, weight)
def text_get_verticies(self): graph = Graph() # Create test Verticies v1,v2,v3 = Vertex("a"), Vertex("b"), Vertex("c") # Add verticies graph.add_vertex(v1) graph.add_vertex(v2) graph.add_vertex(v3) self.assertListEqual(graph.get_vertices, ["a","b","c"])
def test_init(self): # Tests the initialization of the Vertex class v1 = "a" vertex = Vertex(v1) self.assertEqual(vertex.id, "a") self.assertDictEqual(vertex.neighbors, {})
def create_er_graph(self, number_of_vertices, probability, seed, thread=None, **kwargs): """ Commented lines of code serve debugging purposes. """ self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" random.seed(seed) number_of_edges = [0] * number_of_vertices for i in range(number_of_vertices): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) self.graph.add_vertex(Vertex(i)) for new_node in range(number_of_vertices): for adjacency_vertex in range(number_of_vertices): per = random.uniform(0, 1) if new_node == adjacency_vertex or adjacency_vertex >= number_of_vertices: pass elif probability >= per: if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) if not self.graph.isAdjacent(new_node, adjacency_vertex): self.graph.add_edge_undirected(new_node, adjacency_vertex) number_of_edges[new_node] += 1 number_of_edges[adjacency_vertex] += 1 # print(f"""Connected node {new_node} ({number_of_edges[new_node]}) edges with """ # f"""node {adjacency_vertex} ({number_of_edges[adjacency_vertex]}) # edges with probability {probability} > {per}""") # print() # self.graph.get_number_of_edges() generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices, None, None, None, None, probability, seed)
def add_vertex(self, key): """ Add a new vertex object to the graph with the given key and return the vertex. """ self.num_verticies += 1 new_vertex = Vertex(key) self.vert_dict[key] = new_vertex return new_vertex
def read_graph_file(filename: str) -> (Graph, [Vertex], [tuple]): """ Read a graph file from the class specified format. Args: * filename - Read in the file specified by filename Returns: A tuple that contains a graph object and two lists """ graph = Graph() verts = [] edges = [] is_weighted = None # Open up the file and parse the graph from text with open(filename, "r") as file: counter = 0 # Iterate through the file for line in file: # Obtain the type of graph if counter == 0: graph_type = line.strip() if graph_type == "G": graph = Graph() elif graph_type == "D": graph = Digraph() else: raise ValueError("Graph type not properly specified") # Obtain the verticies for the graph. elif counter == 1: for key in line.strip().split(","): verts.append(Vertex(key)) # Obtain all the edges. elif counter > 1: edge = line.strip("()\n").split(",") if is_weighted is None: is_weighted = bool(len(edge) == 3) elif is_weighted and len(edge) < 3: raise ValueError( "You specified an edge with weights and one without. You should only do one or the other." ) if len(edge) != 3 and len(edge) != 2: raise ValueError( f"You specified an incorrect amount of args for the edge: {line}" ) edges.append(edge) counter += 1 return graph, verts, edges
def test_add_vertex(self): graph = Graph() # Creates test Verticies v1,v2,v3 = Vertex("a"), Vertex("b"), Vertex("c") # Add vertex "a" graph.add_vertex(v1) self.assertEqual(graph.num_verticies, 1) self.assertEqual(graph.num_edges, 0) # Add vertex "b" graph.add_vertex(v2) self.assertEqual(graph.num_verticies, 2) self.assertEqual(graph.num_edges, 0) # Add vertex "c" graph.add_vertex(v3) self.assertEqual(graph.num_verticies, 3) self.assertEqual(graph.num_edges, 0)
def traverse_npm_folder(root_path): seen_verts = set() edges = [] real_root = root_path.split("/")[-1] vertices = {real_root: Vertex(real_root)} for dir_name, subdir_list, _ in os.walk("./" + root_path + "/node_modules"): pkg, node_module = dir_name.split("/")[-2], dir_name.split("/")[-1] for subdir in subdir_list: if node_module == "node_modules" and subdir != ".bin": vertices[subdir] = Vertex(subdir) short_dir_name = os.path.basename(pkg) if short_dir_name == "": short_dir_name = real_root if short_dir_name in vertices and short_dir_name != subdir: edges.append((subdir, short_dir_name, 1)) return vertices.values(), edges
def add_vertex(self, key): """add a new vertex object to the graph with the given key and return the vertex """ # increment the number of vertices self.num_verticies += 1 # create a new vertex new_vertex = Vertex(key) # add the new vertex to the vertex list self.vert_dict[key] = new_vertex # return the new vertex return new_vertex
def add_vertex(self, vertex_id=None, vertex=None): if vertex is not None: vid = vertex.get_id() if vid in self.vertices: # be careful of any existing nbrs of this vertex (incoming edges) self.vertices[vid] = vertex return else: self.vertices[vid] = vertex self.no_of_vertices += 1 return if vertex_id not in self.vertices: if vertex_id not in self.vertices: self.vertices[vertex_id] = Vertex(vertex_id) self.no_of_vertices += 1 return
def create_homogeneous_graph(self, number_of_vertices, thread=None, **kwargs): self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" for i in range(number_of_vertices): self.graph.add_vertex(Vertex(str(i))) if thread and thread.isStopped(): sys.exit(0) for i in range(number_of_vertices): for j in range(number_of_vertices): if i != j and i < j: self.graph.add_edge_undirected(i, j) if thread and thread.isStopped(): sys.exit(0) generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices)
def create_custom_er_graph(self, number_of_vertices, number_of_edges, probability, seed, thread=None, **kwargs): """ Commented lines of code serve debugging purposes. """ self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" random.seed(seed) node_edges = [0] * number_of_vertices number_of_connected_edges = 0 for i in range(number_of_vertices): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) self.graph.add_vertex(Vertex(i)) graph_vector = self.graph.edge_indices.copy() while number_of_connected_edges < number_of_edges: new_node = int(random.choice(list(graph_vector.keys()))) adjacency_vertex = int(random.choice(list(graph_vector.keys()))) per = random.uniform(0, 1) while new_node == adjacency_vertex or self.graph.isAdjacent( new_node, adjacency_vertex): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) if len(graph_vector) > 1: counter = 0 for w, l in graph_vector.items(): if self.graph.isAdjacent(new_node, w) and new_node != w: counter += 1 if counter == len(graph_vector) - 1: break adjacency_vertex = int(random.choice(list( graph_vector.keys()))) per = random.uniform(0, 1) if probability > per: if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) self.graph.add_edge_undirected(new_node, adjacency_vertex) node_edges[new_node] += 1 node_edges[adjacency_vertex] += 1 number_of_connected_edges += 1 # print(f"""Connected node {new_node} ({node_edges[new_node]}) edges with """ # f"""node {adjacency_vertex} ({node_edges[adjacency_vertex]}) edges with probability # {probability} > {per}""") # print(f"Number of connected edges {number_of_connected_edges}") if node_edges[new_node] >= number_of_vertices - 1: try: del graph_vector[str(new_node)] # print(f"Removed node {new_node} from play.") # print(graph_vector) except KeyError: pass elif node_edges[adjacency_vertex] >= number_of_vertices - 1: try: del graph_vector[str(adjacency_vertex)] # print(f"Removed node {adjacency_vertex} from play.") # print(graph_vector) except KeyError: pass elif len(graph_vector) == 1: last_node = random.choice(list(graph_vector.keys())) del graph_vector[last_node] # print(f"Removed node {adjacency_vertex} from play.") # print(graph_vector) # print("Terminating...") break # print() # self.graph.get_number_of_edges() generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices, None, number_of_edges, None, None, probability, seed)
def create_random_fixed_graph(self, number_of_vertices, graph_degree, seed, thread=None, **kwargs): """ Commented lines of code serve debugging purposes. """ self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" random.seed(seed) number_of_edges = [0] * number_of_vertices for i in range(number_of_vertices): if thread and thread.isStopped(): sys.exit(0) self.graph.add_vertex(Vertex(i)) graph_vector = self.graph.edge_indices.copy() for v, i in self.graph.edge_indices.items(): if v in graph_vector: # print(f"Connecting node {int(v)} with others...") while number_of_edges[int(v)] < graph_degree and len( graph_vector) != 0: if thread and thread.isStopped(): sys.exit(0) random_node = random.choice(list(graph_vector.keys())) if random_node == v and len(graph_vector) != 1: while random_node == v: random_node = random.choice( list(graph_vector.keys())) if number_of_edges[int(random_node)] >= graph_degree: del graph_vector[random_node] # print(f"Removed node {int(random_node)} from play.") # print(graph_vector) if number_of_edges[int(v)] >= graph_degree: try: del graph_vector[v] # print(f"Removed node {int(v) + 1} from play.") # print(graph_vector) except KeyError: pass if number_of_edges[int(random_node)] < graph_degree and v != random_node \ and not self.graph.isAdjacent(v, random_node): self.graph.add_edge_undirected(v, random_node) number_of_edges[int(v)] += 1 number_of_edges[int(random_node)] += 1 # print(f"""Connected node {int(v)} ({number_of_edges[int(v)]}) """ # f"""edges with node {int(random_node)} ({number_of_edges[int(random_node)]}) edges.""") if number_of_edges[int(v)] >= graph_degree: try: del graph_vector[v] # print(f"Removed node {int(v)} from play.") # print(graph_vector) except KeyError: pass if number_of_edges[int(random_node)] >= graph_degree: del graph_vector[random_node] # print(f"Removed node {int(random_node)} from play.") # print(graph_vector) elif len(graph_vector) == 1: break elif len(graph_vector) > 1: counter = 0 for w, l in graph_vector.items(): if self.graph.isAdjacent(v, w) and v != w: counter += 1 if counter == len(graph_vector) - 1: break elif not self.graph.isAdjacent(v, random_node) and len( graph_vector) == 2 and v != random_node: self.graph.add_edge_directed(v, random_node) number_of_edges[int(v)] += 1 number_of_edges[int(random_node)] += 1 # print(f"""Connected node {int(v)} ({number_of_edges[int(v)]}) edges with """ # f"""node {int(random_node)} ({number_of_edges[int(random_node)]}) edges.""") # print() # self.graph.get_number_of_edges() generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices, graph_degree, None, None, None, None, seed)
def add_edge(self, from_key, to_key, weight=0): if from_key not in self.vertices: self.add_vertex(Vertex(from_key)) if to_key not in self.vertices: self.add_vertex(Vertex(to_key)) self.vertices[from_key].add_neighbor(self.vertices[to_key], weight)
def create_scale_free_graph(self, number_of_vertices, seed, thread=None, **kwargs): """ Commented lines of code serve debugging purposes. """ self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" number_of_edges = [0] * number_of_vertices number_of_connected_edges = 0 random.seed(seed) # Generate the tank with all nodes and a support graph vector. for i in range(number_of_vertices): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) self.graph.add_vertex(Vertex(i)) graph_vector = self.graph.edge_indices.copy() # ====================================== # Make a random initial connection. random_node1 = random.choice(list( self.graph.edge_indices.keys())) # random_node1 --> str random_node2 = random.choice(list( self.graph.edge_indices.keys())) # random_node2 --> str while random_node1 == random_node2: random_node2 = random.choice(list( self.graph.edge_indices.keys())) # random_node2 --> str self.graph.add_edge_undirected(random_node1, random_node2) number_of_edges[int(random_node1)] += 1 number_of_edges[int(random_node2)] += 1 number_of_connected_edges += 1 del graph_vector[random_node1] del graph_vector[random_node2] # print("Initial connection: ") # print(f"""Connected node {int(random_node1) + 1} ({number_of_edges[int(random_node1)]}) edges with """ # f"""node {int(random_node2) + 1} ({number_of_edges[int(random_node2)]}) edges.\n""") # ====================================== # Connected the rest of the nodes with all other with specified probability. while len(graph_vector) != 0: if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) random_node3 = random.choice(list(graph_vector.keys())) # print(f"Connecting node {int(random_node3) + 1} with others...") for j in range(number_of_vertices): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) if int(random_node3) != j and number_of_edges[j] != 0: probability = number_of_edges[j] / number_of_connected_edges probability_random = random.uniform(0, 1) if probability > probability_random: self.graph.add_edge_undirected(int(random_node3), j) number_of_edges[int(random_node3)] += 1 number_of_edges[j] += 1 number_of_connected_edges += 1 # print(f"""Connected node {int(random_node3) + 1} ({number_of_edges[int(random_node3)]}) """ # f"""edges with node {j + 1} ({number_of_edges[j]}) edges with probability {probability}""") # print() del graph_vector[random_node3] # ====================================== # self.graph.get_number_of_edges() generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices, None, None, None, None, None, seed)
def create_full_scale_free_graph(self, number_of_vertices, number_of_initial_nodes, seed, thread=None, initial_connections_per_node=None, **kwargs): """ Commented lines of code serve debugging purposes. """ self.graph.reset_graph() if self.graph.graph_representation_type == "matrix": if kwargs.get('rle'): self.graph.mode = "memory efficient" number_of_edges = [0] * number_of_vertices number_of_connected_edges = 0 random.seed(seed) graph_vector = {} # In case there is only one initial node. if number_of_initial_nodes == 1: number_of_connected_edges += 1 # Generating tank with all nodes inside. for i in range(number_of_vertices): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) graph_vector[str(i)] = i # Adding random mo initial nodes to the graph. # print("Initial nodes:") for i in range(number_of_initial_nodes): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) random_node = random.choice(list(graph_vector.keys())) self.graph.add_vertex(Vertex(random_node)) del graph_vector[random_node] # print(int(random_node) + 1) # Connecting all mo (initial nodes). if number_of_initial_nodes == 1: # If number of initial node is one give the node a starting edge. for v, i in list(self.graph.edge_indices.items()): number_of_edges[int(v)] += 1 for v, i in list(self.graph.edge_indices.items()): for b, j in list(self.graph.edge_indices.items()): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) # If Custom Full Scale-Free Graph is chosen. if initial_connections_per_node is not None and number_of_connected_edges >= initial_connections_per_node: break if v != b and v < b: self.graph.add_edge_undirected(v, b) number_of_edges[int(v)] += 1 number_of_edges[int(b)] += 1 number_of_connected_edges += 1 # If Custom Full Scale-Free Graph is chosen. if initial_connections_per_node is not None and number_of_connected_edges >= initial_connections_per_node: break # print(f"""Connected node {int(v) + 1} ({number_of_edges[int(v)]}) edges with """ # f"""node {int(b) + 1} ({number_of_edges[int(b)]}) edges with probability 1.0""") # print("Finished initial nodes.") # ====================================== # Go for the rest nodes. while len(graph_vector) != 0: random_node = random.choice(list(graph_vector.keys())) # random_node --> str self.graph.add_vertex(Vertex(random_node)) del graph_vector[random_node] for v, i in list(self.graph.edge_indices.items()): if thread and thread.isStopped(): # --> Thread Status. sys.exit(0) if v != random_node: probability = number_of_edges[int(v)] / number_of_connected_edges probability_random = random.uniform(0, 1) if probability > probability_random: self.graph.add_edge_undirected(random_node, v) number_of_edges[int(random_node)] += 1 number_of_edges[int(v)] += 1 number_of_connected_edges += 1 # print(f"""Connected node {int(random_node) + 1} ({number_of_edges[int(random_node)]}) """ # f"""edges with node {int(v) + 1} ({number_of_edges[int(v)]}) edges with probability """ # f"""{probability}""") graph_vector.clear() # Sort randomized graph order. # Method 1 self.graph.edge_indices = {int(c): v for c, v in self.graph.edge_indices.items()} self.graph.edge_indices = OrderedDict(sorted(self.graph.edge_indices.items())) self.graph.edge_indices = {str(c): v for c, v in self.graph.edge_indices.items()} # self.graph.get_number_of_edges() generator.generate(self.graph.graph_representation_type, self.graph, thread) analyzer.analyze_generated_graph(self.graph.edges, self.graph.graph_representation_type, self.graph.graph_type, number_of_vertices, None, None, initial_connections_per_node, None, None, seed)