Example #1
0
    def option_change_log_level(self):
        """change the file logging.conf's logging level"""

        log_level = str(self.sender().text())

        IOTool.set_config_setting("level", log_level,
                                  os.path.join(ABS_PATH, "logging.conf"))

        logging.config.fileConfig(os.path.join(ABS_PATH, "logging.conf"))
Example #2
0
    def emit_axis_lim(self, mode, limits):
        """
            emits the limits of the selected axis on the highlighted plot
        """
        current_window = self.zoneCentrale.activeSubWindow()

        if current_window:
            current_widget = self.zoneCentrale.activeSubWindow().widget()

            # this is a small check that we are no trying to get the limits from
            # the wrong plot
            #            if current_widget.windowTitle() == "Past Data Window":
            try:
                paramX = current_widget.get_X_axis_index()
            except:
                paramX = 0
            try:
                paramY = current_widget.get_Y_axis_index()
            except:
                paramY = 1
            try:
                paramYfit = current_widget.get_fit_axis_index()
            except:
                paramYfit = 1
#                except:
#                    logging.info( "G2GUI.emit_axis_lim : the params are not defined, the default is X-> Channel 1 and Y->Channel 2")

#            else:
#                try:
#                    paramX = current_widget.get_X_axis_index()
#                    paramY = current_widget.get_Y_axis_index()
#                    paramYfit = current_widget.get_fit_axis_index()
#                except:
#                    logging.info("G2GUI.emit_axis_lim : the params are not defined, the default is X-> Channel 1 and Y->Channel 2")
#                    paramX = 0
#                    paramY = 1
#                    paramYfit = 1
#
            try:
                #                logging.warning("%i%i"%(paramX,paramY))
                x = current_widget.data_array[:, paramX]
                xmin = limits[0][0]
                xmax = limits[0][1]
                imin = IOTool.match_value2index(x, xmin)
                imax = IOTool.match_value2index(x, xmax)
                self.emit(
                    SIGNAL("selections_limits(PyQt_PyObject,int,int,int,int)"),
                    np.array([imin, imax, xmin, xmax]), paramX, paramY,
                    paramYfit, mode)
            except IndexError:
                logging.debug("There is apparently no data generated yet")
            except:
                logging.warning("There was an error with the limits")
Example #3
0
    def fit_func_changed(self):
        """
        when a new fit fonction is choosen, the fit parameters are 
        automatically adjusted
        """

        new_func_name = str(self.fitCombo.currentText())

        self.fit_func = io.import_module_func(self.fonctions_module,
                                              new_func_name,
                                              package=self.fonctions_pkg)

        self.fit_params["fit_func"] = new_func_name

        #if the user defined extra physical parameters needed once the fit
        #is performed, they will be defined in the dict PHYS_PARAMS
        if new_func_name in ad.PHYS_PARAMS:
            self.physparam_list = ad.PHYS_PARAMS[new_func_name]
        else:
            self.physparam_list = []

        #update the layout according to the parameters
        self.remove_phys_layout()
        self.remove_fit_layout()

        self.create_fit_layout()
        self.create_phys_layout()
Example #4
0
    def __init__(self, lock, instr_hub, parent=None):
        print("DTT created")
        super(DataTaker, self).__init__(parent)

        self.instr_hub = instr_hub
        self.connect(self.instr_hub, SIGNAL("changed_list()"),
                     self.reset_lists)
        self.lock = lock
        self.stopped = True
        self.paused = False
        self.mutex = QMutex()

        self.completed = False
        self.DEBUG = IOTool.get_debug_setting()

        #the script which is run everytime the user call the routine "run"
        self.script_file_name = ''

        #a dict that can be populated by variable the user would like to change
        #in real time while the script is ran
        self.user_variables = {}

        self.t_start = None
        # scriptize the intruments and their parameters
        self.reset_lists()
Example #5
0
 def load_data_set(self, fname): #(only in this one)
     if not fname == None:
         extension = fname.rsplit('.')[len(fname.rsplit('.')) - 1]
         if extension == "adat":
             [data, labels] = io.load_file_windows(fname, '\t')
         elif extension == "adat2":
             [data, labels] = io.load_file_windows(fname)
         elif extension == "a5dat":
             data, param = load_experiment(fname)
             data = np.transpose(np.array(data))
             labels = {}
             labels["param"] = ["Vc", "T", "P"]
         else:
             [data, labels] = io.load_file_windows(fname)
 #        print "load data set "+fname
         new_data_set = DataSet(data, labels)
         self.change_data_set(new_data_set)
Example #6
0
    def load_data_subsets(self, fname):
        extension = fname.rsplit('.')[len(fname.rsplit('.')) - 1]
        if extension == "aset":
            [data, labels] = io.load_aset_file(fname)
        else:
            print("analyse_data.load_data_subsets: wrong extensionfor the file ", fname, ", should be '.aset' but it is '", extension, "'")
