class ComparisonIntegrationResult(IntegrationResultBase):
    headers = [
        'Excitation WL', 'Counts 1st', 'Counts 2nd', 'Counts Subtraction'
    ]
    #save_data = Button('Export Data') #Action(name = 'Export', action = 'save_data')

    #table_fmt = Enum(['plain', 'simple', 'grid', 'fancy_grid', 'pipe','orgtbl','rst','mediawiki','html', 'latex', 'latex_booktabs',])
    #fmt = Str('e')
    #ndec = Int(2)
    #float_fmt = Property(Str)

    view = View(
        VGroup(
            HGroup(
                Item(
                    name='int_range',
                    label='Integration Range',
                    style='readonly',
                ), ),
            HGroup(
                #Item(name='save_type', show_label=False),
                Item(name='export', show_label=False),
                #Item(name='table_fmt', label='Table Format',enabled_when='save_type=="Text"'),
                #Item(name='fmt',editor=EnumEditor(values={'f':'Regular', 'e':'Exponential'}), label='Number Format'),
                #Item(name='ndec', label='Decimals'),
            ),
            Group(
                Item(
                    'results',
                    show_label=False,
                    editor=ArrayViewEditor(
                        titles=[
                            'Excitation WL', '1st Exp. (BG corrected)',
                            '2nd Exp. (BG corrected)',
                            'Subtraction (BG corrected)'
                        ],
                        format='%.2e',
                        show_index=False,
                        # Font fails with wx in OSX;
                        #   see traitsui issue #13:
                        # font   = 'Arial 8'
                    )),
                show_border=True,
                label='Results'),
        ),

        #handler=IntegrationResultBaseHandler(),
        resizable=True,
        scrollable=True,
    )

    # def _get_float_fmt(self):
    #return '.{}{}'.format(self.ndec,self.fmt)

    def _results_default(self):
        return np.asarray([[0.0, 0.0, 0.0, 0.0]] * 4)
Пример #2
0
class NpyData(HasTraits):
    data = Array()
    def _data_default(self):
        return np.empty(1)
    traits = View(
                Item('data',
                        show_label=False,
                        editor=ArrayViewEditor(format='%.4f',
                                               )
                    ),
                )
Пример #3
0
class DataSheet(HasStrictTraits):

    data = Array(np.float_)

    view = View(Item('data',
                     show_label=False,
                     resizable=True,
                     editor=ArrayViewEditor(
                         titles=['x', 'y', 'z'],
                         format='%.4f',
                     )),
                width=0.5,
                height=0.6)
Пример #4
0
class DataSheet(HasStrictTraits):

    data = Array(np.float_)

    view = View(
        Item(
            'data',
            show_label=False,
            resizable=True,
            editor=ArrayViewEditor(
                titles=['x', 'y', 'z'],
                format='%.4f',
                # Font fails with wx in OSX;
                #   see traitsui issue #13:
                # font   = 'Arial 8'
            )),
        width=0.5,
        height=0.6)
Пример #5
0
class ShowArray(HasTraits):

    data = Array

    view = View(
        Item(
            'data',
            show_label=False,
            editor=ArrayViewEditor(
                titles=['x', 'y', 'z'],
                format='%.4f',
                # Font fails with wx in OSX;
                #   see traitsui issue #13:
                # font   = 'Arial 8'
            )),
        title='Array Viewer',
        width=0.3,
        height=0.8,
        resizable=True)
Пример #6
0
class ArrayViewer(HasTraits):

    data = Array

    view = View(
        Item(
            'data',
            show_label=False,
            editor=ArrayViewEditor(
                titles=['Wavelength', 'Counts'],
                format='%.2f',
                show_index=False,
                # Font fails with wx in OSX;
                #   see traitsui issue #13:
                # font   = 'Arial 8'
            )),
        title='Array Viewer',
        width=0.3,
        height=0.8,
        resizable=True)
Пример #7
0
    class ATree(HasTraits):
        h5_tree = Instance(Hdf5FileNode)
        node = Any
        data=Array


        traits_view =View(
            Group(
                Item('h5_tree',
                    editor = _hdf5_tree_editor(selected='node'),
                    resizable =True,

                    ),
                Item('data', editor=ArrayViewEditor(titles = [ 'data' ],
                                           format = '%s')),
                orientation = 'horizontal',

                ),
            title = 'HDF5 Tree Example',
            buttons = [ 'Undo', 'OK', 'Cancel' ],
            resizable = True,
            width = .5,
            height = .3
            )

        def _node_changed(self):
            print self.node.path

            #print self.node.contents
            if isinstance(self.node, Hdf5ArrayNode):
                print self.node.contents
                for item in self.node.contents:
                    print type(item)
                    print shape(item)
                    break
                self.data=self.node.contents
