Esempio n. 1
0
    def write_tiles(
        self,
        dir: str,
        n_jobs=1,
        predictions=None,
        mask_features=None,
        cmap: mpl.colors.Colormap = plt.get_cmap("viridis"),
        min_threshold: Union[int, float] = 0,
        bad_value={
            "color": "k",
            "alpha": 0
        },
        metadata: Dict = None,
        transform: Callable = None,
        backend="multiprocessing",
        **kwargs,
    ):
        if min_threshold is not None:
            cmap.set_bad(**bad_value)
            cmap.set_under(**bad_value)
        if not os.path.isdir(dir):
            os.makedirs(dir)
        if metadata:
            with open("{dir}/metadata.json".format(dir=dir), "w") as file:
                file.write(json.dumps(metadata))
        if predictions is None:
            predictions = self.generate_predictions(n_jobs=n_jobs,
                                                    transform=transform,
                                                    backend=backend)
        max_threshold = np.max(predictions)
        min_threshold = np.min(predictions)
        for idx, tile in enumerate(self.tiles):
            x, y, z = tile
            preds = predictions[idx]
            if mask_features is not None:
                fdw = self.transformers[idx]
                vector_mask = geometry_mask(
                    mask_features,
                    transform=fdw,
                    all_touched=True,
                    out_shape=(self.tile_dimension, self.tile_dimension),
                )
                preds[vector_mask] = min_threshold - 100
            folder = "{directory}/{z}/{x}".format(directory=dir, z=z, x=x)
            if not os.path.exists(folder):
                os.makedirs(folder)
            file_path = "{folder}/{y}.png".format(folder=folder, y=y)

            plt.imsave(file_path,
                       preds,
                       cmap=cmap,
                       vmin=min_threshold,
                       vmax=max_threshold)
Esempio n. 2
0
def prepare_colormap(colormap: matplotlib.colors.Colormap) -> matplotlib.colors.Colormap:
    """ Apply fix to colormaps to remove the need for transparency.

    Since transparency is not support EPS, we change "bad" values (such as NaN in a plot)
    from (0,0,0,0) (this value can be accessed via `cm._rgba_bad`) to white with
    alpha = 1 (no transparency).

    Args:
        colormap: Colormap used to map data to colors.
    Returns:
        The updated colormap.
    """
    # Set bad values to white instead of transparent because EPS doesn't support transparency
    colormap.set_bad("w", 1)

    return colormap
Esempio n. 3
0
def draw_3d_plot(ax: mpl.axes.Axes,
                 x: np.ndarray,
                 y: np.ndarray,
                 z: np.ndarray,
                 plot_type: str = 'contour',
                 marker: str = 'X',
                 marker_size: int = 50,
                 marker_color: str = 'red',
                 interpolation: str = 'linear',
                 cmap: matplotlib.colors.Colormap = matplotlib.cm.RdBu_r,
                 min_level: float = math.nan,
                 max_level: float = math.nan) -> None:
    '''Draw a 3d plot.  See XYZData class for explanation of arguments
    
    >>> points = np.random.rand(1000, 2)
    >>> x = np.random.rand(10)
    >>> y = np.random.rand(10)
    >>> z = x ** 2 + y ** 2
    >>> if has_display():
    ...    fig, ax = plt.subplots()
    ...    draw_3d_plot(ax, x = x, y = y, z = z, plot_type = 'contour', interpolation = 'linear');
    '''
    xi = np.linspace(min(x), max(x))
    yi = np.linspace(min(y), max(y))
    X, Y = np.meshgrid(xi, yi)
    Z = griddata((x, y), z, (xi[None, :], yi[:, None]), method=interpolation)
    Z = np.nan_to_num(Z)

    if plot_type == 'surface':
        ax.plot_surface(X, Y, Z, cmap=cmap)
        if marker is not None:
            ax.scatter(x, y, z, marker=marker, s=marker_size, c=marker_color)
        m = cm.ScalarMappable(cmap=cmap)
        m.set_array(Z)
        plt.colorbar(m, ax=ax)

    elif plot_type == 'contour':
        # extract all colors from the  map
        cmaplist = [cmap(i) for i in range(cmap.N)]
        # create the new map
        cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)
        Z = np.ma.masked_array(Z, mask=~np.isfinite(Z))
        if math.isnan(min_level): min_level = np.min(Z)
        if math.isnan(max_level): max_level = np.max(Z)
        # define the bins and normalize and forcing 0 to be part of the colorbar!
        bounds = np.arange(min_level, max_level,
                           (max_level - min_level) / cmap.N)
        idx = np.searchsorted(bounds, 0)
        bounds = np.insert(bounds, idx, 0)
        norm = BoundaryNorm(bounds, cmap.N)
        cs = ax.contourf(X, Y, Z, cmap=cmap, norm=norm)

        if marker is not None:
            x = x[np.isfinite(z)]
            y = y[np.isfinite(z)]
            ax.scatter(x,
                       y,
                       marker=marker,
                       s=marker_size,
                       c=z[np.isfinite(z)],
                       zorder=10,
                       cmap=cmap)
        LABEL_SIZE = 16
        ax.tick_params(axis='both', which='major', labelsize=LABEL_SIZE)
        ax.tick_params(axis='both', which='minor', labelsize=LABEL_SIZE)
        cbar = plt.colorbar(cs, ax=ax)
        cbar.ax.tick_params(labelsize=LABEL_SIZE)

    else:
        raise Exception(f'unknown plot type: {plot_type}')