-
Notifications
You must be signed in to change notification settings - Fork 18
/
subDialogs.py
1860 lines (1667 loc) · 76.1 KB
/
subDialogs.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
from PyQt5 import QtGui, QtCore, uic
from PyQt5.QtWidgets import (QTableWidgetItem, QGridLayout, QGroupBox, QLineEdit,
QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QComboBox, QScrollArea,
QFileDialog, QHeaderView, QMainWindow)
import pyqtgraph as pg
import pyqtgraph.exporters as pgexp
import pyqtgraph.opengl as gl
import OpenGL.GL as ogl
from pyqtgraph.GraphicsScene import exportDialog
from ecogvis.signal_processing import bands as default_bands
from ecogvis.signal_processing.processing_data import processing_data
from ecogvis.signal_processing.periodogram import psd_estimate
from ecogvis.signal_processing.detect_events import detect_events
from .FS_colorLUT import get_lut
from threading import Event, Thread
from pynwb import NWBHDF5IO
from pynwb.epoch import TimeIntervals
import numpy as np
import os
import time
ui_path = os.path.join(os.path.dirname(__file__), '..', 'ui')
# Creates custom interval type -------------------------------------------------
Ui_CustomInterval, _ = uic.loadUiType(os.path.join(ui_path,"intervals_gui.ui"))
class CustomIntervalDialog(QtGui.QDialog, Ui_CustomInterval):
def __init__(self):
super().__init__()
self.setupUi(self)
def getResults(self):
if self.exec_() == QtGui.QDialog.Accepted:
# get all values
int_type = str(self.lineEdit_1.text())
color = str(self.comboBox.currentText())
return int_type, color
else:
return '', ''
# Warning of no High gamma data in the NWB file ------------ -------------------
class NoHighGammaDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is no high gamma data in the current NWB file.\n"+
"To calculate high gamma power traces, use button:\n"+
"High Gamma")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('No high gama data')
self.exec_()
def onAccepted(self):
self.accept()
# Warning of no High gamma data in the NWB file --------------------------------
class NoPreprocessedDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is no preprocessed data in the current NWB file.\n"+
"To generate preprocessed voltage traces, use button:\n"+
"Preprocess")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('No preprocessed data')
self.exec_()
def onAccepted(self):
self.accept()
# Warning of no Raw data in the NWB file --------------------------------
class NoRawDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is no raw data in the current NWB file.")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('No raw data')
self.exec_()
def onAccepted(self):
self.accept()
# Warning of no Trials data in the NWB file ------------------------------------
class NoTrialsDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is no trials data in the current NWB file.\n"+
"Trial times are needed to generate ERP.")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('No trial data')
self.exec_()
def onAccepted(self):
self.accept()
# Warning that Trials data already exists in the NWB file ----------------------
class ExistTrialsDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is already Trials data saved in the current NWB file.\n"+
"It is not possible to substitute it.")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('Trial data already exists')
self.exec_()
def onAccepted(self):
self.accept()
# Warning of no Audio data in the NWB file ------------------------------------
class NoAudioDialog(QtGui.QDialog):
def __init__(self):
super().__init__()
self.text = QLabel("There is no audio data in the current NWB file.")
self.okButton = QtGui.QPushButton("OK")
self.okButton.clicked.connect(self.onAccepted)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addWidget(self.okButton)
self.setLayout(vbox)
self.setWindowTitle('No audio data')
self.exec_()
def onAccepted(self):
self.accept()
# Warning of no Spectrum data in the NWB file --------------------------------
class NoSpectrumDialog(QtGui.QDialog):
def __init__(self, parent, type):
super().__init__()
self.parent = parent
self.type = type
self.val = -1
self.text = QLabel("There is no Spectrum data for "+self.type+" data in the current NWB file.\n"+
"To calculate the Power Spectral Density, click Calculate.")
self.cancelButton = QtGui.QPushButton("Cancel")
self.cancelButton.clicked.connect(lambda: self.out_close(val=-1))
self.calculateButton = QtGui.QPushButton("Calculate")
self.calculateButton.clicked.connect(self.run_estimation)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.cancelButton)
hbox.addWidget(self.calculateButton)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.text)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setWindowTitle('No Spectrum data')
self.exec_()
def run_estimation(self):
self.text.setText("Calculating the Power Spectral Density for "+self.type+" data.\n"+
"Please wait, this might take around 5 minutes.")
self.cancelButton.setEnabled(False)
self.calculateButton.setEnabled(False)
self.thread = PSDCalcFunction(self)
self.thread.finished.connect(lambda: self.out_close(val=1))
self.thread.start()
def out_close(self, val):
self.val = val
self.accept()
# Runs 'psd_estimate' function, useful to wait for thread -------------------
class PSDCalcFunction(QtCore.QThread):
def __init__(self, parent):
super().__init__()
self.parent = parent
self.data = parent.parent.model.source
self.src_file = parent.parent.file
self.type = parent.type #'raw' or 'preprocessed'
def run(self):
psd_estimate(src_file=self.src_file,
type=self.type)
# Exit confirmation ------------------------------------------------------------
Ui_Exit, _ = uic.loadUiType(os.path.join(ui_path,"exit_gui.ui"))
class ExitDialog(QtGui.QDialog, Ui_Exit):
def __init__(self, parent):
super().__init__()
self.setupUi(self)
self.pushButton_1.setEnabled(False)
self.pushButton_1.clicked.connect(self.save)
self.pushButton_2.clicked.connect(self.cancel)
self.pushButton_3.clicked.connect(self.exit)
if parent.model.unsaved_changes_annotation or parent.model.unsaved_changes_interval:
text = "There are unsaved changes in this session.\n"+ \
"Do you want to save them before exit?"
self.label.setText(text)
self.pushButton_1.setEnabled(True)
self.setWindowTitle('Exit ecogVIS')
self.exec_()
def save(self):
self.value = 1
self.accept()
def cancel(self):
self.value = 0
self.accept()
def exit(self):
self.value = -1
self.accept()
# Selects channels from specific brain regions to be plotted -------------------
class SelectChannelsDialog(QtGui.QDialog):
def __init__(self, stringlist, checked):
super().__init__()
self.model = QtGui.QStandardItemModel()
for i, string in enumerate(stringlist):
item = QtGui.QStandardItem(string)
item.setCheckable(True)
check = (QtCore.Qt.Checked if checked[i] else QtCore.Qt.Unchecked)
item.setCheckState(check)
self.model.appendRow(item)
self.listView = QtGui.QListView()
self.listView.setModel(self.model)
self.okButton = QtGui.QPushButton("OK")
self.selectButton = QtGui.QPushButton("Select All")
self.unselectButton = QtGui.QPushButton("Unselect All")
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.okButton)
hbox.addWidget(self.selectButton)
hbox.addWidget(self.unselectButton)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.listView)
#vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
#self.setLayout(layout)
self.setWindowTitle('Select Regions:')
self.okButton.clicked.connect(self.onAccepted)
self.selectButton.clicked.connect(self.select_all)
self.unselectButton.clicked.connect(self.unselect_all)
self.select_all()
self.choices = [self.model.item(i).text() for i in
range(self.model.rowCount())
if self.model.item(i).checkState()
== QtCore.Qt.Checked]
self.exec_()
def onAccepted(self):
self.choices = [self.model.item(i).text() for i in
range(self.model.rowCount())
if self.model.item(i).checkState()
== QtCore.Qt.Checked]
self.accept()
def select_all(self):
for i in range(self.model.rowCount()):
item = self.model.item(i)
item.setCheckState(QtCore.Qt.Checked)
def unselect_all(self):
for i in range(self.model.rowCount()):
item = self.model.item(i)
item.setCheckState(QtCore.Qt.Unchecked)
# Creates Spectral Analysis choice dialog --------------------------------------
Ui_SpectralChoice, _ = uic.loadUiType(os.path.join(ui_path,"spectral_choice_gui.ui"))
class SpectralChoiceDialog(QtGui.QDialog, Ui_SpectralChoice):
def __init__(self, parent):
super().__init__()
self.setupUi(self)
self.nwb = parent.model.nwb
self.fpath = parent.model.pathName
self.fname = parent.model.fileName
self.chosen_bands = None #Values for custom filter bands (user input)
self.value = -1 #Reference value for user pressed exit button
self.radioButton_1.clicked.connect(self.choice_default)
self.radioButton_2.clicked.connect(self.choice_custom)
self.pushButton_1.clicked.connect(self.add_band)
self.pushButton_2.clicked.connect(self.del_band)
self.runButton.clicked.connect(self.run_decomposition)
self.cancelButton.clicked.connect(lambda: self.out_close(val=-1))
if 'ecephys' in parent.model.nwb.processing:
# If there's no preprocessed data in NWB file
if 'LFP' not in parent.model.nwb.processing['ecephys'].data_interfaces:
self.disable_all()
text = "There's no preprocessed data in the current file.\n" \
"Run 'Preprocess' to generate it."
self.label_1.setText(text)
self.cancelButton.setEnabled(True)
# If there's already Bandpower data in NWB file
if 'Bandpower' in self.nwb.processing['ecephys'].data_interfaces:
self.disable_all()
text = "Frequency decomposition data already exists in current file."
self.label_1.setText(text)
self.cancelButton.setEnabled(True)
else:
self.disable_all()
text = "There's no preprocessed data in the current file.\n" \
"Run 'Preprocess' to generate it."
self.label_1.setText(text)
self.cancelButton.setEnabled(True)
self.setWindowTitle('Spectral decomposition')
self.exec_()
def choice_default(self): # default chosen
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
text = "Spectral decomposition data does not exist in current file.\n" \
"It can be created from the bands shown in the table. "\
"The results will be saved in the current NWB file.\nDo you want to create it?"
self.label_1.setText(text)
self.runButton.setEnabled(True)
# Populate table with values
self.tableWidget.setHorizontalHeaderLabels(['center [Hz]','sigma [Hz]'])
p0 = default_bands.chang_lab['cfs']
p1 = default_bands.chang_lab['sds']
self.tableWidget.setRowCount(len(p0))
for i in np.arange(len(p0)):
self.tableWidget.setItem(i, 0, QTableWidgetItem(str(round(p0[i],1))))
self.tableWidget.setItem(i, 1, QTableWidgetItem(str(round(p1[i],1))))
def choice_custom(self): # default chosen
text = "Spectral decomposition data does not exist in current file.\n" \
"To create it, add the bands of interest to the table. "\
"The results will be saved in the current NWB file.\nDo you want to create it?"
self.label_1.setText(text)
self.runButton.setEnabled(True)
# Allows user to populate table with values
self.tableWidget.setRowCount(1)
self.tableWidget.setHorizontalHeaderLabels(['center [Hz]','sigma [Hz]'])
self.tableWidget.setItem(0, 0, QTableWidgetItem(str(0)))
self.tableWidget.setItem(0, 1, QTableWidgetItem(str(0)))
self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked)
self.pushButton_1.setEnabled(True)
self.pushButton_2.setEnabled(True)
def add_band(self):
nRows = self.tableWidget.rowCount()
self.tableWidget.insertRow(nRows)
self.tableWidget.setItem(nRows, 0, QTableWidgetItem(str(0)))
self.tableWidget.setItem(nRows, 1, QTableWidgetItem(str(0)))
def del_band(self):
nRows = self.tableWidget.rowCount()
self.tableWidget.removeRow(nRows-1)
def run_decomposition(self):
self.disable_all()
nRows = self.tableWidget.rowCount()
self.chosen_bands = np.zeros((2,nRows))
for i in np.arange(nRows): #read bands from table
self.chosen_bands[0,i] = float(self.tableWidget.item(i, 0).text())
self.chosen_bands[1,i] = float(self.tableWidget.item(i, 1).text())
self.label_1.setText('Processing spectral decomposition.\nPlease wait...')
subj, aux = self.fname.split('_')
block = [ aux.split('.')[0][1:] ]
self.thread = ProcessingDataFunction(path=self.fpath, subject=subj,
blocks=block, mode='decomposition',
config=self.chosen_bands)
self.thread.finished.connect(lambda: self.out_close(val=1))
self.thread.start()
def disable_all(self):
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.tableWidget.setEnabled(False)
self.groupBox.setEnabled(False)
self.runButton.setEnabled(False)
self.cancelButton.setEnabled(False)
def out_close(self, val):
self.value = val
self.accept()
# Runs 'processing_data' function, useful to wait for thread -------------------
class ProcessingDataFunction(QtCore.QThread):
def __init__(self, path, subject, blocks, mode, config, new_file=''):
super().__init__()
self.fpath = path
self.subject = subject
self.blocks = blocks
self.mode = mode
self.config = config
self.new_fname = new_file
def run(self):
processing_data(path=self.fpath,
subject=self.subject,
blocks=self.blocks,
mode=self.mode,
config=self.config,
new_file=self.new_fname)
# Creates High Gamma dialog ----------------------------------------------------
Ui_HighGamma, _ = uic.loadUiType(os.path.join(ui_path,"high_gamma_gui.ui"))
class HighGammaDialog(QtGui.QDialog, Ui_HighGamma):
def __init__(self, parent):
super().__init__()
self.setupUi(self)
self.parent = parent
self.nwb = parent.model.nwb
self.fpath = parent.model.pathName
self.fname = parent.model.fileName
self.chosen_bands = None #Values for custom filter bands (user input)
self.value = -1 #Reference value for user pressed exit button'
self.new_fname = ''
self.radioButton_1.setChecked(True)
self.radioButton_3.setChecked(True)
self.lineEdit.setEnabled(False)
self.radioButton_1.clicked.connect(self.choice_default)
self.radioButton_2.clicked.connect(self.choice_custom)
self.radioButton_3.clicked.connect(lambda: self.choose_file(0))
self.radioButton_4.clicked.connect(lambda: self.choose_file(1))
self.pushButton_1.clicked.connect(self.add_band)
self.pushButton_2.clicked.connect(self.del_band)
self.runButton.clicked.connect(self.run)
self.cancelButton.clicked.connect(lambda: self.out_close(val=-1))
self.check_hg_exists()
self.setWindowTitle('High Gamma power estimation')
self.exec_()
def check_hg_exists(self):
if 'ecephys' in self.parent.model.nwb.processing:
# If there's no preprocessed data in NWB file
if 'LFP' not in self.parent.model.nwb.processing['ecephys'].data_interfaces:
self.disable_all()
text = "There's no preprocessed data in the current file.\n" \
"Run 'Preprocess' to generate it."
self.label_1.setText(text)
self.radioButton_4.setEnabled(False)
self.cancelButton.setEnabled(True)
# If there's already Bandpower data in NWB file
elif 'high_gamma' in self.nwb.processing['ecephys'].data_interfaces:
self.disable_all()
text = "High Gamma data already exists in current file."
self.label_1.setText(text)
self.cancelButton.setEnabled(True)
else:
self.radioButton_1.setChecked(True)
self.choice_default()
else:
self.disable_all()
text = "There's no preprocessed data in the current file.\n" \
"Run 'Preprocess' to generate it."
self.label_1.setText(text)
self.radioButton_4.setEnabled(False)
self.cancelButton.setEnabled(True)
def choose_file(self, flag):
if flag==0: #save in current NWB file
self.nwb = self.parent.model.nwb
self.lineEdit.setEnabled(False)
self.new_fname = ''
self.check_hg_exists()
elif flag==1: #save in new NWB file
part0, part1 = self.fname.split('.')
default_path_name = os.path.join(self.fpath,part0+'_hg.'+part1)
filename, _ = QFileDialog.getSaveFileName(self, 'New file',
default_path_name, "(*.nwb)")
self.lineEdit.setEnabled(True)
self.lineEdit.setText(filename)
self.new_fname = filename
self.enable_all()
self.radioButton_1.setChecked(True)
self.choice_default()
def disable_all(self):
self.lineEdit.setEnabled(False)
self.groupBox_1.setEnabled(False)
self.tableWidget.setEnabled(False)
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.runButton.setEnabled(False)
def enable_all(self):
self.lineEdit.setEnabled(True)
self.groupBox_1.setEnabled(True)
self.tableWidget.setEnabled(True)
self.pushButton_1.setEnabled(True)
self.pushButton_2.setEnabled(True)
self.runButton.setEnabled(True)
def choice_default(self): # default chosen
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
text = "'High gamma' power data can be created from the averaged power "\
"of the bands shown in the table. "\
"The results will be saved in the chosen NWB file.\nDo you want to create it?"
self.label_1.setText(text)
self.runButton.setEnabled(True)
# Populate table with values
self.tableWidget.setHorizontalHeaderLabels(['','center [Hz]','sigma [Hz]'])
self.tableWidget.setColumnWidth(0, 14)
self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.tableWidget.setFocusPolicy(QtCore.Qt.NoFocus)
self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.NoSelection)
p0 = default_bands.chang_lab['cfs'][29:]
p1 = default_bands.chang_lab['sds'][29:]
self.tableWidget.setRowCount(len(p0))
for i in np.arange(len(p0)):
cell_widget = QWidget()
chk_bx = QtGui.QCheckBox()
chk_bx.setMaximumWidth(14)
if i<8:
chk_bx.setChecked(True)
else: chk_bx.setChecked(False)
self.tableWidget.setCellWidget(i, 0, chk_bx)
self.tableWidget.setItem(i, 1, QTableWidgetItem(str(round(p0[i],1))))
self.tableWidget.setItem(i, 2, QTableWidgetItem(str(round(p1[i],1))))
self.tableWidget.item(i, 1).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.tableWidget.item(i, 2).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
def choice_custom(self): # default chosen
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
text = "'High gamma' power data can be created from the averaged power "\
"of the bands shown in the table. "\
"The results will be saved in the chosen NWB file.\nDo you want to create it?"
self.label_1.setText(text)
self.runButton.setEnabled(True)
# Populate table with values
self.tableWidget.setHorizontalHeaderLabels(['','center [Hz]','sigma [Hz]'])
self.tableWidget.setColumnWidth(0, 14)
self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.tableWidget.setFocusPolicy(QtCore.Qt.NoFocus)
self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.NoSelection)
p0 = default_bands.chang_lab['cfs'][29:]
p1 = default_bands.chang_lab['sds'][29:]
self.tableWidget.setRowCount(len(p0))
for i in np.arange(len(p0)):
cell_widget = QWidget()
chk_bx = QtGui.QCheckBox()
chk_bx.setChecked(True)
chk_bx.setMaximumWidth(14)
self.tableWidget.setCellWidget(i, 0, chk_bx)
self.tableWidget.setItem(i, 1, QTableWidgetItem(str(round(p0[i],1))))
self.tableWidget.setItem(i, 2, QTableWidgetItem(str(round(p1[i],1))))
self.tableWidget.item(i, 1).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.tableWidget.item(i, 2).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
# Allows user to populate table with values
self.tableWidget.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked)
self.pushButton_1.setEnabled(True)
self.pushButton_2.setEnabled(True)
def add_band(self):
nRows = self.tableWidget.rowCount()
self.tableWidget.insertRow(nRows)
cell_widget = QWidget()
chk_bx = QtGui.QCheckBox()
chk_bx.setChecked(True)
chk_bx.setMaximumWidth(14)
self.tableWidget.setCellWidget(nRows, 0, chk_bx)
self.tableWidget.setItem(nRows, 1, QTableWidgetItem(str(0)))
self.tableWidget.setItem(nRows, 2, QTableWidgetItem(str(0)))
self.tableWidget.item(nRows, 1).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.tableWidget.item(nRows, 2).setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
def del_band(self):
nRows = self.tableWidget.rowCount()
self.tableWidget.removeRow(nRows-1)
def run(self):
self.chosen_bands = np.zeros((2,0))
nRows = self.tableWidget.rowCount()
for i in np.arange(nRows):
if self.tableWidget.cellWidget(i, 0).isChecked():
val0 = float(self.tableWidget.item(i, 1).text())
val1 = float(self.tableWidget.item(i, 2).text())
self.chosen_bands = np.append(self.chosen_bands, np.array([[val0],[val1]]), axis=1)
# If Decomposition data does not exist in NWB file and user decides to create it
self.label_1.setText('Processing High Gamma power estimation. \nPlease wait...')
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.tableWidget.setEnabled(False)
self.groupBox_1.setEnabled(False)
self.groupBox_2.setEnabled(False)
self.runButton.setEnabled(False)
self.cancelButton.setEnabled(False)
subj, aux = self.fname.split('_')
block = [ aux.split('.')[0][1:] ]
self.thread = ProcessingDataFunction(path=self.fpath,
subject=subj,
blocks=block,
mode='high_gamma',
config=self.chosen_bands,
new_file=self.new_fname)
self.thread.finished.connect(lambda: self.out_close(1))
self.thread.start()
def out_close(self, val):
"""When out of this function, the current file will be refreshed or the
newly created will be opened"""
self.value = val
if self.new_fname=='':
self.new_fname = os.path.join(self.fpath,self.fname)
self.accept()
# Creates preprocessing dialog -------------------------------------------------
Ui_Preprocessing, _ = uic.loadUiType(os.path.join(ui_path,"preprocessing_gui.ui"))
class PreprocessingDialog(QtGui.QDialog, Ui_Preprocessing):
def __init__(self, parent):
super().__init__()
self.setupUi(self)
self.value = -1
self.checkBox_1.setChecked(True)
self.checkBox_2.setChecked(True)
self.checkBox_3.setChecked(True)
self.lineEdit_1.setText('16')
self.lineEdit_2.setText('60')
self.lineEdit_3.setText('400')
self.pushButton_1.clicked.connect(lambda: self.out_close(-1))
self.pushButton_2.clicked.connect(self.ok)
self.fname = parent.model.fileName
self.fpath = parent.model.pathName
#if preprocessed signals already exist on NWB file
if 'ecephys' in parent.model.nwb.processing:
if 'LFP' in parent.model.nwb.processing['ecephys'].data_interfaces:
self.disable_all()
aux = parent.model.nwb.processing['ecephys'].data_interfaces['LFP'].electrical_series['preprocessed']
car, notch, downs = aux.comments.split(',')
_, car = car.split(':')
_, notch = notch.split(':')
_, downs = downs.split(':')
if car=='None':
self.checkBox_1.setChecked(False)
self.lineEdit_1.setText(car)
if notch=='None':
self.checkBox_2.setChecked(False)
self.lineEdit_2.setText(notch)
if downs=='No':
self.checkBox_3.setChecked(False)
self.lineEdit_3.setText(str(aux.rate))
self.pushButton_1.setEnabled(True)
self.label_2.setText('Preprocessed data already exists in file,'\
' with the parameters shown above.')
self.setWindowTitle('Preprocessing ')
self.exec_()
def ok(self):
self.disable_all()
self.label_2.setText('Preprocessing ECoG signals.\nPlease wait...')
config = {}
if self.checkBox_1.isChecked():
config['CAR'] = int(self.lineEdit_1.text())
else: config['CAR'] = None
if self.checkBox_2.isChecked():
config['Notch'] = float(self.lineEdit_2.text())
else: config['Notch'] = None
if self.checkBox_3.isChecked():
config['Downsample'] = float(self.lineEdit_3.text())
else: config['Downsample'] = None
subj, aux = self.fname.split('_')
block = [ aux.split('.')[0][1:] ]
self.thread = ProcessingDataFunction(path=self.fpath, subject=subj,
blocks=block, mode='preprocess',
config=config)
self.thread.finished.connect(lambda: self.out_close(1))
self.thread.start()
def out_close(self, val):
self.value = val
self.accept()
def disable_all(self):
self.label_1.setEnabled(False)
self.checkBox_1.setEnabled(False)
self.checkBox_2.setEnabled(False)
self.checkBox_3.setEnabled(False)
self.lineEdit_1.setEnabled(False)
self.lineEdit_2.setEnabled(False)
self.lineEdit_3.setEnabled(False)
self.pushButton_1.setEnabled(False)
self.pushButton_2.setEnabled(False)
# Creates Group Periodograms window --------------------------------------------
class Periodograms(QtGui.QDialog):
def __init__(self, parent, psd):
super().__init__()
self.parent = parent
self.psd = psd #Power Spectral Density data
self.nChannels = parent.model.nChTotal
self.freqMax = 200.
self.freqTickRes = 20
self.chTickGrid = 5
self.chTickSpace = self.nChannels/(self.chTickGrid-1)
self.transparent = []
#Left panel
self.push0_0 = QPushButton('Draw')
self.push0_0.clicked.connect(self.draw_periodograms)
self.push1_0 = QPushButton('Brain areas')
self.push1_0.clicked.connect(self.areas_select)
label2 = QLabel('Freq bin [Hz]:')
self.qline2 = QLineEdit('20')
self.qline2.returnPressed.connect(self.set_freq_bin)
label3 = QLabel('Ch grid [#]:')
self.qline3 = QLineEdit('5')
self.qline3.returnPressed.connect(self.set_ch_grid)
self.push4_0 = QPushButton('Save image')
self.push4_0.clicked.connect(self.save_image)
grid0 = QGridLayout()
grid0.addWidget(label2, 0, 0, 1, 4)
grid0.addWidget(self.qline2, 0, 4, 1, 2)
grid0.addWidget(label3, 1, 0, 1, 4)
grid0.addWidget(self.qline3, 1, 4, 1, 2)
grid0.addWidget(QHLine(), 2, 0, 1, 6)
grid0.addWidget(self.push1_0, 3, 0, 1, 6)
grid0.addWidget(self.push4_0, 4, 0, 1, 6)
grid0.setAlignment(QtCore.Qt.AlignTop)
panel0 = QGroupBox('Controls:')
panel0.setFixedWidth(180)
panel0.setLayout(grid0)
self.leftbox = QVBoxLayout()
self.leftbox.addWidget(self.push0_0)
self.leftbox.addWidget(panel0)
#Right panel -----------------------------------------------------------
self.fig1 = CustomGLWidget(self) #gl.GLViewWidget()
background_color = self.palette().color(QtGui.QPalette.Background)
self.fig1.setBackgroundColor(background_color)
self.fig1.setToolTip('Tooltip')
self.rightbox = QGridLayout() #QVBoxLayout()
self.rightbox.setSpacing(0.0)
self.rightbox.setRowStretch(0, 2)
#self.rightbox.setRowStretch(1, 1)
self.rightbox.addWidget(self.fig1)
self.hbox = QHBoxLayout()
self.hbox.addLayout(self.leftbox) #add panels in the left
self.hbox.addLayout(self.rightbox) #add plot on the right
self.setLayout(self.hbox)
self.setWindowTitle('Periodogram')
self.resize(1100,600)
self.exec_()
def set_freq_bin(self):
self.freqTickRes = float(self.qline2.text())
self.draw_periodograms()
def set_ch_grid(self):
self.chTickGrid = float(self.qline3.text())
self.chTickSpace = self.nChannels/(self.chTickGrid-1)
self.draw_periodograms()
def save_image(self):
"""Export image. For 3D scenes, this is still a bit limited."""
default_path_name = self.parent.model.pathName
filename, _ = QFileDialog.getSaveFileName(self, 'Export image',
default_path_name, "(*.png)")
print(filename)
self.fig1.grabFrameBuffer().save(filename+'.png')
def areas_select(self):
"""Dialog to choose channels from specific brain regions."""
w = SelectChannelsDialog(self.parent.model.all_regions, self.parent.model.regions_mask)
self.transparent = []
for ch in np.arange(self.nChannels):
loc = self.parent.model.nwb.electrodes['location'][ch]
if loc not in w.choices:
self.transparent.append(ch)
self.draw_periodograms()
def draw_periodograms(self):
"""Draw periodograms."""
#Cleans scene
for it in self.fig1.items[:]:
self.fig1.removeItem(it)
# nBins = 400
# y = np.linspace(0,self.nChannels,self.nChannels)
# x = np.linspace(0,self.freqMax,nBins)
# maxz = 0
# Yscale = self.freqMax/2 #Scale Z for better visualization
# for ch in range(self.nChannels):
# if ch in self.transparent: #if it should be made transparent
# elem_alpha = .1
# else:
# elem_alpha = 1
# yi = np.array([y[ch]]*nBins)
# z = Yscale*(np.exp(-x/70) + np.random.randn(len(x))*np.exp(-x/70)/5)
# maxz = max(maxz,max(z))
# pts = np.vstack([x,yi,z]).transpose()
# plt = gl.GLLinePlotItem(pos=pts, color=(0,0,0,elem_alpha), width=1., antialias=True)
# self.fig1.addItem(plt)
idx = self.psd.frequencies[:]<=self.freqMax
idx[0] = False
x = self.psd.frequencies[idx]
nX = np.sum(idx)
nY = self.nChannels
y = np.linspace(0,nY,nY)
for ch in range(nY):
zch = self.psd.power[idx,ch]
if ch == 0:
z = zch
else:
z = np.vstack((z,zch))
z = z.T #z.shape (nBinsFreq,nChannels)
zmax = z.max()
zmin = z.min()
zpercs = np.percentile(z, [10, 90])
## Manually specified colors
csize = 101
cmap = np.hstack((np.linspace(0,1,csize).reshape(-1,1),
np.zeros(csize).reshape(-1,1)+.4,
np.linspace(1,0,csize).reshape(-1,1)))
colors = np.zeros((nX,nY,4))
# Finds color for each point in surface
for f in range(nX):
for ch in range(nY):
#rel = (z[f,ch]-zmin)/(zmax-zmin)
#relative position to choose color
rel = np.clip((z[f,ch]-zpercs[0])/(zpercs[1]-zpercs[0]), 0, 1)
relc = int(rel*(csize-1))
colors[f,ch,0] = cmap[relc,0] #red
colors[f,ch,1] = cmap[relc,1] #green
colors[f,ch,2] = cmap[relc,2] #blue
# Surface plot
p3 = gl.GLSurfacePlotItem(x=x, y=y, z=z, colors=colors.reshape(nX*nY,4),
shader='shaded', smooth=False)
zscale = 200/zmax
p3.scale(1, 1, zscale)
self.fig1.addItem(p3)
#Axes
axis = Custom3DAxis(self.fig1)
axis.setSize(x=self.freqMax, y=self.nChannels, z=zmax*zscale)
axis.add_labels(labels=['Frequency [Hz]','Channel #','PSD [V**2/Hz]'])
xticks=np.arange(0,self.freqMax+0.01,self.freqTickRes, dtype='int')
yticks=np.linspace(1,self.nChannels,self.chTickGrid, dtype='int')
zticks=np.round(np.linspace(0,zmax*zscale,4),1)
axis.add_tick_values(xticks=xticks, yticks=yticks, zticks=zticks)
self.fig1.addItem(axis)
#Camera initial position
self.fig1.setCameraPosition(distance=497, elevation=22, azimuth=-83)
self.fig1.opts['center'] = QtGui.QVector3D(95.6, 195.4, 0)
#Reference grids
# gx = CustomGLGrid(self)#gl.GLGridItem()
# gx.rotate(90, 0, 1, 0)
# gx.setSize(x=zmax*zscale, y=self.nChannels)
# gx.translate(dx=0, dy=self.nChannels/2, dz=zmax*zscale/2.)
# gx.setSpacing(x=np.diff(zticks)[0], y=self.chTickSpace)
# self.fig1.addItem(gx)
# gy = CustomGLGrid(self)#gl.GLGridItem()
# gy.rotate(90, 1, 0, 0)
# gy.setSize(x=self.freqMax, y=zmax*zscale)
# gy.translate(dx=self.freqMax/2, dy=self.nChannels, dz=zmax*zscale/2)
# gy.setSpacing(x=np.diff(xticks)[0], y=np.diff(zticks)[0])
# self.fig1.addItem(gy)
# gz = CustomGLGrid(self)#gl.GLGridItem()
# gz.setSize(x=self.freqMax, y=self.nChannels)
# gz.translate(dx=self.freqMax/2, dy=self.nChannels/2, dz=0)
# gz.setSpacing(x=np.diff(xticks)[0], y=self.chTickSpace)
# self.fig1.addItem(gz)
class Custom3DAxis(gl.GLAxisItem):
"""Class defined to extend 'gl.GLAxisItem'."""
def __init__(self, parent):
gl.GLAxisItem.__init__(self)
self.parent = parent
def add_labels(self, labels=['X','Y','Z']):
"""Adds axes labels."""
x,y,z = self.size()
#X label
self.xLabel = CustomTextItem(X=x/2, Y=-y/10, Z=-z/10, text=labels[0])
self.xLabel.setGLViewWidget(self.parent)
self.parent.addItem(self.xLabel)
#Y label
self.yLabel = CustomTextItem(X=x+x/10, Y=y/2, Z=-z/10, text=labels[1])
self.yLabel.setGLViewWidget(self.parent)
self.parent.addItem(self.yLabel)
#Z label
self.zLabel = CustomTextItem(X=-x/8, Y=-y/8, Z=z/2, text=labels[2])
self.zLabel.setGLViewWidget(self.parent)
self.parent.addItem(self.zLabel)
def add_tick_values(self, xticks=[], yticks=[], zticks=[]):
"""Adds ticks values."""
x,y,z = self.size()
xtpos = xticks#np.linspace(0, x, len(xticks))
ytpos = yticks#np.linspace(0, y, len(yticks))
ztpos = np.linspace(0, z, len(zticks))
#X ticks
for i, xt in enumerate(xticks):
val = CustomTextItem(X=xtpos[i], Y=-y/50, Z=-z/50, text=str(xt))
val.setGLViewWidget(self.parent)
self.parent.addItem(val)
#Y ticks
for i, yt in enumerate(yticks):
val = CustomTextItem(X=x+x/50, Y=ytpos[i], Z=-z/50, text=str(yt))
val.setGLViewWidget(self.parent)
self.parent.addItem(val)
#Z ticks
for i, zt in enumerate(zticks):
val = CustomTextItem(X=-x/15, Y=-y/15, Z=ztpos[i], text=str(zt))
val.setGLViewWidget(self.parent)
self.parent.addItem(val)
def paint(self):
self.setupGLState()
if self.antialias:
ogl.glEnable(ogl.GL_LINE_SMOOTH)
ogl.glHint(ogl.GL_LINE_SMOOTH_HINT, ogl.GL_NICEST)
ogl.glBegin(ogl.GL_LINES)
x,y,z = self.size()
#Draw Z
ogl.glColor4f(0, 0, 0, .6)
ogl.glVertex3f(0, 0, 0)
ogl.glVertex3f(0, 0, z)
#Draw Y
ogl.glColor4f(0, 0, 0, .6)
ogl.glVertex3f(0, 0, 0)
ogl.glVertex3f(0, y, 0)
#Draw X
ogl.glColor4f(0, 0, 0, .6)
ogl.glVertex3f(0, 0, 0)
ogl.glVertex3f(x, 0, 0)
ogl.glEnd()
class CustomGLWidget(gl.GLViewWidget):
"""Class defined to extend 'gl.GLAxisItem'."""
def __init__(self, parent):
gl.GLViewWidget.__init__(self)
self.parent = parent
def mousePressEvent(self, ev):
"""Method altered to allow for mouse-click print of region."""
self.mousePos = ev.pos()
region = (ev.pos().x()-5, ev.pos().y()-5, 10, 10)
if len(self.itemsAt(region))>1:
item = self.itemsAt(region)[0]
if type(item).__name__=='GLLinePlotItem':
print(item.pos[0,1])
def mouseMoveEvent(self, ev):
"""Method altered to allow for mouse-driven pan."""
diff = ev.pos() - self.mousePos
self.mousePos = ev.pos()