Esempio n. 1
0
    def calibrate_pc(self, event):
        """"
        Perform and calibrate the PC measurement
        """
        self.view1.show_calibration_modal()

        null_metadata = ExperimentSettings()
        null_metadata.waveform = "NullWave"

        pc_data = self.measurement_handler.pc_calibration_measurement(
            null_metadata)

        self.pc_calibration.update_data(pc_data)
Esempio n. 2
0
    def calibrate_pc(self, event):
        """"
        Perform and calibrate the PC measurement
        """
        self.view1.show_calibration_modal()

        null_metadata = ExperimentSettings()
        null_metadata.waveform = "NullWave"

        pc_data = self.measurement_handler.pc_calibration_measurement(
            null_metadata
        )

        self.pc_calibration.update_data(pc_data)
Esempio n. 3
0
class ExperimentSettingsTest(unittest.TestCase):
    # np.set_printoptions(threshold='nan')
    def setUp(self):
        self.meta_data = ExperimentSettings()
        self.maxDiff = None

    def test_get_settings_as_dict(self):
        meta_data = {
            "channel": "High (2A/V)",
            "averaging": 1,
            "measurement_binning": 1,
            "threshold_mA": 150,
            "inverted_channels": {"Reference": False, "PC": False, "PL": True},
            "sample_rate": 1.2e3,
            "output_sample_rate": 1.2e3,
            "input_voltage_range": 10.0,
            "output_voltage_range": 10.0,
            "waveform": "Sin",
            "amplitude": 0.5,
            "offset_before": 1,
            "offset_after": 10,
            "duration": 1,
            "voltage_threshold": 0.08152173913043478,
            "channel_name": "ao0",
            #
            "pc_calibration_mean": None,
            "pc_calibration_std": None,
        }
        self.assertDictEqual(self.meta_data.as_dict(), meta_data)

    def test_init(self):
        self.assertEqual(self.meta_data.voltage_threshold, 0.08152173913043478)
        self.assertEqual(self.meta_data.channel_name, "ao0")

    def test_set_amplitude(self):
        self.assertTrue(self.meta_data.amplitude, 0.5)

    def test_set_amplitude_too_high(self):
        self.meta_data.channel = "Low (50mA/V)"
        self.meta_data.amplitude = 15
        self.assertEqual(self.meta_data.amplitude, 10)

        self.meta_data.channel = "High (2A/V)"
        self.meta_data.amplitude = 15
        self.assertEqual(self.meta_data.amplitude, 1.5)

    def test_set_voltage_too_high(self):
        pass

    def test_set_sample_rate_too_high(self):
        self.meta_data.sample_rate = 9e90
        self.assertEqual(self.meta_data.sample_rate, 1.2e6)
Esempio n. 4
0
    def test_single_measurement_with_averaging(self, mock_waveform_thread):
        # setup
        settings = ExperimentSettings()
        settings.averaging = 2
        handler = MeasurementHandler()
        return_tuple = [
            (np.array([2, 3, 4, 5, 6, 7]), np.array([0, 1])),
            (np.array([3, 4, 5, 6, 7, 8]), np.array([0, 1])),
        ]

        handler.add_to_queue(self.lp.create_waveform(), settings)

        with patch.object(handler, '_run_thread', side_effect=return_tuple) as method:
            # perform
            test_dataset = handler.single_measurement()

            # assert
            self.assertEqual(2, method.call_count)
            np.testing.assert_array_equal(
                test_dataset,
                np.array([[0, 2.5, 4.5, 6.5], [1, 3.5, 5.5, 7.5]])
            )

        self.assertEqual(len(handler._queue), 0)
Esempio n. 5
0
    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()
Esempio n. 6
0
    def _parse_experiment_settings(self, config):
        measurement_list = []
        experiments_list = config["experiment_settings"]
        for item in experiments_list:
            try:
                measurement_list.append(
                    ExperimentSettings(waveform=item['waveform'],
                                       duration=item['duration'],
                                       amplitude=item['amplitude'],
                                       offset_before=item['offset_before'],
                                       offset_after=item['offset_after'],
                                       sample_rate=item['sample_rate'],
                                       channel=item['channel'],
                                       binning=item['binning'],
                                       averaging=item['averaging']))
            except KeyError as e:
                raise ("Missing value in Experiment Settings: {0}".format(e))

        return measurement_list
Esempio n. 7
0
 def setUp(self):
     self.meta_data = ExperimentSettings()
     self.maxDiff = None
Esempio n. 8
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)
Esempio n. 9
0
 def setUp(self):
     self.settings = ExperimentSettings()
     self.lp = LightPulse(self.settings)
Esempio n. 10
0
 def setUp(self):
     self.meta_data = ExperimentSettings()
     self.maxDiff = None
Esempio n. 11
0
class ExperimentSettingsTest(unittest.TestCase):
    # np.set_printoptions(threshold='nan')
    def setUp(self):
        self.meta_data = ExperimentSettings()
        self.maxDiff = None

    def test_get_settings_as_dict(self):
        meta_data = {
            'channel': 'High (2A/V)',
            'averaging': 1,
            'measurement_binning': 1,
            'threshold_mA': 150,
            "inverted_channels": {
                'Reference': False,
                'PC': False,
                'PL': True
            },

            'sample_rate': 1.2e3,
            'output_sample_rate': 1.2e3,

            "input_voltage_range": 10.0,
            "output_voltage_range": 10.0,
            "waveform": 'Sin',
            "amplitude": 0.5,

            "offset_before": 1,
            "offset_after": 10,
            "duration": 1,
            "voltage_threshold": 0.08152173913043478,
            "channel_name": 'ao0',

            #
            "pc_calibration_mean": None,
            "pc_calibration_std": None
        }
        self.assertDictEqual(self.meta_data.as_dict(), meta_data)

    def test_init(self):
        self.assertEqual(
            self.meta_data.voltage_threshold,
            0.08152173913043478,
        )
        self.assertEqual(
            self.meta_data.channel_name,
            'ao0'
        )

    def test_set_amplitude(self):
        self.assertTrue(self.meta_data.amplitude, 0.5)

    def test_set_amplitude_too_high(self):
        self.meta_data.channel = 'Low (50mA/V)'
        self.meta_data.amplitude = 15
        self.assertEqual(self.meta_data.amplitude, 10)

        self.meta_data.channel = 'High (2A/V)'
        self.meta_data.amplitude = 15
        self.assertEqual(self.meta_data.amplitude, 1.5)

    def test_set_voltage_too_high(self):
        pass

    def test_set_sample_rate_too_high(self):
        self.meta_data.sample_rate = 9e90
        self.assertEqual(self.meta_data.sample_rate, 1.2e6)