Esempio n. 1
0
 def quit(self, signum=None):
     if self._setup is None:
         return self._quit_master(signum)
     if self._stoprequest:
         return  # already quitting
     self.log.info('poller quitting on signal %s...', signum)
     self._stoprequest = True
     for worker in itervalues(self._workers):
         worker.queue.put('quit', False)  # wake up to quit
     for worker in itervalues(self._workers):
         worker.join()
     self.log.info('poller finished')
Esempio n. 2
0
    def setCustomStyle(self, font, back):
        self.user_font = font
        self.user_color = back

        for plot in itervalues(self.setplots):
            plot.setBackgroundColor(back)
            plot.update()

        bold = QFont(font)
        bold.setBold(True)
        larger = scaledFont(font, 1.6)
        for plot in itervalues(self.setplots):
            plot.setFonts(font, bold, larger)
Esempio n. 3
0
 def _update_proposal_info(self):
     values = self.client.eval(
         'session.experiment.proposal, '
         'session.experiment.title, '
         'session.experiment.users, '
         'session.experiment.localcontact, '
         'session.experiment.sample.samplename, '
         'session.experiment.errorbehavior', None)
     if values:
         self._orig_proposal_info = values
         self.proposalNum.setText(values[0])
         self.expTitle.setText(decodeAny(values[1]))
         self.users.setText(decodeAny(values[2]))
         self.localContact.setText(decodeAny(values[3]))
         self.sampleName.setText(decodeAny(values[4]))
         self.errorAbortBox.setChecked(values[5] == 'abort')
     receiverinfo = self.client.eval(
         '__import__("nicos").commands.basic._listReceivers('
         '"nicos.devices.notifiers.Mailer")', {})
     emails = []
     for data in itervalues(receiverinfo):
         for (addr, what) in data:
             if what == 'receiver' and addr not in emails:
                 emails.append(addr)
     self._orig_email = emails
     self.notifEmails.setPlainText(decodeAny('\n'.join(self._orig_email)))
     propinfo = self.client.eval('session.experiment.propinfo', {})
     self._orig_datamails = propinfo.get('user_email', '')
     if not isinstance(self._orig_datamails, list):
         self._orig_datamails = self._orig_datamails.splitlines()
     self.dataEmails.setPlainText(decodeAny('\n'.join(
         self._orig_datamails)))
Esempio n. 4
0
def info(*devlist):
    """Print general information of the given device or all devices.

    Information is the device value, status and any other parameters that are
    marked as "interesting" by giving them a category.

    Examples:

    >>> info()           # show all information
    >>> info(Sample)     # show information relevant to the Sample object
    """
    if not devlist:
        devlist = [
            dev for dev in itervalues(session.devices) if not dev.lowlevel
        ]
    bycategory = {}
    for dev in devlist:
        for key, _value, strvalue, unit, category in dev.info():
            bycategory.setdefault(category, []).append(
                (str(dev), key + ':', strvalue + ' ' + unit))
    for catname, catinfo in INFO_CATEGORIES:
        if catname not in bycategory:
            continue
        session.log.info(catinfo)
        session.log.info('=' * len(catinfo))
        printTable(None,
                   sorted(bycategory[catname]),
                   session.log.info,
                   minlen=8)
        session.log.info()
Esempio n. 5
0
    def on_client_connected(self):
        self.clear()

        state = self.client.ask('getstatus')
        if not state:
            return
        devlist = state['devices']
        self._read_setup_info(state['setups'])

        for devname in devlist:
            self._create_device_item(devname)

        # close all control dialogs for now nonexisting devices
        for ldevname in list(self._control_dialogs):
            if ldevname not in self._devitems:
                self._control_dialogs[ldevname].close()

        # add all toplevel items to the tree, sorted
        for cat in self._catitems:
            self.tree.addTopLevelItem(self._catitems[cat])
            self._catitems[cat].setExpanded(True)
        for devitem in itervalues(self._devitems):
            devitem.setExpanded(True)
        self.tree.sortItems(0, Qt.AscendingOrder)
        self._update_view()
