-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmotifSurvey.py
More file actions
1687 lines (1052 loc) · 57.9 KB
/
motifSurvey.py
File metadata and controls
1687 lines (1052 loc) · 57.9 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
import os
import statistics
from Bio import SeqIO
from Bio import Entrez
from Bio.Align.Applications import ClustalOmegaCommandline
import re
import regex
import sys
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
#Used to create object to store information about each sequence
class inputSeqCapsule:
#Used on object initiation, creates multiple variables from list input)
def __init__(self, list):
self.sequence = list[0][0]
# print(self.sequence)
self.GCcontent = list[0][1]
# print(self.GCcontent)
self.gapSegements = list[0][2]
# print(self.gapSegements)
self.sequenceLength = list[0][3]
# print(self.sequenceLength)
self.countA = list[0][4]
# print(self.countA)
self.countT = list[0][5]
# print(self.countT)
self.countC = list[0][6]
# print(self.countT)
self.countG = list[0][7]
# print(self.countG)
self.name = list[0][8]
self.subsequenceDict = {}
self.genBankFile = ''
#Prints output to screen
def objectInformation(self, l="N", ):
a = "Sequence Name:\t" + self.name
b = "Sequence Length:\t" + str(self.sequenceLength)
c = "GC%:\t" + str(self.GCcontent)
d = "Gaps:\t" + str(self.gapSegements)
e = "Adenosine:\t" + str(self.countA)
f = "Thymine:\t" + str(self.countT)
g = "Cytosine:\t" + str(self.countC)
h = "Guanine:\t" + str(self.countG)
if l == "N":
return a + "\n" + b + "\n" + c + "\n"
elif l == "Y":
return a + "\n" + b + "\n" + c + "\n" + d + "\n" + e + "\n" + f + "\n" + g + "\n" + h + "\n"
#Main function called by each object, creates a dictionary of substrings that occur more than once in each sequence
#Records positions of matches using (x,y) notation, stored as set() in each dictionary value
def seqSearch(self, subsequence="", window=0):
#If a nucletotide is repeated more than 10 (default value) times, it is stored here and output to ""
#Planned update, currently seqSearch handles motifs >3 nt in length
repeatNtCheck = []
#Checks if there is input, if "" then using sliding window to match substring
if subsequence == "":
windowStart = 0
windowStop = windowStart + window
#If sequence length < window returns sequence
if (len(self.sequence) <= windowStop):
return (self.sequence)
else:
#Uses sliding window, subtracts end one position to account starting position
for i in range(len(self.sequence) - (windowStop + 1)):
s1 = self.sequence
#Sets search pattern
pattern = (self.sequence[i:i + windowStop])
if pattern in motifsToIgnore:
continue
else:
#Index is used here to denote the exact substring position
subStringStart = ((self.sequence).index(self.sequence[i:i + windowStop]))
subStringEnd = ((self.sequence).index(self.sequence[i:i + windowStop]) + window)
#%s is string formatting, this allows use of 'r' in other regex function
r = regex.compile('(%s)' % pattern, re.IGNORECASE)
#Finds match and then
for match in regex.finditer(r, s1):
s = match.start()
e = match.end()
subSeqKey = s1[s:e]
matchAsRange = "(" + str(s) + "," + str(e) + ")"
originalStringAsRange = "(" + str(subStringStart) + "," + str(subStringEnd) + ")"
#Does not include itself as a match
if s == subStringStart and e == subStringEnd:
next
#If subSeqKey is not in dictionary, it creates an entry
elif subSeqKey not in self.subsequenceDict.keys():
self.subsequenceDict[subSeqKey] = set()
self.subsequenceDict[subSeqKey].add(originalStringAsRange)
#If subSeqKey is in dictionary it prints output to screen of match
else:
print('Motif match "%s" at %d:%d' % (s1[s:e], s, e))
print('Original motif is at ' + str(subStringStart) + ": " + str(subStringEnd))
self.subsequenceDict[subSeqKey].add(matchAsRange)
#Opens FASTA file and stores them in headerAndSequence
#edit: great spot for seq. length options
def fastaFormatFileInput(multiFASTA):
currentHeader = ''
#Opens FASTA file and stores them in headerAndSequence
with open(multiFASTA) as a_file:
for line in a_file:
strippedLine = line.strip()
if len(strippedLine) == 0: # skips empty lines
continue
# Uses sequence header as key
elif strippedLine.startswith(tuple(headerIdentifiers)):
headerAndSequence[strippedLine] = ''
currentHeader = strippedLine
# if strippedLine is not empty or header it is sequence and will be appended
else:
headerAndSequence[currentHeader] += strippedLine
#edit: could alter what region of sequence to search here
for key, value in headerAndSequence.items():
if endPositionofSurvey > len(str(value)):
print("End position is greater than sequence length. Please choose a different value")
break
elif startPositionofSurvey > 0 and endPositionofSurvey == 0:
headerAndSequence[key] = [value[startPositionofSurvey:]]
elif startPositionofSurvey and endPositionofSurvey > 0:
headerAndSequence[key] = [value[startPositionofSurvey:endPositionofSurvey]]
else:
headerAndSequence[key] = [value]
#used to ensure .gb file is read correctly
headerAndSequenceFullLength[key] = [value]
# print(headerAndSequence)
outputComparison['ENTRY COUNT'] = len(headerAndSequence.keys())
a_file.close()
#Appends information about genome to previous entry in headerAndSequence using updatedValue
#updatedValue = [value + sequenceInformation + [(key)]]
#headerAndSequence[key] = updatedValue
#updatedValue is also appended to inputSeqMasterList
#inputSeqMasterList is used to initialize
def sequenceInformation(dictObj):
# Displays preliminary sequence information
seqInfoDict = dictObj
entryNumber = 1
for key, value in seqInfoDict.items():
GCcount = 0
gapSegments = 0
countA, countT, countC, countG = (0,) * 4
#edit: use count function here instead of list
for i in str(value):
if i == 'A':
countA += 1
elif i == 'T':
countT += 1
elif i == 'C':
countC += 1
elif i == 'G':
countG += 1
elif i == '-':
gapSegments += 1
if i == 'G' or i == 'C':
GCcount += 1
GCpercentage = GCcount / len(str(value)[2:-2])
sequenceLength = len(str(value)[2:-2])
sequenceInformation = [GCpercentage, gapSegments, sequenceLength, countA, countT, countC, countG]
fullLengthOfSequence = str(headerAndSequenceFullLength[key])
updatedValue = [value + sequenceInformation + [(key)]]
headerAndSequence[key] = updatedValue
# print(str(entryNumber) + ')')
# print(key)
# print('GC Percetage:\t' + str(GCpercentage))
# print('Gaps:\t' + str(gapSegments))
# print('Sequence Length:\t' + str(sequenceLength))
# print('Adenosine:\t' + str(countA))
# print('Thymine:\t' + str(countT))
# print('Cytosine:\t' + str(countC))
# print('Guanine:\t' + str(countG))
# print('\n')
entryNumber += 1
inputSeqMasterList.append(updatedValue)
# print(inputSeqMasterList)
# print(inputSeqMasterList)
# print(inputSeqMasterList)
# print(headerAndSequence)
#Iterates through genBank file previously associated with seqObj, attempts to find position in range of entries
def genBankLocationObj(seqObj, arrayOne, windowSize, notFoundList, substring, pos=0):
matchesIngenBank = 0
sequenceRecord = seqObj
#Iterates through all GenBank features
for record in range(len(sequenceRecord.features)):
locationRangeString = str(sequenceRecord.features[record].location)[1:-4]
rangeAsList = locationRangeString.split(":")
currentProduct = (sequenceRecord.features[record].qualifiers.get('product', ''))
positionForLabel = " (" + str(pos) + "-" + str(pos + windowSize) + ") "
labelForNoEntry = str(sequenceRecord.description) + positionForLabel + substring
# print(rangeAsList[0])
if re.search('^(oin)', str(rangeAsList[0])):
continue
elif int(rangeAsList[0]) == 0:
continue
elif (pos) in range(int(rangeAsList[0]), int(rangeAsList[1])) and len(
sequenceRecord.features[record].qualifiers) > 2:
print("START POSITION OF MOTIF:" + str(pos) + "\n")
print(sequenceRecord.features[record])
arrayOne.append(currentProduct)
matchesIngenBank = 1
#If not matches are found, this is the output
if matchesIngenBank == 0:
print(str(pos) + " WAS NOT FOUND IN THE RANGE OF ANY RECORDED FEATURES \n\n")
#Takes note of positions not found in recorded features
notFoundList.append(labelForNoEntry)
#this function links .gb files with input FASTA sequences using the sequence itself as identifier
def genBankFileLink(dict, path):
fastaDict = dict
keyAndAccessionDict = {}
# with open(direc) as b_file:
#
# for line in b_file:
# lineAsList = (line.strip()).split("\t")
#
# genBankFileName = lineAsList[0].upper()
#
# accessionNumber = lineAsList[1]
#
# keyAndAccessionDict[genBankFileName] = accessionNumber
#
# b_file.close()
for file in os.listdir(path):
#print(file)
with open(os.path.join(path, file)) as gbFile:
fullGBText = SeqIO.read(gbFile, "genbank")
for k, v in fastaDict.items():
seqObjLabel = str(k)
gbSeq = ''.join(str(fullGBText.seq))
fastaName = fastaDict[seqObjLabel].name
if fastaName in headerAndSequenceFullLength.keys():
fastaSeq = headerAndSequenceFullLength[fastaName]
fastaSeq = ''.join(fastaSeq)
# print(str(len(fastaSeq)))
# print(str(len(gbSeq)))
if str(fastaSeq) == str(gbSeq):
fastaDict[seqObjLabel].genBankFile = fullGBText
#Calculates the % of the genome not contained in gb Records
#Gives perspective if a substring occurs in an area more often than expected by chance
def genomePercentNotCoveredInGB(seqObj):
overLapAdjustment = 0
valueForOverlapAdjustment = 0
if type(seqObj) == str:
return
if seqObj is None:
return
else:
#seqObj is gbFile saved to object
sequenceRecord = seqObj
dictionaryCheck = {}
lengthOfSequenceNoSpace = 0
itemCheck = set()
itemtest = []
#Iterates through each record in gbFile
for record in range(len(sequenceRecord.features)):
locationRangeString = str(sequenceRecord.features[record].location)[1:-4]
#print(locationRangeString)
rangeAsList = locationRangeString.split(":")
#print(rangeAsList)
#print((rangeAsList[1]))
#print(len(sequenceRecord.seq))
if re.search('^(oin)', str(rangeAsList[0])):
continue
#Adds the length of the record to lengthOfSequenceNoSpace
else:
rangeInputLength = len(range(int(rangeAsList[0]), int(rangeAsList[1])))
#print(rangeInputLength)
rangeInput = range(int(rangeAsList[0]), int(rangeAsList[1]))
#print(rangeInput)
if int(rangeAsList[0]) == 0:
continue
elif rangeInput in itemCheck:
continue
else:
if valueForOverlapAdjustment > int(rangeAsList[0]):
adjustment = valueForOverlapAdjustment - int(rangeAsList[0])
overLapAdjustment = overLapAdjustment + adjustment
#print(rangeAsList)
valueForOverlapAdjustment = int(rangeAsList[1])
#print(valueForOverlapAdjustment)
itemCheck.add(rangeInput)
#print(rangeInputLength)
#print(rangeInput)
lengthOfSequenceNoSpace = lengthOfSequenceNoSpace + rangeInputLength
# print('TESTING')
# print(lengthOfSequenceNoSpace)
# print(overLapAdjustment)
# print(len(sequenceRecord.seq))
# print(lengthOfSequenceNoSpace/len(sequenceRecord.seq))
# print((lengthOfSequenceNoSpace - overLapAdjustment) / len(sequenceRecord.seq))
#print("\n")
#divides lengthOfSequenceNoSpace by full sequence length to determine difference in length
#this sequence length is taken directly from the gb file
return (lengthOfSequenceNoSpace - overLapAdjustment) / len(sequenceRecord.seq)
#Used to create masterSequenceDictionary, this dictionary assigns each header and sequence its own object
#SO,S1,S2,S3..... is the key
#The value will be the class object, this is neccessary for substring comparisons between the sequence objects
#This object contains sequence information, a seqSearch function and variables needed for downstream analysis
#This dictionary is one of the values reset after each run (A1, A2, A3 etc.)
def classCreation(list):
objectNameDict = {}
allSequenceInformation = list
# print((len(allSequenceInformation)))
# print((len(headerAndSequence.values())))
for x in range(len(headerAndSequence.values())):
objectName = "S" + str(x)
objectNameDict[objectName] = ""
# print(objectNameDict)
numberLabel = 0
#inputSeqCapsule is class creation function. Takes list of all sequences and gives each its own object. numberLabel
#is used to ensure all sequences get an object of their own
for k, v in objectNameDict.items():
objectNameDict[k] = inputSeqCapsule(allSequenceInformation[numberLabel])
numberLabel += 1
# print(objectNameDict[k].name)
# print(objectNameDict[k].subsequenceDict)
print(objectNameDict[k].objectInformation("Y"))
return (objectNameDict)
#Using masterSequenceDictionary as, the seqSearch function within each object is called
#Heavily commented
#Each seqSearch input is saved in comparisonDict, which is used for file output
#Substring = key, position of occurrence in that ONE sequence = value (subseqDictionary)
#Substring = key, position and specific sequence = value (comparisonDict)
#edit: optional parameter for sequence length
def seqSearch(dInput, searchWindow, summaryFileName, maxSequenceLength=0, filePrefix='', numberOfAlignments=0,
outputDirectory=''):
#Contains masterSequenceDictionary, S#: classObject containing information about 1 specific sequence
#Each sequence from FASTA input file gets its own object
totalSeqDict = dInput
substringPositionsForRange = []
productAsList = []
translationAsDict = {}
#used to set ranges for later alignments, observers alignments in a 10000 bp range
binSize = 0
originalBinSize = 0
seqWithoutGenBank = []
#stores paths for alignments using ClustalO
fastaPathsForAlignment = []
substringAlignmentList = []
listOfNoGBEntry = []
gbGenevSpace = []
#edit: Used to determine string length, better method to be added
inputMessage = 0
masterTextList = []
averageForSegmentOccurances = []
#Used to set the range for alignments to be made. ie/ 60000 bp with 6 alignments is 6 10000 bp bins
if maxSequenceLength > 0 and numberOfAlignments > 0:
binSize = int(maxSequenceLength / numberOfAlignments)
originalBinSize = binSize
# print(binSize)
#Calls seqSearch in each object of masterSequenceDictionary
for k, v in totalSeqDict.items():
print(totalSeqDict[k].name + "\n")
totalSeqDict[k].seqSearch(window=searchWindow)
#subSequenceDict is the dictionary within each object for seqSearch output. Substring = key, position and sequence = value
print(totalSeqDict[k].subsequenceDict.items())
print(len(totalSeqDict[k].subsequenceDict.keys()))
print("END OF ENTRY")
print("_________________\n\n")
#Dictionary that compares sequences (object by object). Makes note
comparisonDict = {}
uniqueSubSeqs = set()
#Handles case where only one sequence is in FASTA
#Compares masterSequenceDictionary to itself, ignoring exact comparisons. Matching substrings are passed to comparisonDict
#comparisonDict[sharedKey] = []
#The list value stores the sequence and positions in the sequence where the match occured
#Thus, a dictionary with substrings as the key will be created. The values will be all the sequences and respective positions
#where matches to that substring occured
if len(totalSeqDict.items()) == 1:
# print("LENGTH == 1")
for k, v in totalSeqDict.items():
# print(k)
# print(v)
for j, w in totalSeqDict.items():
# point of intersection between sequeunces, if there is a match that substrng is used as a key and the two sequences
# as well as where the match occured will be stored in the list contained in the value
subSeqIntersection = list(
totalSeqDict[k].subsequenceDict.keys() & totalSeqDict[j].subsequenceDict.keys())
# print(subSeqIntersection)
# print(totalSeqDict[k].name)
# print(totalSeqDict[j].name)
if len(subSeqIntersection) > 0:
for x in range(len(subSeqIntersection)):
sharedKey = subSeqIntersection[x]
# print(sharedKey)
# x will be key in both dictionaries, can use to access them
outerLoopMatch = [totalSeqDict[k].name, totalSeqDict[k].subsequenceDict[sharedKey], k]
innerLoopMatch = [totalSeqDict[j].name, totalSeqDict[j].subsequenceDict[sharedKey], j]
if subSeqIntersection[x] not in comparisonDict.keys():
comparisonDict[sharedKey] = []
comparisonDict[sharedKey].append(outerLoopMatch)
comparisonDict[sharedKey].append(innerLoopMatch)
elif subSeqIntersection[x] in comparisonDict.keys():
comparisonDict[sharedKey].append(outerLoopMatch)
comparisonDict[sharedKey].append(innerLoopMatch)
# print(comparisonDict)
comparisonOfAllInput.append(comparisonDict)
original_stdout = sys.stdout
with open(outputDirectory + "/" + summaryFileName, 'w') as f:
sys.stdout = f
entryNumber = 1
comparisonDictOutput = {}
#removes duplicate entries from dictionary
for key, value in comparisonDict.items():
NoDupOutput = []
for item in comparisonDict[key]:
if item not in NoDupOutput:
NoDupOutput.append(item)
comparisonDictOutput[key] = NoDupOutput
comparisonDictMotifEdit = {}
#edit: Add filter variable to start
#Uses regexList to filter only potential motifs, without this all entries are kept
for x in regexList:
for k,v in comparisonDict.items():
if re.search(x,k):
comparisonDictMotifEdit[k] = v
else:
continue
#print(comparisonDictOutput)
# print(len(comparisonDictOutput))
#edit: motif Edit
#Saves to original variable name
comparisonDictOutput = comparisonDictMotifEdit
#print(comparisonDictOutput)
# print(len(comparisonDictOutput))
#edit: Change this to reflect all motif occurence at top of page
print("TOTAL SEQUENCES IN FILE: " + str(len(totalSeqDict)))
print("MOTIF AND NUMBER OF SEQUENCES LOCATED IN\n")
#prints output to file using comparisonDict and string manipulations.
#Lists all motifs shared
totalMotifs = 0
for y in sorted(comparisonDictOutput, key=lambda y: len(list(comparisonDictOutput[y])), reverse=True):
print(str(y) + ":" + str(len(list(comparisonDictOutput[y]))))
substringAlignmentList.append(str(y))
totalMotifs += len(list(comparisonDictOutput[y]))
print("\n")
print('TOTAL MOTIFS: ' + str(totalMotifs))
print("\n")
print("#" * 40)
print("#" * 40)
totalSubstringMatches = 0
#section dedicated to each motif
for k in sorted(comparisonDictOutput, key=lambda k: len(comparisonDictOutput[k]), reverse=True):
similarKeys = comparisonDict[k]
# print(len(similarKeys))
numberOfMatches = 0
# print("LOOK:"+ str(similarKeys))
similiarKeysNoDupicates = []
for item in similarKeys:
if item not in similiarKeysNoDupicates:
similiarKeysNoDupicates.append(item)
similarKeys = similiarKeysNoDupicates
# print("LOOK:" + str(similarKeys) + "\n")
print("_" * 40)
print("_" * 40)
print("_" * 40)
print("ENTRY " + "(" + str(entryNumber) + ")")
print("MOTIF: " + str(k))
print("SEQUENCES WITH MOTIF: " + str(len(similarKeys)))
print("_" * 40)
#This is the updated input, similar keys are the entries for the current motif iteration
for x in sorted(similarKeys, key=len, reverse=True):
name = x[0]
#uses a function to sort for simplicity
positionInSequence = sorted(list(x[1]), key = motifPositionSort)
# print(positionInSequence)
#All individuals matches are calculated addition this each iteration
numberOfSubstringMatches = len(positionInSequence)
averageForSegmentOccurances.append(numberOfSubstringMatches)
# print(str(positionInSequence))
pattern = re.compile(r"[0-9]+")
#adds only numbers to list
posAsList = pattern.findall(str(positionInSequence))
seqObjLabel = x[2]
gbFile = totalSeqDict[seqObjLabel].genBankFile
sequenceLength = len(totalSeqDict[seqObjLabel].sequence)
# print(str(gbFile))
currentName = totalSeqDict[seqObjLabel].name
print("_" * 40)
print("SEQUENCE NAME: " + str(name))
print("POSITION(S) OF OCCURRENCE IN ORIGINAL SEQUENCE: " + str((positionInSequence)))
print("TOTAL OCCURRENCES IN SEQUENCE: " + str(numberOfSubstringMatches))
totalSubstringMatches = totalSubstringMatches + numberOfSubstringMatches
print("_" * 40)
print("_" * 40)
# print(str(posAsList) + "\n")
for value in range(len(posAsList)):
if type(gbFile) == '':
# print(currentName + " NO GENBANK FILE PROVIDED")
seqWithoutGenBank.append(currentName)
continue
elif type(gbFile) == str:
continue
#List input is [0,1,2,3,4], this ensures only the start position is used to find sequence
elif value % 2 == 0:
currentPos = posAsList[value]
totalLength = len(gbFile.seq)
adjustedPosition = startPositionofSurvey + int(currentPos)
print(adjustedPosition)
if startPositionofSurvey == 0 and endPositionofSurvey == 0:
print("POSITION OF MOTIF: " + currentPos + "\n")
genBankLocationObj(gbFile, productAsList, searchWindow,
listOfNoGBEntry, str(k),
int(currentPos))
substringPositionsForRange.append(currentPos)
elif startPositionofSurvey > 0:
print("POSITION OF MOTIF: " + str(adjustedPosition) + "\n")
# print(sequenceLength)
print(totalLength)
print(startPositionofSurvey)
print(adjustedPosition)
genBankLocationObj(gbFile, productAsList, searchWindow,
listOfNoGBEntry, str(k),
int(adjustedPosition))
substringPositionsForRange.append(adjustedPosition)
# print(returnTest)
entryNumber += 1
print("END OF ENTRY")
print("#" * 40)
print("#" * 40)
print("\n")
print("TOTAL OCCURRENCES OF ALL MOTIFS: " + str(totalSubstringMatches))
masterTextList.append("TOTAL OCCURRENCES OF ALL MOTIFS: " + str(totalSubstringMatches))
#if entry not found in range of gb it is appended to listOfNoGBEntry
print(str(len(listOfNoGBEntry)) + " POSITIONS WERE NOT FOUND IN RANGE OF GB RECORDS")
#print(comparisonDictOutput)
print("\n")
if totalSubstringMatches > 0:
print(str(100*round(len(listOfNoGBEntry) / totalSubstringMatches,
3)) + "% OF DETECTED MOTIFS WERE FOUND OUT OF RANGE OF GB RECORDS\n")
masterTextList.append(str(100*round(len(listOfNoGBEntry) / totalSubstringMatches,
3)) + "% OF DETECTED MOTIFS WERE FOUND OUT OF RANGE OF GB RECORDS\n")
#edit: Put this higher in notes, change function if needed
substringAlignmentListEdit = set(substringAlignmentList)
# print(substringAlignmentListEdit)
print("TOTAL MOTIF COUNT: " + str(len(substringAlignmentListEdit)) + "\n")
masterTextList.append("TOTAL MOTIF COUNT: " + str(len(substringAlignmentListEdit)) + "\n")
for k, v in totalSeqDict.items():
# print(k)
# print(v)
currentGenBank = totalSeqDict[k].genBankFile
valueForGBCalc = genomePercentNotCoveredInGB(currentGenBank)
if valueForGBCalc is None or valueForGBCalc < 0:
continue
else:
gbGenevSpace.append(valueForGBCalc)
print(gbGenevSpace)
if len(gbGenevSpace) > 0:
print("MEAN: " + str(statistics.fmean(gbGenevSpace)))
print("MEDIAN: " + str(statistics.median(gbGenevSpace)))
print("STDEV: " + str(statistics.pstdev(gbGenevSpace)))
print("MIN: " + str(min(gbGenevSpace)))
print("MAX: " + str(max(gbGenevSpace)))
noRecord = 1 - statistics.fmean(gbGenevSpace)
print("ON AVERAGE " + str(100*round(1 - statistics.fmean(gbGenevSpace),
3)) + "% OF EACH SEQUENCE WAS FOUND OUT OF RANGE OF LISTED GB RECORDS")
masterTextList.append("ON AVERAGE " + str(100*round(1 - statistics.fmean(gbGenevSpace),
3)) + "% OF EACH SEQUENCE WAS FOUND OUT OF RANGE OF LISTED GB RECORDS")
print()
fileOutput = open(outputDirectory + "/" + str(fileName.split('.')[0]) + "_SubstringAlignmentFASTA.txt", 'w')
fileInputAsString = outputDirectory + "/" + str(fileName.split('.')[0]) + "_SubstringAlignmentFASTA.txt"
fileOutputAsString = outputDirectory + "/" + str(fileName.split('.')[0]) + "_SubstringAlignmentALN.txt"
#Aligns all substring using ClustalO for similarities between them
sequencesInFile = 0
if len(substringAlignmentList) > 1:
for item in range(len(substringAlignmentList)):
sequencesInFile += 1
substringEntry = str(substringAlignmentList[item])
fastaLabel = "MOTIF: " + str(substringAlignmentList[item])
fileOutput.write(">" + fastaLabel + "\n" + substringEntry + "\n")
fileOutput.close()
clustalo_exe = pathToClustalEXE
# print(fileInputAsString)
if len(substringAlignmentList) > 1:
clustalomega_cline = ClustalOmegaCommandline(clustalo_exe, infile=fileInputAsString,
outfile=fileOutputAsString, force=True)
clustalomega_cline()
if len(seqWithoutGenBank) > 0:
print("THE FOLLOWING ENTRIES HAVE NO GENBANK FILE PROVIDED")
for entry in seqWithoutGenBank:
print(entry)
print("\n")
if len(substringPositionsForRange) > 0:
rangeLadder(substringPositionsForRange, 60000, 6)
matplotHistogramList[fileName] = substringPositionsForRange
print("\n")
productOutputDict = {}
for entry in productAsList:
# print(str(entry))
if str(entry) in productOutputDict:
productOutputDict[str(entry)] += 1
else:
productOutputDict[str(entry)] = 1
# print(productOutputDict)
for k, v in sorted(productOutputDict.items(), key=lambda item: item[1], reverse=True):
print(str(k) + ": " + str(v))
print('\n')
if len(averageForSegmentOccurances) > 0:
masterTextList.append(["STATS OF OCCURANCE GIVEN EACH SITE", "MEAN: " + str(statistics.fmean(averageForSegmentOccurances)),
"MEDIAN: " + str(statistics.median(averageForSegmentOccurances)), "STDEV: " + str(statistics.pstdev(averageForSegmentOccurances)),
"MIN: " + str(min(averageForSegmentOccurances)),"MAX: " + str(max(averageForSegmentOccurances))])
outputComparison[fileName] = masterTextList
outputComparison[fileName].append(outputComparison['ENTRY COUNT'])
del outputComparison['ENTRY COUNT']
# for item in masterTextList:
#
# print(str(item) + "\n")
# print("STATS OF OCCURANCE GIVEN EACH SITE")
# print("MEAN: " + str(statistics.fmean(averageForSegmentOccurances)))
# print("MEDIAN: " + str(statistics.median(averageForSegmentOccurances)))
# print("STDEV: " + str(statistics.pstdev(averageForSegmentOccurances)))
# print("MIN: " + str(min(averageForSegmentOccurances)))
# print("MAX: " + str(max(averageForSegmentOccurances)))
sys.stdout = original_stdout
f.close()
else:
for k, v in totalSeqDict.items():
# print(k)
# print(v)
for j, w in totalSeqDict.items():
#point of intersection between sequeunces, if there is a match that substrng is used as a key and the two sequences
#as well as where the match occured will be stored in the list contained in the value
subSeqIntersection = list(totalSeqDict[k].subsequenceDict.keys() & totalSeqDict[j].subsequenceDict.keys())
# print(subSeqIntersection)
# print(totalSeqDict[k].name)
# print(totalSeqDict[j].name)
if totalSeqDict[k].subsequenceDict.keys() == totalSeqDict[j].subsequenceDict.keys() and totalSeqDict[k].name == totalSeqDict[j].name:
next
elif len(subSeqIntersection) > 0:
for x in range(len(subSeqIntersection)):
sharedKey = subSeqIntersection[x]
# print(sharedKey)
# x will be key in both dictionaries, can use to access them
#subsequenceDict match is the position of substring matches