#        print "load data set "+fname
        new_data_set = data_set(data, labels)
        self.change_data_set(new_data_set)
Example #7
0
    def option_change_debug_state(self):
        """Togggle the debug state"""

        if self.DEBUG:
            self.option_display_normal_state()
            self.DEBUG = False

        else:
            self.option_display_debug_state()
            self.DEBUG = True

        #if DEBUG is false, the port list needs to be fetched
        self.refresh_ports_list()

        IOTool.set_config_setting(IOTool.DEBUG_ID,
                                  self.DEBUG,
                                  config_file_path=self.config_file)

        self.emit(SIGNAL("DEBUG_mode_changed(bool)"), self.DEBUG)
Example #8
0
    def file_load_data(self):
        default_path = IOTool.get_config_setting(
            "DATAFILE", config_file_path=self.config_file)

        if not default_path:

            default_path = './'

        fname = str(
            QtGui.QFileDialog.getOpenFileName(self, 'Open settings file',
                                              default_path))

        if fname:

            self.create_plw(fname)
Example #9
0
    def manage_fix_value_fit_params(self):
        """
        this methods goes through the list of parameters and see whether
        they are fixed or not, then generate a fonction with only the 
        non fixed parameters that can be varied by the fitting procedure
        """
        at_least_one_param_fixed = False

        #prepare the list of argument of ad.restrict_function_parameters
        fit_func_var = []
        for fp in self.fit_params["fix_param"]:

            #if the fit param is set to fixed == True
            if self.fit_params["fix_param"][fp]:

                at_least_one_param_fixed = True

                #retrieve the value of the text_box with that parameter name
                fitp_fixed_value = self.get_lineedit_value(fp)

                #modify the value list to create a fonction with this
                #parameter fixed
                fit_func_var.append(fitp_fixed_value)

                #assigns the value to the fixed fit param
                self.fit_params["fit_func_params"][fp] = fitp_fixed_value

            else:

                #prepare the value list to create a fonction with this
                #parameter value to be varied to find the best fit
                fit_func_var.append(None)

        original_func = io.import_module_func(self.fonctions_module,
                                              str(self.fit_params["fit_func"]),
                                              package=self.fonctions_pkg)

        if at_least_one_param_fixed:
            #modifing the fit function by fixing some of its variables
            self.fit_func = ad.restrict_function_parameters(
                original_func, fit_func_var)

        else:

            self.fit_func = original_func
Example #10
0
    def __init__(self, lock, instr_hub, parent=None):
        print("DTT created")
        super(DataTaker, self).__init__(parent)

        self.instr_hub = instr_hub
        self.connect(self.instr_hub, SIGNAL("changed_list()"),
                     self.reset_lists)
        self.lock = lock
        self.stopped = True
        self.paused = False
        self.mutex = QMutex()

        self.completed = False
        self.DEBUG = IOTool.get_debug_setting()

        self.script_file_name = ''
        self.t_start = None
        # initialize the intruments and their parameters
        self.reset_lists()
Example #11
0
    def __init__(self, parent=None):
        super(ScriptWidget, self).__init__(parent)

        self.scriptLayout = QHBoxLayout()

        self.scriptFileLabel = QLabel(self)
        self.scriptFileLabel.setText("Script to run:")
        self.scriptFileLineEdit = QLineEdit(self)
        self.scriptFileButton = QPushButton(self)
        self.scriptFileButton.setText("Browse")
        self.scriptLayout.addWidget(self.scriptFileLabel)
        self.scriptLayout.addWidget(self.scriptFileLineEdit)
        self.scriptLayout.addWidget(self.scriptFileButton)

        self.setLayout(self.scriptLayout)

        self.scriptFileLineEdit.setText(IOTool.get_script_name())

        self.scriptFileButton.clicked.connect(self.on_scriptFileButton_clicked)
Example #12
0
    def __init__(self, parent=None, fname=IOTool.get_file_name()):
        super(OutputFileWidget, self).__init__(parent)

        # main layout of the form is the verticallayout

        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")

        #moved the script stuff to a separate widget that lives in the toolbar

        self.outputLayout = QtGui.QHBoxLayout()
        self.outputLayout.setObjectName("outputLayout")
        self.outputFileLabel = QtGui.QLabel(self)
        self.outputFileLabel.setText("Output File:")
        self.outputFileLineEdit = QtGui.QLineEdit(self)
        self.outputFileButton = QtGui.QPushButton(self)
        self.outputFileButton.setText("Browse")
        self.outputLayout.addWidget(self.outputFileLabel)
        self.outputLayout.addWidget(self.outputFileLineEdit)
        self.outputLayout.addWidget(self.outputFileButton)
        self.verticalLayout.addLayout(self.outputLayout)

        self.headerTextEdit = QtGui.QPlainTextEdit("")
        fontsize = self.headerTextEdit.fontMetrics()
        self.headerTextEdit.setFixedHeight(fontsize.lineSpacing() * 8)
        self.verticalLayout.addWidget(self.headerTextEdit)

        # moved the start stop button to the toolbar only

        self.setLayout(self.verticalLayout)

        self.outputFileLineEdit.setText(fname)

        self.connect(self.outputFileButton, SIGNAL('clicked()'),
                     self.on_outputFileButton_clicked)

        self.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum,
                              QtGui.QSizePolicy.Maximum))