Esempio n. 6
0
 def wait(self):
     if self._setup is None:
         if os.name == 'nt':
             return self._wait_master_nt()
         return self._wait_master()
     while not self._stoprequest:
         sleep(1)
     for worker in itervalues(self._workers):
         worker.join()
Esempio n. 7
0
def resolve_devindex(app, doctree, fromdocname):
    env = app.builder.env

    for indexnode in doctree.traverse(device_index):
        table = nodes.table('')
        group = nodes.tgroup('',
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             nodes.colspec('', colwidth=30),
                             cols=3)
        table.append(group)

        group.append(
            nodes.thead(
                '',
                nodes.row(
                    '',
                    nodes.entry('', nodes.paragraph('', 'Class')),
                    nodes.entry('', nodes.paragraph('', 'Module')),
                    nodes.entry('', nodes.paragraph('', 'Description')),
                )))

        body = nodes.tbody('')
        group.append(body)

        for entry in sorted(itervalues(env.nicos_all_devices),
                            key=lambda v: v['name']):
            if not entry['module'].startswith('nicos.devices.'):
                continue
            row = nodes.row('')

            reftgt = '%s.%s' % (entry['module'], entry['name'])
            node = nodes.paragraph(
                '', '',
                addnodes.pending_xref('',
                                      nodes.Text(entry['name']),
                                      refdomain='py',
                                      reftype='class',
                                      reftarget=reftgt))
            env.resolve_references(node, fromdocname, app.builder)
            row.append(nodes.entry('', node))

            row.append(
                nodes.entry(
                    '',
                    nodes.paragraph('', '',
                                    nodes.literal('', entry['module'][6:]))))

            row.append(nodes.entry('', nodes.paragraph('', entry['blurb'])))

            body.append(row)
        indexnode.replace_self([table])
Esempio n. 8
0
    def __new__(mcs, name, bases, attrs):
        # set source class for parameters
        if 'parameters' in attrs:
            for pinfo in itervalues(attrs['parameters']):
                pinfo.classname = attrs['__module__'] + '.' + name
        for base in bases:
            if hasattr(base, 'parameters'):
                for pinfo in itervalues(base.parameters):
                    if pinfo.classname is None:
                        pinfo.classname = base.__module__ + '.' + base.__name__
        newtype = type.__new__(mcs, name, bases, attrs)
        if '__constructed__' in attrs:
            return newtype
        for entry in newtype.__mergedattrs__:
            newentry = {}
            for base in reversed(bases):
                if hasattr(base, entry):
                    newentry.update(getattr(base, entry))
            newentry.update(attrs.get(entry, {}))
            setattr(newtype, entry, newentry)

        # add usermethods to registry, check names of methods to comply with
        # coding style
        for aname in attrs:
            if aname.startswith(('_', 'do')):
                continue
            value = getattr(newtype, aname)
            if not isinstance(value, (types.FunctionType, types.MethodType)):
                continue
            args = formatArgs(value, strip_self=True)
            if value.__doc__:
                docline = value.__doc__.strip().splitlines()[0]
            else:
                docline = ''
            newtype.methods[aname] = (args, docline, newtype,
                                      hasattr(value, 'is_usermethod'))

        return newtype
Esempio n. 9
0
def setall(param, value):
    """Set the given parameter to the given value for all devices that have it.

    Example:

    >>> setall('offset', 0)

    set the offset for all devices to zero.
    """
    for dev in itervalues(session.devices):
        if param not in dev.parameters:
            continue
        prevalue = getattr(dev, param)
        setattr(dev, param, value)
        dev.log.info('%s set to %r (was %r)', param, value, prevalue)
Esempio n. 10
0
 def statusinfo(self):
     self.log.info('got SIGUSR2')
     if self._setup is not None:
         info = []
         for worker in itervalues(self._workers):
             wname = worker.getName()
             if worker.is_alive():
                 info.append('%s: alive' % wname)
             else:
                 info.append('%s: dead' % wname)
         self.log.info(', '.join(info))
         self.log.info('current stacktraces for each thread:')
         active = threading._active
         for tid, frame in listitems(sys._current_frames()):
             if tid in active:
                 name = active[tid].getName()
             else:
                 name = str(tid)
             self.log.info('%s: %s', name,
                           ''.join(traceback.format_stack(frame)))
