Example #1
0
    def _graph_factory(self, graph=None):
        if graph is None:
            graph = Graph(
                window_title=self.title,
                container_dict=dict(padding=5,
                                    bgcolor='lightgray'))

        graph.new_plot(
            padding=[50, 5, 5, 50],
            xtitle='DAC (V)',
            ytitle='Intensity (fA)',
            zoom=False,
            show_legend='ul',
            legend_kw=dict(
                font='modern 8',
                line_spacing=1))

        self._series_factory(graph)

        graph.set_series_label('*{}'.format(self.reference_detector))
        self._markup_idx = 1
        spec = self.spectrometer
        for di in self.additional_detectors:
            det = spec.get_detector(di)
            c = det.color
            self._series_factory(graph, line_color=c)
            graph.set_series_label(di)

        if self.show_label:
            graph.add_plot_label('{}@{}'.format(self.reference_isotope,
                                                self.reference_detector), hjustify='center')
        return graph
Example #2
0
 def _pos_graph_default(self):
     g = Graph()
     p = g.new_plot()
     s, p = g.new_series()
     cp = CurrentPointOverlay(component=s)
     s.overlays.append(cp)
     self._cp = cp
     return g
Example #3
0
 def _pos_graph_default(self):
     g = Graph()
     p = g.new_plot()
     s, p = g.new_series()
     cp = CurrentPointOverlay(component=s)
     s.overlays.append(cp)
     self._cp = cp
     return g
Example #4
0
    def _src_graph_default(self):
        g = Graph()
        p = g.new_plot(padding_top=10)
        p.data.set_data("imagedata", zeros((self.height * self.pxpermm, self.width * self.pxpermm)))
        p.img_plot("imagedata", colormap=jet)

        p = g.new_plot(padding_bottom=10)
        p.data.set_data("imagedata", zeros((self.height * self.pxpermm, self.width * self.pxpermm)))
        p.img_plot("imagedata", colormap=jet)

        return g
    def _graph_factory(self):
        graph = Graph(container_dict=dict(padding=5,
                                          bgcolor='lightgray'))

        graph.new_plot(
                       padding=[50, 5, 5, 50],
#                       title='{}'.format(self.title),
                       xtitle='CDD Operating Voltage (V)',
                       ytitle='Intensity (fA)',
                       )
        graph.new_series(type='scatter',
                         marker='pixel')
        return graph
Example #6
0
    def _test(self):

        p = '/Users/ross/Pychrondata_demo/data/snapshots/scan6/007.jpg'
        g = Graph()
        g.new_plot()

        for scan_i, z, idxs in [
                #                    1,
                #                     2,
                #                     3, 4, 5,
                #                     (6, [20, 30, 40, 50, 60, 70, 80, 90, 100, ],
                #                         [2, 3, 4, 5, 6, 7, 8, 9, 10]
                #                      ),
            (6, [10], [1]),
                #                     (6, [100, 90, 80, 70, 60, 50, 40, 30, 20],
                #                         [11, 12, 13, 14, 15, 16, 17, 18, 19]
                #                     )
        ]:
            dxs = []
            zs = []
            root = '/Users/ross/Pychrondata_demo/data/snapshots/scan{}'.format(
                scan_i)
            for zi, idx in zip(z, idxs):
                pn = os.path.join(root, '{:03n}.jpg'.format(idx))
                d = load_image(pn)

                dx = self._calculate_spacing(d)
                dxs.append(dx)

                zs.append(zi)

            g.new_series(zs, dxs, type='scatter')

            coeffs = polyfit(zs, dxs, 2)
            print 'parabolic intercept {}'.format(coeffs[-1])

            xs = linspace(0, max(zs))
            ys = polyval(coeffs, xs)
            g.new_series(xs, ys)

            fitfunc = lambda p, x: p[0] * exp(p[1] * x) + p[2]
            lr = LeastSquaresRegressor(fitfunc=fitfunc,
                                       initial_guess=[1, 0.1, 0],
                                       xs=zs,
                                       ys=dxs)
            xs = linspace(0, max(zs))
            ys = lr.predict(xs)
            print 'exponential intercept {}'.format(lr.predict(0))
            g.new_series(xs, ys)

        invoke_in_main_thread(g.edit_traits)
Example #7
0
    def _graph_factory(self):
        g = Graph(window_title='Coincidence Scan',
                  container_dict=dict(padding=5, bgcolor='lightgray')
                  )
        g.new_plot(padding=[50, 5, 5, 50],
                   ytitle='Intensity (fA)',
                   xtitle='Operating Voltage (V)')

        for di in self.spectrometer.detectors:
            g.new_series(
                         name=di.name,
                         color=di.color)

        return g
Example #8
0
    def _test(self):

        p = '/Users/ross/Pychrondata_demo/data/snapshots/scan6/007.jpg'
        g = Graph()
        g.new_plot()


        for scan_i, z, idxs in [
#                    1,
#                     2,
#                     3, 4, 5,
#                     (6, [20, 30, 40, 50, 60, 70, 80, 90, 100, ],
#                         [2, 3, 4, 5, 6, 7, 8, 9, 10]
#                      ),
                    (6, [10],
                        [1]
                     ),
#                     (6, [100, 90, 80, 70, 60, 50, 40, 30, 20],
#                         [11, 12, 13, 14, 15, 16, 17, 18, 19]
#                     )

                   ]:
            dxs = []
            zs = []
            root = '/Users/ross/Pychrondata_demo/data/snapshots/scan{}'.format(scan_i)
            for  zi, idx in zip(z, idxs):
                pn = os.path.join(root, '{:03n}.jpg'.format(idx))
                d = load_image(pn)

                dx = self._calculate_spacing(d)
                dxs.append(dx)

                zs.append(zi)

            g.new_series(zs, dxs, type='scatter')

            coeffs = polyfit(zs, dxs, 2)
            print 'parabolic intercept {}'.format(coeffs[-1])

            xs = linspace(0, max(zs))
            ys = polyval(coeffs, xs)
            g.new_series(xs, ys)

            fitfunc = lambda p, x: p[0] * exp(p[1] * x) + p[2]
            lr = LeastSquaresRegressor(fitfunc=fitfunc,
                                       initial_guess=[1, 0.1, 0],
                                       xs=zs,
                                       ys=dxs
                                       )
            xs = linspace(0, max(zs))
            ys = lr.predict(xs)
            print 'exponential intercept {}'.format(lr.predict(0))
            g.new_series(xs, ys)

        invoke_in_main_thread(g.edit_traits)
