Esempio n. 1
0
    def setUp(self):
        self.root = server.BaseServer(share.SharingManager())
        storage.Storage(parent=self.root)  
        self.obj = instrument.Instrument(self.root, 'instrument')
        dumps(self.obj)
        self.obj.outFile = False
        # Create a device server with some sub-devices
        self.dsrv = device.DeviceServer(self.root, 'dsrv')
        self.root.deviceservers = [self.dsrv]
        self.dev1 = device.Device(self.dsrv, 'dev1')
        self.dev2 = device.Device(self.dsrv, 'dev2')
        self.assertEqual(len(self.dsrv.devices), 2)

        set_options(self.dev1)
        set_options(self.dev2)
        set_options(self.obj)
#		self.obj.devices=[self.dev1,self.dev2]
        self.obj.measure['measureFile'] = hdfpath
        d = {}
        ao(d, 'dev1role', 'Role', ['/dsrv/dev1/', 'default'])
        ao(d, 'dev2role', 'Role', ['/dsrv/dev2/', 'default'])

        self.obj.desc.update(d)
        self.d = d
        
        self.obj.init_instrument()
Esempio n. 2
0
 def newCheckpoint(self):
     crow = self.selection.currentIndex().row()
     if crow == 0:
         QtGui.QMessageBox.warning(self, _('Impossible event requested'),
                                   _('Cannot insert a checkpoint event as first row'))
         return False
     elif isinstance(self.model().dat[crow][1], basestring):
         # Currently unsupported
         QtGui.QMessageBox.warning(self, _('Impossible event requested'),
                                   _('Cannot insert a checkpoint event after another event'))
         return False
     desc = {}
     option.ao(desc, 'deltaST', 'Float', name=_("Temperature-Setpoint tolerance"),
               unit='celsius', current=3, min=0, max=100, step=0.1)
     option.ao(desc, 'timeout', 'Float', name=_("Timeout"),
               unit='minute', current=120, min=0, max=1e3, step=0.1)
     cp = option.ConfigurationProxy({'self': desc})
     chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
     chk.setWindowTitle(_("Checkpoint configuration"))
     ok = chk.exec_()
     if ok:
         timeout = units.Converter.convert('minute', 'second', cp['timeout'])
         event = '>checkpoint,{:.1f},{:.1f}'.format(cp['deltaST'], timeout)
         self.insert_event(event)
     return ok
    def steps_template(self):
        steps_options = {}
        option.ao(
            steps_options, 'heatingRate', 'Float', name=_("Heating Rate"),
                  unit='celsius/minute', current=80, min=0.1, max=80, step=0.1)
        option.ao(
            steps_options, 'firstStepTemperature', 'Float', name=_("First step Temperature"),
                  unit='celsius', current=1000, min=0, max=1800, step=0.1)
        option.ao(
            steps_options, 'stasisDuration', 'Float', name=_("Stasis Duration"),
                  unit='seconds', current=600, step=1)
        option.ao(steps_options, 'numberOfSteps', 'Integer',
                  name=_("Number of Steps"), current=10, step=1)
        option.ao(
            steps_options, 'stepsDeltaT', 'Float', name=_("Steps delta T"),
                  unit='celsius', current=20, min=0, max=100, step=0.1)

        configuration_proxy = option.ConfigurationProxy(
            {'self': steps_options})
        temperature_dialog = conf.InterfaceDialog(
            configuration_proxy, configuration_proxy, steps_options, parent=self.parent)
        temperature_dialog.setWindowTitle(_('Single ramp template'))
        if temperature_dialog.exec_():
            new_curve = steps_template_to_thermal_cycle_curve(configuration_proxy)
            self.model.setCurve(new_curve)
            self.replot()
            self.apply()
    def steps_template(self):
        steps_options = {}
        option.ao(
            steps_options, 'heatingRate', 'Float', name=_("Heating Rate"),
                  unit='celsius/minute', current=80, min=0.1, max=80, step=0.1)
        option.ao(
            steps_options, 'firstStepTemperature', 'Float', name=_("First step Temperature"),
                  unit='celsius', current=1000, min=0, max=1800, step=0.1)
        option.ao(
            steps_options, 'stasisDuration', 'Float', name=_("Stasis Duration"),
                  unit='seconds', current=600, step=1)
        option.ao(steps_options, 'numberOfSteps', 'Integer',
                  name=_("Number of Steps"), current=10, step=1)
        option.ao(
            steps_options, 'stepsDeltaT', 'Float', name=_("Steps delta T"),
                  unit='celsius', current=20, min=0, max=100, step=0.1)

        configuration_proxy = option.ConfigurationProxy(
            {'self': steps_options})
        temperature_dialog = conf.InterfaceDialog(
            configuration_proxy, configuration_proxy, steps_options, parent=self.parent)
        temperature_dialog.setWindowTitle(_('Single ramp template'))
        if temperature_dialog.exec_():
            new_curve = steps_template_to_thermal_cycle_curve(configuration_proxy)
            self.model.setCurve(new_curve)
            self.replot()
            self.apply()
Esempio n. 5
0
 def test_keepnames(self):
     cf = self.cf
     cf.update(option.ao({}, 'opt1', current=0))
     cf.update(
         option.ao({},
                   'preset',
                   type='Preset',
                   options=[],
                   current='factory_default'))
     cf.setConf_dir(self.cfd)
     # Protect the `opt` name
     cf.setKeep_names(['opt'])
     self.assertEqual(cf.keepnames, ['opt'])
     cf['opt'] = 0
     cf['opt1'] = 5
     cf.save('test')
     self.assertEqual(cf.desc['opt1']['current'], cf.get_current('opt1'))
     cf['opt'] = 1
     cf['opt1'] = 1
     # Current value should be updated
     self.assertEqual(cf.get_current('opt1'), 1)
     self.assertEqual(cf.get_current('opt'), 1)
     # Load previous config
     self.assertEqual(cf.keepnames, ['opt'])
     cf.load('test')
     self.assertEqual(cf.keepnames, ['opt'])
     self.assertEqual(cf.keepnames, cf.getKeep_names())
     # 'opt1' name should be overwritten by the load operation
     self.assertEqual(cf['opt1'], 5)
     # 'opt' name should NOT be overwritten during load, because it is protected
     self.assertEqual(cf['opt'], 1)
