Exemplo n.º 1
0
    def __init__(self, parent, param, size=(80, -1), precision=4, **kws):
        self.param = param
        self.precision = precision
        wx.Panel.__init__(self, parent, -1)
        self.wids = Empty()

        self.wids.conf = wx.BitmapButton(self, -1, infoicon.GetBitmap(),
                                         size=(24, 24))

        self.wids.conf.Bind(wx.EVT_BUTTON, self.onConfigure)
        self.wids.conf.SetToolTip(wx.ToolTip("Configure Parameter"))
        self.wids.val = FloatCtrl(self, value=param.value,
                                  minval=param.min, maxval=param.max,
                                  precision=precision, size=size)

        self.wids.vary = Choice(self, choices=VARY_CHOICES,
                                action=self.onVaryChoice, size=(80, -1))

        vary_choice = 0
        if param.vary:
            vary_choice = 1
        elif param.expr is not None:
            vary_choice = 2
        self.wids.vary.SetSelection(vary_choice)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.wids.val,   0, LEFT|wx.TOP)
        sizer.Add(self.wids.vary,  0, LEFT|wx.TOP|wx.ALL)
        sizer.Add(self.wids.conf,  0, LEFT)
        pack(self, sizer)
Exemplo n.º 2
0
    def __init__(self, parent=None, prefix=None, det_type='ME-4',
                 ioc_type='Xspress3', nmca=4,
                 title='Select Epics MCA Detector'):
        if prefix is None:
            prefix = self.def_prefix
        if det_type not in self.det_types:
            det_type = self.det_types[0]

        wx.Dialog.__init__(self, parent, wx.ID_ANY, title=title)

        self.SetBackgroundColour((240, 240, 230))
        self.SetFont(Font(9))
        if parent is not None:
            self.SetFont(parent.GetFont())

        self.ioctype = Choice(self,size=(120, -1), choices=self.ioc_types)
        self.ioctype.SetStringSelection(ioc_type)

        self.dettype = Choice(self,size=(120, -1), choices=self.det_types)
        self.dettype.SetStringSelection(det_type)

        self.prefix = wx.TextCtrl(self, -1, prefix, size=(120, -1))
        self.nelem = FloatCtrl(self, value=nmca, precision=0, minval=1,
                               size=(120, -1))

        btnsizer = wx.StdDialogButtonSizer()

        if wx.Platform != "__WXMSW__":
            btn = wx.ContextHelpButton(self)
            btnsizer.AddButton(btn)

        btn = wx.Button(self, wx.ID_OK)
        btn.SetHelpText("Use this detector")
        btn.SetDefault()
        btnsizer.AddButton(btn)

        btn = wx.Button(self, wx.ID_CANCEL)
        btnsizer.AddButton(btn)
        btnsizer.Realize()

        hline = wx.StaticLine(self, size=(225, 3), style=wx.LI_HORIZONTAL)
        sty = LEFT|wx.ALIGN_CENTER_VERTICAL
        sizer = wx.GridBagSizer(5, 2)
        def txt(label):
            return SimpleText(self, label, size=(120, -1), style=LEFT)

        sizer.Add(txt('  Detector Type'),  (0, 0), (1, 1), sty, 2)
        sizer.Add(txt('  Uses Xspress3?'), (1, 0), (1, 1), sty, 2)
        sizer.Add(txt('  Epics Prefix'),  (2, 0), (1, 1), sty, 2)
        sizer.Add(txt('  # Elements'),    (3, 0), (1, 1), sty, 2)
        sizer.Add(self.dettype,         (0, 1), (1, 1), sty, 2)
        sizer.Add(self.ioctype,         (1, 1), (1, 1), sty, 2)
        sizer.Add(self.prefix,          (2, 1), (1, 1), sty, 2)
        sizer.Add(self.nelem,           (3, 1), (1, 1), sty, 2)

        sizer.Add(hline,                (4, 0), (1, 2), sty, 2)
        sizer.Add(btnsizer,             (5, 0), (1, 2), sty, 2)
        self.SetSizer(sizer)
        sizer.Fit(self)
Exemplo n.º 3
0
    def __init__(self, parent, calfile, **kws):

        self.parent = parent
        self.scandb = parent.scandb
        self.calfile = calfile
        poni = read_poni(calfile)

        wx.Dialog.__init__(self,
                           parent,
                           wx.ID_ANY,
                           size=(600, 525),
                           title="Read Calibration File")

        panel = GridPanel(self, ncols=3, nrows=4, pad=2, itemstyle=LCEN)

        self.wids = wids = {}

        wids['filename'] = SimpleText(panel, calfile)

        _p, fname = os.path.split(calfile)
        wids['calname'] = wx.TextCtrl(panel, value=fname, size=(350, -1))

        wids['ok'] = Button(panel, 'OK', size=(150, -1), action=self.on_apply)

        def add_text(text, dcol=1, newrow=True):
            panel.Add(SimpleText(panel, text), dcol=dcol, newrow=newrow)

        add_text('  Calibration file: ', newrow=False)
        panel.Add(wids['filename'], dcol=3)
        add_text('  Save as : ')
        panel.Add(wids['calname'], dcol=3)

        opts = dict(size=(90, -1), digits=5)
        for wname in ('wavelength', 'dist', 'pixel1', 'pixel2', 'poni1',
                      'poni2', 'rot1', 'rot2', 'rot3'):
            scale, units = self.conv[wname]
            val = scale * float(poni[wname])
            if wname == 'wavelength':
                energy = 12398.4193 / val
                units = '%s,  Energy=%.2f' % (units, energy)

            wids[wname] = FloatCtrl(panel,
                                    value=val,
                                    size=(100, -1),
                                    precision=4)
            wids[wname + '_units'] = SimpleText(panel, units)
            add_text('  %s:' % wname.title())
            panel.Add(wids[wname])
            panel.Add(wids[wname + '_units'])

        panel.Add((5, 5))
        panel.Add(wids['ok'], dcol=2, newrow=True)
        panel.pack()
Exemplo n.º 4
0
    def __init__(self,
                 parent,
                 param,
                 size=(80, -1),
                 show_name=False,
                 precision=4,
                 **kws):
        self.param = param
        self.precision = precision
        wx.Panel.__init__(self, parent, -1)
        self.wids = Empty()

        self.wids.val = FloatCtrl(self,
                                  value=param.value,
                                  minval=param.min,
                                  maxval=param.max,
                                  precision=precision,
                                  size=size)

        self.wids.name = None
        self.wids.edit = wx.Button(self, label='edit', size=(45, 25))
        self.wids.edit.Bind(wx.EVT_BUTTON, self.onConfigure)
        self.wids.edit.SetToolTip(wx.ToolTip("Configure Parameter"))

        self.wids.vary = Choice(self,
                                choices=VARY_CHOICES,
                                action=self.onVaryChoice,
                                size=(80, -1))

        vary_choice = 0
        if param.vary:
            vary_choice = 1
        elif param.expr is not None:
            vary_choice = 2
        self.wids.vary.SetSelection(vary_choice)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        CLEFT = LEFT | wx.ALL | wx.ALIGN_CENTER_VERTICAL
        if show_name:
            self.wids.name = wx.StaticText(self,
                                           label="%s: " % param.name,
                                           size=(len(param.name) * 8, -1))
            sizer.Add(self.wids.name, 0, CLEFT)

        sizer.Add(self.wids.val, 0, CLEFT)
        sizer.Add(self.wids.vary, 0, CLEFT)
        sizer.Add(self.wids.edit, 0, CLEFT)
        pack(self, sizer)
Exemplo n.º 5
0
    def filters_page(self):
        "create row for filters parameters"
        mca = self.parent.mca
        self.wids.filters = []

        p = GridPanel(self, itemstyle=LEFT)

        bx = Button(p,
                    'Customize Filter List',
                    size=(150, -1),
                    action=self.onEditFilters)
        bx.Disable()
        p.AddManyText(
            (' filter', 'material', 'density (gr/cm^3)', 'thickness (mm)'),
            style=CEN)
        p.Add(HLine(p, size=(600, 3)), dcol=5, newrow=True)
        for i in range(4):
            _mat = Choice(p,
                          choices=self.Filter_Materials,
                          default=0,
                          size=(125, -1),
                          action=partial(self.onFilterMaterial, index=i))
            _den = FloatCtrl(p,
                             value=0,
                             minval=0,
                             maxval=30,
                             precision=4,
                             size=(75, -1))

            pnam = 'filter%i_thickness' % (i + 1)
            param = Parameter(value=0.0, vary=False, min=0, name=pnam)
            setattr(self.paramgroup, pnam, param)
            _len = ParameterPanel(p, param, precision=4)

            self.wids.filters.append((_mat, _den, _len))
            p.AddText('  %i ' % (i + 1), newrow=True)
            p.Add(_mat)
            p.Add(_den, style=wx.ALIGN_CENTER)
            p.Add(_len)
        p.Add(HLine(p, size=(600, 3)), dcol=5, newrow=True)
        p.AddText(' ', newrow=True)
        p.Add(bx, dcol=3)

        p.pack()
        return p
