forked from TrinhLab/CASPERapp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ncbi.py
1686 lines (1446 loc) · 77.1 KB
/
ncbi.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 Bio import Entrez
from bs4 import BeautifulSoup
from PyQt5 import QtWidgets, Qt, QtCore, uic
from ftplib import FTP
import gzip
import pandas as pd
import shutil
import os, time
import ssl
import GlobalSettings
import platform
import traceback
import math
#global logger
logger = GlobalSettings.logger
ssl._create_default_https_context = ssl._create_unverified_context
Entrez.email = "[email protected]"
#model for filtering columns in ncbi table
class CustomProxyModel(QtCore.QSortFilterProxyModel):
def __init__(self, parent=None):
try:
super().__init__(parent)
self._filters = dict()
except Exception as e:
logger.critical("Error initializing CustomProxyModel class in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidge/ts.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@property
def filters(self):
try:
return self._filters
except Exception as e:
logger.critical("Error in filter() in custom proxy model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def setFilter(self, expresion, column):
try:
if expresion:
self.filters[column] = expresion
elif column in self.filters:
del self.filters[column]
self.invalidateFilter()
except Exception as e:
logger.critical("Error in setFilters() in custom proxy model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def filterAcceptsRow(self, source_row, source_parent):
try:
for column, expresion in self.filters.items():
text = self.sourceModel().index(source_row, column, source_parent).data()
regex = QtCore.QRegExp(
expresion, QtCore.Qt.CaseInsensitive, QtCore.QRegExp.RegExp
)
if regex.indexIn(text) == -1:
return False
return True
except Exception as e:
logger.critical("Error in filterAcceptsRow() in custom proxy model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
#model for the data in the ncbi search table
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, df=pd.DataFrame(), parent=None):
try:
QtCore.QAbstractTableModel.__init__(self, parent=parent)
self._df = df.copy()
except Exception as e:
logger.critical("Error initializing PandasModel class in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def toDataFrame(self):
try:
return self._df.copy()
except Exception as e:
logger.critical("Error in toDataFrame() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
try:
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if orientation == QtCore.Qt.Horizontal:
try:
return self._df.columns.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
elif orientation == QtCore.Qt.Vertical:
try:
return self._df.index.tolist()[section]
except (IndexError, ):
return QtCore.QVariant()
except Exception as e:
logger.critical("Error in headerData() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def data(self, index, role=QtCore.Qt.DisplayRole):
try:
if role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if not index.isValid():
return QtCore.QVariant()
return QtCore.QVariant(str(self._df.iloc[index.row(), index.column()]))
except Exception as e:
logger.critical("Error in data() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def setData(self, index, value, role):
try:
row = self._df.index[index.row()]
col = self._df.columns[index.column()]
if hasattr(value, 'toPyObject'):
# PyQt4 gets a QVariant
value = value.toPyObject()
else:
# PySide gets an unicode
dtype = self._df[col].dtype
if dtype != object:
value = None if value == '' else dtype.type(value)
self._df.set_value(row, col, value)
return True
except Exception as e:
logger.critical("Error in setData() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def rowCount(self, parent=QtCore.QModelIndex()):
try:
return len(self._df.index)
except Exception as e:
logger.critical("Error in rowCount() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def columnCount(self, parent=QtCore.QModelIndex()):
try:
return len(self._df.columns)
except Exception as e:
logger.critical("Error in columnCount() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def sort(self, column, order):
try:
colname = self._df.columns.tolist()[column]
self.layoutAboutToBeChanged.emit()
self._df.sort_values(colname, ascending=order, inplace=True)
self._df.reset_index(inplace=True, drop=True)
self.layoutChanged.emit()
except Exception as e:
logger.critical("Error in sort() in Pandas Model in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
## Taken from StackOverflow: https://stackoverflow.com/questions/57607072/update-pyqt-progress-from-another-thread-running-ftp-download
class DownloadThread(QtCore.QThread):
""" Overall signals """
finished = QtCore.pyqtSignal(object)
started = QtCore.pyqtSignal(object)
""" Download specific signals """
data_progress = QtCore.pyqtSignal(object) # This signal emits progress data for the progress bar
data_size = QtCore.pyqtSignal(object) # This signal emits the size of the file being downloaded
file_started = QtCore.pyqtSignal(object) # This signal emits when the file starts downloading
file_finished = QtCore.pyqtSignal(object) # This signal emits the name of the file downloaded
def __init__(self,parent,url,id):
try:
QtCore.QThread.__init__(self,parent)
self.id = id # Initialize ID
self.url = url # Initialize URL
self.ftp = FTP('ftp.ncbi.nlm.nih.gov') # Initialize FTP object
self.ftp.login()
except Exception as e:
logger.critical("Error initializing Thread class in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(GlobalSettings.mainWindow.ncbi.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidge/ts.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def run(self):
try:
### Start by making sure the url is valid
if self.url == "":
self.finished.emit((self.id, False))
return
else:
self.started.emit(self.id)
self.ftp.cwd(self.url) # Change to appropriate directory
dir_files = self.ftp.nlst() # Get list of files in directory
for file in dir_files: # Loop through every file in the directory
if GlobalSettings.mainWindow.ncbi.gbff_checkbox.isChecked(): # If a GBFF is supposed to be downloaded
if file.find('genomic.gbff') != -1: # If a GBFF exists in this directory
# check OS for output path
if platform.system() == "Windows":
output_file = GlobalSettings.CSPR_DB + "\\GBFF\\" + file
else:
output_file = GlobalSettings.CSPR_DB + "/GBFF/" + file
self.ftp.voidcmd('TYPE I')
totalsize = self.ftp.size(file) # Get size of file that is being downloaded
# The first signal sets the maximum for the progress bar
self.file_started.emit((self.id,'Downloading GBFF: ' + str(round(totalsize/1e6,2)) + 'MB...',str(totalsize))) # Emit that the file download is starting and size of file
with open(output_file, 'wb') as self.f:
self.ftp.retrbinary(f"RETR {file}", self.file_write) # Download the file, emitting progress as we go
self.decompress_file(output_file) # Decompress the file
self.file_finished.emit((self.id,'GBFF Downloaded!',output_file)) # Once download is finished, emit signal
if GlobalSettings.mainWindow.ncbi.fna_checkbox.isChecked(): # If a FNA is supposed to be downloaded
if file.find('genomic.fna') != -1 and file.find('_cds_') == -1 and file.find('_rna_') == -1: # If a FNA exists in this directory
# check OS for output path
if platform.system() == "Windows":
output_file = GlobalSettings.CSPR_DB + "\\FNA\\" + file
else:
output_file = GlobalSettings.CSPR_DB + "/FNA/" + file
self.ftp.voidcmd('TYPE I')
totalsize = self.ftp.size(file) # Get size of file that is being downloaded
self.file_started.emit((self.id,'Downloading FNA: ' + str(round(totalsize/1e6,2)) + 'MB...',str(totalsize))) # Emit that file download is starting
with open(output_file, 'wb') as self.f:
self.ftp.retrbinary(f"RETR {file}", self.file_write) # Download the file
self.decompress_file(output_file) # Decompress the file
self.file_finished.emit((self.id,'FNA Downloaded!',output_file)) # Once download is finished, emit signal
self.finished.emit((self.id,True))
self.ftp.quit() # Stop the FTP connection once everything has been downloaded
except Exception as e:
logger.critical("Error downloading file within DownloadThread class.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(GlobalSettings.mainWindow.ncbi.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def file_write(self, data):
self.f.write(data) # Write the downloaded data to a file
# The other signals increase a progress
self.data_progress.emit((self.id,str(len(data)))) # Emit a signal updating progress
# decompress file function
def decompress_file(self, filename):
try:
block_size = 65536
with gzip.open(filename, 'rb') as f_in:
with open(str(filename).replace('.gz', ''), 'wb') as f_out:
while True:
block = f_in.read(block_size)
if not block:
break
else:
f_out.write(block)
os.remove(str(filename))
except Exception as e:
logger.critical("Error in decompress_file() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
#ncbi
class NCBI_search_tool(QtWidgets.QMainWindow):
def __init__(self):
try:
super(NCBI_search_tool, self).__init__()
uic.loadUi(GlobalSettings.appdir + 'ncbi.ui', self)
self.setWindowIcon(Qt.QIcon(GlobalSettings.appdir + "cas9image.ico"))
self.setWindowTitle("NCBI Download Tool")
self.logicalIndex = 0
self.filters = dict()
self.download_button.clicked.connect(self.download_files_wrapper)
self.search_button.clicked.connect(self.query_db)
self.ncbi_table.verticalHeader().hide()
self.all_rows.clicked.connect(self.select_all)
self.back_button.clicked.connect(self.go_back)
self.ncbi_table.setFocusPolicy(QtCore.Qt.NoFocus)
self.progressBar.setValue(0)
self.rename_window = rename_window()
self.rename_window.submit_button.clicked.connect(self.submit_rename)
self.rename_window.go_back.clicked.connect(self.rename_go_back)
self.df = pd.DataFrame()
groupbox_style = """
QGroupBox:title{subcontrol-origin: margin;
left: 10px;
padding: 0 5px 0 5px;}
QGroupBox#Step1{border: 2px solid rgb(111,181,110);
border-radius: 9px;
font: bold 14pt 'Arial';
margin-top: 10px;}"""
self.Step1.setStyleSheet(groupbox_style)
self.Step2.setStyleSheet(groupbox_style.replace("Step1","Step2"))
self.Step3.setStyleSheet(groupbox_style.replace("Step1","Step3"))
self.ncbi_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.ncbi_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
#navigation page
self.goToPrompt = goToPrompt()
self.goToPrompt.stay.clicked.connect(self.stay)
self.goToPrompt.close.clicked.connect(self.close)
#loading label
self.loading_window = loading_window()
self.genbank_checkbox.toggled.connect(self.check_genbank)
#scale UI
self.first_show = True
self.scaleUI()
except Exception as e:
logger.critical("Error initializing NCBI_search_tool class.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def check_genbank(self):
if self.genbank_checkbox.isChecked():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Warning)
msgBox.setWindowTitle("Warning!")
msgBox.setText("Warning!\n\nThe GenBank collection may contain poorly or partially annotated annotation files. We highly recommend using the RefSeq collection if it is available.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
else:
pass # Do nothing
#scale UI based on current screen
def scaleUI(self):
try:
self.repaint()
QtWidgets.QApplication.processEvents()
screen = self.screen()
dpi = screen.physicalDotsPerInch()
width = screen.geometry().width()
height = screen.geometry().height()
# font scaling
fontSize = 12
self.fontSize = fontSize
self.centralWidget().setStyleSheet("font: " + str(fontSize) + "pt 'Arial';")
# CASPER header scaling
fontSize = 30
self.title.setStyleSheet("font: bold " + str(fontSize) + "pt 'Arial';")
self.adjustSize()
currentWidth = self.size().width()
currentHeight = self.size().height()
# window scaling
# 1920x1080 => 850x750
scaledWidth = int((width * 1000) / 1920)
scaledHeight = int((height * 750) / 1080)
if scaledHeight < currentHeight:
scaledHeight = currentHeight
if scaledWidth < currentWidth:
scaledWidth = currentWidth
screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos())
centerPoint = QtWidgets.QApplication.desktop().screenGeometry(screen).center()
x = centerPoint.x()
y = centerPoint.y()
x = x - (math.ceil(scaledWidth / 2))
y = y - (math.ceil(scaledHeight / 2))
self.setGeometry(x, y, scaledWidth, scaledHeight)
self.repaint()
QtWidgets.QApplication.processEvents()
except Exception as e:
logger.critical("Error in scaleUI() in NCBI tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
#center UI on current screen
def centerUI(self):
try:
self.repaint()
QtWidgets.QApplication.processEvents()
# center window on current screen
width = self.width()
height = self.height()
screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos())
centerPoint = QtWidgets.QApplication.desktop().screenGeometry(screen).center()
x = centerPoint.x()
y = centerPoint.y()
x = x - (math.ceil(width / 2))
y = y - (math.ceil(height / 2))
self.setGeometry(x, y, width, height)
self.repaint()
QtWidgets.QApplication.processEvents()
except Exception as e:
logger.critical("Error in centerUI() in NCBI tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
def go_back(self):
try:
""" Clear table """
self.df = pd.DataFrame() ###Make empty DF
self.model = PandasModel(self.df)
self.proxy = CustomProxyModel(self)
self.proxy.setSourceModel(self.model)
self.ncbi_table.setModel(self.proxy)
self.ncbi_table.verticalHeader().hide()
""" Clear all line edits """
self.organism_line_edit.clear()
self.infra_name_line_edit.clear()
self.ret_max_line_edit.setText("100")
self.infra_name_line_edit.clear()
""" Reset all checkboxes """
self.yes_box.setChecked(False)
self.genbank_checkbox.setChecked(False)
self.refseq_checkbox.setChecked(False)
self.gbff_checkbox.setChecked(False)
self.fna_checkbox.setChecked(False)
""" Hide window """
self.close()
except Exception as e:
logger.critical("Error in go_back() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@QtCore.pyqtSlot()
def query_db(self):
try:
#show loading
self.loading_window.loading_bar.setValue(5)
self.loading_window.centerUI()
self.loading_window.show()
QtCore.QCoreApplication.processEvents()
#setup table
self.comboBox = QtWidgets.QComboBox(self)
self.horizontalHeader = self.ncbi_table.horizontalHeader()
self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)
#Build Query commands
retmax = int(self.ret_max_line_edit.text())
if retmax == "":
retmax = 100
org = self.organism_line_edit.text()
term = '"' + org + '"[Organism]'
if self.yes_box.isChecked():
term += ' AND "Complete Genome"[Assembly Level]'
if self.infra_name_line_edit.text() != "":
term += ' AND "' + self.infra_name_line_edit.text() + '"[Infraspecific name]'
#Search DB for IDs
handle = Entrez.esearch(db="assembly", retmax=retmax, term=term)
content = handle.readlines()
content = "".join(str(content))
#bs_content = BeautifulSoup(content, "lxml")
bs_content = BeautifulSoup(content, "html.parser")
self.loading_window.loading_bar.setValue(20)
QtCore.QCoreApplication.processEvents()
#Extract IDs
idlist = bs_content.find('idlist')
ids = idlist.find_all('id')
ids = [i.text for i in ids]
self.loading_window.loading_bar.setValue(35)
QtCore.QCoreApplication.processEvents()
# Get Details on IDs
handle = Entrez.esummary(db="assembly", id=','.join(ids))
content = handle.readlines()
handle.close()
content = "".join(str(content))
#bs_content = BeautifulSoup(content, 'lxml')
bs_content = BeautifulSoup(content, "html.parser")
self.loading_window.loading_bar.setValue(55)
QtCore.QCoreApplication.processEvents()
#Prep Data for Table
assembly_name = bs_content.find_all('assemblyname')
genbank_ids = bs_content.find_all('genbank')
refseq_ids = bs_content.find_all('refseq')
assembly_status = bs_content.find_all('assemblystatus')
species_name = bs_content.find_all('speciesname')
temp_strains = bs_content.find_all('infraspecieslist')
assembly_name = [i.text for i in assembly_name]
genbank_ids = [i.text for i in genbank_ids]
refseq_ids = [i.text for i in refseq_ids]
assembly_status = [i.text for i in assembly_status]
species_name = [i.text for i in species_name]
ids = [int(i) for i in ids]
strains = []
for i in range(len(genbank_ids)):
temp_str = str(temp_strains[i])
#temp_str = BeautifulSoup(temp_str, 'lxml')
temp_str = BeautifulSoup(temp_str, 'html.parser')
temp_str = temp_str.find('sub_value')
if temp_str != None:
strains.append(temp_str.text)
else:
strains.append('N/A')
self.loading_window.loading_bar.setValue(65)
QtCore.QCoreApplication.processEvents()
#Get ftp links
genbank_links = bs_content.find_all('ftppath_genbank')
refseq_links = bs_content.find_all('ftppath_refseq')
refseq_links = bs_content.find_all('ftppath_refseq')
genbank_links = [i.text for i in genbank_links]
refseq_links = [i.text for i in refseq_links]
self.genbank_ftp_dict = {}
self.refseq_ftp_dict = {}
for i in range(len(ids)):
if genbank_ids[i] == '':
self.genbank_ftp_dict[ids[i]] = ''
else:
self.genbank_ftp_dict[ids[i]] = genbank_links[i] + '/'
if refseq_ids[i] == '':
self.refseq_ftp_dict[ids[i]] = ''
else:
self.refseq_ftp_dict[ids[i]] = refseq_links[i] + '/'
self.loading_window.loading_bar.setValue(80)
QtCore.QCoreApplication.processEvents()
#Build dataframe
self.df = pd.DataFrame({'ID': ids,
'Species Name' : species_name,
'Strain' : strains,
'Assembly Name' : assembly_name,
'GenBank assembly accession': genbank_ids,
'RefSeq assembly accession': refseq_ids,
'Assembly Status': assembly_status})
self.loading_window.loading_bar.setValue(90)
QtCore.QCoreApplication.processEvents()
#Build table view
self.df.replace('', 'N/A', inplace=True)
self.model = PandasModel(self.df)
self.proxy = CustomProxyModel(self)
self.proxy.setSourceModel(self.model)
self.ncbi_table.setModel(self.proxy)
self.ncbi_table.resizeColumnsToContents()
self.comboBox.addItems(["{0}".format(col) for col in self.model._df.columns])
self.activateWindow()
#close loading gif
self.loading_window.hide()
self.loading_window.loading_bar.setValue(0)
QtCore.QCoreApplication.processEvents()
except Exception as e:
logger.critical("Error in query_db() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@QtCore.pyqtSlot(int)
def on_view_horizontalHeader_sectionClicked(self, logicalIndex):
try:
self.logicalIndex = logicalIndex
self.menuValues = QtWidgets.QMenu(self)
self.signalMapper = QtCore.QSignalMapper(self)
self.comboBox.blockSignals(True)
self.comboBox.setCurrentIndex(logicalIndex)
self.comboBox.blockSignals(True)
valuesUnique = self.model._df.iloc[:, logicalIndex].unique()
if logicalIndex == 0:
valuesUnique = ['Sort: 0-9', 'Sort: 9-0']
elif logicalIndex == 2:
valuesUnique = ['Exclude N/A', 'Only N/A', 'Sort: A-Z', 'Sort: Z-A']
elif logicalIndex == 3:
valuesUnique = ['Sort: A-Z', 'Sort: Z-A']
elif logicalIndex == 4 or logicalIndex == 5:
valuesUnique = ['Exclude N/A', 'Only N/A', 'Sort: A-Z', 'Sort: Z-A']
actionAll = QtWidgets.QAction("All", self)
actionAll.triggered.connect(self.on_actionAll_triggered)
self.menuValues.addAction(actionAll)
self.menuValues.addSeparator()
for actionNumber, actionName in enumerate(sorted(list(set(valuesUnique)))):
action = QtWidgets.QAction(actionName, self)
self.signalMapper.setMapping(action, actionNumber)
action.triggered.connect(self.signalMapper.map)
self.menuValues.addAction(action)
self.signalMapper.mapped.connect(self.on_signalMapper_mapped)
headerPos = self.ncbi_table.mapToGlobal(self.horizontalHeader.pos())
posY = headerPos.y() + self.horizontalHeader.height()
posX = headerPos.x() + self.horizontalHeader.sectionViewportPosition(logicalIndex)
self.menuValues.exec_(QtCore.QPoint(posX, posY))
except Exception as e:
logger.critical("Error in on_view_horizontalHeader_sectionClicked() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@QtCore.pyqtSlot()
def on_actionAll_triggered(self):
try:
filterColumn = self.logicalIndex
self.proxy.setFilter("", filterColumn)
except Exception as e:
logger.critical("Error in on_actionAll_triggered() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@QtCore.pyqtSlot(int)
def on_signalMapper_mapped(self, i):
try:
indices = self.ncbi_table.selectionModel().selectedRows()
#stringAction = self.signalMapper.mapping(i).text()
if self.logicalIndex == 0:
if i == 0:
self.model.sort(self.logicalIndex, QtCore.Qt.DescendingOrder)
else:
self.model.sort(self.logicalIndex, QtCore.Qt.AscendingOrder)
elif self.logicalIndex == 3:
if i == 0:
self.model.sort(self.logicalIndex, QtCore.Qt.DescendingOrder)
else:
self.model.sort(self.logicalIndex, QtCore.Qt.AscendingOrder)
elif self.logicalIndex == 2 or self.logicalIndex == 4 or self.logicalIndex == 5:
if i == 0:
stringAction = "(?!^N/A$)(^.*$)"
filterColumn = self.logicalIndex
self.proxy.setFilter(stringAction, filterColumn)
elif i == 1:
stringAction = "N/A"
filterColumn = self.logicalIndex
self.proxy.setFilter(stringAction, filterColumn)
elif i == 2:
self.model.sort(self.logicalIndex, QtCore.Qt.DescendingOrder)
else:
self.model.sort(self.logicalIndex, QtCore.Qt.AscendingOrder)
elif self.logicalIndex == 6:
stringAction = self.signalMapper.mapping(i).text()
filterColumn = self.logicalIndex
self.proxy.setFilter(stringAction, filterColumn)
except Exception as e:
logger.critical("Error in on_signalMapper_mapped() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
@QtCore.pyqtSlot()
def download_files_wrapper(self):
try:
self.progressBar.setValue(0)
#make sure rows are present in table
if self.df.shape[0] == 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("No Query Results")
msgBox.setText("Please run an NCBI query to fill the table with results to choose from!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
#make sure user has selected at least one row
indices = self.ncbi_table.selectionModel().selectedRows()
if len(indices) == 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("No Rows Selected")
msgBox.setText("Please select rows from the table!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
threadCount = QtCore.QThreadPool.globalInstance().maxThreadCount() # Get thread count
if len(indices) > threadCount:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Too Many Selections!")
msgBox.setText("You only have " + str(threadCount) + " threads avaiable to download with.\n\nPlease select " + str(threadCount) + " or fewer rows.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
#make sure file type is selected
if self.gbff_checkbox.isChecked() == False and self.fna_checkbox.isChecked() == False:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("No File Type Selected")
msgBox.setText("No file type selected. Please select the file types you want to download!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
self.download_files()
except Exception as e:
logger.critical("Error in download_files_wrapper() in ncbi tool.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Fatal Error")
msgBox.setText("Fatal Error:\n"+str(e)+ "\n\nFor more information on this error, look at CASPER.log in the application folder.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)
msgBox.exec()
exit(-1)
### When a new thread is started, spawn a label and progress bar for that thread and add it to the form layout.
def on_thread_start(self, data):
id = data # This is the id for the thread
tmp_lbl = QtWidgets.QLabel()
tmp_lbl.setText("Download(s) Started...")
tmp_bar = QtWidgets.QProgressBar()
self.labels[id] = tmp_lbl # Append thread label to list
self.progressbars[id] = tmp_bar # Append thread label to list
self.formLayout.addRow(tmp_lbl,tmp_bar) # Add label and bar to form layout
### When a thread is finished, update its label and progressbar for the last time
def on_thread_finish(self,data):
id = data[0]
my_bool = data[1]
if my_bool: # If thread finished succesfully
self.progressbars[id].setValue(int(self.progressbars[id].maximum())) #Make sure progress bar is full
self.labels[id].setText("Download(s) Complete!") #Make sure progress bar is full
self.progressBar.setValue(int(self.progressBar.value()+1)) # Increment overall progress bar when a thread finishes
QtWidgets.QApplication.processEvents() # Allow the progress bar to update
else:
self.progressBar.setMaximum(int(self.progressBar.maximum()-1)) # Subtract 1 from progress bar to reflect failed thread.
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Link Failed!")
msgBox.setText("Failed to find a valid link for ID: " + str(id) + ". Please make sure this ID is available in the selected database.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
### When a file download starts, update the label and progress bar
def on_file_start(self, data):
id = data[0] # This is the id for the thread
prompt = data[1] # This is the prompt to set the label to
maxval = int(data[2]) # This is the file size
self.progressbars[id].setValue(0) # Set max value of progressbar
self.progressbars[id].setMaximum(int(maxval/1e3)) # Set max value of progressbar
self.labels[id].setText(str(prompt)) # Set label text