Example #9
0
    def _src_graph_default(self):
        g = Graph()
        p = g.new_plot(padding_top=10)
        p.data.set_data(
            'imagedata',
            zeros((self.height * self.pxpermm, self.width * self.pxpermm)))
        p.img_plot('imagedata', colormap=jet)

        p = g.new_plot(padding_bottom=10)
        p.data.set_data(
            'imagedata',
            zeros((self.height * self.pxpermm, self.width * self.pxpermm)))
        p.img_plot('imagedata', colormap=jet)

        return g
Example #10
0
 def _graph_default(self):
     g = Graph(container_dict=dict(padding=5))
     g.new_plot(padding=5)
     g.set_axis_traits(axis='y', visible=False)
     g.set_axis_traits(axis='x', visible=False)
     g.set_grid_traits(grid='x', visible=False)
     g.set_grid_traits(grid='y', visible=False)
     return g
Example #11
0
    def _graph_default(self):
        g = Graph(container_dict={
#                                  'fill_padding':True,
#                                  'bgcolor':'red',
                                  'padding':5
                                  })
        self._plot_factory(g)
        return g
Example #12
0
    def __init__(self, *args, **kw):
        super(FractionalLossCalculator, self).__init__(*args, **kw)

        self.graph = g = Graph()
        g.new_plot()

        xs, ys = self._calculate_data()
        g.new_series(xs, ys)
    def _graph_factory(self):
        gc = self.graph_cnt
        cnt = '' if not gc else gc
        self.graph_cnt += 1
        name = self.parent.name if self.parent else 'Foo'

        g = Graph(window_title='{} Power Calibration {}'.format(name, cnt),
                               container_dict=dict(padding=5),
                               window_x=500 + gc * 25,
                               window_y=25 + gc * 25
                               )

        g.new_plot(
                   xtitle='Setpoint (%)',
                   ytitle='Measured Power (W)')
        g.new_series()
        return g
Example #14
0
    def _rebuild_hole_vs_j(self, x, y, r, reg):
        g = Graph()
        self.graph = g

        p = g.new_plot(xtitle='Hole (Theta)',
                       ytitle='J',
                       padding=[90, 5, 5, 40])

        p.y_axis.tick_label_formatter = lambda x: floatfmt(x, n=2, s=3)

        xs = arctan2(x, y)
        ys = reg.ys
        yserr = reg.yserr

        scatter, _ = g.new_series(xs, ys,
                                  yerror=yserr,
                                  type='scatter', marker='circle')

        ebo = ErrorBarOverlay(component=scatter,
                              orientation='y')
        scatter.overlays.append(ebo)
        self._add_inspector(scatter)

        a = max((abs(min(xs)), abs(max(xs))))

        fxs = linspace(-a, a)

        a = r * sin(fxs)
        b = r * cos(fxs)
        pts = vstack((a, b)).T

        fys = reg.predict(pts)

        g.new_series(fxs, fys)
        g.set_x_limits(-3.2, 3.2)
Example #15
0
    def _gc(self, p, det, kind):
        g = Graph(container_dict=dict(padding=5), window_width=1000, window_height=800, window_x=40, window_y=20)
        with open(p, "r") as rfile:
            # gather data
            reader = csv.reader(rfile)
            header = reader.next()
            groups = self._parse_data(reader)
            """
                groups= [data,]
                data shape = nrow,ncols
                
            """
            data = groups[0]
            x = data[0]
            y = data[header.index(det)]

        sy = smooth(y, window_len=120)  # , window='flat')

        x = x[::50]
        y = y[::50]
        sy = sy[::50]

        # smooth

        # plot
        g.new_plot(zoom=True, xtitle="Time (s)", ytitle="{} Baseline Intensity (fA)".format(det))
        g.new_series(x, y, type=kind, marker="dot", marker_size=2)
        g.new_series(x, sy, line_width=2)
        #        g.set_x_limits(500, 500 + 60 * 30)
        #        g.edit_traits()
        return g
Example #16
0
 def _graph_default(self):
     g = Graph(container_dict=dict(padding=5))
     g.new_plot(padding=5)
     g.set_axis_traits(axis='y', visible=False)
     g.set_axis_traits(axis='x', visible=False)
     g.set_grid_traits(grid='x', visible=False)
     g.set_grid_traits(grid='y', visible=False)
     return g
Example #17
0
        def _graph_default(self):
            g = Graph()
            p = g.new_plot()
            txt = 'gooiooi \N{Plus-minus sign} \N{Greek Small Letter Sigma} \u03AE \u00ae \u00a3'
            txt2 = 'aaaaaa \xb1 \u00b1'

            pl = PlotLabel(txt,
                           overlay_position='inside bottom',
                           font='Helvetica 12')
            pl2 = PlotLabel(txt2,
                            x=100,
                            y=100,
                            overlay_position='inside bottom',
                            font='Helvetica 24')

            s, p = g.new_series([1, 2, 3, 4, 5, 6], [10, 21, 34, 15, 133, 1])
            s.overlays.append(pl)
            s.overlays.append(pl2)
            return g
Example #18
0
    def _pre_execute(self):
        pattern = self.pattern

        kind = pattern.kind
        if kind == 'SeekPattern':
            from pychron.graph.graph import Graph

            g = Graph(window_x=1000, window_y=100, window_height=900)
            self._info = open_view(g)
            self._seek_graph = g
    def _execute_power_calibration_check(self):
        """

        """
        g = Graph()
        g.new_plot()
        g.new_series()
        g.new_series(x=[0, 100], y=[0, 100], line_style='dash')
        do_later(self._open_graph, graph=g)

        self._stop_signal = TEvent()
        callback = lambda pi, r: None
        self._iterate(self.check_parameters, g, False, callback)
