コード例 #1
0
    def doInit(self, mode):
        if self.fallback in self.mapping:
            raise ConfigurationError(
                self, 'Value of fallback parameter is '
                'not allowed to be in the mapping!')
        self._devices = {
            dev.name: dev
            for dev in (self._attached_anodes + self._attached_banodes +
                        self._attached_cathodes + self._attached_window)
        }

        if len(self._attached_anodes) != len(self._attached_banodes) + 1:
            raise ConfigurationError(
                self, 'Number of anode devices must be '
                'the number of boundary anodes + 1: %d, '
                '%d' % (len(self.anodes), len(self.banodes)))
        # if not self.relax_mapping:
        #     self.valuetype = oneof(*sorted(self.mapping, key=num_sort))

        for value in sorted(self.mapping, key=num_sort):
            try:
                self.valuetype(value)
            except ValueError as err:
                raise ConfigurationError(
                    self, '%r not allowed as key in mapping. %s' %
                    (value, err)) from err
コード例 #2
0
ファイル: detector.py プロジェクト: ess-dmsc/nicos
    def doInit(self, _mode):
        self._masters = []
        self._slaves = []
        self._channel_presets = {}
        self._postprocess = []
        self._postpassives = []

        for tup in self.postprocess:
            if tup[0] not in session.configured_devices:
                self.log.warning(
                    "device %r not found but configured in "
                    "'postprocess' parameter. No "
                    "post processing for this device. Please "
                    "check the detector setup.", tup[0])
                continue
            postdev = session.getDevice(tup[0])
            img_or_passive_devs = [session.getDevice(name) for name in tup[1:]]
            if not isinstance(postdev, PostprocessPassiveChannel):
                raise ConfigurationError("Device '%s' is not a "
                                         "PostprocessPassiveChannel" %
                                         postdev.name)
            if postdev not in self._channels:
                raise ConfigurationError("Device '%s' has not been configured "
                                         "for this detector" % postdev.name)
            for dev in img_or_passive_devs:
                if dev not in self._channels:
                    raise ConfigurationError("Device '%s' has not been "
                                             "configured for this detector" %
                                             dev.name)
                elif isinstance(dev, PassiveChannel):
                    self._postpassives.append(dev)
            self._postprocess.append((postdev, img_or_passive_devs))
コード例 #3
0
 def _d(self, maxage=0):
     crystal = self._crystal()
     if crystal:
         p = crystal.get(self.plane, None)
         if p:
             return p[0]
         raise ConfigurationError('No plane of the crystal set.')
     raise ConfigurationError('No crystal set.')
コード例 #4
0
ファイル: pulse.py プロジェクト: umithardal/nicos
 def doInit(self, mode):
     if not self._attached_moveable.isAllowed(self.onvalue)[0]:
         raise ConfigurationError(
             self, "'onvalue' is not allowed for the "
             "'%s' device" % self._attached_moveable)
     if not self._attached_moveable.isAllowed(self.offvalue)[0]:
         raise ConfigurationError(
             self, "'offvalue' is not allowed for the "
             "'%s' device" % self._attached_moveable)
     self.valuetype = oneof(self.offvalue, self.onvalue)
コード例 #5
0
 def doInit(self, mode):
     units = set(d.unit for d in self._adevs.values())
     if len(units) != 1:
         raise ConfigurationError(
             self, 'different units for L, d and sdd '
             '(%s vs %s vs %s)' %
             (self._attached_l.unit, self._attached_d.unit,
              self._attached_sdd.unit))
     if 'mm' not in units:
         raise ConfigurationError(
             self, "attached devices units have to be "
             "'mm'")
コード例 #6
0
 def doStart(self, target):
     crystal = self._crystal()
     if not crystal:
         raise ConfigurationError(self, 'Not valid setup')
     plane = crystal.get(self.plane, None)
     if not plane:
         raise ConfigurationError(self, 'No valid mono configuration')
     tthm = asin(target / (2 * self._d())) / pi * 360.
     omgm = tthm / 2.0 + plane[1] + plane[2]
     self.log.debug(self._attached_base, 'will be moved to %.3f' % tthm)
     self.log.debug(self._attached_omgm, 'will be moved to %.3f' % omgm)
     if self._attached_base.isAllowed(tthm) and \
        self._attached_omgm.isAllowed(omgm):
         self._attached_base.start(tthm)
         self._attached_omgm.start(omgm)
