Пример #1
0
 def _update_sample_info(self):
     names = self.client.eval('Exp.sample.samples', None)
     if names is None:
         return
     for i in range(self._numSamples):
         name = from_maybe_utf8(names.get(i + 1, {}).get('name', ''))
         self._tableWidget.cellWidget(i, 0).setText(name)
Пример #2
0
 def _hash(self, password):
     password = to_utf8(from_maybe_utf8(password))
     if self.hashing == 'sha1':
         password = hashlib.sha1(password).hexdigest()
     elif self.hashing == 'md5':
         password = hashlib.md5(password).hexdigest()
     return password
Пример #3
0
 def addMessage(self, message):
     existing = self.errorText.text()
     message = from_maybe_utf8(message)
     if existing:
         # limit the amount of displayed lines
         new = existing.splitlines()[-20:] + [message]
         self.errorText.setText('\n'.join(new))
     else:
         self.errorText.setText(message)
Пример #4
0
    def _process(self, msgs, kwds):
        # standard logging keyword arg
        exc_info = kwds.pop('exc_info', None)
        # nicos easy keyword arg
        exc = kwds.pop('exc', None)
        if not exc_info:
            if isinstance(exc, Exception):
                exc_info = (type(exc), exc, None)
            elif exc:
                exc_info = sys.exc_info()
                # did an exception really occur?
                if exc_info[0] is None:
                    exc_info = None
        extramsgs = []
        if exc_info:
            if msgs:
                extramsgs += ['-']
            from nicos.core.errors import NicosError
            if issubclass(exc_info[0], NicosError):
                extramsgs += [exc_info[0].category + ' -', exc_info[1]]
            else:
                extramsgs += [exc_info[0].__name__ + ' -', exc_info[1]]

        if not msgs:
            msg = ''
            args = ()
        else:
            msg = msgs[0]
            if isinstance(msg, binary_type):
                msg = from_maybe_utf8(msg)
            else:
                msg = text_type(msg)
            args = msgs[1:]
        if extramsgs:
            if msg:
                msg += ' '
            msg += ' '.join(
                from_maybe_utf8(msg) if isinstance(msg, binary_type
                                                   ) else text_type(msg)
                for msg in extramsgs)
        return msg, args, exc_info
Пример #5
0
 def on_devValueChange(self, dev, value, strvalue, unitvalue, expired):
     # check expired values
     self._expired = expired
     self._lastvalue = value
     self._lastchange = currenttime()
     if self.props['maxlen'] > -1:
         self.valuelabel.setText(
             from_maybe_utf8(strvalue[:self.props['maxlen']]))
     else:
         self.valuelabel.setText(from_maybe_utf8(strvalue))
     if self._expired:
         setBothColors(self.valuelabel, (self._colorscheme['fore'][UNKNOWN],
                                         self._colorscheme['expired']))
         if self.props['showExpiration']:
             self.valuelabel.setText(NOT_AVAILABLE)
     elif not self.props['istext']:
         setBothColors(self.valuelabel, (self._colorscheme['fore'][BUSY],
                                         self._colorscheme['back'][BUSY]))
         QTimer.singleShot(1000, self._applystatuscolor)
     else:
         self._applystatuscolor()
Пример #6
0
    def _write_instr_data(self, meas, image):
        # get corresponding scan dataset with scan info if available
        stack = self.manager._stack
        if len(stack) >= 2 and isinstance(stack[-2], ScanDataset):
            scands = stack[-2]
            meas["info"] = scands.info
        else:
            meas["info"] = self.dataset.info

        sample = session.experiment.sample
        meas["sample"]["comment"] = from_maybe_utf8(sample.comment)
        meas["sample"]["timefactor"] = sample.timefactor
        meas["sample"]["thickness"] = sample.thickness
        meas["sample"]["detoffset"] = sample.detoffset

        # store device information
        devs = meas["devices"] = []
        # all available nicos devices
        devices = dict(session.devices)
        # log all devices in the dataset
        for (info, val) in zip(self.dataset.devvalueinfo,
                               self.dataset.devvaluelist):
            dev = session.getDevice(info.name)
            state, status = dev.status()
            entry = self._dict()
            entry["name"] = info.name
            entry["unit"] = info.unit
            entry["value"] = val
            entry["state"] = state
            entry["status"] = status
            devs.append(entry)
            # remove devices already logged here
            devices.pop(info.name, None)

        # log all remaining nicos devices
        for name, dev in iteritems(devices):
            if isinstance(dev, Readable):
                entry = self._dict()
                state, status = dev.status()
                entry["name"] = name
                entry["unit"] = self._devpar(name, "unit")
                entry["value"] = self._readdev(name)
                entry["state"] = state
                entry["status"] = status
                devs.append(entry)