Example #20
0
    def graph(poly, opoly, line):
        from pychron.graph.graph import Graph

        g = Graph()
        g.new_plot()

        for po in (poly, opoly):
            po = np.array(po)
            try:
                xs, ys = po.T
            except ValueError:
                xs, ys, _ = po.T
            xs = np.hstack((xs, xs[0]))
            ys = np.hstack((ys, ys[0]))
            g.new_series(xs, ys)

        #    for i, (p1, p2) in enumerate(lines):
        #        xi, yi = (p1[0], p2[0]), (p1[1], p2[1])
        #        g.new_series(xi, yi, color='black')
        return g
Example #21
0
    def __init__(self, *args, **kw):
        super(Scanner, self).__init__(*args, **kw)
        graph = Graph()
        self.graph = graph

        p = graph.new_plot(padding_top=30, padding_right=10)

        self._add_bounds(p)
        self._add_mftable_overlay(p)
        self._add_limit_tool(p)
        p.index_range.on_trait_change(self._handle_xbounds_change, 'updated')
        # graph.set_x_limits(self.min_dac, self.max_dac)
        graph.new_series()
        graph.set_x_title('Magnet DAC (Voltage)')
        graph.set_y_title('Intensity')

        self._use_mftable_limits_fired()
Example #22
0
    def _graph_default(self):
        g = Graph(container_dict=dict(padding=5,

                                      kind='h'))
        g.new_plot(xtitle='weight (mg)', ytitle='40Ar* (fA)',
                   padding=[60, 20, 60, 60]
#                   padding=60
                   )

        g.new_series()
        g.new_plot(xtitle='40Ar* (fA)', ytitle='%Error in Age',
                   padding=[30, 30, 60, 60]
                   )
        g.new_series()
#        fp = create_line_plot(([], []), color='red')
#        left, bottom = add_default_axes(fp)
#        bottom.visible = False
#        left.orientation = 'right'
#        left.axis_line_visible = False
#        bottom.axis_line_visible = False
#        left.visible = False

#        if self.kind == 'weight':
#            bottom.visible = True
#            bottom.orientation = 'top'
#            bottom.title = 'Error (ka)'
#            bottom.tick_color = 'red'
#            bottom.tick_label_color = 'red'
#            bottom.line_color = 'red'
#            bottom.title_color = 'red'
#        else:
#            left.title = 'Weight (mg)'
#        fp.visible = False
#        gd = GuideOverlay(fp, value=0.01, orientation='v')
#        fp.overlays.append(gd)
#        g.plots[0].add(fp)
#        self.secondary_plot = fp

        return g
Example #23
0
    def __init__(self, *args, **kw):
        super(Scanner, self).__init__(*args, **kw)
        graph = Graph()
        self.graph = graph

        p = graph.new_plot(padding_top=30, padding_right=10)

        self._add_bounds(p)
        self._add_mftable_overlay(p)
        self._add_limit_tool(p)
        p.index_range.on_trait_change(self._handle_xbounds_change, 'updated')
        # graph.set_x_limits(self.min_dac, self.max_dac)
        graph.new_series()
        graph.set_x_title('Magnet DAC (Voltage)')
        graph.set_y_title('Intensity')

        self._use_mftable_limits_fired()
Example #24
0
    def make_component(self, padding):
        cg = ContourGraph()

        cg.new_plot(title='Beam Space',
                    xtitle='X mm',
                    ytitle='Y mm',
                    aspect_ratio=1
                    )

        g = Graph()
        g.new_plot(title='Motor Space',
                     xtitle='X mm',
                     ytitle='Power',
                     )
        g.new_series(
                     )

        self.graph = g
        self.contour_graph = cg
        c = HPlotContainer()
        c.add(g.plotcontainer)
        c.add(cg.plotcontainer)

        return c
    def _execute_power_calibration_check(self):
        '''
        
        '''
        g = Graph()
        g.new_plot()
        g.new_series()
        g.new_series(x=[0, 100], y=[0, 100], line_style='dash')
        do_later(self._open_graph, graph=g)

        self._stop_signal = TEvent()
        callback = lambda pi, r: None
        self._iterate(self.check_parameters,
                      g, False, callback)
    def _graph_factory(self):
        graph = Graph(container_dict=dict(padding=5, bgcolor='lightgray'))

        graph.new_plot(
            padding=[50, 5, 5, 50],
            #                       title='{}'.format(self.title),
            xtitle='CDD Operating Voltage (V)',
            ytitle='Intensity (fA)',
        )
        graph.new_series(type='scatter', marker='pixel')
        return graph
Example #27
0
    def _graph_default(self):
        g = Graph(container_dict=dict(padding=5,

                                      kind='h'))
        g.new_plot(xtitle='weight (mg)', ytitle='40Ar* (fA)',
                   padding=[60, 20, 60, 60]
#                   padding=60
                   )

        g.new_series()
        g.new_plot(xtitle='40Ar* (fA)', ytitle='%Error in Age',
                   padding=[30, 30, 60, 60]
                   )
        g.new_series()
#        fp = create_line_plot(([], []), color='red')
#        left, bottom = add_default_axes(fp)
#        bottom.visible = False
#        left.orientation = 'right'
#        left.axis_line_visible = False
#        bottom.axis_line_visible = False
#        left.visible = False

#        if self.kind == 'weight':
#            bottom.visible = True
#            bottom.orientation = 'top'
#            bottom.title = 'Error (ka)'
#            bottom.tick_color = 'red'
#            bottom.tick_label_color = 'red'
#            bottom.line_color = 'red'
#            bottom.title_color = 'red'
#        else:
#            left.title = 'Weight (mg)'
#        fp.visible = False
#        gd = GuideOverlay(fp, value=0.01, orientation='v')
#        fp.overlays.append(gd)
#        g.plots[0].add(fp)
#        self.secondary_plot = fp

        return g
Example #28
0
    def _graph_factory(self):
        g = Graph(window_title='Coincidence Scan',
                  container_dict=dict(padding=5, bgcolor='lightgray')
                  )
        g.new_plot(padding=[50, 5, 5, 50],
                   ytitle='Intensity (fA)',
                   xtitle='Operating Voltage (V)')

        for di in self.spectrometer.detectors:
            g.new_series(
                         name=di.name,
                         color=di.color)

        return g