コード例 #7
0
    def doInit(self, mode):
        MemoryCacheDatabase.doInit(self, mode)

        # Create the producer
        self._producer = KafkaProducer(bootstrap_servers=self.brokers)

        # Create the consumer
        self._consumer = KafkaConsumer(
            bootstrap_servers=self.brokers,
            auto_offset_reset='earliest'  # start at earliest topic
        )

        # Give up if the topic does not exist
        if self.currenttopic not in self._consumer.topics():
            raise ConfigurationError(
                'Topic "%s" does not exit. Create this topic and restart.' %
                self.currenttopic)

        # Assign the partitions
        partitions = self._consumer.partitions_for_topic(self.currenttopic)
        self._consumer.assign(
            [TopicPartition(self.currenttopic, p) for p in partitions])

        # Cleanup thread configuration
        self._stoprequest = False
        self._cleaner = createThread('cleaner', self._clean, start=False)
コード例 #8
0
ファイル: secop.py プロジェクト: umithardal/nicos
    def replaceClass(self, config):
        """replace the class on the fly

        happens when the structure fo the device has changed
        """
        cls = self.__class__.__bases__[0]
        newclass = cls.makeDevClass(self.name, **config)
        bad_attached = False
        for dev, cls in get_attaching_devices(self):
            if issubclass(newclass, cls):
                self.log.warning('reattach %s to %s' % (dev.name, self.name))
            else:
                self.log.error('can not attach %s to %s' % (dev.name, self.name))
                bad_attached = True
        if bad_attached:
            raise ConfigurationError('device class mismatch')
        for dev, cls in get_aliases(self):
            if issubclass(newclass, cls):
                self.log.warning('redirect alias %s to %s' % (dev.name, self.name))
            else:
                self.log.error('release alias %s from %s' % (dev.name, self.name))
                dev.alias = ''
        self.__class__ = newclass
        # as we do not go through self.__init__ again, we have to update self._config
        self._config = dict((name.lower(), value) for (name, value) in config.items())
        for aname in self.attached_devices:
            self._config.pop(aname, None)
コード例 #9
0
 def doPreinit(self, mode):
     if len(self._attached_others) != 1 or not isinstance(
             self._attached_others[0], Configuration):
         raise ConfigurationError(
             'pilatus detectors require exactly one "other" channel that '
             'is an instance of {}'.format(Configuration))
     self._cfg_channel = self._attached_others[0]._dev
     GenericDetector.doPreinit(self, mode)
コード例 #10
0
 def _get_pv_name(self, pvparam):
     prefix = getattr(self, 'basepv')
     if pvparam == 'alarm':
         return prefix + 'ALARM'
     elif pvparam == 'values':
         return prefix + 'VALUES'
     else:
         raise ConfigurationError(
             'requested invalid pv %s for LMD400' % (pvparam))
コード例 #11
0
 def doInit(self, mode):
     if any(idx < 10 or idx > 19 for idx, _ in self.workspaces):
         raise ConfigurationError("Workspace ids muste be in 10..19 "
                                  "(Jülich workspace range)")
     if mode != SIMULATION:
         workspaces = self._dev.workspaces  # Tango get workspaces
         for wsid, ws in self.workspaces:
             workspaces[wsid] = ws
         self._dev.workspaces = workspaces  # Tango set workspaces
コード例 #12
0
 def doWritePlane(self, target):
     crystal = self._crystal()
     if crystal:
         if not crystal.get(target, None):
             raise ValueError('The "%s" plane is not allowed for "%s" '
                              'crystal' % (target, crystal))
     else:
         raise ConfigurationError('No valid setup of the monochromator')
     return target
コード例 #13
0
ファイル: mythen_det.py プロジェクト: umithardal/nicos
 def doInit(self, _mode):
     for dev_name in self.detectors:
         detector = session.getDevice(dev_name)
         for img in detector._attached_images:
             if not isinstance(session.getDevice(img), ImageChannel):
                 raise ConfigurationError(
                     'mythen image sink can only be used by detector '
                     'devices that come up with image channels that are '
                     'instances of {}'.format(ImageChannel))
コード例 #14
0
 def _get_pv_name(self, pvparam):
     prefix = getattr(self, 'basepv')
     if pvparam == 'target':
         return prefix + 'RUN'
     elif pvparam == 'readback':
         return prefix + 'RUNRBV'
     else:
         raise ConfigurationError(
             'requested invalid pv %s for radial collimator' % (pvparam))
コード例 #15
0
ファイル: __init__.py プロジェクト: ess-dmsc/nicos
 def doInit(self, mode):
     if requests is None:
         raise ConfigurationError(self, 'requests package is missing')
     self._prefix = self.prefix.strip('/')
     if self._prefix:
         self._prefix += '/'
     self._initFilters()
     self._queue = queue.Queue(1000)
     self._processor = createThread('webhookprocessor', self._processQueue)
