Exemplo n.º 1
0
    def _add_error_bars(self,
                        scatter,
                        errors,
                        axis,
                        nsigma,
                        end_caps,
                        visible=True):

        ebo = ErrorBarOverlay(component=scatter,
                              orientation=axis,
                              nsigma=nsigma,
                              visible=visible,
                              use_end_caps=end_caps)

        scatter.underlays.append(ebo)
        setattr(scatter, '{}error'.format(axis), ArrayDataSource(errors))
        return ebo
Exemplo n.º 2
0
def make_data_sources(session, index_sort="none", *args):
    """ Given a list of arguments, returns a list of (index, value) datasources
    to create plots from.
    """
    # Make sure everything is a numpy array
    data = []
    for arg in args:
        if isinstance(arg, list) or isinstance(arg, tuple):
            data.append(array(arg))
        else:
            data.append(arg)

    if len(data) == 0:
        raise ChacoShellError("Insufficient data for plot.")

    # 1D array(s)
    if len(data[0].shape) == 1:
        if len(data) == 1:
            # Only a single array was provided
            index_ds = ArrayDataSource(arange(len(data[0])),
                                       sort_order="ascending")
            value_ds = ArrayDataSource(data[0], sort_order="none")
            return [(index_ds, value_ds)]

        else:
            # multiple arrays were provided
            index_ds = ArrayDataSource(data[0], sort_order=index_sort)
            return [(index_ds, ArrayDataSource(v, sort_order="none"))
                    for v in data[1:]]

    # 2D arrays
    elif len(data[0].shape) == 2:
        sources = []
        # Loop over all the 2D arrays
        for ary in data:
            if ary.shape[0] > ary.shape[1]:
                index_ary = ary[:, 0]
                value_arrays = ary[:, 1:]
            else:
                index_ary = ary[0]
                value_arrays = transpose(ary[1:])
            index_ds = ArrayDataSource(index_ary, sort_order=index_sort)
            sources.extend([(index_ds, ArrayDataSource(v, sort_order="none"))
                            for v in value_arrays])
        return sources

    # Not a two-dimensional array, error.
    else:
        raise ChacoShellError(
            "Unable to create plot data sources from array of shape " +
            str(data[1].shape) + ".")
Exemplo n.º 3
0
    def _add_error_bars(self,
                        scatter,
                        errors,
                        orientation='y',
                        visible=True,
                        nsigma=1,
                        line_width=1):
        from pychron.graph.error_bar_overlay import ErrorBarOverlay

        ebo = ErrorBarOverlay(component=scatter,
                              orientation=orientation,
                              nsigma=nsigma,
                              line_width=line_width,
                              visible=visible)

        scatter.underlays.append(ebo)
        # print len(errors),scatter.index.get_size()
        setattr(scatter, '{}error'.format(orientation),
                ArrayDataSource(errors))
        return ebo
Exemplo n.º 4
0
    def show_blank_time_series(self):
        g = StackedRegressionGraph(window_height=0.75)
        isotopes = self.blank_selected[0].isotopes
        keys = sort_isotopes([iso.isotope for iso in isotopes], reverse=False)
        _mi, _ma = None, None

        for k in keys:
            iso = next((i for i in isotopes if i.isotope == k))
            # print iso.analyses
            g.new_plot(padding_right=10)
            g.set_time_xaxis()
            g.set_y_title(iso.isotope)

            g.new_series([self.timestamp], [iso.value],
                         marker_size=3,
                         fit=False,
                         type='scatter',
                         marker_color='black')
            vs = iso.values
            if vs:
                ts = [vi.timestamp for vi in vs]
                _mi = min(ts)
                _ma = max(ts)
                g.new_series(ts, [vi.value for vi in vs],
                             yerror=ArrayDataSource([vi.error for vi in vs]),
                             marker_size=3,
                             fit=(iso.fit, 'SD'),
                             type='scatter',
                             marker_color='red')

        if not _mi:
            _mi, _ma = self.timestamp - 86400, self.timestamp + 86400

        g.set_x_limits(_mi, _ma, pad='0.1')
        g.refresh()

        g.set_x_title('Time', plotid=0)
        g.edit_traits()
Exemplo n.º 5
0
    def _plot_interpolated(self, ans, c_xs, i, iso, reg, series_id):
        p_uys, p_ues = self.set_interpolated_values(iso, reg, ans)
        if len(p_uys):
            graph = self.graph
            # display the predicted values
            s, p = graph.new_series(c_xs,
                                    p_uys,
                                    isotope=iso,
                                    yerror=ArrayDataSource(p_ues),
                                    fit=False,
                                    add_tools=False,
                                    add_inspector=False,
                                    type='scatter',
                                    marker_size=3,
                                    color='blue',
                                    plotid=i,
                                    bind_id=-1)
            series = len(p.plots) - 1
            graph.set_series_label('Unknowns-predicted{}'.format(series_id),
                                   plotid=i,
                                   series=series)

            self._add_error_bars(s, p_ues)
