Beispiel #1
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """

        # Check the platform architecture:
        arch = platform.architecture()
        if arch == ('32bit', 'WindowsPE'):
            libname = 'spinapi.dll'
        elif arch == ('64bit', 'WindowsPE'):
            libname = 'spinapi64.dll'
        elif arch == ('32bit', 'ELF'):
            folderpath = os.path.join(get_main_dir(), 'hardware',
                                      'SpinCore')
            libname = os.path.join(folderpath, 'libspinapi.so')
        elif arch == ('64bit', 'ELF'):
            folderpath = os.path.join(get_main_dir(), 'hardware',
                                      'SpinCore')
            libname = os.path.join(folderpath, 'libspinapi64.so')

        # In Windows load the spinapi library file spinapi.dll from the folder
        # <Windows>/System32/. For Unix systems, the shared object (= *.so)
        # file muss be within the same directory, where the file is situated.
        self._dll = ctypes.cdll.LoadLibrary(libname)

        #FIXME: Check before if library exists and if it is loadable.

        self.open_connection()
Beispiel #2
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """

        # Check the platform architecture:
        arch = platform.architecture()
        if arch == ('32bit', 'WindowsPE'):
            libname = 'spinapi.dll'
        elif arch == ('64bit', 'WindowsPE'):
            libname = 'spinapi64.dll'
        elif arch == ('32bit', 'ELF'):
            folderpath = os.path.join(get_main_dir(), 'hardware', 'SpinCore')
            libname = os.path.join(folderpath, 'libspinapi.so')
        elif arch == ('64bit', 'ELF'):
            folderpath = os.path.join(get_main_dir(), 'hardware', 'SpinCore')
            libname = os.path.join(folderpath, 'libspinapi64.so')

        # In Windows load the spinapi library file spinapi.dll from the folder
        # <Windows>/System32/. For Unix systems, the shared object (= *.so)
        # file muss be within the same directory, where the file is situated.
        self._dll = ctypes.cdll.LoadLibrary(libname)

        #FIXME: Check before if library exists and if it is loadable.

        self.open_connection()
Beispiel #3
0
    def set_sample_rate(self, sample_rate):
        """ Set the sample rate of the pulse generator hardware.

        @param float sample_rate: The sampling rate to be set (in Hz)

        @return float: the sample rate returned from the device.

        Note: After setting the sampling rate of the device, retrieve it again
              for obtaining the actual set value and use that information for
              further processing.
        """
        bitfile_name = 'pulsegen_8chnl_'
        if sample_rate == 950e6:
            bitfile_name = bitfile_name + '950MHz_' + self._fpga_type.split('_')[1] + '.bit'
        elif sample_rate == 500e6:
            bitfile_name = bitfile_name + '500MHz_' + self._fpga_type.split('_')[1] + '.bit'
        else:
            self.log.error('Setting "{0:.3e}" as sample rate for FPGA pulse generator is not allowed. '
                           'Use 950e6 or 500e6 instead.'.format(sample_rate))
            return -1
        bitfile_path = os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga', bitfile_name)

        self.sample_rate = sample_rate
        self.fpga.ConfigureFPGA(bitfile_path)
        self.log.debug('FPGA pulse generator configured with {0}'.format(bitfile_path))
        return self.sample_rate
