Exemplo n.º 1
0
def sleep(secs):
    """Sleep for a given number of seconds.

    This is different from Python's `time.sleep()` in that it allows breaking
    and stopping the sleep, and supports dry run mode.  Fractional values are
    supported.

    Examples:

    >>> sleep(10)     # sleep for 10 seconds
    >>> sleep(0.5)    # sleep for half a second
    """
    session.log.info('sleeping for %.1f seconds...', secs)

    if session.mode == SIMULATION:
        session.clock.tick(secs)
        return

    def f_notify(tmr):
        session.breakpoint(2)  # allow break and continue here
        session.action('%s left' % formatDuration(tmr.remaining_time()))

    session.beginActionScope('Sleeping')
    session.action('%s left' % formatDuration(secs))
    try:
        tmr = Timer(secs)
        tmr.wait(interval=1.0, notify_func=f_notify)
    finally:
        session.endActionScope()
Exemplo n.º 2
0
def test_timer():
    t = time.time()

    def cb(tmr, x, y=None):
        if x == 3 and y == 'ykwd':
            tmr.cb_called = True

    def nf(tmr, info):
        if info == "notify":
            tmr.notify_called = True

    def nf1(tmr):
        tmr.notify_called = "yes"

    # a) test a (short) timed timer
    tmr = Timer(0.1, cb, cb_args=(3, ), cb_kwds={'y': 'ykwd'})
    assert tmr.is_running()
    while (time.time() - t < 1.5) and tmr.is_running():
        time.sleep(0.05)
    assert not tmr.is_running()
    assert tmr.cb_called
    assert tmr.elapsed_time() == 0.1
    assert tmr.remaining_time() == 0
    tmr.restart()
    # timer timed out, can not restart
    assert not tmr.is_running()

    # b) test an unlimited timer (for a short while)
    tmr.start()
    time.sleep(0.02)  # due to windows time.time() resolution
    assert tmr.is_running()
    assert tmr.elapsed_time() > 0
    assert tmr.remaining_time() is None
    time.sleep(0.1)
    assert 0.1 < tmr.elapsed_time() < 0.2
    tmr.stop()
    # check elapsed time for stopped timer
    assert 0.1 < tmr.elapsed_time() < 0.2
    assert not (tmr.is_running())
    assert not (tmr.wait())

    # c) stopping before timeout and then restart
    tmr.restart()
    tmr.restart()

    tmr.start(run_for=0.5)
    time.sleep(0.1)
    tmr.stop()
    tmr.restart()
    tmr.wait(interval=0.1, notify_func=nf, notify_args=('notify', ))
    assert tmr.notify_called
    tmr.start(run_for=0.5)
    tmr.wait(0.1, nf1)
    assert tmr.notify_called == "yes"
Exemplo n.º 3
0
 def doStart(self):
     self._last_update = 0
     self._timer = Timer()
     self._timer.start()
     self._stopflag = False
     self._mythread = createThread('virtual detector %s' % self, self._run)
Exemplo n.º 4
0
def waitfor(dev, condition, timeout=86400):
    """Wait for a device until a condition is fulfilled.

    Convenience function to avoid writing code like this:

    >>> while not motor.read() < 10:
    ...     sleep(0.3)

    which now can be written as:

    >>> waitfor(motor, '< 10')

    The supported conditions are [#]_:

    - '<', '<=', '==', '!=', '>=', '>' with a value
    - 'is False', 'is True', 'is None'
    - 'in list', where list could be a Python list or tuple

    An optional timeout value can be added, which denominates the maximum time
    the command will wait (in seconds).  If the timeout value is reached, an
    error will be raised.  The default timeout value is 86400 seconds (1 day).
    Example:

    >>> waitfor(T, '< 10', timeout=3600)

    Will wait a maximum of 1 hour for T to get below 10.

    .. note::

       In contrast to the `wait()` command this command will not only wait
       until the target is reached.  You may define also conditions which
       represent intermediate states of a movement or you may wait on
       external trigger signals and so on.

    .. [#] The device value, determined by ``dev.read()``, will be added in
       front of the condition, so the resulting conditions is:

        >>> dev.read() < 10

       The condition parameter will be given as a simple comparison to
       the value of the device.
    """
    dev = session.getDevice(dev, Readable)
    full_condition = '_v %s' % condition

    try:
        ast.parse(full_condition)
    except Exception:
        raise UsageError('Could not parse condition %r' % condition)

    if session.mode == SIMULATION:
        return

    def check(tmr):
        session.breakpoint(2)  # allow break and continue here
        waitfor.cond_fulfilled = eval(full_condition, {}, {'_v': dev.read(0)})
        if waitfor.cond_fulfilled:
            session.log.info('Waiting for \'%s %s\' finished.', dev, condition)
            tmr.stop()

    waitfor.cond_fulfilled = False
    try:
        session.beginActionScope('Waiting until %s %s' % (dev, condition))
        tmr = Timer(timeout if timeout else 86400)  # max wait time 1 day
        tmr.wait(dev._base_loop_delay * 3, check)
    finally:
        if not waitfor.cond_fulfilled:
            raise NicosTimeoutError(
                dev, 'Waiting for \'%s %s\' timed out.' % (dev, condition))
        session.endActionScope()
