-
Notifications
You must be signed in to change notification settings - Fork 5
/
IDCBrowser.py
1619 lines (1408 loc) · 65.2 KB
/
IDCBrowser.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
# Future imports
from __future__ import division
# Standard library imports
import codecs
import csv
import json
import logging
import os.path
import pickle
import string
import time
import unittest
import webbrowser
import xml.etree.ElementTree as ET
import zipfile
from random import randint
# Third-party imports
import pydicom
import pkg_resources
import qt
import urllib
#slicer
from __main__ import vtk, qt, ctk, slicer
# Local application imports
from slicer.ScriptedLoadableModule import *
#
# IDCBrowser
#
class IDCBrowser(ScriptedLoadableModule):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
parent.title = "SlicerIDCBrowser"
parent.categories = ["Informatics"]
parent.dependencies = []
parent.contributors = ["Andrey Fedorov (SPL, BWH)"]
parent.helpText = """ Explore the content of NCI Imaging Data Commons and download DICOM data into 3D Slicer. See <a href=\"https://github.com/ImagingDataCommons/SlicerIDCBrowser\">
the documentation</a> for more information. This project has been funded in whole or in part with Federal funds from the National Cancer Institute, National Institutes of Health, under Task Order No. HHSN26110071 under Contract No. HHSN261201500003l.
"""
#
# qIDCBrowserWidget
#
class IDCBrowserWidget(ScriptedLoadableModuleWidget):
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.setup(self)
self.loadToScene = False
# This module is often used in developer mode, therefore
# collapse reload & test section by default.
if hasattr(self, "reloadCollapsibleButton"):
self.reloadCollapsibleButton.collapsed = True
self.logic = IDCBrowserLogic()
logging.info("Checking requirements ...")
self.logic.setupPythonRequirements()
from idc_index import index
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
logging.info("Initializing IDC client ...")
startTime = time.time()
self.IDCClient = index.IDCClient()
logging.info("IDC Client initialized in {0:.2f} seconds.".format(time.time() - startTime))
qt.QApplication.restoreOverrideCursor()
logging.debug("s5cmd path: " + self.IDCClient.s5cmdPath)
self.IDCClient.IDCIndexPath = self.logic.getIDCIndexPath()
logging.debug("IDCIndex path: " + self.IDCClient.IDCIndexPath)
logging.info("Initialization done.")
self.browserWidget = qt.QWidget()
self.browserWidget.setWindowTitle('SlicerIDCBrowser | NCI Imaging Data Commons data release '+self.logic.idc_version)
self.initialConnection = False
self.seriesTableRowCount = 0
self.studiesTableRowCount = 0
self.downloadProgressBars = {}
self.downloadProgressLabels = {}
self.selectedSeriesNicknamesDic = {}
self.downloadQueue = {}
self.seriesRowNumber = {}
self.imagesToDownloadCount = 0
self.downloadProgressBarWidgets = []
item = qt.QStandardItem()
# Load settings from the system
self.settings = qt.QSettings()
# Put the files downloaded from IDC in the DICOM database folder by default.
# This makes downloaded files relocatable along with the DICOM database in
# recent Slicer versions.
if not os.path.isfile(slicer.dicomDatabase.databaseFilename):
dicomBrowser = ctk.ctkDICOMBrowser()
dicomBrowser.databaseDirectory = slicer.dicomDatabase.databaseDirectory
dicomBrowser.createNewDatabaseDirectory()
slicer.dicomDatabase.openDatabase(slicer.dicomDatabase.databaseFilename)
logging.info("DICOM database created")
else:
logging.info('DICOM database is available at '+slicer.dicomDatabase.databaseFilename)
slicer.dicomDatabase.updateSchemaIfNeeded()
databaseDirectory = slicer.dicomDatabase.databaseDirectory
self.storagePath = self.settings.value("IDCCustomStoragePath") if self.settings.contains("IDCCustomStoragePath") else databaseDirectory + "/IDCLocal/"
logging.debug("IDC downloaded data storage path: " + self.storagePath)
if not os.path.exists(self.storagePath):
os.makedirs(self.storagePath)
if not self.settings.contains("IDCDefaultStoragePath"):
self.settings.setValue("IDCDefaultStoragePath", (databaseDirectory + "/IDCLocal/"))
self.cachePath = self.storagePath + "/ServerResponseCache/"
logging.debug("IDC cache path: " + self.cachePath)
self.downloadedSeriesArchiveFile = self.storagePath + 'archive.p'
if os.path.isfile(self.downloadedSeriesArchiveFile):
print("Reading "+self.downloadedSeriesArchiveFile)
f = open(self.downloadedSeriesArchiveFile, 'rb')
self.previouslyDownloadedSeries = pickle.load(f)
f.close()
else:
with open(self.downloadedSeriesArchiveFile, 'wb') as f:
self.previouslyDownloadedSeries = []
pickle.dump(self.previouslyDownloadedSeries, f)
f.close()
if not os.path.exists(self.cachePath):
os.makedirs(self.cachePath)
self.useCacheFlag = False
# Instantiate and connect widgets ...
if 'IDCBrowser' in slicer.util.moduleNames():
self.modulePath = slicer.modules.idcbrowser.path.replace("IDCBrowser.py", "")
else:
self.modulePath = '.'
self.reportIcon = qt.QIcon(self.modulePath + '/Resources/Icons/report.png')
downloadAndIndexIcon = qt.QIcon(self.modulePath + '/Resources/Icons/downloadAndIndex.png')
downloadAndLoadIcon = qt.QIcon(self.modulePath + '/Resources/Icons/downloadAndLoad.png')
browserIcon = qt.QIcon(self.modulePath + '/Resources/Icons/IDCBrowser.png')
cancelIcon = qt.QIcon(self.modulePath + '/Resources/Icons/cancel.png')
self.downloadIcon = qt.QIcon(self.modulePath + '/Resources/Icons/download.png')
self.storedlIcon = qt.QIcon(self.modulePath + '/Resources/Icons/stored.png')
self.browserWidget.setWindowIcon(browserIcon)
#
# Reload and Test area
#
reloadCollapsibleButton = ctk.ctkCollapsibleButton()
reloadCollapsibleButton.text = "Reload && Test"
# uncomment the next line for developing and testing
# self.layout.addWidget(reloadCollapsibleButton)
reloadFormLayout = qt.QFormLayout(reloadCollapsibleButton)
# reload button
# (use this during development, but remove it when delivering
# your module to users)
self.reloadButton = qt.QPushButton("Reload")
self.reloadButton.toolTip = "Reload this module."
self.reloadButton.name = "IDCBrowser Reload"
reloadFormLayout.addWidget(self.reloadButton)
self.reloadButton.connect('clicked()', self.onReload)
# reload and test button
# (use this during development, but remove it when delivering
# your module to users)
self.reloadAndTestButton = qt.QPushButton("Reload and Test")
self.reloadAndTestButton.toolTip = "Reload this module and then run the self tests."
reloadFormLayout.addWidget(self.reloadAndTestButton)
self.reloadAndTestButton.connect('clicked()', self.onReloadAndTest)
#
# Browser Area
#
browserCollapsibleButton = ctk.ctkCollapsibleButton()
browserCollapsibleButton.text = "SlicerIDCBrowser | NCI Imaging Data Commons data release " + self.logic.idc_version
self.layout.addWidget(browserCollapsibleButton)
browserLayout = qt.QVBoxLayout(browserCollapsibleButton)
self.popupGeometry = qt.QRect()
settings = qt.QSettings()
mainWindow = slicer.util.mainWindow()
if mainWindow:
width = mainWindow.width * 0.75
height = mainWindow.height * 0.75
self.popupGeometry.setWidth(width)
self.popupGeometry.setHeight(height)
self.popupPositioned = False
self.browserWidget.setGeometry(self.popupGeometry)
#
# Show Browser Button
#
self.showBrowserButton = qt.QPushButton("Show Browser")
# self.showBrowserButton.toolTip = "."
self.showBrowserButton.enabled = False
browserLayout.addWidget(self.showBrowserButton)
# Browser Widget Layout within the collapsible button
browserWidgetLayout = qt.QVBoxLayout(self.browserWidget)
self.collectionsCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox()
self.collectionsCollapsibleGroupBox.setTitle('Collections')
browserWidgetLayout.addWidget(self.collectionsCollapsibleGroupBox) #
collectionsFormLayout = qt.QHBoxLayout(self.collectionsCollapsibleGroupBox)
#
# Manifest Downloader Area
#
downloaderCollapsibleButton = ctk.ctkCollapsibleButton()
downloaderCollapsibleButton.text = "IDC Portal manifest downloader"
self.layout.addWidget(downloaderCollapsibleButton)
downloaderLayout = qt.QGridLayout(downloaderCollapsibleButton)
comment = qt.QTextEdit()
# Add hyperlink
comment.append("You can use this section of the module to download data from Imaging Data Commons based on your selection in <a href=\"http://imaging.datacommons.cancer.gov\">IDC Portal</a>. Populate any of the fields below to download data based on your selection: download manifest created using IDC Portal, or PatientID, StudyInstanceUID or SeriesInstanceUID.<br>")
comment.setReadOnly(True)
downloaderLayout.addWidget(comment, 0, 0, 1, 4)
# TODO: add automatic check for the validity of the entered text
# add manifest file selector
label = qt.QLabel('s5cmd manifest:')
self.manifestSelector = ctk.ctkPathLineEdit()
self.downloadFromManifestButton = qt.QPushButton("D")
self.downloadAndIndexFromManifestButton = qt.QPushButton("DI")
downloaderLayout.addWidget(label, 1, 0)
downloaderLayout.addWidget(self.manifestSelector, 1, 1)
#downloaderLayout.addWidget(self.downloadFromManifestButton, 1, 2)
#downloaderLayout.addWidget(self.downloadAndIndexFromManifestButton, 1, 3)
# add download by PatientID
label = qt.QLabel('PatientID:')
self.patientIDSelector = qt.QLineEdit()
self.patientIDSelector.setPlaceholderText('Enter PatientID here')
self.downloadFromPatientIDButton = qt.QPushButton("D")
self.downloadAndIndexFromPatientIDButton = qt.QPushButton("DI")
downloaderLayout.addWidget(label, 2, 0)
downloaderLayout.addWidget(self.patientIDSelector, 2, 1)
#downloaderLayout.addWidget(self.downloadFromPatientIDButton, 2, 2)
#downloaderLayout.addWidget(self.downloadAndIndexFromPatientIDButton, 2, 3)
# add download by StudyInstanceUID
label = qt.QLabel('StudyInstanceUID:')
self.studyUIDSelector = qt.QLineEdit()
self.studyUIDSelector.setPlaceholderText('Enter DICOM StudyInstanceUID here')
self.downloadFromStudyUIDButton = qt.QPushButton("D")
self.downloadAndIndexFromStudyUIDButton = qt.QPushButton("DI")
downloaderLayout.addWidget(label, 3, 0)
downloaderLayout.addWidget(self.studyUIDSelector, 3, 1)
#downloaderLayout.addWidget(self.downloadFromStudyUIDButton, 3, 2)
#downloaderLayout.addWidget(self.downloadAndIndexFromStudyUIDButton, 3, 3)
# add download by SeriesInstanceUID
label = qt.QLabel('SeriesInstanceUID:')
self.seriesUIDSelector = qt.QLineEdit()
self.seriesUIDSelector.setPlaceholderText('Enter DICOM SeriesInstanceUID here')
self.downloadFromSeriesUIDButton = qt.QPushButton("D")
self.downloadAndIndexFromSeriesUIDButton = qt.QPushButton("DI")
downloaderLayout.addWidget(label, 4, 0)
downloaderLayout.addWidget(self.seriesUIDSelector, 4, 1)
#downloaderLayout.addWidget(self.downloadFromSeriesUIDButton, 4, 2)
#downloaderLayout.addWidget(self.downloadAndIndexFromSeriesUIDButton, 4, 3)
# add output directory selector
label = qt.QLabel('Download directory:')
self.downloadDestinationSelector = ctk.ctkDirectoryButton()
self.downloadDestinationSelector.caption = 'Output directory'
self.downloadDestinationSelector.directory = self.storagePath
downloaderLayout.addWidget(label, 5, 0)
downloaderLayout.addWidget(self.downloadDestinationSelector, 5, 1, 1, 3)
self.download_status = qt.QLabel('Download status: Ready')
downloaderLayout.addWidget(self.download_status, 6, 0)
#
# Show Download Button
#
self.downloadButton = ctk.ctkMenuButton()
self.downloadButton.text = "Download, import and load into scene"
downloadButtonMenu = qt.QMenu("Download options", self.downloadButton)
self.downloadButton.setMenu(downloadButtonMenu)
self.importOnDownloadAction = qt.QAction("Import downloaded files to DICOM database", downloadButtonMenu)
self.importOnDownloadAction.setToolTip("If enabled, all downloaded files are imported into the DICOM database.")
self.importOnDownloadAction.setCheckable(True)
self.importOnDownloadAction.setChecked(True)
downloadButtonMenu.addAction(self.importOnDownloadAction)
self.loadOnDownloadAction = qt.QAction("Open downloaded series", downloadButtonMenu)
self.loadOnDownloadAction.setToolTip("If enabled, all downloaded files are imported into the DICOM database and loaded into the scene.")
self.loadOnDownloadAction.setCheckable(False)
self.loadOnDownloadAction.setChecked(False)
#downloadButtonMenu.addAction(self.loadOnDownloadAction)
self.onDownloadOptionsToggled(False)
downloaderLayout.addWidget(self.downloadButton, 7,0,1,3)
#
# Collection Selector ComboBox
#
self.collectionSelectorLabel = qt.QLabel('Select collection:')
collectionsFormLayout.addWidget(self.collectionSelectorLabel)
# Selector ComboBox
self.collectionSelector = qt.QComboBox()
self.collectionSelector.setMinimumWidth(200)
collectionsFormLayout.addWidget(self.collectionSelector)
collectionsFormLayout.addStretch(4)
logoLabelText = "IDC release "+self.logic.idc_version
self.logoLabel = qt.QLabel(logoLabelText)
collectionsFormLayout.addWidget(self.logoLabel)
#Patient Table Widget
self.patientsCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox()
self.patientsCollapsibleGroupBox.setTitle('Patients')
browserWidgetLayout.addWidget(self.patientsCollapsibleGroupBox)
patientsVBoxLayout1 = qt.QVBoxLayout(self.patientsCollapsibleGroupBox)
patientsExpdableArea = ctk.ctkExpandableWidget()
patientsVBoxLayout1.addWidget(patientsExpdableArea)
patientsVBoxLayout2 = qt.QVBoxLayout(patientsExpdableArea)
# patientsVerticalLayout = qt.QVBoxLayout(patientsExpdableArea)
self.patientsTableWidget = qt.QTableWidget()
self.patientsModel = qt.QStandardItemModel()
self.patientsTableHeaderLabels = ['Patient ID', 'Patient Sex', 'Patient Age']
self.patientsTableWidget.setColumnCount(3)
self.patientsTableWidget.sortingEnabled = True
self.patientsTableWidget.setHorizontalHeaderLabels(self.patientsTableHeaderLabels)
self.patientsTableWidgetHeader = self.patientsTableWidget.horizontalHeader()
self.patientsTableWidgetHeader.setStretchLastSection(True)
# patientsTableWidgetHeader.setResizeMode(qt.QHeaderView.Stretch)
patientsVBoxLayout2.addWidget(self.patientsTableWidget)
self.patientsTreeSelectionModel = self.patientsTableWidget.selectionModel()
abstractItemView = qt.QAbstractItemView()
self.patientsTableWidget.setSelectionBehavior(abstractItemView.SelectRows)
verticalheader = self.patientsTableWidget.verticalHeader()
verticalheader.setDefaultSectionSize(20)
patientsVBoxLayout1.setSpacing(0)
patientsVBoxLayout2.setSpacing(0)
patientsVBoxLayout1.setMargin(0)
patientsVBoxLayout2.setContentsMargins(7, 3, 7, 7)
#
# Studies Table Widget
#
self.studiesCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox()
self.studiesCollapsibleGroupBox.setTitle('Studies')
browserWidgetLayout.addWidget(self.studiesCollapsibleGroupBox)
studiesVBoxLayout1 = qt.QVBoxLayout(self.studiesCollapsibleGroupBox)
studiesExpdableArea = ctk.ctkExpandableWidget()
studiesVBoxLayout1.addWidget(studiesExpdableArea)
studiesVBoxLayout2 = qt.QVBoxLayout(studiesExpdableArea)
self.studiesTableWidget = qt.QTableWidget()
self.studiesTableWidget.setCornerButtonEnabled(True)
self.studiesModel = qt.QStandardItemModel()
self.studiesTableHeaderLabels = ['Study Instance UID', 'Study Date', 'Study Description', 'Series Count']
self.studiesTableWidget.setColumnCount(4)
self.studiesTableWidget.sortingEnabled = True
self.studiesTableWidget.hideColumn(0)
self.studiesTableWidget.setHorizontalHeaderLabels(self.studiesTableHeaderLabels)
self.studiesTableWidget.resizeColumnsToContents()
studiesVBoxLayout2.addWidget(self.studiesTableWidget)
self.studiesTreeSelectionModel = self.studiesTableWidget.selectionModel()
self.studiesTableWidget.setSelectionBehavior(abstractItemView.SelectRows)
studiesVerticalheader = self.studiesTableWidget.verticalHeader()
studiesVerticalheader.setDefaultSectionSize(20)
self.studiesTableWidgetHeader = self.studiesTableWidget.horizontalHeader()
self.studiesTableWidgetHeader.setStretchLastSection(True)
studiesSelectOptionsWidget = qt.QWidget()
studiesSelectOptionsLayout = qt.QHBoxLayout(studiesSelectOptionsWidget)
studiesSelectOptionsLayout.setMargin(0)
studiesVBoxLayout2.addWidget(studiesSelectOptionsWidget)
studiesSelectLabel = qt.QLabel('Select:')
studiesSelectOptionsLayout.addWidget(studiesSelectLabel)
self.studiesSelectAllButton = qt.QPushButton('All')
self.studiesSelectAllButton.enabled = False
self.studiesSelectAllButton.setMaximumWidth(50)
studiesSelectOptionsLayout.addWidget(self.studiesSelectAllButton)
self.studiesSelectNoneButton = qt.QPushButton('None')
self.studiesSelectNoneButton.enabled = False
self.studiesSelectNoneButton.setMaximumWidth(50)
studiesSelectOptionsLayout.addWidget(self.studiesSelectNoneButton)
studiesSelectOptionsLayout.addStretch(1)
studiesVBoxLayout1.setSpacing(0)
studiesVBoxLayout2.setSpacing(0)
studiesVBoxLayout1.setMargin(0)
studiesVBoxLayout2.setContentsMargins(7, 3, 7, 7)
#
# Series Table Widget
#
self.seriesCollapsibleGroupBox = ctk.ctkCollapsibleGroupBox()
self.seriesCollapsibleGroupBox.setTitle('Series')
browserWidgetLayout.addWidget(self.seriesCollapsibleGroupBox)
seriesVBoxLayout1 = qt.QVBoxLayout(self.seriesCollapsibleGroupBox)
seriesExpdableArea = ctk.ctkExpandableWidget()
seriesVBoxLayout1.addWidget(seriesExpdableArea)
seriesVBoxLayout2 = qt.QVBoxLayout(seriesExpdableArea)
self.seriesTableWidget = qt.QTableWidget()
# self.seriesModel = qt.QStandardItemModel()
self.seriesTableWidget.setColumnCount(10)
self.seriesTableWidget.sortingEnabled = True
self.seriesTableWidget.hideColumn(0)
self.seriesTableHeaderLabels = ['Series Instance UID', 'Status', 'Modality',
'Series Date', 'Series Description', 'Body Part Examined',
'Series Number','Manufacturer',
'Manufacturer Model Name','Instance Count']
self.seriesTableWidget.setHorizontalHeaderLabels(self.seriesTableHeaderLabels)
self.seriesTableWidget.resizeColumnsToContents()
seriesVBoxLayout2.addWidget(self.seriesTableWidget)
self.seriesTreeSelectionModel = self.studiesTableWidget.selectionModel()
self.seriesTableWidget.setSelectionBehavior(abstractItemView.SelectRows)
self.seriesTableWidget.setSelectionMode(3)
self.seriesTableWidgetHeader = self.seriesTableWidget.horizontalHeader()
self.seriesTableWidgetHeader.setStretchLastSection(True)
# seriesTableWidgetHeader.setResizeMode(qt.QHeaderView.Stretch)
seriesVerticalheader = self.seriesTableWidget.verticalHeader()
seriesVerticalheader.setDefaultSectionSize(20)
seriesSelectOptionsWidget = qt.QWidget()
seriesSelectOptionsLayout = qt.QHBoxLayout(seriesSelectOptionsWidget)
seriesVBoxLayout2.addWidget(seriesSelectOptionsWidget)
seriesSelectOptionsLayout.setMargin(0)
seriesSelectLabel = qt.QLabel('Select:')
seriesSelectOptionsLayout.addWidget(seriesSelectLabel)
self.seriesSelectAllButton = qt.QPushButton('All')
self.seriesSelectAllButton.enabled = False
self.seriesSelectAllButton.setMaximumWidth(50)
seriesSelectOptionsLayout.addWidget(self.seriesSelectAllButton)
self.seriesSelectNoneButton = qt.QPushButton('None')
self.seriesSelectNoneButton.enabled = False
self.seriesSelectNoneButton.setMaximumWidth(50)
seriesSelectOptionsLayout.addWidget(self.seriesSelectNoneButton)
seriesVBoxLayout1.setSpacing(0)
seriesVBoxLayout2.setSpacing(0)
seriesVBoxLayout1.setMargin(0)
seriesVBoxLayout2.setContentsMargins(7, 3, 7, 7)
seriesSelectOptionsLayout.addStretch(1)
self.imagesCountLabel = qt.QLabel()
self.imagesCountLabel.text = 'No. of images to download: ' + '<span style=" font-size:8pt; font-weight:600; ' \
'color:#aa0000;">' + str(self.imagesToDownloadCount) + '</span>' + ' '
seriesSelectOptionsLayout.addWidget(self.imagesCountLabel)
# seriesSelectOptionsLayout.setAlignment(qt.Qt.AlignTop)
# Index Button
#
self.indexButton = qt.QPushButton()
self.indexButton.setMinimumWidth(50)
self.indexButton.toolTip = "Download and Index: The browser will download" \
" the selected series and index them in 3D Slicer DICOM Database."
self.indexButton.setIcon(downloadAndIndexIcon)
iconSize = qt.QSize(70, 40)
self.indexButton.setIconSize(iconSize)
# self.indexButton.setMinimumHeight(50)
self.indexButton.enabled = False
# downloadWidgetLayout.addStretch(4)
seriesSelectOptionsLayout.addWidget(self.indexButton)
# downloadWidgetLayout.addStretch(1)
#
# Load Button
#
self.loadButton = qt.QPushButton("")
self.loadButton.setMinimumWidth(50)
self.loadButton.setIcon(downloadAndLoadIcon)
self.loadButton.setIconSize(iconSize)
# self.loadButton.setMinimumHeight(50)
self.loadButton.toolTip = "Download and Load: The browser will download" \
" the selected series and Load them in 3D Slicer scene."
self.loadButton.enabled = False
seriesSelectOptionsLayout.addWidget(self.loadButton)
# downloadWidgetLayout.addStretch(4)
self.cancelDownloadButton = qt.QPushButton('')
seriesSelectOptionsLayout.addWidget(self.cancelDownloadButton)
self.cancelDownloadButton.setIconSize(iconSize)
self.cancelDownloadButton.toolTip = "Cancel all downloads."
self.cancelDownloadButton.setIcon(cancelIcon)
self.cancelDownloadButton.enabled = False
self.statusFrame = qt.QFrame()
browserWidgetLayout.addWidget(self.statusFrame)
statusHBoxLayout = qt.QHBoxLayout(self.statusFrame)
statusHBoxLayout.setMargin(0)
statusHBoxLayout.setSpacing(0)
self.statusLabel = qt.QLabel('')
statusHBoxLayout.addWidget(self.statusLabel)
statusHBoxLayout.addStretch(1)
#
# delete data context menu
#
self.seriesTableWidget.setContextMenuPolicy(2)
self.removeSeriesAction = qt.QAction("Remove from disk", self.seriesTableWidget)
self.seriesTableWidget.addAction(self.removeSeriesAction)
# self.removeSeriesAction.enabled = False
#
# Settings Area
#
settingsCollapsibleButton = ctk.ctkCollapsibleButton()
settingsCollapsibleButton.text = "Settings"
self.layout.addWidget(settingsCollapsibleButton)
settingsGridLayout = qt.QGridLayout(settingsCollapsibleButton)
settingsCollapsibleButton.collapsed = True
# Storage Path button
#
# storageWidget = qt.QWidget()
# storageFormLayout = qt.QFormLayout(storageWidget)
# settingsVBoxLayout.addWidget(storageWidget)
storagePathLabel = qt.QLabel("Storage Folder: ")
self.storagePathButton = ctk.ctkDirectoryButton()
self.storagePathButton.directory = self.storagePath
self.storageResetButton = qt.QPushButton("Reset Path")
self.storageResetButton.toolTip = "Resetting the storage folder to default."
self.storageResetButton.enabled = True if self.settings.contains("IDCCustomStoragePath") else False
settingsGridLayout.addWidget(storagePathLabel, 0, 0, 1, 1)
settingsGridLayout.addWidget(self.storagePathButton, 0, 1, 1, 2)
settingsGridLayout.addWidget(self.storageResetButton, 0, 3, 1, 1)
# connections
self.showBrowserButton.connect('clicked(bool)', self.onShowBrowserButton)
self.downloadButton.connect('clicked(bool)', self.onDownloadButton)
self.collectionSelector.connect('currentIndexChanged(QString)', self.collectionSelected)
self.patientsTableWidget.connect('itemSelectionChanged()', self.patientsTableSelectionChanged)
self.studiesTableWidget.connect('itemSelectionChanged()', self.studiesTableSelectionChanged)
self.seriesTableWidget.connect('itemSelectionChanged()', self.seriesSelected)
#self.useCacheCeckBox.connect('stateChanged(int)', self.onUseCacheStateChanged)
self.indexButton.connect('clicked(bool)', self.onIndexButton)
self.loadButton.connect('clicked(bool)', self.onLoadButton)
self.cancelDownloadButton.connect('clicked(bool)', self.onCancelDownloadButton)
self.storagePathButton.connect('directoryChanged(const QString &)', self.onStoragePathButton)
self.storageResetButton.connect('clicked(bool)', self.onStorageResetButton)
self.removeSeriesAction.connect('triggered()', self.onRemoveSeriesContextMenuTriggered)
self.seriesSelectAllButton.connect('clicked(bool)', self.onSeriesSelectAllButton)
self.seriesSelectNoneButton.connect('clicked(bool)', self.onSeriesSelectNoneButton)
self.studiesSelectAllButton.connect('clicked(bool)', self.onStudiesSelectAllButton)
self.studiesSelectNoneButton.connect('clicked(bool)', self.onStudiesSelectNoneButton)
self.loadOnDownloadAction.connect('toggled(bool)', self.onDownloadOptionsToggled)
self.importOnDownloadAction.connect('toggled(bool)', self.onDownloadOptionsToggled)
# Add vertical spacer
self.layout.addStretch(1)
if self.showBrowserButton != None and self.showBrowserButton.enabled:
self.showBrowser()
if not self.initialConnection:
self.getCollectionValues()
def cleanup(self):
pass
def onDownloadOptionsToggled(self, state):
importState = self.importOnDownloadAction.isChecked()
loadState = self.loadOnDownloadAction.isChecked()
buttonLabel = "Download"
if importState:
if loadState:
buttonLabel = buttonLabel + ", import and load into scene"
else:
buttonLabel = buttonLabel + " and import into DICOM database"
self.downloadButton.text = buttonLabel
def onShowBrowserButton(self):
self.showBrowser()
# TODO: goes to logic
def downloadFromQuery(self, query, downloadDestination):
logging.debug("Downloading from query: " + query)
manifest_path = os.path.join(downloadDestination,'manifest.csv')
manifest_df = self.IDCClient.sql_query(query)
manifest_df.to_csv(manifest_path, index=False, header=False)
logging.info("Will download to "+downloadDestination)
self.IDCClient.download_from_manifest(manifest_path, downloadDestination)
def onDownloadButton(self):
startTime = time.time()
self.download_status.setText('Download status: Downloading...')
slicer.app.processEvents()
import os
if(os.path.exists(self.manifestSelector.currentPath)):
self.download_status.setText('Downloading from manifest...')
self.IDCClient.download_from_manifest(self.manifestSelector.currentPath, self.downloadDestinationSelector.directory)
self.download_status.setText('Download from manifest done.')
if(self.patientIDSelector.text != ''):
# TODO: how to interrupt long download from GUI?
self.download_status.setText('Downloading from PatientID...')
query = """
SELECT CONCAT('cp ',series_aws_url,' .')
FROM index
WHERE PatientID = '""" + self.patientIDSelector.text + """'
"""
self.downloadFromQuery(query, self.downloadDestinationSelector.directory)
self.download_status.setText('Download from PatientID done.')
if(self.studyUIDSelector.text != ''):
# TODO: how to interrupt long download from GUI?
self.download_status.setText('Downloading from StudyInstanceUID...')
query = """
SELECT CONCAT('cp ',series_aws_url,' .')
FROM index
WHERE StudyInstanceUID = '""" + self.studyUIDSelector.text + """'
"""
self.downloadFromQuery(query, self.downloadDestinationSelector.directory)
self.download_status.setText('Download from StudyInstanceUID done.')
if(self.seriesUIDSelector.text != ''):
# TODO: how to interrupt long download from GUI?
self.download_status.setText('Downloading from SeriesInstanceUID...')
query = """
SELECT CONCAT('cp ',series_aws_url,' .')
FROM index
WHERE SeriesInstanceUID = '""" + self.seriesUIDSelector.text + """'
"""
self.downloadFromQuery(query, self.downloadDestinationSelector.directory)
self.download_status.setText('Download from SeriesInstanceUID done.')
self.download_status.setText('Download status: Done in {0:.2f} seconds.'.format(time.time() - startTime))
logging.info('Download status: Done in {0:.2f} seconds.'.format(time.time() - startTime))
if self.importOnDownloadAction.isChecked():
logging.info('Importing downloaded data into DICOM database ...')
self.download_status.setText('Importing downloaded data into DICOM database ...')
self.addFilesToDatabase(self.downloadDestinationSelector.directory)
self.download_status.setText('Importing downloaded data into DICOM database done.')
logging.info('Importing downloaded data into DICOM database done.')
if self.loadOnDownloadAction.isChecked():
logging.info('Loading downloaded data into scene ...')
self.download_status.setText('Loading downloaded data into scene ...')
self.logic.loadData(self.downloadDestinationSelector.directory)
self.download_status.setText('Loading downloaded data into scene done.')
logging.info('Loading downloaded data into scene done.')
def onUseCacheStateChanged(self, state):
if state == 0:
self.useCacheFlag = False
elif state == 2:
self.useCacheFlag = True
def onContextMenuTriggered(self):
self.clinicalPopup.getData(self.selectedCollection, self.selectedPatient)
def onRemoveSeriesContextMenuTriggered(self):
removeList = []
for uid in self.seriesInstanceUIDs:
if uid.isSelected():
removeList.append(uid.text())
with open(self.downloadedSeriesArchiveFile, 'rb') as f:
self.previouslyDownloadedSeries = pickle.load(f)
f.close()
updatedDownloadSeries = []
for item in self.previouslyDownloadedSeries:
if item not in removeList:
updatedDownloadSeries.append(item)
with open(self.downloadedSeriesArchiveFile, 'wb') as f:
pickle.dump(updatedDownloadSeries,f)
f.close()
self.previouslyDownloadedSeries = updatedDownloadSeries
self.studiesTableSelectionChanged()
def showBrowser(self):
if not self.browserWidget.isVisible():
self.popupPositioned = False
self.browserWidget.show()
if self.popupGeometry.isValid():
self.browserWidget.setGeometry(self.popupGeometry)
self.browserWidget.raise_()
if not self.popupPositioned:
mainWindow = slicer.util.mainWindow()
if mainWindow is None:
return
screenMainPos = mainWindow.pos
x = screenMainPos.x() + 100
y = screenMainPos.y() + 100
self.browserWidget.move(qt.QPoint(x, y))
self.popupPositioned = True
def showStatus(self, message, waitMessage='Waiting for IDC server .... '):
self.statusLabel.text = waitMessage + message
self.statusLabel.setStyleSheet("QLabel { background-color : #F0F0F0 ; color : #383838; }")
slicer.app.processEvents()
def clearStatus(self):
self.statusLabel.text = ''
self.statusLabel.setStyleSheet("QLabel { background-color : white; color : black; }")
def onStoragePathButton(self):
self.storagePath = self.storagePathButton.directory
self.settings.setValue("IDCCustomStoragePath", self.storagePath)
self.storageResetButton.enabled = True
def onStorageResetButton(self):
self.storagePath = self.settings.value("IDCDefaultStoragePath")
self.settings.remove("IDCCustomStoragePath")
self.storageResetButton.enabled = False
self.storagePathButton.directory = self.storagePath
def getCollectionValues(self):
self.initialConnection = True
self.showStatus("Getting Available Collections")
try:
responseString = self.IDCClient.get_collections()
logging.debug("getCollectionValues: responseString = " + str(responseString))
self.populateCollectionsTreeView(responseString)
self.clearStatus()
except Exception as error:
self.connectButton.enabled = True
self.clearStatus()
message = "getCollectionValues: Error in getting response from IDC server.\nHTTP Error:\n" + str(error)
qt.QMessageBox.critical(slicer.util.mainWindow(),
'SlicerIDCBrowser', message, qt.QMessageBox.Ok)
self.showBrowserButton.enabled = True
self.showBrowser()
def onStudiesSelectAllButton(self):
self.studiesTableWidget.selectAll()
def onStudiesSelectNoneButton(self):
self.studiesTableWidget.clearSelection()
def onSeriesSelectAllButton(self):
self.seriesTableWidget.selectAll()
def onSeriesSelectNoneButton(self):
self.seriesTableWidget.clearSelection()
def collectionSelected(self, item):
self.loadButton.enabled = False
self.indexButton.enabled = False
self.clearPatientsTableWidget()
self.clearStudiesTableWidget()
self.clearSeriesTableWidget()
self.selectedCollection = item
cacheFile = self.cachePath + self.selectedCollection + '.json'
self.progressMessage = "Getting available patients for collection: " + self.selectedCollection
# make collection summary
collection_summary = self.IDCClient.collection_summary.loc[self.selectedCollection]
if float(collection_summary.series_size_MB) > 1000:
summary_text = "Modalities: "+str(collection_summary.Modality).replace('\'','')+" Total size: "+str(round(float(collection_summary.series_size_MB)/1000,2))+" GB"
else:
summary_text = "Modalities: "+str(collection_summary.Modality).replace('\'','')+" Total size: "+str(round(float(collection_summary.series_size_MB),2))+" MB"
self.logoLabel.setText(summary_text)
patientsList = None
if os.path.isfile(cacheFile) and self.useCacheFlag:
f = codecs.open(cacheFile, 'rb', encoding='utf8')
patientsList = f.read()[:]
f.close()
if not len(patientsList):
patientsList = None
if patientsList:
self.populatePatientsTableWidget(patientsList)
self.clearStatus()
#groupBoxTitle = 'Patients (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Patients'
self.patientsCollapsibleGroupBox.setTitle(groupBoxTitle)
else:
try:
responseString = self.IDCClient.get_patients(collection_id=self.selectedCollection)
'''
with open(cacheFile, 'w') as outputFile:
self.stringBufferReadWrite(outputFile, response)
outputFile.close()
f = codecs.open(cacheFile, 'r', encoding='utf8')
responseString = f.read()
'''
self.populatePatientsTableWidget(responseString)
#groupBoxTitle = 'Patients (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Patients'
self.patientsCollapsibleGroupBox.setTitle(groupBoxTitle)
self.clearStatus()
except Exception as error:
self.clearStatus()
message = "collectionSelected: Error in getting response from IDC server.\nHTTP Error:\n" + str(error)
qt.QMessageBox.critical(slicer.util.mainWindow(),
'SlicerIDCBrowser', message, qt.QMessageBox.Ok)
def patientsTableSelectionChanged(self):
self.clearStudiesTableWidget()
self.clearSeriesTableWidget()
self.studiesTableRowCount = 0
self.numberOfSelectedPatients = 0
for n in range(len(self.patientsIDs)):
if self.patientsIDs[n].isSelected():
self.numberOfSelectedPatients += 1
self.patientSelected(n)
def patientSelected(self, row):
self.loadButton.enabled = False
self.indexButton.enabled = False
# self.clearStudiesTableWidget()
self.clearSeriesTableWidget()
self.selectedPatient = self.patientsIDs[row].text()
cacheFile = self.cachePath + self.selectedPatient + '.json'
self.progressMessage = "Getting available studies for patient ID: " + self.selectedPatient
self.showStatus(self.progressMessage)
if os.path.isfile(cacheFile) and self.useCacheFlag:
f = codecs.open(cacheFile, 'rb', encoding='utf8')
responseString = f.read()[:]
f.close()
self.populateStudiesTableWidget(responseString)
self.clearStatus()
if self.numberOfSelectedPatients == 1:
#groupBoxTitle = 'Studies (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Studies '
else:
groupBoxTitle = 'Studies '
self.studiesCollapsibleGroupBox.setTitle(groupBoxTitle)
else:
try:
responseString = self.IDCClient.get_dicom_studies(patientId=self.selectedPatient)
'''
with open(cacheFile, 'wb') as outputFile:
outputFile.write(responseString)
outputFile.close()
f = codecs.open(cacheFile, 'rb', encoding='utf8')
responseString = f.read()[:]
'''
self.populateStudiesTableWidget(responseString)
if self.numberOfSelectedPatients == 1:
#groupBoxTitle = 'Studies (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Studies '
else:
groupBoxTitle = 'Studies '
self.studiesCollapsibleGroupBox.setTitle(groupBoxTitle)
self.clearStatus()
except Exception as error:
self.clearStatus()
message = "patientSelected: Error in getting response from IDC server.\nHTTP Error:\n" + str(error)
qt.QMessageBox.critical(slicer.util.mainWindow(),
'SlicerIDCBrowser', message, qt.QMessageBox.Ok)
def studiesTableSelectionChanged(self):
self.clearSeriesTableWidget()
self.seriesTableRowCount = 0
self.numberOfSelectedStudies = 0
for n in range(len(self.studyInstanceUIDs)):
if self.studyInstanceUIDs[n].isSelected():
self.numberOfSelectedStudies += 1
self.studySelected(n)
def studySelected(self, row):
self.loadButton.enabled = False
self.indexButton.enabled = False
self.selectedStudy = self.studyInstanceUIDs[row].text()
self.selectedStudyRow = row
self.progressMessage = "Getting available series for studyInstanceUID: " + self.selectedStudy
self.showStatus(self.progressMessage)
cacheFile = self.cachePath + self.selectedStudy + '.json'
if os.path.isfile(cacheFile) and self.useCacheFlag:
logging.debug("studySelected: using cache file: " + cacheFile)
f = codecs.open(cacheFile, 'rb', encoding='utf8')
responseString = f.read()[:]
f.close()
self.populateSeriesTableWidget(responseString)
self.clearStatus()
if self.numberOfSelectedStudies == 1:
#groupBoxTitle = 'Series (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Series '
else:
groupBoxTitle = 'Series '
self.seriesCollapsibleGroupBox.setTitle(groupBoxTitle)
else:
self.progressMessage = "Getting available series for studyInstanceUID: " + self.selectedStudy
self.showStatus(self.progressMessage)
try:
responseString = self.IDCClient.get_dicom_series(studyInstanceUID=self.selectedStudy)
'''
with open(cacheFile, 'wb') as outputFile:
outputFile.write(responseString)
outputFile.close()
'''
self.populateSeriesTableWidget(responseString)
if self.numberOfSelectedStudies == 1:
#groupBoxTitle = 'Series (Accessed: ' + time.ctime(os.path.getmtime(cacheFile)) + ')'
groupBoxTitle = 'Series '
else:
groupBoxTitle = 'Series '
self.seriesCollapsibleGroupBox.setTitle(groupBoxTitle)
self.clearStatus()
except Exception as error:
self.clearStatus()
message = "studySelected: Error in getting response from IDC server.\nHTTP Error:\n" + str(error)
qt.QMessageBox.critical(slicer.util.mainWindow(),
'SlicerIDCBrowser', message, qt.QMessageBox.Ok)
self.onSeriesSelectAllButton()
# self.loadButton.enabled = True
# self.indexButton.enabled = True
def seriesSelected(self):
self.imagesToDownloadCount = 0
self.imagesToDownloadSize = 0
self.loadButton.enabled = False
self.indexButton.enabled = False
for n in range(len(self.seriesInstanceUIDs)):
if self.seriesInstanceUIDs[n].isSelected():
self.imagesToDownloadCount += int(self.imageCounts[n].text())
self.imagesToDownloadSize += float(self.imageSizes[n])
self.loadButton.enabled = True
self.indexButton.enabled = True
if self.imagesToDownloadSize > 1000:
self.imagesToDownloadSize = self.imagesToDownloadSize / 1000
unit = 'GB'
else:
unit = 'MB'
self.imagesCountLabel.text = 'Total size to download: ' + '<span style=" font-weight:600; color:#aa0000;">' + str(
round(self.imagesToDownloadSize,2)) + unit+'</span>' + ' '
def onIndexButton(self):
self.loadToScene = False
self.addSelectedToDownloadQueue()
# self.addFilesToDatabase()
def onLoadButton(self):
self.loadToScene = True
startTime = time.time()
self.addSelectedToDownloadQueue()
logging.info('onLoadButton: Done in {0:.2f} seconds.'.format(time.time() - startTime))
def onCancelDownloadButton(self):
self.cancelDownload = True
for series in self.downloadQueue.keys():
self.removeDownloadProgressBar(series)
downloadQueue = {}
seriesRowNumber = {}
def addFilesToDatabase(self, directory=None):
self.progressMessage = "Adding Files to DICOM Database "
self.showStatus(self.progressMessage)
indexer = ctk.ctkDICOMIndexer()
# DICOM indexer uses the current DICOM database folder as the basis for relative paths,
# therefore we must convert the folder path to absolute to ensure this code works
# even when a relative path is used as self.extractedFilesDirectory.
if not directory:
indexer.addDirectory(slicer.dicomDatabase, os.path.abspath(self.extractedFilesDirectory))
else:
indexer.addDirectory(slicer.dicomDatabase, os.path.abspath(directory))
indexer.waitForImportFinished()
self.clearStatus()
def addSelectedToDownloadQueue(self):
self.cancelDownload = False
allSelectedSeriesUIDs = []
downloadQueue = {}