def load_graph(path, mode, directed): f = open(path, 'r+') for line in f.readlines(): vals = [int(val) for val in line.split(' ')] if len(vals) == 2: if mode == 'matrix': graph = Matrix(vals[1]) else: graph = ListGraph(vals[1]) else: if mode == 'matrix': graph.set(vals[0], vals[1], vals[2]) if directed and graph.get(vals[1], vals[0]) == 0: graph.set(vals[1], vals[0], -1) else: graph.set(vals[1], vals[0], vals[2]) else: graph.add_connection(vals[0], vals[1], vals[2]) if not directed: graph.add_connection(vals[1], vals[0], vals[2]) return graph
def generate_graph_nx( nodes: int, density, mode, directed, force=settings.force): # graph generation using networkx bar = ProgBar(20, title='Generating graph', stream=sys.stdout) if directed: # calculate edge count based on node count and density edges = nodes * (nodes - 1) * density if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(1 / nodes)), file=sys.stderr) edges = nodes - 1 else: edges = nodes * (nodes - 1) * density / 2 if edges < nodes - 1 and not force: print( "Minimum graph density for this problem is {:2.0%}. " "To generate less dense graph anyway, set argument force to True." .format(float(2 / nodes)), file=sys.stderr) edges = nodes - 1 bar.update() G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) # generate random graph bar.update() if not directed: # check connectivity and generate new graph if failed while not nx.is_connected(G): G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) else: cont = False while not cont: cont = True for node in G.nodes: if len([x for x in G.neighbors(node)]) == 0: cont = False G = nx.generators.random_graphs.gnm_random_graph( nodes, edges, directed=directed) break bar.update() if mode == 'matrix': # convert generated networkx graph to own structure ret = Matrix(nodes) for x, y in G.edges: w = randint(1, nodes) ret.set(x, y, w) if directed and ret.get(y, x) == 0: ret.set(y, x, 0) else: ret.set(y, x, w) bar.update() return ret else: ret = ListGraph(nodes) for x, y in G.edges: w = randint(1, nodes) ret.add_connection(x, y, w) if not directed: ret.add_connection(y, x, w) bar.update() return ret