Example #29
0
    def passive_focus(self, block=False, **kw):

        self._evt_autofocusing = TEvent()
        self._evt_autofocusing.clear()
        #        manager = self.laser_manager
        oper = self.parameters.operator
        self.info('passive focus. operator = {}'.format(oper))

        g = self.graph
        if not g:
            g = Graph(plotcontainer_dict=dict(padding=10),
                      window_x=0.70,
                      window_y=20,
                      window_width=325,
                      window_height=325,
                      window_title='Autofocus')
            self.graph = g

        g.clear()

        g.new_plot(padding=[40, 10, 10, 40],
                   xtitle='Z (mm)',
                   ytitle='Focus Measure ({})'.format(oper))
        g.new_series()
        g.new_series()

        invoke_in_main_thread(self._open_graph)

        target = self._passive_focus
        self._passive_focus_thread = Thread(name='autofocus',
                                            target=target,
                                            args=(self._evt_autofocusing, ),
                                            kwargs=kw)
        self._passive_focus_thread.start()
        if block:
            #             while 1:
            #                 if not self._passive_focus_thread.isRunning():
            #                     break
            #                 time.sleep(0.25)
            self._passive_focus_thread.join()
    def _graph_factory(self):
        gc = self.graph_cnt
        cnt = '' if not gc else gc
        self.graph_cnt += 1
        name = self.parent.name if self.parent else 'Foo'

        g = Graph(window_title='{} Power Calibration {}'.format(name, cnt),
                  container_dict=dict(padding=5),
                  window_x=500 + gc * 25,
                  window_y=25 + gc * 25)

        g.new_plot(xtitle='Setpoint (%)', ytitle='Measured Power (W)')
        g.new_series()
        return g
Example #31
0
    def passive_focus(self, block=False, **kw):

        self._evt_autofocusing = TEvent()
        self._evt_autofocusing.clear()
#        manager = self.laser_manager
        oper = self.parameters.operator
        self.info('passive focus. operator = {}'.format(oper))

        g = self.graph
        if not g:
            g = Graph(plotcontainer_dict=dict(padding=10),
                      window_x=0.70,
                      window_y=20,
                      window_width=325,
                      window_height=325,
                      window_title='Autofocus'
                      )
            self.graph = g

        g.clear()

        g.new_plot(padding=[40, 10, 10, 40],
                   xtitle='Z (mm)',
                   ytitle='Focus Measure ({})'.format(oper)
                   )
        g.new_series()
        g.new_series()

        invoke_in_main_thread(self._open_graph)

        target = self._passive_focus
        self._passive_focus_thread = Thread(name='autofocus', target=target,
                                            args=(self._evt_autofocusing,

                                                  ),
                                            kwargs=kw
                                            )
        self._passive_focus_thread.start()
        if block:
#             while 1:
#                 if not self._passive_focus_thread.isRunning():
#                     break
#                 time.sleep(0.25)
            self._passive_focus_thread.join()
    def _finish_calibration(self):
        super(FusionsCO2PowerCalibrationManager, self)._finish_calibration()
        g = Graph()
        g.new_plot()

        # plot W vs 8bit dac
        x = self.graph.get_data(axis=1)
        _, y = self.graph.get_aux_data()

        xf = self.graph.get_data(axis=1, series=2)
        _, yf = self.graph.get_aux_data(series=3)

#        print xf
#        print yf
        x, y = zip(*zip(x, y))
        xf, yf = zip(*zip(xf, yf))
        g.new_series(x, y)
        g.new_series(xf, yf)

        self._ipm_coeffs_w_v_r = self._regress(x, y, FITDEGREES['linear'])
        self. _ipm_coeffs_w_v_r1 = self._regress(xf, yf, FITDEGREES['linear'])

        self._open_graph(graph=g)
Example #33
0
    def _gc(self, p, det, kind):
        g = Graph(container_dict=dict(padding=5),
                  window_width=1000,
                  window_height=800,
                  window_x=40,
                  window_y=20)
        with open(p, 'r') as rfile:
            # gather data
            reader = csv.reader(rfile)
            header = reader.next()
            groups = self._parse_data(reader)
            '''
                groups= [data,]
                data shape = nrow,ncols
                
            '''
            data = groups[0]
            x = data[0]
            y = data[header.index(det)]

        sy = smooth(y, window_len=120)  # , window='flat')

        x = x[::50]
        y = y[::50]
        sy = sy[::50]

        # smooth

        # plot
        g.new_plot(zoom=True,
                   xtitle='Time (s)',
                   ytitle='{} Baseline Intensity (fA)'.format(det))
        g.new_series(x, y, type=kind, marker='dot', marker_size=2)
        g.new_series(x, sy, line_width=2)
        #        g.set_x_limits(500, 500 + 60 * 30)
        #        g.edit_traits()
        return g
Example #34
0
    def _rebuild_hole_vs_j(self, x, y, r, reg):
        g = Graph()
        self.graph = g

        p = g.new_plot(xtitle='Hole (Theta)',
                       ytitle='J',
                       padding=[90, 5, 5, 40])

        p.y_axis.tick_label_formatter = lambda x: floatfmt(x, n=2, s=3)

        xs = arctan2(x, y)
        ys = reg.ys
        yserr = reg.yserr

        scatter, _ = g.new_series(xs,
                                  ys,
                                  yerror=yserr,
                                  type='scatter',
                                  marker='circle')

        ebo = ErrorBarOverlay(component=scatter, orientation='y')
        scatter.overlays.append(ebo)
        self._add_inspector(scatter)

        a = max((abs(min(xs)), abs(max(xs))))

        fxs = linspace(-a, a)

        a = r * sin(fxs)
        b = r * cos(fxs)
        pts = vstack((a, b)).T

        fys = reg.predict(pts)

        g.new_series(fxs, fys)
        g.set_x_limits(-3.2, 3.2)