Exemplo n.º 6
0
def get_4d_scatter_plot():
    boston = datasets.load_boston()
    prices = boston['target']
    lower_status = boston['data'][:, -1]
    tax = boston['data'][:, 9]
    nox = boston['data'][:, 4]

    x, y = get_data_sources(x=lower_status, y=prices)
    x_mapper, y_mapper = get_mappers(x, y)

    color_source = ArrayDataSource(nox)
    color_mapper = dc.reverse(dc.RdYlGn)(DataRange1D(low=nox.min(),
                                                     high=nox.max()))

    # normalize between 0 and 10
    marker_size = tax / tax.max() * 10.

    scatter_plot = ColormappedScatterPlot(
        index=x,
        value=y,
        index_mapper=x_mapper,
        value_mapper=y_mapper,
        color_data=color_source,
        color_mapper=color_mapper,
        fill_alpha=0.8,
        marker='circle',
        marker_size=marker_size,
        title='Size represents property-tax rate, '
        'color nitric oxides concentration',
        render_method='bruteforce',
        **PLOT_DEFAULTS)

    add_axes(scatter_plot,
             x_label='Percent lower status in the population',
             y_label='Median house prices')

    return scatter_plot
Exemplo n.º 7
0
    def _plot_unknowns_current(self, pid, po):
        ymi, yma = 0, 0

        if self.analyses and self.show_current:
            graph = self.graph
            n = [ai.record_id for ai in self.sorted_analyses]

            ys, ye = self.current_data(po)
            ymi, yma = self._calc_limits(ys, ye)

            scatter, plot = graph.new_series(
                x=self.xs,
                y=ys,
                yerror=ye,
                type='scatter',
                display_index=ArrayDataSource(data=n),
                fit=False,
                plotid=pid,
                bind_id=-2,
                add_tools=False,
                add_inspector=False,
                marker=po.marker,
                marker_size=po.marker_size)

            def af(i, x, y, analysis):
                v, e = self._get_interpolated_value(po, analysis)
                return (u'Interpolated: {}{}{}'.format(floatfmt(v), PLUSMINUS,
                                                       floatfmt(e)),
                        'Run Date: {}'.format(
                            analysis.rundate.strftime('%m-%d-%Y %H:%M')),
                        'Rel. Time: {:0.4f}'.format(x))

            self._add_error_bars(scatter, ye, 'y', self.options.nsigma, True)
            self._add_scatter_inspector(scatter,
                                        add_selection=False,
                                        additional_info=af)
        return ymi, yma
Exemplo n.º 8
0
    def _plot_inverse_isochron(self, po, plot, pid):
        analyses = self.sorted_analyses
        plot.padding_left = 75

        refiso = analyses[0]

        self._ref_constants = refiso.arar_constants
        self._ref_j = refiso.j
        self._ref_age_scalar = refiso.arar_constants.age_scalar
        self._ref_age_units = refiso.arar_constants.age_units

        try:
            age, reg, data = calculate_isochron(analyses)
        except TypeError:
            return

        xs, ys, xerrs, yerrs = data
        self._cached_data = data
        self._cached_reg = reg
        self._age = age

        graph = self.graph
        graph.set_x_title('39Ar/40Ar')
        graph.set_y_title('36Ar/40Ar')

        graph.set_grid_traits(visible=False)
        graph.set_grid_traits(visible=False, grid='y')

        scatter, _p = graph.new_series(
            xs,
            ys,
            xerror=ArrayDataSource(data=xerrs),
            yerror=ArrayDataSource(data=yerrs),
            type='scatter',
            marker='circle',
            bind_id=self.group_id,
            #selection_marker_size=5,
            #selection_color='green',
            marker_size=2)
        #self._scatter = scatter
        graph.set_series_label('data{}'.format(self.group_id))

        eo = ErrorEllipseOverlay(component=scatter)
        scatter.overlays.append(eo)

        mi, ma = graph.get_x_limits()

        ma = max(ma, max(xs))
        mi = min(mi, min(xs))
        rxs = linspace(mi, ma)
        rys = reg.predict(rxs)

        graph.set_x_limits(min_=mi, max_=ma, pad='0.1')

        graph.new_series(rxs, rys, color=scatter.color)
        graph.set_series_label('fit{}'.format(self.group_id))

        if po.show_labels:
            self._add_point_labels(scatter)
        self._add_scatter_inspector(scatter)

        self._add_info(plot, reg, text_color=scatter.color)
