class LoggerDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle("Data Logger")
        self.groupbox1 = DataSetEditGroupBox("Parametres de lock",Loggerdataset,show_button = False)   
        self.groupbox1.dataset.parent = self
        self.values = self.groupbox1.dataset
        self.groupbox1.dataset.parent = self
        lay = QVBoxLayout()
        lay.addWidget(self.groupbox1)
        self.setLayout(lay)
        self.resize(800,300)
        
        self.timer = QTimer()
        self.timer.timeout.connect(self.log)
        #self.timer.timeout.connect(self.update_values)
        self.timer.setInterval(100) #ms
        self.show()
    
    def transform_number(self):
        self.values.next = self.values.next*self.values.mult + self.values.add
        self.groupbox1.get()
    
    def log(self):
        self.groupbox1.set()
        if not vsa.on_screen.meas_done():
            return
        if vsa.on_screen.current_average()<self.values.next:
            vsa.on_screen.resume()
            return
        if self.values.save:
            self.manual()
        else:
            vsa.on_screen.resume()
        self.transform_number()
        #vsa.on_screen.set_average(self.values.next)
        

    def manual(self):
        vsa.on_screen.pause()
        try:
            df = load(self.values.filename)
        except IOError:
            df = matched_df()
        append_one_av(df)
        df.save(self.values.filename)
        vsa.on_screen.resume()
        
    
    def start(self):
        print "starting"
        vsa.on_screen.set_average(self.values.next)
        vsa.on_screen.restart()
        self.timer.start()
Beispiel #2
0
class ParamWidget(QWidget):
    def __init__(self, dataset, title = '', settings = None, settingskey = None, parent = None):
        super(ParamWidget, self).__init__(parent = parent)
        
        self.settings = settings
        self.settingskey = settingskey
        
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)
        
        
        if self.settings is not None and self.settingskey is not None:
            stored_list = self.settings.getValueOrDefault('storedParameters/'+self.settingskey, [ ])

            h = QHBoxLayout()
            self.mainLayout.addLayout(h)
            h.addStretch(1)
            self.comboParam = QComboBox()
            h.addWidget(self.comboParam, 3)
            
            self.refreshCombo()
            self.comboParam.currentIndexChanged.connect(self.comboParamChanged)

            buttonSave = QPushButton(QIcon(':/list-add.png') ,'')
            buttonSave.setMaximumSize(25,25)
            h.addWidget(buttonSave)
            buttonSave.clicked.connect(self.saveNewParam)
            buttonDel = QPushButton(QIcon(':/list-remove.png') ,'')
            buttonDel.setMaximumSize(25,25)
            h.addWidget(buttonDel)
            buttonDel.clicked.connect(self.delSavedParam)
        
        self.params = DataSetEditGroupBox(title,dataset, show_button = False)
        self.mainLayout.addWidget( self.params )
        
        self.default_dict = self.to_dict()
        

    def to_dict(self):
        self.params.set()
        ds = self.params.dataset
        d = OrderedDict()
        for item in ds._items:
            if type(item) is ChoiceItem:
                val = None
                ind = getattr(ds,  item._name)
                choices = item.get_prop_value("data", item, "choices")
                for choice in choices:
                    if choice[0] == ind:
                        val = choice[1]
            else:
                val = getattr(ds,  item._name)
            d[item._name] = val
        return d
        
    def update(self, d):
        ds = self.params.dataset
        for item in ds._items:
            if item._name in d:
                if type(item) is ChoiceItem:
                    choices = item.get_prop_value("data", item, "choices")
                    choices = [ c[1] for c in choices ]
                    ind = choices.index(d[item._name])
                    setattr(ds,  item._name, ind)
                else:
                    setattr(ds,  item._name, d[item._name])
        self.params.getInstance()
    
    def reset(self):
        self.update(self.default_dict)
    
    def refreshCombo(self):
        stored_list = self.settings['storedParameters/'+self.settingskey]
        self.comboParam.clear()
        list_name = [ l[0] for l in stored_list ]
        self.comboParam.addItems(['Default' , ]+list_name  )
        
    
    def comboParamChanged(self, pos) :
        if pos <= 0 :
            self.reset()
        else :
            stored_list = self.settings['storedParameters/'+self.settingskey]
            self.update(stored_list[pos-1][1])
    
    def saveNewParam( self ) :
        class Parameters(DataSet):
            name = StringItem('name', default = '')
        dia = ParamDialog(Parameters, title = 'key')
        ok = dia.exec_()
        if  ok !=  QDialog.Accepted: return
        
        name = dia.to_dict()['name']
        stored_list = self.settings['storedParameters/'+self.settingskey]
        stored_list += [ [ name , self.to_dict() ] ]
        self.settings['storedParameters/'+self.settingskey] = stored_list

        self.refreshCombo()
        self.comboParam.setCurrentIndex(len(stored_list))

    def delSavedParam( self) :
        pos = self.comboParam.currentIndex()
        if pos == 0: return

        stored_list = self.settings['storedParameters/'+self.settingskey]
        del stored_list[pos-1]
        self.settings['storedParameters/'+self.settingskey] = stored_list
            
        self.refreshCombo()
        self.comboParam.setCurrentIndex(0)
