latools/filtering/signal_optimiser.py
def optimisation_plot(d, overlay_alpha=0.5, **kwargs):
    """
    Plot the result of signal_optimise.

    `signal_optimiser` must be run first, and the output
    stored in the `opt` attribute of the latools.D object.

    Parameters
    ----------
    d : latools.D object
        A latools data object.
    overlay_alpha : float
        The opacity of the threshold overlays. Between 0 and 1.
    **kwargs
        Passed to `tplot`
    """
    if not hasattr(d, 'opt'):
        raise ValueError('Please run `signal_optimiser` before trying to plot its results.')
    
    out = []
    for n, opt in d.opt.items():
        if not opt['optimisation_success']:
            out.append((None, None))
        
        else:
            # unpack variables
            means = opt['means']
            stds = opt['stds']
            min_points = opt['min_points']
            mean_threshold = opt['mean_threshold']
            std_threshold = opt['std_threshold']
            opt_centre = opt['opt_centre']
            opt_n_points = opt['opt_n_points']
            
            centres, npoints = np.meshgrid(np.arange(means.shape[1]), np.arange(min_points, min_points + means.shape[0]))
            rind = (stds < std_threshold)
            mind = (means < mean_threshold)

            # color scale and histogram limits
            mlim = np.percentile(means.flatten()[~np.isnan(means.flatten())], (0, 99))
            rlim = np.percentile(stds.flatten()[~np.isnan(stds.flatten())], (0, 99))

            cmr = plt.cm.Blues
            cmr.set_bad((0,0,0,0.3))

            cmm = plt.cm.Reds
            cmm.set_bad((0,0,0,0.3))
            
            # create figure
            fig = plt.figure(figsize=[7,7])

            ma = fig.add_subplot(3, 2, 1)
            ra = fig.add_subplot(3, 2, 2)

            # work out image limits
            nonan = np.argwhere(~np.isnan(means))
            xdif = np.ptp(nonan[:, 1])
            ydif = np.ptp(nonan[:, 0])
            extent = (nonan[:, 1].min() - np.ceil(0.1 * xdif),  # x min
                    nonan[:, 1].max() + np.ceil(0.1 * xdif),  # x max
                    nonan[:, 0].min() + min_points,  # y min
                    nonan[:, 0].max() + np.ceil(0.1 * ydif) + min_points)  # y max

            mm = ma.imshow(means, origin='bottomleft', cmap=cmm, vmin=mlim[0], vmax=mlim[1],
                        extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            ma.set_ylabel('N points')
            ma.set_xlabel('Center')
            fig.colorbar(mm, ax=ma, label='Amplitude')

            mr = ra.imshow(stds, origin='bottomleft', cmap=cmr, vmin=rlim[0], vmax=rlim[1],
                        extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            ra.set_xlabel('Center')
            fig.colorbar(mr, ax=ra, label='std')

            # view limits
            ra.imshow(~rind, origin='bottomleft', cmap=plt.cm.Greys, alpha=overlay_alpha,
                    extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))
            ma.imshow(~mind, origin='bottomleft', cmap=plt.cm.Greys, alpha=overlay_alpha,
                    extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            for ax in [ma, ra]:
                ax.scatter(opt_centre, opt_n_points, c=(1,1,1,0.7), edgecolor='k',marker='o')
                ax.set_xlim(extent[:2])
                ax.set_ylim(extent[-2:])

            # draw histograms
            mah = fig.add_subplot(3, 2, 3)
            rah = fig.add_subplot(3, 2, 4)

            mah.set_xlim(mlim)
            mbin = np.linspace(*mah.get_xlim(), 50)
            mah.hist(means.flatten()[~np.isnan(means.flatten())], mbin)
            mah.axvspan(mean_threshold, mah.get_xlim()[1], color=(0,0,0,overlay_alpha))

            mah.axvline(mean_threshold, c='r')
            mah.set_xlabel('Scaled Mean Analyte Conc')
            mah.set_ylabel('N')

            rah.set_xlim(rlim)
            rbin = np.linspace(*rah.get_xlim(), 50)
            rah.hist(stds.flatten()[~np.isnan(stds.flatten())], rbin)
            rah.axvspan(std_threshold, rah.get_xlim()[1], color=(0,0,0,0.4))
            rah.axvline(std_threshold, c='r')
            rah.set_xlabel('std')
            
            tax = fig.add_subplot(3,1,3)
            tplot(d, opt.analytes, ax=tax, **kwargs)
            tax.axvspan(*d.Time[[opt.lims[0], opt.lims[1]]], alpha=0.2)
            
            tax.set_xlim(d.Time[d.ns == n].min() - 3, d.Time[d.ns == n].max() + 3)

            fig.tight_layout()

            out.append((fig, (ma, ra, mah, rah, tax)))
    return out
def optimisation_plot(d, overlay_alpha=0.5, **kwargs):
    """
    Plot the result of signal_optimise.

    `signal_optimiser` must be run first, and the output
    stored in the `opt` attribute of the latools.D object.

    Parameters
    ----------
    d : latools.D object
        A latools data object.
    overlay_alpha : float
        The opacity of the threshold overlays. Between 0 and 1.
    **kwargs
        Passed to `tplot`
    """
    if not hasattr(d, 'opt'):
        raise ValueError('Please run `signal_optimiser` before trying to plot its results.')
    
    out = []
    for n, opt in d.opt.items():
        if not opt['optimisation_success']:
            out.append((None, None))
        
        else:
            # unpack variables
            means = opt['means']
            stds = opt['stds']
            min_points = opt['min_points']
            mean_threshold = opt['mean_threshold']
            std_threshold = opt['std_threshold']
            opt_centre = opt['opt_centre']
            opt_n_points = opt['opt_n_points']
            
            centres, npoints = np.meshgrid(np.arange(means.shape[1]), np.arange(min_points, min_points + means.shape[0]))
            rind = (stds < std_threshold)
            mind = (means < mean_threshold)

            # color scale and histogram limits
            mlim = np.percentile(means.flatten()[~np.isnan(means.flatten())], (0, 99))
            rlim = np.percentile(stds.flatten()[~np.isnan(stds.flatten())], (0, 99))

            cmr = plt.cm.Blues
            cmr.set_bad((0,0,0,0.3))

            cmm = plt.cm.Reds
            cmm.set_bad((0,0,0,0.3))
            
            # create figure
            fig = plt.figure(figsize=[7,7])

            ma = fig.add_subplot(3, 2, 1)
            ra = fig.add_subplot(3, 2, 2)

            # work out image limits
            nonan = np.argwhere(~np.isnan(means))
            xdif = np.ptp(nonan[:, 1])
            ydif = np.ptp(nonan[:, 0])
            extent = (nonan[:, 1].min() - np.ceil(0.1 * xdif),  # x min
                    nonan[:, 1].max() + np.ceil(0.1 * xdif),  # x max
                    nonan[:, 0].min() + min_points,  # y min
                    nonan[:, 0].max() + np.ceil(0.1 * ydif) + min_points)  # y max

            mm = ma.imshow(means, origin='bottomleft', cmap=cmm, vmin=mlim[0], vmax=mlim[1],
                        extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            ma.set_ylabel('N points')
            ma.set_xlabel('Center')
            fig.colorbar(mm, ax=ma, label='Amplitude')

            mr = ra.imshow(stds, origin='bottomleft', cmap=cmr, vmin=rlim[0], vmax=rlim[1],
                        extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            ra.set_xlabel('Center')
            fig.colorbar(mr, ax=ra, label='std')

            # view limits
            ra.imshow(~rind, origin='bottomleft', cmap=plt.cm.Greys, alpha=overlay_alpha,
                    extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))
            ma.imshow(~mind, origin='bottomleft', cmap=plt.cm.Greys, alpha=overlay_alpha,
                    extent=(centres.min(), centres.max(), npoints.min(), npoints.max()))

            for ax in [ma, ra]:
                ax.scatter(opt_centre, opt_n_points, c=(1,1,1,0.7), edgecolor='k',marker='o')
                ax.set_xlim(extent[:2])
                ax.set_ylim(extent[-2:])

            # draw histograms
            mah = fig.add_subplot(3, 2, 3)
            rah = fig.add_subplot(3, 2, 4)

            mah.set_xlim(mlim)
            mbin = np.linspace(*mah.get_xlim(), 50)
            mah.hist(means.flatten()[~np.isnan(means.flatten())], mbin)
            mah.axvspan(mean_threshold, mah.get_xlim()[1], color=(0,0,0,overlay_alpha))

            mah.axvline(mean_threshold, c='r')
            mah.set_xlabel('Scaled Mean Analyte Conc')
            mah.set_ylabel('N')

            rah.set_xlim(rlim)
            rbin = np.linspace(*rah.get_xlim(), 50)
            rah.hist(stds.flatten()[~np.isnan(stds.flatten())], rbin)
            rah.axvspan(std_threshold, rah.get_xlim()[1], color=(0,0,0,0.4))
            rah.axvline(std_threshold, c='r')
            rah.set_xlabel('std')
            
            tax = fig.add_subplot(3,1,3)
            tplot(d, opt.analytes, ax=tax, **kwargs)
            tax.axvspan(*d.Time[[opt.lims[0], opt.lims[1]]], alpha=0.2)
            
            tax.set_xlim(d.Time[d.ns == n].min() - 3, d.Time[d.ns == n].max() + 3)

            fig.tight_layout()

            out.append((fig, (ma, ra, mah, rah, tax)))
    return out
Plot the result of signal_optimise.

    `signal_optimiser` must be run first, and the output
    stored in the `opt` attribute of the latools.D object.

    Parameters
    ----------
    d : latools.D object
        A latools data object.
    overlay_alpha : float
        The opacity of the threshold overlays. Between 0 and 1.
    **kwargs
        Passed to `tplot`