counter.py 7.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
# Copyright (c) 2017 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.

import numpy
import time
Matias Guijarro's avatar
Matias Guijarro committed
10
11
import gevent
from gevent import event
12
from bliss.common.event import dispatcher
Matias Guijarro's avatar
Matias Guijarro committed
13
from ..chain import AcquisitionDevice, AcquisitionChannel
14
15
from bliss.common.measurement import GroupedReadMixin
from bliss.common.utils import all_equal
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
class BaseCounterAcquisitionDevice(AcquisitionDevice):
    def __init__(self, counter, count_time, auto_add_channel, **keys):
        npoints = max(1, keys.pop('npoints', 1))
        prepare_once = keys.pop('prepare_once', npoints > 1)
        start_once = keys.pop('start_once', npoints > 1)

        AcquisitionDevice.__init__(self, counter, counter.name, "zerod",
                                   npoints=npoints,
                                   trigger_type=AcquisitionDevice.SOFTWARE,
                                   prepare_once=prepare_once,
                                   start_once=start_once)

        self.__count_time = count_time
        self.__grouped_read_counters_list = list()
        self.__counter_names = list()
        self._nb_acq_points = 0

        if auto_add_channel:
            self.channels.append(AcquisitionChannel(counter.name, numpy.double, (1,)))
            self.__counter_names.append(counter.name)
        
    @property
    def count_time(self):
        return self.__count_time
       
    @property
    def grouped_read_counters(self):
        return self.__grouped_read_counters_list
 
    @property
    def counter_names(self):
        return self.__counter_names

    def add_counter(self, counter):
        if not isinstance(self.device, GroupedReadMixin):
            raise RuntimeError("Cannot add counter to single-read counter acquisition device")

        self.__grouped_read_counters_list.append(counter)
        self.__counter_names.append(counter.name)
        self.channels.append(AcquisitionChannel(counter.name, numpy.double, (1,)))

    def _emit_new_data(self, data):
        channel_data = dict([ (name, data[i]) for i, name in enumerate(self.counter_names) ])
        dispatcher.send("new_data", self, {"channel_data": channel_data})


class SamplingCounterAcquisitionDevice(BaseCounterAcquisitionDevice):
64
65
    SIMPLE_AVERAGE,TIME_AVERAGE,INTEGRATE = range(3)

66
    def __init__(self, counter, count_time=None, mode=SIMPLE_AVERAGE, auto_add_channel=True, **keys):
67
68
69
70
71
72
73
74
75
        """
        Helper to manage acquisition of a sampling counter.

        count_time -- the master integration time.
        mode -- three mode are available *SIMPLE_AVERAGE* (the default)
        which sum all the sampling values and divide by the number of read value.
        the *TIME_AVERAGE* which sum all integration  then divide by the sum
        of time spend to measure all values. And *INTEGRATION* which sum all integration
        and then normalize it when the *count_time*.
76
77
78
79
80
        auto_add_channel -- specify if channel is directly added from counter (default: True)
        Other keys are:
          * npoints -- number of point for this acquisition
          * prepare_once --
          * start_once --
81
        """
82
83
        BaseCounterAcquisitionDevice.__init__(self, counter, count_time, auto_add_channel, **keys)

84
85
86
87
        self._event = event.Event()
        self._stop_flag = False
        self._ready_event = event.Event()
        self._ready_flag = True
88
89
90
91
92
93
94
95
        self.__mode = mode

    @property
    def mode(self):
        return self.__mode
    @mode.setter
    def mode(self,value):
        self.__mode = value
96
97
98
99
100
101
102
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
133
134

    def prepare(self):
        self._nb_acq_points = 0
        self._stop_flag = False
        self._ready_flag = True
        self._event.clear()

    def start(self):
        pass

    def stop(self):
        self._stop_flag = True
        self._trig_time = None
        self._event.set()

    def trigger(self):
        self._trig_time = time.time()
        self._event.set()

    def wait_ready(self):
        """
        will wait until the last triggered point is read
        """
        while not self._ready_flag:
            self._ready_event.wait()
            self._ready_event.clear()

    def reading(self):
        while self._nb_acq_points < self.npoints:
            #trigger wait
            self._event.wait()
            self._event.clear()
            self._ready_flag = False
            trig_time = self._trig_time
            if trig_time is None: continue
            if self._stop_flag: break

            nb_read = 0
            acc_read_time = 0
135
            acc_value = numpy.zeros((len(self.counter_names),), dtype=numpy.double)
136
            stop_time = trig_time + self.count_time or 0
137
138
139
            #Counter integration loop
            while not self._stop_flag:
                start_read = time.time()
140
                read_value = numpy.array(self.device.read(*self.grouped_read_counters), dtype=numpy.double)
141
                end_read = time.time()
142
143
                read_time = end_read - start_read
                
144
                if self.__mode == SamplingCounterAcquisitionDevice.TIME_AVERAGE:
145
                    acc_value += read_value * (end_read - start_read)
146
147
148
                else:
                    acc_value += read_value

149
150
151
152
153
154
                nb_read += 1
                acc_read_time += end_read - start_read

                current_time = time.time()
                if (current_time + (acc_read_time / nb_read)) > stop_time:
                    break
Matias Guijarro's avatar
Matias Guijarro committed
155
                gevent.sleep(0) # Be able to kill the task
156
            self._nb_acq_points += 1
Matias Guijarro's avatar
Matias Guijarro committed
157
            if self.__mode == SamplingCounterAcquisitionDevice.TIME_AVERAGE:
158
                data = acc_value / acc_read_time
159
160
            else:
                data = acc_value / nb_read
161
                
Matias Guijarro's avatar
Matias Guijarro committed
162
            if self.__mode == SamplingCounterAcquisitionDevice.INTEGRATE:
163
                data *= self.count_time
164
            
165
166
            self._emit_new_data(data)

167
168
            self._ready_flag = True
            self._ready_event.set()
169
            
170

171
172
173
class IntegratingCounterAcquisitionDevice(BaseCounterAcquisitionDevice):
    def __init__(self, counter, count_time=None, auto_add_channel=True, **keys):
        BaseCounterAcquisitionDevice.__init__(self, counter, count_time, auto_add_channel, **keys)
174
175
176
177
178
179
180
181
182
183
184
185
186
187

    def prepare(self):
        self._nb_acq_points = 0
        self._stop_flag = False

    def start(self):
        pass

    def stop(self):
        self._stop_flag = True

    def trigger(self):
        pass
    
188
189
190
191
192
193
    def _read_data(self, from_index):
        if self.grouped_read_counters:
            return self.device.get_values(from_index, *self.grouped_read_counters)
        else:
            return [numpy.array(self.device.get_value(from_index), dtype=numpy.double)]

194
    def reading(self):
195
        from_index = 0
196
        while self._nb_acq_points < self.npoints and not self._stop_flag:
197
198
199
200
201
            data = self._read_data(from_index)
            if all_equal([len(d) for d in data]) and len(data[0]) > 0:
                from_index += len(data[0])
                self._nb_acq_points += len(data[0])
                self._emit_new_data(data)
202
203
204
205
                gevent.idle()
            else:
                gevent.sleep(count_time/2.)