コード例 #16
0
ファイル: setups.py プロジェクト: ess-dmsc/nicos
 def configdata(name):
     from nicos.core.errors import ConfigurationError
     try:
         setupname, element = name.split('.')
     except ValueError:
         raise ConfigurationError('configdata() argument must be in the '
                                  'form \'module.valuename\'') from None
     if setupname not in all_setups:
         raise ConfigurationError('config setup "%s" not found' % setupname)
     else:
         fullname = all_setups[setupname]
     ns = {}
     with open(fullname, encoding='utf-8') as fp:
         exec(fp.read(), ns)
     dep_files.add(fullname)
     try:
         return ns[element]
     except KeyError:
         raise ConfigurationError('value named %s not found in config setup'
                                  ' "%s"' % (element, setupname)) from None
コード例 #17
0
 def _name_server(self):
     tmp = self.config.split()
     if tmp[2].count(':') and not self.absdev:
         return tmp[2].split(':')[0]
     elif self.nameserver:
         return self.nameserver
     else:
         raise ConfigurationError(
             self, 'No name server configured. Please '
             'use the "nameserver" parameter or put it'
             'into the "config" parameter.')
コード例 #18
0
ファイル: motor.py プロジェクト: umithardal/nicos
    def _checkLimits(self, limits):
        # Called by doReadUserlimits and doWriteUserlimits
        low, high = self.abslimits
        if low == 0 and high == 0:
            # No limits defined in IOC.
            # Could be a rotation stage for example.
            return

        if limits[0] < low or limits[1] > high:
            raise ConfigurationError('cannot set user limits outside of '
                                     'absolute limits (%s, %s)' % (low, high))
コード例 #19
0
ファイル: caress.py プロジェクト: umithardal/nicos
 def doInit(self, mode):
     if mode == SIMULATION:
         return
     CARESSDevice.doInit(self, mode)
     if hasattr(self._caressObject, 'is_counting_module'):
         is_counting = \
             self._caress_guard(self._caressObject.is_counting_module,
                                self.cid)
     self.log.debug('counting module: %r', is_counting)
     if not is_counting:
         raise ConfigurationError(self, 'Object is not a measurable module')
コード例 #20
0
ファイル: generic.py プロジェクト: umithardal/nicos
 def __init__(self, parent, client, options):
     Panel.__init__(self, parent, client, options)
     self._error_window = None
     if 'uifile' not in options:
         raise ConfigurationError('GenericPanels require at least an'
                                  ' `uifile` option.')
     loadUi(self, findResource(options['uifile']))
     if options.get('showmsg'):
         self.client.message.connect(self.on_client_message)
     if client.isconnected:
         self.on_client_connected()
     client.connected.connect(self.on_client_connected)
コード例 #21
0
 def _checkLimits(self, limits):
     umin, umax = limits
     amin, amax = self.abslimits
     if isinstance(self, HasOffset):
         offset = getattr(self, '_new_offset', self.offset)
         umin += offset
         umax += offset
     else:
         offset = 0
     if umin > umax:
         raise ConfigurationError(
             self, 'user minimum (%s, offset %s) above the user '
             'maximum (%s, offset %s)' % (umin, offset, umax, offset))
     if umin < amin - abs(amin * 1e-12):
         raise ConfigurationError(
             self, 'user minimum (%s, offset %s) below the '
             'absolute minimum (%s)' % (umin, offset, amin))
     if umax > amax + abs(amax * 1e-12):
         raise ConfigurationError(
             self, 'user maximum (%s, offset %s) above the '
             'absolute maximum (%s)' % (umax, offset, amax))
コード例 #22
0
    def subscribe(self, topic):
        """ Create the thread that provides call backs on new messages
        """
        # Remove all the assigned topics
        self._consumer.unsubscribe()

        topics = self._consumer.topics()
        if topic not in topics:
            raise ConfigurationError('Provided topic %s does not exist' % topic)

        # Assign the partitions
        partitions = self._consumer.partitions_for_topic(topic)
        if not partitions:
            raise ConfigurationError('Cannot query partitions for %s' % topic)

        self._consumer.assign([kafka.TopicPartition(topic, p)
                               for p in partitions])
        self._stoprequest = False
        self._updater_thread = createThread('updater_' + topic,
                                            self._get_new_messages)
        self.log.debug('subscribed to updates from topic: %s' % topic)
