forked from simonhmartin/genomics_general
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genomics.py
executable file
·2408 lines (1966 loc) · 104 KB
/
genomics.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
#functions for manipulating sequences and alignments, working with sliding windows, doing population genetics etx.
import numpy as np
from copy import copy, deepcopy
from collections import defaultdict
import sys, string, time, re, math, itertools, random
np.seterr(divide='ignore')
##################################################################################################################
#Bits for intyerpreting and manipulating sequence data
DIPLOTYPES = ('A', 'C', 'G', 'K', 'M', 'N', 'S', 'R', 'T', 'W', 'Y')
PAIRS = ('AA', 'CC', 'GG', 'GT', 'AC', 'NN', 'CG', 'AG', 'TT', 'AT', 'CT')
HOMOTYPES = ('A', 'C', 'G', 'N', 'N', 'N', 'N', 'N', 'T', 'N', 'N')
IUPAC = ('A', 'C', 'G', 'T', 'M', 'R', 'W', 'S', 'Y', 'K', 'V', 'H', 'D', 'B', 'N')
ALLTYPES = ('A', 'C', 'G', 'T', 'AC', 'AG', 'AT', 'CG', 'CT', 'GT', 'ACG', 'ACT', 'AGT', 'CGT', 'ACGT')
diploHaploDict = dict(zip(DIPLOTYPES,PAIRS))
haploDiploDict = dict(zip(PAIRS,DIPLOTYPES))
diploHomoDict = dict(zip(DIPLOTYPES,HOMOTYPES))
basesIupacDict = dict(zip(ALLTYPES,IUPAC))
iupacBasesDict = dict(zip(IUPAC,ALLTYPES))
def haplo(diplo): return diploHaploDict[diplo]
def diplo(pair): return haploDiploDict[pair]
def homo(diplo): return diploHomoDict[diplo]
seqNumDict = {"A":0,"C":1,"G":2,"T":3,"N":-999}
numSeqDict = {0:"A",1:"C",2:"G",3:"T",-999:"N"}
#translation tables - method epends on version
if sys.version_info>=(3,0):
#translation for conversion of missing bases to gaps
missingtrans = str.maketrans("Nn", "--")
#translation table for bases
complementTrans = str.maketrans("ACGTKMRYVHBDN", "TGCAMKYRBDVHN")
else:
#translation for conversion of missing bases to gaps
missingtrans = string.maketrans("Nn", "--")
#translation table for bases
complementTrans = string.maketrans("ACGTKMRYVHBDN", "TGCAMKYRBDVHN")
complementDict = dict(zip(list("ACGTKMRYVHBDN"), list("TGCAMKYRBDVHN")))
def complement(seq):
if type(seq) == str: return seq.translate(complementTrans)
else: return [complementDict[a] for a in seq]
def revComplement(seq):
if type(seq) == str: return seq.translate(complementTrans)[::-1]
else: return [complementDict[a] for a in seq[::-1]]
def allPossibleSeqs(seq, ignoreNs = True):
if ignoreNs: basesList = [iupacBasesDict[s] if s != "N" else "N" for s in seq]
else: basesList = [iupacBasesDict[s] for s in seq]
seqs = [[]]
for bases in basesList:
for x in range(len(seqs)):
seqs[x].append(bases[0])
for b in bases[1:]:
newSeq = seqs[x][:]
newSeq[-1] = b
seqs.append(newSeq)
return ["".join(s) for s in seqs]
def seqArrayToNumArray(seqArray):
numArray = np.empty(shape = seqArray.shape, dtype=int)
for x in ["A","C","G","T","N"]: numArray[seqArray==x] = seqNumDict[x]
return numArray
def numArrayToSeqArray(numArray):
seqArray = np.empty(shape = numArray.shape, dtype=str)
for x in [0,1,2,3,-999]: seqArray[numArray==x] = numSeqDict[x]
return seqArray
def alleles(bases):
s = set(bases)
return [i for i in "ACGT" if i in s]
def nanmean_min(a, min=0):
if 1 - (1.* np.isnan(a).sum()/a.size) < min: return np.NaN
return np.nanmean(a)
################################################################################
#working with coding sequences
gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}
def translate(sequence, missing='X'):
"""Return the translated protein from 'sequence' assuming +1 reading frame"""
return ''.join([gencode.get(sequence[3*i:3*i+3],missing) for i in range(len(sequence)//3)])
def possibleCodons(pos1Alleles,pos2Alleles,pos3Alleles):
return ["".join(x) for x in itertools.product(pos1Alleles,pos2Alleles,pos3Alleles)]
def possibleAAs(pos1Alleles,pos2Alleles,pos3Alleles):
AAs = set([translate(codon) for codon in possibleCodons(pos1Alleles,pos2Alleles,pos3Alleles)])
try: AAs.remove("X")
except: pass
return sorted(AAs)
#function that takes three sets of allels, corresponding to the alleles at the three codon positions
#and outputs whether each one is synonymous or nonsynonymous
#rejects cases where two sites are variable
def synNon(pos1Alleles,pos2Alleles,pos3Alleles):
output = ["NA","NA","NA"]
#first check that each position has at least one allele and at most one position is variable
nAlleles = [len(alleles) for alleles in (pos1Alleles,pos2Alleles,pos3Alleles,)]
if not sorted(nAlleles) == [1,1,2]:
return output
else:
focal = nAlleles.index(2)
l = len(possibleAAs(pos1Alleles,pos2Alleles,pos3Alleles))
if l == 1: output[focal] = "syn"
elif l > 1: output[focal] = "non"
return output
#dictionary to tell you how degenerate a site is based on how many unique amino acids are formed when that site is mutated
#eg if four distinct amino acids can be formed, the site is 0-fold degenerate
degenDict = {4:0, 3:2, 2:2, 1:4, 0:"NA"}
def degeneracy(pos1Alleles,pos2Alleles,pos3Alleles):
#if its invariant, then they all get a degeneracy
if len(pos1Alleles) == len(pos2Alleles) == len(pos3Alleles) == 1:
output = [degenDict[len(possibleAAs("ACGT",pos2Alleles,pos3Alleles))],
degenDict[len(possibleAAs(pos1Alleles,"ACGT",pos3Alleles))],
degenDict[len(possibleAAs(pos1Alleles,pos2Alleles,"ACGT"))]]
elif len(pos1Alleles) == 2 and len(pos2Alleles) == len(pos3Alleles) == 1:
output = [degenDict[len(possibleAAs("ACGT",pos2Alleles,pos3Alleles))], "NA", "NA"]
elif len(pos2Alleles) == 2 and len(pos1Alleles) == len(pos3Alleles) == 1:
output = ["NA", degenDict[len(possibleAAs(pos1Alleles,"ACGT",pos3Alleles))], "NA"]
elif len(pos3Alleles) == 2 and len(pos1Alleles) == len(pos2Alleles) == 1:
output = ["NA","NA", degenDict[len(possibleAAs(pos1Alleles,pos2Alleles,"ACGT"))]]
else:
output = ["NA","NA","NA"]
return output
#function takes gff file and retrieves coordinates of all CDSs for all mRNAs
def parseGenes(lines, fmt="gff3", targets=None):
#little function to parse the info line
if fmt == "gtf":
makeInfoDict = lambda infoString: dict([x.strip().split() for x in infoString.strip(";").split(";")])
ID_key = "transcript_id"
parent_key = "transcript_id"
else:
makeInfoDict = lambda infoString: dict([x.strip().split("=") for x in infoString.strip(";").split(";")])
ID_key = "ID"
parent_key = "Parent"
output = defaultdict(dict)
for line in lines:
if len(line) > 1 and line[0] != "#":
gffObjects = line.strip().split("\t")
#store all mRNA and CDS data for the particular scaffold
scaffold = gffObjects[0]
if gffObjects[2] == "mRNA" or gffObjects[2] == "mrna" or gffObjects[2] == "MRNA" or gffObjects[2] == "transcript":
#we've found a new mRNA
try: mRNA = makeInfoDict(gffObjects[-1])[ID_key]
except:
raise ValueError("Problem parsing mRNA information: " + gffObjects[-1])
if not targets or mRNA in targets:
output[scaffold][mRNA] = {'start':int(gffObjects[3]), 'end':int(gffObjects[4]), 'strand':gffObjects[6], 'exons':0, 'cdsStarts':[], 'cdsEnds':[]}
elif gffObjects[2] == "CDS" or gffObjects[2] == "cds":
#we're reading CDSs for an existing mRNA
mRNA = makeInfoDict(gffObjects[-1])[parent_key]
if not targets or mRNA in targets:
output[scaffold][mRNA]['exons'] += 1
output[scaffold][mRNA]['cdsStarts'].append(int(gffObjects[3]))
output[scaffold][mRNA]['cdsEnds'].append(int(gffObjects[4]))
return(output)
#function to extract a CDS sequence from a genomic sequence given the exon starts, ands and strand
def CDSpositions(exonStarts, exonEnds, strand, trim=False):
nExons = len(exonStarts)
assert nExons == len(exonEnds)
#index them by start position
idx = np.argsort(exonEnds)[::-1] if strand == "-" else np.argsort(exonStarts)
#for each exon, extract a list of scaffold positions
codingPositions = [list(range(exonStarts[i], exonEnds[i] + 1)) for i in idx]
#reverse the positions if necessary
if strand == "-":
for _codingPositions_ in codingPositions: _codingPositions_.reverse()
#unlist them to make one long set of positions
codingPositions = [i for _codingPositions_ in codingPositions for i in _codingPositions_]
if trim:
overhang = len(codingPositions) % 3
if overhang != 0: codingPositions = codingPositions[:-overhang]
return codingPositions
#function to extract a CDS sequence from a genomic sequence given the exon starts, ands and strand
def CDSsequence(exonStarts, exonEnds, strand, seqDict=None, seq=None, seqPos=None, trim=True):
if seqDict is None:
#if dictionary of bases for each position is not provided, make it
assert len(seq) == len(seqPos)
seqDict = defaultdict(lambda: "N", zip(seqPos, seq))
#for each exon, extract a list of scaffold positions
codingPositions = CDSpositions(exonStarts, exonEnds, strand, trim=trim)
cdsSeq = "".join([seqDict[p] for p in codingPositions])
if strand=="-": cdsSeq = cdsSeq.translate(complementTrans)
return cdsSeq
def countStops(cds, includeTerminal=False):
if includeTerminal:
triplets = [cds[i:i+3] for i in range(len(cds))[::3]]
else:
triplets = [cds[i:i+3] for i in range(len(cds)-3)[::3]]
stopCount = len([t for t in triplets if t in set(["TAA","TAG","TGA"])])
return stopCount
################################################################################
########### some general list manipulation code
#subset list into smaller lists
def subset(things,subLen,asLists=False):
starts = range(0,len(things),subLen)
ends = [start+subLen for start in starts]
if asLists: return [list(things[starts[i]:ends[i]]) for i in range(len(starts))]
return [things[starts[i]:ends[i]] for i in range(len(starts))]
#similar to above, but can have variable sizes of smaller lists, or can specify the number of chunks
def chunkList(l, nChunks = None, chunkSize = None, return_indices=False):
N = len(l)
assert not nChunks is chunkSize is None
if nChunks is not None:
assert N % nChunks == 0, "list must be divizable by number of chunks"
chunkSize = [N/nChunks]*nChunks
elif isinstance(chunkSize, int):
assert N % chunkSize == 0, "list must be divizable by chunk size"
chunkSize = [chunkSize]*(N/chunkSize)
elif len(chunkSize) == 1:
assert N % chunkSize[0] == 0, "list must be divizable by chunk size"
chunkSize*=(N/chunkSize[0])
else: assert N == sum(chunkSize), "Chunk sizes must sum to list length"
indices = []
r = range(N)
i = 0
for c in chunkSize:
indices.append(range(i,i+c))
i = i+c
if return_indices: return ([[l[x] for x in ind] for ind in indices], indices,)
else: return [[l[x] for x in ind] for ind in indices]
def invertDictOfLists(d):
new = {}
for key, lst in d.items():
for i in lst:
try: new[i].append(key)
except: new[i] = [key]
new
return new
def makeList(thing):
if isinstance(thing, str): return [thing]
else:
try: iter(thing)
except TypeError: return [thing]
else: return list(thing)
def uniqueIndices(things, preserveOrder = False, asDict=False):
T,X,I = np.unique(things, return_index=True, return_inverse=True)
indices = np.array([np.where(I == i)[0] for i in range(len(T))])
order = np.argsort(X) if preserveOrder else np.arange(len(X))
return dict(zip(T[order], indices[order])) if asDict else [T[order], indices[order]]
#################################################################################################
class Genotype:
__slots__ = ['geno', 'genoFormat', 'ploidy', 'forcePloidy', 'alleles', 'phase', 'numAlleles']
def __init__(self, geno, genoFormat, ploidy = None, forcePloidy=False, partialToMissing=False):
if genoFormat == "phased":
self.alleles = list(geno)[::2]
self.phase = geno[1] if len(geno) > 1 and len(geno)%2 == 1 else "/"
elif genoFormat == "alleles" or genoFormat == "pairs" or genoFormat == "haplo":
self.alleles = list(geno)
self.phase = "/"
elif genoFormat == "diplo":
self.alleles = list(haplo(geno))
self.phase = "/"
else:
raise ValueError("Valid genotype formats are 'phased' (eg A/T), 'alleles' (eg AT), 'pairs' (eg AT), 'haplo' (eg A) or 'diplo' (eg W)")
if ploidy is not None:
ploidyError = ploidy - len(self.alleles)
if ploidyError != 0:
if forcePloidy:
if ploidyError > 0: self.alleles += ["N"]*ploidyError
elif ploidyError < 0:
if len(set(self.alleles)) == 1: self.alleles = [self.alleles[0]]*ploidy
else: self.alleles = ["N"]*ploidy
else: raise ValueError("Ploidy doesn't match number of alleles")
else: ploidy = len(self.alleles)
if partialToMissing and "N" in self.alleles: self.alleles = ["N"]*ploidy
self.ploidy = ploidy
#now make the alleles immutable
self.alleles = tuple(self.alleles)
try: self.numAlleles = np.array([seqNumDict[a] for a in self.alleles])
except: self.numAlleles = np.array([-999]*self.ploidy)
def isHaploid(self): return self.ploidy == 1
def asPhased(self): return self.phase.join(self.alleles)
def asDiplo(self):
assert self.ploidy == 2, "Can only convert diploid genotypes to diplotypes."
return diplo("".join(sorted(self.alleles)))
def asCoded(self, codeDict, missing = None): #code alleles e.g. 0 and 1, with phase (0/1)
if missing is None: missing = "."
try: return self.phase.join([codeDict[a] for a in self.alleles])
except: return self.phase.join([missing]*self.ploidy)
def asCount(self, countAllele, missing = None): # code whole genotype as single value
if missing is None: missing = -1
try: return np.bincount(self.numAlleles, minlength = 4)[seqNumDict[countAllele]]
except: return missing
def asBaseCounts(self):
return np.bincount(self.numAlleles[self.numAlleles >= 0], minlength = 4)
def asRandomAllele(self):
return self.alleles[0] if len(self.alleles)==1 else random.sample(self.alleles, 1)[0]
def isMissing(self): return np.any(self.numAlleles==-999)
#convert one ambiguous sequence into two haploid pseudoPhased sequences
##NOTE this is depricated and should be replaced by splitSeq()
def pseudoPhase(sequence, genoFormat = "diplo"):
if genoFormat == "pairs": return [[g[0] for g in sequence], [g[1] for g in sequence]]
elif genoFormat == "phased": return [[g[0] for g in sequence], [g[2] for g in sequence]]
else:
pairs = [haplo(g) for g in sequence]
return [[p[0] for p in pairs], [p[1] for p in pairs]]
def splitSeq(sequence, genoFormat = "phased"):
assert genoFormat in ("haplo", "diplo", "pairs", "alleles", "phased",)
if genoFormat == "diplo": sequence = [haplo(d) for d in sequence]
split = list(zip(*sequence))
#remove phase splitters
if genoFormat == "phased": split = split[::2]
return split
#convert a sequence of phased genotypes into two separate sequences
##NOTE this is depricated and should be replaced by splitSeq()
def parsePhase(genotypes):
first = [geno[0] for geno in genotypes]
second = [geno[2] for geno in genotypes]
return [first,second]
#Force diploid sequence to be haploid
def forceHomo(sequence):
return [homo(s) for s in sequence]
#make haploid sequences N-ploid
def haploToPhased(seqs, seqNames=None, ploidy=2, randomPhase=False):
_ploidy_ = makeList(ploidy)
Nseqs = len(seqs)
#if ploidy is 1 for all sequences, just return them
if set(_ploidy_) == {1}:
#if seqNames provided, return a tuple
if seqNames != None:
assert len(seqNames) == Nseqs, "incorrect number of sequence names"
return (seqs, seqNames,)
#otherwise just return the seqs
return seqs
else:
if len(_ploidy_) == 1:
assert Nseqs % _ploidy_[0] == 0, "Sequence number must be divizable by ploidy"
_ploidy_ = _ploidy_*(Nseqs/_ploidy_[0])
else:
assert Nseqs == sum(_ploidy_), "Ploidys must sum to number of sequences"
indices = chunkList(range(Nseqs), chunkSize=_ploidy_, return_indices=True)[1]
zipSeqs = [zip(*[seqs[x] for x in ind]) for ind in indices]
#randomize phase if necessary
if randomPhase:
for i in range(len(indices)):
if _ploidy_[i] > 1:
for j in range(len(zipSeqs[i])):
zipSeqs[i][j] = random.sample(zipSeqs[i][j], _ploidy_[i])
seqs = [["|".join(x) for x in zipSeq] for zipSeq in zipSeqs]
#if seqNames provided, return a tuple
if seqNames != None:
assert len(seqNames) == Nseqs, "incorrect number of sequence names"
seqNames = ["_".join([seqNames[x] for x in ind]) for ind in indices]
return (seqs, seqNames,)
#otherwise just return the seqs
return seqs
def makeHaploidNames(names,ploidy=2):
ploidy=makeList(ploidy)
if len(ploidy) == 1: ploidy = ploidy*len(names)
if np.all(np.array(ploidy) == 1) : return(names)
ploidyDict = dict(zip(names, ploidy))
return [n + "_" + letter for n in names for letter in string.ascii_uppercase[:ploidyDict[n]]]
def makePhasedNames(names,ploidy=2):
nameGroups = chunkList(names, chunkSize=ploidy)
return ["_".join(group) for group in nameGroups]
################################################################################################################
#modules for working with individual sites
class GenomeSite:
def __init__(self, genoDict = None, genotypes = None, sampleNames = None, contig = None, position = 0, popDict = {},
genoFormat = None, ploidyDict = None, forcePloidy=False, partialToMissing=False, precompGTs=None, addToPrecomp=True):
#genotypes is a list of genotypes as strings, lists or tuples in any format. e.g. ['AT', 'W', 'T|A', ('A','T)]
#or use genoDict, which is a dictionary with sample names as the keys. Again, all genotype formats accepted
if not genoDict:
assert genotypes is not None, "Either a genotypes dictionary or list must be specified."
if not sampleNames: sampleNames = [str(x) for x in range(len(genotypes))]
assert len(genotypes) == len(sampleNames), "Genotypes and sample names must be of equal length."
self.sampleNames = sampleNames
genoDict = dict(zip(sampleNames, genotypes))
else:
self.sampleNames = sampleNames if sampleNames is not None else sorted(genoDict.keys())
self.contig = contig
self.position = position
self.pops = popDict
self.ploidy = ploidyDict if ploidyDict else dict(zip(self.sampleNames, [None]*len(self.sampleNames)))
self.genotypes = {}
for sample in self.sampleNames:
#now, for each sample, if using precomputed genotypes, we check if the geno has already been computed
if precompGTs and genoDict[sample] in precompGTs[sample]:
self.genotypes[sample] = precompGTs[sample][genoDict[sample]]
#if not, compute gentype normally
else:
self.genotypes[sample] = Genotype(genoDict[sample], genoFormat=genoFormat,
ploidy = self.ploidy[sample],forcePloidy=forcePloidy, partialToMissing=partialToMissing)
#add to precomputed
if precompGTs and addToPrecomp:
precompGTs[sample][genoDict[sample]] = self.genotypes[sample]
def asList(self, samples = None, pop = None, mode = "phased", alleles = None,
codeDict=None, missing=None, alleleOrder=None, countAllele=None):
if pop: samples = self.pops[pop]
if not samples: samples = self.sampleNames
if mode == "bases":
#if we want the bases returned in order of their overall frequency
if alleleOrder == "freq":
siteAlleles = self.alleles(samples=samples,byFreq = True) + ["N"]
return [a for sample in samples for a in sorted(self.genotypes[sample].alleles, key=lambda x: siteAlleles.index(x))]
#otherwise just return the bases as they appear
else:
return [a for alleles in [self.genotypes[sample].alleles for sample in samples] for a in alleles]
elif mode == "alleles": #just bases with no phase
#if we want the bases returned in order of their overall frequency
if alleleOrder == "freq":
siteAlleles = self.alleles(samples=samples,byFreq = True) + ["N"]
return ["".join(sorted(self.genotypes[sample].alleles,
key=lambda x: siteAlleles.index(x))) for sample in samples]
#otherwise just return the bases as they appear
else:
return [self.genotypes[sample].alleles for sample in samples]
if mode == "numeric":
return np.concatenate([self.genotypes[sample].numAlleles for sample in samples])
elif mode == "numAlleles": #numpy array of numeric alleles
return [self.genotypes[sample].numAlleles for sample in samples]
elif mode == "phased": # like 'A|T'
return [self.genotypes[sample].asPhased() for sample in samples]
elif mode == "diplo": #ACGT and KMRSYW for hets
return [self.genotypes[sample].asDiplo() for sample in samples]
elif mode == "randomAllele": #ACGT and KMRSYW for hets
return [self.genotypes[sample].asRandomAllele() for sample in samples]
elif mode == "coded": # vcf format '0/1' - optionally alleles can be provided (REF first)
if alleles is None: alleles = self.alleles(byFreq = True)
if codeDict is None: codeDict = dict(zip(alleles, [str(x) for x in range(len(alleles))]))
return [self.genotypes[sample].asCoded(codeDict, missing) for sample in samples]
elif mode == "count":
if countAllele is None:
if alleles is None: alleles = self.alleles(byFreq = True)
countAllele = alleles[-1]
return [self.genotypes[sample].asCount(countAllele,missing) for sample in samples]
else:
raise ValueError("mode must be 'bases', 'alleles', 'numeric', 'numAlleles', 'phased', 'diplo', 'randomAllele', 'coded', or 'count'")
def baseFreqs(self, samples = None, pop=None, asCounts=False):
if pop: samples = self.pops[pop]
if not samples: samples = self.sampleNames
numBases = np.concatenate([self.genotypes[sample].numAlleles for sample in samples])
return binBaseFreqs(numBases[numBases >= 0], asCounts = asCounts)
def alleles(self, samples = None, pop=None, byFreq = False, numeric=False):
if pop: samples = self.pops[pop]
if not samples: samples = self.sampleNames
counts = self.baseFreqs(samples=samples,asCounts = True)
idx = counts>0
alleles = np.array(["A","C","G","T"])[idx] if not numeric else idx
counts = counts[idx]
if byFreq: return list(alleles[np.argsort(counts)[::-1]])
else: return sorted(list(alleles))
def nsamp(self): return len(self.sampleNames)
def changeGeno(self, sample, newGeno, genoFormat="phased"):
self.genotypes[sample] = Genotype(newGeno, genoFormat=genoFormat,
ploidy = self.ploidy[sample],forcePloidy=forcePloidy, partialToMissing=partialToMissing)
def hets(self, samples=None):
if not samples: samples = self.sampleNames
sampAlleles = self.asList(mode = "alleles")
sampUniqueAlleles = [set(alleles) for alleles in sampAlleles]
nSampAlleles = np.array([len(uniqueAlleles) for uniqueAlleles in sampUniqueAlleles])
return 1.*(nSampAlleles > 1).sum()/self.nonMissing()
def nonMissing(self, prop=False):
present = sum([~self.genotypes[sample].isMissing() for sample in self.sampleNames])
if prop: return 1.*present/(len(sampleNames))
else: return present
def baseFreqs(bases, asCounts = False, asDict = False):
counts = np.array([bases.count(i) for i in ["A","C","G","T"]])
if asCounts: freqs = counts
else: freqs = counts/sum(counts * 1.)
if asDict: return dict(zip(["A","C","G","T"], freqs))
else: return freqs
def majorAllele(bases):
baseCounts = baseFreqs(bases, asCounts = True, asDict = True)
m = max(baseCounts.values())
return [b for b in ["A","C","G","T"] if baseCounts[b] == m]
def binBaseFreqs(numArr, asCounts = False):
n = len(numArr)
if n == 0:
if asCounts: return np.zeros(4, dtype=int)
else: return np.array([np.NaN]*4)
else:
if asCounts: return np.bincount(numArr, minlength=4)
else: return 1.* np.bincount(numArr, minlength=4) / n
#quickest method I could find to determine if a numeric array is variable or not
def numVar(numArray):
return max(np.bincount(numArray)) != len(numArray)
#timeit.timeit("numVar(numArray)", setup="from __main__ import numVar, numArray", number = 1000000)
#site-wise pi for multi-allelic sites (input is counts of four bases)
def baseCountPi(baseCounts):
N = sum(baseCounts)
return (baseCounts[0]*baseCounts[1] +
baseCounts[0]*baseCounts[2] +
baseCounts[0]*baseCounts[3] +
baseCounts[1]*baseCounts[2] +
baseCounts[1]*baseCounts[3] +
baseCounts[2]*baseCounts[3]) / (.5*N*(N-1))
def TajimaD(n,S,theta_pi):
# https://ocw.mit.edu/courses/health-sciences-and-technology/hst-508-quantitative-genomics-fall-2005/study-materials/tajimad1.pdf
a= sum( 1./i for i in range(1, n))
theta_w = 1.*S/a # M
a2 = sum( 1./(i**2) for i in range(1, n))
b1 = (n + 1.) / (3*(n-1))
b2 = (2. * (n**2 + n + 3)) / (9*n*(n-1))
c1 = b1 - (1./a)
c2 = b2 - ((n+2)/(a*n)) + a2/(a**2)
e1 = c1/a
e2 = c2/(a**2 + a2)
d = theta_pi - theta_w
D = d / np.sqrt(e1*S + e2*S*(S-1))
return D
def derivedAllele(inBases=None, outBases=None,
inBaseCounts=None, outBaseCounts=None,
inAlleles=[], outAlleles=[],
maxOneDerivedAllele=True, numeric=False):
if inBases is not None: inAlleles = np.unique(inBases)
elif inBaseCounts is not None:
if not numeric: inAlleles=["ACGT"[i] for i in range(4) if inBaseCounts[i] > 0]
else: inAlleles= np.where(np.array(inBaseCounts) > 0)[0]
if outBases is not None: outAlleles = np.unique(outBases)
elif outBaseCounts is not None:
if not numeric: outAlleles=["ACGT"[i] for i in range(4) if outBaseCounts[i] > 0]
outAlleles= np.where(np.array(outBaseCounts) > 0)[0]
if not isinstance(inAlleles, np.ndarray): inAlleles = np.array(inAlleles)
if not isinstance(outAlleles, np.ndarray): outAlleles = np.array(outAlleles)
if maxOneDerivedAllele and len(outAlleles) == 1 and len(inAlleles) == 2 and np.any(outAlleles[0] == inAlleles):
return inAlleles[inAlleles != outAlleles[0]][0]
elif not maxOneDerivedAllele and len(outAlleles) == 1 and len(inAlleles) >= 2 and np.any(outAlleles[0] == inAlleles):
return inAlleles[inAlleles != outAlleles[0]]
elif numeric or isinstance(inAlleles[0], np.int) or isinstance(inAlleles[0], np.float): return np.nan
else: return "N"
def minorAllele(bases):
alleles = np.unique(bases)
if len(alleles) == 2:
alleles, counts = np.unique(bases, return_counts = True)
return np.random.choice(alleles[counts==min(counts)])
else: return np.nan
def consensus(bases):
x = "".join(np.unique([b for b in bases if b in "ACGT"]))
if x == "": x = "ACGT"
return(basesIupacDict[x])
# method of Wigginton, Cutler and Abecasis, 2005 Am Gen Human Genet. (Adapted from their supplied R code)
def HWEtest(obsHet, obsHom1, obsHom2, side = "both"):
if obsHom1 < 0 or obsHom2 < 0 or obsHet < 0:
return -1.0
# total genotypes
N = obsHet + obsHom1 + obsHom2
#rare and common number of homozygotes
obsHomRare,obsHomCom = sorted([obsHom1,obsHom2])
#rare allele count
rare = obsHomRare * 2 + obsHet
#initialize probability array
probs = [0] * (rare + 1)
# Find midpoint of the distribution
mid = math.floor(rare * ( 2 * N - rare) / (2 * N))
if mid % 2 != rare % 2: mid = mid + 1
probs[int(mid)] = 1.0
mySum = 1.0
# Calculate probablities from midpoint down
currHet = int(mid)
currHomRare = int(rare - mid) / 2
currHomCom = N - currHet - currHomRare
while currHet >= 2:
probs[currHet - 2] = probs[currHet] * currHet * (currHet - 1.0) / (4.0 * (currHomRare + 1.0) * (currHomCom + 1.0))
mySum += probs[currHet - 2]
# 2 fewer heterozygotes -> add 1 rare homozygote, 1 common homozygote
currHet = currHet - 2
currHomRare = currHomRare + 1
currHomCom = currHomCom + 1
# Calculate probabilities from midpoint up
currHet = int(mid)
currHomRare = int(rare - mid) / 2
currHomCom = N - currHet - currHomRare
while currHet <= rare - 2:
probs[currHet + 2] = probs[currHet] * 4.0 * currHomRare * currHomCom / ((currHet + 2.0) * (currHet + 1.0))
mySum += probs[currHet + 2]
# add 2 heterozygotes -> subtract 1 rare homozygtote, 1 common homozygote
currHet = currHet + 2
currHomRare = currHomRare - 1
currHomCom = currHomCom - 1
if side == "top": p = min(1.0, sum(probs[obsHet:(rare+1)]) / mySum)
elif side == "bottom": p = min(1.0, sum(probs[0:(obsHet+1)]) / mySum)
else:
target = probs[obsHet]
p = min(1.0, sum([prob for prob in probs if prob <= target])/ mySum)
return p
def inHWE(diplos, P_value, side = "both", verbose = False):
diplos = [d for d in diplos if d != "N"]
if verbose: sys.stderr.write(diplos)
if len(diplos) == 0: return True
alleles = unique([haplo(d) for d in diplos])
if len(alleles) == 1: return True
if len(alleles) > 2: return False
Hom1Count = int(diplos.count(alleles[0]))
Hom2Count = int(diplos.count(alleles[1]))
HetCount = len(diplos) - (Hom1Count + Hom2Count)
if verbose: sys.stderr.write(str(Hom1Count) + " " + str(Hom2Count) + " " + str(HetCount))
p = HWEtest(HetCount,Hom1Count,Hom2Count)
if verbose: sys.stderr.write("P: " + str(p))
if p <= P_value: return False
else: return True
def siteTest(site,samples=None,minCalls=1,minPopCalls=None,minAlleles=0,maxAlleles=float("inf"),
minPopAlleles=None,maxPopAlleles=None,minVarCount=None,maxHet=None,minFreq=None,maxFreq=None,
HWE_P=None,HWE_side="both",fixed=False,nearlyFixedDiff=None):
if not samples: samples = site.sampleNames
#check sufficient number of non-N calls
if site.nonMissing() < minCalls: return False
numBases = site.asList(mode = "numeric", samples=samples)
numBases = numBases[numBases >= 0]
#check min and max alleles
nAlleles = len(set(site.alleles(samples)))
if not minAlleles <= nAlleles <= maxAlleles: return False
#check variant filters
if nAlleles > 1:
# minor allele count
if minVarCount and sorted(binBaseFreqs(numBases, asCounts = True))[-2] < minVarCount: return False
#check maximum heterozygots?
if maxHet != None and site.hets(samples) > maxHet: return False
#if there is a frequency cutoff
if minFreq and not minFreq <= sorted(binBaseFreqs(numBases))[-2]: return False
if maxFreq and not sorted(binBaseFreqs(numBases))[-2] <= maxFreq: return False
#if checking HWE
if HWE_P:
#if there are defined pops, check all of them
if site.pops is not {}:
for popName in site.pops.keys():
if not inHWE(site.asList(pop = popName,mode="diplo"), HWE_P, side = HWE_side): return False
#otherwise just check all samples
elif not inHWE(site.asList(mode="diplo"), HWE_P, side = HWE_side): return False
#if there are population-specific filters
popNames = site.pops.keys()
if len(popNames) >= 1:
for popName in popNames:
if minPopCalls:
popCalls = sum([site.genotypes[sample].isMissing()==False for sample in site.pops[popName]])
if popCalls < minPopCalls[popName]: return False
#if we want fixed differences only and there are two or more pops specified
if fixed or minPopAlleles or maxPopAlleles:
#if fixed all pops must have only one allele, but taken together must have more than one
allelesByPop = [site.alleles(pop=popName) for popName in popNames]
if fixed and not (set([len(alleles) for alleles in allelesByPop]) == {1} and
len(set([a for popAlleles in allelesByPop for a in popAlleles])) > 1): return False
#otherwise
if minPopAlleles or maxPopAlleles:
if minPopAlleles == None: minPopAlleles = dict(zip(popNames, [0]*len(popNames)))
if maxPopAlleles == None: maxPopAlleles = dict(zip(popNames, [4]*len(popNames)))
for x in range(len(popNames)):
if not minPopAlleles[popNames[x]] <= len(allelesByPop[x]) <= maxPopAlleles[popNames[x]]: return False
#if we want nearly fixed differences, we need to get pop freqs and find any freq difference big enough
elif nearlyFixedDiff is not None:
popFreqs = [site.baseFreqs(pop=popName) for popName in popNames]
freqDiffs = [popFreqs[c[0]] - popFreqs[c[1]] for c in list(itertools.combinations(range(len(popNames)), 2))]
if not np.any(np.absolute(np.concatenate(freqDiffs)) >= nearlyFixedDiff): return False
#if we get here we've passed all filters
return True
######################################################################################################################
#modules for working with and analysing alignments
class Alignment:
__slots__ = ['sequences', 'names', 'groups', 'groupIndDict', 'indGroupDict',
'length', 'numArray', 'positions', 'sampleNames', 'nanMask', 'N', 'l',
'array','numArray', '_distMat_', '_pairNonNan_']
def __init__(self, sequences = None, names=None, groups = None, groupIndDict=None, length = None, numArray = None, positions=None, sampleNames=None):
assert not sequences is numArray is length is None, "Specify sequences or length of empty sequence object."
if sequences is not None:
assert isinstance(sequences, (list,tuple,np.ndarray)), "Sequences must be a list, tuple or numpy array."
if isinstance(sequences, np.ndarray): seqArray = sequences
else: seqArray = np.array([list(seq) for seq in sequences])
if numArray is not None: assert numArray.shape == sequences.shape, "Numeric array is different shape from sequence array."
else: numArray = seqArrayToNumArray(seqArray)
elif numArray is not None:
assert isinstance(numArray, np.ndarray), "Numeric sequences must be a numpy array."
seqArray = numArrayToSeqArray(numArray)
else:
seqArray = np.empty(shape=(0,length), dtype=str)
numArray = np.empty((0,length), dtype=int)
self.array = seqArray
self.numArray = numArray
self.nanMask = self.numArray >= 0
self.N,self.l = self.array.shape
if positions is not None:
assert len(positions)==self.l, "Positions must match sequence length."
self.positions = positions
else: self.positions = range(1,self.l+1)
if names is None: names = np.arange(self.N)
else: assert len(names) == self.N, "Incorrect number of names."
self.names = np.array(names)
if sampleNames is None: sampleNames = self.names
else: assert len(sampleNames) == self.N, "Incorrect number of sample names."
self.sampleNames = np.array(sampleNames)
if groups is not None:
assert len(groups) == self.N, "Incorrect number of groups."
self.groups = np.array(groups)
self.indGroupDict = dict(zip(self.names, [makeList(g) for g in self.groups]))
self.groupIndDict = invertDictOfLists(self.indGroupDict)
elif groupIndDict is not None:
self.groupIndDict = groupIndDict
self.indGroupDict = invertDictOfLists(self.groupIndDict)
for name in self.names:
if name not in self.indGroupDict: self.indGroupDict[name] = []
self.groups = np.array([self.indGroupDict[n] for n in self.names])
else:
self.groups = np.array([None]*self.N) #groups is just a list of names, giving the group name for each sample
self.indGroupDict = dict(zip(self.names, [makeList(g) for g in self.groups]))
self.groupIndDict = {}
#we make a None object for distance matrix, but if any dist matrix type function is run, this will be filled
self._distMat_ = None
self._pairNonNan_ = None
def subset(self, indices = None, names = None, groups = None):
if indices is None: indices = []
if names is None: names = []
if groups is None: groups = []
names = names + [j for i in [self.groupIndDict[g] for g in groups] for j in i]
indices += [np.where(self.names == n)[0][0] for n in names]
indices = np.unique(indices)
return Alignment(sequences = self.array[indices], numArray=self.numArray[indices],
names=self.names[indices], groups=self.groups[indices], sampleNames=self.sampleNames[indices])
def slice(self, indices = None, startPos = None, endPos = None):
if indices is None:
if startPos is None: startPos = min(self.positions)
if endPos is None: endPos = max(self.positions)
indices = [x for x in range(self.l) if startPos<=self.positions[x]<=endPos]
return Alignment(sequences = self.array[:,indices], names = self.names, groups=self.groups,
numArray=self.numArray[:,indices], positions=[self.positions[i] for i in indices])
def column(self,x): return self.array[:,x]
def numColumn(self,x): return self.numArray[:,x]
def pairDist(self, i, j):
nanMask = self.nanMask[i,:] & self.nanMask[j,:]
return numHamming(self.numArray[i,:][nanMask], self.numArray[j,:][nanMask])
def distMatrix(self, minSites=None):
distMat = np.zeros((self.N,self.N))
for i in range(self.N - 1):
for j in range(i + 1, self.N):
distMat[i,j] = distMat[j,i] = self.pairDist(i,j)
self._distMat_ = distMat
if minSites:
pairNonNan = self._pairNonNan_ if self._pairNonNan_ is not None else self.pairNonNan()
distMat[pairNonNan < minSites] = np.NaN
return distMat
def sampleHet(self, sampleNames=None, asList = False):
if sampleNames is None: sampleNames,sampleIndices = uniqueIndices(self.sampleNames, preserveOrder=True)
else: sampleIndices = [np.where(self.sampleNames == sampleName)[0] for sampleName in sampleNames]
#if a pre-computed distance matrix is available, use that
if self._distMat_ is not None:
hets = [self._distMat_[x[0],x[1]] if len(x)==2 else np.NaN for x in sampleIndices]
#otherwise compute pairwise distances (i.e. entire matrix not needed)
else:
hets = [self.pairDist(x[0],x[1]) if len(x)==2 else np.NaN for x in sampleIndices]
return dict(zip(sampleNames,hets)) if not asList else hets
#makes a dict of average distance among samples.
#if all are haploid, this is just a dictionary of the output of distMatrix()
#if some have ploidy > 1, this will average distance among sample haplotypes
def indPairDists(self, asDict=True, includeSameWithSame=False):
distMat = self.distMatrix() if self._distMat_ is None else self._distMat_
#mask diagonal if necessary
if not includeSameWithSame: np.fill_diagonal(distMat, np.NaN) # set all same-with-same to Na
sampleNames,sampleIndices = uniqueIndices(self.sampleNames, preserveOrder=True)
n = len(sampleNames)
if asDict:
pairDists = {}
for sampleName in sampleNames: pairDists[sampleName] = {}
for i,j in itertools.product(range(n),repeat=2):
pairDists[sampleNames[i]][sampleNames[j]] = np.nanmean(distMat[np.ix_(sampleIndices[i],sampleIndices[j])])
return pairDists
else:
indDistMat = np.zeros(n,n)
for i,j in itertools.combinations_with_replacement(range(n),2):
indDistMat[i,j] = indDistMat[j,i] = np.nanmean(distMat[np.ix_(sampleIndices[i],sampleIndices[j])])
return indDistMat
def groupDistStats(self, doPairs = True, minSites=None, minData=0.01):
#get distance matrix unless a precomputed one is available
distMat = self._distMat_ if self._distMat_ is not None else self.distMatrix()
if minSites:
pairNonNan = self._pairNonNan_ if self._pairNonNan_ is not None else self.pairNonNan()
distMat[pairNonNan < minSites] = np.NaN
np.fill_diagonal(distMat, np.NaN) # set all same-with-same to Na
pops,indices = np.unique(self.groups, return_inverse = True)
nPops = len(pops)
#get population indices - which positions in the alignment correspond to each population
# this will allow indexing specific pops from the matrix.
popIndices = [list(np.where(indices==x)[0]) for x in range(nPops)]
output = {}
#pi for each pop
for x in range(nPops):
output["pi_" + pops[x]] = nanmean_min(distMat[np.ix_(popIndices[x],popIndices[x])], min=minData)
if nPops == 1 or not doPairs: return output
#pairs
for x in range(nPops-1):
for y in range(x+1, nPops):
#dxy
output["dxy_" + pops[x] + "_" + pops[y]] = output["dxy_" + pops[y] + "_" + pops[x]] = nanmean_min(distMat[np.ix_(popIndices[x],popIndices[y])], min=minData)
#fst
#first get the weightings for each pop
n_x = len(popIndices[x])
n_y = len(popIndices[y])
w = 1.* n_x/(n_x + n_y)
pi_s = w*(output["pi_" + pops[x]]) + (1-w)*(output["pi_" + pops[y]])
pi_t = nanmean_min(distMat[np.ix_(popIndices[x]+popIndices[y],popIndices[x]+popIndices[y])], min=minData)
output["Fst_" + pops[x] + "_" + pops[y]] = output["Fst_" + pops[y] + "_" + pops[x]] = 1 - pi_s/pi_t
return output
def varSites(self, indices=None, names=None):
if names is not None: indices = np.where(np.in1d(aln.names,names))[0]
if indices is None: indices = np.arange(self.N)
return np.where([numVar(self.numArray[indices,x][self.nanMask[indices,x]]) for x in range(self.l)])[0]
def groupFreqStats(self):
#dictionary of popgen statistics based on sites (as opposed to pairwise sequence comparisons)
# THIS ONLY USES SITES WITHOUT ANY MISSING DATA IN A GIVEN GROUP
output = {}
for groupName in np.unique(self.groups):
seqIdx = np.where(self.groups==groupName)[0]
N = len(seqIdx)
siteIdx = np.where(np.all(self.nanMask, axis=0))[0]
l = len(siteIdx)
if l >= 1:
siteBaseCounts = np.apply_along_axis(binBaseFreqs,0,self.numArray[np.ix_(seqIdx,siteIdx)],asCounts=True)
#Here I caculate a site-wise pi by summing multplied pairs of base frequencies and dividing by total possible pairs