Exemple #1
0
    def plot(self, experiment, plot_name=None, **kwargs):
        """
        Parameters
        ----------
        orientation : {'vertical', 'horizontal'}
        
        lim : (float, float)
            Set the range of the plot's axis.
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        data = self._make_data(experiment)

        if not self.variable:
            raise util.CytoflowViewError('variable', "variable not set")

        if self.variable not in experiment.conditions:
            raise util.CytoflowViewError(
                'variable',
                "variable {0} not in the experiment".format(self.variable))

        scale = util.scale_factory(self.scale,
                                   experiment,
                                   statistic=self.statistic,
                                   error_statistic=self.error_statistic)

        super().plot(experiment,
                     data,
                     plot_name=plot_name,
                     scale=scale,
                     **kwargs)
Exemple #2
0
    def plot(self, experiment, **kwargs):
        """
        Parameters
        ----------
        lim : (float, float)
            Set the range of the plot's data axis.
            
        orientation : {'vertical', 'horizontal'}
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        if not self.channel:
            raise util.CytoflowViewError('channel', "Must specify a channel")

        if self.channel not in experiment.data:
            raise util.CytoflowViewError(
                'channel',
                "Channel {0} not in the experiment".format(self.channel))

        # get the scale
        scale = kwargs.pop('scale', None)
        if scale is None:
            scale = util.scale_factory(self.scale,
                                       experiment,
                                       channel=self.channel)

        lim = kwargs.pop("lim", None)

        super().plot(experiment,
                     lim={self.channel: lim},
                     scale={self.channel: scale},
                     **kwargs)
Exemple #3
0
 def plot(self, experiment, plot_name = None, **kwargs):       
     data = self._make_data(experiment)
     
     if not self.variable:
         raise util.CytoflowViewError('variable',
                                      "variable not set")
         
     if self.variable not in experiment.conditions:
         raise util.CytoflowViewError('variable',
                                      "variable {0} not in the experiment"
                                 .format(self.variable))
         
     if util.is_numeric(experiment[self.variable]):
         xscale = util.scale_factory(self.xscale, experiment, condition = self.variable)
     else:
         xscale = None 
     
     yscale = util.scale_factory(self.yscale, 
                                 experiment, 
                                 statistic = self.statistic, 
                                 error_statistic = self.error_statistic)
         
     super().plot(experiment, 
                  data, 
                  plot_name, 
                  xscale = xscale, 
                  yscale = yscale, 
                  **kwargs)
    def plot(self, experiment=None, **kwargs):
        """Plot a faceted histogram view of a channel"""

        if not experiment:
            raise util.CytoflowViewError("No experiment specified")

        if not self.op.controls:
            raise util.CytoflowViewError("No controls specified")

        if not self.op._splines:
            raise util.CytoflowViewError(
                "No splines. Did you forget to call estimate()?")

        kwargs.setdefault('histtype', 'stepfilled')
        kwargs.setdefault('alpha', 0.5)
        kwargs.setdefault('antialiased', True)

        plt.figure()

        channels = self.op._splines.keys()
        num_channels = len(channels)

        for from_idx, from_channel in enumerate(channels):
            for to_idx, to_channel in enumerate(channels):
                if from_idx == to_idx:
                    continue

                # make a little Experiment
                check_tube(self.op.controls[from_channel], experiment)
                tube_exp = ImportOp(
                    tubes=[Tube(file=self.op.controls[from_channel])],
                    name_metadata=experiment.metadata['name_metadata']).apply(
                    )

                # apply previous operations
                for op in experiment.history:
                    tube_exp = op.apply(tube_exp)

                tube_data = tube_exp.data

                plt.subplot(num_channels, num_channels,
                            from_idx + (to_idx * num_channels) + 1)
                plt.xscale('log', nonposx='mask')
                plt.yscale('log', nonposy='mask')
                plt.xlabel(from_channel)
                plt.ylabel(to_channel)
                plt.scatter(tube_data[from_channel],
                            tube_data[to_channel],
                            alpha=0.1,
                            s=1,
                            marker='o')

                spline = self.op._splines[from_channel][to_channel]
                xs = np.logspace(-1, math.log(tube_data[from_channel].max(),
                                              10))

                plt.plot(xs, spline(xs), 'g-', lw=3)

        plt.tight_layout(pad=0.8)
