Example #1
0
    def __init__(self,parent,owner=None,_larch=None,size=(500, 100)):

        wx.Panel.__init__(self, parent)
        self.owner = owner

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1D = PlotPanel(self,size=size,messenger=self.owner.write_message)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        self.SetSizer(vbox)

        self.plot1D.cursor_callback = self.on_cursor
Example #2
0
    def __init__(self, parent):
        SectionPointDefsPanelBase.__init__(self, parent)
        # 用于存放 solve之后的值
        self._args = dict()
        self.point_list = list()

        # 这是一个复连通的全局变量
        self.MP = MultiConnectPoly()
        # 再来一个复合截面的全局变量
        self.Comp = compoundSection()

        # 仅仅只是初始化了画布
        self.plotpanel = PlotPanel(self.m_panel1, size=(300, 300), fontsize=5)
        self.plotpanel.BuildPanel()
Example #3
0
    def render_power(self, event):
        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            if (self.power_rendered):
                self.canvas2.update_line(0,
                                         self.data.truncated_frequency,
                                         self.data.truncated_power,
                                         draw=True)
            else:
                self.canvas2 = PlotPanel(self.m_panel3,
                                         size=(self.m_panel3.GetSize()))

                if hasattr(self.data, 'truncated_frequency') and hasattr(
                        self.data, 'truncated_power'):
                    self.canvas2.plot(self.data.truncated_frequency,
                                      self.data.truncated_power, 'r')
                    self.canvas2.oplot(
                        self.data.truncated_frequency,
                        np.full((len(self.data.truncated_frequency)),
                                self.data.min))
                    self.power_rendered = True

            return

        # For slider
        else:

            p = backend.get_cutoff_value(self.data.min, self.data.slope,
                                         self.m_slider1.GetValue())
            if (self.power_rendered):
                self.canvas2.update_line(
                    1,
                    self.data.truncated_frequency,
                    np.full((len(self.data.truncated_frequency)), p),
                    draw=True)

            else:
                self.canvas2 = PlotPanel(self.m_panel3,
                                         size=(self.m_panel3.GetSize()))
                self.canvas2.plot(self.data.truncated_frequency,
                                  self.data.truncated_power, 'r')
                self.canvas2.oplot(
                    self.data.truncated_frequency,
                    np.full((len(self.data.truncated_frequency)),
                            self.data.min))
                self.power_rendered = True

            return
    def __init__(self, parent):
        SectionParamsDefsPanelBase.__init__(self, parent)
        # ÓÃÓÚ´æ·Å solveÖ®ºóµÄÖµ
        self._args = dict()

        self.plotpanel = PlotPanel(self.m_panel_canvas, size=(300, 300), fontsize=5)
        self.plotpanel.BuildPanel()

        # ĬÈϽØÃæÐÎ×´
        self._section_type = u'Ö±½Ç¸Ö'

        # ½ØÃæ²ÎÊýµÚÒ»ÁÐÖ»¶Á
        for irow in range(self.m_grid_params_defs.GetNumberRows()):
            self.m_grid_params_defs.SetReadOnly(irow, 0, True)

        self.grid_value = {
                           u'Ö±½Ç¸Ö': ['±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2', 'ÄÚÔ²»¡°ë¾¶'],
                           u'¹¤×Ö¸Ö': ['¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶', '½Ç¶ËÔ²»¡°ë¾¶' ],
                           u'²Û¸Ö':   ['¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶', '½Ç¶ËÔ²»¡°ë¾¶' ],
                           #u'CÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ßºñ¶È1', 'Ñüºñ¶È', '±ßºñ¶È2', '±ß¿í¶È2'],
                           u'TÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2'],
                           u'ñÐ͸Ö': ['¸ß¶È', '½Å±ß¿í¶È', 'Í·±ß¿í¶È', 'ÍÈÇã½Ç', '½Å±ßºñ¶È', 'ÍȺñ¶È', 'Í·ºñ¶È'],
                           u'JÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ß¿í¶È3', '±ßºñ¶È1', '±ßºñ¶È2', '±ßºñ¶È3']
                          }

        for num in range(len(self.grid_value[self._section_type])):
            self.m_grid_params_defs.SetCellValue(num, 0, self.grid_value[self._section_type][num])
Example #5
0
class diFFit1DPanel(wx.Panel):
    '''
    Panel for housing 1D XRD
    '''
    def __init__(self,parent,owner=None,_larch=None,size=(500, 100)):

        wx.Panel.__init__(self, parent)
        self.owner = owner

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1D = PlotPanel(self,size=size,messenger=self.owner.write_message)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        self.SetSizer(vbox)

        self.plot1D.cursor_callback = self.on_cursor

    def on_cursor(self,x=None, y=None, **kw):

        xi = self.owner.xaxis_type.GetSelection()
        if xi == 1:
            self.owner.twth = x
        else:
            ix = np.abs(self.owner.data1dxrd[1]-self.owner.twth).argmin()
            self.owner.twth = self.owner.data1dxrd[1][ix]

        self.owner.xrd1Dviewer.plot_line(x=x)
        self.owner.xrd2Dviewer.plot_ring()
        self.owner.xrd2Dcake.plot_line()

    def plot_line(self,x=None):

        if x is None:
            xi = self.owner.xaxis_type.GetSelection()
            if xi != 1:
                ix = np.abs(self.owner.data1dxrd[1]-self.owner.twth).argmin()
                x = self.owner.data1dxrd[xi][ix]
            else:
                x = self.owner.twth

        try:
            self.xrd_line.remove()
        except:
            pass

        self.xrd_line = self.plot1D.axes.axvline(x=x, color='r', linewidth=1)
        self.plot1D.draw()
Example #6
0
 def createPlotPanel(self):
     """xrd plot window"""
     pan = PlotPanel(self, fontsize=7,
                     axisbg='#FEFEFE',
                     output_title='test.xrd',
                     messenger=self.write_message)
     pan.conf.grid_color='#E5E5C0'
     pan.conf.show_grid = False
     pan.conf.canvas.figure.set_facecolor('#FCFCFE')
     pan.conf.labelfont.set_size(6)
     pan.conf.labelfont.set_size(6)
     pan.onRightDown= partial(self.on_cursor, side='right')
     pan.add_cursor_mode('zoom',  motion = self.ignoreEvent,
                         leftup   = self.ignoreEvent,
                         leftdown = self.on_cursor,
                         rightdown = partial(self.on_cursor, side='right'))
     return pan
Example #7
0
 def createPlotPanel(self):
     """xrd plot window"""
     pan = PlotPanel(self, fontsize=7,
                     axisbg='#FEFEFE',
                     output_title='test.xrd',
                     messenger=self.write_message)
     pan.conf.grid_color='#E5E5C0'
     pan.conf.show_grid = False
     pan.conf.canvas.figure.set_facecolor('#FCFCFE')
     pan.conf.labelfont.set_size(6)
     pan.conf.labelfont.set_size(6)
     pan.onRightDown= partial(self.on_cursor, side='right')
     pan.add_cursor_mode('zoom',  motion = self.ignoreEvent,
                         leftup   = self.ignoreEvent,
                         leftdown = self.on_cursor,
                         rightdown = partial(self.on_cursor, side='right'))
     return pan
Example #8
0
class diFFit1DPanel(wx.Panel):
    '''
    Panel for housing 1D XRD
    '''
    def __init__(self,parent,owner=None,_larch=None,size=(500, 100)):

        wx.Panel.__init__(self, parent)
        self.owner = owner

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1D = PlotPanel(self,size=size,messenger=self.owner.write_message)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        self.SetSizer(vbox)

        self.plot1D.cursor_callback = self.on_cursor

    def on_cursor(self,x=None, y=None, **kw):

        xi = self.owner.xaxis_type.GetSelection()
        if xi == 1:
            self.owner.twth = x
        else:
            ix = np.abs(self.owner.data1dxrd[1]-self.owner.twth).argmin()
            self.owner.twth = self.owner.data1dxrd[1][ix]

        self.owner.xrd1Dviewer.plot_line(x=x)
        self.owner.xrd2Dviewer.plot_ring()
        self.owner.xrd2Dcake.plot_line()

    def plot_line(self,x=None):

        if x is None:
            xi = self.owner.xaxis_type.GetSelection()
            if xi != 1:
                ix = np.abs(self.owner.data1dxrd[1]-self.owner.twth).argmin()
                x = self.owner.data1dxrd[xi][ix]
            else:
                x = self.owner.twth

        try:
            self.xrd_line.remove()
        except:
            pass

        self.xrd_line = self.plot1D.axes.axvline(x=x, color='r', linewidth=1)
        self.plot1D.draw()
Example #9
0
    def plot1DXRD(self,panel):
    
        self.plot1D = PlotPanel(panel,size=(1000, 500))
        self.plot1D.messenger = self.owner.write_message
        

        ## Set defaults for plotting  
        self.plot1D.set_ylabel('Intensity (a.u.)')
        self.plot1D.cursor_mode = 'zoom'
    def __init__(self, parent):
        SectionParamsDefsPanelBase.__init__(self, parent)
        # ÓÃÓÚ´æ·Å solveÖ®ºóµÄÖµ
        self._args = dict()

        self.plotpanel = PlotPanel(self.m_panel_canvas,
                                   size=(300, 300),
                                   fontsize=5)
        self.plotpanel.BuildPanel()

        # ĬÈϽØÃæÐÎ×´
        self._section_type = u'Ö±½Ç¸Ö'

        # ½ØÃæ²ÎÊýµÚÒ»ÁÐÖ»¶Á
        for irow in range(self.m_grid_params_defs.GetNumberRows()):
            self.m_grid_params_defs.SetReadOnly(irow, 0, True)

        self.grid_value = {
            u'Ö±½Ç¸Ö':
            ['±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2', 'ÄÚÔ²»¡°ë¾¶'],
            u'¹¤×Ö¸Ö': [
                '¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶',
                '½Ç¶ËÔ²»¡°ë¾¶'
            ],
            u'²Û¸Ö': [
                '¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶',
                '½Ç¶ËÔ²»¡°ë¾¶'
            ],
            #u'CÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ßºñ¶È1', 'Ñüºñ¶È', '±ßºñ¶È2', '±ß¿í¶È2'],
            u'TÐ͸Ö': ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2'],
            u'ñÐ͸Ö': [
                '¸ß¶È', '½Å±ß¿í¶È', 'Í·±ß¿í¶È', 'ÍÈÇã½Ç', '½Å±ßºñ¶È', 'ÍȺñ¶È',
                'Í·ºñ¶È'
            ],
            u'JÐ͸Ö': [
                '¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ß¿í¶È3', '±ßºñ¶È1', '±ßºñ¶È2',
                '±ßºñ¶È3'
            ]
        }

        for num in range(len(self.grid_value[self._section_type])):
            self.m_grid_params_defs.SetCellValue(
                num, 0, self.grid_value[self._section_type][num])
Example #11
0
    def __init__(self,parent,owner=None,_larch=None,size=(500, 100)):

        wx.Panel.__init__(self, parent)
        self.owner = owner

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1D = PlotPanel(self,size=size,messenger=self.owner.write_message)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        self.SetSizer(vbox)

        self.plot1D.cursor_callback = self.on_cursor
Example #12
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: MainFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.alarm_plt = PlotPanel(self)
        #self.timestamp_sld = wx.Slider(self, -1, 0, 0, 10)
        self.avg_hr_title_lbl = wx.StaticText(self, -1, "Current avg. HR:")
        self.avg_hr_lbl = wx.StaticText(self, -1, "nan")
        self.panel_1 = wx.Panel(self, -1)
        self.avg_acc_title_lbl = wx.StaticText(self, -1,
                                               "Current avg. Acceleration:")
        self.avg_acc_lbl = wx.StaticText(self, -1, "nan")
        self.panel_2 = wx.Panel(self, -1)
        self.anomaly_lvl_curr_title_lbl = wx.StaticText(
            self, -1, "Anomaly level: Current:")
        self.anomaly_lvl_curr_lbl = wx.StaticText(self, -1, "nan")
        self.panel_3 = wx.Panel(self, -1)
        self.anomaly_lvl_max_title_lbl = wx.StaticText(
            self, -1, "                                 Max:")
        self.anomaly_lvl_max_lbl = wx.StaticText(self, -1, "nan")
        self.red_alarm_lbl = wx.Panel(self, -1)
        self.anomaly_lvl_min_title_lbl = wx.StaticText(
            self, -1, "                                 Min:")
        self.anomaly_lvl_min_lbl = wx.StaticText(self, -1, "nan")
        self.yellow_alarm_lbl = wx.Panel(self, -1)
        self.anomaly_lvl_avg_title_lbl = wx.StaticText(
            self, -1, "                                 Average:")
        self.anomaly_lvl_avg_lbl = wx.StaticText(self, -1, "nan")
        self.green_alarm_lbl = wx.Panel(self, -1)
        self.collect_btn = wx.Button(self, -1, "Collect data")

        self.__set_properties()
        self.__do_layout()

        #self.Bind(wx.EVT_COMMAND_SCROLL, self.timestamp_sld_scroll, self.timestamp_sld)
        self.Bind(wx.EVT_BUTTON, self.collect_btn_click, self.collect_btn)
        # end wxGlade
        self.timer_thread = Timer(target=self.timer_tick)
        self.proxy = DeviceProxy(MainFrame.monitor_address)
        self.alarms = set()
Example #13
0
    def render_input_sound(self, event):

        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            self.m_panel2.Refresh()

            self.canvas1 = PlotPanel(self.m_panel2,
                                     size=(self.m_panel2.GetSize()))

            if hasattr(self.data, 'time') and hasattr(self.data,
                                                      'input_sound'):
                self.canvas1.plot(self.data.time, self.data.input_sound)

            return

        else:
            self.canvas1.update_line(0,
                                     self.data.time,
                                     self.data.input_sound,
                                     draw=True)
            return
Example #14
0
    def render_output(self, event):

        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            self.m_panel4.Refresh()

            self.canvas3 = PlotPanel(self.m_panel4,
                                     size=(self.m_panel4.GetSize()))

            if hasattr(self.data, 'time') and hasattr(self.data, 'ifft'):
                self.canvas3.plot(self.data.time, self.data.ifft)

            return

        else:

            self.canvas3.update_line(0,
                                     self.data.time,
                                     self.data.ifft,
                                     draw=True)
            return