Beispiel #3
0
class ParamWidget(QWidget):
    def __init__(self, dataset, title = '', settings = None, settingskey = None, parent = None):
        super(ParamWidget, self).__init__(parent = parent)
        
        self.settings = settings
        self.settingskey = settingskey
        
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)
        
        
        if self.settings is not None and self.settingskey is not None:
            stored_list = self.settings.getValueOrDefault('storedParameters/'+self.settingskey, [ ])

            h = QHBoxLayout()
            self.mainLayout.addLayout(h)
            h.addStretch(1)
            self.comboParam = QComboBox()
            h.addWidget(self.comboParam, 3)
            
            self.refreshCombo()
            self.comboParam.currentIndexChanged.connect(self.comboParamChanged)

            buttonSave = QPushButton(QIcon(':/list-add.png') ,'')
            buttonSave.setMaximumSize(25,25)
            h.addWidget(buttonSave)
            buttonSave.clicked.connect(self.saveNewParam)
            buttonDel = QPushButton(QIcon(':/list-remove.png') ,'')
            buttonDel.setMaximumSize(25,25)
            h.addWidget(buttonDel)
            buttonDel.clicked.connect(self.delSavedParam)
        
        self.params = DataSetEditGroupBox(title,dataset, show_button = False)
        self.mainLayout.addWidget( self.params )
        
        self.default_dict = self.to_dict()
        

    def to_dict(self):
        self.params.set()
        ds = self.params.dataset
        d = OrderedDict()
        for item in ds._items:
            if type(item) is ChoiceItem:
                val = None
                ind = getattr(ds,  item._name)
                choices = item.get_prop_value("data", item, "choices")
                for choice in choices:
                    if choice[0] == ind:
                        val = choice[1]
            else:
                val = getattr(ds,  item._name)
            d[item._name] = val
        return d
        
    def update(self, d):
        ds = self.params.dataset
        for item in ds._items:
            if item._name in d:
                if type(item) is ChoiceItem:
                    choices = item.get_prop_value("data", item, "choices")
                    choices = [ c[1] for c in choices ]
                    ind = choices.index(d[item._name])
                    setattr(ds,  item._name, ind)
                else:
                    setattr(ds,  item._name, d[item._name])
        self.params.get()
    
    def reset(self):
        self.update(self.default_dict)
    
    def refreshCombo(self):
        stored_list = self.settings['storedParameters/'+self.settingskey]
        self.comboParam.clear()
        list_name = [ l[0] for l in stored_list ]
        self.comboParam.addItems(['Default' , ]+list_name  )
        
    
    def comboParamChanged(self, pos) :
        if pos <= 0 :
            self.reset()
        else :
            stored_list = self.settings['storedParameters/'+self.settingskey]
            self.update(stored_list[pos-1][1])
    
    def saveNewParam( self ) :
        class Parameters(DataSet):
            name = StringItem('name', default = '')
        dia = ParamDialog(Parameters, title = 'key')
        ok = dia.exec_()
        if  ok !=  QDialog.Accepted: return
        
        name = dia.to_dict()['name']
        stored_list = self.settings['storedParameters/'+self.settingskey]
        stored_list += [ [ name , self.to_dict() ] ]
        self.settings['storedParameters/'+self.settingskey] = stored_list

        self.refreshCombo()
        self.comboParam.setCurrentIndex(len(stored_list))

    def delSavedParam( self) :
        pos = self.comboParam.currentIndex()
        if pos == 0: return

        stored_list = self.settings['storedParameters/'+self.settingskey]
        del stored_list[pos-1]
        self.settings['storedParameters/'+self.settingskey] = stored_list
            
        self.refreshCombo()
        self.comboParam.setCurrentIndex(0)
