def test_read_equals_from_bytes(self): data = b"DF{" G = nx.from_graph6_bytes(data) fh = BytesIO(data) Gin = nx.read_graph6(fh) assert nodes_equal(G.nodes(), Gin.nodes()) assert edges_equal(G.edges(), Gin.edges())
def test_read_equals_from_bytes(self): data = b'DF{' G = nx.from_graph6_bytes(data) fh = BytesIO(data) Gin = nx.read_graph6(fh) assert_nodes_equal(G.nodes(), Gin.nodes()) assert_edges_equal(G.edges(), Gin.edges())
def search_ground_truth(self, vertex_num, limit, graph_num): limit_list, limit_vec = self.process_limit(limit) # print(limit_list) # print(limit_vec) ready_graphs = [] stat_file_name = database_path + gt_common_prefix + str( vertex_num) + gt_stat_suffix graph_file_name = database_path + gt_common_prefix + str( vertex_num) + gt_graph_suffix with open(stat_file_name, "r") as stat_set, open(graph_file_name, "rb") as graph_set: datareader = csv.reader(stat_set) for graph_stat in datareader: graph = graph_set.readline() graph_stat = [float(i) for i in graph_stat] row = [graph_stat[i] for i in limit_list] save_graph = 1 for (stat, stat_range) in zip(row, limit_vec): if not (stat_range[0] <= stat <= stat_range[1]): save_graph = 0 if save_graph == 1: graph = nx.from_graph6_bytes(graph.rstrip()) ready_graphs.append(graph) if DEBUG: print(graph_stat) # nx.write_graphml(graph,"Gc_=_0.graphml") # nx.draw(graph) # plt.show() if len(ready_graphs) > graph_num: break return ready_graphs
def test(self: ExamplesCotreeAlgorithmsTests, line=line): graph: nx.Graph[Any] = nx.from_graph6_bytes( bytes(line.strip(), "utf-8")) cotree = cast(TreeNode[VT], cps.compute_cotree(graph)) self.assertIsNotNone(cotree) self.assertTrue(verify_algo_output(graph, algo(cotree)))
def plot_graph(self, graph): if graph is None: self.view_box.removeItem(self.graph) return g = nx.from_graph6_bytes(graph.encode('utf-8')) self.view_box.addItem(self.graph) self.define_graph(g)
def test_ten(self): fname = 'g/planar_conn.10.g6' if os.path.isfile(fname): expected = True with open(fname, 'rb') as f: for g in f.read().splitlines(): actual = is_planar(nx.from_graph6_bytes(g)) self.assertEqual(expected, actual)
def save_all_graphs(file, output): with open(file, "r") as f: for i, line in enumerate(f, 1): print(line) G = nx.from_graph6_bytes(line[:-1].encode()) nx.draw(G) fig_path = os.path.join(output, str(i)) plt.savefig(fig_path) plt.close()
def graph6_to_networkx(graph): """ Convert a graph6 graph to a NetworkX graph. :graph: The graph6 graph. :return: The corresponding NetworkX graph. """ return nx.from_graph6_bytes(str.encode(graph))
def handle_one_g6_string(G, g6_string_H): H = nx.from_graph6_bytes(bytes(g6_string_H, 'ascii')) part = [] for j in range(2, len(H) + 1): part = find_a_homomorphism(G, H, j) if len(part) != 0: break return part
def cl(g6): """ compute the canonical labeling? from graph6 """ g = nx.from_graph6_bytes(g6) adj = {v: list(g[v]) for v in g} nauty_graph = pynauty.Graph(g.order(), adjacency_dict=adj) s = pynauty.certificate(nauty_graph) g.clear() del nauty_graph return s
def test_name_of_all_bool_invariant(self): for inv in inv_bool.InvariantBool().all: self.assertTrue( Helper.run('single_graph.g6', '', {inv.name: 'true'}) >= 0) self.assertTrue( Helper.run('single_graph.g6', '', {inv.name: 'false'}) >= 0) self.assertTrue( isinstance( inv.calculate( nx.from_graph6_bytes('I???h?HpG'.encode('utf-8'))), bool))
def main(): # The first eight graphs in this list are those with dmg_1(G)>1, whereas the remaining thirteen have dmg_1(G)=1. graphs_to_check = [ "F?ov?", "F?q`o", "FCQb_", "FCRV?", "FCZb_", "FCpV?", "FCpbO", "FCpb_", "F?`f_", "F?ov_", "F?q_w", "F?qdo", "F?re_", "F?reg", "FCQf?", "FCQf_", "FCRbg", "FCXf?", "FCXfO", "FCZbg", "FCpbo" ] for graph in graphs_to_check: graph_nx = nx.from_graph6_bytes(bytes( graph, encoding='utf-8')) # convert from g6 to nx format print(str(graph) + " - " + str(is_dismantlable(graph_nx)))
def test_all_invariants_with_disconnected_graph(self): # NOTE: disconnected graph with isolate vertice discon_graph = nx.from_graph6_bytes('J????OC?wF_'.encode('utf-8')) for inv in inv_num.InvariantNum().all: self.assertTrue( isinstance(inv.calculate(discon_graph), (float, int, numpy.int32, numpy.int64))) for inv in inv_bool.InvariantBool().all: self.assertTrue(isinstance(inv.calculate(discon_graph), bool)) for inv in inv_other.InvariantOther().all: self.assertTrue( isinstance(inv.calculate(discon_graph), (numpy.ndarray, list, tuple, dict, str, set))) for op in oper.GraphOperations().all: self.assertTrue(isinstance(op.calculate(discon_graph), nx.Graph))
def __framework(self, graph_data, cheat_sheet): if os.path.isfile(graph_data) and os.path.isfile(cheat_sheet): with open(graph_data, 'rb') as f: sg = f.read().splitlines() with open(cheat_sheet, 'rb') as f: bit_vector = pickle.load(f) for i, g in enumerate(sg): expected = True if self.__bit_getter(bit_vector, i) == 0: expected = False nx_g = nx.from_graph6_bytes(g) actual = is_planar(nx_g) if expected != actual: nx.write_gml(nx_g, 'sg.gml') nx_g.clear() self.assertEqual(expected, actual)
def test_case_generator(full=False): """ Return a generator for all test cases. Each test case is a tuple (name, grfilestream, treewidth) where - name is a string indicating the name of the test case - grfilestream is a stream from which the grfile can be read - treewidth is the known treewidth of the graph (or None if we don't care) """ # This covers some corner cases (comments, empty graphs, etc) for grfile in glob.glob("test/valid/*.gr"): yield grfile, open(grfile, "r"), None # Test cases where some tw-solvers were buggy in the past for grfile in glob.glob("test/tw-solver-bugs/*.gr"): treewidth = None with open(grfile[:-3] + ".td") as td_stream: treewidth = read_tw_from_td(td_stream) yield grfile, open(grfile, "r"), treewidth # More test cases where some tw-solvers were buggy in the past tests = ["test/tw-solver-bugs.graph6"] if full: tests.append("test/n_upto_8.graph6") for fname in tests: with open(fname) as tests: for line in tests: line = line.strip().split(" ") graph6 = line[0] treewidth = int(line[1]) G = networkx.from_graph6_bytes(bytes(graph6, "utf-8")) n = G.order() m = G.size() with tempfile.TemporaryFile("w+") as tmp: tmp.write("p tw {:d} {:d}\n".format(n, m)) for (u, v) in G.edges(data=False): tmp.write("{:d} {:d}\n".format(u + 1, v + 1)) tmp.flush() tmp.seek(0) yield graph6 + " from " + fname, tmp, treewidth
def read_graph6(file): tmp = tempfile.NamedTemporaryFile() content = file.read_text() for i in iter(content.splitlines()): i = i.strip().split(" ") graph6 = i[0] g = nx.from_graph6_bytes(bytes(graph6, "UTF-8")) for (u, v) in g.edges(data=False): tmp.write(bytes("{:d} {:d}\n".format(u + 1, v + 1), "UTF-8")) tmp.seek(0) g = nx.read_edgelist(tmp.name) tmp.seek(0) to_sif(file, tmp) # return initial graph to caller return g
def calculate_gt_property(self, vertex_num, file_name, gt_path): stat_list = [] with open(file_name + '.csv', 'w', newline='') as stat_file, open(gt_path + '.g6', 'rb') as graph_file: stat_file_writer = csv.writer(stat_file, delimiter=',') counter = 0 for graph_compressed in graph_file.readlines(): if (counter + 1) % self.bunchsize == 0: stat_file_writer.writerows(stat_list) stat_list = [] graph = nx.from_graph6_bytes(graph_compressed.rstrip()) if self.connected_exp and (not nx.is_connected(graph)): continue stat_list.append( self.ana_tool.standardized_data_analysis( graph, vertex_num)) counter += 1 stat_file_writer.writerows(stat_list)
def generateSmallGraphs(N): startTotal = time.time() print("Importing graphs of size %d..." % N, end=" ") if not (5 < N < 10): raise Exception('The size for small graphs should be between 6 and 10') exit(0) graphs = [] with open('./graphs/non-isomorphs/graph' + str(N) + 'c.g6') as graphs_file: graph_line = graphs_file.readline() while graph_line: graph_line = graph_line.rstrip().encode('ascii') graph = from_graph6_bytes(graph_line) graphs.append(graph) graph_line = graphs_file.readline() endTotal = int(time.time()) print("Duration: %d minutes and %d seconds" % secondsToMinSec(endTotal - startTotal)) return graphs
def test(self: SmallGraphsTests, line=line): graph: nx.Graph[Any] = nx.from_graph6_bytes( bytes(line.strip(), "utf-8")) self.assertEqual(is_cograph(graph), expected_value)
def export_g6_to_png(g6code, folder, count): graph = nx.from_graph6_bytes(g6code.encode('utf-8')) nx.draw(graph) plt.savefig(f"{folder}\Graph_{count}.png", format="PNG") plt.close()
def from_graph6(graph6: str) -> nx.Graph: """Convert a string encoded in graph6 format to a networkx graph""" return nx.from_graph6_bytes(bytes(graph6, "utf-8"))
import FindHomomorphisms as fh import csv for i in range(4, 11): with open("gminust_t" + str(i) + ".g6", "r") as f1: data = f1.read() i = 0 with open("trianglefree_nontree_graphs_upto_10.csv", "w") as f: csvwriter = csv.writer(f) csvwriter.writerow([ 'graph6', 'NumOfV', 'NumOfE', 'Diameter', 'MinDeg', 'MaxDeg', 'Coloring' ]) for line in data.split("\n"): if line != "": H = nx.from_graph6_bytes(bytes(line, 'ascii')) num_tri = nx.triangles(H) if sum(num_tri.values()) == 0: maxdegree = sorted(H.degree, key=lambda x: x[1], reverse=True)[0][1] mindegree = sorted(H.degree, key=lambda x: x[1])[0][1] if maxdegree == mindegree: col = max( nx.coloring.greedy_color( H, strategy='largest_first').values()) + 1 if H.number_of_edges() == 15: csvwriter.writerow([ line, len(H), H.number_of_edges(),
def test_from_graph6_bytes(self): data = b"DF{" G = nx.from_graph6_bytes(data) assert nodes_equal(G.nodes(), [0, 1, 2, 3, 4]) assert edges_equal(G.edges(), [(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)])
def test_from_graph6_bytes(self): data = b'DF{' G=nx.from_graph6_bytes(data) assert_nodes_equal(G.nodes(),[0, 1, 2, 3, 4]) assert_edges_equal(G.edges(), [(0, 3), (0, 4), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)])
pos = {v: 0.35 * scale_factor * p + t for v, p in pos.items()} return pos if __name__ == '__main__': plt.figure(figsize=(11, 11)) """ We can refer graph data in https://users.cecs.anu.edu.au/~bdm/data/graphs.html """ # with open('planar_conn.3.g6', 'rb') as f: # with open('planar_conn.4.g6', 'rb') as f: with open('planar_conn.5.g6', 'rb') as f: # with open('planar_conn.6.g6', 'rb') as f: # with open('planar_conn.7.g6', 'rb') as f: # with open('planar_conn.8.g6', 'rb') as f: lines = f.readlines() n = len(lines) N = get_square(n) print n, N for i, gcode in enumerate(lines): g = nx.from_graph6_bytes(gcode.rstrip('\n')) pos = get_pos(g, N, i) nx.draw_networkx(g, pos, node_size=0, width=0.6, with_labels=False) plt.gca().set_aspect('equal') plt.gca().axis('off') plt.tight_layout() plt.savefig('connected_planar_graphs_n_vertices.png', bbox_inches='tight') plt.show()
def stringtomat(s): I = np.identity(N) A = nx.to_numpy_array(nx.from_graph6_bytes(s)) mat = EIGEN * I - A return np.linalg.inv(mat)
def run_from_g6(g6code, list_invariants): graph = nx.from_graph6_bytes(g6code.encode('utf-8')) dic = {} for inv in list_invariants: dic[inv.name] = str(inv.calculate(graph)) return dic
def convert_g6_to_nx(g6code): return nx.from_graph6_bytes(g6code.encode('utf-8'))
def __graphs_read(self, data_dir: str) -> List[nx.DiGraph]: graphs = [] with open(data_dir + "graphs.txt", "rb") as f: for g in f: graphs.append(nx.from_graph6_bytes(g[:-1]).to_directed()) return graphs
def export_g6_to_tikz(g6code, folder, count): graph = nx.from_graph6_bytes(g6code.encode('utf-8')) tkz.plot(graph, f"{folder}\Graph_{count}.tex", layout='fr', node_size=0.4)
def transform_g6_in_graph(self, g6): self.nx_graph = nx.from_graph6_bytes(g6.encode('utf-8')) pass
def _cli(): parser = argparse.ArgumentParser( description=__description__) parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-i', '--fin', action='store', dest='fin', default='', metavar='FILE', help='Read parameters from file') parser.add_argument('-o', '--fout', action='store', dest='fout', default='', metavar='FILE', help='Write parameters to file') parser.add_argument('-N', '--nodes', type=int, dest='nodes', default=DEFAULT_NODES) parser.add_argument('-P', '--steps', type=int, dest='steps', default=DEFAULT_STEPS) parser.add_argument('--lr', type=float, dest='learning_rate', default=LEARNING_RATE) parser.add_argument('graph', nargs='*', metavar='GRAPH', type=str, action='store', default=['random'], help='Graph to maxcut') examples = { 'ring8': [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 0)], 'example1': [(0, 3), (0, 5), (0, 6), (1, 4), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 7), (4, 7), (6, 7)], 'example2': # 0.93 [(0, 4), (0, 6), (1, 4), (1, 7), (2, 5), (2, 6), (3, 5), (3, 7), (4, 5), (4, 6), (4, 7), (5, 6), (5, 7), (6, 7)], 'example3': [(0, 2), (0, 4), (0, 7), (1, 2), (1, 5), (1, 6), (2, 3), (2, 5), (2, 6), (2, 7), (3, 5), (3, 7), (4, 6), (4, 7), (5, 6), (5, 7)], } # Run command opts = vars(parser.parse_args()) verbose = opts.pop('verbose') steps = opts.pop('steps') N = opts.pop('nodes') learning_rate = opts.pop('learning_rate') fin = opts.pop('fin') if fin: graphs = nx.read_graph6(fin) else: graphs = [] for grapharg in opts.pop('graph'): if grapharg == 'random': graph = nx.gnp_random_graph(N, 0.5) elif grapharg in examples: graph = examples[grapharg] elif grapharg[0] == '[': graph = ast.literal_eval(grapharg) else: graph = nx.from_graph6_bytes(grapharg) graphs.append(graph) for graph in graphs: if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) ratio, betas, gammas = maxcut_qaoa(graph, steps=steps, learning_rate=learning_rate, verbose=verbose) # YAML compatible output. print('---') print('graph:', to_graph6(graph)) print('edges:', list(map(list, graph.edges()))) print('ratio: {:.4f}'.format(ratio)) print('beta: ', list(betas)) print('gamma:', list(gammas)) print() sys.stdout.flush() tf.reset_default_graph()