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
etho/cli.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import defopt
|
|
2
|
+
import logging
|
|
3
|
+
import platform
|
|
4
|
+
import importlib
|
|
5
|
+
import yaml
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import rich
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
from . import client
|
|
16
|
+
except Exception as e:
|
|
17
|
+
logging.error(e)
|
|
18
|
+
client = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def run(
|
|
22
|
+
protocolfile: str,
|
|
23
|
+
playlistfile: Optional[str] = None,
|
|
24
|
+
*,
|
|
25
|
+
save_prefix: Optional[str] = None,
|
|
26
|
+
show_progress: bool = True,
|
|
27
|
+
debug: bool = False,
|
|
28
|
+
preview: bool = False,
|
|
29
|
+
):
|
|
30
|
+
"""Starts an experiment from the CLI."""
|
|
31
|
+
return client.client(
|
|
32
|
+
protocolfile=protocolfile,
|
|
33
|
+
playlistfile=playlistfile,
|
|
34
|
+
save_prefix=save_prefix,
|
|
35
|
+
show_progress=show_progress,
|
|
36
|
+
debug=debug,
|
|
37
|
+
preview=preview,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def version(*, debug: bool = False):
|
|
42
|
+
"""Displays system, version, and hardware info.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
debug (bool): Display exception info for failed imports. Defaults to False.
|
|
46
|
+
"""
|
|
47
|
+
import etho
|
|
48
|
+
import sys
|
|
49
|
+
import pandas as pd
|
|
50
|
+
import numpy as np
|
|
51
|
+
import scipy
|
|
52
|
+
import h5py
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
import pyqtgraph
|
|
56
|
+
import qtpy
|
|
57
|
+
|
|
58
|
+
has_gui = True
|
|
59
|
+
except (ImportError, ModuleNotFoundError):
|
|
60
|
+
has_gui = False
|
|
61
|
+
|
|
62
|
+
logger.info(f"{platform.platform()}")
|
|
63
|
+
logger.info(f"etho v{etho.__version__}")
|
|
64
|
+
logger.info("")
|
|
65
|
+
logger.info(" LIBRARY VERSIONS")
|
|
66
|
+
logger.info(f" python v{sys.version}")
|
|
67
|
+
logger.info(f" pandas v{pd.__version__}")
|
|
68
|
+
logger.info(f" numpy v{np.__version__}")
|
|
69
|
+
logger.info(f" h5py v{h5py.__version__}")
|
|
70
|
+
logger.info(f" scipy v{scipy.__version__}")
|
|
71
|
+
logger.info("")
|
|
72
|
+
logger.info(" GUI SUPPORT")
|
|
73
|
+
logger.info(f" GUI is {'' if has_gui else 'not'}available.")
|
|
74
|
+
if has_gui:
|
|
75
|
+
logger.info(f" pyqtgraph v{pyqtgraph.__version__}")
|
|
76
|
+
logger.info(f" {qtpy.API_NAME} v{qtpy.PYQT_VERSION or qtpy.PYSIDE_VERSION}")
|
|
77
|
+
logger.info(f" Qt v{qtpy.QT_VERSION}")
|
|
78
|
+
logger.info(f" qtpy v{qtpy.__version__}")
|
|
79
|
+
|
|
80
|
+
logger.info("")
|
|
81
|
+
logger.info(" HARDWARE SUPPORT")
|
|
82
|
+
|
|
83
|
+
libs = {
|
|
84
|
+
"Spinnaker camera SDK": "PySpin",
|
|
85
|
+
"FlyCapture camera SDK": "PyCapture2",
|
|
86
|
+
"Ximea camera SDK": "ximea",
|
|
87
|
+
"DCAM (Hamamatsu) camera SDK": "pylablib",
|
|
88
|
+
"NI daqmx": "pydaqmx",
|
|
89
|
+
"Lightcrafter projector": "pycrafter4500",
|
|
90
|
+
}
|
|
91
|
+
for lib_name, lib_import in libs.items():
|
|
92
|
+
try:
|
|
93
|
+
importlib.import_module(lib_import)
|
|
94
|
+
logger.info(f" {lib_name} ({lib_import}) is available")
|
|
95
|
+
except (ImportError, ModuleNotFoundError) as e:
|
|
96
|
+
logger.warning(f" {lib_name} ({lib_import}) is NOT available.")
|
|
97
|
+
if debug:
|
|
98
|
+
logger.exception(" DEBUG info", exc_info=e)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def no_gui():
|
|
102
|
+
"""Could not import the GUI. For instructions on how to install the GUI, check the docs janclemenslab.org/etho/install.html."""
|
|
103
|
+
logger.warning("Could not import the GUI.")
|
|
104
|
+
logger.warning("For instructions on how to install the GUI,")
|
|
105
|
+
logger.warning("check the docs janclemenslab.org/etho/install.html.")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def init():
|
|
109
|
+
"""Initializes config files and folders."""
|
|
110
|
+
home = Path.home()
|
|
111
|
+
|
|
112
|
+
cfg = {
|
|
113
|
+
"user": "ncb",
|
|
114
|
+
"savefolder": str(home / "data"),
|
|
115
|
+
"python_exe": sys.executable,
|
|
116
|
+
"ATTENUATION": {
|
|
117
|
+
-1: 1,
|
|
118
|
+
0: 1,
|
|
119
|
+
100: 1,
|
|
120
|
+
150: 1,
|
|
121
|
+
200: 1,
|
|
122
|
+
250: 1,
|
|
123
|
+
300: 1,
|
|
124
|
+
350: 1,
|
|
125
|
+
400: 1,
|
|
126
|
+
450: 1,
|
|
127
|
+
500: 1,
|
|
128
|
+
600: 1,
|
|
129
|
+
700: 1,
|
|
130
|
+
800: 1,
|
|
131
|
+
900: 1,
|
|
132
|
+
1000: 1,
|
|
133
|
+
1500: 1,
|
|
134
|
+
2000: 1,
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
paths = {
|
|
139
|
+
"playlistfolder": "ethoconfig/playlists",
|
|
140
|
+
"protocolfolder": "ethoconfig/protocols",
|
|
141
|
+
"stimfolder": "ethoconfig/stim",
|
|
142
|
+
}
|
|
143
|
+
logging.info("Creating default directories:")
|
|
144
|
+
for name, path in paths.items():
|
|
145
|
+
logging.info(" " + path)
|
|
146
|
+
p = home / Path(path)
|
|
147
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
cfg[name] = str(p)
|
|
149
|
+
|
|
150
|
+
rich.print(cfg)
|
|
151
|
+
|
|
152
|
+
path_cfg = home / "ethoconfig" / "ethoconfig.yml"
|
|
153
|
+
if path_cfg.exists():
|
|
154
|
+
logging.info(f"The configuration file {str(path_cfg)} exists. Will not overwrite. Delete the file or update it manually.")
|
|
155
|
+
else:
|
|
156
|
+
logging.info(f"Writing configuration to {str(path_cfg)}.")
|
|
157
|
+
with open(path_cfg, mode="w") as f:
|
|
158
|
+
yaml.dump(cfg, f, Dumper=yaml.SafeDumper)
|
|
159
|
+
|
|
160
|
+
logging.info("Generating test files:")
|
|
161
|
+
# generate test protocol
|
|
162
|
+
protocol = {
|
|
163
|
+
"maxduration": 30,
|
|
164
|
+
"use_services": ["GCM"],
|
|
165
|
+
"GCM": {
|
|
166
|
+
"frame_rate": 30,
|
|
167
|
+
"frame_width": 320,
|
|
168
|
+
"frame_height": 240,
|
|
169
|
+
"shutter_speed": 1.0,
|
|
170
|
+
"cam_serialnumber": 42,
|
|
171
|
+
"cam_type": "Dummy",
|
|
172
|
+
"callbacks": {"disp": {"framerate": 10}},
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
path_protocol = home / "ethoconfig/protocols/dummy_1min.yml"
|
|
176
|
+
logging.info(f" protocol {str(path_protocol)}.")
|
|
177
|
+
|
|
178
|
+
with open(path_protocol, mode="w") as f:
|
|
179
|
+
yaml.dump(protocol, f, Dumper=yaml.SafeDumper)
|
|
180
|
+
|
|
181
|
+
# generate test playlist
|
|
182
|
+
playlist = {
|
|
183
|
+
"stimFileName": {0: "SIN_100_0_1000"},
|
|
184
|
+
"silencePre": {0: 10000},
|
|
185
|
+
"silencePost": {0: 9000},
|
|
186
|
+
"delayPost": {0: 0},
|
|
187
|
+
"intensity": {0: 0.0},
|
|
188
|
+
"freq": {0: 100},
|
|
189
|
+
"MODE": {0: None},
|
|
190
|
+
}
|
|
191
|
+
path_playlist = home / "ethoconfig/playlists/0_silence.txt"
|
|
192
|
+
logging.info(f" playlist {str(path_playlist)}.")
|
|
193
|
+
pd.DataFrame.from_dict(playlist).to_csv(path_playlist, sep="\t", index=False)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def main():
|
|
197
|
+
"""Command line interface for DAS."""
|
|
198
|
+
subcommands = {
|
|
199
|
+
"version": version,
|
|
200
|
+
"init": init,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if client is not None:
|
|
204
|
+
subcommands.update({"run": run})
|
|
205
|
+
try:
|
|
206
|
+
from . import app
|
|
207
|
+
|
|
208
|
+
subcommands["gui"] = app.main
|
|
209
|
+
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
|
+
logging.basicConfig(level=logging.INFO, force=True)
|
|
215
|
+
defopt.run(subcommands, show_defaults=False)
|
etho/client.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import numpy as np
|
|
3
|
+
import logging
|
|
4
|
+
from itertools import cycle
|
|
5
|
+
from rich.progress import Progress
|
|
6
|
+
import rich
|
|
7
|
+
import threading
|
|
8
|
+
import _thread as thread
|
|
9
|
+
import queue
|
|
10
|
+
from typing import Optional, Union, Dict, Any
|
|
11
|
+
import psutil
|
|
12
|
+
|
|
13
|
+
from .utils.tui import rich_information
|
|
14
|
+
|
|
15
|
+
from . import config
|
|
16
|
+
from .utils.config import defaultify, readconfig, undefaultify
|
|
17
|
+
from .utils.sound import parse_table, load_sounds, build_playlist
|
|
18
|
+
|
|
19
|
+
from .services.GOVZeroService import GOV
|
|
20
|
+
from .services.DAQZeroService import DAQ
|
|
21
|
+
from .services.GCMZeroService import GCM
|
|
22
|
+
from .services.NICounterZeroService import NIC
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def timed(fn, s, *args, **kwargs):
|
|
26
|
+
quit_fun = thread.interrupt_main # raises KeyboardInterrupt
|
|
27
|
+
timer = threading.Timer(s, quit_fun)
|
|
28
|
+
timer.start()
|
|
29
|
+
try:
|
|
30
|
+
result = fn(*args, **kwargs)
|
|
31
|
+
except: # catch KeyboardInterrupt for silent timeouts
|
|
32
|
+
result = 1
|
|
33
|
+
finally:
|
|
34
|
+
timer.cancel()
|
|
35
|
+
return result
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def kill_child_processes():
|
|
39
|
+
try:
|
|
40
|
+
parent = psutil.Process()
|
|
41
|
+
except psutil.NoSuchProcess:
|
|
42
|
+
return
|
|
43
|
+
children = parent.children(recursive=True)
|
|
44
|
+
for child in children:
|
|
45
|
+
child.terminate() # friendly termination
|
|
46
|
+
_, still_alive = psutil.wait_procs(children, timeout=3)
|
|
47
|
+
for child in still_alive:
|
|
48
|
+
child.kill() # unfriendly termination
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _reject_remote_host_blocks(prot: Dict[str, Any]) -> None:
|
|
52
|
+
remote_services = []
|
|
53
|
+
for service_name in prot["use_services"]:
|
|
54
|
+
service_config = prot.get(service_name, {})
|
|
55
|
+
if isinstance(service_config, dict) and "host" in service_config:
|
|
56
|
+
remote_services.append(service_name)
|
|
57
|
+
if remote_services:
|
|
58
|
+
services = ", ".join(remote_services)
|
|
59
|
+
raise ValueError(f"Remote service hosts are no longer supported. Remove the 'host' block from: {services}.")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def client(
|
|
63
|
+
protocolfile: Optional[str],
|
|
64
|
+
playlistfile: Optional[str] = None,
|
|
65
|
+
*,
|
|
66
|
+
protocol: Optional[Dict[str, Any]] = None,
|
|
67
|
+
save_prefix: Optional[str] = None,
|
|
68
|
+
show_progress: bool = True,
|
|
69
|
+
monitor: bool = False,
|
|
70
|
+
debug: bool = False,
|
|
71
|
+
preview: bool = False,
|
|
72
|
+
_stop_event: Optional[threading.Event] = None,
|
|
73
|
+
_done_event: Optional[threading.Event] = None,
|
|
74
|
+
_queue: Optional[queue.Queue] = None,
|
|
75
|
+
):
|
|
76
|
+
"""Starts an experiment.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
protocolfile (Optional[str]): Path to the protocol file.
|
|
80
|
+
playlistfile (Optional[str]): _description_.
|
|
81
|
+
protocol (Optional[Dict[str, Any]]): Protocol parameters provided directly by the GUI.
|
|
82
|
+
save_prefix (Optional[str]): Specify the stem of the filename for all saved data and logs. Will defaults to HOSTNAME-YYYYMMDD_hhmmss, where HOSTNAME is the computer name the service is run on (typically localhost).
|
|
83
|
+
show_progress (bool): Show a progress bar. Disable if performance is criticial.
|
|
84
|
+
monitor (bool): Keep the run in the progress/cleanup loop even when the progress display is hidden.
|
|
85
|
+
debug (bool): More verbose logs.
|
|
86
|
+
preview (bool): Preview the camera (will disable saving and logging and only open a window with the camera view).
|
|
87
|
+
_stop_event (threading.Event, optional): Used to stop the task from an outside thread. Defaults to None.
|
|
88
|
+
_done_event (threading.Event, optional): Set to signal that the task is done/stopped to an outside thread. Defaults to None.
|
|
89
|
+
_queue (queue.Queue, optional): Signal the expected duration of the task to outside funs. Defaults to None.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
# load config/protocols
|
|
93
|
+
if protocol is not None:
|
|
94
|
+
prot = defaultify(protocol)
|
|
95
|
+
else:
|
|
96
|
+
prot = readconfig(protocolfile)
|
|
97
|
+
logging.debug(prot)
|
|
98
|
+
defaults = config
|
|
99
|
+
if defaults["host"] is None:
|
|
100
|
+
defaults["host"] = "localhost"
|
|
101
|
+
if defaults["python_exe"] is None:
|
|
102
|
+
defaults["python_exe"] = "python"
|
|
103
|
+
if defaults["serializer"] is None:
|
|
104
|
+
defaults["serializer"] = "pickle"
|
|
105
|
+
_reject_remote_host_blocks(prot)
|
|
106
|
+
|
|
107
|
+
rich.print(defaults)
|
|
108
|
+
# unique file name for video and node-local logs
|
|
109
|
+
if save_prefix is None:
|
|
110
|
+
save_prefix = f"{defaults['host']}-{time.strftime('%Y%m%d_%H%M%S')}"
|
|
111
|
+
logging.info(f"Saving as {save_prefix}.")
|
|
112
|
+
|
|
113
|
+
new_console = debug
|
|
114
|
+
|
|
115
|
+
services = {}
|
|
116
|
+
if "GOV" in prot["use_services"] and not preview:
|
|
117
|
+
this = defaults.copy()
|
|
118
|
+
|
|
119
|
+
if prot["GOV"].get("port") is None:
|
|
120
|
+
prot["GOV"]["port"] = GOV.SERVICE_PORT
|
|
121
|
+
|
|
122
|
+
interval = prot["GOV"].get("interval")
|
|
123
|
+
if interval is None:
|
|
124
|
+
interval = 60
|
|
125
|
+
|
|
126
|
+
gov = GOV.make(
|
|
127
|
+
this["serializer"],
|
|
128
|
+
this["host"],
|
|
129
|
+
this["python_exe"],
|
|
130
|
+
port=prot["GOV"]["port"],
|
|
131
|
+
)
|
|
132
|
+
gov.setup(prot["GOV"]["address"], interval, prot["maxduration"] + 10)
|
|
133
|
+
gov.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}_gov.log")
|
|
134
|
+
services["GOV"] = gov
|
|
135
|
+
|
|
136
|
+
gcm_keys = [key for key in prot["use_services"] if "GCM" in key]
|
|
137
|
+
for gcm_cnt, gcm_key in enumerate(gcm_keys):
|
|
138
|
+
# if gcm_key in prot["use_services"] and gcm_key in prot:
|
|
139
|
+
this = defaults.copy()
|
|
140
|
+
this.update(prot[gcm_key])
|
|
141
|
+
|
|
142
|
+
if "port" not in prot[gcm_key]:
|
|
143
|
+
prot[gcm_key]["port"] = GCM.SERVICE_PORT + gcm_cnt
|
|
144
|
+
gcm = GCM.make(
|
|
145
|
+
this["serializer"],
|
|
146
|
+
this["host"],
|
|
147
|
+
this["python_exe"],
|
|
148
|
+
new_console=new_console,
|
|
149
|
+
port=prot[gcm_key]["port"],
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
cam_params = undefaultify(prot[gcm_key])
|
|
153
|
+
if not preview:
|
|
154
|
+
maxduration = prot["maxduration"] + 10
|
|
155
|
+
else:
|
|
156
|
+
maxduration = 1_000_000
|
|
157
|
+
|
|
158
|
+
if preview:
|
|
159
|
+
cam_params["callbacks"] = {"disp_fast": None}
|
|
160
|
+
|
|
161
|
+
save_suffix = f"_{gcm_cnt + 1}" if gcm_cnt > 0 else ""
|
|
162
|
+
gcm.setup(
|
|
163
|
+
f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}",
|
|
164
|
+
maxduration,
|
|
165
|
+
cam_params,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
if not preview:
|
|
169
|
+
gcm.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_gcm.log")
|
|
170
|
+
services[gcm_key] = gcm
|
|
171
|
+
|
|
172
|
+
daq_keys = [key for key in prot["use_services"] if "DAQ" in key]
|
|
173
|
+
daq_keys = [] if preview else daq_keys
|
|
174
|
+
for daq_cnt, daq_key in enumerate(daq_keys):
|
|
175
|
+
this = defaults.copy()
|
|
176
|
+
this.update(prot[daq_key])
|
|
177
|
+
|
|
178
|
+
if "device" not in prot[daq_key]:
|
|
179
|
+
prot[daq_key]["device"] = "Dev1"
|
|
180
|
+
|
|
181
|
+
if "port" not in prot[daq_key]:
|
|
182
|
+
prot[daq_key]["port"] = DAQ.SERVICE_PORT + daq_cnt
|
|
183
|
+
|
|
184
|
+
if this["host"] in config["ATTENUATION"]: # use node specific attenuation data
|
|
185
|
+
attenuation = config["ATTENUATION"][this["host"]]
|
|
186
|
+
logging.info(f"Using attenuation data specific to {this['host']}.")
|
|
187
|
+
else:
|
|
188
|
+
attenuation = config["ATTENUATION"]
|
|
189
|
+
|
|
190
|
+
# Load/generate all stimuli specified in playlist
|
|
191
|
+
fs = prot[daq_key]["samplingrate"]
|
|
192
|
+
playlist = parse_table(playlistfile)
|
|
193
|
+
sounds = load_sounds(
|
|
194
|
+
playlist,
|
|
195
|
+
fs,
|
|
196
|
+
attenuation=attenuation,
|
|
197
|
+
LEDamp=prot[daq_key]["ledamp"],
|
|
198
|
+
stimfolder=config["stimfolder"],
|
|
199
|
+
)
|
|
200
|
+
sounds = [sound.astype(np.float64) for sound in sounds]
|
|
201
|
+
|
|
202
|
+
# Generate stimulus sequence (shuffle, loop playlist)
|
|
203
|
+
playlist_items, totallen = build_playlist(sounds, prot["maxduration"], fs, shuffle=prot[daq_key]["shuffle"])
|
|
204
|
+
if prot["maxduration"] == -1:
|
|
205
|
+
logging.info(f"Setting maxduration from playlist to {totallen}.")
|
|
206
|
+
prot["maxduration"] = totallen
|
|
207
|
+
playlist_items = cycle(playlist_items) # iter(playlist_items)
|
|
208
|
+
else:
|
|
209
|
+
playlist_items = cycle(playlist_items)
|
|
210
|
+
|
|
211
|
+
# split analog and digital outputs
|
|
212
|
+
# TODO: catch errors if channel numbers are inconsistent - sounds[ii].shape[-1] should be nb_analog+nb_digital
|
|
213
|
+
if prot[daq_key]["digital_chans_out"] is not None:
|
|
214
|
+
nb_digital_chans_out = len(prot[daq_key]["digital_chans_out"])
|
|
215
|
+
digital_data = [snd[:, -nb_digital_chans_out:].astype(np.uint8) for snd in sounds]
|
|
216
|
+
analog_data = [snd[:, :-nb_digital_chans_out] for snd in sounds] # remove digital traces from stimset
|
|
217
|
+
else:
|
|
218
|
+
digital_data = None
|
|
219
|
+
analog_data = sounds
|
|
220
|
+
|
|
221
|
+
daq = DAQ.make(
|
|
222
|
+
this["serializer"],
|
|
223
|
+
this["host"],
|
|
224
|
+
this["python_exe"],
|
|
225
|
+
new_console=new_console,
|
|
226
|
+
port=prot[daq_key]["port"],
|
|
227
|
+
)
|
|
228
|
+
save_suffix = f"_{daq_cnt + 1}" if daq_cnt > 0 else ""
|
|
229
|
+
daq.setup(
|
|
230
|
+
f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}",
|
|
231
|
+
playlist_items,
|
|
232
|
+
playlist,
|
|
233
|
+
prot["maxduration"],
|
|
234
|
+
fs,
|
|
235
|
+
dev_name=prot[daq_key]["device"],
|
|
236
|
+
clock_source=prot[daq_key]["clock_source"],
|
|
237
|
+
nb_inputsamples_per_cycle=prot[daq_key]["nb_inputsamples_per_cycle"],
|
|
238
|
+
analog_chans_in=prot[daq_key]["analog_chans_in"],
|
|
239
|
+
# analog_chans_in_limits=None,
|
|
240
|
+
# analog_chans_in_terminals=None,
|
|
241
|
+
analog_chans_out=prot[daq_key]["analog_chans_out"],
|
|
242
|
+
# analog_chans_out_limits=None,
|
|
243
|
+
analog_data_out=analog_data,
|
|
244
|
+
digital_chans_out=prot[daq_key]["digital_chans_out"],
|
|
245
|
+
digital_data_out=digital_data,
|
|
246
|
+
metadata={
|
|
247
|
+
"analog_chans_in_info": prot[daq_key]["analog_chans_in_info"],
|
|
248
|
+
"analog_chans_out_info": prot[daq_key]["analog_chans_out_info"],
|
|
249
|
+
"digitial_chans_out_info": prot[daq_key]["digitial_chans_out_info"],
|
|
250
|
+
},
|
|
251
|
+
params=undefaultify(prot[daq_key]),
|
|
252
|
+
)
|
|
253
|
+
daq.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_daq.log")
|
|
254
|
+
services[daq_key] = daq
|
|
255
|
+
|
|
256
|
+
if "NIC" in prot["use_services"]:
|
|
257
|
+
this = defaults.copy()
|
|
258
|
+
this.update(prot["NIC"])
|
|
259
|
+
|
|
260
|
+
nic = NIC.make(
|
|
261
|
+
this["serializer"],
|
|
262
|
+
this["host"],
|
|
263
|
+
this["python_exe"],
|
|
264
|
+
new_console=new_console,
|
|
265
|
+
port=prot["NIC"]["port"],
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
nic_params = undefaultify(prot["NIC"])
|
|
269
|
+
nic.setup(
|
|
270
|
+
nic_params["output_channel"],
|
|
271
|
+
prot["maxduration"] + 10,
|
|
272
|
+
nic_params["frequency"],
|
|
273
|
+
nic_params["duty_cycle"],
|
|
274
|
+
nic_params,
|
|
275
|
+
)
|
|
276
|
+
nic.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_daq.log")
|
|
277
|
+
|
|
278
|
+
# display config info
|
|
279
|
+
for key, s in services.items():
|
|
280
|
+
rich_information(s.information(), prefix=key)
|
|
281
|
+
|
|
282
|
+
logging.info("Starting services")
|
|
283
|
+
# First, start video services - this will start acquisition or, if external triggering is enabled, arm the cameras to wait for the triggers
|
|
284
|
+
time_last_cam_started = time.time() + 5 # in case no cam was initialized
|
|
285
|
+
for service_name, service in services.items():
|
|
286
|
+
if "GCM" in service_name or "GOV" in service_name:
|
|
287
|
+
logging.info(f" {service_name}.")
|
|
288
|
+
service.start()
|
|
289
|
+
time_last_cam_started = time.time()
|
|
290
|
+
time.sleep(0.5)
|
|
291
|
+
|
|
292
|
+
# start the counter task for triggering frames
|
|
293
|
+
if "NIC" in prot["use_services"]:
|
|
294
|
+
logging.info(" NI Counter service.")
|
|
295
|
+
nic.start()
|
|
296
|
+
time_last_cam_started = time.time()
|
|
297
|
+
|
|
298
|
+
# Wait 5 seconds for cams to run
|
|
299
|
+
if daq_keys:
|
|
300
|
+
while time.time() - time_last_cam_started < 5:
|
|
301
|
+
time.sleep(0.1)
|
|
302
|
+
|
|
303
|
+
# Start DAQ services
|
|
304
|
+
for service_name, service in services.items():
|
|
305
|
+
if "DAQ" in service_name:
|
|
306
|
+
logging.info(f" {service_name}.")
|
|
307
|
+
service.start()
|
|
308
|
+
|
|
309
|
+
logging.info("All services started.")
|
|
310
|
+
|
|
311
|
+
if monitor or show_progress:
|
|
312
|
+
total = 0
|
|
313
|
+
for service_name, service in services.items():
|
|
314
|
+
total = max(total, service.progress()["total"])
|
|
315
|
+
if _queue is not None:
|
|
316
|
+
_queue.put(total)
|
|
317
|
+
cli_progress(services, save_prefix, _stop_event, _done_event, show_progress=show_progress)
|
|
318
|
+
else:
|
|
319
|
+
return services
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def cli_progress(
|
|
323
|
+
services: Dict[str, Any],
|
|
324
|
+
save_prefix: str,
|
|
325
|
+
stop_event: Optional[threading.Event] = None,
|
|
326
|
+
done_event: Optional[threading.Event] = None,
|
|
327
|
+
show_progress: bool = True,
|
|
328
|
+
):
|
|
329
|
+
"""_summary_
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
services (_type_): Dictionary of intialized services.
|
|
333
|
+
save_prefix (_type_): Name of the expt.
|
|
334
|
+
stop_event (_type_, optional): Used to stop the task from an outside thread. Defaults to None.
|
|
335
|
+
done_event (_type_, optional): Set to signal that the task is done/stopped to an outside thread. Defaults to None.
|
|
336
|
+
"""
|
|
337
|
+
STOPPED_PREMATURELY = False
|
|
338
|
+
try:
|
|
339
|
+
with Progress(disable=not show_progress) as progress:
|
|
340
|
+
tasks = {}
|
|
341
|
+
for service_name, service in services.items():
|
|
342
|
+
tasks[service_name] = progress.add_task(f"[red]{service_name}", total=service.progress()["total"])
|
|
343
|
+
RUN = True
|
|
344
|
+
while RUN and not progress.finished:
|
|
345
|
+
for task_name, task_id in tasks.items():
|
|
346
|
+
if stop_event is not None and stop_event.is_set():
|
|
347
|
+
break
|
|
348
|
+
if progress._tasks[task_id].finished:
|
|
349
|
+
continue
|
|
350
|
+
try:
|
|
351
|
+
p = timed(services[task_name].progress, 5)
|
|
352
|
+
description = None
|
|
353
|
+
if "framenumber" in p:
|
|
354
|
+
description = f"{task_name} {p['framenumber_delta'] / p['elapsed_delta']: 7.2f} fps"
|
|
355
|
+
progress.update(task_id, completed=p["elapsed"], description=description)
|
|
356
|
+
except: # if call times out, stop progress display - this will stop the display whenever a task times out - not necessarily when a task is done
|
|
357
|
+
progress.stop_task(task_id)
|
|
358
|
+
time.sleep(1)
|
|
359
|
+
|
|
360
|
+
if stop_event is not None and stop_event.is_set():
|
|
361
|
+
logging.info("Received STOP signal. Cancelling jobs:")
|
|
362
|
+
for task_name, task_id in tasks.items():
|
|
363
|
+
progress.stop_task(task_id)
|
|
364
|
+
RUN = False
|
|
365
|
+
STOPPED_PREMATURELY = True
|
|
366
|
+
time.sleep(1)
|
|
367
|
+
if STOPPED_PREMATURELY:
|
|
368
|
+
logging.info("Finishing jobs.")
|
|
369
|
+
for service_name, service in services.items():
|
|
370
|
+
logging.info(f" {service_name}")
|
|
371
|
+
try:
|
|
372
|
+
service.finish()
|
|
373
|
+
except Exception as e:
|
|
374
|
+
logging.warning(" Failed.")
|
|
375
|
+
print(e)
|
|
376
|
+
logging.info(" done.")
|
|
377
|
+
|
|
378
|
+
time.sleep(4)
|
|
379
|
+
finally:
|
|
380
|
+
logging.info("Cleaning up jobs.")
|
|
381
|
+
kill_child_processes()
|
|
382
|
+
if done_event is not None:
|
|
383
|
+
done_event.set()
|
|
384
|
+
logging.info(f"Done with experiment {save_prefix}.")
|