Example #35
0
    def graph(poly, opoly, line):
        from pychron.graph.graph import Graph

        g = Graph()
        g.new_plot()

        for po in (poly, opoly):
            po = np.array(po)
            try:
                xs, ys = po.T
            except ValueError:
                xs, ys, _ = po.T
            xs = np.hstack((xs, xs[0]))
            ys = np.hstack((ys, ys[0]))
            g.new_series(xs, ys)

    #    for i, (p1, p2) in enumerate(lines):
    #        xi, yi = (p1[0], p2[0]), (p1[1], p2[1])
    #        g.new_series(xi, yi, color='black')
        return g
Example #36
0
    def make_component(self, padding):
        cg = ContourGraph()

        cg.new_plot(title='Beam Space',
                    xtitle='X mm',
                    ytitle='Y mm',
                    aspect_ratio=1)

        g = Graph()
        g.new_plot(
            title='Motor Space',
            xtitle='X mm',
            ytitle='Power',
        )
        g.new_series()

        self.graph = g
        self.contour_graph = cg
        c = HPlotContainer()
        c.add(g.plotcontainer)
        c.add(cg.plotcontainer)

        return c
Example #37
0
        r = [i40 / i36 for i40, i36 in zip(s40, s36)]

        v = [vi.nominal_value for vi in r]
        errs = [vi.std_dev for vi in r]

        m, e = calculate_weighted_mean(v, errs)

        return m, e


if __name__ == '__main__':
    from numpy import linspace, polyfit, polyval

    d = DeadTime()
    g = Graph()

    g.new_plot(padding=[30, 10, 20, 40])
    g.new_plot(padding=[30, 10, 20, 40], show_legend=True)
    nshots = d.read_csv()
    #    taus = range(5, 40, 5)
    taus = linspace(0, 30, 41)
    rratios1 = []
    mswds1 = []

    for i in KEYS:
        s40 = nshots[i + '40']
        s36 = nshots[i + '36']
        m1, _ = d._calculate_mean_ratio(s40, s36)
        print 'uncorrected ratio {} = {:0.2f} '.format(i, m1)
Example #38
0
    def _graph_factory(self, graph=None):
        if graph is None:
            graph = Graph(
                container_dict=dict(padding=5,
                                    bgcolor='lightgray'))

        graph.new_plot(
            padding=[50, 5, 5, 50],
            #                       title='{}'.format(self.title),
            xtitle='DAC (V)',
            ytitle='Intensity (fA)',
            show_legend='ul',
            legend_kw=dict(
                font='modern 8',
                line_spacing=1))

        graph.new_series(line_width=2)

        graph.set_series_label('*{}'.format(self.reference_detector))
        self._markup_idx = 1
        spec = self.spectrometer
        for di in self.additional_detectors:
            det = spec.get_detector(di)
            c = det.color
            graph.new_series(line_color=c)
            graph.set_series_label(di)
            self._markup_idx += 1

        graph.new_series(type='scatter', marker='circle',
                         marker_size=4,
                         color='green')
        graph.new_series(type='scatter', marker='circle',
                         marker_size=4,
                         color='green')

        #graph.plots[0].value_range.tight_bounds = False
        return graph
Example #39
0
 def _peak_center_graph_default(self):
     g = Graph()
     g.page_name = 'Peak Center'
     return g
Example #40
0
    def _graph_factory(self, **kw):
        g = Graph(
            window_height=250,
            window_width=300,
            container_dict=dict(padding=0))
        g.new_plot(
            bounds=[250, 250],
            resizable='',
            padding=[30, 0, 0, 30])

        cx = self.cx
        cy = self.cy
        cbx = self.xbounds
        cby = self.ybounds
        tr = self.target_radius

        g.set_x_limits(*cbx)
        g.set_y_limits(*cby)

        lp, _plot = g.new_series()
        t = TargetOverlay(component=lp,
                          cx=cx,
                          cy=cy,
                          target_radius=tr)

        lp.overlays.append(t)
        overlap_overlay = OverlapOverlay(component=lp,
                                         visible=self.show_overlap)
        lp.overlays.append(overlap_overlay)

        self._graph_factory_hook(lp)

        g.new_series(type='scatter', marker='circle')
        g.new_series(type='line', color='red')
        return g
Example #41
0
 def _graph_factory(self):
     g = Graph()
     p = g.new_plot(padding_top=30, padding_right=10)
     self._setup_graph(g, p)
     return g
Example #42
0
    poly = np.array(poly)
    poly *= 1000

#    xs, ys = poly.T
#    cx, cy = xs.mean(), ys.mean()
#    poly = rotate_poly(poly.T, 45, loc=(cx, cy))
#    poly = poly.T

    use_convex_hull = False
    npoints, lens = raster(poly,
                     step=750,
                     offset=-500,
                     use_convex_hull=use_convex_hull, find_min=True)

    from pychron.graph.graph import Graph
    g = Graph(window_height=700)
    g.plotcontainer.padding = 5
    g.new_plot(padding=[60, 30, 30, 50],
               bounds=[400, 400],
               resizable='h',
               xtitle='X (microns)',
               ytitle='Y (microns)')

    if use_convex_hull:
        poly = convex_hull(poly)
        xs, ys = poly.T
        cx, cy = xs.mean(), ys.mean()
        P = poly.T
        xs = np.hstack((xs, xs[0]))
        ys = np.hstack((ys, ys[0]))
    else:
Example #43
0
    def _graph_factory(self, **kw):
        g = Graph(
            window_height=250,
            window_width=300,
            container_dict=dict(padding=0))
        g.new_plot(
            bounds=[250, 250],
            resizable='',
            padding=[30, 0, 0, 30])

        cx = self.cx
        cy = self.cy
        cbx = self.xbounds
        cby = self.ybounds
        tr = self.target_radius

        g.set_x_limits(*cbx)
        g.set_y_limits(*cby)

        lp, _plot = g.new_series()
        t = TargetOverlay(component=lp,
                          cx=cx,
                          cy=cy,
                          target_radius=tr)

        lp.overlays.append(t)
        overlap_overlay = OverlapOverlay(component=lp,
                                         visible=self.show_overlap)
        lp.overlays.append(overlap_overlay)

        self._graph_factory_hook(lp)

        g.new_series(type='scatter', marker='circle')
        g.new_series(type='line', color='red')
        return g
