Example #1
0
            y = scale.inverse(np.linspace(scale(scale.clip(plt_min)), 
                                          scale(scale.clip(plt_max)), 500))   
            pdf_scale = patch_area * gmm.weights_[idx]
            mean = gmm.means_[idx][0]
            stdev = np.sqrt(gmm.covariances_[idx][0])
            x = stats.norm.pdf(scale(y), mean, stdev) * pdf_scale
            axes.plot(x, y, color = annotation_color)
        else:
            scale = kwargs['xscale']
            patch_area = 0.0
                                     
            for k in range(0, len(axes.patches)):
                patch = axes.patches[k]
                xy = patch.get_xy()
                patch_area += poly_area([scale(p[0]) for p in xy], [p[1] for p in xy])
            
            plt_min, plt_max = plt.gca().get_xlim()
            x = scale.inverse(np.linspace(scale(scale.clip(plt_min)), 
                                          scale(scale.clip(plt_max)), 500))   
            pdf_scale = patch_area * gmm.weights_[idx]
            mean = gmm.means_[idx][0]
            stdev = np.sqrt(gmm.covariances_[idx][0])
            y = stats.norm.pdf(scale(x), mean, stdev) * pdf_scale
            axes.plot(x, y, color = annotation_color)
                
# from http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
def poly_area(x,y):
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

util.expand_class_attributes(GaussianMixture1DView)
util.expand_method_parameters(GaussianMixture1DView, GaussianMixture1DView.plot)
Example #2
0
        
        return {'xlim' : xlim, 'ylim' : ylim}

                
def _error_bars(x, y, yerr, ax = None, color = None, **kwargs):
    
    if isinstance(yerr.iloc[0], tuple):
        lo = [ye[0] for ye in yerr]
        hi = [ye[1] for ye in yerr]
    else:
        lo = [y.iloc[i] - ye for i, ye in yerr.reset_index(drop = True).items()]
        hi = [y.iloc[i] + ye for i, ye in yerr.reset_index(drop = True).items()]

    plt.vlines(x, lo, hi, color = color, **kwargs)
    
util.expand_class_attributes(Stats1DView)
util.expand_method_parameters(Stats1DView, Stats1DView.plot)
    

