foreshore 0.0.1__tar.gz
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-0.0.1/PKG-INFO +21 -0
- foreshore-0.0.1/README.md +92 -0
- foreshore-0.0.1/foreshore/__init__.py +6 -0
- foreshore-0.0.1/foreshore/data_preparation/prepare_evaluation_data.py +99 -0
- foreshore-0.0.1/foreshore/debugging/AFESamna_AFESim_chirp_test.py +42 -0
- foreshore-0.0.1/foreshore/debugging/afe_chirp_experiment.py +393 -0
- foreshore-0.0.1/foreshore/debugging/chirp_gen.py +86 -0
- foreshore-0.0.1/foreshore/deployment/xyloMonitor_test.py +55 -0
- foreshore-0.0.1/foreshore/deployment/xyloSamna_test.py +61 -0
- foreshore-0.0.1/foreshore/deployment/xyloSim_test.py +58 -0
- foreshore-0.0.1/foreshore/deployment/xylo_deployment.py +559 -0
- foreshore-0.0.1/foreshore/deployment/xylo_experiment.py +586 -0
- foreshore-0.0.1/foreshore/docs/templates/dataset/your_dataset.py +256 -0
- foreshore-0.0.1/foreshore/docs/templates/train_snn.py +161 -0
- foreshore-0.0.1/foreshore/docs/tutorial_rare_sound/data_module_rare_sound.py +138 -0
- foreshore-0.0.1/foreshore/docs/tutorial_rare_sound/train_snn_rare_sound.py +119 -0
- foreshore-0.0.1/foreshore/tests/test_afesim.py +71 -0
- foreshore-0.0.1/foreshore/tests/test_basic_transforms.py +321 -0
- foreshore-0.0.1/foreshore/tests/test_binary_predicitons.py +258 -0
- foreshore-0.0.1/foreshore/tests/test_loss.py +603 -0
- foreshore-0.0.1/foreshore/tests/test_multiclass_predictions.py +234 -0
- foreshore-0.0.1/foreshore/training_testing/data_module.py +373 -0
- foreshore-0.0.1/foreshore/training_testing/loss.py +739 -0
- foreshore-0.0.1/foreshore/training_testing/metrics/binary_metrics.py +68 -0
- foreshore-0.0.1/foreshore/training_testing/metrics/multiclass_metrics.py +181 -0
- foreshore-0.0.1/foreshore/training_testing/metrics/non_scalar_metrics.py +376 -0
- foreshore-0.0.1/foreshore/training_testing/metrics/stat_scores.py +57 -0
- foreshore-0.0.1/foreshore/training_testing/predictions/__init__.py +2 -0
- foreshore-0.0.1/foreshore/training_testing/predictions/binary.py +291 -0
- foreshore-0.0.1/foreshore/training_testing/predictions/multiclass.py +145 -0
- foreshore-0.0.1/foreshore/training_testing/training_module.py +653 -0
- foreshore-0.0.1/foreshore/training_testing/transforms/basic_transforms.py +129 -0
- foreshore-0.0.1/foreshore/training_testing/transforms/to_spike_transform.py +127 -0
- foreshore-0.0.1/foreshore/training_testing/weights_checkpoint.py +32 -0
- foreshore-0.0.1/foreshore/utils/audio_test_utils.py +88 -0
- foreshore-0.0.1/foreshore/utils/cache_utils.py +44 -0
- foreshore-0.0.1/foreshore/utils/model_validation_utils.py +156 -0
- foreshore-0.0.1/foreshore/utils/xylohdk_utils.py +63 -0
- foreshore-0.0.1/foreshore.egg-info/PKG-INFO +21 -0
- foreshore-0.0.1/foreshore.egg-info/SOURCES.txt +43 -0
- foreshore-0.0.1/foreshore.egg-info/dependency_links.txt +1 -0
- foreshore-0.0.1/foreshore.egg-info/requires.txt +7 -0
- foreshore-0.0.1/foreshore.egg-info/top_level.txt +1 -0
- foreshore-0.0.1/setup.cfg +4 -0
- foreshore-0.0.1/setup.py +20 -0
foreshore-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: foreshore
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Python package for training a network with Rockpool.
|
|
5
|
+
Home-page: https://gitlab.com/synsense/thunder-experiments/rockpool_training_pipeline
|
|
6
|
+
Author: Karla Burelo and Vanessa Leite
|
|
7
|
+
Author-email: support@synsense.ai
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Requires-Dist: rockpool
|
|
10
|
+
Requires-Dist: torch
|
|
11
|
+
Requires-Dist: pytorch_lightning>=2.6.6
|
|
12
|
+
Requires-Dist: tonic>=1.7.0
|
|
13
|
+
Requires-Dist: jsonargparse>=4.52.0
|
|
14
|
+
Requires-Dist: bitstruct>=8.23.0
|
|
15
|
+
Requires-Dist: mlflow>=3.17.1
|
|
16
|
+
Dynamic: author
|
|
17
|
+
Dynamic: author-email
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: license
|
|
20
|
+
Dynamic: requires-dist
|
|
21
|
+
Dynamic: summary
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Rockpool training pipeline
|
|
2
|
+
This repository provides a training pipeline example for Rockpool.
|
|
3
|
+
The main branch contains templates for dataset, datamodule as well as general deployment and debugging example code.
|
|
4
|
+
We provide three branches with example code.
|
|
5
|
+
|
|
6
|
+
- rare-sound
|
|
7
|
+
- neurobench
|
|
8
|
+
- baby-cry
|
|
9
|
+
|
|
10
|
+
The rare-sound and neurobench branches are fully worked examples that the user should be able to reproduce after downloading the corresponding data.
|
|
11
|
+
Additionally, we provide a baby-cry branch. While the data for this case is not publicly available, these are other good examples of how the Dataset and DataModule change for each dataset.
|
|
12
|
+
Moreover, since baby-cry is a binary classification problem, we use different metrics that might be useful for the user to explore.
|
|
13
|
+
|
|
14
|
+
We mainly focus on the rare-sound branch as we have also provided a trained checkpoint and figures of the results at the deployment stage.
|
|
15
|
+
|
|
16
|
+
## Python version and repository dependencies
|
|
17
|
+
Python 3.10.8
|
|
18
|
+
Create a new environment using the `requirements.txt ` file
|
|
19
|
+
|
|
20
|
+
## Dataset
|
|
21
|
+
The first step is to work on the dataset. We provide a general template so the user familiarizes with how we prepare a dataset for our training pipeline.
|
|
22
|
+
The DataModule handles the load and preparation of the data together with the Dataset. Once again, in the main branch the Datamodule is a template that should be modified according to the dataset and use-case. However, we expect most of the changes to be done on the Dataset, while the structure of the DataModule will stay very similar to that of the template.
|
|
23
|
+
See rare-sound, neurobench and baby-cry examples of Dataset and Datamodule for more concrete examples. Keep in mind, however, that the dataset might require extra functions depending on the formatting of the original dataset and will therefore vary across datasets and applications.
|
|
24
|
+
|
|
25
|
+
## TrainingRockpoolModule and Datamodule
|
|
26
|
+
We provide a TrainingRockpoolModule and a ThresholdSweep module. The TrainingRockpoolModule is the basis for handling the training steps.
|
|
27
|
+
However we have extended this module to have a threshold sweep.
|
|
28
|
+
In this child class, the training, validation and test steps include an extra computation after passing the data through the model.
|
|
29
|
+
While we compute our model's loss using the vmem, we evaluate the model in spike mode. This decision allows us to have a better control on the mapping of the model in the xylo board.
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
## Training a model
|
|
33
|
+
In order to train a model, the user must provide a config yaml file specifying the parameters for training.
|
|
34
|
+
We have included templates for this yaml file in the `config` folder. Additionally we provide templates with examples for configurations used for XyloA2, XyloA3, as well as for binary and multiclass classification.
|
|
35
|
+
|
|
36
|
+
The information in this yaml file contains, but it is not limited to:
|
|
37
|
+
- Parameters of the dataset
|
|
38
|
+
- SNN model and init parameters
|
|
39
|
+
- Prediction method
|
|
40
|
+
- Metrics
|
|
41
|
+
|
|
42
|
+
Once the user has updated their Dataset as well as their DataModule, they can run a training experiment:
|
|
43
|
+
- open a terminal
|
|
44
|
+
- go to the parent folder of this repository
|
|
45
|
+
- run `python training_testing/train_snn.py fit --config config/train.yaml`
|
|
46
|
+
|
|
47
|
+
Where `train.yaml` should include the user's specifications for the training.
|
|
48
|
+
|
|
49
|
+
We recommend to save the results under `./experiments/trained_checkpoints/`
|
|
50
|
+
In the example `train.yaml` file, this path is already set as an example
|
|
51
|
+
(See logger under the trainer section)
|
|
52
|
+
|
|
53
|
+
## Model validation and deployment using XyloSim, XyloSamna, and XyloMonitor:
|
|
54
|
+
After training a model, we recommend to move to the deployment stage.
|
|
55
|
+
In the rare-sound branch, we provide a trained model as well as the validation dataset to validate the model.
|
|
56
|
+
The trained model is under `./experiments/trained_checkpoints/{experiment_id}/`
|
|
57
|
+
In this folder the user can find the `trained_model_dict.json` containing all the trained parameters (weights, time constants, etc) and the `config.yaml` which contains all the information used to train this model. For example, in this file the user can find the initialization of the SynNet model.
|
|
58
|
+
|
|
59
|
+
### Model deployment in XyloSim and XyloSamna
|
|
60
|
+
The input to `XyloSim` and `XyloSamna` is a num_AFE_channel**x**time_steps.
|
|
61
|
+
In XyloAudio2 and XyloAudio3 we have 16 filterbanks, or channels.
|
|
62
|
+
For the rare-sound application, we used audios of 3 seconds.
|
|
63
|
+
Using a `dt` of ~0.01 for AFESim results in a 16**x**300 array as input for both `XyloSim` and `XyloSamna`.
|
|
64
|
+
|
|
65
|
+
Using any of these modalities, means that only the SNN core of the board will be 'used'. While for `XyloSim`
|
|
66
|
+
this is a simulation of the SNN, `XyloSamna` actually maps the network and runs the SNN on the chip, hence, a xylo board must be connected to the PC.
|
|
67
|
+
In these modes, we are not using the AFE front-end, which takes an audio and filters it using 16 bandpass filters.
|
|
68
|
+
|
|
69
|
+
An example code on how to deploy the model in XyloSim and XyloSamna can be found under `./deployment/xyloSim.py` and `./deployment/xyloSamna.py` respectively.
|
|
70
|
+
|
|
71
|
+
Note that in the rare-sound branch we have ran the experiments and also plotted and save the metrics. See the documentation of `XyloSimExperiment` and `XyloSamnaExperiment` to better understand the use of `XyloExperiment`
|
|
72
|
+
|
|
73
|
+
### Model deployment in XyloMonitor
|
|
74
|
+
For this test, the user must connect a xylo board and a speaker to the PC.
|
|
75
|
+
`XyloMonitorExperiment` is very similar to the experiments using `XyloSim` and `XyloSamna`.
|
|
76
|
+
However, the input is different: in this mode, we are using the AFE front-end.
|
|
77
|
+
Thus, the input of this test is a real audio. `XyloMonitorExperiment` finds the json file inside the data file saved during the training process (data.txt)
|
|
78
|
+
This json file contains a dictionary with the original audio paths used for training, validation and test. This is important since we want to make sure to use the correct audios for evaluation.
|
|
79
|
+
The user can refer to the `XyloMonitorExperiment` documentation and use `xyloMonitor_test.py` to run their own XyloMonitor experiments.
|
|
80
|
+
|
|
81
|
+
## Debugging tools
|
|
82
|
+
'My results in XyloSim and XyloSamna are great but my model performance decays when using XyloMonitor, what do I do?'
|
|
83
|
+
This is a very common issue when users trained their model and try to deploy it to Xylo. We hope the steps above as well as the example scripts already help the user to train a good model.
|
|
84
|
+
However, it can happen that the accuracy drops when mapping to XyloMonitor. Remember that when we use XyloSim and XyloSamna, we are using the SNN core only. We feed pre-recorded samples from AFEsim, a simulator of the Analog-Front-End (AFE) of the xylo boards.
|
|
85
|
+
When we use XyloMonitor, the data is fed through the microphone, and the real AFE will process the audio.
|
|
86
|
+
This means that anything that affects the audio can affect our network performance. For example, the background noise, the sound quality of the speaker, the distance/direction between the speaker and the xylo board, among other possible factors.
|
|
87
|
+
In order to minimize this environment-condition mismatch, we provide a chirp test that should help the user see differences between the AFE in simulation and the real one in the chip.
|
|
88
|
+
The user can simply run the `AFESamna_AFESim_chirp_test.py`. Note that a xylo board must be connected to run this experiment.
|
|
89
|
+
See also the `AFE_chirp_experiment` documentation to have a better understanding of how this experiment works.
|
|
90
|
+
|
|
91
|
+
We also provide a vmem analysis of the results from XyloMonitor experiments that should also help the user find a better threshold for their trained model.
|
|
92
|
+
See `vmem_analysis_xyloMonitor.py` for more details
|
|
@@ -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
|