Example #13
0
def add_widget_into_main(parent):
    """add a widget into the main window of LabGuiMain
    
    create a QDock widget and store a reference to the widget
    """

    ofname = IOTool.get_file_name(config_file_path=parent.config_file)

    mywidget = OutputFileWidget(parent=parent, fname=ofname)

    outDockWidget = QtGui.QDockWidget("Output file and header text", parent)
    outDockWidget.setObjectName("OutputFileDockWidget")
    outDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea
                                  | Qt.RightDockWidgetArea)

    #fill the dictionnary with the widgets added into LabGuiMain
    parent.widgets['OutputFileWidget'] = mywidget

    outDockWidget.setWidget(mywidget)
    parent.addDockWidget(Qt.RightDockWidgetArea, outDockWidget)

    #Enable the toggle view action
    parent.windowMenu.addAction(outDockWidget.toggleViewAction())
Example #14
0
    def __init__(self, parent=None):
        super(ScriptWidget, self).__init__(parent)

        self.scriptLayout = QHBoxLayout()

        self.scriptFileLabel = QLabel(self)
        self.scriptFileLabel.setText("Script to run:")
        self.scriptFileLineEdit = QLineEdit(self)
        self.scriptFileButton = QPushButton(self)
        self.scriptFileButton.setText("Browse")
        self.scriptLayout.addWidget(self.scriptFileLabel)
        self.scriptLayout.addWidget(self.scriptFileLineEdit)
        self.scriptLayout.addWidget(self.scriptFileButton)

        self.setLayout(self.scriptLayout)

        self.scriptFileLineEdit.setText(IOTool.get_script_name())

        # make the magic function names/decorators work!
        # self.retranslateUi(StartWidget)

        self.connect(self.scriptFileButton, SIGNAL('clicked()'),
                     self.on_scriptFileButton_clicked)
Example #15
0
    def file_save_config(self):
        """
        this function get the actual values of parameters and save them into the config file
        """
        script_fname = str(
            self.widgets['SciptWidget'].scriptFileLineEdit.text())
        IOTool.set_config_setting(IOTool.SCRIPT_ID, script_fname,
                                  self.config_file)

        output_path = os.path.dirname(
            self.widgets['OutputFileWidget'].get_output_fname()) + os.path.sep
        IOTool.set_config_setting(IOTool.SAVE_DATA_PATH_ID, output_path,
                                  self.config_file)

        if not self.instrument_connexion_setting_fname == "":
            IOTool.set_config_setting(IOTool.SETTINGS_ID,
                                      self.instrument_connexion_setting_fname,
                                      self.config_file)
Example #16
0
import os
import inspect

from importlib import import_module
import logging

import glob
import sys
import serial
import visa

from LabTools.IO import IOTool

INTF_VISA = 'pyvisa'
INTF_PROLOGIX = 'prologix'
INTF_GPIB = IOTool.get_interface_setting()
INTF_SERIAL = 'serial'

INTF_NONE = 'None'

PROLOGIX_COM_PORT = "COM5"

LABDRIVER_PACKAGE_NAME = "LabDrivers"

old_visa = True

try:
    #poke at something that only exists in older versions of visa, as a probe for the version
    visa.term_chars_end_input
    logging.info("using pyvisa version less than 1.6")
except:
Example #17
0
def create_plw(parent, load_fname = None):
    """
        add a new plot load window in the MDI area. The data and channels 
        are loaded from a file
    """
    # maintain the previous functionality if file name not passed in
    if not load_fname:
        load_fname = str(parent.widgets["loadPlotWidget"].load_file_name())
        
    logging.info("loading %s for plot"%(load_fname))

    extension = load_fname.rsplit('.')[len(load_fname.rsplit('.')) - 1]