Beispiel #4
0
    def set_sample_rate(self, sample_rate):
        """ Set the sample rate of the pulse generator hardware.

        @param float sample_rate: The sampling rate to be set (in Hz)

        @return float: the sample rate returned from the device (in Hz).

        Note: After setting the sampling rate of the device, use the actually set return value for
              further processing.
        """
        if self.__current_status == 1:
            self.log.error('Can`t change the sample rate while the FPGA is running.')
            return self.__sample_rate

        # Round sample rate either to 500MHz or 950MHz since no other values are possible.
        if sample_rate < 725e6:
            self.__sample_rate = 500e6
            bitfile_name = 'pulsegen_8chnl_500MHz_{0}.bit'.format(self._fpga_type.split('_')[1])
        else:
            self.__sample_rate = 950e6
            bitfile_name = 'pulsegen_8chnl_950MHz_{0}.bit'.format(self._fpga_type.split('_')[1])

        bitfile_path = os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga', bitfile_name)

        self.fpga.ConfigureFPGA(bitfile_path)
        self.log.info('FPGA pulse generator configured with {0}'.format(bitfile_path))

        if self.fpga.IsFrontPanel3Supported():
            self._fp3support = True
        else:
            self._fp3support = False
            self.log.warning('FrontPanel3 is not supported. '
                             'Please check if the FPGA is directly connected by USB3.')
        self.__current_status = 0
        return self.__sample_rate
    def set_sample_rate(self, sample_rate):
        """ Set the sample rate of the pulse generator hardware.

        @param float sample_rate: The sampling rate to be set (in Hz)

        @return float: the sample rate returned from the device (in Hz).

        Note: After setting the sampling rate of the device, use the actually set return value for
              further processing.
        """
        if self.__current_status == 1:
            self.log.error('Can`t change the sample rate while the FPGA is running.')
            return self.__sample_rate

        # Round sample rate either to 500MHz or 950MHz since no other values are possible.
        if sample_rate < 725e6:
            self.__sample_rate = 500e6
            bitfile_name = 'pulsegen_8chnl_500MHz_{0}.bit'.format(self._fpga_type.split('_')[1])
        else:
            self.__sample_rate = 950e6
            bitfile_name = 'pulsegen_8chnl_950MHz_{0}.bit'.format(self._fpga_type.split('_')[1])

        bitfile_path = os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga', bitfile_name)

        self.fpga.ConfigureFPGA(bitfile_path)
        self.log.info('FPGA pulse generator configured with {0}'.format(bitfile_path))

        if self.fpga.IsFrontPanel3Supported():
            self._fp3support = True
        else:
            self._fp3support = False
            self.log.warning('FrontPanel3 is not supported. '
                             'Please check if the FPGA is directly connected by USB3.')
        self.__current_status = 0
        return self.__sample_rate
Beispiel #6
0
 def get_data_testfile(self):
     """ Load data test file """
     data = np.loadtxt(
         os.path.join(get_main_dir(), 'tools',
                      'FastComTec_demo_timetrace.asc'))
     time.sleep(0.5)
     return data
Beispiel #7
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """
        self.gated_extraction_methods = OrderedDict()
        self.ungated_extraction_methods = OrderedDict()
        self.extraction_methods = OrderedDict()
        filename_list = []
        # The assumption is that in the directory pulse_extraction_methods, there are
        # *.py files, which contain only methods!
        path = os.path.join(get_main_dir(), 'logic', 'pulse_extraction_methods')
        for entry in os.listdir(path):
            if os.path.isfile(os.path.join(path, entry)) and entry.endswith('.py'):
                filename_list.append(entry[:-3])

        for filename in filename_list:
            mod = importlib.import_module('logic.pulse_extraction_methods.{0}'.format(filename))
            for method in dir(mod):
                try:
                    # Check for callable function or method:
                    ref = getattr(mod, method)
                    if callable(ref) and (inspect.ismethod(ref) or inspect.isfunction(ref)):
                        # Bind the method as an attribute to the Class
                        setattr(PulseExtractionLogic, method, getattr(mod, method))
                        # Add method to dictionary if it is an extraction method
                        if method.startswith('gated_'):
                            self.gated_extraction_methods[method[6:]] = eval('self.' + method)
                            self.extraction_methods[method[6:]] = eval('self.' + method)
                        elif method.startswith('ungated_'):
                            self.ungated_extraction_methods[method[8:]] = eval('self.' + method)
                            self.extraction_methods[method[8:]] = eval('self.' + method)
                except:
                    self.log.error('It was not possible to import element {0} from {1} into '
                                   'PulseExtractionLogic.'.format(method, filename))
        return
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """
        path_dll = os.path.join(get_main_dir(), 'thirdparty', 'vaunix',
                                'vnx_fmsynth.dll')
        self._vaunixdll = ctypes.windll.LoadLibrary(path_dll)

        self._vaunixdll.fnLMS_GetNumDevices()
        self._vaunixdll.fnLMS_SetTestMode(ctypes.c_bool(False))

        active_devices = (ctypes.c_uint * 64)()
        numofdevs = self._vaunixdll.fnLMS_GetDevInfo(active_devices)

        if numofdevs == 1:
            self._devID = active_devices[0]
            err = self._vaunixdll.fnLMS_InitDevice(self._devID)
            if err:
                self.log.error(
                    'Error occurred during initialization: {}'.format(err))
                return -1
            return 0

        elif numofdevs > 1:
            self.log.warning(
                'There is more than 1 Vaunix device connected, currently only one connection is supported.'
            )
            return -1

        else:
            self.log.warning('No Vaunix devices found.')
            return -1