Exemplo n.º 6
0
    def __init__(self, parent, mca, size=(-1, -1), callback=None):
        self.mca = mca
        self.callback = callback
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Calibrate MCA',
                          size=size,
                          style=wx.DEFAULT_FRAME_STYLE)

        opanel = scrolled.ScrolledPanel(self)
        osizer = wx.BoxSizer(wx.VERTICAL)
        panel = GridPanel(opanel)
        self.calib_updated = False
        panel.AddText("Calibrate MCA Energy (Energies in eV)",
                      colour='#880000',
                      dcol=7)
        panel.AddText("ROI", newrow=True, style=CEN)
        panel.AddText("Predicted", style=CEN)
        panel.AddText("Peaks with Current Calibration", dcol=3, style=CEN)
        panel.AddText("Peaks with Refined Calibration", dcol=3, style=CEN)

        panel.AddText("Name", newrow=True, style=CEN)
        panel.AddText("Energy", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Use? ", style=CEN)

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        self.wids = []

        # find ROI peak positions
        self.init_wids = {}
        for roi in self.mca.rois:
            eknown, ecen, fwhm = 1, 1, 1

            words = roi.name.split()
            elem = words[0].title()
            family = 'ka'
            if len(words) > 1:
                family = words[1]
            try:
                eknown = xray_line(elem, family).energy / 1000.0
            except (AttributeError, ValueError):
                eknown = 0.0001
            mid = (roi.right + roi.left) / 2
            wid = (roi.right - roi.left) / 2
            ecen = mid * mca.slope + mca.offset
            fwhm = 2.354820 * wid * mca.slope

            diff = ecen - eknown
            name = ('   ' + roi.name + ' ' * 10)[:10]
            opts = {'style': CEN, 'size': (75, -1)}
            w_name = SimpleText(panel, name, **opts)
            w_pred = SimpleText(panel, "% .1f" % (1000 * eknown), **opts)
            w_ccen = SimpleText(panel, "% .1f" % (1000 * ecen), **opts)
            w_cdif = SimpleText(panel, "% .1f" % (1000 * diff), **opts)
            w_cwid = SimpleText(panel, "% .1f" % (1000 * fwhm), **opts)
            w_ncen = SimpleText(panel, "-----", **opts)
            w_ndif = SimpleText(panel, "-----", **opts)
            w_nwid = SimpleText(panel, "-----", **opts)
            w_use = Check(panel, label='', size=(40, -1), default=0)
            panel.Add(w_name, style=LEFT, newrow=True)
            panel.AddMany((w_pred, w_ccen, w_cdif, w_cwid, w_ncen, w_ndif,
                           w_nwid, w_use))
            self.init_wids[roi.name] = [
                False, w_pred, w_ccen, w_cdif, w_cwid, w_use
            ]
            self.wids.append(
                (roi.name, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use))

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        offset = 1000.0 * self.mca.offset
        slope = 1000.0 * self.mca.slope
        panel.AddText("Current Calibration:", dcol=2, newrow=True)
        panel.AddText("offset(eV):")
        panel.AddText("%.3f" % (offset), dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.AddText("%.3f" % (slope), dcol=1, style=RIGHT)

        panel.AddText("Refined Calibration:", dcol=2, newrow=True)
        self.new_offset = FloatCtrl(panel,
                                    value=offset,
                                    precision=3,
                                    size=(80, -1))
        self.new_slope = FloatCtrl(panel,
                                   value=slope,
                                   precision=3,
                                   size=(80, -1))
        panel.AddText("offset(eV):")
        panel.Add(self.new_offset, dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.Add(self.new_slope, dcol=1, style=RIGHT)

        self.calib_btn = Button(panel,
                                'Compute Calibration',
                                size=(175, -1),
                                action=self.onCalibrate)
        self.calib_btn.Disable()
        panel.Add(self.calib_btn, dcol=3, newrow=True)
        panel.Add(Button(panel,
                         'Use New Calibration',
                         size=(175, -1),
                         action=self.onUseCalib),
                  dcol=3,
                  style=RIGHT)
        panel.Add(Button(panel, 'Done', size=(125, -1), action=self.onClose),
                  dcol=2,
                  style=RIGHT)
        panel.pack()
        a = panel.GetBestSize()
        self.SetSize((a[0] + 25, a[1] + 50))
        osizer.Add(panel)
        pack(opanel, osizer)
        opanel.SetupScrolling()
        self.Show()
        self.Raise()
        self.init_proc = False
        self.init_t0 = time.time()
        self.init_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onInitTimer, self.init_timer)
        self.init_timer.Start(2)
Exemplo n.º 7
0
class XRFCalibrationFrame(wx.Frame):
    def __init__(self, parent, mca, size=(-1, -1), callback=None):
        self.mca = mca
        self.callback = callback
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Calibrate MCA',
                          size=size,
                          style=wx.DEFAULT_FRAME_STYLE)

        opanel = scrolled.ScrolledPanel(self)
        osizer = wx.BoxSizer(wx.VERTICAL)
        panel = GridPanel(opanel)
        self.calib_updated = False
        panel.AddText("Calibrate MCA Energy (Energies in eV)",
                      colour='#880000',
                      dcol=7)
        panel.AddText("ROI", newrow=True, style=CEN)
        panel.AddText("Predicted", style=CEN)
        panel.AddText("Peaks with Current Calibration", dcol=3, style=CEN)
        panel.AddText("Peaks with Refined Calibration", dcol=3, style=CEN)

        panel.AddText("Name", newrow=True, style=CEN)
        panel.AddText("Energy", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Use? ", style=CEN)

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        self.wids = []

        # find ROI peak positions
        self.init_wids = {}
        for roi in self.mca.rois:
            eknown, ecen, fwhm = 1, 1, 1

            words = roi.name.split()
            elem = words[0].title()
            family = 'ka'
            if len(words) > 1:
                family = words[1]
            try:
                eknown = xray_line(elem, family).energy / 1000.0
            except (AttributeError, ValueError):
                eknown = 0.0001
            mid = (roi.right + roi.left) / 2
            wid = (roi.right - roi.left) / 2
            ecen = mid * mca.slope + mca.offset
            fwhm = 2.354820 * wid * mca.slope

            diff = ecen - eknown
            name = ('   ' + roi.name + ' ' * 10)[:10]
            opts = {'style': CEN, 'size': (75, -1)}
            w_name = SimpleText(panel, name, **opts)
            w_pred = SimpleText(panel, "% .1f" % (1000 * eknown), **opts)
            w_ccen = SimpleText(panel, "% .1f" % (1000 * ecen), **opts)
            w_cdif = SimpleText(panel, "% .1f" % (1000 * diff), **opts)
            w_cwid = SimpleText(panel, "% .1f" % (1000 * fwhm), **opts)
            w_ncen = SimpleText(panel, "-----", **opts)
            w_ndif = SimpleText(panel, "-----", **opts)
            w_nwid = SimpleText(panel, "-----", **opts)
            w_use = Check(panel, label='', size=(40, -1), default=0)
            panel.Add(w_name, style=LEFT, newrow=True)
            panel.AddMany((w_pred, w_ccen, w_cdif, w_cwid, w_ncen, w_ndif,
                           w_nwid, w_use))
            self.init_wids[roi.name] = [
                False, w_pred, w_ccen, w_cdif, w_cwid, w_use
            ]
            self.wids.append(
                (roi.name, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use))

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        offset = 1000.0 * self.mca.offset
        slope = 1000.0 * self.mca.slope
        panel.AddText("Current Calibration:", dcol=2, newrow=True)
        panel.AddText("offset(eV):")
        panel.AddText("%.3f" % (offset), dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.AddText("%.3f" % (slope), dcol=1, style=RIGHT)

        panel.AddText("Refined Calibration:", dcol=2, newrow=True)
        self.new_offset = FloatCtrl(panel,
                                    value=offset,
                                    precision=3,
                                    size=(80, -1))
        self.new_slope = FloatCtrl(panel,
                                   value=slope,
                                   precision=3,
                                   size=(80, -1))
        panel.AddText("offset(eV):")
        panel.Add(self.new_offset, dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.Add(self.new_slope, dcol=1, style=RIGHT)

        self.calib_btn = Button(panel,
                                'Compute Calibration',
                                size=(175, -1),
                                action=self.onCalibrate)
        self.calib_btn.Disable()
        panel.Add(self.calib_btn, dcol=3, newrow=True)
        panel.Add(Button(panel,
                         'Use New Calibration',
                         size=(175, -1),
                         action=self.onUseCalib),
                  dcol=3,
                  style=RIGHT)
        panel.Add(Button(panel, 'Done', size=(125, -1), action=self.onClose),
                  dcol=2,
                  style=RIGHT)
        panel.pack()
        a = panel.GetBestSize()
        self.SetSize((a[0] + 25, a[1] + 50))
        osizer.Add(panel)
        pack(opanel, osizer)
        opanel.SetupScrolling()
        self.Show()
        self.Raise()
        self.init_proc = False
        self.init_t0 = time.time()
        self.init_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onInitTimer, self.init_timer)
        self.init_timer.Start(2)

    def onInitTimer(self, evt=None):
        """initial calibration"""
        if self.init_proc:
            # print("skipping in init_proc...")
            return
        nextroi = None
        if time.time() - self.init_t0 > 20:
            self.init_timer.Stop()
            self.init_proc = False
            self.calib_btn.Enable()
        for roiname, wids in self.init_wids.items():
            if not wids[0]:
                nextroi = roiname
                break

        if nextroi is None:
            self.init_timer.Stop()
            self.init_proc = False
            self.calib_btn.Enable()
        else:
            self.init_proc = True
            xrf_calib_init_roi(self.mca, roiname)
            s, w_pred, w_ccen, w_cdif, w_cwid, w_use = self.init_wids[roiname]
            if roiname in self.mca.init_calib:
                eknown, ecen, fwhm, amp, fit = self.mca.init_calib[roiname]

                diff = ecen - eknown
                opts = {'style': CEN, 'size': (75, -1)}
                w_pred.SetLabel("% .1f" % (1000 * eknown))
                w_ccen.SetLabel("% .1f" % (1000 * ecen))
                w_cdif.SetLabel("% .1f" % (1000 * diff))
                w_cwid.SetLabel("% .1f" % (1000 * fwhm))
                if fwhm > 0.001 and fwhm < 2.00 and fit is not None:
                    w_use.SetValue(1)

            self.init_wids[roiname][0] = True
            self.init_proc = False

    def onCalibrate(self, event=None):
        x, y = [], []
        mca = self.mca
        # save old calib
        old_calib = mca.offset, mca.slope
        init_calib = copy.deepcopy(mca.init_calib)
        for roiname, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use in self.wids:
            if not w_use.IsChecked():
                mca.init_calib.pop(roiname)
            w_ncen.SetLabel("-----")
            w_ndif.SetLabel("-----")
            w_nwid.SetLabel("-----")

        xrf_calib_compute(mca, apply=True)
        offset, slope = mca.new_calib
        self.calib_updated = True
        self.new_offset.SetValue("% .3f" % (1000 * offset))
        self.new_slope.SetValue("% .3f" % (1000 * slope))

        # find ROI peak positions using this new calibration
        xrf_calib_fitrois(mca)
        for roi in self.mca.rois:
            try:
                eknown, ecen, fwhm, amp, fit = mca.init_calib[roi.name]
            except:
                continue
            diff = ecen - eknown
            for roiname, eknown, ocen, w_ncen, w_ndif, w_nwid, w_use in self.wids:
                if roiname == roi.name and w_use.IsChecked():
                    w_ncen.SetLabel("%.1f" % (1000 * ecen))
                    w_ndif.SetLabel("% .1f" % (1000 * diff))
                    w_nwid.SetLabel("%.1f" % (1000 * fwhm))
                    break

        # restore calibration to old values until new values are accepted
        xrf_calib_apply(mca, offset=old_calib[0], slope=old_calib[1])
        mca.init_calib = init_calib

        tsize = self.GetSize()
        self.SetSize((tsize[0] + 1, tsize[1]))
        self.SetSize((tsize[0], tsize[1]))

    def onUseCalib(self, event=None):
        mca = self.mca
        offset = 0.001 * float(self.new_offset.GetValue())
        slope = 0.001 * float(self.new_slope.GetValue())
        mca.new_calib = offset, slope
        xrf_calib_apply(mca, offset=offset, slope=slope)
        if callable(self.callback):
            self.callback(mca)
        self.Destroy()

    def onClose(self, event=None):
        self.Destroy()
Exemplo n.º 8
0
    def __init__(self, parent, size=(475, 325), **kws):
        self.parent = parent
        conf = parent.conf
        kws['style'] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          size=size,
                          title='XRF Line Selection',
                          **kws)
        panel = GridPanel(self)
        self.checkbox = {}

        def add_elines(panel, lines, checked):
            for i in lines:
                cb = Check(panel,
                           '%s ' % i,
                           default=i in checked,
                           action=partial(self.onLine, label=i, lines=checked))
                self.checkbox[i] = cb
                panel.Add(cb, style=LEFT)

        hopts = {'size': (125, -1), 'bgcolour': (250, 250, 200)}
        labopts = {'newrow': True, 'style': LEFT}
        self.linedata = {
            'Major K Lines:': self.k1lines,
            'Minor K Lines:': self.k2lines,
            'Major L Lines:': self.l1lines,
            'Minor L Lines:': self.l2lines + self.l3lines,
            'Major M Lines:': self.mlines
        }
        panel.AddText(' Select X-ray Emission Lines', dcol=4, colour='#880000')
        panel.Add(HLine(panel, size=(450, 3)), dcol=5, newrow=True)

        panel.Add(
            HyperText(panel,
                      'Major K Lines:',
                      action=partial(self.ToggleLines, lines=conf.K_major),
                      **hopts), **labopts)
        add_elines(panel, self.k1lines, conf.K_major)

        panel.Add(
            HyperText(panel,
                      'Minor K Lines:',
                      action=partial(self.ToggleLines, lines=conf.K_minor),
                      **hopts), **labopts)
        add_elines(panel, self.k2lines, conf.K_minor)

        panel.Add(
            HyperText(panel,
                      'Major L Lines:',
                      action=partial(self.ToggleLines, lines=conf.L_major),
                      **hopts), **labopts)
        add_elines(panel, self.l1lines, conf.L_major)

        panel.Add(
            HyperText(panel,
                      'Minor L Lines:',
                      action=partial(self.ToggleLines, lines=conf.L_minor),
                      **hopts), **labopts)
        add_elines(panel, self.l2lines, conf.L_minor)

        panel.AddText(' ', **labopts)
        add_elines(panel, self.l3lines, conf.L_minor)

        panel.Add(
            HyperText(panel,
                      'Major M Lines:',
                      action=partial(self.ToggleLines, lines=conf.M_major),
                      **hopts), **labopts)
        add_elines(panel, self.mlines, conf.M_major)

        panel.AddText('Energy Range (keV): ', **labopts)
        fopts = {'minval': 0, 'maxval': 1000, 'precision': 2, 'size': (75, -1)}
        panel.Add(FloatCtrl(panel,
                            value=conf.e_min,
                            action=partial(self.onErange, is_max=False),
                            **fopts),
                  dcol=2,
                  style=LEFT)

        panel.AddText(' : ')
        panel.Add(FloatCtrl(panel,
                            value=conf.e_max,
                            action=partial(self.onErange, is_max=True),
                            **fopts),
                  dcol=2,
                  style=LEFT)

        panel.Add(HLine(panel, size=(450, 3)), dcol=5, newrow=True)
        panel.Add(Button(panel, 'Done', size=(80, -1), action=self.onDone),
                  newrow=True,
                  style=LEFT)
        panel.pack()
        self.Show()
        self.Raise()
Exemplo n.º 9
0
    def CreateXASPanel(self, parent):
        opchoices = ('Raw Data', 'Normalized', 'Derivative',
                     'Normalized + Derivative', 'Pre-edge subtracted',
                     'Raw Data + Pre-edge/Post-edge')
        p = panel = wx.Panel(parent)
        opts = {'action': self.UpdateXASPlot}
        self.xas_autoe0 = Check(panel, default=True, label='auto?', **opts)
        self.xas_showe0 = Check(panel, default=True, label='show?', **opts)
        self.xas_autostep = Check(panel, default=True, label='auto?', **opts)
        self.xas_op = Choice(panel, size=(300, -1), choices=opchoices, **opts)

        self.btns = {}
        for name in ('e0', 'pre1', 'pre2', 'nor1', 'nor2'):
            bb = BitmapButton(panel,
                              get_icon('plus'),
                              action=partial(self.onXAS_selpoint, opt=name),
                              tooltip='use last point selected from plot')
            self.btns[name] = bb

        opts = {'size': (85, -1), 'precision': 3, 'action': self.UpdateXASPlot}
        self.xwids = {}
        self.xas_e0 = FloatCtrl(panel, value=0, **opts)
        self.xas_step = FloatCtrl(panel, value=0, **opts)
        opts['precision'] = 1
        self.xas_pre1 = FloatCtrl(panel, value=-200, **opts)
        self.xas_pre2 = FloatCtrl(panel, value=-30, **opts)
        self.xas_nor1 = FloatCtrl(panel, value=50, **opts)
        self.xas_nor2 = FloatCtrl(panel, value=-50, **opts)

        opts = {
            'size': (50, -1),
            'choices': ('0', '1', '2', '3'),
            'action': self.UpdateXASPlot
        }
        self.xas_vict = Choice(panel, **opts)
        self.xas_nnor = Choice(panel, **opts)
        self.xas_vict.SetSelection(1)
        self.xas_nnor.SetSelection(2)
        sizer = wx.GridBagSizer(10, 7)

        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, 6), LCEN)
        sizer.Add(self.btns['e0'], (1, 1), (1, 1), LCEN)
        sizer.Add(self.xas_e0, (1, 2), (1, 1), LCEN)
        sizer.Add(self.xas_autoe0, (1, 3), (1, 3), LCEN)
        sizer.Add(self.xas_showe0, (1, 6), (1, 2), LCEN)

        sizer.Add(self.xas_step, (2, 2), (1, 1), LCEN)
        sizer.Add(self.xas_autostep, (2, 3), (1, 3), LCEN)

        sizer.Add(self.btns['pre1'], (3, 1), (1, 1), LCEN)
        sizer.Add(self.xas_pre1, (3, 2), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (3, 3), (1, 1), LCEN)
        sizer.Add(self.btns['pre2'], (3, 4), (1, 1), LCEN)
        sizer.Add(self.xas_pre2, (3, 5), (1, 1), LCEN)
        sizer.Add(self.btns['nor1'], (4, 1), (1, 1), LCEN)
        sizer.Add(self.xas_nor1, (4, 2), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (4, 3), (1, 1), LCEN)
        sizer.Add(self.btns['nor2'], (4, 4), (1, 1), LCEN)
        sizer.Add(self.xas_nor2, (4, 5), (1, 1), LCEN)

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

        pack(panel, sizer)
        return panel
