-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol_widget.py
1195 lines (985 loc) · 45.8 KB
/
protocol_widget.py
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
# Author: William Liu <liwi@ohsu.edu>
from PySide6.QtWidgets import (QWidget, QLabel, QPushButton, QMessageBox, QComboBox, QGridLayout,
QFileDialog, QLineEdit, QRadioButton)
from PySide6.QtCore import Slot, Signal, Qt, QTimer
from graph_viewer import BaselineGraphDialog, StepGraphDialog
import numpy as np
from scipy.signal import find_peaks
import csv
from datetime import datetime
import os.path
import consts
def get_mediolateral_force(data: list) -> list:
"""Extract the force along the x axis (mediolateral) and return it.
Parameters
----------
data : list
list of raw data for all channels
Returns
-------
list
list of force data along the x axis
"""
return [row[consts.FX] for row in data]
def calculate_force_delta(force: list) -> np.ndarray:
"""Calculate the change in force relative to quiet stance.
The relative change of force is found by subtracting the mean of the force
during quiet stance from the force values.
Parameters
----------
force : list
a list of time-series force data along a single axis
Returns
-------
np.ndarray
an array of time-series force data, corrected for quiet stance
"""
quiet_stance = force[:consts.QUIET_STANCE_DURATION]
force_during_quiet_stance = np.mean(quiet_stance)
return np.array([f - force_during_quiet_stance for f in force])
def calculate_center_of_pressure(fx, fy, fz, mx, my) -> tuple:
"""Calculate the center of pressure (CoP).
Parameters
----------
fx : float
the force along the x axis
fy : float
the force along the y axis
fz : float
the force along the z axis
mx : float
the moment about the x axis
my : float
the moment about the y axis
Returns
-------
tuple
(x coordinate of the CoP, y coordinate of the CoP)
"""
cop_x = (-1) * ((my + (consts.ZOFF * fx)) / fz)
cop_y = ((mx - (consts.ZOFF * fy)) / fz)
return cop_x, cop_y
def create_csv_export(
datetime_of_export: str,
patient_id: str,
step_data: list,
quiet_stance_data: list = None,
**kwargs
) -> list:
"""Save data from a step trial as a .csv file.
Parameters
----------
datetime_of_export : str
string representing the date/time the export was generated
patient_id : str
patient identifier
step_data : list
data recorded during a step trial
quiet_stance_data : list, optional
data recorded during the quiet stance that precedes a step trial
**kwargs
additional rows to add to the export file
"""
export = [
["DateTimeOfExport", datetime_of_export],
["PatientID", patient_id],
]
for label, value in kwargs.items():
export.append([label, value])
export.append(
['Fx (N)', 'Fy (N)', 'Fz (N)',
'Mx (N/m)', 'My (N/m)', 'Mz (N/m)',
'EMG_Tibialis (V)', 'EMG_Soleus (V)',
'CoPx (m)', 'CoPy (m)', 'Stim']
)
if quiet_stance_data is None:
full_trial_data = step_data
else:
full_trial_data = [*quiet_stance_data, *step_data]
for row in full_trial_data:
CoPx, CoPy = calculate_center_of_pressure(
row[consts.FX], row[consts.FY], row[consts.FZ], row[consts.MX], row[consts.MY]
)
new_row = [
row[consts.FX], row[consts.FY], row[consts.FZ],
row[consts.MX], row[consts.MY], row[consts.MZ],
row[consts.EMG_1], row[consts.EMG_2], CoPx, CoPy, row[consts.STIM]
]
export.append(new_row)
return export
def demographics_warning(parent: QWidget) -> None:
"""Opens a pop-up to warn that patient demographics have not been saved.
Parameters
----------
parent : QWidget
a parent widget for this pop-up
"""
message_box = QMessageBox(parent=parent)
message_box.setWindowTitle("Warning!")
message_box.setText(
"Patient ID and Foot Measurements have not been saved.\n"
"Before proceeding you must enter a Patient ID and Foot Measurements."
)
message_box.setIcon(QMessageBox.Warning)
message_box.setStandardButtons(QMessageBox.Ok)
message_box.exec()
def data_streaming_warning(parent: QWidget) -> None:
"""Opens a pop-up to warn that the data is not streaming from the DAQ.
Parameters
----------
parent : QWidget
a parent widget for this pop-up
"""
message_box = QMessageBox(parent=parent)
message_box.setWindowTitle("Warning!")
message_box.setText(
"Click the Record button to start data stream, then proceed with\n"
"the data collection."
)
message_box.setIcon(QMessageBox.Warning)
message_box.setStandardButtons(QMessageBox.Ok)
message_box.exec()
def directory_not_set_warning(parent: QWidget) -> None:
"""Opens a pop-up to warn that the export directory has not been set.
Parameters
----------
parent : QWidget
a parent widget for this pop-up
"""
message_box = QMessageBox(parent=parent)
message_box.setWindowTitle("Warning!")
message_box.setText(
"Cannot proceed with data collection until the export directory\n"
"has been set."
)
message_box.setIcon(QMessageBox.Warning)
message_box.setStandardButtons(QMessageBox.Ok)
message_box.exec()
def generate_filename(patient_id, trial_type, stimulator_setup, medication, vibrotactile, trial_num) -> str:
"""Create a standard filename based on info collected from the user.
Parameters
----------
patient_id : str
a de-identified patient code
trial_type : str
the type of trial that was collected
stimulator_setup : str
the configuration of the stimulator(s) used for a trial
medication : str
a string, whehter patient is ON PD meds or not
vibrotactile : bool
a bool describing whether vibrotactile stimulation was used
trial_num : int
an int representing the trial number
"""
if trial_type == "Step Trial":
trial = "step"
else:
trial = "stand"
if stimulator_setup == "None":
stimulator_setup = False
elif stimulator_setup == "Conditioned":
stimulator_setup = "cond"
elif stimulator_setup == "Test":
stimulator_setup = "test"
if medication == "On":
medication = "on"
else:
medication = False
if vibrotactile:
vibrotactile = "vibro"
else:
vibrotactile = False
if not stimulator_setup and not vibrotactile and not medication:
return f"{patient_id}_{trial}_{trial_num}.csv"
elif not stimulator_setup and not vibrotactile:
return f"{patient_id}_{trial}_{medication}_{trial_num}.csv"
elif not stimulator_setup and not medication:
return f"{patient_id}_{trial}_{vibrotactile}_{trial_num}.csv"
elif not vibrotactile and not medication:
return f"{patient_id}_{trial}_{stimulator_setup}_{trial_num}.csv"
elif not stimulator_setup:
return f"{patient_id}_{trial}_{medication}_{vibrotactile}_{trial_num}.csv"
elif not medication:
return f"{patient_id}_{trial}_{stimulator_setup}_{vibrotactile}_{trial_num}.csv"
elif not vibrotactile:
return f"{patient_id}_{trial}_{stimulator_setup}_{medication}_{trial_num}.csv"
else:
return f"{patient_id}_{trial}_{stimulator_setup}_{medication}_{vibrotactile}_{trial_num}.csv"
class ProtocolWidget(QWidget):
"""Sidebar with buttons that control data collection and display progress.
Attributes
----------
disable_record_button_signal : PySide6.QtCore.Signal
a signal to disable the recording button
enable_record_button_signal : PySide6.QtCore.Signal
a signal to enable the recording button
connect_signal : PySide6.QtCore.Signal
a signal that connects this widget to the data stream from the DAQ
disconnect_signal : PySide6.QtCore.Signal
a signal that disconnects this widget from the data stream
stimulus_signal : PySide6.QtCore.Signal
a signal that indicates when a stimulus should be provided
"""
disable_record_button_signal = Signal()
enable_record_button_signal = Signal()
connect_signal = Signal(str)
disconnect_signal = Signal(str)
stimulus_signal = Signal()
def __init__(self, parent: QWidget) -> None:
super().__init__(parent=parent)
# Initiate variable to store the baseline data
self.baseline_data = dict()
self.incoming_data_storage = list()
self.quiet_stance_data = list()
# Initiate a variable to store whether the DAQ is streaming or not
self.data_is_streaming = False
# Initiate variables to store whether an APA has been detected
self.APA_detected = False
# Initiate variable to store number of stims during standing trial
self.number_of_stims_standing = 0
# Initiate variables to store patient demographics
self.patient_id = None
self.patient_right_foot_measurement = None
self.patient_left_foot_measurement = None
self.patient_malleolus_measurement = None
self.demographics_saved = False
# Create the parent layout
layout = QGridLayout()
# Create layout for entering patient info
patient_info_layout = QGridLayout()
# Create layout for the baseline buttons
baseline_layout = QGridLayout()
# Create a layout for the threshold buttons
threshold_layout = QGridLayout()
# Create a layout for the trial buttons
trial_layout = QGridLayout()
# Populate the layout
layout.addLayout(patient_info_layout, 0, 0)
layout.addLayout(baseline_layout, 1, 0)
layout.addLayout(threshold_layout, 2, 0)
layout.addLayout(trial_layout, 3, 0)
# Populate the baseline and threshold layouts
self._create_patient_info_layout(patient_info_layout)
self._create_baseline_layout(baseline_layout)
self._create_threshold_layout(threshold_layout)
self._create_trial_layout(trial_layout)
self.setLayout(layout)
self.setFixedWidth(300)
def _create_patient_info_layout(self, layout: QGridLayout) -> None:
"""Create the layout for entering patient info
Parameters
----------
layout : PySide6.QtWidgets.QGridLayout
an empty grid layout
"""
self.set_directory_btn = QPushButton("Set Export Location", parent=self)
self.set_directory_btn.clicked.connect(self._set_directory_button_clicked)
self.export_directory = "" # Initialize to empty
self.current_directory_label = QLabel("No working directory has been set", parent=self)
self.current_directory_label.setScaledContents(True)
self.current_directory_label.setWordWrap(True)
self.patient_id_entry = QLineEdit(parent=self)
self.patient_id_entry.setPlaceholderText("Enter ID here")
patient_id_label = QLabel("Patient ID", parent=self)
patient_id_label.setFont(consts.DEFAULT_FONT)
self.right_foot_size_entry = QLineEdit(parent=self)
self.right_foot_size_entry.setPlaceholderText("Enter right foot measurement here")
right_foot_size_label = QLabel("Right foot (cm)", parent=self)
right_foot_size_label.setFont(consts.DEFAULT_FONT)
self.left_foot_size_entry = QLineEdit(parent=self)
self.left_foot_size_entry.setPlaceholderText("Enter left foot measurement here")
left_foot_size_label = QLabel("Left foot (cm)", parent=self)
left_foot_size_label.setFont(consts.DEFAULT_FONT)
self.malleolus_distance_entry = QLineEdit(parent=self)
self.malleolus_distance_entry.setPlaceholderText("Enter distance to malleolus here")
malleolus_distance_label = QLabel("Malleolus distance (cm)", parent=self)
malleolus_distance_label.setFont(consts.DEFAULT_FONT)
# Create a combobox to select medication status
self.medication_select_combobox = QComboBox(parent=self)
self.medication_select_combobox.addItems(["Off", "On"])
self.medication_select_combobox.currentTextChanged.connect(self._set_medication_status)
self._set_medication_status(self.medication_select_combobox.currentText())
self.store_demographics_button = QPushButton(parent=self, text="Store Patient Info")
self.store_demographics_button.setCheckable(True)
self.store_demographics_button.setChecked(True)
self.store_demographics_button.clicked.connect(self._demographics_button_clicked)
layout.addWidget(self.set_directory_btn, 0, 0, 1, 2, Qt.AlignBottom)
layout.addWidget(self.current_directory_label, 1, 0, 1, 2, Qt.AlignTop)
layout.addWidget(patient_id_label, 2, 0)
layout.addWidget(self.patient_id_entry, 2, 1)
layout.addWidget(right_foot_size_label, 3, 0)
layout.addWidget(self.right_foot_size_entry, 3, 1)
layout.addWidget(left_foot_size_label, 4, 0)
layout.addWidget(self.left_foot_size_entry, 4, 1)
layout.addWidget(malleolus_distance_label, 5, 0)
layout.addWidget(self.malleolus_distance_entry, 5, 1)
layout.addWidget(self.medication_select_combobox, 6, 0, 1, 2)
layout.addWidget(self.store_demographics_button, 7, 0, 1, 2)
def _create_baseline_layout(self, layout: QGridLayout) -> None:
"""Create buttons for baseline collection, add them to a layout.
Parameters
----------
layout : PySide6.QtWidgets.QGridLayout
an empty grid layout
"""
self.start_baseline_button = QPushButton(self, text="Start baseline collection")
self.start_baseline_button.setEnabled(False)
self.start_baseline_button.clicked.connect(self._start_baseline_button_clicked)
self.stop_baseline_button = QPushButton(self, text="Stop baseline collection")
self.stop_baseline_button.setEnabled(False)
self.stop_baseline_button.clicked.connect(self._stop_baseline_button_clicked)
self.collect_baseline_button = QPushButton(self, text="Collect a step")
self.collect_baseline_button.setEnabled(False)
self.collect_baseline_button.clicked.connect(self._collect_baseline_button_clicked)
self.finish_baseline_button = QPushButton(parent=self, text="Finish step")
self.finish_baseline_button.setEnabled(False)
self.finish_baseline_button.clicked.connect(self._finish_baseline_button_clicked)
# Create a label to keep track of the number of baseline trials
self.baseline_trial_counter = 0
self.baseline_trial_counter_label = QLabel(parent=self)
self.baseline_trial_counter_label.setFont(consts.DEFAULT_FONT)
self.baseline_trial_counter_label.setWordWrap(True)
self._update_baseline_trial_counter_label()
layout.addWidget(self.start_baseline_button, 0, 0)
layout.addWidget(self.stop_baseline_button, 0, 1)
layout.addWidget(self.collect_baseline_button, 1, 0, 1, 2)
layout.addWidget(self.finish_baseline_button, 2, 0, 1, 2)
layout.addWidget(self.baseline_trial_counter_label, 3, 0, 1, 2, Qt.AlignTop)
def _create_threshold_layout(self, layout: QGridLayout) -> None:
"""Create buttons for setting/displaying APA threshold.
Parameters
----------
layout : PySide6.QtWidgets.QGridLayout
an empty grid layout
"""
# ComboBox for specifying % threshold
self.threshold_percentage_entry = QComboBox(parent=self)
self.threshold_percentage_entry.addItems([str(i) for i in range(1, 51)])
self.threshold_percentage_entry.currentTextChanged.connect(self._set_APA_threshold)
self.threshold_percentage = int(self.threshold_percentage_entry.currentText()) # Initialize a default value
# Label for the ComboBox
self.threshold_percentage_label = QLabel(parent=self)
self.threshold_percentage_label.setFont(consts.DEFAULT_FONT)
self.threshold_percentage_label.setWordWrap(True)
self.threshold_percentage_label.setText(
"Select a % for the threshold:"
)
# Label for tracking the APA threshold
self.threshold = None
self.threshold_label = QLabel(parent=self)
self.threshold_label.setFont(consts.DEFAULT_FONT)
self.threshold_label.setWordWrap(True)
self._update_APA_threshold_label()
layout.addWidget(self.threshold_percentage_entry, 0, 3)
layout.addWidget(self.threshold_percentage_label, 0, 0, 1, 2)
layout.addWidget(self.threshold_label, 1, 0, 1, 2, Qt.AlignTop)
def _create_trial_layout(self, layout: QGridLayout) -> None:
"""Add widgets to the trial layout.
Parameters
----------
layout : PySide6.QtWidgets.QGridLayout
an empty grid layout
"""
# Create combobox to select type of trial
self.trial_select_combobox = QComboBox(parent=self)
self.trial_select_combobox.addItems(["Standing Trial", "Step Trial"])
self.trial_select_combobox.currentTextChanged.connect(self._set_trial_type)
# Create combobox to select Virbotactile/No Vibrotactile
self.vibrotactile_combobox = QComboBox(parent=self)
self.vibrotactile_combobox.addItems(["With Vibrotactile", "Without Vibrotactile"])
self.vibrotactile_combobox.currentTextChanged.connect(self._set_vibrotactile)
# Create a label for specifying stimulator setup
stimulator_setup_label = QLabel("Stimulator Setup", parent=self)
stimulator_setup_label.setFont(consts.DEFAULT_FONT)
# Create buttons to select stimulation paradigm
self.no_stimulus_btn = QRadioButton("None", self)
self.no_stimulus_btn.toggled.connect(self._no_stimulus_btn_toggled)
self.test_stimulus_btn = QRadioButton("Test", self)
self.test_stimulus_btn.toggled.connect(self._test_stimulus_btn_toggled)
self.conditioned_stimulus_btn = QRadioButton("Conditioned", self)
self.conditioned_stimulus_btn.toggled.connect(self._conditioned_stimulus_btn_toggled)
self.no_stimulus_btn.toggle()
# Initialize the trial type and vibrotactile condition
self._set_trial_type(self.trial_select_combobox.currentText())
self._set_vibrotactile(self.vibrotactile_combobox.currentText())
# Create buttons for starting/stopping the protocol
self.start_trial_button = QPushButton(parent=self, text="Start Trial")
self.start_trial_button.setEnabled(False)
self.start_trial_button.clicked.connect(self._start_trial_button_clicked)
self.stop_trial_button = QPushButton(parent=self, text="Stop Trial")
self.stop_trial_button.setEnabled(False)
self.stop_trial_button.clicked.connect(self._stop_trial_button_clicked)
# Create label to track number of collected trials
self.trial_counter = 0
self.trial_counter_label = QLabel(parent=self)
self.trial_counter_label.setFont(consts.DEFAULT_FONT)
self._update_trial_counter_label()
# Create a button to reset the trial counter
self.reset_trial_counter = QPushButton(parent=self, text="Reset Trial Counter")
self.reset_trial_counter.clicked.connect(self._reset_trial_counter)
# Add widgets to the layout
layout.addWidget(self.trial_select_combobox, 0, 0, 1, 3)
layout.addWidget(self.vibrotactile_combobox, 1, 0, 1, 3)
layout.addWidget(stimulator_setup_label, 2, 0, 1, 3)
layout.addWidget(self.no_stimulus_btn, 3, 0, 1, 1)
layout.addWidget(self.test_stimulus_btn, 3, 1, 1, 1)
layout.addWidget(self.conditioned_stimulus_btn, 3, 2, 1, 1)
layout.addWidget(self.start_trial_button, 4, 0, 1, 3)
layout.addWidget(self.stop_trial_button, 5, 0, 1, 3)
layout.addWidget(self.trial_counter_label, 6, 0, 1, 3)
layout.addWidget(self.reset_trial_counter, 7, 0, 1, 3)
def _update_baseline_trial_counter_label(self) -> None:
self.baseline_trial_counter_label.setText(
f"Number of baseline trials collected: {self.baseline_trial_counter}"
)
def _update_APA_threshold_label(self) -> None:
if self.threshold is None:
self.threshold_label.setText("No baseline threshold set")
else:
self.threshold_label.setText(f"APA Threshold: {round(self.threshold, 4)}")
def _update_trial_counter_label(self) -> None:
self.trial_counter_label.setText(
f"Number of trials collected: {self.trial_counter}"
)
@Slot()
def _set_directory_button_clicked(self) -> None:
""""""
self.export_directory = QFileDialog.getExistingDirectory(
parent=self,
caption="Select a folder where the data will be saved.",
dir=os.path.expanduser("~"),
options=QFileDialog.ShowDirsOnly
)
if not self.export_directory == "":
self.current_directory_label.setText(f"Directory set as: {self.export_directory}")
else:
self.current_directory_label.setText("No working directory has been set")
@Slot(bool)
def _demographics_button_clicked(self, check_state: bool) -> None:
"""Handle when user clicks `store_demographics_button`.
If user has not entered both a Patient ID and the Foot Measurement then
show a pop-up warning message telling them to do so. They will not be
able to collect any data (including baseline data) until they do so.
Parameters
----------
check_state : bool
the check state of the `store_demographics_button`
"""
# Get entry from the text boxes, remove whitespace at beginning and end
self.patient_id = self.patient_id_entry.text().strip()
self.patient_right_foot_measurement = self.right_foot_size_entry.text().strip()
self.patient_left_foot_measurement = self.left_foot_size_entry.text().strip()
self.patient_malleolus_measurement = self.malleolus_distance_entry.text().strip()
if check_state:
self.store_demographics_button.setText("Store Patient Info")
else:
if (
self.patient_id == "" or
self.patient_right_foot_measurement == "" or
self.patient_left_foot_measurement == "" or
self.patient_malleolus_measurement == ""
):
demographics_warning(self)
self.store_demographics_button.setChecked(True)
else:
self.store_demographics_button.setText("Edit Patient Info")
# Disable/enable the text entrys as appropriate
self.patient_id_entry.setEnabled(self.store_demographics_button.isChecked())
self.right_foot_size_entry.setEnabled(self.store_demographics_button.isChecked())
self.left_foot_size_entry.setEnabled(self.store_demographics_button.isChecked())
self.malleolus_distance_entry.setEnabled(self.store_demographics_button.isChecked())
self.medication_select_combobox.setEnabled(self.store_demographics_button.isChecked())
# Update the state variable to keep track of whether demographics info is saved
self.demographics_saved = not self.store_demographics_button.isChecked()
@Slot(bool)
def toggle_baseline_buttons(self, check_state: bool) -> None:
self.start_baseline_button.setEnabled(check_state)
self.stop_baseline_button.setEnabled(check_state)
self.data_is_streaming = check_state
@Slot()
def _start_baseline_button_clicked(self):
"""Open blocking message when the user starts baseline APA collection.
Window prompts user to Hardware Zero the force platform. User can also
cancel the baseline collection.
"""
if self.demographics_saved:
message_box = QMessageBox(self)
message_box.setWindowTitle("Attention!")
message_box.setText(
"Instruct patient to step off the platform,\n"
"then hit the Auto-Zero button on the amplifier.\n"
"When you have done this click OK.")
message_box.setIcon(QMessageBox.Information)
message_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
button = message_box.exec()
if button == QMessageBox.Ok:
self.disable_record_button_signal.emit()
self.stop_baseline_button.setEnabled(True)
self.collect_baseline_button.setEnabled(True)
self.start_baseline_button.setEnabled(False)
self.start_trial_button.setEnabled(False)
self.store_demographics_button.setEnabled(False)
else:
demographics_warning(self)
@Slot()
def _stop_baseline_button_clicked(self):
"""Opens dialog for user to stop baseline collection, if they choose.
Pop-up message box will allow user to save any previously collected
baseline trials. If no baseline data has been collected user is given
the choice to stop baseline collection or continue.
"""
message_box = QMessageBox()
message_box.setWindowTitle("Stop baseline collection?")
message_box.setIcon(QMessageBox.Information)
if self.baseline_data:
message_box.setText(
f"Number of pending baseline trials: {self.baseline_trial_counter}"
)
message_box.setInformativeText("Do you want to save these trials?")
message_box.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
message_box.setDefaultButton(QMessageBox.Save)
else:
message_box.setText("You have not collected any baseline trials")
message_box.setInformativeText("Do you want to stop baseline collection?")
message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
message_box.setDefaultButton(QMessageBox.Yes)
ret = message_box.exec()
if ret == QMessageBox.Discard:
self.baseline_data.clear()
self.baseline_trial_counter = 0
self._update_baseline_trial_counter_label()
self.threshold = None # Clear any previously set APA threshold
self._update_APA_threshold_label()
self.start_trial_button.setEnabled(False)
elif ret == QMessageBox.Save:
if self.threshold is None:
self._set_APA_threshold(self.threshold_percentage_entry.currentText())
self.start_trial_button.setEnabled(True)
if ret in {QMessageBox.Discard, QMessageBox.Save, QMessageBox.Yes}:
self.start_baseline_button.setEnabled(True)
self.stop_baseline_button.setEnabled(False)
self.collect_baseline_button.setEnabled(False)
self.store_demographics_button.setEnabled(True)
self.enable_record_button_signal.emit()
@Slot()
def _collect_baseline_button_clicked(self):
if self.demographics_saved:
self.collect_baseline_button.setEnabled(False)
self.stop_baseline_button.setEnabled(False)
self._collect_quiet_stance("baseline")
else:
demographics_warning(self)
@Slot()
def _finish_baseline_button_clicked(self):
self.disconnect_signal.emit("baseline")
self.collect_baseline_button.setEnabled(True)
self.finish_baseline_button.setEnabled(False)
self.stop_baseline_button.setEnabled(True)
# Open the Graph Dialog
self._show_baseline_graph()
def _show_baseline_graph(self):
"""Display the mediolateral force data from the most recent trial.
Open a dialog window with a graph of the lateral CoP position vs. time.
User can choose to save the trial or discard it, depending on how the
graph looks.
"""
mediolateral_force = get_mediolateral_force(self.incoming_data_storage)
corrected_mediolateral_force = calculate_force_delta(mediolateral_force)
peaks, _ = find_peaks(corrected_mediolateral_force, height=10, prominence=10)
valleys, _ = find_peaks(-corrected_mediolateral_force, height=10, prominence=10)
graph_dialog = BaselineGraphDialog(corrected_mediolateral_force, peaks, valleys, parent=self)
graph_dialog.open()
graph_dialog.finished.connect(
lambda result: self._handle_baseline_trial(result, corrected_mediolateral_force, peaks, valleys)
)
@Slot(int)
def _handle_baseline_trial(
self,
result: int,
corrected_mediolateral_force: np.ndarray,
peaks: np.ndarray,
valleys: np.ndarray
):
"""Save/discard the most recent baseline trial, based on user selection.
Parameters
----------
result : int
result code emitted when `GraphDialog` window is closed, 1 indicates
user wants to save the trial
corrected_mediolateral_force : np.ndarray
array of corrected mediolateral force data
peaks : np.ndarray
array containing indexes of peaks in mediolateral force data
valleys : np.ndarray
array containing indexes of valleys in mediolateral force data
"""
if result == 1:
self.baseline_trial_counter += 1
if self.vibrotactile_used:
file_name = f"{self.patient_id}_baseline_vibro_{self.baseline_trial_counter}"
else:
file_name = f"{self.patient_id}_baseline_{self.medication_status.lower()}_{self.baseline_trial_counter}"
fname = QFileDialog.getSaveFileName(
parent=self,
dir=os.path.join(self.export_directory, file_name),
caption="Select a location to save the data.",
filter="*.csv"
)
if fname[0] != '':
now = datetime.today().strftime("%Y%m%d-%H%M%S")
to_csv = create_csv_export(
now,
self.patient_id,
self.incoming_data_storage,
RightFootMeasurement=self.patient_right_foot_measurement,
LeftFootMeasurement=self.patient_left_foot_measurement,
MalleolusMeasurement=self.patient_malleolus_measurement,
Medication=self.medication_status
)
file = open(fname[0], 'w+', newline='')
with file:
write = csv.writer(file)
write.writerows(to_csv)
else:
self.baseline_trial_counter -= 1
# During a step there is usually a M/L force in the direction of the
# swing leg followed by a M/L force in the direction of the stance
# leg. To keep the code functional for a left or right step, look
# for whichever occurs first, a peak or a valley, then take that as
# the APA.
if peaks[0] < valleys[0]:
max_force_during_apa = corrected_mediolateral_force[peaks[0]]
else:
max_force_during_apa = corrected_mediolateral_force[valleys[0]]
self.baseline_data[f"trial {self.baseline_trial_counter}"] = max_force_during_apa
self._update_baseline_trial_counter_label()
self._set_APA_threshold(self.threshold_percentage_entry.currentText())
self.incoming_data_storage.clear()
@Slot()
def _start_trial_button_clicked(self) -> None:
if self.demographics_saved:
if self.data_is_streaming:
if not self.export_directory == "":
self.start_trial_button.setEnabled(False)
self.start_baseline_button.setEnabled(False)
self.trial_select_combobox.setEnabled(False)
self.vibrotactile_combobox.setEnabled(False)
self.no_stimulus_btn.setEnabled(False)
self.test_stimulus_btn.setEnabled(False)
self.conditioned_stimulus_btn.setEnabled(False)
self.set_directory_btn.setEnabled(False)
self.store_demographics_button.setEnabled(False)
self.threshold_percentage_entry.setEnabled(False)
self.disable_record_button_signal.emit()
if self.trial_type == "Step Trial":
self._collect_quiet_stance("quiet stance")
elif self.trial_type == "Standing Trial":
self._collect_quiet_stance("standing quiet stance")
else:
raise NameError(f"{self.trial_type} was not found.")
else:
directory_not_set_warning(self)
else:
data_streaming_warning(self)
else:
demographics_warning(self)
@Slot()
def _stop_trial_button_clicked(self) -> None:
if self.trial_type == "Step Trial":
self.disconnect_signal.emit("step")
elif self.trial_type == "Standing Trial":
if self.standing_timer.isActive():
self.standing_timer.stop()
print("Standing timer stopped prematurely", datetime.now())
self.disconnect_signal.emit("standing")
self.enable_record_button_signal.emit()
self.start_trial_button.setEnabled(True)
self.stop_trial_button.setEnabled(False)
self.start_baseline_button.setEnabled(True)
self.trial_select_combobox.setEnabled(True)
self.vibrotactile_combobox.setEnabled(True)
self.no_stimulus_btn.setEnabled(True)
self.test_stimulus_btn.setEnabled(True)
self.conditioned_stimulus_btn.setEnabled(True)
self.set_directory_btn.setEnabled(True)
self.store_demographics_button.setEnabled(True)
self.threshold_percentage_entry.setEnabled(True)
self.APA_detected = False
# Open the GraphDialog
self._show_step_graph()
def _show_step_graph(self):
"""Open a window with graphs of the data collected during a step trial.
User has the choice to save the trial or discard it, based on how the
data looks.
"""
graph_dialog = StepGraphDialog(self.incoming_data_storage, parent=self)
graph_dialog.finished.connect(self._handle_step_trial)
graph_dialog.notes_signal.connect(self._receive_collection_notes)
graph_dialog.open()
@Slot(int)
def _handle_step_trial(self, result: int):
"""Save or discard a step trial."""
if result == 1:
self.trial_counter += 1
file_name = generate_filename(
self.patient_id, self.trial_type, self.stimulator_setup,
self.medication_status, self.vibrotactile_used, self.trial_counter
)
fname = QFileDialog.getSaveFileName(
parent=self,
dir=os.path.join(self.export_directory, file_name),
caption="Select a location to save the trial.",
filter="*.csv"
)
if fname[0] != '':
now = datetime.today().strftime("%Y%m%d-%H%M%S")
to_csv = create_csv_export(
now,
self.patient_id,
self.incoming_data_storage,
self.quiet_stance_data,
Medication=self.medication_status,
RightFootMeasurement=self.patient_right_foot_measurement,
LeftFootMeasurement=self.patient_left_foot_measurement,
MalleolusMeasurement=self.patient_malleolus_measurement,
TrialType=self.trial_type,
Stimulus=self.stimulator_setup,
Vibrotactile=self.vibrotactile_used,
APAThreshold=self.threshold,
APAThresholdPercentage=self.threshold_percentage,
Notes=self.collection_notes,
)
file = open(fname[0], 'w+', newline='')
with file:
write = csv.writer(file)
write.writerows(to_csv)
else:
self.trial_counter -= 1
self._update_trial_counter_label()
del self.collection_notes
self.incoming_data_storage.clear()
self.quiet_stance_data.clear()
self.number_of_stims_standing = 0
@Slot()
def _reset_trial_counter(self) -> None:
"""Reset the trial counter."""
message_box = QMessageBox()
message_box.setWindowTitle("Reset Trial Counter?")
message_box.setIcon(QMessageBox.Warning)
message_box.setInformativeText("Are you sure you want to reset the trial counter?")
message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
message_box.setDefaultButton(QMessageBox.No)
result = message_box.exec()
if result == QMessageBox.Yes:
self.trial_counter = 0
self._update_trial_counter_label()
@Slot(str)
def _receive_collection_notes(self, notes: str) -> None:
"""Slot that receives notes entered in the step graph dialog.
Parameters
----------
notes : str
a str of user-entered notes
"""
self.collection_notes = notes
@Slot(bool)
def _no_stimulus_btn_toggled(self, checked) -> None:
"""Handle user clicking the no stimulus button.
Parameters
----------
checked : bool
bool indicating the check-state of the button
"""
if checked:
self.stimulator_setup = "None"
self.stimulus_enabled = False
@Slot(bool)
def _test_stimulus_btn_toggled(self, checked) -> None:
"""Handle the user clicking the test stimulus button.
Parameters
----------
checked : bool
bool indicating the check-state of the button
"""
if checked:
message_box = QMessageBox(self)
message_box.setWindowTitle("Attention!")
message_box.setIcon(QMessageBox.Warning)
message_box.setStandardButtons(QMessageBox.Ok)
message_box.setText(
"Make sure you disconnect the DS8R BNC cable from the delay box.\n"
"Plug the NATUS BNC cable into the top port (SYNC) on the delay box. "
"Verify BNC connections on the delay box before proceeding."
)
message_box.exec()
self.stimulator_setup = "Test"
self.stimulus_enabled = True
@Slot(bool)
def _conditioned_stimulus_btn_toggled(self, checked) -> None:
"""Handle the user clicking the conditioned stimulus button.
Parameters
----------
checked : bool
bool indicating the check-state of the button
"""
if checked:
message_box = QMessageBox(self)
message_box.setWindowTitle("Attention!")
message_box.setIcon(QMessageBox.Warning)
message_box.setStandardButtons(QMessageBox.Ok)