Exemple #5
0
    def plot(self, experiment, **kwargs):
        """
        Plot a violin plot of a variable
        
        Parameters
        ----------
        
        orient : "v" | "h", optional
            Orientation of the plot (vertical or horizontal). 
        
        bw : {{'scott', 'silverman', float}}, optional
            Either the name of a reference rule or the scale factor to use when
            computing the kernel bandwidth. The actual kernel size will be
            determined by multiplying the scale factor by the standard deviation of
            the data within each bin.

        scale : {{"area", "count", "width"}}, optional
            The method used to scale the width of each violin. If ``area``, each
            violin will have the same area. If ``count``, the width of the violins
            will be scaled by the number of observations in that bin. If ``width``,
            each violin will have the same width.
            
        scale_hue : bool, optional
            When nesting violins using a ``hue`` variable, this parameter
            determines whether the scaling is computed within each level of the
            major grouping variable (``scale_hue=True``) or across all the violins
            on the plot (``scale_hue=False``).
            
        gridsize : int, optional
            Number of points in the discrete grid used to compute the kernel
            density estimate.

        inner : {{"box", "quartile", "point", "stick", None}}, optional
            Representation of the datapoints in the violin interior. If ``box``,
            draw a miniature boxplot. If ``quartiles``, draw the quartiles of the
            distribution.  If ``point`` or ``stick``, show each underlying
            datapoint. Using ``None`` will draw unadorned violins.
            
        split : bool, optional
            When using hue nesting with a variable that takes two levels, setting
            ``split`` to True will draw half of a violin for each level. This can
            make it easier to directly compare the distributions.

        """
        
        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")
        
        if not self.variable:
            raise util.CytoflowViewError('variable',
                                         "Variable not specified")
        
        facets = [x for x in [self.xfacet, self.yfacet, self.huefacet, self.variable] if x]
        if len(facets) != len(set(facets)):
            raise util.CytoflowViewError("Can't reuse facets")
        
        super().plot(experiment, **kwargs)
Exemple #6
0
 def plot(self, experiment, **kwargs):
     if not self.huefacet:
         raise util.CytoflowViewError("didn't set BinningOp.name")
     
     try:
         temp_experiment = self.op.apply(experiment)
         super(BinningView, self).plot(temp_experiment, **kwargs)
     except util.CytoflowOpError as e:
         raise util.CytoflowViewError(e.__str__())
    def plot(self, experiment = None, **kwargs):
        """Plot a faceted histogram view of a channel"""

        if not experiment:
            raise util.CytoflowViewError("No experiment specified")

        if not self.op.controls:
            raise util.CytoflowViewError("No controls specified")

        if not self.op.spillover:
            raise util.CytoflowViewError("No spillover matrix specified")

        kwargs.setdefault('histtype', 'stepfilled')
        kwargs.setdefault('alpha', 0.5)
        kwargs.setdefault('antialiased', True)

        plt.figure()

        # the completely arbitrary ordering of the channels
        channels = list(set([x for (x, _) in self.op.spillover.keys()]))
        num_channels = len(channels)

        for from_idx, from_channel in enumerate(channels):
            for to_idx, to_channel in enumerate(channels):
                if from_idx == to_idx:
                    continue

                check_tube(self.op.controls[from_channel], experiment)
                tube_exp = ImportOp(tubes = [Tube(file = self.op.controls[from_channel])],
                                    name_metadata = experiment.metadata['name_metadata']).apply()

                # apply previous operations
                for op in experiment.history:
                    tube_exp = op.apply(tube_exp)

                tube_data = tube_exp.data

                plt.subplot(num_channels,
                            num_channels,
                            from_idx + (to_idx * num_channels) + 1)
                plt.xlim(np.percentile(tube_data[from_channel], (5, 95)))
                plt.ylim(np.percentile(tube_data[to_channel], (5, 95)))
                plt.xlabel(from_channel)
                plt.ylabel(to_channel)
                plt.scatter(tube_data[from_channel],
                            tube_data[to_channel],
                            alpha = 0.1,
                            s = 1,
                            marker = 'o')

                xstart, xstop = np.percentile(tube_data[from_channel], (5, 95))
                xs = np.linspace(xstart, xstop, 2)
                ys = xs * self.op.spillover[(from_channel, to_channel)]

                plt.plot(xs, ys, 'g-', lw=3)

        plt.tight_layout(pad = 0.8)