Exemplo n.º 10
0
    def CreateXASPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.xas_autoe0 = Check(panel, default=True, label='auto?')
        self.xas_showe0 = Check(panel, default=True, label='show?')
        self.xas_autostep = Check(panel, default=True, label='auto?')
        self.xas_op = Choice(
            panel,
            size=(225, -1),
            choices=('Raw Data', 'Normalized', 'Derivative',
                     'Normalized + Derivative', 'Pre-edge subtracted',
                     'Raw Data With Pre-edge/Post-edge Curves'),
            action=self.onXASChoice)
        opts = {
            'size': (95, -1),
            'precision': 3
        }  # , 'action': self.onXASChoice}
        self.xas_e0 = FloatCtrl(panel, value=0, **opts)
        self.xas_step = FloatCtrl(panel, value=0, **opts)
        opts['precision'] = 1
        self.xas_pre1 = FloatCtrl(panel, value=-200, **opts)
        self.xas_pre2 = FloatCtrl(panel, value=-30, **opts)
        self.xas_nor1 = FloatCtrl(panel, value=50, **opts)
        self.xas_nor2 = FloatCtrl(panel, value=-50, **opts)
        opts = {
            'size': (50, -1),
            'choices': ('0', '1', '2', '3'),
            'action': self.onXASChoice
        }
        self.xas_vict = Choice(panel, **opts)
        self.xas_nnor = Choice(panel, **opts)
        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, 3), 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_showe0, (1, 4), (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
Exemplo n.º 11
0
    def __init__(self,
                 parent,
                 param,
                 name_size=None,
                 prefix=None,
                 expr_size=120,
                 stderr_size=120,
                 float_size=80,
                 minmax_size=60,
                 widgets=PAR_WIDS):

        self.parent = parent
        self.param = param
        self._saved_expr = ''
        if (prefix is not None and not self.param.name.startswith(prefix)):
            self.param.name = "%s%s" % (prefix, self.param.name)

        for attr in PAR_WIDS:
            setattr(self, attr, None)

        # set vary_choice from param attributes
        vary_choice = PAR_VAR
        if param.expr not in (None, 'None', ''):
            vary_choice = PAR_CON
        elif not param.vary:
            vary_choice = PAR_FIX

        if 'name' in widgets:
            name = param.name
            if name in (None, 'None', ''):
                name = ''
            if name_size is None:
                name_size = min(50, len(param.name) * 10)
            self.name = wx.StaticText(parent, label=name, size=(name_size, -1))

        if 'value' in widgets:
            self.value = FloatCtrl(parent,
                                   value=param.value,
                                   minval=param.min,
                                   maxval=param.max,
                                   action=self.onValue,
                                   act_on_losefocus=True,
                                   gformat=True,
                                   size=(float_size, -1))

        if 'minval' in widgets:
            minval = param.min
            if minval in (None, 'None', -np.inf):
                minval = -np.inf
            self.minval = FloatCtrl(parent,
                                    value=minval,
                                    gformat=True,
                                    size=(minmax_size, -1),
                                    act_on_losefocus=True,
                                    action=self.onMinval)
            self.minval.Enable(vary_choice == PAR_VAR)

        if 'maxval' in widgets:
            maxval = param.max
            if maxval in (None, 'None', np.inf):
                maxval = np.inf
            self.maxval = FloatCtrl(parent,
                                    value=maxval,
                                    gformat=True,
                                    size=(minmax_size, -1),
                                    act_on_losefocus=True,
                                    action=self.onMaxval)
            self.maxval.Enable(vary_choice == PAR_VAR)

        if 'vary' in widgets:
            self.vary = Choice(parent,
                               size=(90, -1),
                               choices=VARY_CHOICES,
                               action=self.onVaryChoice)
            self.vary.SetStringSelection(vary_choice)

        if 'expr' in widgets:
            expr = param.expr
            if expr in (None, 'None', ''):
                expr = ''
            self._saved_expr = expr
            self.expr = wx.TextCtrl(parent,
                                    -1,
                                    value=expr,
                                    size=(expr_size, -1))
            self.expr.Enable(vary_choice == PAR_CON)
            self.expr.Bind(wx.EVT_CHAR, self.onExprChar)
            self.expr.Bind(wx.EVT_KILL_FOCUS, self.onExprKillFocus)
            SetTip(self.expr, 'Enter constraint expression')

        if 'stderr' in widgets:
            stderr = param.stderr
            if stderr in (None, 'None', ''):
                stderr = ''
            self.stderr = wx.StaticText(parent,
                                        label=stderr,
                                        size=(stderr_size, -1))

        if 'minval' in widgets or 'maxval' in widgets:
            minval = param.min
            maxval = param.max
            bounds_choice = BOUNDS_custom
            if minval in (None, 'None', -np.inf) and maxval in (None, 'None',
                                                                np.inf):
                bounds_choice = BOUNDS_none
            elif minval == 0:
                bounds_choice = BOUNDS_pos
            elif maxval == 0:
                bounds_choice = BOUNDS_neg

            self.bounds = Choice(parent,
                                 size=(90, -1),
                                 choices=BOUNDS_CHOICES,
                                 action=self.onBOUNDSChoice)
            self.bounds.SetStringSelection(bounds_choice)
Exemplo n.º 12
0
class ParameterWidgets(object):
    """a set of related widgets for a lmfit Parameter

    param = Parameter(value=11.22, vary=True, min=0, name='x1')
    wid   = ParameterPanel(parent_wid, param)
    """
    def __init__(self,
                 parent,
                 param,
                 name_size=None,
                 prefix=None,
                 expr_size=120,
                 stderr_size=120,
                 float_size=80,
                 minmax_size=60,
                 widgets=PAR_WIDS):

        self.parent = parent
        self.param = param
        self._saved_expr = ''
        if (prefix is not None and not self.param.name.startswith(prefix)):
            self.param.name = "%s%s" % (prefix, self.param.name)

        for attr in PAR_WIDS:
            setattr(self, attr, None)

        # set vary_choice from param attributes
        vary_choice = PAR_VAR
        if param.expr not in (None, 'None', ''):
            vary_choice = PAR_CON
        elif not param.vary:
            vary_choice = PAR_FIX

        if 'name' in widgets:
            name = param.name
            if name in (None, 'None', ''):
                name = ''
            if name_size is None:
                name_size = min(50, len(param.name) * 10)
            self.name = wx.StaticText(parent, label=name, size=(name_size, -1))

        if 'value' in widgets:
            self.value = FloatCtrl(parent,
                                   value=param.value,
                                   minval=param.min,
                                   maxval=param.max,
                                   action=self.onValue,
                                   act_on_losefocus=True,
                                   gformat=True,
                                   size=(float_size, -1))

        if 'minval' in widgets:
            minval = param.min
            if minval in (None, 'None', -np.inf):
                minval = -np.inf
            self.minval = FloatCtrl(parent,
                                    value=minval,
                                    gformat=True,
                                    size=(minmax_size, -1),
                                    act_on_losefocus=True,
                                    action=self.onMinval)
            self.minval.Enable(vary_choice == PAR_VAR)

        if 'maxval' in widgets:
            maxval = param.max
            if maxval in (None, 'None', np.inf):
                maxval = np.inf
            self.maxval = FloatCtrl(parent,
                                    value=maxval,
                                    gformat=True,
                                    size=(minmax_size, -1),
                                    act_on_losefocus=True,
                                    action=self.onMaxval)
            self.maxval.Enable(vary_choice == PAR_VAR)

        if 'vary' in widgets:
            self.vary = Choice(parent,
                               size=(90, -1),
                               choices=VARY_CHOICES,
                               action=self.onVaryChoice)
            self.vary.SetStringSelection(vary_choice)

        if 'expr' in widgets:
            expr = param.expr
            if expr in (None, 'None', ''):
                expr = ''
            self._saved_expr = expr
            self.expr = wx.TextCtrl(parent,
                                    -1,
                                    value=expr,
                                    size=(expr_size, -1))
            self.expr.Enable(vary_choice == PAR_CON)
            self.expr.Bind(wx.EVT_CHAR, self.onExprChar)
            self.expr.Bind(wx.EVT_KILL_FOCUS, self.onExprKillFocus)
            SetTip(self.expr, 'Enter constraint expression')

        if 'stderr' in widgets:
            stderr = param.stderr
            if stderr in (None, 'None', ''):
                stderr = ''
            self.stderr = wx.StaticText(parent,
                                        label=stderr,
                                        size=(stderr_size, -1))

        if 'minval' in widgets or 'maxval' in widgets:
            minval = param.min
            maxval = param.max
            bounds_choice = BOUNDS_custom
            if minval in (None, 'None', -np.inf) and maxval in (None, 'None',
                                                                np.inf):
                bounds_choice = BOUNDS_none
            elif minval == 0:
                bounds_choice = BOUNDS_pos
            elif maxval == 0:
                bounds_choice = BOUNDS_neg

            self.bounds = Choice(parent,
                                 size=(90, -1),
                                 choices=BOUNDS_CHOICES,
                                 action=self.onBOUNDSChoice)
            self.bounds.SetStringSelection(bounds_choice)

    def onBOUNDSChoice(self, evt=None):
        bounds = str(evt.GetString().lower())
        if bounds == BOUNDS_custom:
            pass
        elif bounds == BOUNDS_none:
            self.minval.SetValue(-np.inf)
            self.maxval.SetValue(np.inf)

        elif bounds == BOUNDS_pos:
            self.minval.SetValue(0)
            if float(self.maxval.GetValue()) == 0:
                self.maxval.SetValue(np.inf)
        elif bounds == BOUNDS_neg:
            self.maxval.SetValue(0)
            if float(self.minval.GetValue()) == 0:
                self.minval.SetValue(-np.inf)

    def onValue(self, evt=None, value=None):
        if value is not None:
            self.param.value = value

    def onExprChar(self, evt=None):
        key = evt.GetKeyCode()
        if key == wx.WXK_RETURN:
            self.onExpr(value=self.expr.GetValue())
        evt.Skip()

    def onExprKillFocus(self, evt=None):
        self.onExpr(value=self.expr.GetValue())
        evt.Skip()

    def onExpr(self, evt=None, value=None):
        if value is None and evt is not None:
            value = evt.GetString()
        try:
            ast.parse(value)
            self.param.expr = value
            bgcol, fgcol = 'white', 'black'
        except SyntaxError:
            bgcol, fgcol = 'red', 'yellow'

        self.expr.SetForegroundColour(fgcol)
        self.expr.SetBackgroundColour(bgcol)

    def onMinval(self, evt=None, value=None):
        if value in (None, 'None', ''):
            value = -np.inf
        if self.value is not None:
            v = self.value.GetValue()
            self.value.SetMin(value)
            self.value.SetValue(v)
            self.param.min = value
        if self.bounds is not None:
            if value == 0:
                self.bounds.SetStringSelection(BOUNDS_pos)
            elif value == -np.inf:
                if self.maxval.GetValue() == np.inf:
                    self.bounds.SetStringSelection(BOUNDS_none)
            else:
                self.bounds.SetStringSelection(BOUNDS_custom)

    def onMaxval(self, evt=None, value=None):
        # print "onMaxval " , value, self.value, self.value
        if value in (None, 'None', ''):
            value = np.inf
        if self.value is not None:
            v = self.value.GetValue()
            self.value.SetMax(value)
            self.value.SetValue(v)
            self.param.max = value

        if self.bounds is not None:
            if value == 0:
                self.bounds.SetStringSelection(BOUNDS_neg)
            elif value == np.inf:
                if self.minval.GetValue() == -np.inf:
                    self.bounds.SetStringSelection(BOUNDS_none)
            else:
                self.bounds.SetStringSelection(BOUNDS_custom)

    def onVaryChoice(self, evt=None):
        if self.vary is None:
            return
        vary = str(evt.GetString().lower())
        self.param.vary = (vary == PAR_VAR)
        if ((vary == PAR_VAR or vary == PAR_FIX)
                and self.param.expr not in (None, 'None', '')):
            self._saved_expr = self.param.expr
            self.param.expr = ''
        elif (vary == PAR_CON and self.param.expr in (None, 'None', '')):
            self.param.expr = self._saved_expr

        if self.value is not None:
            self.value.Enable(vary != PAR_CON)
        if self.expr is not None:
            self.expr.Enable(vary == PAR_CON)
        if self.minval is not None:
            self.minval.Enable(vary == PAR_VAR)
        if self.maxval is not None:
            self.maxval.Enable(vary == PAR_VAR)
        if self.bounds is not None:
            self.bounds.Enable(vary == PAR_VAR)
Exemplo n.º 13
0
    def __init__(self):

        wx.Frame.__init__(self,
                          None,
                          -1,
                          'wxutil demo',
                          style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER
                          | wx.TAB_TRAVERSAL)
        self.SetTitle('wxutil demo')

        self.SetFont(Font(11))

        self.set_menu()
        self.statusbar = self.CreateStatusBar(2, 1)
        self.statusbar.SetStatusWidths([-2, -1])
        statusbar_fields = ['Initializing....', ' ']
        for i in range(len(statusbar_fields)):
            self.statusbar.SetStatusText(statusbar_fields[i], i)

        self.Bind(wx.EVT_CLOSE, self.onExit)

        panel = GridPanel(self, nrows=8, ncols=4)

        tctrl_name = TextCtrl(panel,
                              value='',
                              action=self.onName,
                              size=(250, -1))

        lctrl_addr = LabeledTextCtrl(self,
                                     value='<>',
                                     action=self.onAddr,
                                     labeltext=' Address: ',
                                     size=(250, -1))

        lab3 = HyperText(panel,
                         ' FloatCtrl: ',
                         size=(100, -1),
                         action=self.onHyperText)

        val3 = FloatCtrl(panel,
                         '3',
                         action=self.onFloat1,
                         precision=2,
                         minval=0,
                         maxval=1000,
                         size=(250, -1))

        lab4 = HyperText(panel,
                         ' FloatSpin: ',
                         size=(100, -1),
                         action=self.onHyperText)
        val4 = FloatSpin(panel,
                         '12.2',
                         action=self.onFloatSpin,
                         digits=2,
                         increment=0.1,
                         size=(250, -1))

        labx = HyperText(panel,
                         ' NumericCombo: ',
                         size=(100, -1),
                         action=self.onHyperText)

        steps = make_steps(prec=1, tmin=0, tmax=100)
        valx = NumericCombo(panel, steps, precision=1)

        self.choice1 = Choice(panel, size=(200, -1), action=self.onChoice)
        self.choice1.SetChoices(['Apple', 'Banana', 'Cherry'])

        yesno = YesNo(panel)

        check1 = Check(panel, label='enable? ', action=self.onCheck)

        btn1 = Button(panel,
                      label='Start',
                      size=(100, -1),
                      action=self.onStart)

        pinbtn = BitmapButton(panel,
                              get_icon('pin'),
                              size=(50, -1),
                              action=partial(self.onBMButton, opt='pin1'),
                              tooltip='use last point selected from plot')

        togbtn = ToggleButton(panel,
                              'Press Me',
                              action=self.onToggleButton,
                              size=(100, -1),
                              tooltip='do it, do it now, you will like it')

        browse_btn = Button(panel,
                            'Open File',
                            action=self.onFileOpen,
                            size=(150, -1))

        okcancel = OkCancel(panel, onOK=self.onOK, onCancel=self.onCancel)

        ptable_btn = Button(panel,
                            'Show Periodic Table',
                            action=self.onPTable,
                            size=(175, -1))

        edlist_btn = Button(panel,
                            'Show Editable Listbox',
                            action=self.onEdList,
                            size=(175, -1))

        filelist_btn = Button(panel,
                              'Show File CheckList',
                              action=self.onFileList,
                              size=(175, -1))

        panel.AddText(' Name: ', style=LEFT)

        panel.Add(tctrl_name, dcol=2)
        panel.Add(lctrl_addr.label, newrow=True)
        panel.Add(lctrl_addr, dcol=2)

        panel.Add(lab3, newrow=True)
        panel.Add(val3, dcol=3)

        panel.Add(lab4, newrow=True)
        panel.Add(val4, dcol=3)

        panel.Add(labx, newrow=True)
        panel.Add(valx, dcol=3)

        panel.AddText(' Choice : ', newrow=True)
        panel.Add(check1)
        panel.Add(self.choice1)
        panel.AddText(' Yes or No: ', newrow=True)
        panel.Add(yesno)
        panel.Add(HLine(panel, size=(500, -1)), dcol=3, newrow=True)

        panel.Add(btn1, newrow=True)
        panel.Add(pinbtn)
        panel.Add(togbtn)

        panel.Add(browse_btn, newrow=True)
        panel.Add(ptable_btn)
        panel.Add(edlist_btn, newrow=True)
        panel.Add(filelist_btn)

        panel.Add(okcancel, newrow=True)

        panel.pack()

        self.timer = wx.Timer(self)
        self.last_time = time.time()
        self.Bind(wx.EVT_TIMER, self.onTimer, self.timer)

        fsizer = wx.BoxSizer(wx.VERTICAL)
        fsizer.Add(panel, 0, LEFT | wx.EXPAND)
        wx.CallAfter(self.init_timer)

        psize = panel.GetBestSize()
        self.SetSize((psize[0] + 5, psize[1] + 25))

        pack(self, fsizer)
        self.Refresh()
Exemplo n.º 14
0
    def createEpicsPanel(self):
        pane = wx.Panel(self, name='epics panel')
        style = wx.ALIGN_LEFT
        rstyle = wx.ALIGN_RIGHT

        det_btnpanel = self.create_detbuttons(pane)

        bkg_choices = ['None'] + ["%d" % (i + 1) for i in range(self.nmca)]

        self.wids['det_status'] = SimpleText(pane,
                                             ' ',
                                             size=(120, -1),
                                             style=style)
        self.wids['deadtime'] = SimpleText(pane,
                                           ' ',
                                           size=(120, -1),
                                           style=style)

        self.wids['bkg_det'] = Choice(pane,
                                      size=(100, -1),
                                      choices=bkg_choices,
                                      action=self.onSelectDet)

        self.wids['dwelltime'] = FloatCtrl(pane,
                                           value=0.0,
                                           precision=1,
                                           minval=0,
                                           size=(80, -1),
                                           act_on_losefocus=True,
                                           action=self.onSetDwelltime)
        self.wids['elapsed'] = SimpleText(pane,
                                          ' ',
                                          size=(80, -1),
                                          style=style)

        self.wids['mca_sum'] = Choice(pane,
                                      size=(100, -1),
                                      choices=['Single', 'Accumulate'],
                                      action=self.onMcaSumChoice,
                                      default=1)

        b1 = Button(pane, 'Start', size=(90, -1), action=self.onStart)
        b2 = Button(pane, 'Stop', size=(90, -1), action=self.onStop)
        b3 = Button(pane, 'Erase', size=(90, -1), action=self.onErase)
        b4 = Button(pane,
                    'Continuous',
                    size=(90, -1),
                    action=partial(self.onStart, dtime=0.0))

        sum_lab = SimpleText(pane, 'Accumulate Mode:', size=(150, -1))
        bkg_lab = SimpleText(pane, 'Background MCA:', size=(150, -1))
        pre_lab = SimpleText(pane, 'Dwell Time (s):', size=(125, -1))
        ela_lab = SimpleText(pane, 'Elapsed Time (s):', size=(125, -1))
        sta_lab = SimpleText(pane, 'Status :', size=(100, -1))
        dea_lab = SimpleText(pane, '% Deadtime:', size=(100, -1))

        psizer = wx.GridBagSizer(5, 5)
        psizer.Add(SimpleText(pane, ' MCAs: '), (0, 0), (1, 1), style, 1)
        psizer.Add(det_btnpanel, (0, 1), (2, 1), style, 1)
        psizer.Add(bkg_lab, (0, 2), (1, 1), style, 1)
        psizer.Add(self.wids['bkg_det'], (0, 3), (1, 1), style, 1)
        psizer.Add(sum_lab, (1, 2), (1, 1), style, 1)
        psizer.Add(self.wids['mca_sum'], (1, 3), (1, 1), style, 1)
        psizer.Add(pre_lab, (0, 4), (1, 1), style, 1)
        psizer.Add(ela_lab, (1, 4), (1, 1), style, 1)
        psizer.Add(self.wids['dwelltime'], (0, 5), (1, 1), style, 1)
        psizer.Add(self.wids['elapsed'], (1, 5), (1, 1), style, 1)

        psizer.Add(b1, (0, 6), (1, 1), style, 1)
        psizer.Add(b4, (0, 7), (1, 1), style, 1)
        psizer.Add(b2, (1, 6), (1, 1), style, 1)
        psizer.Add(b3, (1, 7), (1, 1), style, 1)

        psizer.Add(sta_lab, (0, 8), (1, 1), style, 1)
        psizer.Add(self.wids['det_status'], (0, 9), (1, 1), style, 1)
        psizer.Add(dea_lab, (1, 8), (1, 1), style, 1)
        psizer.Add(self.wids['deadtime'], (1, 9), (1, 1), style, 1)
        pack(pane, psizer)
        # pane.SetMinSize((500, 53))
        self.det.connect_displays(status=self.wids['det_status'],
                                  elapsed=self.wids['elapsed'])

        wx.CallAfter(self.onSelectDet, index=1, init=True)
        self.timer_counter = 0
        self.mca_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.UpdateData, self.mca_timer)
        self.mca_timer.Start(100)
        return pane
    def createEpicsPanel(self):
        pane = wx.Panel(self, name='epics panel')
        psizer = wx.GridBagSizer(4, 12)  # wx.BoxSizer(wx.HORIZONTAL)

        btnpanel = wx.Panel(pane, name='buttons')

        nmca = self.nmca
        NPERROW = 6
        self.SetFont(Font(9))
        if self.det_type.lower().startswith('me-4') and nmca < 5:
            btnsizer = wx.GridBagSizer(2, 2)
        else:
            btnsizer = wx.GridBagSizer(
                int((nmca + NPERROW - 2) / (1.0 * NPERROW)), NPERROW)

        style = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL
        rstyle = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL
        bkg_choices = ['None']

        psizer.Add(SimpleText(pane, ' MCAs: '), (0, 0), (1, 1), style, 1)
        for i in range(1, 1 + nmca):
            bkg_choices.append("%i" % i)
            b = Button(btnpanel,
                       '%i' % i,
                       size=(30, 25),
                       action=partial(self.onSelectDet, index=i))
            self.wids['det%i' % i] = b
            loc = divmod(i - 1, NPERROW)
            if self.det_type.lower().startswith('me-4') and nmca < NPERROW - 1:
                loc = self.me4_layout[i - 1]
            btnsizer.Add(b, loc, (1, 1), style, 1)
        pack(btnpanel, btnsizer)
        nrows = 1 + loc[0]

        if self.det_type.lower().startswith('me-4') and nmca < 5:
            nrows = 2

        psizer.Add(btnpanel, (0, 1), (nrows, 1), style, 1)

        self.wids['det_status'] = SimpleText(pane,
                                             ' ',
                                             size=(120, -1),
                                             style=style)
        self.wids['deadtime'] = SimpleText(pane,
                                           ' ',
                                           size=(120, -1),
                                           style=style)

        self.wids['bkg_det'] = Choice(pane,
                                      size=(75, -1),
                                      choices=bkg_choices,
                                      action=self.onSelectDet)

        self.wids['dwelltime'] = FloatCtrl(pane,
                                           value=0.0,
                                           precision=1,
                                           minval=0,
                                           size=(80, -1),
                                           act_on_losefocus=True,
                                           action=self.onSetDwelltime)
        self.wids['elapsed'] = SimpleText(pane,
                                          ' ',
                                          size=(80, -1),
                                          style=style)

        b1 = Button(pane, 'Start', size=(90, 25), action=self.onStart)
        b2 = Button(pane, 'Stop', size=(90, 25), action=self.onStop)
        b3 = Button(pane, 'Erase', size=(90, 25), action=self.onErase)
        b4 = Button(pane,
                    'Continuous',
                    size=(90, 25),
                    action=partial(self.onStart, dtime=0))

        bkg_lab = SimpleText(pane, 'Background MCA:', size=(150, -1))
        pre_lab = SimpleText(pane, 'Preset Time (s):', size=(125, -1))
        ela_lab = SimpleText(pane, 'Elapsed Time (s):', size=(125, -1))
        sta_lab = SimpleText(pane, 'Status :', size=(100, -1))
        dea_lab = SimpleText(pane, '% Deadtime:', size=(100, -1))

        psizer.Add(bkg_lab, (0, 2), (1, 1), style, 1)
        psizer.Add(self.wids['bkg_det'], (1, 2), (1, 1), style, 1)
        psizer.Add(pre_lab, (0, 3), (1, 1), style, 1)
        psizer.Add(ela_lab, (1, 3), (1, 1), style, 1)
        psizer.Add(self.wids['dwelltime'], (0, 4), (1, 1), style, 1)
        psizer.Add(self.wids['elapsed'], (1, 4), (1, 1), style, 1)

        psizer.Add(b1, (0, 5), (1, 1), style, 1)
        psizer.Add(b4, (0, 6), (1, 1), style, 1)
        psizer.Add(b2, (1, 5), (1, 1), style, 1)
        psizer.Add(b3, (1, 6), (1, 1), style, 1)

        psizer.Add(sta_lab, (0, 7), (1, 1), style, 1)
        psizer.Add(self.wids['det_status'], (0, 8), (1, 1), style, 1)
        psizer.Add(dea_lab, (1, 7), (1, 1), style, 1)
        psizer.Add(self.wids['deadtime'], (1, 8), (1, 1), style, 1)
        pack(pane, psizer)
        # pane.SetMinSize((500, 53))
        self.det.connect_displays(status=self.wids['det_status'],
                                  elapsed=self.wids['elapsed'],
                                  deadtime=self.wids['deadtime'])

        wx.CallAfter(self.onSelectDet, index=1, init=True)
        self.timer_counter = 0
        self.mca_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.UpdateData, self.mca_timer)
        self.mca_timer.Start(100)
        return pane