class MeasurementAnalysisTool(AnalysisToolBase):
    measurement = Any()

    calc_data_names = List(
        ['bg_corrected', 'bg', 'ref', 'signal']
    )  # values = [('bg_corrected','BG Corrected'),(,'Signal'), (,'Background'), (,'Reference')]

    view = View(
        HSplit(
            VGroup(
                HGroup(
                    Item(
                        name='calc_type',
                        label='Statistic scope',
                    ),
                    Item(name='rolling_statistic',
                         label='Statistic',
                         visible_when="calc_type=='Rolling Window'"),
                    Item(name='global_statistic',
                         label='Statistic',
                         visible_when="calc_type=='Global'"),
                ),
                HGroup(
                    Item(name='calc_data_names',
                         label='Data to use',
                         style='custom',
                         editor=CheckListEditor(cols=4,
                                                values=[('bg_corrected',
                                                         'BG Corrected'),
                                                        ('signal', 'Signal'),
                                                        ('bg', 'Background'),
                                                        ('ref', 'Reference')
                                                        ])), ),
                HGroup(
                    Item(name='window_size',
                         label='Window',
                         enabled_when="calc_type=='Rolling Window'"),
                    Item(name='bin', label='Bin Data'),
                    Item(name='nbins', label='Bins', enabled_when='bin'),
                    Item(name='round_wl', label='Round WLs'),
                ),
                HGroup(
                    Item(
                        name='calc',
                        show_label=False,
                    ),
                    Item(name='calc_on_result', label='Perform on result'),
                    spring,
                    Item(name='export_result',
                         show_label=False,
                         enabled_when='has_result'),
                ),
                Item(name='result_array',
                     show_label=False,
                     style='custom',
                     editor=ArrayViewEditor(
                         titles=[
                             'BG corrected', 'Signal', 'Background',
                             'Reference'
                         ],
                         format='%g',
                         show_index=False,
                     )),
            ),
            VGroup(
                HGroup(
                    Item(name='plot_what', label='Data to plot'),
                    Item(name='plot_type',
                         label='Statistic',
                         enabled_when="plot_what=='Statistic'"),
                    Item(name='result_plot_type',
                         show_label=False,
                         visible_when="plot_what=='Result Table'"),
                ),
                HGroup(
                    Item(
                        name='clear_plot',
                        label='Clear Previous',
                    ),
                    Item(name='subplots',
                         label='Sub Plots',
                         enabled_when="plot_what=='Result Table'"),
                    spring,
                    Item(
                        name='alpha',
                        label='Opacity',
                    ),
                    Item(
                        name='hist_bins',
                        label='Bins',
                        visible_when=
                        "(plot_what=='Result Table' and result_plot_type=='Hist')"
                        " or (plot_what=='Statistic' and plot_type=='hist')"),
                ),
                HGroup(
                    Item(
                        name='plot',
                        show_label=False,
                    ),
                    Item(
                        name='plot_data',
                        label='Data',
                    ),
                ),
                Item(name='display',
                     show_label=False,
                     style='custom',
                     springy=False),
            ),
            #show_border=True, label='Analysis'
        ), )

    def __init__(self, measurement):
        super(MeasurementAnalysisTool, self).__init__()
        self.measurement = measurement

    def _plot_fired(self):
        if self.clear_plot:
            self.display.clear_plots()
        if self.display.axs is None:
            ax = self.display.add_subplots(1)[0]
        elif len(self.display.axs):
            ax = self.display.axs[0]
        else:
            ax = self.display.add_subplots(1)[0]

        if self.plot_what in [
                'bg_corrected',
                'signal',
                'bg',
                'ref',
        ]:
            self.measurement.plot_data(ax=ax, data_name=self.plot_what)

        elif self.plot_what == 'Result Table':
            if self.result_plot_type == 'Lines':
                self.calc_result.plot(ax=ax, subplots=self.subplots)
            elif self.result_plot_type == 'Area':
                self.calc_result.plot.area(ax=ax,
                                           subplots=self.subplots,
                                           stacked=False,
                                           alpha=self.alpha)
            elif self.result_plot_type == 'Hist':
                self.calc_result.plot.hist(ax=ax,
                                           subplots=self.subplots,
                                           stacked=False,
                                           alpha=self.alpha,
                                           bins=self.hist_bins)

        elif self.plot_what == 'Statistic':
            if self.plot_type == 'kde':
                self.measurement.plot_by_name(ax=ax,
                                              plot_name=self.plot_type,
                                              data_name=self.plot_data)

            elif self.plot_type == 'hist':
                self.measurement.plot_by_name(ax=ax,
                                              plot_name=self.plot_type,
                                              data_name=self.plot_data,
                                              bins=self.hist_bins)

            elif self.plot_type in ['lag', 'autocorrelation']:
                self.measurement.plot_special(ax=ax,
                                              plot_name=self.plot_type,
                                              data_name=self.plot_data)

        elif self.plot_what == 'Scatter Matrix':
            self.measurement.plot_scatter_matrix(ax=ax,
                                                 plot_name=self.plot_type)

        ax.relim()
        ax.autoscale_view()
        self.display.figure.canvas.draw()

    def _calc_fired(self):
        final = pd.DataFrame(columns=['bg_corrected', 'signal', 'bg', 'ref'])
        if self.calc_on_result:
            df = self.calc_result
        else:
            df = self.measurement.create_dataframe(
                data_names=self.calc_data_names,
                bin=self.bin,
                nbins=self.nbins,
                round_wl=self.round_wl)
        if self.calc_type == 'Rolling Window':
            r = df.rolling(window=self.window_size)

            results = getattr(r, self.rolling_statistic)()

        elif self.calc_type == 'Global':
            results = calc_df_statistics(
                df,
                statistic=self.global_statistic,
            )

        for col in results:
            final[col] = results[col]
        final.dropna(how='all', inplace=True)
        self.calc_result = final
        self.result_array = final.as_matrix()
        if len(self.result_array) > 1:
            self.has_result = True