Пример #7
0
    def writeData(self, fp, image):
        """Save in YAML format."""
        fp.seek(0)

        expdev = session.experiment
        instrdev = session.instrument

        o = AutoDefaultODict()
        instr = o['instrument']
        instr['name'] = instrdev.instrument
        instr['facility'] = instrdev.facility
        instr['operator'] = ', '.join(instrdev.operators)
        instr['website'] = instrdev.website
        instr['references'] = [AutoDefaultODict({'doi': instrdev.doi})]

        o['format']['identifier'] = self.__class__.filetype
        for obj, unit in zip(self.objects, self.units):
            o['format']['units'][obj] = unit

        exp = o['experiment']
        # TODO: use experiment number when we have it in NICOS
        exp['number'] = expdev.proposal
        exp['proposal'] = expdev.proposal
        exp['title'] = from_maybe_utf8(expdev.title)
        exp['authors'] = []
        authors = [
            {
                'name': from_maybe_utf8(expdev.users),
                'roles': ['principal_investigator']
            },
            {
                'name': from_maybe_utf8(expdev.localcontact),
                'roles': ['local_contact']
            },
        ]
        for author in authors:
            a = AutoDefaultODict()
            a['name'] = author['name']
            a['roles'] = self._flowlist(author['roles'])
            exp['authors'].append(a)

        meas = o['measurement']
        meas['number'] = self.dataset.number
        meas['unique_identifier'] = '%s/%s/%s' % (
            expdev.proposal, self.dataset.counter, self.dataset.number)

        hist = meas['history']
        hist['started'] = nice_datetime(self.dataset.started)
        hist['stopped'] = nice_datetime(currenttime())

        sample = meas['sample']['description']
        sample['name'] = from_maybe_utf8(expdev.sample.samplename)

        env = meas['sample']['environment'] = []
        stats = self.dataset.valuestats
        for (info, val) in zip(self.dataset.envvalueinfo,
                               self.dataset.envvaluelist):
            entry = self._dict()
            entry['name'] = info.name
            entry['unit'] = info.unit
            entry['value'] = val
            if info.name in stats:
                entry['mean'] = stats[info.name][0]
                entry['stddev'] = stats[info.name][1]
                entry['min'] = stats[info.name][2]
                entry['max'] = stats[info.name][3]
            env.append(entry)

        self._write_instr_data(meas, image)

        quickyaml.Dumper(width=self.max_yaml_width,
                         array_handling=self.yaml_array_handling).dump(o, fp)
        fp.flush()