Exemplo n.º 9
0
    def _plot_inverse_isochron(self, po, plot, pid):
        analyses = self.sorted_analyses
        # plot.padding_left = 75

        refiso = analyses[0]

        self._ref_constants = refiso.arar_constants
        self._ref_j = refiso.j
        self._ref_age_scalar = refiso.arar_constants.age_scalar
        self._ref_age_units = refiso.arar_constants.age_units

        # try:
        # age, reg, data = calculate_isochron(analyses)
        # except TypeError:
        # return
        ec = self.options.error_calc_method
        self.analysis_group.isochron_age_error_kind = ec
        data = self.analysis_group.get_isochron_data()

        _, reg, (xs, ys, xerrs, yerrs) = data
        self._cached_data = data
        self._cached_reg = reg

        graph = self.graph

        u39 = u'\u00b3\u2079'
        u40 = u'\u2074\u2070'
        u36 = u'\u00b3\u2076'
        xtitle = u'{}Ar/{}Ar'.format(u39, u40)
        ytitle = u'{}Ar/{}Ar'.format(u36, u40)

        # xtitle = '39Ar/40Ar'
        # ytitle = '36Ar/40Ar'
        xtitle = '<sup>39</sup>Ar/<sub>40</sup>Ar'
        ytitle = '<sup>36</sup>Ar/<sub>40</sup>Ar'
        # for axis in (plot.x_axis, plot.y_axis):
        #     axis.title_font = 'courier 15'

        # graph.set_x_title(xtitle, plotid=pid)
        # graph.set_y_title(ytitle, plotid=pid)

        # if '<sup>' in title or '<sub>' in title:
        self._set_ml_title(ytitle, pid, 'y')
        self._set_ml_title(xtitle, pid, 'x')

        p = graph.plots[pid]
        p.y_axis.title_spacing = 50

        graph.set_grid_traits(visible=False)
        graph.set_grid_traits(visible=False, grid='y')
        scatter, _p = graph.new_series(xs, ys,
                                       xerror=ArrayDataSource(data=xerrs),
                                       yerror=ArrayDataSource(data=yerrs),
                                       type='scatter',
                                       marker='circle',
                                       bind_id=self.group_id,
                                       # selection_marker_size=5,
                                       # selection_color='green',
                                       marker_size=2)
        # self._scatter = scatter
        graph.set_series_label('data{}'.format(self.group_id))

        eo = ErrorEllipseOverlay(component=scatter,
                                 reg=reg,
                                 fill=self.options.fill_ellipses)
        scatter.overlays.append(eo)

        # mi, ma = graph.get_x_limits()

        # ma = max(ma, max(xs))
        # mi = min(mi, min(xs))
        mi, ma = min(xs), max(xs)
        self.xma = max(self.xma, ma)
        self.xmi = min(self.xmi, mi)

        # print len(xs),mi,ma
        mi = 0
        rxs = linspace(mi, ma)
        rys = reg.predict(rxs)

        graph.set_x_limits(min_=mi, max_=ma, pad='0.1')

        l, _ = graph.new_series(rxs, rys, color=scatter.color)
        graph.set_series_label('fit{}'.format(self.group_id))

        l.index.set_data(rxs)
        l.value.set_data(rys)
        yma, ymi = max(rys), min(rys)

        try:
            self.ymis[pid] = min(self.ymis[pid], ymi)
            self.ymas[pid] = max(self.ymas[pid], yma)
        except IndexError:
            self.ymis.append(ymi)
            self.ymas.append(yma)

        print 'isochron regressor error type {}'.format(reg.error_calc_type)

        lci, uci = reg.calculate_error_envelope(l.index.get_data())
        ee = ErrorEnvelopeOverlay(component=l,
                                  upper=uci, lower=lci)
        l.underlays.append(ee)
        l.error_envelope = ee

        def ad(i, x, y, ai):
            a = ai.isotopes['Ar39'].get_interference_corrected_value()
            b = ai.isotopes['Ar40'].get_interference_corrected_value()
            r = a / b
            v = r.nominal_value
            e = r.std_dev

            try:
                pe = '({:0.2f}%)'.format(e / v * 100)
            except ZeroDivisionError:
                pe = '(Inf%)'

            return u'39Ar/40Ar = {} {}{} {}'.format(floatfmt(v, n=6), PLUSMINUS, floatfmt(e, n=7), pe)

        if self.group_id == 0:
            if self.options.display_inset:
                self._add_inset(plot, xs, ys, reg)

            if self.options.show_nominal_intercept:
                self._add_atm_overlay(plot)

        graph.add_vertical_rule(0, color='black')
        self._add_info(plot, reg, text_color=scatter.color)

        if po.show_labels:
            self._add_point_labels(scatter)

        self._add_scatter_inspector(scatter, additional_info=ad)

        # d = lambda a, b, c, d: self.update_index_mapper(a, b, c, d)
        p.index_mapper.on_trait_change(self.update_index_mapper, 'updated')
Exemplo n.º 10
0
    def _build_plot(self, i, iso, fit, current_args, ref_args,
                    series_id=0,
                    regression_bounds=None):
        ans, c_xs, c_ys, c_es=current_args
        refs, r_xs, r_ys, r_es, display_xs=ref_args

        graph=self.graph
        if c_es and c_ys:
            # plot unknowns
            s, _p = graph.new_series(c_xs, c_ys,
                                     yerror=c_es,
                                     fit=False,
                                     type='scatter',
                                     plotid=i,
                                     marker='square',
                                     marker_size=3,
                                     bind_id=-1,
                                     color='black',
                                     add_inspector=False)
            self._add_inspector(s, ans)
            self._add_error_bars(s, c_es)

            graph.set_series_label('Unknowns-Current', plotid=i)

        if r_ys:
            reg = None
            # plot references

            if fit in ['preceding', 'bracketing interpolate', 'bracketing average']:
                reg = InterpolationRegressor(xs=r_xs,
                                             ys=r_ys,
                                             yserr=r_es,
                                             kind=fit)
                s, _p = graph.new_series(r_xs, r_ys,
                                         yerror=r_es,
                                         type='scatter',
                                         plotid=i,
                                         fit=False,
                                         marker_size=3,
                                         color='red',
                                         add_inspector=False, )
                self._add_inspector(s, refs)
                self._add_error_bars(s, r_es)
                series_id=(series_id + 1)*2
            else:
                series_id=(series_id + 1) * 3
                _p, s, l = graph.new_series(r_xs, r_ys,
                                            display_index=ArrayDataSource(data=display_xs),
                                            yerror=ArrayDataSource(data=r_es),
                                            fit=fit,
                                            color='red',
                                            plotid=i,
                                            marker_size=3,
                                            add_inspector=False,
                                            )
                if hasattr(l, 'regressor'):
                    reg = l.regressor

                l.regression_bounds=regression_bounds

                self._add_inspector(s, refs)
                self._add_error_bars(s, array(r_es))

            if reg:
                p_uys, p_ues = self.set_interpolated_values(iso, reg, ans)
                # display the predicted values
                s, _p = graph.new_series(c_xs,
                                         p_uys,
                                         isotope=iso,
                                         yerror=ArrayDataSource(p_ues),
                                         fit=False,
                                         type='scatter',
                                         marker_size=3,
                                         color='blue',
                                         plotid=i,
                                         bind_id=-1)

                graph.set_series_label('Unknowns-predicted{}'.format(series_id), plotid=i,
                                       series=series_id)

                # print 'c', series_id, len(ans), len(c_xs), len(c_ys), len(c_es)
                # print 'r', series_id, len(refs), len(r_xs), len(r_ys), len(r_es)
                # print 'p', '', len(c_xs), len(p_uys), len(p_ues)
                self._add_error_bars(s, p_ues)
