示例#1
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
    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()
示例#3
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
示例#4
0
 def __init__(self, conf=option.ConfigurationProxy(), linked=None, ref=True, idx=-1):
     self.conf = conf
     self.ref = ref
     self.linked = linked
     self.m_style = False
     self.m_marker = False
     self.m_color = False
     self.children = collections.OrderedDict()  # children datasets
     self._name = 'sample'
     self.idx = idx
     self.parent = False
    def setUp(self):
        from misura.droid import server

        self.server = server.MainServer()
        self.server_proxy = option.ConfigurationProxy(self.server.tree()[0])
        self.instr = self.server_proxy.flex
        self.instr = self.server.flex
        self.instr.init_instrument = lambda *foo: True
        self.main_window = acquisition.MainWindow()

        self.calls_counter = {}
示例#6
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()
示例#7
0
 def __init__(self, params):
     base.LinkedFileBase.__init__(self, params)
     self.samples = []
     """List of samples contained in this file"""
     self.prefix = ''
     """Dataset prefix"""
     self.version = -1
     """SharedFile version"""
     self.conf = option.ConfigurationProxy()
     """Additional configuration parameters"""
     self.instr = option.ConfigurationProxy()
     """Instrument configuration"""
     self.cycle = []
     """Thermal cycle"""
     self.header = []
     """Available column names"""
     self.name = 'linkedfile'
     self.instrument = False
     """Instrument which produced the file"""
     self.title = 'default'
     """File title"""
     #		self.filename=params.filename
     self.basename = os.path.basename(unicode(params.filename))
示例#8
0
 def load_conf(self):
     """Override remote load_conf method in order to receive remote tree 
     and build a local ConfigurationProxy object."""
     # The configuration of a live file is the remote server itself!
     if self.live:
         if not self.conf:
             self.conf = self.obj.root
         return True
     # Otherwise unpickle the configuration tree dict and get a
     # ConfigurationProxy for it
     d = self._decode(self.obj.conf_tree)
     logging.debug('loading conf', len(d), d.keys())
     self.conf = option.ConfigurationProxy(desc=d)
     return True
示例#9
0
 def setUpClass(cls):
     cls.root = option.ConfigurationProxy({
         'self': {'role': {'current': ['/dev/', 'default'], 'type': 'Role'},
                  'roleio': {'options': ['/dev/', 'default', 'value'], 'type': 'RoleIO'}
                  },
         'dev': {'self': {
             'name': {'type': 'String'},
             'value': {'attr': ['History'], 'type': 'Integer'},
             'value2': {'current': 2, 'attr': ['History'], 'unit': 'celsius', 'type': 'Integer'},
         }
         }
     })
     cls.root.validate()
     cls.root.dev.validate()
示例#10
0
def make_conf_proxy():
    proxy = option.ConfigurationProxy()
    proxy.add_option('ok', 'Table', [[('time', 'Float'), ('Temp', 'Float'),
                                      ('value', 'Float')], (1, 2, 3),
                                     (10, 20, 30), (100, 200, 300)])
    proxy.add_option('non_float', 'Table', [
        [('time', 'Float'), ('T', 'Float'), ('value', 'String')],
        (1, 2, 'a'),
    ])

    proxy.add_option('double_time', 'Table', [
        [('time', 'Float'), ('Time', 'Float'), ('value', 'Float')],
        (1, 2, 3),
    ])
    return proxy
 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()             
示例#13
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
示例#14
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
 def setUp(self):
     self.root = option.ConfigurationProxy()
     self.root.time = lambda: time() - self.shift
 def setUp(self):
     self.root = option.ConfigurationProxy()
示例#17
0
 def setUp(self):
     self.root = option.ConfigurationProxy()
     self.root.sete('name',
                    option.ao({}, 'name', 'String', 'object name')['name'])
示例#18
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
示例#19
0
 def setUp(self):
     registry.clear()
     from misura.droid import server
     self.root = option.ConfigurationProxy(server.BaseServer().tree()[0])
     registry.obj = self.root