Пример #1
0
class ClusterForm(wx.Dialog):
    def __init__(self, parent, title, label):
        wx.Dialog.__init__(self, parent, 20, title, wx.DefaultPosition,
                           wx.Size(300, 140))

        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        buttonbox = wx.BoxSizer(wx.HORIZONTAL)

        fgs = wx.FlexGridSizer(3, 2, 9, 5)

        self.title_tc1 = wx.StaticText(self, label=label)

        self.tc1 = wx.TextCtrl(self, size=(150, 25))

        self.max = IntCtrl(self, size=(150, 25))

        self.max.Enable(True)

        self.max.Hide()

        fgs.AddMany([(self.title_tc1), (self.tc1, 1, wx.EXPAND)])

        fgs.AddMany([(self.title_tc1), (self.max, 1, wx.EXPAND)])

        fgs.AddGrowableRow(2, 1)
        fgs.AddGrowableCol(1, 1)

        hbox.Add(fgs, flag=wx.ALL | wx.EXPAND, border=15)
        self.b_ok = wx.Button(self, label='Ok', id=OK_DIALOG)
        self.b_cancel = wx.Button(self, label='Cancel', id=CANCEL_DIALOG)

        buttonbox.Add(self.b_ok, 1, border=15)
        buttonbox.Add(self.b_cancel, 1, border=15)

        vbox.Add(hbox, flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND)
        vbox.Add(buttonbox, flag=wx.ALIGN_CENTER)
        self.SetSizer(vbox)