Exemple #8
0
    def plot(self, experiment):
        """
        Plots the diagnostic view.
        
        Parameters
        ----------
        experiment : Experiment
            The experiment used to create the diagnostic plot.
        
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        channels = list(self.op.units.keys())

        if not channels:
            raise util.CytoflowViewError(None, "No channels to plot")

        if set(channels) != set(self.op._histograms.keys()):
            raise util.CytoflowViewError(
                None, "You must estimate the parameters "
                "before plotting")

        plt.figure()

        for idx, channel in enumerate(channels):
            hist_bins, hist_smooth = self.op._histograms[channel]

            plt.subplot(len(channels), 2, 2 * idx + 1)
            plt.xscale('log')
            plt.xlabel(channel)
            plt.plot(hist_bins[1:], hist_smooth)

            if channel in self.op._peaks and channel in self.op._mefs:
                for peak in self.op._peaks[channel]:
                    plt.axvline(peak, color='r')
                plt.subplot(len(channels), 2, 2 * idx + 2)
                plt.xscale('log')
                plt.yscale('log')
                plt.xlabel(channel)
                plt.ylabel(self.op.units[channel])
                plt.plot(self.op._peaks[channel],
                         self.op._mefs[channel],
                         marker='o')

                xmin, xmax = plt.xlim()
                x = np.logspace(np.log10(xmin), np.log10(xmax))
                plt.plot(x,
                         self.op._calibration_functions[channel](x),
                         color='r',
                         linestyle=':')

        plt.tight_layout(pad=0.8)
Exemple #9
0
    def plot(self, experiment, **kwargs):
        """
        Parameters
        ----------  
        xlim, ylim : (float, float)
            Set the range of the plot's axis.
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        if not self.xchannel:
            raise util.CytoflowViewError('xchannel',
                                         "Must specify an xchannel")

        if self.xchannel not in experiment.data:
            raise util.CytoflowViewError(
                'xchannel',
                "Channel {} not in the experiment".format(self.xchannel))

        if not self.ychannel:
            raise util.CytoflowViewError('ychannel', "Must specify a ychannel")

        if self.ychannel not in experiment.data:
            raise util.CytoflowViewError(
                'ychannel',
                "Channel {} not in the experiment".format(self.ychannel))

        # get the scale
        xscale = kwargs.pop('xscale', None)
        if xscale is None:
            xscale = util.scale_factory(self.xscale,
                                        experiment,
                                        channel=self.xchannel)

        yscale = kwargs.pop('yscale', None)
        if yscale is None:
            yscale = util.scale_factory(self.yscale,
                                        experiment,
                                        channel=self.ychannel)

        xlim = kwargs.pop('xlim', None)
        ylim = kwargs.pop('ylim', None)

        super().plot(experiment,
                     lim={
                         self.xchannel: xlim,
                         self.ychannel: ylim
                     },
                     scale={
                         self.xchannel: xscale,
                         self.ychannel: yscale
                     },
                     **kwargs)
Exemple #10
0
    def default_view(self, **kwargs):
        """
        Returns a diagnostic plot of the Gaussian mixture model.
         
        Returns
        -------
            IView : an IView, call plot() to see the diagnostic plot.
        """
        channels = kwargs.pop('channels', self.channels)
        scale = kwargs.pop('scale', self.scale)
        density = kwargs.pop('density', False)

        for c in channels:
            if c not in self.channels:
                raise util.CytoflowViewError(
                    "Channel {} isn't in the operation's channels".format(c))

        for s in scale:
            if s not in self.channels:
                raise util.CytoflowViewError(
                    "Channel {} isn't in the operation's channels".format(s))

        for c in channels:
            if c not in scale:
                scale[c] = util.get_default_scale()

        if len(channels) == 0:
            raise util.CytoflowViewError(
                "Must specify at least one channel for a default view")
        elif len(channels) == 1:
            return FlowPeaks1DView(op=self,
                                   channel=channels[0],
                                   scale=scale[channels[0]],
                                   **kwargs)
        elif len(channels) == 2:
            if density:
                return FlowPeaks2DDensityView(op=self,
                                              xchannel=channels[0],
                                              ychannel=channels[1],
                                              xscale=scale[channels[0]],
                                              yscale=scale[channels[1]],
                                              **kwargs)
            else:
                return FlowPeaks2DView(op=self,
                                       xchannel=channels[0],
                                       ychannel=channels[1],
                                       xscale=scale[channels[0]],
                                       yscale=scale[channels[1]],
                                       **kwargs)
        else:
            raise util.CytoflowViewError(
                "Can't specify more than two channels for a default view")