Пример #9
0
class FittingTool1D(FittingToolBase):
    measurements = List([])
    view = View(
        VGroup(
            VGroup(
                HGroup(Item(
                    name='editing',
                    style='custom',
                    label='Edit',
                ),
                       Item(
                           name='clear',
                           show_label=False,
                       ),
                       Item(
                           name='clear_fits',
                           show_label=False,
                       ),
                       Item(name='refresh', show_label=False),
                       Item(name='message',
                            style='readonly',
                            show_label=False,
                            springy=True),
                       spring,
                       Item(
                           name='perform_fit',
                           show_label=False,
                       ),
                       show_border=True,
                       label='Region Selection'),
                Group(Item(name='display', style='custom', show_label=False),
                      show_border=True,
                      label='Plots'),
            ),
            VGroup(
                Group(Item(name='fits_list',
                           show_label=False,
                           editor=ArrayViewEditor(
                               titles=[
                                   'Wavelength',
                                   'Amplitude',
                                   'Mean',
                                   'Sigma',
                                   'Integral',
                               ],
                               format='%g',
                               show_index=False,
                           )),
                      show_border=True,
                      label='Fits',
                      scrollable=True), ),
        ),
        buttons=['OK'],
        title='Fitting Tool',
        kind='live',
        scrollable=True,
        resizable=True,
        height=800,
        width=1200,
    )

    def __init__(self, measurements, **kwargs):
        super(FittingTool1D, self).__init__()
        self.name = kwargs.get('name', 'Fitting Plots')
        self.measurements = measurements
        #self.refresh_display()

    def _display_default(self):
        return FittingDataPlot1D()

    def _fits_list_default(self):
        return np.asarray([[0.0, 0.0, 0.0, 0.0, 0.0]])

    def _fitter_default(self):
        return SpectrumFitter1D()

    def _perform_fit_fired(self):
        if self.has_peaks and self.has_frange:
            self.message = ' '
        else:
            if self.has_peaks:
                self.message = 'Please select a Fit Range'
            elif self.has_frange:
                self.message = 'Please select Peaks'
            else:
                self.message = 'Please select Peaks and a Fit Range '
            return
        peaks = []
        for xmin, xmax in self.display.peaks:
            if xmax - xmin > 1:
                peaks.append((xmin, xmax))
        if len(peaks) == 0:
            self.message = 'Please select Peaks'
            return
        fitter = SpectrumFitter1D(peaks=peaks)
        frange = self.display.frange
        for meas in self.measurements:
            data = meas.bg_corrected
            data = data[np.where(
                np.logical_and(data[:, 0] >= frange[0],
                               data[:, 0] <= frange[1]))]
            if len(data) == 0:
                continue
            data = pad_with_zeros(data, frange[0], frange[1])
            fitter.xdata, fitter.ydata = data[:, 0], data[:, 1]
            fitter.perform_fit()
            if fitter.fit_success:
                for fit in fitter.p.reshape(fitter.nexp, 3):
                    meas.fits.append(fit)
        self.refresh_display()

    def _clear_fits_fired(self):
        for meas in self.measurements:
            meas.fits = []
        self.refresh_display()

    def get_fits_list(self):
        def keyf(data):
            return data[0], data[2]

        fits = []
        for meas in self.measurements:
            if len(meas.fits):
                fits.extend([[
                    meas.ex_wl, a, m, s,
                    gaussian_integral(meas.ex_wl, 1000, a, m, s,
                                      meas.resolution)
                ] for a, m, s in meas.fits])
        if len(fits):
            return np.asarray(sorted(fits, key=keyf))
        else:
            return np.asarray([[0.0, 0.0, 0.0, 0.0, 0.0]])

    def _refresh_fired(self):
        self.refresh_display()

    def _clear_fired(self):
        self.display.clear_selections()
        self.refresh_display()
        self.display.configure_selector(peaks=True)

    def refresh_display(self):
        self.fits_list = self.get_fits_list()
        self.display.remove_subplots()
        self.display.add_subplots(self.display.nplots)
        if len(self.display.axs):
            for meas in self.measurements:
                meas.plot_data(ax=self.display.axs[0], legend=False)
                #meas.plot_fits(ax=self.display.axs[1], legend=False, frange=self.display.frange)
        self.set_titles()
        self.display.draw()
        self.display.configure_selector()

    def set_titles(self):
        self.display.set_title(self.name, size=12, y=1.0)
        if len(self.display.axs):
            self.display.axs[0].set_title('BG Corrected Data', fontsize=11)
            self.display.axs[1].set_title('Fits', fontsize=11)

            self.display.axs[0].set_xlabel('')
            self.display.axs[1].set_xlabel('Emission Wavelength')
            self.display.axs[0].set_ylabel('Counts')
            self.display.axs[1].set_ylabel('Counts')
