/
bidseditor.py
executable file
·1409 lines (1183 loc) · 65.9 KB
/
bidseditor.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
#!/usr/bin/env python3
"""
This tool launches a graphical user interface for editing the bidsmap.yaml file
that is produced by the bidsmapper. The user can fill in or change the BIDS labels
for entries that are unidentified or sub-optimal, such that meaningful and nicely
readable BIDS output names will be generated. The saved bidsmap.yaml output file
will be used by the bidscoiner to actually convert the source data to BIDS.
You can hoover with your mouse over items to get help text (pop-up tooltips).
"""
import sys
import argparse
import textwrap
import logging
import copy
import webbrowser
import pydicom
from pathlib import Path
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileSystemModel, QFileDialog, QDialogButtonBox,
QTreeView, QHBoxLayout, QVBoxLayout, QLabel, QDialog, QMessageBox,
QTableWidget, QTableWidgetItem, QHeaderView, QGroupBox, QTextBrowser,
QAbstractItemView, QPushButton, QComboBox, QDesktopWidget, QAction)
try:
from bidscoin import bids
except ImportError:
import bids # This should work if bidscoin was not pip-installed
LOGGER = logging.getLogger('bidscoin')
ROW_HEIGHT = 22
ICON_FILENAME = Path(__file__).parent/'bidscoin.ico'
MAIN_HELP_URL = f"https://bidscoin.readthedocs.io/en/{bids.version()}"
HELP_URL_DEFAULT = f"https://bids-specification.readthedocs.io/en/v{bids.bidsversion()}"
HELP_URLS = {
'anat': f"{HELP_URL_DEFAULT}/04-modality-specific-files/01-magnetic-resonance-imaging-data.html#anatomy-imaging-data",
'dwi' : f"{HELP_URL_DEFAULT}/04-modality-specific-files/01-magnetic-resonance-imaging-data.html#diffusion-imaging-data",
'fmap': f"{HELP_URL_DEFAULT}/04-modality-specific-files/01-magnetic-resonance-imaging-data.html#fieldmap-data",
'func': f"{HELP_URL_DEFAULT}/04-modality-specific-files/01-magnetic-resonance-imaging-data.html#task-including-resting-state-imaging-data",
'perf': f"{HELP_URL_DEFAULT}/04-modality-specific-files/01-magnetic-resonance-imaging-data.html#arterial-spin-labeling-perfusion-data",
'eeg' : f"{HELP_URL_DEFAULT}/04-modality-specific-files/03-electroencephalography.html",
'ieeg': f"{HELP_URL_DEFAULT}/04-modality-specific-files/04-intracranial-electroencephalography.html",
'beh' : f"{HELP_URL_DEFAULT}/04-modality-specific-files/07-behavioral-experiments.html",
'pet' : 'https://docs.google.com/document/d/1mqMLnxVdLwZjDd4ZiWFqjEAmOmfcModA_R535v3eQs0',
bids.unknowndatatype: HELP_URL_DEFAULT,
bids.ignoredatatype : HELP_URL_DEFAULT
}
TOOLTIP_BIDSCOIN = """BIDScoin
version: should correspond with the version in ../bidscoin/version.txt
bidsignore: Semicolon-separated list of entries that are added to the .bidsignore file
(for more info, see BIDS specifications), e.g. extra_data/;pet/;myfile.txt;yourfile.csv"""
TOOLTIP_DCM2NIIX = """dcm2niix
path: Command to set the path to dcm2niix, e.g.:
module add dcm2niix/1.0.20180622; (note the semi-colon at the end)
PATH=/opt/dcm2niix/bin:$PATH; (note the semi-colon at the end)
/opt/dcm2niix/bin/ (note the slash at the end)
'\"C:\\Program Files\\dcm2niix\"' (note the quotes to deal with the whitespace)
args: Argument string that is passed to dcm2niix. Click [Test] and see the terminal output for usage
Tip: SPM users may want to use '-z n', which produces unzipped nifti's"""
class myQTableWidget(QTableWidget):
def __init__(self, minimum: bool=True):
super().__init__()
self.setAlternatingRowColors(False)
self.setShowGrid(False)
self.verticalHeader().setVisible(False)
self.verticalHeader().setDefaultSectionSize(ROW_HEIGHT)
self.setMinimumHeight(2 * (ROW_HEIGHT + 5))
self.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.minimizeHeight(minimum)
def minimizeHeight(self, minimum: bool=True):
"""Set the vertical QSizePolicy to Minimum"""
self.minimum = minimum
if minimum:
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
else:
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
class myWidgetItem(QTableWidgetItem):
def __init__(self, value: str='', iseditable: bool=True):
"""A QTableWidgetItem that is editable or not"""
super().__init__()
if isinstance(value, int):
value = str(value)
self.setText(value)
self.setEditable(iseditable)
def setEditable(self, iseditable: bool=True):
"""Make the WidgetItem editable"""
self.iseditable = iseditable
if iseditable:
self.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable)
self.setForeground(QtGui.QColor('black'))
else:
self.setFlags(QtCore.Qt.ItemIsEnabled)
self.setForeground(QtGui.QColor('gray'))
class InspectWindow(QDialog):
def __init__(self, filename: Path, sourcedict, dataformat: str):
super().__init__()
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(str(ICON_FILENAME)), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(icon)
self.setWindowTitle(f"Inspect {dataformat} file")
layout = QVBoxLayout(self)
label_path = QLabel(f"Path: {filename.parent}")
label_path.setWordWrap(True)
label_path.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
layout.addWidget(label_path)
label = QLabel(f"Filename: {filename.name}")
label.setWordWrap(True)
label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
layout.addWidget(label)
text = str(sourcedict)
textBrowser = QTextBrowser(self)
textBrowser.setFont(QtGui.QFont("Courier New"))
textBrowser.insertPlainText(text)
textBrowser.setLineWrapMode(QtWidgets.QTextEdit.NoWrap)
self.scrollbar = textBrowser.verticalScrollBar() # For setting the slider to the top (can only be done after self.show()
layout.addWidget(textBrowser)
buttonBox = QDialogButtonBox(self)
buttonBox.setStandardButtons(QDialogButtonBox.Ok)
buttonBox.button(QDialogButtonBox.Ok).setToolTip('Close this window')
layout.addWidget(buttonBox)
# Set the width to the width of the text
fontMetrics = QtGui.QFontMetrics(textBrowser.font())
textwidth = fontMetrics.size(0, text).width()
self.resize(min(textwidth + 70, 1200), self.height())
buttonBox.accepted.connect(self.close)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
actionQuit = QAction('Quit', self)
actionQuit.triggered.connect(self.closeEvent)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(str(ICON_FILENAME)), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(icon)
def closeEvent(self, event):
"""Handle exit. """
QApplication.quit() # TODO: Do not use class method but self.something
class Ui_MainWindow(MainWindow):
def setupUi(self, MainWindow, bidsfolder, bidsmap_filename, input_bidsmap, output_bidsmap, template_bidsmap,
dataformat, selected_tab_index=2, subprefix='sub-', sesprefix='ses-', reload: bool=False):
# Set the input data
self.MainWindow = MainWindow
self.bidsfolder = Path(bidsfolder)
self.bidsmap_filename = Path(bidsmap_filename)
self.input_bidsmap = input_bidsmap
self.output_bidsmap = output_bidsmap
self.template_bidsmap = template_bidsmap
self.dataformat = dataformat
self.subprefix = subprefix
self.sesprefix = sesprefix
self.has_edit_dialog_open = None
# Set-up the tabs
self.tabwidget = QtWidgets.QTabWidget()
tabwidget = self.tabwidget
tabwidget.setTabPosition(QtWidgets.QTabWidget.North)
tabwidget.setTabShape(QtWidgets.QTabWidget.Rounded)
tabwidget.setObjectName('tabwidget')
self.set_tab_file_browser()
self.set_tab_options()
self.set_tab_bidsmap()
tabwidget.setTabText(0, 'File browser')
tabwidget.setTabText(1, 'Options')
tabwidget.setTabText(2, 'BIDS map')
tabwidget.setCurrentIndex(selected_tab_index)
# Set-up the buttons. TODO: Add validate bidsmap button
buttonBox = QDialogButtonBox()
buttonBox.setStandardButtons(QDialogButtonBox.Save | QDialogButtonBox.Reset | QDialogButtonBox.Help)
buttonBox.button(QDialogButtonBox.Help).setToolTip('Go to the online BIDScoin documentation')
buttonBox.button(QDialogButtonBox.Save).setToolTip('Save the Options and BIDS-map to disk if you are satisfied with all the BIDS output names')
buttonBox.button(QDialogButtonBox.Reset).setToolTip('Reload the options and BIDS-map from disk')
buttonBox.helpRequested.connect(self.get_help)
buttonBox.button(QDialogButtonBox.Reset).clicked.connect(self.reload)
buttonBox.button(QDialogButtonBox.Save).clicked.connect(self.save_bidsmap_to_file)
# Set-up the main layout
centralwidget = QtWidgets.QWidget(self.MainWindow)
centralwidget.setLocale(QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates))
centralwidget.setObjectName('centralwidget')
top_layout = QtWidgets.QVBoxLayout(centralwidget)
top_layout.addWidget(tabwidget)
top_layout.addWidget(buttonBox)
self.MainWindow.setCentralWidget(centralwidget)
# Restore the samples_table stretching after the main window has been sized / current tabindex has been set (otherwise the main window can become too narrow)
header = self.samples_table.horizontalHeader()
header.setSectionResizeMode(1, QHeaderView.Interactive)
header.setSectionResizeMode(3, QHeaderView.Stretch)
if not reload:
self.setObjectName('MainWindow')
self.set_menu_and_status_bar()
# Center the main window to the center point of screen
self.MainWindow.adjustSize()
cp = QDesktopWidget().availableGeometry().center()
qr = self.MainWindow.frameGeometry()
qr.moveCenter(cp)
self.MainWindow.move(qr.topLeft()) # Top left of rectangle becomes top left of window centering it
def set_menu_and_status_bar(self):
# Set the menus
menubar = QtWidgets.QMenuBar(self.MainWindow)
menuFile = QtWidgets.QMenu(menubar)
menuFile.setTitle('File')
menubar.addAction(menuFile.menuAction())
menuHelp = QtWidgets.QMenu(menubar)
menuHelp.setTitle('Help')
menubar.addAction(menuHelp.menuAction())
self.MainWindow.setMenuBar(menubar)
# Set the file menu actions
actionReload = QAction(self.MainWindow)
actionReload.setText('Reset')
actionReload.setStatusTip('Reload the BIDS-map from disk')
actionReload.setShortcut('Ctrl+R')
actionReload.triggered.connect(self.reload)
menuFile.addAction(actionReload)
actionSave = QAction(self.MainWindow)
actionSave.setText('Save')
actionSave.setStatusTip('Save the BIDS-map to disk')
actionSave.setShortcut('Ctrl+S')
actionSave.triggered.connect(self.save_bidsmap_to_file)
menuFile.addAction(actionSave)
actionExit = QAction(self.MainWindow)
actionExit.setText('Exit')
actionExit.setStatusTip('Exit the application')
actionExit.setShortcut('Ctrl+X')
actionExit.triggered.connect(self.exit_application)
menuFile.addAction(actionExit)
# Set help menu actions
actionHelp = QAction(self.MainWindow)
actionHelp.setText('Documentation')
actionHelp.setStatusTip('Go to the online BIDScoin documentation')
actionHelp.setShortcut('F1')
actionHelp.triggered.connect(self.get_help)
menuHelp.addAction(actionHelp)
actionBidsHelp = QAction(self.MainWindow)
actionBidsHelp.setText('BIDS specification')
actionBidsHelp.setStatusTip('Go to the online BIDS specification documentation')
actionBidsHelp.setShortcut('F2')
actionBidsHelp.triggered.connect(self.get_bids_help)
menuHelp.addAction(actionBidsHelp)
actionAbout = QAction(self.MainWindow)
actionAbout.setText('About BIDScoin')
actionAbout.setStatusTip('Show information about the application')
actionAbout.triggered.connect(self.show_about)
menuHelp.addAction(actionAbout)
# Set the statusbar
statusbar = QtWidgets.QStatusBar(self.MainWindow)
statusbar.setObjectName('statusbar')
statusbar.setStatusTip('Statusbar')
self.MainWindow.setStatusBar(statusbar)
def inspect_sourcefile(self, item):
"""When double clicked, show popup window. """
if item.column() == 1:
row = item.row()
cell = self.samples_table.item(row, 5)
sourcefile = Path(cell.text())
if bids.is_dicomfile(sourcefile):
sourcedata = pydicom.dcmread(sourcefile, force=True)
elif bids.is_parfile(sourcefile):
with open(sourcefile, 'r') as parfid:
sourcedata = parfid.read()
else:
LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
return
self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
self.popup.show()
self.popup.scrollbar.setValue(0) # This can only be done after self.popup.show()
def set_tab_file_browser(self):
"""Set the raw data folder inspector tab. """
# Parse the sourcefolder from the bidsmap provenance info
sourcefolder = Path('/').resolve()
for provenance in bids.dir_bidsmap(self.input_bidsmap, self.dataformat):
sourcefolder = Path(provenance.parents[min(3, len(provenance.parents)-1)])
break
label = QLabel(str(sourcefolder))
label.setWordWrap(True)
self.model = QFileSystemModel()
model = self.model
model.setRootPath('')
model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllDirs | QtCore.QDir.Files)
tree = QTreeView()
tree.setModel(model)
tree.setAnimated(False)
tree.setIndentation(20)
tree.sortByColumn(0, QtCore.Qt.AscendingOrder)
tree.setSortingEnabled(True)
tree.setRootIndex(model.index(str(sourcefolder)))
tree.doubleClicked.connect(self.on_double_clicked)
tree.header().resizeSection(0, 800)
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(tree)
tab1 = QtWidgets.QWidget()
tab1.setObjectName('filebrowser')
tab1.setLayout(layout)
self.tabwidget.addTab(tab1, '')
def subses_cell_was_changed(self, row: int, column:int):
"""Subject or session value has been changed in subject-session table. """
if column == 1:
key = self.subses_table.item(row, 0).text()
value = self.subses_table.item(row, 1).text()
oldvalue = self.output_bidsmap[self.dataformat][key]
# Only if cell was actually clicked, update
if key and value!=oldvalue:
LOGGER.warning(f"Expert usage: User has set {self.dataformat}['{key}'] from '{oldvalue}' to '{value}'")
self.output_bidsmap[self.dataformat][key] = value
self.update_subses_and_samples(self.output_bidsmap)
def tool_cell_was_changed(self, tool: str, idx: int, row: int, column: int):
"""Option value has been changed tool options table. """
if column == 2:
table = self.tables_options[idx] # Select the selected table
key = table.item(row, 1).text()
value = table.item(row, 2).text()
oldvalue = self.output_bidsmap['Options'][tool][key]
# Only if cell was actually clicked, update
if key and value!=oldvalue:
LOGGER.info(f"User has set {self.dataformat}['Options']['{key}'] from '{oldvalue}' to '{value}'")
self.output_bidsmap['Options'][tool][key] = value
def handle_click_test_plugin(self, plugin: str):
"""Test the bidsmap plugin and show the result in a pop-up window
:param plugin: Name of the plugin that is being tested in bidsmap['PlugIns']
"""
if bids.test_plugins(Path(plugin)):
result = 'Passed'
else:
result = 'Failed'
QMessageBox.information(self.MainWindow, 'Test', f"Test {plugin}: {result}\n"
f"See terminal output for more info")
def handle_click_test_tool(self, tool: str):
"""Test the bidsmap tool and show the result in a pop-up window
:param tool: Name of the tool that is being tested in bidsmap['Options']
"""
if bids.test_tooloptions(tool, self.output_bidsmap['Options'][tool]):
result = 'Passed'
else:
result = 'Failed'
QMessageBox.information(self.MainWindow, 'Test', f"Test {tool}: {result}\n"
f"See terminal output for more info")
def handle_click_plugin_add(self):
"""Add a plugin by letting the user select a plugin-file"""
plugin = QFileDialog.getOpenFileNames(self.MainWindow, 'Select the plugin-file(s)', directory=str(self.bidsfolder/'code'/'bidscoin'), filter='Python files (*.py *.pyc *.pyo);; All files (*)')
LOGGER.info(f'Added plugins: {plugin[0]}')
self.output_bidsmap['PlugIns'] += plugin[0]
self.update_plugintable()
def plugin_cell_was_changed(self, row: int, column: int):
"""Add / edit a plugin or delete if cell is empty"""
if column==1:
plugin = self.plugin_table.item(row, column).text()
if plugin and row == len(self.output_bidsmap['PlugIns']):
LOGGER.info(f"Added plugin: '{plugin}'")
self.output_bidsmap['PlugIns'].append(plugin)
elif plugin:
LOGGER.info(f"Edited plugin: '{self.output_bidsmap['PlugIns'][row]}' -> '{plugin}'")
self.output_bidsmap['PlugIns'][row] = plugin
elif row < len(self.output_bidsmap['PlugIns']):
LOGGER.info(f"Deleted plugin: '{self.output_bidsmap['PlugIns'][row]}'")
del self.output_bidsmap['PlugIns'][row]
else:
LOGGER.error(f"Unexpected cell change for {plugin}")
self.update_plugintable()
def update_plugintable(self):
"""Plots an extendable table of plugins from self.output_bidsmap['PlugIns']"""
plugins = self.output_bidsmap['PlugIns']
num_rows = len(plugins) + 1
# Fill the rows of the plugin table
plugintable = self.plugin_table
plugintable.disconnect()
plugintable.setRowCount(num_rows)
for i, plugin in enumerate(plugins + ['']):
for j in range(3):
if j==0:
item = myWidgetItem('path', iseditable=False)
plugintable.setItem(i, j, item)
elif j==1:
item = myWidgetItem(plugin)
item.setToolTip('Double-click to edit/delete the plugin, which can be the basename of the plugin in the heuristics folder or a custom full pathname')
plugintable.setItem(i, j, item)
elif j==2: # Add the test-button cell
test_button = QPushButton('Test')
test_button.clicked.connect(partial(self.handle_click_test_plugin, plugin))
test_button.setToolTip(f"Click to test {plugin}")
plugintable.setCellWidget(i, j, test_button)
# Append the Add-button cell
add_button = QPushButton('Select')
add_button.setToolTip('Click to interactively add a plugin')
plugintable.setCellWidget(num_rows - 1, 2, add_button)
add_button.clicked.connect(self.handle_click_plugin_add)
plugintable.cellChanged.connect(self.plugin_cell_was_changed)
def set_tab_options(self):
"""Set the options tab. """
# Create the tool tables
bidsmap_options = self.output_bidsmap['Options']
tool_list = []
tool_options = {}
for tool, parameters in bidsmap_options.items():
# Set the tools
if tool == 'BIDScoin':
tooltip_text = TOOLTIP_BIDSCOIN
elif tool == 'dcm2niix':
tooltip_text = TOOLTIP_DCM2NIIX
else:
tooltip_text = tool
tool_list.append({
'tool': tool,
'tooltip_text': tooltip_text
})
# Store the options for each tool
tool_options[tool] = []
for key, value in parameters.items():
tool_options[tool].append([
{
'value': tool,
'iseditable': False,
'tooltip_text': None
},
{
'value': key,
'iseditable': False,
'tooltip_text': tooltip_text
},
{
'value': value,
'iseditable': True,
'tooltip_text': 'Double-click to edit the option'
}
])
labels = []
self.tables_options = []
for n, tool_item in enumerate(tool_list):
tool = tool_item['tool']
tooltip_text = tool_item['tooltip_text']
data = tool_options[tool]
num_rows = len(data)
num_cols = len(data[0]) + 1 # Always three columns (i.e. tool, key, value) + test-button
label = QLabel(tool)
label.setToolTip(tooltip_text)
tool_table = myQTableWidget()
tool_table.setRowCount(num_rows)
tool_table.setColumnCount(num_cols)
tool_table.setColumnHidden(0, True) # Hide tool column
tool_table.setMouseTracking(True)
horizontal_header = tool_table.horizontalHeader()
horizontal_header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
horizontal_header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
horizontal_header.setSectionResizeMode(2, QHeaderView.Stretch)
horizontal_header.setSectionResizeMode(3, QHeaderView.Fixed)
horizontal_header.setVisible(False)
for i, row in enumerate(data):
for j, item in enumerate(row):
value = item.get('value', '')
if value == 'None':
value = ''
iseditable = item.get('iseditable', False)
tooltip_text = item.get('tooltip_text')
tool_table.setItem(i, j, myWidgetItem(value, iseditable=iseditable))
if tooltip_text:
tool_table.item(i, j).setToolTip(tooltip_text)
# Add the test-button cell
test_button = QPushButton('Test')
test_button.clicked.connect(partial(self.handle_click_test_tool, tool))
test_button.setToolTip(f'Click to test the {tool} options')
tool_table.setCellWidget(0, num_cols-1, test_button)
tool_table.cellChanged.connect(partial(self.tool_cell_was_changed, tool, n))
labels.append(label)
self.tables_options.append(tool_table)
# Create the plugin table
plugin_table = myQTableWidget(minimum=False)
plugin_label = QLabel('Plugins')
plugin_label.setToolTip('List of plugins')
plugin_table.setMouseTracking(True)
plugin_table.setColumnCount(3) # Always three columns (i.e. path, plugin, test-button)
horizontal_header = plugin_table.horizontalHeader()
horizontal_header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
horizontal_header.setSectionResizeMode(1, QHeaderView.Stretch)
horizontal_header.setSectionResizeMode(2, QHeaderView.Fixed)
horizontal_header.setVisible(False)
self.plugin_table = plugin_table
self.update_plugintable()
# Set-up the tab layout and add the tables
layout = QVBoxLayout()
for label, tool_table in zip(labels, self.tables_options):
layout.addWidget(label)
layout.addWidget(tool_table)
layout.addWidget(plugin_label)
layout.addWidget(plugin_table)
layout.addStretch(1)
tab2 = QtWidgets.QWidget()
tab2.setObjectName('Options')
tab2.setLayout(layout)
self.tabwidget.addTab(tab2, '')
def update_subses_and_samples(self, output_bidsmap):
"""(Re)populates the sample list with bidsnames according to the bidsmap"""
self.output_bidsmap = output_bidsmap # input main window / output from edit window -> output main window
# Update the subject / session table
subitem = myWidgetItem('subject', iseditable=False)
subitem.setToolTip(bids.get_bidshelp('sub'))
sesitem = myWidgetItem('session', iseditable=False)
sesitem.setToolTip(bids.get_bidshelp('ses'))
subses_table = self.subses_table
subses_table.setItem(0, 0, subitem)
subses_table.setItem(1, 0, sesitem)
subses_table.setItem(0, 1, myWidgetItem(output_bidsmap[self.dataformat]['subject']))
subses_table.setItem(1, 1, myWidgetItem(output_bidsmap[self.dataformat]['session']))
# Update the run samples table
idx = 0
samples_table = self.samples_table
samples_table.blockSignals(True)
samples_table.setSortingEnabled(False)
samples_table.clearContents()
for datatype in bids.bidsdatatypes + (bids.unknowndatatype, bids.ignoredatatype):
runs = output_bidsmap.get(self.dataformat, {}).get(datatype, [])
if not runs: continue
for run in runs:
provenance = Path(run['provenance'])
subid, sesid = bids.get_subid_sesid(provenance,
output_bidsmap[self.dataformat]['subject'],
output_bidsmap[self.dataformat]['session'],
self.subprefix, self.sesprefix)
bidsname = bids.get_bidsname(subid, sesid, run)
session = self.bidsfolder/subid/sesid
row_index = self.ordered_file_index[provenance]
samples_table.setItem(idx, 0, QTableWidgetItem(f"{row_index+1:03d}"))
samples_table.setItem(idx, 1, QTableWidgetItem(provenance.name))
samples_table.setItem(idx, 2, QTableWidgetItem(datatype)) # Hidden column
samples_table.setItem(idx, 3, QTableWidgetItem(str(Path(datatype)/bidsname) + '.*'))
samples_table.setItem(idx, 5, QTableWidgetItem(str(provenance))) # Hidden column
samples_table.item(idx, 0).setFlags(QtCore.Qt.NoItemFlags)
samples_table.item(idx, 1).setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
samples_table.item(idx, 2).setFlags(QtCore.Qt.ItemIsEnabled)
samples_table.item(idx, 3).setFlags(QtCore.Qt.ItemIsEnabled)
samples_table.item(idx, 1).setToolTip('Double-click to inspect the header information (Copy: Ctrl+C)')
samples_table.item(idx, 1).setStatusTip(str(provenance.parent) + str(Path('/')))
samples_table.item(idx, 3).setStatusTip(str(session) + str(Path('/')))
if samples_table.item(idx, 3):
if datatype == bids.unknowndatatype:
samples_table.item(idx, 3).setForeground(QtGui.QColor('red'))
samples_table.item(idx, 3).setToolTip(f"Red: This imaging data type is not part of BIDS but will be converted to a BIDS-like entry in the '{bids.unknowndatatype}' folder")
elif datatype == bids.ignoredatatype:
samples_table.item(idx, 1).setForeground(QtGui.QColor('gray'))
samples_table.item(idx, 3).setForeground(QtGui.QColor('gray'))
f = samples_table.item(idx, 3).font()
f.setStrikeOut(True)
samples_table.item(idx, 3).setFont(f)
samples_table.item(idx, 3).setToolTip('Gray / Strike-out: This imaging data type will be ignored and not converted BIDS')
else:
samples_table.item(idx, 3).setForeground(QtGui.QColor('green'))
samples_table.item(idx, 3).setToolTip(f"Green: This '{datatype}' imaging data type is part of BIDS")
edit_button = QPushButton('Edit')
edit_button.setToolTip('Click to see more details and edit the BIDS output name')
edit_button.clicked.connect(self.handle_edit_button_clicked)
edit_button.setCheckable(not sys.platform.startswith('darwin'))
edit_button.setAutoExclusive(True)
if provenance.name and str(provenance)==self.has_edit_dialog_open: # Highlight the previously opened item
edit_button.setChecked(True)
else:
edit_button.setChecked(False)
samples_table.setCellWidget(idx, 4, edit_button)
idx += 1
samples_table.setSortingEnabled(True)
samples_table.blockSignals(False)
def set_tab_bidsmap(self):
"""Set the SOURCE file sample listing tab. """
# Set the Participant labels table
subses_label = QLabel('Participant labels')
subses_label.setToolTip('Subject/session mapping')
self.subses_table = myQTableWidget()
subses_table = self.subses_table
subses_table.setToolTip(f"Use <<SourceFilePath>> to parse the subject and (optional) session label from the pathname\n"
f"Use <Your{self.dataformat}FieldName> (e.g. <PatientID>) to extract the subject and (optional) session label from the {self.dataformat} header")
subses_table.setMouseTracking(True)
subses_table.setRowCount(2)
subses_table.setColumnCount(2)
horizontal_header = subses_table.horizontalHeader()
horizontal_header.setVisible(False)
horizontal_header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
horizontal_header.setSectionResizeMode(1, QHeaderView.Stretch)
subses_table.cellChanged.connect(self.subses_cell_was_changed)
# Set the BIDSmap table
provenance = bids.dir_bidsmap(self.input_bidsmap, self.dataformat)
ordered_file_index = {} # The mapping between the ordered provenance and an increasing file-index
num_files = 0
for file_index, file_name in enumerate(provenance):
ordered_file_index[file_name] = file_index
num_files = file_index + 1
self.ordered_file_index = ordered_file_index
label = QLabel('Data samples')
label.setToolTip('List of unique source-data samples')
self.samples_table = myQTableWidget(minimum=False)
samples_table = self.samples_table
samples_table.setMouseTracking(True)
samples_table.setShowGrid(True)
samples_table.setColumnCount(6)
samples_table.setRowCount(num_files)
samples_table.setHorizontalHeaderLabels(['', f'{self.dataformat} input', 'BIDS data type', 'BIDS output', 'Action', 'Provenance'])
samples_table.setSortingEnabled(True)
samples_table.sortByColumn(0, QtCore.Qt.AscendingOrder)
samples_table.setColumnHidden(2, True)
samples_table.setColumnHidden(5, True)
samples_table.itemDoubleClicked.connect(self.inspect_sourcefile)
header = samples_table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch) # Temporarily set it to Stretch to have Qt set the right window width -> set to Stretch in setupUI -> not reload
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
self.update_subses_and_samples(self.output_bidsmap)
layout = QVBoxLayout()
layout.addWidget(subses_label)
layout.addWidget(subses_table)
layout.addWidget(label)
layout.addWidget(samples_table)
tab3 = QtWidgets.QWidget()
tab3.setObjectName('BIDSmapping')
tab3.setLayout(layout)
self.tabwidget.addTab(tab3, '')
def get_help(self):
"""Get online help. """
webbrowser.open(MAIN_HELP_URL)
def get_bids_help(self):
"""Get online help. """
webbrowser.open(HELP_URL_DEFAULT)
def reload(self):
"""Reset button: reload the original input BIDS map. """
if self.has_edit_dialog_open:
self.dialog_edit.reject(confirm=False)
LOGGER.info('User reloads the bidsmap')
current_tab_index = self.tabwidget.currentIndex()
self.output_bidsmap, _ = bids.load_bidsmap(self.bidsmap_filename)
self.setupUi(self.MainWindow,
self.bidsfolder,
self.bidsmap_filename,
self.input_bidsmap,
self.output_bidsmap,
self.template_bidsmap,
self.dataformat,
selected_tab_index=current_tab_index,
reload=True)
# Start with a fresh errorlog
for filehandler in LOGGER.handlers:
if filehandler.name=='errorhandler' and Path(filehandler.baseFilename).stat().st_size:
errorfile = filehandler.baseFilename
LOGGER.info(f"Resetting {errorfile}")
with open(errorfile, 'w'): # TODO: This works but it is a hack that somehow prefixes a lot of whitespace to the first LOGGER call
pass
def save_bidsmap_to_file(self):
"""Check and save the BIDSmap to file. """
if self.output_bidsmap[self.dataformat].get('fmap'):
for run in self.output_bidsmap[self.dataformat]['fmap']:
if not run['bids']['IntendedFor']:
LOGGER.warning(f"IntendedFor fieldmap value is empty for {run['provenance']}")
filename, _ = QFileDialog.getSaveFileName(self.MainWindow, 'Save File',
str(self.bidsfolder/'code'/'bidscoin'/'bidsmap.yaml'),
'YAML Files (*.yaml *.yml);;All Files (*)')
if filename:
bids.save_bidsmap(Path(filename), self.output_bidsmap)
QtCore.QCoreApplication.setApplicationName(f"{filename} - BIDS editor")
def handle_edit_button_clicked(self):
"""Make sure that index map has been updated. """
button = self.MainWindow.focusWidget()
rowindex = self.samples_table.indexAt(button.pos()).row()
datatype = self.samples_table.item(rowindex, 2).text()
provenance = Path(self.samples_table.item(rowindex, 5).text())
self.open_edit_dialog(provenance, datatype)
def on_double_clicked(self, index: int):
"""Opens the inspect window when a source file in the file-tree tab is double-clicked"""
sourcefile = Path(self.model.fileInfo(index).absoluteFilePath())
if bids.is_dicomfile(sourcefile):
sourcedata = pydicom.dcmread(sourcefile, force=True)
elif bids.is_parfile(sourcefile):
with open(sourcefile, 'r') as parfid:
sourcedata = parfid.read()
else:
LOGGER.warning(f"Could not read {self.dataformat} file: {sourcefile}")
return
self.popup = InspectWindow(sourcefile, sourcedata, self.dataformat)
self.popup.show()
self.popup.scrollbar.setValue(0) # This can only be done after self.popup.show()
def show_about(self):
"""Shows a pop-up window with the BIDScoin version"""
about = f"BIDS editor\n{bids.version()}"
QMessageBox.about(self.MainWindow, 'About', about)
def open_edit_dialog(self, provenance: Path, datatype: str, modal=False):
"""Check for open edit window, find the right datatype index and open the edit window"""
if not self.has_edit_dialog_open:
# Find the source index of the run in the list of runs (using the provenance) and open the edit window
for run in self.output_bidsmap[self.dataformat][datatype]:
if run['provenance']==str(provenance):
LOGGER.info(f'User is editing {provenance}')
self.dialog_edit = EditDialog(self.dataformat, provenance, datatype, self.output_bidsmap, self.template_bidsmap, self.subprefix, self.sesprefix)
if provenance.name:
self.has_edit_dialog_open = str(provenance)
else:
self.has_edit_dialog_open = True
self.dialog_edit.done_edit.connect(self.update_subses_and_samples)
self.dialog_edit.finished.connect(self.release_edit_dialog)
if modal:
self.dialog_edit.exec()
else:
self.dialog_edit.show()
break
else:
# Ask the user if he wants to save his results first before opening a new edit window
self.dialog_edit.reject()
if self.has_edit_dialog_open:
return
self.open_edit_dialog(provenance, datatype, modal)
def release_edit_dialog(self):
"""Allow a new edit window to be opened"""
self.has_edit_dialog_open = None
def exit_application(self):
"""Handle exit. """
self.MainWindow.close()
class EditDialog(QDialog):
"""
EditDialog().result() == 1: done with result, i.e. done_edit -> new bidsmap
EditDialog().result() == 2: done without result
"""
# Emit the new bidsmap when done (see docstring)
done_edit = QtCore.pyqtSignal(dict)
def __init__(self, dataformat: str, provenance: Path, datatype: str, bidsmap: dict, template_bidsmap: dict, subprefix='sub-', sesprefix='ses-'):
super().__init__()
# Set the data
self.dataformat = dataformat
self.source_datatype = datatype
self.target_datatype = datatype
self.current_datatype = datatype
self.source_bidsmap = bidsmap
self.target_bidsmap = copy.deepcopy(bidsmap)
self.template_bidsmap = template_bidsmap
for run in bidsmap[self.dataformat][datatype]:
if run['provenance'] == str(provenance):
self.source_run = run
self.target_run = copy.deepcopy(self.source_run)
self.get_allowed_suffixes()
self.subid, self.sesid = bids.get_subid_sesid(Path(self.source_run['provenance']),
bidsmap[dataformat]['subject'],
bidsmap[dataformat]['session'],
subprefix, sesprefix)
# Set-up the window
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(str(ICON_FILENAME)), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(icon)
self.setWindowFlags(QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMaximizeButtonHint)
self.setWindowTitle('Edit BIDS mapping')
# Get data for the tables
data_provenance, data_source, data_bids = self.get_editwin_data()
# Set-up the provenance table
self.provenance_label = QLabel()
self.provenance_label.setText('Provenance')
self.provenance_table = self.set_table(data_provenance)
self.provenance_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.provenance_table.setToolTip(f"The {self.dataformat} source file from which the attributes were taken (Copy: Ctrl+C)")
self.provenance_table.cellDoubleClicked.connect(self.inspect_sourcefile)
# Set-up the source table
self.source_label = QLabel()
self.source_label.setText('Attributes')
self.source_table = self.set_table(data_source, minimum=False)
self.source_table.cellChanged.connect(self.source_cell_changed)
self.source_table.setToolTip(f"The {self.dataformat} attributes that are used to uniquely identify source files. NB: Expert usage (e.g. using '*string*' wildcards, see documentation), only change these if you know what you are doing!")
# Set-up the datatype dropdown menu
self.label_dropdown = QLabel()
self.label_dropdown.setText('Data type')
self.datatype_dropdown = QComboBox()
self.datatype_dropdown.addItems(bids.bidsdatatypes + (bids.unknowndatatype, bids.ignoredatatype))
self.datatype_dropdown.setCurrentIndex(self.datatype_dropdown.findText(self.target_datatype))
self.datatype_dropdown.currentIndexChanged.connect(self.datatype_dropdown_change)
self.datatype_dropdown.setToolTip('The BIDS data type. First make sure this one is correct, then choose the right suffix')
# Set-up the BIDS table
self.bids_label = QLabel()
self.bids_label.setText('Entities')
self.bids_table = self.set_table(data_bids, minimum=False)
self.bids_table.setToolTip(f"The BIDS value that is used to construct the BIDS output name. You can freely change the value to be more meaningful and readable")
self.bids_table.cellChanged.connect(self.bids_cell_changed)
# Set-up non-editable BIDS output name section
self.label_bids_name = QLabel()
self.label_bids_name.setText('Output name')
self.view_bids_name = QTextBrowser()
self.view_bids_name.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.view_bids_name.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.view_bids_name.setMinimumHeight(ROW_HEIGHT + 2)
self.refresh_bidsname()
# Group the tables in boxes
sizepolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizepolicy.setHorizontalStretch(1)
groupbox1 = QGroupBox(self.dataformat + ' input')
groupbox1.setSizePolicy(sizepolicy)
layout1 = QVBoxLayout()
layout1.addWidget(self.provenance_label)
layout1.addWidget(self.provenance_table)
layout1.addWidget(self.source_label)
layout1.addWidget(self.source_table)
groupbox1.setLayout(layout1)
groupbox2 = QGroupBox('BIDS output')
groupbox2.setSizePolicy(sizepolicy)
layout2 = QVBoxLayout()
layout2.addWidget(self.label_dropdown)
layout2.addWidget(self.datatype_dropdown)
layout2.addWidget(self.bids_label)
layout2.addWidget(self.bids_table)
layout2.addWidget(self.label_bids_name)
layout2.addWidget(self.view_bids_name)
groupbox2.setLayout(layout2)
# Add the boxes to the layout
layout_tables = QHBoxLayout()
layout_tables.addWidget(groupbox1)
layout_tables.addWidget(groupbox2)
# Set-up buttons
buttonBox = QDialogButtonBox()
exportbutton = buttonBox.addButton('Export', QDialogButtonBox.ActionRole)
exportbutton.setIcon(QtGui.QIcon.fromTheme('document-save'))
exportbutton.setToolTip('Export this run item to an existing (template) bidsmap')
exportbutton.clicked.connect(self.export_run)
buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Reset | QDialogButtonBox.Help)
buttonBox.button(QDialogButtonBox.Reset).setToolTip('Reset the edits you made')
buttonBox.button(QDialogButtonBox.Ok).setToolTip('Apply the edits you made and close this window')
buttonBox.button(QDialogButtonBox.Cancel).setToolTip('Discard the edits you made and close this window')
buttonBox.button(QDialogButtonBox.Help).setToolTip('Go to the online BIDS specification for more info')
buttonBox.accepted.connect(self.accept_run)
buttonBox.rejected.connect(partial(self.reject, False))
buttonBox.helpRequested.connect(self.get_help)
buttonBox.button(QDialogButtonBox.Reset).clicked.connect(self.reset)
# Set-up the main layout
layout_all = QVBoxLayout(self)
layout_all.addLayout(layout_tables)
layout_all.addWidget(buttonBox)
self.center()
finish = QAction(self)
finish.triggered.connect(self.closeEvent)
def center(self):
"""Center the edit window. """
cp = QDesktopWidget().availableGeometry().center() # Center point of screen
qr = self.frameGeometry() # Get the rectangular geometry
qr.moveCenter(cp) # Move rectangle's center point to screen's center point
self.move(qr.topLeft()) # Top left of rectangle becomes top left of window centering it
def get_allowed_suffixes(self):
"""Derive the possible suffixes for each datatype from the template. """
allowed_suffixes = {}
for datatype in bids.bidsdatatypes + (bids.unknowndatatype, bids.ignoredatatype):
allowed_suffixes[datatype] = []
runs = self.template_bidsmap.get(self.dataformat, {}).get(datatype, [])
if not runs: continue
for run in runs:
suffix = run['bids'].get('suffix')
if suffix and suffix not in allowed_suffixes.get(datatype, []):
allowed_suffixes[datatype].append(suffix)
self.allowed_suffixes = allowed_suffixes