etho-python 0.22.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- etho/__init__.py +9 -0
- etho/app.py +569 -0
- etho/assets/etho_icon1_pipeline_dark.svg +23 -0
- etho/assets/etho_icon1_pipeline_light.svg +30 -0
- etho/cli.py +215 -0
- etho/client.py +384 -0
- etho/services/ANAZeroService.py +123 -0
- etho/services/BLTZeroService.py +108 -0
- etho/services/DAQZeroService.py +326 -0
- etho/services/DLPZeroService.py +240 -0
- etho/services/GCMZeroService.py +271 -0
- etho/services/GOVZeroService.py +231 -0
- etho/services/NICounterZeroService.py +92 -0
- etho/services/NITriggerZeroService.py +120 -0
- etho/services/TemplateZeroService.py +98 -0
- etho/services/ZeroService.py +272 -0
- etho/services/__init__.py +0 -0
- etho/services/callbacks/__init__.py +19 -0
- etho/services/callbacks/_base.py +92 -0
- etho/services/callbacks/_image.py +798 -0
- etho/services/callbacks/_trace.py +456 -0
- etho/services/camera/__init__.py +13 -0
- etho/services/camera/base.py +164 -0
- etho/services/camera/basler.py +201 -0
- etho/services/camera/dummy.py +139 -0
- etho/services/camera/hamamatsu.py +133 -0
- etho/services/camera/spinnaker.py +317 -0
- etho/services/camera/ximea.py +167 -0
- etho/services/daq/IOTask.py +311 -0
- etho/services/daq/ai.py +174 -0
- etho/services/dlp/dlp_make_warpfiles.py +131 -0
- etho/services/dlp/dlp_runners.py +238 -0
- etho/services/utils/__init__.py +0 -0
- etho/services/utils/concurrent_task.py +236 -0
- etho/services/utils/log_exceptions.py +39 -0
- etho/utils/__init__.py +0 -0
- etho/utils/calibration.py +88 -0
- etho/utils/config.py +41 -0
- etho/utils/runner.py +121 -0
- etho/utils/shuffled_cycle.py +45 -0
- etho/utils/sound.py +336 -0
- etho/utils/tui.py +105 -0
- etho/utils/zeroclient.py +95 -0
- etho_python-0.22.0.dist-info/METADATA +49 -0
- etho_python-0.22.0.dist-info/RECORD +47 -0
- etho_python-0.22.0.dist-info/WHEEL +4 -0
- etho_python-0.22.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Define your own class here (see examples below for how to do that),
|
|
3
|
+
decorate with `@register_runner`.
|
|
4
|
+
Then select runners and set init params in prot file:
|
|
5
|
+
`
|
|
6
|
+
DLP:
|
|
7
|
+
runners:
|
|
8
|
+
LED_blinker: # this needs to be the name of the class
|
|
9
|
+
object: 'Rect' # should be the classname: psychopy.visuals.NAME
|
|
10
|
+
led_frame: 360
|
|
11
|
+
led_duration: 180
|
|
12
|
+
LED_blinker_file:
|
|
13
|
+
object: 'Rect' # should be the classname: psychopy.visuals.NAME
|
|
14
|
+
filename: `absolute_path_to_file/filename.npz` # needs to have fields as expected by the class
|
|
15
|
+
`
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
NOTE: for the logging to work, ensure that the values returned by `status` have the same type when initialized.
|
|
19
|
+
"""
|
|
20
|
+
import numpy as np
|
|
21
|
+
import matplotlib.pyplot as plt
|
|
22
|
+
import pandas as pd
|
|
23
|
+
from typing import Callable, Optional, Dict
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# Populated by decorating classes with `register_runner`.
|
|
27
|
+
# Enables selecting runners by string in `DLPZeroService`.
|
|
28
|
+
runners = dict()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def register_runner(cls: Callable):
|
|
32
|
+
"""Adds func to model_dict Dict[str: Class]. For selecting runners by string."""
|
|
33
|
+
runners[cls.__name__] = cls
|
|
34
|
+
return cls
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DLP_runner:
|
|
38
|
+
"""Base class for all runners."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, win, **kwargs):
|
|
41
|
+
"""All variants need to accept `win` as the first param
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
win (psychopy.visual.Window): PsychoPy win instance
|
|
45
|
+
"""
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def update(self, frame_number: int, **kwargs) -> Dict:
|
|
49
|
+
"""Will be called by DLPZeroService on every frame."""
|
|
50
|
+
raise NotImplementedError()
|
|
51
|
+
|
|
52
|
+
def status(self) -> Dict: # Dict[key:str, value:int/float]
|
|
53
|
+
"""Generate status message."""
|
|
54
|
+
return {}
|
|
55
|
+
|
|
56
|
+
def destroy(self):
|
|
57
|
+
"""Free any resources (close files etc)."""
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@register_runner
|
|
62
|
+
class LED_blinker(DLP_runner):
|
|
63
|
+
"""Blinking square read in by a photodiode for syncing DLP frames with DAQ samples."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, win, object, led_size=0.3, led_pos=[-1, -0.3], led_frame=180 * 60, led_duration=180, **kwignore):
|
|
66
|
+
"""Set up LED blinker
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
win (psychopy.visual.Window): PsychoPy win instance
|
|
70
|
+
object (e.g. psychopy.visual.Rect/Circle): Geometric object to manipulate on screen. Specify in protocol file as string.
|
|
71
|
+
led_size (float, optional): [description]. Defaults to 0.3.
|
|
72
|
+
led_pos (list, optional): [description]. Defaults to [-1,-0.3].
|
|
73
|
+
led_frame ([type], optional): [description]. Defaults to 180*60.
|
|
74
|
+
led_duration (int, optional): [description]. Defaults to 180.
|
|
75
|
+
kwignore (Dict): Extra args to ignore for robustness when passing unspecified parameters.
|
|
76
|
+
"""
|
|
77
|
+
self.led_size = led_size
|
|
78
|
+
self.led_pos = led_pos
|
|
79
|
+
self.led_frame = led_frame
|
|
80
|
+
self.led_duration = led_duration
|
|
81
|
+
self.win = win
|
|
82
|
+
|
|
83
|
+
self.rectangle = object(
|
|
84
|
+
win=self.win,
|
|
85
|
+
units="norm",
|
|
86
|
+
size=self.led_size,
|
|
87
|
+
pos=self.led_pos,
|
|
88
|
+
autoDraw=True,
|
|
89
|
+
fillColor=[-1, -1, -1],
|
|
90
|
+
lineWidth=0,
|
|
91
|
+
opacity=1,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def update(self, frame_number: int, ball_info: Dict, **kwargs: Optional[Dict]):
|
|
95
|
+
"""Update LED blinker.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
frame_number (int): [description]
|
|
99
|
+
ball_info (Dict): from fictrac (not used)
|
|
100
|
+
**kwargs (Optional[Any]): could be externally set positions, e.g. during closed loop (not used)
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
Dict[str: float/int]: values should be numbers - not lists or np.arrays!
|
|
104
|
+
"""
|
|
105
|
+
if frame_number % self.led_frame == 0:
|
|
106
|
+
self.rectangle.opacity = 0.0
|
|
107
|
+
|
|
108
|
+
if (frame_number - self.led_duration) % self.led_frame == 0:
|
|
109
|
+
self.rectangle.opacity = 1.0
|
|
110
|
+
|
|
111
|
+
return self.status()
|
|
112
|
+
|
|
113
|
+
def status(self):
|
|
114
|
+
"""Generate status message."""
|
|
115
|
+
log_msg = {"opacity": self.rectangle.opacity}
|
|
116
|
+
return log_msg
|
|
117
|
+
|
|
118
|
+
def destroy(self, **kwargs):
|
|
119
|
+
"""Free any resources (close files etc)."""
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# Example with stim control via param file
|
|
124
|
+
@register_runner
|
|
125
|
+
class ObjectMoverSizer(DLP_runner):
|
|
126
|
+
"""Move and resize object based on `size` and `position` fields in npz file."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, win, object, filename: str, **kwignore):
|
|
129
|
+
"""Set up LED blinker.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
win (psychopy.visual.Window): PsychoPy win instance
|
|
133
|
+
object, e.g. psychopy.visual.Rect
|
|
134
|
+
filename (str): file with stim params
|
|
135
|
+
led_size (float, optional): [description]. Defaults to 0.3.
|
|
136
|
+
led_pos (list, optional): [description]. Defaults to [-1,-0.3].
|
|
137
|
+
kwignore (Dict): Extra args to ignore for robustness when passing unspecified parameters.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
Dict[str: float/int]: values should be numbers - not lists or np.arrays!
|
|
141
|
+
|
|
142
|
+
"""
|
|
143
|
+
self.object = object(
|
|
144
|
+
win=win, units="norm", size=0, pos=[-1, 0], radius=2 * 1 / 270, autoDraw=True, fillColor=[-1, -1, -1], lineWidth=0
|
|
145
|
+
)
|
|
146
|
+
# self.object = object(win=win, units = 'norm', size=self.led_size, pos=self.led_pos,
|
|
147
|
+
# autoDraw = True, fillColor=[-1, -1, -1], lineWidth=0, opacity=1)
|
|
148
|
+
|
|
149
|
+
# do not use plain arrays - either pd.DataFrames.read_csv, or np.recarrays
|
|
150
|
+
# so we parameters in the data are more obvious
|
|
151
|
+
# if filename is list -> load all extend the list
|
|
152
|
+
file = np.load(filename)
|
|
153
|
+
self.params = dict(file) # force read all data from disk into memory
|
|
154
|
+
self.arrays_length = min([len(x) for x in self.params.values()])
|
|
155
|
+
|
|
156
|
+
def update(self, frame_number: int, ball_info: Dict, **kwargs: Optional[Dict]):
|
|
157
|
+
"""Update LED blinker.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
frame_number (int): [description]
|
|
161
|
+
ball_info (Dict): from fictrac
|
|
162
|
+
**kwargs (Optional[Any]): could be externally set positions, e.g. during closed loop
|
|
163
|
+
Returns:
|
|
164
|
+
Dict[str: float/int]: values should be numbers - not lists or np.arrays!
|
|
165
|
+
"""
|
|
166
|
+
self.object.size = self.params["sizes"][frame_number % self.arrays_length]
|
|
167
|
+
self.object.pos = [self.params["positions"][frame_number % self.arrays_length], 0]
|
|
168
|
+
return self.status()
|
|
169
|
+
|
|
170
|
+
def status(self):
|
|
171
|
+
"""Generate status message."""
|
|
172
|
+
log_msg = {"size": self.object.size, "position_0": self.object.pos[0], "position_1": self.object.pos[1]}
|
|
173
|
+
return log_msg
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@register_runner
|
|
177
|
+
class ObjectCirclesGrid(DLP_runner):
|
|
178
|
+
"""Move and resize object based on `size` and `position` fields in npz file."""
|
|
179
|
+
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
win,
|
|
183
|
+
object,
|
|
184
|
+
grid_direction_change_frames: int = 30 * 180,
|
|
185
|
+
grid_speed: float = 2 / 180,
|
|
186
|
+
grid_direction: int = 1,
|
|
187
|
+
ncircles: int = 1,
|
|
188
|
+
**kwignore
|
|
189
|
+
):
|
|
190
|
+
"""Set up grid of circles, using a list of Circles.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
win (psychopy.visual.Window): PsychoPy win instance
|
|
194
|
+
object, e.g. psychopy.visual.Rect
|
|
195
|
+
filename (str): file with stim params
|
|
196
|
+
kwignore (Dict): Extra args to ignore for robustness when passing unspecified parameters.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
Dict[str: float/int]: values should be numbers - not lists or np.arrays!
|
|
200
|
+
"""
|
|
201
|
+
self.grid_direction = grid_direction
|
|
202
|
+
self.grid_direction_change_frames = grid_direction_change_frames
|
|
203
|
+
self.grid_speed = grid_speed
|
|
204
|
+
self.object = [
|
|
205
|
+
object(
|
|
206
|
+
win=win,
|
|
207
|
+
units="norm",
|
|
208
|
+
size=15,
|
|
209
|
+
pos=[x, 0],
|
|
210
|
+
radius=2 * 1 / 270,
|
|
211
|
+
autoDraw=True,
|
|
212
|
+
fillColor=[-1, -1, -1],
|
|
213
|
+
lineWidth=0,
|
|
214
|
+
)
|
|
215
|
+
for x in np.linspace(-1, 1, ncircles)
|
|
216
|
+
]
|
|
217
|
+
|
|
218
|
+
def update(self, frame_number: int, ball_info: Dict, **kwargs: Optional[Dict]):
|
|
219
|
+
"""Update LED blinker.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
frame_number (int): [description]
|
|
223
|
+
ball_info (Dict): from fictrac
|
|
224
|
+
**kwargs (Optional[Any]): could be externally set positions, e.g. during closed loop
|
|
225
|
+
Returns:
|
|
226
|
+
Dict[str: float/int]: values should be numbers - not lists or np.arrays!
|
|
227
|
+
"""
|
|
228
|
+
if frame_number % self.grid_direction_change_frames == 0:
|
|
229
|
+
self.grid_direction *= -1
|
|
230
|
+
for mc in self.object:
|
|
231
|
+
new_x = mc.pos[0] + self.grid_direction * self.grid_speed
|
|
232
|
+
mc.pos = [new_x if new_x * self.grid_direction < 1 else new_x - self.grid_direction * 2, 0]
|
|
233
|
+
return self.status()
|
|
234
|
+
|
|
235
|
+
def status(self):
|
|
236
|
+
"""Generate status message."""
|
|
237
|
+
log_msg = {"grid_direction": self.grid_direction}
|
|
238
|
+
return log_msg
|
|
File without changes
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Communication primitives with a common interface
|
|
2
|
+
and a helper class for running tasks in independent processes."""
|
|
3
|
+
from multiprocessing import Process
|
|
4
|
+
import multiprocessing as mp
|
|
5
|
+
import time
|
|
6
|
+
import sys
|
|
7
|
+
import numpy as np
|
|
8
|
+
import ctypes
|
|
9
|
+
from typing import Optional, Any, Dict, Callable, Literal
|
|
10
|
+
import multiprocessing.connection
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SharedNumpyArray:
|
|
14
|
+
"""Class for sharing a numpy array between processes.
|
|
15
|
+
|
|
16
|
+
Contains functions for synchronized read/write access and a staleness indicator.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
WHOAMI = "array"
|
|
20
|
+
|
|
21
|
+
def __init__(self, shape, ctype=ctypes.c_double):
|
|
22
|
+
"""[summary]
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
shape (tuple/list-like): [description]
|
|
26
|
+
ctype ([type], optional): Data type of the numpy array. Defaults to ctypes.c_double (is np.float64).
|
|
27
|
+
"""
|
|
28
|
+
self.shape = shape # need to know shape before hand since the array has to be initialized at init
|
|
29
|
+
self.qsize = 0 # for interface compatibility with Queues and Pipes
|
|
30
|
+
self.first = True
|
|
31
|
+
# indicator whether the current array values are "fresh"
|
|
32
|
+
# stale is set to False upon `put` and to True on `get`
|
|
33
|
+
self._stale = mp.RawValue("b", True)
|
|
34
|
+
# add one more RawValue for system_time?
|
|
35
|
+
|
|
36
|
+
# common lock to sync read/write access
|
|
37
|
+
self._lock = mp.Lock()
|
|
38
|
+
# will be the np representation of the base array - need to convert from base array
|
|
39
|
+
# on both ends for updates to propagate - see _asnp()
|
|
40
|
+
self._shared_array = None # initialize with None to mark as not yet created
|
|
41
|
+
|
|
42
|
+
# add one more RawValue for system_time?
|
|
43
|
+
with self._lock:
|
|
44
|
+
# create array in shared memory segment
|
|
45
|
+
self._shared_array_base = mp.RawArray(ctype, int(np.prod(self.shape)))
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def stale(self):
|
|
49
|
+
"""Thread safe access to whether or not the current array values have been get-ed already."""
|
|
50
|
+
with self._lock:
|
|
51
|
+
return self._stale.value
|
|
52
|
+
|
|
53
|
+
def _asnp(self):
|
|
54
|
+
if self._shared_array is None:
|
|
55
|
+
# need to get the np array from the underlying base array on both ends, but
|
|
56
|
+
# only once - we detect first access by setting _array_base=None at init.
|
|
57
|
+
# convert to numpy array vie ctypeslib
|
|
58
|
+
self._shared_array = np.ctypeslib.as_array(self._shared_array_base)
|
|
59
|
+
# do a reshape for correct shape
|
|
60
|
+
# Returns a masked array containing the same data, but with a new shape.
|
|
61
|
+
# The result is a view on the original array
|
|
62
|
+
self._shared_array = self._shared_array.reshape(self.shape)
|
|
63
|
+
return self._shared_array
|
|
64
|
+
|
|
65
|
+
def poll(self):
|
|
66
|
+
"""Returns true if the array has been update since the last put."""
|
|
67
|
+
return not self.stale
|
|
68
|
+
|
|
69
|
+
def get(self, timeout=None, block=True):
|
|
70
|
+
"""Returns array values. Block is unsed and their for interface consistency with Queue."""
|
|
71
|
+
with self._lock:
|
|
72
|
+
self._stale.value = True
|
|
73
|
+
return self._asnp()
|
|
74
|
+
|
|
75
|
+
def put(self, data):
|
|
76
|
+
"""Update the values in the shared array."""
|
|
77
|
+
if data is None:
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
with self._lock:
|
|
81
|
+
self._shared_array = self._asnp()
|
|
82
|
+
self._shared_array[:] = data[0][:]
|
|
83
|
+
self._stale.value = False
|
|
84
|
+
|
|
85
|
+
def close(self):
|
|
86
|
+
del self
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Faucet:
|
|
90
|
+
"""Wrapper for Pipe connection objects that exposes
|
|
91
|
+
`get` function for common interface with Queues."""
|
|
92
|
+
|
|
93
|
+
WHOAMI = "pipe"
|
|
94
|
+
|
|
95
|
+
def __init__(self, connection: multiprocessing.connection.Connection):
|
|
96
|
+
"""Wraps Connection object returned when calling Pipe and
|
|
97
|
+
delegates function calls to have a common interface with the Queue.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
connection (multiprocessing.connection.Connection): [description]
|
|
101
|
+
"""
|
|
102
|
+
self.connection = connection
|
|
103
|
+
self.qsize = 0
|
|
104
|
+
|
|
105
|
+
# delegate function calls
|
|
106
|
+
self.send = self.connection.send
|
|
107
|
+
self.close = self.connection.close
|
|
108
|
+
self.closed = self.connection.closed
|
|
109
|
+
|
|
110
|
+
def get(self, block: bool = True, timeout: Optional[float] = 0.001, empty_value: Any = None) -> Any:
|
|
111
|
+
"""Mimics the logic of the `Queue.get`.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
block (bool, optional): [description]. Defaults to True.
|
|
115
|
+
timeout (float, optional): [description]. Defaults to 0.001.
|
|
116
|
+
empty_value ([type], optional): [description]. Defaults to None.
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
[type]: [description]
|
|
120
|
+
"""
|
|
121
|
+
if block:
|
|
122
|
+
timeout = None
|
|
123
|
+
if self.connection.poll(timeout):
|
|
124
|
+
return self.connection.recv()
|
|
125
|
+
else:
|
|
126
|
+
return empty_value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def Pipe(duplex: bool = False):
|
|
130
|
+
receiver, sender = mp.Pipe(duplex)
|
|
131
|
+
receiver = Faucet(receiver)
|
|
132
|
+
sender = Faucet(sender)
|
|
133
|
+
return sender, receiver
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def Queue(maxsize: int = 0):
|
|
137
|
+
sender = mp.Queue(maxsize)
|
|
138
|
+
sender.send = sender.put
|
|
139
|
+
receiver = sender
|
|
140
|
+
return sender, receiver
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def NumpyArray(shape=(1,), ctype=ctypes.c_double):
|
|
144
|
+
sender = SharedNumpyArray(shape, ctype)
|
|
145
|
+
sender.send = sender.put
|
|
146
|
+
receiver = sender
|
|
147
|
+
return sender, receiver
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class ConcurrentTask:
|
|
151
|
+
"""Helper class for running tasks in independent
|
|
152
|
+
processes with communication tools attached."""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
task: Callable,
|
|
157
|
+
task_kwargs: Dict[str, Any] = {},
|
|
158
|
+
comms: Literal["array", "pipe", "queue"] = "queue",
|
|
159
|
+
comms_kwargs: Dict[str, Any] = {},
|
|
160
|
+
taskstopsignal: Any = None,
|
|
161
|
+
):
|
|
162
|
+
"""[summary]
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
task (Callable): First arg to task must be the end of the comms and is provided via `args`.
|
|
166
|
+
task_kwargs (Dict[str, Any], optional): Defaults to {}.
|
|
167
|
+
comms (Literal["array", "pipe", "queue"], optional): For passing data to the task. Either "queue", "pipe", or "array".
|
|
168
|
+
"array" if you want speed and don't mind loosing data (displaying data)
|
|
169
|
+
or if you want to ensure you are always assessing fresh data (realtime feedback).
|
|
170
|
+
"queue" is slower but great when data loss is unacceptable (saving data).
|
|
171
|
+
"pipe" probably never??
|
|
172
|
+
Defaults to "queue".
|
|
173
|
+
comms_kwargs (Dict[str, Any], optional): kwargs for constructing comms. Defaults to {}.
|
|
174
|
+
taskstopsignal (Any, optional): Data to send over comms that tells the task to stop. Defaults to None.
|
|
175
|
+
Raises:
|
|
176
|
+
ValueError: for unknown comms
|
|
177
|
+
"""
|
|
178
|
+
self.comms = comms
|
|
179
|
+
self.taskstopsignal = taskstopsignal
|
|
180
|
+
if self.comms == "pipe":
|
|
181
|
+
self._sender, self._receiver = Pipe(**comms_kwargs)
|
|
182
|
+
elif self.comms == "queue":
|
|
183
|
+
self._sender, self._receiver = Queue(**comms_kwargs)
|
|
184
|
+
elif self.comms == "array":
|
|
185
|
+
self._sender, self._receiver = NumpyArray(**comms_kwargs)
|
|
186
|
+
else:
|
|
187
|
+
raise ValueError(f'Unknown comms {comms} - allowed values are "pipe", "queue", "array"')
|
|
188
|
+
|
|
189
|
+
# delegate send calls from sender
|
|
190
|
+
self.send = self._sender.send
|
|
191
|
+
|
|
192
|
+
self._process = Process(target=task, args=(self._receiver,), kwargs=task_kwargs)
|
|
193
|
+
self.start = self._process.start
|
|
194
|
+
|
|
195
|
+
def finish(
|
|
196
|
+
self, verbose: bool = False, sleepduration: float = 1, sleepcycletimeout: int = 5, maxsleepcycles: int = 100000000
|
|
197
|
+
):
|
|
198
|
+
if self.comms == "queue":
|
|
199
|
+
sleepcounter = 0
|
|
200
|
+
try:
|
|
201
|
+
queuesize = self._sender.qsize()
|
|
202
|
+
except NotImplementedError: # catch python bug on OSX
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
queuehasnotchangedcounter = 0
|
|
206
|
+
while queuesize > 0 and sleepcounter < maxsleepcycles and queuehasnotchangedcounter < sleepcycletimeout:
|
|
207
|
+
time.sleep(sleepduration)
|
|
208
|
+
try:
|
|
209
|
+
queuesize = self._sender.qsize()
|
|
210
|
+
except NotImplementedError: # catch python bug on OSX
|
|
211
|
+
break
|
|
212
|
+
sleepcounter += 1
|
|
213
|
+
queuehasnotchanged = queuesize == self._sender.qsize()
|
|
214
|
+
if queuehasnotchanged:
|
|
215
|
+
queuehasnotchangedcounter += 1
|
|
216
|
+
else:
|
|
217
|
+
queuehasnotchangedcounter = 0
|
|
218
|
+
if verbose:
|
|
219
|
+
sys.stdout.write(
|
|
220
|
+
"\r waiting {} seconds for {} frames to self.".format(sleepcounter, self._sender.qsize())
|
|
221
|
+
) # frame interval in ms
|
|
222
|
+
|
|
223
|
+
def close(self, sleep_time: float = 0.5):
|
|
224
|
+
self.send(self.taskstopsignal)
|
|
225
|
+
time.sleep(sleep_time)
|
|
226
|
+
try:
|
|
227
|
+
self._process.terminate()
|
|
228
|
+
except AttributeError:
|
|
229
|
+
pass
|
|
230
|
+
time.sleep(sleep_time)
|
|
231
|
+
self._sender.close()
|
|
232
|
+
del self._process
|
|
233
|
+
del self._sender
|
|
234
|
+
if self._receiver is not None:
|
|
235
|
+
self._receiver.close()
|
|
236
|
+
del self._receiver
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def for_all_methods(decorator):
|
|
5
|
+
""" "Decorates all methods of a class with 'decorator'."""
|
|
6
|
+
|
|
7
|
+
def decorate(cls):
|
|
8
|
+
for attr in cls.__dict__: # there's propably a better way to do this
|
|
9
|
+
if callable(getattr(cls, attr)):
|
|
10
|
+
setattr(cls, attr, decorator(getattr(cls, attr)))
|
|
11
|
+
return cls
|
|
12
|
+
|
|
13
|
+
return decorate
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def log_exceptions(logger=None):
|
|
17
|
+
"""
|
|
18
|
+
A decorator that wraps the passed in function and logs
|
|
19
|
+
exceptions should one occur
|
|
20
|
+
|
|
21
|
+
@param logger (optional): The logging object
|
|
22
|
+
"""
|
|
23
|
+
if logger is None:
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
def decorator(func):
|
|
27
|
+
def wrapper(*args, **kwargs):
|
|
28
|
+
try:
|
|
29
|
+
return func(*args, **kwargs)
|
|
30
|
+
except Exception:
|
|
31
|
+
# log the exception
|
|
32
|
+
err = f"Exception in {func.__name__}: "
|
|
33
|
+
logger.exception(err)
|
|
34
|
+
# re-raise the exception
|
|
35
|
+
raise
|
|
36
|
+
|
|
37
|
+
return wrapper
|
|
38
|
+
|
|
39
|
+
return decorator
|
etho/utils/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
from typing import Optional, Dict, Any
|
|
2
|
+
import logging
|
|
3
|
+
import numpy as np
|
|
4
|
+
from .config import readconfig, undefaultify
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def parse(filename):
|
|
11
|
+
calibration_data = undefaultify(readconfig(filename))
|
|
12
|
+
|
|
13
|
+
calibrations = {}
|
|
14
|
+
for key, val in calibration_data.items():
|
|
15
|
+
try:
|
|
16
|
+
if "frequency" in val:
|
|
17
|
+
calibrations[key] = CalibrationLinear(val["output"], val["gain"], val["frequency"], attr=val)
|
|
18
|
+
else:
|
|
19
|
+
calibrations[key] = CalibrationCurve(val["output"], val["gain"], attr=val)
|
|
20
|
+
except Exception as e:
|
|
21
|
+
logging.exception(f'Something went wrong parsing calibrations from block "{key}" in {filename}.', exc_info=e)
|
|
22
|
+
return calibrations
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CalibrationCurve:
|
|
26
|
+
# nonlinear gain, calibrated at a single frequency, multiple intensities
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
intensities: np.ndarray[float],
|
|
31
|
+
gains: np.ndarray[float],
|
|
32
|
+
frequencies: Optional[np.ndarray[float]] = None,
|
|
33
|
+
interpolate: Optional[bool] = True,
|
|
34
|
+
extrapolate: Optional[bool] = True,
|
|
35
|
+
attr: Optional[Dict[str, Any]] = None,
|
|
36
|
+
):
|
|
37
|
+
self.intensities = intensities
|
|
38
|
+
self.gains = gains
|
|
39
|
+
self.interpolate = interpolate
|
|
40
|
+
self.extrapolate = extrapolate
|
|
41
|
+
self.attr = attr if attr is not None else {}
|
|
42
|
+
print(self.attr)
|
|
43
|
+
|
|
44
|
+
self.data = {o: g for o, g in zip(self.intensities, self.gains)}
|
|
45
|
+
|
|
46
|
+
def __str__(self):
|
|
47
|
+
try:
|
|
48
|
+
return f"Calbration curve for outputs in {self.attr['output_units']}."
|
|
49
|
+
except:
|
|
50
|
+
return super().__str__()
|
|
51
|
+
|
|
52
|
+
def __call__(self, intensity, frequency=None):
|
|
53
|
+
if self.interpolate:
|
|
54
|
+
gain = np.interp(intensity, self.intensities, self.gains, left=0)
|
|
55
|
+
else:
|
|
56
|
+
print('e')
|
|
57
|
+
gain = self.data[intensity]
|
|
58
|
+
return gain
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CalibrationLinear:
|
|
62
|
+
# linear gain, calibrated at a single intensity, multiple frequencies
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self, intensities, gains, frequencies, interpolate=True, extrapolate=True, attr: Optional[Dict[str, Any]] = None
|
|
66
|
+
):
|
|
67
|
+
self.intensities = np.asarray(intensities)
|
|
68
|
+
self.gains = np.asarray(gains)
|
|
69
|
+
self.frequencies = np.asarray(frequencies)
|
|
70
|
+
self.attr = attr if attr is not None else {}
|
|
71
|
+
|
|
72
|
+
if len(self.intensities) != len(self.gains) or len(self.intensities) != len(self.frequencies):
|
|
73
|
+
raise ValueError(
|
|
74
|
+
f"Intensities, gains and frequencies need to have the same length but have {len(self.intensities)}, {len(self.gains)} and {len(self.frequencies)} elements."
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
self.gains /= self.intensities # normalize gains to correspond to intensities of 1.0.
|
|
78
|
+
self.interpolate = interpolate
|
|
79
|
+
self.extrapolate = extrapolate
|
|
80
|
+
|
|
81
|
+
self.data = {o: g for o, g in zip(self.frequencies, self.gains)}
|
|
82
|
+
|
|
83
|
+
def __call__(self, intensity, frequency=None):
|
|
84
|
+
if self.interpolate:
|
|
85
|
+
gain = intensity * np.interp(frequency, self.frequencies, self.gains)
|
|
86
|
+
else:
|
|
87
|
+
gain = intensity * self.data[frequency]
|
|
88
|
+
return gain
|
etho/utils/config.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import pathlib
|
|
2
|
+
import os
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
import yaml
|
|
5
|
+
from typing import Dict, Union, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# Find global config file
|
|
9
|
+
HOME = str(pathlib.Path.home())
|
|
10
|
+
GLOBALCONFIGFILEPATH = os.path.join(HOME, "ethoconfig/ethoconfig.yml")
|
|
11
|
+
|
|
12
|
+
if not os.path.exists(GLOBALCONFIGFILEPATH):
|
|
13
|
+
raise FileNotFoundError("No config file found. Should be at ~/ethoconfig/ethoconfig.yml")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def defaultify(d: Dict, defaultfactory=lambda: None) -> defaultdict:
|
|
17
|
+
"""Convert nested dict to defaultdict."""
|
|
18
|
+
if not isinstance(d, dict):
|
|
19
|
+
return d
|
|
20
|
+
return defaultdict(defaultfactory, {k: defaultify(v, defaultfactory) for k, v in d.items()})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def undefaultify(d: Union[Dict, defaultdict]) -> Dict:
|
|
24
|
+
if not isinstance(d, dict):
|
|
25
|
+
return d
|
|
26
|
+
return {k: undefaultify(v) for k, v in d.items()}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def saveconfig(filename: str, prot: Union[Dict, defaultdict]):
|
|
30
|
+
prot = undefaultify(prot)
|
|
31
|
+
with open(filename, "w") as f:
|
|
32
|
+
yaml.dump(prot, f)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def readconfig(filename: Optional[str] = None) -> defaultdict:
|
|
36
|
+
if filename is None:
|
|
37
|
+
filename = GLOBALCONFIGFILEPATH
|
|
38
|
+
|
|
39
|
+
with open(filename, "r") as f:
|
|
40
|
+
config_dict = yaml.load(f.read(), Loader=yaml.FullLoader)
|
|
41
|
+
return defaultify(config_dict)
|