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/utils/runner.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import platform
|
|
4
|
+
import subprocess
|
|
5
|
+
from typing import List, Optional, Union
|
|
6
|
+
|
|
7
|
+
import psutil
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Runner:
|
|
13
|
+
"""Manages local processes."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, host: str = "localhost", python_exe: str = "python"):
|
|
16
|
+
self.host = host
|
|
17
|
+
self.python_exe = python_exe
|
|
18
|
+
|
|
19
|
+
system = platform.system().lower()
|
|
20
|
+
if system.startswith("win"):
|
|
21
|
+
self.host_os = "win"
|
|
22
|
+
elif system == "darwin":
|
|
23
|
+
self.host_os = "mac"
|
|
24
|
+
else:
|
|
25
|
+
self.host_os = system or "unknown"
|
|
26
|
+
|
|
27
|
+
def run(
|
|
28
|
+
self,
|
|
29
|
+
cmd: str,
|
|
30
|
+
timeout: Optional[float] = None,
|
|
31
|
+
asynchronous: Optional[bool] = False,
|
|
32
|
+
disown: bool = False,
|
|
33
|
+
new_console: bool = False,
|
|
34
|
+
) -> Union[subprocess.CompletedProcess, subprocess.Popen, None]:
|
|
35
|
+
"""Run a command on the local machine."""
|
|
36
|
+
logging.debug(
|
|
37
|
+
f"Running {cmd} with timeout={timeout}, asynchronous={asynchronous}, disown={disown}, new_console={new_console}."
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
if new_console:
|
|
41
|
+
if self.host_os == "win":
|
|
42
|
+
subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE)
|
|
43
|
+
elif self.host_os == "mac":
|
|
44
|
+
script = f'tell application "Terminal" to do script {json.dumps(cmd)}'
|
|
45
|
+
subprocess.Popen(["osascript", "-e", script])
|
|
46
|
+
else:
|
|
47
|
+
subprocess.Popen(cmd, shell=True, start_new_session=True)
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
if disown:
|
|
51
|
+
subprocess.Popen(
|
|
52
|
+
cmd,
|
|
53
|
+
shell=True,
|
|
54
|
+
stdin=subprocess.DEVNULL,
|
|
55
|
+
stdout=subprocess.DEVNULL,
|
|
56
|
+
stderr=subprocess.DEVNULL,
|
|
57
|
+
start_new_session=True,
|
|
58
|
+
)
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
if asynchronous:
|
|
62
|
+
return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
63
|
+
|
|
64
|
+
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
|
|
65
|
+
if result.returncode != 0:
|
|
66
|
+
raise subprocess.CalledProcessError(result.returncode, cmd, output=result.stdout, stderr=result.stderr)
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
def kill(self, pids: Union[int, List[int]]):
|
|
70
|
+
"""Kill process pid."""
|
|
71
|
+
if pids is None:
|
|
72
|
+
return
|
|
73
|
+
if isinstance(pids, int):
|
|
74
|
+
pids = [pids]
|
|
75
|
+
|
|
76
|
+
for pid in pids:
|
|
77
|
+
logging.debug(f"Killing process with pid {pid}.")
|
|
78
|
+
try:
|
|
79
|
+
psutil.Process(pid).kill()
|
|
80
|
+
except psutil.NoSuchProcess:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
def kill_python(self):
|
|
84
|
+
"""Kill all local python processes matching the runner's python executable name."""
|
|
85
|
+
logging.debug("Killing python processes.")
|
|
86
|
+
query = "python.exe" if self.host_os == "win" else "python"
|
|
87
|
+
pids = self.pid(query=query)
|
|
88
|
+
if pids:
|
|
89
|
+
self.kill(pids)
|
|
90
|
+
|
|
91
|
+
def kill_service(self, service_name):
|
|
92
|
+
pids = self.pid(query=service_name)
|
|
93
|
+
if pids:
|
|
94
|
+
logging.debug(f"Killing service '{service_name}' with pids {pids}.")
|
|
95
|
+
self.kill(pids)
|
|
96
|
+
|
|
97
|
+
def pid(self, query: str) -> List[int]:
|
|
98
|
+
"""Get pids of all local processes partially matching `query`."""
|
|
99
|
+
pids = []
|
|
100
|
+
for process in psutil.process_iter(attrs=["cmdline", "pid"]):
|
|
101
|
+
cmdline = process.info["cmdline"]
|
|
102
|
+
if cmdline is None:
|
|
103
|
+
continue
|
|
104
|
+
cmd = " ".join(cmdline)
|
|
105
|
+
if query in cmd:
|
|
106
|
+
pids.append(process.info["pid"])
|
|
107
|
+
return pids
|
|
108
|
+
|
|
109
|
+
def is_running(self, pids: List[int]) -> bool:
|
|
110
|
+
"""Return True if at least one of the pids is running."""
|
|
111
|
+
return any(psutil.pid_exists(pid) for pid in pids)
|
|
112
|
+
|
|
113
|
+
def is_online(self) -> bool:
|
|
114
|
+
"""Return True if the configured host responds to ping."""
|
|
115
|
+
params = "-n 1" if self.host_os == "win" else "-c 1"
|
|
116
|
+
try:
|
|
117
|
+
self.run(f"ping {params} {self.host}")
|
|
118
|
+
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
|
|
119
|
+
logger.debug(e, exc_info=e)
|
|
120
|
+
return False
|
|
121
|
+
return True
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from typing import Iterable
|
|
2
|
+
from itertools import cycle
|
|
3
|
+
import random
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class shuffled_cycle(cycle):
|
|
7
|
+
"""Shuffled cycle.
|
|
8
|
+
|
|
9
|
+
cycle('ABCD') --> ABCD ABCD ABCD ...
|
|
10
|
+
cycle('ABCD', shuffle='block') --> ACBD BDCA CDAB ...
|
|
11
|
+
cycle('ABCD', shuffle='full') --> ACCBBDBDCABA ...
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, it: Iterable, shuffle: str = "block"):
|
|
15
|
+
""".
|
|
16
|
+
|
|
17
|
+
Arguments:
|
|
18
|
+
it: Iterable
|
|
19
|
+
shuffle: None, 'block', 'full'
|
|
20
|
+
"""
|
|
21
|
+
allowed_shuffles = ["block", "full"]
|
|
22
|
+
if shuffle not in allowed_shuffles:
|
|
23
|
+
raise ValueError(f"shuffle should be one of {allowed_shuffles}.")
|
|
24
|
+
super(shuffled_cycle, self).__init__()
|
|
25
|
+
self._shuffle = shuffle
|
|
26
|
+
self._it = list(it)
|
|
27
|
+
self._pos = -1
|
|
28
|
+
|
|
29
|
+
def __next__(self):
|
|
30
|
+
"""Return next item in iterator."""
|
|
31
|
+
self._pos = (self._pos + 1) % len(self._it) # wrap index
|
|
32
|
+
if self._shuffle == "block":
|
|
33
|
+
if self._pos == 0:
|
|
34
|
+
random.shuffle(self._it) # in-place shuffle the iterator
|
|
35
|
+
idx = self._pos
|
|
36
|
+
elif self._shuffle == "full":
|
|
37
|
+
idx = random.randint(0, len(self._it) - 1) # since randint bounds are inclusive
|
|
38
|
+
# else:
|
|
39
|
+
# idx = self._pos
|
|
40
|
+
return self._it[idx]
|
|
41
|
+
|
|
42
|
+
def __deepcopy__(self, memo=None):
|
|
43
|
+
cp = shuffled_cycle(self._it, shuffle=self._shuffle)
|
|
44
|
+
cp._pos = self._pos
|
|
45
|
+
return cp
|
etho/utils/sound.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
from typing import Callable, List, Union, Dict
|
|
2
|
+
import os
|
|
3
|
+
import random
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import scipy.io.wavfile as wav
|
|
7
|
+
import scipy.signal
|
|
8
|
+
import h5py
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_cell(cell, dtype: Callable = None) -> List:
|
|
12
|
+
"""Cast cell to desired type and wrap into list."""
|
|
13
|
+
if isinstance(cell, str):
|
|
14
|
+
cell = cell.strip()
|
|
15
|
+
token = cell.lstrip("[").rstrip("]").split(",")
|
|
16
|
+
token = [tok.strip() for tok in token]
|
|
17
|
+
if dtype:
|
|
18
|
+
token = [dtype(tok) for tok in token]
|
|
19
|
+
else:
|
|
20
|
+
token = [cell]
|
|
21
|
+
return token
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def parse_table(
|
|
25
|
+
table: Union[pd.DataFrame, str],
|
|
26
|
+
dtypes: List[Callable] = [str, float, float, float, float, float, str],
|
|
27
|
+
normalize: bool = True,
|
|
28
|
+
) -> pd.DataFrame:
|
|
29
|
+
"""Parse table to desired types.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
table - either string (filepath pointing to playlist file) or dataframe
|
|
33
|
+
dtypes - types each col to cast to - methods which return the desired type
|
|
34
|
+
Returns:
|
|
35
|
+
table (dataframe)
|
|
36
|
+
"""
|
|
37
|
+
if isinstance(table, str):
|
|
38
|
+
table = pd.read_table(table, dtype=None, delimiter="\t", decimal=".")
|
|
39
|
+
tb = table.values
|
|
40
|
+
for row, row_values in enumerate(tb):
|
|
41
|
+
for col, cell in enumerate(row_values):
|
|
42
|
+
tb[row, col] = parse_cell(cell, dtypes[col])
|
|
43
|
+
df = pd.DataFrame(tb, columns=table.columns)
|
|
44
|
+
if normalize:
|
|
45
|
+
df = normalize_table(df)
|
|
46
|
+
return df
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def normalize_table(table: pd.DataFrame) -> pd.DataFrame:
|
|
50
|
+
"""Make sure each cell in a row has one entry for stimFileName.
|
|
51
|
+
|
|
52
|
+
E.g. if two stimFileName but only one intensity, will duplicate the intensity entries.
|
|
53
|
+
"""
|
|
54
|
+
# strict - throw error in case of inconsistencies
|
|
55
|
+
tb = table.values
|
|
56
|
+
for row, row_values in enumerate(tb):
|
|
57
|
+
nchans = len(row_values[0]) # 1. get n stim channels from len(stimFileName)
|
|
58
|
+
for col, cell in enumerate(row_values[1:]):
|
|
59
|
+
if len(cell) < nchans:
|
|
60
|
+
tb[row, col + 1] = [
|
|
61
|
+
cell[0]
|
|
62
|
+
] * nchans # 2. fill remaining cols to match len(stimFileName)
|
|
63
|
+
df = pd.DataFrame(tb, columns=table.columns)
|
|
64
|
+
return df
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def select_channels_from_playlist(playlist: pd.DataFrame, channels_to_keep: List[str]):
|
|
68
|
+
"""[summary]
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
playlist (pd.DataFrame): [description]
|
|
72
|
+
channels_to_keep (List[str]): [description]
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
pd.DataFrame: playlist with selected channels
|
|
76
|
+
"""
|
|
77
|
+
playlist_new = playlist.copy()
|
|
78
|
+
for col_name, col_data in playlist_new.iteritems():
|
|
79
|
+
for row_name, row_data in col_data.iteritems():
|
|
80
|
+
if isinstance(row_data, (list, tuple)):
|
|
81
|
+
# playlist_new.set_value(row_name, col_name, [row_data[channel] for channel in channels_to_keep])
|
|
82
|
+
playlist_new.at[row_name, col_name] = [
|
|
83
|
+
row_data[channel] for channel in channels_to_keep
|
|
84
|
+
]
|
|
85
|
+
if isinstance(row_data, np.ndarray):
|
|
86
|
+
# playlist_new.set_value(row_name, col_name, np.array(row_data)[channels_to_keep])
|
|
87
|
+
playlist_new.at[row_name, col_name] = np.array(row_data)[
|
|
88
|
+
channels_to_keep
|
|
89
|
+
]
|
|
90
|
+
return playlist_new
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_pulse_parameters(playlist, sounds, fs):
|
|
94
|
+
"""[summary]
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
playlist ([type]): [description]
|
|
98
|
+
sounds ([type]): list of np.arrays, the length of which determines the trial period
|
|
99
|
+
fs (float): sampling rate for translating nb_samples in sounds to seconds
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
[type]: [description]
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
nb_led = len(playlist.stimFileName[0]) # max over rows of len(stimFileNames) - 2
|
|
106
|
+
blink_durs = np.zeros((nb_led,), dtype=np.int)
|
|
107
|
+
blink_paus = np.zeros_like(blink_durs)
|
|
108
|
+
blink_nums = np.zeros_like(blink_durs)
|
|
109
|
+
blink_dels = np.zeros_like(blink_durs)
|
|
110
|
+
blink_amps = np.zeros_like(blink_durs)
|
|
111
|
+
pulse_params = pd.DataFrame(
|
|
112
|
+
columns=["duration", "pause", "number", "delay", "amplitude", "trial_period"],
|
|
113
|
+
dtype=object,
|
|
114
|
+
)
|
|
115
|
+
for index, row in playlist.iterrows():
|
|
116
|
+
for stim_num, stim_amp in enumerate(row.intensity):
|
|
117
|
+
blink_amps[stim_num] = stim_amp
|
|
118
|
+
pulse_params.loc[index, "amplitude"] = row.intensity
|
|
119
|
+
|
|
120
|
+
for stim_num, stim in enumerate(row.stimFileName):
|
|
121
|
+
if stim.startswith("PUL"):
|
|
122
|
+
(
|
|
123
|
+
blink_durs[stim_num],
|
|
124
|
+
blink_paus[stim_num],
|
|
125
|
+
blink_nums[stim_num],
|
|
126
|
+
blink_dels[stim_num],
|
|
127
|
+
) = [int(token) for token in stim.split("_")[1:]]
|
|
128
|
+
pulse_params.loc[index, "duration"] = blink_durs / 1000
|
|
129
|
+
pulse_params.loc[index, "pause"] = blink_paus / 1000
|
|
130
|
+
pulse_params.loc[index, "number"] = blink_nums
|
|
131
|
+
pulse_params.loc[index, "delay"] = blink_dels / 1000
|
|
132
|
+
pulse_params.loc[index, "trial_period"] = sounds[index].shape[0] / fs
|
|
133
|
+
return pulse_params
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def make_sine(
|
|
137
|
+
frequency: float, phase: float, duration: float, samplingrate: float
|
|
138
|
+
) -> np.array:
|
|
139
|
+
"""Make sinusoidal from parameters.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
frequency [Hz], phase [pi], duration [ms], samplingrate [Hz]
|
|
143
|
+
Returns:
|
|
144
|
+
np.array with stimulus waveform
|
|
145
|
+
"""
|
|
146
|
+
t = np.arange(0, duration / 1000, 1 / samplingrate)
|
|
147
|
+
x = np.sin(2 * np.pi * t * frequency + phase)
|
|
148
|
+
return x
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def make_pulse(
|
|
152
|
+
pulseDur: float,
|
|
153
|
+
pulsePau: float,
|
|
154
|
+
pulseNumber: float,
|
|
155
|
+
pulseDelay: float,
|
|
156
|
+
samplingrate: float,
|
|
157
|
+
) -> np.array:
|
|
158
|
+
"""Make square pulse train.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
pulseDur [ms], pulsePau [ms], pulseNumber, pulseDelay [ms], samplingrate [Hz]
|
|
162
|
+
Returns:
|
|
163
|
+
np.array with stimulus waveform
|
|
164
|
+
"""
|
|
165
|
+
x = np.concatenate(
|
|
166
|
+
(
|
|
167
|
+
np.ones((np.intp(samplingrate * pulseDur / 1000),)),
|
|
168
|
+
np.zeros((np.intp(samplingrate * pulsePau / 1000),)),
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
x = np.tile(x, (np.intp(pulseNumber),))
|
|
172
|
+
x = np.concatenate((np.ones((np.intp(samplingrate * pulseDelay / 1000),)), x))
|
|
173
|
+
return x
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def build_playlist(
|
|
177
|
+
soundlist: List[np.array],
|
|
178
|
+
duration: float,
|
|
179
|
+
fs: float,
|
|
180
|
+
shuffle=False,
|
|
181
|
+
sound_order=None,
|
|
182
|
+
):
|
|
183
|
+
"""Block-shuffle playlist and concatenate to duration."""
|
|
184
|
+
if sound_order is None:
|
|
185
|
+
sound_order = np.arange(len(soundlist))
|
|
186
|
+
|
|
187
|
+
totallen = 0
|
|
188
|
+
if duration > 0:
|
|
189
|
+
playlist_items = list()
|
|
190
|
+
# add sounds to list as long as total duration is shorter than max duration
|
|
191
|
+
while totallen < duration:
|
|
192
|
+
# re-shuffle at the end of each block
|
|
193
|
+
if shuffle and len(playlist_items) % len(sound_order) == 0:
|
|
194
|
+
sound_order = np.random.permutation(sound_order)
|
|
195
|
+
|
|
196
|
+
next_item = sound_order[len(playlist_items) % len(sound_order)]
|
|
197
|
+
playlist_items.append(next_item)
|
|
198
|
+
totallen += len(soundlist[playlist_items[-1]]) / fs
|
|
199
|
+
elif duration == -1: # play sound_order once
|
|
200
|
+
if shuffle:
|
|
201
|
+
sound_order = np.random.permutation(sound_order)
|
|
202
|
+
playlist_items = sound_order.tolist()
|
|
203
|
+
|
|
204
|
+
# get total duration of playlist
|
|
205
|
+
for item in playlist_items:
|
|
206
|
+
totallen += len(soundlist[item]) / fs
|
|
207
|
+
return playlist_items, totallen
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def load_sounds(
|
|
211
|
+
playlist: pd.DataFrame,
|
|
212
|
+
fs: float,
|
|
213
|
+
attenuation: Dict[float, float] = None,
|
|
214
|
+
calibration: Dict = None,
|
|
215
|
+
LEDamp: float = 1.0,
|
|
216
|
+
stimfolder: str = "./",
|
|
217
|
+
aslist: bool = False,
|
|
218
|
+
stim_key: str = "stimulus",
|
|
219
|
+
ignore_stop: bool = False,
|
|
220
|
+
):
|
|
221
|
+
sounddata = []
|
|
222
|
+
for row_number, (row_name, listitem) in enumerate(playlist.iterrows()):
|
|
223
|
+
mirror_led_channel = []
|
|
224
|
+
xx = [None] * len(listitem.stimFileName)
|
|
225
|
+
for stimIdx, stimName in enumerate(listitem.stimFileName):
|
|
226
|
+
x = np.zeros((0, 1))
|
|
227
|
+
# These all acknowledge the pre/post stim silence: SIN, PUL, MIRROR_LED, *.wav, *.h5
|
|
228
|
+
if stimName[:3] == "SIN": # SIN_FREQ_PHASE_DURATION
|
|
229
|
+
# print('sine')
|
|
230
|
+
token = stimName[4:].split("_")
|
|
231
|
+
token = [float(item) for item in token]
|
|
232
|
+
freq, phase, duration = token[:3]
|
|
233
|
+
x = make_sine(freq, phase, duration, fs)
|
|
234
|
+
elif stimName[:3] == "PUL": # PUL_DUR_PAU_NUM_DEL
|
|
235
|
+
# print('pulse')
|
|
236
|
+
token = stimName[4:].split("_")
|
|
237
|
+
token = [float(item) for item in token]
|
|
238
|
+
pulsedur, pulsepause, pulsenumber, pulsedelay = token[:4]
|
|
239
|
+
x = make_pulse(pulsedur, pulsepause, pulsenumber, pulsedelay, fs)
|
|
240
|
+
elif (
|
|
241
|
+
stimName == "MIRROR_LED"
|
|
242
|
+
): # this channel contains a pulse train which mirrors the sound from another channel
|
|
243
|
+
mirror_led_channel.append(stimIdx) # mirror led
|
|
244
|
+
elif stimName.endswith(".wav"): # WAV file
|
|
245
|
+
# return time x channels
|
|
246
|
+
wav_rate, x = wav.read(os.path.join(stimfolder, stimName))
|
|
247
|
+
x = x.astype(np.float32) / 32768
|
|
248
|
+
if wav_rate != fs: # resample to fs
|
|
249
|
+
x = scipy.signal.resample_poly(x, int(fs), int(wav_rate), axis=0)
|
|
250
|
+
elif stimName.endswith(".h5"): # HDF5 file
|
|
251
|
+
with h5py.File(os.path.join(stimfolder, stimName), "r") as f:
|
|
252
|
+
try:
|
|
253
|
+
x = f[stim_key][:].astype(np.float32)
|
|
254
|
+
except KeyError as e:
|
|
255
|
+
print(e)
|
|
256
|
+
|
|
257
|
+
# if `attenuation` arg is provided:
|
|
258
|
+
if attenuation:
|
|
259
|
+
x = x * float(attenuation[listitem.freq[stimIdx]])
|
|
260
|
+
# set_volume
|
|
261
|
+
if len(x):
|
|
262
|
+
x = x * float(listitem.intensity[stimIdx]) # "* 20" NOT USED FOR DAQ
|
|
263
|
+
|
|
264
|
+
# pre/post pend silence
|
|
265
|
+
sample_start = np.intp(listitem.silencePre[stimIdx] / 1000 * fs)
|
|
266
|
+
sample_end = np.intp(listitem.silencePost[stimIdx] / 1000 * fs)
|
|
267
|
+
sample_sound = x.shape[0]
|
|
268
|
+
|
|
269
|
+
x = np.insert(x, 0, np.zeros((sample_start,)))
|
|
270
|
+
x = np.insert(x, x.shape[0], np.zeros((sample_end,)))
|
|
271
|
+
x = x.reshape((x.shape[0], 1))
|
|
272
|
+
|
|
273
|
+
xx[stimIdx] = x
|
|
274
|
+
non_mirror_led_chan = [
|
|
275
|
+
x for x in list(range(len(xx))) if not x in mirror_led_channel
|
|
276
|
+
][0]
|
|
277
|
+
for chan in mirror_led_channel:
|
|
278
|
+
xLED = np.zeros(
|
|
279
|
+
xx[non_mirror_led_chan].shape
|
|
280
|
+
) # second channel is all zeros unless we mirrorsound
|
|
281
|
+
# copy channel for led
|
|
282
|
+
# duration of the LED pattern at least 100ms if possible so it registers in video
|
|
283
|
+
minLEDduration = 3 * fs # at least 3s
|
|
284
|
+
# set to minimal duration
|
|
285
|
+
LEDduration = np.max((sample_sound, minLEDduration))
|
|
286
|
+
# prevent overflow (if 100ms exceeds duration of sound)
|
|
287
|
+
LEDduration = np.min((xLED.shape[0] - sample_start, LEDduration))
|
|
288
|
+
# parameters of the LED pattern
|
|
289
|
+
pdur = 5 # ms
|
|
290
|
+
ppau = 5 # ms
|
|
291
|
+
pdel = 0 # ms
|
|
292
|
+
LEDpattern = make_pulse(
|
|
293
|
+
pdur, ppau, LEDduration / (pdur + ppau) / fs * 1000, pdel, fs
|
|
294
|
+
)
|
|
295
|
+
xLED[sample_start : sample_start + LEDpattern.shape[0], 0] = (
|
|
296
|
+
LEDpattern - 0.5
|
|
297
|
+
) * float(LEDamp)
|
|
298
|
+
xx[chan] = xLED
|
|
299
|
+
|
|
300
|
+
# make sure each channel in xx has the same length
|
|
301
|
+
max_len = max([len(ii) for ii in xx])
|
|
302
|
+
xx = [np.insert(ii, ii.shape[0], np.zeros((max_len - len(ii),))) for ii in xx]
|
|
303
|
+
xx = [x.reshape((x.shape[0], 1)) for x in xx]
|
|
304
|
+
|
|
305
|
+
for cnt, (x, stimName) in enumerate(zip(xx, listitem.stimFileName)):
|
|
306
|
+
# These DO NOT acknowledge silencePre/Post - will start at the first sample (during pre stim silence) and end at the last sample (end of post stim silence:
|
|
307
|
+
# SI_START, SI_STOP, SI_NEXT, CLOCK_durMS_pauMS
|
|
308
|
+
if stimName == "SI_START":
|
|
309
|
+
x[:20] = 1
|
|
310
|
+
elif stimName == "SI_NEXT":
|
|
311
|
+
x[-20:-2] = 1
|
|
312
|
+
elif stimName == "SI_STOP":
|
|
313
|
+
# if playlist is not shuffled, add STOP trigger to last stimulus in the playlist
|
|
314
|
+
last_stim = row_number == len(playlist) - 1
|
|
315
|
+
if not ignore_stop and last_stim:
|
|
316
|
+
x[-20:-2] = 1
|
|
317
|
+
elif stimName[:5] == "CLOCK":
|
|
318
|
+
token = stimName[5:].split("_")
|
|
319
|
+
token = [float(item) for item in token]
|
|
320
|
+
pulsedur, pulsepause = token[:2]
|
|
321
|
+
pulseperiod = pulsedur + pulsepause
|
|
322
|
+
pulsenumber = (len(x) / fs * 1000) // pulseperiod + 1
|
|
323
|
+
tmp_x = make_pulse(
|
|
324
|
+
pulsedur,
|
|
325
|
+
pulsepause,
|
|
326
|
+
pulsenumber=pulsenumber,
|
|
327
|
+
pulseDelay=0,
|
|
328
|
+
samplingrate=fs,
|
|
329
|
+
)
|
|
330
|
+
x = tmp_x[: len(x)]
|
|
331
|
+
|
|
332
|
+
x = np.concatenate(xx, axis=1)
|
|
333
|
+
if aslist:
|
|
334
|
+
x = x.tolist()
|
|
335
|
+
sounddata.append(x)
|
|
336
|
+
return sounddata
|
etho/utils/tui.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import rich
|
|
2
|
+
from rich.panel import Panel
|
|
3
|
+
from rich.console import Console
|
|
4
|
+
from rich.table import Table
|
|
5
|
+
from typing import Optional
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def dict_to_def(d, defaults=None):
|
|
11
|
+
s = ""
|
|
12
|
+
for key, val in d.items():
|
|
13
|
+
s += f"[bold]{key}[/]:\n {str(val)}"
|
|
14
|
+
if defaults is not None and key in defaults:
|
|
15
|
+
s += f" (target: {str(defaults[key])})"
|
|
16
|
+
s += "\n"
|
|
17
|
+
return s
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def dict_to_table(d, title=None, key_name="Key", value_names=None):
|
|
21
|
+
|
|
22
|
+
table = Table(title=title)
|
|
23
|
+
|
|
24
|
+
table.add_column(key_name, justify="right", style="cyan", no_wrap=True)
|
|
25
|
+
if value_names is None:
|
|
26
|
+
first_key = list(d.keys())[0]
|
|
27
|
+
value_names = [f"Value {cnt}" for cnt, _ in enumerate(d[first_key])]
|
|
28
|
+
|
|
29
|
+
for value_name in value_names:
|
|
30
|
+
table.add_column(value_name, justify="left", style="magenta")
|
|
31
|
+
|
|
32
|
+
for key, val in d.items():
|
|
33
|
+
table.add_row(key, *[str(v) for v in val])
|
|
34
|
+
return table
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def df_to_table(
|
|
38
|
+
pandas_dataframe: pd.DataFrame,
|
|
39
|
+
show_index: bool = True,
|
|
40
|
+
index_name: Optional[str] = None,
|
|
41
|
+
) -> Table:
|
|
42
|
+
"""Convert a pandas.DataFrame obj into a rich.Table obj.
|
|
43
|
+
Args:
|
|
44
|
+
pandas_dataframe (DataFrame): A Pandas DataFrame to be converted to a rich Table.
|
|
45
|
+
show_index (bool): Add a column with a row count to the table. Defaults to True.
|
|
46
|
+
index_name (str, optional): The column name to give to the index column. Defaults to None, showing no value.
|
|
47
|
+
Returns:
|
|
48
|
+
Table: The rich Table instance passed, populated with the DataFrame values."""
|
|
49
|
+
rich_table = Table()
|
|
50
|
+
|
|
51
|
+
if show_index:
|
|
52
|
+
index_name = str(index_name) if index_name else ""
|
|
53
|
+
rich_table.add_column(index_name)
|
|
54
|
+
|
|
55
|
+
for column in pandas_dataframe.columns:
|
|
56
|
+
rich_table.add_column(str(column))
|
|
57
|
+
|
|
58
|
+
for index, value_list in enumerate(pandas_dataframe.values.tolist()):
|
|
59
|
+
row = [str(index)] if show_index else []
|
|
60
|
+
row += [str(x) for x in value_list]
|
|
61
|
+
rich_table.add_row(*row)
|
|
62
|
+
|
|
63
|
+
return rich_table
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def rich_information(info, prefix=""):
|
|
67
|
+
for key, val in info.items():
|
|
68
|
+
if isinstance(val, dict):
|
|
69
|
+
rich.print(Panel(dict_to_def(val), title=f"{prefix}: {key}"))
|
|
70
|
+
elif isinstance(val, (list, tuple)):
|
|
71
|
+
rich.print(Panel(dict_to_def(val[0], defaults=val[1]), title=f"{prefix}: {key}"))
|
|
72
|
+
elif isinstance(val, pd.DataFrame):
|
|
73
|
+
rich.print(Panel(df_to_table(val), title=f"{prefix}: {key}"))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class CameraProgress:
|
|
77
|
+
def __init__(self, nbFrames: int):
|
|
78
|
+
self.prev_t: Optional[float] = None
|
|
79
|
+
self.prev_n: Optional[int] = None
|
|
80
|
+
self.console = Console()
|
|
81
|
+
self.nbFrames = nbFrames
|
|
82
|
+
self.nDigits = len(str(int(self.nbFrames)))
|
|
83
|
+
|
|
84
|
+
def update(self, number_of_frames: int, payload=None):
|
|
85
|
+
t = time.time()
|
|
86
|
+
if self.prev_t is not None:
|
|
87
|
+
current_frame_interval = (t - self.prev_t) / (number_of_frames - self.prev_n)
|
|
88
|
+
current_frame_rate = 1 / current_frame_interval
|
|
89
|
+
|
|
90
|
+
prgrs_len = self.console.size.width // 2 - 40
|
|
91
|
+
prgrs_cut = round(number_of_frames / (self.nbFrames // prgrs_len))
|
|
92
|
+
|
|
93
|
+
prgrs = []
|
|
94
|
+
for pos in range(prgrs_len):
|
|
95
|
+
if pos < prgrs_cut:
|
|
96
|
+
prgrs.append("█")
|
|
97
|
+
else:
|
|
98
|
+
prgrs.append("░")
|
|
99
|
+
|
|
100
|
+
progressbar = f"\rCamera: [{''.join(prgrs)}] {int(number_of_frames): {self.nDigits}d}/{self.nbFrames} frames at {current_frame_rate:1.2f} fps "
|
|
101
|
+
if payload is not None:
|
|
102
|
+
progressbar += f"{payload}"
|
|
103
|
+
print(progressbar, end="")
|
|
104
|
+
self.prev_t = t
|
|
105
|
+
self.prev_n = number_of_frames
|