foreshore 0.0.1__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.
- foreshore/__init__.py +6 -0
- foreshore/data_preparation/prepare_evaluation_data.py +99 -0
- foreshore/debugging/AFESamna_AFESim_chirp_test.py +42 -0
- foreshore/debugging/afe_chirp_experiment.py +393 -0
- foreshore/debugging/chirp_gen.py +86 -0
- foreshore/deployment/xyloMonitor_test.py +55 -0
- foreshore/deployment/xyloSamna_test.py +61 -0
- foreshore/deployment/xyloSim_test.py +58 -0
- foreshore/deployment/xylo_deployment.py +559 -0
- foreshore/deployment/xylo_experiment.py +586 -0
- foreshore/docs/templates/dataset/your_dataset.py +256 -0
- foreshore/docs/templates/train_snn.py +161 -0
- foreshore/docs/tutorial_rare_sound/data_module_rare_sound.py +138 -0
- foreshore/docs/tutorial_rare_sound/train_snn_rare_sound.py +119 -0
- foreshore/tests/test_afesim.py +71 -0
- foreshore/tests/test_basic_transforms.py +321 -0
- foreshore/tests/test_binary_predicitons.py +258 -0
- foreshore/tests/test_loss.py +603 -0
- foreshore/tests/test_multiclass_predictions.py +234 -0
- foreshore/training_testing/data_module.py +373 -0
- foreshore/training_testing/loss.py +739 -0
- foreshore/training_testing/metrics/binary_metrics.py +68 -0
- foreshore/training_testing/metrics/multiclass_metrics.py +181 -0
- foreshore/training_testing/metrics/non_scalar_metrics.py +376 -0
- foreshore/training_testing/metrics/stat_scores.py +57 -0
- foreshore/training_testing/predictions/__init__.py +2 -0
- foreshore/training_testing/predictions/binary.py +291 -0
- foreshore/training_testing/predictions/multiclass.py +145 -0
- foreshore/training_testing/training_module.py +653 -0
- foreshore/training_testing/transforms/basic_transforms.py +129 -0
- foreshore/training_testing/transforms/to_spike_transform.py +127 -0
- foreshore/training_testing/weights_checkpoint.py +32 -0
- foreshore/utils/audio_test_utils.py +88 -0
- foreshore/utils/cache_utils.py +44 -0
- foreshore/utils/model_validation_utils.py +156 -0
- foreshore/utils/xylohdk_utils.py +63 -0
- foreshore-0.0.1.dist-info/METADATA +21 -0
- foreshore-0.0.1.dist-info/RECORD +40 -0
- foreshore-0.0.1.dist-info/WHEEL +5 -0
- foreshore-0.0.1.dist-info/top_level.txt +1 -0
foreshore/__init__.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import yaml
|
|
3
|
+
import json
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
def prepare_evaluation_data(txt_file, partition, model_path, data_module_cls):
|
|
7
|
+
"""
|
|
8
|
+
During training we save the cache data path for the AFESim data for each partition.
|
|
9
|
+
If a direct cache path was given to the data module, only direct_cached_data will be stored on the file.
|
|
10
|
+
Otherwise, the data.txt file will contain the cache_path and cache_id.
|
|
11
|
+
Once having the cache path and the configuration used during training, the code calls the DataModule
|
|
12
|
+
to get all the samples from the give partition ('train', 'val', 'test')
|
|
13
|
+
We format the data as a dictionary with 'data' and 'label' keys. XyloSimExperiment and XyloSamnaExperiment expect this format.
|
|
14
|
+
This dictionary will be saved in the correspoding experiment folder, this ensures the model is evaluated with the correct data.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
txt_file (str): Path to the text file that was saved during training. This text file includes the paths for AFEsim data and original audio paths
|
|
18
|
+
partition(str): Indicates the partition data to be used to evaluate the model. Options are: 'train', 'val', or 'test'
|
|
19
|
+
model_path (str): Path to the trained model specifications and checkpoints
|
|
20
|
+
data_module_cls
|
|
21
|
+
"""
|
|
22
|
+
config_file = os.path.join(model_path, "config.yaml")
|
|
23
|
+
data_path = os.path.join(model_path, "data/")
|
|
24
|
+
save_name = f"{partition}_input_data.npy"
|
|
25
|
+
with open(txt_file, "r") as f:
|
|
26
|
+
data = dict(line.strip().split("=", 1) for line in f)
|
|
27
|
+
|
|
28
|
+
if "direct_cached_data" in list(data.keys()):
|
|
29
|
+
cache_dir = data["direct_cached_data"]
|
|
30
|
+
else:
|
|
31
|
+
cache_path = data["cache_path"]
|
|
32
|
+
cache_id = data["cache_id"]
|
|
33
|
+
|
|
34
|
+
cache_dir = os.path.join(cache_path, "cache", cache_id, partition)
|
|
35
|
+
with open(config_file, "r") as f:
|
|
36
|
+
config = yaml.safe_load(f)
|
|
37
|
+
|
|
38
|
+
params_dataset = config["data"]["params_dataset"]
|
|
39
|
+
|
|
40
|
+
# Set the data module
|
|
41
|
+
dl = data_module_cls(
|
|
42
|
+
batch_size_train=100,
|
|
43
|
+
batch_size_val=10000,
|
|
44
|
+
batch_size_test=10000,
|
|
45
|
+
params_dataset=params_dataset,
|
|
46
|
+
cache_dataset=True,
|
|
47
|
+
direct_cached_data=cache_dir,
|
|
48
|
+
reset_cache=False,
|
|
49
|
+
)
|
|
50
|
+
dl.setup()
|
|
51
|
+
|
|
52
|
+
if partition == "test":
|
|
53
|
+
dataloader = dl.test_dataloader()
|
|
54
|
+
|
|
55
|
+
elif partition == "val":
|
|
56
|
+
dataloader = dl.val_dataloader()
|
|
57
|
+
|
|
58
|
+
# We set the val and test batch size high so we can have a single batch with all the samples.
|
|
59
|
+
# If your dataset is too big, you would generate more than one npy file containing your val/test samples.
|
|
60
|
+
if len(dataloader) > 1:
|
|
61
|
+
for i in range(len(dataloader)):
|
|
62
|
+
save_path = os.path.join(data_path, f"{save_name}_batch_{i}")
|
|
63
|
+
data_test, label_test = next(iter(dataloader))
|
|
64
|
+
data["data"] = data_test.squeeze().detach().numpy()
|
|
65
|
+
data["label"] = label_test.squeeze().detach().numpy()
|
|
66
|
+
np.save(save_path, data)
|
|
67
|
+
|
|
68
|
+
elif len(dataloader) == 1:
|
|
69
|
+
save_path = os.path.join(data_path, f"{save_name}")
|
|
70
|
+
data_test, label_test = next(iter(dataloader))
|
|
71
|
+
data["data"] = data_test.squeeze().detach().numpy()
|
|
72
|
+
data["label"] = label_test.squeeze().detach().numpy()
|
|
73
|
+
np.save(save_path, data)
|
|
74
|
+
|
|
75
|
+
else:
|
|
76
|
+
raise Exception("Data loader is empty, please check your parameters")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def prepare_audio_paths(txt_file, partition):
|
|
80
|
+
"""
|
|
81
|
+
During training we save the cache data path for the AFESim data
|
|
82
|
+
But also the config_data that points to the original audio paths in each partition.
|
|
83
|
+
The code expects a json file that has 3 keys:
|
|
84
|
+
'train', 'val', and 'test'. The user needs to define which partition
|
|
85
|
+
to use to get the audios and load them for the xyloMonitor_experiment
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
txt_file (str): Path to the text file that was saved during training. This text file includes the paths for AFEsim data and original audio paths
|
|
89
|
+
partition(str): Indicates the partition data to be used to evaluate the model. Options are: 'train', 'val', or 'test'
|
|
90
|
+
"""
|
|
91
|
+
with open(txt_file, "r") as f:
|
|
92
|
+
data = dict(line.strip().split("=", 1) for line in f)
|
|
93
|
+
|
|
94
|
+
json_config = data["config_data"]
|
|
95
|
+
with open(json_config) as f:
|
|
96
|
+
config = json.load(f)
|
|
97
|
+
partition_audio_paths = config[partition]
|
|
98
|
+
|
|
99
|
+
return partition_audio_paths
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
from foreshore.debugging.afe_chirp_experiment import AFE_chirp_experiment
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
In this script we compare the spike activity produced by:
|
|
6
|
+
|
|
7
|
+
- **AFESim**: the software simulation of the Xylo analog frontend (AFE).
|
|
8
|
+
- **AFESamna**: the physical AFE on the connected Xylo development kit.
|
|
9
|
+
|
|
10
|
+
The experiment plays a chirp through a speaker connected to your PC while AFESamna records the events produced
|
|
11
|
+
from sound captured by the board microphone. The same chirp waveform is also passed directly to AFESim.
|
|
12
|
+
|
|
13
|
+
This provides a practical check that the board AFE is receiving and encoding audio as expected.
|
|
14
|
+
It also helps compare the simulated AFE with the physical setup used for deployment.
|
|
15
|
+
|
|
16
|
+
See docs/debugging/AFE_chirp_test.ipynb for more details about this test.
|
|
17
|
+
"""
|
|
18
|
+
# ------------------------------------------- TEST PARAMS ------------------------------------------- #
|
|
19
|
+
# Select which device are you using for delpoyment, XyloA2 or XyloA3
|
|
20
|
+
device_type = "XyloA3"
|
|
21
|
+
# Specify the duraiton of the chirp signal
|
|
22
|
+
duration_input_signal = 2
|
|
23
|
+
add_silence = False
|
|
24
|
+
exp_tag = "max_volume"
|
|
25
|
+
|
|
26
|
+
# -------------------------------------------- INITIALIZE TEST --------------------------------------------- #
|
|
27
|
+
afe_chirp_exp = AFE_chirp_experiment(
|
|
28
|
+
device_type=device_type,
|
|
29
|
+
duration_input_signal=duration_input_signal,
|
|
30
|
+
add_silence_period=add_silence,
|
|
31
|
+
experiment_tag=exp_tag,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------- RUN TEST FOR AFE ---------------------------------------- #
|
|
35
|
+
# AFESim
|
|
36
|
+
afe_chirp_exp.evolve_afe(mode="AFESim")
|
|
37
|
+
# AFESamna
|
|
38
|
+
afe_chirp_exp.evolve_afe(mode="AFESamna")
|
|
39
|
+
|
|
40
|
+
# ---------------------------------------- PLOT COMPARISSON ---------------------------------------- #
|
|
41
|
+
figure = afe_chirp_exp.plot_comparison(save_fig=True)
|
|
42
|
+
plt.show()
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy.io import wavfile
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
from chirp_gen import ChirpGen
|
|
6
|
+
from foreshore.utils.xylohdk_utils import find_xylo
|
|
7
|
+
from foreshore.utils.audio_test_utils import get_wave_object
|
|
8
|
+
|
|
9
|
+
dt_AFE_xyloA3 = 0.009994
|
|
10
|
+
dt_AFE_xyloA2 = 0.01
|
|
11
|
+
# ----------------------------------------- AFESIM PARAMETERS ----------------------------------------- #
|
|
12
|
+
AFESIM_A2_PARAMETERS = {
|
|
13
|
+
"max_spike_per_raster_period": 15,
|
|
14
|
+
"add_noise": True,
|
|
15
|
+
"add_offset": True,
|
|
16
|
+
"add_mismatch": True,
|
|
17
|
+
"dt": dt_AFE_xyloA2,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
AFESIM_A3_PARAMETERS = {
|
|
21
|
+
"spike_gen_mode": "divisive_norm",
|
|
22
|
+
"dn_EPS": 32,
|
|
23
|
+
"fixed_threshold_vec": None,
|
|
24
|
+
"rate_scale_factor": 63,
|
|
25
|
+
"low_pass_averaging_window": 84e-3,
|
|
26
|
+
"dt": dt_AFE_xyloA3,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
# ----------------------------------------- AFESAMNA PARAMETERS ----------------------------------------- #
|
|
30
|
+
AFESAMNA_A2_PARAMETERS = {
|
|
31
|
+
"config": None,
|
|
32
|
+
"dt": dt_AFE_xyloA2,
|
|
33
|
+
"auto_calibrate": False,
|
|
34
|
+
"amplify_level": "mid",
|
|
35
|
+
"hibernation_mode": False,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
AFESAMNA_A3_PARAMETERS = {
|
|
39
|
+
"config": None,
|
|
40
|
+
"dt": dt_AFE_xyloA3,
|
|
41
|
+
"hibernation_mode": False,
|
|
42
|
+
"divisive_norm": True,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# ----------------------------------------- CHIRP PARAMETERS ----------------------------------------- #
|
|
46
|
+
CHIRP_PARAMETERS = {
|
|
47
|
+
"fs": 48e3, # sampling frequency of the audio in Hz
|
|
48
|
+
"fmin": 100, # min frequency of the chirp signal in Hz
|
|
49
|
+
"fmax": 17_000, # max frequency of the chirp signal in Hz
|
|
50
|
+
"num_bits_Q": 16, # number of bits used for quantizing the audio signal.
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------------------------------- #
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AFE_chirp_experiment:
|
|
57
|
+
"""
|
|
58
|
+
AFE_chirp_experiment sets and runs a test for AFESamna and AFESim to compare the behavior of the
|
|
59
|
+
Analog font-end of xylo board. This experiment requires a XyloAudio board connected to your machine.
|
|
60
|
+
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
device_type,
|
|
66
|
+
duration_input_signal=2,
|
|
67
|
+
add_silence_period=False,
|
|
68
|
+
experiment_tag=None,
|
|
69
|
+
):
|
|
70
|
+
"""
|
|
71
|
+
Instantiates AFE_chirp_experiment
|
|
72
|
+
Args:
|
|
73
|
+
device_type (str): indicates which device the user wants to use for deployment (XyloA2 or XyloA3)
|
|
74
|
+
duration_input_signal (float): duration of the experiment's input signal in seconds
|
|
75
|
+
add_silence_period (bool): if True, a silence period of the same duration of the signal will be added at the beginning. Default to False
|
|
76
|
+
experiment_tag (str): extra tag name to add to the experiment results filename to identify a specific experiment. For example, let's say the user
|
|
77
|
+
would like to run two experiments with the same parameters but changing the distance between speaker and xylo board. Then the user can add
|
|
78
|
+
a "_distance_5cm" and "_distance_10cm" to the results filename and compare them later. Default to None
|
|
79
|
+
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
self.device_type = device_type
|
|
83
|
+
self.duration_input_signal = duration_input_signal
|
|
84
|
+
self.fs = CHIRP_PARAMETERS["fs"]
|
|
85
|
+
self.fmin = CHIRP_PARAMETERS["fmin"]
|
|
86
|
+
self.fmax = CHIRP_PARAMETERS["fmax"]
|
|
87
|
+
self.num_bits_Q = CHIRP_PARAMETERS["num_bits_Q"]
|
|
88
|
+
|
|
89
|
+
self.prepare_folders()
|
|
90
|
+
self.generate_chirp_file_name_tag(experiment_tag=experiment_tag)
|
|
91
|
+
# Load or generate chirp data
|
|
92
|
+
self.load_data(add_silence_period=add_silence_period)
|
|
93
|
+
# Initiaize AFESim and AFESamna objects
|
|
94
|
+
self.init_AFEsim()
|
|
95
|
+
self.init_AFESamna()
|
|
96
|
+
|
|
97
|
+
def prepare_folders(self):
|
|
98
|
+
"""
|
|
99
|
+
Prepare the folders for:
|
|
100
|
+
- input data
|
|
101
|
+
- results of the test
|
|
102
|
+
- figures
|
|
103
|
+
"""
|
|
104
|
+
folders = ["afe_test_resutls", f"chirp_test"]
|
|
105
|
+
test_results_path = debug_path
|
|
106
|
+
for name in folders:
|
|
107
|
+
test_results_path = os.path.join(test_results_path, name)
|
|
108
|
+
if not os.path.exists(test_results_path):
|
|
109
|
+
os.mkdir(test_results_path)
|
|
110
|
+
# Prepare input path
|
|
111
|
+
input_data_path = os.path.join(test_results_path, "input_data")
|
|
112
|
+
if not os.path.exists(input_data_path):
|
|
113
|
+
os.mkdir(input_data_path)
|
|
114
|
+
# Prepare results path
|
|
115
|
+
output_path = os.path.join(test_results_path, "results")
|
|
116
|
+
if not os.path.exists(output_path):
|
|
117
|
+
os.mkdir(output_path)
|
|
118
|
+
# Prepare figures path
|
|
119
|
+
fig_path = os.path.join(test_results_path, "Figures")
|
|
120
|
+
if not os.path.exists(fig_path):
|
|
121
|
+
os.mkdir(fig_path)
|
|
122
|
+
self.input_data_path = input_data_path
|
|
123
|
+
self.output_path = output_path
|
|
124
|
+
self.fig_path = fig_path
|
|
125
|
+
|
|
126
|
+
def generate_chirp_file_name_tag(self, experiment_tag):
|
|
127
|
+
"""
|
|
128
|
+
Generates the chirp filename using sampling frequency, fmin, fmax, and duration of the input signal.
|
|
129
|
+
"""
|
|
130
|
+
filename = f"_fs{int(self.fs)}_fmin{self.fmin}_fmax{self.fmax}_duration_{self.duration_input_signal}"
|
|
131
|
+
if experiment_tag:
|
|
132
|
+
filename = filename + "_" + experiment_tag
|
|
133
|
+
self.filename_tag = filename
|
|
134
|
+
|
|
135
|
+
def prepare_input_data(self):
|
|
136
|
+
"""
|
|
137
|
+
Look for an existing chirp signal with the specified parameters or generate a new one and save it for future experiments
|
|
138
|
+
"""
|
|
139
|
+
wav_filename = "chirp_signal" + self.filename_tag + ".wav"
|
|
140
|
+
input_data_filename = os.path.join(self.input_data_path, wav_filename)
|
|
141
|
+
|
|
142
|
+
if not os.path.exists(input_data_filename):
|
|
143
|
+
print("Chirp test data not found on the input path")
|
|
144
|
+
print("Generating chirp data...")
|
|
145
|
+
# generate the chirp signal
|
|
146
|
+
chirpgen = ChirpGen(
|
|
147
|
+
num_bits_Q=self.num_bits_Q,
|
|
148
|
+
fmin=self.fmin,
|
|
149
|
+
fmax=self.fmax,
|
|
150
|
+
period=self.duration_input_signal,
|
|
151
|
+
fs=self.fs,
|
|
152
|
+
)
|
|
153
|
+
_, _, data_filename = chirpgen(
|
|
154
|
+
filename=input_data_filename, duration=self.duration_input_signal
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
return data_filename
|
|
158
|
+
else:
|
|
159
|
+
self.chirp_data = input_data_filename
|
|
160
|
+
return input_data_filename
|
|
161
|
+
|
|
162
|
+
def load_data(self, add_silence_period):
|
|
163
|
+
"""
|
|
164
|
+
Load the chirp signal data and adds a silence period at the beggining if add_silence_period is True
|
|
165
|
+
"""
|
|
166
|
+
data_filename = self.prepare_input_data()
|
|
167
|
+
sample_rate, data = wavfile.read(data_filename)
|
|
168
|
+
|
|
169
|
+
if add_silence_period:
|
|
170
|
+
silence_period = np.zeros(sample_rate)
|
|
171
|
+
data = np.concatenate((silence_period.astype(np.int16), data))
|
|
172
|
+
|
|
173
|
+
self.input_data = data
|
|
174
|
+
self.sample_rate = sample_rate
|
|
175
|
+
|
|
176
|
+
def init_AFEsim(self):
|
|
177
|
+
"""
|
|
178
|
+
Import and initialize the corresponding AFESim class for the device type (XyloA2 or XyloA3)
|
|
179
|
+
"""
|
|
180
|
+
# Import the AFESim that corresponds to the device type
|
|
181
|
+
if self.device_type == "XyloA2":
|
|
182
|
+
from rockpool.devices.xylo.syns61201.afe_sim_empirical import AFESim
|
|
183
|
+
|
|
184
|
+
self.afesim = AFESim(
|
|
185
|
+
fs=self.fs,
|
|
186
|
+
raster_period=AFESIM_A2_PARAMETERS["dt"],
|
|
187
|
+
add_noise=AFESIM_A2_PARAMETERS["add_noise"],
|
|
188
|
+
add_offset=AFESIM_A2_PARAMETERS["add_offset"],
|
|
189
|
+
add_mismatch=AFESIM_A2_PARAMETERS["add_mismatch"],
|
|
190
|
+
max_spike_per_raster_period=AFESIM_A2_PARAMETERS[
|
|
191
|
+
"max_spike_per_raster_period"
|
|
192
|
+
],
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
elif self.device_type == "XyloA3":
|
|
196
|
+
from rockpool.devices.xylo.syns65302 import AFESimExternal
|
|
197
|
+
|
|
198
|
+
self.afesim = AFESimExternal.from_specification(
|
|
199
|
+
spike_gen_mode=AFESIM_A3_PARAMETERS["spike_gen_mode"],
|
|
200
|
+
dn_EPS=AFESIM_A3_PARAMETERS["dn_EPS"],
|
|
201
|
+
fixed_threshold_vec=AFESIM_A3_PARAMETERS["fixed_threshold_vec"],
|
|
202
|
+
rate_scale_factor=AFESIM_A3_PARAMETERS["rate_scale_factor"],
|
|
203
|
+
low_pass_averaging_window=AFESIM_A3_PARAMETERS[
|
|
204
|
+
"low_pass_averaging_window"
|
|
205
|
+
],
|
|
206
|
+
dt=AFESIM_A3_PARAMETERS["dt"],
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def init_AFESamna(self):
|
|
210
|
+
"""
|
|
211
|
+
Import and initialize the corresponding AFESamna class for the device type (XyloA2 or XyloA3)
|
|
212
|
+
"""
|
|
213
|
+
# Find xylo board
|
|
214
|
+
xylo_board = find_xylo(self.device_type)
|
|
215
|
+
# Import the init_AFESamna that corresponds to the device type
|
|
216
|
+
if self.device_type == "XyloA2":
|
|
217
|
+
from rockpool.devices.xylo.syns61201 import AFESamna
|
|
218
|
+
|
|
219
|
+
self.afesamna = AFESamna(
|
|
220
|
+
device=xylo_board,
|
|
221
|
+
config=AFESAMNA_A2_PARAMETERS["config"],
|
|
222
|
+
dt=AFESAMNA_A2_PARAMETERS["dt"],
|
|
223
|
+
auto_calibrate=AFESAMNA_A2_PARAMETERS["auto_calibrate"],
|
|
224
|
+
amplify_level=AFESAMNA_A2_PARAMETERS["amplify_level"],
|
|
225
|
+
hibernation_mode=AFESAMNA_A2_PARAMETERS["hibernation_mode"],
|
|
226
|
+
)
|
|
227
|
+
self.dt_AFE = AFESAMNA_A2_PARAMETERS["dt"]
|
|
228
|
+
|
|
229
|
+
elif self.device_type == "XyloA3":
|
|
230
|
+
from rockpool.devices.xylo.syns65302 import AFESamna
|
|
231
|
+
|
|
232
|
+
self.afesamna = AFESamna(
|
|
233
|
+
device=xylo_board,
|
|
234
|
+
config=AFESAMNA_A3_PARAMETERS["config"],
|
|
235
|
+
dt=AFESAMNA_A3_PARAMETERS["dt"],
|
|
236
|
+
hibernation_mode=AFESAMNA_A3_PARAMETERS["hibernation_mode"],
|
|
237
|
+
divisive_norm=AFESAMNA_A3_PARAMETERS["divisive_norm"],
|
|
238
|
+
)
|
|
239
|
+
self.dt_AFE = AFESAMNA_A3_PARAMETERS["dt"]
|
|
240
|
+
|
|
241
|
+
def evolve_afesim(self):
|
|
242
|
+
"""
|
|
243
|
+
Evolve AFESim with the chirp input data and save the results
|
|
244
|
+
"""
|
|
245
|
+
afesim_spikes, _, _ = self.afesim((self.input_data, self.sample_rate))
|
|
246
|
+
|
|
247
|
+
# Save AFESim results
|
|
248
|
+
afesim_filename = "AFESim_chirp_test_results" + self.filename_tag
|
|
249
|
+
np.save(os.path.join(self.output_path, afesim_filename), afesim_spikes)
|
|
250
|
+
print(f"AFESim chirp test with fmin:{self.fmin}, fmax:{self.fmax}, completed")
|
|
251
|
+
|
|
252
|
+
def evolve_afesamna(self):
|
|
253
|
+
"""
|
|
254
|
+
Evolve AFESamna with the chirp input data and save the results
|
|
255
|
+
"""
|
|
256
|
+
duration, wave_obj = get_wave_object(
|
|
257
|
+
audio_input_file=None, direct_data=(self.input_data, self.sample_rate)
|
|
258
|
+
)
|
|
259
|
+
num_time_steps = int(duration / self.dt_AFE)
|
|
260
|
+
play_obj = wave_obj.play()
|
|
261
|
+
afesamna_spikes, _, _ = self.afesamna.evolve(
|
|
262
|
+
np.zeros([0, num_time_steps, 0]), record=True
|
|
263
|
+
)
|
|
264
|
+
play_obj.wait_done()
|
|
265
|
+
del self.afesamna
|
|
266
|
+
|
|
267
|
+
# Save AFESamna results
|
|
268
|
+
afesamna_spikes = np.asarray(afesamna_spikes)
|
|
269
|
+
afesamna_filename = "AFESamna_chirp_test_results" + self.filename_tag
|
|
270
|
+
np.save(os.path.join(self.output_path, afesamna_filename), afesamna_spikes)
|
|
271
|
+
|
|
272
|
+
print(f"AFESamna chirp test with fmin:{self.fmin}, fmax:{self.fmax}, completed")
|
|
273
|
+
|
|
274
|
+
def evolve_afe(self, mode="AFESim"):
|
|
275
|
+
"""
|
|
276
|
+
Call evolve for the specified AFE mode (AFESim or AFESamna)
|
|
277
|
+
"""
|
|
278
|
+
if mode == "AFESim":
|
|
279
|
+
self.evolve_afesim()
|
|
280
|
+
elif mode == "AFESamna":
|
|
281
|
+
self.evolve_afesamna()
|
|
282
|
+
else:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
"Unrecognized afe mode, only supporting AFESamna or AFESim"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def plot_comparison(
|
|
288
|
+
self, save_fig=False, min_spikes=0, max_spikes=14, normalize=False
|
|
289
|
+
):
|
|
290
|
+
"""
|
|
291
|
+
Load and plot the chirp response of the AFESim and AFESamna.
|
|
292
|
+
This plots aims to compare the outputs of the AFE in simulation vs the AFE in the chip.
|
|
293
|
+
Ideally we want the two plots to have similar activity, otherwise the user can run the AFESamna experiment again and change,
|
|
294
|
+
for example, the background noise, or the distance between the xylo board and the speaker, or what they consider useful to figure out the best
|
|
295
|
+
setting for their data and application.
|
|
296
|
+
"""
|
|
297
|
+
afesim_filename = "AFESim_chirp_test_results" + self.filename_tag + ".npy"
|
|
298
|
+
afesamna_filename = "AFESamna_chirp_test_results" + self.filename_tag + ".npy"
|
|
299
|
+
afe_sim_sample = np.load(os.path.join(self.output_path, afesim_filename))
|
|
300
|
+
afe_samna_sample = np.load(os.path.join(self.output_path, afesamna_filename))
|
|
301
|
+
|
|
302
|
+
ch_sum_afe_sim = np.sum(afe_sim_sample, axis=0)
|
|
303
|
+
ch_sum_afe_samna = np.sum(afe_samna_sample, axis=0)
|
|
304
|
+
|
|
305
|
+
# -------------------------Figure settings -------------------------------- #
|
|
306
|
+
ytick_labels = np.arange(16)
|
|
307
|
+
figure_size = (15, 5)
|
|
308
|
+
# figure colors
|
|
309
|
+
fig_colors = ["#0066cc", "#730099"]
|
|
310
|
+
# font sizes
|
|
311
|
+
fig_label_size = 12
|
|
312
|
+
# columns and rows
|
|
313
|
+
fig_columns = 3
|
|
314
|
+
fig_rows = 1
|
|
315
|
+
|
|
316
|
+
# ---------------------------------Figure --------------------------------- #
|
|
317
|
+
figure, axs = plt.subplots(
|
|
318
|
+
fig_rows, fig_columns, figsize=figure_size, facecolor="white"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
# set the spacing between subplots
|
|
322
|
+
figure.subplots_adjust(left=0.1, wspace=0.2, hspace=0.4)
|
|
323
|
+
|
|
324
|
+
# ----------------------------------- #
|
|
325
|
+
# AFEsim
|
|
326
|
+
# ----------------------------------- #
|
|
327
|
+
image = axs[0].imshow(
|
|
328
|
+
afe_sim_sample.T, vmin=min_spikes, vmax=max_spikes, aspect="auto"
|
|
329
|
+
)
|
|
330
|
+
axs[0].figure.colorbar(image)
|
|
331
|
+
axs[0].set_title("AFESim", fontsize=fig_label_size)
|
|
332
|
+
|
|
333
|
+
# ----------------------------------- #
|
|
334
|
+
# AFESamna
|
|
335
|
+
# ----------------------------------- #
|
|
336
|
+
# if afe_rec_tool == "rockpool" :
|
|
337
|
+
image = axs[1].imshow(
|
|
338
|
+
afe_samna_sample.T, vmin=min_spikes, vmax=max_spikes, aspect="auto"
|
|
339
|
+
)
|
|
340
|
+
axs[1].figure.colorbar(image)
|
|
341
|
+
axs[1].set_title("AFESamna", fontsize=fig_label_size)
|
|
342
|
+
|
|
343
|
+
# ----------------------------------- #
|
|
344
|
+
# Activity comparison
|
|
345
|
+
# ----------------------------------- #
|
|
346
|
+
if normalize:
|
|
347
|
+
axs[2].plot(
|
|
348
|
+
ch_sum_afe_sim[::-1] / np.max(ch_sum_afe_sim),
|
|
349
|
+
ytick_labels,
|
|
350
|
+
label="AFESim",
|
|
351
|
+
color=fig_colors[0],
|
|
352
|
+
)
|
|
353
|
+
axs[2].plot(
|
|
354
|
+
ch_sum_afe_samna[::-1] / np.max(ch_sum_afe_samna),
|
|
355
|
+
ytick_labels,
|
|
356
|
+
label=f"AFESamna ({self.device_type})",
|
|
357
|
+
color=fig_colors[1],
|
|
358
|
+
)
|
|
359
|
+
else:
|
|
360
|
+
axs[2].plot(
|
|
361
|
+
ch_sum_afe_sim[::-1], ytick_labels, label="AFESim", color=fig_colors[0]
|
|
362
|
+
)
|
|
363
|
+
axs[2].plot(
|
|
364
|
+
ch_sum_afe_samna[::-1],
|
|
365
|
+
ytick_labels,
|
|
366
|
+
label="AFESamna",
|
|
367
|
+
color=fig_colors[1],
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
axs[2].legend(frameon=True, facecolor="white", framealpha=1)
|
|
371
|
+
axs[2].set_title(" Channel activity comparison", fontsize=fig_label_size)
|
|
372
|
+
axs[2].set_xlabel("Spike sum", fontsize=fig_label_size)
|
|
373
|
+
axs[2].spines[["right", "top"]].set_visible(False)
|
|
374
|
+
axs[2].set_yticks(range(16))
|
|
375
|
+
axs[2].set_yticklabels(ytick_labels[::-1], fontsize=fig_label_size - 2)
|
|
376
|
+
|
|
377
|
+
# ----------------------------------- #
|
|
378
|
+
# Tick params
|
|
379
|
+
# ----------------------------------- #
|
|
380
|
+
for j in range(fig_columns):
|
|
381
|
+
axs[j].set_ylabel("AFE channels", fontsize=fig_label_size)
|
|
382
|
+
axs[j].grid(axis="y", color="k", alpha=0.5)
|
|
383
|
+
if j != 2:
|
|
384
|
+
axs[j].set_yticks(range(16))
|
|
385
|
+
axs[j].set_yticklabels(ytick_labels, fontsize=fig_label_size - 2)
|
|
386
|
+
axs[j].set_xlabel("Time steps", fontsize=fig_label_size)
|
|
387
|
+
|
|
388
|
+
fig_name = "chirp" + self.filename_tag + f"_{self.device_type}"
|
|
389
|
+
plt.suptitle(fig_name, fontsize=fig_label_size)
|
|
390
|
+
if save_fig:
|
|
391
|
+
plt.savefig(os.path.join(self.fig_path, fig_name))
|
|
392
|
+
|
|
393
|
+
return figure
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.io import wavfile
|
|
3
|
+
from typing import Union
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ChirpGen:
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
num_bits_Q: int = 8,
|
|
12
|
+
fmin: float = 100,
|
|
13
|
+
fmax: float = 8000,
|
|
14
|
+
period: float = 1,
|
|
15
|
+
fs: float = 16000,
|
|
16
|
+
):
|
|
17
|
+
"""this is a simple class for producing audio chirp signals.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
num_bits_Q(int, optional): number of bits used for quantizing the audio signal. Defaults to 8 bits.
|
|
21
|
+
fmin (float, optional): minimim frequency. Defaults to 100.
|
|
22
|
+
fmax (float, optional): maximum frequency. Defaults to 8000.
|
|
23
|
+
period (float, optional): period of the chirp signal. Defaults to 1.
|
|
24
|
+
fs (float, optional): sampling rate of the audio chirp signal. Defaults to 16000 Hz.
|
|
25
|
+
"""
|
|
26
|
+
self.fmin = fmin
|
|
27
|
+
self.fmax = fmax
|
|
28
|
+
self.period = period
|
|
29
|
+
if num_bits_Q not in [8, 16]:
|
|
30
|
+
raise ValueError("only 8 or 16 bits per sample are supported!")
|
|
31
|
+
self.num_bits_Q = num_bits_Q
|
|
32
|
+
self.fs = fs
|
|
33
|
+
|
|
34
|
+
def evolve(
|
|
35
|
+
self,
|
|
36
|
+
duration: float = 1,
|
|
37
|
+
relative_amplitude: float = 1.0,
|
|
38
|
+
filename: str = ".chirp.wav",
|
|
39
|
+
) -> Union[np.ndarray, str]:
|
|
40
|
+
"""this function produces a chirp of given duration.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
duration (float, optional): duration of the audio signal. Defaults to 1.
|
|
44
|
+
relative_amplitude (float, optional): relative amplitude of the the audio signal compared with the full amplitude. Defaults to 1.0 for full amplitude.
|
|
45
|
+
filename (str, optional): filename used for storing the chirp signal.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Union[np.ndarray, str]: an array containing the quantzied audio and the name of the audio file.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
t_vec = np.arange(0, duration, step=1 / self.fs)
|
|
52
|
+
t_vec_periodic = np.mod(t_vec, self.period)
|
|
53
|
+
inst_freq = self.fmin + (self.fmax - self.fmin) * t_vec_periodic / self.period
|
|
54
|
+
|
|
55
|
+
inst_phase = 2 * np.pi * np.cumsum(inst_freq) * 1 / self.fs
|
|
56
|
+
random_phase = 2 * np.pi * np.random.rand(1)[0]
|
|
57
|
+
chirp_sig = np.sin(inst_phase + random_phase)
|
|
58
|
+
|
|
59
|
+
# quantize the chirp signal
|
|
60
|
+
EPS = 0.0001
|
|
61
|
+
chirp_sig = (
|
|
62
|
+
relative_amplitude * chirp_sig / (np.max(np.abs(chirp_sig)) * (1 + EPS))
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
if self.num_bits_Q == 8:
|
|
66
|
+
chirp_sig_q = (chirp_sig * 2 ** (self.num_bits_Q - 1)).astype(np.int8)
|
|
67
|
+
elif self.num_bits_Q == 16:
|
|
68
|
+
chirp_sig_q = (chirp_sig * 2 ** (self.num_bits_Q - 1)).astype(np.int16)
|
|
69
|
+
else:
|
|
70
|
+
raise ValueError("only 1 or 2 bytes per sample are supported!")
|
|
71
|
+
|
|
72
|
+
wavfile.write(
|
|
73
|
+
filename=filename,
|
|
74
|
+
rate=int(self.fs),
|
|
75
|
+
data=chirp_sig_q,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
return chirp_sig_q, t_vec, filename
|
|
79
|
+
|
|
80
|
+
def __call__(self, *args, **kwargs) -> Union[np.ndarray, str]:
|
|
81
|
+
"""This is the same as evolve function.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Union[np.ndarray, str]: output chirp signal and the corresponding audio file.
|
|
85
|
+
"""
|
|
86
|
+
return self.evolve(*args, **kwargs)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from xylo_deployment import XyloMonitorExperiment
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
This scripts is a template that you can use to evaluate your trained model in **real-time mode** using `XyloMonitor`.
|
|
7
|
+
See first /docs/tutorial_rare_sound/XyloSim_test.ipynb and /docs/tutorial_rare_sound/XyloSamna_test.ipynb to verify
|
|
8
|
+
the SNN core is working as expected before testing the whole pipeline using XyloMonitor.
|
|
9
|
+
|
|
10
|
+
Unlike XyloSim and XyloSamna, XyloMonitor does not receive pre-generated AFESim spikes.
|
|
11
|
+
Instead, audio is played through the computer speakers, captured by the Xylo development kit microphone,
|
|
12
|
+
and processed by the board’s audio front end before reaching the Xylo SNN core.
|
|
13
|
+
|
|
14
|
+
To have a step-by-step use of XyloMonitorExperiment, please check the tutorial:
|
|
15
|
+
/docs/tutorial_rare_sound/XyloMonitor_test.ipynb
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
# ------------------------------------------- TEST PARAMS ------------------------------------------- #
|
|
19
|
+
device_type = "XyloA3"
|
|
20
|
+
record_power = False
|
|
21
|
+
divisive_norm = True
|
|
22
|
+
output_mode = "Vmem"
|
|
23
|
+
# Set new_thrs only when you know why the thrs need to be modified, for example by running the vmem_analysis_xyloMonitor.ipynb
|
|
24
|
+
# or to explore possible changes on the original thrs
|
|
25
|
+
new_thrs = [359, 150, 300, 650]
|
|
26
|
+
|
|
27
|
+
# ------------------------------------------- MODEL PATHS ------------------------------------------- #
|
|
28
|
+
model_path = "path/to/your/trained/model/folder/"
|
|
29
|
+
trained_model = "checkpoints/your_best_checkpoint.pt"
|
|
30
|
+
partition = "val"
|
|
31
|
+
# -------------------------------------------- RUN TEST --------------------------------------------- #
|
|
32
|
+
xylo_experiment = XyloMonitorExperiment(
|
|
33
|
+
device_type=device_type,
|
|
34
|
+
model_path=model_path,
|
|
35
|
+
checkpoint_name=trained_model,
|
|
36
|
+
partition=partition,
|
|
37
|
+
output_mode=output_mode,
|
|
38
|
+
thrs=None,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
xylo_experiment.load_input_data()
|
|
42
|
+
# We now set up XyloMonitor. It is important to not move the board, and avoid making noise during the set-up
|
|
43
|
+
# If using XyloA2, the configuration will last a bit longer, since we need to force a pause of 40 seconds.
|
|
44
|
+
# During this time, xylo board is capturing backgorund noise.
|
|
45
|
+
xylo_experiment.set_up(divisive_norm=divisive_norm)
|
|
46
|
+
xylo_experiment.run(record_power=record_power, verbose=True)
|
|
47
|
+
|
|
48
|
+
# ------------------------------------------ TEST ANALYSIS ------------------------------------------- #
|
|
49
|
+
class_names = ["classA", "classB", "classC", "classD"]
|
|
50
|
+
xylo_experiment.load_results()
|
|
51
|
+
xylo_experiment.calculate_metrics(thr_out=new_thrs)
|
|
52
|
+
figure = xylo_experiment.plot_metric_results(class_names=class_names, save_fig=False)
|
|
53
|
+
|
|
54
|
+
plt.show()
|
|
55
|
+
print(xylo_experiment.predictions)
|