-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheden.py
1177 lines (1005 loc) · 42.2 KB
/
eden.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
""" Eden module for network toolbox
This module contains Eden specific classes.
"""
import collections
import pynet,random,netext
import communities
from communities import communityTree
from math import sin,cos,asin,sqrt,pi
import math
import numpy
from itertools import *
class EDENException(Exception):
pass
class ParsingError(EDENException):
pass
def getGoldsteinLists(poplist):
"""Transforms the list of population indices (poplist) into
a list of lists, where each internal list contains all indices of
a population. Useful for getting the Goldstein population-level
distances for microsatellite data. Outputs: the population
member list of lists (goldstein_lists), list of unique population labels (uniquepops)"""
uniquepops=[]
pops=set()
for pop in poplist:
if pop not in pops:
uniquepops.append(pop)
pops.add(pop)
#uniquepops=[ uniq for uniq in poplist if uniq not in locals()['_[1]']]
goldstein_lists=[]
for population in uniquepops:
thislist=[]
for i,item in enumerate(poplist):
if item==population:
thislist.append(i)
goldstein_lists.append(thislist)
return [goldstein_lists,uniquepops]
def loadNet_microsatellite(input,removeClones=True,distance="lm"):
"""
Reads microsatellite data as full net from iterable object
containing strings (opened file). Look eden.MicrosatelliteData for
the format the data is read. This function also removes the clones by default.
"""
msData=MicrosatelliteData(input)
if removeClones:
msData=msData.getUniqueSubset()
msNet=msData.getDistanceMatrix(distance)
return msNet
class SampleFeatureData(object):
""" A class for representing data for a set of samples.
The features can be microsatellites, alleles, presence/absence
or presence/abundace data.
"""
def __init__(self,input_iterator,missingValue="999",ploidity=2):
self.diploidity=ploidity
self.missingValue=missingValue
self.parse_input(input_iterator)
def parse_input(input_iterator):
#read the data to memory first:
lines=list(input_iterator)
#parse the first line to guess the format
try:
fields=map(int,lines[0].split())
self.numeric=True
missingValue=int(missingValue)
except ValueError:
self.numeric=False
#construct an empty array for the data
self._alleles=numpy.zeros() #sample, locus, allele
#--> old code
self._alleles=[] #The list of locus lists. Each locus list contains alleles as tuples.
for lineNumber,line in enumerate(input):
fields=line.split()
#At the first line, test if data is numerical
if lineNumber==0:
try:
fields=map(int,fields)
self.numeric=True
missingValue=int(missingValue)
except ValueError:
self.numeric=False
if len(fields)%2!=0:
raise SyntaxError("Input should have even number of columns");
elif lastNumberOfFields!=None and lastNumberOfFields!=len(fields):
raise SyntaxError("The input has inconsistent number of columns")
else:
lastNumberOfFields=len(fields)
if self.numeric:
try:
fields=map(int,fields)
except ValueError:
raise SyntaxError("Input contains mixed numeric and not numeric alleles.")
#At the first line, add lists for loci
if len(self._alleles)==0:
for dummy in range(0,len(fields)/2):
self._alleles.append([])
for i in range(0,len(fields),2):
if fields[i]!=missingValue and fields[i+1]!=missingValue:
if fields[i]>fields[i+1]:
fields[i],fields[i+1]=fields[i+1],fields[i]
self._alleles[i/2].append((fields[i],fields[i+1]))
elif fields[i]==missingValue: #None comes first
if fields[i+1]==missingValue:
self._alleles[i/2].append((None,None))
else:
self._alleles[i/2].append((None,fields[i+1]))
else:
self._alleles[i/2].append((None,fields[i]))
if lastNumberOfFields!=None:
self.nLoci=lastNumberOfFields/2
def _clear_cache(self):
pass
class MicrosatelliteData:
""" A class for parsing and using microsatellite data
"""
def __init__(self,input,missingValue="999"):
"""
The microsatellite data must be given as a input where each row
has microsatellites for one node/specimen. Alleles should be given as
integer numbers representing the number of repetitions. The data should have
even number of columns where each pair represents two homologous alleles.
Input variable should contain iterable object that outputs the row as a string
at each iteration step: for example open('msfile.txt').
"""
self.diploid=True
lastNumberOfFields=None
self._alleles=[] #The list of locus lists. Each locus list contains alleles as tuples.
for lineNumber,line in enumerate(input):
line=line.strip()
if len(line)>0:
fields=line.split()
#At the first line, test if data is numerical
if lineNumber==0:
try:
fields=map(int,fields)
self.numeric=True
missingValue=int(missingValue)
except ValueError:
self.numeric=False
if len(fields)%2!=0:
raise SyntaxError("Input should have even number of columns");
elif lastNumberOfFields!=None and lastNumberOfFields!=len(fields):
raise SyntaxError("The input has inconsistent number of columns")
else:
lastNumberOfFields=len(fields)
if self.numeric:
try:
fields=map(int,fields)
except ValueError:
raise SyntaxError("Input contains mixed numeric and not numeric alleles.")
#At the first line, add lists for loci
if len(self._alleles)==0:
for dummy in range(0,len(fields)/2):
self._alleles.append([])
for i in range(0,len(fields),2):
if fields[i]!=missingValue and fields[i+1]!=missingValue:
if fields[i]>fields[i+1]:
fields[i],fields[i+1]=fields[i+1],fields[i]
self._alleles[i/2].append((fields[i],fields[i+1]))
elif fields[i]==missingValue: #None comes first
if fields[i+1]==missingValue:
self._alleles[i/2].append((None,None))
else:
self._alleles[i/2].append((None,fields[i+1]))
else:
self._alleles[i/2].append((None,fields[i]))
if lastNumberOfFields!=None:
self.nLoci=lastNumberOfFields/2
def copy(self):
return self.getSubset(range(self.getNumberOfNodes()))
def shuffleNodes(self):
"""
Shuffles the order of nodes
"""
nNodes=len(self._alleles[0])
nLoci=self.getNumberofLoci()
for i in range(nNodes):
r=random.randint(i,nNodes-1)
for li in range(nLoci):
tempA=self._alleles[li][i]
self._alleles[li][i]=self._alleles[li][r]
self._alleles[li][r]=tempA
def getNode(self,index):
"""
Returns a list of alleles where every two alleles in the same loci
are coupled together with a tuple object.
"""
node=[]
for allele in self._alleles:
node.append(allele[index])
return tuple(node)
def getLocusforNodeIndex(self, locus, node):
return self._alleles[locus][node]
def getNumberofLoci(self):
return len(self._alleles)
def getMSDistance_hybrid(self,x,y,lm_w=None,nsa_w=None):
if lm_w==None:
lm_w=self.lm_w
if nsa_w==None:
nsa_w=self.nsa_w
return float(sum(self.getMSDistance_vectorHybrid(x,y,lm_w=lm_w,nsa_w=nsa_w)))
def getMSDistance_vectorHybrid(self,x,y,lm_w=None,nsa_w=None):
if lm_w==None:
lm_w=self.lm_w
if nsa_w==None:
nsa_w=self.nsa_w
distance=numpy.zeros(len(x))
return nsa_w*self.getMSDistance_vectorNonsharedAlleles(x,y)+lm_w*self.getMSDistance_vectorLinearManhattan(x,y)
def getGroupwiseDistance_DyerNason(self,x,y):
"""
Returns the distance between two populations defined by Dyer and Nason in:
"Population graphs: The graph theoretic shape of genetic structure, Mol Ecol
13:1713-1727 (2004)". This implementation is coded by following:
"M.A. Fortuna et al.: Networks of spatial genetic variation across species, PNAS
vol. 106 no. 45 pp. 19044-19049 (2009)".
Parameters
----------
x and y are lists of sample indices correspoding to samples of two populations.
The distance between these populations is calculated.
"""
#calculate the centroid multivariate coding vector:
x_cod={} # the codification vector for population x
for nodeIndex in x:
for locus in range(self.getNumberofLoci()):
alleles=self.getLocusforNodeIndex(locus,nodeIndex)
key=(locus,alleles[0])
x_cod[key]+=x_cod.get(key,0)+1
key=(locus,alleles[1])
x_cod[key]+=x_cod.get(key,0)+1
for key in x_cod.keys(): #normalize
x_cod[key]=x_cod[key]/float(len(x))
raise NotImplementedError()
def getGroupwiseDistance_Goldstein_D1(self,x,y):
"""
Returns the goldstein distance between two populations
This is the ASD (average square distance) of the Goldstein distances.
Parameters
----------
x and y are lists of sample indices correspoding to samples of two populations.
The distance between these populations is calculated.
Example
-------
>>> ms=eden.MicrosatelliteData(open("../data/microsatellites/microsatellites.txt",'r'))
>>> ms_u = ms.getUniqueSubset()
>>> ms_u.getGroupwiseDistance_Goldstein([1,2,3,4],[1,2,3,4]) == 47.517857142857146
True
"""
distList = []
for locus in range(self.getNumberofLoci()):
# calculates allele frequences
xdict = {}
for nodeIndex in x:
xlocus = self.getLocusforNodeIndex(locus,nodeIndex)
xdict[xlocus[0]] = xdict.get(xlocus[0],0) + 1
xdict[xlocus[1]] = xdict.get(xlocus[1],0) + 1
ydict = {}
for nodeIndex in y:
ylocus = self.getLocusforNodeIndex(locus,nodeIndex)
ydict[ylocus[0]] = ydict.get(ylocus[0],0) + 1
ydict[ylocus[1]] = ydict.get(ylocus[1],0) + 1
dist = 0
NElementsX=float(sum(xdict.itervalues())-xdict.get(None,0))
NElementsY=float(sum(ydict.itervalues())-ydict.get(None,0))
if NElementsX!=0 and NElementsY!=0:
for i in xdict:
if i!=None:
for j in ydict:
if j!=None:
dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY
distList.append(dist)
return sum(distList)/len(distList)
def getGroupwiseDistance_Goldstein(self,x,y):
"""
Returns the goldstein distance between two populations.
For each allele this is the square of the averages. This function
returns the average of the values for each allele.
Parameters
----------
x and y are lists of sample indices correspoding to samples of two populations.
The distance between these populations is calculated.
"""
distList=[]
for locus in range(self.getNumberofLoci()):
#Calculate the averages
mx=0.0
nx=0.0
for nodeIndex in x:
xlocus = self.getLocusforNodeIndex(locus,nodeIndex)
if xlocus[0]!=None:
mx+=xlocus[0]
nx+=1
if xlocus[1]!=None:
mx+=xlocus[1]
nx+=1
if nx!=0.0:
mx=mx/float(nx)
else:
mx=None
my=0.0
ny=0.0
for nodeIndex in y:
ylocus = self.getLocusforNodeIndex(locus,nodeIndex)
if ylocus[0]!=None:
my+=ylocus[0]
ny+=1
if ylocus[1]!=None:
my+=ylocus[1]
ny+=1
if ny!=0:
my=my/float(ny)
else:
my=None
if mx != None and my != None:
distList.append((mx-my)**2)
if len(distList)!=0:
return sum(distList)/len(distList)
else:
return 0.0
def getGroupwiseDistanceMatrix(self,groups,distance,groupNames=None):
"""
Returns a distance matrix in form of a full network (pynet.SymmFullNet). The groups
argument must be an iterable object where each element is also iterable object containing
the indices of the nodes belonging to each group.
"""
distance=distance.lower() #any case is ok
grouplist=list(groups)
ngroups=len(grouplist)
matrix=pynet.SymmFullNet(ngroups)
if groupNames==None:
groupNames=range(ngroups)
if distance in ["goldstein","goldstein_d1"]:
#only distance measure implemented so far:
if distance=="goldstein":
getGroupwiseDistance=self.getGroupwiseDistance_Goldstein
elif distance=="goldstein_d1":
getGroupwiseDistance=self.getGroupwiseDistance_Goldstein_D1
for i in range(0,ngroups):
for j in range(i+1,ngroups):
matrix[groupNames[i],groupNames[j]]=getGroupwiseDistance(grouplist[i],grouplist[j])
return matrix
elif distance in ["fst"]: #allele frequency table based distances
afTable=AlleleFrequencyTable()
afTable.init_msData(self,grouplist,groupNames)
if distance=="fst":
return afTable.getFST()
else:
raise NotImplementedError("Distance '"+distance+"' is not implemented.")
#--- Distances between individuals
def getMSDistance_linearManhattan(self,x,y):
"""
Returns the distance between two nodes/specimen
"""
return self.getMSDistanceByVector(self.getMSDistance_vectorLinearManhattan(x,y))
def getMSDistance_nonsharedAlleles(self,x,y):
return self.getMSDistanceByVector(self.getMSDistance_vectorNonsharedAlleles(x,y))
def getMSDistance_alleleParsimony(self,x,y):
return self.getMSDistanceByVector(self.getMSDistance_vectorAlleleParsimony(x,y))
#-> Distance specific distance vectors
"""
def getMSDistance_vectorLinearManhattan(self,x,y):
distance=numpy.zeros(len(x))
for locus in range(0,len(x)):
if x[locus]!=None and y[locus]!=None:
distance[locus]=abs(x[locus][0]-y[locus][0])+abs(x[locus][1]-y[locus][1])
else:
distance[locus]=numpy.nan
return distance
"""
def getMSDistance_vectorLinearManhattan(self,x,y):
return self.getMSDistanceVectorByAlleles(x,y,self.getMSDistance_singleLocus_LinearManhattan)
def getMSDistance_vectorNonsharedAlleles(self,x,y):
return self.getMSDistanceVectorByAlleles(x,y,self.getMSDistance_singleLocus_NonsharedAlleles)
def getMSDistance_vectorAlleleParsimony(self,x,y):
return self.getMSDistanceVectorByAlleles(x,y,self.getMSDistance_singleLocus_AlleleParsimony)
#<-
#-> Distance specific single locus distances
def getMSDistance_singleLocus_NonsharedAlleles(self,x,y):
alleles=x+y
distance=0
for allele in alleles:
if allele not in x or allele not in y:
distance+=1
return distance
def getMSDistance_singleLocus_AlleleParsimony(self,x,y):
first=len(set([x[0],y[0]]))+len(set([x[1],y[1]]))
second=len(set([x[0],y[1]]))+len(set([x[1],y[0]]))
return float(min([first,second]))-2.0
def getMSDistance_singleLocus_LinearManhattan(self,x,y):
return abs(x[0]-y[0])+abs(x[1]-y[1])
#<-
#->General functions for distance calculations
def getMSDistanceVectorByAlleles(self,x,y,distance_singleLocus):
distance=numpy.zeros(len(x))
for locus in range(0,len(x)):
if x[locus][0]!=None and y[locus][0]!=None:
distance[locus]=distance_singleLocus(x[locus],y[locus])
else:
distance[locus]=numpy.nan
return distance
def getMSDistanceByVector(self,distanceVector):
size=0
sum=0
for i in xrange(len(distanceVector)):
if distanceVector[i]>=-1: #distanceVector[i]!=numpy.nan
sum+=distanceVector[i]
size+=1
if size!=0:
return sum/float(size)
else:
return -1 #numpy.nan
def getMSDistanceByAlleles(self,x,y,distance_singleLocus):
return self.getMSDistanceByVector(self.getMSDistanceVectorByAlleles(x,y,distance_singleLocus))
#<-
def getDistanceMatrix(self,distance="lm",nodeNames=None,progressUpdater=None):
"""
Computes the distance between each node and returns the corresponding
distance matrix.
"""
if distance=="lm":
getMSDistance=self.getMSDistance_linearManhattan
elif distance=="nsa":
getMSDistance=self.getMSDistance_nonsharedAlleles
elif distance=="ap":
getMSDistance=self.getMSDistance_alleleParsimony
elif distance=="hybrid":
getMSDistance=self.getMSDistance_hybrid
elif distance=="czekanowski":
getMSDistance=self.get_czekanowski_dissimilarity
else: #default
getMSDistance=self.getMSDistance_linearManhattan
numberOfSpecimens=len(self._alleles[0])
j=0
minUpdateInterval=1000
minUpdateSteps=30
totElems=numberOfSpecimens*(numberOfSpecimens-1)/2
updateInterval=max(min(minUpdateInterval,int(totElems/float(minUpdateSteps))),1)
elementsAdded=0
lastUpdate=0
matrix=pynet.SymmFullNet(numberOfSpecimens)
if nodeNames==None:
nodeNames=range(0,numberOfSpecimens)
for i,iName in enumerate(nodeNames):
if progressUpdater!=None:
if elementsAdded-lastUpdate>updateInterval:
progressUpdater(float(elementsAdded)/float(totElems))
lastUpdate=elementsAdded
elementsAdded+=numberOfSpecimens-i
for j in range(i+1,numberOfSpecimens):
jName=nodeNames[j]
matrix[iName,jName]=getMSDistance(self.getNode(i),self.getNode(j))
return matrix
def getSubset(self,nodes):
"""
Returns a new MicrosatelliteData object containing only nodes given
as a input. The input is a list of indices of the nodes.
"""
newData=self.__class__([])
for allele in self._alleles:
newAllele=[]
for node in nodes:
newAllele.append(allele[node])
newData._alleles.append(newAllele)
newData.nLoci=self.nLoci
return newData
def randomize(self,full=False):
"""
Shuffles the homologous alleles in the whole dataset
"""
if full:
for j,allele in enumerate(self._alleles):
newAlleles=[]
alleleList=[]
for apair in allele:
alleleList.append(apair[0])
alleleList.append(apair[1])
random.shuffle(alleleList)
for i in range(0,len(alleleList),2):
newAlleles.append((alleleList[i],alleleList[i+1]))
self._alleles[j]=newAlleles
#this really should shuffle all the homologous alleles
#and not small and large alleles separately
else:
for allele in self._alleles:
random.shuffle(allele)
def getNumberOfNodes(self):
return len(self._alleles[0])
def getUniqueSubset(self,returnOldIndices=False):
"""
Returns a new MicrosatelliteData object with all identical nodes
removed except the first occurances of them.
"""
numberOfNodes=self.getNumberOfNodes()
nodeSet=set()
uniqueNodes=[]
for i in range(0,numberOfNodes):
node=self.getNode(i)
if node not in nodeSet:
nodeSet.add(node)
uniqueNodes.append(i)
#print i+1 #indices for Jenni and Jari
if returnOldIndices:
return (self.getSubset(uniqueNodes),uniqueNodes)
else:
return self.getSubset(uniqueNodes)
def __str__(self):
theStr=""
for nodeIndex in range(self.getNumberOfNodes()):
node=self.getNode(nodeIndex)
alleleList=reduce(lambda x,y:x+y,node)
alleleStr=reduce(lambda x,y:str(x)+" "+str(y),alleleList)
theStr+=alleleStr+"\n"
return theStr
class MicrosatelliteDataHaploid(MicrosatelliteData):
def __init__(self,input,missingValue="999"):
"""
The microsatellite data must be given as a input where each row
has microsatellites for one node/specimen. Alleles should be given as
integer numbers representing the number of repetitions. The data should have
even number of columns where each pair represents two homologous alleles.
Input variable should contain iterable object that outputs the row as a string
at each iteration step: for example open('msfile.txt').
"""
self.diploid=False
lastNumberOfFields=None
self._alleles=[] #The list of locus lists. Each locus list contains alleles as tuples.
for lineNumber,line in enumerate(input):
line=line.strip()
if len(line)>0:
fields=line.split()
#At the first line, test if data is numerical
if lineNumber==0:
try:
fields=map(int,fields)
self.numeric=True
missingValue=int(missingValue)
except ValueError:
self.numeric=False
if lastNumberOfFields!=None and lastNumberOfFields!=len(fields):
raise SyntaxError("The input has inconsistent number of columns")
else:
lastNumberOfFields=len(fields)
if self.numeric:
try:
fields=map(int,fields)
except ValueError:
raise SyntaxError("Input contains mixed numeric and not numeric alleles.")
#At the first line, add lists for loci
if len(self._alleles)==0:
for dummy in range(0,len(fields)):
self._alleles.append([])
for i in range(0,len(fields)):
if fields[i]!=missingValue:
self._alleles[i].append(fields[i])
else:
self._alleles[i].append(None)
if lastNumberOfFields!=None:
self.nLoci=lastNumberOfFields
def get_czekanowski_dissimilarity(self,x,y):
up=0.0
down=0.0
for locus_index in range(len(x)):
up+=min(x[locus_index],y[locus_index])
down+=x[locus_index]+y[locus_index]
if down!=0:
return 1.0-2*up/float(down)
else:
return 0.0
def getMSDistance_singleLocus_NonsharedAlleles(self,x,y):
if x==y:
return 0.0
else:
return 1.0
def getMSDistance_singleLocus_AlleleParsimony(self,x,y):
if x==y:
return 0.0
else:
return 1.0
def getMSDistance_singleLocus_LinearManhattan(self,x,y):
return abs(x-y)
def getMSDistanceVectorByAlleles(self,x,y,distance_singleLocus):
distance=numpy.zeros(len(x))
for locus in range(0,len(x)):
if x[locus]!=None and y[locus]!=None:
distance[locus]=distance_singleLocus(x[locus],y[locus])
else:
distance[locus]=numpy.nan
return distance
def getGroupwiseDistance_Goldstein(self,x,y):
"""
Returns the goldstein distance between two populations.
For each allele this is the square of the averages. This function
returns the average of the values for each allele.
Parameters
----------
x and y are lists of sample indices correspoding to samples of two populations.
The distance between these populations is calculated.
"""
distList=[]
for locus in range(self.getNumberofLoci()):
#Calculate the averages
mx=0.0
nx=0.0
for nodeIndex in x:
xlocus = self.getLocusforNodeIndex(locus,nodeIndex)
if xlocus!=None:
mx+=xlocus
nx+=1
if nx!=0.0:
mx=mx/float(nx)
else:
mx=None
my=0.0
ny=0.0
for nodeIndex in y:
ylocus = self.getLocusforNodeIndex(locus,nodeIndex)
if ylocus!=None:
my+=ylocus
ny+=1
if ny!=0.0:
my=my/float(ny)
else:
my=None
if mx!=None and my!=None:
distList.append((mx-my)**2)
if len(distList)!=0:
return sum(distList)/len(distList)
else:
return 0.0
def getGroupwiseDistance_Goldstein_D1(self,x,y):
"""
Returns the goldstein distance between two populations
Parameters
----------
x and y are lists of sample indices correspoding to samples of two populations.
The distance between these populations is calculated.
"""
distList = []
for locus in range(self.getNumberofLoci()):
# calculates allele frequences
xdict = {}
for nodeIndex in x:
xlocus = self.getLocusforNodeIndex(locus,nodeIndex)
xdict[xlocus] = xdict.get(xlocus,0) + 1
ydict = {}
for nodeIndex in y:
ylocus = self.getLocusforNodeIndex(locus,nodeIndex)
ydict[ylocus] = ydict.get(ylocus,0) + 1
# calculates goldstein distance
dist = 0
NElementsX=float(sum(xdict.itervalues())-xdict.get(None,0))
NElementsY=float(sum(ydict.itervalues())-ydict.get(None,0))
if NElementsX!=0 and NElementsY!=0:
for i in xdict:
if i!=None:
for j in ydict:
if j!=None:
dist += float(i-j)**2*xdict[i]/NElementsX*ydict[j]/NElementsY
distList.append(dist)
return sum(distList)/len(distList)
def __str__(self):
raise NotImplemented()
class AlleleDistribution(collections.defaultdict):
def __init__(self):
super(AlleleDistribution, self).__init__()
#self.freqs=collections.defaultdict()
self.default_factory=lambda:0
self.totalFrequency=0
#def __get__(self,item):
# return self.freqs[item]
def __set__(self,item,value):
self.totalFrequency+=value-self[item]
super(AlleleDistribution, self).__set__(item,value)
def get_normaized_distribution(self):
pass
class AlleleFrequencyTable:
def init_freqFile(self,filename):
f=open(filename,'r')
data=[]
groups=set()
loci=set()
for line in f:
line=line.strip()
if not (line.startswith("%") or len(line)==0):
group,locus,allele=line.split()
allele = int(allele)
data.append((group,locus,allele))
groups.add(group)
loci.add(locus)
self.nLoci=len(loci)
self.nGroups=len(groups)
self.groupNames=sorted(groups)
locusNames=sorted(loci)
groupNameToIndex=dict(((g,i) for i,g in enumerate(self.groupNames)))
locusNameToIndex=dict(((l,i) for i,l in enumerate(locusNames)))
self.freqsTable=[[{} for l in loci] for n in groups]
for group,locus,allele in data:
gi=groupNameToIndex[group]
li=locusNameToIndex[locus]
self.freqsTable[gi][li][allele]=self.freqsTable[gi][li].get(allele,0)+1
def init_msData(self,msdata,groups,groupNames=None):
#self.msdata=msdata
self.nLoci=msdata.getNumberofLoci()
self.nGroups=len(groups)
self.freqsTable=[]
if groupNames==None:
self.groupNames=range(self.nGroups)
else:
self.groupNames=groupNames
for groupIndex,group in enumerate(groups):
freqList=[]
self.freqsTable.append(freqList)
for locus in range(msdata.getNumberofLoci()):
#freqs = collections.defaultdict()
#freqs.default_factory=lambda:0
freqs={}
for nodeIndex in group:
allele = msdata.getLocusforNodeIndex(locus,nodeIndex)
if msdata.diploid and allele!=(None,None):
if allele[0]!=None:
freqs[allele[0]] = freqs.get(allele[0],0) + 1
if allele[1]!=None:
freqs[allele[1]] = freqs.get(allele[1],0) + 1
elif allele!=None:
freqs[allele] = freqs.get(allele,0) + 1
if len(freqs)==0:
raise EDENException("Group %s in input data has only missing values in locus %s."%(self.groupNames[groupIndex],locus))
freqList.append(freqs)
def normalizedFreqs(self,group,locus):
nfreqs = collections.defaultdict()
nfreqs.default_factory=lambda:0
tf=float(self.totalFreq(group,locus))
for key,freq in self.freqsTable[group][locus].iteritems():
nfreqs[key]=freq/tf
return nfreqs
def totalFreq(self,group,locus):
return sum(self.freqsTable[group][locus].itervalues())
def getFST(self):
""" From Reynolds, J., Weir, B.S., and Cockerham, C.C. (1983) Estimation of the
coancestry coefficient: basis for a short-term genetic distance. _Genetics_,
105:767-779, p. 769.
"""
d=pynet.SymmFullNet(self.nGroups)
for i in range(self.nGroups):
for j in range(i):
num=0.0
den=0.0
for locus in range(self.nLoci):
ni=float(self.totalFreq(i,locus))
nj=float(self.totalFreq(j,locus))
if ni>0 and nj>0:
summ=0.0
ai=1.0
aj=1.0
fi=self.normalizedFreqs(i,locus)
fj=self.normalizedFreqs(j,locus)
for l in set(chain(fi.iterkeys(),fj.iterkeys())):
summ+=(fi[l]-fj[l])**2
ai-=fi[l]**2
aj-=fj[l]**2
num+=summ/2.-((ni+nj)*(ni*ai+nj*aj))/(4*ni*nj*(ni+nj-1))
den+=summ/2.+((4*ni*nj-ni-nj)*(ni*ai+nj*aj))/(4*ni*nj*(ni+nj-1))
if den>0:
d[self.groupNames[i]][self.groupNames[j]] =-math.log(1-num/den)
else:
d[self.groupNames[i]][self.groupNames[j]]=0.0 #not defined
return d
def heterozygozity(self,freqs):
result=1.0
total=float(sum(freqs.itervalues()))
for freq in freqs.itervalues():
f=freq/total
result-=f*f
return result
def __get__(self,item):
return self.freqTable[item]
class BinaryData(object):
"""A class for representing presence/absense data.
"""
def __init__(self):
self.data=[]
def read_file(self,inputfile):
"""Read in and parse the input file. The input is expected to be in a format where
each row represents one organism/taxa. The inputfile can be given either as a file
name or any iterable list of strings, e.g. open file.
"""
def to_bool(element):
element=element.strip()
if element in ["0","1"]:
return bool(int(element))
else:
raise ParsingError("Invalid element: "+element+", should be 0 or 1.")
if isinstance(inputfile,str):
ifile=open(inputfilen,'rU')
else:
ifile=inputfile
nElements=None
for i,line in enumerate(ifile):
if len(line.strip())>0: #skip lines with only whitespaces
try:
elements=map(to_bool,line.split())
except ParsingError,e:
raise ParsingError("Error reading row "+str(i+1)+".\n"+str(e))
if nElements!=None and len(elements)!=nElements:
raise ParsingError("Row %d has %d features while previous row(s) have %d features." % (i+1,len(elements),nElements))
nElements=len(elements)
self.data.append(elements)
if len(self.data)==0 or len(self.data[0])==0:
raise ParsingError("Error reading data: Empty file.")
def get_union(self,x,y):
count=0
for i in range(len(self.data[0])):
if self.data[x][i]==True or self.data[y][i]==True:
count +=1
return count
def get_intersection(self,x,y):
count=0
for i in range(len(self.data[0])):
if self.data[x][i]==True and self.data[y][i]==True:
count +=1
return count
def count_true(self,x):
count=0
for i in range(len(self.data[x])):
if self.data[x][i]==True:
count +=1
return count
def get_bc_dissimilarity(self,x,y):
""" Bray-Curtis dissimilarity, defined as
d = 1.0 - 2*intersection(x,y)/(n(x)+n(y))
If n(x)+n(y) is zero, distance of 1.0 is returned.
"""
s=self.count_true(x)+self.count_true(y)
if s>0:
return 1.0 - 2*self.get_intersection(x,y)/float(s)
else:
return 1.0
def get_jaccard_distance(self,x,y):
union=float(self.get_union(x,y))
if union!=0.0:
return 1-self.get_intersection(x,y)/union
else:
return 1.0
def get_distance_matrix(self,distance_function,node_names,progressUpdater=None):
size=len(self.data)
j=0
updateInterval=1000
totElems=size*(size-1)/2
elementsAdded=0
lastUpdate=0
distance={"jaccard_distance":self.get_jaccard_distance,
"bc_dissimilarity":self.get_bc_dissimilarity}
matrix=pynet.SymmFullNet(size)
if node_names==None:
node_names=range(0,size)