standard.py 10.5 KB
Newer Older
1
2
3
# -*- coding: utf-8 -*-

"""
4
5
Standard bliss macros (:func:`~bliss.common.standard.wa`, \
:func:`~bliss.common.standard.mv`, etc)
6
7
8
"""

__all__ = ['wa', 'wm', 'sta', 'mv', 'umv', 'mvr', 'umvr', 'move',
Jose Tiago Macara Coutinho's avatar
Jose Tiago Macara Coutinho committed
9
           'enable', 'disable', 'lsct', 'prdef']
10

Jose Tiago Macara Coutinho's avatar
Jose Tiago Macara Coutinho committed
11
import inspect
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import logging
import functools

from six import print_
from gevent import sleep
from tabulate import tabulate
try:
    from collections import OrderedDict
except ImportError:
    try:
        from ordereddict import OrderedDict
    except ImportError:
        OrderedDict = dict

from bliss import setup_globals

from bliss.common.axis import Axis
from bliss.common.measurement import CounterBase

from bliss.config.static import get_config
from bliss.config.settings import QueueSetting

from bliss.controllers.motor_group import Group

36
from bliss.common.units import ureg as ur
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

_ERR = '!ERR'
_MAX_COLS = 9
_MISSING_VAL = '-----'
_FLOAT_FORMAT = '.05f'


_log = logging.getLogger('bliss.standard')


def __get_objects_iter(*names_or_objs):
    cfg = get_config()
    for i in names_or_objs:
        if isinstance(i, (str, unicode)):
            i = cfg.get(i)
        yield i


def __get_objects_type_iter(typ):
    for name in dir(setup_globals):
        elem = getattr(setup_globals, name)
        if isinstance(elem, typ):
            yield elem


__get_axes_iter = functools.partial(__get_objects_type_iter, Axis)


def __get_axes_names_iter():
    for axis in __get_axes_iter():
        yield axis.name


__get_counters_iter = functools.partial(__get_objects_type_iter, CounterBase)


def __get_counters_names_iter():
    for counter in __get_counters_iter():
        yield counter.name


def __safe_get(obj, member, on_error=_ERR):
    try:
        return getattr(obj, member)()
    except Exception as e:
        return on_error


def __tabulate(data, **kwargs):
    kwargs.setdefault('headers', 'firstrow')
    kwargs.setdefault('floatfmt', _FLOAT_FORMAT)
    kwargs.setdefault('numalign', 'right')

    return str(tabulate(data, **kwargs))


MEASUREMENT_GROUP = None
def active_measurement_group():
95
96
97
98
99
100
    """
    Returns the active measurement group

    Returns:
        QueueSetting: a list of active counters
    """
101
    global MEASUREMENT_GROUP
102
    if MEASUREMENT_GROUP is not None:
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        return MEASUREMENT_GROUP
    def write(value):
        if not isinstance(value, (str, unicode)):
            value = value.name
        return value
    MEASUREMENT_GROUP = QueueSetting('measurement_group.active',
                                     write_type_conversion=write)
    MEASUREMENT_GROUP.set(tuple(__get_counters_names_iter()))
    return MEASUREMENT_GROUP


def get_active_counters_iter():
    cfg = get_config()
    for name in active_measurement_group():
        yield cfg.get(name)


def __enable_ct(counters):
    amg = active_measurement_group()
    amg.extend([counter.name for counter in counters])


def __disable_ct(counters):
    amg = active_measurement_group()
    for counter in counters:
        print 'removing', counter.name
        amg.remove(counter.name)


def enable(*elems):
133
    """
134
135
    Enables given elements.

136
137
138
    Args:
        elem: a object or object name
    """
139
140
141
142
143
144
145
146
    counters = []
    for elem in __get_objects_iter(*elems):
        if isinstance(elem, CounterBase):
            counters.append(elem)
    __enable_ct(counters)


def disable(*elems):
147
    """
148
149
    Disables given elements.

150
151
152
    Args:
        elem: object or object name
    """