#        print extension

    if extension == "ldat":
        lb_data = LabeledData(fname = load_fname)
        data = lb_data.data
        labels = {}
        labels["param"] = lb_data.labels
    else:
        [data, labels] = IOTool.load_file_windows(load_fname)
        #add the header to the header text area
        parent.widgets["loadPlotWidget"].header_text(labels['hdr'])
                
        #update the name information in the widget
        parent.widgets["loadPlotWidget"].load_file_name(load_fname)          
                
        #store the hdr is there is more than one file
        parent.loaded_data_header[load_fname] = labels['hdr']

    chan_contr = OrderedDict()
    chan_contr["groupBox_Name"] = ["Channel", "lineEdit"]
    chan_contr["groupBox_X"] = ["X", "radioButton"]
    chan_contr["groupBox_Y"] = ["YL", "checkBox"]
    chan_contr["groupBox_YR"] = ["YR", "checkBox"]
    chan_contr["groupBox_fit"] = ["fit", "radioButton"]
    chan_contr["groupBox_invert"] = ["+/-", "checkBox"]
    chan_contr["groupBox_marker"] = ["M", "comboBox"]
    chan_contr["groupBox_line"] = ["L", "comboBox"]

    logging.info("channel names are ", labels)
#        print data
    nb_channels = np.size(data, 1)
    logging.info("%i channels in total"% (nb_channels))
    plw = PlotDisplayWindow.PlotDisplayWindow(
        data_array = data, 
        name = PlotDisplayWindow.PLOT_WINDOW_TITLE_PAST + load_fname, 
        window_type = PlotDisplayWindow.PLOT_WINDOW_TYPE_PAST,
        default_channels = nb_channels, 
        channel_controls = chan_contr)
    
    
    parent.connect(plw.mplwidget, SIGNAL(
        "limits_changed(int,PyQt_PyObject)"), parent.emit_axis_lim)
        
    parent.connect(parent.widgets['AnalyseDataWidget'], SIGNAL(
        "data_set_updated(PyQt_PyObject)"), plw.update_plot)
        
    parent.connect(parent.widgets['AnalyseDataWidget'], SIGNAL(
        "update_fit(PyQt_PyObject)"), plw.update_fit)
        
    parent.connect(parent, SIGNAL("remove_fit()"), plw.remove_fit)

    try:
        for i, param in enumerate(labels['channel_labels']):
            plw.lineEdit_Name[i].setText(param)
    except:
        pass
    
    try:
        plw.set_axis_ticks(IOTool.load_pset_file(load_fname, labels['param']))
    except:
        pass

#        self.dataAnalyseWidget.refresh_active_set()
    
    plw.update_labels(labels['channel_labels'])
    parent.widgets['AnalyseDataWidget'].update_data_and_fit(data)
#        plw.update_plot(data)
    parent.zoneCentrale.addSubWindow(plw)
    plw.show()
Example #18
0
    def create_fit_layout(self, fparam_list=None):
        """
           The parameters that will be displayed depend on the function to fit, they are automatically extracted from the functions described in the module Fitting
        """
        self.state
        logging.debug("Just called fit Layout")

        if fparam_list == None:
            fparam_list = io.get_func_variables(self.fit_func)
            # the first variable is the x axis coordinate, is it not a fit
            # parameter
            fparam_list = fparam_list[1:]

        #store them for later use
        self.fit_func_variables = fparam_list

        #This is to choose whether one wants to pass the fit parameter
        #as a guess parameter or to fix one or more fit parameters
        fit_func_params = OrderedDict()
        fit_func_guess = OrderedDict()
        fit_func_fix_param = OrderedDict()

        for fp in self.fit_func_variables:

            #this should store the value of the fit param after the fit
            fit_func_params[fp] = None
            #if None, it will not be passed as a guess argument
            fit_func_guess[fp] = None
            #if False it is not fixed, if True it is fixed
            fit_func_fix_param[fp] = False

        #store this information for later use
        self.fit_params["fit_func_params"] = fit_func_params
        self.fit_params["guess"] = fit_func_guess
        self.fit_params["fix_param"] = fit_func_fix_param

        self.fitLayout = QtGui.QVBoxLayout()
        self.fitLayout.setObjectName("fitLayout")
        self.fit_param_labelLayout = QtGui.QHBoxLayout()
        self.fit_paramLayout = QtGui.QHBoxLayout()

        for fparam in fparam_list:
            aLabel = QtGui.QLabel(self)
            aLabel.setText(fparam)
            self.fit_param_labelLayout.addWidget(aLabel,
                                                 alignment=Qt.AlignCenter)

            self.aCheckBox = QtGui.QCheckBox(self)
            self.aCheckBox.setObjectName("ch_%s" % (fparam))
            self.connect(self.aCheckBox, QtCore.SIGNAL('clicked()'),
                         self.checkbox_handler)
            self.fit_paramLayout.addWidget(self.aCheckBox)

            self.aValue = QtGui.QLineEdit(self)
            self.aValue.setObjectName("le_%s" % (fparam))
            self.connect(self.aValue, QtCore.SIGNAL("editingFinished()"),
                         self.lineedit_handler)

            self.fit_paramLayout.addWidget(self.aValue)


