-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_data_profiles.py
More file actions
785 lines (653 loc) · 30.6 KB
/
Copy pathcreate_data_profiles.py
File metadata and controls
785 lines (653 loc) · 30.6 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
import sys, argparse, random
from visualize_data import FeatureData, create_indices_for_features, feature_loading
from brics_toolkit.utils.config import *
def parse_jsonl_line(line):
"""
Parses a single line of a JSONL file and extracts the timestamp and ADC values.
Parameters
----------
line : str
A single line from a JSONL file containing a JSON object with 'timestamp' and 'adc_outputs'.
Returns
-------
timestamp : int
The timestamp extracted from the JSON object.
adc_values : list of int
A list of ADC output values extracted from the JSON object.
Side Effects
------------
This function has no side effects.
"""
data = json.loads(line)
timestamp = data.get('timestamp', 0)
adc_values = [data.get('adc_outputs')[i] for i in range(ADC_COUNT)]
return timestamp, adc_values
def extract_breath_features(signal):
"""
Initializes breath features and extracts depth and length from a single breath signal.
Parameters
----------
signal : list of float
The normalized ADC signal corresponding to a single breath.
Returns
-------
dict
A dictionary containing the initialized and extracted breath features:
depth, length, inhale duration, inspiratory pause duration, exhale duration
and expiratory pause duration.
Side Effects
------------
This function has no side effects.
"""
depth = np.max(signal) - np.min(signal)
length = len(signal)
return {
"depth": float(depth),
"length": int(length),
"inhale": 0.0,
"inspiratory_pause": 0.0,
"exhale": 0.0,
"expiratory_pause": 0.0,
}
def detect_breath_peaks(signal):
"""
Detects breath peaks (minima and maxima) in the given signal using the scipy.signal.find_peaks function.
Parameters
----------
signal : list of float
The normalized ADC signal from which to detect breath peaks.
Returns
-------
tuple: list of int (minima), list of int (maxima)
A tuple containing the indices of the detected minima and maxima.
Side Effects
------------
This function has no side effects.
"""
inverted_signal = [-x for x in signal]
mean_signal = np.mean(signal)
std_dev_signal = np.std(signal)
maxima, _ = scipy.signal.find_peaks(signal, distance=MIN_DISTANCE, height=mean_signal + std_dev_signal*STD_DEV_CONST)
minima, _ = scipy.signal.find_peaks(inverted_signal, distance=MIN_DISTANCE, height=mean_signal + std_dev_signal*STD_DEV_CONST)
return minima, maxima
def get_mode_breaths(all_breath_data, mode_values, avg_values, people_files):
"""
Identifies a set of MODE_BREATH_COUNT most representative breaths from the given breath dataset defined in all_breath_data.
The selection is based on a weighted distance metric that considers the breath's depth, length and breathing
phases' durations (inhale and exhale, the inspiratory and expiratory pauses have been excluded).
Parameters
----------
all_breath_data : list of dict
A list of dictionaries, where each dictionary contains the features of a single breath.
mode_values : dict
A dictionary containing the mode values for breath features (depth, length, inhale duration,
exhale duration, inspiratory pause duration, expiratory pause duration).
avg_values : dict
A dictionary containing the average values for breath features (depth, length, inhale duration,
exhale duration, inspiratory pause duration, expiratory pause duration).
people_files : list of str
A list of file names (located in the ./results directory) from which to extract data for
the additional (other than TARGET_ADC) ADC channels for the selected mode breaths.
Returns
-------
representative_breath : dict
A dictionary containing the features of the most representative breath (mode breath) from the dataset.
representative_breaths_weights: list of int
A list of weights corresponding to the selected mode breaths, where the weight is inversely proportional
to the distance from mode values
Side Effects
------------
This function has no side effects.
"""
breath_distances = np.array([])
weights = {
'depth': 0.3,
'length': 0.3,
'inhale': 1.0,
'exhale': 1.0,
}
for i, breath in enumerate(all_breath_data):
dist = 0.0
dist += weights['depth'] * abs(breath['depth'] - avg_values['avg_depth'])
dist += weights['length'] * abs(breath['length'] - avg_values['avg_length'])
dist += weights['inhale'] * abs(breath['inhale'] - avg_values['avg_inhale'])
dist += weights['exhale'] * abs(breath['exhale'] - avg_values['avg_exhale'])
dist += weights['depth'] * abs(breath['depth'] - mode_values['mode_depth'])
dist += weights['length'] * abs(breath['length'] - mode_values['mode_length'])
dist += weights['inhale'] * abs(breath['inhale'] - mode_values['mode_inhale'])
dist += weights['exhale'] * abs(breath['exhale'] - mode_values['mode_exhale'])
# dist += (breath['inspiratory_pause'] - mode_values['mode_inspiratory_pause'])
# dist += (breath['expiratory_pause'] - mode_values['mode_expiratory_pause'])
breath_distances = np.append(breath_distances, {"index": i, "distance": dist})
# TODO: rewrite this to np functions, for now I had some strange issues with them so we are using "sorted"
sorted_distances = sorted(breath_distances, key=lambda x: x['distance'])
selected_count = min(MODE_BREATH_COUNT, len(sorted_distances))
selected_breaths = [all_breath_data[sorted_distances[i]['index']] for i in range(selected_count)]
representative_breaths_weights = [selected_count - i for i in range(selected_count)]
file_cache = {}
for file in people_files:
file_cache[file] = extract_breath_data_from_file(file)
mode_breaths = [[] for _ in range(ADC_COUNT)]
for breath in selected_breaths:
file_name = breath["file_name"]
start_idx = breath["start_idx"]
end_idx = breath["end_idx"]
file_data = file_cache[file_name]
timestamps = file_data["timestamps"][start_idx:end_idx]
adc_signals = file_data["adc_signals"]
for adc in range(ADC_COUNT):
signal = adc_signals[adc][start_idx:end_idx]
adc_breath = {
"file_name": file_name,
"start_idx": start_idx,
"end_idx": end_idx,
"adc": adc,
"signal": signal,
"timestamps": timestamps,
}
if adc == TARGET_ADC:
adc_breath["inhale"] = breath["inhale"]
adc_breath["inspiratory_pause"] = breath["inspiratory_pause"]
adc_breath["exhale"] = breath["exhale"]
adc_breath["expiratory_pause"] = breath["expiratory_pause"]
mode_breaths[adc].append(adc_breath)
return mode_breaths, representative_breaths_weights
# return representative_breaths_target_adc, representative_breaths_weights
def calculate_breathing_phases_for_breath(breath_signal, breath_timestamps, peak_index, start_idx, end_idx):
"""
Calculates the durations of the breathing phases (inhale, inspiratory pause, exhale, expiratory pause) for a single breath.
Parameters
----------
breath_signal : list of float
The normalized ADC signal corresponding to a single breath.
breath_timestamps : list of int
The timestamps corresponding to the breath signal.
peak_index : int
The index of the peak (maximum) in the breath signal.
start_idx : int
The index of the start of the breath (first minimum).
end_idx : int
The index of the end of the breath (the minimum after the peak).
Returns
-------
phases : list of float
A list containing the durations of the breathing phases: [inhale, inspiratory pause, exhale, expiratory pause].
Side Effects
------------
This function has no side effects.
"""
if len(breath_signal) < 3:
return 0.0, 0.0, 0.0, 0.0
phases = [0.0, 0.0, 0.0, 0.0] # inhale, inspiratory_pause, exhale, expiratory_pause
phases[0] = breath_timestamps[start_idx] - breath_timestamps[peak_index]
phases[1] = 0.0
phases[2] = breath_timestamps[end_idx] - breath_timestamps[peak_index]
phases[3] = 0.0
return phases
def extract_breath_data_from_file(file):
"""
Extracts minima and maxima indices from a given file (from the ./results directory)
as well as the corresponding timestamps and ADC signals.
Parameters
----------
file : str
The name of the file from which to extract breath data. The file should be located in the ./results directory.
Returns
-------
dict
A dictionary containing the extracted breath data:
- minima: A list of indices of detected minima in the ADC signal.
- maxima: A list of indices of detected maxima in the ADC signal.
- timestamps: A list of timestamps corresponding to the ADC signal samples.
- adc_signals: A list of lists, each inner list contains the ADC signal values for one of the 5 ADC channels.
Side Effects
------------
This function has no side effects.
"""
with open (f'./results/{file}', 'r') as f:
file_lines = f.read().strip().split("\n")
timestamps = []
adc_signals = [[] for _ in range(ADC_COUNT)]
for line in file_lines:
if line:
timestamp, adc_values = parse_jsonl_line(line)
timestamps.append(timestamp)
for i in range(ADC_COUNT):
adc_signals[i].append(adc_values[i])
minima, maxima = detect_breath_peaks(adc_signals[TARGET_ADC])
return { "minima": minima, "maxima": maxima, "timestamps": timestamps, "adc_signals": adc_signals }
def calculate_breath_characteristics(people_files):
"""
Calculates breath characteristics (depth, length, start_idx, end_idx, inhale duration, exhale duration)
for each breath in the given files.
Parameters
----------
people_files : list of str
A list of file names (located in the ./results directory) from which to extract and calculate breath
characteristics - they describe the breathing patterns of a single person.
Returns
-------
all_breath_data : list of dict
A list of dictionaries, where each dictionary contains the features of a single breath extracted from the given files.
Side Effects
------------
This function has no side effects.
"""
all_breath_data = []
for file in people_files:
file_breath_data = extract_breath_data_from_file(file)
minima = file_breath_data["minima"]
maxima = file_breath_data["maxima"]
timestamps = file_breath_data["timestamps"]
adc_signals = file_breath_data["adc_signals"]
for i in range(len(minima)-1):
start_idx = minima[i]
end_idx = minima[i+1]
breath_signal = adc_signals[TARGET_ADC][start_idx:end_idx]
breath_timestamps = timestamps[start_idx:end_idx]
if len(breath_signal) == 0:
continue
breath_features = extract_breath_features(breath_signal)
breath_features['file_name'] = file
breath_features['start_idx'] = start_idx
breath_features['end_idx'] = end_idx
breath_features['signal'] = breath_signal
breath_features['timestamps'] = breath_timestamps
# Find all maxima within the breath
peaks_in_breath = []
for peak in maxima:
if start_idx <= peak < end_idx:
peaks_in_breath.append(peak)
break
# If there is more than one peak we want to take the "highest" one
peak_in_breath = np.max(peaks_in_breath) if peaks_in_breath else None
if peak_in_breath is not None:
phases = calculate_breathing_phases_for_breath(adc_signals[TARGET_ADC], timestamps, peak_in_breath, start_idx, end_idx)
breath_features['inhale'] = phases[0]
breath_features['inspiratory_pause'] = phases[1]
breath_features['exhale'] = phases[2]
breath_features['expiratory_pause'] = phases[3]
all_breath_data.append(breath_features)
return all_breath_data
def get_mode_param(all_breath_data, param):
"""
Calculates the mode value for a given breath parameter (e.g., depth, length, inhale duration) from the breath dataset.
Parameters
----------
all_breath_data : list of dict
A list of dictionaries, where each dictionary contains the features of a single breath.
param : str
The name of the breath parameter for which to calculate the mode (e.g., 'depth', 'length', 'inhale', 'exhale').
Returns
-------
mode_value : float
The mode value for the specified breath parameter, calculated using a histogram-based approach.
Side Effects
------------
This function has no side effects.
"""
values = [breath[param] for breath in all_breath_data]
non_zero_values = [v for v in values if v != 0]
if len(non_zero_values) == 0:
return 0.0
hist, bin_edges = np.histogram(non_zero_values, bins=50)
max_count = np.max(hist)
max_bins = np.where(hist == max_count)[0]
if len(max_bins) > 1:
mean_value = np.mean(values)
closest_bin = min(max_bins, key=lambda b: abs((bin_edges[b] + bin_edges[b + 1]) / 2 - mean_value))
mode_upper_bin = closest_bin
else:
mode_upper_bin = np.argmax(hist)
mode_depth = (bin_edges[mode_upper_bin] + bin_edges[mode_upper_bin + 1]) / 2
return mode_depth
def calculate_mode_and_avg_features(all_breath_data):
"""
Calculates the average and mode values for breath characteristics (depth, length, inhale duration,
exhale duration) from the breath dataset.
Parameters
----------
all_breath_data : list of dict
A list of dictionaries, where each dictionary contains the features of a single breath.
Returns
-------
avg_values : dict
A dictionary containing the average values for breath characteristics (depth, length, inhale duration,
exhale duration).
mode_values : dict
A dictionary containing the mode values for breath characteristics (depth, length, inhale duration,
exhale duration).
Side Effects
------------
This function has no side effects.
"""
rounding_precision = 10
avg_values = {
"avg_depth": round(np.mean([breath['depth'] for breath in all_breath_data]), rounding_precision),
"avg_length": round(np.mean([breath['length'] for breath in all_breath_data]), rounding_precision),
"avg_inhale": round(np.mean([breath['inhale'] for breath in all_breath_data]), rounding_precision),
"avg_inspiratory_pause": round(np.mean([breath['inspiratory_pause'] for breath in all_breath_data]), rounding_precision),
"avg_exhale": round(np.mean([breath['exhale'] for breath in all_breath_data]), rounding_precision),
"avg_expiratory_pause": round(np.mean([breath['expiratory_pause'] for breath in all_breath_data]), rounding_precision),
}
mode_values = {
"mode_depth": round(get_mode_param(all_breath_data, 'depth'), rounding_precision),
"mode_length": round(get_mode_param(all_breath_data, 'length'), rounding_precision),
"mode_inhale": round(get_mode_param(all_breath_data, 'inhale'), rounding_precision),
"mode_inspiratory_pause": round(get_mode_param(all_breath_data, 'inspiratory_pause'), rounding_precision),
"mode_exhale": round(get_mode_param(all_breath_data, 'exhale'), rounding_precision),
"mode_expiratory_pause": round(get_mode_param(all_breath_data, 'expiratory_pause'), rounding_precision),
}
return avg_values, mode_values
def create_data_profiles():
"""
Creates data profiles for each person in the analyzed dataset (./results) by processing their respective files
and calculating a set of characteristics.
Parameters
----------
None
Returns
-------
people_profiles : dict
A dictionary where each key is a person's identifier (e.g., initials) and the value is another dictionary containing:
- avg_values: A dictionary of average breath characteristics (depth, length, inhale duration, exhale duration).
- mode_values: A dictionary of mode breath characteristics (depth, length, inhale duration, exhale duration).
- mode_breaths_weights: A list of weights corresponding to the selected mode breaths.
- mode_breaths: A list of dictionaries containing the signal, timestamps and features of mode breaths for that person.
Side Effects
------------
This function has no side effects.
"""
files = [file.name for file in os.scandir('./results')]
people_files = dict()
people_profiles = dict()
for file in files:
if pathlib.Path(file).suffix != '.jsonl':
continue
person = file.split("_")[3]
if person not in people_files:
people_files[person] = []
people_files[person].append(file)
for person in people_files:
people_profiles[person] = {}
target_adc_all_breath_data = calculate_breath_characteristics(people_files[person])
avg_values, mode_values = calculate_mode_and_avg_features(target_adc_all_breath_data)
mode_breaths, mode_breaths_weights = get_mode_breaths(target_adc_all_breath_data, mode_values, avg_values, people_files[person])
people_profiles[person] = {
"avg_values": avg_values,
"mode_values": mode_values,
"mode_breaths_weights": mode_breaths_weights,
"mode_breaths": mode_breaths
}
return people_profiles
def plot_mode_breath_on_file(mode_breath, target_adc = TARGET_ADC):
file_name = mode_breath['file_name']
file_path = f'./results/{file_name}'
with open(file_path, 'r') as f:
file_lines = f.read().strip().split("\n")
timestamps = []
adc_signals = [[] for _ in range(5)]
for line in file_lines:
if line:
timestamp, adc_values = parse_jsonl_line(line)
timestamps.append(timestamp)
for i in range(5):
adc_signals[i].append(adc_values[i])
mode_timestamps = mode_breath['timestamps']
mode_signal = mode_breath['signal']
plt.figure(figsize=(14, 7))
plt.plot(timestamps, adc_signals[target_adc], label='Full Signal', color='blue', linewidth=1)
plt.plot(mode_timestamps, mode_signal, label='Mode Breath', color='red', linewidth=2.5, alpha=0.8)
plt.title(f'Mode Breath Highlighted on File: {file_name}')
plt.xlabel('Time (ms)')
plt.ylabel('ADC Voltage')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
# plt.savefig(f'./results/mode_breath_{file_name.replace(".jsonl", ".png")}')
plt.show()
def group_plot_mode_breaths(people_profiles):
retimed_breaths_for_people = {}
for person in people_profiles:
mode_breaths_target_adc = people_profiles[person]["mode_breaths"][TARGET_ADC]
if mode_breaths_target_adc is None:
continue
mode_breath = mode_breaths_target_adc[0]
signal = mode_breath['signal']
timestamps = mode_breath['timestamps']
timestamps = [t - timestamps[0] for t in timestamps]
retimed_breaths_for_people[person] = (timestamps, signal)
plt.figure(figsize=(14, 7))
for person, (timestamps, signal) in retimed_breaths_for_people.items():
plt.plot(timestamps, signal, label=f'Mode Breath - {person}', linewidth=2.0, alpha=0.8)
plt.title('Mode Breaths for All People')
plt.xlabel('Time (ms)')
plt.ylabel('ADC Voltage')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
# plt.savefig(f'./results/mode_breaths_all_people.png')
plt.show()
def plot_profiles(profiles):
"""
Creates a plot for data from features displaying an approximated breath
profile calculated from features.
Parameters
----------
profiles : a dictionary where the keys are people tags and the value is a dictionary with
the mode values shown below
- "bpm_mode"
- "breath_depth_mode"
- "inhale_length_mode"
- "ip_length_mode"
- "exhale_length_mode"
- "ep_length_mode"
Returns
-------
None
Side Effects
------------
This function has no side effects.
"""
length = len(profiles)
fig, ax = plt.subplots(length, 1)
i = 0
no_of_points = 10
alpha = 0.3
total_length = 0
biggest_height = 0
for key, values in profiles.items():
biggest_height = max(biggest_height, values["breath_depth_mode"])
total_length = max(total_length, (values["inhale_length_mode"]+values["ip_length_mode"]+values["exhale_length_mode"]+values["ep_length_mode"])/1000)
for key, values in profiles.items():
bps = 1/(values["bpm_mode"]/60)
inhale_x = np.linspace(0, values["inhale_length_mode"]/1000, no_of_points)
inhale_y = [values["breath_depth_mode"] * math.sin(math.pi * 2 * inhale_x[x] / (4*values["inhale_length_mode"]/1000)) for x in range(no_of_points)]
ax[i].plot(inhale_x, inhale_y)
ax[i].add_patch(patches.Rectangle(
(0.0, 0.0), # (x,y)
values["inhale_length_mode"]/1000, # width
values["breath_depth_mode"], # height
color = "blue",
alpha = alpha)) #transparency
ip_start = values["inhale_length_mode"]/1000
ip_x = np.linspace(ip_start, ip_start+values["ip_length_mode"]/1000, no_of_points)
ip_y = [inhale_y[-1] for _ in ip_x]
ax[i].plot(ip_x, ip_y)
ax[i].add_patch(patches.Rectangle(
(ip_x[0], 0.0), # (x,y)
values["ip_length_mode"]/1000, # width
values["breath_depth_mode"], # height
color = "orange",
alpha = alpha)) #transparency
exhale_start = ip_start+values["ip_length_mode"]/1000
exhale_x = np.linspace(0, values["exhale_length_mode"]/1000, no_of_points)
exhale_y = [values["breath_depth_mode"] * math.cos(math.pi * 2 * exhale_x[x] / (4*values["exhale_length_mode"]/1000)) for x in range(no_of_points)]
exhale_x += exhale_start
ax[i].add_patch(patches.Rectangle(
(exhale_x[0], 0.0), # (x,y)
values["exhale_length_mode"]/1000, # width
values["breath_depth_mode"], # height
color = "red",
alpha = alpha)) #transparency
ep_start = exhale_x[-1]
ep_x = np.linspace(ep_start, ep_start+values["ep_length_mode"]/1000, no_of_points)
ep_y = [exhale_y[-1] for _ in ep_x]
ax[i].plot(ep_x, ep_y)
ax[i].add_patch(patches.Rectangle(
(ep_x[0], 0.0), # (x,y)
values["ep_length_mode"]/1000, # width
values["breath_depth_mode"], # height
color = "green",
alpha = alpha)) #transparency
ax[i].plot(exhale_x, exhale_y)
ax[i].set_xlabel("time [s]")
ax[i].set_xlim(xmin=0.0, xmax=total_length)
ax[i].set_ylabel("breath_depth")
ax[i].set_ylim(ymin=0.0, ymax=biggest_height)
ax[i].set_title(key)
i += 1
fig.tight_layout(pad=0.5)
plt.show()
def create_profile_from_features(plot_enabled=False):
"""
This function creates a dictionary with appropriate mode data in a dictionary.
It then calls to plot the data
Parameters
----------
None
Returns
-------
None
Side Effects
------------
This function has no side effects.
"""
feature_data = FeatureData()
create_indices_for_features(feature_data, "./features/extracted_features.jsonl")
feature_data.features = feature_loading(feature_data)
# print(feature_data.person_indices)
people_profiles = {}
for person in feature_data.person_initials:
records = feature_data.features[feature_data.person_indices[person]]
# print(records[0])
dicts = []
for i in range(len(feature_data.person_indices[person])):
dicts.append({
"bpm": records[i][0],
"breath_depth": records[i][1],
"inhale_length": records[i][13],
"ip_length": records[i][14],
"exhale_length": records[i][15],
"ep_length": records[i][16]
})
people_profiles[person] = {
"bpm_mode": get_mode_param(dicts, "bpm"),
"breath_depth_mode": get_mode_param(dicts, "breath_depth"),
"inhale_length_mode": get_mode_param(dicts, "inhale_length"),
"ip_length_mode": get_mode_param(dicts, "ip_length"),
"exhale_length_mode": get_mode_param(dicts, "exhale_length"),
"ep_length_mode": get_mode_param(dicts, "ep_length")
}
if plot_enabled:
plot_profiles(profiles=people_profiles)
def generate_breathing_signals(profiles):
"""
Generates breathing signal for each person in the profiles dictionary by stacking randomly
(with weights) selected breaths from the person's mode breaths. For now the generated signal
is not saved anywhere.
Parameters
----------
profiles : dict
A dictionary where each key is a person's identifier (e.g., initials) and the value is another dictionary containing:
- avg_values: A dictionary of average breath characteristics (depth, length, inhale duration, exhale duration).
- mode_values: A dictionary of mode breath characteristics (depth, length, inhale duration, exhale duration).
- mode_breaths_weights: A list of weights corresponding to the selected mode breaths.
- mode_breaths: A list of dictionaries containing the signal, timestamps and features of mode breaths for that person.
Returns
-------
None
Side Effects
------------
This function has no side effects.
"""
for person, profile in profiles.items():
breath_connect_points = []
mode_breaths = profile["mode_breaths"]
breath_length_time = mode_breaths[TARGET_ADC][0]["timestamps"][-1] - mode_breaths[TARGET_ADC][0]["timestamps"][0]
mode_breaths_weights = profile["mode_breaths_weights"]
breaths_per_set_time = math.floor(SIM_MINUTES_COUNT*60*1000 / breath_length_time)
generated_signal = [[] for _ in range(ADC_COUNT)]
generated_timestamps = []
total_time = 0
for _ in range(breaths_per_set_time):
rand_breath = random.choices(list(range(MODE_BREATH_COUNT)), weights=mode_breaths_weights)[0]
target_timestamps = mode_breaths[TARGET_ADC][rand_breath]["timestamps"]
generated_timestamps += [t - target_timestamps[0] + total_time for t in target_timestamps]
total_time += (target_timestamps[-1] - target_timestamps[0])
total_time += (target_timestamps[-1] - target_timestamps[-2]) # we need to simulate some time between breaths, otherwise we get overlapping signals
breath_connect_points.append(len(generated_timestamps))
for adc in range(ADC_COUNT):
generated_signal[adc] += mode_breaths[adc][rand_breath]["signal"]
# plt.figure(figsize=(14, 7))
# for adc in range(ADC_COUNT):
# plt.plot(generated_timestamps, generated_signal[adc], label=f'Generated Breathing Signal - ADC {adc}', alpha=0.5)
# plt.scatter(generated_timestamps, generated_signal[adc], label=f'Generated Breathing Signal - ADC {adc}', alpha=0.5)
# plt.plot(generated_timestamps, generated_signal[0], label=f'Generated Breathing Signal - {person}', linewidth=2.0, alpha = 0.5, color="red")
# plt.title(f"generated breathing signal - {person}")
# Smoothing out the connections between breaths
interp_margin = 5
breath_connect_points = breath_connect_points[:-1]
for adc in range(ADC_COUNT):
for i in range(len(breath_connect_points)):
start_idx = breath_connect_points[i] - interp_margin
end_idx = breath_connect_points[i] + interp_margin
if end_idx >= len(generated_timestamps):
end_idx = len(generated_timestamps) - 1
x = generated_timestamps[start_idx:end_idx]
y = generated_signal[adc][start_idx:end_idx]
f = spi.make_splrep(x, y, k=3, s=10)
for j in range(start_idx, end_idx):
generated_signal[adc][j] = f(generated_timestamps[j])
plt.figure(figsize=(14, 7))
for adc in range(ADC_COUNT):
plt.plot(generated_timestamps, generated_signal[adc], label=f'Generated Breathing Signal - ADC {adc}', alpha=0.5)
plt.scatter(generated_timestamps, generated_signal[adc], label=f'Generated Breathing Signal - ADC {adc}', alpha=0.5)
# plt.plot(generated_timestamps, generated_signal[0], label=f'Generated Breathing Signal - {person}', linewidth=2.0, alpha=0.5, color="blue")
plt.title(f"breathing signal gen - {person}")
plt.show()
def create_breathing_animation(plot_enabled: bool):
pass
# load clean files
# ---------------
# create separate subplots for each person
# ---------------
# animate them according to data
def main():
gen = input("Signal generation: 0/1\n")
plot = input("Plotting: 0/1\n")
plot_enabled = plot == "1"
gen_enabled = gen == "1"
people_profiles = create_data_profiles()
if plot_enabled:
plt.figure(figsize=(14, 7))
for person in people_profiles:
random_color = np.random.rand(3)
# target_adc_breaths = people_profiles[person]["mode_breaths"][TARGET_ADC]
for breath in people_profiles[person]["mode_breaths"][TARGET_ADC]:
first_timestamp = breath['timestamps'][0]
temp_timestamps = [t - first_timestamp for t in breath['timestamps']]
plt.plot(temp_timestamps, breath['signal'], alpha=0.8, color=random_color)
plt.title(f'Mode Breaths - {person}')
plt.xlabel('Time (ms)')
plt.ylabel('ADC Voltage')
plt.show()
for person in people_profiles:
plot_mode_breath_on_file(people_profiles[person]["mode_breaths"][TARGET_ADC][0], TARGET_ADC)
group_plot_mode_breaths(people_profiles)
if gen_enabled:
generate_breathing_signals(people_profiles)
create_profile_from_features(plot_enabled)
create_breathing_animation(plot_enabled)
if __name__ == "__main__":
main()