Exemplo n.º 5
0
class VirtualImage(ImageChannelMixin, PassiveChannel):
    """A virtual 2-dimensional detector that generates a direct beam and
    four peaks of scattering intensity.
    """

    parameters = {
        'sizes': Param('Detector size in pixels (x, y)',
                       settable=False,
                       type=tupleof(intrange(1, 1024), intrange(1, 1024)),
                       default=(128, 128)),
        'background': Param('Background level, use 0 to switch off',
                            settable=True, type=int, default=10),
    }

    attached_devices = {
        'distance':    Attach('The detector distance for simulation', Moveable,
                              optional=True),
        'collimation': Attach('The collimation', Readable, optional=True),
    }

    _last_update = 0
    _buf = None
    _mythread = None
    _stopflag = False
    _timer = None

    def doInit(self, mode):
        self.arraydesc = ArrayDesc(self.name, self.sizes, '<u4')

    def doPrepare(self):
        self.readresult = [0]
        if self._mythread and self._mythread.is_alive():
            self._stopflag = True
            self._mythread.join()
            self._mythread = None
        self._buf = self._generate(0).astype('<u4')

    def doStart(self):
        self._last_update = 0
        self._timer = Timer()
        self._timer.start()
        self._stopflag = False
        self._mythread = createThread('virtual detector %s' % self, self._run)

    def _run(self):
        while not self._stopflag:
            elapsed = self._timer.elapsed_time()
            self.log.debug('update image: elapsed = %.1f', elapsed)
            array = self._generate(self._base_loop_delay).astype('<u4')
            self._buf = self._buf + array
            self.readresult = [self._buf.sum()]
            time.sleep(self._base_loop_delay)

    def doPause(self):
        self._timer.stop()
        return True

    def doResume(self):
        self._timer.restart()

    def doFinish(self):
        self._stopflag = True

    def doStop(self):
        self.doFinish()

    def doStatus(self,  maxage=0):
        if self._mythread and self._mythread.is_alive():
            return status.BUSY,  'busy'
        return status.OK,  'idle'

    def doReadArray(self, _quality):
        return self._buf

    def valueInfo(self):
        return Value(self.name + '.sum', unit='cts', type='counter',
                     errors='sqrt', fmtstr='%d'),

    def _generate(self, t):
        dst = ((self._attached_distance.read() * 5) if self._attached_distance
               else 5)
        coll = (self._attached_collimation.read() if self._attached_collimation
                else '15m')
        xl, yl = self.sizes
        # pylint: disable=unbalanced-tuple-unpacking
        xx, yy = np.meshgrid(np.linspace(-(xl // 2), (xl // 2) - 1, xl),
                             np.linspace(-(yl // 2), (yl // 2) - 1, yl))
        beam = (t * 100 * np.exp(-xx**2/50) * np.exp(-yy**2/50)).astype(int)
        sigma2 = coll == '10m' and 200 or (coll == '15m' and 150 or 100)
        beam += (
            t * 30 * np.exp(-(xx-dst)**2/sigma2) * np.exp(-yy**2/sigma2) +
            t * 30 * np.exp(-(xx+dst)**2/sigma2) * np.exp(-yy**2/sigma2) +
            t * 20 * np.exp(-xx**2/sigma2) * np.exp(-(yy-dst)**2/sigma2) +
            t * 20 * np.exp(-xx**2/sigma2) * np.exp(-(yy+dst)**2/sigma2)
        ).astype(int)
        return np.random.poisson(np.ascontiguousarray(beam.T +
                                                      self.background))

    def doEstimateTime(self, elapsed):
        return self._timer.remaining_time()