Exemple #11
0
    def plot(self, experiment, **kwargs):
        """
        Plot a faceted histogram view of a channel
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        if not self.op.channels:
            raise util.CytoflowViewError('op', "No channels specified")

        if not self.op._af_median:
            raise util.CytoflowViewError(
                'op', "Autofluorescence values aren't set. Did "
                "you forget to run estimate()?")

        if not set(self.op._af_median.keys()) <= set(experiment.channels) or \
           not set(self.op._af_stdev.keys()) <= set(experiment.channels) or \
           not set(self.op._af_histogram.keys()) <= set(experiment.channels):
            raise util.CytoflowViewError(
                'op', "Autofluorescence estimates aren't set, or are "
                "different than those in the experiment "
                "parameter. Did you forget to run estimate()?")

        if not set(self.op._af_median.keys()) == set(self.op._af_stdev.keys()):
            raise util.CytoflowOpError(
                'op', "Median and stdev keys are different! "
                "What the heck happened?!")

        if not set(self.op.channels) == set(self.op._af_median.keys()):
            raise util.CytoflowOpError(
                'channels', "Estimated channels differ from the channels "
                "parameter.  Did you forget to (re)run estimate()?")

        import matplotlib.pyplot as plt

        plt.figure()

        for idx, channel in enumerate(self.op.channels):
            hist, bin_edges = self.op._af_histogram[channel]
            hist = hist[1:-1]
            bin_edges = bin_edges[1:-1]
            plt.subplot(len(self.op.channels), 1, idx + 1)
            plt.title(channel)
            plt.bar(bin_edges[:-1],
                    hist,
                    width=bin_edges[2] - bin_edges[1],
                    linewidth=0)
            plt.axvline(self.op._af_median[channel], color='r')

        plt.tight_layout(pad=0.8)
Exemple #12
0
    def enum_plots(self, experiment, data):
        """
        Enumerate the named plots we can make from this set of statistics.
        
        Returns
        -------
        iterator
            An iterator across the possible plot names. The iterator ALSO has an instance
            attribute called :attribute::`by`, which holds a list of the facets that are
            not yet set (and thus need to be specified in the plot name.)
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        if not self.variable:
            raise util.CytoflowViewError('variable', "variable not set")

        if self.variable not in experiment.conditions:
            raise util.CytoflowViewError(
                'variable',
                "variable {0} not in the experiment".format(self.variable))

        data, facets, names = self._subset_data(data)

        by = list(set(names) - set(facets))

        class plot_enum(object):
            def __init__(self, data, by):
                self.by = by
                self._iter = None
                self._returned = False

                if by:
                    self._iter = data.groupby(by).__iter__()

            def __iter__(self):
                return self

            def __next__(self):
                if self._iter:
                    return next(self._iter)[0]
                else:
                    if self._returned:
                        raise StopIteration
                    else:
                        self._returned = True
                        return None

        return plot_enum(data.reset_index(), by)
Exemple #13
0
    def default_view(self, **kwargs):
        """
        Returns a diagnostic plot of the k-means clustering.
         
        Returns
        -------
            IView : an IView, call :meth:`KMeans1DView.plot` to see the diagnostic plot.
        """
        channels = kwargs.pop('channels', self.channels)
        scale = kwargs.pop('scale', self.scale)

        for c in channels:
            if c not in self.channels:
                raise util.CytoflowViewError(
                    'channels',
                    "Channel {} isn't in the operation's channels".format(c))

        for s in scale:
            if s not in self.channels:
                raise util.CytoflowViewError(
                    'scale',
                    "Channel {} isn't in the operation's channels".format(s))

        for c in channels:
            if c not in scale:
                scale[c] = util.get_default_scale()

        if len(channels) == 0:
            raise util.CytoflowViewError(
                'channels',
                "Must specify at least one channel for a default view")
        elif len(channels) == 1:
            v = KMeans1DView(op=self)
            v.trait_set(channel=channels[0],
                        scale=scale[channels[0]],
                        **kwargs)
            return v

        elif len(channels) == 2:
            v = KMeans2DView(op=self)
            v.trait_set(xchannel=channels[0],
                        ychannel=channels[1],
                        xscale=scale[channels[0]],
                        yscale=scale[channels[1]],
                        **kwargs)
            return v

        else:
            raise util.CytoflowViewError(
                'channels',
                "Can't specify more than two channels for a default view")
