counter.py 7.33 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
class BaseCounterAcquisitionDevice(AcquisitionDevice):
18
    def __init__(self, counter, count_time, **keys):
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
        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

34
        if not isinstance(counter, GroupedReadMixin):
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
            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, **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
        Other keys are:
          * npoints -- number of point for this acquisition
          * prepare_once --
          * start_once --
80
        """
81
        BaseCounterAcquisitionDevice.__init__(self, counter, count_time, **keys)
82

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

    @property
    def mode(self):
        return self.__mode
    @mode.setter
    def mode(self,value):
        self.__mode = value
95
96

    def prepare(self):
97
98
        self.device.prepare(*self.grouped_read_counters)

99
100
101
102
103
104
        self._nb_acq_points = 0
        self._stop_flag = False
        self._ready_flag = True
        self._event.clear()

    def start(self):
105
        self.device.start(*self.grouped_read_counters)
106
107

    def stop(self):
108
109
        self.device.stop(*self.grouped_read_counters)

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

152
153
154
155
156
157
                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
158
                gevent.sleep(0) # Be able to kill the task
159
            self._nb_acq_points += 1
Matias Guijarro's avatar
Matias Guijarro committed
160
            if self.__mode == SamplingCounterAcquisitionDevice.TIME_AVERAGE:
161
                data = acc_value / acc_read_time
162
163
            else:
                data = acc_value / nb_read
164
                
Matias Guijarro's avatar
Matias Guijarro committed
165
            if self.__mode == SamplingCounterAcquisitionDevice.INTEGRATE:
166
                data *= self.count_time
167
            
168
169
            self._emit_new_data(data)

170
171
            self._ready_flag = True
            self._ready_event.set()
172
            
173

174
class IntegratingCounterAcquisitionDevice(BaseCounterAcquisitionDevice):
175
176
    def __init__(self, counter, count_time=None, **keys):
        BaseCounterAcquisitionDevice.__init__(self, counter, count_time, **keys)
177
178

    def prepare(self):
179
        self.device.prepare(*self.grouped_read_counters)
180
181
182
183
        self._nb_acq_points = 0
        self._stop_flag = False

    def start(self):
184
        self.device.start(*self.grouped_read_counters)
185
186

    def stop(self):
187
        self.device.stop(*self.grouped_read_counters)
188
189
190
191
192
        self._stop_flag = True

    def trigger(self):
        pass
    
193
194
195
196
197
198
    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)]

199
    def reading(self):
200
        from_index = 0
201
        while self._nb_acq_points < self.npoints and not self._stop_flag:
202
            data = self._read_data(from_index)
203
204
205
            if not all_equal([len(d) for d in data]):
                raise RuntimeError("Can't have a different data length")
            if len(data[0]) > 0:
206
207
208
                from_index += len(data[0])
                self._nb_acq_points += len(data[0])
                self._emit_new_data(data)
209
210
211
212
                gevent.idle()
            else:
                gevent.sleep(count_time/2.)