Exemplo n.º 11
0
    def _plot_series(self, po, pid, omits):
        graph = self.graph
        try:
            if po.name == ANALYSIS_TYPE:
                from pychron.pipeline.plot.plotter.ticks import analysis_type_formatter

                ys = list(self._unpack_attr(po.name))
                kw = dict(y=ys,
                          colors=ys,
                          type='cmap_scatter',
                          fit='',
                          color_map_name='gist_rainbow')
                yerr = None
                value_format = analysis_type_formatter
                set_ylimits = False

            else:
                set_ylimits = True
                value_format = None
                ys = array(
                    [nominal_value(ai) for ai in self._unpack_attr(po.name)])
                yerr = array(
                    [std_dev(ai) for ai in self._unpack_attr(po.name)])

                if po.use_dev or po.use_percent_dev:
                    graph.add_horizontal_rule(0,
                                              plotid=pid,
                                              color='black',
                                              line_style='solid')
                    m = ys.mean()
                    ys = ys - m
                    if po.use_percent_dev:
                        ys = ys / m * 100
                        yerr = yerr / m * 100

                kw = dict(y=ys,
                          yerror=yerr,
                          type='scatter',
                          fit='{}_{}'.format(po.fit, po.error_type),
                          filter_outliers_dict=po.filter_outliers_dict)

            n = [ai.record_id for ai in self.sorted_analyses]
            args = graph.new_series(x=self.xs,
                                    display_index=ArrayDataSource(data=n),
                                    plotid=pid,
                                    add_tools=True,
                                    add_inspector=True,
                                    add_point_inspector=False,
                                    marker=po.marker,
                                    marker_size=po.marker_size,
                                    **kw)
            if len(args) == 2:
                scatter, p = args
            else:
                p, scatter, l = args

                if self.options.show_statistics:
                    graph.add_statistics(
                        plotid=pid,
                        options=self.options.get_statistics_options())

            sel = scatter.index.metadata.get('selections', [])
            sel += omits
            scatter.index.metadata['selections'] = list(set(sel))

            def af(i, x, y, analysis):
                return ('Run Date: {}'.format(
                    analysis.rundate.strftime('%m-%d-%Y %H:%M')),
                        'Rel. Time: {:0.4f}'.format(x))

            self._add_scatter_inspector(scatter,
                                        add_selection=False,
                                        additional_info=af,
                                        value_format=value_format)

            # if po.use_time_axis:
            #     p.x_axis.tick_generator = ScalesTickGenerator(scale=CalendarScaleSystem())

            if po.y_error and yerr is not None:
                s = self.options.error_bar_nsigma
                ec = self.options.end_caps
                self._add_error_bars(scatter, yerr, 'y', s, ec, visible=True)

            # if set_ylimits and not po.has_ylimits():
            #     mi, mx = min(ys - 2 * yerr), max(ys + 2 * yerr)
            #     graph.set_y_limits(min_=mi, max_=mx, pad='0.1', plotid=pid)

        except (KeyError, ZeroDivisionError, AttributeError) as e:
            import traceback

            traceback.print_exc()
            print('Series', e)
Exemplo n.º 12
0
 def test_array_data_source(self):
     with warnings.catch_warnings(record=True) as w:
         src = ArrayDataSource(np.arange(5))
     self.assertEqual(w, [])