Esempio n. 6
0
 def newThermocoupleControlTransition(self):
     desc = {}
     option.ao(desc,
               'target',
               'Float',
               name=_("Target Sample Thermocouple Weight"),
               current=1,
               min=0,
               max=1,
               step=0.01)
     option.ao(desc,
               'rate',
               'Float',
               name=_("Control temperature switching rate (0=sudden)"),
               unit='celsius/minute',
               current=5,
               min=0,
               max=30,
               step=0.1)
     cp = option.ConfigurationProxy({'self': desc})
     chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
     chk.setWindowTitle(_("Thermocouple Control Transition Configuration"))
     ok = chk.exec_()
     if ok:
         event = '>tctrans,{:.2f},{:.1f}'.format(cp['target'], cp['rate'])
         self.insert_event(event)
     return ok
Esempio n. 7
0
    def test_applyDesc(self):
        class SubDevice(device.Device):
            hardvar = 0
            softvar = 0

            def set_hard(self, val):
                self.hardvar = val
                return val

            def set_soft(self, val):
                self.softvar = val
                return val

        dev = SubDevice(node='null')
        self.assertTrue(dev.desc.has_key('name'))
        print 'KEYS', dev.desc.keys()
        d = dev.describe()
        self.assertTrue(d.has_key('name'))
        # Keep current config
        oldd = deepcopy(d)
        # Modify a copy of current config
        d['dev']['current'] = 'dev0'
        d['devpath']['current'] = '/dev/0/1/'
        d['name']['current'] = 'pippo'
        del d['zerotime']
        # Apply modified config to dev
        dev.applyDesc(d)
        # Should maintain dev and devpath
        for k in ('dev', 'devpath'):
            self.assertEqual(dev[k], oldd[k]['current'])
        # Should update any other property
        for k in ('name', ):
            self.assertEqual(dev[k], d[k]['current'])
        # Should not delete missing keys
        self.assertTrue(dev.desc.has_key('zerotime'))

        # Test Hardware triggers
        dev.hardvar = 0
        h = ao({}, 'hard', type='Integer', attr=['Hardware'])
        h = ao(h, 'soft', type='Integer')
        dev.update(h)

        self.assertEqual(dev['hard'], dev.hardvar)
        self.assertEqual(dev['soft'], dev.softvar)
        dev['hard'] = 3
        dev['soft'] = 3
        self.assertEqual(dev['hard'], dev.hardvar)
        self.assertEqual(dev['soft'], dev.softvar)

        h['hard']['current'] = 5
        h['soft']['current'] = 5
        dev.applyDesc(h)
        # Both current values should be updated
        self.assertEqual(dev['hard'], 5)
        self.assertEqual(dev['soft'], 5)
        # The set_hard should be triggered:
        self.assertEqual(dev['hard'], dev.hardvar)
        # The set_soft should NOT be triggered:
        self.assertEqual(dev.softvar, 3)
 def test_human(self):
     self.root.sete('delay', option.ao({}, 'delay', 'Time')['delay'])
     self.root.sete('delayStart',
                    option.ao({}, 'delayStart', 'Boolean')['delayStart'])
     w = self.wgGen('delay')
     w1 = widgets.build(self.root, self.root, self.root.gete('delayStart'))
     w.lay.addWidget(w1)
     iutils_testing.show(w, __name__)
 def test_human(self):
     self.root.sete('delay', option.ao({}, 'delay', 'Time')['delay'])
     self.root.sete(
         'delayStart', option.ao({}, 'delayStart', 'Boolean')['delayStart'])
     w = self.wgGen('delay')
     w1 = widgets.build(self.root, self.root, self.root.gete('delayStart'))
     w.lay.addWidget(w1)
     iutils_testing.show(w, __name__)
Esempio n. 10
0
 def setUp(self):
     self.cf = data.Conf()
     self.cf.update(option.ao({}, 'fullpath', type='ReadOnly'))
     self.cf.update(option.ao({}, 'opt', current=0))
     self.cf.update(option.ao({}, 'log', type='Log'))
     self.cfd = tempfile.mkdtemp()
     self.cf.setConf_dir(self.cfd)
     shutil.copy(c1, self.cfd)
     shutil.copy(c2, self.cfd)
Esempio n. 11
0
 def test_describe(self):
     self.cf.update(option.ao({}, 'bin', type='Binary'))
     self.cf.update(option.ao({}, 'num', type='Float'))
     self.cf['num'] = np.int32(0)
     self.cf['bin'] = 'binary'
     d = self.cf.describe()
     print 'test_describe', type(d['num']['current']), repr(
         d['bin']['factory_default'])
     self.assertIsInstance(d['num']['current'], np.int32)
     self.assertEqual(d['bin']['current'], '')
Esempio n. 12
0
 def test_update(self):
     cf = self.cf
     self.assertEqual(cf['opt'], 0)
     cf.update(option.ao({}, 'opt1', current=1))
     self.assertEqual(cf['opt'], 0)
     self.assertEqual(cf['opt1'], 1)
     cf.update(option.ao(cf.desc, 'opt2', current=2))
     self.assertEqual(cf['opt'], 0)
     self.assertEqual(cf['opt1'], 1)
     self.assertEqual(cf['opt2'], 2)
     cf.update(option.ao({}, 'opt', current=10))
     self.assertEqual(cf['opt'], 10)
    def test_RoleProgress(self):
        self.root.sete(
            'Test', option.ao({}, 'Test', 'Progress', current=3, max=10)['Test'])
        self.root.sete(
            'Test2', option.ao({}, 'Test2', 'Progress', current=5, max=8)['Test2'])

        self.root.sete('progress', option.ao(
            {}, 'progress', 'List', current=['/Test', '/Test2'])['progress'])
        self.root.setattr('progress', 'kid', '/progress')

        widget = self.wgGen('progress')
        iutils_testing.show(widget, __name__)
