etho-python 1.0__py3-none-any.whl → 1.2__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/app.py +235 -242
- etho/cli.py +72 -19
- etho/res_app.py +225 -0
- etho/resumable.py +283 -0
- etho/services/DAQZeroService.py +1 -2
- etho/services/GCMZeroService.py +6 -2
- etho/services/GOVZeroService.py +31 -0
- etho/services/NICounterZeroService.py +80 -73
- etho/services/resumable.py +476 -0
- etho/utils/sound.py +62 -98
- {etho_python-1.0.dist-info → etho_python-1.2.dist-info}/METADATA +48 -21
- {etho_python-1.0.dist-info → etho_python-1.2.dist-info}/RECORD +15 -11
- etho_python-1.2.dist-info/licenses/LICENSE +21 -0
- {etho_python-1.0.dist-info → etho_python-1.2.dist-info}/WHEEL +0 -0
- {etho_python-1.0.dist-info → etho_python-1.2.dist-info}/entry_points.txt +0 -0
etho/cli.py
CHANGED
|
@@ -36,6 +36,52 @@ def run(
|
|
|
36
36
|
debug=debug,
|
|
37
37
|
preview=preview,
|
|
38
38
|
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def res_run(
|
|
42
|
+
protocolfile: str,
|
|
43
|
+
playlistfile: Optional[str] = None,
|
|
44
|
+
*,
|
|
45
|
+
save_prefix: Optional[str] = None,
|
|
46
|
+
show_progress: bool = True,
|
|
47
|
+
debug: bool = False,
|
|
48
|
+
preview: bool = False,
|
|
49
|
+
):
|
|
50
|
+
"""Starts a resumable DAQ/GCM experiment from the CLI."""
|
|
51
|
+
from . import resumable
|
|
52
|
+
|
|
53
|
+
return resumable.run(
|
|
54
|
+
protocolfile=protocolfile,
|
|
55
|
+
playlistfile=playlistfile,
|
|
56
|
+
save_prefix=save_prefix,
|
|
57
|
+
show_progress=show_progress,
|
|
58
|
+
debug=debug,
|
|
59
|
+
preview=preview,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def res_gui(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
64
|
+
"""Opens the resumable DAQ/GCM graphical user interface."""
|
|
65
|
+
from . import res_app
|
|
66
|
+
|
|
67
|
+
return res_app.main(protocol_folder=protocol_folder, playlist_folder=playlist_folder)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def govee(duration: float = 10.0):
|
|
71
|
+
"""Lists nearby Govee H5075 sensors and their protocol addresses/readings."""
|
|
72
|
+
import asyncio
|
|
73
|
+
|
|
74
|
+
from .services.GOVZeroService import discover_h5075_sensors
|
|
75
|
+
|
|
76
|
+
print(f"Scanning for Govee sensors for {duration:g} seconds...", flush=True)
|
|
77
|
+
sensors = asyncio.run(discover_h5075_sensors(duration))
|
|
78
|
+
if not sensors:
|
|
79
|
+
print("No Govee H5075 sensors found.")
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
print(f"{'Address (use as GOV.address)':<38} {'Name':<16} {'Temperature':>11} {'Humidity':>9}")
|
|
83
|
+
for address, name, measurement in sensors:
|
|
84
|
+
print(f"{address:<38} {(name or '-'):<16} {measurement.temperature_c:>10.1f}°C {measurement.humidity:>8.1f}%")
|
|
39
85
|
|
|
40
86
|
|
|
41
87
|
def version(*, debug: bool = False):
|
|
@@ -179,15 +225,13 @@ def init():
|
|
|
179
225
|
yaml.dump(protocol, f, Dumper=yaml.SafeDumper)
|
|
180
226
|
|
|
181
227
|
# generate test playlist
|
|
182
|
-
playlist = {
|
|
183
|
-
"stimFileName": {0: "SIN_100_0_1000"},
|
|
184
|
-
"silencePre": {0: 10000},
|
|
185
|
-
"silencePost": {0: 9000},
|
|
186
|
-
"
|
|
187
|
-
"
|
|
188
|
-
|
|
189
|
-
"MODE": {0: None},
|
|
190
|
-
}
|
|
228
|
+
playlist = {
|
|
229
|
+
"stimFileName": {0: "SIN_100_0_1000"},
|
|
230
|
+
"silencePre": {0: 10000},
|
|
231
|
+
"silencePost": {0: 9000},
|
|
232
|
+
"intensity": {0: 0.0},
|
|
233
|
+
"freq": {0: 100},
|
|
234
|
+
}
|
|
191
235
|
path_playlist = home / "ethoconfig/playlists/0_silence.txt"
|
|
192
236
|
logging.info(f" playlist {str(path_playlist)}.")
|
|
193
237
|
pd.DataFrame.from_dict(playlist).to_csv(path_playlist, sep="\t", index=False)
|
|
@@ -198,18 +242,27 @@ def main():
|
|
|
198
242
|
subcommands = {
|
|
199
243
|
"version": version,
|
|
200
244
|
"init": init,
|
|
245
|
+
"govee": govee,
|
|
201
246
|
}
|
|
202
247
|
|
|
203
248
|
if client is not None:
|
|
204
249
|
subcommands.update({"run": run})
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
250
|
+
subcommands["res-run"] = res_run
|
|
251
|
+
try:
|
|
252
|
+
from . import app
|
|
253
|
+
|
|
254
|
+
subcommands["gui"] = app.main
|
|
209
255
|
except (ImportError, ModuleNotFoundError):
|
|
210
|
-
logging.exception("No GUI avalaible.")
|
|
211
|
-
# fall back to function that displays helpful instructions
|
|
212
|
-
subcommands["gui"] = no_gui
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
256
|
+
logging.exception("No GUI avalaible.")
|
|
257
|
+
# fall back to function that displays helpful instructions
|
|
258
|
+
subcommands["gui"] = no_gui
|
|
259
|
+
try:
|
|
260
|
+
from . import res_app
|
|
261
|
+
|
|
262
|
+
subcommands["res-gui"] = res_app.main
|
|
263
|
+
except (ImportError, ModuleNotFoundError):
|
|
264
|
+
logging.exception("No resumable GUI avalaible.")
|
|
265
|
+
subcommands["res-gui"] = no_gui
|
|
266
|
+
|
|
267
|
+
logging.basicConfig(level=logging.INFO, force=True)
|
|
268
|
+
defopt.run(subcommands, show_defaults=False)
|
etho/res_app.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sys
|
|
3
|
+
import threading
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
from qtpy.QtCore import QObject, Signal
|
|
7
|
+
from qtpy.QtWidgets import QApplication, QLabel, QMessageBox, QPushButton, QSizePolicy
|
|
8
|
+
|
|
9
|
+
from .app import MainWindow as EthoMainWindow
|
|
10
|
+
from .app import _system_icon
|
|
11
|
+
from .resumable import ResumableExperimentRunner
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
CONTROL_COLUMN_WIDTH = 145
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WorkerSignals(QObject):
|
|
19
|
+
finished = Signal(str)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MainWindow(EthoMainWindow):
|
|
23
|
+
def __init__(self, protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
24
|
+
super().__init__(protocol_folder, playlist_folder)
|
|
25
|
+
self.setWindowTitle("etho resumable control")
|
|
26
|
+
self.runner = None
|
|
27
|
+
self.worker = None
|
|
28
|
+
self.progress_thread = None
|
|
29
|
+
self.progress_stop_event = None
|
|
30
|
+
self.run_active = False
|
|
31
|
+
self.signals = WorkerSignals()
|
|
32
|
+
self.signals.finished.connect(self.on_worker_finished)
|
|
33
|
+
try:
|
|
34
|
+
self.run_timer.timeout.disconnect(self.sync_run_state)
|
|
35
|
+
except (TypeError, RuntimeError):
|
|
36
|
+
pass
|
|
37
|
+
self.run_timer.stop()
|
|
38
|
+
|
|
39
|
+
buttons = self.layout.itemAtPosition(0, 0).layout()
|
|
40
|
+
self.button["Initialize hardware"] = QPushButton("Initialize hardware")
|
|
41
|
+
self.button["Initialize hardware"].clicked.connect(self.initialize_hardware)
|
|
42
|
+
self.button["Shutdown hardware"] = QPushButton("Shutdown hardware")
|
|
43
|
+
self.button["Shutdown hardware"].clicked.connect(self.shutdown_hardware)
|
|
44
|
+
self.status_label = QLabel("Select a protocol and initialize hardware.")
|
|
45
|
+
self.status_label.setWordWrap(True)
|
|
46
|
+
self.status_label.setFixedWidth(CONTROL_COLUMN_WIDTH)
|
|
47
|
+
self.status_label.setMinimumHeight(72)
|
|
48
|
+
self.status_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
|
|
49
|
+
|
|
50
|
+
buttons.insertWidget(1, self.button["Initialize hardware"])
|
|
51
|
+
buttons.insertWidget(2, self.button["Shutdown hardware"])
|
|
52
|
+
buttons.insertSpacing(3, 12)
|
|
53
|
+
buttons.insertSpacing(6, 8)
|
|
54
|
+
buttons.insertWidget(buttons.count() - 1, self.status_label)
|
|
55
|
+
self.layout.setColumnMinimumWidth(0, CONTROL_COLUMN_WIDTH)
|
|
56
|
+
self.layout.setColumnStretch(0, 0)
|
|
57
|
+
for button in self.button.values():
|
|
58
|
+
if hasattr(button, "setFixedWidth"):
|
|
59
|
+
button.setFixedWidth(CONTROL_COLUMN_WIDTH)
|
|
60
|
+
self.set_resumable_buttons("idle")
|
|
61
|
+
|
|
62
|
+
def refresh_lists(self, init: bool = False):
|
|
63
|
+
super().refresh_lists(init)
|
|
64
|
+
if self.playlists_view.selected_string is None:
|
|
65
|
+
self.playlists_view.selected_string = str(self.playlists_view.model()._data.iloc[0, 0])
|
|
66
|
+
if self.protocols_view.selected_string is None:
|
|
67
|
+
self.protocols_view.selected_string = str(self.protocols_view.model()._data.iloc[0, 0])
|
|
68
|
+
|
|
69
|
+
def selected_playlist(self):
|
|
70
|
+
if self.playlists_view.selected_string is None:
|
|
71
|
+
return None
|
|
72
|
+
return (self.playlist_folder / self.playlists_view.selected_string).as_posix()
|
|
73
|
+
|
|
74
|
+
def run_background(self, message, target):
|
|
75
|
+
if self.worker is not None and self.worker.is_alive():
|
|
76
|
+
return
|
|
77
|
+
self.status_label.setText(message)
|
|
78
|
+
self.set_resumable_buttons("busy")
|
|
79
|
+
|
|
80
|
+
def wrapped():
|
|
81
|
+
try:
|
|
82
|
+
status = target()
|
|
83
|
+
except Exception as e:
|
|
84
|
+
logger.exception("Resumable GUI action failed.")
|
|
85
|
+
self.run_active = False
|
|
86
|
+
status = f"Error: {e}"
|
|
87
|
+
self.signals.finished.emit(status)
|
|
88
|
+
|
|
89
|
+
self.worker = threading.Thread(target=wrapped, daemon=True)
|
|
90
|
+
self.worker.start()
|
|
91
|
+
|
|
92
|
+
def on_worker_finished(self, status):
|
|
93
|
+
self.worker = None
|
|
94
|
+
self.status_label.setText(status)
|
|
95
|
+
if not self.run_active:
|
|
96
|
+
self.run_timer.stop()
|
|
97
|
+
elif self.progress_thread is None or not self.progress_thread.is_alive():
|
|
98
|
+
self.start_progress_monitor()
|
|
99
|
+
self.set_resumable_buttons("ready" if self.runner else "idle")
|
|
100
|
+
|
|
101
|
+
def initialize_hardware(self):
|
|
102
|
+
if self.runner is not None:
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
def work():
|
|
106
|
+
logging.getLogger().setLevel(logging.DEBUG if self.button["Debug"].isChecked() else logging.INFO)
|
|
107
|
+
runner = ResumableExperimentRunner(protocol=self.current_protocol)
|
|
108
|
+
runner.setup_hardware()
|
|
109
|
+
self.runner = runner
|
|
110
|
+
services = ", ".join(runner.services)
|
|
111
|
+
return f"Hardware {services} initialized. Ready to run an experiment"
|
|
112
|
+
|
|
113
|
+
self.run_background("Initializing hardware...", work)
|
|
114
|
+
|
|
115
|
+
def shutdown_hardware(self):
|
|
116
|
+
if self.runner is None:
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
def work():
|
|
120
|
+
self.runner.close()
|
|
121
|
+
self.runner = None
|
|
122
|
+
self.run_active = False
|
|
123
|
+
if self.progress_stop_event is not None:
|
|
124
|
+
self.progress_stop_event.set()
|
|
125
|
+
return "Hardware shut down."
|
|
126
|
+
|
|
127
|
+
self.run_background("Shutting down hardware...", work)
|
|
128
|
+
|
|
129
|
+
def start(self, preview: bool = False):
|
|
130
|
+
if self.runner is None:
|
|
131
|
+
QMessageBox.warning(self, "Hardware not initialized", "Initialize hardware first.")
|
|
132
|
+
return
|
|
133
|
+
playlist = self.selected_playlist()
|
|
134
|
+
if playlist is None:
|
|
135
|
+
QMessageBox.warning(self, "Missing playlist", "Select a playlist first.")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
def work():
|
|
139
|
+
logging.getLogger().setLevel(logging.DEBUG if self.button["Debug"].isChecked() else logging.INFO)
|
|
140
|
+
if self.progress_stop_event is not None:
|
|
141
|
+
self.progress_stop_event.set()
|
|
142
|
+
if self.progress_thread is not None and self.progress_thread.is_alive():
|
|
143
|
+
self.progress_thread.join(timeout=0.2)
|
|
144
|
+
self.runner.stop_run()
|
|
145
|
+
self.progress_stop_event = threading.Event()
|
|
146
|
+
self.runner.prepare_playlist_run(playlist, preview=preview)
|
|
147
|
+
self.runner.start()
|
|
148
|
+
self.run_active = True
|
|
149
|
+
return "Camera preview running." if preview else "Experiment running."
|
|
150
|
+
|
|
151
|
+
self.run_background("Starting experiment...", work)
|
|
152
|
+
|
|
153
|
+
def request_stop(self):
|
|
154
|
+
if self.runner is None:
|
|
155
|
+
return
|
|
156
|
+
|
|
157
|
+
def work():
|
|
158
|
+
if self.progress_stop_event is not None:
|
|
159
|
+
self.progress_stop_event.set()
|
|
160
|
+
self.runner.stop_run()
|
|
161
|
+
self.run_active = False
|
|
162
|
+
return "Experiment stopped."
|
|
163
|
+
|
|
164
|
+
self.run_background("Stopping experiment...", work)
|
|
165
|
+
|
|
166
|
+
def camera_preview(self):
|
|
167
|
+
self.start(preview=True)
|
|
168
|
+
|
|
169
|
+
def start_progress_monitor(self):
|
|
170
|
+
if self.runner is None or self.progress_stop_event is None:
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
def monitor():
|
|
174
|
+
try:
|
|
175
|
+
self.runner.monitor_progress(
|
|
176
|
+
show_progress=self.button["Progress"].isChecked(),
|
|
177
|
+
stop_event=self.progress_stop_event,
|
|
178
|
+
)
|
|
179
|
+
finally:
|
|
180
|
+
if self.run_active and self.progress_stop_event is not None and not self.progress_stop_event.is_set():
|
|
181
|
+
self.runner.stop_run()
|
|
182
|
+
self.run_active = False
|
|
183
|
+
self.signals.finished.emit("Experiment finished.")
|
|
184
|
+
|
|
185
|
+
self.progress_thread = threading.Thread(target=monitor, daemon=True)
|
|
186
|
+
self.progress_thread.start()
|
|
187
|
+
|
|
188
|
+
def set_resumable_buttons(self, state):
|
|
189
|
+
busy = state == "busy"
|
|
190
|
+
ready = self.runner is not None
|
|
191
|
+
running = ready and self.run_active
|
|
192
|
+
self.button["Refresh lists"].setEnabled(not busy and not ready)
|
|
193
|
+
self.button["Initialize hardware"].setEnabled(not busy and not ready)
|
|
194
|
+
self.button["Shutdown hardware"].setEnabled(not busy and ready)
|
|
195
|
+
self.button["Start"].setEnabled(not busy and ready)
|
|
196
|
+
self.button["Stop"].setEnabled(not busy and running)
|
|
197
|
+
self.button["Camera_preview"].setEnabled(not busy and ready)
|
|
198
|
+
self.button["Debug"].setEnabled(not busy)
|
|
199
|
+
self.button["Progress"].setEnabled(not busy)
|
|
200
|
+
self.button["Exit"].setEnabled(not busy)
|
|
201
|
+
self.protocols_view.setEnabled(not busy and not ready)
|
|
202
|
+
self.protocol_view.setEnabled(not busy and not ready)
|
|
203
|
+
self.playlists_view.setEnabled(not busy)
|
|
204
|
+
self.playlist_view.setEnabled(not busy)
|
|
205
|
+
|
|
206
|
+
def closeEvent(self, event):
|
|
207
|
+
if self.progress_stop_event is not None:
|
|
208
|
+
self.progress_stop_event.set()
|
|
209
|
+
if self.runner is not None:
|
|
210
|
+
self.runner.close()
|
|
211
|
+
self.runner = None
|
|
212
|
+
self.run_active = False
|
|
213
|
+
event.accept()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def main(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
217
|
+
app = QApplication(sys.argv)
|
|
218
|
+
icon = _system_icon(app)
|
|
219
|
+
app.setWindowIcon(icon)
|
|
220
|
+
|
|
221
|
+
window = MainWindow(protocol_folder, playlist_folder)
|
|
222
|
+
window.setWindowIcon(icon)
|
|
223
|
+
window.show()
|
|
224
|
+
|
|
225
|
+
sys.exit(app.exec_())
|
etho/resumable.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import logging
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import rich
|
|
8
|
+
from rich.progress import Progress
|
|
9
|
+
|
|
10
|
+
from . import config
|
|
11
|
+
from .services import service_base_name
|
|
12
|
+
from .services.resumable import ResumableDAQ, ResumableGCM
|
|
13
|
+
from .utils.tui import rich_information
|
|
14
|
+
from .utils.config import defaultify, readconfig
|
|
15
|
+
from .utils.sound import build_playlist, load_sounds, parse_table
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _attenuation_for_host():
|
|
22
|
+
attenuation = config["ATTENUATION"]
|
|
23
|
+
host = config["host"] or "localhost"
|
|
24
|
+
if isinstance(attenuation, dict) and host in attenuation:
|
|
25
|
+
return attenuation[host]
|
|
26
|
+
return attenuation
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _playlist_cache_key(protocol, playlistfile):
|
|
30
|
+
daq_name = next((name for name in protocol["use_services"] if service_base_name(name) == "DAQ"), None)
|
|
31
|
+
if daq_name is None:
|
|
32
|
+
return None
|
|
33
|
+
daq_params = protocol[daq_name]
|
|
34
|
+
attenuation = _attenuation_for_host()
|
|
35
|
+
return (
|
|
36
|
+
daq_name,
|
|
37
|
+
str(Path(playlistfile).resolve()),
|
|
38
|
+
daq_params["samplingrate"],
|
|
39
|
+
str(config["stimfolder"]),
|
|
40
|
+
repr(attenuation),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def playlist_arrays(protocol, playlistfile, cache=None):
|
|
45
|
+
daq_name = next((name for name in protocol["use_services"] if service_base_name(name) == "DAQ"), None)
|
|
46
|
+
if daq_name is None:
|
|
47
|
+
return None, None, protocol["maxduration"]
|
|
48
|
+
|
|
49
|
+
daq_params = protocol[daq_name]
|
|
50
|
+
fs = daq_params["samplingrate"]
|
|
51
|
+
cache_key = _playlist_cache_key(protocol, playlistfile)
|
|
52
|
+
if cache is not None and cache_key in cache:
|
|
53
|
+
playlist, sounds = cache[cache_key]
|
|
54
|
+
logger.info(f"Reusing loaded stimuli for {playlistfile}.")
|
|
55
|
+
else:
|
|
56
|
+
playlist = parse_table(playlistfile)
|
|
57
|
+
attenuation = _attenuation_for_host()
|
|
58
|
+
sounds = load_sounds(playlist, fs, attenuation=attenuation, stimfolder=config["stimfolder"])
|
|
59
|
+
sounds = [sound.astype(np.float64) for sound in sounds]
|
|
60
|
+
if cache is not None:
|
|
61
|
+
cache[cache_key] = (playlist, sounds)
|
|
62
|
+
playlist_items, duration = build_playlist(sounds, protocol["maxduration"], fs, shuffle=daq_params["shuffle"])
|
|
63
|
+
data = np.concatenate([sounds[item] for item in playlist_items], axis=0)
|
|
64
|
+
|
|
65
|
+
nb_digital = len(daq_params["digital_chans_out"] or [])
|
|
66
|
+
if nb_digital:
|
|
67
|
+
return data[:, :-nb_digital], data[:, -nb_digital:].astype(np.uint8), duration
|
|
68
|
+
return data, None, duration
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ResumableExperimentRunner:
|
|
72
|
+
def __init__(self, protocolfile=None, *, protocol=None, save_prefix_root=None):
|
|
73
|
+
if protocolfile is None and protocol is None:
|
|
74
|
+
raise ValueError("Provide protocolfile or protocol.")
|
|
75
|
+
self.protocolfile = protocolfile
|
|
76
|
+
self.protocol = copy.deepcopy(protocol) if protocol is not None else None
|
|
77
|
+
self.save_prefix_root = save_prefix_root
|
|
78
|
+
self.run_count = 0
|
|
79
|
+
self.services = {}
|
|
80
|
+
self._playlist_cache = {}
|
|
81
|
+
|
|
82
|
+
def setup_hardware(self):
|
|
83
|
+
prot = defaultify(copy.deepcopy(self.protocol)) if self.protocol is not None else readconfig(self.protocolfile)
|
|
84
|
+
self.prot = prot
|
|
85
|
+
defaults = config
|
|
86
|
+
if defaults["host"] is None:
|
|
87
|
+
defaults["host"] = "localhost"
|
|
88
|
+
rich.print(defaults)
|
|
89
|
+
logger.info("Setting up resumable hardware.")
|
|
90
|
+
for service_name in prot["use_services"]:
|
|
91
|
+
base = service_base_name(service_name)
|
|
92
|
+
logger.info(f" {service_name}.")
|
|
93
|
+
if base == "GCM":
|
|
94
|
+
self.services[service_name] = ResumableGCM(prot[service_name]).setup_hardware()
|
|
95
|
+
elif base == "DAQ":
|
|
96
|
+
self.services[service_name] = ResumableDAQ(prot[service_name]).setup_hardware()
|
|
97
|
+
else:
|
|
98
|
+
raise ValueError(f"Resumable runner only supports DAQ and GCM, got {service_name}.")
|
|
99
|
+
services = ", ".join(prot["use_services"])
|
|
100
|
+
logger.info(f"Hardware {services} initialized. Ready to run an experiment")
|
|
101
|
+
self.print_information()
|
|
102
|
+
return self
|
|
103
|
+
|
|
104
|
+
def print_information(self):
|
|
105
|
+
for key, service in self.services.items():
|
|
106
|
+
if hasattr(service, "information"):
|
|
107
|
+
rich_information(service.information(), prefix=key)
|
|
108
|
+
|
|
109
|
+
def prepare_run(
|
|
110
|
+
self,
|
|
111
|
+
save_prefix=None,
|
|
112
|
+
analog_data_out=None,
|
|
113
|
+
digital_data_out=None,
|
|
114
|
+
duration=None,
|
|
115
|
+
metadata=None,
|
|
116
|
+
preview=False,
|
|
117
|
+
):
|
|
118
|
+
if not self.services:
|
|
119
|
+
self.setup_hardware()
|
|
120
|
+
self.run_count += 1
|
|
121
|
+
if save_prefix is None:
|
|
122
|
+
if self.save_prefix_root is not None:
|
|
123
|
+
save_prefix = self.save_prefix_root
|
|
124
|
+
else:
|
|
125
|
+
save_prefix = f"{config['host'] or 'localhost'}-{time.strftime('%Y%m%d_%H%M%S')}"
|
|
126
|
+
|
|
127
|
+
savefolder = Path(config["savefolder"] or ".")
|
|
128
|
+
if self.save_prefix_root is None:
|
|
129
|
+
while (savefolder / save_prefix).exists():
|
|
130
|
+
time.sleep(1)
|
|
131
|
+
save_prefix = f"{config['host'] or 'localhost'}-{time.strftime('%Y%m%d_%H%M%S')}"
|
|
132
|
+
run_duration = duration
|
|
133
|
+
if run_duration is None and self.prot["maxduration"] > 0:
|
|
134
|
+
run_duration = self.prot["maxduration"]
|
|
135
|
+
if run_duration is None:
|
|
136
|
+
n_samples = 0
|
|
137
|
+
if analog_data_out is not None:
|
|
138
|
+
n_samples = analog_data_out.shape[0]
|
|
139
|
+
if digital_data_out is not None:
|
|
140
|
+
n_samples = max(n_samples, digital_data_out.shape[0])
|
|
141
|
+
for service in self.services.values():
|
|
142
|
+
if isinstance(service, ResumableDAQ) and n_samples:
|
|
143
|
+
run_duration = n_samples / service.fs
|
|
144
|
+
if run_duration is None:
|
|
145
|
+
raise ValueError("Provide duration or DAQ output arrays so run duration can be inferred.")
|
|
146
|
+
if preview:
|
|
147
|
+
run_duration = 1_000_000
|
|
148
|
+
|
|
149
|
+
run_folder = savefolder / save_prefix
|
|
150
|
+
run_folder.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
logger.info(f"Preparing resumable experiment {save_prefix}.")
|
|
152
|
+
service_counts = {}
|
|
153
|
+
for service_name, service in self.services.items():
|
|
154
|
+
service_type = service_base_name(service_name)
|
|
155
|
+
service_index = service_counts.get(service_type, 0)
|
|
156
|
+
service_counts[service_type] = service_index + 1
|
|
157
|
+
save_suffix = f"_{service_index + 1}" if service_index > 0 else ""
|
|
158
|
+
savefilename = run_folder / f"{save_prefix}{save_suffix}"
|
|
159
|
+
if isinstance(service, ResumableGCM):
|
|
160
|
+
logger.info(f" preparing {service_name}.")
|
|
161
|
+
service.prepare_run(str(savefilename), run_duration + 10, preview=preview)
|
|
162
|
+
elif isinstance(service, ResumableDAQ):
|
|
163
|
+
if preview:
|
|
164
|
+
logger.info(f" skipping {service_name} for preview.")
|
|
165
|
+
service.stop_run()
|
|
166
|
+
continue
|
|
167
|
+
logger.info(f" preparing {service_name}.")
|
|
168
|
+
service.prepare_run(
|
|
169
|
+
str(savefilename),
|
|
170
|
+
analog_data_out=analog_data_out,
|
|
171
|
+
digital_data_out=digital_data_out,
|
|
172
|
+
duration=run_duration,
|
|
173
|
+
metadata=metadata,
|
|
174
|
+
)
|
|
175
|
+
self.print_information()
|
|
176
|
+
return self
|
|
177
|
+
|
|
178
|
+
def prepare_playlist_run(self, playlistfile, save_prefix=None, metadata=None, preview=False):
|
|
179
|
+
analog_data_out, digital_data_out, duration = playlist_arrays(self.prot, playlistfile, cache=self._playlist_cache)
|
|
180
|
+
return self.prepare_run(
|
|
181
|
+
save_prefix=save_prefix,
|
|
182
|
+
analog_data_out=analog_data_out,
|
|
183
|
+
digital_data_out=digital_data_out,
|
|
184
|
+
duration=duration,
|
|
185
|
+
metadata=metadata,
|
|
186
|
+
preview=preview,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def start(self):
|
|
190
|
+
logger.info("Starting resumable experiment.")
|
|
191
|
+
for service in self.services.values():
|
|
192
|
+
if isinstance(service, ResumableGCM):
|
|
193
|
+
service.start()
|
|
194
|
+
time.sleep(0.5)
|
|
195
|
+
for service in self.services.values():
|
|
196
|
+
if isinstance(service, ResumableDAQ) and getattr(service, "state", "prepared") == "prepared":
|
|
197
|
+
service.start()
|
|
198
|
+
logger.info("Resumable experiment running.")
|
|
199
|
+
return self
|
|
200
|
+
|
|
201
|
+
def stop_run(self):
|
|
202
|
+
logger.info("Stopping resumable experiment.")
|
|
203
|
+
for service in self.services.values():
|
|
204
|
+
if isinstance(service, ResumableDAQ):
|
|
205
|
+
service.stop_run()
|
|
206
|
+
for service in self.services.values():
|
|
207
|
+
if isinstance(service, ResumableGCM):
|
|
208
|
+
service.stop_run()
|
|
209
|
+
logger.info("Resumable experiment stopped.")
|
|
210
|
+
return self
|
|
211
|
+
|
|
212
|
+
def close(self):
|
|
213
|
+
logger.info("Shutting down resumable hardware.")
|
|
214
|
+
for service in self.services.values():
|
|
215
|
+
service.close()
|
|
216
|
+
logger.info("Resumable hardware shut down.")
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
def progress(self):
|
|
220
|
+
progress = {}
|
|
221
|
+
for service_name, service in self.services.items():
|
|
222
|
+
progress[service_name] = service.progress()
|
|
223
|
+
return progress
|
|
224
|
+
|
|
225
|
+
def monitor_progress(self, show_progress=True, stop_event=None):
|
|
226
|
+
with Progress(disable=not show_progress) as progress:
|
|
227
|
+
tasks = {}
|
|
228
|
+
for service_name, service in self.services.items():
|
|
229
|
+
service_progress = service.progress()
|
|
230
|
+
if service_progress["total"]:
|
|
231
|
+
tasks[service_name] = progress.add_task(f"[red]{service_name}", total=service_progress["total"])
|
|
232
|
+
while tasks and not progress.finished:
|
|
233
|
+
if stop_event is not None and stop_event.is_set():
|
|
234
|
+
break
|
|
235
|
+
for task_name, task_id in tasks.items():
|
|
236
|
+
if progress._tasks[task_id].finished:
|
|
237
|
+
continue
|
|
238
|
+
p = self.services[task_name].progress()
|
|
239
|
+
description = None
|
|
240
|
+
if "framenumber" in p and p["elapsed_delta"]:
|
|
241
|
+
description = f"{task_name} {p['framenumber_delta'] / p['elapsed_delta']: 7.2f} fps"
|
|
242
|
+
progress.update(task_id, completed=p["elapsed"], description=description)
|
|
243
|
+
time.sleep(1)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _wait_for_run(runner, duration, show_progress=True):
|
|
247
|
+
runner.monitor_progress(show_progress=show_progress)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def run(
|
|
251
|
+
protocolfile,
|
|
252
|
+
playlistfile=None,
|
|
253
|
+
*,
|
|
254
|
+
save_prefix=None,
|
|
255
|
+
show_progress=True,
|
|
256
|
+
debug=False,
|
|
257
|
+
preview=False,
|
|
258
|
+
):
|
|
259
|
+
if debug:
|
|
260
|
+
logging.getLogger().setLevel(logging.DEBUG)
|
|
261
|
+
runner = ResumableExperimentRunner(protocolfile=protocolfile, save_prefix_root=save_prefix)
|
|
262
|
+
try:
|
|
263
|
+
runner.setup_hardware()
|
|
264
|
+
if preview:
|
|
265
|
+
runner.prepare_run(save_prefix=save_prefix, preview=True)
|
|
266
|
+
duration = 1_000_000
|
|
267
|
+
elif playlistfile is None:
|
|
268
|
+
runner.prepare_run(save_prefix=save_prefix)
|
|
269
|
+
duration = runner.prot["maxduration"]
|
|
270
|
+
else:
|
|
271
|
+
analog_data_out, digital_data_out, duration = playlist_arrays(runner.prot, playlistfile)
|
|
272
|
+
runner.prepare_run(
|
|
273
|
+
save_prefix=save_prefix,
|
|
274
|
+
analog_data_out=analog_data_out,
|
|
275
|
+
digital_data_out=digital_data_out,
|
|
276
|
+
duration=duration,
|
|
277
|
+
)
|
|
278
|
+
runner.start()
|
|
279
|
+
if duration and duration > 0:
|
|
280
|
+
_wait_for_run(runner, duration, show_progress=show_progress)
|
|
281
|
+
return runner.stop_run()
|
|
282
|
+
finally:
|
|
283
|
+
runner.close()
|
etho/services/DAQZeroService.py
CHANGED
|
@@ -59,7 +59,6 @@ class DAQ(BaseZeroService):
|
|
|
59
59
|
playlist,
|
|
60
60
|
fs,
|
|
61
61
|
attenuation=attenuation,
|
|
62
|
-
LEDamp=prot[service_key]["ledamp"],
|
|
63
62
|
stimfolder=global_config["stimfolder"],
|
|
64
63
|
)
|
|
65
64
|
sounds = [sound.astype(np.float64) for sound in sounds]
|
|
@@ -103,7 +102,7 @@ class DAQ(BaseZeroService):
|
|
|
103
102
|
metadata={
|
|
104
103
|
"analog_chans_in_info": prot[service_key]["analog_chans_in_info"],
|
|
105
104
|
"analog_chans_out_info": prot[service_key]["analog_chans_out_info"],
|
|
106
|
-
"
|
|
105
|
+
"digital_chans_out_info": prot[service_key]["digital_chans_out_info"],
|
|
107
106
|
},
|
|
108
107
|
params=undefaultify(prot[service_key]),
|
|
109
108
|
)
|
etho/services/GCMZeroService.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
from .ZeroService import BaseZeroService
|
|
2
|
+
from pathlib import Path
|
|
2
3
|
import time
|
|
3
4
|
import threading
|
|
4
5
|
import sys
|
|
@@ -44,14 +45,17 @@ class GCM(BaseZeroService):
|
|
|
44
45
|
params["callbacks"] = {"disp_fast": None}
|
|
45
46
|
|
|
46
47
|
save_suffix = f"_{service_index + 1}" if service_index > 0 else ""
|
|
48
|
+
save_dir = Path(this["savefolder"]) / save_prefix
|
|
49
|
+
save_dir.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
save_base = save_dir / f"{save_prefix}{save_suffix}"
|
|
47
51
|
service.setup(
|
|
48
|
-
|
|
52
|
+
str(save_base),
|
|
49
53
|
duration,
|
|
50
54
|
params,
|
|
51
55
|
)
|
|
52
56
|
|
|
53
57
|
if not preview:
|
|
54
|
-
service.init_local_logger(f"{
|
|
58
|
+
service.init_local_logger(f"{save_base}_gcm.log")
|
|
55
59
|
return service
|
|
56
60
|
|
|
57
61
|
def setup(self, savefilename, duration, params):
|