예제 #1
0
    def generate_random(nr_vertices, nr_edges=0):
        if not 0 <= nr_edges <= nr_vertices * (nr_vertices - 1) / 2:
            raise ValueError

        if not nr_edges:
            nr_edges = 0.5

        graph = Graph()
        graph.add(bits(*range(nr_vertices)))

        if nr_edges < 1:
            # Add random edges between groups
            for v in graph:
                for w in graph:
                    if v < w and random() < nr_edges:
                        graph.connect(v, w)
            return graph
        else:
            vertex_list = list(iterate(graph.vertices))
            for _ in range(nr_edges):
                while 1:
                    v, w = sample(vertex_list, 2)
                    # Don't connect vertices twice
                    if not w in graph[v]:
                        break
                graph.connect(v, w)

            return graph
예제 #2
0
    def __init__(self, grid_dict):
        """The grid is a 2d array of numbers."""
        self.grid_dict = grid_dict
        self.grid_matrix = dict_to_matrix(grid_dict)

        for row in self.grid_matrix:
            if len(row) != self.grid_width:
                raise ValueError('Input grid is not a valid matrix.')
            for val in row:
                if val < 0:
                    raise ValueError('Input grid has negative numbers.')

        # Detect fields by BFS
        todo = [cell for cell in grid_dict]
        fields = {}  # Mapping from field number to group of cells

        while todo:
            front = [todo.pop()]
            field = front[:]
            current_number = grid_dict[field[0]]
            if current_number in fields:
                raise ValueError(
                    'Not all cells with the same number are in the same field'
                )

            while front:
                current_cell = front.pop()
                for neighbor_cell in neighbor_cells(grid_dict, current_cell):
                    if neighbor_cell in todo and grid_dict[neighbor_cell] == current_number:
                        front.append(neighbor_cell)
                        field.append(neighbor_cell)
                        todo.remove(neighbor_cell)
            fields[current_number] = field
        self.fields = fields

        # Detect and create vertices
        vertex_numbers = fields.keys()
        vertices = bits(*vertex_numbers)

        # Detect and create neighborhoods
        neighborhoods = {}
        for number, cells in fields.items():
            neighbors = 0
            for cell in cells:
                for neighbor_cell in neighbor_cells(grid_dict, cell):
                    neighbors |= bit(grid_dict[neighbor_cell])
            neighborhoods[bit(number)] = neighbors

        Graph.__init__(self, vertices, neighborhoods)