Example #44
0
    poly = [(2, 7), (4, 12), (8, 15), (16, 9), (11, 5), (8, 7), (5, 5)]
    poly = sort_clockwise(poly, poly)
    poly = np.array(poly)
    poly *= 1000

    #    xs, ys = poly.T
    #    cx, cy = xs.mean(), ys.mean()
    #    poly = rotate_poly(poly.T, 45, loc=(cx, cy))
    #    poly = poly.T

    use_convex_hull = False
    npoints, lens = raster(poly, step=750, offset=-500, use_convex_hull=use_convex_hull, find_min=True)

    from pychron.graph.graph import Graph

    g = Graph(window_height=700)
    g.plotcontainer.padding = 5
    g.new_plot(padding=[60, 30, 30, 50], bounds=[400, 400], resizable="h", xtitle="X (microns)", ytitle="Y (microns)")

    if use_convex_hull:
        poly = convex_hull(poly)
        xs, ys = poly.T
        cx, cy = xs.mean(), ys.mean()
        P = poly.T
        xs = np.hstack((xs, xs[0]))
        ys = np.hstack((ys, ys[0]))
    else:
        xs, ys = poly.T
        xs = np.hstack((xs, xs[0]))
        ys = np.hstack((ys, ys[0]))
Example #45
0
 def _graph_default(self):
     return Graph(container_dict=dict(
         stack_order='top_to_bottom', padding=5, spacing=0))
Example #46
0
    def _graph_hole_vs_j(self, x, y, r, reg, refresh):

        if self._individual_analyses_enabled:
            sel = [
                i for i, (a, x, y, e) in enumerate(zip(*self._analyses))
                if a.is_omitted()
            ]

        g = self.graph
        if not isinstance(g, Graph):
            g = Graph(container_dict={'bgcolor': self.plotter_options.bgcolor})
            self.graph = g

        po = self.plotter_options

        ys = reg.ys
        xs = arctan2(x, y)

        yserr = reg.yserr
        lyy = ys - yserr
        uyy = ys + yserr
        a = max((abs(min(xs)), abs(max(xs))))
        fxs = linspace(-a, a, 200)

        a = r * sin(fxs)
        b = r * cos(fxs)
        pts = vstack((a, b)).T
        fys = reg.predict(pts)

        use_ee = False
        if po.model_kind not in (MATCHING, BRACKETING, NN):
            use_ee = True
            try:
                l, u = reg.calculate_error_envelope(fxs, rmodel=fys)
            except BaseException:
                l, u = reg.calculate_error_envelope(pts, rmodel=fys)

        if not refresh:
            g.clear()
            p = g.new_plot(
                xtitle='Hole (Theta)',
                ytitle='J',
                # padding=[90, 5, 5, 40],
                padding=po.get_paddings())
            p.bgcolor = po.plot_bgcolor

            add_axes_tools(g, p)

            def label_fmt(xx):
                return floatfmt(xx, n=2, s=4, use_scientific=True)

            p.y_axis.tick_label_formatter = label_fmt

            # plot fit line
            # plot0 == line

            if po.model_kind in (MATCHING, BRACKETING, NN):
                g.new_series(fxs, fys, render_style='connectedhold')
            else:
                line, _p = g.new_series(fxs, fys)
                if use_ee:
                    ee = ErrorEnvelopeOverlay(component=line,
                                              xs=fxs,
                                              lower=l,
                                              upper=u)
                    line.error_envelope = ee
                    line.underlays.append(ee)

            miy = 100
            may = -1

            if self._individual_analyses_enabled:
                # plot the individual analyses
                # plot1 == scatter
                iscatter, iys = self._graph_individual_analyses()
                miy = min(iys)
                may = max(iys)

            # plot means
            # plot2 == scatter
            scatter, _ = g.new_series(xs,
                                      ys,
                                      yerror=yserr,
                                      type='scatter',
                                      marker_size=4,
                                      marker='diamond')

            ebo = ErrorBarOverlay(component=scatter, orientation='y')
            scatter.underlays.append(ebo)
            scatter.error_bars = ebo

            add_inspector(scatter, self._additional_info)

            ymi = min(lyy.min(), miy)
            yma = max(uyy.max(), may)
            g.set_x_limits(-3.5, 3.5)
            g.set_y_limits(ymi, yma, pad='0.1')

            if self._individual_analyses_enabled:
                # set metadata last because it will trigger a refresh
                self.suppress_metadata_change = True
                iscatter.index.metadata['selections'] = sel
                self.suppress_metadata_change = False

            if self._individual_analyses_enabled:
                # add a legend
                labels = [
                    ('plot1', 'Individual'),
                    ('plot2', 'Mean'),
                    ('plot0', 'Fit'),
                ]
            else:
                labels = [('plot0', 'Mean')]

            legend = ExplicitLegend(plots=self.graph.plots[0].plots,
                                    labels=labels)
            p.overlays.append(legend)

        else:
            plot = g.plots[0]
            s1 = plot.plots['plot2'][0]
            s1.yerror.set_data(yserr)
            s1.error_bars.invalidate()

            g.set_data(ys, plotid=0, series=2, axis=1)

            l1 = plot.plots['plot0'][0]
            l1.index.metadata['selections'] = sel
            g.set_data(fys, plotid=0, series=0, axis=1)

            if use_ee:
                l1.error_envelope.trait_set(xs=fxs, lower=l, upper=u)
                l1.error_envelope.invalidate()

        self.max_j = fys.max()
        self.min_j = fys.min()
Example #47
0

d = os.path.dirname(os.getcwd())
sys.path.append(d)

from pychron.core.ui import set_toolkit

set_toolkit('qt4')

from pychron.graph.graph import Graph
from pychron.graph.tools.limits_tool import LimitsTool, LimitOverlay


xs = linspace(0, pi * 2)
ys = cos(xs)

g = Graph()
p = g.new_plot()
g.new_series(xs, ys)

t = LimitsTool(component=p)
o = LimitOverlay(component=p, tool=t)
p.tools.append(t)
p.overlays.append(o)

t = LimitsTool(component=p, orientation='y')
o = LimitOverlay(component=p, tool=t)
p.tools.append(t)
p.overlays.append(o)