Esempio n. 14
0
    def setUpClass(cls):
        s = option.ConfigurationProxy()
        s.sete('isRunning',
               option.ao({}, 'isRunning', 'Integer', 0)['isRunning'])
        s.sete('eq_sn', option.ao({}, 'eq_sn', 'String', 'test_sync')['eq_sn'])
        cls.srv = s  # base configuration proxy

        p = iut.FakeProxy(s)  # server proxy
        p.addr = 'https://127.0.0.1:{}/RPC'.format(PORT)
        p.storage = indexer.Indexer(remote_dbpath)
        cls.server = p
        cls.local = indexer.Indexer(local_dbpath)
        iut.enableSignalDebugging()
Esempio n. 15
0
    def setUpClass(cls):
        s = option.ConfigurationProxy()
        s.sete('isRunning', option.ao(
            {}, 'isRunning', 'Integer', 0)['isRunning'])
        s.sete('eq_sn', option.ao({}, 'eq_sn', 'String', 'test_sync')['eq_sn'])
        cls.srv = s  # base configuration proxy

        p = iut.FakeProxy(s)  # server proxy
        p.addr = 'https://127.0.0.1:{}/RPC'.format(PORT)
        p.storage = indexer.Indexer(remote_dbpath)
        cls.server = p
        cls.local = indexer.Indexer(local_dbpath)
        iut.enableSignalDebugging()
Esempio n. 16
0
 def newThermocoupleControlTransition(self):
     desc = {}
     option.ao(desc, 'target', 'Float', name=_("Target Sample Thermocouple Weight"),
               current=1, min=0, max=1, step=0.01)
     option.ao(desc, 'rate', 'Float', name=_("Control temperature switching rate (0=sudden)"),
               unit='celsius/minute', current=5, min=0, max=30, step=0.1)
     cp = option.ConfigurationProxy({'self': desc})
     chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
     chk.setWindowTitle(_("Thermocouple Control Transition Configuration"))
     ok = chk.exec_()
     if ok:
         event = '>tctrans,{:.2f},{:.1f}'.format(cp['target'], cp['rate'])
         self.insert_event(event)
     return ok
Esempio n. 17
0
    def test_log(self):
        cf = self.cf
        cf.update(option.ao({}, 'log', type='Log'))
        cf.db = DummyLogDb()

        def check_log(set_log, expect_log):
            cf['log'] = set_log
            self.assertEqual(cf['log'], expect_log)
            self.assertEqual(cf.db.args[0], expect_log[1])
            self.assertEqual(cf.db.kwargs.get('p', None), expect_log[0])
            self.assertEqual(cf.db.kwargs.get('o', None), '')

        check_log([10, 'test'], [10, 'test'])
        check_log([20, '<\xeb\xa7\xc1'], [20, u'<\ufffd\ufffd'])

        for i in xrange(100):
            msg = struct.pack("=I", random.randint(0, 4294967295))
            level = random.randint(0, 5) * 10
            cf['log'] = [level, msg]
            out_level, out_msg = cf['log']
            self.assertEqual(out_level, level)
            # Should not raise any exception
            self.assertIsInstance(out_msg, unicode)
            # Should not raise any exception
            out_msg.encode('utf-8', 'strict')

        cf['log']
Esempio n. 18
0
    def test_rotation(self):
        rows = [['pippo' + str(i), i, i * 100] for i in range(20)]
        tab = [[('ColStr', 'String'), ('ColInt', 'Integer'),
                ('ColFloat', 'Float')]] + rows
        self.root.sete('test', option.ao({}, 'test', 'Table', tab)['test'])
        widget = self.wgGen()
        view = widget.table
        model = view.model()
        self.assertFalse(model.rotated)

        # Check rotation
        model.rotated = False
        self.assertEqual(model.rowCount(), 20)
        print len(model.rows)
        self.assertEqual(model.columnCount(), 3)
        self.assertEqual(model.headerData(0, QtCore.Qt.Vertical), None)
        model.perpendicular_header_col = 0
        self.assertEqual(model.headerData(0, QtCore.Qt.Vertical), 'pippo0')
        self.assertEqual(model.headerData(1, QtCore.Qt.Vertical), 'pippo1')

        self.assertEqual(model.headerData(0, QtCore.Qt.Horizontal), 'ColStr')
        self.assertEqual(model.headerData(1, QtCore.Qt.Horizontal), 'ColInt')
        self.assertEqual(model.headerData(2, QtCore.Qt.Horizontal), 'ColFloat')

        # Check rotation
        model.rotated = True
        self.assertEqual(model.rowCount(), 3)
        self.assertEqual(model.columnCount(), 20)

        self.assertEqual(model.headerData(0, QtCore.Qt.Horizontal), 'pippo0')
        self.assertEqual(model.headerData(1, QtCore.Qt.Horizontal), 'pippo1')

        self.assertEqual(model.headerData(0, QtCore.Qt.Vertical), 'ColStr')
        self.assertEqual(model.headerData(1, QtCore.Qt.Vertical), 'ColInt')
        self.assertEqual(model.headerData(2, QtCore.Qt.Vertical), 'ColFloat')