Beispiel #4
0
class ProjectGUI(QObject):
    logger = logging.getLogger()
    _new_project_signal = pyqtSignal()

    def __init__(self, parent):
        super(ProjectGUI, self).__init__()
        self.parent = parent
        self._connect_project_properties()

    def _reset_data(self):
        self.projectproperties.dataset._reset_values()
        self.rewrite_values_in_gui_with_variables()

    def _connect_project_properties(self):
        self.projectproperties = DataSetEditGroupBox(
            "Project Data",
            ProjectPropertiesDataset,
            comment="Parameters common to all assets")
        self.projectproperties.SIG_APPLY_BUTTON_CLICKED.connect(
            self._apply_dataset_values)

    def _apply_dataset_values(self):
        """This is connected to a signal. When mocking, use parent.apply_dataset_values method."""
        self.logger.info("Me pressed.")
        self.parent.apply_dataset_values()

    def check_epanetfile(self, enfile):
        if (os.path.isfile(enfile)):
            self.logger.info("EPANET valid file check. To be implemented")
            return enfile
        else:
            self.logger.info("Not a valid epanetfile: %s" % enfile)
            msgBox = QMessageBox(parent=self.parent)
            msgBox.setText("This is not a valid epanet file")
            msgBox.exec_()
            return None

    def log(self):
        try:
            k = self.projectproperties.dataset
            self.logger.info("discount rate =%s" % (k.discountrate))
        except Exception:
            pass

    def rewrite_values_in_gui_with_variables(self):
        self.logger.info("Writing: var>GUI ")
        self.log()
        self.projectproperties.get()

    def rewrite_values_in_variables_with_gui(self):
        self.logger.info("Writing: GUI>var ")
        self.log()
        # disable events from firing
        __status = self.projectproperties.blockSignals(True)
        self.projectproperties.set()
        # now enable them again
        self.projectproperties.blockSignals(__status)

    def new_project(self):
        self.logger.info("New Project")
        # first step, get the name of the epanet file from the user.
        if (self._new_project()):
            # now we inform the project_manager to do the calculation
            self._new_project_signal.emit()
            return True
        else:
            return False

    def _new_project(self):
        epanetfile, filter = self._getSaveFileName2(
            self.parent,
            "Select a valid EPANET 2.0 network file",
            self.parent.EPANETLOC or c.HOMEDIR,
            filter='*.inp')

        epanetfile = self.check_epanetfile(epanetfile)
        if (not epanetfile):
            return False
        msg = "New Project"
        self.projectproperties.dataset.projectname = self._create_empty_project(
            msg, epanetfile)
        self.parent.LASTPROJECT = self.projectproperties.dataset.projectname
        self.parent.EPANETLOC = os.path.dirname(epanetfile)
        self.rewrite_values_in_gui_with_variables()
        return True

    def _getSaveFileName(self, *args, **kwargs):
        # why this function and _getSaveFileName2? for tests to mock this method easily.
        self.logger.info("proxy calling QFileDialog.getSaveFileName ")
        return QFileDialog.getSaveFileName(*args, **kwargs)

    def _getSaveFileName2(self, *args, **kwargs):
        # why this function and _getSaveFileName? for tests to mock this method easily.
        self.logger.info("proxy calling QFileDialog.getOpenFileName ")
        return QFileDialog.getOpenFileName(*args, **kwargs)

    def _getOpenFileName(self, *args, **kwargs):
        self.logger.info("proxy calling QFileDialog.getOpenFileName ")
        return QFileDialog.getOpenFileName(*args, **kwargs)

    def _create_empty_project(self, msg, epanetfile):
        projectfile = self.get_save_filename(msg)
        self.logger.info(
            "creating empty project with filename %s and epanetfile %s " %
            (projectfile, epanetfile))
        if (not projectfile):
            return None
        else:
            return self._save_project_to_dest(projectfile,
                                              epanetfile=epanetfile)

    def get_save_filename(self, msg):
        projectfile, filter = self._getSaveFileName(
            self.parent,
            msg,
            self.parent.LASTPROJECT or c.HOMEDIR,
            filter='*' + c.PROJECTEXTENSION)
        self.logger.info("Selected file for save/new project : %s " %
                         projectfile)
        return projectfile

    def _update_results_with_gui_values(self):
        """Update the self.projectproperties.dataset.results object with
        group information. Call this before pickling data"""
        r = self.projectproperties.dataset.results
        if (not r):
            self.logger.info(
                "No results available yet with projectproperties. So, not updating"
            )
        else:
            self.logger.info(
                "Updating projectproperties.dataset.results with my_group")
            for item in r.links:
                item.asset_group = self.parent.datawindow.get_asset_group(
                    item.id)
                item.age = self.parent.datawindow.get_age(item.id)

    def _save_project_to_dest(self, projectfile, epanetfile=None):

        self.logger.info("Getting values from datawindow..")
        # First get latest values from dataWindow
        inf = self.parent.datawindow.get_information(all=True)
        self.projectproperties.dataset.group_list_to_save_or_load = inf
        self._update_results_with_gui_values()
        self.logger.info("Now writing data")
        prjname, subdir, ext = c._get_dir_and_extention(projectfile)
        self.projectproperties.dataset.write_data(prjname)

        if (not os.path.isdir(subdir)):
            os.mkdir(subdir)
            self.logger.info("Created  directory %s" % subdir)

        if (epanetfile):
            base = os.path.basename(epanetfile)
            dst = os.path.join(os.path.dirname(prjname), base)
            shutil.copy(epanetfile, dst)
            self.projectproperties.dataset.fname = base
            self.logger.info("copied epanet file to %s" % dst)
        return prjname

    def try_loading_project_properties(self, prj):
        try:
            self.logger.info("Trying to read properties from %s " % prj)
            if (self.projectproperties.dataset.read_data(prj)):
                self.logger.info(" %s project read successfully." % prj)
                return True
        except Exception as e:
            self.logger.exception("Could not load the project properties: %s" %
                                  e)
        return False

    def save_project(self):
        self.logger.info("Saving the project")
        # Implement the actions needed to save the project here.
        # first update any user changes in parameters
        self.rewrite_values_in_variables_with_gui()
        try:
            return self._save_project_to_dest(
                self.projectproperties.dataset.projectname)
        except Exception as e:
            self.logger.exception("Exception %s " % e)
            return False

    def save_project_as(self):
        msg = "Save project as"
        self.projectproperties.dataset.projectname = self.get_save_filename(
            msg)
        if (self.projectproperties.dataset.projectname):
            return self.save_project()
        else:
            return None

    def open_project(self):
        while (True):
            projectfile, filter = self._getOpenFileName(
                self.parent,
                "Open project",
                self.parent.LASTPROJECT or c.HOMEDIR,
                filter='*' + c.PROJECTEXTENSION)
            if (not projectfile):
                return None
            projectfile, dir, ext = c._get_dir_and_extention(projectfile)
            self.logger.info("Selected file to open : %s " % projectfile)
            # check if it is a valid project
            if (self._valid_project(projectfile)):
                self.projectproperties.dataset.projectname = projectfile
                self.parent.LASTPROJECT = self.projectproperties.dataset.projectname
                self.parent._display_project()
                # now update the dataWindow with project groups in opened project
                self.parent.datawindow.set_information(
                    self.projectproperties.dataset.group_list_to_save_or_load)
                self.logger.info("Updated dataWindow with project groups")
                # since we have done both (a) displaying network and
                # (b) updating the asset groups, now we can assign correct asset group
                # to each asset item
                if (self.projectproperties.dataset.results):
                    r = self.projectproperties.dataset.results.links
                    self.parent.datawindow.assign_values_to_asset_items(r)
                break
            else:
                self.logger.info("Project loading failed: Not a valid project")
                return None

        self.logger.info("Open Project valid")
        self.rewrite_values_in_gui_with_variables()
        self.parent.apply_dataset_values()
        return (projectfile)

    def _valid_project(self, prj):
        """Check if prj represents a valid project. """
        if (not os.path.isfile(prj)):
            return False
        if (not os.path.isdir(c._get_dir_and_extention(prj)[1])):
            return False
        # Try opening
        self.logger.info("Now calling try_loading_project_properties ")
        return self.try_loading_project_properties(prj)
