frenztoolkit 0.1.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.
Potentially problematic release.
This version of frenztoolkit might be problematic. Click here for more details.
- frenztoolkit/RawSignal/BLEBleak.cpython-312-darwin.so +0 -0
- frenztoolkit/RawSignal/Experiment.cpython-312-darwin.so +0 -0
- frenztoolkit/RawSignal/OfflineReplay.cpython-312-darwin.so +0 -0
- frenztoolkit/RawSignal/__init__.py +311 -0
- frenztoolkit/STATE/__init__.py +306 -0
- frenztoolkit/STATE/algorithms/blink_detection.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/emg_event_detection.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/focus.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/gaze_3.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/gaze_detection.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/gesture.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/gesture_2.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/model_files/__init__.py +6 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/Sleep_Staging_Models.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/__init__.py +6 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/asr_ref_data_P100025005_600_680s.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/pretrain_means_v01.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/pretrain_stds_v01.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/auto_sleep_scoring/release_model_3.6.0_PoAs.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/eye_stage/__init__.py +6 -0
- frenztoolkit/STATE/algorithms/model_files/eye_stage/eye_model_v0.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/eye_stage/eye_model_v0.h5 +0 -0
- frenztoolkit/STATE/algorithms/model_files/eyes_condition.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/eyes_condition.h5 +0 -0
- frenztoolkit/STATE/algorithms/model_files/focus/__init__.py +6 -0
- frenztoolkit/STATE/algorithms/model_files/focus/focus v1.4/lstm_model_v0.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/focus/focus v1.4/lstm_model_v0.h5 +0 -0
- frenztoolkit/STATE/algorithms/model_files/focus/release_0.4/asr_ref_data_P100025005_600_680s.encrypted +1 -0
- frenztoolkit/STATE/algorithms/model_files/focus/release_0.4/beta_percentile_vals.encrypted +1 -0
- frenztoolkit/STATE/algorithms/poas.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/posture.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/posture_2.cpython-312-darwin.so +0 -0
- frenztoolkit/STATE/algorithms/respiratory_rate.cpython-312-darwin.so +0 -0
- frenztoolkit/__init__.py +11 -0
- frenztoolkit/reader.cpython-312-darwin.so +0 -0
- frenztoolkit/scanner.cpython-312-darwin.so +0 -0
- frenztoolkit/streamer.cpython-312-darwin.so +0 -0
- frenztoolkit/streamer_old.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/LiveFilter.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/WindowFiltering.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/WindowFiltering_focus.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/asr.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/asr_reduced.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/backend_connector.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/channel_selection.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/edf_conversion.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/feature_extraction.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/feature_extraction_poas.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/gaze_sqc_model/GazeSQCModelTFLite.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/gaze_sqc_model/gaze_sqc_feature_extraction.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/gaze_sqc_model/gaze_sqc_model.h5 +0 -0
- frenztoolkit/utils/model_encryption.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/model_resources.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/params.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/post_processing/score_smoothing/score_smoothing.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/python_utils.cpython-312-darwin.so +0 -0
- frenztoolkit/utils/signal_processing.cpython-312-darwin.so +0 -0
- frenztoolkit/utilsthon_utils.cpython-312-darwin.so +0 -0
- frenztoolkit-0.1.0.dist-info/METADATA +173 -0
- frenztoolkit-0.1.0.dist-info/RECORD +63 -0
- frenztoolkit-0.1.0.dist-info/WHEEL +5 -0
- frenztoolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- frenztoolkit-0.1.0.dist-info/top_level.txt +1 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"Create the streaming data flow"
|
|
2
|
+
import sys
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
import copy
|
|
6
|
+
import threading
|
|
7
|
+
import asyncio
|
|
8
|
+
|
|
9
|
+
from .BLEBleak import BLE_device_instance, get_ble_device_address
|
|
10
|
+
from .Experiment import Experiment
|
|
11
|
+
# from .OfflineReplay import OfflineData
|
|
12
|
+
|
|
13
|
+
from ..utils.params import *
|
|
14
|
+
from ..utils.WindowFiltering_focus import *
|
|
15
|
+
|
|
16
|
+
class StreamingFLow:
|
|
17
|
+
"Connect to a device and streaming data"
|
|
18
|
+
def __init__(self, device_id=None, cache_folder='./cache', source=None, data_folder=None, s3_prefix=None, is_split_brain_signal=True):
|
|
19
|
+
'''initializinng parameters, get device_id
|
|
20
|
+
Args:
|
|
21
|
+
device_id: str: if the streaming is in online mode (from a device)
|
|
22
|
+
cache_folder: str: cache foldeer
|
|
23
|
+
data_folder: str: pre-recorded data folder in offline mode, only consider if device_id==None
|
|
24
|
+
source: str: "PC" or "S3": source of the pre-recorded data, only in offline mode
|
|
25
|
+
'''
|
|
26
|
+
self.device_id = device_id
|
|
27
|
+
self.cache_folder = cache_folder
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if self.device_id is not None:
|
|
31
|
+
# If in online mode: create a BLE instantce
|
|
32
|
+
self.Ble_stack = BLE_device_instance()
|
|
33
|
+
# print("self.Ble_stack = BLE_device_instance()") # DEBUG
|
|
34
|
+
else:
|
|
35
|
+
# If in offline mode
|
|
36
|
+
self.data_folder = data_folder
|
|
37
|
+
self.source = source
|
|
38
|
+
self.s3_prefix = s3_prefix
|
|
39
|
+
|
|
40
|
+
# All data is stored in:
|
|
41
|
+
# self.experiment.eeg
|
|
42
|
+
# self.experiment.imu
|
|
43
|
+
# self.experiment.ppg
|
|
44
|
+
|
|
45
|
+
# Thêm tính toán các giá trị EEG/EOG/EMG
|
|
46
|
+
if is_split_brain_signal:
|
|
47
|
+
self.GetRawBrainComponents = GetRawBrainComponents()
|
|
48
|
+
else:
|
|
49
|
+
self.GetRawBrainComponents = None
|
|
50
|
+
|
|
51
|
+
def start_streaming(self):
|
|
52
|
+
"Start the data streaming threads (device -> BLE and BLE -> Experiment)"
|
|
53
|
+
if self.device_id is not None:
|
|
54
|
+
# Online mode processing
|
|
55
|
+
# Set up BLE, connect to the device and start streaming data from the device to the BLE
|
|
56
|
+
self.connect2device(self.device_id)
|
|
57
|
+
|
|
58
|
+
#Set up the experiment
|
|
59
|
+
self._createExperiment(self.device_id, cache_folder=self.cache_folder)
|
|
60
|
+
|
|
61
|
+
# Start streaming data from the BLE (binary) to the Experiment (numpy)
|
|
62
|
+
self.start_streaming_data_ble_to_databucket()
|
|
63
|
+
|
|
64
|
+
else:
|
|
65
|
+
# Offline mode processing
|
|
66
|
+
# Tạo luồng data
|
|
67
|
+
self.OfflineDataProcessor = OfflineData(data_folder=self.data_folder, source=self.source, s3_prefix=self.s3_prefix)
|
|
68
|
+
# print("self.OfflineDataProcessor.eeg_full_data shape: ", self.OfflineDataProcessor.eeg_full_data.shape)
|
|
69
|
+
|
|
70
|
+
#Set up the experiment
|
|
71
|
+
self._createExperiment(self.device_id, cache_folder=self.cache_folder)
|
|
72
|
+
|
|
73
|
+
# Tạo luồng streaming data offline
|
|
74
|
+
self.start_stream_offline_data()
|
|
75
|
+
|
|
76
|
+
# Khởi tạo data (khi chưa có update)
|
|
77
|
+
self.eeg = self.experiment.eeg_data[:self.experiment.eeg_data_size, :]
|
|
78
|
+
self.imu = self.experiment.imu_data[:self.experiment.imu_data_size, :]
|
|
79
|
+
self.ppg = self.experiment.ppg_data[:self.experiment.ppg_data_size, :]
|
|
80
|
+
|
|
81
|
+
def get_last_window(self, window_in_seconds=1):
|
|
82
|
+
"Lấy data của một window(theo giây) gần nhất"
|
|
83
|
+
data = {
|
|
84
|
+
"EEG": self.eeg[-int(eeg_sampling_rate*window_in_seconds):, :],
|
|
85
|
+
"IMU": self.imu[-int(imu_sampling_rate*window_in_seconds):, :],
|
|
86
|
+
"PPG": self.ppg[-int(ppg_sampling_rate*window_in_seconds):, :],
|
|
87
|
+
}
|
|
88
|
+
return data
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _ble_initializer(self, address):
|
|
92
|
+
''' Initilize BLE connection
|
|
93
|
+
:address: ble address of the device'''
|
|
94
|
+
asyncio.run(self.Ble_stack.main(address))
|
|
95
|
+
|
|
96
|
+
def connect2device(self, device_id):
|
|
97
|
+
''' Set up BLE streaming and recording
|
|
98
|
+
Start a threath to run streaming from device to BLE queue (BLE.raw_eeg_data)
|
|
99
|
+
'''
|
|
100
|
+
ble_address = asyncio.run(get_ble_device_address(device_id))
|
|
101
|
+
if ble_address is None:
|
|
102
|
+
sys.exit('Unable to find device {}'.format(device_id))
|
|
103
|
+
|
|
104
|
+
# Start the streaming data from the device to the BLE
|
|
105
|
+
print ("Connecting ....")
|
|
106
|
+
self.init_thread = threading.Thread(name='ble_initializer', target=self._ble_initializer, args=(ble_address,))
|
|
107
|
+
self.init_thread.start()
|
|
108
|
+
|
|
109
|
+
def _createExperiment(self, device_id, cache_folder=None):
|
|
110
|
+
'''Create Experiment object which processed and stored data (RAM and disk)'''
|
|
111
|
+
experiment_id = str(time.time())
|
|
112
|
+
if cache_folder is None:
|
|
113
|
+
# Create cache folder if none
|
|
114
|
+
experiment_id_data_path = os.path.join(cache_folder, experiment_id)
|
|
115
|
+
else:
|
|
116
|
+
experiment_id_data_path = os.path.join(cache_folder, experiment_id)
|
|
117
|
+
self.experiment_id_data_path = experiment_id_data_path
|
|
118
|
+
# create experiment object
|
|
119
|
+
self.experiment = Experiment(max_streaming_time_s=max_streaming_time_s, params=all_params,
|
|
120
|
+
device_id=device_id, experiment_id=experiment_id_data_path)
|
|
121
|
+
|
|
122
|
+
def start_streaming_data_ble_to_databucket(self):
|
|
123
|
+
'''start data streaming thread'''
|
|
124
|
+
print ("Starting streaming ....")
|
|
125
|
+
try:
|
|
126
|
+
self.stream_thread = threading.Thread(name='ble_stream', target=self._streaming_data_ble_to_databucket)
|
|
127
|
+
self.stream_thread.start()
|
|
128
|
+
except:
|
|
129
|
+
return False
|
|
130
|
+
return True
|
|
131
|
+
|
|
132
|
+
# def _split_brain_signals(self):
|
|
133
|
+
# "cắt electrode data thành các thành phần eeg/eog/emg"
|
|
134
|
+
# data_to_filter = self.get_last_window(1)
|
|
135
|
+
# noise_removed_signal, eeg, eog, emg = self.GetRawBrainComponents.filter(data_to_filter)
|
|
136
|
+
# self.filtered_eeg.append(eeg)
|
|
137
|
+
# self.filtered_eog.append(eog)
|
|
138
|
+
# self.filtered_emg.append(emg)
|
|
139
|
+
# time.sleep(0.9)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _streaming_data_ble_to_databucket(self):
|
|
144
|
+
"""Process binary data received from BLE => convert to int array => append to the experiment's data
|
|
145
|
+
Nơi xử lý từng binary packet trước khi chuyển đi
|
|
146
|
+
"""
|
|
147
|
+
clock = time.time()
|
|
148
|
+
expected_sequence_number = None
|
|
149
|
+
|
|
150
|
+
while True:
|
|
151
|
+
update = False
|
|
152
|
+
self.DATA_SAVED = False
|
|
153
|
+
|
|
154
|
+
# Check queue of eeg, ppg, imu; if there are packets of data haven't been processed yet:
|
|
155
|
+
# Get the binary packet from the queue (FIFO)
|
|
156
|
+
# Convert the binary packet -> int array
|
|
157
|
+
# Append the processed data to experiment.eeg_data (memmap)
|
|
158
|
+
if len(self.Ble_stack.raw_eeg_data) == 0:
|
|
159
|
+
time.sleep(0.03) # Tránh hit vòng lặp quá nhiều lần khi không cần thiết
|
|
160
|
+
|
|
161
|
+
# Processing eeg
|
|
162
|
+
if len(self.Ble_stack.raw_eeg_data) != 0:
|
|
163
|
+
packet_data = self.Ble_stack.raw_eeg_data.pop(0)
|
|
164
|
+
pc_packet_timestamp = self.Ble_stack.raw_eeg_pc_timestamps.pop(0)
|
|
165
|
+
timestamp, seq_num, channel_data = self.Ble_stack.get_data_from_eeg_binary_packet(packet_data, n_channels=num_eeg_channels)
|
|
166
|
+
|
|
167
|
+
if expected_sequence_number is None:
|
|
168
|
+
# channel_data: numpy array: packet of EEG data
|
|
169
|
+
self.experiment.add_eeg_data(channel_data, pc_packet_timestamp, timestamp)
|
|
170
|
+
# expected_sequence_number = (seq_num+1)%256
|
|
171
|
+
update = True
|
|
172
|
+
# else:
|
|
173
|
+
# if seq_num != expected_sequence_number:
|
|
174
|
+
# print('Sequence received:', seq_num, " Expected one:", expected_sequence_number)
|
|
175
|
+
# print('Missing or Duplicate packet')
|
|
176
|
+
# expected_sequence_number = (seq_num+1)%256
|
|
177
|
+
# else:
|
|
178
|
+
# self.experiment.add_eeg_data(channel_data, pc_packet_timestamp, timestamp)
|
|
179
|
+
# expected_sequence_number = (expected_sequence_number+1)%256
|
|
180
|
+
# update = True
|
|
181
|
+
|
|
182
|
+
# Processing imu
|
|
183
|
+
if len(self.Ble_stack.raw_imu_data) != 0:
|
|
184
|
+
packet_data = self.Ble_stack.raw_imu_data.pop(0)
|
|
185
|
+
pc_packet_timestamp = self.Ble_stack.raw_imu_pc_timestamps.pop(0)
|
|
186
|
+
timestamp, data = self.Ble_stack.get_data_from_imu_binary_packet(packet_data, n_channels=num_imu_channels)
|
|
187
|
+
# data: numpy array: packet of IMU data
|
|
188
|
+
self.experiment.add_imu_data(data, pc_packet_timestamp)
|
|
189
|
+
update = True
|
|
190
|
+
|
|
191
|
+
# Processing ppg
|
|
192
|
+
if len(self.Ble_stack.raw_ppg_data) != 0:
|
|
193
|
+
packet_data = self.Ble_stack.raw_ppg_data.pop(0)
|
|
194
|
+
pc_packet_timestamp = self.Ble_stack.raw_ppg_pc_timestamps.pop(0)
|
|
195
|
+
timestamp, data = self.Ble_stack.get_data_from_ppg_binary_packet(packet_data, n_channels=num_ppg_channels)
|
|
196
|
+
# data: numpy array: packet of PPG data
|
|
197
|
+
self.experiment.add_ppg_data(data, pc_packet_timestamp)
|
|
198
|
+
update = True
|
|
199
|
+
|
|
200
|
+
if update:
|
|
201
|
+
self.eeg = self.experiment.eeg_data[:self.experiment.eeg_data_size, :]
|
|
202
|
+
self.imu = self.experiment.imu_data[:self.experiment.imu_data_size, :]
|
|
203
|
+
self.ppg = self.experiment.ppg_data[:self.experiment.ppg_data_size, :]
|
|
204
|
+
|
|
205
|
+
current_time = time.time()
|
|
206
|
+
if current_time-clock > data_save_frequency:
|
|
207
|
+
# Save experiment data
|
|
208
|
+
self.experiment.save_data()
|
|
209
|
+
clock = current_time
|
|
210
|
+
self.DATA_SAVED = True
|
|
211
|
+
|
|
212
|
+
def start_stream_offline_data(self):
|
|
213
|
+
"Tạo thread để tạo luồng stream giả cho một bộ data offline"
|
|
214
|
+
self.offline_stream_thread = threading.Thread(name='offline_stream', target=self._to_streaming_offline_data)
|
|
215
|
+
self.offline_stream_thread.start()
|
|
216
|
+
|
|
217
|
+
def _to_streaming_offline_data(self, frequency=10):
|
|
218
|
+
"Thực hiện cắt dữ liệu để luồng streaming offline trông giống như một luồng online"
|
|
219
|
+
# remain_seconds: toàn bộ số giây mà data có => mỗi lần cắt đi một chút đến khi hết thì thôi
|
|
220
|
+
remain_seconds = self.OfflineDataProcessor.eeg_full_data.shape[0]/eeg_sampling_rate
|
|
221
|
+
end_second=0 # điểm kết thúc của block trước đó
|
|
222
|
+
|
|
223
|
+
while remain_seconds >0:
|
|
224
|
+
start_second = end_second # điểm bắt đầu của block hiện tại
|
|
225
|
+
end_second = start_second+1/frequency # điểm kết thúc của block hiện tại
|
|
226
|
+
|
|
227
|
+
# EEG: get a block and add to the Experiment
|
|
228
|
+
eeg_package = self.OfflineDataProcessor.eeg_full_data[ int(start_second*eeg_sampling_rate):int(end_second*eeg_sampling_rate),:]
|
|
229
|
+
self.experiment.add_eeg_data(data=eeg_package, pc_timestamp=start_second, timestamp=start_second)
|
|
230
|
+
|
|
231
|
+
# IMU: get a block and add to the Experiment
|
|
232
|
+
imu_package = self.OfflineDataProcessor.imu_full_data[ int(start_second*imu_sampling_rate):int(end_second*imu_sampling_rate),:]
|
|
233
|
+
self.experiment.add_imu_data(data=imu_package, timestamp=start_second)
|
|
234
|
+
|
|
235
|
+
# PPG: get a block and add to the Experiment
|
|
236
|
+
ppg_package = self.OfflineDataProcessor.ppg_full_data[ int(start_second*ppg_sampling_rate):int(end_second*ppg_sampling_rate),:]
|
|
237
|
+
self.experiment.add_ppg_data(data=ppg_package, timestamp=start_second)
|
|
238
|
+
|
|
239
|
+
# 20230213
|
|
240
|
+
self.eeg = self.experiment.eeg_data[:self.experiment.eeg_data_size, :]
|
|
241
|
+
self.imu = self.experiment.imu_data[:self.experiment.imu_data_size, :]
|
|
242
|
+
self.ppg = self.experiment.ppg_data[:self.experiment.ppg_data_size, :]
|
|
243
|
+
|
|
244
|
+
time.sleep(1/frequency)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def exit_signal_handler(self):
|
|
248
|
+
"""
|
|
249
|
+
Xử lý phần dữ liệu còn tồn trong queue nhưng chưa xử lý xong + lưu data
|
|
250
|
+
|
|
251
|
+
"""
|
|
252
|
+
# global expected_sequence_number, DATA_SAVED
|
|
253
|
+
print('Exiting...')
|
|
254
|
+
expected_sequence_number = None
|
|
255
|
+
# Save any additionall EEG data still in the raw data buffer
|
|
256
|
+
remaining_eeg_data = copy.deepcopy(self.Ble_stack.raw_eeg_data)
|
|
257
|
+
remaining_eeg_pc_timestamps = copy.deepcopy(self.Ble_stack.raw_eeg_pc_timestamps)
|
|
258
|
+
while len(remaining_eeg_data) > 0:
|
|
259
|
+
packet_data = remaining_eeg_data.pop(0)
|
|
260
|
+
pc_packet_timestamp = remaining_eeg_pc_timestamps.pop(0)
|
|
261
|
+
timestamp, seq_num, channel_data = self.Ble_stack.get_data_from_eeg_binary_packet(packet_data, n_channels=num_eeg_channels)
|
|
262
|
+
if expected_sequence_number is None:
|
|
263
|
+
self.experiment.add_eeg_data(channel_data, pc_packet_timestamp, timestamp)
|
|
264
|
+
# expected_sequence_number = (seq_num+1)%256
|
|
265
|
+
# else:
|
|
266
|
+
# if seq_num != expected_sequence_number:
|
|
267
|
+
# print('Missing or Duplicate packet')
|
|
268
|
+
# continue
|
|
269
|
+
# else:
|
|
270
|
+
# self.experiment.add_eeg_data(channel_data, pc_packet_timestamp, timestamp)
|
|
271
|
+
# expected_sequence_number = (expected_sequence_number+1)%256
|
|
272
|
+
|
|
273
|
+
# Save IMU data still in the raw data buffer
|
|
274
|
+
remaining_imu_data = copy.deepcopy(self.Ble_stack.raw_imu_data)
|
|
275
|
+
remaining_imu_pc_timestamps = copy.deepcopy(self.Ble_stack.raw_imu_pc_timestamps)
|
|
276
|
+
while len(remaining_imu_data) > 0:
|
|
277
|
+
packet_data = remaining_imu_data.pop(0)
|
|
278
|
+
pc_packet_timestamp = remaining_imu_pc_timestamps.pop(0)
|
|
279
|
+
timestamp, data = self.Ble_stack.get_data_from_imu_binary_packet(packet_data, n_channels=num_imu_channels)
|
|
280
|
+
self.experiment.add_imu_data(data, pc_packet_timestamp)
|
|
281
|
+
|
|
282
|
+
# Save PPG data still in the raw data buffer
|
|
283
|
+
remaining_ppg_data = copy.deepcopy(self.Ble_stack.raw_ppg_data)
|
|
284
|
+
remaining_ppg_pc_timestamps = copy.deepcopy(self.Ble_stack.raw_ppg_pc_timestamps)
|
|
285
|
+
while len(remaining_ppg_data) > 0:
|
|
286
|
+
packet_data = remaining_ppg_data.pop(0)
|
|
287
|
+
pc_packet_timestamp = remaining_ppg_pc_timestamps.pop(0)
|
|
288
|
+
timestamp, data = self.Ble_stack.get_data_from_ppg_binary_packet(packet_data, n_channels=num_ppg_channels)
|
|
289
|
+
self.experiment.add_ppg_data(data, pc_packet_timestamp)
|
|
290
|
+
|
|
291
|
+
self.experiment.save_data()
|
|
292
|
+
print('Data saved')
|
|
293
|
+
|
|
294
|
+
self.Ble_stack.close()
|
|
295
|
+
# sys.exit(0)
|
|
296
|
+
os._exit(0)
|
|
297
|
+
|
|
298
|
+
class GetRawBrainComponents:
|
|
299
|
+
def __init__(self) -> None:
|
|
300
|
+
self.BaseFilter = WindowFilter([WindowIIRNotchFilter(60, 12, 125), \
|
|
301
|
+
WindowIIRNotchFilter(50, 10, 125)])
|
|
302
|
+
self.EogFilter = WindowFilter([ WindowButterBandpassFilter(2, 0.3, 10, 125)])
|
|
303
|
+
self.EegFilter = WindowFilter([ WindowButterBandpassFilter(2, 1, 20, 125)])
|
|
304
|
+
self.Emg_Filter = WindowFilter([ WindowButterHighpassFilter(2, 20, 125)])
|
|
305
|
+
|
|
306
|
+
def filter(self, data):
|
|
307
|
+
noise_removed_signal = self.BaseFilter.filter_data(data)
|
|
308
|
+
eog = self.EogFilter.filter_data(noise_removed_signal)
|
|
309
|
+
eeg = self.EegFilter.filter_data(noise_removed_signal)
|
|
310
|
+
emg = self.Emg_Filter.filter_data(noise_removed_signal)
|
|
311
|
+
return noise_removed_signal, eeg, eog, emg
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Calculate STATE of the user
|
|
2
|
+
tổng hợp từ 2 nguồn : Low-level state và High-level state,
|
|
3
|
+
STATE: { input: raw signals; output: state }
|
|
4
|
+
versus
|
|
5
|
+
HLS: { input: STATE; output: state }
|
|
6
|
+
|
|
7
|
+
Version:
|
|
8
|
+
v1.x: chỉ bao gồm các scores hiện đã có (trước 1/2/2023)
|
|
9
|
+
"""
|
|
10
|
+
# import sys
|
|
11
|
+
# import os
|
|
12
|
+
# sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
import datetime
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from ..utils.params import imu_sampling_rate
|
|
19
|
+
from .algorithms.posture import get_posture
|
|
20
|
+
# from STATE.algorithms.posture_2 import get_posture as get_posture2
|
|
21
|
+
from .algorithms.poas import POAs_Calculator
|
|
22
|
+
# from .algorithms.focus import Focus_Calculator
|
|
23
|
+
from .algorithms.respiratory_rate import calculate_respiratory_rate
|
|
24
|
+
# from STATE.algorithms.gesture import detect_gaze
|
|
25
|
+
# from STATE.HLS import HLS_Inferor
|
|
26
|
+
from .algorithms.gesture_2 import BlinkDetection#, GazeDetection
|
|
27
|
+
from .algorithms.gaze_3 import GazeDetection
|
|
28
|
+
from .algorithms.emg_event_detection import emg_event_exists
|
|
29
|
+
from ..utils.WindowFiltering_focus import *
|
|
30
|
+
import copy
|
|
31
|
+
# from .utils.signal_processing import preprocess_eog
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StatesCalculator:
|
|
35
|
+
"Khởi tạo, lưu trữ, cung cấp hàm tính STATE từ raw data"
|
|
36
|
+
def __init__(self) -> None:
|
|
37
|
+
self.all_states = {}
|
|
38
|
+
|
|
39
|
+
# State khởi tạo
|
|
40
|
+
# self.all_states["welcome_message"] = 'No' # 02Feb: "No" là giá trị mặc định ban đầu => không cần khởi tạo
|
|
41
|
+
# self.all_states["remind_laydown"]='No'
|
|
42
|
+
self.all_states["start_time"]= time.time()
|
|
43
|
+
|
|
44
|
+
# Khởi tạo container cho historical STATE
|
|
45
|
+
# self.all_states["posture_array"] = []
|
|
46
|
+
|
|
47
|
+
# Khởi tạo, load các model cần cho tính chỉ số
|
|
48
|
+
## Tính POAS
|
|
49
|
+
self.POAs_Calculator = POAs_Calculator()
|
|
50
|
+
|
|
51
|
+
## Tính Focus score
|
|
52
|
+
# self.Focus_Calculator = Focus_Calculator()
|
|
53
|
+
|
|
54
|
+
## Tính HLS
|
|
55
|
+
# self.HLS_Inferor = HLS_Inferor()
|
|
56
|
+
|
|
57
|
+
## Detect Blink, Gaze
|
|
58
|
+
self.BlinkDetection = BlinkDetection()
|
|
59
|
+
self.GazeDetection = GazeDetection()
|
|
60
|
+
self.EOGFilter = {}
|
|
61
|
+
|
|
62
|
+
base_eog_filter = WindowFilter([
|
|
63
|
+
WindowIIRNotchFilter(60, 12, 125),
|
|
64
|
+
WindowIIRNotchFilter(50, 10, 125),
|
|
65
|
+
WindowButterBandpassFilter(2, 0.3, 10, 125)])
|
|
66
|
+
self.EOGFilter = {i:copy.deepcopy(base_eog_filter) for i in ["lf", "rf","otel", "oter"]}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def __getitem__(self, key):
|
|
70
|
+
"Slicing STATE object to get a STATE"
|
|
71
|
+
if key in self.all_states.keys():
|
|
72
|
+
# Nếu tồn tại STATE key thì trả về giá trị hiện tại của STATE
|
|
73
|
+
out = self.all_states[key]
|
|
74
|
+
else:
|
|
75
|
+
if key[:7] == "array__":
|
|
76
|
+
out = []
|
|
77
|
+
else:
|
|
78
|
+
# Nếu không tồn tại STATE key thì gán giá trị No cho key đó (không báo lỗi)
|
|
79
|
+
out = "No"
|
|
80
|
+
# self.all_states[key] = out # Không lưu, tất cả value nếu không có key thì đều là "No"
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
def get(self, key):
|
|
84
|
+
"API like python dictionary"
|
|
85
|
+
return self[key]
|
|
86
|
+
|
|
87
|
+
def __setitem__(self, key, value):
|
|
88
|
+
"Set value to STATE"
|
|
89
|
+
self.all_states[key] = value
|
|
90
|
+
|
|
91
|
+
def update(self, STATE, stored_array=True):
|
|
92
|
+
"""
|
|
93
|
+
Update all_states by a new STATE dictionary
|
|
94
|
+
Params
|
|
95
|
+
STATE: dict: states that need to be updated
|
|
96
|
+
stored_array: bool: are that states would be stored in memory arrays?"""
|
|
97
|
+
# Update state hiện tại
|
|
98
|
+
self.all_states.update(STATE)
|
|
99
|
+
|
|
100
|
+
# Append vào list của biến array__{score đang xét}
|
|
101
|
+
if stored_array:
|
|
102
|
+
available_keys = self.all_states.keys()
|
|
103
|
+
# print("STATE available_keys: ", available_keys)
|
|
104
|
+
for score_key in STATE.keys():
|
|
105
|
+
if ("array__"+score_key) not in available_keys:
|
|
106
|
+
self.all_states["array__"+score_key] = []
|
|
107
|
+
else:
|
|
108
|
+
self.all_states["array__"+score_key].append(STATE[score_key])
|
|
109
|
+
# self["array__"+score_key].append(STATE[score_key])
|
|
110
|
+
# print("APPEND: ", "array__"+score_key, " To value: " , STATE[score_key])
|
|
111
|
+
|
|
112
|
+
def update_STATE_atstart(self):
|
|
113
|
+
"""
|
|
114
|
+
Update STATE at the beginning of the session, one time only
|
|
115
|
+
No params needed (using LLS to infer)
|
|
116
|
+
"""
|
|
117
|
+
current_bedtime = get_decimal_hour(datetime.datetime.fromtimestamp(self["start_time"]))
|
|
118
|
+
scores = {"BEDTIME":current_bedtime}
|
|
119
|
+
# print("STATE.current_bedtime: ", current_bedtime)
|
|
120
|
+
# if (self["PURPOSE"] == 'DEEP_SLEEP') and ((current_bedtime>20) or (current_bedtime<8)):
|
|
121
|
+
# # ONly check bedtime if the user use a sleep session (not a nap) and they start session at night
|
|
122
|
+
# last_average_bedtime = self["BEDTIME_2d"]
|
|
123
|
+
# recommended_bedtime = 22
|
|
124
|
+
|
|
125
|
+
# BETTER_BEDTIME = self.HLS_Inferor.is_better_bedtime(last_average_bedtime, current_bedtime, recommended_bedtime)
|
|
126
|
+
# print("BETTER_BEDTIME: ", BETTER_BEDTIME)
|
|
127
|
+
# scores["BETTER_BEDTIME"] = BETTER_BEDTIME
|
|
128
|
+
|
|
129
|
+
self.update(scores, stored_array=False)
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def eye_map_value_to_state(value):
|
|
133
|
+
"""
|
|
134
|
+
Mapping đầu ra của model eye detection (từ score 0-1) về dạng state: sure open, open, close, sure close
|
|
135
|
+
"""
|
|
136
|
+
if type(value) == list:
|
|
137
|
+
value = value[0]
|
|
138
|
+
|
|
139
|
+
if value is None:
|
|
140
|
+
return None
|
|
141
|
+
elif value <= 0.1:
|
|
142
|
+
return "sure_close"
|
|
143
|
+
elif value <= 0.2:
|
|
144
|
+
return "close"
|
|
145
|
+
elif value <= 0.5:
|
|
146
|
+
return "open"
|
|
147
|
+
else:
|
|
148
|
+
return "sure_open"
|
|
149
|
+
|
|
150
|
+
def update_STATE_1s(self, data_4s, data_3s):
|
|
151
|
+
"""
|
|
152
|
+
Get Low level score, which update with frequency of 1s
|
|
153
|
+
Params:
|
|
154
|
+
data_4s: dict: với 3 keys: EEG, IMU, PPG
|
|
155
|
+
"""
|
|
156
|
+
data_4s_eeg = data_4s["EEG"].T
|
|
157
|
+
data_3s_eeg = data_3s["EEG"].T
|
|
158
|
+
lf5 = data_3s_eeg[0]
|
|
159
|
+
rf6 = data_3s_eeg[3]
|
|
160
|
+
|
|
161
|
+
otel = data_3s_eeg[1]
|
|
162
|
+
oter = data_3s_eeg[4]
|
|
163
|
+
# print("rf6.SHAPE: ", rf6.shape)
|
|
164
|
+
|
|
165
|
+
# gesture_id = detect_gaze(lf5, rf6, fs=125)
|
|
166
|
+
eog_otel = self.EOGFilter["otel"].filter_data(otel)[-125*2:]
|
|
167
|
+
eog_oter = self.EOGFilter["oter"].filter_data(oter)[-125*2:]
|
|
168
|
+
is_blink = self.BlinkDetection.get_blink(otel_data=eog_otel, oter_data=eog_oter)
|
|
169
|
+
|
|
170
|
+
eog_lf = self.EOGFilter["lf"].filter_data(lf5)[-125*2:]
|
|
171
|
+
eog_rf = self.EOGFilter["rf"].filter_data(rf6)[-125*2:]
|
|
172
|
+
# print("CHECK lf5: ", lf5.shape)
|
|
173
|
+
# eog_lf = preprocess_eog(lf5, 125)[-125*2:]
|
|
174
|
+
# eog_rf = preprocess_eog(rf6, 125)[-125*2:]
|
|
175
|
+
gesture_id = self.GazeDetection.get_gaze(eog_lf, eog_rf) #lf5, rf6)
|
|
176
|
+
gesture_map = {1:"eye_left", -1:"eye_right", 0:"undetected"}
|
|
177
|
+
gesture_id = gesture_map[gesture_id]
|
|
178
|
+
|
|
179
|
+
# emg_event, emg_event_channel = emg_event_exists([lf5[-125*2:], rf6[-125*2:]], 125)
|
|
180
|
+
emg_event, emg_event_channel = emg_event_exists([otel[-125*2:], oter[-125*2:]], 125)
|
|
181
|
+
|
|
182
|
+
if emg_event:
|
|
183
|
+
current_gesture = 'emg'
|
|
184
|
+
if emg_event_channel == "left":
|
|
185
|
+
current_gesture = 'emg_left'
|
|
186
|
+
elif emg_event_channel == "right":
|
|
187
|
+
current_gesture = 'emg_right'
|
|
188
|
+
elif is_blink:
|
|
189
|
+
current_gesture = 'blink'
|
|
190
|
+
elif gesture_id == 'eye_left':
|
|
191
|
+
current_gesture = 'eye_left'
|
|
192
|
+
elif gesture_id == 'eye_right':
|
|
193
|
+
current_gesture = 'eye_right'
|
|
194
|
+
else:
|
|
195
|
+
current_gesture = 'normal'
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
data_1s_imu = data_4s["IMU"]
|
|
199
|
+
# posture_1s = get_posture(data=data_1s_imu.T[:,-(imu_sampling_rate*2):], imu_fs=imu_sampling_rate, window_size=2)
|
|
200
|
+
|
|
201
|
+
scores = {
|
|
202
|
+
# "eog_lf": eog_lf,
|
|
203
|
+
"eye_gesture": gesture_id,
|
|
204
|
+
"eye_blink": is_blink,
|
|
205
|
+
"emg_event": emg_event,
|
|
206
|
+
"current_gesture": current_gesture,
|
|
207
|
+
"emg_event_channel":emg_event_channel
|
|
208
|
+
# "posture_1s": posture_1s
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
print(scores)
|
|
212
|
+
self.update(scores)
|
|
213
|
+
|
|
214
|
+
def update_STATE_2s(self, data_2s, data_30s):
|
|
215
|
+
"""
|
|
216
|
+
Get low level scores, which update with frequencies of 2s
|
|
217
|
+
Params
|
|
218
|
+
data_5s: dict: với 3 keys: EEG, IMU, PPG
|
|
219
|
+
"""
|
|
220
|
+
data_2s_eeg = data_2s["EEG"].T
|
|
221
|
+
|
|
222
|
+
data_30s_imu = data_30s["IMU"].T
|
|
223
|
+
data_30s_ppg = data_30s["PPG"].T
|
|
224
|
+
|
|
225
|
+
# focus_score = self.Focus_Calculator.get_focus(data_2s_eeg)
|
|
226
|
+
# respiratory_rate = calculate_respiratory_rate(imu_segment=data_30s_imu, ppg_segment=data_30s_ppg) # NOTE: OFF FOR DEBUG
|
|
227
|
+
|
|
228
|
+
# EYE_score = self.Focus_Calculator.get_eyeStage()
|
|
229
|
+
|
|
230
|
+
# EYE_ST = self.eye_map_value_to_state(EYE_score)
|
|
231
|
+
|
|
232
|
+
# Tập hợp các state được tính trong mỗi 2s -> update STATE
|
|
233
|
+
# scores = {
|
|
234
|
+
# "focus": focus_score,
|
|
235
|
+
# # "respiratory_rate":respiratory_rate, # NOTE: OFF FOR DEBUG
|
|
236
|
+
# "EYE_score": EYE_score,
|
|
237
|
+
# "EYE_ST" : EYE_ST
|
|
238
|
+
# }
|
|
239
|
+
|
|
240
|
+
# v1: thinking và stress được tính thông qua focus
|
|
241
|
+
# TODO: v2: các thuật toán riêng cho thinking và stress
|
|
242
|
+
# if focus_score > 0.65:
|
|
243
|
+
# THINKING_ST = 'high'
|
|
244
|
+
# scores["THINKING_ST"] = THINKING_ST
|
|
245
|
+
# if focus_score > 0.7:
|
|
246
|
+
# STRESS_ST = 'high'
|
|
247
|
+
# scores["STRESS_ST"] = STRESS_ST
|
|
248
|
+
|
|
249
|
+
# self.update(scores)
|
|
250
|
+
|
|
251
|
+
def update_STATE_5s(self, data_5s):
|
|
252
|
+
"""
|
|
253
|
+
Get low level scores, which update with frequencies of 5s
|
|
254
|
+
Params
|
|
255
|
+
data_5s: dict: với 3 keys: EEG, IMU, PPG
|
|
256
|
+
"""
|
|
257
|
+
data_5s_imu = data_5s["IMU"]
|
|
258
|
+
# data_30s_imu = data_30s["IMU"]
|
|
259
|
+
|
|
260
|
+
# Tính posture: từ 20230214: chia X8/X2 ngay trong chính function tính posture
|
|
261
|
+
# Chỉ chia case trên PC, trên mobile đã có phiên bản tính r nên không cần chia case
|
|
262
|
+
# if self["DEVICE_TYPE"] == 'X8':
|
|
263
|
+
# posture = get_posture2(data_5s_imu.T)
|
|
264
|
+
# else:
|
|
265
|
+
# posture = get_posture(data=data_5s_imu.T, imu_fs=imu_sampling_rate, window_size=5)[0]
|
|
266
|
+
# print("data_5s_imu: ", data_5s_imu)
|
|
267
|
+
posture = get_posture(data=data_5s_imu.T, imu_fs=imu_sampling_rate, window_size=5)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# Tập hợp các state được tính trong mỗi 5s -> update STATE
|
|
271
|
+
scores = {
|
|
272
|
+
"posture": posture
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
self.update(scores)
|
|
276
|
+
|
|
277
|
+
def update_STATE_30s(self, data_30s):
|
|
278
|
+
""" Tính các score với tần số 30s, input data=30s
|
|
279
|
+
Params
|
|
280
|
+
data_30s: dict: với 3 keys: EEG, IMU, PPG
|
|
281
|
+
"""
|
|
282
|
+
data_30s_eeg = data_30s["EEG"].T
|
|
283
|
+
epoch_poas, sleep_stage = self.POAs_Calculator.get_poas_and_sleepstage(data_30s_eeg)
|
|
284
|
+
scores = {
|
|
285
|
+
"poas": epoch_poas,
|
|
286
|
+
'sleep_stage': sleep_stage
|
|
287
|
+
}
|
|
288
|
+
self.update(scores)
|
|
289
|
+
|
|
290
|
+
# Sleep progress
|
|
291
|
+
# if len (self["array__poas"])>=6:
|
|
292
|
+
# SLEEP_PROGRESS = self.HLS_Inferor.get_sleep_progress(self["array__poas"])
|
|
293
|
+
|
|
294
|
+
# self.update({
|
|
295
|
+
# "SLEEP_PROGRESS": SLEEP_PROGRESS,
|
|
296
|
+
# })
|
|
297
|
+
if len (self["array__poas"])>=10:
|
|
298
|
+
poas_5m = np.mean(self["array__poas"][-10:])
|
|
299
|
+
|
|
300
|
+
self.update({
|
|
301
|
+
"poas_5m": poas_5m,
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
def get_decimal_hour(dt):
|
|
305
|
+
total_seconds = dt.hour * 3600 + dt.minute * 60 + dt.second
|
|
306
|
+
return float(total_seconds) / 3600
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|