def _checksafe(self): if fabs(self._attached_mth1.read( 0) - self.safe_position) > self._attached_mth1.precision: raise NicosError(self, 'MTH1 has not reached a safe position') if fabs(self._attached_mth2.read( 0) - self.safe_position) > self._attached_mth2.precision: raise NicosError(self, 'MTH2 has not reached a safe position')
def _stop(self, stopmode=KEEP_ACTION): self.log.debug('stop: StopMode : %d', stopmode) if hasattr(self._caressObject, 'stop_module'): result = self._caress_guard(self._caressObject.stop_module, stopmode, self.cid) if result in [(CARESS.OK, ACTIVE), (CARESS.OK, ACTIVE1)]: raise NicosError(self, 'Could not stop the module') else: result = self._caress_guard(self._caressObject.stop_module_orb, stopmode, self.cid) if result in [(0, ACTIVE), (0, ACTIVE1)]: raise NicosError(self, 'Could not stop the module')
def setDataFromFile(self, filename, tag, uid=None, display=True): """Load data array from file and dispatch to live widgets using ``setData``. Do not use caching if uid is ``None``. """ try: array = ReaderRegistry.getReaderCls(tag).fromfile(filename) except KeyError: raise NicosError('Unsupported fileformat %r' % tag) if array is not None: self.setData(array, uid, display=display) else: raise NicosError('Cannot read file %r' % filename)
def fromfile(cls, filename): ndim = 254 ndet = 80 sizes = (ndet, ndim) corrData = DataParser.ReadCorrectionFile( findResource(cls.correctionfile)) with open(filename, 'r', encoding='utf-8') as f: if not f.readline().startswith('QMesyDAQ CARESS Histogram File'): raise NicosError('File is not a CARESS histogram file.') for line in f: if line.startswith('Resosteps'): resosteps = int(line.split()[1]) elif line.startswith('2Theta start'): startpos = float(line.split()[2]) elif line.startswith('Comment'): for p in line.replace(' = ', '=').replace(' x ', 'x').split()[1:]: k, v = p.split('=') if k == 'detsampledist': detsampledist = float(v) thetaRaw = DataParser.ThetaInitial(startpos, resosteps, ndet) thetaCorr = DataParser.ThetaModified(thetaRaw, corrData, resosteps, ndet) data = DataParser.CaressFormat(filename, sizes[1], sizes[0])[-1] return np.sum(DataParser.RingStraight( thetaCorr, thetaRaw, DataParser.VertCalibIntensCorr(data, corrData, resosteps, ndet, ndim), resosteps, ndet, ndim, detsampledist), axis=1)
def __init__(self, positions, firstmoves=None, multistep=None, detlist=None, envlist=None, preset=None, scaninfo=None, subscan=False): from nicos.devices.tas import TAS inst = session.instrument if not isinstance(inst, TAS): raise NicosError('cannot do a Q scan, your instrument device ' 'is not a triple axis device') self._xindex = 0 Scan.__init__(self, [inst], positions, [], firstmoves, multistep, detlist, envlist, preset, scaninfo, subscan) if inst.scanmode == 'DIFF': self._envlist[0:0] = [ inst._attached_mono, inst._attached_psi, inst._attached_phi ] else: self._envlist[0:0] = [ inst._attached_mono, inst._attached_ana, inst._attached_psi, inst._attached_phi ] if inst in self._envlist: self._envlist.remove(inst)
def doReset(self): BaseSequencer.doReset(self) for d in self._adevs: d.reset() session.delay(2) if self.doStatus()[0] == status.OK: raise NicosError(self, 'cannot reset')
def _read(self): if not self.cid: raise InvalidValueError(self, 'Connection lost to CARESS') if hasattr(self._caressObject, 'read_module'): # result = self._caressObject.read_module(0x80000000, self.cid) result, state, val = self._caressObject.read_module(0, self.cid) if result != CARESS.OK: raise CommunicationError( self, 'Could not read the CARESS module: %d' % self.cid) if hasattr(val, 'f'): return (state, val.f) return ( state, val.l, ) else: _ = () self.log.debug('read module: %d', self.cid) l, result = self._caressObject.read_module_orb(0, self.cid, _) self.log.debug('read_module: %d, %r', l, result) if l != 0: raise CommunicationError( self, 'Could not read the CARESS module: %d' % self.cid) if result[0].value() != self.cid: raise CommunicationError( self, 'Answer from wrong module!: %d %r' % (self.cid, result[0])) state = result[1].value() if state == OFF_LINE: raise NicosError(self, 'Module is off line!') if result[2].value() < 1: raise InvalidValueError(self, 'No position in data') return state, result[4].value()
def doReference(self, *args): refswitch = args[0] if args and isinstance(args[0], string_types) \ else None if self.doStatus()[0] == status.BUSY: self.stop() self.wait() # The sixfold and triple cards will be reset as whole card, so values # of all channels will reset !!! # self.reset() # self.wait() if self.doStatus()[0] == status.OK: if self._refcontrol and self._refcontrol.is_alive(): self._refcontrol.join() self._refcontrol = None if self._refcontrol is None: threadname = 'referencing %s' % self self._refcontrol = createThread(threadname, self._reference, args=(refswitch, )) session.delay(0.2) else: raise NicosError(self, 'in error or busy state')
def _reference(self, refswitch=None): """Drive motor to reference switch.""" self.log.debug('referencing: %s', refswitch) # init referencing self._stoprequest = 0 # if reference switch is explicitly given only drive to given limit # switch fullref = refswitch is None if refswitch is None: refswitch = self.refswitch if refswitch == self.refswitch: refdirection = self.refdirection else: # refdirection must be opposite from configured if self.refdirection == 'upper': refdirection = 'lower' else: refdirection = 'upper' self.log.debug('switch %s, direction %s, %s', refswitch, self.refdirection, refdirection) try: _min, _max, motspeed = self.min, self.max, self.speed self._resetlimits() self._drive_to_limit_switch(refswitch, refdirection) if fullref: if self.isAtReference(): self._move_away_from_reference(refswitch, refdirection) self.resetTimeout(0) self._move_until_referenced() if self.isAtReference(): if self.parkpos is not None: self._start(self.parkpos) if self._stoprequest == 1: raise NicosError(self, 'reference stopped by user') except NicosTimeoutError as e: self.log.error('%s occured during referencing', e) except NicosError as e: self.log.error('%s: occured during referencing', e) except Exception as e: self.log.error('%s: occured during referencing', e) finally: self.log.debug('stoprequest: %d', self._stoprequest) self.speed = motspeed self.min = _min self.max = _max if fullref: try: temp = self.read(0) self.log.info('new position of %s is now %.3f %s', self.name, temp, self.unit) if (self.abslimits[0] - self.precision) <= temp <= \ (self.abslimits[1] + self.precision): self._resetlimits() else: self.log.warning('in _referencing limits not restored ' 'after positioning') except NicosError as e: self.log.warning('error catched in finally positioning %s', e)
def _drive_to_limit_switch(self, switch, direction): self.log.debug('driving to %r switch towards %r', switch, direction) if not self.isAtReference(switch): self.log.debug('in _drive_to_limitswitch checkrefswitch') self._drive_to_reference(self.refspeed, switch, direction) if not self.isAtReference(switch): if self._stoprequest == 1: raise NicosError(self, 'limitswitch drive stopped by user')
def _readblock(self): if hasattr(self._caressObject, 'readblock_module') and \ hasattr(self._caressObject, 'readblock_params'): _type = CARESS.TypeLong _start = 0 _end = 0 try: result, _start, _end, _type = \ self._caress_guard(self._caressObject.readblock_params, READBLOCK_NORMAL, self.cid, _start, _end, _type) if result != CARESS.OK: raise CommunicationError( self, 'Could not read the CARESS ' 'module') result, _status, data = \ self._caress_guard(self._caressObject.readblock_module, READBLOCK_NORMAL, self.cid, _start, _end) if result != CARESS.OK: raise CommunicationError( self, 'Could not read the CARESS ' 'module') # self.log.warning('%r', data) return [self._width, self._height, 1] + data.al except CORBA.COMM_FAILURE as ex: raise CommunicationError( self, 'Could not read the CARESS ' 'module : %s' % (ex, )) else: _ = () result = self._caress_guard(self._caressObject.read_module_orb, 0, self.cid, _) self.log.debug('read_module: %r', result) if result[0] != 0: raise CommunicationError(self, 'Could not read the CARESS module') if result[1][0].value() != self.cid: raise NicosError( self, 'Answer from wrong module!: %d %r' % (self.cid, result[1][0])) if result[1][1].value() == OFF_LINE: raise NicosError(self, 'Module is off line!') if result[1][2].value() < 1: raise InvalidValueError(self, 'No position in data') return result[1][1].value(), result[1][4].value()
def _break(self, kind=0): if hasattr(self._caressObject, 'stop_module'): result = self._caress_guard(self._caressObject.stop_module, kind, self.cid) elif self.ismaster: result = \ self._caress_guard(self._caressObject.stop_acquisition_orb, kind) if result[0] not in [0, CARESS.OK]: raise NicosError('Could not set module into paused state!')
def _start(self, kind): if hasattr(self._caressObject, 'start_module'): result = self._caress_guard(self._caressObject.start_module, kind, self.cid, self.runnumber, 0) else: result = \ self._caress_guard(self._caressObject.start_acquisition_orb, kind, self.runnumber, 0) if result[0] not in (0, CARESS.OK): raise NicosError(self, 'Could not start the module')
def doReset(self, *args): BaseSequencer.doReset(self, *args) self._attached_block.reset() self._attached_tt.reset() self._attached_st.reset() session.delay(0.5) if self.doStatus(0)[0] != status.OK: raise NicosError(self, 'cannot reset secondary collimator lift ' 'unit')
def _stop(self, kind=0): if hasattr(self._caressObject, 'stop_module'): result = self._caress_guard(self._caressObject.stop_module, 11, self._cid) else: result = self._caress_guard(self._caressObject.stop_module_orb, 11, self._cid) if result in [(CARESS.OK, ACTIVE), (CARESS.OK, ACTIVE1), (0, ACTIVE), (0, ACTIVE1)]: raise NicosError(self, 'Could not stop the module')
def begin(self): if self.h5file is None: self.template = copy_nexus_template(self.sink.loadTemplate()) if not isinstance(self.template, dict): raise NicosError('The template should be of type dict') self.h5file = h5py.File(self._filename, 'w') self.h5file.attrs['file_name'] = numpy.string_(self._filename) tf = NXTime() self.h5file.attrs['file_time'] = numpy.string_(tf.formatTime())
def doStop(self): self.log.debug("doStop") if self._moveTo in self._mapStop: self._mapStop[self._moveTo]() else: myStatus = self.status(0) if myStatus[0] == status.OK: self.log.warning("Device already stopped.") else: raise NicosError(self, "Internal moveTo state unknown. " "Check device status.")
def _move_away_from_reference(self, refswitch, refdirection): self.log.debug('%s limit switch active', refswitch) self.steps = self.refpos if self.refstep != 0: d = abs(self.refstep / self.slope) if refdirection == 'lower': d = -d self.log.debug('move away from reference switch %f', d) self._start(self.read(0) - d) if self._stoprequest: raise NicosError(self, 'move away from reference stopped by user')
def doRead(self, maxage=0): r1 = 0 if self._attached_cover.read(maxage) == 'out' else 1 r2 = 0 if self._attached_frame.read(maxage) == 'out' else 1 if r1 and r2: raise NicosError(self, 'frame and cover in beam?!') if r1: return 'cover' elif r2: return 'frame' else: return 'open'
def _init(self, cid): try: if session.sessiontype != POLLER: if hasattr(self._caressObject, 'init_system_orb'): if not CARESSDevice._caress_initialized: self.log.debug('initialize the CARESS absdev ' 'container') if self._caressObject.init_system_orb(0)[0] in \ (0, CARESS.OK): CARESSDevice._caress_initialized = True else: raise CommunicationError( self, 'could not ' 'initialize CARESS absdev' ' container') _config = self._normalized_config() res = self._caressObject.init_module(INIT_CONNECT, cid, _config) self.log.debug('INIT_CONNECT: %r', res) if res[0] in (0, CARESS.OK): if res[1] == OFF_LINE: res = self._caressObject.init_module( INIT_REINIT, cid, _config) else: res = self._caressObject.init_module(INIT_NORMAL, cid, _config) self.log.debug('init module (Connect): %r', res) if res[0] not in (0, CARESS.OK) or res[1] == OFF_LINE: raise NicosError( self, 'Could not initialize module! (%r) %d' % ((res, ), self._device_kind())) # res = self._caressObject.init_module(INIT_REINIT, cid, _config) # self.log.debug('Init module (Re-Init): %r', res) # if res not in[(0, ON_LINE), (CARESS.OK, ON_LINE)]: # self.log.error('Init module (Re-Init): %r (%d, %s)', # res, cid, self.config) if self._device_kind() == CORBA_DEVICE: if self.absdev: res = self._caressObject.char_loadblock_module_orb( 0, cid, 1, len(self.loadblock), 16, self.loadblock) else: val = CARESS.Value(ab=self.loadblock.encode()) res = self._caressObject.loadblock_module( 0, cid, 1, len(self.loadblock), val) # 16, val) self._initialized = True if not self._is_corba_device(): CARESSDevice._used_counter += 1 except CORBA.TRANSIENT as err: raise CommunicationError( self, 'could not init CARESS module %r (%d: %s)' % (err, cid, self.config)) from err
def _query(self): result = None if _thirdparty_available: res = requests.get(_REST_URL + '/' + self.location + '/' + self.query + "/by-height/%.1f" % self.height) self.log.debug("REST-statuscode: %d", res.status_code) if res.status_code == 200: result = res.json()[MeteoStation._MAP_REST[self.query]]["value"] self._status = status.OK, '' else: errmsg = ("MeteoMunich, RESTful Webservice HTTPError %d" % res.status_code) self._status = (status.ERROR, errmsg) raise NicosError(self, errmsg) return result
def run(self): if not self._subscan and getattr(session, '_currentscan', None): raise NicosError('cannot start scan while another scan is running') # stop previous inner_count / acquisition thread if available stop_acquire_thread() session._currentscan = self # XXX(dataapi): this is too early, dataset has no number yet session.beginActionScope(self.shortDesc()) try: self._inner_run() finally: session.endActionScope() session._currentscan = None return self.dataset
def set_template(self, val): """ Sets the template from the given template modules. Parses the template using *parserclass* method parse. The parsed root, event kafka streams and device placeholders are then set. :param val: template name """ if not hasattr(self._templates, val): raise NicosError('Template %s not found in module %s' % (val, self.templatesmodule)) self.template = getattr(self._templates, val) if self.templatename != val: self._setROParam('templatename', val)
def doStart(self, target): self.log.debug('target: %r', target) timeout = 0 if hasattr(self._caressObject, 'drive_module'): val = CARESS.Value(f=target) self.log.debug('%r', val.f) result = self._caress_guard(self._caressObject.drive_module, 0, self.cid, val, timeout) if result[0] != CARESS.OK: raise NicosError(self, 'Could not start the device') else: params = [] params.append(CORBA.Any(CORBA._tc_long, self.cid)) params.append(CORBA.Any(CORBA._tc_long, 0)) # status placeholder params.append(CORBA.Any(CORBA._tc_long, 2)) # 2 values params.append(CORBA.Any(CORBA._tc_long, 5)) # type 32 bit float params.append(CORBA.Any(CORBA._tc_float, target)) params.append(CORBA.Any(CORBA._tc_float, self.precision)) params.append(CORBA.Any(CORBA._tc_long, 0)) # no next module result = self._caress_guard(self._caressObject.drive_module_orb, 0, params, 0, timeout) if result[0] != 0: raise NicosError(self, 'Could not start the device') self._setROParam('_started', True)
def _checkpower(self, onoff): on_off_str = 'on' if onoff else 'off' msg = '' if self._attached_a2_powvalunit.read(0) != onoff: msg += 'valve unit not switched "%s"; check device!' % on_off_str if self._attached_a2_lgon.read(0) != onoff: msg += ' logo device not switched "%s"; check device!' % on_off_str if self._attached_a2_press.read(0) != onoff: if onoff: msg += ' no air pressure for alpha2 changing unit; check air '\ 'pressure' else: msg += ' air pressure for alpha2 changing unit not switched '\ 'off!' if msg: raise NicosError(self, msg)
def __init__(self, *args): QFileDialog.__init__(self, *args) self.setAcceptMode(QFileDialog.AcceptOpen) self.setFileMode(QFileDialog.ExistingFiles) self.setOption(QFileDialog.DontUseNativeDialog) filterproxy = FileFilterProxyModel(self) self.setProxyModel(filterproxy) child = None # make pylint happy for child in self.children(): if isinstance(child, QLineEdit): break else: raise NicosError("QLineEdit not found in QFileDialog") child.textChanged.connect(filterproxy.setFilterWildcard) child.returnPressed.disconnect(self.accept) child.returnPressed.connect(self.on_returnPressed)
def _count(*detlist, **preset): temporary = preset.pop('temporary', False) live = preset.get('live', False) # sanitize detector list; support count(1) and count('info') detectors = [] for det in detlist: if isinstance(det, number_types): preset['t'] = det continue elif isinstance(det, string_types): preset['info'] = det # XXX continue if not isinstance(det, Measurable): raise UsageError('device %s is not a measurable device' % det) detectors.append(det) # check if manual scan is active scan = getattr(session, '_manualscan', None) if scan is not None: if detectors: raise UsageError('cannot specify different detector list ' 'in manual scan') return scan.step(**preset) # counting without detectors is not useful, but does not error out if not detectors: detectors = session.experiment.detectors if not detectors: session.log.warning('counting without detector, use SetDetectors()' ' to select which detector(s) you want to use') # check preset names for validity names = set(preset) for det in detectors: names.difference_update(det.presetInfo()) if names: session.log.warning( 'these preset keys were not recognized by any of ' 'the detectors: %s -- detectors are %s', ', '.join(names), ', '.join(map(str, detectors))) # check detector types has_sub = sum(isinstance(det, SubscanMeasurable) for det in detectors) if has_sub > 0: # XXX(dataapi): support both types if not len(detectors) == has_sub == 1: raise NicosError('cannot acquire on normal and subscan detectors') return inner_count(detectors, preset, temporary, live)
def doRead(self, maxage=0): if self.path is None: path = session.experiment.dataroot else: path = self.path try: if os.name == 'nt': free = ctypes.c_ulonglong(0) ret = ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(path), None, None, ctypes.pointer(free)) if ret == 0: raise OSError('GetDiskFreeSpaceExW call failed') return free.value / self._factor else: st = os.statvfs(path) return (st.f_frsize * st.f_bavail) / self._factor except OSError as err: raise NicosError(self, 'could not determine free space: %s' % err)
def begin(self): if self.dataset.settype == POINT and not self.h5file: self.template = copy_nexus_template(self.sink.loadTemplate()) self.h5file = h5py.File(self.startdataset.filepaths[0], 'w') self.h5file.attrs['file_name'] = numpy.string_( self.startdataset.filepaths[0]) tf = NXTime() self.h5file.attrs['file_time'] = numpy.string_(tf.formatTime()) if not isinstance(self.template, dict): raise NicosError('The template should be of type dict') # Update meta information of devices, only if not present if not self.dataset.metainfo: self.manager.updateMetainfo() self.createStructure()
def _load_preset(self, kind, preset=0): if hasattr(self._caressObject, 'load_module'): result, loaded = self._caress_guard(self._caressObject.load_module, kind, self.cid, CARESS.Value(l=preset)) self.log.debug('preset module: %r, %r', result, loaded) else: params = [] params.append(CORBA.Any(CORBA._tc_long, self.cid)) params.append(CORBA.Any(CORBA._tc_long, 0)) # status placeholder params.append(CORBA.Any(CORBA._tc_long, 1)) # 1 value params.append(CORBA.Any(CORBA._tc_long, 2)) # 32 bit int type params.append(CORBA.Any(CORBA._tc_long, preset)) params.append(CORBA.Any(CORBA._tc_long, 0)) # no next module result, loaded = self._caress_guard( self._caressObject.load_module_orb, kind, params, 0) self.log.debug('preset module: %r %r', result, loaded) if result not in [0, CARESS.OK]: raise NicosError(self, 'Could not preset module')