g.configure_traits()
Example #48
0
    def _graph_factory(self, with_image=False):
        g = Graph(window_height=250, window_width=300, container_dict=dict(padding=0))
        g.new_plot(bounds=[250, 250], resizable="", padding=[30, 0, 0, 30])

        cx = self.cx
        cy = self.cy
        cbx = self.xbounds
        cby = self.ybounds
        tr = self.target_radius

        #        if with_image:
        #            px = self.pxpermm  #px is in mm
        #            cbx, cby = self._get_crop_bounds()
        #            #g.set_axis_traits(tick_label_formatter=lambda x: '{:0.2f}'.format((x - w / 2) / px))
        #            #g.set_axis_traits(tick_label_formatter=lambda x: '{:0.2f}'.format((x - h / 2) / px), axis='y')
        #
        #            bx, by = g.plots[0].bounds
        #            g.plots[0].x_axis.mapper = LinearMapper(high_pos=bx,
        #                                                    range=DataRange1D(low_setting=self.xbounds[0],
        #                                                                      high_setting=self.xbounds[1]))
        #            g.plots[0].y_axis.mapper = LinearMapper(high_pos=by,
        #                                                    range=DataRange1D(low_setting=self.ybounds[0],
        #                                                                      high_setting=self.ybounds[1]))
        #            cx += self.image_width / 2
        #            cy += self.image_height / 2
        #            tr *= px

        g.set_x_limits(*cbx)
        g.set_y_limits(*cby)

        lp, _plot = g.new_series()
        t = TargetOverlay(component=lp, cx=cx, cy=cy, target_radius=tr)

        lp.overlays.append(t)
        overlap_overlay = OverlapOverlay(component=lp, visible=self.show_overlap)
        lp.overlays.append(overlap_overlay)

        g.new_series(type="scatter", marker="circle")
        g.new_series(type="line", color="red")
        return g
Example #49
0
 def _graph_factory(self):
     g = Graph()
     p = g.new_plot(padding_top=30, padding_right=10)
     self._setup_graph(g, p)
     return g
Example #50
0
    def _execute_seek(self, controller, pattern):
        from pychron.core.ui.gui import invoke_in_main_thread
        from pychron.graph.graph import Graph

        duration = pattern.duration
        g = Graph()
        g.edit_traits()
        g.new_plot()
        s, p = g.new_series()

        g.new_plot()
        g.new_series(type='line')

        cp = CurrentPointOverlay(component=s)
        s.overlays.append(cp)
        w = 2
        g.set_x_limits(-w, w)
        g.set_y_limits(-w, w)
        om = 60
        g.set_x_limits(max_=om, plotid=1)

        lm = self.laser_manager
        sm = lm.stage_manager

        st = time.time()

        def update_graph(zs, zz, xx, yy):
            cp.point = (xx, yy)
            g.add_datum((xx, yy), plotid=0)
            t = time.time() - st
            g.add_datum((t, zz),
                        update_y_limits=True,
                        plotid=1)

            g.add_datum((t,) * len(zs), zs,
                        update_y_limits=True,
                        plotid=1, series=1)
            g.set_x_limits(max_=max(om, t + 10), plotid=1)
            g.redraw()

        pp = os.path.join(paths.data_dir, 'seek_pattern.txt')
        with open(pp, 'w') as wfile:
            cx, cy = pattern.cx, pattern.cy
            wfile.write('{},{}\n'.format(cx, cy))
            wfile.write('#z,     x,     y,     n\n')
            gen = pattern.point_generator()
            for x, y in gen:
                if not self._alive:
                    break

                with PeriodCTX(1):
                    # x, y = gen.next()
                    # x, y = pattern.next_point
                    controller.linear_move(cx + x, cy + y, block=False, velocity=pattern.velocity)

                    mt = time.time()
                    zs = []
                    while sm.moving():
                        _, _, v = sm.get_brightness()
                        zs.append(v)

                    while 1:
                        if time.time() - mt > duration:
                            break
                        _, _, v = sm.get_brightness()
                        zs.append(v)

                    if zs:
                        n = len(zs)
                        z = sum(zs) / float(n)
                        self.debug('XY:({},{}) Z:{}, N:{}'.format(x, y, z, n))
                        pattern.set_point(z, x, y)

                        wfile.write('{:0.5f},{:0.3f},{:0.3f},{}\n'.format(z, x, y, n))

                        invoke_in_main_thread(update_graph, zs, z, x, y)
        g.close_ui()
Example #51
0
    poly = np.array(poly)
    poly *= 1000

#    xs, ys = poly.T
#    cx, cy = xs.mean(), ys.mean()
#    poly = rotate_poly(poly.T, 45, loc=(cx, cy))
#    poly = poly.T

    use_convex_hull = False
    npoints, lens = raster(poly,
                     step=750,
                     offset=-500,
                     use_convex_hull=use_convex_hull, find_min=True)

    from pychron.graph.graph import Graph
    g = Graph(window_height=700)
    g.plotcontainer.padding = 5
    g.new_plot(padding=[60, 30, 30, 50],
               bounds=[400, 400],
               resizable='h',
               xtitle='X (microns)',
               ytitle='Y (microns)')

    if use_convex_hull:
        poly = convex_hull(poly)
        xs, ys = poly.T
        cx, cy = xs.mean(), ys.mean()
        P = poly.T
        xs = np.hstack((xs, xs[0]))
        ys = np.hstack((ys, ys[0]))
    else:
Example #52
0
    def _amplitude_graph_factory(self):
        g = Graph()
        p = g.new_plot(show_legend='ul')
        p.index_range.tight_bounds = False
        p.value_range.tight_bounds = False

        x, y, spx, spy = self._calculate_power_series()
        g.new_series(x, y, type='line', color='red')
        g.set_series_label('Power')
        x, y, szx, szy = self._calculate_z_series()
        g.new_series(x, y, type='line', color='blue')
        g.set_series_label('Z')

        g.new_series(spx, spy, type='scatter', color='red')
        g.new_series(szx, szy, type='scatter', color='blue')

        # g.new_series(type='scatter', marker='circle')
        return g
