|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +import random |
| 4 | +from collections import defaultdict |
| 5 | +from graph_tool.all import * |
| 6 | + |
| 7 | +class MyGraph: |
| 8 | + def __init__(self): |
| 9 | + self.graph = None |
| 10 | + self.labels = None |
| 11 | + self.verts = [] |
| 12 | + self.gates = None |
| 13 | + self.edge_labels = None |
| 14 | + |
| 15 | + def generate(self, n_verts): |
| 16 | + self.graph = Graph(directed = True) |
| 17 | + self.labels = self.graph.new_vp("int") |
| 18 | + #self.vert_idxs = self.graph.new_vp("int") |
| 19 | + self.gates = defaultdict(dict) |
| 20 | + self.edge_labels = self.graph.new_ep("int") |
| 21 | + |
| 22 | + self.verts = [] |
| 23 | + for i in range(n_verts): |
| 24 | + v = self.graph.add_vertex() |
| 25 | + label = random.randint(0, 3) |
| 26 | + self.labels[v] = label |
| 27 | + #self.graph.vertex_index[v] = i |
| 28 | + self.verts.append(v) |
| 29 | + |
| 30 | + for v1_idx, v1 in enumerate(self.verts): |
| 31 | + for src_gate_idx in range(6): |
| 32 | + existing_edge = self.gates[v1_idx].get(src_gate_idx, None) |
| 33 | + if existing_edge is not None: |
| 34 | + continue |
| 35 | + #print(f"connect [{v1_idx}].{src_gate_idx} to...") |
| 36 | + found = False |
| 37 | + while not found: |
| 38 | + v2_idx = random.randint(0, n_verts-1) |
| 39 | + dst_gate_idx = random.randint(0, 5) |
| 40 | + #print(f"check: [{v2_idx}].{dst_gate_idx}...") |
| 41 | + existing_edge = self.gates[v2_idx].get(dst_gate_idx, None) |
| 42 | + #print(f"edge: {existing_edge}") |
| 43 | + if existing_edge is None: |
| 44 | + found = True |
| 45 | + edge = self.graph.add_edge(v1, self.verts[v2_idx]) |
| 46 | + self.gates[v1_idx][src_gate_idx] = edge |
| 47 | + self.gates[v2_idx][dst_gate_idx] = edge |
| 48 | + self.edge_labels[edge] = src_gate_idx |
| 49 | + #print(f"...selected: [{v2_idx}].{dst_gate_idx}") |
| 50 | + break |
| 51 | + |
| 52 | + def other_vert(self, edge, vert): |
| 53 | + if edge.source() == vert: |
| 54 | + return edge.target() |
| 55 | + else: |
| 56 | + return edge.source() |
| 57 | + |
| 58 | + def draw(self, filename=None): |
| 59 | + graph_draw(self.graph, vertex_text = self.labels, edge_text = self.edge_labels, output=filename) |
| 60 | + |
| 61 | + def explore(self, path): |
| 62 | + idx = 0 |
| 63 | + result = [self.labels[self.verts[idx]]] |
| 64 | + for gate_idx in path: |
| 65 | + edge = self.gates[idx][gate_idx] |
| 66 | + next_vert = self.other_vert(edge, self.verts[idx]) |
| 67 | + label = self.labels[next_vert] |
| 68 | + result.append(label) |
| 69 | + idx = self.graph.vertex_index[next_vert] |
| 70 | + return result |
| 71 | + |
| 72 | +#g = MyGraph() |
| 73 | +#g.generate(3) |
| 74 | +#g.draw() |
0 commit comments