if __name__ == '__main__':
    import cytoflow as flow
    
    tube1 = flow.Tube(file = '../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions = {"Dox" : 10.0})
    
    tube2 = flow.Tube(file = '../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions = {"Dox" : 1.0})                      

    ex = flow.ImportOp(conditions = {"Dox" : "float"}, tubes = [tube1, tube2])
    
    thresh = flow.ThresholdOp()
    ax = plt.gca()

    color = kwargs.pop("color")
    ax.pcolormesh(X, Y, h.T, cmap=AlphaColormap("AlphaColor", color), **kwargs)

    return ax


class AlphaColormap(Colormap):
    def __init__(self, name, color, min_alpha=0.0, max_alpha=1.0, N=256):
        Colormap.__init__(self, name, N)
        self._color = color
        self._min_alpha = min_alpha
        self._max_alpha = max_alpha

    def _init(self):
        self._lut = np.ones((self.N + 3, 4), np.float)
        self._lut[:-3, 0] = self._color[0]
        self._lut[:-3, 1] = self._color[1]
        self._lut[:-3, 2] = self._color[2]
        self._lut[:-3, 3] = np.linspace(self._min_alpha,
                                        self._max_alpha,
                                        num=self.N,
                                        dtype=np.float)
        self._isinit = True
        self._set_extremes()


util.expand_class_attributes(Histogram2DView)
util.expand_method_parameters(Histogram2DView, Histogram2DView.plot)
Example #4
0
        plt.draw()

    @on_trait_change('interactive', post_init=True)
    def _interactive(self):
        if self._ax and self.interactive:
            self._widget = util.PolygonSelector(self._ax,
                                                self._onselect,
                                                useblit=True)
        elif self._widget:
            self._widget = None

    def _onselect(self, vertices):
        self.op.vertices = vertices


util.expand_class_attributes(PolygonSelection)
util.expand_method_parameters(PolygonSelection, PolygonSelection.plot)

if __name__ == '__main__':
    import cytoflow as flow
    tube1 = flow.Tube(file='../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions={"Dox": 10.0})

    tube2 = flow.Tube(file='../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions={"Dox": 1.0})

    ex = flow.ImportOp(conditions={"Dox": "float"}, tubes=[tube1, tube2])

    p = PolygonOp(xchannel="V2-A", ychannel="Y2-A")
    v = p.default_view(xscale="logicle", yscale="logicle")
Example #5
0
                                               rectprops=dict(facecolor='none',
                                                              edgecolor='blue',
                                                              linewidth=2),
                                               useblit=True)
        else:
            self._selector = None

    def _onselect(self, pos1, pos2):
        """Update selection traits"""
        self.op.xlow = min(pos1.xdata, pos2.xdata)
        self.op.xhigh = max(pos1.xdata, pos2.xdata)
        self.op.ylow = min(pos1.ydata, pos2.ydata)
        self.op.yhigh = max(pos1.ydata, pos2.ydata)


util.expand_class_attributes(RangeSelection2D)
util.expand_method_parameters(RangeSelection2D, RangeSelection2D.plot)

if __name__ == '__main__':
    import cytoflow as flow

    tube1 = flow.Tube(file='../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions={"Dox": 10.0})

    tube2 = flow.Tube(file='../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions={"Dox": 1.0})

    ex = flow.ImportOp(conditions={"Dox": "float"}, tubes=[tube1, tube2])

    r = flow.Range2DOp(xchannel="V2-A", ychannel="Y2-A")
    rv = r.default_view()
Example #6
0
    bins are shown in different colors.
    
    Attributes
    ----------
    
    """

    id = Constant('edu.mit.synbio.cytoflow.views.binning')
    friendly_id = Constant('Binning Setup')

    def plot(self, experiment, **kwargs):
        """
        Plot the histogram.
        
        Parameters
        ----------
        
        """

        view, trait_name = self._strip_trait(self.op.name)

        super(BinningView, view).plot(experiment,
                                      annotation_facet=self.op.name,
                                      annotation_trait=trait_name,
                                      annotations={},
                                      **kwargs)


util.expand_class_attributes(BinningView)
util.expand_method_parameters(BinningView, BinningView.plot)
Example #7
0
                                       color='blue',
                                       useblit=True)
            self._cursor.connect_event('button_press_event', self._onclick)

        elif self._cursor:
            self._cursor.disconnect_events()
            self._cursor = None

    def _onclick(self, event):
        """Update the threshold location"""
        # sometimes the axes aren't set up and we don't get xdata (??)
        if event.xdata:
            self.op.threshold = event.xdata


util.expand_class_attributes(ThresholdSelection)
util.expand_method_parameters(ThresholdSelection, ThresholdSelection.plot)

if __name__ == '__main__':
    import cytoflow as flow

    tube1 = flow.Tube(file='../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions={"Dox": 10.0})

    tube2 = flow.Tube(file='../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions={"Dox": 1.0})

    ex = flow.ImportOp(conditions={"Dox": "float"}, tubes=[tube1, tube2])

    t = ThresholdOp(channel="Y2-A", scale="logicle")
    v = t.default_view()
Example #8
0
        super(KMeans2DView, view).plot(experiment,
                                       annotation_facet = self.op.name,
                                       annotation_trait = trait_name,
                                       annotations = self.op._kmeans,
                                       xscale = xscale,
                                       yscale = yscale,
                                       **kwargs)
 
    def _annotation_plot(self, axes, annotation, annotation_facet, 
                         annotation_value, annotation_color, **kwargs):
                                                        
        # plot the cluster centers
            
        km = annotation
        xscale = kwargs['xscale']
        yscale = kwargs['yscale']
        
        ix = self.op.channels.index(self.xchannel)
        iy = self.op.channels.index(self.ychannel)
        
        for k in range(self.op.num_clusters):
            x = xscale.inverse(km.cluster_centers_[k][ix])
            y = yscale.inverse(km.cluster_centers_[k][iy])
            
            axes.plot(x, y, '*', color = 'blue')

util.expand_class_attributes(KMeans1DView)
util.expand_method_parameters(KMeans1DView, KMeans1DView.plot)

util.expand_class_attributes(KMeans2DView)
util.expand_method_parameters(KMeans2DView, KMeans2DView.plot)
Example #9
0
    x = scale.inverse(support[:, 0])
    y = np.exp(log_density)

    # Check if a label was specified in the call
    label = kwargs.pop("label", None)
    color = kwargs.pop("color", None)
    alpha = kwargs.pop("alpha", 0.25)

    # Draw the KDE plot and, optionally, shade
    if orientation == "vertical":
        ax.plot(x, y, color=color, label=label, **kwargs)
        if shade:
            ax.fill_between(x, 1e-12, y, facecolor=color, alpha=alpha)
    else:
        ax.plot(y, x, color=color, label=label, **kwargs)
        if shade:
            ax.fill_between(y, 1e-12, x, facecolor=color, alpha=alpha)

    return ax


def _kde_support(data, bw, gridsize, cut, clip):
    """Establish support for a kernel density estimate."""
    support_min = max(data.min() - bw * cut, clip[0])
    support_max = min(data.max() + bw * cut, clip[1])
    return np.linspace(support_min, support_max, gridsize)


util.expand_class_attributes(Kde1DView)
util.expand_method_parameters(Kde1DView, Kde1DView.plot)
Example #10
0
        for k in range(len(km.cluster_centers_)):

            x = self.op._scale[self.xchannel].inverse(
                km.cluster_centers_[k][ix])
            y = self.op._scale[self.ychannel].inverse(
                km.cluster_centers_[k][iy])

            plt.plot(x, y, '*', color='blue')

            peak_idx = cluster_peak[k]
            peak = peaks[peak_idx]
            peak_x = xscale.inverse(peak[0])
            peak_y = yscale.inverse(peak[1])

            plt.plot([x, peak_x], [y, peak_y])

        for peak in peaks:
            x = self.op._scale[self.ychannel].inverse(peak[0])
            y = self.op._scale[self.xchannel].inverse(peak[1])
            plt.plot(x, y, 'o', color="magenta")


util.expand_class_attributes(FlowPeaks1DView)
util.expand_method_parameters(FlowPeaks1DView, FlowPeaks1DView.plot)

util.expand_class_attributes(FlowPeaks2DView)
util.expand_method_parameters(FlowPeaks2DView, FlowPeaks2DView.plot)

util.expand_class_attributes(FlowPeaks2DDensityView)
util.expand_method_parameters(FlowPeaks2DDensityView,
                              FlowPeaks2DDensityView.plot)
Example #11
0
    if orient and orient == 'h':
        x = data_scale(x)
    else:
        y = data_scale(y)
            
    plotter = _ViolinPlotter(x, y, hue, data, order, hue_order,
                             bw, cut, scale, scale_hue, gridsize,
                             width, inner, split, dodge, orient, linewidth,
                             color, palette, saturation)

    for i in range(len(plotter.support)):
        if plotter.hue_names is None:       
            if plotter.support[i].shape[0] > 0:
                plotter.support[i] = data_scale.inverse(plotter.support[i])
        else:
            for j in range(len(plotter.support[i])):
                if plotter.support[i][j].shape[0] > 0:
                    plotter.support[i][j] = data_scale.inverse(plotter.support[i][j])

    for i in range(len(plotter.plot_data)):
        plotter.plot_data[i] = data_scale.inverse(plotter.plot_data[i])

    if ax is None:
        ax = plt.gca()

    plotter.plot(ax)
    return ax


util.expand_class_attributes(ViolinPlotView)
util.expand_method_parameters(ViolinPlotView, ViolinPlotView.plot)
Example #12
0
        super().plot(experiment, **kwargs)

    def _grid_plot(self, experiment, grid, xlim, ylim, xscale, yscale,
                   **kwargs):

        kwargs.setdefault('alpha', 0.25)
        kwargs.setdefault('s', 2)
        kwargs.setdefault('marker', 'o')
        kwargs.setdefault('antialiased', True)

        grid.map(plt.scatter, self.xchannel, self.ychannel, **kwargs)

        return {}


util.expand_class_attributes(ScatterplotView)
util.expand_method_parameters(ScatterplotView, ScatterplotView.plot)

if __name__ == '__main__':
    import cytoflow as flow
    tube1 = flow.Tube(file='../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions={"Dox": 10.0})

    tube2 = flow.Tube(file='../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions={"Dox": 1.0})

    ex = flow.ImportOp(conditions={"Dox": "float"}, tubes=[tube1, tube2])

    thresh = flow.ThresholdOp()
    thresh.name = "Y2-A+"
    thresh.channel = 'Y2-A'
Example #13
0
            ax.text(xy[0] + 0.025, xy[1] - 0.025, name,
                    ha='left', va='top', size='small')
        elif xy[0] >= 0.0 and xy[1] >= 0.0:
            ax.text(xy[0] + 0.025, xy[1] + 0.025, name,
                    ha='left', va='bottom', size='small')

    ax.axis('scaled')
    
def _get_necklaces(L):
    import itertools as it

    B = it.combinations(L,2)
    swaplist = [e for e in B]

    unique_necklaces = []
    unique_necklaces.append(L)
    for pair in swaplist:
        necklace = list(L)
        e1 = pair[0]
        e2 = pair[1]
        indexe1 = np.where(L == e1)[0][0]
        indexe2 = np.where(L == e2)[0][0]
        #swap
        necklace[indexe1],necklace[indexe2] = necklace[indexe2], necklace[indexe1]
        unique_necklaces.append(necklace)
    
    return unique_necklaces
    
util.expand_class_attributes(RadvizView)
util.expand_method_parameters(RadvizView, RadvizView.plot)
Example #14
0
            annotations[i] = (self.op._keep_xbins[i],
                              self.op._keep_ybins[i],
                              self.op._histogram[i])
        
        super().plot(experiment,
                     annotations = annotations,
                     xscale = self.op._xscale,
                     yscale = self.op._yscale,
                     **kwargs)
     
    def _annotation_plot(self, 
                         axes, 
                         annotation, 
                         annotation_facet, 
                         annotation_value, 
                         annotation_color, 
                         **kwargs):
        # plot a countour around the bins that got kept
  
        keep_x = annotation[0]
        keep_y = annotation[1]
        h = annotation[2]
        xbins = self.op._xbins[0:-1]
        ybins = self.op._ybins[0:-1]
        last_level = h[keep_x[-1], keep_y[-1]]

        axes.contour(xbins, ybins, h.T, [last_level], colors = 'w')
        
util.expand_class_attributes(DensityGateView)
util.expand_method_parameters(DensityGateView, DensityGateView.plot)
Example #15
0
    out = pd.Series()
    for i in range(len(df.columns) - 1):
        new_series = df.apply(lambda x: [(i, x[i]), (i + 1, x[i + 1])], axis=1)
        out = out.append(new_series)

    lc = matplotlib.collections.LineCollection(out.values,
                                               colors=color,
                                               antialiaseds=aa)
    lc.set_label(label)
    ax.add_collection(lc)

    # have we already annotated these axes?
    if ax in ax_annotations:
        return

    ax_annotations[ax] = True

    x = np.arange(len(df.columns))
    for i in x:
        ax.axvline(i, **axvlines_kwds)

    ax.set_xticks(x)
    ax.set_xticklabels(df.columns)
    ax.set_xlim(x[0], x[-1])
    ax.grid()


util.expand_class_attributes(ParallelCoordinatesView)
util.expand_method_parameters(ParallelCoordinatesView,
                              ParallelCoordinatesView.plot)
Example #16
0
        kws.setdefault("lw", errwidth)
    else:
        kws.setdefault("lw", mpl.rcParams["lines.linewidth"] * 1.8)
         
    if isinstance(confints.iloc[0], tuple):
        ci_lo = [x[0] for x in confints]
        ci_hi = [x[1] for x in confints]
    else:
        ci_lo = [stat.iloc[i] - x for i, x in confints.reset_index(drop = True).items()]
        ci_hi = [stat.iloc[i] + x for i, x in confints.reset_index(drop = True).items()]
 
    for at, lo, hi, color in zip(at_group,
                                 ci_lo,
                                 ci_hi,
                                 colors):
        if orient == "vertical":
            if capsize is not None:
                kws['marker'] = '_'
                kws['markersize'] = capsize * 2
                kws['markeredgewidth'] = kws['lw']
            ax.plot([at, at], [lo, hi], color=color, **kws)
        else:
            if capsize is not None:
                kws['marker'] = '|'
                kws['markersize'] = capsize * 2
                kws['markeredgewidth'] = kws['lw']
            ax.plot([lo, hi], [at, at], color=color, **kws)


util.expand_class_attributes(BarChartView)
util.expand_method_parameters(BarChartView, BarChartView.plot)
Example #17
0
                                       horizOn=True,
                                       vertOn=True,
                                       color='blue',
                                       useblit=True)
            self._cursor.connect_event('button_press_event', self._onclick)
        elif self._cursor:
            self._cursor.disconnect_events()
            self._cursor = None

    def _onclick(self, event):
        """Update the threshold location"""
        self.op.xthreshold = event.xdata
        self.op.ythreshold = event.ydata


util.expand_class_attributes(QuadSelection)
util.expand_method_parameters(QuadSelection, QuadSelection.plot)

if __name__ == '__main__':
    import cytoflow as flow
    tube1 = flow.Tube(file='../../cytoflow/tests/data/Plate01/RFP_Well_A3.fcs',
                      conditions={"Dox": 10.0})

    tube2 = flow.Tube(file='../../cytoflow/tests/data/Plate01/CFP_Well_A4.fcs',
                      conditions={"Dox": 1.0})

    ex = flow.ImportOp(conditions={"Dox": "float"}, tubes=[tube1, tube2])

    r = flow.QuadOp(name="Quad", xchannel="V2-A", ychannel="Y2-A")
    rv = r.default_view(xscale="logicle", yscale="logicle")