|
| 1 | +from .graph import * |
| 2 | + |
| 3 | +class Merger: |
| 4 | + def __init__(self, *graphs, **kwargs): |
| 5 | + """__init__(self, *graphs, **kwargs) -> None |
| 6 | + put several graphs into one |
| 7 | + list graphs -> the graphs that will be merged |
| 8 | + list kwargs: |
| 9 | + None |
| 10 | + """ |
| 11 | + self.graphs = graphs |
| 12 | + self.G = Graph(sum([len(i.edges) - 1 for i in graphs]), graphs[0].directed) |
| 13 | + |
| 14 | + counter = 0 |
| 15 | + for graph in self.graphs: |
| 16 | + graph.offset = counter |
| 17 | + for edge in graph.iterate_edges(): |
| 18 | + self.G.add_edge(edge.start + counter, |
| 19 | + edge.end + counter, |
| 20 | + weight=edge.weight) |
| 21 | + counter += len(graph.edges) - 1 |
| 22 | + |
| 23 | + def __add_edge(self, u, v, **kwargs): |
| 24 | + """__add_edge(self, u, v, **kwargs) |
| 25 | + tuple u -> (graph_index, vertex) indicating the start point |
| 26 | + tuple v -> (graph_index, vertex) indicating the end point |
| 27 | + **kwargs: |
| 28 | + int weight -> edge weight |
| 29 | + """ |
| 30 | + self.G.add_edge(self.graphs[ u[0] ].offset + u[1], |
| 31 | + self.graphs[ v[0] ].offset + v[1], |
| 32 | + weight=kwargs.get("weight", 1)) |
| 33 | + |
| 34 | + def add_edge(self, u, v, **kwargs): |
| 35 | + """add_edge(self, u, v, **kwargs) -> None |
| 36 | + """ |
| 37 | + self.__add_edge(u, v, **kwargs) |
| 38 | + |
| 39 | + def to_str(self, **kwargs): |
| 40 | + return self.G.to_str(**kwargs) |
| 41 | + |
| 42 | + def __str__(self): |
| 43 | + return self.to_str() |
| 44 | + |
| 45 | + @staticmethod |
| 46 | + def component(point_count, edge_count, **kwargs): |
| 47 | + """component(point_count, edge_count, **kwargs) |
| 48 | + generate a graph with certain components |
| 49 | + int point_count -> the number of vertices of each component |
| 50 | + int edge_count -> the number of edges of each component |
| 51 | + **kwargs: |
| 52 | + int component_count -> indicating how many components there are |
| 53 | + """ |
| 54 | + component_count = kwargs.get("component_count", (2, 2)) |
| 55 | + if not list_like(component_count): |
| 56 | + component_count = (component_count, component_count) |
| 57 | + real_count = random.randint(*component_count) |
| 58 | + graphs = [None] * real_count |
| 59 | + for i in xrange(real_count): |
| 60 | + graphs[i] = Graph.graph(point_count, edge_count, **kwargs) |
| 61 | + G = Merger(*graphs) |
| 62 | + return G.G |
0 commit comments