Exemple #14
0
    def enum_plots(self, experiment):
        """
        Returns an iterator over the possible plots that this View can
        produce.  The values returned can be passed to "plot".
        """

        if self.xfacet and self.xfacet not in experiment.conditions:
            raise util.CytoflowViewError(
                "X facet {} not in the experiment".format(self.xfacet))

        if self.xfacet and self.xfacet not in self.op.by:
            raise util.CytoflowViewError(
                "X facet {} must be in GaussianMixture1DOp.by, which is {}".
                format(self.xfacet, self.op.by))

        if self.yfacet and self.yfacet not in experiment.conditions:
            raise util.CytoflowViewError(
                "Y facet {0} not in the experiment".format(self.yfacet))

        if self.yfacet and self.yfacet not in self.op.by:
            raise util.CytoflowViewError(
                "Y facet {} must be in GaussianMixture1DOp.by, which is {}".
                format(self.yfacet, self.op.by))

        for b in self.op.by:
            if b not in experiment.data:
                raise util.CytoflowOpError("Aggregation metadata {0} not found"
                                           " in the experiment".format(b))

        class plot_enum(object):
            def __init__(self, view, experiment):
                self._iter = None
                self._returned = False

                if view._by:
                    self._iter = experiment.data.groupby(view._by).__iter__()

            def __iter__(self):
                return self

            def next(self):
                if self._iter:
                    return self._iter.next()[0]
                else:
                    if self._returned:
                        raise StopIteration
                    else:
                        self._returned = True
                        return None

        return plot_enum(self, experiment)
    def plot(self, experiment, plot_name=None, **kwargs):

        if plot_name not in [
                "Morphology", "Autofluorescence", "Bleedthrough",
                "Bead Calibration", "Color Translation"
        ]:
            raise util.CytoflowViewError(
                "Which plot do you want?  Must be one "
                "of \"Morphology\", \"Autofluorescence\", "
                "\"Bleedthrough\", \"Bead Calibration\", "
                "or \"Color Translation\"")

        if not self.op._blank_exp:
            raise util.CytoflowViewError(
                "Must set at least the blank control file!")

        new_ex = self.op._blank_exp.clone()

        if plot_name == "Morphology":
            if not self._polygon_view:
                self._polygon_view = self.op._polygon_op.default_view()

            self._polygon_view.plot(new_ex, **kwargs)

            return
        else:
            new_ex = self.op._polygon_op.apply(new_ex)

        if plot_name == "Autofluorescence":
            self.op._af_op.default_view().plot(new_ex, **kwargs)
            return
        else:
            new_ex = self.op._af_op.apply(new_ex)

        if plot_name == "Bleedthrough":
            self.op._bleedthrough_op.default_view().plot(new_ex, **kwargs)
            return
        else:
            new_ex = self.op._bleedthrough_op.apply(new_ex)

        if plot_name == "Bead Calibration":
            self.op._bead_calibration_op.default_view().plot(new_ex, **kwargs)
            return
        else:
            new_ex = self.op._bead_calibration_op.apply(new_ex)

        if plot_name == "Color Translation":
            self.op._color_translation_op.default_view().plot(new_ex, **kwargs)