Esempio n. 11
0
 def _handle_control_msg(self, key, value, time, expired):
     if key == 'watchdog/enable':
         time = currenttime()
         for (eid, enabled) in value[1]:
             entry = self._entries.get(eid)
             if entry:
                 entry.cond_obj.enabled = enabled
                 entry.cond_obj.update(time, self._keydict)
                 self._check_state(entry, time)
         self.log.info('updated enabled conditions by user request')
     elif key == 'watchdog/reset':
         # reset all condition enables to their initial state
         # (e.g. due to NewExperiment)
         for entry in itervalues(self._entries):
             if entry.enabled != entry.cond_obj.enabled:
                 entry.cond_obj.enabled = entry.enabled
                 entry.cond_obj.update(time, self._keydict)
                 self._check_state(entry, time)
         self.log.info('enable status of all conditions reset')
     self._publish_config()
Esempio n. 12
0
def ExportTuning(mode, wavelength, filename='tuning'):
    """Export tuning for *mode* and *wavelength* to a CSV file.

    Mode can be "nrse" or "mieze".
    """
    echotime = session.getDevice('echotime')
    exp = session.getDevice('Exp')

    # get the right table
    try:
        tables = echotime.tables[mode]
    except KeyError:
        printerror('Need a valid mode (mieze or nrse)')
        return
    try:
        table = tables[wavelength]
    except KeyError:
        printerror('No table for this wavelength (available: %s)' %
                   ', '.join(map(str, tables)))

    # build list of devices
    it = itervalues(table)
    devices = sorted(it.next())
    for otherdevs in it:
        devices.extend(set(otherdevs) - set(devices))

    # export to CSV
    filename = path.join(exp.dataroot, filename + '_%s_%sA.csv' % (mode, wavelength))
    printinfo('Exporting to %s' % filename)
    if path.exists(filename):
        printerror('File already exists. Please select another name.')
        return
    with open(filename, 'w') as fp:
        writer = csv.writer(fp)
        writer.writerow(['echotime'] + devices)
        for (etime, devs) in iteritems(table):
            writer.writerow([repr(etime)] + [repr(devs.get(d)) for d in devices])
    printinfo('Done.')
Esempio n. 13
0
 def _setups_updated(self, time, new_setups):
     prev_setups, self._setups = self._setups, new_setups
     # check if we need to remove some conditions
     for entry in listvalues(self._entries):
         if entry.from_setup != 'watchdog':
             if entry.from_setup not in self._setups:
                 self._remove_entry(entry.id)
     # check if we need to add some conditions
     session.readSetups()  # refresh setup info
     for new_setup in self._setups - prev_setups:
         info = session._setup_info.get(new_setup)
         if info and info['watch_conditions']:
             self.log.info('adding conditions from setup %s', new_setup)
             for entry_dict in info['watch_conditions']:
                 self._add_entry(entry_dict, new_setup)
     # trigger an update of all conditions
     for entry in itervalues(self._entries):
         entry.cond_obj.new_setups(self._setups)
         entry.cond_obj.update(time, self._keydict)
         self._check_state(entry, time)
     # update everyone els
     self._publish_config()
     self.log.info('new setups list: %s', ', '.join(self._setups))
Esempio n. 14
0
def _access_level_list():
    return ', '.join(repr(l) for l in itervalues(ACCESS_LEVELS))
Esempio n. 15
0
 def _get_all_widgets(self):
     yield self.widget
     for w in itervalues(self._livewidgets):
         yield w
Esempio n. 16
0
 def _wait_data(self):
     t = currenttime()
     for entry in itervalues(self._entries):
         if entry.cond_obj.tick(t) or entry.cond_obj.is_expired(t):
             self._check_state(entry, t)
Esempio n. 17
0
 def _publish_config(self):
     # publish current condition info in the cache
     self._put_message('configured', None,
                       [c.serialize() for c in itervalues(self._entries)])