-
Notifications
You must be signed in to change notification settings - Fork 3
/
Results.py
1765 lines (1541 loc) · 85.8 KB
/
Results.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 Algorithms import get_table_headers
from PyQt5 import QtWidgets, uic, QtCore, QtGui, Qt
from Bio.Seq import Seq
from Bio import SeqIO
from CSPRparser import CSPRparser
import GlobalSettings
import OffTarget
import platform
import traceback
import math
from scoring_window import Scoring_Window
#global logger
logger = GlobalSettings.logger
# =========================================================================================
# CLASS NAME: Results
# Inputs: Takes information from the main application window and displays the gRNA results
# Outputs: The display of the gRNA results search
# =========================================================================================
class Results(QtWidgets.QMainWindow):
def __init__(self, parent=None):
try:
super(Results, self).__init__(parent)
uic.loadUi(GlobalSettings.appdir + 'results.ui', self)
self.setWindowIcon(Qt.QIcon(GlobalSettings.appdir + "cas9image.ico"))
self.setWindowTitle('Results')
self.geneViewer.setReadOnly(True)
self.curgene = ""
self.dbpath = ""
# Main Data container
# Keys: Gene names
# Values: #
self.annotation_path = ""
self.AllData = {}
self.highlighted = {}
self.co_target_endo_list = list()
self.startpos = 0
self.endpos = 0
self.directory = ""
self.inputtype = ""
self.featureDict = dict() # dictionary passed into transfer_data
self.featureNTDict = dict() #dictionary passed into transfer_data, same key as featureDict, but hols the NTSEQ
self.chromDict = dict() # Initialize dictionary for storing chromosome lengths, same key as featureDict
self.switcher = [1,1,1,1,1,1,1,1] # for keeping track of where we are in the sorting clicking for each column
# Initialize Filter Options Object
self.filter_options = Filter_Options()
# Initialize Scoring Window Object
self.scoring_window = Scoring_Window()
# Target Table settings #
self.targetTable.setColumnCount(8) #
self.targetTable.setShowGrid(False)
self.targetTable.setHorizontalHeaderLabels("Location;Endonuclease;Sequence;Strand;PAM;Score;Off-Target;Details".split(";"))
self.targetTable.horizontalHeader().setSectionsClickable(True)
self.targetTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.targetTable.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.targetTable.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.targetTable.horizontalHeader().setSectionResizeMode(7, QtWidgets.QHeaderView.Stretch) #Ensures last column goes to the edge of table
self.targetTable.horizontalHeader().setSectionResizeMode(7, QtWidgets.QHeaderView.Stretch) #Ensures last column goes to the edge of table
self.back_button.clicked.connect(self.goBack)
self.targetTable.horizontalHeader().sectionClicked.connect(self.table_sorting)
self.off_target_button.clicked.connect(self.Off_Target_Analysis)
self.cotargeting_button.clicked.connect(self.open_cotarget)
self.displayGeneViewer.stateChanged.connect(self.checkGeneViewer)
self.filter_options.cotarget_checkbox.stateChanged.connect(self.prep_cotarget_checkbox)
self.highlight_gene_viewer_button.clicked.connect(self.highlight_gene_viewer)
self.checkBoxSelectAll.stateChanged.connect(self.selectAll)
self.filter_options_button.clicked.connect(self.show_filter_options)
self.scoring_options_button.clicked.connect(self.show_scoring_window)
self.change_start_end_button.clicked.connect(self.change_indices)
self.reset_location_button.clicked.connect(self.reset_location)
self.export_button.clicked.connect(self.open_export_tool)
#self.targetTable.itemSelectionChanged.connect(self.item_select)
self.filter_options.minScoreLine.setText("0")
# Connecting the filters to the displayGeneData function
self.filter_options.fivegseqCheckBox.stateChanged.connect(self.displayGeneData)
self.filter_options.minScoreLine.textChanged.connect(self.displayGeneData)
# Setting up the score filter:
self.filter_options.scoreSlider.setMinimum(0)
self.filter_options.scoreSlider.setMaximum(100)
self.filter_options.scoreSlider.setTracking(False)
self.filter_options.scoreSlider.valueChanged.connect(self.update_score_filter)
#bool used to make sure only 1 instance of the OffTarget window is created
self.first_boot = True
#OTA is used to hold the row numbers of the items selected by user for OffTargetAnalysis
#using this helps speed up updating the chart
self.OTA = []
self.clear_highlighted_guides_button.clicked.connect(self.clear_highlighted_guides)
self.detail_output_list = []
self.rows_and_seq_list = []
self.seq_and_avg_list = []
self.files_list = []
self.mwfg = self.frameGeometry() ##Center window
self.cp = QtWidgets.QDesktopWidget().availableGeometry().center() ##Center window
groupbox_style = """
QGroupBox:title{subcontrol-origin: margin;
left: 10px;
padding: 0 5px 0 5px;}
QGroupBox#guide_viewer{border: 2px solid rgb(111,181,110);
border-radius: 9px;
margin-top: 10px;
font: bold 14pt 'Arial';}"""
self.guide_viewer.setStyleSheet(groupbox_style)
self.guide_analysis.setStyleSheet(groupbox_style.replace("guide_viewer", "guide_analysis"))
self.gene_viewer.setStyleSheet(groupbox_style.replace("guide_viewer", "gene_viewer"))
self.get_endo_data()
### Make line edits only accept integers
self.lineEditStart.setValidator(QtGui.QIntValidator())
self.lineEditEnd.setValidator(QtGui.QIntValidator())
#scale UI
self.first_show = True
self.scaleUI()
except Exception as e:
logger.critical("Error initializing results 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)
#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 * 1250) / 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 results.")
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 results.")
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 get_endo_data(self):
try:
f = open(GlobalSettings.appdir + "CASPERinfo")
self.endo_data = {}
while True:
line = f.readline()
if line.startswith('ENDONUCLEASES'):
while True:
line = f.readline()
line = line.replace("\n","")
if (line[0] == "-"):
break
line_tokened = line.split(";")
if len(line_tokened) == 10:
endo = line_tokened[0]
five_length = line_tokened[2]
seed_length = line_tokened[3]
three_length = line_tokened[4]
prime = line_tokened[5]
hsu = line_tokened[9]
self.endo_data[endo] = [int(five_length) + int(three_length) + int(seed_length), prime, "MATRIX:" + hsu]
break
f.close()
except Exception as e:
logger.critical("Error in get_endo_data() in results.")
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 resets (turns off, then on) the selection of all the rows in the ViewTargets table.
# For some reason this is necessary after adding values to the table through alternative scoring
# (different on-target scoring or off-target), otherwise the export function will bug due to newly
# added items being queued to the back of the list of self.targetTable.selectedItems(), instead of
# where they belong at the end of each row.
def reset_selection(self):
rows = sorted(set(index.row() for index in self.targetTable.selectedIndexes())) # Find selected rows
self.targetTable.clearSelection() # Clear the selection
for row in rows: # For each selected row
self.targetTable.selectRow(row) # Reselect each row
# this function opens the export_tool window
# first it makes sure that the user actually has some highlighted targets that they want exported
def open_export_tool(self):
try:
self.reset_selection()
select_items = self.targetTable.selectedItems()
if len(select_items) <= 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Nothing Selected")
msgBox.setText("No targets were highlighted. Please highlight the targets you want to be exported to a CSV File!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
# now launch the window
GlobalSettings.mainWindow.export_tool_window.launch(select_items,"vt")
except Exception as e:
logger.critical("Error in open_export_tool() in results.")
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 change_indices(self):
try:
### Make sure the gene viewer is on
if not self.displayGeneViewer.isChecked():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Gene Viewer Error")
msgBox.setText("Gene Viewer display is off! Please turn the Gene Viewer on in order to highlight the sequences selected")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
### Change the start and end values
prevTuple = self.featureDict[self.curgene]
tempTuple = (self.featureDict[self.curgene][0], int(self.lineEditStart.displayText())-1, int(self.lineEditEnd.displayText()))
### Make sure both indices are greater than 0
if tempTuple[1]+1 <= 0 or tempTuple[2] <= 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Invalid location indices.")
msgBox.setText("Location indices cannot be negative or zero! Please set values larger than 0.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
self.reset_location()
return
### Make sure start is less than stop
if tempTuple[1] >= tempTuple[2]:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Invalid location indices.")
msgBox.setText("Start location must be less than stop location.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
self.reset_location()
return
### Make sure that the difference between indicies is not too large
if abs(tempTuple[1] - tempTuple[2]) > 50000:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Sequence Too Long")
msgBox.setText("The sequence is too long! Please choose indicies that will make the sequence less than 50,000!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
self.reset_location()
return
### Make sure search is within chromosome range
if int(tempTuple[2]) > self.chromDict[self.curgene]:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Position Error: Region not in Chromosome")
msgBox.setText(
"The stop location is greater than the chromosome's length.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
self.reset_location()
return
sequence, chrom_len = self.sequence_finder(tempTuple) # Get the appropriate NT sequence
self.geneViewer.setText(sequence) # Set the gene viewer to display the sequence
except Exception as e:
logger.critical("Error in change_indices() in results.")
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 listens for a stateChange in selectAllShown
# if it is checked, it selects all shown
# if it is unchecked, it deselects all shown
# Note: it is a little buggy, possibly because when you change the minimum score it resets it all
def selectAll(self):
try:
if self.checkBoxSelectAll.isChecked():
self.targetTable.selectAll()
else:
self.targetTable.clearSelection()
except Exception as e:
logger.critical("Error in selectAll() in results.")
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 resets gene viewer to the appropriate sequence
def reset_location(self):
try:
if self.displayGeneViewer.isChecked():
self.geneViewer.setText(self.featureNTDict[self.curgene])
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
else:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Gene Viewer Error")
msgBox.setText("Gene Viewer display is off! Please turn the Gene Viewer on in order to reset the locations")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
except Exception as e:
logger.critical("Error in reset_location() in results.")
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)
# hightlights the sequences found in the gene viewer
# highlighting should stay the exact same with fasta and genbank files, as this function only edits what
# is currently in the gene viewer text table anyways
def highlight_gene_viewer(self):
try:
# make sure gene viewer is enabled
if not self.displayGeneViewer.isChecked():
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Gene Viewer Error")
msgBox.setText("Gene Viewer display is off! Please turn the Gene Viewer on in order to highlight the sequences selected")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
# variables needed
cursor = self.geneViewer.textCursor()
format = QtGui.QTextCharFormat()
failed_guides = []
# check and make sure still is actually highlighted!
selectedList = self.targetTable.selectedItems()
if len(selectedList) <= 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Nothing Selected")
msgBox.setText("No targets were highlighted. Please highlight the targets you want to be highlighted in the gene viewer!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
# this is the loop that actually goes in and highlights all the things
for i in range(self.targetTable.rowCount()):
if self.targetTable.item(i, 0).isSelected():
# get the strand and sequence strings
locationString = self.targetTable.item(i,0).text()
strandString = self.targetTable.item(i, 3).text()
sequenceString = self.targetTable.item(i, 2).text()
printSequence = ""
movementIndex = len(sequenceString)
left_right = ""
#print("Length of geneViewer: ", len(self.geneViewer.toPlainText()))
if strandString == "+":
format.setBackground(QtGui.QBrush(QtGui.QColor("green")))
index = self.geneViewer.toPlainText().upper().find(str(sequenceString))
if index != -1: # If gRNA is found in GeneViewer
cursor.setPosition(index)
for i in range(movementIndex): # Actually highlight the gRNA now
cursor.movePosition(QtGui.QTextCursor.NextCharacter, 1)
cursor.mergeCharFormat(format)
else:
failed_guides.append(sequenceString)
continue
else: # gRNA is on negative strand
format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
index = self.geneViewer.toPlainText().upper().find(str(Seq(sequenceString).reverse_complement()))
if index != -1: # If gRNA is found in GeneViewer
cursor.setPosition(index)
for i in range(movementIndex): # Actually highlight the gRNA now
cursor.movePosition(QtGui.QTextCursor.NextCharacter, 1)
cursor.mergeCharFormat(format)
else:
failed_guides.append(sequenceString)
continue
# if any of the sequences return 0 matches, show the user which ones were not found
if len(failed_guides) > 0:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Warning")
msgBox.setText(
"The following sequence(s) were not found in the Gene Viewer text:\n\t" + "\n".join(failed_guides))
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
except Exception as e:
logger.critical("Error in highlight_gene_viewer() in results.")
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 updates the gene viewer based on the user clicking 'display on'
# if it is check marked, it displays the correct data
# if it is un-marked, it hides the data
def checkGeneViewer(self):
try:
if self.displayGeneViewer.isChecked():
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1))
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2]))
self.geneViewer.setText(self.featureNTDict[self.curgene])
elif not self.displayGeneViewer.isChecked():
self.lineEditStart.clear()
self.lineEditEnd.clear()
self.geneViewer.clear()
except Exception as e:
logger.critical("Error in checkGeneViewer() in results.")
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 opens when the user clicks the CoTargeting button
def open_cotarget(self):
try:
endo_list = list()
if self.endonucleaseBox.count() <= 1:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Not Enough Endonucleases")
msgBox.setText(
"There are not enough endonucleases with this organism. At least 2 endonucleases are required for this function. Use Analyze New Genome to create CSPR files with other endonucleases.")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
for i in range(self.endonucleaseBox.count()):
endo_list.append(self.endonucleaseBox.itemText(i))
GlobalSettings.mainWindow.CoTargeting.launch(endo_list, GlobalSettings.mainWindow.orgChoice.currentText())
except Exception as e:
logger.critical("Error in open_cotarget() in results.")
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 goes through and calls transfer_data again.
# Uses data from the mainWindow in Globalsettings, but that's because that info should not change
# unless the user closes out of the Results window
def changeEndonuclease(self):
try:
full_org = str(GlobalSettings.mainWindow.orgChoice.currentText())
# organism = GlobalSettings.mainWindow.shortHand[full_org]
endoChoice = self.endonucleaseBox.currentText().split("|")
# make sure the user actually selects a new endonuclease
if self.endo == endoChoice:
msgBox = QtWidgets.QMessageBox()
msgBox.setStyleSheet("font: " + str(self.fontSize) + "pt 'Arial'")
msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)
msgBox.setWindowTitle("Select a different Endonuclease")
msgBox.setText(
"Please be sure to select a different endonuclease!")
msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Ok)
msgBox.exec()
return
# enable the cotarget checkbox if needed
if len(endoChoice) > 1:
self.filter_options.cotarget_checkbox.setEnabled(True)
self.filter_options.cotarget_checkbox.setChecked(0)
else:
self.filter_options.cotarget_checkbox.setEnabled(False)
self.filter_options.cotarget_checkbox.setChecked(0)
self.transfer_data(full_org, GlobalSettings.mainWindow.organisms_to_files[full_org], endoChoice, GlobalSettings.CSPR_DB, self.featureDict,
self.featureNTDict, self.inputtype)
except Exception as e:
logger.critical("Error in changeEndonuclease() in results.")
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)
# Function that is used to set up the results page.
# it calls get_targets, which in turn calls display data
def transfer_data(self, org, org_files, endo, path, feature_dict, featureNTSeqDict, inputtype):
try:
# set all of the classes variables
self.org = org
self.org_files = org_files
self.endo = endo
self.directory = path
self.comboBoxGene.clear()
self.AllData.clear()
self.featureDict =feature_dict
self.featureNTDict = featureNTSeqDict
self.inputtype = inputtype
self.highlighted.clear()
self.detail_output_list.clear()
self.seq_and_avg_list.clear()
self.rows_and_seq_list.clear()
self.OTA.clear()
for feature in feature_dict:
if self.inputtype == "feature":
detail_output1 = {}
rows_and_seq2 = {}
seq_and_avg3 = {}
self.detail_output_list.append(detail_output1)
self.seq_and_avg_list.append(seq_and_avg3)
self.rows_and_seq_list.append(rows_and_seq2)
self.comboBoxGene.addItem(feature)
self.get_targets(feature, feature_dict[feature])
if self.inputtype == "position":
detail_output1 = {}
rows_and_seq2 = {}
seq_and_avg3 = {}
self.detail_output_list.append(detail_output1)
self.seq_and_avg_list.append(seq_and_avg3)
self.rows_and_seq_list.append(rows_and_seq2)
self.comboBoxGene.addItem(feature)
self.get_targets(feature, feature_dict[feature])
if self.inputtype == "sequence":
detail_output1 = {}
rows_and_seq2 = {}
seq_and_avg3 = {}
self.detail_output_list.append(detail_output1)
self.seq_and_avg_list.append(seq_and_avg3)
self.rows_and_seq_list.append(rows_and_seq2)
self.comboBoxGene.addItem(feature)
self.get_targets(feature, feature_dict[feature])
# Enable the combobox to be toggled now that the data is in AllData
self.comboBoxGene.currentTextChanged.connect(self.displayGeneData)
self.first_boot = True
except Exception as e:
logger.critical("Error in transfer_data() in results.")
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 goBack(self):
try:
GlobalSettings.mainWindow.show()
self.filter_options.cotarget_checkbox.setChecked(0)
self.filter_options.hide()
try:
self.off_tar_win.hide()
except:
pass
GlobalSettings.mainWindow.CoTargeting.hide()
self.scoring_window.hide()
self.hide()
except Exception as e:
logger.critical("Error in goBack() in results.")
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)
# called when the user hits 'gene viewer settings'
def changeGeneViewerSettings(self):
try:
GlobalSettings.mainWindow.gene_viewer_settings.show()
GlobalSettings.mainWindow.gene_viewer_settings.activateWindow()
except Exception as e:
logger.critical("Error in changeGeneViewerSettings() in results.")
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 is the function that sets up the cotargeting.
# it is called from the Cotargeting class, when the user hits submit
# myBool is whether or not to change the endoChoice comboBox
def populate_cotarget_table(self, myBool = True):
try:
try:
self.endonucleaseBox.currentIndexChanged.disconnect()
except:
pass
# make a string of the combination, separated by commas's
endoBoxString = ""
for i in range(len(self.co_target_endo_list)):
if endoBoxString == "":
endoBoxString = self.co_target_endo_list[i]
else:
endoBoxString = endoBoxString + '|' + self.co_target_endo_list[i]
# put the new endoChoice at the beginning. This is the only way i could find to do it
# get a list of all endo choices, and put the newest at the front
endoBoxList = list()
endoBoxList.append(endoBoxString)
for i in range(self.endonucleaseBox.count()):
if self.endonucleaseBox.itemText(i) not in endoBoxList: # Prevent duplicate entries
endoBoxList.append(self.endonucleaseBox.itemText(i))
# clear the current endo choices, and append the new order
if myBool:
self.endonucleaseBox.clear()
for i in range(len(endoBoxList)):
self.endonucleaseBox.addItem(endoBoxList[i])
# enable the cotarget checkbox
self.filter_options.cotarget_checkbox.setEnabled(True)
self.filter_options.cotarget_checkbox.setChecked(0)
self.endonucleaseBox.currentIndexChanged.connect(self.changeEndonuclease)
# add it to the endoBox choices, and then call transfer_data
self.transfer_data(self.org, self.org_files, self.co_target_endo_list, GlobalSettings.CSPR_DB, self.featureDict, self.featureNTDict,self.inputtype)
except Exception as e:
logger.critical("Error in populate_cotarget_table() in results.")
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)
# prep function for the checkbox for cotargeting
# if the checkbox is checked, just go ahead and displayGeneData
# if not, call populate_cotarget_table, as a reset to get all of the data there
def prep_cotarget_checkbox(self):
try:
if self.filter_options.cotarget_checkbox.isChecked():
self.displayGeneData()
elif not self.filter_options.cotarget_checkbox.isChecked():
self.populate_cotarget_table(myBool=False)
except Exception as e:
logger.critical("Error in prep_cotarget_checkbox() in results.")
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)
# Function grabs the information from the .cspr file and adds them to the AllData dictionary
#changed to now call CSPRparser's function. Same function essentially, just cleaned up here
def get_targets(self, genename, pos_tuple):
try:
#get the right files
for endo in self.endo:
if platform.system() == "Windows":
file = self.directory + "\\" + self.org_files[endo][0]
else:
file = self.directory + "/" + self.org_files[endo][0]
#create the parser, read the targets store it. then display the GeneData screen
parser = CSPRparser(file)
# if genename is not in the dict, make that spot into a list
if genename not in self.AllData:
self.AllData[genename] = list()
# now append parser's data to it
self.AllData[genename].append(parser.read_targets(genename, pos_tuple, endo))
# for each list item
for item in self.AllData[genename]:
# for each tuple item
for i in range(len(item)):
self.highlighted[item[i][1]] = False
# if the endo choice is greater than 1, call the combine
if len(self.endo) > 1:
self.combine_coTargets(genename)
self.displayGeneData()
except Exception as e:
logger.critical("Error in get_targets() in results.")
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)
###############################################################################################################
# Main Function for updating the Table. Connected to all filter buttons and the Gene toggling of the combobox.
###############################################################################################################
def displayGeneData(self):
try:
self.curgene = str(self.comboBoxGene.currentText()) # Gets the current gene
# Creates the set object from the list of the current gene:
if self.curgene=='' or len(self.AllData)<1:
return
subset_display = []
# set the start and end numbers, as well as set the geneViewer text, if the displayGeneViewer is checked
if self.displayGeneViewer.isChecked():
self.lineEditStart.setText(str(self.featureDict[self.curgene][1]+1)) # Set start index for gene (Add 1 to account for Python indexing convention)
self.lineEditEnd.setText(str(self.featureDict[self.curgene][2])) # Set end index for gene
self.geneViewer.setText(self.featureNTDict[self.curgene]) # Get gene sequence
# if this checkBox is checked, remove the single endo
if self.filter_options.cotarget_checkbox.isChecked():
gene = self.curgene
self.remove_single_endo(gene)
# Removing all sequences below minimum score and creating the set:
# for each list item
for item in self.AllData[self.curgene]:
# for each tuple item
for i in range(len(item)):
if int(item[i][3]) > int(self.filter_options.minScoreLine.text()):
# Removing all non 5' G sequences:
if self.filter_options.fivegseqCheckBox.isChecked():
if item[i][1].startswith("G"):
subset_display.append(item[i])
else:
subset_display.append(item[i])
self.targetTable.setRowCount(len(subset_display))
index = 0
#changed the number items to use setData so that sorting will work correctly
#because before the numbers were interpretted as strings and not numbers
### Remove alternative scoring columns (Azimuth, etc.) when switching between genes or loading new data...this prevents carry-over of the wrong scores from previously scored genes
### One possible solution would be to add alternate scores to self.AllData, but I won't do that for now.
header = get_table_headers(self.targetTable) # Returns headers of the target table
num_cols = len(header) # Get number of columns
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.targetTable.removeColumn(i)
for item in subset_display:
num = int(item[0])
loc = QtWidgets.QTableWidgetItem()
loc.setData(QtCore.Qt.EditRole, abs(num))
seq = QtWidgets.QTableWidgetItem(item[1])
strand = QtWidgets.QTableWidgetItem(str(item[4]))
PAM = QtWidgets.QTableWidgetItem(item[2])
num1 = int(item[3])
endonuclease = QtWidgets.QTableWidgetItem(item[5])
score = QtWidgets.QTableWidgetItem()
score.setData(QtCore.Qt.EditRole, num1)
self.targetTable.setItem(index, 0, loc)
self.targetTable.setItem(index, 1, endonuclease)
self.targetTable.setItem(index, 2, seq)
self.targetTable.setItem(index, 3, strand)
self.targetTable.setItem(index, 4, PAM)
self.targetTable.setItem(index, 5, score)
self.targetTable.setItem(index, 6, QtWidgets.QTableWidgetItem("--.--")) # Give "blank" value for Off-Target
self.targetTable.removeCellWidget(index, num_cols-1) # Leave the "Details" column empty
if (item[1] in self.seq_and_avg_list[self.comboBoxGene.currentIndex()].keys()):
OT = QtWidgets.QTableWidgetItem()
OT.setData(QtCore.Qt.EditRole, self.seq_and_avg_list[self.comboBoxGene.currentIndex()][item[1]])
self.targetTable.setItem(index, 6, OT)
if (item[1] in self.detail_output_list[self.comboBoxGene.currentIndex()].keys()):
details = QtWidgets.QPushButton()
details.setText("Details")
details.clicked.connect(self.show_details)
self.targetTable.setCellWidget(index, 7, details)
index += 1