Exemplo n.º 13
0
    def _plot_relative_probability(self, po, plot, pid):
        graph = self.graph
        bins, probs = self._calculate_probability_curve(self.xs,
                                                        self.xes,
                                                        calculate_limits=True)

        ogid = self.group_id
        gid = ogid + 1
        sgid = ogid * 2
        plotkw = self.options.get_plot_dict(ogid, self.subgroup_id)

        line, _ = graph.new_series(x=bins, y=probs, plotid=pid, **plotkw)
        line.history_id = self.group_id

        self._add_peak_labels(line)

        graph.set_series_label('Current-{}'.format(gid),
                               series=sgid,
                               plotid=pid)

        # add the dashed original line
        dline, _ = graph.new_series(x=bins,
                                    y=probs,
                                    plotid=pid,
                                    visible=False,
                                    color=line.color,
                                    line_style='dash')
        dline.history_id = self.group_id

        graph.set_series_label('Original-{}'.format(gid),
                               series=sgid + 1,
                               plotid=pid)

        self._add_info(graph, plot)
        self._add_mean_indicator(graph, line, po, bins, probs, pid)

        mi, ma = min(probs), max(probs)
        self._set_y_limits(mi, ma, min_=0, pad='0.025')

        # d = lambda a, b, c, d: self.update_index_mapper(a, b, c, d)
        # if ogid == 0:
        plot.index_mapper.range.on_trait_change(self.update_index_mapper,
                                                'updated')

        if self.options.display_inset:
            xs = self.xs
            n = xs.shape[0]

            startidx = 1
            if self.group_id > 0:
                for ov in plot.overlays:
                    if isinstance(ov, IdeogramPointsInset):
                        print('ideogram point inset', self.group_id, startidx,
                              ov.value.get_bounds()[1] + 1)
                        startidx = max(startidx, ov.value.get_bounds()[1] + 1)
            else:
                startidx = 1

            if self.options.analysis_number_sorting == 'Oldest @Top':
                ys = arange(startidx, startidx + n)
            else:
                ys = arange(startidx + n - 1, startidx - 1, -1)

            yma2 = max(ys) + 1
            h = self.options.inset_height / 2.0
            if self.group_id == 0:
                bgcolor = self.options.plot_bgcolor
            else:
                bgcolor = 'transparent'

            d = self.options.get_plot_dict(ogid, self.subgroup_id)
            o = IdeogramPointsInset(self.xs,
                                    ys,
                                    color=d['color'],
                                    outline_color=d['color'],
                                    bgcolor=bgcolor,
                                    width=self.options.inset_width,
                                    height=h,
                                    visible_axes=False,
                                    xerror=ArrayDataSource(self.xes),
                                    location=self.options.inset_location)
            plot.overlays.append(o)

            def cfunc(x1, x2):
                return cumulative_probability(self.xs, self.xes, x1, x2, n=N)

            xs, ys, xmi, xma = self._calculate_asymptotic_limits(
                cfunc, tol=self.options.asymptotic_height_percent)
            oo = IdeogramInset(xs,
                               ys,
                               color=d['color'],
                               bgcolor=bgcolor,
                               yoffset=h,
                               visible_axes=self.group_id == 0,
                               width=self.options.inset_width,
                               height=self.options.inset_height,
                               location=self.options.inset_location)

            yma = max(ys)
            if self.group_id > 0:
                for ov in plot.overlays:
                    if isinstance(ov, IdeogramInset):
                        mi, ma = ov.get_x_limits()
                        xmi = min(mi, xmi)
                        xma = max(ma, xma)

                        _, ma = ov.get_y_limits()
                        yma = max(ma, yma)

            plot.overlays.append(oo)
            for ov in plot.overlays:
                if isinstance(ov, IdeogramInset):
                    ov.set_x_limits(xmi, xma)
                    ov.set_y_limits(0, yma * 1.1)
                elif isinstance(ov, IdeogramPointsInset):
                    ov.set_x_limits(xmi, xma)
                    ov.set_y_limits(0, yma2)
Exemplo n.º 14
0
    def _plot_series(self, po, pid, omits):
        graph = self.graph
        try:
            if po.name == 'AnalysisType':
                from pychron.pipeline.plot.plotter.ticks import analysis_type_formatter

                ys = list(self._unpack_attr(po.name))
                kw = dict(y=ys,
                          colors=ys,
                          type='cmap_scatter',
                          fit='',
                          color_map_name='gist_rainbow')
                yerr = None
                value_format = analysis_type_formatter
                set_ylimits = False

            else:
                set_ylimits = True
                value_format = None
                ys = array(
                    [ai.nominal_value for ai in self._unpack_attr(po.name)])
                yerr = array([ai.std_dev for ai in self._unpack_attr(po.name)])
                kw = dict(y=ys,
                          yerror=yerr,
                          type='scatter',
                          fit='{}_{}'.format(po.fit, po.error_type),
                          filter_outliers_dict=po.filter_outliers_dict)

            # print ys
            n = [ai.record_id for ai in self.sorted_analyses]
            args = graph.new_series(x=self.xs,
                                    display_index=ArrayDataSource(data=n),
                                    plotid=pid,
                                    add_inspector=False,
                                    marker=po.marker,
                                    marker_size=po.marker_size,
                                    **kw)
            if len(args) == 2:
                scatter, p = args
            else:
                p, scatter, l = args

            sel = scatter.index.metadata.get('selections', [])
            sel += omits
            scatter.index.metadata['selections'] = list(set(sel))

            def af(i, x, y, analysis):
                return ('Run Date: {}'.format(
                    analysis.rundate.strftime('%m-%d-%Y %H:%M')),
                        'Rel. Time: {:0.4f}'.format(x))

            self._add_scatter_inspector(scatter,
                                        additional_info=af,
                                        value_format=value_format)

            if po.use_time_axis:
                p.x_axis.tick_generator = ScalesTickGenerator(
                    scale=CalendarScaleSystem())

            # p.value_scale = po.scale
            end_caps = True
            if po.y_error and yerr is not None:
                self._add_error_bars(scatter,
                                     yerr,
                                     'y',
                                     2,
                                     end_caps,
                                     visible=True)

            if set_ylimits:
                mi, mx = min(ys - 2 * yerr), max(ys + 2 * yerr)
                graph.set_y_limits(min_=mi, max_=mx, pad='0.1', plotid=pid)

        except (KeyError, ZeroDivisionError, AttributeError), e:
            import traceback

            traceback.print_exc()
            print 'Series', e