#
        aLabel = QtGui.QLabel(self)
        aLabel.setText(u"Fit Parameters for %s" % (self.fit_func.__doc__))

        self.fitLayout.addWidget(aLabel, alignment=Qt.AlignCenter)
        self.fitLayout.addLayout(self.fit_param_labelLayout)
        self.fitLayout.addLayout(self.fit_paramLayout)

        self.verticalLayout.addLayout(self.fitLayout)
        self.setLayout(self.verticalLayout)

        #enable/disable the widget in the layout
        toggle_layout(self.fitLayout, self.state)
        toggle_layout(self.fit_paramLayout, self.state)
        toggle_layout(self.fit_param_labelLayout, self.state)
Example #19
0
    def __init__(self, argv=[]):

        # run the initializer of the class inherited from6
        super(LabGuiMain, self).__init__()

        self.settings = QSettings(self)
        self.settings.setValue("state", self.saveState())

        #debug parameter used to run labgui even when there is no instrument
        #to connect to, used to plot past data or test the code
        self.DEBUG = True

        #variable to store the configfile name
        self.config_file = ''

        #parse the argument(s) passed inline
        try:
            #option c is to provide a name for config file
            opts, args = getopt.getopt(argv, "c:")

            #loop through the arguments on the inline command
            for opt, arg in opts:

                #user passed configfile
                if opt == '-c':

                    self.config_file = arg

        except getopt.GetoptError:

            logging.error('configuration file : option -c argument missing')

        #verify if the config file passed by the user is valid and exists
        if self.config_file:

            if not exists(self.config_file):

                logging.error("The config file you provided ('%s') doesn't \
exist, '%s' will be used instead" % (self.config_file, CONFIG_FILE))

                self.config_file = CONFIG_FILE

        else:

            #check whether the default config file exists or not
            if exists(CONFIG_FILE) == False:

                logging.warning("A '%s' file has been generated for you." %
                                (CONFIG_FILE))
                logging.warning("Please modify it to change the default \
    script, settings and data locations, or to enter debug mode.")

                # creates a config.txt with basic needs
                IOTool.create_config_file()

            #sets default config file name
            self.config_file = CONFIG_FILE

        #to make sure the config file is of the right format
        #ie that the user didn't specify the name of an existing file which
        #isn't a configuration file
        config_file_ok = False

        while not config_file_ok:

            try:
                #try to read the DEBUG parameter from the configuration file
                #as a test of the good formatting of the file
                self.DEBUG = IOTool.get_debug_setting(
                    config_file_path=self.config_file)

                #if this didn't generate errors we allow to get out of the loop
                config_file_ok = True

            except IOError:

                logging.error("The config file you provided ('%s') doesn't \
have the right format, '%s' will be used instead" %
                              (self.config_file, CONFIG_FILE))

                #check whether the default config file exists or not
                if exists(CONFIG_FILE) == False:

                    logging.warning("A '%s' file has been generated for you." %
                                    (CONFIG_FILE))
                    logging.warning("Please modify it to change the default \
    script, settings and data locations, or to enter debug mode.")

                    # creates a config.txt with basic needs
                    IOTool.create_config_file()

                #sets default config file name
                self.config_file = CONFIG_FILE

        print("Configuration loaded from : %s" % (self.config_file))

        if self.DEBUG == True:

            print("*" * 20)
            print("Debug mode is set to True")
            print("*" * 20)

            self.option_display_debug_state()

        else:

            self.option_display_normal_state()

        #create the central part of the application
        self.zoneCentrale = QtGui.QMdiArea()
        self.zoneCentrale.subWindowActivated.connect(
            self.update_current_window)
        self.setCentralWidget(self.zoneCentrale)

        #load the parameter for the GPIB interface setting of the instruments
        interface = IOTool.get_interface_setting(
            config_file_path=self.config_file)

        #test if the parameter is correct
        if interface not in [Tool.INTF_VISA, Tool.INTF_PROLOGIX]:

            msg = """The %s variable of the config file '%s' is not correct
            The only two allowed values are : '%s' and '%s' """ % (
                IOTool.GPIB_INTF_ID, IOTool.CONFIG_FILE, Tool.INTF_VISA,
                Tool.INTF_PROLOGIX)
            logging.warning(msg)
            #default setting
            Tool.INTF_GPIB = Tool.INTF_PROLOGIX

        else:

            Tool.INTF_GPIB = interface

        print("*" * 20)
        print("The GPIB setting for connecting instruments is %s" %
              (Tool.INTF_GPIB))
        print("*" * 20)

        # the lock is something for multithreading... not sure if it's important in our application.
        self.lock = QReadWriteLock()

        # InstrumentHub is responsible for storing and managing the user
        # choices about which instrument goes on which port
        self.instr_hub = Tool.InstrumentHub(parent=self, debug=self.DEBUG)

        # DataTaker is responsible for taking data from instruments in the
        # InstrumentHub object
        self.datataker = DataManagement.DataTaker(self.lock, self.instr_hub)

        # handle data emitted by datataker (basically stuff it into a shared,
        # central array)
        self.connect(self.datataker, SIGNAL("data(PyQt_PyObject)"),
                     self.update_data_array)

        #a signal to signify the data taking script is over
        self.connect(self.datataker, SIGNAL("script_finished(bool)"),
                     self.finished_DTT)

        #the array in which the data will be stored
        self.data_array = np.array([])

        # all actions related to the figure widget (mplZoomWidget.py) are
        # set up in the actionmanager
        self.action_manager = mplZoomWidget.ActionManager(self)

        #this will contain the widget of the latest pdw created upon
        #connecting the instrument Hub
        self.actual_pdw = None

        #this will contain windows settings (labels, checkboxes states, colors)
        #of the plotdisplaw window which is created when the user click on
        #the connect button
        self.plot_window_settings = None

        #### set up menus and toolbars

        self.fileMenu = self.menuBar().addMenu("File")
        self.plotMenu = self.menuBar().addMenu("&Plot")
        self.instMenu = self.menuBar().addMenu("&Meas/Connect")
        self.windowMenu = self.menuBar().addMenu("&Window")
        self.optionMenu = self.menuBar().addMenu("&Options")

        self.loggingSubMenu = self.optionMenu.addMenu("&Logger output level")

        self.plotToolbar = self.addToolBar("Plot")
        self.instToolbar = self.addToolBar("Instruments")

        # start/stop/pause buttons
        self.start_DTT_action = QtTools.create_action(
            self,
            "Start DTT",
            slot=self.start_DTT,
            shortcut=QtGui.QKeySequence("F5"),
            icon="start",
            tip="Start script")

        self.stop_DTT_action = QtTools.create_action(
            self,
            "Stop DTT",
            slot=self.stop_DTT,
            shortcut=QtGui.QKeySequence("F6"),
            icon="stop",
            tip="stop script")

        self.pause_DTT_action = QtTools.create_action(
            self,
            "Pause DTT",
            slot=self.pause_DTT,
            shortcut=QtGui.QKeySequence("F7"),
            icon="pause",
            tip="pause script")

        self.pause_DTT_action.setEnabled(False)
        self.stop_DTT_action.setEnabled(False)

        self.instToolbar.setObjectName("InstToolBar")

        self.instToolbar.addAction(self.start_DTT_action)
        self.instToolbar.addAction(self.pause_DTT_action)
        self.instToolbar.addAction(self.stop_DTT_action)

        #this will contain the different widgets in the window
        self.widgets = {}

        cur_path = os.path.dirname(__file__)

        #find the path to the widgets folders
        widget_path = os.path.join(cur_path, 'LabTools')

        #these are widgets essential to the interface
        core_widget_path = os.path.join(widget_path, 'CoreWidgets')

        #these are widgets which were added by users
        user_widget_path = os.path.join(widget_path, 'UserWidgets')

        #this is the legitimate list of core widgets
        widgets_list = [
            o.rstrip('.py') for o in os.listdir(core_widget_path)
            if o.endswith(".py") and not "__init__" in o
        ]

        #this is the legitimate list of user widgets
        user_widgets_list = [
            o.rstrip('.py') for o in os.listdir(user_widget_path)
            if o.endswith(".py") and not "__init__" in o
        ]

        #the user widgets the user would like to run, given in the config file
        user_widgets = IOTool.get_user_widgets(
            config_file_path=self.config_file)

        if user_widgets:

            for user_widget in user_widgets:
                #check that the given widget is legitimate
                if user_widget in user_widgets_list:
                    #add the given widget to the widget list which will be
                    #loaded
                    widgets_list.append(user_widget)

                else:

                    logging.warning("The user widget '%s' is not found at %s" %
                                    (user_widget, user_widget_path))

        #add the widgets to the interface
        for widget in widgets_list:

            widget_name = widget
            try:
                widget_module = import_module("." + widget_name,
                                              package=COREWIDGETS_PACKAGE_NAME)
            except ImportError:

                widget_module = import_module("." + widget_name,
                                              package=USERWIDGETS_PACKAGE_NAME)

            self.add_widget(widget_module.add_widget_into_main)

