-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor_utils.py
More file actions
1947 lines (1609 loc) · 77.5 KB
/
Copy pathsensor_utils.py
File metadata and controls
1947 lines (1609 loc) · 77.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import numpy as np
import time
import math
from bleak import BleakClient, BleakScanner
import os
import datetime
import queue
import asyncio
import struct
from scipy.spatial.transform import Rotation
from audio_utils import process_audio_data
import threading
import atexit
import pickle
import pandas as pd
import torch
import torch.nn as nn
from typing import List, Dict, Tuple, Any, Optional, Union
from scipy.ndimage import gaussian_filter1d
# Data buffer to store recent sensor data
sensor_data_buffer = {}
buffer_max_age = 40 # Maximum age of data to keep in buffer (seconds) - older data will be removed
# Batching system for file I/O operations
file_write_batches = {}
file_batch_lock = threading.Lock()
FILE_BATCH_SIZE = 50 # Number of samples to batch before writing
FILE_BATCH_TIMEOUT = 1.0 # Maximum time (seconds) to hold data before forced write
# UUIDs for BLE characteristics (from test.py)
UUID_A = "F00044DC-0451-4000-B000-000000000000" # Data characteristic
UUID_X = "F000ABCD-0451-4000-B000-000000000000" # Command characteristic
UUID_SERVICE = "F0002642-0451-4000-B000-000000000000" # Service UUID
# Global variables for BLE
ble_devices = []
freq = 100 # Default frequency
# BLE reconnection parameters
BLE_RECONNECT_ATTEMPTS = 5 # Maximum reconnection attempts
BLE_RECONNECT_DELAY = 3.0 # Initial delay between reconnection attempts (seconds)
BLE_RECONNECT_MAX_DELAY = 30.0 # Maximum delay between attempts (seconds)
BLE_CONNECTION_CHECK_INTERVAL = 5.0 # How often to check connection status (seconds)
# Connection monitor thread
ble_connection_monitor = None
ble_monitor_stop_event = threading.Event()
ble_main_event_loop = None # Store reference to main thread's event loop
ble_reconnection_lock = threading.Lock() # Lock to prevent concurrent reconnections to the same device
ble_reconnecting_devices = {} # Track devices that are currently in reconnection process
# File batch worker thread
file_batch_thread = None
file_batch_stop_event = threading.Event()
# Machine learning model
model_loader = None
node_mapping_cache = {} # Cache BLE index -> expected model node name mapping
# Register cleanup function to run at exit
atexit.register(lambda: cleanup_sensor_system())
# Define sampling rates and buffer sizes for EmotiBit sensors
EMOTIBIT_SAMPLING_RATES = {
"motion": 25, # AX, AY, AZ, GX, GY, GZ, MX, MY, MZ at 25Hz
"ppg": 25, # PI, PG, PR at 25Hz
"temperature": 7.5, # T0, TH at 7.5Hz
"eda": 15 # EA, EL, ER at 15Hz
}
# EmotiBit OSC signal types mapped to human-readable names
EMOTIBIT_SIGNAL_TYPES = {
# Motion signals
"ACC:X": "Accelerometer X",
"ACC:Y": "Accelerometer Y",
"ACC:Z": "Accelerometer Z",
"GYRO:X": "Gyroscope X",
"GYRO:Y": "Gyroscope Y",
"GYRO:Z": "Gyroscope Z",
"MAG:X": "Magnetometer X",
"MAG:Y": "Magnetometer Y",
"MAG:Z": "Magnetometer Z",
# PPG signals
"PPG:RED": "PPG Red",
"PPG:IR": "PPG Infrared",
"PPG:GRN": "PPG Green",
# Temperature signals
"TEMP": "Temperature",
"TEMP:T1": "Temperature T1",
"THERM": "Thermopile",
# EDA signals
"EDA": "Electrodermal Activity",
"EDL": "Electrodermal Level",
"EDR": "Electrodermal Response",
# Derived metrics
"SCR:AMP": "SCR Amplitude",
"SCR:RISE": "SCR Rise Time",
"SCR:FREQ": "SCR Frequency",
# Heart metrics
"HR": "Heart Rate",
"IBI": "Inter-beat Interval",
# Humidity
"HUMIDITY": "Humidity"
}
# Global variables for EmotiBit OSC
emotibit_osc_server = None
emotibit_data_buffers = {}
emotibit_active_signals = []
emotibit_connected = False
# Global variables for data collection
data_queue = None
sensors = None
def simulate_imu_data(time_val):
"""Simulate IMU sensor data"""
# Generate quaternion (normalized)
qw = 1.0 + 0.1 * math.sin(time_val * 0.1)
qx = 0.1 * math.sin(time_val * 0.2)
qy = 0.1 * math.cos(time_val * 0.3)
qz = 0.1 * math.sin(time_val * 0.4)
# Normalize quaternion
norm = math.sqrt(qw**2 + qx**2 + qy**2 + qz**2)
qw, qx, qy, qz = qw/norm, qx/norm, qy/norm, qz/norm
# Calculate Euler angles (roll, pitch, yaw)
roll = math.atan2(2*(qw*qx + qy*qz), 1 - 2*(qx**2 + qy**2))
pitch = math.asin(2*(qw*qy - qz*qx))
yaw = math.atan2(2*(qw*qz + qx*qy), 1 - 2*(qy**2 + qz**2))
return [qw, qx, qy, qz, roll, pitch, yaw]
def simulate_osc_data(time_val):
"""Simulate OSC sensor data"""
value1 = math.sin(time_val * 0.1) * 10
value2 = math.cos(time_val * 0.2) * 5
value3 = math.sin(time_val * 0.3) * 2
return [value1, value2, value3]
def simulate_audio_data(time_val):
"""Simulate audio sensor data"""
amplitude = 0.5 + 0.5 * math.sin(time_val * 0.1)
frequency = 440 + 100 * math.sin(time_val * 0.05)
return [amplitude, frequency]
def collect_sensor_data(sensors_dict, queue, running, paused):
"""Collect data from all sensors and put in queue"""
global data_queue, sensors
# Store these as module variables so they can be accessed by handlers
# since the handlers are called outside of this function's context
data_queue = queue
sensors = sensors_dict
if not running or paused:
return
# Get current time
current_time = time.time()
# Sync any buffered EmotiBit data every second
if "OSC_EmotiBit" in sensors and sensors["OSC_EmotiBit"]["connected"]:
sensor_info = sensors["OSC_EmotiBit"]
if sensor_info["type"] == "real" and "connector" in sensor_info:
# Use a timestamp-based approach to sync only once per second
if not hasattr(collect_sensor_data, "last_sync_time"):
collect_sensor_data.last_sync_time = 0
if current_time - collect_sensor_data.last_sync_time >= 1.0:
try:
# First trim buffers to remove old data
sensor_info["connector"].trim_buffers()
# Don't clear the buffer, as the OSC thread might still be adding to it
sensor_info["connector"].sync_buffered_data(data_queue, clear_buffer=False)
collect_sensor_data.last_sync_time = current_time
except Exception as e:
print(f"Error syncing EmotiBit data: {str(e)}")
# Collect data from all sensors
for sensor_id, sensor_info in sensors.items():
if sensor_info["connected"]:
if sensor_info["type"] == "simulated":
# Generate simulated data based on sensor type
if "BLE_IMU" in sensor_id:
data = simulate_imu_data(current_time)
elif "OSC_" in sensor_id and sensor_id.count('_') == 1:
# The old style OSC generic simulation
data = simulate_osc_data(current_time)
elif "OSC_" in sensor_id:
# EmotiBit-style OSC simulation for specific signals
signal_type = sensor_id.replace("OSC_", "")
data = [simulate_emotibit_data(signal_type, current_time)]
elif "Audio" in sensor_id:
data = simulate_audio_data(current_time)
else:
data = None
if data:
# Put data in queue for processing
data_queue.put({
"sensor_id": sensor_id,
"timestamp": current_time,
"data": data
})
elif sensor_info["type"] == "real":
if "BLE_IMU" in sensor_id:
# For real BLE sensors, get all data from the device buffer
if "device" in sensor_info and hasattr(sensor_info["device"], "data_buffer") and sensor_info["device"].data_buffer:
# Process all samples in the buffer
for sample in sensor_info["device"].data_buffer:
if sample is not None:
# Extract quaternion and Euler angles
# Format: [timestamp, battery, cal, qw, qx, qy, qz, roll, pitch, yaw]
qw, qx, qy, qz = sample[3:7]
roll, pitch, yaw = sample[7:10]
# Ensure data is in the correct format: [qw, qx, qy, qz, roll, pitch, yaw]
data = [float(qw), float(qx), float(qy), float(qz),
float(roll), float(pitch), float(yaw)]
# Put data in queue for processing with the sample's timestamp
data_queue.put({
"sensor_id": sensor_id,
"timestamp": float(sample[0]), # Ensure timestamp is float
"data": data
})
# Clear the buffer after processing
sensor_info["device"].data_buffer = []
elif "Audio" in sensor_id and "processor" in sensor_info:
try:
# For real audio sensor, get features from the processor
audio_features = sensor_info["processor"].get_audio_features()
if audio_features is not None:
# Process audio features to match simulated data format [amplitude, frequency]
data = process_audio_data(audio_features)
if data is not None:
# Put data in queue for processing
data_queue.put({
"sensor_id": sensor_id,
"timestamp": audio_features['timestamp'],
"data": data
})
except Exception as e:
print(f"Error processing audio data: {str(e)}")
# Note: OSC sensors with type="real" don't need handling here
# they're automatically handled by the emotibit_handler callback
def simulate_emotibit_data(signal_type, time_val):
"""Simulate EmotiBit sensor data for a specific signal type"""
if "ACC:" in signal_type:
return math.sin(time_val * 0.5) * 0.5 # Simulate accelerometer data
elif "GYRO:" in signal_type:
return math.cos(time_val * 0.3) * 10.0 # Simulate gyroscope data
elif "MAG:" in signal_type:
return math.sin(time_val * 0.1) * 50.0 # Simulate magnetometer data
elif "PPG:" in signal_type:
return math.sin(time_val * 1.0) * 100.0 + 500.0 # Simulate PPG signal
elif "TEMP" in signal_type or "THERM" in signal_type:
return 36.5 + math.sin(time_val * 0.05) * 0.5 # Simulate temperature ~37°C
elif "ED" in signal_type: # EDA, EDL, EDR
return 2.0 + math.sin(time_val * 0.2) * 0.5 # Simulate EDA around 2 µS
elif "SCR:" in signal_type:
return math.sin(time_val * 0.3) * 0.2 # Simulate SCR metrics
elif "HR" == signal_type:
return 70.0 + math.sin(time_val * 0.1) * 5.0 # Simulate HR ~70 BPM
elif "IBI" == signal_type:
return 0.85 + math.sin(time_val * 0.1) * 0.05 # Simulate IBI ~850ms
elif "HUMIDITY" == signal_type:
return 40.0 + math.sin(time_val * 0.05) * 5.0 # Simulate humidity ~40%
else:
return math.sin(time_val * 0.2) * 5.0 # Default simulation
def start_file_batch_writer():
"""Start the background thread for batch file writing"""
global file_batch_thread, file_batch_stop_event
if file_batch_thread is not None and file_batch_thread.is_alive():
return # Thread already running
file_batch_stop_event = threading.Event()
file_batch_thread = threading.Thread(target=file_batch_worker, daemon=True)
file_batch_thread.start()
def stop_file_batch_writer():
"""Stop the background thread for batch file writing"""
global file_batch_thread, file_batch_stop_event
if file_batch_thread is not None and file_batch_thread.is_alive():
file_batch_stop_event.set()
file_batch_thread.join(timeout=2.0)
# Flush any remaining data
with file_batch_lock:
for file_key, batch_info in file_write_batches.items():
if batch_info["data"]:
write_batch_to_file(file_key)
file_batch_thread = None
def file_batch_worker():
"""Background worker that periodically writes batched data to files"""
last_check_time = time.time()
while not file_batch_stop_event.is_set():
current_time = time.time()
flush_needed = False
# Check if any batches need to be written due to timeout
if current_time - last_check_time >= 0.1: # Check every 100ms
with file_batch_lock:
for file_key, batch_info in list(file_write_batches.items()):
if (batch_info["data"] and
(current_time - batch_info["last_update"] >= FILE_BATCH_TIMEOUT or
len(batch_info["data"]) >= FILE_BATCH_SIZE)):
write_batch_to_file(file_key)
flush_needed = True
last_check_time = current_time
# Sleep a bit to avoid busy waiting
time.sleep(0.01)
def write_batch_to_file(file_key):
"""Write a batch of data to a file"""
if file_key not in file_write_batches:
return
batch_info = file_write_batches[file_key]
if not batch_info["data"]:
return
data_dir, filename = file_key
full_path = os.path.join(data_dir, filename)
try:
# Create directory if it doesn't exist
os.makedirs(data_dir, exist_ok=True)
# Check if we need to write a header
file_exists = os.path.exists(full_path) and os.path.getsize(full_path) > 0
# Open the file with explicit closing to ensure file handles are released
f = None
try:
f = open(full_path, "a")
if not file_exists:
# Write header if file is new
f.write(batch_info["header"] + "\n")
# Write all data at once
f.write("".join(batch_info["data"]))
# Explicitly flush to ensure data is written
f.flush()
finally:
# Ensure file is closed even if an error occurs
if f is not None:
f.close()
# Clear the batch after successful write
batch_info["data"] = []
except Exception as e:
print(f"Error writing batch to file {full_path}: {str(e)}")
# Don't clear the batch on error, so we can retry later
def get_sensor_file_header(sensor_id):
"""Get the CSV header for a specific sensor type"""
if "BLE_IMU" in sensor_id:
return "timestamp,qw,qx,qy,qz,roll,pitch,yaw"
elif "OSC_" in sensor_id and sensor_id.count('_') == 1:
# Old generic OSC style
return "timestamp,value"
elif "OSC_" in sensor_id:
# EmotiBit-style OSC for specific signals
signal_type = sensor_id.replace("OSC_", "")
if signal_type in EMOTIBIT_SIGNAL_TYPES:
return f"timestamp,{EMOTIBIT_SIGNAL_TYPES[signal_type]}"
else:
return "timestamp,value"
elif "Audio" in sensor_id:
return "timestamp,amplitude,frequency"
return "timestamp,data"
def add_to_write_batch(sensor_id, timestamp, data, data_dir):
"""Add a data item to the write batch for a specific sensor"""
# Get device name for BLE sensors
device_name = ""
if "BLE_IMU" in sensor_id:
for device in ble_devices:
if device.idx == int(sensor_id.split("_")[-1]) - 1: # Subtract 1 to convert from 1-based to 0-based indexing
device_name = f"_{device.name}"
break
# Create filename
filename = f"{sensor_id}{device_name}.csv"
file_key = (data_dir, filename)
# Format data for writing
formatted_data = [f"{x:.3f}" for x in data]
formatted_timestamp = f"{timestamp:.3f}"
line = f"{formatted_timestamp},{','.join(formatted_data)}\n"
with file_batch_lock:
# Initialize batch if it doesn't exist
if file_key not in file_write_batches:
file_write_batches[file_key] = {
"data": [],
"header": get_sensor_file_header(sensor_id),
"last_update": time.time()
}
# Add line to batch
file_write_batches[file_key]["data"].append(line)
file_write_batches[file_key]["last_update"] = time.time()
# Write immediately if batch is full
if len(file_write_batches[file_key]["data"]) >= FILE_BATCH_SIZE:
write_batch_to_file(file_key)
def process_sensor_data(data_item, data_dir, current_session, session_types):
"""Process and save sensor data"""
sensor_id = data_item["sensor_id"]
timestamp = data_item["timestamp"]
data = data_item["data"]
# Add data to in-memory buffer
if sensor_id not in sensor_data_buffer:
sensor_data_buffer[sensor_id] = []
sensor_data_buffer[sensor_id].append((timestamp, data))
# Trim buffer to keep only recent data
current_time = time.time()
sensor_data_buffer[sensor_id] = [
(ts, d) for ts, d in sensor_data_buffer[sensor_id]
if current_time - ts <= buffer_max_age
]
# Add to write batch (batch file I/O)
add_to_write_batch(sensor_id, timestamp, data, data_dir)
def get_recent_sensor_data(seconds=5):
"""
Get the last N seconds of sensor data for all sensors
Args:
seconds: Number of seconds of data to retrieve
Returns:
Dictionary containing recent sensor data organized by sensor type
"""
current_time = time.time()
min_timestamp = current_time - seconds
# Create a dictionary to hold all recent sensor data
recent_data = {
"timestamp_range": (min_timestamp, current_time),
"imu_sensors": {},
"osc_sensors": {},
"audio_sensors": {}
}
# Process each sensor's data
for sensor_id, data_list in sensor_data_buffer.items():
# Filter data by timestamp
recent_sensor_data = [
(ts, d) for ts, d in data_list
if ts >= min_timestamp
]
if not recent_sensor_data:
continue
# Organize data by sensor type
if "BLE_IMU" in sensor_id:
recent_data["imu_sensors"][sensor_id] = {
"timestamps": [ts for ts, _ in recent_sensor_data],
"data": [d for _, d in recent_sensor_data]
}
elif "OSC_" in sensor_id:
recent_data["osc_sensors"][sensor_id] = {
"timestamps": [ts for ts, _ in recent_sensor_data],
"data": [d for _, d in recent_sensor_data]
}
elif "Audio" in sensor_id:
recent_data["audio_sensors"][sensor_id] = {
"timestamps": [ts for ts, _ in recent_sensor_data],
"data": [d for _, d in recent_sensor_data]
}
return recent_data
def print_ble_roll(recent_data, ble_idx):
"""
Print the roll values from BLE_IMU sensor
Returns:
List of roll values if sensor data exists, otherwise None
"""
# Look for BLE_IMU_ble_idx in the imu_sensors
ble_data = None
for sensor_id, sensor_data in recent_data["imu_sensors"].items():
if sensor_id == f"BLE_IMU_{ble_idx}" or (sensor_id.startswith("BLE_IMU") and f"{ble_idx}" in sensor_id):
ble_data = sensor_data
break
if ble_data is None:
print(f"No data found for BLE_IMU_{ble_idx}")
return None
# Extract roll values (roll is at index 4 in IMU data format [qw, qx, qy, qz, roll, pitch, yaw])
roll_values = []
for data_point in ble_data["data"]:
if len(data_point) >= 5: # Make sure data has enough elements
roll_values.append(data_point[4])
# Print the roll values
if roll_values:
print(f"Roll values from BLE_IMU_{ble_idx}:")
for i, roll in enumerate(roll_values):
print(f"Sample {i+1}: {roll:.4f} degrees")
return roll_values
else:
print(f"No roll data available for BLE_IMU_{ble_idx}")
return None
def print_emotibit_ppg_ir(recent_data):
"""
Print the PPG:IR values from EmotiBit sensor
Args:
recent_data: Dictionary containing recent sensor data
Returns:
List of PPG:IR values if sensor data exists, otherwise None
"""
# Look for OSC_PPG:IR in the osc_sensors
ppg_ir_data = None
sensor_id = "OSC_PPG:IR"
if "osc_sensors" in recent_data:
for sid, sensor_data in recent_data["osc_sensors"].items():
if sid == sensor_id:
ppg_ir_data = sensor_data
break
if ppg_ir_data is None:
print("No data found for EmotiBit PPG:IR")
return None
# Extract PPG:IR values (data is a list of lists, with one value per sample)
ppg_ir_values = []
for data_point in ppg_ir_data["data"]:
if len(data_point) >= 1: # Make sure data has at least one element
ppg_ir_values.append(data_point[0])
# Print the PPG:IR values
if ppg_ir_values:
print(f"PPG:IR values from EmotiBit:")
for i, value in enumerate(ppg_ir_values):
print(f"Sample {i+1}: {value:.2f}")
return ppg_ir_values
else:
print("No PPG:IR data available from EmotiBit")
return None
def get_samples():
"""Get the last N seconds of sensor data for all sensors"""
requested_seconds = 30
recent_data = get_recent_sensor_data(seconds=requested_seconds)
# Count samples for each sensor type
imu_sample_count = 0
osc_sample_count = 0
audio_sample_count = 0
# Count IMU sensor samples per device
imu_samples_by_device = {}
for sensor_id, sensor_data in recent_data["imu_sensors"].items():
device_name = f"BLE_IMU_{sensor_id.split('_')[-1]}"
imu_samples_by_device[device_name] = len(sensor_data["data"])
imu_sample_count += len(sensor_data["data"])
# Count OSC sensor samples
osc_samples_by_signal = {}
for sensor_id, sensor_data in recent_data["osc_sensors"].items():
signal_count = len(sensor_data["data"])
osc_sample_count += signal_count
# For EmotiBit signals, track by signal type
if sensor_id.replace("OSC_", "") in EMOTIBIT_SIGNAL_TYPES:
signal_type = sensor_id.replace("OSC_", "")
signal_name = EMOTIBIT_SIGNAL_TYPES[signal_type]
osc_samples_by_signal[signal_name] = signal_count
# Count Audio sensor samples
for sensor_id, sensor_data in recent_data["audio_sensors"].items():
audio_sample_count += len(sensor_data["data"])
# Store sample counts in a dictionary
sample_counts = {
"imu_samples": imu_sample_count,
"imu_samples_by_device": imu_samples_by_device,
"osc_samples": osc_sample_count,
"osc_samples_by_signal": osc_samples_by_signal,
"audio_samples": audio_sample_count,
"total_samples": imu_sample_count + osc_sample_count + audio_sample_count
}
print("Sample counts:")
print(f"Total IMU samples: {imu_sample_count}")
print("IMU samples by device:")
for device, count in imu_samples_by_device.items():
# Get actual device name from ble_devices list
actual_device_name = "Unknown"
device_idx = device.split("_")[-1]
if device_idx.isdigit():
for ble_device in ble_devices:
if ble_device.idx == int(device_idx) - 1: # Convert from 1-based to 0-based indexing
actual_device_name = ble_device.name
break
print(f" {device} ({actual_device_name}): {count} samples")
print(f"Total OSC samples: {osc_sample_count}")
print("OSC samples by signal:")
for signal, count in osc_samples_by_signal.items():
print(f" {signal}: {count} samples")
print(f"Audio samples: {audio_sample_count}")
print(f"Total samples: {sample_counts['total_samples']}")
return recent_data, sample_counts
class EmbeddingNet(nn.Module):
"""
A multi-layer perceptron that embeds input features into a latent space.
Replicates the architecture from the original model.
"""
def __init__(self, input_dim: int, embedding_dim: int = 64):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(input_dim, 128),
nn.ReLU(),
nn.BatchNorm1d(128),
nn.Dropout(0.5),
nn.Linear(128, embedding_dim),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.fc(x)
class DeepPrototypeModelLoader:
"""
Standalone class for loading and using a saved deep prototype model.
"""
def __init__(self, model_dir: str, device: str = "cpu"):
"""
Initialize the model loader by loading all necessary components.
Args:
model_dir: Directory containing the saved model artifacts
device: Device to load the model onto ("cpu" or "cuda")
"""
self.model_dir = model_dir
self.device = torch.device(device)
# Check if model directory exists
if not os.path.exists(model_dir):
raise FileNotFoundError(f"Model directory not found: {model_dir}")
# Load feature names
feature_names_path = os.path.join(model_dir, "feature_names.pkl")
if not os.path.exists(feature_names_path):
raise FileNotFoundError(f"Feature names file not found: {feature_names_path}")
with open(feature_names_path, "rb") as f:
self.feature_names = pickle.load(f)
# Load scaler
scaler_path = os.path.join(model_dir, "scaler.pkl")
if not os.path.exists(scaler_path):
raise FileNotFoundError(f"Scaler file not found: {scaler_path}")
with open(scaler_path, "rb") as f:
self.scaler = pickle.load(f)
# Load model configuration
config_path = os.path.join(model_dir, "model_config.pkl")
if not os.path.exists(config_path):
raise FileNotFoundError(f"Model config file not found: {config_path}")
with open(config_path, "rb") as f:
model_config = pickle.load(f)
input_dim = model_config["input_dim"]
embedding_dim = model_config["embedding_dim"]
# Initialize and load model
model_path = os.path.join(model_dir, "model.pt")
if not os.path.exists(model_path):
raise FileNotFoundError(f"Model weights file not found: {model_path}")
self.model = EmbeddingNet(input_dim, embedding_dim).to(self.device)
self.model.load_state_dict(torch.load(
model_path,
map_location=self.device
))
self.model.eval()
self.last_distances = None # store last distances for UI
# Load prototypes
prototypes_path = os.path.join(model_dir, "prototypes.pkl")
if not os.path.exists(prototypes_path):
raise FileNotFoundError(f"Prototypes file not found: {prototypes_path}")
with open(prototypes_path, "rb") as f:
prototype_dict = pickle.load(f)
# Convert numpy arrays back to torch tensors
self.prototypes = {k: torch.tensor(v, device=self.device, dtype=torch.float32) for k, v in prototype_dict.items()}
# Normalize prototype keys and determine negative key
# Support either 'Negative' or 0 as the negative prototype key
possible_negative_keys = ['Negative', 0, '0']
self.negative_key = None
for k in possible_negative_keys:
if k in self.prototypes:
self.negative_key = k
break
if self.negative_key is None:
# Fallback: if only two prototypes, assume the first key sorted is negative
# But warn clearly
print("Warning: Could not find explicit negative prototype key; defaulting to first key.")
self.negative_key = list(self.prototypes.keys())[0]
# Build ordered labels list: negative first, then all positives
self.prototype_labels = ['Negative']
self.positive_labels = []
for key in self.prototypes.keys():
if key != self.negative_key:
self.positive_labels.append(str(key))
# Preserve stable ordering of positives
self.positive_labels.sort()
def preprocess_features(self, features_df: pd.DataFrame) -> np.ndarray:
"""
Preprocess the input features using the saved scaler.
Ensures all expected features are present, adding zero columns for missing features.
Args:
features_df: DataFrame containing raw features
Returns:
Scaled feature array ready for model input
"""
# Create a copy to avoid modifying the original DataFrame
features_df = features_df.copy()
# Check and add missing features all at once using a dictionary
missing_features = {}
for feature in self.feature_names:
if feature not in features_df.columns:
missing_features[feature] = 0
# Add all missing columns at once if any
if missing_features:
for feature, value in missing_features.items():
features_df[feature] = value
# Keep only needed features and in the right order
X = features_df[self.feature_names]
# Scale the features
X_scaled = self.scaler.transform(X)
return X_scaled
def predict(self, features_df: pd.DataFrame, smoothing_sigma: float = 2.0) -> pd.DataFrame:
"""
Generate predictions for input features.
Args:
features_df: DataFrame containing features for prediction
smoothing_sigma: Sigma parameter for Gaussian smoothing of probabilities
Returns:
DataFrame with prediction results
"""
# Preprocess features
X_scaled = self.preprocess_features(features_df)
X_tensor = torch.tensor(X_scaled, dtype=torch.float32).to(self.device)
# Get timestamps if available, otherwise create index-based timestamps
if "timestamp" in features_df.columns:
timestamps = features_df["timestamp"].values
else:
timestamps = np.arange(len(features_df))
# Generate embeddings
with torch.no_grad():
embeddings = self.model(X_tensor)
# Prepare prototype tensors for distance calculation using saved ordering
all_prototype_tensors = []
ordered_labels = []
# Negative first
all_prototype_tensors.append(self.prototypes[self.negative_key].unsqueeze(0))
ordered_labels.append('Negative')
# Then all positives (sorted string labels)
for label in self.positive_labels:
# Find the original key that stringifies to this label
# Saved keys could be strings already; map robustly
proto_key = None
for k in self.prototypes.keys():
if k == self.negative_key:
continue
if str(k) == label:
proto_key = k
break
if proto_key is None:
continue
all_prototype_tensors.append(self.prototypes[proto_key].unsqueeze(0))
ordered_labels.append(label)
# Expose ordered labels for downstream consumers (e.g., logging/saving)
self.ordered_labels = ordered_labels
# Stack all prototypes
all_prototypes_stacked = torch.cat(all_prototype_tensors, dim=0)
# Compute distances to all prototypes
dists = torch.cdist(embeddings, all_prototypes_stacked, p=2) ** 2
# Apply model-behavior adjustment: subtract 4 from Negative prototype distance (index 0)
if dists.shape[1] > 0:
dists[:, 0] = dists[:, 0] - 15
# Log distances to each prototype for the first sample (useful in live 1-row inference)
try:
if dists.shape[0] > 0:
row0 = dists[0].detach().cpu().numpy()
dist_log = ", ".join(f"{label}:{float(row0[i]):.4f}" for i, label in enumerate(ordered_labels))
print(f"Prototype distances -> {dist_log}")
# Save for external access
self.last_distances = [(label, float(row0[i])) for i, label in enumerate(ordered_labels)]
except Exception as _:
pass
# Softmax over negative and all positive prototypes
probs = nn.functional.softmax(-dists, dim=1)
# Probability of being positive = 1 - P(negative)
prob_positive = (1.0 - probs[:, 0]).cpu().numpy()
if smoothing_sigma > 0:
prob_positive = gaussian_filter1d(prob_positive, sigma=smoothing_sigma)
# Closest overall prototype (may be 'Negative')
closest_overall_idx = torch.argmin(dists, dim=1).cpu().numpy()
most_likely_prototype = [ordered_labels[idx] for idx in closest_overall_idx]
# Closest positive-only prototype
positive_only_dists = dists[:, 1:] # exclude negative at index 0
if positive_only_dists.shape[1] > 0:
closest_positive_rel_idx = torch.argmin(positive_only_dists, dim=1).cpu().numpy()
closest_positive_idx = (closest_positive_rel_idx + 1) # shift because we excluded negative
closest_positive = [ordered_labels[idx] for idx in closest_positive_idx]
# Probability of the closest positive prototype
closest_positive_prob = probs.gather(
1, torch.tensor(closest_positive_idx, device=self.device).unsqueeze(1)
).squeeze().detach().cpu().numpy()
else:
closest_positive = ['Negative'] * len(embeddings)
closest_positive_prob = np.zeros(len(embeddings))
# Binary decision reflective of original training:
# Positive iff any positive prototype is closer than the negative prototype
negative_dists = dists[:, 0]
min_positive_dists, _ = torch.min(dists[:, 1:], dim=1) if dists.shape[1] > 1 else (torch.full((dists.shape[0],), float('inf'), device=dists.device), None)
is_positive = (min_positive_dists < negative_dists).int().cpu().numpy()
# Create predictions DataFrame
predictions = pd.DataFrame({
"timestamp": timestamps,
"prob_positive": prob_positive,
"most_likely_prototype": most_likely_prototype,
"most_likely_positive": closest_positive,
"most_likely_positive_prob": closest_positive_prob,
"is_positive": is_positive
})
return predictions
def run_ml_prediction(participant_data, session_type=None):
"""Run machine learning prediction on sensor data"""
global model_loader
models_base_dir = "models"
# Choose desired model directory based on session type and participant selection
selected_folder = None
try:
if session_type == "Group":
selected_folder = "group"
elif participant_data:
selected_folder = participant_data.get("model_participant", None)
except Exception:
selected_folder = None
desired_dir = None
try:
# Validate selected folder
if selected_folder:
candidate = os.path.join(models_base_dir, selected_folder)
if os.path.isdir(candidate) and os.path.exists(os.path.join(candidate, "model.pt")):
desired_dir = candidate
# Prefer 'group' fallback
if desired_dir is None:
group_dir = os.path.join(models_base_dir, "group")
if os.path.isdir(group_dir) and os.path.exists(os.path.join(group_dir, "model.pt")):
desired_dir = group_dir
# First valid model under models/
if desired_dir is None and os.path.isdir(models_base_dir):
for name in sorted(os.listdir(models_base_dir)):
path = os.path.join(models_base_dir, name)
if os.path.isdir(path) and os.path.exists(os.path.join(path, "model.pt")):
desired_dir = path
break
except Exception:
desired_dir = None
if desired_dir is None:
# Clear error path (will raise inside loader)
desired_dir = models_base_dir
# Load or reload model if needed
if model_loader is None or getattr(model_loader, "model_dir", None) != desired_dir:
model_loader = DeepPrototypeModelLoader(model_dir=desired_dir)
# Get the last 5 seconds of sensor data
recent_data, sample_counts = get_samples()
# Map quaternion components to expected feature naming
component_mapping = {
"qw": "W",
"qx": "X",
"qy": "Y",
"qz": "Z"
}
# Initialize feature dictionary with a single timestamp
feature_dict = {"timestamp": [time.time()]}
# Initialize all features to 0.0 to handle missing data
for feature in model_loader.feature_names:
feature_dict[feature] = [0.0]
# Build expected node names from model feature names and create a stable mapping
expected_nodes = []
try:
import re as _re
seen = set()
for fname in model_loader.feature_names:
m = _re.search(r"^Wing_(.+?)_0000_", fname)
if m:
node = m.group(1)
if node not in seen:
expected_nodes.append(node)
seen.add(node)
except Exception:
expected_nodes = []
# Create mapping from BLE device idx to expected node name (stable across calls)
global node_mapping_cache
mapping_changed = False
for device in ble_devices:
if device.idx not in node_mapping_cache:
mapped = None
# Prefer 1:1 by index when possible
if 0 <= device.idx < len(expected_nodes):
mapped = expected_nodes[device.idx]
else:
# Fallback: if the device name already appears in expected nodes, use it
if device.name in expected_nodes:
mapped = device.name
elif expected_nodes:
# Last resort: first unused expected node
for cand in expected_nodes:
if cand not in node_mapping_cache.values():
mapped = cand
break