Example #53
0
 def _graph_default(self):
     g = Graph(container_dict=dict(padding=5))
     return g
    def _graph_hole_vs_j(self, x, y, r, reg, refresh):

        sel = [i for i, a in enumerate(self.analyses) if a.is_omitted()]

        g = self.graph
        if not isinstance(g, Graph):
            g = Graph(container_dict={'bgcolor': self.plotter_options.bgcolor})
            self.graph = g

        po = self.plotter_options

        xs = arctan2(x, y)
        ys = reg.ys
        a = max((abs(min(xs)), abs(max(xs))))
        fxs = linspace(-a, a)

        a = r * sin(fxs)
        b = r * cos(fxs)
        pts = vstack((a, b)).T

        fys = reg.predict(pts)
        yserr = reg.yserr
        l, u = reg.calculate_error_envelope([[p] for p in pts], rmodel=fys)

        lyy = ys - yserr
        uyy = ys + yserr

        if not refresh:
            g.clear()
            p = g.new_plot(xtitle='Hole (Theta)',
                           ytitle='J',
                           # padding=[90, 5, 5, 40],
                           padding=po.paddings())
            p.bgcolor = po.plot_bgcolor

            p.y_axis.tick_label_formatter = lambda x: floatfmt(x, n=2, s=4, use_scientific=True)

            scatter, _ = g.new_series(xs, ys,
                                      yerror=yserr,
                                      type='scatter', marker='circle')

            ebo = ErrorBarOverlay(component=scatter,
                                  orientation='y')
            scatter.overlays.append(ebo)
            scatter.error_bars = ebo

            add_inspector(scatter, self._additional_info)
            line, _p = g.new_series(fxs, fys)

            ee = ErrorEnvelopeOverlay(component=line,
                                      xs=fxs, lower=l, upper=u)
            line.error_envelope = ee
            line.overlays.append(ee)

            # plot the individual analyses
            s, iys = self._graph_individual_analyses()
            s.index.metadata['selections'] = sel
            # s.index.metadata_changed = True

            ymi = min(lyy.min(), min(iys))
            yma = max(uyy.max(), max(iys))
            g.set_x_limits(-3.2, 3.2)

        else:
            plot = g.plots[0]

            s1 = plot.plots['plot0'][0]
            s1.yerror.set_data(yserr)
            s1.error_bars.invalidate()

            l1 = plot.plots['plot1'][0]
            l1.error_envelope.trait_set(xs=fxs, lower=l, upper=u)
            l1.error_envelope.invalidate()

            g.set_data(ys, plotid=0, series=0, axis=1)
            g.set_data(fys, plotid=0, series=1, axis=1)

            s2 = plot.plots['plot2'][0]
            iys = s2.value.get_data()
            ymi = min(fys.min(), lyy.min(), iys.min())
            yma = max(fys.max(), uyy.max(), iys.max())

            s2.index.metadata['selections'] = sel

        g.set_y_limits(ymi, yma, pad='0.1')
        self._model_sin_flux(fxs, fys)
Example #55
0
    def _canvas_default(self):
        g = Graph()

        return g
Example #56
0
    def cup_deflection_calibration(self, mass):

        self.info('{} deflection calibration'.format(self.reference_detector))

        rgraph = RegressionGraph(window_x=100,
                                window_y=50)
        rgraph.new_plot()
        rgraph.new_series(yer=[])

        root_dir = unique_dir(os.path.join(paths.data_dir, 'magfield'), '{}_def_calibration'.format(self.reference_detector))
#        if not os.path.exists(root_dir):
#            os.mkdir(root_dir)

        dm = self.data_manager

        p = os.path.join(root_dir, 'defl_vs_dac.csv')
        deflection_frame_key = dm.new_frame(path=p)

        dm.write_to_frame(['Deflection (V)', '40{} DAC'.format(self.reference_detector)],
                          frame_key=deflection_frame_key)

        start = self.dc_start
        stop = self.dc_stop
        width = self.dc_step
        nstep = (stop - start) / width + 1

        npeak_centers = self.dc_npeak_centers
        self.info('Deflection scan parameters start={}, stop={}, stepwidth={}, nstep={}'.format(start, stop, width, nstep))
        self.info('Reference detector {}'.format(self.reference_detector))
        self.info('Peak centers per step n={}'.format(npeak_centers))

        for i, ni in enumerate(np.linspace(start, stop, nstep)):
            if not self.isAlive():
                break
            self.info('Deflection step {} {} (V)'.format(i + 1, ni))
            self._detectors[self.reference_detector].deflection = ni
            ds = []
            for n in range(npeak_centers):
                if not self.isAlive():
                    break
                self.info('Peak center ni = {}'.format(n + 1))

                p = os.path.join(root_dir, 'peak_scan_{:02d}_{:02d}.csv'.format(int(ni), n))
                dm.new_frame(path=p)
                dm.write_to_frame(['DAC (V)', 'Intensity (fA)'])

                graph = Graph(window_title='Peak Centering',
                              window_x=175 + i * 25 + n * 5,
                              window_y=25 + i * 25 + n * 5
                              )

                self.peak_center(graph=graph,
                                  update_mftable=True,
                                  update_pos=False,
                                  center_pos=mass
                                  )

                if self.isAlive():
                    # write scan to file
                    dm.write_to_frame(list(zip(graph.get_data(), graph.get_data(axis=1))))

                    if npeak_centers > 1:
                        if not self.simulation:
                            time.sleep(1)

                    if self.peak_center_results:
                        d = (ni, self.peak_center_results[0][1])
                        ds.append(self.peak_center_results[0][1])
                        dm.write_to_frame(list(d), frame_key=deflection_frame_key)

                        # write the centering results to the centering file
                        dm.write_to_frame([('#{}'.format(x), y) for x, y in  zip(graph.get_data(series=1), graph.get_data(series=1, axis=1))])

            if self.peak_center_results:
                rgraph.add_datum((ni, np.mean(ds), np.std(ds)))

            if i == 2:
                invoke_in_main_thread(rgraph.edit_traits)

            # delay so we can view graph momonetarily
            if not self.simulation and self.isAlive():
                time.sleep(2)

        self.info('deflection calibration finished')