###### FILE MENU SETUP ######

        self.fileSaveSettingsAction = QtTools.create_action(
            self,
            "Save Instrument Settings",
            slot=self.file_save_settings,
            shortcut=QtGui.QKeySequence.SaveAs,
            icon=None,
            tip="Save the current instrument settings")

        self.fileLoadSettingsAction = QtTools.create_action(
            self,
            "Load Instrument Settings",
            slot=self.file_load_settings,
            shortcut=QtGui.QKeySequence.Open,
            icon=None,
            tip="Load instrument settings from file")

        self.fileLoadDataAction = QtTools.create_action(
            self,
            "Load Previous Data",
            slot=self.file_load_data,
            shortcut=None,
            icon=None,
            tip="Load previous data from file")
        """this is not working I will leave it commented right now"""
        #        self.filePrintAction = QtTools.create_action(self, "&Print Report", slot=self.file_print, shortcut=QtGui.QKeySequence.Print,
        #                                                     icon=None, tip="Print the figure along with relevant information")

        self.fileSaveCongfigAction = QtTools.create_action(
            self,
            "Save current configuration",
            slot=self.file_save_config,
            shortcut=None,
            icon=None,
            tip="Save the setting file path, \
the script path and the data output path into the config file")

        self.fileMenu.addAction(self.fileLoadSettingsAction)
        self.fileMenu.addAction(self.fileSaveSettingsAction)
        self.fileMenu.addAction(self.fileLoadDataAction)
        #        self.fileMenu.addAction(self.filePrintAction)
        self.fileMenu.addAction(self.action_manager.saveFigAction)
        self.fileMenu.addAction(self.fileSaveCongfigAction)

        ###### PLOT MENU + TOOLBAR SETUP ######

        self.plotToolbar.setObjectName("PlotToolBar")

        for action in self.action_manager.actions:
            self.plotMenu.addAction(action)
            self.plotToolbar.addAction(action)

        self.clearPlotAction = QtTools.create_action(
            self,
            "Clear All Plots",
            slot=self.clear_plot,
            shortcut=None,
            icon="clear_plot",
            tip="Clears the live data arrays")

        self.removeFitAction = QtTools.create_action(
            self,
            "Remove Fit",
            slot=self.remove_fit,
            shortcut=None,
            icon="clear",
            tip="Reset the fit data to an empty array")

        self.plotMenu.addAction(self.clearPlotAction)
        self.plotMenu.addAction(self.removeFitAction)

        ###### INSTRUMENT MENU SETUP ######
        self.read_DTT = QtTools.create_action(
            self,
            "Read",
            slot=self.single_measure_DTT,
            shortcut=None,
            icon=None,
            tip="Take a one shot measure with DTT")

        self.connect_hub = QtTools.create_action(
            self,
            "Connect Instruments",
            slot=self.connect_instrument_hub,
            shortcut=QtGui.QKeySequence("Ctrl+I"),
            icon=None,
            tip="Refresh the list of selected instruments")

        self.refresh_ports_list_action = QtTools.create_action(
            self,
            "Refresh ports list",
            slot=self.refresh_ports_list,
            icon=None,
            tip="Refresh the list of availiable ports")

        self.instMenu.addAction(self.start_DTT_action)
        self.instMenu.addAction(self.read_DTT)
        self.instMenu.addAction(self.connect_hub)
        self.instMenu.addAction(self.refresh_ports_list_action)

        ###### WINDOW MENU SETUP ######
        self.add_pdw = QtTools.create_action(self,
                                             "Add a Plot",
                                             slot=self.create_pdw,
                                             shortcut=None,
                                             icon=None,
                                             tip="Add a recordsweep window")

        self.add_pqtw = QtTools.create_action(self,
                                              "Add a PyQtplot",
                                              slot=self.create_pqtw,
                                              shortcut=None,
                                              icon=None,
                                              tip="Add a pyqt window")

        self.windowMenu.addAction(self.add_pdw)

        try:

            import PyQTWindow
            self.windowMenu.addAction(self.add_pqtw)

        except:
            logging.info("pyqtgraph is unable to load, \
the pyqt window option is disabled")

