예제 #1
0
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          None,
                          size=(600, 600),
                          title='Display Waveforms')
        self.parent = parent
        self.panel = wx.Panel(self)

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

        self.Fig1 = CanvasPanel(self.panel)

        self.m_ok_button = wx.Button(parent=self.panel, id=-1, label='Ok')

        self.sizer.Add(item=self.Fig1, proportion=1, flag=wx.ALL)

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.sizer.Add(item=self.m_ok_button,
                       proportion=1,
                       flag=wx.CENTER | wx.ALL)

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.panel.SetSizer(self.sizer)

        self.panel.Fit()

        # event bindings
        self.m_ok_button.Bind(wx.EVT_BUTTON, self.ok_button)
예제 #2
0
파일: PlotModal.py 프로젝트: MK8J/ui
    def __init__(self, parent):
        wx.Frame.__init__(self, None, size=(600, 600), title='Display Waveforms')
        self.parent = parent
        self.panel = wx.Panel(self)

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

        self.Fig1 = CanvasPanel(self.panel)

        self.m_ok_button = wx.Button(parent=self.panel, id=-1, label='Ok')

        self.sizer.Add(
            item=self.Fig1,
            proportion=1,
            flag=wx.ALL
        )

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.sizer.Add(
            item=self.m_ok_button,
            proportion=1,
            flag=wx.CENTER | wx.ALL
        )

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.panel.SetSizer(self.sizer)

        self.panel.Fit()

        # event bindings
        self.m_ok_button.Bind(wx.EVT_BUTTON, self.ok_button)
예제 #3
0
파일: PlotModal.py 프로젝트: MK8J/ui
class PlotModal(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, None, size=(600, 600), title='Display Waveforms')
        self.parent = parent
        self.panel = wx.Panel(self)

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

        self.Fig1 = CanvasPanel(self.panel)

        self.m_ok_button = wx.Button(parent=self.panel, id=-1, label='Ok')

        self.sizer.Add(
            item=self.Fig1,
            proportion=1,
            flag=wx.ALL
        )

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.sizer.Add(
            item=self.m_ok_button,
            proportion=1,
            flag=wx.CENTER | wx.ALL
        )

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.panel.SetSizer(self.sizer)

        self.panel.Fit()

        # event bindings
        self.m_ok_button.Bind(wx.EVT_BUTTON, self.ok_button)

    def ok_button(self, evt):
        self.Destroy()

    def clear_figure(self):
        self.Fig1.clear()

    def plot_data(self, x, data):
        self.colours = ["r", "g", "b"]
        # This plots the figure
        for index, column in enumerate(data):

            self.Fig1.draw_points(
                x,
                column,
                '.',
                Color=self.colours[index]
            )

        self.Fig1.update()
예제 #4
0
    def __InitUI(self, parent):
        # initialize parent class
        FrameSkeleton.__init__(self, parent)

        # setup Matplotlib Canvas panel
        self.Fig1 = CanvasPanel(self.Figure1_Panel)

        # make status bars
        m_statusBar = wx.StatusBar(self)

        self.SetStatusBar(m_statusBar)
        # self.m_statusBar.SetStatusText("Ready to go!")

        self.data_panel = DataProcessingPanel(self.m_notebook1)

        self.m_notebook1.AddPage(
            self.data_panel,
            u"Data Processing",
            # True
        )

        # Setup the Menu
        menu_bar = wx.MenuBar()

        # File Menu
        filem = wx.Menu()
        filem.Append(wx.ID_OPEN, "Open\tCtrl+O")
        filem.Append(wx.ID_ANY, "Run\tCtrl+R")
        filem.Append(wx.ID_ABOUT, "About")
        filem.Append(wx.ID_EXIT, "Exit\tCtrl+X")

        # TODO: add and bind event handlers
        menu_bar.Append(filem, "&File")

        self.SetMenuBar(menu_bar)

        # initialise view with model parameters
        self.m_voltageRange.AppendItems(INPUT_VOLTAGE_RANGE_STR)
        self.m_Waveform.AppendItems(WAVEFORMS)
        self.m_Output.AppendItems(OUTPUTS)

        self.setWaveformParameters()
        self.setCollectionParameters()