Пример #8
0
    def _writeHeader(self, fp, header):
        headlines = []
        headlines.append('File_Creation_Time: %s' % asctime())
        if ('det', 'usercomment') in header:
            usercomment = header['det', 'usercomment'][1]
        elif ('det', 'info') in header:
            usercomment = header['det', 'info'][1]
        else:
            usercomment = ''
        headlines.append('Title: %s' % from_maybe_utf8(usercomment))
        headlines.append('ExperimentTitle: %s' %
                         from_maybe_utf8(header['Sample', 'samplename'][1]))
        headlines.append('ProposalTitle: %s' %
                         from_maybe_utf8(header['Exp', 'title'][1]))
        headlines.append('ProposalNr: %s' % header['Exp', 'proposal'][1])

        headlines.append('ExperimentTeam: %s' %
                         from_maybe_utf8(header['Exp', 'users'][1]))
        headlines.append('LocalContact: %s' %
                         from_maybe_utf8(header['Exp', 'localcontact'][1]))
        headlines.append('StartDate: %s' %
                         strftime('%d.%m.%Y', self._local_starttime))
        headlines.append('StartTime: %s' %
                         strftime('%H:%M:%S', self._local_starttime))
        if header['det', 'mode'][1] == 'time':
            headlines.append('TOF_MMode: Total_Time')
            headlines.append('TOF_TimePreselection: %d' %
                             header['det', 'preset'][0])
        else:
            headlines.append('TOF_MMode: Monitor_Counts')
            headlines.append('TOF_CountPreselection: %d' %
                             header['det', 'preset'][0])

        headlines.append('TOF_TimeInterval: %f' %
                         header['det', 'timeinterval'][0])
        headlines.append('TOF_ChannelWidth: %s' %
                         header['det', 'channelwidth'][1])
        headlines.append('TOF_TimeChannels: %s' %
                         header['det', 'timechannels'][1])
        headlines.append('TOF_NumInputs: %s' % header['det', 'numinputs'][1])
        headlines.append('TOF_Delay: %s' % header['det', 'delay'][1])
        headlines.append('TOF_MonitorInput: %s' %
                         header['det', 'monitorchannel'][1])

        headlines.append('TOF_Ch5_90deg_Offset: %s' %
                         header['ch', 'ch5_90deg_offset'][1])
        chwl = header['chWL', 'value'][0]
        guess = round(4.0 * chwl * 1e-6 * calc.alpha /
                      (calc.ttr * header['det', 'channelwidth'][0]))
        headlines.append('TOF_ChannelOfElasticLine_Guess: %d' % guess)

        headlines.append('HV_PowerSupplies: hv0-2: %s V, %s V, %s V' % tuple([
            header.get(('hv%d' % i, 'value'), (0, 'unknown'))[1]
            for i in range(3)
        ]))
        headlines.append('LV_PowerSupplies: lv0-7: %s' % ', '.join([
            header.get(('lv%d' % i, 'value'), (0, 'unknown'))[1]
            for i in range(8)
        ]))

        slit_pos = header['slit', 'value'][0]
        headlines.append('SampleSlit_ho: %.2f' % slit_pos[0])
        headlines.append('SampleSlit_hg: %.2f' % slit_pos[2])
        headlines.append('SampleSlit_vo: %.2f' % slit_pos[1])
        headlines.append('SampleSlit_vg: %.2f' % slit_pos[3])

        headlines.append('Guide_config: %s' % header['ngc', 'value'][1])
        if header['ngc', 'value'][1] == 'focus':
            headlines.append('ng_focus: %d %d %d %d' % tuple(
                header.get(('ng_focus', 'value'),
                           ([0, 0, 0, 0], '0 0 0 0'))[0]))
        headlines.append('Chopper_Speed: %s %s' % header['ch', 'value'][1:3])
        headlines.append('Chopper_Wavelength: %s %s' %
                         header['chWL', 'value'][1:3])
        headlines.append('Chopper_Ratio: %s' % header['chRatio', 'value'][1])
        headlines.append('Chopper_CRC: %s' % header['chCRC', 'value'][1])
        headlines.append('Chopper_SlitType: %s' % header['chST', 'value'][1])
        headlines.append('Chopper_Delay: %s' % header['chdelay', 'value'][1])

        for i in range(4):
            headlines.append('Chopper_Vac%d: %s' %
                             (i, header['vac%d' % i, 'value'][1]))

        headlines.append(
            'Goniometer_XYZ: %s %s %s %s %s %s' %
            (header['gx', 'value'][1:3] + header['gy', 'value'][1:3] +
             header['gz', 'value'][1:3]))
        headlines.append(
            'Goniometer_PhiCxCy: %s %s %s %s %s %s' %
            (header['gphi', 'value'][1:3] + header['gcx', 'value'][1:3] +
             header['gcy', 'value'][1:3]))
        headlines.append('FileName: %s' % self._datafile.filepath)
        headlines.append('SavingDate: %s' % strftime('%d.%m.%Y'))
        headlines.append('SavingTime: %s' % strftime('%H:%M:%S'))

        fp.seek(0)
        for line in headlines:
            fp.write(to_utf8('%s\n' % line))
        fp.flush()
Пример #9
0
 def __init__(self, parent, designMode=False, **kwds):
     self._designMode = designMode
     SqueezedLabel.__init__(self, parent, designMode, **kwds)
     if designMode:
         self.setText('(value display)')
     self._callback = lambda value, strvalue: from_maybe_utf8(strvalue)
Пример #10
0
 def addText(self, text, fmt=None):
     textcursor = self.textCursor()
     textcursor.movePosition(self.text_curson_position)
     textcursor.setCharFormat(fmt or std)
     textcursor.insertText(from_maybe_utf8(text))
