-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
2460 lines (2134 loc) · 115 KB
/
main.py
File metadata and controls
2460 lines (2134 loc) · 115 KB
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 Algorithms import get_table_headers
import sys
import os
import io
from PyQt5 import QtWidgets, Qt, QtGui, QtCore, uic
from CoTargeting import CoTargeting
from closingWin import closingWindow
from Results import Results
from NewGenome import NewGenome
from NewEndonuclease import NewEndonuclease
import genomeBrowser
import webbrowser
import requests
import GlobalSettings
import multitargeting
from AnnotationParser import Annotation_Parser
from export_tool import export_tool
from generateLib import genLibrary
from CSPRparser import CSPRparser
import populationAnalysis
import platform
import ncbi
import glob
import traceback
import math
import logging
from annotation_functions import *
#logger alias for global logger
logger = GlobalSettings.logger
#Annotation file and search query from MainWindow
class AnnotationsWindow(QtWidgets.QMainWindow):
#init annotation window class
def __init__(self, info_path):
super(AnnotationsWindow, self).__init__()
uic.loadUi(GlobalSettings.appdir + 'annotation_details.ui', self)
self.setWindowIcon(Qt.QIcon(GlobalSettings.appdir + "cas9image.ico"))
self.Submit_button.clicked.connect(self.submit)
self.Go_Back_Button.clicked.connect(self.go_Back)
self.select_all_checkbox.stateChanged.connect(self.select_all_genes)
self.mainWindow = ""
self.type = ""
self.mwfg = self.frameGeometry() ##Center window
self.cp = QtWidgets.QDesktopWidget().availableGeometry().center() ##Center window
self.switcher_table = [1, 1, 1, 1, 1, 1, 1, 1]
self.tableWidget.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.tableWidget.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidget.setAutoScroll(False)
self.tableWidget.horizontalHeader().sectionClicked.connect(self.table_sorting)
#scale UI
self.scaleUI()
def table_sorting(self,logicalIndex):
try:
self.switcher_table[logicalIndex] *= -1
if self.switcher_table[logicalIndex] == -1:
self.tableWidget.sortItems(logicalIndex, QtCore.Qt.DescendingOrder)
else:
self.tableWidget.sortItems(logicalIndex, QtCore.Qt.AscendingOrder)
except Exception as e:
logger.critical("Error in table_sorting() in Annotation Window.")
logger.critical(e)
logger.critical(traceback.format_exc())
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(GlobalSettings.mainWindow.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)
#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
# 16px is used for 92 dpi / 1920x1080
fontSize = 12
self.centralWidget().setStyleSheet("font: " + str(fontSize) + "pt 'Arial';" )
self.menuBar().setStyleSheet("font: " + str(fontSize) + "pt 'Arial';" )
#CASPER header scaling
fontSize = 30
self.label_8.setStyleSheet("font: bold " + str(fontSize) + "pt 'Arial';")
self.adjustSize()
currentWidth = self.size().width()
currentHeight = self.size().height()
# window scaling
scaledWidth = int((width * 900) / 1920)
scaledHeight = int((height * 600) / 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 AnnotationWindow.")
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()
#center UI 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()
except Exception as e:
logger.critical("Error in centerUI() in AnnotationWindow.")
logger.critical(e)
logger.critical(traceback.format_exc())
QtWidgets.QApplication.processEvents()
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)
#submit selected rows for results to process
def submit(self):
try:
self.mainWindow.collect_table_data_nonkegg()
self.mainWindow.show() # Open main window back up
self.hide() # Close annotation window upon Submit
except Exception as e:
logger.critical("Error in submit() in AnnotationsWindow.")
logger.critical(e)
logger.critical(traceback.format_exc())
self.hide()
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)
#go back to main
def go_Back(self):
try:
self.tableWidget.clear()
self.mainWindow.searches.clear()
self.tableWidget.setColumnCount(0)
self.mainWindow.show()
self.mainWindow.progressBar.setValue(0)
self.hide()
except Exception as e:
logger.critical("Error in go_Back() in AnnotationsWindow.")
logger.critical(e)
logger.critical(traceback.format_exc())
self.mainWindow.checkBoxes.clear()
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)
# this function is very similar to the other fill_table, it just works with the other types of annotation files
def fill_table_nonKegg(self, mainWindow,results_list):
try:
self.tableWidget.clearContents()
self.mainWindow = mainWindow
self.tableWidget.setColumnCount(5)
self.mainWindow.progressBar.setValue(85)
self.tableWidget.setHorizontalHeaderLabels(["Feature Type","Chromosome/Scaffold #","Feature ID/Locus Tag","Feature Name","Feature Description"])
header = self.tableWidget.horizontalHeader()
mainWindow.checkBoxes = []
self.type = "nonkegg"
index = 0
for result in results_list:
self.tableWidget.setRowCount(index + 1) # Increment table row count
### Set temp values
chrom = result[0]
feature = result[1]
### Create table items
feature_type = QtWidgets.QTableWidgetItem(feature.type)
chrom_number = QtWidgets.QTableWidgetItem(str(chrom))
feature_id = QtWidgets.QTableWidgetItem(get_id(feature))
feature_name = QtWidgets.QTableWidgetItem(get_name(feature))
feature_desc = QtWidgets.QTableWidgetItem(get_description(feature))
### Set table items
self.tableWidget.setItem(index, 0, feature_type)
self.tableWidget.setItem(index, 1, chrom_number)
self.tableWidget.setItem(index, 2, feature_id)
self.tableWidget.setItem(index, 3, feature_name)
self.tableWidget.setItem(index, 4, feature_desc)
mainWindow.checkBoxes.append((result[0],feature,index)) # Append chromosome number, SeqFeature object, and index in table to checkBoxes list. This list will be indexed later to return selected rows in the table by matching indices
index +=1
if index >= 1000:
break
index = 0
self.tableWidget.resizeColumnsToContents()
mainWindow.hide()
#center on current screen
self.centerUI()
self.show()
self.activateWindow()
return 0
except Exception as e:
logger.critical("Error in fill_table_nonKegg() in AnnotationsWindow.")
logger.critical(e)
logger.critical(traceback.format_exc())
self.mainWindow = mainWindow
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)
# this is the connection for the select all checkbox - selects/deselects all the genes in the table
def select_all_genes(self):
try:
# check to see if we're selecting all of them or not
if self.select_all_checkbox.isChecked():
select_all = True
else:
select_all = False
# # go through and do the selection
# for i in range(self.tableWidget.rowCount()):
# #self.tableWidget.cellWidget(i, 4).setChecked(select_all)
if select_all == True:
self.tableWidget.selectAll()
else:
self.tableWidget.clearSelection()
except Exception as e:
logger.critical("Error in select_all_genes() in AnnotationsWindow.")
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)
# this function calls the closingWindow class.
def closeEvent(self, event):
try:
GlobalSettings.mainWindow.closeFunction()
except Exception as e:
logger.critical("Error in closeEvent() in AnnotationsWindow.")
logger.critical(e)
logger.critical(traceback.format_exc())
event.accept()
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)
# =========================================================================================
# CLASS NAME: CMainWindow
# Inputs: Takes in the path information from the startup window and also all input parameters
# Outputs: The results of the target search process by generating a new Results window
# =========================================================================================
class CMainWindow(QtWidgets.QMainWindow):
def __init__(self, info_path):
super(CMainWindow, self).__init__()
uic.loadUi(GlobalSettings.appdir + 'CASPER_main.ui', self)
self.dbpath = ""
self.inputstring = "" # This is the search string
self.info_path = info_path
self.anno_name = ""
self.endo_name = ""
self.org = ""
self.TNumbers = {} # the T numbers from a kegg search
self.orgcodes = {} # Stores the Kegg organism code by the format {full name : organism code}
self.gene_list = {} # list of genes (no ides what they pertain to
self.searches = {}
self.checkBoxes = []
self.genlib_list = [] # This list stores selected SeqFeatures from annotation window
self.checked_info = {}
self.check_ntseq_info = {} # the ntsequences that go along with the checked_info
self.annotation_parser = Annotation_Parser()
self.link_list = list() # the list of the downloadable links from the NCBI search
self.organismDict = dict() # the dictionary for the links to download. Key is the description of the organism, value is the ID that can be found in link_list
self.results_list = list()
self.organismData = list()
self.ncbi = ncbi.NCBI_search_tool()
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;
margin-top: 10px;
font: bold 14pt 'Arial';}
"""
self.Step1.setStyleSheet(groupbox_style)
self.Step2.setStyleSheet(groupbox_style.replace("Step1", "Step2"))
self.Step3.setStyleSheet(groupbox_style.replace("Step1", "Step3"))
self.CASPER_Navigation.setStyleSheet(groupbox_style.replace("Step1", "CASPER_Navigation").replace("solid","dashed").replace("rgb(111,181,110)","rgb(88,89,91)"))
self.setWindowIcon(Qt.QIcon(GlobalSettings.appdir + "cas9image.ico"))
self.pushButton_FindTargets.clicked.connect(self.gather_settings)
self.pushButton_ViewTargets.clicked.connect(self.view_results)
self.pushButton_ViewTargets.setEnabled(False)
self.GenerateLibrary.setEnabled(False)
self.radioButton_Gene.clicked.connect(self.toggle_annotation)
self.radioButton_Position.clicked.connect(self.toggle_annotation)
""" Connect functions to buttons """
self.newGenome_button.clicked.connect(self.launch_newGenome) # Connect launch function to New Genome
self.newEndo_button.clicked.connect(self.launch_newEndonuclease) # Connect launch function to New Endonuclease
self.multitargeting_button.clicked.connect(self.changeto_multitargeting) # Connect launch function to Multitargeting
self.populationAnalysis_button.clicked.connect(self.changeto_population_Analysis) # Connect launch function to PA
self.GenerateLibrary.clicked.connect(self.prep_genlib)
""" Connect functions to actions (toolbar) """
self.actionOpen_Genome_Browser.triggered.connect(self.launch_newGenomeBrowser)
self.actionExit.triggered.connect(self.close_app)
self.visit_repo.triggered.connect(self.visit_repo_func)
self.actionChange_Directory.triggered.connect(self.change_directory)
self.actionNCBI.triggered.connect(self.open_ncbi_web_page)
# self.actionCasper2.triggered.connect(self.open_casper2_web_page)
self.actionNCBI_BLAST.triggered.connect(self.open_ncbi_blast_web_page)
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(100)
self.progressBar.reset()
self.Annotation_Window = AnnotationsWindow(info_path)
self.geneEntryField.setPlaceholderText("Example Inputs: \n\n"
"Option 1: Feature (ID, Locus Tag, or Name)\n"
"Example: 854068/YOL086C/ADH1 for S. cerevisiae alcohol dehydrogenase 1\n\n"
"Option 2: Position (chromosome,start,stop)\n"
"Example: 1,1,1000 for targeting chromosome 1, base pairs 1 to 1000\n\n"
"Option 3: Sequence (must be within the selected organism)\n"
"Example: Any nucleotide sequence between 100 and 10,000 base pairs.\n\n"
"*Note: to multiplex, separate multiple queries by new lines*\n"
"Example:\n"
"1,1,1000\n"
"5,1,500\n"
"etc.")
# show functionalities on window
self.newGenome = NewGenome(info_path)
self.newEndonuclease = NewEndonuclease()
self.CoTargeting = CoTargeting(info_path)
self.Results = Results()
self.export_tool_window = export_tool()
self.genLib = genLibrary()
self.myClosingWindow = closingWindow()
self.genomebrowser = genomeBrowser.genomebrowser()
self.launch_ncbi_button.clicked.connect(self.launch_ncbi)
#scale UI
self.first_show = True
self.scaleUI()
#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
# 16px is used for 92 dpi / 1920x1080
fontSize = 12
self.fontSize = fontSize
self.centralWidget().setStyleSheet("font: " + str(fontSize) + "pt 'Arial';" )
self.menuBar().setStyleSheet("font: " + str(fontSize) + "pt 'Arial';" )
#CASPER header scaling
fontSize = 30
self.label_8.setStyleSheet("font: bold " + str(fontSize) + "pt 'Arial';")
self.adjustSize()
currentWidth = self.size().width()
currentHeight = self.size().height()
#window resize and center
scaledWidth = int((width * 1150) / 1920)
scaledHeight = int((height * 650) / 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 main.")
logger.critical(e)
logger.critical(traceback.format_exc())
# that define the search for targets e.g. endonuclease, organism genome, gene target etc.
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()
width = self.width()
height = self.height()
# scale/center window
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()
except Exception as e:
logger.critical("Error in centerUI() in main.")
logger.critical(e)
logger.critical(traceback.format_exc())
QtWidgets.QApplication.processEvents()
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)
# this function prepares everything for the generate library function
# it is very similar to the gather settings, how ever it stores the data instead of calling the Annotation Window class
# it moves the data onto the generateLib function, and then opens that window
def prep_genlib(self):
# make sure the user actually inputs something
try:
inputstring = str(self.geneEntryField.toPlainText())
if (inputstring.startswith("Example Inputs:") or inputstring == ""):
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error")
msgBox.setText("No gene has been entered. Please enter a gene.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
else:
# standardize the input
inputstring = inputstring.lower()
found_matches_bool = True
# call the respective function
self.progressBar.setValue(10)
if self.radioButton_Gene.isChecked():
if len(self.genlib_list) > 0:
found_matches_bool = True
else:
found_matches_bool = False
elif self.radioButton_Position.isChecked() or self.radioButton_Sequence.isChecked():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error")
msgBox.setText("Generate Library can only work with feature searches.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
"""
elif self.radioButton_Position.isChecked():
pinput = inputstring.split(';')
found_matches_bool = self.run_results("position", pinput,openAnnoWindow=False)
elif self.radioButton_Sequence.isChecked():
sinput = inputstring
found_matches_bool = self.run_results("sequence", sinput, openAnnoWindow=False)
"""
# if matches are found
if found_matches_bool == True:
# get the cspr file name
cspr_file = self.organisms_to_files[self.orgChoice.currentText()][self.endoChoice.currentText()][0]
if platform.system() == 'Windows':
cspr_file = GlobalSettings.CSPR_DB + '\\' + cspr_file
else:
cspr_file = GlobalSettings.CSPR_DB + '/' + cspr_file
kegg_non = 'non_kegg'
# launch generateLib
self.progressBar.setValue(100)
# calculate the total number of matches found
tempSum = len(self.genlib_list)
# warn the user if the number is greater than 50
if tempSum > 50:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Question)
msgBox.setWindowTitle("Many Matches Found")
msgBox.setText("More than 50 matches have been found. Continuing could cause a slow down...\n\n Do you wish to continue?")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Yes)
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.No)
msgBox.exec()
if (msgBox.result() == QtWidgets.QMessageBox.No):
self.searches.clear()
self.progressBar.setValue(0)
return -2
self.genLib.launch(self.genlib_list,cspr_file, kegg_non)
else:
self.progressBar.setValue(0)
except Exception as e:
logger.critical("Error in prep_genlib() in main.")
logger.critical(e)
logger.critical(traceback.format_exc())
#print("prep genlib")
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)
# Function for collecting the settings from the input field and transferring them to run_results
def gather_settings(self):
try:
### If user searches multiple times for the same thing, this avoids re-searching the entire annotation file
check_org = self.orgChoice.currentText().lower()
check_endo = self.endoChoice.currentText().lower()
check_anno_name = self.annotation_files.currentText().lower()
check_input = str(self.geneEntryField.toPlainText()).lower()
if (check_input == self.inputstring and check_org == self.org and check_anno_name == self.anno_name and check_endo == self.endo_name):
same_search = True
else:
self.org = check_org
self.anno_name = check_anno_name
self.inputstring = check_input
self.endo_name = check_endo
same_search = False
# Error check: make sure the user actually inputs something
if (self.inputstring.startswith("Example Inputs:") or self.inputstring == ""):
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error")
msgBox.setText(
"No feature has been searched for. Please enter a search.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
else:
### Remove additional scoring columns if necessary
header = get_table_headers(self.Results.targetTable) # Returns headers of the target table in View Targets window
col_indices = [header.index(x) for x in GlobalSettings.algorithms if x in header] # Returns the index(es) of the alternative scoring column(s) in the target table of View Targets window
if len(col_indices) > 0: # If alternative scoring has been done
for i in col_indices:
self.Results.targetTable.removeColumn(i)
self.Results.targetTable.resizeColumnsToContents()
self.progressBar.setValue(10)
if self.radioButton_Gene.isChecked():
ginput = [x.strip() for x in self.inputstring.split('\n')] # Split search based on newline character and remove deadspace
self.run_results("feature", ginput, same_search)
elif self.radioButton_Position.isChecked():
pinput = [x.strip() for x in self.inputstring.split('\n')] # Split search based on newline character and remove deadspace
self.run_results("position", pinput, same_search)
elif self.radioButton_Sequence.isChecked():
sinput = self.inputstring
self.run_results("sequence", sinput, same_search)
except Exception as e:
logger.critical("Error in gather_settings() in main.")
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()
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)
# ---- Following functions are for running the auxillary algorithms and windows ---- #
# this function is parses the annotation file given, and then goes through and goes onto results
# it will call other versions of collect_table_data and fill_table that work with these file types
# this function should work with the any type of annotation file, besides kegg.
# this assumes that the parsers all store the data the same way, which gff and feature table do
# please make sure the genbank parser stores the data in the same way
# so far the gff files seems to all be different. Need to think about how we want to parse it
def run_results_own_ncbi_file(self, inputstring, fileName, same_search, openAnnoWindow=True):
try:
self.progressBar.setValue(35)
### Now actually search for inputs in annotation file
self.results_list = self.annotation_parser.genbank_search(inputstring,same_search)
### Quick error check to make sure the chromosome numbers match
cspr_file = self.organisms_to_files[self.orgChoice.currentText()][self.endoChoice.currentText()][0]
if platform.system() == 'Windows':
cspr_file = GlobalSettings.CSPR_DB + '\\' + cspr_file
else:
cspr_file = GlobalSettings.CSPR_DB + '/' + cspr_file
own_cspr_parser = CSPRparser(cspr_file)
own_cspr_parser.read_first_lines()
if len(own_cspr_parser.karystatsList) != self.annotation_parser.max_chrom:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Warning:")
msgBox.setText(
"The number of chromosomes do not match. This could cause errors.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(60)
# now go through and search for the actual locus tag, in the case the user input that
searchValues = self.separate_line(inputstring[0])
self.searches.clear()
self.progressBar.setValue(75)
if len(self.results_list) <= 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("No Matches Found")
msgBox.setText(
"No matches found with that search, please try again.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
if openAnnoWindow:
return
else:
return False
# if we get to this point, that means that the search yieleded results, so fill the table
self.progressBar.setValue(80)
# check whether this function call is for Annotation Window, or for generate Lib
if openAnnoWindow:
self.Annotation_Window.fill_table_nonKegg(self,self.results_list)
else:
return True
except Exception as e:
logger.critical("Error in run_results_own_ncbi_file() in main.")
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 run_results(self, inputtype, inputstring, same_search, openAnnoWindow=True):
try:
fileName = self.annotation_files.currentText()
# self.annotation_parser = Annotation_Parser()
#get complete path of file
for file in glob.glob(GlobalSettings.CSPR_DB + "/**/*.gb*", recursive=True):
if file.find(fileName) != -1:
self.annotation_parser.annotationFileName = file
break
self.Results.annotation_path = self.annotation_parser.annotationFileName ### Set annotation path
#print("run results")
progvalue = 15
self.searches = {}
self.gene_list = {}
self.progressBar.setValue(progvalue)
try:
self.Results.endonucleaseBox.currentIndexChanged.disconnect()
except Exception as e:
pass
# set Results endo combo box
self.Results.endonucleaseBox.clear()
# set the results window endoChoice box menu
# set the mainWindow's endoChoice first, and then loop through and set the rest of them
self.Results.endonucleaseBox.addItem(self.endoChoice.currentText())
for item in self.organisms_to_endos[str(self.orgChoice.currentText())]:
if item != self.Results.endonucleaseBox.currentText():
self.Results.endonucleaseBox.addItem(item)
self.Results.endonucleaseBox.currentIndexChanged.connect(self.Results.changeEndonuclease)
self.Results.get_endo_data()
# self.Results.change_start_end_button.setEnabled(False)
self.Results.displayGeneViewer.setChecked(0)
if inputtype == "feature":
fileType = self.annotation_parser.find_which_file_version()
# if the parser retuns the 'wrong file type' error
if fileType == -1:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error:")
msgBox.setText("Feature search requires a GenBank formatted annotation file. Please select a file from the dropdown menu or search by position")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
# make sure an annotation file has been selected
if self.annotation_files.currentText() == "None":
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("No Annotation")
msgBox.setText("Search by feature requires a GenBank annotation file. Please select one from the dropdown menu or search by position.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
# this now just goes onto the other version of run_results
myBool = self.run_results_own_ncbi_file(inputstring, self.annotation_files.currentText(), same_search, openAnnoWindow=openAnnoWindow)
if not openAnnoWindow:
return myBool
else:
self.progressBar.setValue(0)
return
# position code below
if inputtype == "position":
full_org = str(self.orgChoice.currentText())
self.checked_info.clear()
self.check_ntseq_info.clear()
for item in inputstring: # Loop through each search
searchIndices = [x.strip() for x in item.split(',')] # Parse input query
### Make sure the right amount of arguments were passed
if len(searchIndices) != 3:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Invalid Input")
msgBox.setText(
"There are 3 arguments required for this function: chromosome, start position, and end position.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
### Make sure user inputs digits
if not searchIndices[0].isdigit() or not searchIndices[1].isdigit() or not searchIndices[2].isdigit():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Invalid Input")
msgBox.setText(
"The positions given must be integers. Please try again.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
### Make sure start is less than end
elif int(searchIndices[1]) >= int(searchIndices[2]):
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Start Must Be Less Than End")
msgBox.setText(
"The start index must be less than the end index.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
### Make sure range isn't too large
elif abs(int(searchIndices[2])-int(searchIndices[1])) > 50000:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Range Too Large")
msgBox.setText(
"The search range must be less than 50,000 nt.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
### Make sure chromosome exists
elif int(searchIndices[0]) > self.annotation_parser.get_max_chrom():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Chromsome Doesn't Exist")
msgBox.setText(
"Chromosome %s does not exist in the selected annotation file." % searchIndices[0])
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
# append the data into the checked_info
tempString = 'chrom: ' + str(searchIndices[0]) + ',start: ' + str(searchIndices[1]) + ',end: ' + str(searchIndices[2])
self.checked_info[tempString] = (int(searchIndices[0]), int(searchIndices[1])-1, int(searchIndices[2]))
self.progressBar.setValue(50)
self.Results.transfer_data(full_org, self.organisms_to_files[full_org], [str(self.endoChoice.currentText())], os.getcwd(), self.checked_info, self.check_ntseq_info,inputtype)
self.Results.load_gene_viewer()
self.progressBar.setValue(100)
self.pushButton_ViewTargets.setEnabled(True)
self.GenerateLibrary.setEnabled(True)
# sequence code below
if inputtype == "sequence":
fileType = self.annotation_parser.find_which_file_version()
# if the parser retuns the 'wrong file type' error
if fileType == -1:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error:")
msgBox.setText("Search by sequence requires a GenBank annotation file. Please select one from the dropdown menu or search by position.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
if self.annotation_files.currentText() == "None":
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error:")
msgBox.setText("Search by sequence requires a GenBank annotation file. Please select one from the dropdown menu or search by position.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
checkString = 'AGTCN'
full_org = str(self.orgChoice.currentText())
self.checked_info.clear()
self.progressBar.setValue(10)
inputstring = inputstring.replace('\n','').upper().strip()
# make sure all the chars are one of A, G, T, C, or N
for letter in inputstring:
if letter not in checkString:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Sequence Error")
msgBox.setText(
"The sequence must consist of A, G, T, C, or N. No other characters are allowed.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.progressBar.setValue(0)
return
# check to make sure that the use gave a long enough sequence
if len(inputstring) < 100:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Error")
msgBox.setText(
"The sequence given is too small. At least 100 characters are required.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()