예제 #5
0
class PlotModal(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          None,
                          size=(600, 600),
                          title='Display Waveforms')
        self.parent = parent
        self.panel = wx.Panel(self)

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

        self.Fig1 = CanvasPanel(self.panel)

        self.m_ok_button = wx.Button(parent=self.panel, id=-1, label='Ok')

        self.sizer.Add(item=self.Fig1, proportion=1, flag=wx.ALL)

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.sizer.Add(item=self.m_ok_button,
                       proportion=1,
                       flag=wx.CENTER | wx.ALL)

        self.sizer.AddSpacer((10, 10), 1, wx.EXPAND, 10)

        self.panel.SetSizer(self.sizer)

        self.panel.Fit()

        # event bindings
        self.m_ok_button.Bind(wx.EVT_BUTTON, self.ok_button)

    def ok_button(self, evt):
        self.Destroy()

    def clear_figure(self):
        self.Fig1.clear()

    def plot_data(self, data):
        self.colours = ["r", "g", "b"]
        # This plots the figure
        for index, column in enumerate(data):

            self.Fig1.draw_points(range(len(column)),
                                  column,
                                  '.',
                                  Color=self.colours[index])

        self.Fig1.update()
예제 #6
0
class GUIController(FrameSkeleton):
    """
    Controller to handle interface with wx UI

    Attributes
    ----------


    MyFrame1:
    Fig1
    Data

    LoadPath
    Path
    measurement_type


    """

    def __init__(self, parent):

        # models
        self.metadata = ExperimentSettings()

        self.Data = ExperimentData(metadata=self.metadata)

        self.light_pulse = LightPulse(self.metadata)

        # setup file data
        self.dirname = os.getcwd()
        self.data_file = "untitled.dat"
        self.metadata_file = "untitled.inf"

        self.__InitUI(parent)
        self.__InitValidators()

    def __InitUI(self, parent):
        # initialize parent class
        FrameSkeleton.__init__(self, parent)

        # setup Matplotlib Canvas panel
        self.Fig1 = CanvasPanel(self.Figure1_Panel)

        # make status bars
        m_statusBar = wx.StatusBar(self)

        self.SetStatusBar(m_statusBar)
        # self.m_statusBar.SetStatusText("Ready to go!")

        self.data_panel = DataProcessingPanel(self.m_notebook1)

        self.m_notebook1.AddPage(
            self.data_panel,
            u"Data Processing",
            # True
        )

        # Setup the Menu
        menu_bar = wx.MenuBar()

        # File Menu
        filem = wx.Menu()
        filem.Append(wx.ID_OPEN, "Open\tCtrl+O")
        filem.Append(wx.ID_ANY, "Run\tCtrl+R")
        filem.Append(wx.ID_ABOUT, "About")
        filem.Append(wx.ID_EXIT, "Exit\tCtrl+X")

        # TODO: add and bind event handlers
        menu_bar.Append(filem, "&File")

        self.SetMenuBar(menu_bar)

        # initialise view with model parameters
        self.m_voltageRange.AppendItems(INPUT_VOLTAGE_RANGE_STR)
        self.m_Waveform.AppendItems(WAVEFORMS)
        self.m_Output.AppendItems(OUTPUTS)

        self.setWaveformParameters()
        self.setCollectionParameters()

    def __InitValidators(self):

        # Waveform validators
        self.m_Intensity.SetValidator(NumRangeValidator(numeric_type='int'))
        self.m_Threshold.SetValidator(NumRangeValidator(numeric_type='int'))
        self.m_Period.SetValidator(NumRangeValidator(numeric_type='float'))
        self.m_Offset_Before.SetValidator(NumRangeValidator(numeric_type='float'))
        self.m_Offset_After.SetValidator(NumRangeValidator(numeric_type='float'))

        # Data collection validators
        self.m_samplingFreq.SetValidator(NumRangeValidator(numeric_type='float'))
        self.m_Averaging.SetValidator(NumRangeValidator(numeric_type='int'))
        self.m_Binning.SetValidator(NumRangeValidator(numeric_type='int'))

    def setPCCalibrationMean(self):
        self.m_pcCalibrationMean.SetValue('{0:3.3f}'.format(
            self.metadata.pc_calibration_mean
        ))

    def setPCCalibrationStd(self):
        self.m_pcCalibrationStd.SetValue('{0:3.3f}'.format(
            self.metadata.pc_calibration_std
        ))

    def setSampleDataPoints(self, sample_data_points):
        self.m_DataPoint.SetValue('{0:.2e}'.format(sample_data_points))

    def setFrequency(self, frequence_val):
        self.m_Frequency.SetValue('{0:3.3f}'.format(frequence_val))

    def setWaveformParameters(self):
        self.m_Intensity.SetValue(str(self.metadata.amplitude))
        self.m_Period.SetValue(str(self.metadata.duration))
        self.m_Offset_Before.SetValue(str(self.metadata.offset_before))
        self.m_Offset_After.SetValue(str(self.metadata.offset_after))
        self.setFrequency(self.metadata.get_frequency())

    def setCollectionParameters(self):
        self.m_Binning.SetValue(str(self.metadata.binning))
        self.m_Averaging.SetValue(str(self.metadata.averaging))
        self.m_Threshold.SetValue(str(self.metadata.threshold))
        self.m_samplingFreq.SetValue(str(self.metadata.sample_rate))

        self.setSampleDataPoints(self.metadata.get_total_data_points())


    #################################
    # Event Handlers for Measurements
    def Perform_Measurement(self, event):

        print("GUIController: Perform_Measurement")

        # Using that instance we then run the lights,
        # and measure the outputs
        self.measurement_handler = MeasurementHandler()
        measurement_handler.add_to_queue(
            self.light_pulse.complete_waveform,
            self.metadata
        )

        raw_data = self.measurement_handler.single_measurement()
        self.Data.updateRawData(raw_data)
        self.Data.Data = utils.bin_data(raw_data, self.metadata.binning)
        # We then plot the datas, this has to be changed if the plots want
        # to be updated on the fly.

        pub.sendMessage('update.plot')


    def fftHandler(self):
        channel = self.data_panel.m_fftChoice.GetStringSelection()
        freq_data = self.Data.fftOperator(channel, self.metadata.get_total_time())
        self.PlotData(freq_data, title=['FFT of Raw data', 'Frequency (hz)', 'Voltage (V)'])


    def onWaveformParameters(self, event):
        self.metadata.A = float(self.m_Intensity.GetValue())
        self.metadata.Duration = float(self.m_Period.GetValue())
        self.metadata.Offset_Before = float(self.m_Offset_Before.GetValue())
        self.metadata.Offset_After = float(self.m_Offset_After.GetValue())
        self.metadata.Waveform = self.m_Waveform.GetStringSelection()

        pub.sendMessage('waveform.change')


    def onCollectionParameters(self, event):
        # TODO: refactor so it obeys DRY

        self.metadata.binning = int(self.m_Binning.GetValue())
        self.metadata.averaging = int(self.m_Averaging.GetValue())
        self.metadata.channel = self.m_Output.GetStringSelection()
        self.metadata.threshold = float(self.m_Threshold.GetValue())
        self.metadata.sample_rate = float(self.m_samplingFreq.GetValue())
        self.metadata.sample_data_points = self.metadata.get_total_data_points()

        pub.sendMessage('collection.change')

    ##########################
    # Plot Handlers
    #

    def plotHandler(self):
        self.PlotData(self.Data.Data)

    def PlotData(self, data, data_labels=['Reference', 'PC', 'PL'],
                 title=['Raw Data', 'Time (s)', 'Voltage (V)'], e=None):

        self.Fig1.clear()
        labels = data_labels
        colours = ['b', 'r', 'g']

        # this is done not to clog up the plot with many points
        if data.shape[0] > 1000:
            num = data.shape[0] // 1000
        else:
            num = 1

        # This plots the figure
        for i, label, colour in zip(data[:, 1:].T, labels, colours):

            self.Fig1.draw_points(
                data[::num, 0],
                i[::num],
                '.',
                Color=colour,
                Label=label
            )

        self.Fig1.legend()
        self.Fig1.labels(title[0], title[1], title[2])
        self.Fig1.update()
        if e is not None:
            e.skip()

    #################
    # Helper methods:
    def defaultFileDialogOptions(self):
        """
        Return a dictionary with file dialog options that can be
        used in both the save file dialog as well as in the open
        file dialog.
        """
        return dict(message='Choose a file', defaultDir=self.dirname, wildcard='*.*')

    def askUserForFilename(self, **dialogOptions):
        dialog = wx.FileDialog(self, **dialogOptions)
        if dialog.ShowModal() == wx.ID_OK:
            userProvidedFilename = True
            self.data_file = dialog.GetFilename()
            self.dirname = dialog.GetDirectory()
        else:
            userProvidedFilename = False
        dialog.Destroy()
        return userProvidedFilename

    def ShowCalibrationModal(self):
        msg_text = (
            "Please remove sample from measurement area\n"
            "Only one PC calibration is necessary per experimental session"
        )
        wx.MessageBox(msg_text, 'Info', wx.OK | wx.ICON_INFORMATION)

    ##########################
    # App state Event Handlers
    #
    def onSave(self, event):
        """
        Method to handle dialogue window and saving data to file
        """

        dialog = wx.FileDialog(
            None,
            'Save measurement data and metadata',
            self.dirname,
            '',
            r'DAT and INF files (*.dat;*.inf)|*.inf;*.dat',
            wx.FD_SAVE
        )

        if dialog.ShowModal() == wx.ID_OK:
            dialog_path = dialog.GetPath()
            self.dirname = os.path.dirname(dialog_path)
            self.SaveName = os.path.splitext(os.path.basename(dialog_path))[0]

            experiment_settings = self.metadata.get_settings_as_dict()
            waveform_settings = self.light_pulse.get_settings_as_dict()
            metadata_dict = experiment_settings.copy()

            utils.save_data(self.Data.Data, self.SaveName, self.dirname)
            utils.save_metadata(
                metadata_dict,
                self.SaveName,
                self.dirname
            )

        else:
            print('Canceled save')
        dialog.Destroy()

        event.Skip()

    def onSaveData(self, event):
        print("onSaveData")
        if self.askUserForFilename(style=wx.SAVE,
                                   **self.defaultFileDialogOptions()):
            utils.save_data(self.Data.Data, self.data_file, self.dirname)

        # print(filename)
        # fullpath = os.path.join(self.dirname, self.data_file)
        # self.Data.updateRawData(utils.load_data(fullpath))


    def onLoad(self, event):
        """
        Method to handle load metadata dialog window and update metadata state
        """

        dialog = wx.FileDialog(
            None,
            'Select a metadata file',
            self.dirname,
            '',
            r'*.inf',
            wx.FD_OPEN
        )

        if dialog.ShowModal() == wx.ID_OK:

            metadata_dict = utils.load_metadata(dialog.GetPath())
            metadata_stringified = dict(
                [a, str(x)] for a, x in metadata_dict.iteritems()
            )
            print(metadata_stringified)

            # experimental data
            self.m_Output.SetStringSelection(metadata_stringified[u'Channel'])
            self.m_Averaging.SetValue(metadata_stringified[u'Averaging'])
            try:
                self.m_Binning.SetValue(metadata_stringified[u'Measurement_Binning'])
            except:
                self.m_Binning.SetValue(metadata_stringified[u'Binning'])
            self.m_Threshold.SetValue(metadata_stringified[u'Threshold_mA'])


            # waveform data
            self.m_Intensity.SetValue(metadata_stringified[u'Intensity_v'])
            self.m_Waveform.SetStringSelection(metadata_stringified[u'Waveform'])

            self.m_Offset_Before.SetValue(metadata_stringified[u'Offset_Before_ms'])
            self.m_Offset_After.SetValue(metadata_stringified[u'Offset_After_ms'])
            self.m_Period.SetValue(metadata_stringified[u'Peroid_s'])

        dialog.Destroy()
        event.Skip()

    def onLoadData(self, event):
        """
        Handlers loading of new data set into Frame
        """
        print("start data loading")
        if self.askUserForFilename(style=wx.OPEN,
                                   **self.defaultFileDialogOptions()):
            fullpath = os.path.join(self.dirname, self.data_file)
            self.Data.updateRawData(utils.load_data(fullpath))

            print(self.Data.Data)
            pub.sendMessage('update.plot')
            self.onWaveformParameters(self, event)
            self.onCollectionParameters(self, event)

    def onExit(self, event):
        self.Close()

    def OnAbout(self, event):
        dialog = wx.MessageDialog(
            self,
            'An PV experimental assistant in wxPython',
            'About PVapp',
            wx.OK
        )
        dialog.ShowModal()
        dialog.Destroy()


    def onStatusUpdate(self, status, is_error=False):

        self.SetStatusText(status, 0)
        if is_error:
            self.m_statusBar.SetBackgroundColour('RED')
            self.m_statusBar.SetStatusText(status)
        else:
            self.m_statusBar.SetStatusText(status)