Beispiel #9
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """

        self.analysis_methods = OrderedDict()
        filename_list = []
        # The assumption is that in the directory pulsed_analysis_methods, there are
        # *.py files, which contain only methods!
        path = os.path.join(get_main_dir(), 'logic', 'pulsed_analysis_methods')
        for entry in os.listdir(path):
            if os.path.isfile(os.path.join(path, entry)) and entry.endswith('.py'):
                filename_list.append(entry[:-3])

        for filename in filename_list:
            mod = importlib.import_module('logic.pulsed_analysis_methods.{0}'.format(filename))
            for method in dir(mod):
                try:
                    # Check for callable function or method:
                    ref = getattr(mod, method)
                    if callable(ref) and (inspect.ismethod(ref) or inspect.isfunction(ref)):
                        # Bind the method as an attribute to the Class
                        setattr(PulseAnalysisLogic, method, getattr(mod, method))
                        # Add method to dictionary if it is a generator method
                        if method.startswith('analyse_'):
                            self.analysis_methods[method[8:]] = eval('self.' + method)
                except:
                    self.log.error('It was not possible to import element {0} from {1} into '
                                   'PulseAnalysisLogic.'.format(method, filename))
        return
Beispiel #10
0
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to
        # determine also how many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error('No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper hardware switch configuration bitfile to the FPGA
        bitfile_name = 'switch_8chnl_withcopy_LX150.bit'
        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                                              bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA')
            return -1
        else:
            self._fpga.SetWireInValue(0x00, 0x00000000)
            self._fpga.UpdateWireIns()

        self._switch_status = {0: False, 1: False, 2: False, 3: False,
                               4: False, 5: False, 6: False, 7: False}
        self._connected = True
        return 0
 def getSaveFile(self):
     """ Ask the user for a file where the configuration should be saved
         to.
     """
     defaultconfigpath = os.path.join(get_main_dir(), 'config')
     filename = QtWidgets.QFileDialog.getSaveFileName(
         self._mw, 'Save Configration', defaultconfigpath,
         'Configuration files (*.cfg)')[0]
     if filename != '':
         self.sigSaveConfig.emit(filename)
Beispiel #12
0
    def __init__(self, pulsedmeasurementlogic):
        # Init base class
        super().__init__(pulsedmeasurementlogic)

        # Dictionaries holding references to the extraction methods
        self._gated_extraction_methods = dict()
        self._ungated_extraction_methods = dict()
        # dictionary containing all possible parameters that can be used by the extraction methods
        self._parameters = dict()
        # Currently selected extraction method
        self._current_extraction_method = None

        # import path for extraction modules from default directory (logic.pulse_extraction_methods)
        path_list = [
            os.path.join(get_main_dir(), 'logic', 'pulsed',
                         'pulse_extraction_methods')
        ]
        # import path for extraction modules from non-default directory if a path has been given
        if isinstance(pulsedmeasurementlogic.extraction_import_path, str):
            path_list.append(pulsedmeasurementlogic.extraction_import_path)

        # Import extraction modules and get a list of extractor classes
        extractor_classes = self.__import_external_extractors(paths=path_list)

        # create an instance of each class and put them in a temporary list
        extractor_instances = [
            cls(pulsedmeasurementlogic) for cls in extractor_classes
        ]

        # add references to all extraction methods in each instance to a dict
        self.__populate_method_dicts(instance_list=extractor_instances)

        # populate "_parameters" dictionary from extraction method signatures
        self.__populate_parameter_dict()

        # Set default extraction method
        if self.is_gated:
            self._current_extraction_method = natural_sort(
                self._gated_extraction_methods)[0]
        else:
            self._current_extraction_method = natural_sort(
                self._ungated_extraction_methods)[0]

        # Update from parameter_dict if handed over
        if isinstance(pulsedmeasurementlogic.extraction_parameters, dict):
            # Delete unused parameters
            params = [
                p for p in pulsedmeasurementlogic.extraction_parameters
                if p not in self._parameters and p != 'method'
            ]
            for param in params:
                del pulsedmeasurementlogic.extraction_parameters[param]
            # Update parameter dict and current method
            self.extraction_settings = pulsedmeasurementlogic.extraction_parameters
        return
Beispiel #13
0
 def on_activate(self):
     self.fp = ok.FrontPanel()
     self.fp.GetDeviceCount()
     self.fp.OpenBySerial(self.fp.GetDeviceListSerial(0))
     self.fp.ConfigureFPGA(os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga', 'switch_top.bit'))
     if not self.fp.IsFrontPanelEnabled():
         self.log.error('FrontPanel is not enabled in FPGA switch!')
         return
     else:
         self.reset()
         self.log.info('FPGA connected')
Beispiel #14
0
 def getSaveFile(self):
     """ Ask the user for a file where the configuration should be saved
         to.
     """
     defaultconfigpath = os.path.join(get_main_dir(), 'config')
     filename = QtWidgets.QFileDialog.getSaveFileName(
         self._mw,
         'Save Configration',
         defaultconfigpath,
         'Configuration files (*.cfg)')[0]
     if filename != '':
         self.sigSaveConfig.emit(filename)
Beispiel #15
0
    def __init__(self, config, **kwargs):
        super().__init__(config=config, **kwargs)

        self.log.debug('The following configuration was found.')

        # checking for the right configuration
        for key in config.keys():
            self.log.info('{0}: {1}'.format(key, config[key]))

        if self.trace_path is None:
            self.trace_path = os.path.join(get_main_dir(), 'tools',
                                           'FastComTec_demo_timetrace.asc')
Beispiel #16
0
    def getSoftwareVersion(self):
        """ Try to determine the software version in case the program is in
            a git repository.
        """
        try:
            repo = Repo(get_main_dir())
            branch = repo.active_branch
            rev = str(repo.head.commit)
            return (rev, str(branch))

        except Exception as e:
            print('Could not get git repo because:', e)
            return ('unknown', -1)
    def getSoftwareVersion(self):
        """ Try to determine the software version in case the program is in
            a git repository.
        """
        try:
            repo = Repo(get_main_dir())
            branch = repo.active_branch
            rev = str(repo.head.commit)
            return rev, str(branch)

        except Exception as e:
            print('Could not get git repo because:', e)
            return 'unknown', -1
Beispiel #18
0
 def on_activate(self):
     self.fp = ok.FrontPanel()
     self.fp.GetDeviceCount()
     self.fp.OpenBySerial(self.fp.GetDeviceListSerial(0))
     self.fp.ConfigureFPGA(
         os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                      'switch_top.bit'))
     if not self.fp.IsFrontPanelEnabled():
         self.log.error('FrontPanel is not enabled in FPGA switch!')
         return
     else:
         self.reset()
         self.log.info('FPGA connected')
Beispiel #19
0
    def __init__(self, config, **kwargs):
        super().__init__(config=config, **kwargs)

        self.log.debug('The following configuration was found.')

        # checking for the right configuration
        for key in config.keys():
            self.log.info('{0}: {1}'.format(key,config[key]))

        if self.trace_path is None:
            self.trace_path = os.path.join(
                get_main_dir(),
                'tools',
                'FastComTec_demo_timetrace.asc')
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to determine also how
        # many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error(
                'No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper fast counter configuration bitfile to the FPGA
        bitfile_name = 'fastcounter_' + self._fpga_type + '.bit'
        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(
            os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                         bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is
        # enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA.\n'
                           'Upload of bitfile failed.')
            self.statusvar = -1
            return -1

        # Wait until all power-up initialization processes on the FPGA have finished
        timeout = 5
        start_time = time.time()
        while True:
            if time.time() - start_time >= timeout:
                self.log.error(
                    'Power-on initialization of FPGA-timetagger timed out. '
                    'Device non-functional.')
                self.statusvar = -1
                break
            status_messages = self._get_status_messages()
            if len(status_messages) == 2 and (
                    'idle_ready' in status_messages) and ('TDC_in_reset'
                                                          in status_messages):
                self.log.info(
                    'Power-on initialization of FPGA-timetagger complete.')
                self.statusvar = 0
                break
            time.sleep(0.2)
        return self.statusvar
 def getLoadFile(self):
     """ Ask the user for a file where the configuration should be loaded
         from
     """
     defaultconfigpath = os.path.join(get_main_dir(), 'config')
     filename = QtWidgets.QFileDialog.getOpenFileName(
         self._mw, 'Load Configration', defaultconfigpath,
         'Configuration files (*.cfg)')[0]
     if filename != '':
         reply = QtWidgets.QMessageBox.question(
             self._mw, 'Restart',
             'Do you want to restart to use the configuration?',
             QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
         restart = (reply == QtWidgets.QMessageBox.Yes)
         self.sigLoadConfig.emit(filename, restart)
    def on_activate(self):
        """ Connect and configure the access to the FPGA.
        """
        tt._Tagger_setSerial(self._fpgacounter_serial)
        thirdpartypath = os.path.join(get_main_dir(), 'thirdparty')
        bitfilepath = os.path.join(thirdpartypath, 'stuttgart_counter',
                                   'TimeTaggerController.bit')
        tt._Tagger_setBitfilePath(bitfilepath)
        del bitfilepath, thirdpartypath

        self._number_of_gates = int(100)
        self._bin_width = 1
        self._record_length = int(4000)

        self.configure(self._bin_width * 1e-9, self._record_length * 1e-9,
                       self._number_of_gates)

        self.statusvar = 0
Beispiel #23
0
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to determine also how
        # many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error('No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper fast counter configuration bitfile to the FPGA
        bitfile_name = 'fastcounter_' + self._fpga_type + '.bit'
        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                                              bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is
        # enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA.\n'
                           'Upload of bitfile failed.')
            self.statusvar = -1
            return -1

        # Wait until all power-up initialization processes on the FPGA have finished
        timeout = 5
        start_time = time.time()
        while True:
            if time.time()-start_time >= timeout:
                self.log.error('Power-on initialization of FPGA-timetagger timed out. '
                               'Device non-functional.')
                self.statusvar = -1
                break
            status_messages = self._get_status_messages()
            if len(status_messages) == 2 and ('idle_ready' in status_messages) and (
                'TDC_in_reset' in status_messages):
                self.log.info('Power-on initialization of FPGA-timetagger complete.')
                self.statusvar = 0
                break
            time.sleep(0.2)
        return self.statusvar
Beispiel #24
0
    def on_activate(self):
        """ Connect and configure the access to the FPGA.
        """
        tt._Tagger_setSerial(self._fpgacounter_serial)
        thirdpartypath = os.path.join(get_main_dir(), 'thirdparty')
        bitfilepath = os.path.join(thirdpartypath, 'stuttgart_counter', 'TimeTaggerController.bit')
        tt._Tagger_setBitfilePath(bitfilepath)
        del bitfilepath, thirdpartypath

        self._number_of_gates = int(100)
        self._bin_width = 1
        self._record_length = int(4000)

        self.configure(
            self._bin_width * 1e-9,
            self._record_length * 1e-9,
            self._number_of_gates)

        self.statusvar = 0
Beispiel #25
0
    def __init__(self, pulsedmeasurementlogic):
        # Init base class
        super().__init__(pulsedmeasurementlogic)

        # Dictionary holding references to all analysis methods
        self._analysis_methods = dict()
        # dictionary containing all possible parameters that can be used by the analysis methods
        self._parameters = dict()
        # Currently selected analysis method
        self._current_analysis_method = None

        # import path for analysis modules from default directory (logic.pulse_analysis_methods)
        path_list = [os.path.join(get_main_dir(), 'logic', 'pulsed', 'pulsed_analysis_methods')]
        # import path for analysis modules from non-default directory if a path has been given
        if isinstance(pulsedmeasurementlogic.analysis_import_path, str):
            path_list.append(pulsedmeasurementlogic.analysis_import_path)

        # Import analysis modules and get a list of analyzer classes
        analyzer_classes = self.__import_external_analyzers(paths=path_list)

        # create an instance of each class and put them in a temporary list
        analyzer_instances = [cls(pulsedmeasurementlogic) for cls in analyzer_classes]

        # add references to all analysis methods in each instance to a dict
        self.__populate_method_dict(instance_list=analyzer_instances)

        # populate "_parameters" dictionary from analysis method signatures
        self.__populate_parameter_dict()

        # Set default analysis method
        self._current_analysis_method = natural_sort(self._analysis_methods)[0]

        # Update from parameter_dict if handed over
        if isinstance(pulsedmeasurementlogic.analysis_parameters, dict):
            # Delete unused parameters
            params = [p for p in pulsedmeasurementlogic.analysis_parameters if
                      p not in self._parameters and p != 'method']
            for param in params:
                del pulsedmeasurementlogic.analysis_parameters[param]
            # Update parameter dict and current method
            self.analysis_settings = pulsedmeasurementlogic.analysis_parameters
        return
Beispiel #26
0
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to
        # determine also how many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error(
                'No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper hardware switch configuration bitfile to the FPGA
        if self._fpga_type == 'XEM6310_LX45':
            bitfile_name = 'switch_8chnl_withcopy_LX45.bit'
        elif self._fpga_type == 'XEM6310_LX150':
            bitfile_name = 'switch_8chnl_withcopy_LX150.bit'
        else:
            self.log.error(
                'Unsupported FPGA type "{0}" specified in config. Valid options are '
                '"XEM6310_LX45" and "XEM6310_LX150".\nConnection to FPGA module failed.'
                ''.format(self._fpga_type))
            return -1

        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(
            os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                         bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA')
            return -1

        self._fpga.SetWireInValue(0x00, 0x00000000)
        self._fpga.UpdateWireIns()

        self._switch_status = {chnl: False for chnl in range(8)}
        self._connected = True
        return 0
Beispiel #27
0
 def getLoadFile(self):
     """ Ask the user for a file where the configuration should be loaded
         from
     """
     defaultconfigpath = os.path.join(get_main_dir(), 'config')
     filename = QtWidgets.QFileDialog.getOpenFileName(
         self._mw,
         'Load Configration',
         defaultconfigpath,
         'Configuration files (*.cfg)')[0]
     if filename != '':
         reply = QtWidgets.QMessageBox.question(
             self._mw,
             'Restart',
             'Do you want to restart to use the configuration?',
             QtWidgets.QMessageBox.Yes,
             QtWidgets.QMessageBox.No
         )
         restart = (reply == QtWidgets.QMessageBox.Yes)
         self.sigLoadConfig.emit(filename, restart)
Beispiel #28
0
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to
        # determine also how many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error(
                'No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper hardware switch configuration bitfile to the FPGA
        bitfile_name = 'switch_8chnl_withcopy_LX150.bit'
        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(
            os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                         bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA')
            return -1
        else:
            self._fpga.SetWireInValue(0x00, 0x00000000)
            self._fpga.UpdateWireIns()

        self._switch_status = {
            0: False,
            1: False,
            2: False,
            3: False,
            4: False,
            5: False,
            6: False,
            7: False
        }
        self._connected = True
        return 0
Beispiel #29
0
    def _connect(self):
        """
        Connect host PC to FPGA module with the specified serial number.
        """
        # check if a FPGA is connected to this host PC. That method is used to
        # determine also how many devices are available.
        if not self._fpga.GetDeviceCount():
            self.log.error('No FPGA connected to host PC or FrontPanel.exe is running.')
            return -1

        # open a connection to the FPGA with the specified serial number
        self._fpga.OpenBySerial(self._serial)

        # upload the proper hardware switch configuration bitfile to the FPGA
        if self._fpga_type == 'XEM6310_LX45':
            bitfile_name = 'switch_8chnl_withcopy_LX45.bit'
        elif self._fpga_type == 'XEM6310_LX150':
            bitfile_name = 'switch_8chnl_withcopy_LX150.bit'
        else:
            self.log.error('Unsupported FPGA type "{0}" specified in config. Valid options are '
                           '"XEM6310_LX45" and "XEM6310_LX150".\nConnection to FPGA module failed.'
                           ''.format(self._fpga_type))
            return -1

        # Load on the FPGA a configuration file (bit file).
        self._fpga.ConfigureFPGA(os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga',
                                              bitfile_name))

        # Check if the upload was successful and the Opal Kelly FrontPanel is enabled on the FPGA
        if not self._fpga.IsFrontPanelEnabled():
            self.log.error('Opal Kelly FrontPanel is not enabled in FPGA')
            return -1

        self._fpga.SetWireInValue(0x00, 0x00000000)
        self._fpga.UpdateWireIns()

        self._switch_status = {chnl: False for chnl in range(8)}
        self._connected = True
        return 0
Beispiel #30
0
    def set_sample_rate(self, sample_rate):
        """ Set the sample rate of the pulse generator hardware.

        @param float sample_rate: The sampling rate to be set (in Hz)

        @return float: the sample rate returned from the device (in Hz).

        Note: After setting the sampling rate of the device, use the actually set return value for
              further processing.
        """
        # Round sample rate either to 500MHz or 950MHz since no other values are possible.
        if sample_rate < 725e6:
            self.__sample_rate = 500e6
            bitfile_name = 'pulsegen_8chnl_500MHz_{0}.bit'.format(self._fpga_type.split('_')[1])
        else:
            self.__sample_rate = 950e6
            bitfile_name = 'pulsegen_8chnl_950MHz_{0}.bit'.format(self._fpga_type.split('_')[1])

        bitfile_path = os.path.join(get_main_dir(), 'thirdparty', 'qo_fpga', bitfile_name)

        self.fpga.ConfigureFPGA(bitfile_path)
        self.log.debug('FPGA pulse generator configured with {0}'.format(bitfile_path))
        return self.__sample_rate
Beispiel #31
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # locking for thread safety
        self.lock = Mutex()

        filenames = []
        # for path in directories:
        path = join(get_main_dir(), 'logic', 'fitmethods')
        for f in listdir(path):
            if isfile(join(path, f)):
                if f[-3:] == '.py':
                    filenames.append(f[:-3])

        # A dictionary containing all fit methods and their estimators.
        self.fit_list = OrderedDict()
        self.fit_list['1d'] = OrderedDict()
        self.fit_list['2d'] = OrderedDict()
        self.fit_list['3d'] = OrderedDict()

        # Go through the fitmethods files and import all methods.
        # Also determine which methods need to be added to the fit_list dictionary
        estimators_for_dict = list()
        models_for_dict = list()
        fits_for_dict = list()

        for files in filenames:

            mod = importlib.import_module('logic.fitmethods.{0}'.format(files))

            for method in dir(mod):
                ref = getattr(mod, method)
                if callable(ref) and (inspect.ismethod(ref) or inspect.isfunction(ref)):
                    method_str = str(method)
                    try:
                        # import methods in Fitlogic
                        setattr(FitLogic, method, ref)
                        # append method to a list of methods to include in the fit_list dictionary
                        if method_str.startswith('make_') and method_str.endswith('_fit'):
                            fits_for_dict.append(method_str.split('_', 1)[1].rsplit('_', 1)[0])
                        elif method_str.startswith('make_') and method_str.endswith('_model'):
                            models_for_dict.append(method_str.split('_', 1)[1].rsplit('_', 1)[0])
                        elif method_str.startswith('estimate_'):
                            estimators_for_dict.append(method_str.split('_', 1)[1])
                    except:
                        self.log.error('Method "{0}" could not be imported to FitLogic.'
                                       ''.format(str(method)))

        fits_for_dict.sort()
        models_for_dict.sort()
        estimators_for_dict.sort()
        # Now attach the fit, model and estimator methods to the proper dictionary fields
        for fit_name in fits_for_dict:
            fit_method = 'make_' + fit_name + '_fit'
            model_method = 'make_' + fit_name + '_model'

            # Determine fit dimension
            if 'twoD' in fit_name:
                dimension = '2d'
            elif 'threeD' in fit_name:
                dimension = '3d'
            else:
                dimension = '1d'

            # Attach make_*_fit method to fit_list
            if fit_name not in self.fit_list[dimension]:
                self.fit_list[dimension][fit_name] = OrderedDict()
            self.fit_list[dimension][fit_name]['make_fit'] = getattr(self, fit_method)

            # Attach make_*_model method to fit_list
            if fit_name in models_for_dict:
                self.fit_list[dimension][fit_name]['make_model'] = getattr(self, model_method)
            else:
                self.log.error('No make_*_model method for fit "{0}" found in FitLogic.'
                               ''.format(fit_name))

            # Attach all estimate_* methods to corresponding fit method in fit_list
            found_estimator = False
            for estimator_name in estimators_for_dict:
                estimator_method = 'estimate_' + estimator_name
                if fit_name == estimator_name:
                    self.fit_list[dimension][fit_name]['generic'] = getattr(self, estimator_method)
                    found_estimator = True
                elif estimator_name.startswith(fit_name + '_'):
                    custom_name = estimator_name.split('_', 1)[1]
                    self.fit_list[dimension][fit_name][custom_name] = getattr(self, estimator_method)
                    found_estimator = True
            if not found_estimator:
                self.log.error('No estimator method for fit "{0}" found in FitLogic.'
                               ''.format(fit_name))

        self.log.info('Methods were included to FitLogic, but only if naming is right: check the'
                         ' doxygen documentation if you added a new method and it does not show.')
Beispiel #32
0
 def get_data_testfile(self):
     """ Load data test file """
     data = np.loadtxt(os.path.join(get_main_dir(), 'tools', 'FastComTec_demo_timetrace.asc'))
     time.sleep(0.5)
     return data