Beispiel #5
0
class MathPanel(PlotPanel):
    class cSet(DataSet):
        _bg1 = BeginGroup("Source 1").set_pos(0)
        tab1 = ChoiceItem("Tab", ['a'])
        data1 = ChoiceItem("Data", ['a'])
        _eg1 = EndGroup("")

        _bg2 = BeginGroup("Source 2").set_pos(1)
        tab2 = ChoiceItem("Tab", ['a'])
        data2 = ChoiceItem("Data", ['a'])
        _eg2 = EndGroup("")

        _bg3 = BeginGroup("Operation").set_pos(2)
        function = ChoiceItem("Function", [('y1-y2', 'y1-y2'),
                                           ('y1+y2', 'y1+y2'),
                                           ('y1/y2', 'y1/y2'),
                                           ('custom', 'f(x,y1,y2)')])
        custom = StringItem("f(x,y1,y2):")
        _eg3 = EndGroup("")

        text = TextItem("").set_pos(3)

    def __init__(self, parent):
        plots=\
         [[
          {'name':'Source 1','curves':['in1']},
          {'name':'Source 2','curves':['in2']}],
         [
          {'name':'Result','curves':['out']},
         ]]

        self.tabs = parent.sp

        df = [n.axisLimits[1] - n.axisLimits[0] for n in self.tabs]
        df2 = max(df) / 2

        axisLimits = [
            -df2, df2,
            min([n.axisLimits[2] for n in self.tabs]),
            max([n.axisLimits[3] for n in self.tabs])
        ]

        PlotPanel.__init__(self,
                           parent=parent,
                           plots=plots,
                           axisLimits=axisLimits)

        self._cBox = DataSetEditGroupBox("Control",
                                         self.cSet,
                                         show_button=False)
        self.addWidget(self._cBox)

        tabchoices = [(m, n.name, None) for m, n in enumerate(self.tabs)]
        curvechoices = [(n, n, None) for n in self.tabs[0].curves.keys()]

        self.cSet._items[1].set_prop('data', choices=tabchoices)
        self._cBox.dataset.tab1 = 0
        self.cSet._items[2].set_prop('data', choices=curvechoices)
        self._cBox.dataset.data1 = curvechoices[0][0]
        self.cSet._items[5].set_prop('data', choices=tabchoices)
        self._cBox.dataset.tab2 = 0
        self.cSet._items[6].set_prop('data', choices=curvechoices)
        self._cBox.dataset.data2 = curvechoices[0][0]
        self._cBox.get()

    def refreshTab(self):
        if self.curves is None: return
        self._cBox.set()
        d = self._cBox.dataset
        tab1, tab2 = self.tabs[d.tab1], self.tabs[d.tab2]

        x1, y1 = tab1.getx(), tab1.curves[d.data1].y
        x2, y2 = tab2.getx(), tab2.curves[d.data2].y

        if x1 is None or x2 is None: return

        x_min = min(min(x1), min(x2))
        x_max = max(max(x1), max(x2))
        dx1 = x1[1] - x1[0] if len(x1) > 1 else 1e9
        dx2 = x2[1] - x2[0] if len(x2) > 1 else 1e9
        dx = min(dx1, dx2)

        x = np.arange(x_min, x_max, dx)
        y1 = np.interp(x, x1, y1, left=0, right=0)
        y2 = np.interp(x, x2, y2, left=0, right=0)

        fun = self._cBox.dataset.function
        if fun == 'custom': fun = self._cBox.dataset.custom

        try:
            y = eval(fun)
        except:
            y = x * 0.

        self.curves['in1'].setplot(x, y1)
        self.curves['in2'].setplot(x, y2)
        self.curves['out'].setplot(x, y)