Пример #10
0
class FittingTool2D(FittingToolBase):

    experiment = Any()

    interp_method = Enum('linear', ['cubic', 'linear', 'nearest'])
    nlevel = Int(70)
    set_levels = Enum('log', ['linear', 'log'])
    level_range = Tuple((1e0, 1e5), cols=2, labels=['min', 'max'])

    view = View(
        VGroup(
            VGroup(
                HGroup(
                    Item(name='refresh', show_label=False),
                    Item(
                        name='clear',
                        show_label=False,
                    ),
                    Item(
                        name='clear_fits',
                        show_label=False,
                    ),
                    spring,
                ),
                HGroup(
                    Item(
                        name='interp_method',
                        label='Interpolation Method',
                    ),
                    Item(
                        name='nlevel',
                        label='Contour Levels',
                    ),
                    Item(
                        name='set_levels',
                        label='Scale',
                    ),
                    #Item(name='level_range', style='custom', label='Range', ),
                    spring,
                ),
                VGroup(HGroup(
                    Item(
                        name='editing',
                        style='custom',
                        label='Edit',
                    ),
                    Item(
                        name='perform_fit',
                        show_label=False,
                    ),
                    Item(name='message',
                         style='readonly',
                         show_label=False,
                         springy=True),
                    spring,
                ),
                       Item(name='display', style='custom', show_label=False),
                       show_border=True,
                       label='Plots'),
            ),
            VGroup(
                Group(Item(name='fits_list',
                           show_label=False,
                           editor=ArrayViewEditor(
                               titles=[
                                   'Amplitude',
                                   'X0',
                                   'Y0',
                                   'SigmaX',
                                   'SigmaY',
                                   'Theta',
                               ],
                               format='%g',
                               show_index=False,
                           )),
                      show_border=True,
                      label='Fit Result',
                      scrollable=True), ),
        ),
        buttons=['OK'],
        title='Fitting Tool',
        kind='live',
        scrollable=True,
        resizable=True,
        height=800,
        width=1200,
    )

    def __init__(self, experiment=None, **kwargs):
        super(FittingTool2D, self).__init__()
        self.name = kwargs.get('name', 'Fitting Plots')
        self.experiment = experiment
        #self.refresh_display()

    def _interp_method_changed(self):
        self.experiment.has_mesh = False

    def _display_default(self):
        return FittingDataPlot2D()

    def _fits_list_default(self):
        return self.get_fits_list()

    def _fitter_default(self):
        return SpectrumFitter2D()

    def _perform_fit_fired(self):
        if self.has_peaks and self.has_frange:
            self.message = ' '
        else:
            if self.has_peaks:
                self.message = 'Please select a Fit Range'
            elif self.has_frange:
                self.message = 'Please select Peaks'
            else:
                self.message = 'Please select Peaks and a Fit Range '
            return
        peaks = []
        for xmid, ymid, width, height in self.display.peaks:
            if width > 10 and height > 10:
                peaks.append([xmid, ymid, width, height])
        if len(peaks) == 0:
            self.message = 'Selected Peaks are too small'
            return
        fitter = SpectrumFitter2D()
        fitter.peaks = peaks
        frangex = self.display.frangex
        frangey = self.display.frangey
        X, Y, Z = self.experiment.collect_XYZ_arrays()
        idx = np.where(
            np.logical_and(np.logical_and(X >= frangex[0], X <= frangex[1]),
                           np.logical_and(
                               Y >= frangey[0],
                               Y <= frangey[1],
                           )))

        if not all([len(X[idx]), len(Y[idx]), len(Z[idx])]):
            return
        fitter.xdata, fitter.ydata, fitter.zdata = X[idx], Y[idx], Z[idx]

        fitter.perform_fit()
        if fitter.fit_success:
            if fitter.nexp > 1:
                p = fitter.p.reshape(fitter.nexp, 6)
            else:
                p = np.asarray([fitter.p.ravel()])
            self.experiment.fit_results = p
            self.fits_list = p
            self.fit_result = fitter.result_object()

        self.fitter = fitter
        self.refresh_display()

    def _clear_fits_fired(self):
        self.fits_list = np.asarray([[0.0] * 6])
        self.refresh_display()

    def get_fits_list(self):
        if len(self.experiment.fit_results):
            return list(self.experiment.fit_results)
        else:
            return np.asarray([[0.0] * 6])

    def _refresh_fired(self):
        self.refresh_display()

    def _clear_fired(self):
        self.display.clear_selections()
        self.display.draw_patches()
        self.refresh_display()
        self.display.configure_selector(peaks=True)

    def refresh_display(self):
        self.fits_list = self.get_fits_list()
        self.display.remove_subplots()
        self.display.add_subplots(2)
        if len(self.display.axs):
            self.experiment.plot_2d_contour(
                figure=self.display.figure,
                axs=self.display.axs[0],
                setlabels=False,
                colbar=False,
                nlevel=self.nlevel,
                #bin = self.bin,
                #nbins = self.nbins,
                interp_method=self.interp_method,
                set_levels=self.set_levels,
                #level_range = self.level_range
            )

        if np.any(self.fits_list):
            fitter = SpectrumFitter2D()  #self.fitter
            fitter.peaks = [[]] * (self.fits_list.size / 6)
            fitter.xdata, fitter.ydata, fitter.zdata = self.experiment.collect_XYZ_arrays(
            )
            fitter.p = self.fits_list.ravel()
            fitter.plot_data(
                figure=self.display.figure,
                axs=self.display.axs[1],
                nlevel=self.nlevel,
                interp_method=self.interp_method,
            )
            fitter.plot_fit(
                figure=self.display.figure,
                axs=self.display.axs[1],
                nlevel=self.nlevel,
            )

        self.set_titles()
        self.display.draw_patches()
        self.display.configure_selector()

    def set_titles(self):
        self.display.set_title(self.name, size=12, y=1.0)
        if len(self.display.axs):
            self.display.axs[0].set_title('BG Corrected Data', fontsize=11)
            self.display.axs[1].set_title('Fit', fontsize=11)
            self.display.add_common_labels(xlabel='Excitation Wavelength',
                                           ylabel='Emission Wavelength')