Exemplo n.º 16
0
class ScanViewerFrame(wx.Frame):
    _about = """Scan 2D Plotter
  Matt Newville <newville @ cars.uchicago.edu>
  """

    def __init__(self, _larch=None, **kws):

        wx.Frame.__init__(self, None, -1, style=FRAMESTYLE)
        self.file_groups = {}
        self.file_paths = []
        title = "Column Data File Viewer"
        self.larch = _larch
        self.larch_buffer = None
        self.subframes = {}
        self.plotframe = None
        self.groupname = None
        self.SetTitle(title)
        self.SetSize((850, 650))
        self.SetFont(Font(10))

        self.config = {'chdir_on_fileopen': True}

        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)
        read_workdir('scanviewer.dat')

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

        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 = Choice(panel,
                           choices=[],
                           action=self.onColumnChoices,
                           size=(120, -1))
        self.xop = Choice(panel,
                          choices=('', 'log'),
                          action=self.onColumnChoices,
                          size=(90, -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 = []

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

        for opts, sel, siz in ((PRE_OPS, 0, 90), (ARR_OPS, 3, 50), (ARR_OPS, 3,
                                                                    50)):
            w1 = Choice(panel,
                        choices=opts,
                        action=self.onColumnChoices,
                        size=(siz, -1))
            w1.SetSelection(sel)
            self.yops.append(w1)

        ir += 1
        label = 'Y = '
        sizer.Add(SimpleText(panel, label), (ir, 0), (1, 1), CEN, 0)
        sizer.Add(self.yops[0], (ir, 1), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, '[('), (ir, 2), (1, 1), CEN, 0)
        sizer.Add(self.yarr[0], (ir, 3), (1, 1), CEN, 0)
        sizer.Add(self.yops[1], (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.yarr[1], (ir, 5), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, ')'), (ir, 6), (1, 1), LCEN, 0)
        ir += 1
        sizer.Add(self.yops[2], (ir, 4), (1, 1), CEN, 0)
        sizer.Add(self.yarr[2], (ir, 5), (1, 1), CEN, 0)
        sizer.Add(SimpleText(panel, ']'), (ir, 6), (1, 1), LCEN, 0)

        self.use_deriv = Check(panel,
                               default=False,
                               label='Use Derivative?',
                               action=self.onColumnChoices)
        self.dtcorr = Check(panel,
                            default=True,
                            label='correct deadtime?',
                            action=self.onColumnChoices)
        ir += 1
        sizer.Add(self.use_deriv, (ir, 0), (1, 3), LCEN, 0)
        sizer.Add(self.dtcorr, (ir, 3), (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)

        btnbox = wx.Panel(mainpanel)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        for ttl, opt in (('New Plot', 'new'), ('Over Plot (left)', 'left'),
                         ('Over Plot (right)', 'right')):

            btnsizer.Add(
                Button(btnbox,
                       ttl,
                       size=(135, -1),
                       action=partial(self.onPlot, opt=opt)), LCEN, 1)

        pack(btnbox, btnsizer)
        mainsizer.Add(btnbox, 0, LCEN, 2)
        mainsizer.Add(self.nb, 1, LCEN | wx.EXPAND, 2)

        pack(mainpanel, mainsizer)

        return mainpanel

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

        tsizer = wx.GridBagSizer(10, 4)
        tsizer.Add(SimpleText(tpan, 'Fit Model: '), (0, 0), (1, 1), LCEN)
        tsizer.Add(self.fit_model, (0, 1), (1, 1), LCEN)

        tsizer.Add(SimpleText(tpan, 'Background: '), (0, 2), (1, 1), LCEN)
        tsizer.Add(self.fit_bkg, (0, 3), (1, 1), LCEN)

        tsizer.Add(
            Button(tpan, 'Show Fit', size=(100, -1), action=self.onFitPeak),
            (1, 1), (1, 1), LCEN)

        tsizer.Add(SimpleText(tpan, 'Step Form: '), (1, 2), (1, 1), LCEN)
        tsizer.Add(self.fit_step, (1, 3), (1, 1), LCEN)

        pack(tpan, tsizer)

        self.fit_report = RichTextCtrl(panel,
                                       size=(525, 250),
                                       style=wx.VSCROLL | wx.NO_BORDER)

        self.fit_report.SetEditable(False)
        self.fit_report.SetFont(Font(9))

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(tpan, 0, wx.GROW | wx.ALL, 2)
        sizer.Add(self.fit_report, 1, LCEN | wx.GROW, 2)
        pack(panel, sizer)
        return panel

    def InitializeXASPanel(self):
        if self.groupname is None:
            lgroup = None
        lgroup = getattr(self.larch.symtable, self.groupname)
        self.xas_e0.SetValue(getattr(lgroup, 'e0', 0))
        self.xas_step.SetValue(getattr(lgroup, 'edge_step', 0))
        self.xas_pre1.SetValue(getattr(lgroup, 'pre1', -200))
        self.xas_pre2.SetValue(getattr(lgroup, 'pre2', -30))
        self.xas_nor1.SetValue(getattr(lgroup, 'norm1', 50))
        self.xas_nor2.SetValue(getattr(lgroup, 'norm2', -10))

        self.xas_vict.SetSelection(getattr(lgroup, 'nvict', 1))
        self.xas_nnor.SetSelection(getattr(lgroup, 'nnorm', 2))

    def CreateXASPanel(self, parent):
        p = panel = wx.Panel(parent)
        self.xas_autoe0 = Check(panel, default=True, label='auto?')
        self.xas_showe0 = Check(panel, default=True, label='show?')
        self.xas_autostep = Check(panel, default=True, label='auto?')
        self.xas_op = Choice(
            panel,
            size=(225, -1),
            choices=('Raw Data', 'Normalized', 'Derivative',
                     'Normalized + Derivative', 'Pre-edge subtracted',
                     'Raw Data With Pre-edge/Post-edge Curves'),
            action=self.onXASChoice)
        opts = {
            'size': (95, -1),
            'precision': 3
        }  # , 'action': self.onXASChoice}
        self.xas_e0 = FloatCtrl(panel, value=0, **opts)
        self.xas_step = FloatCtrl(panel, value=0, **opts)
        opts['precision'] = 1
        self.xas_pre1 = FloatCtrl(panel, value=-200, **opts)
        self.xas_pre2 = FloatCtrl(panel, value=-30, **opts)
        self.xas_nor1 = FloatCtrl(panel, value=50, **opts)
        self.xas_nor2 = FloatCtrl(panel, value=-50, **opts)
        opts = {
            'size': (50, -1),
            'choices': ('0', '1', '2', '3'),
            'action': self.onXASChoice
        }
        self.xas_vict = Choice(panel, **opts)
        self.xas_nnor = Choice(panel, **opts)
        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, 3), 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_showe0, (1, 4), (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

        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)

        try:
            lgroup = getattr(self.larch.symtable, gname)
            x = lgroup._xdat_
            y = lgroup._ydat_
        except AttributeError:
            self.write_message('need data to fit!')
            return
        if step.startswith('error'):
            step = 'erf'
        elif step.startswith('arctan'):
            step = 'atan'

        pgroup = fit_peak(x,
                          y,
                          model,
                          background=bkg,
                          step=step,
                          _larch=self.larch)

        dtext = '\n'.join(dtext)
        dtext = '%s\n%s\n' % (
            dtext, fit_report(
                pgroup.params, min_correl=0.25, _larch=self.larch))

        self.fit_report.SetEditable(True)
        self.fit_report.SetValue(dtext)
        self.fit_report.SetEditable(False)

        popts1 = dict(style='solid', linewidth=3, marker='None', markersize=4)
        popts2 = dict(style='short dashed',
                      linewidth=2,
                      marker='None',
                      markersize=4)

        lgroup.plot_yarrays = [(lgroup._ydat_, popts1, lgroup.plot_ylabel)]
        if bkg is None:
            lgroup._fit = pgroup.fit[:]
            lgroup.plot_yarrays.append((lgroup._fit, popts2, 'fit'))
        else:
            lgroup._fit = pgroup.fit[:]
            lgroup._fit_bgr = pgroup.bkg[:]
            lgroup.plot_yarrays.append((lgroup._fit, popts2, 'fit'))
            lgroup.plot_yarrays.append((lgroup._fit_bgr, popts2, 'background'))
        self.onPlot()

    def xas_process(self, gname, new_mu=False, **kws):
        """ 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
        preopts = {'group': gname, 'e0': None}

        lgroup = getattr(self.larch.symtable, gname)
        dtcorr = self.dtcorr.IsChecked()
        if new_mu:
            try:
                del lgroup.e0, lgroup.edge_step
            except:
                pass

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

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

        dt = debugtime()

        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['nvict'] = self.xas_vict.GetSelection()
        preopts['nnorm'] = self.xas_nnor.GetSelection()

        preopts['make_flat'] = 'False'
        preopts['group'] = gname
        preopts = ", ".join(["%s=%s" % (k, v) for k, v in preopts.items()])

        preedge_cmd = "pre_edge(%s._xdat_, %s._ydat_, %s)"
        self.larch(preedge_cmd % (gname, gname, preopts))
        if self.xas_autoe0.IsChecked():
            self.xas_e0.SetValue(lgroup.e0)
        if self.xas_autostep.IsChecked():
            self.xas_step.SetValue(lgroup.edge_step)

        details_group = lgroup
        try:
            details_group = lgroup.pre_edge_details
        except:
            pass

        self.xas_pre1.SetValue(details_group.pre1)
        self.xas_pre2.SetValue(details_group.pre2)
        self.xas_nor1.SetValue(details_group.norm1)
        self.xas_nor2.SetValue(details_group.norm2)

        popts1 = dict(style='solid', linewidth=3, marker='None', markersize=4)
        popts2 = dict(style='short dashed',
                      linewidth=2,
                      zorder=-5,
                      marker='None',
                      markersize=4)
        poptsd = dict(style='solid',
                      linewidth=2,
                      zorder=-5,
                      side='right',
                      y2label='derivative',
                      marker='None',
                      markersize=4)

        lgroup.plot_yarrays = [(lgroup._ydat_, popts1, lgroup.plot_ylabel)]
        y4e0 = lgroup._ydat_
        if out.startswith('raw data with'):
            lgroup.plot_yarrays = [(lgroup._ydat_, popts1, lgroup.plot_ylabel),
                                   (lgroup.pre_edge, popts2, 'pre edge'),
                                   (lgroup.post_edge, popts2, 'post edge')]
        elif out.startswith('pre'):
            self.larch('%s.pre_edge_sub = %s.norm * %s.edge_step' %
                       (gname, gname, gname))
            lgroup.plot_yarrays = [(lgroup.pre_edge_sub, popts1,
                                    'pre edge subtracted XAFS')]
            y4e0 = lgroup.pre_edge_sub
        elif 'norm' in out and 'deriv' in out:
            lgroup.plot_yarrays = [(lgroup.norm, popts1, 'normalized XAFS'),
                                   (lgroup.dmude, poptsd, 'derivative')]
            y4e0 = lgroup.norm

        elif out.startswith('norm'):
            lgroup.plot_yarrays = [(lgroup.norm, popts1, 'normalized XAFS')]
            y4e0 = lgroup.norm
        elif out.startswith('deriv'):
            lgroup.plot_yarrays = [(lgroup.dmude, popts1, 'derivative')]
            y4e0 = lgroup.dmude

        lgroup.plot_ymarkers = []
        if self.xas_showe0.IsChecked():
            ie0 = index_of(lgroup._xdat_, lgroup.e0)
            lgroup.plot_ymarkers = [(lgroup.e0, y4e0[ie0], {'label': 'e0'})]
        return

    def init_larch(self):
        t0 = time.time()
        if self.larch is None:
            self.larch = Interpreter()
        self.larch.symtable.set_symbol('_sys.wx.wxapp', wx.GetApp())
        self.larch.symtable.set_symbol('_sys.wx.parent', self)

        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_data(self, group, arrayname, correct=False):
        if hasattr(group, 'get_data'):
            return group.get_data(arrayname, correct=correct)
        return getattr(group, arrayname, None)

    def onXASChoice(self, evt=None, **kws):
        if self.groupname is None:
            return
        self.xas_process(self.groupname, **kws)
        self.onPlot()

    def onColumnChoices(self, evt=None):
        """column selections changed ..
        recalculate _xdat_ and _ydat_
        arrays for this larch group"""
        dtcorr = self.dtcorr.IsChecked()
        use_deriv = self.use_deriv.IsChecked()
        ix = self.xarr.GetSelection()
        x = self.xarr.GetStringSelection()
        xop = self.xop.GetStringSelection()
        op1 = self.yops[0].GetStringSelection()
        op2 = self.yops[1].GetStringSelection()
        op3 = self.yops[2].GetStringSelection()
        y1 = self.yarr[0].GetStringSelection()
        y2 = self.yarr[1].GetStringSelection()
        y3 = self.yarr[2].GetStringSelection()

        array_sel = {
            'xop': xop,
            'xarr': x,
            'op1': op1,
            'op2': op2,
            'op3': op3,
            'y1': y1,
            'y2': y2,
            'y3': y3,
            'dtcorr': dtcorr,
            'use_deriv': use_deriv
        }
        try:
            gname = self.groupname
            lgroup = getattr(self.larch.symtable, gname)
        except:
            gname = SCANGROUP
            lgroup = getattr(self.larch.symtable, gname)

        xlabel = x
        try:
            xunits = lgroup.array_units[ix]
        except:
            xunits = ''
        if xop != '':
            xlabel = "%s(%s)" % (xop, xlabel)
        if xunits != '':
            xlabel = '%s (%s)' % (xlabel, xunits)

        ylabel = y1
        if y2 == '':
            y2, op2 = '1.0', '*'
        else:
            ylabel = "%s%s%s" % (ylabel, op2, y2)
        if y3 == '':
            y3, op3 = '1.0', '*'
        else:
            ylabel = "(%s)%s%s" % (ylabel, op3, y3)

        if op1 != '':
            ylabel = "%s(%s)" % (op1, ylabel)

        if y1 in ('0.0', '1.0'):
            y1 = float(yl1)
        else:
            y1 = self.get_data(lgroup, y1, correct=dtcorr)

        if y2 in ('0.0', '1.0'):
            y2 = float(y2)
            if op2 == '/': y2 = 1.0
        else:
            y2 = self.get_data(lgroup, y2, correct=dtcorr)
        if y3 in ('0.0', '1.0'):
            y3 = float(y3)
            if op3 == '/': y3 = 1.0
        else:
            y3 = self.get_data(lgroup, y3, correct=dtcorr)
        if x not in ('0', '1'):
            x = self.get_data(lgroup, x)
        lgroup._x = x
        lgroup._y1 = y1
        lgroup._y2 = y2
        lgroup._y3 = y3

        self.larch("%s._xdat_ = %s(%s._x)" % (gname, xop, gname))
        try:
            yexpr = "%s._ydat_ = %s((%s._y1 %s %s._y2) %s %s._y3)" % (
                gname, op1, gname, op2, gname, op3, gname)
            self.larch(yexpr)
        except RuntimeWarning:
            self.larch("%s._ydat_ = %s._y1")

        try:
            if use_deriv:
                d_calc = "%s._ydat_ = gradient(%s._ydat_)/gradient(%s._xdat_)"
                self.larch(d_calc % (gname, gname, gname))
        except:
            pass

        try:
            npts = min(len(lgroup._xdat_), len(lgroup._ydat_))
        except AttributeError:
            print('Error calculating arrays (npts not correct)')
            return

        del lgroup._x, lgroup._y1, lgroup._y2, lgroup._y3

        lgroup.array_sel = array_sel
        lgroup.plot_xlabel = xlabel
        lgroup.plot_ylabel = ylabel
        lgroup._xdat_ = np.array(lgroup._xdat_[:npts])
        lgroup._ydat_ = np.array(lgroup._ydat_[:npts])

        if (self.nb.GetCurrentPage() == self.xas_panel):
            self.xas_process(self.groupname, new_mu=True)
        else:
            lgroup.plot_yarrays = [(lgroup._ydat_, {}, None)]

    def onPlot(self, evt=None, opt='new', npts=None, reprocess=False):

        try:
            self.plotframe.Show()
        except:  #  wx.PyDeadObjectError
            self.plotframe = PlotFrame(None, size=(650, 400))
            self.plotframe.Show()
            self.plotpanel = self.plotframe.panel

        if reprocess:
            if (self.nb.GetCurrentPage() == self.xas_panel):
                self.xas_process(self.groupname, new_mu=True)

        side = 'left'
        update = False
        plotcmd = self.plotpanel.plot
        if opt in ('left', 'right'):
            side = opt
            plotcmd = self.plotpanel.oplot
        elif opt == 'update' and npts > 4:
            plotcmd = self.plotpanel.update_line
            update = True
        if 'new' in opt:
            self.plotpanel.clear()
        popts = {'side': side}

        try:
            gname = self.groupname
            lgroup = getattr(self.larch.symtable, gname)
        except:
            gname = SCANGROUP
            lgroup = getattr(self.larch.symtable, gname)
            return

        if not hasattr(lgroup, '_xdat_'):
            self.onColumnChoices()

        lgroup._xdat_ = np.array(lgroup._xdat_[:npts])
        plot_yarrays = [(lgroup._ydat_, {}, None)]
        if hasattr(lgroup, 'plot_yarrays'):
            plot_yarrays = lgroup.plot_yarrays
        #for yarr in plot_yarrays:
        #    yarr = np.array(yarr[:npts])

        path, fname = os.path.split(lgroup.filename)
        popts['label'] = "%s: %s" % (fname, lgroup.plot_ylabel)
        if side == 'right':
            popts['y2label'] = lgroup.plot_ylabel
        else:
            popts['ylabel'] = lgroup.plot_ylabel

        if plotcmd == self.plotpanel.plot:
            popts['title'] = fname

        if update:
            self.plotpanel.set_xlabel(lgroup.plot_xlabel)
            self.plotpanel.set_ylabel(lgroup.plot_ylabel)
            for itrace, yarr, label in enumerate(plot_yarrays):
                plotcmd(itrace,
                        lgroup._xdat_,
                        yarr[0],
                        draw=True,
                        update_limits=((npts < 5) or (npts % 5 == 0)),
                        **yarr[1])
                self.plotpanel.set_xylims(
                    (min(lgroup._xdat_), max(lgroup._xdat_), min(yarr),
                     max(yarr)))

        else:
            for yarr in plot_yarrays:
                popts.update(yarr[1])
                if yarr[2] is not None:
                    popts['label'] = yarr[2]
                plotcmd(lgroup._xdat_, yarr[0], **popts)
                plotcmd = self.plotpanel.oplot
            if hasattr(lgroup, 'plot_ymarkers'):
                for x, y, opts in lgroup.plot_ymarkers:
                    popts = {'marker': 'o', 'markersize': 4}
                    popts.update(opts)
                    self.plotpanel.oplot([x], [y], **popts)
            self.plotpanel.canvas.draw()

    def onShowLarchBuffer(self, evt=None):
        if self.larch_buffer is None:
            self.larch_buffer = larchframe.LarchFrame(_larch=self.larch)

        self.larch_buffer.Show()
        self.larch_buffer.Raise()

    def ShowFile(self, evt=None, groupname=None, **kws):
        if groupname is None and evt is not None:
            fpath = self.file_paths[evt.GetInt()]
            groupname = self.file_groups[fpath]

        if not hasattr(self.datagroups, groupname):
            print('Error reading file ', groupname)
            return

        self.groupname = groupname
        self.lgroup = getattr(self.datagroups, groupname, None)

        if groupname == SCANGROUP:
            self.lgroup.filename = filename
        elif self.lgroup is not None:
            if hasattr(self.lgroup, 'array_labels'):
                array_labels = self.lgroup.array_labels[:]
            elif hasattr(self.lgroup, 'column_labels'):
                array_labels = self.lgroup.column_labels[:]
            else:
                array_labels = []
                for attr in dir(self.lgroup):
                    if isinstance(getattr(self.lgroup, attr), np.ndarray):
                        array_labels.append(attr)
                self.lgroup.array_labels = array_labels
            self.set_array_labels()
            if hasattr(self.lgroup, 'array_sel'):
                sel = self.lgroup.array_sel
                try:
                    self.xarr.SetStringSelection(sel['xarr'])
                    self.xop.SetStringSelection(sel['xop'])
                    self.yops[0].SetStringSelection(sel['op1'])
                    self.yops[1].SetStringSelection(sel['op2'])
                    self.yops[2].SetStringSelection(sel['op3'])
                    self.yarr[0].SetStringSelection(sel['y1'])
                    self.yarr[1].SetStringSelection(sel['y2'])
                    self.yarr[2].SetStringSelection(sel['y3'])
                    self.dtcorr.SetValue({True: 1, False: 0}[sel['dtcorr']])
                    self.use_deriv.SetValue({
                        True: 1,
                        False: 0
                    }[sel['use_deriv']])
                except:
                    pass

    def set_array_labels(self, labels=None):
        """set choices for array dropdowns from array labels"""
        array_labels = self.lgroup.array_labels
        xcols = array_labels[:]
        ycols = array_labels[:]
        y2cols = array_labels[:] + ['1.0', '0.0', '']
        ncols = len(xcols)
        self.title.SetLabel(self.lgroup.filename)

        _xarr = self.xarr.GetStringSelection()
        if len(_xarr) < 1 or _xarr not in xcols:
            _xarr = xcols[0]

        _yarr = [[], [], []]
        for j in range(3):
            _yarr[j] = self.yarr[j].GetStringSelection()
            if _yarr[j] not in ycols:
                _yarr[j] = ''

        self.xarr.SetItems(xcols)
        self.xarr.SetStringSelection(_xarr)
        for j in range(3):
            if j == 0:
                self.yarr[j].SetItems(ycols)
                if _yarr[j] in ycols and len(_yarr[j]) > 0:
                    self.yarr[j].SetStringSelection(_yarr[j])
                elif ycols[0] == _xarr and len(ycols) > 1:
                    self.yarr[j].SetStringSelection(ycols[1])
            else:
                self.yarr[j].SetItems(y2cols)
                self.yarr[j].SetStringSelection(_yarr[j])

        inb = 0
        for colname in xcols:
            if 'energ' in colname.lower():
                inb = 1
        self.nb.SetSelection(inb)
        if inb == 1:
            self.InitializeXASPanel()

    def createMenus(self):
        # ppnl = self.plotpanel
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        MenuItem(self, fmenu, "&Open Data File\tCtrl+O", "Read Scan File",
                 self.onReadScan)

        MenuItem(self, fmenu, "Show Larch Buffer",
                 "Show Larch Programming Buffer", self.onShowLarchBuffer)

        fmenu.AppendSeparator()

        MenuItem(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

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

        omenu = wx.Menu()
        MenuItem(self, omenu, "Edit Column Labels\tCtrl+E",
                 "Edit Column Labels", self.onEditColumnLabels)

        self.menubar.Append(omenu, "Options")

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

        #MenuItem(self, pmenu, "Unzoom\tCtrl+Z", "Unzoom Plot", self.onUnzoom)
        ##pmenu.AppendSeparator()
        #MenuItem(self, pmenu, "Toggle Legend\tCtrl+L",
        #         "Toggle Legend on Plot", self.onToggleLegend)
        #MenuItem(self, pmenu, "Toggle Grid\tCtrl+G",
        #         "Toggle Grid on Plot", self.onToggleGrid)
        # self.menubar.Append(pmenu, "Plot Options")
        self.SetMenuBar(self.menubar)
        self.Bind(wx.EVT_CLOSE, self.onClose)

    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):
        save_workdir('scanviewer.dat')

        try:
            self.plotframe.Destroy()
        except:
            pass
        if self.larch_buffer is not None:
            try:
                self.larch_buffer.onClose()
            except:
                pass

        for nam in dir(self.larch.symtable._sys.wx):
            obj = getattr(self.larch.symtable._sys.wx, nam)
            del obj

        self.Destroy()

    def show_subframe(self, name, frameclass):
        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)

    def onEditColumnLabels(self, evt=None):
        self.show_subframe('coledit', EditColumnFrame)

    def onReadScan(self, evt=None):
        dlg = wx.FileDialog(self,
                            message="Load Column 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.file_groups:
                if wx.ID_YES != popup(self, "Re-read file '%s'?" % path,
                                      'Re-read file?'):
                    return

            gname = '_sview0001'
            count, maxcount = 1, 9999
            while hasattr(self.datagroups, gname) and count < maxcount:
                count += 1
                gname = '_sview%4.4i' % count

            if hasattr(self.datagroups, gname):
                gname = randname()

            parent, fname = os.path.split(path)
            if self.config['chdir_on_fileopen']:
                os.chdir(parent)

            fh = open(path, 'r')
            line1 = fh.readline().lower()
            fh.close()
            reader = 'read_ascii'
            if 'epics scan' in line1:
                reader = 'read_gsescan'
            elif 'xdi' in line1:
                reader = 'read_xdi'
                if 'epics stepscan file' in line1:
                    reader = 'read_gsexdi'

            self.larch("%s = %s('%s')" % (gname, reader, path))
            self.larch("%s.path  = '%s'" % (gname, path))
            self.filelist.Append(fname)
            self.file_paths.append(path)
            self.file_groups[path] = gname

            self.ShowFile(groupname=gname)

        dlg.Destroy()
Exemplo n.º 17
0
class XRFCalibrationFrame(wx.Frame):
    def __init__(self, parent, mca, larch=None, size=(-1, -1), callback=None):
        self.mca = mca
        self.larch = larch
        self.callback = callback
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Calibrate MCA',
                          size=size,
                          style=wx.DEFAULT_FRAME_STYLE)

        self.SetFont(Font(8))
        panel = GridPanel(self)
        self.calib_updated = False
        panel.AddText("Calibrate MCA Energy (Energies in eV)",
                      colour='#880000',
                      dcol=7)
        panel.AddText("ROI", newrow=True, style=CEN)
        panel.AddText("Predicted", style=CEN)
        panel.AddText("Peaks with Current Calibration", dcol=3, style=CEN)
        panel.AddText("Peaks with Refined Calibration", dcol=3, style=CEN)

        panel.AddText("Name", newrow=True, style=CEN)
        panel.AddText("Energy", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Use? ", style=CEN)

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        self.wids = []

        # find ROI peak positions
        xrf_calib_fitrois(mca, _larch=self.larch)

        for roi in self.mca.rois:
            try:
                eknown, ecen, fwhm, amp, fit = mca.init_calib[roi.name]
            except:
                continue
            diff = ecen - eknown
            name = ('   ' + roi.name + ' ' * 10)[:10]
            opts = {'style': CEN, 'size': (75, -1)}
            w_name = SimpleText(panel, name, **opts)
            w_pred = SimpleText(panel, "% .1f" % (1000 * eknown), **opts)
            w_ccen = SimpleText(panel, "% .1f" % (1000 * ecen), **opts)
            w_cdif = SimpleText(panel, "% .1f" % (1000 * diff), **opts)
            w_cwid = SimpleText(panel, "% .1f" % (1000 * fwhm), **opts)
            w_ncen = SimpleText(panel, "-----", **opts)
            w_ndif = SimpleText(panel, "-----", **opts)
            w_nwid = SimpleText(panel, "-----", **opts)
            w_use = Check(panel,
                          label='use?',
                          size=(40, -1),
                          default=fwhm < 0.50)

            panel.Add(w_name, style=LEFT, newrow=True)
            panel.AddMany((w_pred, w_ccen, w_cdif, w_cwid, w_ncen, w_ndif,
                           w_nwid, w_use))

            self.wids.append(
                (roi.name, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use))

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        offset = 1000.0 * self.mca.offset
        slope = 1000.0 * self.mca.slope
        panel.AddText("Current Calibration:", dcol=2, newrow=True)
        panel.AddText("offset(eV):")
        panel.AddText("%.3f" % (offset), dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.AddText("%.3f" % (slope), dcol=1, style=RIGHT)

        panel.AddText("Refined Calibration:", dcol=2, newrow=True)
        self.new_offset = FloatCtrl(panel,
                                    value=offset,
                                    precision=3,
                                    size=(80, -1))
        self.new_slope = FloatCtrl(panel,
                                   value=slope,
                                   precision=3,
                                   size=(80, -1))
        panel.AddText("offset(eV):")
        panel.Add(self.new_offset, dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.Add(self.new_slope, dcol=1, style=RIGHT)

        panel.Add(Button(panel,
                         'Compute Calibration',
                         size=(125, -1),
                         action=self.onCalibrate),
                  dcol=2,
                  newrow=True)

        panel.Add(Button(panel,
                         'Use New Calibration',
                         size=(125, -1),
                         action=self.onUseCalib),
                  dcol=2,
                  style=RIGHT)

        panel.Add(Button(panel, 'Done', size=(125, -1), action=self.onClose),
                  dcol=2,
                  style=RIGHT)

        panel.pack()
        a = panel.GetBestSize()
        self.SetSize((a[0] + 25, a[1] + 50))
        self.Show()
        self.Raise()

    def onCalibrate(self, event=None):
        x, y = [], []
        mca = self.mca
        # save old calib
        old_calib = mca.offset, mca.slope
        init_calib = copy.deepcopy(mca.init_calib)
        for roiname, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use in self.wids:
            if not w_use.IsChecked():
                mca.init_calib.pop(roiname)

        xrf_calib_compute(mca, apply=True, _larch=self.larch)
        offset, slope = mca.new_calib
        self.calib_updated = True
        self.new_offset.SetValue("% .3f" % (1000 * offset))
        self.new_slope.SetValue("% .3f" % (1000 * slope))

        # find ROI peak positions using this new calibration
        xrf_calib_fitrois(mca, _larch=self.larch)
        for roi in self.mca.rois:
            try:
                eknown, ecen, fwhm, amp, fit = mca.init_calib[roi.name]
            except:
                continue

            diff = ecen - eknown
            for roiname, eknown, ocen, w_ncen, w_ndif, w_nwid, w_use in self.wids:
                if roiname == roi.name:
                    w_ncen.SetLabel("%.1f" % (1000 * ecen))
                    w_ndif.SetLabel("% .1f" % (1000 * diff))
                    w_nwid.SetLabel("%.1f" % (1000 * fwhm))
                    break

        # restore calibration to old values until new values are accepted
        xrf_calib_apply(mca,
                        offset=old_calib[0],
                        slope=old_calib[1],
                        _larch=self.larch)
        mca.init_calib = init_calib

        tsize = self.GetSize()
        self.SetSize((tsize[0] + 1, tsize[1]))
        self.SetSize((tsize[0], tsize[1]))

    def onUseCalib(self, event=None):
        mca = self.mca
        offset = float(self.new_offset.GetValue())
        slope = float(self.new_slope.GetValue())
        mca.new_calib = offset, slope
        xrf_calib_apply(mca, offset=offset, slope=slope, _larch=self.larch)
        if hasattr(self.callback, '__call__'):
            self.callback(offset, slope, mca=mca)
        self.Destroy()

    def onClose(self, event=None):
        self.Destroy()
Exemplo n.º 18
0
    def settings_page(self):
        "create fit and background settings"
        mca = self.parent.mca
        conf = self.parent.conf
        wids = self.wids

        width = getattr(mca, 'bgr_width', 4)
        compr = getattr(mca, 'bgr_compress', 2)
        expon = getattr(mca, 'bgr_exponent', 2)

        p = GridPanel(self, itemstyle=LEFT)
        wids.bgr_use = Check(p,
                             label='Fit Background-Subtracted Spectra',
                             default=True)
        wids.bgr_width = FloatCtrl(p,
                                   value=width,
                                   minval=0,
                                   maxval=10,
                                   precision=1,
                                   size=(70, -1))
        wids.bgr_compress = Choice(p,
                                   choices=['1', '2', '4', '8', '16'],
                                   size=(70, -1),
                                   default=1)
        wids.bgr_exponent = Choice(p,
                                   choices=['2', '4', '6'],
                                   size=(70, -1),
                                   default=0)

        sopts = {'vary': True, 'precision': 5}
        sig_offset = Parameter(value=0.050, name=self.gsig_offset, vary=True)
        sig_slope = Parameter(value=0.005, name=self.gsig_slope, vary=True)
        sig_quad = Parameter(value=0.000, name=self.gsig_quad, vary=False)

        setattr(self.paramgroup, self.gsig_offset, sig_offset)
        setattr(self.paramgroup, self.gsig_slope, sig_slope)
        setattr(self.paramgroup, self.gsig_quad, sig_quad)

        wids.sig_offset = ParameterPanel(p, sig_offset, vary=True, precision=5)
        wids.sig_slope = ParameterPanel(p, sig_slope, vary=True, precision=5)
        wids.sig_quad = ParameterPanel(p, sig_quad, vary=False, precision=5)

        wids.xray_en = FloatCtrl(p,
                                 value=20.0,
                                 size=(70, -1),
                                 minval=0,
                                 maxval=1000,
                                 precision=3)

        wids.fit_emin = FloatCtrl(p,
                                  value=conf.e_min,
                                  size=(70, -1),
                                  minval=0,
                                  maxval=1000,
                                  precision=3)
        wids.fit_emax = FloatCtrl(p,
                                  value=conf.e_max,
                                  size=(70, -1),
                                  minval=0,
                                  maxval=1000,
                                  precision=3)
        wids.flyield_use = Check(
            p, label='Account for Absorption, Fluorescence Efficiency')

        p.AddText(' General Settings ', colour='#880000', dcol=3)

        p.AddText(' X-ray Energy (keV): ', newrow=True)
        p.Add(wids.xray_en)
        p.AddText(' Min Energy (keV): ', newrow=True)
        p.Add(wids.fit_emin)
        p.AddText(' Max Energy (keV): ', newrow=False)
        p.Add(wids.fit_emax)

        wids.det_mat = Choice(p,
                              choices=self.Detector_Materials,
                              size=(55, -1),
                              default=0)
        wids.det_thk = FloatCtrl(p,
                                 value=0.40,
                                 size=(70, -1),
                                 minval=0,
                                 maxval=100,
                                 precision=3)
        wids.det_use = Check(p, label='Account for Detector Thickness')

        p.AddText(' Detector Material:  ', newrow=True)
        p.Add(wids.det_mat)
        p.AddText(' Thickness (mm): ', newrow=False)
        p.Add(wids.det_thk)
        p.Add(wids.det_use, dcol=4, newrow=True)
        p.Add(wids.flyield_use, dcol=4, newrow=True)

        p.Add(HLine(p, size=(600, 3)), dcol=5, newrow=True)

        p.AddText(' Energy Dependence of Peak Width:',
                  colour='#880000',
                  newrow=True,
                  dcol=2)
        # p.AddText(' ', newrow=True)
        p.AddText(' sigma = offset + slope * Energy + quad * Energy^2 (keV)',
                  dcol=3)
        p.AddText(' Offset: ', newrow=True)
        p.Add(wids.sig_offset, dcol=3)
        p.AddText(' Slope: ', newrow=True)
        p.Add(wids.sig_slope, dcol=3)
        p.AddText(' Quad: ', newrow=True)
        p.Add(wids.sig_quad, dcol=3)
        p.Add(HLine(p, size=(600, 3)), dcol=5, newrow=True)

        p.AddText(" Background Parameters: ",
                  colour='#880000',
                  dcol=2,
                  newrow=True)
        p.Add(wids.bgr_use, dcol=2)

        p.AddText(" Exponent:", newrow=True)
        p.Add(wids.bgr_exponent)
        p.AddText(" Energy Width (keV): ", newrow=False)
        p.Add(wids.bgr_width)

        p.AddText(" Compression: ", newrow=True)
        p.Add(wids.bgr_compress)
        p.Add(Button(p,
                     'Show Background',
                     size=(130, -1),
                     action=self.onShowBgr),
              dcol=2)

        p.Add(HLine(p, size=(600, 3)), dcol=5, newrow=True)
        p.pack()
        return p
Exemplo n.º 19
0
    def __init__(self, parent, mca, larch=None, size=(-1, -1), callback=None):
        self.mca = mca
        self.larch = larch
        self.callback = callback
        wx.Frame.__init__(self,
                          parent,
                          -1,
                          'Calibrate MCA',
                          size=size,
                          style=wx.DEFAULT_FRAME_STYLE)

        self.SetFont(Font(8))
        panel = GridPanel(self)
        self.calib_updated = False
        panel.AddText("Calibrate MCA Energy (Energies in eV)",
                      colour='#880000',
                      dcol=7)
        panel.AddText("ROI", newrow=True, style=CEN)
        panel.AddText("Predicted", style=CEN)
        panel.AddText("Peaks with Current Calibration", dcol=3, style=CEN)
        panel.AddText("Peaks with Refined Calibration", dcol=3, style=CEN)

        panel.AddText("Name", newrow=True, style=CEN)
        panel.AddText("Energy", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Center", style=CEN)
        panel.AddText("Difference", style=CEN)
        panel.AddText("FWHM", style=CEN)
        panel.AddText("Use? ", style=CEN)

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        self.wids = []

        # find ROI peak positions
        xrf_calib_fitrois(mca, _larch=self.larch)

        for roi in self.mca.rois:
            try:
                eknown, ecen, fwhm, amp, fit = mca.init_calib[roi.name]
            except:
                continue
            diff = ecen - eknown
            name = ('   ' + roi.name + ' ' * 10)[:10]
            opts = {'style': CEN, 'size': (75, -1)}
            w_name = SimpleText(panel, name, **opts)
            w_pred = SimpleText(panel, "% .1f" % (1000 * eknown), **opts)
            w_ccen = SimpleText(panel, "% .1f" % (1000 * ecen), **opts)
            w_cdif = SimpleText(panel, "% .1f" % (1000 * diff), **opts)
            w_cwid = SimpleText(panel, "% .1f" % (1000 * fwhm), **opts)
            w_ncen = SimpleText(panel, "-----", **opts)
            w_ndif = SimpleText(panel, "-----", **opts)
            w_nwid = SimpleText(panel, "-----", **opts)
            w_use = Check(panel,
                          label='use?',
                          size=(40, -1),
                          default=fwhm < 0.50)

            panel.Add(w_name, style=LEFT, newrow=True)
            panel.AddMany((w_pred, w_ccen, w_cdif, w_cwid, w_ncen, w_ndif,
                           w_nwid, w_use))

            self.wids.append(
                (roi.name, eknown, ecen, w_ncen, w_ndif, w_nwid, w_use))

        panel.Add(HLine(panel, size=(700, 3)), dcol=9, newrow=True)
        offset = 1000.0 * self.mca.offset
        slope = 1000.0 * self.mca.slope
        panel.AddText("Current Calibration:", dcol=2, newrow=True)
        panel.AddText("offset(eV):")
        panel.AddText("%.3f" % (offset), dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.AddText("%.3f" % (slope), dcol=1, style=RIGHT)

        panel.AddText("Refined Calibration:", dcol=2, newrow=True)
        self.new_offset = FloatCtrl(panel,
                                    value=offset,
                                    precision=3,
                                    size=(80, -1))
        self.new_slope = FloatCtrl(panel,
                                   value=slope,
                                   precision=3,
                                   size=(80, -1))
        panel.AddText("offset(eV):")
        panel.Add(self.new_offset, dcol=1, style=RIGHT)
        panel.AddText("slope(eV/chan):")
        panel.Add(self.new_slope, dcol=1, style=RIGHT)

        panel.Add(Button(panel,
                         'Compute Calibration',
                         size=(125, -1),
                         action=self.onCalibrate),
                  dcol=2,
                  newrow=True)

        panel.Add(Button(panel,
                         'Use New Calibration',
                         size=(125, -1),
                         action=self.onUseCalib),
                  dcol=2,
                  style=RIGHT)

        panel.Add(Button(panel, 'Done', size=(125, -1), action=self.onClose),
                  dcol=2,
                  style=RIGHT)

        panel.pack()
        a = panel.GetBestSize()
        self.SetSize((a[0] + 25, a[1] + 50))
        self.Show()
        self.Raise()
Exemplo n.º 20
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)
Exemplo n.º 21
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)
Exemplo n.º 22
0
    def __init__(self, parent, param, precision=4, vary=None, **kws):
        self.param = param
        title = "  Parameter:  %s  " % (param.name)
        wx.Dialog.__init__(self, parent, wx.ID_ANY, title=title)
        panel = GridPanel(self)
        self.SetFont(parent.GetFont())

        if vary is None:
            vary = 0
            if param.vary:
                vary = 1
            elif param.expr is not None:
                vary = 2

        minval, maxval = param.min, param.max
        stderr, expr = param.stderr, param.expr
        sminval = "%s" % minval
        smaxval = "%s" % maxval
        if minval in (None, 'None', -np.inf): minval = -np.inf
        if maxval in (None, 'None', np.inf): maxval = np.inf
        if stderr is None: stderr = ''
        if expr is None: expr = ''

        self.wids = Empty()
        self.wids.vary = Choice(panel,
                                choices=VARY_CHOICES,
                                action=self.onVaryChoice,
                                size=(110, -1))
        self.wids.vary.SetSelection(vary)

        self.wids.val = FloatCtrl(panel,
                                  value=param.value,
                                  size=(100, -1),
                                  precision=precision,
                                  minval=minval,
                                  maxval=maxval)
        self.wids.min = FloatCtrl(panel, value=minval, size=(100, -1))
        self.wids.max = FloatCtrl(panel, value=maxval, size=(100, -1))
        self.wids.expr = wx.TextCtrl(panel, value=expr, size=(300, -1))
        self.wids.err = wx.StaticText(panel, label="%s" % stderr)

        SetTip(self.wids.expr, "Mathematical expression to calcutate value")

        btnsizer = wx.StdDialogButtonSizer()
        ok_btn = wx.Button(panel, wx.ID_OK)
        ok_btn.SetDefault()
        btnsizer.AddButton(ok_btn)
        btnsizer.AddButton(wx.Button(panel, wx.ID_CANCEL))
        btnsizer.Realize()

        panel.AddText(' Name:', style=LEFT)
        panel.AddText(param.name, style=LEFT)
        panel.AddText(' Type:', style=LEFT)
        panel.Add(self.wids.vary, style=LEFT)
        panel.AddText(' Value:', style=LEFT, newrow=True)
        panel.Add(self.wids.val, style=LEFT)
        panel.AddText(' Std Error:', style=LEFT)
        panel.Add(self.wids.err, style=LEFT)
        panel.AddText(' Min Value:', style=LEFT, newrow=True)
        panel.Add(self.wids.min, style=LEFT)
        panel.AddText(' Max Value:', style=LEFT)
        panel.Add(self.wids.max, style=LEFT)
        panel.AddText(' Constraint:', style=LEFT, newrow=True)
        panel.Add(self.wids.expr, style=LEFT, dcol=3)

        panel.Add(HLine(panel, size=(375, 2)), dcol=4, newrow=True)
        panel.Add(btnsizer, dcol=4, newrow=True, style=LEFT)
        panel.pack()

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(panel, 0, 0, 25)
        self.onVaryChoice()
        pack(self, sizer)
        bsize = self.GetBestSize()
        self.SetSize((bsize[0] + 10, bsize[1] + 10))
Exemplo n.º 23
0
class ScanViewerFrame(wx.Frame):
    _about = """Scan 2D Plotter
  Matt Newville <newville @ cars.uchicago.edu>
  """

    def __init__(self, parent=None, size=(850, 650), _larch=None, **kws):
        wx.Frame.__init__(self, parent, -1, size=size, style=FRAMESTYLE)
        self.file_groups = {}
        self.last_array_sel = {}
        title = "Column Data File Viewer"
        self.larch = _larch
        self.larch_buffer = None
        self.subframes = {}
        self.plotframe = None
        self.groupname = None
        self.SetTitle(title)
        self.SetSize(size)
        self.SetFont(Font(10))

        self.config = {'chdir_on_fileopen': True}

        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)
        read_workdir('scanviewer.dat')
        self.need_xas_update = False
        self.xas_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onXASProcessTimer, self.xas_timer)
        self.xas_timer.Start(500)

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

        self.filelist = EditableCheckListBox(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.plot_one = Button(panel,
                               'Plot',
                               size=(200, 30),
                               action=self.onPlotOne)
        self.plot_sel = Button(panel,
                               'Plot Selected',
                               size=(200, 30),
                               action=self.onPlotSel)

        ir += 1
        sizer.Add(self.plot_one, (ir, 0), (1, 2), LCEN, 0)
        sizer.Add(self.plot_sel, (ir, 2), (1, 2), LCEN, 0)
        pack(panel, sizer)

        mainsizer.Add(panel, 0, LCEN | wx.EXPAND, 2)

        o = """
        btnbox   = wx.Panel(mainpanel)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)
        for ttl, opt in (('New Plot',   'new'),
                         ('Over Plot (left)',  'left'),
                         ('Over Plot (right)', 'right')):

            btnsizer.Add(Button(btnbox, ttl, size=(135, -1),
                                action=partial(self.onPlot, opt=opt)),
                         LCEN, 1)

        pack(btnbox, btnsizer)
        mainsizer.Add(btnbox, 0, LCEN, 2)
        """

        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 Curve Fitting ', True)
        self.nb.AddPage(self.xas_panel, ' XAS Processing ', True)

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

        pack(mainpanel, mainsizer)

        return mainpanel

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

        tsizer = wx.GridBagSizer(10, 4)
        tsizer.Add(SimpleText(tpan, 'Fit Model: '), (0, 0), (1, 1), LCEN)
        tsizer.Add(self.fit_model, (0, 1), (1, 1), LCEN)

        tsizer.Add(SimpleText(tpan, 'Background: '), (0, 2), (1, 1), LCEN)
        tsizer.Add(self.fit_bkg, (0, 3), (1, 1), LCEN)

        tsizer.Add(
            Button(tpan, 'Show Fit', size=(100, -1), action=self.onFitPeak),
            (1, 1), (1, 1), LCEN)

        tsizer.Add(SimpleText(tpan, 'Step Form: '), (1, 2), (1, 1), LCEN)
        tsizer.Add(self.fit_step, (1, 3), (1, 1), LCEN)

        pack(tpan, tsizer)

        self.fit_report = RichTextCtrl(panel,
                                       size=(525, 250),
                                       style=wx.VSCROLL | wx.NO_BORDER)

        self.fit_report.SetEditable(False)
        self.fit_report.SetFont(Font(9))

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(tpan, 0, wx.GROW | wx.ALL, 2)
        sizer.Add(self.fit_report, 1, LCEN | wx.GROW, 2)
        pack(panel, sizer)
        return panel

    def InitializeXASPanel(self, dgroup):
        predefs = dict(e0=0,
                       pre1=-200,
                       pre2=-30,
                       norm1=50,
                       edge_step=0,
                       norm2=-10,
                       nnorm=3,
                       nvict=2,
                       auto_step=True,
                       auto_e0=True,
                       show_e0=True)

        if hasattr(dgroup, 'pre_edge_details'):
            predefs.update(group2dict(dgroup.pre_edge_details))

        self.xas_e0.SetValue(predefs['e0'])
        self.xas_step.SetValue(predefs['edge_step'])
        self.xas_pre1.SetValue(predefs['pre1'])
        self.xas_pre2.SetValue(predefs['pre2'])
        self.xas_nor1.SetValue(predefs['norm1'])
        self.xas_nor2.SetValue(predefs['norm2'])
        self.xas_vict.SetSelection(predefs['nvict'])
        self.xas_nnor.SetSelection(predefs['nnorm'])

        self.xas_showe0.SetValue(predefs['show_e0'])
        self.xas_autoe0.SetValue(predefs['auto_e0'])
        self.xas_autostep.SetValue(predefs['auto_step'])

    def CreateXASPanel(self, parent):
        opchoices = ('Raw Data', 'Normalized', 'Derivative',
                     'Normalized + Derivative', 'Pre-edge subtracted',
                     'Raw Data + Pre-edge/Post-edge')
        p = panel = wx.Panel(parent)
        opts = {'action': self.UpdateXASPlot}
        self.xas_autoe0 = Check(panel, default=True, label='auto?', **opts)
        self.xas_showe0 = Check(panel, default=True, label='show?', **opts)
        self.xas_autostep = Check(panel, default=True, label='auto?', **opts)
        self.xas_op = Choice(panel, size=(300, -1), choices=opchoices, **opts)

        self.btns = {}
        for name in ('e0', 'pre1', 'pre2', 'nor1', 'nor2'):
            bb = BitmapButton(panel,
                              get_icon('plus'),
                              action=partial(self.onXAS_selpoint, opt=name),
                              tooltip='use last point selected from plot')
            self.btns[name] = bb

        opts = {'size': (85, -1), 'precision': 3, 'action': self.UpdateXASPlot}
        self.xwids = {}
        self.xas_e0 = FloatCtrl(panel, value=0, **opts)
        self.xas_step = FloatCtrl(panel, value=0, **opts)
        opts['precision'] = 1
        self.xas_pre1 = FloatCtrl(panel, value=-200, **opts)
        self.xas_pre2 = FloatCtrl(panel, value=-30, **opts)
        self.xas_nor1 = FloatCtrl(panel, value=50, **opts)
        self.xas_nor2 = FloatCtrl(panel, value=-50, **opts)

        opts = {
            'size': (50, -1),
            'choices': ('0', '1', '2', '3'),
            'action': self.UpdateXASPlot
        }
        self.xas_vict = Choice(panel, **opts)
        self.xas_nnor = Choice(panel, **opts)
        self.xas_vict.SetSelection(1)
        self.xas_nnor.SetSelection(2)
        sizer = wx.GridBagSizer(10, 7)

        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, 6), LCEN)
        sizer.Add(self.btns['e0'], (1, 1), (1, 1), LCEN)
        sizer.Add(self.xas_e0, (1, 2), (1, 1), LCEN)
        sizer.Add(self.xas_autoe0, (1, 3), (1, 3), LCEN)
        sizer.Add(self.xas_showe0, (1, 6), (1, 2), LCEN)

        sizer.Add(self.xas_step, (2, 2), (1, 1), LCEN)
        sizer.Add(self.xas_autostep, (2, 3), (1, 3), LCEN)

        sizer.Add(self.btns['pre1'], (3, 1), (1, 1), LCEN)
        sizer.Add(self.xas_pre1, (3, 2), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (3, 3), (1, 1), LCEN)
        sizer.Add(self.btns['pre2'], (3, 4), (1, 1), LCEN)
        sizer.Add(self.xas_pre2, (3, 5), (1, 1), LCEN)
        sizer.Add(self.btns['nor1'], (4, 1), (1, 1), LCEN)
        sizer.Add(self.xas_nor1, (4, 2), (1, 1), LCEN)
        sizer.Add(SimpleText(p, ':'), (4, 3), (1, 1), LCEN)
        sizer.Add(self.btns['nor2'], (4, 4), (1, 1), LCEN)
        sizer.Add(self.xas_nor2, (4, 5), (1, 1), LCEN)

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

        pack(panel, sizer)
        return panel

    def onXAS_selpoint(self, evt=None, opt='e0'):
        xval = None
        try:
            xval = self.larch.symtable._plotter.plot1_x
        except:
            pass
        if xval is None:
            return

        e0 = self.xas_e0.GetValue()
        if opt == 'e0':
            self.xas_e0.SetValue(xval)
            self.xas_autoe0.SetValue(0)
        elif opt == 'pre1':
            self.xas_pre1.SetValue(xval - e0)
        elif opt == 'pre2':
            self.xas_pre2.SetValue(xval - e0)
        elif opt == 'nor1':
            self.xas_nor1.SetValue(xval - e0)
        elif opt == 'nor2':
            self.xas_nor2.SetValue(xval - e0)

    def onCustomColumns(self, evt=None):
        pass

    def onFitPeak(self, evt=None):
        gname = self.groupname

        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)

        try:
            lgroup = getattr(self.larch.symtable, gname)
            x = lgroup._xdat
            y = lgroup._ydat
        except AttributeError:
            self.write_message('need data to fit!')
            return
        if step.startswith('error'):
            step = 'erf'
        elif step.startswith('arctan'):
            step = 'atan'

        pgroup = fit_peak(x,
                          y,
                          model,
                          background=bkg,
                          step=step,
                          _larch=self.larch)

        dtext = '\n'.join(dtext)
        dtext = '%s\n%s\n' % (
            dtext, fit_report(
                pgroup.params, min_correl=0.25, _larch=self.larch))

        self.fit_report.SetEditable(True)
        self.fit_report.SetValue(dtext)
        self.fit_report.SetEditable(False)

        lgroup.plot_yarrays = [(lgroup._ydat, PLOTOPTS_1, lgroup.plot_ylabel)]
        if bkg is None:
            lgroup._fit = pgroup.fit[:]
            lgroup.plot_yarrays.append((lgroup._fit, PLOTOPTS_2, 'fit'))
        else:
            lgroup._fit = pgroup.fit[:]
            lgroup._fit_bgr = pgroup.bkg[:]
            lgroup.plot_yarrays.append((lgroup._fit, PLOTOPTS_2, 'fit'))
            lgroup.plot_yarrays.append(
                (lgroup._fit_bgr, PLOTOPTS_2, 'background'))
        self.plot_group(gname, new=True)

    def xas_process(self, gname, new_mu=False, **kws):
        """ process (pre-edge/normalize) XAS data from XAS form, overwriting
        larch group '_y1_' attribute to be plotted
        """
        dgroup = getattr(self.larch.symtable, gname)

        if not hasattr(dgroup, 'energy'):
            dgroup.energy = dgroup._xdat
        if not hasattr(dgroup, 'mu'):
            dgroup.mu = dgroup._ydat

        e0 = None
        if not self.xas_autoe0.IsChecked():
            _e0 = self.xas_e0.GetValue()
            if _e0 < max(dgroup.energy) and _e0 > min(dgroup.energy):
                e0 = float(_e0)

        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['make_flat'] = False
        preopts['_larch'] = self.larch

        pre_edge(dgroup, **preopts)
        dgroup.pre_edge_details.e0 = dgroup.e0
        dgroup.pre_edge_details.edge_step = dgroup.edge_step
        dgroup.pre_edge_details.auto_e0 = self.xas_autoe0.IsChecked()
        dgroup.pre_edge_details.show_e0 = self.xas_showe0.IsChecked()
        dgroup.pre_edge_details.auto_step = self.xas_autostep.IsChecked()

        if self.xas_autoe0.IsChecked():
            self.xas_e0.SetValue(dgroup.e0)
        if self.xas_autostep.IsChecked():
            self.xas_step.SetValue(dgroup.edge_step)

        details_group = dgroup.pre_edge_details
        self.xas_pre1.SetValue(details_group.pre1)
        self.xas_pre2.SetValue(details_group.pre2)
        self.xas_nor1.SetValue(details_group.norm1)
        self.xas_nor2.SetValue(details_group.norm2)

        dgroup.orig_ylabel = dgroup.plot_ylabel
        dgroup.plot_ylabel = '$\mu$'
        dgroup.plot_y2label = None
        dgroup.plot_xlabel = '$E \,\mathrm{(eV)}$'
        dgroup.plot_yarrays = [(dgroup.mu, PLOTOPTS_1, dgroup.plot_ylabel)]
        y4e0 = dgroup.mu

        out = self.xas_op.GetStringSelection().lower()  # raw, pre, norm, flat
        if out.startswith('raw data + pre'):
            dgroup.plot_yarrays = [(dgroup.mu, PLOTOPTS_1, '$\mu$'),
                                   (dgroup.pre_edge, PLOTOPTS_2, 'pre edge'),
                                   (dgroup.post_edge, PLOTOPTS_2, 'post edge')]
        elif out.startswith('pre'):
            dgroup.pre_edge_sub = dgroup.norm * dgroup.edge_step
            dgroup.plot_yarrays = [(dgroup.pre_edge_sub, PLOTOPTS_1,
                                    'pre-edge subtracted $\mu$')]
            y4e0 = dgroup.pre_edge_sub
            dgroup.plot_ylabel = 'pre-edge subtracted $\mu$'
        elif 'norm' in out and 'deriv' in out:
            dgroup.plot_yarrays = [(dgroup.norm, PLOTOPTS_1,
                                    'normalized $\mu$'),
                                   (dgroup.dmude, PLOTOPTS_D, '$d\mu/dE$')]
            y4e0 = dgroup.norm
            dgroup.plot_ylabel = 'normalized $\mu$'
            dgroup.plot_y2label = '$d\mu/dE$'
        elif out.startswith('norm'):
            dgroup.plot_yarrays = [(dgroup.norm, PLOTOPTS_1,
                                    'normalized $\mu$')]
            y4e0 = dgroup.norm
            dgroup.plot_ylabel = 'normalized $\mu$'
        elif out.startswith('deriv'):
            dgroup.plot_yarrays = [(dgroup.dmude, PLOTOPTS_1, '$d\mu/dE$')]
            y4e0 = dgroup.dmude
            dgroup.plot_ylabel = '$d\mu/dE$'

        dgroup.plot_ymarkers = []
        if self.xas_showe0.IsChecked():
            ie0 = index_of(dgroup._xdat, dgroup.e0)
            dgroup.plot_ymarkers = [(dgroup.e0, y4e0[ie0], {'label': 'e0'})]
        return

    def init_larch(self):
        t0 = time.time()
        if self.larch is None:
            self.larch = Interpreter()
        self.larch.symtable.set_symbol('_sys.wx.wxapp', wx.GetApp())
        self.larch.symtable.set_symbol('_sys.wx.parent', self)

        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 onXASProcessTimer(self, evt=None):
        if self.groupname is None:
            return
        if self.need_xas_update:
            self.xas_process(self.groupname)
            self.plot_group(self.groupname, new=True)
            self.need_xas_update = False

    def UpdateXASPlot(self, evt=None, **kws):
        self.need_xas_update = True

    def onPlotOne(self, evt=None, groupname=None):
        if groupname is None:
            groupname = self.groupname

        dgroup = getattr(self.larch.symtable, groupname, None)
        if dgroup is None:
            return
        self.groupname = groupname
        if (dgroup.is_xas and (getattr(dgroup, 'plot_yarrays', None) is None
                               or getattr(dgroup, 'energy', None) is None
                               or getattr(dgroup, 'mu', None) is None)):
            self.xas_process(groupname)
        self.plot_group(groupname, new=True)

    def onPlotSel(self, evt=None):
        newplot = True
        group_ids = self.filelist.GetCheckedStrings()
        for checked in group_ids:
            groupname = self.file_groups[str(checked)]
            dgroup = getattr(self.larch.symtable, groupname, None)
            if dgroup is None:
                continue
            if dgroup.is_xas:
                if ((getattr(dgroup, 'plot_yarrays', None) is None
                     or getattr(dgroup, 'energy', None) is None
                     or getattr(dgroup, 'mu', None) is None)):
                    self.xas_process(groupname)

                dgroup.plot_yarrays = [(dgroup.norm, PLOTOPTS_1,
                                        '%s norm' % dgroup._filename)]
                dgroup.plot_ylabel = 'normalized $\mu$'
                dgroup.plot_xlabel = '$E\,\mathrm{(eV)}$'
                dgroup.plot_ymarkers = []

            else:
                dgroup.plot_yarrays = [(dgroup._ydat, PLOTOPTS_1,
                                        dgroup._filename)]

            self.plot_group(groupname, title='', new=newplot)
            newplot = False

    def plot_group(self, groupname, title=None, new=True):

        oplot = self.larch.symtable._plotter.plot
        newplot = self.larch.symtable._plotter.newplot
        getdisplay = self.larch.symtable._plotter.get_display

        plotcmd = oplot
        if new:
            plotcmd = newplot

        dgroup = getattr(self.larch.symtable, groupname, None)
        if not hasattr(dgroup, '_xdat'):
            print("Cannot plot group ", groupname)

        if hasattr(dgroup, 'plot_yarrays'):
            plot_yarrays = dgroup.plot_yarrays
        else:
            plot_yarrays = [(dgroup._ydat, {}, None)]
        # print("Plt Group ", groupname, hasattr(dgroup,'plot_yarrays'))

        popts = {}
        path, fname = os.path.split(dgroup.filename)
        popts['label'] = "%s: %s" % (fname, dgroup.plot_ylabel)
        popts['xlabel'] = dgroup.plot_xlabel
        popts['ylabel'] = dgroup.plot_ylabel
        if getattr(dgroup, 'plot_y2label', None) is not None:
            popts['y2label'] = dgroup.plot_y2label

        if plotcmd == newplot and title is None:
            title = fname

        popts['title'] = title

        for yarr in plot_yarrays:
            popts.update(yarr[1])
            if yarr[2] is not None:
                popts['label'] = yarr[2]
            plotcmd(dgroup._xdat, yarr[0], **popts)
            plotcmd = oplot  # self.plotpanel.oplot

        ppanel = getdisplay(_larch=self.larch).panel
        if hasattr(dgroup, 'plot_ymarkers'):
            axes = ppanel.axes
            for x, y, opts in dgroup.plot_ymarkers:
                popts = {
                    'marker': 'o',
                    'markersize': 4,
                    'markerfacecolor': 'red',
                    'markeredgecolor': 'black'
                }
                popts.update(opts)
                axes.plot([x], [y], **popts)
        ppanel.canvas.draw()

    def onShowLarchBuffer(self, evt=None):
        if self.larch_buffer is None:
            self.larch_buffer = larchframe.LarchFrame(_larch=self.larch)

        self.larch_buffer.Show()
        self.larch_buffer.Raise()

    def ShowFile(self, evt=None, groupname=None, **kws):
        if groupname is None and evt is not None:
            groupname = self.file_groups[str(evt.GetString())]

        if not hasattr(self.larch.symtable, groupname):
            print('Error reading file ', groupname)
            return

        self.groupname = groupname
        self.dgroup = getattr(self.larch.symtable, groupname, None)

        if self.dgroup.is_xas:
            self.nb.SetSelection(1)
        else:
            self.nb.SetSelection(0)

    def createMenus(self):
        # ppnl = self.plotpanel
        self.menubar = wx.MenuBar()
        #
        fmenu = wx.Menu()
        MenuItem(self, fmenu, "&Open Data File\tCtrl+O", "Read Scan File",
                 self.onReadScan)

        MenuItem(self, fmenu, "Show Larch Buffer\tCtrl+L",
                 "Show Larch Programming Buffer", self.onShowLarchBuffer)

        fmenu.AppendSeparator()

        MenuItem(self, fmenu, "&Quit\tCtrl+Q", "Quit program", self.onClose)

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

        omenu = wx.Menu()
        MenuItem(self, omenu, "Edit Column Labels\tCtrl+E",
                 "Edit Column Labels", self.onEditColumnLabels)

        self.menubar.Append(omenu, "Options")

        self.SetMenuBar(self.menubar)
        self.Bind(wx.EVT_CLOSE, self.onClose)

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

    def onClose(self, evt):
        save_workdir('scanviewer.dat')

        for nam in dir(self.larch.symtable._plotter):
            obj = getattr(self.larch.symtable._plotter, nam)
            try:
                obj.Destroy()
            except:
                pass

        for nam in dir(self.larch.symtable._sys.wx):
            obj = getattr(self.larch.symtable._sys.wx, nam)
            del obj

        if self.larch_buffer is not None:
            try:
                self.larch_buffer.onClose()
            except:
                pass
        for w in self.GetChildren():
            w.Destroy()

        self.Destroy()

    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 onEditColumnLabels(self, evt=None):
        self.show_subframe('coledit',
                           EditColumnFrame,
                           group=self.dgroup,
                           last_array_sel=self.last_array_sel,
                           read_ok_cb=self.onReadScan_Success)

    def onReadScan(self, evt=None):
        dlg = wx.FileDialog(self,
                            message="Load Column 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.file_groups:
                if wx.ID_YES != popup(self, "Re-read file '%s'?" % path,
                                      'Re-read file?'):
                    return

            filedir, filename = os.path.split(path)
            pref = fix_varname((filename + '____')[:7]).replace('.', '_')
            count, maxcount = 1, 9999
            groupname = "%s%3.3i" % (pref, count)
            while hasattr(self.larch.symtable, groupname) and count < maxcount:
                count += 1
                groupname = '%s%3.3i' % (pref, count)

            if self.config['chdir_on_fileopen']:
                os.chdir(filedir)

            fh = open(path, 'r')
            line1 = fh.readline().lower()
            fh.close()
            reader = read_ascii
            if 'epics stepscan file' in line1:
                reader = read_gsexdi
            elif 'epics scan' in line1:
                reader = gsescan_group
            elif 'xdi' in line1:
                reader = read_xdi

            dgroup = reader(str(path), _larch=self.larch)
            if reader == gsescan_group:
                assign_gsescan_groups(dgroup)
            dgroup._path = path
            dgroup._filename = filename
            dgroup._groupname = groupname

            self.show_subframe('coledit',
                               EditColumnFrame,
                               group=dgroup,
                               last_array_sel=self.last_array_sel,
                               read_ok_cb=self.onReadScan_Success)

        dlg.Destroy()

    def onReadScan_Success(self, datagroup, array_sel):
        """ called when column data has been selected and is ready to be used"""
        self.last_array_sel = array_sel
        filename = datagroup._filename
        groupname = datagroup._groupname
        # print("   storing datagroup ", datagroup, groupname, filename)
        # file /group may already exist in list
        if filename in self.file_groups:
            for i in range(1, 101):
                ftest = "%s (%i)" % (filename, i)
                if ftest not in self.groups:
                    filename = ftest
                    break

        if filename not in self.file_groups:
            self.filelist.Append(filename)
            self.file_groups[filename] = groupname

        setattr(self.larch.symtable, groupname, datagroup)
        if datagroup.is_xas:
            self.nb.SetSelection(1)
            self.InitializeXASPanel(datagroup)
        else:
            self.nb.SetSelection(0)
        self.onPlotOne(groupname=groupname)