def test_img_split_combine():
    '''
    Testing that the split and combine functions are opposites of one another
    '''

    fake_data = np.random.randn(1024, 1024)

    split_data = su.split_img(fake_data, 4)

    combine_data = su.combine_img(split_data[:, 0])

    assert np.all(fake_data == combine_data)
def test_img_split_combine2():
    '''
    Testing that the split and combine functions work properly with real data
    '''

    data_path = os.path.join('fixtures', '488 nm SIM 0.80_cam1_0.mrc')
    data = Mrc(data_path).data

    # split data 4 ways and then take mean along second dimension
    # (phase dimension)
    split_data = su.split_img(data, 4).mean(1)
    # combine data
    combine_data = su.combine_img(split_data)
    # compare to straight mean.
    assert np.all(data.mean(0) == combine_data)
Example #3
0
def recovery_plot(k, v, bg=100, p0=(-0.1, 100, 1), num_tiles=16):
    """Plot the recovery of intensity

    Parameters
    ----------
    k : str
        Figure title
    v : nd.array (t, y, x)
        Assumes an image stack
    bg : numeric
        Background for image data
    p0 : tuple
        Initial guesses for exponential decay
    num_tiles : int
        The number of sub images to calculate

    Returns
    -------
    fig : figure handle
    axs : axes handles"""
    # make figure
    fig, axs = plt.subplots(1,
                            4,
                            figsize=(4 * 3.3, 3),
                            gridspec_kw=dict(width_ratios=(1, 1.3, 1, 1)))
    (ax, ax_k, ax_h, ax_i) = axs
    my_shape = v.shape
    fig.suptitle(k, y=1.05)
    # split the image
    img_split = split_img(v, v.shape[-1] // num_tiles) * 1.0 - bg
    # sum kinetics, convert to float
    kinetics = img_split.mean((2, 3))
    norm_kinetics = kinetics / kinetics[:, np.newaxis].max(-1)
    xdata = np.arange(my_shape[0]) * 0.1 * 46
    ks = np.array(
        [curve_fit(exp, xdata, kin, p0=p0)[0][1] for kin in norm_kinetics])
    kin_img = np.ones_like(img_split)[:, 0, ...] * ks[:, np.newaxis,
                                                      np.newaxis]
    # plot kinetics, color by amount of bleaching and set alpha to initial intensity
    for trace, cpoint in zip(norm_kinetics, scale(ks)):
        if np.isfinite(cpoint):
            ax.plot(xdata, trace, c=plt.get_cmap("spring")(cpoint))
    # start plotting
    ax.set_title("Bleaching Kinetics")
    ax.set_xlabel("J/cm$^2$")
    ax.set_ylabel("Relative Intensity (a.u.)")
    ax.tick_params()
    img = ax_k.matshow(combine_img(kin_img), cmap="spring")
    cb = plt.colorbar(img, ax=ax_k, aspect=10, use_gridspec=True)
    cb.set_label("Decay constant (J/cm$^2$)")
    ax_k.matshow(v.max(0), cmap=greys_alpha_cm, norm=LogNorm())
    ax_i.matshow(adjust_gamma(v.max(0), 0.25), cmap="Greys_r")
    ax_h.hist(ks, bins=int(np.sqrt(ks.size)))
    ax_h.set_title("Median = {:.0f}".format(np.median(ks)))
    for ax in (ax_i, ax_k):
        ax.grid("off")
        ax.axis("off")
    ax_i.set_title("Image")
    ax_k.set_title("Bleaching Map")
    fig.tight_layout()
    return fig, axs
Example #4
0
def bleach_plot2(k, v, bg=100.0, num_tiles=16, gamma=0.5, dt=1):
    """Plot bleaching of image timeseries

    Parameters
    ----------
    k : str
        Title string
    v : ndarray (t, y, x)
        Image stack (x must y)
    bg : float
        Background counts
    num_tiles : int
        Number of tiles per image side
    """
    nt, ny, nx = v.shape
    assert ny == nx, "data isn't square"
    # make figure
    fig, axs = plt.subplots(1, 3, figsize=(9, 3))
    (ax, ax_k, ax_i) = axs
    fig.suptitle(k, y=1.05)
    # split the image
    img_split = split_img(v, nx // num_tiles)
    # sum kinetics, convert to float
    bg = np.asarray(bg)
    bg.shape = (-1, 1, 1)
    kinetics = (img_split * 1.0 - bg).sum((2, 3))
    # anything that's negative mask with an nan
    kinetics[kinetics < 0] = np.nan
    # normalize all the kinetics with the max one
    norm_kinetics = kinetics / np.max(kinetics[:, np.newaxis], -1)
    kin_img = np.ones_like(img_split)[:, 0,
                                      ...] * norm_kinetics[:, -1, np.newaxis,
                                                           np.newaxis]
    # start plotting
    # plot kinetics, color by amount of bleaching and set alpha to initial intensity
    for trace, cpoint in zip(norm_kinetics, scale(norm_kinetics[:, -1])):
        # make sure the point is not an nan
        if np.isfinite(cpoint):
            ax.loglog(np.arange(len(trace)) * dt,
                      trace,
                      c=plt.get_cmap("spring")(cpoint))
    # label stuff
    ax.set_title("Bleaching Kinetics")
    ax.set_xlabel("Time (s)")
    ax.set_ylabel("Relative Intensity (a.u.)")
    ax.tick_params()
    # calculate the max image
    v_max = v.max(0)
    # plot color coded kinetics
    ax_k.matshow(combine_img(kin_img), cmap="spring", zorder=0)
    # plot image with alpha over it
    ax_k.matshow(v_max, cmap=greys_alpha_cm, norm=LogNorm(), zorder=1)
    # plot raw image with gamma adjustment for reference
    ax_i.matshow(adjust_gamma(v_max, gamma), cmap="Greys_r")
    # remove grids
    for ax in (ax_i, ax_k):
        ax.grid("off")
        ax.axis("off")
    # set titles
    ax_i.set_title("Image")
    ax_k.set_title("Bleaching Map")
    fig.tight_layout()
    return fig, axs