-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexecute.py
More file actions
287 lines (244 loc) · 10.7 KB
/
execute.py
File metadata and controls
287 lines (244 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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
95
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
'''
.. versionadded:: 2.37
'''
import logging
from logging_helpers import _L
import dropbot as db
import dropbot.hardware_test
import dropbot.self_test
import dropbot.threshold
import numpy as np
import pandas as pd
import si_prefix as si
import trollius as asyncio
NAME = 'dropbot_plugin'
@asyncio.coroutine
def actuate(proxy, dmf_device, electrode_states, duration_s=0,
volume_threshold=0, c_unit_area=None):
'''
XXX Coroutine XXX
Actuate electrodes according to specified states.
Parameters
----------
electrode_states : pandas.Series
duration_s : float, optional
If ``volume_threshold`` step option is set, maximum duration before
timing out. Otherwise, time to actuate before actuation is
considered completed.
c_unit_area : float, optional
Specific capacitance, i.e., units of $F/mm^2$.
Returns
-------
actuated_electrodes : list
List of actuated electrode IDs.
.. versionchanged:: 2.39.0
Do not save actuation uuid for volume threshold actuations.
.. versionchanged:: 2.39.0
Fix actuated area field typo.
.. versionchanged:: 2.39.0
Compute actuated area for static (i.e., delay-based) actuations.
'''
requested_electrodes = electrode_states[electrode_states > 0].index
requested_channels = (dmf_device.channels_by_electrode
.loc[requested_electrodes])
actuated_channels = pd.Series()
actuated_area = 0
channels_updated = asyncio.Event()
def _on_channels_updated(message):
'''
Message keys:
- ``"n"``: number of actuated channel
- ``"actuated"``: list of actuated channel identifiers.
- ``"start"``: ms counter before setting shift registers
- ``"end"``: ms counter after setting shift registers
'''
global actuated_area
global actuated_channels
actuated_channels = message['actuated']
if actuated_channels:
actuated_electrodes = \
dmf_device.actuated_electrodes(actuated_channels).dropna()
actuated_areas = \
dmf_device.electrode_areas.ix[actuated_electrodes.values]
actuated_area = actuated_areas.sum()
else:
actuated_area = 0
# m^2 area
area = actuated_area * (1e-3 ** 2)
# Approximate area in SI units.
value, pow10 = si.split(np.sqrt(area))
si_unit = si.SI_PREFIX_UNITS[len(si.SI_PREFIX_UNITS) // 2 +
pow10 // 3]
status = ('actuated electrodes: %s (%.1f %sm^2)' % (actuated_channels,
value ** 2,
si_unit))
_L().debug(status)
channels_updated.set()
proxy.signals.signal('channels-updated').connect(_on_channels_updated)
# Criteria that must be met to set target capacitance.
threshold_criteria = [duration_s > 0,
volume_threshold > 0,
len(requested_electrodes) > 0,
c_unit_area is not None]
_L().debug('threshold_criteria: `%s`', threshold_criteria)
result = {}
actuated_areas = (dmf_device.electrode_areas
.ix[requested_electrodes.values])
actuated_area = actuated_areas.sum()
if not all(threshold_criteria):
# ## Case 1: no volume threshold specified.
# 1. Set control board state of channels according to requested
# actuation states.
# 2. Wait for channels to be actuated.
actuated_channels = \
db.threshold.actuate_channels(proxy, requested_channels, timeout=5)
# 3. Connect to `capacitance-updated` signal to record capacitance
# values measured during the step.
capacitance_messages = []
def _on_capacitance_updated(message):
message['actuated_channels'] = actuated_channels
message['actuated_area'] = actuated_area
capacitance_messages.append(message)
proxy.signals.signal('capacitance-updated')\
.connect(_on_capacitance_updated)
# 4. Delay for specified duration.
try:
yield asyncio.From(asyncio.sleep(duration_s))
finally:
proxy.signals.signal('capacitance-updated')\
.disconnect(_on_capacitance_updated)
else:
# ## Case 2: volume threshold specified.
#
# A volume threshold has been set for this step.
# Calculate target capacitance based on actuated area.
#
# Note: `app_values['c_liquid']` represents a *specific
# capacitance*, i.e., has units of $F/mm^2$.
meters_squared_area = actuated_area * (1e-3 ** 2) # m^2 area
# Approximate length of unit side in SI units.
si_length, pow10 = si.split(np.sqrt(meters_squared_area))
si_unit = si.SI_PREFIX_UNITS[len(si.SI_PREFIX_UNITS) // 2 +
pow10 // 3]
target_capacitance = volume_threshold * actuated_area * c_unit_area
logger = _L() # use logger with function context
if logger.getEffectiveLevel() <= logging.DEBUG:
message = ('target capacitance: %sF (actuated area: (%.1f '
'%sm^2) actuated channels: %s)' %
(si.si_format(target_capacitance), si_length ** 2,
si_unit, requested_channels))
map(logger.debug, message.splitlines())
# Wait for target capacitance to be reached in background thread,
# timing out if the specified duration is exceeded.
co_future = \
db.threshold.co_target_capacitance(proxy,
requested_channels,
target_capacitance,
allow_disabled=False,
timeout=duration_s)
try:
dropbot_event = yield asyncio.From(asyncio
.wait_for(co_future,
duration_s))
_L().debug('target capacitance reached: `%s`', dropbot_event)
actuated_channels = dropbot_event['actuated_channels']
capacitance_messages = dropbot_event['capacitance_updates']
# Add actuated area to capacitance update messages.
for capacitance_i in capacitance_messages:
capacitance_i['actuated_area'] = actuated_area
capacitance_i.pop('actuation_uuid1', None)
result['threshold'] = {'target': dropbot_event['target'],
'measured': dropbot_event['new_value'],
'start': dropbot_event['start'],
'end': dropbot_event['end']}
# Show notification in main window status bar.
if logger.getEffectiveLevel() <= logging.DEBUG:
status = ('reached %sF (> %sF) over electrodes: %s (%.1f '
'%sm^2) after %ss' %
(si.si_format(result['threshold']['measured']),
si.si_format(result['threshold']['target']),
actuated_channels, si_length ** 2, si_unit,
(dropbot_event['end'] -
dropbot_event['start']).total_seconds()))
logger.debug(status)
except asyncio.TimeoutError:
raise RuntimeError('Timed out waiting for target capacitance.')
yield asyncio.From(channels_updated.wait())
actuated_electrodes = (dmf_device.electrodes_by_channel
.loc[actuated_channels])
# Return list of actuated channels (which _may_ be fewer than the
# number of requested actuated channels if one or more channels is
# _disabled_).
result.update({'actuated_electrodes': actuated_electrodes,
'capacitance_messages': capacitance_messages,
'actuated_channels': actuated_channels,
'actuated_area': actuated_area})
raise asyncio.Return(result)
@asyncio.coroutine
def execute(proxy, dmf_device, plugin_kwargs, signals):
'''
Parameters
----------
plugin_kwargs : dict
Plugin settings as JSON serializable dictionary.
signals : blinker.Namespace
Signals namespace.
'''
def verify_connected(coro):
@asyncio.coroutine
def _wrapped(*args, **kwargs):
if proxy is None:
raise RuntimeError('DropBot not connected.')
result = yield asyncio.From(coro(*args, **kwargs))
raise asyncio.Return(result)
return _wrapped
@verify_connected
@asyncio.coroutine
def _set_frequency(frequency):
proxy.frequency = frequency
@verify_connected
@asyncio.coroutine
def _set_voltage(voltage):
proxy.voltage = voltage
@verify_connected
@asyncio.coroutine
def on_actuation_request(electrode_states, duration_s=0):
'''
XXX Coroutine XXX
Actuate electrodes according to specified states.
Parameters
----------
electrode_states : pandas.Series
duration_s : float, optional
If ``volume_threshold`` step option is set, maximum duration before
timing out. Otherwise, time to actuate before actuation is
considered completed.
Returns
-------
actuated_electrodes : list
List of actuated electrode IDs.
'''
try:
result = yield asyncio\
.From(actuate(proxy, dmf_device,
electrode_states, duration_s=duration_s,
volume_threshold=volume_threshold,
c_unit_area=c_unit_area))
# Notify other plugins that actuation completed.
responses = signals.signal('actuation-completed')\
.send('dropbot_plugin', **result)
yield asyncio.From(asyncio.gather(*(r[1] for r in responses)))
except asyncio.CancelledError:
raise
except:
logging.info('on_actuation_request', exc_info=True)
raise
else:
raise asyncio.Return(result['actuated_electrodes'])
kwargs = plugin_kwargs.get(NAME, {})
volume_threshold = kwargs.get('volume_threshold')
c_unit_area = kwargs.get('c_unit_area')
signals.signal('set-frequency').connect(_set_frequency, weak=False)
signals.signal('set-voltage').connect(_set_voltage, weak=False)
signals.signal('on-actuation-request').connect(on_actuation_request,
weak=False)