###### OPTION MENU SETUP ######
        self.toggle_debug_state = QtTools.create_action(
            self,
            "Change debug mode",
            slot=self.option_change_debug_state,
            shortcut=None,
            icon=None,
            tip="Change the state of the debug mode")

        #        self.toggle_debug_state = QtTools.create_action(self,
        #        "Change debug mode", slot = self.option_change_debug_state,
        #        shortcut = None, icon = None,
        #        tip = "Change the state of the debug mode")

        self.optionMenu.addAction(self.toggle_debug_state)

        for log_level in ["DEBUG", "INFO", "WARNING", "ERROR"]:
            action = QtTools.create_action(
                self,
                log_level,
                slot=self.option_change_log_level,
                shortcut=None,
                icon=None,
                tip="Change the state of the logger to %s" % log_level)

            self.loggingSubMenu.addAction(action)

###############################

#Load the user settings for the instrument connectic and parameters

        self.default_settings_fname = IOTool.get_settings_name(
            config_file_path=self.config_file)

        if not exists(self.default_settings_fname):

            logging.warning(
                "The filename '%s' wasn't found, using '%s'" %
                (self.default_settings_fname, 'settings/default_settings.txt'))

            self.default_settings_fname = 'settings/default_settings.txt'

        if os.path.isfile(self.default_settings_fname):

            self.widgets['CalcWidget'].load_settings(
                self.default_settings_fname)

            self.widgets['InstrumentWidget'].load_settings(
                self.default_settings_fname)

        # Create the object responsible to display information send by the
        # datataker
        self.data_displayer = DataManagement.DataDisplayer(self.datataker)

        # platform-independent way to restore settings such as toolbar positions,
        # dock widget configuration and window size from previous session.
        # this doesn't seem to be working at all on my computer (win7 system)
        self.settings = QSettings("Gervais Lab", "RecordSweep")
        try:
            self.restoreState(self.settings.value("windowState").toByteArray())
            self.restoreGeometry(self.settings.value("geometry").toByteArray())
        except:
            logging.info(
                'Using default window configuration'
            )  # no biggie - probably means settings haven't been saved on this machine yet