Example #15
0
class ColumnDataFileFrame(wx.Frame) :
    """Column Data File, select columns"""
    def __init__(self, parent, filename=None, groupname=None,
                 last_array_sel=None, read_ok_cb=None,
                 edit_groupname=True, _larch=None):
        self.parent = parent
        self._larch = _larch
        self.path = filename
        self.extra_sums = {}

        group = self.initgroup = self.read_column_file(self.path)

        self.subframes = {}
        self.workgroup  = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype',
                     'array_labels', 'data'):
            setattr(self.workgroup, attr, getattr(group, attr, None))

        arr_labels = [l.lower() for l in self.initgroup.array_labels]

        if self.workgroup.datatype is None:
            self.workgroup.datatype = 'raw'
            for arrlab in arr_labels[:4]:
                if 'energ' in arrlab:
                    self.workgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb
        self.array_sel = {'xpop': '',  'xarr': None,
                          'ypop': '',  'yop': '/',
                          'yarr1': None, 'yarr2': None, 'use_deriv': False}

        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in arr_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in arr_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in arr_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % group.filename
        wx.Frame.__init__(self, None, -1,
                          'Build Arrays from Data Columns for %s' % group.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel, message, font=Font(13),
                           colour=self.colors.title, style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']

        self.xarr   = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1  = Choice(panel, choices= arr_labels, **opts)
        self.yarr2  = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.workgroup.datatype)


        opts['size'] = (50, -1)
        self.yop =  Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (150, -1)

        self.use_deriv = Check(panel, label='use derivative',
                               default=self.array_sel['use_deriv'], **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')
        self.message = SimpleText(panel, '', font=Font(11),
                           colour=self.colors.title, style=LCEN)

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels)-1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)

        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        _ok    = Button(bpanel, 'OK', action=self.onOK)
        _cancel = Button(bpanel, 'Cancel', action=self.onCancel)
        _edit   = Button(bpanel, 'Edit Array Names', action=self.onEditNames)
        _add    = Button(bpanel, 'Select Columns to Sum', action=self.onAddColumns)

        bsizer.Add(_ok)
        bsizer.Add(_cancel)
        bsizer.Add(_edit)
        bsizer.Add(_add)
        _ok.SetDefault()
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title,     (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab,       (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop,   (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf,  (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'),  (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype,                    (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel, value=group.groupname,
                                         size=(200, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname,               (ir, 1), (1, 2), LCEN, 0)
        sizer.Add(self.message,                     (ir, 3), (1, 4), LCEN, 0)


        ir += 1
        sizer.Add(bpanel,     (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel, style=wx.TE_MULTILINE|wx.TE_READONLY,
                               size=(400, 250))

        ftext.SetValue(group.text)
        ftext.SetFont(Font(10))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN|wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW|wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN|wx.GROW,   2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [group.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.Show()
        self.Raise()
        self.onUpdate(self)

    def read_column_file(self, path):
        """read column file, generally as initial read"""
        parent, filename = os.path.split(path)
        with open(path, 'r') as fh:
            lines = fh.readlines()

        text = ''.join(lines)
        line1 = lines[0].lower()

        reader = 'read_ascii'
        if 'epics stepscan file' in line1:
            reader = 'read_gsexdi'
        elif 'xdi' in line1:
            reader = 'read_xdi'
        elif 'epics scan' in line1:
            reader = 'read_gsescan'

        tmpname = '_tmp_file_'
        read_cmd = "%s = %s('%s')" % (tmpname, reader, path)
        self.reader = reader
        _larch = self._larch
        if (not isinstance(_larch, larch.Interpreter) and
            hasattr(_larch, '_larch')):
            _larch = _larch._larch
        try:
            _larch.eval(read_cmd, add_history=False)
        except:
            pass
        if _larch.error:
            msg = ["Error trying to read '%s':" % path, ""]
            for err in _larch.error:
                exc_name, errmsg = err.get_error()
                msg.append(errmsg)

            title = "Cannot read %s" % path
            r = Popup(self.parent, "\n".join(msg), title)
            return None

        group = _larch.symtable.get_symbol(tmpname)
        _larch.symtable.del_symbol(tmpname)

        group.text = text
        group.path = path
        group.filename = filename
        group.groupname = file2groupname(filename,
                                         symtable=self._larch.symtable)
        return group

    def show_subframe(self, name, frameclass, **opts):
        shown = False
        if name in self.subframes:
            try:
                self.subframes[name].Raise()
                shown = True
            except:
                del self.subframes[name]
        if not shown:
            self.subframes[name] = frameclass(self, **opts)

    def onAddColumns(self, event=None):
        self.show_subframe('addcol', AddColumnsFrame,
                           group=self.workgroup,
                           on_ok=self.add_columns)

    def add_columns(self, label, selection):
        new_labels = self.workgroup.array_labels
        self.set_array_labels(new_labels)
        self.yarr1.SetStringSelection(new_labels[-1])
        self.extra_sums[label] = selection
        self.onUpdate()

    def onEditNames(self, evt=None):
        self.show_subframe('editcol', EditColumnFrame,
                           group=self.workgroup,
                           on_ok=self.set_array_labels)



    def set_array_labels(self, arr_labels):
        self.workgroup.array_labels = arr_labels
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']
        def update(wid, choices):
            curstr = wid.GetStringSelection()
            curind = wid.GetSelection()
            wid.SetChoices(choices)
            if curstr in choices:
                wid.SetStringSelection(curstr)
            else:
                wid.SetSelection(curind)
        update(self.xarr,  xarr_labels)
        update(self.yarr1, yarr_labels)
        update(self.yarr2, yarr_labels)
        update(self.yerr_arr, yarr_labels)
        self.onUpdate()

    def onOK(self, event=None):
        """ build arrays according to selection """
        if self.wid_groupname is not None:
            groupname = fix_varname(self.wid_groupname.GetValue())

        yerr_op = self.yerr_op.GetStringSelection().lower()
        yerr_expr = '1'
        if yerr_op.startswith('const'):
            yerr_expr = "%f" % self.yerr_const.GetValue()
        elif yerr_op.startswith('array'):
            yerr_expr = '%%s.data[%i, :]' % self.yerr_arr.GetSelection()
        elif yerr_op.startswith('sqrt'):
            yerr_expr = 'sqrt(%s.ydat)'
        self.expressions['yerr'] = yerr_expr

        # generate script to pass back to calling program:
        labels = ', '.join(self.workgroup.array_labels)
        read_cmd = "%s('{path}', labels='%s')" % (self.reader, labels)

        buff = ["{group} = %s" % read_cmd,
                "{group}.path = '{path}'",
                "{group}.is_frozen = False"]

        for label, selection in self.extra_sums.items():
            buff.append("{group}.array_labels.append('%s')" % label)
            buff.append("_tmparr = {group}.data[%s, :].sum(axis=0)" % repr(selection))
            buff.append("_tmpn   = len(_tmparr)")
            buff.append("{group}.data = append({group}.data, _tmparr.reshape(1, _tmpn), axis=0)")
            buff.append("del _tmparr, _tmpn")


        for attr in ('datatype', 'plot_xlabel', 'plot_ylabel'):
            val = getattr(self.workgroup, attr)
            buff.append("{group}.%s = '%s'" % (attr, val))

        for aname in ('xdat', 'ydat', 'yerr'):
            expr = self.expressions[aname].replace('%s', '{group:s}')
            buff.append("{group}.%s = %s" % (aname, expr))

        if getattr(self.workgroup, 'datatype', 'raw') == 'xas':
            if self.reader == 'read_gsescan':
                buff.append("{group}.energy = {group}.x")
            else:
                buff.append("{group}.energy = {group}.xdat")
            buff.append("{group}.mu = {group}.ydat")
            buff.append("sort_xafs({group}, overwrite=True, fix_repeats=True)")

        script = "\n".join(buff)

        if self.read_ok_cb is not None:
            self.read_ok_cb(script, self.path, groupname=groupname,
                            array_sel=self.array_sel)

        for f in self.subframes.values():
            try:
                f.Destroy()
            except:
                pass
        self.Destroy()

    def onCancel(self, event=None):
        self.workgroup.import_ok = False
        for f in self.subframes.values():
            try:
                f.Destroy()
            except:
                pass
        self.Destroy()

    def onYerrChoice(self, evt=None):
        yerr_choice = evt.GetString()
        self.yerr_arr.Disable()
        self.yerr_const.Disable()
        if 'const' in yerr_choice.lower():
            self.yerr_const.Enable()
        elif 'array' in yerr_choice.lower():
            self.yerr_arr.Enable()
        self.onUpdate()


    def onUpdate(self, value=None, evt=None):
        """column selections changed calc xdat and ydat"""
        # dtcorr = self.dtcorr.IsChecked()
        # print("Column Frame on Update ")

        dtcorr = False
        use_deriv = self.use_deriv.IsChecked()
        rawgroup = self.initgroup
        workgroup = self.workgroup
        rdata = self.initgroup.data

        ix  = self.xarr.GetSelection()
        xname = self.xarr.GetStringSelection()

        exprs = dict(xdat=None, ydat=None, yerr=None)

        ncol, npts = rdata.shape
        workgroup.index = 1.0*np.arange(npts)
        if xname.startswith('_index') or ix >= ncol:
            workgroup.xdat = 1.0*np.arange(npts)
            xname = '_index'
            exprs['xdat'] = 'arange(%i)' % npts
        else:
            workgroup.xdat = rdata[ix, :]
            exprs['xdat'] = '%%s.data[%i, : ]' % ix

        workgroup.datatype = self.datatype.GetStringSelection().strip().lower()

        def pre_op(opwid, arr):
            opstr = opwid.GetStringSelection().strip()
            suf = ''
            if opstr in ('-log(', 'log('):
                suf = ')'
                if opstr == 'log(':
                    arr = np.log(arr)
                elif opstr == '-log(':
                    arr = -np.log(arr)
            return suf, opstr, arr

        try:
            xsuf, xpop, workgroup.xdat = pre_op(self.xpop, workgroup.xdat)
            self.xsuf.SetLabel(xsuf)
            exprs['xdat'] = '%s%s%s' % (xpop, exprs['xdat'], xsuf)
        except:
            return
        try:
            xunits = rawgroup.array_units[ix].strip()
            xlabel = '%s (%s)' % (xname, xunits)
        except:
            xlabel = xname

        yname1  = self.yarr1.GetStringSelection().strip()
        yname2  = self.yarr2.GetStringSelection().strip()
        iy1    = self.yarr1.GetSelection()
        iy2    = self.yarr2.GetSelection()
        yop = self.yop.GetStringSelection().strip()

        ylabel = yname1
        if len(yname2) == 0:
            yname2 = '1.0'
        else:
            ylabel = "%s%s%s" % (ylabel, yop, yname2)

        if yname1 == '0.0':
            yarr1 = np.zeros(npts)*1.0
            yexpr1 = 'zeros(%i)' % npts
        elif len(yname1) == 0 or yname1 == '1.0' or iy1 >= ncol:
            yarr1 = np.ones(npts)*1.0
            yexpr1 = 'ones(%i)' % npts
        else:
            yarr1 = rdata[iy1, :]
            yexpr1 = '%%s.data[%i, : ]' % iy1

        if yname2 == '0.0':
            yarr2 = np.zeros(npts)*1.0
            yexpr2 = '0.0'
        elif len(yname2) == 0 or yname2 == '1.0' or iy2 >= ncol:
            yarr2 = np.ones(npts)*1.0
            yexpr2 = '1.0'
        else:
            yarr2 = rdata[iy2, :]
            yexpr2 = '%%s.data[%i, : ]' % iy2

        workgroup.ydat = yarr1

        exprs['ydat'] = yexpr1
        if yop in ('+', '-', '*', '/'):
            exprs['ydat'] = "%s %s %s" % (yexpr1, yop, yexpr2)
            if yop == '+':
                workgroup.ydat = yarr1.__add__(yarr2)
            elif yop == '-':
                workgroup.ydat = yarr1.__sub__(yarr2)
            elif yop == '*':
                workgroup.ydat = yarr1.__mul__(yarr2)
            elif yop == '/':
                workgroup.ydat = yarr1.__truediv__(yarr2)

        ysuf, ypop, workgroup.ydat = pre_op(self.ypop, workgroup.ydat)
        self.ysuf.SetLabel(ysuf)
        exprs['ydat'] = '%s%s%s' % (ypop, exprs['ydat'], ysuf)

        yerr_op = self.yerr_op.GetStringSelection().lower()
        exprs['yerr'] = '1'
        if yerr_op.startswith('const'):
            yerr = self.yerr_const.GetValue()
            exprs['yerr'] = '%f' % yerr
        elif yerr_op.startswith('array'):
            iyerr = self.yerr_arr.GetSelection()
            yerr = rdata[iyerr, :]
            exprs['yerr'] = '%%s.data[%i, :]' % iyerr
        elif yerr_op.startswith('sqrt'):
            yerr = np.sqrt(workgroup.ydat)
            exprs['yerr'] = 'sqrt(%s.ydat)'

        if use_deriv:
            try:
                workgroup.ydat = (np.gradient(workgroup.ydat) /
                                 np.gradient(workgroup.xdat))
                exprs['ydat'] = 'deriv(%s)/deriv(%s)' % (exprs['ydat'],
                                                         exprs['xdat'])
            except:
                pass

        self.expressions = exprs
        self.array_sel = {'xpop': xpop, 'xarr': xname,
                          'ypop': ypop, 'yop': yop,
                          'yarr1': yname1, 'yarr2': yname2,
                          'use_deriv': use_deriv}

        try:
            npts = min(len(workgroup.xdat), len(workgroup.ydat))
        except AttributeError:
            return
        except ValueError:
            return

        en = workgroup.xdat
        if ((workgroup.datatype == 'xas') and
            ((len(en) > 1000 or any(np.diff(en) < 0) or
              ((max(en)-min(en)) > 350 and
               (np.diff(en[:100]).mean() < 1.0))))):
            self.message.SetLabel("Warning: XAS data may need to be rebinned!")
        else:
            self.message.SetLabel("")

        workgroup.filename    = rawgroup.filename
        workgroup.npts        = npts
        workgroup.plot_xlabel = xlabel
        workgroup.plot_ylabel = ylabel
        workgroup.xdat        = np.array(workgroup.xdat[:npts])
        workgroup.ydat        = np.array(workgroup.ydat[:npts])
        workgroup.y           = workgroup.ydat
        workgroup.yerr        = yerr
        if isinstance(yerr, np.ndarray):
            workgroup.yerr    = np.array(yerr[:npts])

        if workgroup.datatype == 'xas':
            workgroup.energy = workgroup.xdat
            workgroup.mu     = workgroup.ydat

        path, fname = os.path.split(workgroup.filename)
        popts = dict(marker='o', markersize=4, linewidth=1.5,
                     title=fname, ylabel=ylabel, xlabel=xlabel,
                     label="%s: %s" % (fname, workgroup.plot_ylabel))

        self.plotpanel.plot(workgroup.xdat, workgroup.ydat, **popts)

        for i in range(self.nb.GetPageCount()):
            if 'plot' in self.nb.GetPageText(i).lower():
                self.nb.SetSelection(i)

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)
Example #16
0
class AthenaImporter(wx.Frame) :
    """Import Athena File"""
    def __init__(self, parent, filename=None, read_ok_cb=None,
                 size=(725, 450), _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1,   size=size, style=FRAMESTYLE)
        splitter  = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop, 'Select None', size=(100, 30), action=self.onSelNone)
        sel_all  = Button(ltop, 'Select All', size=(100, 30), action=self.onSelAll)
        sel_imp  = Button(ltop, 'Import Selected Groups', size=(200, 30), action=self.onOK)

        self.select_imported = sel_imp
        self.grouplist = FileCheckList(leftpanel, select_action=self.onShowGroup)

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none,  (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp,  (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN|wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN|wx.GROW|wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel, self.filename, font=Font(13),
                                colour=self.colors.title, style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.a_project = read_athena(self.filename, do_bkg=False, do_fft=False,
                                     _larch=_larch)
        self.allgroups = []
        for item in dir(self.a_project):
            if not item.startswith('_athena_'):
                self.allgroups.append(item)
                self.grouplist.Append(item)
        self.Show()
        self.Raise()

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)

    def onOK(self, event=None):
        """generate script to import groups"""
        namelist = [str(n) for n in self.grouplist.GetCheckedStrings()]
        if len(namelist) == 0:

            cancel = Popup(self, """No data groups selected.
        Cancel import from this project?""", 'Cancel Import?',
                           style=wx.YES_NO)
            if wx.ID_YES == cancel:
                self.Destroy()
            else:
                return

        if self.read_ok_cb is not None:
            self.read_ok_cb(self.filename, namelist)

        self.Destroy()

    def onCancel(self, event=None):
        self.Destroy()

    def onSelAll(self, event=None):
        self.grouplist.SetCheckedStrings(self.allgroups)

    def onSelNone(self, event=None):
        self.grouplist.SetCheckedStrings([])

    def onShowGroup(self, event=None):
        """column selections changed calc xdat and ydat"""
        gname = event.GetString()
        grp = getattr(self.a_project, gname)
        glist = list(self.grouplist.GetCheckedStrings())
        if gname not in glist:
            glist.append(gname)
        self.grouplist.SetCheckedStrings(glist)
        if hasattr(grp, 'energy') and hasattr(grp, 'mu'):
            self.plotpanel.plot(grp.energy, grp.mu,
                                xlabel='Energy', ylabel='mu',title=gname)
Example #17
0
class AthenaImporter(wx.Frame):
    """Import Athena File"""
    def __init__(self,
                 parent,
                 filename=None,
                 read_ok_cb=None,
                 size=(725, 450),
                 _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1, size=size, style=FRAMESTYLE)
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop,
                          'Select None',
                          size=(100, 30),
                          action=self.onSelNone)
        sel_all = Button(ltop,
                         'Select All',
                         size=(100, 30),
                         action=self.onSelAll)
        sel_imp = Button(ltop,
                         'Import Selected Groups',
                         size=(200, 30),
                         action=self.onOK)

        self.select_imported = sel_imp
        self.select_imported.Disable()

        self.grouplist = FileCheckList(leftpanel,
                                       select_action=self.onShowGroup)
        self.grouplist.SetBackgroundColour(wx.Colour(255, 255, 255))

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none, (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp, (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN | wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN | wx.GROW | wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel,
                                self.filename,
                                font=Font(13),
                                colour=self.colors.title,
                                style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.all = read_athena(self.filename,
                               do_bkg=False,
                               do_fft=False,
                               with_journal=False,
                               _larch=_larch)
        for item in dir(self.all):
            self.grouplist.Append(item)
        self.Show()
        self.Raise()

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)

    def onOK(self, event=None):
        """generate script to import groups"""
        namelist = [str(n) for n in self.grouplist.GetCheckedStrings()]

        if self.read_ok_cb is not None and len(namelist) > 0:
            self.read_ok_cb(self.filename, namelist)

        self.Destroy()

    def onCancel(self, event=None):
        self.Destroy()

    def onSelAll(self, event=None):
        self.grouplist.SetCheckedStrings(dir(self.all))
        self.select_imported.Enable()

    def onSelNone(self, event=None):
        self.grouplist.SetCheckedStrings([])
        self.select_imported.Disable()

    def onShowGroup(self, event=None):
        """column selections changed calc xdat and ydat"""
        self.select_imported.Enable()
        gname = event.GetString()
        grp = getattr(self.all, gname)
        glist = list(self.grouplist.GetCheckedStrings())
        if gname not in glist:
            glist.append(gname)
        self.grouplist.SetCheckedStrings(glist)
        if hasattr(grp, 'energy') and hasattr(grp, 'mu'):
            self.plotpanel.plot(grp.energy,
                                grp.mu,
                                xlabel='Energy',
                                ylabel='mu',
                                title=gname)
Example #18
0
class MainFrame(wx.Frame):  #

    monitor_address = 'C3/hr_monitor/1'
    yellow_alrm_thrsh = 0.25
    red_alrm_thrsh = 0.5
    sleep_time = 5

    def __init__(self, *args, **kwds):
        # begin wxGlade: MainFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.alarm_plt = PlotPanel(self)
        #self.timestamp_sld = wx.Slider(self, -1, 0, 0, 10)
        self.avg_hr_title_lbl = wx.StaticText(self, -1, "Current avg. HR:")
        self.avg_hr_lbl = wx.StaticText(self, -1, "nan")
        self.panel_1 = wx.Panel(self, -1)
        self.avg_acc_title_lbl = wx.StaticText(self, -1,
                                               "Current avg. Acceleration:")
        self.avg_acc_lbl = wx.StaticText(self, -1, "nan")
        self.panel_2 = wx.Panel(self, -1)
        self.anomaly_lvl_curr_title_lbl = wx.StaticText(
            self, -1, "Anomaly level: Current:")
        self.anomaly_lvl_curr_lbl = wx.StaticText(self, -1, "nan")
        self.panel_3 = wx.Panel(self, -1)
        self.anomaly_lvl_max_title_lbl = wx.StaticText(
            self, -1, "                                 Max:")
        self.anomaly_lvl_max_lbl = wx.StaticText(self, -1, "nan")
        self.red_alarm_lbl = wx.Panel(self, -1)
        self.anomaly_lvl_min_title_lbl = wx.StaticText(
            self, -1, "                                 Min:")
        self.anomaly_lvl_min_lbl = wx.StaticText(self, -1, "nan")
        self.yellow_alarm_lbl = wx.Panel(self, -1)
        self.anomaly_lvl_avg_title_lbl = wx.StaticText(
            self, -1, "                                 Average:")
        self.anomaly_lvl_avg_lbl = wx.StaticText(self, -1, "nan")
        self.green_alarm_lbl = wx.Panel(self, -1)
        self.collect_btn = wx.Button(self, -1, "Collect data")

        self.__set_properties()
        self.__do_layout()

        #self.Bind(wx.EVT_COMMAND_SCROLL, self.timestamp_sld_scroll, self.timestamp_sld)
        self.Bind(wx.EVT_BUTTON, self.collect_btn_click, self.collect_btn)
        # end wxGlade
        self.timer_thread = Timer(target=self.timer_tick)
        self.proxy = DeviceProxy(MainFrame.monitor_address)
        self.alarms = set()

    def __set_properties(self):
        # begin wxGlade: MainFrame.__set_properties
        self.SetTitle("HRMonitor GUI")
        self.red_alarm_lbl.SetBackgroundColour(wx.NullColor)
        self.yellow_alarm_lbl.SetBackgroundColour(wx.NullColor)
        self.green_alarm_lbl.SetBackgroundColour(wx.NullColor)
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MainFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_2 = wx.GridSizer(6, 3, 0, 0)
        sizer_1.Add(self.alarm_plt, 1, wx.EXPAND, 0)
        #sizer_1.Add(self.timestamp_sld, 0, wx.EXPAND, 0)
        grid_sizer_2.Add(self.avg_hr_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.avg_hr_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)
        grid_sizer_2.Add(self.avg_acc_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.avg_acc_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.panel_2, 1, wx.EXPAND, 0)
        grid_sizer_2.Add(self.anomaly_lvl_curr_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.anomaly_lvl_curr_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.panel_3, 1, wx.EXPAND, 0)
        grid_sizer_2.Add(self.anomaly_lvl_max_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.anomaly_lvl_max_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.red_alarm_lbl, 0, wx.EXPAND, 0)
        grid_sizer_2.Add(self.anomaly_lvl_min_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.anomaly_lvl_min_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.yellow_alarm_lbl, 0, wx.EXPAND, 0)
        grid_sizer_2.Add(self.anomaly_lvl_avg_title_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.anomaly_lvl_avg_lbl, 0, 0, 0)
        grid_sizer_2.Add(self.green_alarm_lbl, 0, wx.EXPAND, 0)
        sizer_2.Add(grid_sizer_2, 9, wx.EXPAND, 0)
        sizer_3.Add(self.collect_btn, 0, wx.ALL, 0)
        sizer_2.Add(sizer_3, 1, wx.EXPAND | wx.SHAPED, 0)
        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

    # wxGlade: MainFrame.<event_handler>
    def timestamp_sld_scroll(self, event):
        print("Event handler `timestamp_sld_scroll' not implemented")
        event.Skip()

    # wxGlade: MainFrame.<event_handler>
    def collect_btn_click(self, event):
        if self.collect_btn.GetLabel() == "Stop collecting":
            self.collect_btn.SetLabel("Collect data")
            self.timer_thread.stop()
            del self.timer_thread
            self.timer_thread = Timer(target=self.timer_tick)
        else:
            self.collect_btn.SetLabel("Stop collecting")
            self.timer_thread.start()
        event.Skip()


# end of class MainFrame

    def timer_tick(self):
        timer = current_thread()
        proxy = self.proxy
        while not timer.stopped():
            try:
                avg_hr_idx = proxy.command_inout_asynch('get_avg_hr', 4)
                avg_acc_idx = proxy.command_inout_asynch('get_avg_acc', 4)
                alarms_idx = proxy.command_inout_asynch(
                    'get_current_alarms', 4)
                init = datetime.now()
                avg_hr = proxy.command_inout_reply(avg_hr_idx, timeout=0)
                avg_acc = proxy.command_inout_reply(avg_acc_idx, timeout=0)
                alarms = proxy.command_inout_reply(alarms_idx, timeout=0)
                sleep_time = timedelta(seconds=MainFrame.sleep_time)
                sleep_time -= (datetime.now() - init)
                sleep_time = max(sleep_time, timedelta(0)).total_seconds()
                alarms[0], alarms[1] = alarms[1], alarms[0]
                alarms[0] = [
                    float(
                        datetime.strptime(
                            x, '%Y-%m-%d %H:%M:%S.%f').strftime('%s.%f'))
                    for x in alarms[0]
                ]
                alarms[0] = [x % 100000 for x in alarms[0]]
                if not isnan(avg_hr):
                    wx.CallAfter(self.avg_hr_lbl.SetLabel, str(avg_hr))
                if not isnan(avg_acc):
                    wx.CallAfter(self.avg_acc_lbl.SetLabel, str(avg_acc))
                if len(alarms[0]) > 0:
                    self.alarms.update(zip(*alarms))
                    wx.CallAfter(self.set_alarm_text)

                data = sorted(self.alarms)
                if len(data) > 0:
                    wx.CallAfter(self.plot, zip(*data))
                    wx.CallAfter(self.set_alarm_color, max(data)[1])
                sleep(sleep_time)
            except ConnectionFailed:
                wx.CallAfter(self.collect_btn_click, None)
                break
        del proxy

    def plot(self, data):
        x_data, y_data = data
        self.alarm_plt.plot(x_data, y_data, title="Alarm Level History")

    def set_alarm_text(self):
        alarms = sorted(self.alarms)
        if len(alarms) > 0:
            vals = [x for _, x in alarms]
        else:
            vals = [nan]
            alarms = [(nan, nan)]
        avg = sum(vals) / len(vals)
        self.anomaly_lvl_curr_lbl.SetLabel(str(alarms[-1][1]))
        self.anomaly_lvl_max_lbl.SetLabel(str(max(vals)))
        self.anomaly_lvl_min_lbl.SetLabel(str(min(vals)))
        self.anomaly_lvl_avg_lbl.SetLabel(str(avg))

    def set_alarm_color(self, alarm_lvl):
        if alarm_lvl < MainFrame.yellow_alrm_thrsh:
            self.red_alarm_lbl.SetBackgroundColour(wx.NullColor)
            self.yellow_alarm_lbl.SetBackgroundColour(wx.NullColor)
            self.green_alarm_lbl.SetBackgroundColour('Green')
        elif MainFrame.yellow_alrm_thrsh <= alarm_lvl < MainFrame.red_alrm_thrsh:
            self.red_alarm_lbl.SetBackgroundColour(wx.NullColor)
            self.yellow_alarm_lbl.SetBackgroundColour('Yellow')
            self.green_alarm_lbl.SetBackgroundColour(wx.NullColor)
        else:
            self.red_alarm_lbl.SetBackgroundColour('Red')
            self.yellow_alarm_lbl.SetBackgroundColour(wx.NullColor)
            self.green_alarm_lbl.SetBackgroundColour(wx.NullColor)
        # get a color between green and red, going through yellow
        # offset = 0.2
        # adjusted_lvl = min(alarm_lvl + offset, 1)
        # r, g, b = hsv_to_rgb((1 - adjusted_lvl) / 3, 1, 1)
        # r = int(255 * r)
        # g = int(255 * g)
        # b = int(255 * b)
        # color = wx.Color(r, g, b)
        # self.green_alarm_lbl.SetBackgroundColour(color)
        self.red_alarm_lbl.Refresh()
        self.yellow_alarm_lbl.Refresh()
        self.green_alarm_lbl.Refresh()
        self.Refresh()
Example #19
0
class AthenaImporter(wx.Frame) :
    """Import Athena File"""
    def __init__(self, parent, filename=None, read_ok_cb=None,
                 size=(725, 450), _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1,   size=size, style=FRAMESTYLE)
        splitter  = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop, 'Select None', size=(100, 30), action=self.onSelNone)
        sel_all  = Button(ltop, 'Select All', size=(100, 30), action=self.onSelAll)
        sel_imp  = Button(ltop, 'Import Selected Groups', size=(200, 30), action=self.onOK)

        self.grouplist = FileCheckList(leftpanel, select_action=self.onShowGroup)
        self.grouplist.SetBackgroundColour(wx.Colour(255, 255, 255))

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none,  (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp,  (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN|wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN|wx.GROW|wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel, self.filename, font=Font(13),
                                colour=self.colors.title, style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.all = read_athena(filename, do_bkg=False, do_fft=False, _larch=_larch)
        for item in dir(self.all):
            self.grouplist.Append(item)

        self.Show()
        self.Raise()

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)

    def onOK(self, event=None):
        """ import groups """
        for name in self.grouplist.GetCheckedStrings():
            rawgroup = getattr(self.all, name)
            npts = len(rawgroup.energy)
            outgroup = Group(datatype='xas',
                            path="%s::%s" %(self.filename, name),
                            filename=name,
                            groupname = fix_varname(name),
                            raw=rawgroup,
                            xdat=rawgroup.energy,
                            ydat=rawgroup.mu,
                            y=rawgroup.mu,
                            yerr=1.0,
                            npts=npts, _index=1.0*np.arange(npts),
                            plot_xlabel='Energy (eV)',
                            plot_ylabel='mu')

            self.read_ok_cb(outgroup, array_sel=None, overwrite=True)

        self.Destroy()

    def onCancel(self, event=None):
        self.Destroy()

    def onSelAll(self, event=None):
        self.grouplist.SetCheckedStrings(dir(self.all))

    def onSelNone(self, event=None):
        self.grouplist.SetCheckedStrings([])

    def onShowGroup(self, event=None):
        """column selections changed calc xdat and ydat"""
        gname = event.GetString()
        grp = getattr(self.all, gname)
        if hasattr(grp, 'energy') and hasattr(grp, 'mu'):
            self.plotpanel.plot(grp.energy, grp.mu,
                                xlabel='Energy', ylabel='mu',title=gname)
class SectoinParamsDefsPanel (SectionParamsDefsPanelBase):
    def __init__(self, parent):
        SectionParamsDefsPanelBase.__init__(self, parent)
        # ÓÃÓÚ´æ·Å solveÖ®ºóµÄÖµ
        self._args = dict()

        self.plotpanel = PlotPanel(self.m_panel_canvas, size=(300, 300), fontsize=5)
        self.plotpanel.BuildPanel()

        # ĬÈϽØÃæÐÎ×´
        self._section_type = u'Ö±½Ç¸Ö'

        # ½ØÃæ²ÎÊýµÚÒ»ÁÐÖ»¶Á
        for irow in range(self.m_grid_params_defs.GetNumberRows()):
            self.m_grid_params_defs.SetReadOnly(irow, 0, True)

        self.grid_value = {
                           u'Ö±½Ç¸Ö': ['±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2', 'ÄÚÔ²»¡°ë¾¶'],
                           u'¹¤×Ö¸Ö': ['¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶', '½Ç¶ËÔ²»¡°ë¾¶' ],
                           u'²Û¸Ö':   ['¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶', '½Ç¶ËÔ²»¡°ë¾¶' ],
                           #u'CÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ßºñ¶È1', 'Ñüºñ¶È', '±ßºñ¶È2', '±ß¿í¶È2'],
                           u'TÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2'],
                           u'ñÐ͸Ö': ['¸ß¶È', '½Å±ß¿í¶È', 'Í·±ß¿í¶È', 'ÍÈÇã½Ç', '½Å±ßºñ¶È', 'ÍȺñ¶È', 'Í·ºñ¶È'],
                           u'JÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ß¿í¶È3', '±ßºñ¶È1', '±ßºñ¶È2', '±ßºñ¶È3']
                          }

        for num in range(len(self.grid_value[self._section_type])):
            self.m_grid_params_defs.SetCellValue(num, 0, self.grid_value[self._section_type][num])

    def OnSelectSectionType(self, event):
        self._section_type = self.m_choice_section_type.GetStringSelection()
        section_parameter_name = self.grid_value[self._section_type]
        self.m_grid_params_defs.ClearGrid()
        for name_num in range(len(section_parameter_name)):
            self.m_grid_params_defs.SetCellValue(name_num, 0, section_parameter_name[name_num])

    def m_btn_calculationOnButtonClick( self, event ):
        # µã»÷btnÖ®ºó£¬»ñµÃ´«ÈëµÄ²ÎÊý¡£
        # ͨ¹ý»ñµÃµÄ²ÎÊýÉú³É³ö½ØÃæ¶ÔÏó¡£
        # ͨ¹ý½ØÃæ¼ÆË㣬µÃµ½¼¸ºÎÊýÖµ
        # ͨ¹ýDraw¶ÔÏó»­Í¼£¬»­³ö¼¸ºÎͼÏñ¡£
        _args = list()
        for num in range(len(self.grid_value[self._section_type])):
            _args.append(float(self.m_grid_params_defs.GetCellValue(num, 1)))

        sectionType = self._section_type

        if sectionType == u"¹¤×Ö¸Ö":
            section = ISection(*_args)
        elif sectionType == u"Ö±½Ç¸Ö":
            section = rightAngleSection(*_args)
        elif sectionType == u"²Û¸Ö":
            section = grooveSection(*_args)
        #elif sectionType == u"CÐ͸Ö":
            #pass
        elif sectionType == u"TÐ͸Ö":
            section = TshapeSection(*_args)
        elif sectionType == u"JÐ͸Ö":
            section = JshapeSection(*_args)
        elif sectionType == u"ñÐ͸Ö":
            section = NshapeSection(*_args)

        geo = GeoCalculator(section)
        geo.Solve()
        self._args = geo._args
        if "Area" in self._args:
            if self._args['Area'] < 0.0000001:
                res = 0
            else:
                res = self._args['Area']
            self.m_propertyGridItem2.SetValue(str(res))
        if "Sx" in self._args:
            if self._args['Sx'] < 0.0000001:
                res = 0
            else:
                res = self._args['Sx']
            self.m_propertyGridItem3.SetValue(str(res))
        if "Sy" in self._args:
            if self._args['Sy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Sy']
            self.m_propertyGridItem42.SetValue(str(res))
        if "Ix" in self._args:
            if self._args['Ix'] < 0.0000001:
                res = 0
            else:
                res = self._args['Ix']
            self.m_propertyGridItem4.SetValue(str(res))
        if "Iy" in self._args:
            if self._args['Iy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Iy']
            self.m_propertyGridItem5.SetValue(str(res))
        if "Ixy" in self._args:
            if self._args['Ixy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Ixy']
            self.m_propertyGridItem7.SetValue(str(res))
        if "centroid" in self._args:
            res = self._args['centroid']

            if res[0] < 0.0000001:
                res = [0, res[1]]
            if res[1] < 0.0000001:
                res = [res[0], 0]

            self.m_propertyGridItem8.SetValue(str(res))
        if "tan_alfa" in self._args:
            if self._args['tan_alfa'] < 0.0000001:
                res = 0
            else:
                res = self._args['tan_alfa']

            self.m_propertyGridItem9.SetValue(str(res))
        if "ix" in self._args:
            if self._args['ix'] < 0.0000001:
                res = 0
            else:
                res = self._args['ix']
            self.m_propertyGridItem61.SetValue(str(res))
        if "iy" in self._args:
            if self._args['iy'] < 0.0000001:
                res = 0
            else:
                res = self._args['iy']
            self.m_propertyGridItem62.SetValue(str(res))

        Path = DrawGeometry(section)
        Path.Draw()

        self.plotpanel.clear()
        for i in Path._paths:
                m,n=zip(*i)
                self.plotpanel.oplot(m,n,fullbox=False,axes_style='open')
        for i in Path._dimen:
            m, n = zip(*i)
            self.plotpanel.oplot(m,n,fullbox=False,axes_style='open', linewidth=1, color='green')
        # ±éÀú×ֵ䣬»­Éϱê×¢
        for key, value in Path._text.items():
            x = key[0]
            y = key[1]
            self.plotpanel.add_text(str(value), x, y, size=4)

    def m_btn_calculationOnSetFocus( self, event ):
        print "on btn_Set Focus!"
Example #21
0
class ColumnDataFileFrame(wx.Frame):
    """Column Data File, select columns"""
    def __init__(self,
                 parent,
                 filename=None,
                 groupname=None,
                 last_array_sel=None,
                 read_ok_cb=None,
                 edit_groupname=True,
                 _larch=None):
        self.parent = parent
        self._larch = _larch
        self.path = filename

        group = self.initgroup = self.read_column_file(self.path)
        self.subframes = {}
        self.workgroup = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype',
                     'array_labels'):
            setattr(self.workgroup, attr, getattr(group, attr, None))

        arr_labels = [l.lower() for l in self.initgroup.array_labels]

        if self.workgroup.datatype is None:
            self.workgroup.datatype = 'raw'
            if ('energ' in arr_labels[0] or 'energ' in arr_labels[1]):
                self.workgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb
        self.array_sel = {
            'xpop': '',
            'xarr': None,
            'ypop': '',
            'yop': '/',
            'yarr1': None,
            'yarr2': None,
            'use_deriv': False
        }

        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in arr_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in arr_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in arr_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % group.filename
        wx.Frame.__init__(self,
                          None,
                          -1,
                          'Build Arrays from Data Columns for %s' %
                          group.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel,
                           message,
                           font=Font(13),
                           colour=self.colors.title,
                           style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']

        self.xarr = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1 = Choice(panel, choices=arr_labels, **opts)
        self.yarr2 = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.workgroup.datatype)

        opts['size'] = (50, -1)
        self.yop = Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (120, -1)

        self.use_deriv = Check(panel,
                               label='use derivative',
                               default=self.array_sel['use_deriv'],
                               **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels) - 1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)

        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        _ok = Button(bpanel, 'OK', action=self.onOK)
        _cancel = Button(bpanel, 'Cancel', action=self.onCancel)
        _edit = Button(bpanel, 'Edit Array Names', action=self.onEditNames)
        bsizer.Add(_ok)
        bsizer.Add(_cancel)
        bsizer.Add(_edit)
        _ok.SetDefault()
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title, (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop, (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf, (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype, (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel,
                                         value=group.groupname,
                                         size=(240, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname, (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        sizer.Add(bpanel, (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248, 248, 240))
        self.nb.SetActiveTabColour(wx.Colour(254, 254, 195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40, 40, 180))
        self.nb.SetActiveTabTextColour(wx.Colour(80, 0, 0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel,
                            style=wx.TE_MULTILINE | wx.TE_READONLY,
                            size=(400, 250))

        ftext.SetValue(group.text)
        ftext.SetFont(Font(10))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN | wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW | wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN | wx.GROW, 2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [group.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.Show()
        self.Raise()
        self.onUpdate(self)

    def read_column_file(self, path):
        """read column file, generally as initial read"""
        parent, filename = os.path.split(path)
        with open(path, 'r') as fh:
            lines = fh.readlines()

        text = ''.join(lines)
        line1 = lines[0].lower()

        reader = 'read_ascii'
        if 'epics stepscan file' in line1:
            reader = 'read_gsexdi'
        elif 'xdi' in line1:
            reader = 'read_xdi'
        elif 'epics scan' in line1:
            reader = 'read_gsescan'

        tmpname = '_tmp_file_'
        read_cmd = "%s = %s('%s')" % (tmpname, reader, path)
        self.reader = reader
        deeplarch = self._larch._larch
        try:
            deeplarch.eval(read_cmd, add_history=False)
        except:
            pass
        if deeplarch.error:
            # self._larch.input.clear()
            msg = ["Error trying to read '%s':" % path, ""]
            for err in deeplarch.error:
                exc_name, errmsg = err.get_error()
                msg.append(errmsg)

            title = "Cannot read %s" % path
            r = Popup(self.parent, "\n".join(msg), title)
            return None

        group = self._larch.symtable.get_symbol(tmpname)
        self._larch.symtable.del_symbol(tmpname)

        group.text = text
        group.path = path
        group.filename = filename
        group.groupname = file2groupname(filename,
                                         symtable=self._larch.symtable)
        return group

    def show_subframe(self, name, frameclass, **opts):
        shown = False
        if name in self.subframes:
            try:
                self.subframes[name].Raise()
                shown = True
            except:
                del self.subframes[name]
        if not shown:
            self.subframes[name] = frameclass(self, **opts)

    def onEditNames(self, evt=None):
        self.show_subframe('editcol',
                           EditColumnFrame,
                           group=self.workgroup,
                           on_ok=self.set_array_labels)

    def set_array_labels(self, arr_labels):
        self.workgroup.array_labels = arr_labels
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']

        def update(wid, choices):
            curstr = wid.GetStringSelection()
            curind = wid.GetSelection()
            wid.SetChoices(choices)
            if curstr in choices:
                wid.SetStringSelection(curstr)
            else:
                wid.SetSelection(curind)

        update(self.xarr, xarr_labels)
        update(self.yarr1, yarr_labels)
        update(self.yarr2, yarr_labels)
        update(self.yerr_arr, yarr_labels)
        self.onUpdate()

    def onOK(self, event=None):
        """ build arrays according to selection """
        if self.wid_groupname is not None:
            groupname = fix_varname(self.wid_groupname.GetValue())

        yerr_op = self.yerr_op.GetStringSelection().lower()
        yerr_expr = '1'
        if yerr_op.startswith('const'):
            yerr_expr = "%f" % self.yerr_const.GetValue()
        elif yerr_op.startswith('array'):
            yerr_expr = '%%s.data[%i, :]' % self.yerr_arr.GetSelection()
        elif yerr_op.startswith('sqrt'):
            yerr_expr = 'sqrt(%s.ydat)'
        self.expressions['yerr'] = yerr_expr

        # generate script to pass back to calling program:
        labels = ', '.join(self.workgroup.array_labels)
        read_cmd = "%s('{path:s}', labels='%s')" % (self.reader, labels)

        buff = ["{group:s} = %s" % read_cmd, "{group:s}.path = '{path:s}'"]

        for attr in ('datatype', 'plot_xlabel', 'plot_ylabel'):
            val = getattr(self.workgroup, attr)
            buff.append("{group:s}.%s = '%s'" % (attr, val))

        for aname in ('xdat', 'ydat', 'yerr'):
            expr = self.expressions[aname].replace('%s', '{group:s}')
            buff.append("{group:s}.%s = %s" % (aname, expr))

        if getattr(self.workgroup, 'datatype', 'raw') == 'xas':
            if self.reader == 'read_gsescan':
                buff.append("{group:s}.energy = {group:s}.x")
            else:
                buff.append("{group:s}.energy = {group:s}.xdat")
            buff.append("{group:s}.mu = {group:s}.ydat")

        script = "\n".join(buff)

        if self.read_ok_cb is not None:
            self.read_ok_cb(script,
                            self.path,
                            groupname=groupname,
                            array_sel=self.array_sel)

        self.Destroy()

    def onCancel(self, event=None):
        self.workgroup.import_ok = False
        self.Destroy()

    def onYerrChoice(self, evt=None):
        yerr_choice = evt.GetString()
        self.yerr_arr.Disable()
        self.yerr_const.Disable()
        if 'const' in yerr_choice.lower():
            self.yerr_const.Enable()
        elif 'array' in yerr_choice.lower():
            self.yerr_arr.Enable()
        self.onUpdate()

    def onUpdate(self, value=None, evt=None):
        """column selections changed calc xdat and ydat"""
        # dtcorr = self.dtcorr.IsChecked()
        # print("Column Frame on Update ")

        dtcorr = False
        use_deriv = self.use_deriv.IsChecked()
        rawgroup = self.initgroup
        workgroup = self.workgroup
        rdata = self.initgroup.data

        # print("onUpdate ", dir(rawgroup))
        ix = self.xarr.GetSelection()
        xname = self.xarr.GetStringSelection()

        exprs = dict(xdat=None, ydat=None, yerr=None)

        ncol, npts = rdata.shape
        if xname.startswith('_index') or ix >= ncol:
            workgroup.xdat = 1.0 * np.arange(npts)
            xname = '_index'
            exprs['xdat'] = 'arange(%i)' % npts
        else:
            workgroup.xdat = rdata[ix, :]
            exprs['xdat'] = '%%s.data[%i, : ]' % ix

        workgroup.datatype = self.datatype.GetStringSelection().strip().lower()

        def pre_op(opwid, arr):
            opstr = opwid.GetStringSelection().strip()
            suf = ''
            if opstr in ('-log(', 'log('):
                suf = ')'
                if opstr == 'log(':
                    arr = np.log(arr)
                elif opstr == '-log(':
                    arr = -np.log(arr)
            return suf, opstr, arr

        try:
            xsuf, xpop, workgroup.xdat = pre_op(self.xpop, workgroup.xdat)
            self.xsuf.SetLabel(xsuf)
            exprs['xdat'] = '%s%s%s' % (xpop, exprs['xdat'], xsuf)
        except:
            return
        try:
            xunits = rawgroup.array_units[ix].strip()
            xlabel = '%s (%s)' % (xname, xunits)
        except:
            xlabel = xname

        yname1 = self.yarr1.GetStringSelection().strip()
        yname2 = self.yarr2.GetStringSelection().strip()
        iy1 = self.yarr1.GetSelection()
        iy2 = self.yarr2.GetSelection()
        yop = self.yop.GetStringSelection().strip()

        ylabel = yname1
        if len(yname2) == 0:
            yname2 = '1.0'
        else:
            ylabel = "%s%s%s" % (ylabel, yop, yname2)

        if yname1 == '0.0':
            yarr1 = np.zeros(npts) * 1.0
            yexpr1 = 'zeros(%i)' % npts
        elif len(yname1) == 0 or yname1 == '1.0' or iy1 >= ncol:
            yarr1 = np.ones(npts) * 1.0
            yexpr1 = 'ones(%i)' % npts
        else:
            yarr1 = rdata[iy1, :]
            yexpr1 = '%%s.data[%i, : ]' % iy1

        if yname2 == '0.0':
            yarr2 = np.zeros(npts) * 1.0
            yexpr2 = '0.0'
        elif len(yname2) == 0 or yname2 == '1.0' or iy2 >= ncol:
            yarr2 = np.ones(npts) * 1.0
            yexpr2 = '1.0'
        else:
            yarr2 = rdata[iy2, :]
            yexpr2 = '%%s.data[%i, : ]' % iy2

        workgroup.ydat = yarr1
        exprs['ydat'] = yexpr1
        if yop in ('+', '-', '*', '/'):
            exprs['ydat'] = "%s %s %s" % (yexpr1, yop, yexpr2)
            if yop == '+':
                workgroup.ydat = yarr1.__add__(yarr2)
            elif yop == '-':
                workgroup.ydat = yarr1.__sub__(yarr2)
            elif yop == '*':
                workgroup.ydat = yarr1.__mul__(yarr2)
            elif yop == '/':
                workgroup.ydat = yarr1.__truediv__(yarr2)

        ysuf, ypop, workgroup.ydat = pre_op(self.ypop, workgroup.ydat)
        self.ysuf.SetLabel(ysuf)
        exprs['ydat'] = '%s%s%s' % (ypop, exprs['ydat'], ysuf)

        yerr_op = self.yerr_op.GetStringSelection().lower()
        exprs['yerr'] = '1'
        if yerr_op.startswith('const'):
            yerr = self.yerr_const.GetValue()
            exprs['yerr'] = '%f' % yerr
        elif yerr_op.startswith('array'):
            iyerr = self.yerr_arr.GetSelection()
            yerr = rdata[iyerr, :]
            exprs['yerr'] = '%%s.data[%i, :]' % iyerr
        elif yerr_op.startswith('sqrt'):
            yerr = np.sqrt(workgroup.ydat)
            exprs['yerr'] = 'sqrt(%s.ydat)'

        if use_deriv:
            try:
                workgroup.ydat = (np.gradient(workgroup.ydat) /
                                  np.gradient(workgroup.xdat))
                exprs['ydat'] = 'deriv(%s)/deriv(%s)' % (exprs['ydat'],
                                                         exprs['xdat'])
            except:
                pass

        self.expressions = exprs
        self.array_sel = {
            'xpop': xpop,
            'xarr': xname,
            'ypop': ypop,
            'yop': yop,
            'yarr1': yname1,
            'yarr2': yname2,
            'use_deriv': use_deriv
        }

        try:
            npts = min(len(workgroup.xdat), len(workgroup.ydat))
        except AttributeError:
            return

        workgroup.filename = rawgroup.filename
        workgroup.npts = npts
        workgroup.plot_xlabel = xlabel
        workgroup.plot_ylabel = ylabel
        workgroup.xdat = np.array(workgroup.xdat[:npts])
        workgroup.ydat = np.array(workgroup.ydat[:npts])
        workgroup.y = workgroup.ydat
        workgroup.yerr = yerr
        if isinstance(yerr, np.ndarray):
            workgroup.yerr = np.array(yerr[:npts])

        if workgroup.datatype == 'xas':
            workgroup.energy = workgroup.xdat
            workgroup.mu = workgroup.ydat

        path, fname = os.path.split(workgroup.filename)
        popts = dict(marker='o',
                     markersize=4,
                     linewidth=1.5,
                     title=fname,
                     ylabel=ylabel,
                     xlabel=xlabel,
                     label="%s: %s" % (fname, workgroup.plot_ylabel))

        self.plotpanel.plot(workgroup.xdat, workgroup.ydat, **popts)

        for i in range(self.nb.GetPageCount()):
            if 'plot' in self.nb.GetPageText(i).lower():
                self.nb.SetSelection(i)

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)
Example #22
0
class StripChartFrame(wx.Frame):
    def __init__(self, parent, ID, **kws):
        kws["style"] = wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER|wx.TAB_TRAVERSAL

        wx.Frame.__init__(self, parent, ID, '',
                         wx.DefaultPosition, wx.Size(-1,-1), **kws)
        self.SetTitle("wxmplot StripChart Demo")

        self.tmin = 15.0

        self.SetFont(wx.Font(12,wx.SWISS,wx.NORMAL,wx.BOLD,False))
        menu = wx.Menu()
        ID_EXIT  = wx.NewId()
        ID_TIMER = wx.NewId()

        menu_exit = menu.Append(ID_EXIT, "E&xit",
                                "Terminate the program")

        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File");
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU,  self.OnExit, menu_exit)
        self.Bind(wx.EVT_CLOSE, self.OnExit)

        sbar = self.CreateStatusBar(2,wx.CAPTION)
        sfont = sbar.GetFont()
        sfont.SetWeight(wx.BOLD)
        sfont.SetPointSize(11)
        sbar.SetFont(sfont)
        self.SetStatusWidths([-3,-1])
        self.SetStatusText('',0)

        mainsizer = wx.BoxSizer(wx.VERTICAL)

        btnpanel = wx.Panel(self, -1)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        b_on  = wx.Button(btnpanel, -1, 'Start',   size=(-1,-1))
        b_off = wx.Button(btnpanel, -1, 'Stop',    size=(-1,-1))

        b_on.Bind(wx.EVT_BUTTON, self.onStartTimer)
        b_off.Bind(wx.EVT_BUTTON, self.onStopTimer)

        tlabel = wx.StaticText(btnpanel, -1, '  Time range:')
        self.time_range = FloatCtrl(btnpanel,  size=(100, -1),
                                    value=abs(self.tmin), precision=1)

        btnsizer.Add(b_on,   0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(b_off,  0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(tlabel, 1, wx.GROW|wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(self.time_range, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)

        btnpanel.SetSizer(btnsizer)
        btnsizer.Fit(btnpanel)

        self.plotpanel = PlotPanel(self, messenger=self.write_message)
        self.plotpanel.BuildPanel()
        self.plotpanel.set_xlabel('Time from Present (s)')
        mainsizer.Add(btnpanel,       0,
                      wx.GROW|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        mainsizer.Add(self.plotpanel, 1,
                      wx.GROW|wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        self.SetSizer(mainsizer)
        mainsizer.Fit(self)

        self.Bind(wx.EVT_TIMER, self.onTimer)
        self.timer = wx.Timer(self)
        self.count    = 0
        self.Refresh()
        wx.CallAfter(self.onStartTimer)

    def write_message(self, msg, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(msg, panel)

    def onStartTimer(self,event=None):
        self.count    = 0
        t0,y0 = next_data()
        self.ylist = [y0]
        self.tlist = [t0]
        self.tmin_last = -10000
        self.time0    = time.time()
        self.timer.Start(50)

    def onStopTimer(self,event=None):
        self.timer.Stop()

    def onTimer(self, event):
        self.count += 1
        etime = time.time() - self.time0
        self.tmin = float(self.time_range.GetValue())
        t1, y1 = next_data()
        self.tlist.append(t1)
        self.ylist.append(y1)
        tdat = np.array(self.tlist) - t1
        mask = np.where(tdat > -abs(self.tmin))
        ydat = np.array(self.ylist)

        n = len(self.ylist)
        if n <= 2:
            self.plotpanel.plot(tdat, ydat)
        else:
            self.plotpanel.update_line(0, tdat, ydat, draw=True)
            self.write_message(" %i points in %8.4f s" % (n,etime))

        lims = self.plotpanel.get_viewlimits()
        try:
            ymin, ymax = ydat[mask].min(), ydat[mask].max()
        except:
            ymin, ymax = ydat.min(), ydat.max()
        tmin = max(int(min(tdat)) - 1.0, -self.tmin)
        if (ymin < lims[2] or ymax >  lims[3] or
            tmin != self.tmin_last or time.time()-self.last_update > 2):
            self.tmin_last = tmin
            self.last_update = time.time()
            self.plotpanel.set_xylims((tmin, 0, ymin, ymax))

    def OnAbout(self, event):
        dlg = wx.MessageDialog(self, "wxmplot example: stripchart app",
                              "About WXMPlot test", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def OnExit(self, event):
        self.Destroy()
Example #23
0
    def __init__(self, parent, ID, **kws):
        kws["style"] = wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER|wx.TAB_TRAVERSAL

        wx.Frame.__init__(self, parent, ID, '',
                         wx.DefaultPosition, wx.Size(-1,-1), **kws)
        self.SetTitle("wxmplot StripChart Demo")

        self.tmin = 15.0

        self.SetFont(wx.Font(12,wx.SWISS,wx.NORMAL,wx.BOLD,False))
        menu = wx.Menu()
        ID_EXIT  = wx.NewId()
        ID_TIMER = wx.NewId()

        menu_exit = menu.Append(ID_EXIT, "E&xit",
                                "Terminate the program")

        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File");
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU,  self.OnExit, menu_exit)
        self.Bind(wx.EVT_CLOSE, self.OnExit)

        sbar = self.CreateStatusBar(2,wx.CAPTION)
        sfont = sbar.GetFont()
        sfont.SetWeight(wx.BOLD)
        sfont.SetPointSize(11)
        sbar.SetFont(sfont)
        self.SetStatusWidths([-3,-1])
        self.SetStatusText('',0)

        mainsizer = wx.BoxSizer(wx.VERTICAL)

        btnpanel = wx.Panel(self, -1)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        b_on  = wx.Button(btnpanel, -1, 'Start',   size=(-1,-1))
        b_off = wx.Button(btnpanel, -1, 'Stop',    size=(-1,-1))

        b_on.Bind(wx.EVT_BUTTON, self.onStartTimer)
        b_off.Bind(wx.EVT_BUTTON, self.onStopTimer)

        tlabel = wx.StaticText(btnpanel, -1, '  Time range:')
        self.time_range = FloatCtrl(btnpanel,  size=(100, -1),
                                    value=abs(self.tmin), precision=1)

        btnsizer.Add(b_on,   0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(b_off,  0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(tlabel, 1, wx.GROW|wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        btnsizer.Add(self.time_range, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)

        btnpanel.SetSizer(btnsizer)
        btnsizer.Fit(btnpanel)

        self.plotpanel = PlotPanel(self, messenger=self.write_message)
        self.plotpanel.BuildPanel()
        self.plotpanel.set_xlabel('Time from Present (s)')
        mainsizer.Add(btnpanel,       0,
                      wx.GROW|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        mainsizer.Add(self.plotpanel, 1,
                      wx.GROW|wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER|wx.LEFT, 0)
        self.SetSizer(mainsizer)
        mainsizer.Fit(self)

        self.Bind(wx.EVT_TIMER, self.onTimer)
        self.timer = wx.Timer(self)
        self.count    = 0
        self.Refresh()
        wx.CallAfter(self.onStartTimer)
Example #24
0
class AthenaImporter(wx.Frame):
    """Import Athena File"""
    def __init__(self,
                 parent,
                 filename=None,
                 read_ok_cb=None,
                 size=(725, 450),
                 _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1, size=size, style=FRAMESTYLE)
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop,
                          'Select None',
                          size=(100, 30),
                          action=self.onSelNone)
        sel_all = Button(ltop,
                         'Select All',
                         size=(100, 30),
                         action=self.onSelAll)
        sel_imp = Button(ltop,
                         'Import Selected Groups',
                         size=(200, 30),
                         action=self.onOK)

        self.grouplist = FileCheckList(leftpanel,
                                       select_action=self.onShowGroup)
        self.grouplist.SetBackgroundColour(wx.Colour(255, 255, 255))

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none, (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp, (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN | wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN | wx.GROW | wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel,
                                self.filename,
                                font=Font(13),
                                colour=self.colors.title,
                                style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.all = read_athena(filename,
                               do_bkg=False,
                               do_fft=False,
                               _larch=_larch)
        for item in dir(self.all):
            self.grouplist.Append(item)

        self.Show()
        self.Raise()

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)

    def onOK(self, event=None):
        """ import groups """
        for name in self.grouplist.GetCheckedStrings():
            rawgroup = getattr(self.all, name)
            npts = len(rawgroup.energy)
            outgroup = Group(datatype='xas',
                             path="%s::%s" % (self.filename, name),
                             filename=name,
                             groupname=fix_varname(name),
                             raw=rawgroup,
                             xdat=rawgroup.energy,
                             ydat=rawgroup.mu,
                             y=rawgroup.mu,
                             yerr=1.0,
                             npts=npts,
                             _index=1.0 * np.arange(npts),
                             plot_xlabel='Energy (eV)',
                             plot_ylabel='mu')

            if self.read_ok_cb is not None:
                self.read_ok_cb(outgroup, array_sel=None, overwrite=True)

        self.Destroy()

    def onCancel(self, event=None):
        self.Destroy()

    def onSelAll(self, event=None):
        self.grouplist.SetCheckedStrings(dir(self.all))

    def onSelNone(self, event=None):
        self.grouplist.SetCheckedStrings([])

    def onShowGroup(self, event=None):
        """column selections changed calc xdat and ydat"""
        gname = event.GetString()
        grp = getattr(self.all, gname)
        if hasattr(grp, 'energy') and hasattr(grp, 'mu'):
            self.plotpanel.plot(grp.energy,
                                grp.mu,
                                xlabel='Energy',
                                ylabel='mu',
                                title=gname)
Example #25
0
    def __init__(self, parent, group=None, last_array_sel=None,
                 read_ok_cb=None, edit_groupname=True, with_smooth=False,
                 _larch=None):
        self.parent = parent
        self.larch = _larch
        self.rawgroup = group
        self.with_smooth = with_smooth
        self.outgroup  = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype'):
            setattr(self.outgroup, attr, getattr(group, attr, None))

        if self.outgroup.datatype is None:
            self.outgroup.datatype = 'raw'
            if ('energ' in self.rawgroup.array_labels[0].lower() or
                'energ' in self.rawgroup.array_labels[1].lower()):
                self.outgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb

        self.array_sel = {'xpop': '', 'xarr': None,
                          'ypop': '', 'yop': '/',
                          'yarr1': None, 'yarr2': None,
                          'use_deriv': False}
        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in self.rawgroup.array_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in self.rawgroup.array_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in self.rawgroup.array_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % self.rawgroup.filename
        wx.Frame.__init__(self, None, -1,
                          'Build Arrays from Data Columns for %s' % self.rawgroup.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel, message, font=Font(13),
                           colour=self.colors.title, style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))

        arr_labels = self.rawgroup.array_labels
        yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = arr_labels + ['<index>']

        self.xarr   = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1  = Choice(panel, choices= arr_labels, **opts)
        self.yarr2  = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.outgroup.datatype)


        opts['size'] = (50, -1)
        self.yop =  Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (120, -1)

        self.use_deriv = Check(panel, label='use derivative',
                               default=self.array_sel['use_deriv'], **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        if with_smooth:
            opts['action'] = self.onSmoothChoice
            self.smooth_op = Choice(panel, choices=SMOOTH_OPS, **opts)
            self.smooth_op.SetSelection(0)

            opts['size'] = (100, -1)

            opts['action'] = self.onUpdate
            smooth_panel = wx.Panel(panel)
            smooth_sizer = wx.BoxSizer(wx.HORIZONTAL)
            self.smooth_conv = Choice(smooth_panel, choices=CONV_OPS, **opts)
            opts['size'] =  (30, -1)
            self.smooth_c0 = FloatCtrl(smooth_panel, value=3, precision=0, **opts)
            self.smooth_c1 = FloatCtrl(smooth_panel, value=1, precision=0, **opts)
            opts['size'] =  (75, -1)
            self.smooth_sig = FloatCtrl(smooth_panel, value=1, precision=4, **opts)
            self.smooth_c0.Disable()
            self.smooth_c1.Disable()
            self.smooth_sig.Disable()
            self.smooth_conv.SetSelection(0)
            self.smooth_conv.Disable()


        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels)-1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)


        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.Add(Button(bpanel, 'OK', action=self.onOK), 4)
        bsizer.Add(Button(bpanel, 'Cancel', action=self.onCancel), 4)
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title,     (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab,       (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop,   (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf,  (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        if with_smooth:
            ir += 1
            sizer.Add(SimpleText(panel, 'Smoothing:'), (ir, 0), (1, 1), LCEN, 0)
            sizer.Add(self.smooth_op,  (ir, 1), (1, 1), CEN, 0)

            smooth_sizer.Add(SimpleText(smooth_panel, ' n='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_c0,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' order='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_c1,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' form='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_conv,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' sigma='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_sig,  0, LCEN, 1)
            pack(smooth_panel, smooth_sizer)

            sizer.Add(smooth_panel,  (ir, 2), (1, 5), LCEN, 1)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'),  (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype,                    (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel, value=self.rawgroup.groupname,
                                         size=(120, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname,               (ir, 1), (1, 1), LCEN, 0)


        ir += 1
        sizer.Add(bpanel,     (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel, style=wx.TE_MULTILINE|wx.TE_READONLY,
                               size=(400, 250))
        try:
            m = open(self.rawgroup.filename, 'r')
            text = m.read()
            m.close()
        except:
            text = "The file '%s'\n could not be read" % self.rawgroup.filename
        ftext.SetValue(text)
        ftext.SetFont(Font(11))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN|wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW|wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN|wx.GROW,   2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [self.rawgroup.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)


        self.Show()
        self.Raise()
        self.onUpdate(self)
Example #26
0
class Runner(noname.MyFrame1):

    power_rendered = False
    data = data.Data

    def __init__(self, parent):
        noname.MyFrame1.__init__(self, parent)

    def render_input_sound(self, event):

        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            self.m_panel2.Refresh()

            self.canvas1 = PlotPanel(self.m_panel2,
                                     size=(self.m_panel2.GetSize()))

            if hasattr(self.data, 'time') and hasattr(self.data,
                                                      'input_sound'):
                self.canvas1.plot(self.data.time, self.data.input_sound)

            return

        else:
            self.canvas1.update_line(0,
                                     self.data.time,
                                     self.data.input_sound,
                                     draw=True)
            return

    def render_power(self, event):
        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            if (self.power_rendered):
                self.canvas2.update_line(0,
                                         self.data.truncated_frequency,
                                         self.data.truncated_power,
                                         draw=True)
            else:
                self.canvas2 = PlotPanel(self.m_panel3,
                                         size=(self.m_panel3.GetSize()))

                if hasattr(self.data, 'truncated_frequency') and hasattr(
                        self.data, 'truncated_power'):
                    self.canvas2.plot(self.data.truncated_frequency,
                                      self.data.truncated_power, 'r')
                    self.canvas2.oplot(
                        self.data.truncated_frequency,
                        np.full((len(self.data.truncated_frequency)),
                                self.data.min))
                    self.power_rendered = True

            return

        # For slider
        else:

            p = backend.get_cutoff_value(self.data.min, self.data.slope,
                                         self.m_slider1.GetValue())
            if (self.power_rendered):
                self.canvas2.update_line(
                    1,
                    self.data.truncated_frequency,
                    np.full((len(self.data.truncated_frequency)), p),
                    draw=True)

            else:
                self.canvas2 = PlotPanel(self.m_panel3,
                                         size=(self.m_panel3.GetSize()))
                self.canvas2.plot(self.data.truncated_frequency,
                                  self.data.truncated_power, 'r')
                self.canvas2.oplot(
                    self.data.truncated_frequency,
                    np.full((len(self.data.truncated_frequency)),
                            self.data.min))
                self.power_rendered = True

            return

    def render_output(self, event):

        if wx.Event.GetEventType(event) == 10084 or wx.Event.GetEventType(
                event) == 10161:

            self.m_panel4.Refresh()

            self.canvas3 = PlotPanel(self.m_panel4,
                                     size=(self.m_panel4.GetSize()))

            if hasattr(self.data, 'time') and hasattr(self.data, 'ifft'):
                self.canvas3.plot(self.data.time, self.data.ifft)

            return

        else:

            self.canvas3.update_line(0,
                                     self.data.time,
                                     self.data.ifft,
                                     draw=True)
            return

    def loadAudio(self, event):
        ''' 
        Loads audio from path and calls render functions.\n
        wx event: 10161
        '''

        self.data.load_sound(location=self.m_filePicker1.GetPath())
        self.data.load_power_graph()
        # Fire screen refresh event
        self.render_input_sound(event)
        self.render_power(event)
        self.render_output(event)

        return

    def slider_move(self, event):
        self.render_power(event)

        self.data.load_output(
            backend.get_cutoff_value(self.data.min, self.data.slope,
                                     self.m_slider1.GetValue()))

        self.render_output(event)

    def export(self, event):
        self.data.export()

    def play(self, event):
        sd.play(self.data.ifft, self.data.fs)
        time.sleep(len(self.data.input_sound) / self.data.fs)
        sd.stop()

    def add_noise(self, event):
        self.data.add_noise()
        self.render_input_sound(event)
        self.render_power(event)
        self.render_output(event)
Example #27
0
    def createMainPanel(self):
        wx.CallAfter(self.init_larch)
        mainpanel = wx.Panel(self)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)

        self.yops = [[],[]]
        self.yarr = [[],[]]
        arr_kws= {'choices':[], 'size':(120, -1), 'action':self.onPlot}

        self.title = SimpleText(panel, 'initializing...',
                                font=Font(13), colour='#880000')
        self.xarr = add_choice(panel, **arr_kws)
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **arr_kws))
            self.yarr[1].append(add_choice(panel, **arr_kws))

        for opts, sel, wid in ((PRE_OPS, 0, 100), (ARR_OPS, 3, 60),
                               (ARR_OPS, 3, 60)):
            arr_kws['choices'] = opts
            arr_kws['size'] = (wid, -1)
            self.yops[0].append(add_choice(panel, default=sel, **arr_kws))
            self.yops[1].append(add_choice(panel, default=sel, **arr_kws))

        # place widgets
        sizer = wx.GridBagSizer(5, 10)
        sizer.Add(self.title,                  (0, 1), (1, 6), LCEN, 2)
        sizer.Add(SimpleText(panel, '  X ='), (1, 0), (1, 1), CEN, 0)
        sizer.Add(self.xarr,                   (1, 3), (1, 1), RCEN, 0)

        ir = 1
        for i in range(2):
            ir += 1
            label = '  Y%i =' % (i+1)
            sizer.Add(SimpleText(panel, label),  (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0],           (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('),   (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0],           (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1],           (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1],           (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'),    (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2],           (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2],           (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'),    (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        sizer.Add(hline(panel),   (ir, 0), (1, 12), CEN|wx.GROW|wx.ALL, 0)
        pack(panel, sizer)


        self.plotpanel = PlotPanel(mainpanel, size=(520, 550),
                                   axissize=(0.18, 0.18, 0.70, 0.70),
                                   fontsize=8)

        self.plotpanel.messenger = self.write_message
        self.plotpanel.canvas.figure.set_facecolor((0.98,0.98,0.97))

        btnsizer = wx.StdDialogButtonSizer()
        btnpanel = wx.Panel(mainpanel)
        btnsizer.Add(add_button(btnpanel, 'Pause', action=self.onPause))
        btnsizer.Add(add_button(btnpanel, 'Resume', action=self.onResume))
        btnsizer.Add(add_button(btnpanel, 'Abort', action=self.onAbort))
        pack(btnpanel, btnsizer)

        mainsizer.Add(panel,   0, LCEN|wx.EXPAND, 2)
        mainsizer.Add(self.plotpanel, 1, wx.GROW|wx.ALL, 1)
        mainsizer.Add(btnpanel, 0, wx.GROW|wx.ALL, 1)

        pack(mainpanel, mainsizer)
        return mainpanel
class TelemetrySoftware(wx.Frame):
    def __init__(self):
        super(TelemetrySoftware, self).__init__(None, title="URSS Telemetry")

        # initial data values
        self.voltage = MAX_VOLTAGE
        self.amperage = MIN_AMPERAGE
        self.rpm = MIN_RPM
        self.controllerTemp = MIN_CONTROLLER_TEMP

        # plot data
        self.voltage_values = []
        self.amperage_values = []
        self.timestamps = []
        self.goalVoltageLineDisplayed = False

        # fake telemetry flag
        self.fake_telemetry = True
        self.fake_telemetry_counter = 0

        self.Maximize(True)
        self.InitUI()
        self.InitTelemetryThread()
        self.Centre()
        self.Show()

    def InitUI(self):
        panelRoot = wx.Panel(self)
        panelRootSizer = wx.BoxSizer(wx.VERTICAL)

        topSplitter = wx.SplitterWindow(panelRoot,
                                        style=wx.SP_LIVE_UPDATE | wx.SP_3DSASH)
        topVerticalSplitter = wx.SplitterWindow(topSplitter,
                                                style=wx.SP_LIVE_UPDATE
                                                | wx.SP_3DSASH)

        #############################################
        #   TOP-LEFT PANEL (STATUS AND CONTROLS)    #
        #############################################

        panelTopLeft = wx.Panel(topVerticalSplitter)
        panelTopLeftSizer = wx.BoxSizer(wx.VERTICAL)

        # create gauges and set initial values
        self.voltageGauge = wx.Gauge(panelTopLeft, -1,
                                     MAX_VOLTAGE - MIN_VOLTAGE, (0, 0),
                                     (250, 25))
        self.voltageGauge.SetValue(self.voltage - MIN_VOLTAGE)

        self.amperageGauge = wx.Gauge(panelTopLeft, -1,
                                      MAX_AMPERAGE - MIN_AMPERAGE, (0, 0),
                                      (250, 25))
        self.amperageGauge.SetValue(self.amperage - MIN_AMPERAGE)

        self.rpmGauge = wx.Gauge(panelTopLeft, -1, MAX_RPM - MIN_RPM, (0, 0),
                                 (250, 25))
        self.rpmGauge.SetValue(self.rpm - MIN_RPM)

        self.controllerTempGauge = wx.Gauge(
            panelTopLeft, -1, MAX_CONTROLLER_TEMP - MIN_CONTROLLER_TEMP,
            (0, 0), (250, 25))
        self.controllerTempGauge.SetValue(self.controllerTemp -
                                          MIN_CONTROLLER_TEMP)

        # create labels
        self.voltageLabel = wx.StaticText(
            panelTopLeft, -1, "Voltage (" + str(self.voltage) + ")")
        self.amperagLabel = wx.StaticText(
            panelTopLeft, -1, "Amperage (" + str(self.amperage) + ")")
        self.rpmLabel = wx.StaticText(panelTopLeft, -1,
                                      "RPM (" + str(self.rpm) + ")")
        self.controllerTempLabel = wx.StaticText(
            panelTopLeft, -1,
            "Controller Temperature (" + str(self.controllerTemp) + ")")

        # Add voltage Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.voltageLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.voltageGauge, 1, wx.ALIGN_CENTRE_HORIZONTAL)
        # Add amperage Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.amperagLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.amperageGauge, 1,
                              wx.ALIGN_CENTRE_HORIZONTAL)
        # Add RPM Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.rpmLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.rpmGauge, 1, wx.ALIGN_CENTRE_HORIZONTAL)
        # Add controller temp Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.controllerTempLabel, 0,
                              wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.controllerTempGauge, 1,
                              wx.ALIGN_CENTRE_HORIZONTAL)

        # Add BoxSizer to panel
        panelTopLeft.SetSizer(panelTopLeftSizer)

        ################################
        #   TOP-RIGHT PANEL (GRAPH)    #
        ################################

        panelTopRight = wx.Panel(topVerticalSplitter)
        panelTopRightSizer = wx.BoxSizer(wx.VERTICAL)

        # create top button bar
        topButtonPanel = wx.Panel(panelTopRight, -1)
        topButtonSizer = wx.BoxSizer(wx.HORIZONTAL)

        goalVoltageLabel = wx.StaticText(
            topButtonPanel, -1, '    End Goal Voltage Value (V):    ')
        self.goalEndVoltage = FloatCtrl(topButtonPanel,
                                        size=(100, -1),
                                        value=34.5,
                                        precision=1)
        endTimeLabel = wx.StaticText(topButtonPanel, -1,
                                     '    End Time (min):    ')
        self.endTime = FloatCtrl(topButtonPanel,
                                 size=(100, -1),
                                 value=120,
                                 precision=0)
        plotGoalVoltageButton = wx.Button(topButtonPanel,
                                          -1,
                                          'Plot Goal Voltage',
                                          size=(250, -1))
        plotGoalVoltageButton.Bind(wx.EVT_BUTTON, self.OnPlotGoalVoltage)

        topButtonSizer.Add(goalVoltageLabel)
        topButtonSizer.Add(self.goalEndVoltage)
        topButtonSizer.Add(endTimeLabel)
        topButtonSizer.Add(self.endTime)
        topButtonSizer.Add(plotGoalVoltageButton)

        topButtonPanel.SetSizer(topButtonSizer)
        topButtonSizer.Fit(topButtonPanel)

        # create plot panel

        self.plotPanel = PlotPanel(panelTopRight)

        # create bottom button bar

        bottomButtonPanel = wx.Panel(panelTopRight, -1)
        bottomButtonSizer = wx.BoxSizer(wx.HORIZONTAL)

        exportButton = wx.Button(bottomButtonPanel,
                                 -1,
                                 'Export Plot to CSV',
                                 size=(250, -1))
        exportButton.Bind(wx.EVT_BUTTON, self.ExportPlotDataToCSV)
        resetButton = wx.Button(bottomButtonPanel,
                                -1,
                                'Reset Graph',
                                size=(250, -1))
        resetButton.Bind(wx.EVT_BUTTON, self.ResetGraph)

        bottomButtonSizer.Add(exportButton, 1)
        bottomButtonSizer.Add(resetButton, 1)

        bottomButtonPanel.SetSizer(bottomButtonSizer)
        bottomButtonSizer.Fit(bottomButtonPanel)

        # Add panels to top right sizer
        panelTopRightSizer.Add(topButtonPanel, 0, wx.EXPAND | wx.ALL)
        panelTopRightSizer.Add(self.plotPanel, 1, wx.EXPAND | wx.ALL)
        panelTopRightSizer.Add(bottomButtonPanel, 0)

        # Add BoxSizer to panel
        panelTopRight.SetSizer(panelTopRightSizer)

        # add top panels to vertical splitter
        topVerticalSplitter.SplitVertically(panelTopLeft, panelTopRight)
        topVerticalSplitter.SetSashGravity(0.25)

        #############################################
        #   BOTTOM PANEL (LOG & TELEMETRY INPUT)    #
        #############################################

        panelBottom = wx.Panel(topSplitter)
        panelBottomSizer = wx.BoxSizer(wx.VERTICAL)

        self.logPane = LogPane(panelBottom)

        logPaneLabel = wx.StaticText(
            panelBottom,
            label="Telemetry Message Log (Last 100 messages shown):")
        logPaneLabel.SetFont(
            wx.Font(14, wx.FONTFAMILY_TELETYPE, wx.NORMAL, wx.BOLD))
        panelBottomSizer.Add(logPaneLabel, 0, wx.ALIGN_TOP)
        panelBottomSizer.Add(self.logPane, 1, wx.EXPAND | wx.ALL)

        panelBottom.SetSizer(panelBottomSizer)

        topSplitter.SplitHorizontally(topVerticalSplitter, panelBottom)
        topSplitter.SetSashGravity(0.75)

        panelRootSizer.Add(topSplitter, 1, wx.EXPAND | wx.ALL)
        panelRoot.SetSizer(panelRootSizer)

    def InitTelemetryThread(self):
        print("Initializing telemetry thread...")

        if not self.fake_telemetry:
            success = False
            try:
                self.serial = serial.Serial("/dev/cu.usbserial-DN01236H",
                                            57600)
                success = True
                if not self.serial.is_open:
                    success = False
            except Exception:
                print("Could not open serial radio!")

            if not success:
                # If we fail to connect to serial, display error and then quitself.
                dial = wx.MessageDialog(
                    None,
                    'Could not connect to serial radio. Please plug in the serial radio adapter and restart your computer!',
                    'Error', wx.OK | wx.ICON_ERROR)
                dial.ShowModal()
                exit(0)

        thread = threading.Thread(target=self.TelemetryThread)
        thread.start()

        print("Done.")

    def TelemetryCallback(self, message):
        timestamp = int(round(time.time()))
        if len(self.timestamps) == 0:
            self.t0 = timestamp

        self.logPane.AddLine(message)

        if not self.fake_telemetry:
            # parse JSON message
            m = json.loads(message)
            split_message = m['message'].split(',')
            if split_message[0] == 'BATTERY':
                self.voltage = float(split_message[2][2:]) / 1000
                self.amperage = float(split_message[4][2:]) / 1000 * -1

        # add values to lists
        self.voltage_values.append(self.voltage)
        self.amperage_values.append(self.amperage)
        self.timestamps.append(timestamp - self.t0)

        # update gauges and plot
        self.UpdateGauges()
        self.UpdatePlot()

    def UpdateGauges(self):
        self.voltageGauge.SetValue(self.voltage - MIN_VOLTAGE)
        self.voltageLabel.SetLabel("Voltage (" + str(self.voltage) + "/" +
                                   str(MAX_VOLTAGE) + ")")
        self.amperageGauge.SetValue(self.amperage - MIN_AMPERAGE)
        self.amperagLabel.SetLabel("Amperage (" + str(self.amperage) + "/" +
                                   str(MAX_AMPERAGE) + ")")
        self.rpmGauge.SetValue(self.rpm - MIN_RPM)
        self.rpmLabel.SetLabelText("RPM (" + str(self.rpm) + "/" +
                                   str(MAX_RPM) + ")")
        self.controllerTempGauge.SetValue(self.controllerTemp -
                                          MIN_CONTROLLER_TEMP)
        self.controllerTempLabel.SetLabelText("Controller Temperature (" +
                                              str(self.controllerTemp) + ")")

    def UpdatePlot(self):
        v_n = len(self.voltage_values)
        tdat = np.array(self.timestamps)
        vdat = np.array(self.voltage_values)
        adat = np.array(self.amperage_values)
        if v_n <= 2:
            self.plotPanel.plot(tdat,
                                vdat,
                                xlabel='Time (s from start)',
                                ylabel='Voltage (V)',
                                label='Voltage',
                                style='solid')
            self.plotPanel.oplot(tdat,
                                 adat,
                                 y2label='Amperage (A)',
                                 side='right',
                                 label='Amperage',
                                 style='long dashed',
                                 show_legend=True)
        else:
            self.plotPanel.update_line(0, tdat, vdat, draw=True)
            self.plotPanel.update_line(1, tdat, adat, draw=True)

    def OnPlotGoalVoltage(self, event=None):
        v = float(self.goalEndVoltage.GetValue())
        t = int(self.endTime.GetValue()) * 60
        if len(self.voltage_values) > 2 and v <= self.voltage and t >= 0:
            tdat = np.linspace(0, t, t)
            vdat = np.linspace(self.voltage_values[0], v, t)
            if not self.goalVoltageLineDisplayed:
                self.goalVoltageLineDisplayed = True
                self.plotPanel.oplot(tdat,
                                     vdat,
                                     label='Goal Voltage',
                                     style='short dashed')
            else:
                self.plotPanel.update_line(2, tdat, vdat, draw=True)

    def ResetGraph(self, event=None):
        del self.timestamps[:]
        del self.voltage_values[:]
        del self.amperage_values[:]
        self.goalVoltageLineDisplayed = False

    def ExportPlotDataToCSV(self, event=None):
        filename = 'exported_data_' + str(int(round(
            time.time() * 1000))) + '.csv'
        with open(filename, 'wb') as datafile:
            w = csv.writer(datafile)
            w.writerow(['Time (s)', 'Voltage (V)', 'Amperage (A)'])
            for i in range(len(self.timestamps)):
                w.writerow([
                    str(self.timestamps[i]),
                    str(self.voltage_values[i]),
                    str(self.amperage_values[i])
                ])

    def TelemetryThread(self):
        while True:
            if self.fake_telemetry:
                self.fake_telemetry_counter += 1
                wx.CallAfter(
                    self.TelemetryCallback, "Fake Telemetry Element " +
                    str(self.fake_telemetry_counter) + "\n")
                time.sleep(0.5)
            else:
                line = self.serial.readline()
                wx.CallAfter(self.TelemetryCallback, line)
Example #29
0
class ScanViewerFrame(wx.Frame):
    _about = """Scan Viewer,  Matt Newville <newville @ cars.uchicago.edu>  """
    TIME_MSG = 'Point %i/%i, Time Remaining ~ %s '

    def __init__(self, parent, dbname=None, server='sqlite', host=None,
                 port=None, user=None, password=None, create=True, **kws):

        wx.Frame.__init__(self, None, -1, style=FRAMESTYLE)
        title = "Epics Step Scan Viewer"
        self.parent = parent
        self.scandb = getattr(parent, 'scandb', None)
        if self.scandb is None and dbname is not None:
            self.scandb = ScanDB(dbname=dbname, server=server, host=host,
                                 user=user, password=password, port=port,
                                 create=create)
        self.larch = None
        self.lgroup = None

        self.SetTitle(title)
        self.SetSize((750, 750))
        self.SetFont(Font(9))
        self.createMainPanel()
        self.createMenus()
        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = ["Initializing....", " "]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        if self.scandb is not None:
            self.get_info  = self.scandb.get_info
            self.scandb_server = self.scandb.server
            self.live_scanfile = None
            self.live_cpt = -1
            self.total_npts = 1
            self.scantimer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.onScanTimer, self.scantimer)
            self.scantimer.Start(50)

        self.Show()
        self.Raise()

    def onScanTimer(self, evt=None, **kws):
        if self.lgroup is None:
            return

        curfile = fix_filename(self.get_info('filename'))
        sdata = self.scandb.get_scandata()
        npts = len(sdata[-1].data)

        if (npts > 2 and npts == self.live_cpt and
            curfile == self.live_scanfile): # no new data
            return

        # filename changed -- scan starting, so update
        # list of positioners, detectors, etc
        force_newplot = False
        if curfile != self.live_scanfile:
            force_newplot = True
            self.live_scanfile = curfile
            self.title.SetLabel(curfile)
            self.set_column_names(sdata)

        if npts == self.live_cpt:
            return

        time_est = hms(self.get_info('scan_time_estimate', as_int=True))
        msg = self.TIME_MSG % (npts, self.total_npts, time_est)
        self.SetStatusText(msg)
        self.live_cpt = npts
        for row in sdata:
            dat = row.data
            if self.scandb_server == 'sqlite':
                dat = json.loads(dat.replace('{', '[').replace('}', ']'))
            setattr(self.lgroup, fix_varname(row.name), np.array(dat))

        if npts > 1:
            self.onPlot(npts=npts, force_newplot=force_newplot)

    def set_column_names(self, sdata):
        """set column names from values read from scandata table"""
        self.lgroup.array_units = [fix_varname(s.units) for s in sdata]
        self.total_npts = self.get_info('scan_total_points', as_int=True)
        self.live_cpt = -1
        xcols, ycols, y2cols = [], [], []
        for s in sdata:
            nam = fix_varname(s.name)
            ycols.append(nam)
            if s.notes.lower().startswith('pos'):
                xcols.append(nam)

        y2cols = ycols[:] + ['1.0', '0.0', '']
        xarr_old = self.xarr.GetStringSelection()
        self.xarr.SetItems(xcols)

        ix = xcols.index(xarr_old) if xarr_old in xcols else 0
        self.xarr.SetSelection(ix)
        for i in range(2):
            for j in range(3):
                yold = self.yarr[i][j].GetStringSelection()
                idef, cols = 0, y2cols
                if i == 0 and j == 0:
                    idef, cols = 1, ycols
                self.yarr[i][j].SetItems(cols)
                iy = cols.index(yold) if yold in cols else idef
                self.yarr[i][j].SetSelection(iy)

    def createMainPanel(self):
        wx.CallAfter(self.init_larch)
        mainpanel = wx.Panel(self)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)

        self.yops = [[],[]]
        self.yarr = [[],[]]
        arr_kws= {'choices':[], 'size':(120, -1), 'action':self.onPlot}

        self.title = SimpleText(panel, 'initializing...',
                                font=Font(13), colour='#880000')
        self.xarr = add_choice(panel, **arr_kws)
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **arr_kws))
            self.yarr[1].append(add_choice(panel, **arr_kws))

        for opts, sel, wid in ((PRE_OPS, 0, 100), (ARR_OPS, 3, 60),
                               (ARR_OPS, 3, 60)):
            arr_kws['choices'] = opts
            arr_kws['size'] = (wid, -1)
            self.yops[0].append(add_choice(panel, default=sel, **arr_kws))
            self.yops[1].append(add_choice(panel, default=sel, **arr_kws))

        # place widgets
        sizer = wx.GridBagSizer(5, 10)
        sizer.Add(self.title,                  (0, 1), (1, 6), LCEN, 2)
        sizer.Add(SimpleText(panel, '  X ='), (1, 0), (1, 1), CEN, 0)
        sizer.Add(self.xarr,                   (1, 3), (1, 1), RCEN, 0)

        ir = 1
        for i in range(2):
            ir += 1
            label = '  Y%i =' % (i+1)
            sizer.Add(SimpleText(panel, label),  (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0],           (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('),   (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0],           (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1],           (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1],           (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'),    (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2],           (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2],           (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'),    (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        sizer.Add(hline(panel),   (ir, 0), (1, 12), CEN|wx.GROW|wx.ALL, 0)
        pack(panel, sizer)


        self.plotpanel = PlotPanel(mainpanel, size=(520, 550),
                                   axissize=(0.18, 0.18, 0.70, 0.70),
                                   fontsize=8)

        self.plotpanel.messenger = self.write_message
        self.plotpanel.canvas.figure.set_facecolor((0.98,0.98,0.97))

        btnsizer = wx.StdDialogButtonSizer()
        btnpanel = wx.Panel(mainpanel)
        btnsizer.Add(add_button(btnpanel, 'Pause', action=self.onPause))
        btnsizer.Add(add_button(btnpanel, 'Resume', action=self.onResume))
        btnsizer.Add(add_button(btnpanel, 'Abort', action=self.onAbort))
        pack(btnpanel, btnsizer)

        mainsizer.Add(panel,   0, LCEN|wx.EXPAND, 2)
        mainsizer.Add(self.plotpanel, 1, wx.GROW|wx.ALL, 1)
        mainsizer.Add(btnpanel, 0, wx.GROW|wx.ALL, 1)

        pack(mainpanel, mainsizer)
        return mainpanel

    def onPause(self, evt=None):
        self.scandb.set_info('request_command_pause', 1)

    def onResume(self, evt=None):
        self.scandb.set_info('request_command_pause', 0)

    def onAbort(self, evt=None):
        self.scandb.set_info('request_command_abort', 1)

    def CreateFitPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.fit_model   = add_choice(panel, size=(100, -1),
                                      choices=('Gaussian', 'Lorentzian',
                                               'Voigt', 'Linear', 'Quadratic',
                                               'Step', 'Rectangle',
                                               'Exponential'))
        self.fit_bkg = add_choice(panel, size=(100, -1),
                                  choices=('None', 'constant', 'linear', 'quadtratic'))
        self.fit_step = add_choice(panel, size=(100, -1),
                                  choices=('linear', 'error function', 'arctan'))

        self.fit_report = wx.StaticText(panel, -1, "", (180, 200))
        sizer = wx.GridBagSizer(10, 4)
        sizer.Add(SimpleText(p, 'Fit Model: '),           (0, 0), (1, 1), LCEN)
        sizer.Add(self.fit_model,                         (0, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Background: '),          (1, 0), (1, 1), LCEN)
        sizer.Add(self.fit_bkg,                           (1, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Step Function Form: '),  (2, 0), (1, 1), LCEN)
        sizer.Add(self.fit_step,                          (2, 1), (1, 1), LCEN)
        sizer.Add(add_button(panel, 'Show Fit', size=(100, -1),
                             action=self.onFitPeak),       (3, 0), (1, 1), LCEN)
        sizer.Add(self.fit_report,                         (0, 2), (4, 2), LCEN, 3)
        pack(panel, sizer)
        return panel

    def CreateXASPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.xas_autoe0   = check(panel, default=True, label='auto?')
        self.xas_autostep = check(panel, default=True, label='auto?')
        self.xas_op       = add_choice(panel, size=(95, -1),
                                       choices=('Raw Data', 'Pre-edged',
                                                'Normalized', 'Flattened'))
        self.xas_e0   = FloatCtrl(panel, value  = 0, precision=3, size=(95, -1))
        self.xas_step = FloatCtrl(panel, value  = 0, precision=3, size=(95, -1))
        self.xas_pre1 = FloatCtrl(panel, value=-200, precision=1, size=(95, -1))
        self.xas_pre2 = FloatCtrl(panel, value= -30, precision=1, size=(95, -1))
        self.xas_nor1 = FloatCtrl(panel, value=  30, precision=1, size=(95, -1))
        self.xas_nor2 = FloatCtrl(panel, value= 300, precision=1, size=(95, -1))
        self.xas_vict = add_choice(panel, size=(50, -1), choices=('0', '1', '2', '3'))
        self.xas_nnor = add_choice(panel, size=(50, -1), choices=('0', '1', '2', '3'))
        self.xas_vict.SetSelection(1)
        self.xas_nnor.SetSelection(2)
        sizer = wx.GridBagSizer(10, 4)

        sizer.Add(SimpleText(p, 'Plot XAS as: '),         (0, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'E0 : '),                 (1, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Edge Step: '),           (2, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Pre-edge range: '),      (3, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Normalization range: '), (4, 0), (1, 1), LCEN)

        sizer.Add(self.xas_op,                 (0, 1), (1, 1), LCEN)
        sizer.Add(self.xas_e0,                 (1, 1), (1, 1), LCEN)
        sizer.Add(self.xas_step,               (2, 1), (1, 1), LCEN)
        sizer.Add(self.xas_pre1,               (3, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'),          (3, 2), (1, 1), LCEN)
        sizer.Add(self.xas_pre2,               (3, 3), (1, 1), LCEN)
        sizer.Add(self.xas_nor1,               (4, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'),          (4, 2), (1, 1), LCEN)
        sizer.Add(self.xas_nor2,               (4, 3), (1, 1), LCEN)

        sizer.Add(self.xas_autoe0,             (1, 2), (1, 2), LCEN)
        sizer.Add(self.xas_autostep,           (2, 2), (1, 2), LCEN)

        sizer.Add(SimpleText(p, 'Victoreen:'), (3, 4), (1, 1), LCEN)
        sizer.Add(self.xas_vict,               (3, 5), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'PolyOrder:'), (4, 4), (1, 1), LCEN)
        sizer.Add(self.xas_nnor,               (4, 5), (1, 1), LCEN)

        pack(panel, sizer)
        return panel

    def onFitPeak(self, evt=None):
        gname = self.groupname
        if self.dtcorr.IsChecked():
            print 'fit needs to dt correct!'

        dtext = []
        model = self.fit_model.GetStringSelection().lower()
        dtext.append('Fit Model: %s' % model)
        bkg =  self.fit_bkg.GetStringSelection()
        if bkg == 'None':
            bkg = None
        if bkg is None:
            dtext.append('No Background')
        else:
            dtext.append('Background: %s' % bkg)

        step = self.fit_step.GetStringSelection().lower()
        if model in ('step', 'rectangle'):
            dtext.append('Step form: %s' % step)
        lgroup =  getattr(self.larch.symtable, gname)
        x = lgroup.arr_x
        y = lgroup.arr_y1
        pgroup = fit_peak(x, y, model, background=bkg, step=step,
                          _larch=self.larch)
        text = fit_report(pgroup.params, _larch=self.larch)
        dtext.append('Parameters: ')
        for pname in dir(pgroup.params):
            par = getattr(pgroup.params, pname)
            if isParameter(par):
                ptxt = "    %s= %.4f" % (par.name, par.value)
                if (hasattr(par, 'stderr') and par.stderr is not None):
                    ptxt = "%s(%.4f)" % (ptxt, par.stderr)
                dtext.append(ptxt)

        dtext = '\n'.join(dtext)

        text = fit_report(pgroup.params, _larch=self.larch)
        self.fit_report.SetLabel(dtext)

    def xas_process(self, gname, plotopts):
        """ process (pre-edge/normalize) XAS data from XAS form, overwriting
        larch group '_y1_' attribute to be plotted
        """
        print 'Process XAS ', gname
        out = self.xas_op.GetStringSelection().lower() # raw, pre, norm, flat
        if out.startswith('raw'):
            return plotopts

        preopts = {'group': gname, 'e0': None, 'step': None}

        lgroup = getattr(self.larch.symtable, gname)

        if self.dtcorr.IsChecked():
            print 'need to dt correct!'

        if not self.xas_autoe0.IsChecked():
            xmin, xmax = min(lgroup.arr_x),  max(lgroup.arr_x)
            e0 = self.xas_e0.GetValue()
            if e0 < xmax and e0 > xmin:
                preopts['e0'] = e0

        if not self.xas_autostep.IsChecked():
            preopts['step'] = self.xas_step.GetValue()

        preopts['pre1']  = self.xas_pre1.GetValue()
        preopts['pre2']  = self.xas_pre2.GetValue()
        preopts['norm1'] = self.xas_nor1.GetValue()
        preopts['norm2'] = self.xas_nor2.GetValue()

        preopts['nvict'] = self.xas_vict.GetSelection()
        preopts['nnorm'] = self.xas_nnor.GetSelection()

        preopts = ", ".join(["%s=%s" %(k, v) for k,v in preopts.items()])
        preedge_cmd = "pre_edge(%s._x1_, %s._y1_, %s)" % (gname, gname, preopts)

        self.larch(preedge_cmd)

        self.xas_e0.SetValue(lgroup.e0)
        self.xas_step.SetValue(lgroup.edge_step)

        if out.startswith('pre'):
            self.larch('%s._y1_ = %s.norm * %s.edge_step' % (gname, gname, gname))
        elif out.startswith('norm'):
            self.larch('%s._y1_ = %s.norm' % (gname, gname))
        elif out.startswith('flat'):
            self.larch('%s._y1_ = %s.flat' % (gname, gname))

        return plotopts

    def init_larch(self):
        t0 = time.time()
        from larch.wxlib import inputhook
        self.larch = Interpreter()
        self.larch.symtable.set_symbol('_sys.wx.wxapp', wx.GetApp())
        self.larch.symtable.set_symbol('_sys.wx.parent', self)
        self.larch('%s = group(filename="%s")' % (SCANGROUP, CURSCAN))
        self.larch('_sys.localGroup = %s)' % (SCANGROUP))
        self.lgroup =  getattr(self.larch.symtable, SCANGROUP)
        self.SetStatusText('ready')
        self.title.SetLabel('')

    def write_message(self, s, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(s, panel)

    def onPlot(self, evt=None, npts=None, force_newplot=False):
        """drow plot of newest data"""

        new_plot = force_newplot or npts < 3
        lgroup, gname = self.lgroup, SCANGROUP

        ix = self.xarr.GetSelection()
        x  = self.xarr.GetStringSelection()
        xlabel = x
        popts = {'labelfontsize': 8, 'xlabel': x}
        try:
            xunits = lgroup.array_units[ix]
            xlabel = '%s (%s)' % (xlabel, xunits)
        except:
            pass

        def make_array(wids, iy):
            gn  = SCANGROUP
            op1 = self.yops[iy][0].GetStringSelection()
            op2 = self.yops[iy][1].GetStringSelection()
            op3 = self.yops[iy][2].GetStringSelection()
            yy1 = self.yarr[iy][0].GetStringSelection()
            yy2 = self.yarr[iy][1].GetStringSelection()
            yy3 = self.yarr[iy][2].GetStringSelection()

            if yy1 in ('0', '1', '', None) or len(yy1) < 0:
                return '', ''

            label = yy1
            expr = "%s.%s"  % (gn, yy1)

            if yy2 != '':
                label = "%s%s%s"     % (label, op2, yy2)
                expr  = "%s%s%s.%s"  % (expr, op2, gn, yy2)
            if yy3 != '':
                label = "(%s)%s%s"    % (label, op3, yy3)
                expr  = "(%s)%s%s.%s" % (expr, op3, gn, yy3)
            if op1 != '':
                label = "%s(%s)" % (op1, label)
                expr  = "%s(%s)" % (op1, expr)
            return label, expr

        ylabel, yexpr = make_array(self.yops, 0)
        if yexpr == '':
            return
        self.larch("%s.arr_x = %s.%s" % (gname, gname, x))
        self.larch("%s.arr_y1 = %s" % (gname, yexpr))
        # print 'onPlot Show Groups ', lgroup
        # print ' : ', dir(lgroup)
        # print '  X -> ', x, lgroup.arr_x
        # print '  Y -> ', yexpr, lgroup.arr_y1
        try:
            npts = min(len(lgroup.arr_x), len(lgroup.arr_y1))
        except AttributeError:
            return

        y2label, y2expr = make_array(self.yops, 1)
        if y2expr != '':
            self.larch("%s.arr_y2 = %s" % (gname, y2expr))
            n2pts = npts
            try:
                n2pts = min(len(lgroup.arr_x), len(lgroup.arr_y1),
                            len(lgroup.arr_y2))
                lgroup.arr_y2 = np.array( lgroup.arr_y2[:n2pts])
            except:
                y2expr = ''
            npts = n2pts

        lgroup.arr_y1 = np.array( lgroup.arr_y1[:npts])
        lgroup.arr_x  = np.array( lgroup.arr_x[:npts])

        path, fname = os.path.split(self.live_scanfile)
        popts.update({'title': fname, 'xlabel': xlabel,
                      'ylabel': ylabel, 'y2label': y2label})

        ppnl = self.plotpanel
        if new_plot:
            ppnl.plot(lgroup.arr_x, lgroup.arr_y1,
                      label= "%s: %s" % (fname, ylabel), **popts)
            if y2expr != '':
                ppnl.oplot(lgroup.arr_x, lgroup.arr_y2, side='right',
                           label= "%s: %s" % (fname, y2label), **popts)
            ppnl.canvas.draw()
        else:
            ppnl.set_xlabel(xlabel)
            ppnl.set_ylabel(ylabel)
            ppnl.update_line(0, lgroup.arr_x, lgroup.arr_y1,
                             draw=True, update_limits=True)
            ppnl.set_xylims((min(lgroup.arr_x), max(lgroup.arr_x),
                             min(lgroup.arr_y1), max(lgroup.arr_y1)))

            if y2expr != '':
                ppnl.set_y2label(y2label)
                ppnl.update_line(1, lgroup.arr_x, lgroup.arr_y2, side='right',
                                 draw=True, update_limits=True)
                ppnl.set_xylims((min(lgroup.arr_x), max(lgroup.arr_x),
                                 min(lgroup.arr_y2), max(lgroup.arr_y2)),
                                side='right')

    def createMenus(self):
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        pmenu = wx.Menu()
        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

        self.menubar.Append(fmenu, "&File")

        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Copy\tCtrl+C",  "Copy to Clipboard", self.onClipboard)
        add_menu(self, fmenu, "&Save\tCtrl+S", "Save Figure",   self.onSaveFig)
        add_menu(self, fmenu, "&Print\tCtrl+P", "Print Figure", self.onPrint)
        add_menu(self, fmenu, "Page Setup", "Print Page Setup", self.onPrintSetup)
        add_menu(self, fmenu, "Preview", "Print Preview",       self.onPrintPreview)
        #

        add_menu(self, pmenu, "Configure\tCtrl+K",
                 "Configure Plot", self.onConfigurePlot)
        add_menu(self, pmenu, "Unzoom\tCtrl+Z", "Unzoom Plot", self.onUnzoom)
        pmenu.AppendSeparator()
        add_menu(self, pmenu, "Toggle Legend\tCtrl+L",
                 "Toggle Legend on Plot", self.onToggleLegend)
        add_menu(self, pmenu, "Toggle Grid\tCtrl+G",
                 "Toggle Grid on Plot", self.onToggleGrid)

        self.menubar.Append(pmenu, "Plot Options")
        self.SetMenuBar(self.menubar)

    def onClipboard(self, evt=None):
        self.plotpanel.canvas.Copy_to_Clipboard(evt)

    def onSaveFig(self, evt=None):
        self.plotpanel.save_figure(event=evt,
                                   transparent=True, dpi=300)

    def onPrint(self, evt=None):
        self.plotpanel.Print(evet)

    def onPrintSetup(self, evt=None):
        self.plotpanel.PrintSetup(evt)

    def onPrintPreview(self, evt=None):
        self.plotpanel.PrintPreview(evt)

    def onConfigurePlot(self, evt=None):
        self.plotpanel.configure(evt)

    def onUnzoom(self, evt=None):
        self.plotpanel.unzoom(evt)

    def onToggleLegend(self, evt=None):
        self.plotpanel.toggle_legend(evt)

    def onToggleGrid(self, evt=None):
        self.plotpanel.toggle_grid(evt)

    def onAbout(self,evt):
        dlg = wx.MessageDialog(self, self._about,"About Epics StepScan",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onClose(self,evt):
        for obj in self.plotters:
            try:
                obj.Destroy()
            except:
                pass
        for nam in dir(self.larch.symtable._sys.wx):
            obj = getattr(self.larch.symtable._sys.wx, nam)
            del obj

        self.Destroy()
Example #30
0
class StripChartFrame(wx.Frame):
    def __init__(self, parent, ID, **kws):
        kws["style"] = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.TAB_TRAVERSAL

        wx.Frame.__init__(self, parent, ID, '', wx.DefaultPosition,
                          wx.Size(-1, -1), **kws)
        self.SetTitle("wxmplot StripChart Demo")

        self.tmin = 15.0

        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        menu = wx.Menu()
        ID_EXIT = wx.NewId()
        ID_TIMER = wx.NewId()

        menu_exit = menu.Append(ID_EXIT, "E&xit", "Terminate the program")

        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.OnExit, menu_exit)
        self.Bind(wx.EVT_CLOSE, self.OnExit)

        sbar = self.CreateStatusBar(2, wx.CAPTION)
        sfont = sbar.GetFont()
        sfont.SetWeight(wx.BOLD)
        sfont.SetPointSize(11)
        sbar.SetFont(sfont)
        self.SetStatusWidths([-3, -1])
        self.SetStatusText('', 0)

        mainsizer = wx.BoxSizer(wx.VERTICAL)

        btnpanel = wx.Panel(self, -1)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        b_on = wx.Button(btnpanel, -1, 'Start', size=(-1, -1))
        b_off = wx.Button(btnpanel, -1, 'Stop', size=(-1, -1))

        b_on.Bind(wx.EVT_BUTTON, self.onStartTimer)
        b_off.Bind(wx.EVT_BUTTON, self.onStopTimer)

        tlabel = wx.StaticText(btnpanel, -1, '  Time range:')
        self.time_range = FloatCtrl(btnpanel,
                                    size=(100, -1),
                                    value=abs(self.tmin),
                                    precision=1)

        btnsizer.Add(b_on, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(b_off, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(
            tlabel, 1,
            wx.GROW | wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(self.time_range, 0,
                     wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)

        btnpanel.SetSizer(btnsizer)
        btnsizer.Fit(btnpanel)

        self.plotpanel = PlotPanel(self, messenger=self.write_message)
        self.plotpanel.BuildPanel()
        self.plotpanel.set_xlabel('Time from Present (s)')
        mainsizer.Add(btnpanel, 0,
                      wx.GROW | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        mainsizer.Add(
            self.plotpanel, 1,
            wx.GROW | wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        self.SetSizer(mainsizer)
        mainsizer.Fit(self)

        self.Bind(wx.EVT_TIMER, self.onTimer)
        self.timer = wx.Timer(self)
        self.count = 0
        self.Refresh()
        wx.CallAfter(self.onStartTimer)

    def write_message(self, msg, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(msg, panel)

    def onStartTimer(self, event=None):
        self.count = 0
        t0, y0 = next_data()
        self.ylist = [y0]
        self.tlist = [t0]
        self.tmin_last = -10000
        self.time0 = time.time()
        self.timer.Start(50)

    def onStopTimer(self, event=None):
        self.timer.Stop()

    def onTimer(self, event):
        self.count += 1
        etime = time.time() - self.time0
        self.tmin = float(self.time_range.GetValue())
        t1, y1 = next_data()
        self.tlist.append(t1)
        self.ylist.append(y1)
        tdat = np.array(self.tlist) - t1
        mask = np.where(tdat > -abs(self.tmin))
        ydat = np.array(self.ylist)

        n = len(self.ylist)
        if n <= 2:
            self.plotpanel.plot(tdat, ydat)
        else:
            self.plotpanel.update_line(0, tdat, ydat, draw=True)
            self.write_message(" %i points in %8.4f s" % (n, etime))

        lims = self.plotpanel.get_viewlimits()
        try:
            ymin, ymax = ydat[mask].min(), ydat[mask].max()
        except:
            ymin, ymax = ydat.min(), ydat.max()
        tmin = max(int(min(tdat)) - 1.0, -self.tmin)
        if (ymin < lims[2] or ymax > lims[3] or tmin != self.tmin_last
                or time.time() - self.last_update > 2):
            self.tmin_last = tmin
            self.last_update = time.time()
            self.plotpanel.set_xylims((tmin, 0, ymin, ymax))

    def OnAbout(self, event):
        dlg = wx.MessageDialog(self, "wxmplot example: stripchart app",
                               "About WXMPlot test",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def OnExit(self, event):
        self.Destroy()
Example #31
0
    def __init__(self,
                 parent,
                 filename=None,
                 groupname=None,
                 last_array_sel=None,
                 read_ok_cb=None,
                 edit_groupname=True,
                 _larch=None):
        self.parent = parent
        self._larch = _larch
        self.path = filename

        group = self.initgroup = self.read_column_file(self.path)
        self.subframes = {}
        self.workgroup = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype',
                     'array_labels'):
            setattr(self.workgroup, attr, getattr(group, attr, None))

        arr_labels = [l.lower() for l in self.initgroup.array_labels]

        if self.workgroup.datatype is None:
            self.workgroup.datatype = 'raw'
            if ('energ' in arr_labels[0] or 'energ' in arr_labels[1]):
                self.workgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb
        self.array_sel = {
            'xpop': '',
            'xarr': None,
            'ypop': '',
            'yop': '/',
            'yarr1': None,
            'yarr2': None,
            'use_deriv': False
        }

        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in arr_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in arr_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in arr_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % group.filename
        wx.Frame.__init__(self,
                          None,
                          -1,
                          'Build Arrays from Data Columns for %s' %
                          group.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel,
                           message,
                           font=Font(13),
                           colour=self.colors.title,
                           style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']

        self.xarr = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1 = Choice(panel, choices=arr_labels, **opts)
        self.yarr2 = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.workgroup.datatype)

        opts['size'] = (50, -1)
        self.yop = Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (120, -1)

        self.use_deriv = Check(panel,
                               label='use derivative',
                               default=self.array_sel['use_deriv'],
                               **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels) - 1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)

        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        _ok = Button(bpanel, 'OK', action=self.onOK)
        _cancel = Button(bpanel, 'Cancel', action=self.onCancel)
        _edit = Button(bpanel, 'Edit Array Names', action=self.onEditNames)
        bsizer.Add(_ok)
        bsizer.Add(_cancel)
        bsizer.Add(_edit)
        _ok.SetDefault()
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title, (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop, (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf, (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab, (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype, (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel,
                                         value=group.groupname,
                                         size=(240, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname, (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        sizer.Add(bpanel, (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248, 248, 240))
        self.nb.SetActiveTabColour(wx.Colour(254, 254, 195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40, 40, 180))
        self.nb.SetActiveTabTextColour(wx.Colour(80, 0, 0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel,
                            style=wx.TE_MULTILINE | wx.TE_READONLY,
                            size=(400, 250))

        ftext.SetValue(group.text)
        ftext.SetFont(Font(10))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN | wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW | wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN | wx.GROW, 2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [group.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.Show()
        self.Raise()
        self.onUpdate(self)
Example #32
0
    def createDetailsPanel(self, parent):
        mainpanel = wx.Panel(parent)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)
        sizer = wx.GridBagSizer(8, 7)

        self.title = SimpleText(panel, 'initializing...')
        ir = 0
        sizer.Add(self.title, (ir, 0), (1, 6), LCEN, 2)
        # x-axis

        self.xarr = add_choice(panel, choices=[],
                               action=self.onYchoice,  size=(120, -1))
        self.xop  = add_choice(panel, choices=('', 'log'),
                               action=self.onYchoice, size=(75, -1))

        ir += 1
        sizer.Add(SimpleText(panel, 'X = '), (ir, 0), (1, 1), CEN, 0)
        sizer.Add(self.xop,                  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, '('),    (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xarr,                 (ir, 3), (1, 1), RCEN, 0)
        sizer.Add(SimpleText(panel, ')'),    (ir, 4), (1, 1), CEN, 0)

        self.yops = [[],[]]
        self.yarr = [[],[]]

        for opts, sel, siz in ((PRE_OPS, 0, 75), (ARR_OPS, 3, 50),
                             (ARR_OPS, 3, 50)):
            w1 = add_choice(panel, choices=opts, action=self.onYchoice,
                            size=(siz, -1))
            w1.SetSelection(sel)
            self.yops[0].append(w1)

            w2 = add_choice(panel, choices=opts, action=self.onYchoice,
                            size=(siz, -1))
            w2.SetSelection(sel)
            self.yops[1].append(w2)

        opts= {'choices':[], 'size':(120, -1), 'action':self.onYchoice}
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **opts))
            self.yarr[1].append(add_choice(panel, **opts))

        for i in range(2):
            ir += 1
            label = 'Y%i = ' % (i+1)
            sizer.Add(SimpleText(panel, label),  (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0],           (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('),   (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0],           (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1],           (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1],           (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'),    (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2],           (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2],           (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'),    (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        # sizer.Add(SimpleText(panel, ' New Plot: '),  (ir,   0), (1, 3), LCEN, 0)
        # sizer.Add(SimpleText(panel, ' Over Plot: '), (ir+1, 0), (1, 3), LCEN, 0)

        for jr, ic, dc, opt, ttl in ((0, 0, 4, 'win old',    'New Plot, This Window'),
                                     (0, 4, 2, 'win new',    'New Plot, New Window'),
                                     (1, 0, 4, 'over left',  'Over Plot, Left Axis'),
                                     (1, 4, 2, 'over right', 'Over Plot, Right Axis')):
            sizer.Add(add_button(panel, ttl, size=(165, -1),
                                 action=Closure(self.onPlot, opt=opt)),
                      (ir+jr, ic), (1, dc), LCEN, 2)

        ir += 2
        self.dtcorr   = check(panel, default=True, label='correct deadtime?')
        sizer.Add(self.dtcorr,  (ir,   0), (1, 3), LCEN, 0)
        ir += 1
        sizer.Add(SimpleText(panel, ''), (ir,   0), (1, 3), LCEN, 0)

        pack(panel, sizer)


#         self.nb = flat_nb.FlatNotebook(mainpanel, -1, agwStyle=FNB_STYLE)
#
#         self.nb.SetTabAreaColour(wx.Colour(248,248,240))
#         self.nb.SetActiveTabColour(wx.Colour(254,254,195))
#
#         self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
#         self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))
#
#         self.xas_panel = self.CreateXASPanel(self.nb) # mainpanel)
#         self.fit_panel = self.CreateFitPanel(self.nb) # mainpanel)
#
#         self.nb.AddPage(self.fit_panel, ' General Analysis ', True)
#         self.nb.AddPage(self.xas_panel, ' XAS Processing ',   True)

        mainsizer.Add(panel,   0, LCEN|wx.EXPAND, 2)
        self.plotpanel = PlotPanel(mainpanel, size=(500, 670))
        self.plotpanel.messenger = self.write_message

        bgcol = panel.GetBackgroundColour()
        bgcol = (bgcol[0]/255., bgcol[1]/255., bgcol[2]/255.)
        self.plotpanel.canvas.figure.set_facecolor(bgcol)

        mainsizer.Add(self.plotpanel, 1, wx.GROW|wx.ALL, 1)

        # mainsizer.Add(self.nb, 1, LCEN|wx.EXPAND, 2)
        pack(mainpanel, mainsizer)

        return mainpanel
class SectoinParamsDefsPanel(SectionParamsDefsPanelBase):
    def __init__(self, parent):
        SectionParamsDefsPanelBase.__init__(self, parent)
        # ÓÃÓÚ´æ·Å solveÖ®ºóµÄÖµ
        self._args = dict()

        self.plotpanel = PlotPanel(self.m_panel_canvas,
                                   size=(300, 300),
                                   fontsize=5)
        self.plotpanel.BuildPanel()

        # ĬÈϽØÃæÐÎ×´
        self._section_type = u'Ö±½Ç¸Ö'

        # ½ØÃæ²ÎÊýµÚÒ»ÁÐÖ»¶Á
        for irow in range(self.m_grid_params_defs.GetNumberRows()):
            self.m_grid_params_defs.SetReadOnly(irow, 0, True)

        self.grid_value = {
            u'Ö±½Ç¸Ö':
            ['±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2', 'ÄÚÔ²»¡°ë¾¶'],
            u'¹¤×Ö¸Ö': [
                '¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶',
                '½Ç¶ËÔ²»¡°ë¾¶'
            ],
            u'²Û¸Ö': [
                '¸ß¶È', 'ÍÈ¿í¶È', 'Ñüºñ¶È', 'ƽ¾ùÍȺñ¶È', 'ÄÚÔ²»¡°ë¾¶',
                '½Ç¶ËÔ²»¡°ë¾¶'
            ],
            #u'CÐ͸Ö':  ['¸ß¶È', '±ß¿í¶È1', '±ßºñ¶È1', 'Ñüºñ¶È', '±ßºñ¶È2', '±ß¿í¶È2'],
            u'TÐ͸Ö': ['¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ßºñ¶È1', '±ßºñ¶È2'],
            u'ñÐ͸Ö': [
                '¸ß¶È', '½Å±ß¿í¶È', 'Í·±ß¿í¶È', 'ÍÈÇã½Ç', '½Å±ßºñ¶È', 'ÍȺñ¶È',
                'Í·ºñ¶È'
            ],
            u'JÐ͸Ö': [
                '¸ß¶È', '±ß¿í¶È1', '±ß¿í¶È2', '±ß¿í¶È3', '±ßºñ¶È1', '±ßºñ¶È2',
                '±ßºñ¶È3'
            ]
        }

        for num in range(len(self.grid_value[self._section_type])):
            self.m_grid_params_defs.SetCellValue(
                num, 0, self.grid_value[self._section_type][num])

    def OnSelectSectionType(self, event):
        self._section_type = self.m_choice_section_type.GetStringSelection()
        section_parameter_name = self.grid_value[self._section_type]
        self.m_grid_params_defs.ClearGrid()
        for name_num in range(len(section_parameter_name)):
            self.m_grid_params_defs.SetCellValue(
                name_num, 0, section_parameter_name[name_num])

    def m_btn_calculationOnButtonClick(self, event):
        # µã»÷btnÖ®ºó£¬»ñµÃ´«ÈëµÄ²ÎÊý¡£
        # ͨ¹ý»ñµÃµÄ²ÎÊýÉú³É³ö½ØÃæ¶ÔÏó¡£
        # ͨ¹ý½ØÃæ¼ÆË㣬µÃµ½¼¸ºÎÊýÖµ
        # ͨ¹ýDraw¶ÔÏó»­Í¼£¬»­³ö¼¸ºÎͼÏñ¡£
        _args = list()
        for num in range(len(self.grid_value[self._section_type])):
            _args.append(float(self.m_grid_params_defs.GetCellValue(num, 1)))

        sectionType = self._section_type

        if sectionType == u"¹¤×Ö¸Ö":
            section = ISection(*_args)
        elif sectionType == u"Ö±½Ç¸Ö":
            section = rightAngleSection(*_args)
        elif sectionType == u"²Û¸Ö":
            section = grooveSection(*_args)
        #elif sectionType == u"CÐ͸Ö":
        #pass
        elif sectionType == u"TÐ͸Ö":
            section = TshapeSection(*_args)
        elif sectionType == u"JÐ͸Ö":
            section = JshapeSection(*_args)
        elif sectionType == u"ñÐ͸Ö":
            section = NshapeSection(*_args)

        geo = GeoCalculator(section)
        geo.Solve()
        self._args = geo._args
        if "Area" in self._args:
            if self._args['Area'] < 0.0000001:
                res = 0
            else:
                res = self._args['Area']
            self.m_propertyGridItem2.SetValue(str(res))
        if "Sx" in self._args:
            if self._args['Sx'] < 0.0000001:
                res = 0
            else:
                res = self._args['Sx']
            self.m_propertyGridItem3.SetValue(str(res))
        if "Sy" in self._args:
            if self._args['Sy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Sy']
            self.m_propertyGridItem42.SetValue(str(res))
        if "Ix" in self._args:
            if self._args['Ix'] < 0.0000001:
                res = 0
            else:
                res = self._args['Ix']
            self.m_propertyGridItem4.SetValue(str(res))
        if "Iy" in self._args:
            if self._args['Iy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Iy']
            self.m_propertyGridItem5.SetValue(str(res))
        if "Ixy" in self._args:
            if self._args['Ixy'] < 0.0000001:
                res = 0
            else:
                res = self._args['Ixy']
            self.m_propertyGridItem7.SetValue(str(res))
        if "centroid" in self._args:
            res = self._args['centroid']

            if res[0] < 0.0000001:
                res = [0, res[1]]
            if res[1] < 0.0000001:
                res = [res[0], 0]

            self.m_propertyGridItem8.SetValue(str(res))
        if "tan_alfa" in self._args:
            if self._args['tan_alfa'] < 0.0000001:
                res = 0
            else:
                res = self._args['tan_alfa']

            self.m_propertyGridItem9.SetValue(str(res))
        if "ix" in self._args:
            if self._args['ix'] < 0.0000001:
                res = 0
            else:
                res = self._args['ix']
            self.m_propertyGridItem61.SetValue(str(res))
        if "iy" in self._args:
            if self._args['iy'] < 0.0000001:
                res = 0
            else:
                res = self._args['iy']
            self.m_propertyGridItem62.SetValue(str(res))

        Path = DrawGeometry(section)
        Path.Draw()

        self.plotpanel.clear()
        for i in Path._paths:
            m, n = zip(*i)
            self.plotpanel.oplot(m, n, fullbox=False, axes_style='open')
        for i in Path._dimen:
            m, n = zip(*i)
            self.plotpanel.oplot(m,
                                 n,
                                 fullbox=False,
                                 axes_style='open',
                                 linewidth=1,
                                 color='green')
        # ±éÀú×ֵ䣬»­Éϱê×¢
        for key, value in Path._text.items():
            x = key[0]
            y = key[1]
            self.plotpanel.add_text(str(value), x, y, size=4)

    def m_btn_calculationOnSetFocus(self, event):
        print "on btn_Set Focus!"
Example #34
0
    def __init__(self, parent, filename=None, groupname=None,
                 last_array_sel=None, read_ok_cb=None,
                 edit_groupname=True, _larch=None):
        self.parent = parent
        self._larch = _larch
        self.path = filename
        self.extra_sums = {}

        group = self.initgroup = self.read_column_file(self.path)

        self.subframes = {}
        self.workgroup  = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype',
                     'array_labels', 'data'):
            setattr(self.workgroup, attr, getattr(group, attr, None))

        arr_labels = [l.lower() for l in self.initgroup.array_labels]

        if self.workgroup.datatype is None:
            self.workgroup.datatype = 'raw'
            for arrlab in arr_labels[:4]:
                if 'energ' in arrlab:
                    self.workgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb
        self.array_sel = {'xpop': '',  'xarr': None,
                          'ypop': '',  'yop': '/',
                          'yarr1': None, 'yarr2': None, 'use_deriv': False}

        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in arr_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in arr_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in arr_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % group.filename
        wx.Frame.__init__(self, None, -1,
                          'Build Arrays from Data Columns for %s' % group.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel, message, font=Font(13),
                           colour=self.colors.title, style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))
        yarr_labels = self.yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = self.xarr_labels = arr_labels + ['_index']

        self.xarr   = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1  = Choice(panel, choices= arr_labels, **opts)
        self.yarr2  = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.workgroup.datatype)


        opts['size'] = (50, -1)
        self.yop =  Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (150, -1)

        self.use_deriv = Check(panel, label='use derivative',
                               default=self.array_sel['use_deriv'], **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')
        self.message = SimpleText(panel, '', font=Font(11),
                           colour=self.colors.title, style=LCEN)

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels)-1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)

        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        _ok    = Button(bpanel, 'OK', action=self.onOK)
        _cancel = Button(bpanel, 'Cancel', action=self.onCancel)
        _edit   = Button(bpanel, 'Edit Array Names', action=self.onEditNames)
        _add    = Button(bpanel, 'Select Columns to Sum', action=self.onAddColumns)

        bsizer.Add(_ok)
        bsizer.Add(_cancel)
        bsizer.Add(_edit)
        bsizer.Add(_add)
        _ok.SetDefault()
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title,     (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab,       (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop,   (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf,  (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'),  (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype,                    (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel, value=group.groupname,
                                         size=(200, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname,               (ir, 1), (1, 2), LCEN, 0)
        sizer.Add(self.message,                     (ir, 3), (1, 4), LCEN, 0)


        ir += 1
        sizer.Add(bpanel,     (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel, style=wx.TE_MULTILINE|wx.TE_READONLY,
                               size=(400, 250))

        ftext.SetValue(group.text)
        ftext.SetFont(Font(10))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN|wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW|wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN|wx.GROW,   2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [group.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.Show()
        self.Raise()
        self.onUpdate(self)
Example #35
0
    def __init__(self, parent, ID, **kws):
        kws["style"] = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER | wx.TAB_TRAVERSAL

        wx.Frame.__init__(self, parent, ID, '', wx.DefaultPosition,
                          wx.Size(-1, -1), **kws)
        self.SetTitle("wxmplot StripChart Demo")

        self.tmin = 15.0

        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False))
        menu = wx.Menu()
        ID_EXIT = wx.NewId()
        ID_TIMER = wx.NewId()

        menu_exit = menu.Append(ID_EXIT, "E&xit", "Terminate the program")

        menuBar = wx.MenuBar()
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.OnExit, menu_exit)
        self.Bind(wx.EVT_CLOSE, self.OnExit)

        sbar = self.CreateStatusBar(2, wx.CAPTION)
        sfont = sbar.GetFont()
        sfont.SetWeight(wx.BOLD)
        sfont.SetPointSize(11)
        sbar.SetFont(sfont)
        self.SetStatusWidths([-3, -1])
        self.SetStatusText('', 0)

        mainsizer = wx.BoxSizer(wx.VERTICAL)

        btnpanel = wx.Panel(self, -1)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        b_on = wx.Button(btnpanel, -1, 'Start', size=(-1, -1))
        b_off = wx.Button(btnpanel, -1, 'Stop', size=(-1, -1))

        b_on.Bind(wx.EVT_BUTTON, self.onStartTimer)
        b_off.Bind(wx.EVT_BUTTON, self.onStopTimer)

        tlabel = wx.StaticText(btnpanel, -1, '  Time range:')
        self.time_range = FloatCtrl(btnpanel,
                                    size=(100, -1),
                                    value=abs(self.tmin),
                                    precision=1)

        btnsizer.Add(b_on, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(b_off, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(
            tlabel, 1,
            wx.GROW | wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        btnsizer.Add(self.time_range, 0,
                     wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)

        btnpanel.SetSizer(btnsizer)
        btnsizer.Fit(btnpanel)

        self.plotpanel = PlotPanel(self, messenger=self.write_message)
        self.plotpanel.BuildPanel()
        self.plotpanel.set_xlabel('Time from Present (s)')
        mainsizer.Add(btnpanel, 0,
                      wx.GROW | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        mainsizer.Add(
            self.plotpanel, 1,
            wx.GROW | wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER | wx.LEFT, 0)
        self.SetSizer(mainsizer)
        mainsizer.Fit(self)

        self.Bind(wx.EVT_TIMER, self.onTimer)
        self.timer = wx.Timer(self)
        self.count = 0
        self.Refresh()
        wx.CallAfter(self.onStartTimer)
Example #36
0
class EditColumnFrame(wx.Frame) :
    """Set Column Labels for a file"""
    def __init__(self, parent, group=None, last_array_sel=None,
                 read_ok_cb=None, edit_groupname=True, with_smooth=False,
                 _larch=None):
        self.parent = parent
        self.larch = _larch
        self.rawgroup = group
        self.with_smooth = with_smooth
        self.outgroup  = Group(raw=group)
        for attr in ('path', 'filename', 'groupname', 'datatype'):
            setattr(self.outgroup, attr, getattr(group, attr, None))

        if self.outgroup.datatype is None:
            self.outgroup.datatype = 'raw'
            if ('energ' in self.rawgroup.array_labels[0].lower() or
                'energ' in self.rawgroup.array_labels[1].lower()):
                self.outgroup.datatype = 'xas'

        self.read_ok_cb = read_ok_cb

        self.array_sel = {'xpop': '', 'xarr': None,
                          'ypop': '', 'yop': '/',
                          'yarr1': None, 'yarr2': None,
                          'use_deriv': False}
        if last_array_sel is not None:
            self.array_sel.update(last_array_sel)

        if self.array_sel['yarr2'] is None and 'i0' in self.rawgroup.array_labels:
            self.array_sel['yarr2'] = 'i0'

        if self.array_sel['yarr1'] is None:
            if 'itrans' in self.rawgroup.array_labels:
                self.array_sel['yarr1'] = 'itrans'
            elif 'i1' in self.rawgroup.array_labels:
                self.array_sel['yarr1'] = 'i1'
        message = "Data Columns for %s" % self.rawgroup.filename
        wx.Frame.__init__(self, None, -1,
                          'Build Arrays from Data Columns for %s' % self.rawgroup.filename,
                          style=FRAMESTYLE)

        self.SetFont(Font(10))

        panel = wx.Panel(self)
        self.SetMinSize((600, 600))
        self.colors = GUIColors()

        # title row
        title = SimpleText(panel, message, font=Font(13),
                           colour=self.colors.title, style=LCEN)

        opts = dict(action=self.onUpdate, size=(120, -1))

        arr_labels = self.rawgroup.array_labels
        yarr_labels = arr_labels + ['1.0', '0.0', '']
        xarr_labels = arr_labels + ['<index>']

        self.xarr   = Choice(panel, choices=xarr_labels, **opts)
        self.yarr1  = Choice(panel, choices= arr_labels, **opts)
        self.yarr2  = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr = Choice(panel, choices=yarr_labels, **opts)
        self.yerr_arr.Disable()

        self.datatype = Choice(panel, choices=DATATYPES, **opts)
        self.datatype.SetStringSelection(self.outgroup.datatype)


        opts['size'] = (50, -1)
        self.yop =  Choice(panel, choices=ARR_OPS, **opts)

        opts['size'] = (120, -1)

        self.use_deriv = Check(panel, label='use derivative',
                               default=self.array_sel['use_deriv'], **opts)

        self.xpop = Choice(panel, choices=XPRE_OPS, **opts)
        self.ypop = Choice(panel, choices=YPRE_OPS, **opts)

        opts['action'] = self.onYerrChoice
        self.yerr_op = Choice(panel, choices=YERR_OPS, **opts)
        self.yerr_op.SetSelection(0)

        self.yerr_const = FloatCtrl(panel, value=1, precision=4, size=(90, -1))

        if with_smooth:
            opts['action'] = self.onSmoothChoice
            self.smooth_op = Choice(panel, choices=SMOOTH_OPS, **opts)
            self.smooth_op.SetSelection(0)

            opts['size'] = (100, -1)

            opts['action'] = self.onUpdate
            smooth_panel = wx.Panel(panel)
            smooth_sizer = wx.BoxSizer(wx.HORIZONTAL)
            self.smooth_conv = Choice(smooth_panel, choices=CONV_OPS, **opts)
            opts['size'] =  (30, -1)
            self.smooth_c0 = FloatCtrl(smooth_panel, value=3, precision=0, **opts)
            self.smooth_c1 = FloatCtrl(smooth_panel, value=1, precision=0, **opts)
            opts['size'] =  (75, -1)
            self.smooth_sig = FloatCtrl(smooth_panel, value=1, precision=4, **opts)
            self.smooth_c0.Disable()
            self.smooth_c1.Disable()
            self.smooth_sig.Disable()
            self.smooth_conv.SetSelection(0)
            self.smooth_conv.Disable()


        ylab = SimpleText(panel, 'Y = ')
        xlab = SimpleText(panel, 'X = ')
        yerr_lab = SimpleText(panel, 'Yerror = ')
        self.xsuf = SimpleText(panel, '')
        self.ysuf = SimpleText(panel, '')

        self.xpop.SetStringSelection(self.array_sel['xpop'])
        self.ypop.SetStringSelection(self.array_sel['ypop'])
        self.yop.SetStringSelection(self.array_sel['yop'])
        if '(' in self.array_sel['ypop']:
            self.ysuf.SetLabel(')')

        ixsel, iysel, iy2sel = 0, 1, len(yarr_labels)-1
        if self.array_sel['xarr'] in xarr_labels:
            ixsel = xarr_labels.index(self.array_sel['xarr'])
        if self.array_sel['yarr1'] in arr_labels:
            iysel = arr_labels.index(self.array_sel['yarr1'])
        if self.array_sel['yarr2'] in yarr_labels:
            iy2sel = yarr_labels.index(self.array_sel['yarr2'])
        self.xarr.SetSelection(ixsel)
        self.yarr1.SetSelection(iysel)
        self.yarr2.SetSelection(iy2sel)


        bpanel = wx.Panel(panel)
        bsizer = wx.BoxSizer(wx.HORIZONTAL)
        bsizer.Add(Button(bpanel, 'OK', action=self.onOK), 4)
        bsizer.Add(Button(bpanel, 'Cancel', action=self.onCancel), 4)
        pack(bpanel, bsizer)

        sizer = wx.GridBagSizer(4, 8)
        sizer.Add(title,     (0, 0), (1, 7), LCEN, 5)

        ir = 1
        sizer.Add(xlab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.xpop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xsuf, (ir, 3), (1, 1), CEN, 0)

        ir += 1
        sizer.Add(ylab,       (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.ypop,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yarr1, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yop,   (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yarr2, (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.ysuf,  (ir, 5), (1, 1), CEN, 0)
        sizer.Add(self.use_deriv, (ir, 6), (1, 1), LCEN, 0)

        ir += 1
        sizer.Add(yerr_lab,      (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.yerr_op,  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(self.yerr_arr, (ir, 2), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, 'Value:'), (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yerr_const, (ir, 4), (1, 2), CEN, 0)

        if with_smooth:
            ir += 1
            sizer.Add(SimpleText(panel, 'Smoothing:'), (ir, 0), (1, 1), LCEN, 0)
            sizer.Add(self.smooth_op,  (ir, 1), (1, 1), CEN, 0)

            smooth_sizer.Add(SimpleText(smooth_panel, ' n='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_c0,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' order='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_c1,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' form='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_conv,  0, LCEN, 1)
            smooth_sizer.Add(SimpleText(smooth_panel, ' sigma='), 0, LCEN, 1)
            smooth_sizer.Add(self.smooth_sig,  0, LCEN, 1)
            pack(smooth_panel, smooth_sizer)

            sizer.Add(smooth_panel,  (ir, 2), (1, 5), LCEN, 1)

        ir += 1
        sizer.Add(SimpleText(panel, 'Data Type:'),  (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.datatype,                    (ir, 1), (1, 2), LCEN, 0)

        ir += 1
        self.wid_groupname = wx.TextCtrl(panel, value=self.rawgroup.groupname,
                                         size=(120, -1))
        if not edit_groupname:
            self.wid_groupname.Disable()

        sizer.Add(SimpleText(panel, 'Group Name:'), (ir, 0), (1, 1), LCEN, 0)
        sizer.Add(self.wid_groupname,               (ir, 1), (1, 1), LCEN, 0)


        ir += 1
        sizer.Add(bpanel,     (ir, 0), (1, 5), LCEN, 3)

        pack(panel, sizer)

        self.nb = fnb.FlatNotebook(self, -1, agwStyle=FNB_STYLE)
        self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))

        self.plotpanel = PlotPanel(self, messenger=self.plot_messages)
        textpanel = wx.Panel(self)
        ftext = wx.TextCtrl(textpanel, style=wx.TE_MULTILINE|wx.TE_READONLY,
                               size=(400, 250))
        try:
            m = open(self.rawgroup.filename, 'r')
            text = m.read()
            m.close()
        except:
            text = "The file '%s'\n could not be read" % self.rawgroup.filename
        ftext.SetValue(text)
        ftext.SetFont(Font(11))

        textsizer = wx.BoxSizer(wx.VERTICAL)
        textsizer.Add(ftext, 1, LCEN|wx.GROW, 1)
        pack(textpanel, textsizer)

        self.nb.AddPage(textpanel, ' Text of Data File ', True)
        self.nb.AddPage(self.plotpanel, ' Plot of Selected Arrays ', True)

        mainsizer = wx.BoxSizer(wx.VERTICAL)
        mainsizer.Add(panel, 0, wx.GROW|wx.ALL, 2)
        mainsizer.Add(self.nb, 1, LCEN|wx.GROW,   2)
        pack(self, mainsizer)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-1, -1])
        statusbar_fields = [self.rawgroup.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)


        self.Show()
        self.Raise()
        self.onUpdate(self)

    def onOK(self, event=None):
        """ build arrays according to selection """
        if self.wid_groupname is not None:
            self.outgroup.groupname = fix_varname(self.wid_groupname.GetValue())

        yerr_op = self.yerr_op.GetStringSelection().lower()
        if yerr_op.startswith('const'):
            self.outgroup.yerr = self.yerr_const.GetValue()
        elif yerr_op.startswith('array'):
            yerr = self.yerr_arr.GetStringSelection().strip()
            self.outgroup.yerr = get_data(rawgroup, yerr)
        elif yerr_op.startswith('sqrt'):
            self.outgroup.yerr = np.sqrt(outgroup.ydat)

        if self.read_ok_cb is not None:
            self.read_ok_cb(self.outgroup, array_sel=self.array_sel)
        self.Destroy()

    def onCancel(self, event=None):
        self.outgroup.import_ok = False
        self.Destroy()

    def onYerrChoice(self, evt=None):
        yerr_choice = evt.GetString()
        self.yerr_arr.Disable()
        self.yerr_const.Disable()
        if 'const' in yerr_choice.lower():
            self.yerr_const.Enable()
        elif 'array' in yerr_choice.lower():
            self.yerr_arr.Enable()
        self.onUpdate()

    def onSmoothChoice(self, evt=None):
        choice = self.smooth_op.GetStringSelection().lower()
        conv  = self.smooth_conv.GetStringSelection()
        self.smooth_c0.Disable()
        self.smooth_c1.Disable()
        self.smooth_conv.Disable()
        self.smooth_sig.Disable()

        if choice.startswith('box'):
            self.smooth_c0.Enable()
        elif choice.startswith('savi'):
            self.smooth_c0.Enable()
            self.smooth_c1.Enable()
        elif choice.startswith('conv'):
            self.smooth_conv.Enable()
            self.smooth_sig.Enable()
        self.onUpdate()

    def onUpdate(self, value=None, evt=None):
        """column selections changed calc xdat and ydat"""
        # dtcorr = self.dtcorr.IsChecked()
        dtcorr = False
        use_deriv = self.use_deriv.IsChecked()
        rawgroup = self.rawgroup
        outgroup = self.outgroup

        ix  = self.xarr.GetSelection()
        xname = self.xarr.GetStringSelection()
        if xname == '<index>':
            xname = self.rawgroup.array_labels[0]
            outgroup._index = 1.0*np.arange(len(getattr(rawgroup, xname)))
            xname = '_index'

        outgroup.datatype = self.datatype.GetStringSelection().strip().lower()
        outgroup.xdat = getattr(rawgroup, xname)

        def pre_op(opwid, arr):
            opstr = opwid.GetStringSelection().strip()
            suf = ''
            if opstr in ('-log(', 'log('):
                suf = ')'
                if opstr == 'log(':
                    arr = np.log(arr)
                elif opstr == '-log(':
                    arr = -np.log(arr)
            return suf, opstr, arr

        try:
            xsuf, xpop, outgroup.xdat = pre_op(self.xpop, outgroup.xdat)
            self.xsuf.SetLabel(xsuf)
        except:
            return
        try:
            xunits = rawgroup.array_units[ix].strip()
            xlabel = '%s (%s)' % (xname, xunits)
        except:
            xlabel = xname


        def get_data(grp, arrayname, correct=False):
            if hasattr(grp, 'get_data'):
                return grp.get_data(arrayname, correct=correct)
            return getattr(grp, arrayname, None)

        yname1  = self.yarr1.GetStringSelection().strip()
        yname2  = self.yarr2.GetStringSelection().strip()
        yop = self.yop.GetStringSelection().strip()

        ylabel = yname1
        if len(yname2) == 0:
            yname2 = '1.0'
        else:
            ylabel = "%s%s%s" % (ylabel, yop, yname2)

        yarr1 = get_data(rawgroup, yname1, correct=dtcorr)

        if yname2 in ('0.0', '1.0'):
            yarr2 = float(yname2)
            if yop == '/': yarr2 = 1.0
        else:
            yarr2 = get_data(rawgroup, yname2, correct=dtcorr)

        outgroup.ydat = yarr1
        if yop == '+':
            outgroup.ydat = yarr1.__add__(yarr2)
        elif yop == '-':
            outgroup.ydat = yarr1.__sub__(yarr2)
        elif yop == '*':
            outgroup.ydat = yarr1.__mul__(yarr2)
        elif yop == '/':
            outgroup.ydat = yarr1.__truediv__(yarr2)

        yerr_op = self.yerr_op.GetStringSelection().lower()
        if yerr_op.startswith('const'):
            yerr = self.yerr_const.GetValue()
        elif yerr_op.startswith('array'):
            yerr = self.yerr_arr.GetStringSelection().strip()
            yerr = get_data(rawgroup, yerr)
        elif yerr_op.startswith('sqrt'):
            yerr = np.sqrt(outgroup.ydat)


        ysuf, ypop, outgroup.ydat = pre_op(self.ypop, outgroup.ydat)
        self.ysuf.SetLabel(ysuf)

        if use_deriv:
            try:
                outgroup.ydat = (np.gradient(outgroup.ydat) /
                                 np.gradient(outgroup.xdat))
            except:
                pass

        # apply smoothhing here
        if self.with_smooth:
            smoother = self.smooth_op.GetStringSelection().lower()
            if smoother.startswith('box'):
                n = int(self.smooth_c0.GetValue())
                outgroup.ydat = boxcar(outgroup.ydat, n)
            elif smoother.startswith('savit'):
                n = int(self.smooth_c0.GetValue())
                win_size = 2*n + 1
                order = int(self.smooth_c1.GetValue())
                outgroup.ydat = savitzky_golay(outgroup.ydat, win_size, order)
            elif smoother.startswith('conv'):
                sigma = float(self.smooth_sig.GetValue())
                form  = str(self.smooth_conv.GetStringSelection()).lower()
                outgroup.ydat = smooth(outgroup.xdat, outgroup.ydat,
                                       sigma=sigma, form=form)

        self.array_sel = {'xpop': xpop, 'xarr': xname,
                     'ypop': ypop, 'yop': yop,
                     'yarr1': yname1, 'yarr2': yname2,
                     'use_deriv': use_deriv}

        try:
            npts = min(len(outgroup.xdat), len(outgroup.ydat))
        except AttributeError:
            return

        outgroup.filename    = rawgroup.filename
        outgroup.npts        = npts
        outgroup.plot_xlabel = xlabel
        outgroup.plot_ylabel = ylabel
        outgroup.xdat        = np.array(outgroup.xdat[:npts])
        outgroup.ydat        = np.array(outgroup.ydat[:npts])
        outgroup.y           = outgroup.ydat
        outgroup.yerr        = yerr
        if isinstance(yerr, np.ndarray):
            outgroup.yerr    = np.array(yerr[:npts])

        if outgroup.datatype == 'xas':
            outgroup.energy = outgroup.xdat
            outgroup.mu     = outgroup.ydat

        popts = {}
        path, fname = os.path.split(outgroup.filename)
        popts['label'] = "%s: %s" % (fname, outgroup.plot_ylabel)
        popts['title']  = fname
        popts['ylabel'] = outgroup.plot_ylabel
        popts['xlabel'] = outgroup.plot_xlabel

        self.plotpanel.plot(outgroup.xdat, outgroup.ydat, **popts)

        for i in range(self.nb.GetPageCount()):
            if 'plot' in self.nb.GetPageText(i).lower():
                self.nb.SetSelection(i)

    def plot_messages(self, msg, panel=1):
        self.SetStatusText(msg, panel)
Example #37
0
class PlotterFrame(wx.Frame):
    _about = """StepScan 2D Plotter
  Matt Newville <newville @ cars.uchicago.edu>
  """
    def __init__(self, dbname=None, server='sqlite', host=None,
                 port=None, user=None, password=None, create=True, **kws):


        wx.Frame.__init__(self, None, -1, style=FRAMESTYLE)
        self.data = None
        self.filemap = {}
        title = "Step Scan Data File Viewer"
        self.scandb = None
        if dbname is not None:
            self.scandb = ScanDB(dbname=dbname, server=server, host=host,
                                 user=user, password=password, port=port,
                                 create=create)
            self.filemap[CURSCAN] = SCANGROUP
            title = '%s, with Live Scan Viewing' % title
        self.larch = None
        self.plotters = []

        self.SetTitle(title)
        self.SetSize((850, 650))
        self.SetFont(Font(9))

        self.createMainPanel()
        self.createMenus()
        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = ["Initializing....", " "]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)


        if dbname is not None:
            self.live_scanfile = None
            self.live_cpt = -1
            self.filelist.Append(CURSCAN)
            self.scantimer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.onScanTimer, self.scantimer)
            self.scantimer.Start(250)

    def onScanTimer(self, evt=None, **kws):
        if self.larch is None:
            return
        group =  getattr(self.larch.symtable, SCANGROUP)

        curfile = fix_filename(self.scandb.get_info('filename'))
        if curfile != self.live_scanfile:
            self.live_scanfile = curfile
            group.filename = self.live_scanfile
            group.array_units = []
            self.live_cpt = -1

        sdata = self.scandb.get_scandata()
        if len(sdata) <= 1:
            return
        npts = len(sdata[-1].data)

        if npts <= self.live_cpt:
            return

        self.live_cpt = npts
        if len(group.array_units) < 1:
            group.array_units = [str(row.notes) for row in sdata]

        for row in sdata:
            setattr(group, fix_filename(row.name), np.array(row.data))

        if npts > 1:
            self.onPlot()

    def createMainPanel(self):
        splitter  = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(175)

        self.filelist  = wx.ListBox(splitter)
        self.filelist.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.filelist.Bind(wx.EVT_LISTBOX, self.ShowFile)

        self.detailspanel = self.createDetailsPanel(splitter)

        splitter.SplitVertically(self.filelist, self.detailspanel, 1)
        wx.CallAfter(self.init_larch)

    def createDetailsPanel(self, parent):
        mainpanel = wx.Panel(parent)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)
        sizer = wx.GridBagSizer(8, 7)

        self.title = SimpleText(panel, 'initializing...')
        ir = 0
        sizer.Add(self.title, (ir, 0), (1, 6), LCEN, 2)
        # x-axis

        self.xarr = add_choice(panel, choices=[],
                               action=self.onYchoice,  size=(120, -1))
        self.xop  = add_choice(panel, choices=('', 'log'),
                               action=self.onYchoice, size=(75, -1))

        ir += 1
        sizer.Add(SimpleText(panel, 'X = '), (ir, 0), (1, 1), CEN, 0)
        sizer.Add(self.xop,                  (ir, 1), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, '('),    (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xarr,                 (ir, 3), (1, 1), RCEN, 0)
        sizer.Add(SimpleText(panel, ')'),    (ir, 4), (1, 1), CEN, 0)

        self.yops = [[],[]]
        self.yarr = [[],[]]

        for opts, sel, siz in ((PRE_OPS, 0, 75), (ARR_OPS, 3, 50),
                             (ARR_OPS, 3, 50)):
            w1 = add_choice(panel, choices=opts, action=self.onYchoice,
                            size=(siz, -1))
            w1.SetSelection(sel)
            self.yops[0].append(w1)

            w2 = add_choice(panel, choices=opts, action=self.onYchoice,
                            size=(siz, -1))
            w2.SetSelection(sel)
            self.yops[1].append(w2)

        opts= {'choices':[], 'size':(120, -1), 'action':self.onYchoice}
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **opts))
            self.yarr[1].append(add_choice(panel, **opts))

        for i in range(2):
            ir += 1
            label = 'Y%i = ' % (i+1)
            sizer.Add(SimpleText(panel, label),  (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0],           (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('),   (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0],           (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1],           (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1],           (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'),    (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2],           (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2],           (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'),    (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        # sizer.Add(SimpleText(panel, ' New Plot: '),  (ir,   0), (1, 3), LCEN, 0)
        # sizer.Add(SimpleText(panel, ' Over Plot: '), (ir+1, 0), (1, 3), LCEN, 0)

        for jr, ic, dc, opt, ttl in ((0, 0, 4, 'win old',    'New Plot, This Window'),
                                     (0, 4, 2, 'win new',    'New Plot, New Window'),
                                     (1, 0, 4, 'over left',  'Over Plot, Left Axis'),
                                     (1, 4, 2, 'over right', 'Over Plot, Right Axis')):
            sizer.Add(add_button(panel, ttl, size=(165, -1),
                                 action=Closure(self.onPlot, opt=opt)),
                      (ir+jr, ic), (1, dc), LCEN, 2)

        ir += 2
        self.dtcorr   = check(panel, default=True, label='correct deadtime?')
        sizer.Add(self.dtcorr,  (ir,   0), (1, 3), LCEN, 0)
        ir += 1
        sizer.Add(SimpleText(panel, ''), (ir,   0), (1, 3), LCEN, 0)

        pack(panel, sizer)


#         self.nb = flat_nb.FlatNotebook(mainpanel, -1, agwStyle=FNB_STYLE)
#
#         self.nb.SetTabAreaColour(wx.Colour(248,248,240))
#         self.nb.SetActiveTabColour(wx.Colour(254,254,195))
#
#         self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
#         self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))
#
#         self.xas_panel = self.CreateXASPanel(self.nb) # mainpanel)
#         self.fit_panel = self.CreateFitPanel(self.nb) # mainpanel)
#
#         self.nb.AddPage(self.fit_panel, ' General Analysis ', True)
#         self.nb.AddPage(self.xas_panel, ' XAS Processing ',   True)

        mainsizer.Add(panel,   0, LCEN|wx.EXPAND, 2)
        self.plotpanel = PlotPanel(mainpanel, size=(500, 670))
        self.plotpanel.messenger = self.write_message

        bgcol = panel.GetBackgroundColour()
        bgcol = (bgcol[0]/255., bgcol[1]/255., bgcol[2]/255.)
        self.plotpanel.canvas.figure.set_facecolor(bgcol)

        mainsizer.Add(self.plotpanel, 1, wx.GROW|wx.ALL, 1)

        # mainsizer.Add(self.nb, 1, LCEN|wx.EXPAND, 2)
        pack(mainpanel, mainsizer)

        return mainpanel

    def CreateFitPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.fit_model   = add_choice(panel, size=(100, -1),
                                      choices=('Gaussian', 'Lorentzian',
                                               'Voigt', 'Linear', 'Quadratic',
                                               'Step', 'Rectangle',
                                               'Exponential'))
        self.fit_bkg = add_choice(panel, size=(100, -1),
                                  choices=('None', 'constant', 'linear', 'quadtratic'))
        self.fit_step = add_choice(panel, size=(100, -1),
                                  choices=('linear', 'error function', 'arctan'))

        self.fit_report = wx.StaticText(panel, -1, "", (180, 200))
        sizer = wx.GridBagSizer(10, 4)
        sizer.Add(SimpleText(p, 'Fit Model: '),           (0, 0), (1, 1), LCEN)
        sizer.Add(self.fit_model,                         (0, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Background: '),          (1, 0), (1, 1), LCEN)
        sizer.Add(self.fit_bkg,                           (1, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Step Function Form: '),  (2, 0), (1, 1), LCEN)
        sizer.Add(self.fit_step,                          (2, 1), (1, 1), LCEN)
        sizer.Add(add_button(panel, 'Show Fit', size=(100, -1),
                             action=self.onFitPeak),       (3, 0), (1, 1), LCEN)
        sizer.Add(self.fit_report,                         (0, 2), (4, 2), LCEN, 3)
        pack(panel, sizer)
        return panel

    def CreateXASPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.xas_autoe0   = check(panel, default=True, label='auto?')
        self.xas_autostep = check(panel, default=True, label='auto?')
        self.xas_op       = add_choice(panel, size=(95, -1),
                                       choices=('Raw Data', 'Pre-edged',
                                                'Normalized', 'Flattened'))
        self.xas_e0   = FloatCtrl(panel, value  = 0, precision=3, size=(95, -1))
        self.xas_step = FloatCtrl(panel, value  = 0, precision=3, size=(95, -1))
        self.xas_pre1 = FloatCtrl(panel, value=-200, precision=1, size=(95, -1))
        self.xas_pre2 = FloatCtrl(panel, value= -30, precision=1, size=(95, -1))
        self.xas_nor1 = FloatCtrl(panel, value=  30, precision=1, size=(95, -1))
        self.xas_nor2 = FloatCtrl(panel, value= 300, precision=1, size=(95, -1))
        self.xas_vict = add_choice(panel, size=(50, -1), choices=('0', '1', '2', '3'))
        self.xas_nnor = add_choice(panel, size=(50, -1), choices=('0', '1', '2', '3'))
        self.xas_vict.SetSelection(1)
        self.xas_nnor.SetSelection(2)
        sizer = wx.GridBagSizer(10, 4)

        sizer.Add(SimpleText(p, 'Plot XAS as: '),         (0, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'E0 : '),                 (1, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Edge Step: '),           (2, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Pre-edge range: '),      (3, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Normalization range: '), (4, 0), (1, 1), LCEN)

        sizer.Add(self.xas_op,                 (0, 1), (1, 1), LCEN)
        sizer.Add(self.xas_e0,                 (1, 1), (1, 1), LCEN)
        sizer.Add(self.xas_step,               (2, 1), (1, 1), LCEN)
        sizer.Add(self.xas_pre1,               (3, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'),          (3, 2), (1, 1), LCEN)
        sizer.Add(self.xas_pre2,               (3, 3), (1, 1), LCEN)
        sizer.Add(self.xas_nor1,               (4, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'),          (4, 2), (1, 1), LCEN)
        sizer.Add(self.xas_nor2,               (4, 3), (1, 1), LCEN)

        sizer.Add(self.xas_autoe0,             (1, 2), (1, 2), LCEN)
        sizer.Add(self.xas_autostep,           (2, 2), (1, 2), LCEN)

        sizer.Add(SimpleText(p, 'Victoreen:'), (3, 4), (1, 1), LCEN)
        sizer.Add(self.xas_vict,               (3, 5), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'PolyOrder:'), (4, 4), (1, 1), LCEN)
        sizer.Add(self.xas_nnor,               (4, 5), (1, 1), LCEN)

        pack(panel, sizer)
        return panel

    def onFitPeak(self, evt=None):
        gname = self.groupname
        if self.dtcorr.IsChecked():
            print('fit needs to dt correct!')

        dtext = []
        model = self.fit_model.GetStringSelection().lower()
        dtext.append('Fit Model: %s' % model)
        bkg =  self.fit_bkg.GetStringSelection()
        if bkg == 'None':
            bkg = None
        if bkg is None:
            dtext.append('No Background')
        else:
            dtext.append('Background: %s' % bkg)

        step = self.fit_step.GetStringSelection().lower()
        if model in ('step', 'rectangle'):
            dtext.append('Step form: %s' % step)
        lgroup =  getattr(self.larch.symtable, gname)
        x = lgroup._x1_
        y = lgroup._y1_
        pgroup = fit_peak(x, y, model, background=bkg, step=step,
                          _larch=self.larch)
        text = fit_report(pgroup.params, _larch=self.larch)
        dtext.append('Parameters: ')
        for pname in dir(pgroup.params):
            par = getattr(pgroup.params, pname)
            if isParameter(par):
                ptxt = "    %s= %.4f" % (par.name, par.value)
                if (hasattr(par, 'stderr') and par.stderr is not None):
                    ptxt = "%s(%.4f)" % (ptxt, par.stderr)
                dtext.append(ptxt)

        dtext = '\n'.join(dtext)
        # plotframe = self.get_plotwindow()
        # plotframe.oplot(x, pgroup.fit, label='fit (%s)' % model)
        text = fit_report(pgroup.params, _larch=self.larch)
        self.fit_report.SetLabel(dtext)

    def xas_process(self, gname, plotopts):
        """ process (pre-edge/normalize) XAS data from XAS form, overwriting
        larch group '_y1_' attribute to be plotted
        """
        out = self.xas_op.GetStringSelection().lower() # raw, pre, norm, flat
        if out.startswith('raw'):
            return plotopts

        preopts = {'group': gname, 'e0': None, 'step': None}

        lgroup = getattr(self.larch.symtable, gname)

        if self.dtcorr.IsChecked():
            print( 'need to dt correct!')

        if not self.xas_autoe0.IsChecked():
            xmin, xmax = min(lgroup._x1_),  max(lgroup._x1_)
            e0 = self.xas_e0.GetValue()
            if e0 < xmax and e0 > xmin:
                preopts['e0'] = e0

        if not self.xas_autostep.IsChecked():
            preopts['step'] = self.xas_step.GetValue()

        preopts['pre1']  = self.xas_pre1.GetValue()
        preopts['pre2']  = self.xas_pre2.GetValue()
        preopts['norm1'] = self.xas_nor1.GetValue()
        preopts['norm2'] = self.xas_nor2.GetValue()

        preopts['nvict'] = self.xas_vict.GetSelection()
        preopts['nnorm'] = self.xas_nnor.GetSelection()

        preopts = ", ".join(["%s=%s" %(k, v) for k,v in preopts.items()])
        preedge_cmd = "pre_edge(%s._x1_, %s._y1_, %s)" % (gname, gname, preopts)

        self.larch(preedge_cmd)

        self.xas_e0.SetValue(lgroup.e0)
        self.xas_step.SetValue(lgroup.edge_step)

        if out.startswith('pre'):
            self.larch('%s._y1_ = %s.norm * %s.edge_step' % (gname, gname, gname))
        elif out.startswith('norm'):
            self.larch('%s._y1_ = %s.norm' % (gname, gname))
        elif out.startswith('flat'):
            self.larch('%s._y1_ = %s.flat' % (gname, gname))

        return plotopts

    def init_larch(self):
        t0 = time.time()
        from larch.wxlib import inputhook
        self.larch = Interpreter()
        self.larch.symtable.set_symbol('_sys.wx.wxapp', wx.GetApp())
        self.larch.symtable.set_symbol('_sys.wx.parent', self)
        self.larch('%s = group(filename="%s")' % (SCANGROUP, CURSCAN))
        self.SetStatusText('ready')
        self.datagroups = self.larch.symtable
        self.title.SetLabel('')

    def write_message(self, s, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(s, panel)

    def get_plotwindow(self, new=False, **kws):
        pframe = None
        if not new:
            while pframe is None:
                try:
                    pframe = self.plotters.pop()
                    pframe.Show()
                    pframe.Raise()
                except IndexError:
                    pframe = None
                    break
                except PyDeadObjectError:
                    pframe = None

        if pframe is None:
            pframe = PlotFrame()
            pframe.Show()
            pframe.Raise()

        self.plotters.append(pframe)

        return pframe

    def onYchoice(self, evt=None, side='left'):
        self.onPlot()

    def onPlot(self, evt=None, opt='new old', npts=None):
        # 'win new', 'New Window'),
        # 'win old',  'Old Window'),
        # 'over left', 'Left Axis'),
        # 'over right', 'Right Axis')):
        # 'update left',  from scan

        optwords = opt.split()
        # plotframe = self.get_plotwindow(new=('new' in optwords[1]))
        # plotcmd = plotframe.plot
        plotcmd = self.plotpanel.plot

        optwords = opt.split()
        side = 'left'
        update = False
        if optwords[0] == 'over':
            side = optwords[1]
            plotcmd = self.plotpanel.oplot
        elif optwords[0] == 'update'  and npts > 4:
            plotcmd = self.plotpanel.update_line
            update = True

        popts = {'side': side}

        ix = self.xarr.GetSelection()
        x  = self.xarr.GetStringSelection()

        try:
            gname = self.groupname
            lgroup = getattr(self.larch.symtable, gname)
        except:
            gname = SCANGROUP
            lgroup = getattr(self.larch.symtable, gname)

        xfmt = "%s._x1_ = %s(%s)"
        yfmt = "%s._y1_ = %s((%s %s %s) %s (%s))"
        xop = self.xop.GetStringSelection()

        xlabel = x
        try:
            xunits = lgroup.array_units[ix]
        except:
            xunits = ''
        if xop != '':
            xlabel = "%s(%s)" % (xop, xlabel)
        if xunits != '':
            xlabel = '%s (%s)' % (xlabel, xunits)
        popts['xlabel'] = xlabel

        opl1 = self.yops[0][0].GetStringSelection()
        opl2 = self.yops[0][1].GetStringSelection()
        opl3 = self.yops[0][2].GetStringSelection()

        yl1 = self.yarr[0][0].GetStringSelection()
        yl2 = self.yarr[0][1].GetStringSelection()
        yl3 = self.yarr[0][2].GetStringSelection()

        opr1 = self.yops[1][0].GetStringSelection()
        opr2 = self.yops[1][1].GetStringSelection()
        opr3 = self.yops[1][2].GetStringSelection()

        yr1 = self.yarr[1][0].GetStringSelection()
        yr2 = self.yarr[1][1].GetStringSelection()
        yr3 = self.yarr[1][2].GetStringSelection()

        ylabel = yl1

        if yl2 == '':
            yl2, opl2 = '1', '*'
        else:
            ylabel = "%s%s%s" % (ylabel, opl2, yl2)
        if yl3 == '':
            yl3, opl3 = '1', '*'
        else:
            ylabel = "(%s)%s%s" % (ylabel, opl3, yl3)

        if opl1 != '':
            ylabel = "%s(%s)" % (opl1, ylabel)

        if yl1 not in ('0', '1'): yl1 = "%s.%s" % (gname, yl1)
        if yl2 not in ('0', '1'): yl2 = "%s.%s" % (gname, yl2)
        if yl3 not in ('0', '1'): yl3 = "%s.%s" % (gname, yl3)
        if x  not in ('0', '1'):  x = "%s.%s" % (gname,  x)


        self.larch(xfmt % (gname, xop, x))
        self.larch(yfmt % (gname, opl1, yl1, opl2, yl2, opl3, yl3))

        try:
            npts = min(len(lgroup._x1_), len(lgroup._y1_))
        except AttributeError:
            return

        lgroup._x1_ = np.array( lgroup._x1_[:npts])
        lgroup._y1_ = np.array( lgroup._y1_[:npts])


        path, fname = os.path.split(lgroup.filename)
        popts['label'] = "%s: %s" % (fname, ylabel)
        if side == 'right':
            popts['y2label'] = ylabel
        else:
            popts['ylabel'] = ylabel

        if plotcmd == self.plotpanel.plot:
            popts['title'] = fname

        # XAFS Processing!
        #if (self.nb.GetCurrentPage() == self.xas_panel):
        #    popts = self.xas_process(gname, popts)

        if update:
            self.plotpanel.set_xlabel(popts['xlabel'])
            self.plotpanel.set_ylabel(popts['ylabel'])

            plotcmd(0, lgroup._x1_, lgroup._y1_, draw=True,
                        update_limits=True) # ((npts < 5) or (npts % 5 == 0)))

            self.plotpanel.set_xylims((
                min(lgroup._x1_), max(lgroup._x1_),
                min(lgroup._y1_), max(lgroup._y1_)))

        else:
            plotcmd(lgroup._x1_, lgroup._y1_, **popts)
            self.plotpanel.canvas.draw()

    def ShowFile(self, evt=None, filename=None, **kws):
        if filename is None and evt is not None:
            filename = evt.GetString()
        key = filename
        if filename in self.filemap:
            key = self.filemap[filename]

        if key == SCANGROUP:
            array_labels = [fix_filename(s.name) for s in self.scandb.get_scandata()]
            title = filename
        elif hasattr(self.datagroups, key):
            data = getattr(self.datagroups, key)
            title = data.filename
            array_labels = data.array_labels[:]

        self.groupname = key
        xcols  = array_labels[:]
        ycols  = array_labels[:]
        y2cols = array_labels[:] + ['1.0', '0.0', '']
        ncols  = len(xcols)
        self.title.SetLabel(title)
        self.xarr.SetItems(xcols)
        self.xarr.SetSelection(0)
        self.xop.SetSelection(0)
        for i in range(2):
            for j in range(3):
                self.yarr[i][j].SetItems(y2cols)
                self.yarr[i][j].SetSelection(len(y2cols))
            if i == 0:
                self.yarr[i][0].SetItems(ycols)
                self.yarr[i][0].SetSelection(1)

        inb = 0
        for colname in xcols:
            if 'energ' in colname.lower():
                inb = 1
        #self.nb.SetSelection(inb)

    def createMenus(self):
        # ppnl = self.plotpanel
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        pmenu = wx.Menu()
        add_menu(self, fmenu, "&Open Scan File\tCtrl+O",
                 "Read Scan File",  self.onReadScan)

        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

        self.menubar.Append(fmenu, "&File")

        # fmenu.AppendSeparator()
        # add_menu(self, fmenu, "&Copy\tCtrl+C",
        #          "Copy Figure to Clipboard", self.onClipboard)
        # add_menu(self, fmenu, "&Save\tCtrl+S", "Save Figure", self.onSaveFig)
        # add_menu(self, fmenu, "&Print\tCtrl+P", "Print Figure", self.onPrint)
        # add_menu(self, fmenu, "Page Setup", "Print Page Setup", self.onPrintSetup)
        # add_menu(self, fmenu, "Preview", "Print Preview", self.onPrintPreview)
        #

        # add_menu(self, pmenu, "Configure\tCtrl+K",
        #         "Configure Plot", self.onConfigurePlot)
        #add_menu(self, pmenu, "Unzoom\tCtrl+Z", "Unzoom Plot", self.onUnzoom)
        ##pmenu.AppendSeparator()
        #add_menu(self, pmenu, "Toggle Legend\tCtrl+L",
        #         "Toggle Legend on Plot", self.onToggleLegend)
        #add_menu(self, pmenu, "Toggle Grid\tCtrl+G",
        #         "Toggle Grid on Plot", self.onToggleGrid)
        # self.menubar.Append(pmenu, "Plot Options")
        self.SetMenuBar(self.menubar)


    def onAbout(self,evt):
        dlg = wx.MessageDialog(self, self._about,"About Epics StepScan",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onClose(self,evt):
        for obj in self.plotters:
            try:
                obj.Destroy()
            except:
                pass
        for nam in dir(self.larch.symtable._sys.wx):
            obj = getattr(self.larch.symtable._sys.wx, nam)
            del obj

        self.Destroy()

    def onReadScan(self, evt=None):
        dlg = wx.FileDialog(self, message="Load Epics Scan Data File",
                            defaultDir=os.getcwd(),
                            wildcard=FILE_WILDCARDS, style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            path = path.replace('\\', '/')
            if path in self.filemap:
                if wx.ID_YES != popup(self, "Re-read file '%s'?" % path,
                                      'Re-read file?'):
                    return

            gname = randname(n=5)
            if hasattr(self.datagroups, gname):
                time.sleep(0.005)
                gname = randname(n=6)
            parent, fname = os.path.split(path)
            self.larch("%s = read_xdi('%s')" % (gname, path))
            self.larch("%s.path  = '%s'"     % (gname, path))
            self.filelist.Append(fname)
            self.filemap[fname] = gname
            print( 'Larch:: ', gname, path, fname)
            self.ShowFile(filename=fname)

        dlg.Destroy()
Example #38
0
class PlotterFrame(wx.Frame):
    _about = """StepScan 2D Plotter
  Matt Newville <newville @ cars.uchicago.edu>
  """

    def __init__(self,
                 dbname=None,
                 server='sqlite',
                 host=None,
                 port=None,
                 user=None,
                 password=None,
                 create=True,
                 **kws):

        wx.Frame.__init__(self, None, -1, style=FRAMESTYLE)
        self.data = None
        self.filemap = {}
        title = "Step Scan Data File Viewer"
        self.scandb = None
        if dbname is not None:
            self.scandb = ScanDB(dbname=dbname,
                                 server=server,
                                 host=host,
                                 user=user,
                                 password=password,
                                 port=port,
                                 create=create)
            self.filemap[CURSCAN] = SCANGROUP
            title = '%s, with Live Scan Viewing' % title
        self.larch = None
        self.plotters = []

        self.SetTitle(title)
        self.SetSize((850, 650))
        self.SetFont(Font(9))

        self.createMainPanel()
        self.createMenus()
        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = ["Initializing....", " "]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        if dbname is not None:
            self.live_scanfile = None
            self.live_cpt = -1
            self.filelist.Append(CURSCAN)
            self.scantimer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.onScanTimer, self.scantimer)
            self.scantimer.Start(250)

    def onScanTimer(self, evt=None, **kws):
        if self.larch is None:
            return
        group = getattr(self.larch.symtable, SCANGROUP)

        curfile = fix_filename(self.scandb.get_info('filename'))
        if curfile != self.live_scanfile:
            self.live_scanfile = curfile
            group.filename = self.live_scanfile
            group.array_units = []
            self.live_cpt = -1

        sdata = self.scandb.get_scandata()
        if len(sdata) <= 1:
            return
        npts = len(sdata[-1].data)

        if npts <= self.live_cpt:
            return

        self.live_cpt = npts
        if len(group.array_units) < 1:
            group.array_units = [str(row.notes) for row in sdata]

        for row in sdata:
            setattr(group, fix_filename(row.name), np.array(row.data))

        if npts > 1:
            self.onPlot()

    def createMainPanel(self):
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(175)

        self.filelist = wx.ListBox(splitter)
        self.filelist.SetBackgroundColour(wx.Colour(255, 255, 255))
        self.filelist.Bind(wx.EVT_LISTBOX, self.ShowFile)

        self.detailspanel = self.createDetailsPanel(splitter)

        splitter.SplitVertically(self.filelist, self.detailspanel, 1)
        wx.CallAfter(self.init_larch)

    def createDetailsPanel(self, parent):
        mainpanel = wx.Panel(parent)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)
        sizer = wx.GridBagSizer(8, 7)

        self.title = SimpleText(panel, 'initializing...')
        ir = 0
        sizer.Add(self.title, (ir, 0), (1, 6), LCEN, 2)
        # x-axis

        self.xarr = add_choice(panel,
                               choices=[],
                               action=self.onYchoice,
                               size=(120, -1))
        self.xop = add_choice(panel,
                              choices=('', 'log'),
                              action=self.onYchoice,
                              size=(75, -1))

        ir += 1
        sizer.Add(SimpleText(panel, 'X = '), (ir, 0), (1, 1), CEN, 0)
        sizer.Add(self.xop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, '('), (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 3), (1, 1), RCEN, 0)
        sizer.Add(SimpleText(panel, ')'), (ir, 4), (1, 1), CEN, 0)

        self.yops = [[], []]
        self.yarr = [[], []]

        for opts, sel, siz in ((PRE_OPS, 0, 75), (ARR_OPS, 3, 50), (ARR_OPS, 3,
                                                                    50)):
            w1 = add_choice(panel,
                            choices=opts,
                            action=self.onYchoice,
                            size=(siz, -1))
            w1.SetSelection(sel)
            self.yops[0].append(w1)

            w2 = add_choice(panel,
                            choices=opts,
                            action=self.onYchoice,
                            size=(siz, -1))
            w2.SetSelection(sel)
            self.yops[1].append(w2)

        opts = {'choices': [], 'size': (120, -1), 'action': self.onYchoice}
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **opts))
            self.yarr[1].append(add_choice(panel, **opts))

        for i in range(2):
            ir += 1
            label = 'Y%i = ' % (i + 1)
            sizer.Add(SimpleText(panel, label), (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0], (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('), (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0], (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1], (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1], (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'), (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2], (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2], (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'), (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        # sizer.Add(SimpleText(panel, ' New Plot: '),  (ir,   0), (1, 3), LCEN, 0)
        # sizer.Add(SimpleText(panel, ' Over Plot: '), (ir+1, 0), (1, 3), LCEN, 0)

        for jr, ic, dc, opt, ttl in ((0, 0, 4, 'win old',
                                      'New Plot, This Window'),
                                     (0, 4, 2, 'win new',
                                      'New Plot, New Window'),
                                     (1, 0, 4, 'over left',
                                      'Over Plot, Left Axis'),
                                     (1, 4, 2, 'over right',
                                      'Over Plot, Right Axis')):
            sizer.Add(
                add_button(panel,
                           ttl,
                           size=(165, -1),
                           action=Closure(self.onPlot, opt=opt)),
                (ir + jr, ic), (1, dc), LCEN, 2)

        ir += 2
        self.dtcorr = check(panel, default=True, label='correct deadtime?')
        sizer.Add(self.dtcorr, (ir, 0), (1, 3), LCEN, 0)
        ir += 1
        sizer.Add(SimpleText(panel, ''), (ir, 0), (1, 3), LCEN, 0)

        pack(panel, sizer)

        #         self.nb = flat_nb.FlatNotebook(mainpanel, -1, agwStyle=FNB_STYLE)
        #
        #         self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        #         self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        #
        #         self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        #         self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))
        #
        #         self.xas_panel = self.CreateXASPanel(self.nb) # mainpanel)
        #         self.fit_panel = self.CreateFitPanel(self.nb) # mainpanel)
        #
        #         self.nb.AddPage(self.fit_panel, ' General Analysis ', True)
        #         self.nb.AddPage(self.xas_panel, ' XAS Processing ',   True)

        mainsizer.Add(panel, 0, LCEN | wx.EXPAND, 2)
        self.plotpanel = PlotPanel(mainpanel, size=(500, 670))
        self.plotpanel.messenger = self.write_message

        bgcol = panel.GetBackgroundColour()
        bgcol = (bgcol[0] / 255., bgcol[1] / 255., bgcol[2] / 255.)
        self.plotpanel.canvas.figure.set_facecolor(bgcol)

        mainsizer.Add(self.plotpanel, 1, wx.GROW | wx.ALL, 1)

        # mainsizer.Add(self.nb, 1, LCEN|wx.EXPAND, 2)
        pack(mainpanel, mainsizer)

        return mainpanel

    def CreateFitPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.fit_model = add_choice(panel,
                                    size=(100, -1),
                                    choices=('Gaussian', 'Lorentzian', 'Voigt',
                                             'Linear', 'Quadratic', 'Step',
                                             'Rectangle', 'Exponential'))
        self.fit_bkg = add_choice(panel,
                                  size=(100, -1),
                                  choices=('None', 'constant', 'linear',
                                           'quadtratic'))
        self.fit_step = add_choice(panel,
                                   size=(100, -1),
                                   choices=('linear', 'error function',
                                            'arctan'))

        self.fit_report = wx.StaticText(panel, -1, "", (180, 200))
        sizer = wx.GridBagSizer(10, 4)
        sizer.Add(SimpleText(p, 'Fit Model: '), (0, 0), (1, 1), LCEN)
        sizer.Add(self.fit_model, (0, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Background: '), (1, 0), (1, 1), LCEN)
        sizer.Add(self.fit_bkg, (1, 1), (1, 1), LCEN)

        sizer.Add(SimpleText(p, 'Step Function Form: '), (2, 0), (1, 1), LCEN)
        sizer.Add(self.fit_step, (2, 1), (1, 1), LCEN)
        sizer.Add(
            add_button(panel,
                       'Show Fit',
                       size=(100, -1),
                       action=self.onFitPeak), (3, 0), (1, 1), LCEN)
        sizer.Add(self.fit_report, (0, 2), (4, 2), LCEN, 3)
        pack(panel, sizer)
        return panel

    def CreateXASPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.xas_autoe0 = check(panel, default=True, label='auto?')
        self.xas_autostep = check(panel, default=True, label='auto?')
        self.xas_op = add_choice(panel,
                                 size=(95, -1),
                                 choices=('Raw Data', 'Pre-edged',
                                          'Normalized', 'Flattened'))
        self.xas_e0 = FloatCtrl(panel, value=0, precision=3, size=(95, -1))
        self.xas_step = FloatCtrl(panel, value=0, precision=3, size=(95, -1))
        self.xas_pre1 = FloatCtrl(panel,
                                  value=-200,
                                  precision=1,
                                  size=(95, -1))
        self.xas_pre2 = FloatCtrl(panel, value=-30, precision=1, size=(95, -1))
        self.xas_nor1 = FloatCtrl(panel, value=30, precision=1, size=(95, -1))
        self.xas_nor2 = FloatCtrl(panel, value=300, precision=1, size=(95, -1))
        self.xas_vict = add_choice(panel,
                                   size=(50, -1),
                                   choices=('0', '1', '2', '3'))
        self.xas_nnor = add_choice(panel,
                                   size=(50, -1),
                                   choices=('0', '1', '2', '3'))
        self.xas_vict.SetSelection(1)
        self.xas_nnor.SetSelection(2)
        sizer = wx.GridBagSizer(10, 4)

        sizer.Add(SimpleText(p, 'Plot XAS as: '), (0, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'E0 : '), (1, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Edge Step: '), (2, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Pre-edge range: '), (3, 0), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'Normalization range: '), (4, 0), (1, 1), LCEN)

        sizer.Add(self.xas_op, (0, 1), (1, 1), LCEN)
        sizer.Add(self.xas_e0, (1, 1), (1, 1), LCEN)
        sizer.Add(self.xas_step, (2, 1), (1, 1), LCEN)
        sizer.Add(self.xas_pre1, (3, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (3, 2), (1, 1), LCEN)
        sizer.Add(self.xas_pre2, (3, 3), (1, 1), LCEN)
        sizer.Add(self.xas_nor1, (4, 1), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (4, 2), (1, 1), LCEN)
        sizer.Add(self.xas_nor2, (4, 3), (1, 1), LCEN)

        sizer.Add(self.xas_autoe0, (1, 2), (1, 2), LCEN)
        sizer.Add(self.xas_autostep, (2, 2), (1, 2), LCEN)

        sizer.Add(SimpleText(p, 'Victoreen:'), (3, 4), (1, 1), LCEN)
        sizer.Add(self.xas_vict, (3, 5), (1, 1), LCEN)
        sizer.Add(SimpleText(p, 'PolyOrder:'), (4, 4), (1, 1), LCEN)
        sizer.Add(self.xas_nnor, (4, 5), (1, 1), LCEN)

        pack(panel, sizer)
        return panel

    def onFitPeak(self, evt=None):
        gname = self.groupname
        if self.dtcorr.IsChecked():
            print('fit needs to dt correct!')

        dtext = []
        model = self.fit_model.GetStringSelection().lower()
        dtext.append('Fit Model: %s' % model)
        bkg = self.fit_bkg.GetStringSelection()
        if bkg == 'None':
            bkg = None
        if bkg is None:
            dtext.append('No Background')
        else:
            dtext.append('Background: %s' % bkg)

        step = self.fit_step.GetStringSelection().lower()
        if model in ('step', 'rectangle'):
            dtext.append('Step form: %s' % step)
        lgroup = getattr(self.larch.symtable, gname)
        x = lgroup._x1_
        y = lgroup._y1_
        pgroup = fit_peak(x,
                          y,
                          model,
                          background=bkg,
                          step=step,
                          _larch=self.larch)
        text = fit_report(pgroup.params, _larch=self.larch)
        dtext.append('Parameters: ')
        for pname in dir(pgroup.params):
            par = getattr(pgroup.params, pname)
            if isParameter(par):
                ptxt = "    %s= %.4f" % (par.name, par.value)
                if (hasattr(par, 'stderr') and par.stderr is not None):
                    ptxt = "%s(%.4f)" % (ptxt, par.stderr)
                dtext.append(ptxt)

        dtext = '\n'.join(dtext)
        # plotframe = self.get_plotwindow()
        # plotframe.oplot(x, pgroup.fit, label='fit (%s)' % model)
        text = fit_report(pgroup.params, _larch=self.larch)
        self.fit_report.SetLabel(dtext)

    def xas_process(self, gname, plotopts):
        """ process (pre-edge/normalize) XAS data from XAS form, overwriting
        larch group '_y1_' attribute to be plotted
        """
        out = self.xas_op.GetStringSelection().lower()  # raw, pre, norm, flat
        if out.startswith('raw'):
            return plotopts

        preopts = {'group': gname, 'e0': None, 'step': None}

        lgroup = getattr(self.larch.symtable, gname)

        if self.dtcorr.IsChecked():
            print('need to dt correct!')

        if not self.xas_autoe0.IsChecked():
            xmin, xmax = min(lgroup._x1_), max(lgroup._x1_)
            e0 = self.xas_e0.GetValue()
            if e0 < xmax and e0 > xmin:
                preopts['e0'] = e0

        if not self.xas_autostep.IsChecked():
            preopts['step'] = self.xas_step.GetValue()

        preopts['pre1'] = self.xas_pre1.GetValue()
        preopts['pre2'] = self.xas_pre2.GetValue()
        preopts['norm1'] = self.xas_nor1.GetValue()
        preopts['norm2'] = self.xas_nor2.GetValue()

        preopts['nvict'] = self.xas_vict.GetSelection()
        preopts['nnorm'] = self.xas_nnor.GetSelection()

        preopts = ", ".join(["%s=%s" % (k, v) for k, v in preopts.items()])
        preedge_cmd = "pre_edge(%s._x1_, %s._y1_, %s)" % (gname, gname,
                                                          preopts)

        self.larch(preedge_cmd)

        self.xas_e0.SetValue(lgroup.e0)
        self.xas_step.SetValue(lgroup.edge_step)

        if out.startswith('pre'):
            self.larch('%s._y1_ = %s.norm * %s.edge_step' %
                       (gname, gname, gname))
        elif out.startswith('norm'):
            self.larch('%s._y1_ = %s.norm' % (gname, gname))
        elif out.startswith('flat'):
            self.larch('%s._y1_ = %s.flat' % (gname, gname))

        return plotopts

    def init_larch(self):
        t0 = time.time()
        from larch.wxlib import inputhook
        self.larch = Interpreter()
        self.larch.symtable.set_symbol('_sys.wx.wxapp', wx.GetApp())
        self.larch.symtable.set_symbol('_sys.wx.parent', self)
        self.larch('%s = group(filename="%s")' % (SCANGROUP, CURSCAN))
        self.SetStatusText('ready')
        self.datagroups = self.larch.symtable
        self.title.SetLabel('')

    def write_message(self, s, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(s, panel)

    def get_plotwindow(self, new=False, **kws):
        pframe = None
        if not new:
            while pframe is None:
                try:
                    pframe = self.plotters.pop()
                    pframe.Show()
                    pframe.Raise()
                except IndexError:
                    pframe = None
                    break
                except PyDeadObjectError:
                    pframe = None

        if pframe is None:
            pframe = PlotFrame()
            pframe.Show()
            pframe.Raise()

        self.plotters.append(pframe)

        return pframe

    def onYchoice(self, evt=None, side='left'):
        self.onPlot()

    def onPlot(self, evt=None, opt='new old', npts=None):
        # 'win new', 'New Window'),
        # 'win old',  'Old Window'),
        # 'over left', 'Left Axis'),
        # 'over right', 'Right Axis')):
        # 'update left',  from scan

        optwords = opt.split()
        # plotframe = self.get_plotwindow(new=('new' in optwords[1]))
        # plotcmd = plotframe.plot
        plotcmd = self.plotpanel.plot

        optwords = opt.split()
        side = 'left'
        update = False
        if optwords[0] == 'over':
            side = optwords[1]
            plotcmd = self.plotpanel.oplot
        elif optwords[0] == 'update' and npts > 4:
            plotcmd = self.plotpanel.update_line
            update = True

        popts = {'side': side}

        ix = self.xarr.GetSelection()
        x = self.xarr.GetStringSelection()

        try:
            gname = self.groupname
            lgroup = getattr(self.larch.symtable, gname)
        except:
            gname = SCANGROUP
            lgroup = getattr(self.larch.symtable, gname)

        xfmt = "%s._x1_ = %s(%s)"
        yfmt = "%s._y1_ = %s((%s %s %s) %s (%s))"
        xop = self.xop.GetStringSelection()

        xlabel = x
        try:
            xunits = lgroup.array_units[ix]
        except:
            xunits = ''
        if xop != '':
            xlabel = "%s(%s)" % (xop, xlabel)
        if xunits != '':
            xlabel = '%s (%s)' % (xlabel, xunits)
        popts['xlabel'] = xlabel

        opl1 = self.yops[0][0].GetStringSelection()
        opl2 = self.yops[0][1].GetStringSelection()
        opl3 = self.yops[0][2].GetStringSelection()

        yl1 = self.yarr[0][0].GetStringSelection()
        yl2 = self.yarr[0][1].GetStringSelection()
        yl3 = self.yarr[0][2].GetStringSelection()

        opr1 = self.yops[1][0].GetStringSelection()
        opr2 = self.yops[1][1].GetStringSelection()
        opr3 = self.yops[1][2].GetStringSelection()

        yr1 = self.yarr[1][0].GetStringSelection()
        yr2 = self.yarr[1][1].GetStringSelection()
        yr3 = self.yarr[1][2].GetStringSelection()

        ylabel = yl1

        if yl2 == '':
            yl2, opl2 = '1', '*'
        else:
            ylabel = "%s%s%s" % (ylabel, opl2, yl2)
        if yl3 == '':
            yl3, opl3 = '1', '*'
        else:
            ylabel = "(%s)%s%s" % (ylabel, opl3, yl3)

        if opl1 != '':
            ylabel = "%s(%s)" % (opl1, ylabel)

        if yl1 not in ('0', '1'): yl1 = "%s.%s" % (gname, yl1)
        if yl2 not in ('0', '1'): yl2 = "%s.%s" % (gname, yl2)
        if yl3 not in ('0', '1'): yl3 = "%s.%s" % (gname, yl3)
        if x not in ('0', '1'): x = "%s.%s" % (gname, x)

        self.larch(xfmt % (gname, xop, x))
        self.larch(yfmt % (gname, opl1, yl1, opl2, yl2, opl3, yl3))

        try:
            npts = min(len(lgroup._x1_), len(lgroup._y1_))
        except AttributeError:
            return

        lgroup._x1_ = np.array(lgroup._x1_[:npts])
        lgroup._y1_ = np.array(lgroup._y1_[:npts])

        path, fname = os.path.split(lgroup.filename)
        popts['label'] = "%s: %s" % (fname, ylabel)
        if side == 'right':
            popts['y2label'] = ylabel
        else:
            popts['ylabel'] = ylabel

        if plotcmd == self.plotpanel.plot:
            popts['title'] = fname

        # XAFS Processing!
        #if (self.nb.GetCurrentPage() == self.xas_panel):
        #    popts = self.xas_process(gname, popts)

        if update:
            self.plotpanel.set_xlabel(popts['xlabel'])
            self.plotpanel.set_ylabel(popts['ylabel'])

            plotcmd(0, lgroup._x1_, lgroup._y1_, draw=True,
                    update_limits=True)  # ((npts < 5) or (npts % 5 == 0)))

            self.plotpanel.set_xylims((min(lgroup._x1_), max(lgroup._x1_),
                                       min(lgroup._y1_), max(lgroup._y1_)))

        else:
            plotcmd(lgroup._x1_, lgroup._y1_, **popts)
            self.plotpanel.canvas.draw()

    def ShowFile(self, evt=None, filename=None, **kws):
        if filename is None and evt is not None:
            filename = evt.GetString()
        key = filename
        if filename in self.filemap:
            key = self.filemap[filename]

        if key == SCANGROUP:
            array_labels = [
                fix_filename(s.name) for s in self.scandb.get_scandata()
            ]
            title = filename
        elif hasattr(self.datagroups, key):
            data = getattr(self.datagroups, key)
            title = data.filename
            array_labels = data.array_labels[:]

        self.groupname = key
        xcols = array_labels[:]
        ycols = array_labels[:]
        y2cols = array_labels[:] + ['1.0', '0.0', '']
        ncols = len(xcols)
        self.title.SetLabel(title)
        self.xarr.SetItems(xcols)
        self.xarr.SetSelection(0)
        self.xop.SetSelection(0)
        for i in range(2):
            for j in range(3):
                self.yarr[i][j].SetItems(y2cols)
                self.yarr[i][j].SetSelection(len(y2cols))
            if i == 0:
                self.yarr[i][0].SetItems(ycols)
                self.yarr[i][0].SetSelection(1)

        inb = 0
        for colname in xcols:
            if 'energ' in colname.lower():
                inb = 1
        #self.nb.SetSelection(inb)

    def createMenus(self):
        # ppnl = self.plotpanel
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        pmenu = wx.Menu()
        add_menu(self, fmenu, "&Open Scan File\tCtrl+O", "Read Scan File",
                 self.onReadScan)

        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

        self.menubar.Append(fmenu, "&File")

        # fmenu.AppendSeparator()
        # add_menu(self, fmenu, "&Copy\tCtrl+C",
        #          "Copy Figure to Clipboard", self.onClipboard)
        # add_menu(self, fmenu, "&Save\tCtrl+S", "Save Figure", self.onSaveFig)
        # add_menu(self, fmenu, "&Print\tCtrl+P", "Print Figure", self.onPrint)
        # add_menu(self, fmenu, "Page Setup", "Print Page Setup", self.onPrintSetup)
        # add_menu(self, fmenu, "Preview", "Print Preview", self.onPrintPreview)
        #

        # add_menu(self, pmenu, "Configure\tCtrl+K",
        #         "Configure Plot", self.onConfigurePlot)
        #add_menu(self, pmenu, "Unzoom\tCtrl+Z", "Unzoom Plot", self.onUnzoom)
        ##pmenu.AppendSeparator()
        #add_menu(self, pmenu, "Toggle Legend\tCtrl+L",
        #         "Toggle Legend on Plot", self.onToggleLegend)
        #add_menu(self, pmenu, "Toggle Grid\tCtrl+G",
        #         "Toggle Grid on Plot", self.onToggleGrid)
        # self.menubar.Append(pmenu, "Plot Options")
        self.SetMenuBar(self.menubar)

    def onAbout(self, evt):
        dlg = wx.MessageDialog(self, self._about, "About Epics StepScan",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onClose(self, evt):
        for obj in self.plotters:
            try:
                obj.Destroy()
            except:
                pass
        for nam in dir(self.larch.symtable._sys.wx):
            obj = getattr(self.larch.symtable._sys.wx, nam)
            del obj

        self.Destroy()

    def onReadScan(self, evt=None):
        dlg = wx.FileDialog(self,
                            message="Load Epics Scan Data File",
                            defaultDir=os.getcwd(),
                            wildcard=FILE_WILDCARDS,
                            style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            path = path.replace('\\', '/')
            if path in self.filemap:
                if wx.ID_YES != popup(self, "Re-read file '%s'?" % path,
                                      'Re-read file?'):
                    return

            gname = randname(n=5)
            if hasattr(self.datagroups, gname):
                time.sleep(0.005)
                gname = randname(n=6)
            parent, fname = os.path.split(path)
            self.larch("%s = read_xdi('%s')" % (gname, path))
            self.larch("%s.path  = '%s'" % (gname, path))
            self.filelist.Append(fname)
            self.filemap[fname] = gname
            print('Larch:: ', gname, path, fname)
            self.ShowFile(filename=fname)

        dlg.Destroy()
Example #39
0
    def __init__(self, parent, filename=None, read_ok_cb=None,
                 size=(725, 450), _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1,   size=size, style=FRAMESTYLE)
        splitter  = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop, 'Select None', size=(100, 30), action=self.onSelNone)
        sel_all  = Button(ltop, 'Select All', size=(100, 30), action=self.onSelAll)
        sel_imp  = Button(ltop, 'Import Selected Groups', size=(200, 30), action=self.onOK)

        self.select_imported = sel_imp
        self.grouplist = FileCheckList(leftpanel, select_action=self.onShowGroup)

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none,  (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp,  (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN|wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN|wx.GROW|wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel, self.filename, font=Font(13),
                                colour=self.colors.title, style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.a_project = read_athena(self.filename, do_bkg=False, do_fft=False,
                                     _larch=_larch)
        self.allgroups = []
        for item in dir(self.a_project):
            if not item.startswith('_athena_'):
                self.allgroups.append(item)
                self.grouplist.Append(item)
        self.Show()
        self.Raise()
Example #40
0
class ScanViewerFrame(wx.Frame):
    _about = """Scan Viewer,  Matt Newville <newville @ cars.uchicago.edu>  """
    TIME_MSG = 'Point %i/%i, Time Remaining ~ %s, Status=%s'

    def __init__(self, parent, dbname=None, server='sqlite',
                 host=None, port=None, user=None, password=None,
                 create=True, _larch=None, **kws):

        wx.Frame.__init__(self, None, -1, style=FRAMESTYLE)
        title = "Epics Step Scan Viewer"
        self.parent = parent
        self.scandb = getattr(parent, 'scandb', None)
        if self.scandb is None and dbname is not None:
            self.scandb = ScanDB(dbname=dbname, server=server, host=host,
                                 user=user, password=password, port=port,
                                 create=create)
        self.larch = _larch
        if _larch is None:
            self.larch = LarchScanDBServer(self.scandb)

        self.lgroup = None
        self.larch.run("%s = group(filename='%s')" % (SCANGROUP, CURSCAN))
        self.larch.run("_sys.localGroup = %s" % (SCANGROUP))
        # self.larch.run("show(_sys)")
        self.lgroup =  self.larch.get_symbol(SCANGROUP)

        self.force_newplot = False
        self.scan_inprogress = False
        self.last_column_update = 0.0
        self.need_column_update = True
        self.positioner_pvs = {}
        self.x_cursor = None
        self.x_label = None
        self.SetTitle(title)
        self.SetSize((800, 700))
        self.SetFont(Font(9))
        self.createMainPanel()
        self.createMenus()
        self.last_status_msg = None
        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = ["Initializing....", " "]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        if self.scandb is not None:
            self.get_info  = self.scandb.get_info
            self.scandb_server = self.scandb.server
            self.live_scanfile = None
            self.live_cpt = -1
            self.total_npts = 1
            self.scantimer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.onScanTimer, self.scantimer)
            self.scantimer.Start(300)
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.Show()
        self.SetStatusText('ready')
        self.title.SetLabel('')
        self.Raise()

    def onScanTimer(self, evt=None,  **kws):
        if self.lgroup is None:
            return
        try:
            curfile   = fix_filename(self.get_info('filename'))
            sdata     = self.scandb.get_scandata()
            scan_stat = self.get_info('scan_status')
            msg       = self.get_info('scan_progress')
        except:
            logging.exception("No Scan at ScanTime")

        try:
            # npts = len(sdata[-1].data)
            nptsall = [len(s.data) for s in sdata]
            npts = min(nptsall)
        except:
            npts = 0
        if npts <= 0 or msg.lower().startswith('preparing'):
            self.need_column_update = True

        do_newplot = False

        if ((curfile != self.live_scanfile) or
            (npts > 0 and npts < 3 and self.need_column_update)):
            self.need_column_update = False
            self.scan_inprogress = True
            self.moveto_btn.Disable()
            do_newplot = True
            self.live_scanfile = curfile
            self.title.SetLabel(curfile)
            if len(sdata)>1:
                self.set_column_names(sdata)

        elif msg.lower().startswith('scan complete') and self.scan_inprogress:
            self.scan_inprogress = False
            self.moveto_btn.Enable()
            do_newplot = True
        elif msg.lower().startswith('scan abort'):
            self.moveto_btn.Enable()
            do_newplot = True

        if msg != self.last_status_msg:
            self.last_status_msg = msg
            self.SetStatusText(msg)

        if not (self.scan_inprogress or do_newplot):
            # print 'Scan Timer no reason to plot', do_newplot, self.scan_inprogress
            return

        for row in sdata:
            dat = row.data
            if self.scandb_server == 'sqlite':
                dat = json.loads(dat.replace('{', '[').replace('}', ']'))
            setattr(self.lgroup, fix_varname(row.name), np.array(dat))

        if ((npts > 1 and npts != self.live_cpt)  or
            (time.time() - self.last_column_update) > 30.0):
            if do_newplot:
                self.force_newplot = True
            self.onPlot(npts=npts)
            self.last_column_update = time.time()
        self.live_cpt = npts


    def set_column_names(self, sdata):
        """set column names from values read from scandata table"""
        if len(sdata) < 1:
            return
        try:
            self.lgroup.array_units = [fix_varname(s.units) for s in sdata]
        except:
            return
        self.total_npts = self.get_info('scan_total_points', as_int=True)
        self.live_cpt = -1
        xcols, ycols, y2cols = [], [], []
        self.positioner_pvs = {}
        for s in sdata:
            nam = fix_varname(s.name)
            ycols.append(nam)
            if s.notes.lower().startswith('pos'):
                xcols.append(nam)
                self.positioner_pvs[nam] = s.pvname
        # print("SET COLUMN NAMES", xcols, self.positioner_pvs)

        y2cols = ycols[:] + ['1.0', '0.0', '']
        xarr_old = self.xarr.GetStringSelection()
        self.xarr.SetItems(xcols)

        ix = xcols.index(xarr_old) if xarr_old in xcols else 0
        self.xarr.SetSelection(ix)
        for i in range(2):
            for j in range(3):
                yold = self.yarr[i][j].GetStringSelection()
                idef, cols = 0, y2cols
                if i == 0 and j == 0:
                    idef, cols = 1, ycols
                self.yarr[i][j].SetItems(cols)
                # print(i, j, yold, yold in cols)
                iy = cols.index(yold) if yold in cols else idef
                self.yarr[i][j].SetSelection(iy)
        time.sleep(0.75)


    def createMainPanel(self):
        mainpanel = wx.Panel(self)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)

        self.yops = [[],[]]
        self.yarr = [[],[]]
        arr_kws= {'choices':[], 'size':(150, -1), 'action':self.onPlot}

        self.title = SimpleText(panel, 'initializing...',
                                font=Font(13), colour='#880000')
        self.xarr = add_choice(panel, **arr_kws)
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **arr_kws))
            self.yarr[1].append(add_choice(panel, **arr_kws))

        for opts, sel, wid in ((PRE_OPS, 0, 80),
                               (ARR_OPS, 3, 40),
                               (ARR_OPS, 3, 40)):
            arr_kws['choices'] = opts
            arr_kws['size'] = (wid, -1)
            self.yops[0].append(add_choice(panel, default=sel, **arr_kws))
            self.yops[1].append(add_choice(panel, default=sel, **arr_kws))

        # place widgets
        sizer = wx.GridBagSizer(5, 10)
        sizer.Add(self.title,                  (0, 1), (1, 6), LCEN, 2)
        sizer.Add(SimpleText(panel, '  X ='),  (1, 0), (1, 1), CEN, 0)
        sizer.Add(self.xarr,                   (1, 3), (1, 1), RCEN, 0)

        ir = 1
        for i in range(2):
            ir += 1
            label = '  Y%i =' % (i+1)
            sizer.Add(SimpleText(panel, label),  (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0],           (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('),   (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0],           (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1],           (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1],           (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'),    (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2],           (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2],           (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'),    (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        sizer.Add(hline(panel),   (ir, 0), (1, 12), CEN|wx.GROW|wx.ALL, 0)
        pack(panel, sizer)


        self.plotpanel = PlotPanel(mainpanel, size=(520, 550), fontsize=8)
        self.plotpanel.cursor_callback = self.onLeftDown
        self.plotpanel.messenger = self.write_message
        self.plotpanel.canvas.figure.set_facecolor((0.98,0.98,0.97))
        self.plotpanel.unzoom     = self.unzoom
        # self.plotpanel.popup_menu = None

        btnsizer = wx.StdDialogButtonSizer()
        btnpanel = wx.Panel(mainpanel)
        self.moveto_btn = add_button(btnpanel, 'Move To Position', action=self.onMoveTo)

        btnsizer.Add(add_button(btnpanel, 'Pause Scan', action=self.onPause))
        btnsizer.Add(add_button(btnpanel, 'Resume Scan', action=self.onResume))
        btnsizer.Add(add_button(btnpanel, 'Abort Scan', action=self.onAbort))
        btnsizer.Add(add_button(btnpanel, 'Unzoom Plot', action=self.unzoom))
        btnsizer.Add(self.moveto_btn)
        pack(btnpanel, btnsizer)

        mainsizer.Add(panel,   0, LCEN|wx.EXPAND, 2)
        mainsizer.Add(self.plotpanel, 1, wx.GROW|wx.ALL, 1)
        mainsizer.Add(btnpanel, 0, wx.GROW|wx.ALL, 1)

        pack(mainpanel, mainsizer)
        return mainpanel


    def onMoveTo(self, evt=None):
        pvname = self.positioner_pvs.get(self.x_label, None)

        if pvname is not None and self.x_cursor is not None:
            msg = " Move To Position:\n  %s (%s) to %.4f " % (self.x_label,
                                                              pvname,
                                                              self.x_cursor)
            ret = popup(self, msg, "Move to Position?",
                        style=wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
            if ret == wx.ID_YES:
                epics.caput(pvname, self.x_cursor)

    def onPause(self, evt=None):
        self.scandb.set_info('request_pause', 1)

    def onResume(self, evt=None):
        self.scandb.set_info('request_pause', 0)

    def onAbort(self, evt=None):
        self.scandb.set_info('request_abort', 1)

    def write_message(self, s, panel=0):
        """write a message to the Status Bar"""
        self.SetStatusText(s, panel)

    def onLeftDown(self, x=None, y=None):
        self.x_cursor = x

    def onPlot(self, evt=None, npts=None):
        """draw plot of newest data"""

        new_plot = self.force_newplot or npts < 3
        lgroup, gname = self.lgroup, SCANGROUP

        ix = self.xarr.GetSelection()
        x  = self.xarr.GetStringSelection()
        self.x_label = x
        xlabel = x
        popts = {'labelfontsize': 8, 'xlabel': x,
                 'marker':'o', 'markersize':4}

        try:
            xunits = lgroup.array_units[ix]
            xlabel = '%s (%s)' % (xlabel, xunits)
        except:
            logging.exception("No units at onPlot")

        def make_array(wids, iy):
            gn  = SCANGROUP
            op1 = self.yops[iy][0].GetStringSelection()
            op2 = self.yops[iy][1].GetStringSelection()
            op3 = self.yops[iy][2].GetStringSelection()
            yy1 = self.yarr[iy][0].GetStringSelection()
            yy2 = self.yarr[iy][1].GetStringSelection()
            yy3 = self.yarr[iy][2].GetStringSelection()
            if yy1 in ('0', '1', '', None) or len(yy1) < 0:
                return '', ''
            label = yy1
            expr = "%s.%s"  % (gn, yy1)

            if yy2 != '':
                label = "%s%s%s" % (label, op2, yy2)
                expr = "%s%s" % (expr, op2)
                if yy2 in ('1.0', '0.0'):
                    expr = "%s%s" % (expr, yy2)
                else:
                    expr = "%s%s.%s"  % (expr, gn, yy2)

            if yy3 != '':
                label = "(%s)%s%s" % (label, op3, yy3)
                expr = "(%s)%s" % (expr, op3)
                if yy3 in ('1.0', '0.0'):
                    expr = "%s%s"  % (expr, yy3)
                else:
                    expr = "%s%s.%s" % (expr, gn, yy3)

            if op1 != '':
                end = ''
                if '(' in op1: end = ')'
                label = "%s(%s)%s" % (op1, label, end)
                expr  = "%s(%s)%s" % (op1, expr, end)
            return label, expr

        ylabel, yexpr = make_array(self.yops, 0)
        if yexpr == '':
            return
        self.larch.run("%s.arr_x = %s.%s" % (gname, gname, x))
        self.larch.run("%s.arr_y1 = %s"   % (gname, yexpr))

        try:
            npts = min(len(lgroup.arr_x), len(lgroup.arr_y1))
        except AttributeError:
            logging.exception("Problem getting arrays")

        y2label, y2expr = make_array(self.yops, 1)
        if y2expr != '':
            self.larch.run("%s.arr_y2 = %s" % (gname, y2expr))
            n2pts = npts
            try:
                n2pts = min(len(lgroup.arr_x), len(lgroup.arr_y1),
                            len(lgroup.arr_y2))
                lgroup.arr_y2 = np.array( lgroup.arr_y2[:n2pts])
            except:
                y2expr = ''
            npts = n2pts

        lgroup.arr_y1 = np.array( lgroup.arr_y1[:npts])
        lgroup.arr_x  = np.array( lgroup.arr_x[:npts])

        path, fname = os.path.split(self.live_scanfile)
        popts.update({'title': fname, 'xlabel': xlabel,
                      'ylabel': ylabel, 'y2label': y2label})
        if len(lgroup.arr_x) < 2 or len(lgroup.arr_y1) < 2:
            return

        if len(lgroup.arr_x) != len(lgroup.arr_y1):
            print 'data length mismatch ', len(lgroup.arr_x), len(lgroup.arr_y1)
            return
        ppnl = self.plotpanel
        if new_plot:
            ppnl.conf.zoom_lims = []
            ppnl.plot(lgroup.arr_x, lgroup.arr_y1,
                      label= "%s: %s" % (fname, ylabel), **popts)
            if y2expr != '':
                ppnl.oplot(lgroup.arr_x, lgroup.arr_y2, side='right',
                           label= "%s: %s" % (fname, y2label), **popts)
            xmin, xmax = min(lgroup.arr_x), max(lgroup.arr_x)
            ppnl.axes.set_xlim((xmin, xmax), emit=True)
            ppnl.canvas.draw()
        else:
            ppnl.set_xlabel(xlabel)
            ppnl.set_ylabel(ylabel)
            ppnl.update_line(0, lgroup.arr_x, lgroup.arr_y1, draw=True,
                             update_limits=True)
            ax = ppnl.axes
            ppnl.user_limits[ax] = (min(lgroup.arr_x),  max(lgroup.arr_x),
                                    min(lgroup.arr_y1), max(lgroup.arr_y1))

            if y2expr != '':
                ppnl.set_y2label(y2label)
                ppnl.update_line(1, lgroup.arr_x, lgroup.arr_y2, side='right',
                                 draw=True, update_limits=True)
                ax = ppnl.get_right_axes()
                ppnl.user_limits[ax] = (min(lgroup.arr_x), max(lgroup.arr_x),
                                        min(lgroup.arr_y2), max(lgroup.arr_y2))

        self.force_newplot = False


    def createMenus(self):
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        pmenu = wx.Menu()
        omenu = wx.Menu()

        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

        self.menubar.Append(fmenu, "&File")

        fmenu.AppendSeparator()
        add_menu(self, fmenu, "&Copy\tCtrl+C",  "Copy to Clipboard", self.onClipboard)
        add_menu(self, fmenu, "&Save\tCtrl+S", "Save Figure",   self.onSaveFig)
        add_menu(self, fmenu, "&Print\tCtrl+P", "Print Figure", self.onPrint)
        add_menu(self, fmenu, "Page Setup", "Print Page Setup", self.onPrintSetup)
        add_menu(self, fmenu, "Preview", "Print Preview",       self.onPrintPreview)
        #

        add_menu(self, omenu, "Enable Move To Position", "Force Enable of Move To Position",
                 self.onForceEnableMoveTo)

        add_menu(self, pmenu, "Force Replot\tCtrl+F", "Replot", self.onForceReplot)

        add_menu(self, pmenu, "Configure\tCtrl+K",
                 "Configure Plot", self.onConfigurePlot)
        add_menu(self, pmenu, "Unzoom\tCtrl+Z", "Unzoom Plot", self.unzoom)
        pmenu.AppendSeparator()
        add_menu(self, pmenu, "Toggle Legend\tCtrl+L",
                 "Toggle Legend on Plot", self.onToggleLegend)
        add_menu(self, pmenu, "Toggle Grid\tCtrl+G",
                 "Toggle Grid on Plot", self.onToggleGrid)

        self.menubar.Append(omenu, "Options")
        self.menubar.Append(pmenu, "Plot")
        self.SetMenuBar(self.menubar)

    def onForceEnableMoveTo(self, evt=None):
        self.moveto_btn.Enable()

    def onForceReplot(self, evt=None):
        self.force_newplot = True
        self.onPlot()

    def onClipboard(self, evt=None):
        self.plotpanel.canvas.Copy_to_Clipboard(evt)

    def onSaveFig(self, evt=None):
        self.plotpanel.save_figure(event=evt,
                                   transparent=True, dpi=300)

    def onPrint(self, evt=None):
        self.plotpanel.Print(evt)

    def onPrintSetup(self, evt=None):
        self.plotpanel.PrintSetup(evt)

    def onPrintPreview(self, evt=None):
        self.plotpanel.PrintPreview(evt)

    def onConfigurePlot(self, evt=None):
        self.plotpanel.configure(evt)

    def unzoom(self, event=None, **kwargs):
        ppnl = self.plotpanel
        ppnl.conf.zoom_lims = []
        ppnl.user_limits = {}
        ppnl.user_limits[ppnl.axes] = (None, None, None, None)
        ppnl.user_limits[ppnl.get_right_axes()] = (None, None, None, None)
        self.force_newplot = True
        self.onPlot()

    def onToggleLegend(self, evt=None):
        self.plotpanel.toggle_legend(evt)

    def onToggleGrid(self, evt=None):
        self.plotpanel.toggle_grid(evt)

    def onAbout(self,evt):
        dlg = wx.MessageDialog(self, self._about,"About Epics StepScan",
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def onClose(self, evt=None):
        self.scantimer.Stop()
        self.Destroy()
Example #41
0
    def __init__(self,
                 parent,
                 filename=None,
                 read_ok_cb=None,
                 size=(725, 450),
                 _larch=None):
        self.parent = parent
        self.filename = filename
        self.larch = _larch
        self.read_ok_cb = read_ok_cb

        self.colors = GUIColors()

        wx.Frame.__init__(self, parent, -1, size=size, style=FRAMESTYLE)
        splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
        splitter.SetMinimumPaneSize(200)

        leftpanel = wx.Panel(splitter)
        ltop = wx.Panel(leftpanel)

        sel_none = Button(ltop,
                          'Select None',
                          size=(100, 30),
                          action=self.onSelNone)
        sel_all = Button(ltop,
                         'Select All',
                         size=(100, 30),
                         action=self.onSelAll)
        sel_imp = Button(ltop,
                         'Import Selected Groups',
                         size=(200, 30),
                         action=self.onOK)

        self.select_imported = sel_imp
        self.select_imported.Disable()

        self.grouplist = FileCheckList(leftpanel,
                                       select_action=self.onShowGroup)
        self.grouplist.SetBackgroundColour(wx.Colour(255, 255, 255))

        tsizer = wx.GridBagSizer(2, 2)
        tsizer.Add(sel_all, (0, 0), (1, 1), LCEN, 0)
        tsizer.Add(sel_none, (0, 1), (1, 1), LCEN, 0)
        tsizer.Add(sel_imp, (1, 0), (1, 2), LCEN, 0)

        pack(ltop, tsizer)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(ltop, 0, LCEN | wx.GROW, 1)
        sizer.Add(self.grouplist, 1, LCEN | wx.GROW | wx.ALL, 1)
        pack(leftpanel, sizer)

        # right hand side
        rightpanel = wx.Panel(splitter)

        self.SetTitle("Reading Athena Project '%s'" % self.filename)
        self.title = SimpleText(rightpanel,
                                self.filename,
                                font=Font(13),
                                colour=self.colors.title,
                                style=LCEN)

        self.plotpanel = PlotPanel(rightpanel, messenger=self.plot_messages)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.title, 0, LCEN, 2)
        sizer.Add(self.plotpanel, 0, LCEN, 2)
        pack(rightpanel, sizer)

        splitter.SplitVertically(leftpanel, rightpanel, 1)

        self.statusbar = self.CreateStatusBar(2, 0)
        self.statusbar.SetStatusWidths([-3, -1])
        statusbar_fields = [self.filename, ""]
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.all = read_athena(self.filename,
                               do_bkg=False,
                               do_fft=False,
                               with_journal=False,
                               _larch=_larch)
        for item in dir(self.all):
            self.grouplist.Append(item)
        self.Show()
        self.Raise()
Example #42
0
    def createDetailsPanel(self, parent):
        mainpanel = wx.Panel(parent)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        panel = wx.Panel(mainpanel)
        sizer = wx.GridBagSizer(8, 7)

        self.title = SimpleText(panel, 'initializing...')
        ir = 0
        sizer.Add(self.title, (ir, 0), (1, 6), LCEN, 2)
        # x-axis

        self.xarr = add_choice(panel,
                               choices=[],
                               action=self.onYchoice,
                               size=(120, -1))
        self.xop = add_choice(panel,
                              choices=('', 'log'),
                              action=self.onYchoice,
                              size=(75, -1))

        ir += 1
        sizer.Add(SimpleText(panel, 'X = '), (ir, 0), (1, 1), CEN, 0)
        sizer.Add(self.xop, (ir, 1), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, '('), (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.xarr, (ir, 3), (1, 1), RCEN, 0)
        sizer.Add(SimpleText(panel, ')'), (ir, 4), (1, 1), CEN, 0)

        self.yops = [[], []]
        self.yarr = [[], []]

        for opts, sel, siz in ((PRE_OPS, 0, 75), (ARR_OPS, 3, 50), (ARR_OPS, 3,
                                                                    50)):
            w1 = add_choice(panel,
                            choices=opts,
                            action=self.onYchoice,
                            size=(siz, -1))
            w1.SetSelection(sel)
            self.yops[0].append(w1)

            w2 = add_choice(panel,
                            choices=opts,
                            action=self.onYchoice,
                            size=(siz, -1))
            w2.SetSelection(sel)
            self.yops[1].append(w2)

        opts = {'choices': [], 'size': (120, -1), 'action': self.onYchoice}
        for i in range(3):
            self.yarr[0].append(add_choice(panel, **opts))
            self.yarr[1].append(add_choice(panel, **opts))

        for i in range(2):
            ir += 1
            label = 'Y%i = ' % (i + 1)
            sizer.Add(SimpleText(panel, label), (ir, 0), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][0], (ir, 1), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, '[('), (ir, 2), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][0], (ir, 3), (1, 1), CEN, 0)
            sizer.Add(self.yops[i][1], (ir, 4), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][1], (ir, 5), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ')'), (ir, 6), (1, 1), LCEN, 0)
            sizer.Add(self.yops[i][2], (ir, 7), (1, 1), CEN, 0)
            sizer.Add(self.yarr[i][2], (ir, 8), (1, 1), CEN, 0)
            sizer.Add(SimpleText(panel, ']'), (ir, 9), (1, 1), LCEN, 0)
        ir += 1
        # sizer.Add(SimpleText(panel, ' New Plot: '),  (ir,   0), (1, 3), LCEN, 0)
        # sizer.Add(SimpleText(panel, ' Over Plot: '), (ir+1, 0), (1, 3), LCEN, 0)

        for jr, ic, dc, opt, ttl in ((0, 0, 4, 'win old',
                                      'New Plot, This Window'),
                                     (0, 4, 2, 'win new',
                                      'New Plot, New Window'),
                                     (1, 0, 4, 'over left',
                                      'Over Plot, Left Axis'),
                                     (1, 4, 2, 'over right',
                                      'Over Plot, Right Axis')):
            sizer.Add(
                add_button(panel,
                           ttl,
                           size=(165, -1),
                           action=Closure(self.onPlot, opt=opt)),
                (ir + jr, ic), (1, dc), LCEN, 2)

        ir += 2
        self.dtcorr = check(panel, default=True, label='correct deadtime?')
        sizer.Add(self.dtcorr, (ir, 0), (1, 3), LCEN, 0)
        ir += 1
        sizer.Add(SimpleText(panel, ''), (ir, 0), (1, 3), LCEN, 0)

        pack(panel, sizer)

        #         self.nb = flat_nb.FlatNotebook(mainpanel, -1, agwStyle=FNB_STYLE)
        #
        #         self.nb.SetTabAreaColour(wx.Colour(248,248,240))
        #         self.nb.SetActiveTabColour(wx.Colour(254,254,195))
        #
        #         self.nb.SetNonActiveTabTextColour(wx.Colour(40,40,180))
        #         self.nb.SetActiveTabTextColour(wx.Colour(80,0,0))
        #
        #         self.xas_panel = self.CreateXASPanel(self.nb) # mainpanel)
        #         self.fit_panel = self.CreateFitPanel(self.nb) # mainpanel)
        #
        #         self.nb.AddPage(self.fit_panel, ' General Analysis ', True)
        #         self.nb.AddPage(self.xas_panel, ' XAS Processing ',   True)

        mainsizer.Add(panel, 0, LCEN | wx.EXPAND, 2)
        self.plotpanel = PlotPanel(mainpanel, size=(500, 670))
        self.plotpanel.messenger = self.write_message

        bgcol = panel.GetBackgroundColour()
        bgcol = (bgcol[0] / 255., bgcol[1] / 255., bgcol[2] / 255.)
        self.plotpanel.canvas.figure.set_facecolor(bgcol)

        mainsizer.Add(self.plotpanel, 1, wx.GROW | wx.ALL, 1)

        # mainsizer.Add(self.nb, 1, LCEN|wx.EXPAND, 2)
        pack(mainpanel, mainsizer)

        return mainpanel
    def InitUI(self):
        panelRoot = wx.Panel(self)
        panelRootSizer = wx.BoxSizer(wx.VERTICAL)

        topSplitter = wx.SplitterWindow(panelRoot,
                                        style=wx.SP_LIVE_UPDATE | wx.SP_3DSASH)
        topVerticalSplitter = wx.SplitterWindow(topSplitter,
                                                style=wx.SP_LIVE_UPDATE
                                                | wx.SP_3DSASH)

        #############################################
        #   TOP-LEFT PANEL (STATUS AND CONTROLS)    #
        #############################################

        panelTopLeft = wx.Panel(topVerticalSplitter)
        panelTopLeftSizer = wx.BoxSizer(wx.VERTICAL)

        # create gauges and set initial values
        self.voltageGauge = wx.Gauge(panelTopLeft, -1,
                                     MAX_VOLTAGE - MIN_VOLTAGE, (0, 0),
                                     (250, 25))
        self.voltageGauge.SetValue(self.voltage - MIN_VOLTAGE)

        self.amperageGauge = wx.Gauge(panelTopLeft, -1,
                                      MAX_AMPERAGE - MIN_AMPERAGE, (0, 0),
                                      (250, 25))
        self.amperageGauge.SetValue(self.amperage - MIN_AMPERAGE)

        self.rpmGauge = wx.Gauge(panelTopLeft, -1, MAX_RPM - MIN_RPM, (0, 0),
                                 (250, 25))
        self.rpmGauge.SetValue(self.rpm - MIN_RPM)

        self.controllerTempGauge = wx.Gauge(
            panelTopLeft, -1, MAX_CONTROLLER_TEMP - MIN_CONTROLLER_TEMP,
            (0, 0), (250, 25))
        self.controllerTempGauge.SetValue(self.controllerTemp -
                                          MIN_CONTROLLER_TEMP)

        # create labels
        self.voltageLabel = wx.StaticText(
            panelTopLeft, -1, "Voltage (" + str(self.voltage) + ")")
        self.amperagLabel = wx.StaticText(
            panelTopLeft, -1, "Amperage (" + str(self.amperage) + ")")
        self.rpmLabel = wx.StaticText(panelTopLeft, -1,
                                      "RPM (" + str(self.rpm) + ")")
        self.controllerTempLabel = wx.StaticText(
            panelTopLeft, -1,
            "Controller Temperature (" + str(self.controllerTemp) + ")")

        # Add voltage Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.voltageLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.voltageGauge, 1, wx.ALIGN_CENTRE_HORIZONTAL)
        # Add amperage Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.amperagLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.amperageGauge, 1,
                              wx.ALIGN_CENTRE_HORIZONTAL)
        # Add RPM Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.rpmLabel, 0, wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.rpmGauge, 1, wx.ALIGN_CENTRE_HORIZONTAL)
        # Add controller temp Gauge and label to BoxSizer
        panelTopLeftSizer.Add(self.controllerTempLabel, 0,
                              wx.ALIGN_CENTRE_HORIZONTAL)
        panelTopLeftSizer.Add(self.controllerTempGauge, 1,
                              wx.ALIGN_CENTRE_HORIZONTAL)

        # Add BoxSizer to panel
        panelTopLeft.SetSizer(panelTopLeftSizer)

        ################################
        #   TOP-RIGHT PANEL (GRAPH)    #
        ################################

        panelTopRight = wx.Panel(topVerticalSplitter)
        panelTopRightSizer = wx.BoxSizer(wx.VERTICAL)

        # create top button bar
        topButtonPanel = wx.Panel(panelTopRight, -1)
        topButtonSizer = wx.BoxSizer(wx.HORIZONTAL)

        goalVoltageLabel = wx.StaticText(
            topButtonPanel, -1, '    End Goal Voltage Value (V):    ')
        self.goalEndVoltage = FloatCtrl(topButtonPanel,
                                        size=(100, -1),
                                        value=34.5,
                                        precision=1)
        endTimeLabel = wx.StaticText(topButtonPanel, -1,
                                     '    End Time (min):    ')
        self.endTime = FloatCtrl(topButtonPanel,
                                 size=(100, -1),
                                 value=120,
                                 precision=0)
        plotGoalVoltageButton = wx.Button(topButtonPanel,
                                          -1,
                                          'Plot Goal Voltage',
                                          size=(250, -1))
        plotGoalVoltageButton.Bind(wx.EVT_BUTTON, self.OnPlotGoalVoltage)

        topButtonSizer.Add(goalVoltageLabel)
        topButtonSizer.Add(self.goalEndVoltage)
        topButtonSizer.Add(endTimeLabel)
        topButtonSizer.Add(self.endTime)
        topButtonSizer.Add(plotGoalVoltageButton)

        topButtonPanel.SetSizer(topButtonSizer)
        topButtonSizer.Fit(topButtonPanel)

        # create plot panel

        self.plotPanel = PlotPanel(panelTopRight)

        # create bottom button bar

        bottomButtonPanel = wx.Panel(panelTopRight, -1)
        bottomButtonSizer = wx.BoxSizer(wx.HORIZONTAL)

        exportButton = wx.Button(bottomButtonPanel,
                                 -1,
                                 'Export Plot to CSV',
                                 size=(250, -1))
        exportButton.Bind(wx.EVT_BUTTON, self.ExportPlotDataToCSV)
        resetButton = wx.Button(bottomButtonPanel,
                                -1,
                                'Reset Graph',
                                size=(250, -1))
        resetButton.Bind(wx.EVT_BUTTON, self.ResetGraph)

        bottomButtonSizer.Add(exportButton, 1)
        bottomButtonSizer.Add(resetButton, 1)

        bottomButtonPanel.SetSizer(bottomButtonSizer)
        bottomButtonSizer.Fit(bottomButtonPanel)

        # Add panels to top right sizer
        panelTopRightSizer.Add(topButtonPanel, 0, wx.EXPAND | wx.ALL)
        panelTopRightSizer.Add(self.plotPanel, 1, wx.EXPAND | wx.ALL)
        panelTopRightSizer.Add(bottomButtonPanel, 0)

        # Add BoxSizer to panel
        panelTopRight.SetSizer(panelTopRightSizer)

        # add top panels to vertical splitter
        topVerticalSplitter.SplitVertically(panelTopLeft, panelTopRight)
        topVerticalSplitter.SetSashGravity(0.25)

        #############################################
        #   BOTTOM PANEL (LOG & TELEMETRY INPUT)    #
        #############################################

        panelBottom = wx.Panel(topSplitter)
        panelBottomSizer = wx.BoxSizer(wx.VERTICAL)

        self.logPane = LogPane(panelBottom)

        logPaneLabel = wx.StaticText(
            panelBottom,
            label="Telemetry Message Log (Last 100 messages shown):")
        logPaneLabel.SetFont(
            wx.Font(14, wx.FONTFAMILY_TELETYPE, wx.NORMAL, wx.BOLD))
        panelBottomSizer.Add(logPaneLabel, 0, wx.ALIGN_TOP)
        panelBottomSizer.Add(self.logPane, 1, wx.EXPAND | wx.ALL)

        panelBottom.SetSizer(panelBottomSizer)

        topSplitter.SplitHorizontally(topVerticalSplitter, panelBottom)
        topSplitter.SetSashGravity(0.75)

        panelRootSizer.Add(topSplitter, 1, wx.EXPAND | wx.ALL)
        panelRoot.SetSizer(panelRootSizer)
Example #44
0
class Fitting1DXRD(wx.Panel):
    '''
    Frame for housing all 1D XRD fitting widgets
    '''
    label='Fitting'
    def __init__(self,parent,owner=None,_larch=None):
        
        wx.Panel.__init__(self, parent)

        self.parent = parent
        self.owner = owner

        ## Default information
        self.xlabel       = 'q (A^-1)'
        self.xunits        = ['q','d']

        self.Panel1DFitting()
    

     
##############################################
#### PANEL DEFINITIONS
    def Panel1DFitting(self):
        '''
        Frame for housing all 1D XRD viewer widgets
        '''
        leftside  = self.LeftSidePanel(self)
        rightside = self.RightSidePanel(self)        

        panel1D = wx.BoxSizer(wx.HORIZONTAL)
        panel1D.Add(leftside,flag=wx.ALL,border=10)
        panel1D.Add(rightside,proportion=1,flag=wx.EXPAND|wx.ALL,border=10)

        self.SetSizer(panel1D)
    
    def Toolbox(self,panel):
        '''
        Frame for visual toolbox
        '''
        
        tlbx = wx.StaticBox(self,label='PLOT TOOLBOX')
        vbox = wx.StaticBoxSizer(tlbx,wx.VERTICAL)

        ###########################
        ## X-Scale
        hbox_xaxis = wx.BoxSizer(wx.HORIZONTAL)
        ttl_xaxis = wx.StaticText(self, label='X-SCALE')
        self.ch_xaxis = wx.Choice(self,choices=self.xunits)

        self.ch_xaxis.Bind(wx.EVT_CHOICE, self.checkXaxis)
    
        hbox_xaxis.Add(ttl_xaxis, flag=wx.RIGHT, border=8)
        hbox_xaxis.Add(self.ch_xaxis, flag=wx.EXPAND, border=8)
        vbox.Add(hbox_xaxis, flag=wx.ALL, border=10)

        ###########################
        ## Y-Scale
        hbox_yaxis = wx.BoxSizer(wx.HORIZONTAL)
        ttl_yaxis = wx.StaticText(self, label='Y-SCALE')
        yscales = ['linear','log']
        self.ch_yaxis = wx.Choice(self,choices=yscales)

        self.ch_yaxis.Bind(wx.EVT_CHOICE,   None)
    
        hbox_yaxis.Add(ttl_yaxis, flag=wx.RIGHT, border=8)
        hbox_yaxis.Add(self.ch_yaxis, flag=wx.EXPAND, border=8)
        vbox.Add(hbox_yaxis, flag=wx.ALL, border=10)
        
        return vbox

    def LeftSidePanel(self,panel):
        
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        plttools = self.Toolbox(self)
        
        vbox.Add(plttools,flag=wx.ALL,border=10)
        return vbox

    def RightSidePanel(self,panel):
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1DXRD(panel)
        btnbox = self.QuickButtons(panel)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        vbox.Add(btnbox,flag=wx.ALL|wx.ALIGN_RIGHT,border = 10)
        return vbox

    def QuickButtons(self,panel):
        buttonbox = wx.BoxSizer(wx.HORIZONTAL)
        btn_img = wx.Button(panel,label='SAVE FIGURE')
        btn_calib = wx.Button(panel,label='PLOT SETTINGS')
        btn_integ = wx.Button(panel,label='RESET PLOT')
        
        btn_img.Bind(wx.EVT_BUTTON,   self.onSAVEfig)
        btn_calib.Bind(wx.EVT_BUTTON, self.onPLOTset)
        btn_integ.Bind(wx.EVT_BUTTON, self.onRESETplot)
        
        buttonbox.Add(btn_img, flag=wx.ALL, border=8)
        buttonbox.Add(btn_calib, flag=wx.ALL, border=8)
        buttonbox.Add(btn_integ, flag=wx.ALL, border=8)
        return buttonbox


##############################################
#### PLOTPANEL FUNCTIONS
    def plot1DXRD(self,panel):
    
        self.plot1D = PlotPanel(panel,size=(1000, 500))
        self.plot1D.messenger = self.owner.write_message
        

        ## Set defaults for plotting  
        self.plot1D.set_ylabel('Intensity (a.u.)')
        self.plot1D.cursor_mode = 'zoom'
  
        ## trying to get this functionality into our gui
        ## mkak 2016.11.10      
#         interactive_legend().show()

    def onSAVEfig(self,event):
        self.plot1D.save_figure()
        
    def onPLOTset(self,event):
        self.plot1D.configure()
        
    def onRESETplot(self,event):
        self.plot1D.reset_config()

    def checkXaxis(self, event):
        
        if self.ch_xaxis.GetSelection() == 2:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = calc_q_to_2th(self.xy_data[plt_no*2],self.wavelength)
        elif self.ch_xaxis.GetSelection() == 1:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = calc_q_to_d(self.xy_data[plt_no*2])
        else:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = self.xy_data[plt_no*2]

        if self.ch_xaxis.GetSelection() == 2:
            self.xlabel = r'$2\Theta$'+r' $(^\circ)$'
        elif self.ch_xaxis.GetSelection() == 1:
            self.xlabel = 'd ($\AA$)'
        else:
            self.xlabel = 'q (1/$\AA$)'
         
        self.plot1D.set_xlabel(self.xlabel)
        self.updatePLOT()

    def updatePLOT(self):

        xmax,xmin,ymax,ymin = None,0,None,0
    
        if len(self.plotted_data) > 0:
            for plt_no in range(len(self.plotted_data)):

                i = plt_no*2
                j = i+1
 
                x = self.xy_plot[i]
                y = self.xy_plot[j]
                
                if xmax is None or xmax < max(x):
                    xmax = max(x)
                if xmin > min(x):
                    xmin = min(x)
                if ymax is None or ymax < max(y):
                    ymax = max(y)
                if ymin > min(y):
                    ymin = min(y)
                
                self.plot1D.update_line(plt_no,x,y)
            
            self.unzoom_all()
            self.plot1D.canvas.draw()
            
            if self.ch_xaxis.GetSelection() == 1:
                xmax = 5
            self.plot1D.set_xylims([xmin, xmax, ymin, ymax])

    def reset1Dscale(self,event):

        plt_no = self.ch_data.GetSelection()        
       
        self.xy_plot[(plt_no*2+1)] = self.xy_data[(plt_no*2+1)]
        self.plot1D.update_line(plt_no,self.xy_plot[(plt_no*2)],
                                       self.xy_plot[(plt_no*2+1)])
        self.plot1D.canvas.draw()
        self.unzoom_all()
        
        self.updatePLOT()
        self.xy_scale[plt_no] = max(self.xy_data[(plt_no*2+1)])
        self.entr_scale.SetValue(str(self.xy_scale[plt_no]))

####### BEGIN #######            
## THIS IS DIRECTLY FROM XRDDISPLAY.PY
## mkak 2016.11.11
    def unzoom_all(self, event=None):

        xmid, xrange, xmin, xmax = self._get1Dlims()

        self._set_xview(xmin, xmax)
        self.xview_range = None

    def _get1Dlims(self):
        xmin, xmax = self.plot1D.axes.get_xlim()
        xrange = xmax-xmin
        xmid   = (xmax+xmin)/2.0
        if self.x_for_zoom is not None:
            xmid = self.x_for_zoom
        return (xmid, xrange, xmin, xmax)

    def _set_xview(self, x1, x2, keep_zoom=False, pan=False):

        xmin,xmax = self.abs_limits()
        xrange = x2-x1
        x1 = max(xmin,x1)
        x2 = min(xmax,x2)

        if pan:
            if x2 == xmax:
                x1 = x2-xrange
            elif x1 == xmin:
                x2 = x1+xrange
        if not keep_zoom:
            self.x_for_zoom = (x1+x2)/2.0
        self.plot1D.axes.set_xlim((x1, x2))
        self.xview_range = [x1, x2]
        self.plot1D.canvas.draw()

    def abs_limits(self):
        if len(self.data_name) > 0:
            xmin, xmax = self.xy_plot[0].min(), self.xy_plot[0].max()
   
        return xmin,xmax
Example #45
0
class Viewer1DXRD(wx.Panel):
    '''
    Frame for housing all 1D XRD viewer widgets
    '''
    label='Viewer'
    def __init__(self,parent,owner=None,_larch=None):
        
        wx.Panel.__init__(self, parent)

        self.parent = parent
        self.owner = owner

        ## Default information
        self.data_name    = []
        self.xy_data      = []
        self.xy_plot      = []
        self.plotted_data = []
        self.xy_scale     = []
        self.wavelength   = None
        self.xlabel       = 'q (A^-1)'
        self.xunits        = ['q','d']

        self.cif_name     = []
        self.cif_data     = []
        self.cif_plot     = []
        self.plotted_cif  = []
        
        self.x_for_zoom = None


        self.Panel1DViewer()

##############################################
#### PANEL DEFINITIONS
    def Panel1DViewer(self):
        '''
        Frame for housing all 1D XRD viewer widgets
        '''
        leftside  = self.LeftSidePanel(self)
        rightside = self.RightSidePanel(self)        

        panel1D = wx.BoxSizer(wx.HORIZONTAL)
        panel1D.Add(leftside,flag=wx.ALL,border=10)
        panel1D.Add(rightside,proportion=1,flag=wx.EXPAND|wx.ALL,border=10)

        self.SetSizer(panel1D)
    
    def Toolbox(self,panel):
        '''
        Frame for visual toolbox
        '''
        
        tlbx = wx.StaticBox(self,label='PLOT TOOLBOX')
        vbox = wx.StaticBoxSizer(tlbx,wx.VERTICAL)

        ###########################
        ## X-Scale
        hbox_xaxis = wx.BoxSizer(wx.HORIZONTAL)
        ttl_xaxis = wx.StaticText(self, label='X-SCALE')
        self.ch_xaxis = wx.Choice(self,choices=self.xunits)

        self.ch_xaxis.Bind(wx.EVT_CHOICE, self.checkXaxis)
    
        hbox_xaxis.Add(ttl_xaxis, flag=wx.RIGHT, border=8)
        hbox_xaxis.Add(self.ch_xaxis, flag=wx.EXPAND, border=8)
        vbox.Add(hbox_xaxis, flag=wx.ALL, border=10)

        ###########################
        ## Y-Scale
        hbox_yaxis = wx.BoxSizer(wx.HORIZONTAL)
        ttl_yaxis = wx.StaticText(self, label='Y-SCALE')
        yscales = ['linear','log']
        self.ch_yaxis = wx.Choice(self,choices=yscales)

        self.ch_yaxis.Bind(wx.EVT_CHOICE,   None)
    
        hbox_yaxis.Add(ttl_yaxis, flag=wx.RIGHT, border=8)
        hbox_yaxis.Add(self.ch_yaxis, flag=wx.EXPAND, border=8)
        vbox.Add(hbox_yaxis, flag=wx.ALL, border=10)
        
        return vbox

    def DataBox(self,panel):
        '''
        Frame for data toolbox
        '''
        
        tlbx = wx.StaticBox(self,label='DATA TOOLBOX')
        vbox = wx.StaticBoxSizer(tlbx,wx.VERTICAL)


        ###########################
        ## DATA CHOICE

        self.ch_data = wx.Choice(self,choices=self.data_name)
        self.ch_data.Bind(wx.EVT_CHOICE,   self.onSELECT)
        vbox.Add(self.ch_data, flag=wx.EXPAND|wx.ALL, border=8)
    
        #self.ttl_data = wx.StaticText(self, label='')
        #vbox.Add(self.ttl_data, flag=wx.EXPAND|wx.ALL, border=8)

        ###########################

#         self.ck_bkgd = wx.CheckBox(self,label='BACKGROUND')
#         self.ck_smth = wx.CheckBox(self,label='SMOOTHING')
#         
#         self.ck_bkgd.Bind(wx.EVT_CHECKBOX,   None)
#         self.ck_smth.Bind(wx.EVT_CHECKBOX,   None)
# 
#         vbox.Add(self.ck_bkgd, flag=wx.ALL, border=8)
#         vbox.Add(self.ck_smth, flag=wx.ALL, border=8)
    
        ###########################
        ## Scale
        hbox_scl = wx.BoxSizer(wx.HORIZONTAL)
        ttl_scl = wx.StaticText(self, label='SCALE Y TO:')
        self.entr_scale = wx.TextCtrl(self,wx.TE_PROCESS_ENTER)
        btn_scale = wx.Button(self,label='set')

        btn_scale.Bind(wx.EVT_BUTTON, self.normalize1Ddata)
        
        hbox_scl.Add(ttl_scl, flag=wx.RIGHT, border=8)
        hbox_scl.Add(self.entr_scale, flag=wx.RIGHT, border=8)
        hbox_scl.Add(btn_scale, flag=wx.RIGHT, border=8)

        vbox.Add(hbox_scl, flag=wx.BOTTOM|wx.TOP, border=8)

        ###########################
        ## Hide/show and reset
        hbox_btns = wx.BoxSizer(wx.HORIZONTAL)
        
        btn_hide  = wx.Button(self,label='hide')
        btn_reset = wx.Button(self,label='reset')
        btn_rmv   = wx.Button(self,label='remove')
        
        btn_hide.Bind(wx.EVT_BUTTON,  self.hide1Ddata)
        btn_reset.Bind(wx.EVT_BUTTON, self.reset1Dscale)
        btn_rmv.Bind(wx.EVT_BUTTON,   self.remove1Ddata)

        btn_hide.Disable()
        btn_rmv.Disable()
        
        hbox_btns.Add(btn_reset, flag=wx.ALL, border=10)
        hbox_btns.Add(btn_hide,  flag=wx.ALL, border=10)
        hbox_btns.Add(btn_rmv,   flag=wx.ALL, border=10)
        vbox.Add(hbox_btns, flag=wx.ALL, border=10)
        return vbox   
        

        

    def AddPanel(self,panel):
    
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        
        btn_data = wx.Button(panel,label='ADD NEW DATA SET')
        btn_data.Bind(wx.EVT_BUTTON, self.loadXYFILE)

        btn_cif = wx.Button(panel,label='ADD NEW CIF')
        btn_cif.Bind(wx.EVT_BUTTON, self.loadCIF)
    
        hbox.Add(btn_data, flag=wx.ALL, border=8)
        hbox.Add(btn_cif, flag=wx.ALL, border=8)
        return hbox

    def LeftSidePanel(self,panel):
        
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        plttools = self.Toolbox(self)
        addbtns = self.AddPanel(self)
        dattools = self.DataBox(self)
        
        vbox.Add(plttools,flag=wx.ALL,border=10)
        vbox.Add(addbtns,flag=wx.ALL,border=10)
        vbox.Add(dattools,flag=wx.ALL,border=10)
        return vbox

    def RightSidePanel(self,panel):
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.plot1DXRD(panel)
        btnbox = self.QuickButtons(panel)
        vbox.Add(self.plot1D,proportion=1,flag=wx.ALL|wx.EXPAND,border = 10)
        vbox.Add(btnbox,flag=wx.ALL|wx.ALIGN_RIGHT,border = 10)
        return vbox

    def QuickButtons(self,panel):
        buttonbox = wx.BoxSizer(wx.HORIZONTAL)
        btn_img = wx.Button(panel,label='SAVE FIGURE')
        btn_calib = wx.Button(panel,label='PLOT SETTINGS')
        btn_integ = wx.Button(panel,label='RESET PLOT')
        
        btn_img.Bind(wx.EVT_BUTTON,   self.onSAVEfig)
        btn_calib.Bind(wx.EVT_BUTTON, self.onPLOTset)
        btn_integ.Bind(wx.EVT_BUTTON, self.onRESETplot)
        
        buttonbox.Add(btn_img, flag=wx.ALL, border=8)
        buttonbox.Add(btn_calib, flag=wx.ALL, border=8)
        buttonbox.Add(btn_integ, flag=wx.ALL, border=8)
        return buttonbox


##############################################
#### PLOTPANEL FUNCTIONS
    def plot1DXRD(self,panel):
    
        self.plot1D = PlotPanel(panel,size=(1000, 500))
        self.plot1D.messenger = self.owner.write_message
        

        ## Set defaults for plotting  
        self.plot1D.set_ylabel('Intensity (a.u.)')
        self.plot1D.cursor_mode = 'zoom'
  
        ## trying to get this functionality into our gui
        ## mkak 2016.11.10      
#         interactive_legend().show()

    def onSAVEfig(self,event):
        self.plot1D.save_figure()
        
    def onPLOTset(self,event):
        self.plot1D.configure()
        
    def onRESETplot(self,event):
        self.plot1D.reset_config()



##############################################
#### XRD PLOTTING FUNCTIONS
       
    def add1Ddata(self,x,y,name=None,cif=False,wavelength=None):
        
        plt_no = len(self.data_name)
        
        if cif:
            if name is None:
                name = 'cif %i' % plt_no
            else:
               name = 'cif: %s' % name
        else:
            if name is None:
                name = 'dataset %i' % plt_no
            else:
                name = 'data: %s' % name
                
        if wavelength is not None:
            self.addLAMBDA(wavelength)

        ## Add to data array lists
        self.data_name.append(name)
        self.xy_scale.append(max(y))
        self.xy_data.extend([x,y])

        ## redefine x,y based on scales
        self.xy_plot.extend([x,y])
       
        ## Add to plot       
        self.plotted_data.append(self.plot1D.oplot(x,y,label=name,show_legend=True))#,xlabel=self.xlabel))

        ## Use correct x-axis units
        self.checkXaxis(None)

        self.ch_data.Set(self.data_name)
        self.ch_data.SetStringSelection(name)
        
        ## Update toolbox panel, scale all cif to 1000
        if cif is True:
            self.entr_scale.SetValue('1000')
            self.normalize1Ddata(None)
        else:
            self.entr_scale.SetValue(str(self.xy_scale[plt_no]))

    def addLAMBDA(self,wavelength,units='m'):
        
        ## convert to units A
        if units == 'm':
            self.wavelength = wavelength*1e10 
        elif units == 'cm':
            self.wavelength = wavelength*1e8
        elif units == 'mm':
            self.wavelength = wavelength*1e7        
        elif units == 'um':
            self.wavelength = wavelength*1e4
        elif units == 'nm':
            self.wavelength = wavelength*1e1
        else: ## units 'A'        
            self.wavelength = wavelength

        self.xunits.append(u'2\u03B8')
        self.ch_xaxis.Set(self.xunits)

    def normalize1Ddata(self,event):
    
        plt_no = self.ch_data.GetSelection()
        self.xy_scale[plt_no] = float(self.entr_scale.GetValue())
        if self.xy_scale[plt_no] <= 0:
            self.xy_scale[plt_no] = max(self.xy_data[(plt_no*2+1)])
            self.entr_scale.SetValue(str(self.xy_scale[plt_no]))

        y = self.xy_data[(plt_no*2+1)]
        self.xy_plot[(plt_no*2+1)] = y/np.max(y) * self.xy_scale[plt_no]

        self.updatePLOT()
        

    def remove1Ddata(self,event):
        
        ## Needs pop up warning: "Do you really want to delete this data set from plotter?
        ## Current settings will not be saved."
        ## mkak 2016.11.10
        
        plt_no = self.ch_data.GetSelection()        
        print('EVENTUALLY, button will remove plot: %s' % self.data_name[plt_no])

        ## removing name from list works... do not activate till rest is working
        ## mkak 2016.11.10
#         self.data_name.remove(self.data_name[plt_no])
#         self.ch_data.Set(self.data_name)

    def hide1Ddata(self,event):

        plt_no = self.ch_data.GetSelection()        
        print('EVENTUALLY, button will hide plot: %s' % self.data_name[plt_no])

    def onSELECT(self,event):
    
        data_str = self.ch_data.GetString(self.ch_data.GetSelection())
#         self.ttl_data.SetLabel('SELECTED: %s' % data_str)
        
        plt_no = self.ch_data.GetSelection()
        self.entr_scale.SetValue(str(self.xy_scale[plt_no]))

    def checkXaxis(self, event):
        
        if self.ch_xaxis.GetSelection() == 2:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = calc_q_to_2th(self.xy_data[plt_no*2],self.wavelength)
        elif self.ch_xaxis.GetSelection() == 1:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = calc_q_to_d(self.xy_data[plt_no*2])
        else:
            for plt_no in range(len(self.plotted_data)):
                self.xy_plot[plt_no*2] = self.xy_data[plt_no*2]

        if self.ch_xaxis.GetSelection() == 2:
            self.xlabel = r'$2\Theta$'+r' $(^\circ)$'
        elif self.ch_xaxis.GetSelection() == 1:
            self.xlabel = 'd ($\AA$)'
        else:
            self.xlabel = 'q (1/$\AA$)'
         
        self.plot1D.set_xlabel(self.xlabel)
        self.updatePLOT()

    def updatePLOT(self):

        xmax,xmin,ymax,ymin = None,0,None,0
    
        if len(self.plotted_data) > 0:
            for plt_no in range(len(self.plotted_data)):

                i = plt_no*2
                j = i+1
 
                x = self.xy_plot[i]
                y = self.xy_plot[j]
                
                if xmax is None or xmax < max(x):
                    xmax = max(x)
                if xmin > min(x):
                    xmin = min(x)
                if ymax is None or ymax < max(y):
                    ymax = max(y)
                if ymin > min(y):
                    ymin = min(y)
                
                self.plot1D.update_line(plt_no,x,y)
            
            self.unzoom_all()
            self.plot1D.canvas.draw()
            
            if self.ch_xaxis.GetSelection() == 1:
                xmax = 5
            self.plot1D.set_xylims([xmin, xmax, ymin, ymax])

    def reset1Dscale(self,event):

        plt_no = self.ch_data.GetSelection()        
       
        self.xy_plot[(plt_no*2+1)] = self.xy_data[(plt_no*2+1)]
        self.plot1D.update_line(plt_no,self.xy_plot[(plt_no*2)],
                                       self.xy_plot[(plt_no*2+1)])
        self.plot1D.canvas.draw()
        self.unzoom_all()
        
        self.updatePLOT()
        self.xy_scale[plt_no] = max(self.xy_data[(plt_no*2+1)])
        self.entr_scale.SetValue(str(self.xy_scale[plt_no]))

####### BEGIN #######            
## THIS IS DIRECTLY FROM XRDDISPLAY.PY
## mkak 2016.11.11
    def unzoom_all(self, event=None):

        xmid, xrange, xmin, xmax = self._get1Dlims()

        self._set_xview(xmin, xmax)
        self.xview_range = None

    def _get1Dlims(self):
        xmin, xmax = self.plot1D.axes.get_xlim()
        xrange = xmax-xmin
        xmid   = (xmax+xmin)/2.0
        if self.x_for_zoom is not None:
            xmid = self.x_for_zoom
        return (xmid, xrange, xmin, xmax)

    def _set_xview(self, x1, x2, keep_zoom=False, pan=False):

        xmin,xmax = self.abs_limits()
        xrange = x2-x1
        x1 = max(xmin,x1)
        x2 = min(xmax,x2)

        if pan:
            if x2 == xmax:
                x1 = x2-xrange
            elif x1 == xmin:
                x2 = x1+xrange
        if not keep_zoom:
            self.x_for_zoom = (x1+x2)/2.0
        self.plot1D.axes.set_xlim((x1, x2))
        self.xview_range = [x1, x2]
        self.plot1D.canvas.draw()

    def abs_limits(self):
        if len(self.data_name) > 0:
            xmin, xmax = self.xy_plot[0].min(), self.xy_plot[0].max()
   
        return xmin,xmax
#######  END  #######
       

##############################################
#### XRD FILE OPENING/SAVING 
    def loadXYFILE(self,event):
    
        wildcards = 'XRD data file (*.xy)|*.xy|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, message='Choose 1D XRD data file',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards, style=wx.FD_OPEN)

        path, read = None, False
        if dlg.ShowModal() == wx.ID_OK:
            read = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()
        
        if read:
            try:
                x,y = xy_file_reader(path)

                self.add1Ddata(x,y,name=os.path.split(path)[-1])
            except:
               print('incorrect xy file format: %s' % os.path.split(path)[-1])



    def saveXYFILE(self,event):
        wildcards = 'XRD data file (*.xy)|*.xy|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, 'Save data as...',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards,
                           style=wx.SAVE|wx.OVERWRITE_PROMPT)

        path, save = None, False
        if dlg.ShowModal() == wx.ID_OK:
            save = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()
        
        if save:
            ## mkak 2016.11.16
            print('need to write something to save data - like pyFAI does?')

    def loadCIF(self,event):
    
        wildcards = 'XRD cifile (*.cif)|*.cif|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, message='Choose CIF',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards, style=wx.FD_OPEN)

        path, read = None, False
        if dlg.ShowModal() == wx.ID_OK:
            read = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()
        
        if read:
            cifile = os.path.split(path)[-1]

            try:
                cif = xu.materials.Crystal.fromCIF(path)
            except:
                print('incorrect file format: %s' % os.path.split(path)[-1])
                return

            ## generate hkl list
            hkllist = []
            maxhkl = 8
            for i in range(-maxhkl,maxhkl+1):
                for j in range(-maxhkl,maxhkl+1):
                    for k in range(-maxhkl,maxhkl+1):
                        if i+j+k > 0: # as long as h,k,l all positive, eliminates 0,0,0
                            hkllist.append([i,j,k])
            
            hc = constants.value(u'Planck constant in eV s') * \
                       constants.value(u'speed of light in vacuum') * 1e-3 ## units: keV-m

            if self.wavelength is not None:
                qlist = cif.Q(hkllist)
                Flist = cif.StructureFactorForQ(qlist,(hc/(self.wavelength*(1e-10))*1e3))
            
                Fall = []
                qall = []
                hklall = []
                for i,hkl in enumerate(hkllist):
                    if np.abs(Flist[i]) > 0.01:
                        Fadd = np.abs(Flist[i])
                        qadd = np.linalg.norm(qlist[i])
                        if qadd not in qall and qadd < 6:
                            Fall.extend((0,Fadd,0))
                            qall.extend((qadd,qadd,qadd))
                if np.shape(Fall)[0] > 0:
                    Fall = np.array(Fall)
                    qall = np.array(qall)
                    self.add1Ddata(qall,Fall,name=os.path.split(path)[-1],cif=True)
                else:
                    print('Could not calculate real structure factors.')
            else:
                print('Wavelength/energy must be specified for structure factor calculations.')

    def openPONI(self,event):
             
        wildcards = 'pyFAI calibration file (*.poni)|*.poni|All files (*.*)|*.*'
        dlg = wx.FileDialog(self, message='Choose pyFAI calibration file',
                           defaultDir=os.getcwd(),
                           wildcard=wildcards, style=wx.FD_OPEN)

        path, read = None, False
        if dlg.ShowModal() == wx.ID_OK:
            read = True
            path = dlg.GetPath().replace('\\', '/')
        dlg.Destroy()
        
        if read:

            try:
                print('Loading calibration file: %s' % path)
                ai = pyFAI.load(path)
            except:
                print('Not recognized as a pyFAI calibration file.')
                return

            self.addLAMBDA(ai._wavelength,units='m')

    def setLAMBDA(self,event):

        dlg = SetLambdaDialog()

        path, okay = None, False
        if dlg.ShowModal() == wx.ID_OK:
            okay = True
            wavelength = dlg.wavelength
        dlg.Destroy()
        
        if okay:
            self.addLAMBDA(wavelength,units='A')
Example #46
0
class SectoinPointDefsPanel (SectionPointDefsPanelBase):

    def __init__(self, parent):
        SectionPointDefsPanelBase.__init__(self, parent)
        # 用于存放 solve之后的值
        self._args = dict()
        self.point_list = list()

        # 这是一个复连通的全局变量
        self.MP = MultiConnectPoly()
        # 再来一个复合截面的全局变量
        self.Comp = compoundSection()

        # 仅仅只是初始化了画布
        self.plotpanel = PlotPanel(self.m_panel1, size=(300, 300), fontsize=5)
        self.plotpanel.BuildPanel()

    def m_btn_InsertOnButtonClick( self, event ):
        # 将input进来的点填入复连通截面中,并填入buffet数据中
        x = self.m_textCtrl8.Value
        y = self.m_textCtrl9.Value

        p = Point(x, y)
        self.point_list.append(p)

        string = '(' + x + ',' + y + ')'
        self.m_listBox2.Append(string)

    def btn_addMultiPropOnButtonClick( self, event ):
        # 默认第一个是放进Outer的,后面来的就放在inner里
        if len(self.MP.outerLoop) == 0 :
            _args = self.point_list
            self.MP.setOuterLoop(*_args)
        else:
            _args = self.point_list
            self.MP.addInnerLoop(*_args)

        # procedure -- remove all items of list,as well as the data of point list
        self.m_listBox2.Clear()
        self.point_list = []

        Path = DrawGeometry(self.MP)
        Path.Draw()

        self.plotpanel.clear()
        for i in Path._paths:
                m,n=zip(*i)
                self.plotpanel.oplot(m,n,fullbox=False,axes_style='open')
        for i in Path._dimen:
            m, n = zip(*i)
            self.plotpanel.oplot(m,n,fullbox=False,axes_style='open', linewidth=1, color='green')
        # 遍历字典,画上标注
        for key, value in Path._text.items():
            x = key[0]
            y = key[1]
            self.plotpanel.add_text(str(value), x, y, size=4)

    def btn_genCompOnButtonClick( self, event ):
        # 如果有2个复连通的话就把他们同时画出来。然后直接计算,边上再添加一个数据清空的btn

        self.ShowResult(self.Comp)

        Comp_Path = DrawGeometry(self.Comp)
        Comp_Path.Draw()

        self.plotpanel.clear()
        for i in Comp_Path._paths:
                m,n=zip(*i)
                self.plotpanel.oplot(m,n,fullbox=False,axes_style='open')
        for i in Comp_Path._dimen:
            m, n = zip(*i)
            self.plotpanel.oplot(m,n,fullbox=False,axes_style='open', linewidth=1, color='green')
        # 遍历字典,画上标注
        for key, value in Comp_Path._text.items():
            x = key[0]
            y = key[1]
            self.plotpanel.add_text(str(value), x, y, size=4)

    def ShowResult(self, section):
        geo = GeoCalculator(section)
        geo.Solve()
        self._args = geo._args
        if "Area" in self._args:
            if abs(self._args['Area']) < 0.0000001:
                res = 0
            else:
                res = self._args['Area']
            self.m_propertyGridItem2.SetValue(str(res))
        if "Sx" in self._args:
            #if abs(self._args['Sx']) < 0.0000001:
               # res = 0
            #else:
            res = self._args['Sx']
            self.m_propertyGridItem3.SetValue(str(res))
        if "Sy" in self._args:
            #if abs(self._args['Sy']) < 0.0000001:
                #res = 0
            #else:
            res = self._args['Sy']
            self.m_propertyGridItem42.SetValue(str(res))
        if "Ix" in self._args:
            if abs(self._args['Ix']) < 0.0000001:
                res = 0
            else:
                res = self._args['Ix']
            self.m_propertyGridItem4.SetValue(str(res))
        if "Iy" in self._args:
            if abs(self._args['Iy']) < 0.0000001:
                res = 0
            else:
                res = self._args['Iy']
            self.m_propertyGridItem5.SetValue(str(res))
        if "Ixy" in self._args:
            #if abs(self._args['Ixy']) < 0.0000001:
                #res = 0
            #else:
            res = self._args['Ixy']
            self.m_propertyGridItem7.SetValue(str(res))
        if "centroid" in self._args:
            res = self._args['centroid']

            #if abs(res[0]) < 0.0000001:
                #res = [0, res[1]]
            #if abs(res[1]) < 0.0000001:
                #res = [res[0], 0]
            self.m_propertyGridItem8.SetValue(str(res))
        if "tan_alfa" in self._args:
            #if abs(self._args['tan_alfa']) < 0.0000001:
                #res = 0
            #else:
            res = self._args['tan_alfa']

            self.m_propertyGridItem9.SetValue(str(res))
        if "ix" in self._args:
            if abs(self._args['ix']) < 0.0000001:
                res = 0
            else:
                res = self._args['ix']
            self.m_propertyGridItem61.SetValue(str(res))
        if "iy" in self._args:
            if abs(self._args['iy']) < 0.0000001:
                res = 0
            else:
                res = self._args['iy']
            self.m_propertyGridItem62.SetValue(str(res))

    def showItemOnDClick( self, event ):
        print 'double _click'
        n = self.m_listBox3.GetSelection()
        multisection = self.Comp.dataResource[n]

        self.ShowResult(multisection)

        Path = DrawGeometry(multisection)
        Path.Draw()

        self.plotpanel.clear()
        for i in Path._paths:
                m,n=zip(*i)
                self.plotpanel.oplot(m,n,fullbox=False,axes_style='open')
        for i in Path._dimen:
            m, n = zip(*i)
            self.plotpanel.oplot(m,n,fullbox=False,axes_style='open', linewidth=1, color='green')
        # 遍历字典,画上标注
        for key, value in Path._text.items():
            x = key[0]
            y = key[1]
            self.plotpanel.add_text(str(value), x, y, size=4)

    def btn_genMultiPropOnButtonClick( self, event ):
        # 将MP放进来,然后清空,图像也清空
        self.Comp.addToSections(self.MP)
        n = len(self.Comp.dataResource)
        string = '第' + str(n) + '个截面'
        self.m_listBox3.Append(string)
        self.plotpanel.clear()
        self.MP = MultiConnectPoly()

    def btn_DataClearOnClickButton( self, event ):
        self.MP = MultiConnectPoly()
        self.Comp = compoundSection()
        self.m_listBox3.Clear()
        self.plotpanel.BuildPanel()
        self.m_textCtrl8.SetValue("")
        self.m_textCtrl9.SetValue("")
        self.m_propertyGridItem2.SetValue('0')
        self.m_propertyGridItem3.SetValue('0')
        self.m_propertyGridItem42.SetValue('0')
        self.m_propertyGridItem4.SetValue('0')
        self.m_propertyGridItem5.SetValue('0')
        self.m_propertyGridItem7.SetValue('0')
        self.m_propertyGridItem8.SetValue('[0,0]')
        self.m_propertyGridItem9.SetValue('0')
        self.m_propertyGridItem61.SetValue('0')
        self.m_propertyGridItem62.SetValue('0')

    def del_OnRightClick( self, event ):
        n = self.m_listBox2.GetSelection()
        self.m_listBox2.Delete(n)
        self.point_list.pop(n)
        # 还要把listpoint里的去掉

    def btn_PrintDataOnclick( self, event ):
        # procedure 1:生成UI2.png,2:
        path = os.path.abspath(os.curdir)+'//section.png'
        if hasattr(self, 'fig'):
            self.plotpanel.fig.savefig(path, transparent=False, dpi=300)
        else:
            self.plotpanel.canvas.print_figure(path, transparent=False, dpi=300)
        if (path.find(self.plotpanel.launch_dir) ==  0):
            path = path[len(self.plotpanel.launch_dir)+1:]
        self.plotpanel.write_message('Saved plot to %s' % path)

        self.filePrint()

    def filePrint(self):
        # Create an new Excel file and add a worksheet.
        workbook = xlsxwriter.Workbook('reportData.xlsx')
        worksheet = workbook.add_worksheet()

        # Widen the first column to make the text clearer.
        worksheet.set_column('A:A', 15)
        worksheet.set_column('B:B', 15)

        ID = self.__getcurrentTimeID()

        worksheet.write('A2', 'ID:')
        worksheet.write('B2', ID)

        worksheet.write('A3', 'Area:')
        worksheet.write('B3', self._args['Area'])

        worksheet.write('A4', 'Sx')
        worksheet.write('B4', self._args['Sx'])

        worksheet.write('A5', 'Sy')
        worksheet.write('B5', self._args['Sy'])

        worksheet.write('A6', 'Ix')
        worksheet.write('B6', self._args['Ix'])

        worksheet.write('A7', 'Iy')
        worksheet.write('B7', self._args['Iy'])

        worksheet.write('A8', 'Ixy')
        worksheet.write('B8', self._args['Ixy'])

        worksheet.write('A9', 'centroid')
        worksheet.write('B9', str(self._args['centroid']))

        worksheet.write('A10', 'tan_alfa')
        worksheet.write('B10', str(self._args['tan_alfa']))

        worksheet.write('A11', 'ix')
        worksheet.write('B11', self._args['ix'])

        worksheet.write('A12', 'iy')
        worksheet.write('B12', self._args['iy'])

        worksheet.insert_image('F2', 'section.png')

        workbook.close()

    def __getcurrentTimeID(self):
        currenttime = datetime.datetime.now()
        currenttime = str(currenttime.isoformat())
        currenttime = currenttime[0:len(currenttime)-6]
        for c in '-:.T': # "
            currenttime = currenttime.replace(c, '')

        return currenttime

    def btn_insertToLibOnButtonClick( self, event ):
        # 将该信息存放到库文件中。
        # workbook = xlsxwriter.Workbook('Library.xlsx')
        # 两个步骤:1把section的图片save到lib中,并改名为ID.png
        # 存入数据库。只有打印的时候才有文件。一次性打印出来。

        path = os.path.abspath(os.curdir)+'//section.png'
        if hasattr(self, 'fig'):
            self.plotpanel.fig.savefig(path, transparent=False, dpi=300)
        else:
            self.plotpanel.canvas.print_figure(path, transparent=False, dpi=300)
        if (path.find(self.plotpanel.launch_dir) ==  0):
            path = path[len(self.plotpanel.launch_dir)+1:]
        self.plotpanel.write_message('Saved plot to %s' % path)

        ID = self.__getcurrentTimeID()

        ImageURL = ID+'.png'

        lib = SectionLibrary()

        lib.addSection(ID,ImageURL,self._args)

        # 然后再把图片存到ImageLIB中
        shutil.copy('section.png',"..\\ImageLib\\"+ImageURL)

        # 然后再update一下存放着所有的信息的文件。
        # self.__updateLibFile(lib)

    def __updateLibFile(self,lib):
        workbook = xlsxwriter.Workbook('LibInfo.xlsx')
        worksheet = workbook.add_worksheet()
        worksheet.set_column('A:A', 15)
        worksheet.set_column('B:B', 15)

        # 我要获取info
        info = lib.selectAllSection()

        self.__worksheet_write(worksheet,info)

        workbook.close()

    def __worksheet_write(self,ws,info):
        count = 0
        for singleSec in info:
            # 计数
            ws.write('A'+ str(count*15+1), 'ID')
            ws.write('B'+ str(count*15+1), singleSec[0])

            ws.insert_image('F'+str(count*15+1), "..\\ImageLib\\" + singleSec[1])

            ws.write('A'+ str(count*15+2), 'Area')
            ws.write('B'+ str(count*15+2), singleSec[2])

            ws.write('A'+ str(count*15+3), 'Sx')
            ws.write('B'+ str(count*15+3), singleSec[3])

            ws.write('A'+ str(count*15+4), 'Sy')
            ws.write('B'+ str(count*15+4),singleSec[4])

            ws.write('A'+ str(count*15+5), 'Iy')
            ws.write('B'+ str(count*15+5),singleSec[5])

            ws.write('A'+ str(count*15+6), 'Ix')
            ws.write('B'+ str(count*15+6),singleSec[6])

            ws.write('A'+ str(count*15+7), 'Ixy')
            ws.write('B'+ str(count*15+7),singleSec[7])

            ws.write('A'+ str(count*15+8), 'Centroid')
            ws.write('B'+ str(count*15+8),singleSec[8])

            ws.write('A'+ str(count*15+9), 'Angle')
            ws.write('B'+ str(count*15+9),singleSec[9])

            ws.write('A'+ str(count*15+10), 'ix')
            ws.write('B'+ str(count*15+10),singleSec[10])

            ws.write('A'+ str(count*15+11), 'iy')
            ws.write('B'+ str(count*15+11), singleSec[11])

            count = count+1

    def checkLibOnButtonClick( self, event ):
        lib = SectionLibrary()
        self.__updateLibFile(lib)
        os.system("LibInfo.xlsx")