コード例 #23
0
    def _initObject(self):
        if not self._orb:
            raise ProgrammingError(self, 'Programmer forgot to call _initORB')

        obj = self._orb.resolve_initial_references('NameService')
        _root_context = obj._narrow(CosNaming.NamingContext)

        if not _root_context:
            raise CommunicationError(
                self, 'Failed to narrow the root naming'
                ' context')
        if self._is_corba_device():
            try:
                tmp = self.objname.split('.') if self.objname else \
                    self.config.split()[2].split('.')
                if len(tmp) < 2:
                    tmp.append('caress_object')
                self.log.debug('%r', tmp)
                obj = _root_context.resolve(
                    [CosNaming.NameComponent(tmp[0], tmp[1])])
            except CosNaming.NamingContext.NotFound as ex:
                raise ConfigurationError(self,
                                         'Name not found: %s' % (ex, )) from ex
            self._caressObject = obj._narrow(CARESS.CORBADevice)
        else:
            try:
                self._caressObject = \
                    self._orb.string_to_object('corbaname::%s#%s.context/'
                                               'caress.context/'
                                               'server.context/absdev.object' %
                                               (self.nameserver, self.objname))
            except CORBA.BAD_PARAM as ex:
                raise ConfigurationError(self,
                                         'Name not found: %s' % (ex, )) from ex

        if CORBA.is_nil(self._caressObject):
            raise CommunicationError(self, 'Could not create a CARESS device')

        if hasattr(self._caressObject, 'init_module_orb'):
            self._caressObject.init_module = self._caressObject.init_module_orb
コード例 #24
0
    def doInit(self, mode):
        KafkaCacheDatabase.doInit(self, mode)

        if self.historytopic not in self._consumer.topics():
            raise ConfigurationError(
                'Topic "%s" does not exist. Create this topic and restart.' %
                self.historytopic)

        # Create the history consumer
        self._history_consumer = KafkaConsumer(bootstrap_servers=self.brokers)

        # Give up if the topic does not exist
        if self.historytopic not in self._history_consumer.topics():
            raise ConfigurationError(
                'Topic "%s" does not exist. Create this topic and restart.' %
                self.historytopic)

        # Assign the partitions
        partitions = self._history_consumer.partitions_for_topic(
            self.historytopic)
        self._history_consumer.assign(
            [TopicPartition(self.historytopic, p) for p in partitions])
コード例 #25
0
 def doInit(self, _mode):
     self._pilatus_detectors = []
     for det_name in self.detectors:
         if isinstance(session.getDevice(det_name), Detector):
             self._pilatus_detectors.append(session.getDevice(det_name))
         else:
             self.log.warning('non-pilatus detector %r uses pilatus image '
                              'file sink', det_name)
     if not self._pilatus_detectors:
         raise ConfigurationError(
             'pilatus data sink requires at least one pilatus detector '
             'device that is an instance of {}'.format(Detector)
         )
コード例 #26
0
ファイル: base.py プロジェクト: umithardal/nicos
    def doInit(self, mode):
        CARESSDevice.doInit(self, mode)
        if session.sessiontype == POLLER or mode == SIMULATION:
            return

        self._setROParam('_started', False)
        is_readable = True
        if hasattr(self._caressObject, 'is_readable_module'):
            is_readable = self._caress_guard(
                self._caressObject.is_readable_module, self.cid)

        if hasattr(self._caressObject, 'is_drivable_module'):
            is_drivable = self._caress_guard(
                self._caressObject.is_drivable_module, self.cid)
        elif self._device_kind() in [CORBA_DEVICE, 501]:
            # 500, 501 devices may be any combination of readable or drivable
            # Query capabilities from server
            (ret, _, _, chtype) = self._caress_guard(
                self._caressObject.readblock_params_orb, -0x80000000,
                self.cid, 1, 0, 0)
            if ret != READBLOCK_NORMAL or chtype != CHTYPE_INT32:
                # Something went wrong, assume no capabilities
                is_readable = False
                is_drivable = False
            else:
                (ret, _, dataseq) = self._caress_guard(
                    self._caressObject.int_readblock_module_orb, -0x80000000,
                    self.cid, 1, 1, ())
                if ret != READBLOCK_NORMAL or len(dataseq) != 1:
                    # Something went wrong, assume no capabilities
                    is_readable = False
                    is_drivable = False
                else:
                    is_readable = bool(dataseq[0] & DEVICE_READABLE)
                    is_drivable = bool(dataseq[0] & DEVICE_DRIVABLE)
                    # readable, drivable, counting, status, needs_reference,
                    # new_interface
        else:
            is_drivable = self._device_kind() in [3, 7, 13, 14, 15, 23, 24, 25,
                                                  28, 29, 30, 31, 32, 33, 37,
                                                  39, 40, 41, 43, 44, 45, 49,
                                                  50, 51, 53, 54, 56, 62, 67,
                                                  68, 70, 71, 72, 73, 76, 100,
                                                  103, 105, 106, 107, 108, 110,
                                                  111, 112, 114, 115, 123, 124,
                                                  125, 126]

        self.log.debug('readable module: %r', is_readable)
        self.log.debug('driveable module: %r', is_drivable)
        if not (is_drivable or is_readable):
            raise ConfigurationError(self, 'Object is not a moveable module')