Пример #2
0
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Eye Probe", size=(1024, 620))

        panel = wx.Panel(self, -1)

        self.fbb_waveform_path = filebrowse.FileBrowseButton(
            panel, -1, size=(300, -1), labelText="Waveform")

        self.int_npui = IntCtrl(panel,
                                -1,
                                32,
                                min=1,
                                max=99999,
                                limited=True,
                                size=(50, -1))

        self.fs_datarate = FS.FloatSpin(panel,
                                        -1,
                                        size=(65, -1),
                                        min_val=0,
                                        max_val=9999,
                                        increment=0.1,
                                        value=10,
                                        agwStyle=FS.FS_LEFT)

        self.fs_datarate.SetFormat("%G")
        self.fs_datarate.SetDigits(5)

        self.cb_sinc_interp_n = wx.ComboBox(
            panel, -1, "Off", (-1, -1), (-1, -1),
            ["Off", "2pts", "4pts", "8pts", "16pts"], wx.CB_DROPDOWN
            | wx.CB_READONLY)

        self.cb_CRU = wx.ComboBox(panel, -1, "Constant clock", (-1, -1),
                                  (-1, -1),
                                  ["Constant clock", "Clock times file"],
                                  wx.CB_DROPDOWN
                                  | wx.CB_READONLY)

        self.fbb_clock_time_file = filebrowse.FileBrowseButton(
            panel, -1, size=(300, -1), labelText="Clock times")

        self.fbb_clock_time_file.Enable(False)

        self.int_ignor_cycles = IntCtrl(panel,
                                        -1,
                                        0,
                                        min=0,
                                        max=9999999,
                                        limited=True,
                                        size=(50, -1))
        self.int_ignor_cycles.Enable(False)

        self.cb_colorbar_en = wx.CheckBox(panel, -1, "Enable Colorbar")

        self.cb_mask_en = wx.CheckBox(panel, -1, "Enable Mask")

        self.sld_maskadj = wx.Slider(panel, -1, 0, -100, 100, size=(300, -1))

        self.fbb_mask_path = filebrowse.FileBrowseButton(panel,
                                                         -1,
                                                         size=(300, -1),
                                                         labelText="Mask")
        self.fbb_mask_path.Enable(False)
        self.sld_maskadj.Enable(False)

        self.btn_plot = wx.Button(panel, -1, "Plot Eye")

        self.canvas = FigureCanvas(panel, -1, Figure())
        self.figure = self.canvas.figure
        self.axes1 = self.figure.add_subplot(1, 1, 1)
        self.axes1.set_axis_bgcolor('k')
        self.axes1.grid(c="w")
        self.axes2 = None

        toolbar = NavigationToolbar2Wx(self.canvas)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer_left = wx.GridBagSizer(hgap=5, vgap=10)
        sizer_left.Add(self.fbb_waveform_path,
                       pos=(0, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(wx.StaticText(panel, -1, "Samples per UI"),
                       pos=(1, 0),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.int_npui,
                       pos=(1, 1),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(wx.StaticText(panel, -1, "Data Rate"),
                       pos=(2, 0),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.fs_datarate,
                       pos=(2, 1),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(wx.StaticText(panel, -1, "Gbps"),
                       pos=(2, 2),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(wx.StaticText(panel, -1, "Sin(x)/x Interp"),
                       pos=(3, 0),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.cb_sinc_interp_n,
                       pos=(3, 1),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(wx.StaticText(panel, -1, "Clock Recovery"),
                       pos=(4, 0),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.cb_CRU,
                       pos=(4, 1),
                       span=(1, 2),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(self.fbb_clock_time_file,
                       pos=(5, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(wx.StaticText(panel, -1, "Ignore cycles"),
                       pos=(6, 0),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.int_ignor_cycles,
                       pos=(6, 1),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(self.cb_colorbar_en,
                       pos=(7, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.cb_mask_en,
                       pos=(8, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(self.fbb_mask_path,
                       pos=(9, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)
        sizer_left.Add(self.sld_maskadj,
                       pos=(10, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_left.Add(self.btn_plot,
                       pos=(11, 0),
                       span=(1, 3),
                       flag=wx.ALIGN_CENTER_VERTICAL)

        sizer_right = wx.BoxSizer(wx.VERTICAL)

        sizer_right.Add(toolbar, 0, wx.EXPAND | wx.RIGHT)
        sizer_right.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)

        sizer.Add(sizer_left, 0, wx.ALL, 10)
        sizer.Add(sizer_right, 1, wx.GROW)

        panel.SetSizer(sizer)
        sizer.Fit(panel)

        self.eye_mask_en = True

        self.btn_plot.Bind(wx.EVT_BUTTON, self.OnPlot)
        self.sld_maskadj.Bind(wx.EVT_SCROLL_CHANGED, self.OnAdjustMask)
        self.cb_mask_en.Bind(wx.EVT_CHECKBOX, self.OnEnableEyeMask)
        self.cb_CRU.Bind(wx.EVT_COMBOBOX, self.OnChangeCRU)

        #sig,samps_per_ui,ui = get_demo_data()

        #self.plot_eye(sig,samps_per_ui,ui,colorbar_en=False)

    def _get_conf(self):
        sig_file = self.fbb_waveform_path.GetValue()
        samps_per_ui = self.int_npui.GetValue()
        data_rate = self.fs_datarate.GetValue()
        sinc_interp_str = self.cb_sinc_interp_n.GetValue()
        if sinc_interp_str == "Off":
            sinc_interp_n = 0
        else:
            sinc_interp_n = int(sinc_interp_str[:-3])

        CRU_str = self.cb_CRU.GetValue()
        if CRU_str == "Clock times file":
            clock_times_file = self.fbb_clock_time_file.GetValue()
        else:
            clock_times_file = None

        ignor_cycles = self.int_ignor_cycles.GetValue()

        colorbar_en = self.cb_colorbar_en.GetValue()
        mask_en = self.cb_mask_en.GetValue()
        mask_path = self.fbb_mask_path.GetValue()

        return (sig_file, samps_per_ui, data_rate, sinc_interp_n,
                clock_times_file, ignor_cycles, colorbar_en, mask_en,
                mask_path)

    def OnChangeCRU(self, evt):
        CRU_str = evt.GetEventObject().GetValue()

        if CRU_str == "Clock times file":
            self.fbb_clock_time_file.Enable(True)
            self.int_ignor_cycles.Enable(True)
        else:
            self.fbb_clock_time_file.Enable(False)
            self.int_ignor_cycles.Enable(False)

    def OnPlot(self, evt):
        #print (self._get_conf())
        #print("plot")
        sig_file,samps_per_ui,data_rate,sinc_interp_n,\
        clock_times_file,ignor_cycles,colorbar_en,\
        mask_en,mask_path = self._get_conf()
        sig = np.loadtxt(sig_file)
        if clock_times_file is not None:
            clock_times = np.loadtxt(clock_times_file)[ignor_cycles:]
        else:
            clock_times = None
        #print(len(sig))
        if sinc_interp_n > 0:
            sig = resample(sig, len(sig) * sinc_interp_n)
            samps_per_ui *= sinc_interp_n

        ui = 1e-9 / data_rate
        if mask_en:
            if mask_path:
                norm_mask1 = np.loadtxt(mask_path, delimiter=",")
                eye_mask = self.get_mask(norm_mask1, ui * 1e12)
            else:
                eye_mask = None  # should print some errors
        else:
            eye_mask = None

        self.plot_eye(sig, samps_per_ui, ui, clock_times, colorbar_en,
                      eye_mask)

    def OnAdjustMask(self, evt):
        val = evt.EventObject.GetValue()
        mask_temp = self.mask_array.copy()
        mask_temp[:, 0] = self.mask_array[:, 0] + val
        self.mask_poly.set_xy(mask_temp)
        self.canvas.draw_idle()

    def OnEnableEyeMask(self, evt):
        mask_en = evt.EventObject.GetValue()
        self.fbb_mask_path.Enable(mask_en)
        self.sld_maskadj.Enable(mask_en)

    def get_mask(self, norm_mask, ui, vhigh=1, vlow=-1):
        mask = norm_mask.copy()
        mask[:, 0] -= 0.5
        mask[:, 0] *= ui
        mask[:, 1] -= 0.5
        mask[:, 1] *= (vhigh - vlow)
        return mask

    def plot_eye(self,
                 sig,
                 samps_per_ui,
                 ui,
                 clock_times=None,
                 colorbar_en=False,
                 eye_mask=None,
                 grid_size=(480, 640)):

        #def update_mask(val):
        #print(val)
        #    mask_temp = mask_array.copy()
        #    mask_temp[:,0]=mask_array[:,0]+val
        #    mask_poly.set_xy(mask_temp)
        #    self.canvas.draw_idle()

        self.figure.clf()

        self.axes1 = self.figure.add_subplot(1, 1, 1)
        self.eye_mask_en = False if eye_mask == None else True
        xs, ys, eye_heat = calc_eye_heatmap(sig, samps_per_ui, ui, clock_times,
                                            grid_size)
        im = self.axes1.pcolormesh(xs,
                                   ys,
                                   eye_heat,
                                   cmap=scope_cmap,
                                   shading="gouraud")

        self.axes1.set_xlabel("Time(ps)")
        self.axes1.set_ylabel("Voltage(v)")

        if colorbar_en:
            self.figure.colorbar(im, ax=self.axes1)
        self.axes1.set_xlim([xs.min(), xs.max()])
        self.axes1.set_ylim([ys.min(), ys.max()])
        self.axes1.grid(color="w")

        if self.eye_mask_en:
            #self.figure.subplots_adjust(bottom=0.25)
            #self.axes2 = self.figure.add_axes([0.2, 0.1, 0.65, 0.03])
            #self.slide_mask = Slider(self.axes2, 'Mask Adjust', -ui*1e12,
            #        ui*1e12, valinit=0)
            #self.slide_mask.on_changed(update_mask)

            self.mask_array = eye_mask
            self.mask_poly = mpl.patches.Polygon(self.mask_array,
                                                 color='#3F3F3F',
                                                 alpha=0.75)

            self.axes1.add_patch(self.mask_poly)
            self.sld_maskadj.SetRange(xs.min(), xs.max())
        #else:
        #    self.figure.subplots_adjust(bottom=0.1)

        self.canvas.draw()
Пример #3
0
class DmgPatternEditorDlg(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self,
                           parent,
                           id=wx.ID_ANY,
                           title=u"Damage Pattern Editor",
                           size=wx.Size(400, 240))

        self.block = False
        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.headerSizer = headerSizer = wx.BoxSizer(wx.HORIZONTAL)

        cDP = service.DamagePattern.getInstance()

        self.choices = cDP.getDamagePatternList()
        # Remove "Uniform" and "Selected Ammo" Damage Patterns
        for dp in self.choices:
            if dp.name in ("Uniform", "Selected Ammo"):
                self.choices.remove(dp)
        # Sort the remaining list and continue on
        self.choices.sort(key=lambda p: p.name)
        self.ccDmgPattern = wx.Choice(self,
                                      choices=map(lambda p: p.name,
                                                  self.choices))
        self.ccDmgPattern.Bind(wx.EVT_CHOICE, self.patternChanged)
        self.ccDmgPattern.SetSelection(0)

        self.namePicker = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
        self.namePicker.Bind(wx.EVT_TEXT_ENTER, self.processRename)
        self.namePicker.Hide()

        self.btnSave = wx.Button(self, wx.ID_SAVE)
        self.btnSave.Hide()
        self.btnSave.Bind(wx.EVT_BUTTON, self.processRename)

        size = None
        headerSizer.Add(self.ccDmgPattern, 1,
                        wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT, 3)
        buttons = (("new", wx.ART_NEW),
                   ("rename", bitmapLoader.getBitmap("rename", "icons")),
                   ("copy", wx.ART_COPY), ("delete", wx.ART_DELETE))
        for name, art in buttons:
            bitmap = wx.ArtProvider.GetBitmap(
                art, wx.ART_BUTTON) if name != "rename" else art
            btn = wx.BitmapButton(self, wx.ID_ANY, bitmap)
            if size is None:
                size = btn.GetSize()

            btn.SetMinSize(size)
            btn.SetMaxSize(size)

            btn.Layout()
            setattr(self, name, btn)
            btn.Enable(True)
            btn.SetToolTipString("%s pattern" % name.capitalize())
            headerSizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL)

        mainSizer.Add(headerSizer, 0, wx.EXPAND | wx.ALL, 2)

        self.sl = wx.StaticLine(self)
        mainSizer.Add(self.sl, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5)

        contentSizer = wx.BoxSizer(wx.VERTICAL)
        self.embitmap = bitmapLoader.getBitmap("em_big", "icons")
        self.thermbitmap = bitmapLoader.getBitmap("thermal_big", "icons")
        self.kinbitmap = bitmapLoader.getBitmap("kinetic_big", "icons")
        self.expbitmap = bitmapLoader.getBitmap("explosive_big", "icons")

        dmgeditSizer = wx.FlexGridSizer(2, 4, 0, 2)
        dmgeditSizer.AddGrowableCol(1)
        dmgeditSizer.AddGrowableCol(2)
        dmgeditSizer.SetFlexibleDirection(wx.BOTH)
        dmgeditSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        width = -1
        defSize = wx.Size(width, -1)

        self.editEm = IntCtrl(self, wx.ID_ANY, 0, wx.DefaultPosition, defSize,
                              wx.TE_RIGHT)
        dmgeditSizer.Add(self.editEm, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.bmpEM = wx.StaticBitmap(self, wx.ID_ANY, self.embitmap)
        dmgeditSizer.Add(self.bmpEM, 0,
                         wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,
                         5)

        self.bmpTHERM = wx.StaticBitmap(self, wx.ID_ANY, self.thermbitmap)
        dmgeditSizer.Add(
            self.bmpTHERM, 0, wx.ALIGN_CENTER_HORIZONTAL
            | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        self.editThermal = IntCtrl(self, wx.ID_ANY, 0, wx.DefaultPosition,
                                   defSize, 0)
        dmgeditSizer.Add(self.editThermal, 0,
                         wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.editKinetic = IntCtrl(self, wx.ID_ANY, 0, wx.DefaultPosition,
                                   defSize, wx.TE_RIGHT)
        dmgeditSizer.Add(self.editKinetic, 0,
                         wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        self.bmpKIN = wx.StaticBitmap(self, wx.ID_ANY, self.kinbitmap)
        dmgeditSizer.Add(self.bmpKIN, 0,
                         wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,
                         5)

        self.bmpEXP = wx.StaticBitmap(self, wx.ID_ANY, self.expbitmap)
        dmgeditSizer.Add(
            self.bmpEXP, 0, wx.ALIGN_CENTER_HORIZONTAL
            | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT, 5)

        self.editExplosive = IntCtrl(self, wx.ID_ANY, 0, wx.DefaultPosition,
                                     defSize, 0)
        dmgeditSizer.Add(self.editExplosive, 0,
                         wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)

        contentSizer.Add(dmgeditSizer, 1, wx.EXPAND | wx.ALL, 5)
        self.slfooter = wx.StaticLine(self)
        contentSizer.Add(self.slfooter, 0, wx.EXPAND | wx.TOP, 5)

        footerSizer = wx.BoxSizer(wx.HORIZONTAL)

        perSizer = wx.BoxSizer(wx.VERTICAL)

        self.stPercentages = wx.StaticText(self, wx.ID_ANY, u"")
        self.stPercentages.Wrap(-1)
        perSizer.Add(self.stPercentages, 0, wx.BOTTOM | wx.LEFT, 5)

        footerSizer.Add(perSizer, 0, 0, 5)

        self.totSizer = wx.BoxSizer(wx.VERTICAL)

        self.stTotal = wx.StaticText(self, wx.ID_ANY, u"")
        self.stTotal.Wrap(-1)
        self.totSizer.Add(self.stTotal, 0,
                          wx.ALIGN_RIGHT | wx.BOTTOM | wx.RIGHT, 5)

        footerSizer.Add(self.totSizer, 1, 0, 5)

        contentSizer.Add(footerSizer, 0, wx.EXPAND, 5)

        mainSizer.Add(contentSizer, 1, wx.EXPAND, 0)

        self.SetSizer(mainSizer)

        self.Layout()
        bsize = self.GetBestSize()
        self.SetSize((-1, bsize.height))

        self.editEm.SetLimited(True)
        self.editThermal.SetLimited(True)
        self.editKinetic.SetLimited(True)
        self.editExplosive.SetLimited(True)

        self.editEm.SetMin(0)
        self.editThermal.SetMin(0)
        self.editKinetic.SetMin(0)
        self.editExplosive.SetMin(0)

        self.editEm.SetMax(99999)
        self.editThermal.SetMax(99999)
        self.editKinetic.SetMax(99999)
        self.editExplosive.SetMax(99999)

        self.new.Bind(wx.EVT_BUTTON, self.newPattern)
        self.rename.Bind(wx.EVT_BUTTON, self.renamePattern)
        self.copy.Bind(wx.EVT_BUTTON, self.copyPattern)
        self.delete.Bind(wx.EVT_BUTTON, self.deletePattern)

        self.editEm.Bind(wx.EVT_TEXT, self.ValuesUpdated)
        self.editThermal.Bind(wx.EVT_TEXT, self.ValuesUpdated)
        self.editKinetic.Bind(wx.EVT_TEXT, self.ValuesUpdated)
        self.editExplosive.Bind(wx.EVT_TEXT, self.ValuesUpdated)

        self.patternChanged()

    def ValuesUpdated(self, event=None):
        if self.block:
            return

        p = self.getActivePattern()
        p.emAmount = self._EM = self.editEm.GetValue()
        p.thermalAmount = self._THERM = self.editThermal.GetValue()
        p.kineticAmount = self._KIN = self.editKinetic.GetValue()
        p.explosiveAmount = self._EXP = self.editExplosive.GetValue()
        total = self._EM + self._THERM + self._KIN + self._EXP
        format = "EM: % 3d%% THERM: % 3d%% KIN: % 3d%% EXP: % 3d%%"
        if total > 0:
            ltext = format % (self._EM * 100 / total,
                              self._THERM * 100 / total,
                              self._KIN * 100 / total, self._EXP * 100 / total)
        else:
            ltext = format % (0, 0, 0, 0)

        ttext = "Total: % 6d" % (total)
        self.stPercentages.SetLabel(ltext)
        self.stTotal.SetLabel(ttext)
        self.totSizer.Layout()

        if event is not None:
            event.Skip()

        service.DamagePattern.getInstance().saveChanges(p)

    def restrict(self):
        self.editEm.Enable(False)
        self.editExplosive.Enable(False)
        self.editKinetic.Enable(False)
        self.editThermal.Enable(False)
        self.rename.Enable(False)
        self.delete.Enable(False)

    def unrestrict(self):
        self.editEm.Enable()
        self.editExplosive.Enable()
        self.editKinetic.Enable()
        self.editThermal.Enable()
        self.rename.Enable()
        self.delete.Enable()

    def getActivePattern(self):
        if len(self.choices) == 0:
            return None

        return self.choices[self.ccDmgPattern.GetSelection()]

    def patternChanged(self, event=None):
        p = self.getActivePattern()
        if p is None:
            return

        if p.name == "Uniform" or p.name == "Selected Ammo":
            self.restrict()
        else:
            self.unrestrict()

        self.block = True
        for field in ("em", "thermal", "kinetic", "explosive"):
            edit = getattr(self, "edit%s" % field.capitalize())
            amount = getattr(p, "%sAmount" % field)
            edit.SetValue(amount)

        self.block = False
        self.ValuesUpdated()

    def newPattern(self, event):
        cDP = service.DamagePattern.getInstance()
        p = cDP.newPattern()
        self.choices.append(p)
        id = self.ccDmgPattern.Append(p.name)
        self.ccDmgPattern.SetSelection(id)
        self.btnSave.SetLabel("Create")
        self.renamePattern()

    def renamePattern(self, event=None):
        if event is not None:
            self.btnSave.SetLabel("Rename")

        self.ccDmgPattern.Hide()
        self.namePicker.Show()
        self.headerSizer.Replace(self.ccDmgPattern, self.namePicker)
        self.namePicker.SetFocus()
        self.namePicker.SetValue(self.getActivePattern().name)

        for btn in (self.new, self.rename, self.delete, self.copy):
            btn.Hide()
            self.headerSizer.Remove(btn)

        self.headerSizer.Add(self.btnSave, 0, wx.ALIGN_CENTER)
        self.btnSave.Show()
        self.headerSizer.Layout()
        if event is not None:
            event.Skip()

    def processRename(self, event):
        newName = self.namePicker.GetLineText(0)
        self.stPercentages.SetLabel("")
        self.stTotal.SetLabel("")
        p = self.getActivePattern()
        for pattern in self.choices:
            if pattern.name == newName and p != pattern:
                self.stPercentages.SetLabel(
                    "Name already used, please pick another")
                return

        cDP = service.DamagePattern.getInstance()
        cDP.renamePattern(p, newName)

        self.headerSizer.Replace(self.namePicker, self.ccDmgPattern)
        self.ccDmgPattern.Show()
        self.namePicker.Hide()
        self.btnSave.Hide()
        self.headerSizer.Remove(self.btnSave)
        for btn in (self.new, self.rename, self.delete, self.copy):
            self.headerSizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL)
            btn.Show()

        sel = self.ccDmgPattern.GetSelection()
        self.ccDmgPattern.Delete(sel)
        self.ccDmgPattern.Insert(newName, sel)
        self.ccDmgPattern.SetSelection(sel)
        self.ValuesUpdated()

    def copyPattern(self, event):
        cDP = service.DamagePattern.getInstance()
        p = cDP.copyPattern(self.getActivePattern())
        self.choices.append(p)
        id = self.ccDmgPattern.Append(p.name)
        self.ccDmgPattern.SetSelection(id)
        self.btnSave.SetLabel("Copy")
        self.renamePattern()
        self.patternChanged()

    def deletePattern(self, event):
        cDP = service.DamagePattern.getInstance()
        sel = self.ccDmgPattern.GetSelection()
        cDP.deletePattern(self.getActivePattern())
        self.ccDmgPattern.Delete(sel)
        self.ccDmgPattern.SetSelection(max(0, sel - 1))
        del self.choices[sel]
        self.patternChanged()

    def __del__(self):
        pass
Пример #4
0
class OptionPanel(wx.Panel):
	"""
	A panel with all the available options to customize the plot.
	Some are mandatory, others are just optional.
	"""
	def __init__(self, parent, size : tuple, dataset : nc.Dataset, metadata : dict):
		super(OptionPanel, self).__init__(parent=parent, id=wx.ID_ANY, size=size)
		self.parent = parent
		self.dataset = dataset
		self.metadata = metadata
		self.options = {} # It will gather all the options set by the user
		self.init_options() # Initialize the options dictionary
		
		self.var_ids = {} # Dictionary with id keys and their corresponing variable
		self.c_boxes = [] # List of ComboBox used
		self.text_entries = [] # List of text entries used
		self.chk_boxes = [] # List of check boxes used

		self.main_sizer = wx.BoxSizer(wx.VERTICAL)

		# --------------------------------------- #
		# First StaticBox, general options:
		# Variable / Time index / Level (if necessary)
		stbox_gen = wx.StaticBox(parent=self, label="General")
		stbox_gen_sizer = wx.StaticBoxSizer(stbox_gen, wx.HORIZONTAL)
		
		# Variables
		text_variables = wx.StaticText(parent=stbox_gen, label="Variable : ")
		l_variables = nc_tools.get_variables(self.dataset)
		self.c_box_variables = wx.ComboBox(
									  parent=stbox_gen,
									  id=wx.ID_ANY,
									  choices=l_variables,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_variables.GetId()] = "variable"
		self.c_boxes.append(self.c_box_variables)

		# Time
		text_time = wx.StaticText(parent=stbox_gen, label="Time index : ")
		timesteps =  nc_tools.get_timesteps(self.dataset)
		self.c_box_time = wx.ComboBox(
									  parent=stbox_gen,
									  id=wx.ID_ANY,
									  choices=timesteps,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_time.GetId()] = "time_index"
		self.c_boxes.append(self.c_box_time)

		# Pressure Level (if necessary) 
		if nc_tools.is_pressure_level(meta=self.metadata):
			text_levels = wx.StaticText(parent=stbox_gen, label="Pressure level : ")
			levels = nc_tools.get_pressure_levels(self.dataset)
			self.c_box_levels = wx.ComboBox(
									  		parent=stbox_gen,
									  		id=wx.ID_ANY,
									 	 	choices=levels,
									  		style=wx.CB_DROPDOWN | wx.CB_READONLY
									  		)
			self.var_ids[self.c_box_levels.GetId()] = "pl_index"
			self.c_boxes.append(self.c_box_levels)
		else:
			self.c_box_levels = None

		# StaticBox sizer setup
		stbox_gen_sizer.Add(text_variables, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		stbox_gen_sizer.Add(self.c_box_variables, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		stbox_gen_sizer.Add(text_time, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		stbox_gen_sizer.Add(self.c_box_time, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		if self.c_box_levels:
			# Add levels to the sizer if dataset contains levels
			stbox_gen_sizer.Add(text_levels, 0, wx.ALIGN_CENTER | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
			stbox_gen_sizer.Add(self.c_box_levels, 0, wx.ALIGN_CENTER | wx.ALL, 20)

		# --------------------------------------- #
		# Second StaticBox, data corrections
		stbox_data_corr = wx.StaticBox(parent=self, label="Corrections")
		stbox_data_corr_sizer = wx.StaticBoxSizer(stbox_data_corr, wx.VERTICAL)
		pnl_data_corr = wx.Panel(parent=stbox_data_corr)
		pnl_data_corr_sizer = wx.GridSizer(cols=6, gap=(5, 5))

		# Longitude offset
		text_lon_offset = wx.StaticText(parent=pnl_data_corr, label="Longitude offset : ")
		self.te_lon_offset = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=0, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_lon_offset.GetId()] = "lon_offset"
		self.text_entries.append(self.te_lon_offset)

		# Data multiplicator
		text_coef = wx.StaticText(parent=pnl_data_corr, label="Apply coefficient : ")
		self.te_coef = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=1, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_coef.GetId()] = "coef"
		self.text_entries.append(self.te_coef)

		# Data offset
		text_data_offset = wx.StaticText(parent=pnl_data_corr, label="Data offset : ")
		self.te_data_offset = NumCtrl(parent=pnl_data_corr, id=wx.ID_ANY, value=0, integerWidth=3, fractionWidth=2)
		self.var_ids[self.te_data_offset.GetId()] = "offset"
		self.text_entries.append(self.te_data_offset)

		# StaticBox sizer setup
		pnl_data_corr_sizer.Add(text_lon_offset, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_lon_offset, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr_sizer.Add(text_coef, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_coef, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr_sizer.Add(text_data_offset, 0, wx.EXPAND | wx.LEFT | wx.TOP | wx.BOTTOM, 20)
		pnl_data_corr_sizer.Add(self.te_data_offset, 0, wx.EXPAND | wx.ALL, 20)
		pnl_data_corr.SetSizer(pnl_data_corr_sizer)

		stbox_data_corr_sizer.Add(pnl_data_corr, 0, wx.EXPAND)

		# --------------------------------------- #
		# Third StaticBox, projection setup
		stbox_proj = wx.StaticBox(parent=self, label="Map setup")
		stbox_proj_sizer = wx.StaticBoxSizer(stbox_proj, wx.VERTICAL)

		pnl_stbox_proj = wx.Panel(parent=stbox_proj)
		pnl_stbox_proj_sizer = wx.GridBagSizer(0, 0)

		# Panel projection #
		pnl_proj = wx.Panel(parent=pnl_stbox_proj)
		pnl_proj_sizer = wx.GridSizer(cols=2, gap=(5, 5))
		
		text_preset = wx.StaticText(parent=pnl_proj, label="Map preset : ")
		with open(MAP_PRESETS_PATH, 'r') as foo:
			self.presets = json.load(foo)
			foo.close()
		presets_list = list(self.presets.keys())
		self.c_box_presets = wx.ComboBox(
									  parent=pnl_proj,
									  id=wx.ID_ANY,
									  choices=presets_list,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY
									  )
		self.var_ids[self.c_box_presets.GetId()] = "preset"
		self.c_boxes.append(self.c_box_presets)

		# Sizer setup
		pnl_proj_sizer.Add(text_preset, 0, wx.ALIGN_CENTER_HORIZONTAL, 20)
		pnl_proj_sizer.Add(self.c_box_presets, 0, wx.ALIGN_CENTER_HORIZONTAL, 20)
		pnl_proj.SetSizer(pnl_proj_sizer)

		# Panel other options #
		pnl_other = wx.Panel(parent=pnl_stbox_proj)
		pnl_other_sizer = wx.GridSizer(cols=2, gap=(5, 5))

		text_res = wx.StaticText(parent=pnl_other, label="Resolution : ")
		l_resolutions = ['c', 'l', 'i', 'h', 'f']
		self.c_box_res = wx.ComboBox(
									 parent=pnl_other,
									 id=wx.ID_ANY,
									 choices=l_resolutions,
									 style=wx.CB_DROPDOWN | wx.CB_READONLY,
									 size=(100, 25)
									 )
		self.var_ids[self.c_box_res.GetId()] = "resolution"
		self.c_boxes.append(self.c_box_res)

		self.check_countries = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Draw countries")
		self.var_ids[self.check_countries.GetId()] = "countries"
		self.chk_boxes.append(self.check_countries)

		self.check_rivers = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Draw rivers")
		self.var_ids[self.check_rivers.GetId()] = "rivers"
		self.chk_boxes.append(self.check_rivers)

		text_cmap = wx.StaticText(parent=pnl_other, label="Colormap : ")
		colormaps = display_tools.get_cmap()
		self.c_box_cmap = wx.ComboBox(
									  parent=pnl_other,
									  id=wx.ID_ANY,
									  choices=colormaps,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY,
									  size=(100, 25)
									  )
		self.var_ids[self.c_box_cmap.GetId()] = "cmap"
		self.c_boxes.append(self.c_box_cmap)

		text_pltype = wx.StaticText(parent=pnl_other, label="Plot type : ")
		plot_types = ["pcolormesh"]
		self.c_box_pltype = wx.ComboBox(
									  parent=pnl_other,
									  id=wx.ID_ANY,
									  choices=plot_types,
									  style=wx.CB_DROPDOWN | wx.CB_READONLY,
									  size=(100, 25)
									  )
		self.var_ids[self.c_box_pltype.GetId()] = "plot_type"
		self.c_boxes.append(self.c_box_pltype)

		self.check_colorbar = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Colorbar")
		self.var_ids[self.check_colorbar.GetId()] = "colorbar"
		self.chk_boxes.append(self.check_colorbar)

		self.check_norm = wx.CheckBox(parent=pnl_other, id=wx.ID_ANY, label=" Norm")
		self.var_ids[self.check_norm.GetId()] = "norm"
		# This check box is not added to the list of check boxes because it'll have its own binding.

		text_midpoint = wx.StaticText(parent=pnl_other, label="Midpoint : ")
		self.te_midpoint = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=25)
		self.var_ids[self.te_midpoint.GetId()] = "midpoint"
		self.text_entries.append(self.te_midpoint)
		self.te_midpoint.Enable(False)

		text_min = wx.StaticText(parent=pnl_other, label="Min : ")
		self.te_min = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=0)
		self.var_ids[self.te_min.GetId()] = "c_min"
		self.text_entries.append(self.te_min)
		self.te_min.Enable(False)

		text_max = wx.StaticText(parent=pnl_other, label="Max : ")
		self.te_max = IntCtrl(parent=pnl_other, id=wx.ID_ANY, value=50)
		self.var_ids[self.te_max.GetId()] = "c_max"
		self.text_entries.append(self.te_max)
		self.te_max.Enable(False)

		# Sizer setup
		pnl_other_sizer.Add(text_res, 0)
		pnl_other_sizer.Add(self.c_box_res, 0)
		pnl_other_sizer.Add(self.check_countries, 0)
		pnl_other_sizer.Add(self.check_rivers, 0)
		pnl_other_sizer.Add(text_cmap, 0)
		pnl_other_sizer.Add(self.c_box_cmap, 0)
		pnl_other_sizer.Add(text_pltype, 0)
		pnl_other_sizer.Add(self.c_box_pltype, 0)
		pnl_other_sizer.Add(self.check_colorbar, 0)
		pnl_other_sizer.Add(self.check_norm, 0)
		pnl_other_sizer.Add(text_midpoint, 0)
		pnl_other_sizer.Add(self.te_midpoint, 0)
		pnl_other_sizer.Add(text_min, 0)
		pnl_other_sizer.Add(self.te_min, 0)
		pnl_other_sizer.Add(text_max, 0)
		pnl_other_sizer.Add(self.te_max, 0)
		pnl_other.SetSizer(pnl_other_sizer)

		# Map preview panels
		pnl_map_preview = wx.Panel(parent=pnl_stbox_proj, style=wx.BORDER_THEME)
		pnl_map_preview.SetBackgroundColour(wx.Colour(255, 255, 255))
		pnl_map_preview_sizer = wx.BoxSizer(wx.VERTICAL)

		self.map_previews = {}
		for preset in self.presets.keys():
			filename = os.path.join(MAP_PREVIEW_PATH, self.presets[preset]['filename'])
			image = wx.Image(filename, wx.BITMAP_TYPE_ANY)
			bitmap = wx_tools.rescale_image(image, 400, 300)
			self.map_previews[preset] = wx.StaticBitmap(pnl_map_preview, wx.ID_ANY, bitmap, size=(400,300))
			pnl_map_preview_sizer.Add(self.map_previews[preset], 0, wx.EXPAND)
			self.map_previews[preset].Hide()

		self.map_previews[self.options['preset']].Show()

		pnl_map_preview.SetSizer(pnl_map_preview_sizer)

		# StaticBox Sizer setup
		pnl_stbox_proj_sizer.Add(pnl_proj, pos=(0, 0), span=(1, 1), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj_sizer.Add(pnl_other, pos=(0, 1), span=(1, 1), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj_sizer.Add(pnl_map_preview, pos=(0, 2), span=(1, 2), flag=wx.EXPAND | wx.ALL, border=20)
		pnl_stbox_proj.SetSizer(pnl_stbox_proj_sizer)

		stbox_proj_sizer.Add(pnl_stbox_proj, 0, wx.ALIGN_CENTER)

		# --------------------------------------- #
		# PLot Button

		self.button = wx.Button(parent=self, label="Draw", size=(200, 30))

		# --------------------------------------- #
		# Bindings
		for c_box in self.c_boxes:
			c_box.Bind(wx.EVT_COMBOBOX, handler=self.on_option_change)
		for te in self.text_entries:
			te.Bind(wx.EVT_TEXT, handler=self.on_option_change)
		for chk in self.chk_boxes:
			chk.Bind(wx.EVT_CHECKBOX, handler=self.on_option_change)
		self.check_norm.Bind(wx.EVT_CHECKBOX, handler=self.on_norm_change)

		# --------------------------------------- #
		# Add element to the main sizer
		self.main_sizer.Add(stbox_gen_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 20)
		self.main_sizer.Add(stbox_data_corr_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 20)
		self.main_sizer.Add(stbox_proj_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 20)
		self.main_sizer.Add(self.button, 0, wx.ALIGN_CENTER | wx.ALL, 20)
		self.SetSizer(self.main_sizer)

	def on_option_change(self, event):
		"""
		Event handler catching all the option changes.
		"""
		element = event.GetEventObject()
		_id = element.GetId()
		var_name = self.var_ids[_id]
		if var_name == 'time_index' or var_name == 'pl_index':
			val = int(element.GetValue().split(" ")[0])
		elif var_name == 'preset':
			val = element.GetValue()
			self.display_map_preview(val)
		else:
			val = element.GetValue()
		self.update_option(var_name, val)
		event.Skip()

	def on_norm_change(self, event):
		"""
		Enable or disable text entries for colorbar setup.
		"""
		chk_box = event.GetEventObject()
		val = chk_box.GetValue()
		self.options[self.var_ids[chk_box.GetId()]] = val
		self.te_midpoint.Enable(val)
		self.te_min.Enable(val)
		self.te_max.Enable(val)
		event.Skip()

	def init_options(self):
		"""
		Initialize the map options.
		"""
		self.options = {
			"variable": nc_tools.get_variables(self.dataset)[0],
			"time_index": None,
			"pl_index": None,
			"lon_offset": 0,
			"coef": 1,
			"offset": 0,
			"preset": "default",
			"resolution": 'i',
			"countries": False,
			"rivers": False,
			"cmap": "seismic",
			"colorbar": False,
			"norm": False,
			"c_min": 0,
			"c_max": 50,
			"midpoint": 25,
			"plot_type": "pcolormesh"
		}

	def update_option(self, var_name : str, val):
		"""
		Update the options: assign value :val: to the option associated with element with respect to the associated variable.
		"""
		try:
			self.options[var_name] = val
		except Exception as e:
			raise e

	def display_map_preview(self, preset):
		"""
		Display the map preview associated with the chosen preset.
		"""
		self.map_previews[self.options['preset']].Hide()
		self.map_previews[preset].Show()
Пример #5
0
        class ImportDialog(wx.Dialog):
            def __init__(self,
                         parent,
                         ID,
                         title,
                         data,
                         pos=wx.DefaultPosition,
                         size=wx.DefaultSize,
                         style=wx.SYSTEM_MENU | wx.RESIZE_BORDER):
                pre = wx.PreDialog()
                pre.Create(parent, ID, title, pos, size, style)
                self.this = pre.this
                sizer = wx.BoxSizer(wx.VERTICAL)

                panel1 = wx.Panel(self, -1)
                panel1.SetAutoLayout(True)

                self.sample_data = parent.MyListCtrl(
                    panel1,
                    -1,
                    style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_SINGLE_SEL)

                num_col = len(data[0])

                for i in range(0, num_col):
                    self.sample_data.InsertColumn(i, "Col %d" % i)

                for i in range(0, 5):
                    self.sample_data.InsertStringItem(i, str(data[i][0]))
                    for j in range(0, num_col):
                        self.sample_data.SetStringItem(i, j, str(data[i][j]))

                sizer.Add(panel1, 1, wx.EXPAND, 0)

                def OnPSize(e, win=panel1):
                    self.sample_data.SetSize(panel1.GetSize())

                wx.EVT_SIZE(panel1, OnPSize)

                ctrlsizer = wx.BoxSizer(wx.HORIZONTAL)

                col1 = wx.BoxSizer(wx.VERTICAL)

                rsizer = wx.BoxSizer(wx.HORIZONTAL)
                self.rpm = wx.Choice(self,
                                     -1,
                                     choices=map(str, range(0, num_col)))
                self.rpm.SetSelection(0)
                rsizer.Add(self.rpm, 0, 0, 0)
                txt = wx.StaticText(self, -1, "RPM Column")
                rsizer.Add(txt, 0, wx.WEST, 5)
                col1.Add(rsizer, 0, wx.SOUTH, 5)

                rsizer = wx.BoxSizer(wx.HORIZONTAL)
                self.afr = wx.Choice(self,
                                     -1,
                                     choices=map(str, range(0, num_col)))
                self.afr.SetSelection(0)
                rsizer.Add(self.afr, 0, 0, 0)
                txt = wx.StaticText(self, -1, "Wideband A/F:")
                rsizer.Add(txt, 0, wx.WEST, 5)
                col1.Add(rsizer, 0, wx.SOUTH, 5)

                rsizer = wx.BoxSizer(wx.HORIZONTAL)
                self.knock = wx.Choice(self,
                                       -1,
                                       choices=map(str, range(0, num_col)))
                self.knock.SetSelection(0)
                rsizer.Add(self.knock, 0, 0, 0)
                txt = wx.StaticText(self, -1, "Knock:")
                rsizer.Add(txt, 0, wx.WEST, 5)
                col1.Add(rsizer, 0, wx.SOUTH, 5)

                rsizer = wx.BoxSizer(wx.HORIZONTAL)
                self.ts = wx.Choice(self,
                                    -1,
                                    choices=map(str, range(0, num_col)))
                self.ts.SetSelection(0)
                rsizer.Add(self.ts, 0, 0, 0)
                txt = wx.StaticText(self, -1, "TimingShift:")
                rsizer.Add(txt, 0, wx.WEST, 5)
                col1.Add(rsizer, 0, wx.SOUTH, 5)

                col2 = wx.BoxSizer(wx.VERTICAL)
                # Time source selection
                time_box_title = wx.StaticBox(self, -1, "Power Calculation")
                time_box = wx.StaticBoxSizer(time_box_title, wx.VERTICAL)
                tb = wx.FlexGridSizer(0, 2, 0, 0)

                self.tsfd_radio = wx.RadioButton(self, -1,
                                                 " Timestamp from data ")
                self.sr_radio = wx.RadioButton(self, -1, " Samplerate ")
                self.tfd_radio = wx.RadioButton(self, -1, " Torque from data ")
                self.pfd_radio = wx.RadioButton(self, -1, " Power from data ")
                self.pfd_radio.Enable(False)
                self.time_ctrl1 = wx.Choice(self,
                                            -1,
                                            choices=map(
                                                str, range(0, num_col)))
                self.time_ctrl1.SetSelection(0)
                self.time_ctrl2 = IntCtrl(self, -1)
                self.time_ctrl2.Enable(False)

                self.torque_ctrl = wx.Choice(self,
                                             -1,
                                             choices=map(
                                                 str, range(0, num_col)))
                self.torque_ctrl.Enable(False)
                self.power_ctrl = wx.Choice(self,
                                            -1,
                                            choices=map(
                                                str, range(0, num_col)))
                self.power_ctrl.Enable(False)

                tb.Add(self.tsfd_radio, 1, wx.EAST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.time_ctrl1, 1, wx.WEST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.sr_radio, 1, wx.EAST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.time_ctrl2, 1, wx.WEST | wx.NORTH | wx.SOUTH, 4)

                tb.Add(self.tfd_radio, 1, wx.EAST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.torque_ctrl, 1, wx.WEST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.pfd_radio, 1, wx.EAST | wx.NORTH | wx.SOUTH, 4)
                tb.Add(self.power_ctrl, 1, wx.WEST | wx.NORTH | wx.SOUTH, 4)

                time_box.Add(tb, 0, 0, 0)
                col2.Add(time_box, 0, 0, 0)

                def time_enable(evt):
                    self.time_ctrl1.Enable(False)
                    self.time_ctrl2.Enable(False)
                    self.torque_ctrl.Enable(False)
                    self.power_ctrl.Enable(False)

                    if self.tsfd_radio is evt.GetEventObject():
                        self.time_ctrl1.Enable(True)
                    elif self.sr_radio is evt.GetEventObject():
                        self.time_ctrl2.Enable(True)
                    elif self.tfd_radio is evt.GetEventObject():
                        self.torque_ctrl.Enable(True)
                    elif self.pfd_radio is evt.GetEventObject():
                        self.power_ctrl.Enable(True)

                self.Bind(wx.EVT_RADIOBUTTON, time_enable, self.tsfd_radio)
                self.Bind(wx.EVT_RADIOBUTTON, time_enable, self.sr_radio)
                self.Bind(wx.EVT_RADIOBUTTON, time_enable, self.tfd_radio)
                self.Bind(wx.EVT_RADIOBUTTON, time_enable, self.pfd_radio)

                ctrlsizer.Add(col1, 0, 0, 0)
                ctrlsizer.Add(col2, 0, 0, 0)
                sizer.Add(ctrlsizer, 1, wx.EXPAND | wx.ALL, 10)

                # Ok/cancel controls
                hline = wx.StaticLine(self,
                                      -1,
                                      size=(20, -1),
                                      style=wx.LI_HORIZONTAL)
                sizer.Add(
                    hline, 0,
                    wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP, 0)

                box = wx.BoxSizer(wx.HORIZONTAL)
                box.Add(wx.Button(self, wx.ID_OK, "Import"), 0,
                        wx.ALIGN_CENTRE | wx.ALL, 5),
                box.Add(wx.Button(self, wx.ID_CANCEL, "Cancel"), 0,
                        wx.ALIGN_CENTRE | wx.ALL, 5),
                sizer.Add(box, 0, 0)

                self.SetSizer(sizer)
                sizer.Fit(self)
                self.SetAutoLayout(True)
                self.SetSize((300, 300))

            def get_args(self):
                args = {}
                args['rpm_col'] = int(self.rpm.GetStringSelection())
                args['afr_col'] = int(self.afr.GetStringSelection())
                args['knock_col'] = int(self.knock.GetStringSelection())
                args['ts_col'] = int(self.ts.GetStringSelection())
                if self.tsfd_radio.GetValue():
                    args['time_col'] = \
                         int(self.time_ctrl1.GetStringSelection())
                elif self.sr_radio.GetValue():
                    args['sample_rate'] = self.time_ctrl2.GetValue()
                elif self.tfd_radio.GetValue():
                    args['torque_col'] = \
                         int(self.torque_ctrl.GetStringSelection())
                elif self.pfd_radio.GetValue():
                    args['power_col'] = \
                         int(self.power_ctrl.GetStringSelection())

                return args
Пример #6
0
class ScopeConnection(wx.Panel):
    """This is the view and controller for connecting to the scope"""
    def __init__(self, parent, env):
        """Initialize the panel for setting up the scope"""
        wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.BORDER_SIMPLE)

        self.env = env
        self.scope = self.env.scope_source

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)

        input_host = wx.BoxSizer(wx.HORIZONTAL)
        target_cpu = wx.BoxSizer(wx.HORIZONTAL)
        scope_cpu = wx.BoxSizer(wx.HORIZONTAL)
        buttons = wx.BoxSizer(wx.HORIZONTAL)

        self.status = wx.StaticText(self, wx.ID_ANY, "")
        font = self.status.GetFont()
        font.SetWeight(wx.BOLD)
        self.status.SetFont(font)

        self.btn_enable = wx.Button(self, wx.ID_ANY, "")
        self.btn_collect = wx.Button(self, wx.ID_ANY, "Collect")

        buttons.Add(self.btn_enable, 1, wx.ALIGN_CENTER)
        buttons.Add(self.btn_collect, 1, wx.ALIGN_CENTER)

        lbl_server = wx.StaticText(self, wx.ID_ANY, "Scope Server")
        self.txt_server = wx.TextCtrl(self, wx.ID_ANY, self.scope.server)
        self.btn_connect = wx.Button(self, wx.ID_ANY, "Connect")
        input_host.Add(lbl_server, 0, wx.ALIGN_CENTER | wx.RIGHT, 5)
        input_host.Add(self.txt_server, 1, wx.EXPAND)
        input_host.Add(self.btn_connect, 0, wx.EXPAND)

        self.sizer.Add(self.status, 0, wx.EXPAND | wx.ALL, 5)
        self.sizer.Add(input_host, 0,
                       wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT, 5)

        self.choice_t_cpu = wx.Choice(self, wx.ID_ANY)
        self._add_field("Target CPU", self.choice_t_cpu, small=True)

        self.choice_s_cpu = wx.Choice(self, wx.ID_ANY)
        self._add_field("Scope CPU", self.choice_s_cpu, small=True)

        self.command = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_RIGHT)
        self._add_field("Target Command", self.command)
        self.command.Bind(wx.EVT_TEXT, self.onchange_capture_settings)

        self.ta = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_RIGHT)
        self._add_field("Target App", self.ta)
        self.ta.Bind(wx.EVT_TEXT, self.onchange_capture_settings)

        self.target_cbuf = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_RIGHT)
        self._add_field("Target Trigger Buffer", self.target_cbuf)
        self.target_cbuf.Bind(wx.EVT_TEXT, self.onchange_capture_settings)

        self.msamples = IntCtrl(self, wx.ID_ANY, style=wx.TE_RIGHT)
        self._add_field("Max # Samples", self.msamples, small=True)
        self.msamples.Bind(wx.EVT_TEXT, self.onchange_capture_settings)

        self.delta = IntCtrl(self, wx.ID_ANY, style=wx.TE_RIGHT)
        self._add_field("Time Step", self.delta, small=True)
        self.delta.Bind(wx.EVT_TEXT, self.onchange_capture_settings)

        self.debug = wx.CheckBox(self, wx.ID_ANY)
        self._add_field("Debug TA Calls", self.debug, small=True)
        self.debug.Bind(wx.EVT_CHECKBOX, self.onchange_capture_settings)

        self.sizer.Add(buttons, 0, wx.ALL | wx.CENTER, 5)

        # Events
        self.btn_enable.Bind(wx.EVT_BUTTON, self.onclick_btn_enable)
        self.btn_connect.Bind(wx.EVT_BUTTON, self.onclick_btn_connect)
        self.choice_t_cpu.Bind(wx.EVT_CHOICE, self.onchoice_t_cpu)
        self.choice_s_cpu.Bind(wx.EVT_CHOICE, self.onchoice_s_cpu)
        self.btn_collect.Bind(wx.EVT_BUTTON, self.onclick_btn_collect)

        pub.subscribe(self.on_enable_changed, ScopeSource.ENABLED_CHANGED)
        pub.subscribe(self.on_connect_changed, ScopeSource.CONNECTED_CHANGED)
        pub.subscribe(self.on_capture_settings_changed,
                      ScopeSource.CAPTURE_SETTINGS_CHANGED)
        pub.subscribe(self.on_readiness_changed,
                      CaptureSource.READINESS_CHANGED)

        # Initial data
        self.draw_status()
        self.draw_capture_settings()
        self.draw_collect_btn()

    def _add_field(self, label, item, small=False):
        """Add a label/element pair to the UI"""
        szr = wx.BoxSizer(wx.HORIZONTAL)
        lbl = wx.StaticText(self, wx.ID_ANY, label)
        szr.Add(lbl, 1 if small else 0, wx.ALIGN_CENTER)
        szr.Add((15, 15), 0, wx.EXPAND)
        szr.Add(item, 0 if small else 1, wx.ALIGN_RIGHT)
        self.sizer.Add(szr, 0, wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT, 5)

    def onclick_btn_connect(self, evt):
        """Connect button has been clicked."""
        server = self.txt_server.GetValue()
        if self.scope.is_connected():
            self.scope.disconnect()
        self.scope.connect(server)

    def onclick_btn_enable(self, evt):
        """Enable button has been clicked."""
        if not self.scope.is_enabled():
            self.scope.enable()
        else:
            self.scope.disable()

    def onclick_btn_collect(self, evt):
        """Collect button has been clicked."""
        if self.env.get_active_dataset_name() is not None:
            self.env.collection_pipeline.run(1)

    def onchoice_t_cpu(self, evt):
        """The target CPU has changed."""
        sel = self.choice_t_cpu.GetSelection()
        if sel != wx.NOT_FOUND:
            self.scope.set_target_core(sel)

    def onchoice_s_cpu(self, evt):
        """The scope CPU has changed."""
        sel = self.choice_s_cpu.GetSelection()
        if sel != wx.NOT_FOUND:
            self.scope.set_scope_core(sel)

    def on_enable_changed(self):
        """The enable state of the scope has changed."""
        self.draw_status()

    def on_connect_changed(self):
        """The connection state of the scope has changed."""
        self.draw_status()
        self.draw_capture_settings()

    def on_capture_settings_changed(self):
        """The capture settings have changed."""
        self.draw_capture_settings()

    def on_readiness_changed(self):
        """The readiness of the scope has changed."""
        self.draw_collect_btn()

    def onchange_capture_settings(self, evt):
        """The user is trying to change the capture settings."""
        cmd = self.command.GetValue()
        ta = self.ta.GetValue()
        cbuf = self.target_cbuf.GetValue()
        msamp = self.msamples.GetValue()
        delta = self.delta.GetValue()
        debug = self.debug.GetValue()

        self.scope.set_capture_params(max_samples=msamp,
                                      time_delta=delta,
                                      ta_command=cmd,
                                      ta_name=ta,
                                      ta_cbuf=cbuf,
                                      debug=debug)

    def draw_status(self):
        """Update the state, buttons, and spinners based on current state"""
        enabled = self.scope.is_enabled()
        connected = self.scope.is_connected()

        if enabled and connected:
            scope_state = "Enabled"
        elif connected and not enabled:
            scope_state = "Connected and Disabled"
        else:
            scope_state = "Disconnected"

        btn_label = "Disable" if enabled else "Enable"
        scope_status = "Scope is %s" % scope_state

        self.status.SetLabel(scope_status)
        self.btn_connect.Enable(not enabled or not connected)
        self.txt_server.Enable(not enabled or not connected)
        self.btn_enable.SetLabel(btn_label)
        self.btn_enable.Enable(connected)

        ncores = self.scope.num_cores
        cores = ["Core %u" % i for i in range(ncores)]

        sel = self.choice_t_cpu.GetSelection()
        if sel == wx.NOT_FOUND:
            sel = self.scope.get_target_core()
        self.choice_t_cpu.SetItems(cores)
        if ncores > 0:
            self.choice_t_cpu.SetSelection(sel)
        self.choice_t_cpu.Enable(connected and not enabled)

        sel = self.choice_s_cpu.GetSelection()
        if sel == wx.NOT_FOUND:
            sel = self.scope.get_scope_core()
        self.choice_s_cpu.SetItems(cores)
        if ncores > 0:
            self.choice_s_cpu.SetSelection(sel)
        self.choice_s_cpu.Enable(connected and not enabled)

    def draw_capture_settings(self):
        """Draw the capture settings."""
        enabled = self.scope.is_enabled()
        connected = self.scope.is_connected()

        self.command.ChangeValue(self.scope.ta_command)
        self.ta.ChangeValue(self.scope.ta_name)
        self.target_cbuf.ChangeValue(self.scope.ta_cbuf)
        self.msamples.ChangeValue(self.scope.max_samples)
        self.delta.ChangeValue(self.scope.time_delta)
        self.debug.SetValue(self.scope.debug)

        self.command.Enable(connected)
        self.ta.Enable(connected)
        self.target_cbuf.Enable(connected)
        self.msamples.Enable(connected)
        self.delta.Enable(connected)
        self.debug.Enable(connected)

    def draw_collect_btn(self):
        """Enable or disable the collection button"""
        self.btn_collect.Enable(self.scope.is_ready())
Пример #7
0
class ProbeConfig(wx.Panel):
    """This is the view and controller for a single probe configuration"""
    def __init__(self, parent, probe):
        """Initialization"""
        wx.Panel.__init__(self, parent, wx.ID_ANY, style=wx.BORDER_SIMPLE)
        self.probe = probe

        sizer = wx.BoxSizer(wx.VERTICAL)

        assoc = wx.BoxSizer(wx.HORIZONTAL)
        nset = wx.BoxSizer(wx.HORIZONTAL)
        line = wx.BoxSizer(wx.HORIZONTAL)
        capt = wx.BoxSizer(wx.HORIZONTAL)
        btns = wx.BoxSizer(wx.HORIZONTAL)

        self.status = wx.StaticText(self, wx.ID_ANY, "Probe is Active")
        font = self.status.GetFont()
        font.SetWeight(wx.BOLD)
        self.status.SetFont(font)

        lbl_assoc = wx.StaticText(self, wx.ID_ANY, "Associativity")
        self.int_assoc = IntCtrl(self, wx.ID_ANY)
        self.int_assoc.SetValue(self.probe.associativity)
        assoc.Add(lbl_assoc, 1, wx.ALIGN_CENTER | wx.RIGHT, 5)
        assoc.Add(self.int_assoc, 0, wx.ALIGN_RIGHT)

        lbl_nset = wx.StaticText(self, wx.ID_ANY, "Number of Sets")
        self.int_nset = IntCtrl(self, wx.ID_ANY)
        self.int_nset.SetValue(self.probe.num_sets)
        nset.Add(lbl_nset, 1, wx.ALIGN_CENTER | wx.RIGHT, 5)
        nset.Add(self.int_nset, 0, wx.ALIGN_RIGHT)

        lbl_line = wx.StaticText(self, wx.ID_ANY, "Size of Line")
        self.int_line = IntCtrl(self, wx.ID_ANY)
        self.int_line.SetValue(self.probe.line_size)
        line.Add(lbl_line, 1, wx.ALIGN_CENTER | wx.RIGHT, 5)
        line.Add(self.int_line, 0, wx.ALIGN_RIGHT)

        lbl_capt = wx.StaticText(self, wx.ID_ANY, "Capture Limits:")
        lbl_lp = wx.StaticText(self, wx.ID_ANY, "[")
        self.spn_lo = wx.SpinButton(self, wx.ID_ANY)
        lbl_cm = wx.StaticText(self, wx.ID_ANY, ",")
        self.spn_hi = wx.SpinButton(self, wx.ID_ANY)
        lbl_rp = wx.StaticText(self, wx.ID_ANY, ")")
        self.btn_config = wx.Button(self, wx.ID_ANY, "Configure")
        capt.Add(lbl_capt, 3, wx.ALIGN_CENTER)
        capt.Add(lbl_lp, 0, wx.ALIGN_CENTER)
        capt.Add(self.spn_lo, 1, wx.ALIGN_CENTER)
        capt.Add(lbl_cm, 0, wx.ALIGN_CENTER)
        capt.Add(self.spn_hi, 1, wx.ALIGN_CENTER)
        capt.Add(lbl_rp, 0, wx.ALIGN_CENTER)
        capt.Add(self.btn_config, 0, wx.ALIGN_CENTER)

        self.btn_enable = wx.Button(self, wx.ID_ANY, "Enable")
        btns.Add(self.btn_enable, 0, wx.ALL, 5)

        sizer.Add(self.status, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(assoc, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(nset, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(line, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(capt, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(btns, 0, wx.ALIGN_CENTER | wx.ALL, 5)

        self.SetSizer(sizer)
        sizer.SetSizeHints(self)

        # Events
        self.btn_enable.Bind(wx.EVT_BUTTON, self.onclick_btn_enable)
        self.btn_config.Bind(wx.EVT_BUTTON, self.onclick_btn_config)

        pub.subscribe(self.on_enable_changed, Probe.ENABLED_CHANGED)
        pub.subscribe(self.on_enable_changed, Probe.CONFIG_CHANGED)

        # Initial data
        self.on_enable_changed()

    def set_status(self):
        """Display the status of the probe."""
        name = self.probe.name
        status = "Probe %s is active" % name
        self.status.SetLabel(status)

    def onclick_btn_enable(self, evt):
        """Enable button has been clicked."""
        if not self.probe.is_enabled():
            assoc = self.int_assoc.GetValue()
            nset = self.int_nset.GetValue()
            lsize = self.int_line.GetValue()
            self.probe.enable(assoc, nset, lsize)
        else:
            self.probe.disable()

    def onclick_btn_config(self, evt):
        """Configure button has been clicked."""
        lo = self.spn_lo.GetValue()
        hi = self.spn_hi.GetValue()
        if not self.probe.configure(lo, hi):
            msg = wx.MessageDialog(
                self, 'Failed to configure probe %s' % self.probe.name,
                'Failure', wx.OK)
            msg.ShowModal()
            msg.Destroy()

    def on_enable_changed(self, name=None):
        """The enable state of the scope has changed."""
        if name is not None and self.probe.name != name:
            return

        enabled = self.probe.is_enabled()
        prb_state = "Enabled" if enabled else "Disabled"
        btn_status = "Disable" if enabled else "Enable"
        prb_status = "Probe %s is %s" % (self.probe.name, prb_state)
        self.status.SetLabel(prb_status)
        self.btn_enable.SetLabel(btn_status)

        self.int_assoc.Enable(not enabled)
        self.int_nset.Enable(not enabled)
        self.int_line.Enable(not enabled)
        self.spn_lo.Enable(enabled)
        self.spn_hi.Enable(enabled)
        self.btn_config.Enable(enabled)
        self.spn_lo.SetRange(0, self.probe.num_sets)
        self.spn_hi.SetRange(0, self.probe.num_sets)
        self.spn_lo.SetValue(self.probe.low_set)
        self.spn_hi.SetValue(self.probe.high_set)