Exemple #16
0
    def plot(self, experiment, **kwargs):
        """
        Plot the plots.
        
        Parameters
        ----------
        
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

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

        if self.channel in self.op._scale:
            scale = self.op._scale[self.channel]
        else:
            scale = util.scale_factory(self.scale,
                                       experiment,
                                       channel=self.channel)

        super(FlowPeaks1DView, view).plot(experiment,
                                          annotation_facet=self.op.name,
                                          annotation_trait=trait_name,
                                          annotations=self.op._kmeans,
                                          scale=scale,
                                          **kwargs)
Exemple #17
0
    def plot(self, experiment, **kwargs):
        """
        Parameters
        ----------
        color : matplotlib color
            The color to plot the annotations.  Overrides the default color
            cycle.
        """
        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        annotation_facet = kwargs.pop('annotation_facet', None)
        annotation_trait = kwargs.pop('annotation_trait', None)

        if annotation_facet is not None and annotation_facet in experiment.data:
            if annotation_trait:
                self.trait_set(**{annotation_trait: annotation_facet})
            elif not self.huefacet:
                warn("Setting 'huefacet' to '{}'".format(annotation_facet),
                     util.CytoflowViewWarning)
                annotation_trait = 'huefacet'
                self.trait_set(**{'huefacet': annotation_facet})

        super().plot(experiment, annotation_facet=annotation_facet, **kwargs)
Exemple #18
0
    def plot(self, experiment, **kwargs):
        """
        Plot a faceted parallel coordinates plot
        
        Parameters
        ----------
        
        alpha : float (default = 0.02)
            The alpha blending value, between 0 (transparent) and 1 (opaque).

        axvlines_kwds : dict
            A dictionary of parameters to pass to `ax.axvline <https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.axvline.html>`_

        
        Notes
        -----
        This uses a low-level API for speed; there are far fewer visual options
        that with other views.
  
        """

        if len(self.channels) < 3:
            raise util.CytoflowViewError('channels',
                                         "Must have at least 3 channels")

        super().plot(experiment, **kwargs)

        # clean up the plot
        for ax in plt.gcf().get_axes():
            ax.set_xlabel("")
            ax.set_ylabel("")
            ax.get_yaxis().set_ticks([])
Exemple #19
0
   def plot(self, experiment, **kwargs):
       """
       Plot a faceted Radviz plot
       
       Parameters
       ----------
       
       alpha : float (default = 0.25)
           The alpha blending value, between 0 (transparent) and 1 (opaque).
           
       s : int (default = 2)
           The size in points^2.
           
       marker : a matplotlib marker style, usually a string
           Specfies the glyph to draw for each point on the scatterplot.
           See `matplotlib.markers <http://matplotlib.org/api/markers_api.html#module-matplotlib.markers>`_ for examples.  Default: 'o'
                   
       Notes
       -----
       Other ``kwargs`` are passed to `matplotlib.pyplot.scatter <https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.scatter.html>`_
 
       """
       
       
       if len(self.channels) < 3:
           raise util.CytoflowViewError('channels',
                                        "Must have at least 3 channels")
       
       super().plot(experiment, **kwargs)
Exemple #20
0
    def plot(self, experiment, plot_name=None, **kwargs):
        """
        Parameters
        ----------
        xlim, ylim : (float, float)
            Set the range of the plot's axis.
            
        """
        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        data = self._make_data(experiment)

        xscale = util.scale_factory(self.xscale,
                                    experiment,
                                    statistic=self.xstatistic,
                                    error_statistic=self.x_error_statistic)

        yscale = util.scale_factory(self.yscale,
                                    experiment,
                                    statistic=self.ystatistic,
                                    error_statistic=self.y_error_statistic)

        super().plot(experiment,
                     data,
                     plot_name,
                     xscale=xscale,
                     yscale=yscale,
                     **kwargs)
Exemple #21
0
    def plot(self, experiment, **kwargs):
        """
        Plot the plots.
        
        Parameters
        ----------
        """
        
        if experiment is None:
            raise util.CytoflowViewError('experiment', "No experiment specified")
        
        if self.op.num_components == 1:
            annotation_facet = self.op.name + "_1"
        else:
            annotation_facet = self.op.name
        
        view, trait_name = self._strip_trait(self.op.name)
        
        if self.scale:
            scale = self.op._scale
        else:
            scale = util.scale_factory(self.scale, experiment, channel = self.channel)

    
        super(GaussianMixture1DView, view).plot(experiment,
                                                annotation_facet = annotation_facet,
                                                annotation_trait = trait_name,
                                                annotations = self.op._gmms,
                                                scale = scale,
                                                **kwargs)
Exemple #22
0
    def plot(self, experiment, data, plot_name = None, **kwargs):
        """
        Plot some data from a statistic.
        
        This function takes care of checking for facet name validity and 
        subsetting, then passes the dataframe to `BaseView.plot`
        """
        
        if not self.variable:
            raise util.CytoflowViewError('variable',
                                         "variable not set")
            
        if self.variable not in experiment.conditions:
            raise util.CytoflowViewError('variable',
                                         "variable {0} not in the experiment"
                                    .format(self.variable))
            
        data, facets, names = self._subset_data(data)

        unused_names = list(set(names) - set(facets))

        if plot_name is not None and not unused_names:
            raise util.CytoflowViewError('plot_name',
                                         "You specified a plot name, but all "
                                         "the facets are already used")
        
        if unused_names:
            groupby = data.groupby(unused_names)

            if plot_name is None:
                raise util.CytoflowViewError('plot_name',
                                             "You must use facets {} in either the "
                                             "plot variables or the plot name. "
                                             "Possible plot names: {}"
                                             .format(unused_names, list(groupby.groups.keys())))

            if plot_name not in set(groupby.groups.keys()):
                raise util.CytoflowViewError('plot_name',
                                             "Plot {} not from plot_enum; must "
                                             "be one of {}"
                                             .format(plot_name, list(groupby.groups.keys())))
                
            data = groupby.get_group(plot_name)
        
        # FacetGrid needs a "long" data set
        data.reset_index(inplace = True)
        super().plot(experiment, data, **kwargs)
Exemple #23
0
    def _make_data(self, experiment):
        if experiment is None:
            raise util.CytoflowViewError('experiment', "No experiment specified")
        
        if not self.statistic:
            raise util.CytoflowViewError('statistic', "Statistic not set")
        
        if self.statistic not in experiment.statistics:
            raise util.CytoflowViewError('statistic',
                                         "Can't find the statistic {} in the experiment"
                                         .format(self.statistic))
        else:
            stat = experiment.statistics[self.statistic]
            
        if not util.is_numeric(stat):
            raise util.CytoflowViewError('statistic',
                                         "Statistic must be numeric")
            
        if self.error_statistic[0]:
            if self.error_statistic not in experiment.statistics:
                raise util.CytoflowViewError('error_statistic',
                                             "Can't find the error statistic in the experiment")
            else:
                error_stat = experiment.statistics[self.error_statistic]
        else:
            error_stat = None
         
        if error_stat is not None:

            if set(stat.index.names) != set(error_stat.index.names):
                raise util.CytoflowViewError('error_statistic',
                                             "Data statistic and error statistic "
                                             "don't have the same index.")
                
            try:
                error_stat.index = error_stat.index.reorder_levels(stat.index.names)
                error_stat.sort_index(inplace = True)
            except AttributeError:
                pass
            
            if not stat.index.equals(error_stat.index):
                raise util.CytoflowViewError('error_statistic',
                                             "Data statistic and error statistic "
                                             " don't have the same index.")
               
            if stat.name == error_stat.name:
                raise util.CytoflowViewError('error_statistic',
                                             "Data statistic and error statistic can "
                                             "not have the same name.")
               
        data = pd.DataFrame(index = stat.index)
        data[stat.name] = stat
        
        if error_stat is not None:
            data[error_stat.name] = error_stat
            
        return data
Exemple #24
0
    def enum_plots(self, experiment, data):
        """
        Enumerate the named plots we can make from this set of statistics.
        """
        
        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")
        
        if not self.variable:
            raise util.CytoflowViewError('variable',
                                         "variable not set")
            
        if self.variable not in experiment.conditions:
            raise util.CytoflowViewError('variable',
                                         "variable {0} not in the experiment"
                                    .format(self.variable))
            
        data, facets, names = self._subset_data(data)

        by = list(set(names) - set(facets))
        
        class plot_enum(object):
            
            def __init__(self, data, by):
                self.by = by
                self._iter = None
                self._returned = False
                
                if by:
                    self._iter = data.groupby(by).__iter__()
                
            def __iter__(self):
                return self
            
            def __next__(self):
                if self._iter:
                    return next(self._iter)[0]
                else:
                    if self._returned:
                        raise StopIteration
                    else:
                        self._returned = True
                        return None
            
        return plot_enum(data.reset_index(), by)
Exemple #25
0
    def plot(self, experiment, **kwargs):
        """
        Plot the plots.
        
        Parameters
        ----------
        """

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        annotations = {}
        for k in self.op._kmeans:
            annotations[k] = (self.op._kmeans[k], self.op._peaks[k],
                              self.op._cluster_peak[k])

        if self.xchannel in self.op._scale:
            xscale = self.op._scale[self.xchannel]
        else:
            xscale = util.scale_factory(self.xscale,
                                        experiment,
                                        channel=self.xchannel)

        if self.ychannel in self.op._scale:
            yscale = self.op._scale[self.ychannel]
        else:
            yscale = util.scale_factory(self.yscale,
                                        experiment,
                                        channel=self.ychannel)

        if not self.op._kmeans:
            raise util.CytoflowViewError(
                None, "Must estimate a model before plotting "
                "the density plot.")

        for k in self.op._kmeans:
            annotations[k] = (self.op._kmeans[k], self.op._peaks[k],
                              self.op._cluster_peak[k], self.op._density[k])

        super().plot(experiment,
                     annotations=annotations,
                     xscale=xscale,
                     yscale=yscale,
                     **kwargs)
Exemple #26
0
    def _subset_data(self, data):

        if self.subset:
            try:
                # TODO - either sanitize column names, or check to see that
                # all conditions are valid Python variables
                data = data.query(self.subset)
            except Exception as e:
                raise util.CytoflowViewError(
                    'subset', "Subset string '{0}' isn't valid".format(
                        self.subset)) from e

            if len(data) == 0:
                raise util.CytoflowViewError(
                    'subset', "Subset string '{0}' returned no values".format(
                        self.subset))

        names = list(data.index.names)

        for name in names:
            unique_values = data.index.get_level_values(name).unique()
            if len(unique_values) == 1:
                warn("Only one value for level {}; dropping it.".format(name),
                     util.CytoflowViewWarning)
                try:
                    data.index = data.index.droplevel(name)
                except AttributeError as e:
                    raise util.CytoflowViewError(
                        None, "Must have more than one "
                        "value to plot.") from e

        names = list(data.index.names)

        if self.xfacet and self.xfacet not in data.index.names:
            raise util.CytoflowViewError(
                'xfacet',
                "X facet {} not in statistics; must be one of {}".format(
                    self.xfacet, data.index.names))

        if self.yfacet and self.yfacet not in data.index.names:
            raise util.CytoflowViewError(
                'yfacet',
                "Y facet {} not in statistics; must be one of {}".format(
                    self.yfacet, data.index.names))

        if self.huefacet and self.huefacet not in data.index.names:
            raise util.CytoflowViewError(
                'huefacet',
                "Hue facet {} not in statistics; must be one of {}".format(
                    self.huefacet, data.index.names))

        facets = [
            x
            for x in [self.variable, self.xfacet, self.yfacet, self.huefacet]
            if x
        ]
        if len(facets) != len(set(facets)):
            raise util.CytoflowViewError(None, "Can't reuse facets")

        return data, facets, names
Exemple #27
0
    def enum_plots_wi(self, wi):
        if not self.plotfacet:
            return iter([])

        if self.plotfacet and self.plotfacet not in wi.result.conditions:
            raise util.CytoflowViewError(
                "Plot facet {0} not in the experiment".format(self.huefacet))
        values = np.sort(pd.unique(wi.result[self.plotfacet]))
        return iter(values)
Exemple #28
0
    def plot(self, experiment, **kwargs):
        """Plot the histogram and then plot the threshold on top of it."""

        if not experiment:
            raise util.CytoflowViewError("No experiment specified")

        if self.xfacet:
            raise util.CytoflowViewError(
                "ThresholdSelection.xfacet must be empty")

        if self.yfacet:
            raise util.CytoflowViewError(
                "ThresholdSelection.yfacet must be empty")

        super(ThresholdSelection, self).plot(experiment, **kwargs)
        self._ax = plt.gca()
        self._draw_threshold()
        self._interactive()
Exemple #29
0
    def plot(self, experiment, plot_name=None, **kwargs):

        if experiment is None:
            raise util.CytoflowViewError("No experiment specified")

        if self.plotfacet and plot_name is not None:
            experiment = experiment.subset(self.plotfacet, plot_name)

        HistogramView.plot(self, experiment, **kwargs)
Exemple #30
0
    def plot(self, experiment, **kwargs):
        """Plot the underlying histogram and then plot the selection on top of it."""

        if not experiment:
            raise util.CytoflowViewError("No experiment specified")

        if self.xfacet:
            raise util.CytoflowViewError(
                "RangeSelection.xfacet must be empty or `Undefined`")

        if self.yfacet:
            raise util.CytoflowViewError(
                "RangeSelection.yfacet must be empty or `Undefined`")

        super(RangeSelection, self).plot(experiment, **kwargs)
        self._ax = plt.gca()
        self._draw_span()
        self._interactive()