Пример #11
0
    def putMetainfo(self, metainfo):
        if ('det', 'usercomment') in metainfo:
            usercomment = metainfo['det', 'usercomment'][1]
        elif ('det', 'info') in metainfo:
            usercomment = metainfo['det', 'info'][1]
        else:
            usercomment = ''
        self._tof.write_title(from_maybe_utf8(usercomment))
        self._tof.write_experiment_title(
            from_maybe_utf8(metainfo['Sample', 'samplename'][1]))
        self._tof.write_proposal_title(
            from_maybe_utf8(metainfo['Exp', 'title'][1]))
        self._tof.write_proposal_number(
            from_maybe_utf8(metainfo['Exp', 'proposal'][1]))

        self._tof.write_mode('Total_Time' if metainfo['det', 'mode'][1] ==
                             'time' else 'MonitorCounts')

        slit_pos = metainfo['slit', 'value'][0]
        self._tof.write_slit_ho(slit_pos[0])
        self._tof.write_slit_hg(slit_pos[1])
        self._tof.write_slit_vo(slit_pos[2])
        self._tof.write_slit_vg(slit_pos[3])

        self._tof.write_hv_power_supplies('hv0-2: %s V, %s V, %s V' % tuple([
            metainfo.get(('hv%d' % i, 'value'), (0, 'unknown'))[1]
            for i in range(3)
        ]))
        self._tof.write_lv_power_supplies('lv0-7: %s' % ', '.join([
            metainfo.get(('lv%d' % i, 'value'), (0, 'unknown'))[1]
            for i in range(8)
        ]))
        self._tof.write_goniometer_xyz(
            '%s %s %s %s %s %s' %
            (metainfo['gx', 'value'][1:3] + metainfo['gy', 'value'][1:3] +
             metainfo['gz', 'value'][1:3]))
        self._tof.write_goniometer_phicxcy(
            '%s %s %s %s %s %s' %
            (metainfo['gphi', 'value'][1:3] + metainfo['gcx', 'value'][1:3] +
             metainfo['gcy', 'value'][1:3]))

        self._tof.write_local_contact(
            from_maybe_utf8(metainfo['Exp', 'localcontact'][1]))
        self._tof.write_user(from_maybe_utf8(metainfo['Exp', 'users'][1]))

        self._tof.write_chopper_vacuum(metainfo['vac0', 'value'][1],
                                       metainfo['vac1', 'value'][1],
                                       metainfo['vac2', 'value'][1],
                                       metainfo['vac3', 'value'][1])
        self._tof.write_chopper_speed(' '.join(metainfo['ch', 'value'][1:3]))
        self._tof.write_chopper_ratio(metainfo['chRatio', 'value'][1])
        self._tof.write_chopper_crc(metainfo['chCRC', 'value'][1])
        self._tof.write_chopper_slittype(metainfo['chST', 'value'][1])
        self._tof.write_chopper_delay(metainfo['chdelay', 'value'][1])
        self._tof.write_chopper_tof_time_preselection(metainfo['det',
                                                               'preset'][0])
        self._tof.write_chopper_tof_num_inputs(metainfo['det', 'numinputs'][1])
        self._tof.write_chopper_ch5_90deg_offset(
            metainfo['ch', 'ch5_90deg_offset'][1])
        self._tof.write_chopper_num_of_channels(metainfo['det',
                                                         'timechannels'][1])
        self._tof.write_chopper_num_of_detectors(metainfo['det',
                                                          'numinputs'][1])

        self._tof.write_wavelength(' '.join(metainfo['chWL', 'value'][1:3]))
        chwl = metainfo['chWL', 'value'][0]
        guess = round(4.e-6 * chwl * calc.alpha /
                      (calc.ttr * metainfo['det', 'channelwidth'][0]))
        self._tof.write_monitor_elastic_peak('%d' % guess)
        self._tof.write_monitor_tof(metainfo['det', 'channelwidth'][1],
                                    metainfo['det', 'timechannels'][1],
                                    metainfo['det', 'delay'][1])
        self._tof.write_monitor_tof_time_interval(metainfo['det',
                                                           'timeinterval'][1])
        self._tof.write_monitor_input(metainfo['det', 'monitorchannel'][1])
        self._tof.write_detinfo(self.detector._detinfo[2:])
        self._tof.write_sample_description(
            from_maybe_utf8(metainfo['Sample', 'samplename'][1]))
Пример #12
0
 def _hash(self, password):
     password = to_utf8(from_maybe_utf8(password))
     return hashlib.md5(password).hexdigest()