Exemplo n.º 15
0
    def _plot_inverse_isochron(self, po, plot, pid):
        opt = self.options
        self.analysis_group.isochron_age_error_kind = opt.error_calc_method
        _, _, reg = self.analysis_group.get_isochron_data(exclude_non_plateau=opt.exclude_non_plateau)

        graph = self.graph

        xtitle = '<sup>39</sup>Ar/<sup>40</sup>Ar'
        ytitle = '<sup>36</sup>Ar/<sup>40</sup>Ar'

        # self._set_ml_title(ytitle, pid, 'y')
        # self._set_ml_title(xtitle, pid, 'x')
        graph.set_y_title(ytitle, plotid=pid)
        graph.set_x_title(xtitle, plotid=pid)

        p = graph.plots[pid]
        p.y_axis.title_spacing = 50

        graph.set_grid_traits(visible=False)
        graph.set_grid_traits(visible=False, grid='y')
        group = opt.get_group(self.group_id)
        color = group.color

        marker = opt.marker
        marker_size = opt.marker_size

        scatter, _p = graph.new_series(reg.xs, reg.ys,
                                       xerror=ArrayDataSource(data=reg.xserr),
                                       yerror=ArrayDataSource(data=reg.yserr),
                                       type='scatter',
                                       marker=marker,
                                       selection_marker=marker,
                                       selection_marker_size=marker_size,
                                       bind_id=self.group_id,
                                       color=color,
                                       marker_size=marker_size)
        graph.set_series_label('data{}'.format(self.group_id))

        eo = ErrorEllipseOverlay(component=scatter,
                                 reg=reg,
                                 border_color=color,
                                 fill=opt.fill_ellipses,
                                 kind=opt.ellipse_kind)
        scatter.overlays.append(eo)

        ma = max(reg.xs)
        self.xma = max(self.xma, ma)
        self.xmi = min(self.xmi, min(reg.xs))

        mi = 0
        rxs = linspace(mi, ma * 1.1)
        rys = reg.predict(rxs)

        graph.set_x_limits(min_=mi, max_=ma, pad='0.1')

        l, _ = graph.new_series(rxs, rys, color=color)
        graph.set_series_label('fit{}'.format(self.group_id))

        l.index.set_data(rxs)
        l.value.set_data(rys)
        yma, ymi = max(rys), min(rys)

        try:
            self.ymis[pid] = min(self.ymis[pid], ymi)
            self.ymas[pid] = max(self.ymas[pid], yma)
        except IndexError:
            self.ymis.append(ymi)
            self.ymas.append(yma)

        if opt.include_error_envelope:
            lci, uci = reg.calculate_error_envelope(l.index.get_data())
            ee = ErrorEnvelopeOverlay(component=l,
                                      upper=uci, lower=lci,
                                      line_color=color)
            l.underlays.append(ee)
            l.error_envelope = ee

        if opt.display_inset:
            self._add_inset(plot, reg)

        if self.group_id == 0:
            if opt.show_nominal_intercept:
                self._add_atm_overlay(plot)

            graph.add_vertical_rule(0, color='black')
        if opt.show_results_info:
            self._add_results_info(plot, text_color=color)
        if opt.show_info:
            self._add_info(plot)

        if opt.show_labels:
            self._add_point_labels(scatter)

        def ad(i, x, y, ai):
            a = ai.isotopes['Ar39'].get_interference_corrected_value()
            b = ai.isotopes['Ar40'].get_interference_corrected_value()
            r = a / b
            v = nominal_value(r)
            e = std_dev(r)

            try:
                pe = '({:0.2f}%)'.format(e / v * 100)
            except ZeroDivisionError:
                pe = '(Inf%)'

            return u'39Ar/40Ar= {} {}{} {}'.format(floatfmt(v, n=6), PLUSMINUS, floatfmt(e, n=7), pe)

        self._add_scatter_inspector(scatter, additional_info=ad)
        p.index_mapper.on_trait_change(self.update_index_mapper, 'updated')

        # sel = self._get_omitted_by_tag(self.analyses)
        # self._rebuild_iso(sel)
        self.replot()
Exemplo n.º 16
0
    def _plot_references(self, pid, po):
        graph = self.graph
        efit = po.fit.lower()
        r_xs = self.rxs
        r_ys, r_es = self.reference_data(po)

        ymi, yma = self._calc_limits(r_ys, r_es)

        reg = None
        kw = dict(
            add_tools=False,
            add_inspector=False,
            color='red',
            plotid=pid,
            selection_marker=po.marker,
            marker=po.marker,
            marker_size=po.marker_size,
        )

        update_meta_func = None
        if efit in [
                'preceding', 'bracketing interpolate', 'bracketing average'
        ]:
            reg = InterpolationRegressor(xs=r_xs,
                                         ys=r_ys,
                                         yserr=r_es,
                                         kind=efit)
            scatter, _p = graph.new_series(r_xs,
                                           r_ys,
                                           yerror=r_es,
                                           type='scatter',
                                           fit=False,
                                           **kw)

            def update_meta_func(obj, b, c, d):
                self.update_interpolation_regressor(po.name, reg, obj)

            self._add_error_bars(scatter, r_es, 'y', self.options.nsigma, True)

            ffit = po.fit
        else:
            ffit = '{}_{}'.format(po.fit, po.error_type)
            _, scatter, l = graph.new_series(r_xs,
                                             r_ys,
                                             yerror=ArrayDataSource(data=r_es),
                                             fit=ffit,
                                             **kw)
            if hasattr(l, 'regressor'):
                reg = l.regressor
            self._add_error_bars(scatter, r_es, 'y', self.options.nsigma, True)

        def af(i, x, y, analysis):
            return ('Run Date: {}'.format(
                analysis.rundate.strftime('%m-%d-%Y %H:%M')),
                    'Rel. Time: {:0.4f}'.format(x))

        self._add_scatter_inspector(scatter,
                                    update_meta_func=update_meta_func,
                                    add_selection=True,
                                    additional_info=af,
                                    items=self.sorted_references)
        plot = self.graph.plots[pid]
        plot.isotope = po.name
        plot.fit = ffit

        scatter.index.metadata['selections'] = [
            i for i, r in enumerate(self.sorted_references) if r.temp_selected
        ]
        return reg, ymi, yma