コード例 #27
0
    def __init__(self, parent, client, options):
        Panel.__init__(self, parent, client, options)
        loadUi(self, findResource('nicos_mlz/gui/tunewavetable.ui'))

        self._dev = options.get('tabledev')
        measuremode = options.get('measuremode', 'nrse')
        if measuremode not in ['nrse', 'mieze']:
            measuremode = 'nrse'
        for i in range(self.measModeComboBox.count()):
            if measuremode == self.measModeComboBox.itemText(i):
                self.measModeComboBox.setCurrentIndex(i)
                break
        # access to the echotime device
        if not self._dev:
            raise ConfigurationError('TuneWaveTable panel: At least `tabledev`'
                                     ' is required.')

        self._header_labels = []
        self._available_tables = {}
        self._edit = None
        self._blocked_while_edit = [
            self.measModeComboBox, self.wavelengthComboBox,
            self.restorePushButton, self.savePushButton,
            self.refreshPushButton, self.deletePushButton
        ]

        self.tableWidget.installEventFilter(self)

        self.tableWidget.verticalHeader().setContextMenuPolicy(
            Qt.CustomContextMenu)

        self.measModeComboBox.currentIndexChanged.connect(self._fill_table)
        self.measModeComboBox.currentIndexChanged.connect(
            self._update_combo_boxes)
        self.wavelengthComboBox.currentIndexChanged.connect(self._fill_table)
        self.savePushButton.clicked.connect(self._save_current_table)
        self.refreshPushButton.clicked.connect(self._update_available_tables)
        self.tableWidget.verticalHeader()\
            .customContextMenuRequested.connect(
            self.on_tableWidget_customContextMenuRequested)
        self.tableWidget.cellActivated.connect(self._edit_cell)
        self.tableWidget.verticalHeader().sectionClicked.connect(
            self._stop_edit)
        self.tableWidget.horizontalHeader().sectionPressed.connect(
            self._stop_edit)
        self.tableWidget.setAlternatingRowColors(True)

        client.connected.connect(self.on_client_connected)
        client.device.connect(self.on_client_device)
        self._dev_available = False
コード例 #28
0
 def doInit(self, mode):
     if mode == SIMULATION:
         return
     if not omniORB:
         raise ConfigurationError(self, 'There is no CORBA module found')
     self._initORB(
         ['-ORBInitRef',
          'NameService=corbaname::%s' % self._name_server()])
     self._initObject()
     _cid = self._getCID(self.config.split(None, 2)[0])
     self._init(_cid)
     if session.sessiontype != POLLER:
         # omniORB.setClientCallTimeout(self._caressObject, 0)
         self._setROParam('cid', _cid)
         if self._cache:
             self._cache.invalidate(self, 'cid')
コード例 #29
0
 def create(self, name, h5parent, sinkhandler):
     try:
         array = session.getDevice(self._array_name)
         if not isinstance(array, HistogramConfArray):
             raise ConfigurationError('%s is no HistogramConfArray' %
                                      self._array_name)
     except ConfigurationError:
         session.log.warning('Array %s not found, NOT stored',
                             self._array_name)
         return
     dset = h5parent.create_dataset(name, tuple(array.dim), 'float32')
     if self._scale != 1.:
         dset[...] = np.array(array.data, dtype='float32') * self._scale
     else:
         dset[...] = array.data
     self.createAttributes(dset, sinkhandler)
コード例 #30
0
ファイル: histogramdesc.py プロジェクト: umithardal/nicos
 def __init__(self, name, dtype, dims):
     shape = []
     dimnames = []
     dimunits = []
     dimbins = []
     for dim in dims:
         if not isinstance(dim, HistogramDimDesc):
             raise ConfigurationError('%s should be of type '
                                      'HistogramDimDesc' % dim)
         shape.append(dim.length)
         dimnames.append(dim.label)
         dimunits.append(dim.unit)
         dimbins.append(dim.bins)
     ArrayDesc.__init__(self, name, shape, dtype, dimnames)
     self.dimunits = dimunits
     self.dimbins = dimbins
     self.dimbins = dimbins