Esempio n. 19
0
 def test_units(self):
     self.root.sete(
         'Test',
         option.ao({}, 'Test', 'Float', 0, 'Units', units='second')['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 0)
     self.assertFalse(w.slider)
Esempio n. 20
0
    def test_RoleProgress(self):
        self.root.sete(
            'Test',
            option.ao({}, 'Test', 'Progress', current=3, max=10)['Test'])
        self.root.sete(
            'Test2',
            option.ao({}, 'Test2', 'Progress', current=5, max=8)['Test2'])

        self.root.sete(
            'progress',
            option.ao({}, 'progress', 'List', current=['/Test',
                                                       '/Test2'])['progress'])
        self.root.setattr('progress', 'kid', '/progress')

        widget = self.wgGen('progress')
        iutils_testing.show(widget, __name__)
 def fast_template(self):
     """Reach target temperature at the maximum allowed speed"""
     options = {}
     option.ao(
         options, 'target', 'Float', name=_("Target temperature"),
               unit='celsius', current=1600, min=0, max=1600, step=10)
     configuration_proxy = option.ConfigurationProxy(
         {'self': options})    
     dialog = conf.InterfaceDialog(
         configuration_proxy, configuration_proxy, options, parent=self.parent)
     dialog.setWindowTitle(_('Reach at maximum speed template'))
     if dialog.exec_():
         new_curve = fast_to_thermal_cycle_curve(configuration_proxy['target'], 
                                                      self.remote['rateLimit'][1:], 
                                                      self.remote['maxHeatingRate'])
         self.model.setCurve(new_curve)
         self.replot()
         self.apply()             
 def single_ramp_template(self):
     ramp_options = {}
     option.ao(
         ramp_options, 'temperature', 'Float', name=_("Ramp end Temperature"),
               unit='celsius', current=1000, min=0, max=2000, step=0.1)
     option.ao(ramp_options, 'heatingRate', 'Float', name=_("Heating Rate"),
               unit='celsius/minute', current=20, min=0.1, max=80, step=0.1)
     temperature_configuration_proxy = option.ConfigurationProxy(
         {'self': ramp_options})
     temperature_dialog = conf.InterfaceDialog(
         temperature_configuration_proxy, temperature_configuration_proxy, ramp_options, parent=self.parent)
     temperature_dialog.setWindowTitle(_('Single ramp template'))
     if temperature_dialog.exec_():
         new_curve = ramp_to_thermal_cycle_curve(temperature_configuration_proxy[
                                                 'temperature'], temperature_configuration_proxy['heatingRate'])
         self.model.setCurve(new_curve)
         self.replot()
         self.apply()
 def single_ramp_template(self):
     ramp_options = {}
     option.ao(
         ramp_options, 'temperature', 'Float', name=_("Ramp end Temperature"),
               unit='celsius', current=1000, min=0, max=2000, step=0.1)
     option.ao(ramp_options, 'heatingRate', 'Float', name=_("Heating Rate"),
               unit='celsius/minute', current=20, min=0.1, max=80, step=0.1)
     temperature_configuration_proxy = option.ConfigurationProxy(
         {'self': ramp_options})
     temperature_dialog = conf.InterfaceDialog(
         temperature_configuration_proxy, temperature_configuration_proxy, ramp_options, parent=self.parent)
     temperature_dialog.setWindowTitle(_('Single ramp template'))
     if temperature_dialog.exec_():
         new_curve = ramp_to_thermal_cycle_curve(temperature_configuration_proxy[
                                                 'temperature'], temperature_configuration_proxy['heatingRate'])
         self.model.setCurve(new_curve)
         self.replot()
         self.apply()
 def fast_template(self):
     """Reach target temperature at the maximum allowed speed"""
     options = {}
     option.ao(
         options, 'target', 'Float', name=_("Target temperature"),
               unit='celsius', current=1600, min=0, max=1600, step=10)
     configuration_proxy = option.ConfigurationProxy(
         {'self': options})    
     dialog = conf.InterfaceDialog(
         configuration_proxy, configuration_proxy, options, parent=self.parent)
     dialog.setWindowTitle(_('Reach at maximum speed template'))
     if dialog.exec_():
         new_curve = fast_to_thermal_cycle_curve(configuration_proxy['target'], 
                                                      self.remote['rateLimit'][1:], 
                                                      self.remote['maxHeatingRate'])
         self.model.setCurve(new_curve)
         self.replot()
         self.apply()             
Esempio n. 25
0
 def test_MIN_MAX_dbl(self):
     self.root.sete(
         'Test',
         option.ao({}, 'Test', 'Float', 5, 'Float bounds', min=-10,
                   max=10)['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 5)
     self.assertTrue(w.slider)
     iutils_testing.show(w, __name__)
Esempio n. 26
0
 def newCheckpoint(self):
     crow = self.selection.currentIndex().row()
     if crow == 0:
         QtGui.QMessageBox.warning(
             self, _('Impossible event requested'),
             _('Cannot insert a checkpoint event as first row'))
         return False
     elif isinstance(self.model().dat[crow][1], basestring):
         # Currently unsupported
         QtGui.QMessageBox.warning(
             self, _('Impossible event requested'),
             _('Cannot insert a checkpoint event after another event'))
         return False
     desc = {}
     option.ao(desc,
               'deltaST',
               'Float',
               name=_("Temperature-Setpoint tolerance"),
               unit='celsius',
               current=3,
               min=0,
               max=100,
               step=0.1)
     option.ao(desc,
               'timeout',
               'Float',
               name=_("Timeout"),
               unit='minute',
               current=120,
               min=0,
               max=1e3,
               step=0.1)
     cp = option.ConfigurationProxy({'self': desc})
     chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
     chk.setWindowTitle(_("Checkpoint configuration"))
     ok = chk.exec_()
     if ok:
         timeout = units.Converter.convert('minute', 'second',
                                           cp['timeout'])
         event = '>checkpoint,{:.1f},{:.1f}'.format(cp['deltaST'], timeout)
         self.insert_event(event)
     return ok
Esempio n. 27
0
 def test_presets(self):
     cf = self.cf
     cf.update(option.ao({}, 'opt1', current=0))
     # Get preset should return 'factory_default' if not found
     self.assertEqual(cf.get_preset(), 'factory_default')
     cf.update(
         option.ao({},
                   'preset',
                   type='Preset',
                   options=[],
                   current='factory_default'))
     desc0 = cf.describe()
     self.assertEqual(cf['preset'], 'factory_default')
     cf.setConf_dir(self.cfd)
     cf.save('test0')
     self.assertEqual(cf['preset'], 'test0')
     self.assertEqual(cf.listPresets(), cf.gete('preset')['options'])
     self.assertEqual(cf.listPresets(),
                      ['factory_default', 'Conf', 'Conf2', 'test0'])
     cf['opt'] = 1
     cf.save('test1')
     self.assertEqual(
         set(cf.listPresets()),
         set(['factory_default', 'Conf', 'Conf2', 'test0', 'test1']))
     cf.set_preset('test0')
     self.assertEqual(cf['opt'], 0)
     cf.set_preset('test1')
     self.assertEqual(cf['opt'], 1)
     # Default loading
     cf['opt'] = 2
     print cf.save('default')
     self.assertEqual(
         set(cf.listPresets()),
         set([
             'factory_default', 'Conf', 'Conf2', 'default', 'test0', 'test1'
         ]))
     # Create a totally new object
     cf1 = data.Conf(desc=desc0)
     # Set the same confdir: the default.csv file should be red.
     cf1.setConf_dir(self.cfd)
     print cf1.conf_dir, cf1.keys()
     self.assertEqual(cf['opt'], cf1['opt'])
Esempio n. 28
0
 def setUp(self):
     """Prepare a minimal tree"""
     params.confdir = testdir
     self.root = device.Node(node='root')
     print(self.root.desc.describe())
     self.sub = device.Node(parent=self.root, node='sub')
     name = ao({}, 'name', 'String')['name']
     self.sub.sete('name', name.copy())
     self.subA = device.Node(parent=self.root, node='subA')
     self.subA.sete('name', name.copy())
     self.sub2 = device.Node(parent=self.sub, node='sub2')
     self.sub2.sete('name', name.copy())
Esempio n. 29
0
 def add_tT(path):
     if timecol_name:
         u = unit[timecol_idx]
         if not u:
             u = 'second'
         topt = option.ao({}, handle + '_t', 'Float', 0, 'Time',
                          unit=u).popitem()[1]
         datasets[path + '_t'] = (tab[timecol_idx], path + '_t', 'Time',
                                  None, topt)
     if Tcol_name:
         u = unit[Tcol_idx]
         if not u:
             u = 'celsius'
         Topt = option.ao({},
                          handle + '_T',
                          'Float',
                          0,
                          'Temperature',
                          unit=u).popitem()[1]
         datasets[path + '_T'] = (tab[Tcol_idx], path + '_T', 'Temperature',
                                  None, Topt)
Esempio n. 30
0
def export_images_option_dialog(parent, max_temp):
    opts = {}
    option.ao(opts,
              'standard',
              'Chooser',
              standards[0],
              name=_("Standard for characteristic shapes"),
              options=standards)
    option.ao(opts,
              'start',
              'Integer',
              name=_("Discard images below temperature"),
              unit='celsius',
              current=0,
              min=0,
              max=max_temp + 1,
              step=1)
    option.ao(opts,
              'step',
              'Float',
              name=_("Temperature stepping"),
              unit='celsius',
              current=1,
              min=0,
              max=50,
              step=0.1)
    configuration_proxy = option.ConfigurationProxy({'self': opts})
    temperature_dialog = conf.InterfaceDialog(configuration_proxy,
                                              configuration_proxy,
                                              opts,
                                              parent=parent)
    temperature_dialog.setWindowTitle(_('Image export options'))
    if temperature_dialog.exec_():
        return configuration_proxy
    return False
Esempio n. 31
0
 def test_Properties(self):
     self.root.sete(
         'Test',
         option.ao({},
                   'Test',
                   'Float',
                   120,
                   'Properties',
                   unit='second',
                   precision=4)['Test'])
     w = self.wgGen()
     w.lay.addWidget(w.label_widget)
     iutils_testing.show(w, __name__)
Esempio n. 32
0
    def newCool(self):
        desc = {}

        current_row = self.selection.currentIndex().row()
        previous_row = row.previous_not_event_row_index(
            current_row + 1,
            self.model().dat)
        previous_temperature = self.model().dat[previous_row][1]

        option.ao(desc,
                  'target',
                  'Float',
                  name=_("Target cooling temperature"),
                  unit='celsius',
                  current=50,
                  min=0,
                  max=previous_temperature,
                  step=0.1)
        option.ao(desc,
                  'timeout',
                  'Float',
                  name=_("Timeout (<=0 means forever)"),
                  unit='minute',
                  current=-1,
                  min=-1,
                  max=1e3,
                  step=0.1)
        cp = option.ConfigurationProxy({'self': desc})
        chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
        chk.setWindowTitle(_("Natural cooling configuration"))
        ok = chk.exec_()
        if ok:
            timeout = units.Converter.convert('minute', 'second',
                                              cp['timeout'])
            if timeout < 0:
                timeout = -1
            event = '>cool,{:.1f},{:.1f}'.format(cp['target'], timeout)
            self.insert_event(event)
        return ok
Esempio n. 33
0
    def newCool(self):
        desc = {}

        current_row = self.selection.currentIndex().row()
        previous_row = row.previous_not_event_row_index(current_row + 1, self.model().dat)
        previous_temperature = self.model().dat[previous_row][1]

        option.ao(desc, 'target', 'Float', name=_("Target cooling temperature"),
                  unit='celsius', current=50, min=0, max=previous_temperature, step=0.1)
        option.ao(desc, 'timeout', 'Float', name=_("Timeout (<=0 means forever)"),
                  unit='minute', current=-1, min=-1, max=1e3, step=0.1)
        cp = option.ConfigurationProxy({'self': desc})
        chk = conf.InterfaceDialog(cp, cp, desc, parent=self)
        chk.setWindowTitle(_("Natural cooling configuration"))
        ok = chk.exec_()
        if ok:
            timeout = units.Converter.convert('minute', 'second', cp['timeout'])
            if timeout < 0:
                timeout = -1
            event = '>cool,{:.1f},{:.1f}'.format(cp['target'], timeout)
            self.insert_event(event)
        return ok
Esempio n. 34
0
 def test_integer(self):
     self.root.sete(
         'Test',
         option.ao(
             {},
             'Test',
             'Integer',
             0,
             'Integer',
         )['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 0)
     self.assertFalse(w.slider)
     iutils_testing.show(w, __name__)
    def test(self):
        self.root.sete('test', option.ao({}, 'test', 'Button')['test'])
        # Test with short reply
        self.root['test'] = 'test text'
        widget = self.wgGen()
        msgBox = widget._msgBox()
        self.assertEqual(msgBox.informativeText(), 'test text')
        # Try with long reply
        self.root['test'] = 'test text\n' * 100
        widget.current = self.root['test']
        msgBox = widget._msgBox()
        self.assertTrue(str(msgBox.informativeText()).startswith('test text'))
        self.assertEqual(msgBox.detailedText(), self.root['test'])

        iutils_testing.show(widget, __name__)
Esempio n. 36
0
 def test_MIN_MAX_int(self):
     self.root.sete(
         'Test',
         option.ao({},
                   'Test',
                   'Integer',
                   59298,
                   'Integer bounds',
                   min=0,
                   max=59298,
                   step=388)['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 59298)
     self.assertTrue(w.slider)
     iutils_testing.show(w, __name__)
Esempio n. 37
0
def getCharacteristicShapes(test, cols):
    """Returns the characteristic shapes of a test supporting them"""
    sh = {}
    if test[fprv.Tipo_Prova] not in [etp.ProvinoSingolo, etp.ProvinoR, etp.ProvinoL, etp.ProvinoDoppioCompleto]:
        return sh
    vt = numpy.array(cols[fimg.Tempo]).astype('float')
    vT = numpy.array(cols[fimg.Temp]).astype('float')
    logging.debug(vT)
    for i, name in enumerate('Temp_Sint,Temp_Rammoll,Temp_Sfera,Temp_Mezza_Sfera,Temp_Fusione'.split(',')):
        r = test[getattr(fprv, name)]
        if r == None:
            continue
        # Point as temperature
        if r > 0:
            v = vT  # Search on temp. vector
        # Point as -time
        else:
            r = -r 	# Turn positive
            v = vt  # Search on time vector
        d = numpy.abs(v - r)
        idx = numpy.where(d == d.min())[0][0]
        idx = int(idx)
        logging.debug('Where:', r, idx)
        if idx == 0:
            t = 'None'
            T = 'None'
            point = 'None'
            idx = 'None'
        else:
            t = float(vt[idx])
            T = float(vT[idx])
        hnd = shm4[name]
        d = shm4d[hnd]
        ao(sh, hnd, 'Meta', {
           'time': t, 'temp': T, 'value': 'None'}, d, priority=100 + i)
    return sh
Esempio n. 38
0
    def test_get_rescan(self):
        # Notify dev1, dev2 are really served
        self.ds.ServedClasses = [device.Device]
        device.Device.set_available_devices(['dev1', 'dev2'])
        self.ds.get_rescan()
        self.assertEqual(len(self.ds.devices), 2)

        self.ds.sete(
            'scan_DummyServedDevice',
            ao({}, 'scan_DummyServedDevice', 'Boolean',
               current=True)['scan_DummyServedDevice'])
        self.ds.ServedClasses = [DummyServedDevice]
        DummyServedDevice.set_available_devices(['dummy'])
        #       # This get_rescan purge dev1, dev2 as they are not officially served
        self.ds.get_rescan()
        self.assertEqual(len(self.ds.devices), 1)
        self.assertEqual(self.ds.devices[0]['fullpath'], '/srv/dummy/')
Esempio n. 39
0
 def test(self):
     self.root.sete('val', option.ao({}, 'val', 'Time')['val'])
     w = self.wgGen()
     self.assertAlmostEqual(w.delta, self.shift, delta=self.tol)
     # Server-side update
     t = time() + 60
     self.root['val'] = t
     w.get()
     self.assertAlmostEqual(w.current, t, delta=self.tol)
     self.assertAlmostEqual(self.root['val'], t, delta=self.tol)
     g = w.twg.dateTime().toMSecsSinceEpoch() / 1000.
     self.assertAlmostEqual(g, t + self.shift, delta=self.tol)
     # User editing
     t = time() + 120
     qdt = QtCore.QDateTime()
     qdt.setMSecsSinceEpoch(t * 1000)
     w.edited(qdt)
     self.assertAlmostEqual(w.current, t - self.shift, delta=self.tol)
     self.assertAlmostEqual(
         self.root['val'], t - self.shift, delta=self.tol)
 def test(self):
     self.root.sete('val', option.ao({}, 'val', 'Time')['val'])
     w = self.wgGen()
     self.assertAlmostEqual(w.delta, self.shift, delta=self.tol)
     # Server-side update
     t = time() + 60
     self.root['val'] = t
     w.get()
     self.assertAlmostEqual(w.current, t, delta=self.tol)
     self.assertAlmostEqual(self.root['val'], t, delta=self.tol)
     g = w.twg.dateTime().toMSecsSinceEpoch() / 1000.
     self.assertAlmostEqual(g, t + self.shift, delta=self.tol)
     # User editing
     t = time() + 120
     qdt = QtCore.QDateTime()
     qdt.setMSecsSinceEpoch(t * 1000)
     w.edited(qdt)
     self.assertAlmostEqual(w.current, t - self.shift, delta=self.tol)
     self.assertAlmostEqual(self.root['val'],
                            t - self.shift,
                            delta=self.tol)
Esempio n. 41
0
    def convert(self, frm='ImageM3', max_num_images=-1):
        """Extract a Misura 3 test and export into a Misura 4 test file"""
        conn, cursor = m3db.getConnectionCursor(self.dbpath)
        outFile = self.outFile
        zt = time()
        log_ref = reference.Log(outFile, '/', server_dict['log'])

        def log(msg, priority=10):
            # TODO: check zerotime
            log_ref.commit([[time() - zt, (priority, msg)]])

        log('Importing from %s, id %s' % (self.dbpath, self.tcode))
        log('Conversion Started at ' + 
            datetime.now().strftime("%H:%M:%S, %d/%m/%Y"))
        log('Conversion Parameters: \n\tImages: %r, \n\tUpdate: %r, \n\tKeep Images: %r, \n\tImage Format: %r' % (
            self.img, self.force, self.keep_img, frm))

        self.progress = 11
        # Heating cycle table
        cycle = m3db.getHeatingCycle(self.test)
        self.progress = 12

        # ##
        # CONFIGURATION
        tree = deepcopy(tree_dict)
        # Create instrument dict
        instr = m3db.getInstrumentName(self.test[m3db.fprv.Tipo_Prova])
        tree[instr] = deepcopy(instr_tree)
        if instr == 'hsm':
            tree[instr]['sample0'] = deepcopy(hsm_smp_tree)
        else:
            tree[instr]['sample0'] = deepcopy(smp_tree)
        # Get a configuration proxy
        tree = option.ConfigurationProxy(tree, readLevel=5, writeLevel=5)
        instrobj = getattr(tree, instr)
        tree['runningInstrument'] = instr
        tree['lastInstrument'] = instr
        instrobj['name'] = instr
        # Sample
        smp = instrobj.sample0
        smp['name'] = self.test[m3db.fprv.Desc_Prova]

        # Set ROI
        roi = [0, 0, 640, 480]
        if self.tcode.endswith('L'):
            roi[2] = 320.
        elif self.tcode.endswith('R'):
            roi[0] = 320.
            roi[2] = 320.
        smp['roi'] = roi

        # Measure
        tid = self.dbpath + '|' + self.tcode
        tdate0 = self.test[m3db.fprv.Data]
        zerotime = mktime(tdate0.timetuple())
        tdate = tdate0.strftime("%H:%M:%S, %d/%m/%Y")
        logging.debug(self.test[m3db.fprv.Data].strftime("%H:%M:%S, %d/%m/%Y"))
        instrobj.measure['zerotime'] = zerotime
        instrobj.measure['name'] = self.test[m3db.fprv.Desc_Prova]
        instrobj.measure['comment'] = self.test[m3db.fprv.Note]
        instrobj.measure['date'] = tdate
        instrobj.measure['id'] = tid
        uid = hashlib.md5(self.dbpath + '|' + self.tcode).hexdigest()
        instrobj.measure['uid'] = uid
        instrobj['zerotime'] = zerotime

        # Kiln
        tree.kiln['curve'] = cycle
        tree.kiln['Regulation_Kp'] = self.test[m3db.fprv.Pb]
        tree.kiln['Regulation_Ki'] = self.test[m3db.fprv.ti]
        tree.kiln['Regulation_Kd'] = self.test[m3db.fprv.td]

        # Create the hierarchy
        create_tree(outFile, tree)

        # ##
        # GET THE ACTUAL DATA
        header, columns = m3db.getHeaderCols(self.test[m3db.fprv.Tipo_Prova], self.tcode)
        rows = np.array(self.rows)
        self.rows = rows
        logging.debug(header, columns, len(rows[0]), instr)
        instr_path = '/' + instr
        smp_path = instr_path + '/sample0'

        # TODO: Check conf node (???)
    # 	if not hasattr(outFile.root,'conf'):
    # 		outFile.close()
    # 		os.remove(outpath)
    # 		return convert(dbpath, tcode, outdir, img,force, keep_img,frm)

        self.progress = 13

        arrayRef = {}
        timecol = rows[:, m3db.fimg.Tempo].astype('float')
        timecol, unidx = np.unique(timecol, return_index=True)
        # Set first point as zero time
        timecol -= timecol[0]
        ini_area = 0
        # Convert data points
        for i, col in enumerate(header):
            if self.interrupt:
                self.cancel()
                return False
            if col == 't':
                data = timecol
                continue
            if columns[i] >= rows.shape[1]:
                logging.debug("Skipping undefined column. Old db?", columns[i])
                continue
            data = rows[:, columns[i]].astype('float')[unidx]
            # Skip invalid data
            if np.isnan(data).all():
                continue
            # Unit and client-side unit
            unit = False
            csunit = False
            if col == 'd' or 'Percorso' in col:
                data = data / 1000.
                unit = 'percent'
                csunit = 'micron'
            elif col in ['h', 'soft']:
                data = data / 100.
                unit = 'percent'
                csunit = 'micron'
            elif col == 'A':
                data *= -1
                ini_area = data[0]
                unit = 'percent'
                csunit = 'micron^2'
            elif col == 'P':
                data = data / 10.
                unit = 'micron'
            elif col == 'w':
                logging.debug(data)
                data = data / 200.
                unit = 'micron'
            if col in ['T', 'P', 'S']:
                arrayRef[col] = reference.Array(outFile, '/summary/kiln', kiln_dict[col])
            else:
                opt = ao({}, col, 'Float', 0, col, attr=['History', 'Hidden'])[col]
                if unit:
                    opt['unit'] = unit
                if csunit:
                    opt['csunit'] = csunit
                instrobj.sample0.sete(col, opt)
                arrayRef[col] = reference.Array(outFile, '/summary' + smp_path, opt)
            # Recreate the reference so the data is clean
            arrayRef[col].dump()
            path = arrayRef[col].path
            base_path = path[8:]
            # Create hard links
            if not outFile.has_node(base_path):
                outFile.link(base_path, path)
            ref = arrayRef[col]
            ref.append(np.array([timecol, data]).transpose())
        outFile.flush()

        self.progress = 20
        # ##
        # ASSIGN INITIAL DIMENSION
        dim = set(['d', 'h', 'w', 'camA', 'camB']).intersection(
            set(header))
        ini0 = self.test[m3db.fprv.Inizio_Sint]
        initialDimension = 0
        for d in dim:
            if not arrayRef.has_key(d):
                continue
            if d == 'h':
                ini1 = 3000.
            elif d == 'A':
                ini1 = ini_area
            elif d == 'w':
                ini1 = 2000.
            elif d in ['d', 'camA', 'camB']:
                ini1 = ini0 * 100.
            path = arrayRef[d].path
            outFile.set_attributes(path, attrs={'initialDimension': ini1,
                                                'percent': d not in ['camA', 'camB', 'w']})
            # Sets the sample main initial dimension for future storage
            if d in ['d', 'h']:
                initialDimension = ini1
        smp['initialDimension'] = initialDimension
        outFile.flush()

        self.progress = 21
        log('Converted Points: %i\n' % (len(rows) - 1) * len(header))
        ######
        # Final configuration adjustment and writeout
        ######
        elapsed = float(timecol[-1])
        instrobj.measure['elapsed'] = elapsed
        print 'final timecol', timecol[0], timecol[-1]
        # Get characteristic shapes
        if instr == 'hsm':
            sh = m3db.getCharacteristicShapes(self.test, rows.transpose())
            print 'got characteristic shapes', sh
            instrobj.sample0.desc.update(sh)

        # ##
        # IMAGES
        imgdir = os.path.join(os.path.dirname(self.dbpath), self.icode)
        if os.path.exists(imgdir) and self.img and (instr in ['hsm', 'drop', 'post']):
            omg = self.append_images(imgdir, frm, max_num_images)
            if not omg:
                if self.interrupt:
                    return False
                else:
                    log('ERROR Appending images')


        # Write conf tree
        outFile.save_conf(tree.tree())
        outFile.set_attributes('/conf', attrs={'version': '3.0.0',
                                'zerotime': zerotime,
                                'elapsed': elapsed,
                                'instrument': instr,
                                'date': tdate,
                                'serial': hashlib.md5(self.dbpath).hexdigest(),
                                'uid': uid })
        self.progress = 99
        log('Appending to Misura database')
        outFile.close()
        indexer.Indexer.append_file_to_database(self.m4db, self.outpath)
        log('Conversion ended.')
        self.progress = 100

        return self.outpath
Esempio n. 42
0
import m3db

valid_chars = "-_. %s%s" % (string.ascii_letters, string.digits)

# Heating curve point
HeatingCyclePoint = {
    't': tables.Float32Col(pos=1),
    'T': tables.Float32Col(pos=2),
    'chk': tables.BoolCol(pos=3)
}

base_dict = dataimport.base_dict()

measure_dict = dataimport.measure_dict()
ao(measure_dict, 'maxT', 'Meta', name='Maximum temperature')
ao(measure_dict, 'end', 'Meta', name='End of test')
ao(measure_dict, 'maxHeatingRate', 'Meta', name='Max heating rate')
ao(measure_dict, 'coolingDuration', 'Meta', name='Cooling duration')
ao(measure_dict, 'maxCoolingRate', 'Meta', name='Max cooling rate')

ao(measure_dict, 'scrEnd', 'Script', "mi.Point(idx=-1)", parent='end')
ao(measure_dict, 'scrMaxT', 'Script', """i,t,T=mi.Max('T')
mi.t(t)
mi.T(T)
""", parent='maxT')
ao(measure_dict, 'scrMaxHeatingRate', 'Script', """
print 'scrMaxHeatingRate'
T1=kiln.TimeDerivative('T')
if len(T1)<10: mi.Exit()
rate=max(T1)
 def test(self):
     self.root.sete('test', option.ao({}, 'test', 'Boolean', False, attr=['ReadOnly'])['test'])
     # Test with short reply
     widget = self.wgGen()
     iutils_testing.show(widget, __name__)
 def test_MIN_MAX(self):
     self.root.sete(
         'Test', option.ao({}, 'Test', 'Integer', 5, min=-10,  max=10)['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 5)
     self.assertTrue(w.slider)
 def test_integer(self):
     self.root.sete('Test', option.ao({}, 'Test', 'Integer')['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 0)
     self.assertFalse(w.slider)
     iutils_testing.show(w, __name__)
 def test_units(self):
     self.root.sete(
         'Test', option.ao({}, 'Test', 'Float', units='second')['Test'])
     w = self.wgGen()
     self.assertEqual(w.current, 0)
     self.assertFalse(w.slider)
 def test_Properties(self):
     self.root.sete(
         'Test', option.ao({}, 'Test', 'Float', current=120, unit='second', precision=4)['Test'])
     w = self.wgGen()
     w.lay.addWidget(w.label_widget)
     iutils_testing.show(w, __name__)
 def setUp(self):
     self.root = option.ConfigurationProxy()
     self.root.sete(
         'name', option.ao({}, 'name', 'String', 'object name')['name'])
 def test_zero(self):
     self.root.sete('Test', option.ao({}, 'Test', 'Progress')['Test'])
     widget = self.wgGen('Test')
     self.assertEqual(widget.current, 0)
     iutils_testing.show(widget, __name__)
 def test_more(self):
     self.root.sete(
         'Test', option.ao({}, 'Test', 'Progress', current=3, max=10)['Test'])
     widget = self.wgGen('Test')
     iutils_testing.show(widget, __name__)
 def test_String(self):
     self.root.sete('test', option.ao({}, 'test', 'String')['test'])
     widget = self.wgGen()
     iutils_testing.show(widget, __name__)
 def test_TextArea(self):
     self.root.sete('test', option.ao({}, 'test', 'TextArea')['test'])
     widget = self.wgGen()
     iutils_testing.show(widget, __name__)