Example #20
0
    def __init__(self,
                 parent=None,
                 fonctions_module=FONCTIONS_MODULE,
                 fonctions_pkg=FONCTIONS_PKG):
        super(FittingWidget, self).__init__(parent)

        if not parent == None:

            #this will be triggered whenever the user changes the plot limits
            #or whenever the software changes increases the dataset
            self.connect(
                parent,
                QtCore.SIGNAL(
                    "selections_limits(PyQt_PyObject,int,int,int,int)"),
                self.update_selection_limits)

            #this will call update_experiment whenever the dataset is updated
            self.connect(parent,
                         QtCore.SIGNAL("data_array_updated(PyQt_PyObject)"),
                         self.update_data_and_fit)
            self.connect(
                parent,
                QtCore.SIGNAL("instrument_hub_connected(PyQt_PyObject)"),
                self.update_instruments_information)

            self.connect(parent, QtCore.SIGNAL("removed_selection_box()"),
                         self.selection_removed)

            self.connect(
                parent, QtCore.SIGNAL("plotwindowtype_changed(PyQt_PyObject)"),
                self.data_type_changed)

        #loads the lists of functions from a module
        self.fonctions_pkg = fonctions_pkg

        if parent == None:
            self.fonctions_module = fonctions_module

            self.fit_funcs_names = io.list_module_func(self.fonctions_module)
        else:
            self.fonctions_module = ".%s" % (fonctions_module)
            self.fit_funcs_names = io.list_module_func(
                self.fonctions_module, package=self.fonctions_pkg)

        # main layout of the form is the verticallayout
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        """
        here will be displayed the button to create subsets and choose between livefit or postfit, also the number of the subset is displayed
        """
        self.commandLayout = QtGui.QHBoxLayout()

        self.fitCombo = QtGui.QComboBox(self)
        self.fitCombo.setObjectName("fit_comboBox")
        self.fitCombo.addItems(self.fit_funcs_names)
        self.save_fitButton = QtGui.QPushButton(self)
        self.save_fitButton.setText("Save single fit")
        self.save_setButton = QtGui.QPushButton(self)
        self.save_setButton.setText("Save set fit")
        self.live_fitButton = QtGui.QPushButton(self)
        self.live_fitButton.setText("Enable Fit")

        #initializes the fonction list in the ComboBox for the first time
        if parent == None:
            self.fit_func = io.import_module_func(
                self.fonctions_module, str(self.fitCombo.currentText()))
        else:
            self.fit_func = io.import_module_func(
                self.fonctions_module,
                str(self.fitCombo.currentText()),
                package=self.fonctions_pkg)

        #assigns the name of the fit fonction (python2 and python3)
        try:
            self.fit_params["fit_func"] = self.fit_func.func_name
        except:
            self.fit_params["fit_func"] = self.fit_func.__name__

        self.commandLayout.addWidget(self.fitCombo)
        self.commandLayout.addWidget(self.save_fitButton)
        self.commandLayout.addWidget(self.save_setButton)
        self.commandLayout.addWidget(self.live_fitButton)
        self.verticalLayout.addLayout(self.commandLayout)
        """
        here will be displayed the x-axis boundaries over which the plot is made
        """
        self.create_selection_layout()

        #if the user defined extra physical parameters needed once the fit
        #is performed, they will be defined in the dict PHYS_PARAMS
        if self.fit_params["fit_func"] in ad.PHYS_PARAMS:
            self.physparam_list = ad.PHYS_PARAMS[self.fit_params["fit_func"]]
        else:
            self.physparam_list = []

        self.create_fit_layout()
        self.create_phys_layout()

        self.setLayout(self.verticalLayout)

        self.connect(self.fitCombo, QtCore.SIGNAL("currentIndexChanged(int)"),
                     self.fit_func_changed)

        self.connect(self.live_fitButton, QtCore.SIGNAL('clicked()'),
                     self.on_live_fitButton_clicked)

        #this helps to toggle all the button according to the state False
        #it starts in True)
        self.on_live_fitButton_clicked()

        self.connect(self.save_fitButton, QtCore.SIGNAL('clicked()'),
                     self.on_save_fitButton_clicked)

        self.connect(self.save_setButton, QtCore.SIGNAL('clicked()'),
                     self.on_save_setButton_clicked)