Пример #11
0
class SpectrumMeasurement(BaseMeasurement):
    __klass__ = 'Spectrum'

    #####       User Input      #####
    duration = Float(0)
    ex_pol = Int()  # Excitation Polarization
    em_pol = Int()  # Emission Polarization

    ex_wl = Float()  # Excitation Wavelength
    em_wl = Tuple((0.0, 0.0), labels=['Min', 'Max'])  # Emission Wavelength

    exposure = Float(1)
    frames = Int(1)
    e_per_count = Int(1)  # electrons per ADC count

    #####       Extracted Data      #####
    signal = Array()
    bg = Array()
    ref = Array()
    bg_corrected = Property(Array)
    file_data = Dict()

    simulation_data = Dict()
    data = Instance(pd.DataFrame)
    metadata = Dict()
    #####       Flags      #####
    is_simulated = Bool(False)
    has_signal = Property(Bool)  #Bool(False)
    has_bg = Property(Bool)  #Bool(False)
    has_bg_corrected = Property(Bool)
    has_ref = Property(Bool)  #Bool(False)
    has_fits = Property(Bool)
    color = Property(
    )  #Tuple(0.0, 0.0, 0.0)  # Enum(['r', 'g', 'b', 'y', 'g', 'k','m','c','k'])

    #####       Calculated Data      #####
    fits = List([])
    fit_data = Property(Array)
    resolution = Property()
    all_data_array = Array(transient=True)
    show_data = Button('Show Data')

    #####       UI      #####

    #####       GUI layout      #####
    plotting_tool = Instance(MeasurementPlottingTool, transient=True)
    analysis_tool = Instance(MeasurementAnalysisTool, transient=True)
    fitting_tool = Instance(FittingTool1D, transient=True)

    view = View(
        Tabbed(
            HGroup(
                VGroup(
                    VGroup(
                        #Item(name='ex_pol', label='Excitation POL'),
                        Item(name='ex_wl', label='Excitation WL'),
                        Item(name='frames', label='Frames'),
                        Item(name='exposure', label='Exposure'),
                        Item(name='color', label='Plot Color'),
                        show_border=True,
                        label='Excitation'),
                    VGroup(
                        #Item(name='em_pol', label='Emission POL'),
                        Item(name='em_wl', label='Emission WL'),
                        Item(name='e_per_count', label='e/count'),
                        show_border=True,
                        label='Emission'),
                    HGroup(
                        Item(name='show_data', show_label=False,
                             springy=True)),
                    VGroup(Item(name='file_data',
                                editor=ValueEditor(),
                                show_label=False),
                           label='File Metadata'),
                ),
                HGroup(
                    Item(name='all_data_array',
                         show_label=False,
                         editor=ArrayViewEditor(titles=[
                             'Wavelength', 'BG corrected', 'Signal',
                             'Background', 'Reference'
                         ],
                                                format='%g',
                                                show_index=False),
                         springy=True),

                    #scrollable=True
                    springy=True),
                label='Data'),
            VGroup(Item(name='plotting_tool',
                        show_label=False,
                        style='custom',
                        springy=False),
                   label='Visualization'),
            VGroup(Item(name='fitting_tool',
                        show_label=False,
                        style='custom',
                        springy=False),
                   show_border=True,
                   label='Fitting'),
            VGroup(Item(name='analysis_tool',
                        show_label=False,
                        style='custom',
                        springy=False),
                   label='Statistical Analysis'),
        ), )

    #####       Initialzation Methods      #####

    def make_data_arrays(self):
        self.signal = self.data[['em_wl', 'sig']].as_matrix()
        self.bg = self.data[['em_wl', 'bgd']].as_matrix()
        self.ref = self.data[['em_wl', 'ref']].as_matrix()

    def _signal_default(self):
        return np.array([])

    def _bg_default(self):
        return np.array([[], []])

    def _all_data_array_default(self):
        return np.array([[0.0, 0.0, 0.0, 0.0, 0.0]])

    def _plotting_tool_default(self):
        return MeasurementPlottingTool(measurement=self)

    def _analysis_tool_default(self):
        return MeasurementAnalysisTool(measurement=self)

    def _fitting_tool_default(self):
        return FittingTool1D(measurements=[self], name=self.name)

    #####       getters      #####
    def _get_summary(self):
        report = 'Excitation: %d nm' % self.ex_wl + ' | Emission Range: %d:%d nm' % self.em_wl
        return report

    def _get_has_signal(self):
        if len(self.signal):
            return True
        else:
            return False

    def _get_resolution(self):
        if len(self.signal):
            return np.mean(np.diff(self.signal[:, 0]))
        else:
            return 0.0075

    def _get_color(self):
        return wl_to_rgb(self.ex_wl)

    def _get_has_bg(self):
        if len(self.bg):
            return True
        else:
            return False

    def _get_has_bg_corrected(self):
        if len(self.bg) and len(self.signal):
            return True
        else:
            return False

    def _get_has_ref(self):
        if len(self.ref):
            return True
        else:
            return False

    def _get_has_fits(self):
        if len(self.fits):
            return True
        else:
            return False

    def _get_fit_data(self):
        data = np.zeros_like(self.signal)
        data[:, 0] = self.signal[:, 0]
        for a, m, s in self.fits:
            data[:, 1] += gauss(data[:, 0], a, m, s)

    def _show_data_fired(self):
        df = self.create_dataframe().reset_index()
        self.all_data_array = df.as_matrix(
            columns=['index', 'bg_corrected', 'signal', 'bg', 'ref'])

    def _signal_changed(self):
        if self.signal.size > 2:
            self.em_wl = (np.round(np.min(self.signal[:, 0])),
                          np.round(np.max(self.signal[:, 0])))

    #####       Public Methods      #####
    def rescale(self, scale):
        if self.has_signal:
            self.signal[:, 1] *= scale
        if self.has_bg:
            self.bg[:, 1] *= scale
        if self.has_ref:
            self.ref[:, 1] *= scale

    def create_series(self, normalize=True, **kwargs):
        """

        :return:
        """
        bin = kwargs.get('bin', False)
        nbins = kwargs.get('nbins', None)
        round_wl = kwargs.get('round_wl', False)
        data_name = kwargs.get('data_name', 'bg_corrected')
        normed = np.zeros((1, 2))
        if not getattr(self, 'has_' + data_name):
            return normed

        if normalize:
            normed = self.normalized(data_name)
        else:
            normed = getattr(self, data_name)

        if nbins is not None:
            pass
            if nbins:
                bins = nbins
            else:
                bins = round(normed[:, 0].max()) - round(normed[:, 0].min())
            normed = bin_data_array(normed, nbins=bins)

        if round_wl:
            indx = np.around(normed[:, 0], decimals=1)
        else:
            indx = normed[:, 0]

        return pd.Series(data=normed[:, 1], index=indx, name=self.ex_wl)

    def create_dataframe(self, **kwargs):
        data_names = kwargs.get('data_names',
                                ['bg_corrected', 'signal', 'bg', 'ref'])
        data_dict = {}
        for data_name in data_names:
            if getattr(self, 'has_' + data_name):
                data_dict[data_name] = self.create_series(data_name=data_name,
                                                          **kwargs)
        return pd.DataFrame(data_dict)

    def make_db_dataframe(self, data_names=('signal', 'bg', 'ref')):

        final = None
        for data_name in data_names:
            if getattr(self, 'has_' + data_name):
                new = pd.DataFrame(data=self.normalized(data_name),
                                   columns=['em_wl', data_name])
                if final is not None:
                    final = pd.merge_asof(final, new, on='em_wl')
                else:
                    final = new
        return final.set_index('em_wl')

    def normalized(self, data_name):
        normed = np.copy(getattr(self, data_name))
        normed[:, 1] = normed[:, 1] / (self.exposure * self.frames)
        return normed

    def _get_bg_corrected(self):
        sig = np.copy(self.signal)
        sig[:, 1] -= np.resize(self.bg[:, 1], sig[:, 1].size)
        return sig

    def bin_data(self, data_name='bg_corrected', **kwargs):
        """
        :return:
        """
        normalize = kwargs.get('normalize', True)
        nbins = kwargs.get('nbins', 0)

        normed = np.zeros((1, 2))
        if not self.has_signal:
            return normed

        if normalize:
            normed = self.normalized(data_name)
        else:
            normed = getattr(self, data_name)

        if nbins:
            bins = nbins
        else:
            bins = round(normed[:, 0].max()) - round(normed[:, 0].min())
        binned = bin_data_array(normed, nbins=bins)

        return binned

    def integrate_bg_corrected(self, l, r, fit=False):
        '''

        :param l: integration minimum (inclusive)
        :param r: integration maximum (inclusive)
        :return: background corrected integration result
        '''
        if not self.has_signal:
            return 0.0
        sig = 0.0
        signal = self.norm_signal()
        bgnd = self.norm_bg()
        if fit:
            sig = self.integrate_with_fit(signal, l, r)
        else:
            sig = np.sum(
                np.where(np.logical_and(signal[:, 0] <= r, signal[:, 0] >= l),
                         signal[:, 1], 0.0))
        bg = np.sum(
            np.where(np.logical_and(bgnd[:, 0] <= r, bgnd[:, 0] >= l),
                     bgnd[:, 1], 0.0))
        return sig - bg

    def integrate_data(self, l, r, data_name='bg_corrected'):
        '''
        :param data_name: data to integrate
        :param l: integration minimum (inclusive)
        :param r: integration maximum (inclusive)
        :return: background corrected integration result
        '''
        if not self.has_signal:
            return 0.0
        data = getattr(self, data_name)
        result = np.sum(
            np.where(np.logical_and(data[:, 0] <= r, data[:, 0] >= l),
                     data[:, 1], 0.0))
        return result

    def plot_data(self, **kwargs):
        ax = kwargs.get('ax', None)
        legend = kwargs.get('legend', True)
        data_name = kwargs.get('data_name', 'bg_corrected')
        title = kwargs.get('title', None)

        if self.has_signal:
            ser = self.create_series(**kwargs)
            axs = ser.plot(color=self.color, legend=legend, ax=ax)
            if ax is not None:
                if title is None:
                    ax.set_title(data_name, fontsize=12)
                ax.set_xlabel('Emission Wavelength')
                ax.set_ylabel('Counts')
                #plt.show()
            else:
                plt.show()
            return axs

    def plot_by_name(self,
                     plot_name='hist',
                     title=None,
                     data_name='bg_corrected',
                     **kwargs):
        ax = kwargs.get('ax', None)
        #legend = kwargs.get('legend', True)
        #data = kwargs.get('data', 'bg_corrected')
        #title = kwargs.get('title', None)
        #alpha = kwargs.get('alpha', 1.0)
        if self.has_signal:
            ser = self.create_series(data_name=data_name, **kwargs)
            axs = getattr(ser.plot, plot_name)(color=self.color, **kwargs)
            if ax is not None:
                if title is None:
                    ax.set_title(data_name + ' ' + plot_name, fontsize=12)

            else:
                plt.show()
            return axs

    def plot_special(self,
                     plot_name='autocorrelation',
                     title=None,
                     data_name='bg_corrected',
                     **kwargs):
        if not self.has_signal:
            return
        fig = kwargs.get('figure', plt.figure())
        ax = kwargs.get('ax', fig.add_subplot(111))
        nbins = kwargs.get('nbins', 150)

        ser = self.create_series(**kwargs)
        #data_name = kwargs.get('data_name', 'BG corrected')
        axs = {
            'lag': lag_plot,
            'autocorrelation': autocorrelation_plot,
        }[plot_name](ser, **kwargs)
        if title is None:
            axs.set_title(' '.join([data_name, plot_name]), fontsize=12)
        if ax is None:
            plt.show()

    def plot_scatter_matrix(self, **kwargs):
        diag = kwargs.get('diag', 'kde')
        if not self.has_signal:
            return
        fig = kwargs.get('figure', plt.figure())
        ax = kwargs.get('ax', fig.add_subplot(111))
        df = self.create_dataframe(**kwargs)
        scatter_matrix(df, ax=ax, diagonal=diag)

    def calc_statistics(self, statistic='hist', **kwargs):
        ser = self.create_series(**kwargs)
        if statistic == 'hist':
            bins = kwargs.get('bins', 150)
            cnts, divs = np.histogram(ser, bins=bins)
            return pd.Series(data=cnts,
                             index=divs[:-1] + np.diff(divs) / 2,
                             name=self.ex_wl)

        elif statistic == 'kde':
            nsample = kwargs.get('nsample', 200)
            arr = ser.as_matrix()
            kern = stats.gaussian_kde(arr)
            rng = np.linspace(arr.min(), arr.max(), nsample)
            return pd.Series(data=kern(rng), index=rng, name=self.ex_wl)