153
154
155
156
157
158
159
160
    counters = []
    for elem in __get_objects_iter(*elems):
        if isinstance(elem, CounterBase):
            counters.append(elem)
    __disable_ct(counters)


def wa(**kwargs):
161
162
163
    """
    Displays all position positions (Where All) in both user and dial units
    """
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    max_cols = kwargs.get('max_cols', _MAX_COLS)
    err = kwargs.get('err', _ERR)
    get = functools.partial(__safe_get, on_error=err)

    print_("Current Positions (user, dial)")
    header, pos, dial = [], [], []
    tables = [(header, pos, dial)]
    for axis in __get_axes_iter():
        if len(header) == max_cols:
            header, pos, dial = [], [], []
            tables.append((header, pos, dial))
        header.append(axis.name)
        pos.append(get(axis, "position"))
        dial.append(get(axis, "dial"))

    for table in tables:
        print_()
        print_(__tabulate(table))


def wm(*axes, **kwargs):
185
186
187
188
189
190
    """
    Displays information (position - user and dial, limits) of the given axes

    Args:
        axis (~bliss.common.axis.Axis): motor axis
    """
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    if not axes:
        print_('need at least one axis name/object')
        return
    max_cols = kwargs.get('max_cols', _MAX_COLS)
    err = kwargs.get('err', _ERR)
    get = functools.partial(__safe_get, on_error=err)

    header = [""]
    User, high_user, user, low_user = ["User"], [" High"], [" Current"], [" Low"]
    Dial, high_dial, dial, low_dial = ["Dial"], [" High"], [" Current"], [" Low"]
    tables = [(header, User, high_user, user, low_user,
               Dial, high_dial, dial, low_dial)]
    for axis in __get_objects_iter(*axes):
        low, high = __safe_get(axis, "limits", on_error=(err, err))
        if len(header) == max_cols:
            header = [None]
            User, high_user, user, low_user = ["User"], [" High"], [" Current"], [" Low"]
            Dial, high_dial, dial, low_dial = ["Dial"], [" High"], [" Current"], [" Low"]
            tables.append((header, User, high_user, user, low_user,
                           Dial, high_dial, dial, low_dial))
        header.append(axis.name)
        User.append(None)
        high_user.append(high if high != None else _MISSING_VAL)
        user.append(get(axis, "position"))
        low_user.append(low if low != None else _MISSING_VAL)
        Dial.append(None)
        high_dial.append(axis.user2dial(high) if high != None else _MISSING_VAL)
        dial.append(get(axis, "dial"))
        low_dial.append(axis.user2dial(low) if low != None else _MISSING_VAL)

    for table in tables:
        print_()
        print_(__tabulate(table))


def stm(*axes):
227
    """Displays axis state (not implemented yet!)"""
228
229
230
231
    raise NotImplementedError


def sta():
232
    """Displays state information about all axes"""
233
234
235
236
237
238
239
240
    global __axes
    table = [("Axis", "Status")]
    table += [(axis.name, __safe_get(axis, "state", "<status not available>"))
              for axis in __get_axes_iter()]
    print_(__tabulate(table))


def mv(*args):
241
242
243
244
245
246
247
248
249
250
    """
    Moves given axes to given absolute positions

    Arguments are interleaved axis and respective absolute target position.
    Example::

        >>> mv(th, 180, chi, 90)

    See Also: move
    """
251
252
253
254
    move(*args)


def umv(*args):
255
256
257
258
259
260
    """
    Moves given axes to given absolute positions providing updated display of
    the motor(s) position(s) while it(they) is(are) moving.

    Arguments are interleaved axis and respective absolute target position.
    """
261
262
263
264
    __umove(*args)


def mvr(*args):
265
266
267
268
269
270
271
272
    """
    Moves given axes to given relative positions

    Arguments are interleaved axis and respective relative target position.
    Example::

        >>> mv(th, 180, chi, 90)
    """
273
274
275
276
    __move(*args, relative=True)