Exemplo n.º 17
0
    def _series_factory(self, x, y, yer=None, plotid=0, add=True, **kw):
        """
        """

        if x is None:
            x = array([])
        if y is None:
            y = array([])

        if 'yerror' in kw:
            if not isinstance(kw['yerror'], ArrayDataSource):
                kw['yerror'] = ArrayDataSource(kw['yerror'])

        yername = None
        plot = self.plots[plotid]
        if add:
            if 'xname' in kw:
                xname = kw['xname']
            else:

                xname = next(self.xdataname_generators[plotid])
            if 'yname' in kw:
                yname = kw['yname']
            else:
                yname = next(self.ydataname_generators[plotid])

            names = (xname, yname)
            #             self.raw_x[plotid].append(x)
            #             self.raw_y[plotid].append(y)
            if yer is not None:
                # self.raw_yer[plotid].append(yer)
                yername = next(self.yerdataname_generators[plotid])
                names += (yername, )
            self.series[plotid].append(names)
        else:
            # try:
            xname = self.series[plotid][0][0]
            yname = self.series[plotid][0][1]
            if yer is not None:
                yername = self.series[plotid][0][2]
                # except IndexError:
                #     pass

        plot.data.set_data(xname, x)
        plot.data.set_data(yname, y)
        if yer is not None:
            plot.data.set_data(yername, yer)

        colorkey = 'color'
        if 'color' not in list(kw.keys()):
            color_gen = self.color_generators[plotid]
            c = next(color_gen)
        else:
            c = kw['color']
        if isinstance(c, str):
            c = c.replace(' ', '')

        if 'type' in kw:
            if kw['type'] == 'bar':
                colorkey = 'fill_color'
            elif kw['type'] == 'polygon':
                colorkey = 'face_color'
                kw['edge_color'] = c
            elif kw['type'] == 'scatter':
                if 'outline_color' not in kw:
                    kw['outline_color'] = c

        for k, v in [('render_style', 'connectedpoints'), (colorkey, c),
                     ('selection_color', 'white')]:
            if k not in list(kw.keys()):
                kw[k] = v

        return plot, (xname, yname), kw
Exemplo n.º 18
0
    def plot_desc(self, desc):
        plot = McPlot(desc.data)

        plot.title = desc.title
        plot.x_axis.title = desc.x
        plot.y_axis.title = desc.y

        log = desc.log
        ztool = ZTool

        if None not in (desc.data['value_low'], desc.data['value_high']):
            # 1d
            value_scale = 'log' if log else 'linear'
            plot.plot((desc.x, desc.y),
                      name='data',
                      value_scale=value_scale,
                      **desc.params)

            # extract and prepare data for error bars
            ylow = ArrayDataSource(desc.data['value_low'])
            yhigh = ArrayDataSource(desc.data['value_high'])

            # create error bars object
            x = ArrayDataSource(desc.data[desc.x])
            scp = plot.plots['data'][0]
            ebp = ErrorBarPlot(index=x,
                               value_low=ylow,
                               value_high=yhigh,
                               index_mapper=scp.index_mapper,
                               value_mapper=scp.value_mapper,
                               origin=scp.origin)
            # add error bars to plot
            plot.add(ebp)

            # set aspect ratio
            plot.aspect_ratio = 1.0

        elif desc.data['imagedata'] is not None:
            # 2d
            data_name = 'imagedata_log' if log else 'imagedata'
            plot.img_plot(data_name, colormap=jet)
            # TODO: contour plots: plot.contour_plot('imagedata')

            # set apsect ratio
            img = desc.data[data_name]
            w, h = len(img), len(img[0])

            plot.aspect_ratio = float(h) / w
            ztool = ZoomWithAspectRatio

        # pan
        pan = PTool(plot, restrict_to_data=True)
        plot.tools.append(pan)
        self.pans.append(pan)

        # zoom
        zoom = ztool(plot,
                     tool_mode='box',
                     always_on=True,
                     drag_button='right')
        plot.overlays.append(zoom)
        self.zooms.append(zoom)

        # line inspector
        plot.overlays.append(Snapper(self.layout, plot))

        # save
        save = SaveTool(self.layout, always_on=True, filename="plot.pdf")
        plot.tools.append(save)

        # focus
        focus = FocusTool(self, desc)
        plot.tools.append(focus)

        return plot
