コード例 #1
0
 def test_dimension(self):
     lat = LatticeFactory.build("hexa")(n_rows=2,
                                        n_cols=3,
                                        distance_metric="euclidean")
     self.assertEqual(6, len(lat.coordinates))
     self.assertEqual(2, lat.n_rows)
     self.assertEqual(3, lat.n_cols)
コード例 #2
0
 def test_n_neighbors(self):
     lat = LatticeFactory.build("rect")(n_rows=4,
                                        n_cols=3,
                                        distance_metric="euclidean")
     dist_matrix = squareform(pdist(lat.coordinates))
     n_neighbors = set(np.sum(np.isclose(dist_matrix, 1), axis=0))
     self.assertEqual({2, 3, 4}, n_neighbors)
コード例 #3
0
 def test_ordering(self):
     lat = LatticeFactory.build("hexa")(n_rows=2,
                                        n_cols=3,
                                        distance_metric="euclidean")
     self.assertTrue(lat.distances[0, 0, 0] == 0)
     self.assertTrue(lat.distances[1, 0, 1] == 0)
     self.assertTrue(lat.distances[2, 0, 2] == 0)
     self.assertTrue(lat.distances[5, 1, 2] == 0)
コード例 #4
0
 def test_distances(self):
     lat = LatticeFactory.build("hexa")(n_rows=2,
                                        n_cols=3,
                                        distance_metric="euclidean")
     pairs = list(product(lat.coordinates, lat.coordinates))
     dist = np.array([euclidean_distance(x=u1, y=u2) for (u1, u2) in pairs])
     dist = dist.reshape(6, 2, 3)
     self.assertTrue(np.allclose(dist, lat.distances))
コード例 #5
0
ファイル: codebook.py プロジェクト: ivallesp/somnium
 def __init__(self, mapsize, lattice='hexa', distance_metric="sqeuclidean"):
     self.mapsize = [1, np.max(mapsize)] if 1 == np.min(mapsize) else mapsize
     self.nnodes = mapsize[0]*mapsize[1]
     self.matrix = None
     self.initialized = False
     self.n_rows, self.n_columns = self.mapsize
     self.lattice = LatticeFactory.build(lattice)(n_rows=self.n_rows,
                                                  n_cols=self.n_columns,
                                                  distance_metric=distance_metric)
コード例 #6
0
 def test_neighborhood_method_cherrypick(self):
     lat = LatticeFactory.build("rect")(n_rows=7,
                                        n_cols=8,
                                        distance_metric="euclidean")
     center = 14
     neighbors = [6, 13, 15, 22]
     self.assertTrue(
         all([lat.are_neighbor_indices(center, n) for n in neighbors]))
     lat = LatticeFactory.build("rect")(n_rows=6,
                                        n_cols=7,
                                        distance_metric="euclidean")
     center = 8
     neighbors = [1, 7, 9, 15]
     self.assertTrue(
         all([lat.are_neighbor_indices(center, n) for n in neighbors]))
     center = 15
     neighbors = [8, 14, 16, 22]
     self.assertTrue(
         all([lat.are_neighbor_indices(center, n) for n in neighbors]))
コード例 #7
0
 def test_neighborhood_method(self):
     lat = LatticeFactory.build("rect")(n_rows=4,
                                        n_cols=7,
                                        distance_metric="euclidean")
     pairs = list(combinations(lat.coordinates, 2))
     neighbors = [euclidean_distance(x=u1, y=u2) == 1 for (u1, u2) in pairs]
     neighbor_pairs = list(compress(pairs, neighbors))
     not_neighbor_pairs = list(compress(pairs,
                                        [not (n) for n in neighbors]))
     self.assertTrue(all([lat.are_neighbors(*x) for x in neighbor_pairs]))
     self.assertTrue(not (
         any([lat.are_neighbors(*x) for x in not_neighbor_pairs])))
コード例 #8
0
def plot_comp(component_matrix, title, ax, map_shape, colormap, lattice="hexa", mode="color"):
    """
    Plots a component into a rectangular or hexagonal lattice. It allows 'color' and 'size' modes, meaning that the
    data in the component matrix can be represented as colors or as sizes of the elements in the plot
    :param component_matrix: matrix containing the data which is intended to be ploted. It must be a 2-D matrix
    (np.array)
    :param title: title to be assigned to the component (str)
    :param ax: matplotlib axis to use to plot the component (matplotlib axis)
    :param map_shape: shape of the codebook matrices (tuple)
    :param colormap: colormap to use to generate the plots (matplotlib.cm)
    :param lattice: lattice to be used to plot the components. Allowed lattices are 'rect' and 'hexa', for rectangular
    and hexagonal grids (str)
    :param mode: indicates how the data should be represented in the components (str). There are two possibilities:
      - 'color': the values of the components will be represented as colors in the grid
      - 'size': the value of the components will be represented as sizes of the elements of the grid.
    :return: axis of the last component and list of coordinates of the centers (tuple)
    """
    # describe rectangle or hexagon
    if lattice == "hexa":
        radius_f = lambda x: x * 2 / 3
        rotation = 0
        numsides = 6
    elif lattice == "rect":
        radius_f = lambda x: x / np.sqrt(2)
        rotation = np.pi / 4
        numsides = 4

    coordinates = LatticeFactory.build(lattice).generate_lattice(*map_shape[:2])
    # Sort to draw left-right top-bottom
    coordinates = coordinates.copy()
    coordinates = coordinates[:, ::-1]
    coordinates = coordinates[np.lexsort([-coordinates[:, 0], -coordinates[:, 1]])]
    coordinates[:, 1] = -coordinates[:, 1]

    # Get pixel size between two data points
    xpoints = coordinates[:, 0]
    ypoints = coordinates[:, 1]
    ax.scatter(xpoints, ypoints, s=0.0, marker='s')
    ax.axis([min(xpoints) - 1., max(xpoints) + 1.,
             min(ypoints) - 1., max(ypoints) + 1.])
    xy_pixels = ax.transData.transform(np.vstack([xpoints, ypoints]).T)
    xpix, ypix = xy_pixels.T
    radius = radius_f(abs(ypix[map_shape[1]] - ypix[0]))

    area_inner_circle = math.pi * (radius ** 2)

    if mode == "color":
        sizes = [area_inner_circle] * component_matrix.shape[0]
    elif mode == "size":
        sizes = area_inner_circle * (component_matrix.reshape(-1) / component_matrix.max())
        component_matrix = component_matrix * 0

    collection_bg = RegularPolyCollection(
        numsides=numsides,  # a hexagon
        rotation=rotation,
        sizes=sizes,
        array=component_matrix,
        cmap=colormap,
        offsets=coordinates,
        transOffset=ax.transData,
    )
    ax.add_collection(collection_bg, autolim=True)

    ax.axis('off')
    ax.autoscale_view()
    ax.set_title(title)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cbar = plt.colorbar(collection_bg, cax=cax)
    if mode != "color":
        cbar.remove()
    return ax, coordinates