def umvr(*args):
277
278
279
280
281
282
    """
    Moves given axes to given relative positions providing updated display of
    the motor(s) position(s) while it(they) is(are) moving.

    Arguments are interleaved axis and respective relative target position.
    """
283
284
285
286
    __umove(*args, relative=True)


def move(*args, **kwargs):
287
288
289
290
291
292
293
294
295
296
    """
    Moves given axes to given absolute positions

    Arguments are interleaved axis and respective absolute target position.
    Example::

        >>> mv(th, 180, chi, 90)

    See Also: mv
    """
297
298
299
300
301
302
303
304
305
    __move(*args, **kwargs)


def __row_positions(positions, motors, fmt, sep=' '):
    positions = [positions[m] for m in motors]
    return __row(positions, fmt, sep='  ')


def __row(cols, fmt, sep=' '):
306
307
308
309
310
311
312
313
    data = []
    for col in cols:
        if isinstance(col, ur.Quantity):
            col = str(col)
        else:
            col = format(col, fmt)
        data.append(col)
    return sep.join(data)
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359


def __umove(*args, **kwargs):
    kwargs['wait'] = False
    group, motor_pos = __move(*args, **kwargs)
    try:
        motor_names = [axis.name for axis in motor_pos]
        col_len = max(max(map(len, motor_names)), 8)
        hfmt = '^{width}'.format(width=col_len)
        rfmt = '>{width}.03f'.format(width=col_len)
        print_()
        print_(__row(motor_names, hfmt, sep='  '))

        while group.is_moving:
            positions = group.position()
            row = __row_positions(positions, motor_pos, rfmt, sep='  ')
            print_("\r" + row, end='', flush=True)
            sleep(0.1)
        # print last time for final positions
        positions = group.position()
        row = __row_positions(positions, motor_pos, rfmt, sep='  ')
        print_("\r" + row, end='', flush=True)
        print_()
    except KeyboardInterrupt:
        print_("Ctrl+C pressed. Stopping all motors...")
        group.stop()

    return group, motor_pos


def __move(*args, **kwargs):
    wait, relative = kwargs.get('wait', True), kwargs.get('relative', False)
    motor_pos = OrderedDict()
    for m, p in zip(__get_objects_iter(*args[::2]), args[1::2]):
        motor_pos[m] = p
    group = Group(*motor_pos.keys())
    try:
        group.move(motor_pos, wait=wait, relative=relative)
    except KeyboardInterrupt:
        print_("Ctrl+C pressed. Stopping all motors...")
        group.stop()

    return group, motor_pos


def lsct():
360
    """Displays list of all counters"""
361
362
363
364
365
366
367
368
    table = [('Counter', 'Type', 'Active')]
    active_counters = tuple(get_active_counters_iter())
    for counter in __get_counters_iter():
        table.append((counter.name, counter.__class__.__name__,
                      '*' if counter in active_counters else ''))
    print_(__tabulate(table))


Jose Tiago Macara Coutinho's avatar
Jose Tiago Macara Coutinho committed
369
def prdef(obj_or_name):
370
    """
Jose Tiago Macara Coutinho's avatar
Jose Tiago Macara Coutinho committed
371
    Shows the text of the source code for an object or the name of an object.
372
    """
Jose Tiago Macara Coutinho's avatar
Jose Tiago Macara Coutinho committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    if isinstance(obj_or_name, (str, unicode)):
        obj, name = getattr(setup_globals, obj_or_name), obj_or_name
    else:
        obj = obj_or_name
        name = None
    try:
        real_name = obj.__name__
    except AttributeError:
        real_name = str(obj)
    if name is None:
        name = real_name

    fname = inspect.getfile(obj)
    lines, line_nb = inspect.getsourcelines(obj)

    if name == real_name:
        header = "'{0}' is defined in:\n{1}:{2}\n". \
                 format(name, fname, line_nb)
    else:
        header = "'{0}' is an alias for '{1}' which is defined in:\n{2}:{3}\n". \
                 format(name, real_name, fname, line_nb)
    print_(header)
    print_(''.join(lines))