Exemplo n.º 19
0
    def _plot_relative_probability(self, po, plot, pid):
        graph = self.graph
        bins, probs = self._calculate_probability_curve(self.xs,
                                                        self.xes,
                                                        calculate_limits=True)

        ogid = self.group_id
        gid = ogid + 1
        sgid = ogid * 2
        # print 'ogid={} gid={} sgid={}'.format(ogid, gid, sgid)
        plotkw = dict()
        # if self.group_id==0:
        # if self.options.use_filled_line:
        plotkw.update(**self.options.get_plot_dict(ogid))
        # color= self.options.fill_color
        # color.setAlphaF(self.options.fill_alpha*0.01)
        # plotkw['fill_color']=self.options.fill_color
        # plotkw['type']='filled_line'
        # else:

        line, _ = graph.new_series(x=bins, y=probs, plotid=pid, **plotkw)

        graph.set_series_label('Current-{}'.format(gid),
                               series=sgid,
                               plotid=pid)

        # add the dashed original line
        graph.new_series(x=bins,
                         y=probs,
                         plotid=pid,
                         visible=False,
                         color=line.color,
                         line_style='dash')

        graph.set_series_label('Original-{}'.format(gid),
                               series=sgid + 1,
                               plotid=pid)

        self._add_info(graph, plot)
        self._add_mean_indicator(graph, line, po, bins, probs, pid)

        mi, ma = min(probs), max(probs)

        # if not po.has_ylimits():
        self._set_y_limits(mi, ma, min_=0, pad='0.025')

        d = lambda a, b, c, d: self.update_index_mapper(a, b, c, d)
        plot.index_mapper.on_trait_change(d, 'updated')

        # if self.group_id == 0:
        if self.options.display_inset:
            xs = self.xs
            n = xs.shape[0]

            startidx = 1
            if self.group_id > 0:
                for ov in plot.overlays:
                    if isinstance(ov, IdeogramPointsInset):
                        print self.group_id, startidx, ov.value.get_bounds(
                        )[1] + 1
                        startidx = max(startidx, ov.value.get_bounds()[1] + 1)
            else:
                startidx = 1

            if self.options.analysis_number_sorting == 'Oldest @Top':
                ys = arange(startidx, startidx + n)
            else:
                ys = arange(startidx + n - 1, startidx - 1, -1)

            yma2 = max(ys) + 1
            h = self.options.inset_height / 2.0
            if self.group_id == 0:
                bgcolor = self.options.get_formatting_value('plot_bgcolor')
            else:
                bgcolor = 'transparent'

            d = self.options.get_plot_dict(ogid)
            o = IdeogramPointsInset(self.xs,
                                    ys,
                                    color=d['color'],
                                    outline_color=d['color'],
                                    bgcolor=bgcolor,
                                    width=self.options.inset_width,
                                    height=h,
                                    visible_axes=False,
                                    xerror=ArrayDataSource(self.xes),
                                    location=self.options.inset_location)
            # o.x_axis.visible = False
            plot.overlays.append(o)

            cfunc = lambda x1, x2: self._cumulative_probability(
                self.xs, self.xes, x1, x2)
            xs, ys, xmi, xma = self._calculate_asymptotic_limits(
                cfunc, asymptotic_width=10, tol=10)
            oo = IdeogramInset(xs,
                               ys,
                               color=d['color'],
                               bgcolor=bgcolor,
                               yoffset=h,
                               visible_axes=self.group_id == 0,
                               width=self.options.inset_width,
                               height=self.options.inset_height,
                               location=self.options.inset_location)

            yma = max(ys)
            if self.group_id > 0:
                for ov in plot.overlays:
                    if isinstance(ov, IdeogramInset):
                        mi, ma = ov.get_x_limits()
                        xmi = min(mi, xmi)
                        xma = max(ma, xma)

                        _, ma = ov.get_y_limits()
                        yma = max(ma, yma)

            plot.overlays.append(oo)
            for ov in plot.overlays:
                if isinstance(ov, IdeogramInset):
                    ov.set_x_limits(xmi, xma)
                    ov.set_y_limits(0, yma * 1.1)
                elif isinstance(ov, IdeogramPointsInset):
                    ov.set_x_limits(xmi, xma)
                    ov.set_y_limits(0, yma2)
Exemplo n.º 20
0
    def _rebuild_database_graph(self, options):
        ans = self.analyses
        if ans:
            g = self.graph
            g.new_plot()

            i_attr = options.index_attr
            v_attr = options.value_attr

            if i_attr == 'timestamp' or v_attr == 'timestamp':
                ans = sorted(ans, key=lambda x: x.timestamp)

            uxs = [ai.get_value(i_attr) for ai in ans]
            uys = [ai.get_value(v_attr) for ai in ans]
            xs = array([nominal_value(ui) for ui in uxs])
            ys = array([nominal_value(ui) for ui in uys])
            eys = array([std_dev(ui) for ui in uys])
            exs = array([std_dev(ui) for ui in uxs])

            if i_attr == 'timestamp':
                xtitle = 'Normalized Analysis Time'
                xs = self._normalize(xs, options.index_time_scalar)
            else:
                xtitle = i_attr

            if v_attr == 'timestamp':
                ytitle = 'Normalized Analysis Time'
                ys = self._normalize(ys, options.value_time_scalar)
            else:
                ytitle = v_attr

            ytitle = self._pretty(ytitle)
            xtitle = self._pretty(xtitle)

            scatter = self.plot_series(g, options, xs, ys)

            scatter.yerror = ArrayDataSource(eys)
            scatter.xerror = ArrayDataSource(exs)

            self._add_scatter_inspector(scatter, ans)

            if options.index_error:

                n = options.index_nsigma
                self._add_error_bars(scatter,
                                     exs,
                                     'x',
                                     n,
                                     end_caps=options.index_end_caps)
                xmn, xmx = min(xs - exs), max(xs + exs)
            else:
                xmn, xmx = min(xs), max(xs)

            if options.value_error:

                n = options.value_nsigma
                self._add_error_bars(scatter,
                                     eys,
                                     'y',
                                     n,
                                     end_caps=options.value_end_caps)
                ymn, ymx = min(ys - eys * n), max(ys + eys * n)
            else:
                ymn, ymx = min(ys), max(ys)

            g.set_x_limits(xmn, xmx, pad='0.1')
            g.set_y_limits(ymn, ymx, pad='0.1')

            g.set_x_title(xtitle)
            g.set_y_title(ytitle)
            g.refresh()