-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathclumpp.py
266 lines (227 loc) · 7.13 KB
/
clumpp.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
from __future__ import print_function
from shutil import copyfile
from DefaultListOrderedDict import DefaultListOrderedDict
import os
import sys
class Clumpp():
'Class for finding and preparing clumpp output from the output produced by clumpak'
def __init__(self,wd,k,ad):
self.wd = wd
self.k = k
self.ad = ad
#Construct path to where files should reside
tempdir = "K=" + self.k
self.kdir = os.path.join(self.wd, tempdir)
self.majcdir = os.path.join(self.kdir, "MajorCluster")
self.clusdir = os.path.join(self.majcdir,"clusterFiles")
self.cdir = os.path.join(self.majcdir, "CLUMPP.files")
# check to see if major cluster directory exists
self.dirExists(self.cdir)
self.oldind = "ClumppIndFile.output"
self.oldpop = "ClumppPopFile"
#Get the files that contain clumpp output from major cluster directory
self.clumppoutind = os.path.join(self.cdir, self.oldind)
self.clumppoutpop = os.path.join(self.cdir, self.oldpop)
#Check if major cluster files exist
self.fileExists(self.clumppoutind)
self.fileExists(self.clumppoutpop)
#Check if minor clusters exist
self.mincdir = list()
dirContents = os.listdir(self.kdir)
for d in dirContents:
td = os.path.join(self.kdir, d)
if os.path.isdir(td):
if os.path.basename(td).startswith("MinorCluster"):
self.mincdir.append(td)
#print(self.mincdir)
#Get the files that contain clumpp output from minor cluster directories
self.minclumppoutind = list()
self.minclumppoutpop = list()
for d in self.mincdir:
tdi = os.path.join(d, "CLUMPP.files", self.oldind)
self.minclumppoutind.append(tdi)
self.fileExists(tdi)
tdp = os.path.join(d, "CLUMPP.files", self.oldpop)
self.minclumppoutpop.append(tdp)
self.fileExists(tdp)
#find number of individuals and populations
self.inds = self.linecount(self.clumppoutind)
self.pops = self.linecount(self.clumppoutpop)
def copyMajClustFiles(self):
nd = self.makeDir()
np = self.oldpop + "." + self.k
newpop = os.path.join(nd, np)
ni = self.oldind + "." + self.k
newind = os.path.join(nd, ni)
copyfile(self.clumppoutind, newind)
copyfile(self.clumppoutpop, newpop)
return np,ni,nd
def copyMinClustFiles(self):
nd = self.makeDir()
npList = list()
niList = list()
for f in self.minclumppoutind:
allLevels = self.splitAll(f)
minClust = allLevels[-3]
ni = self.oldind + "." + self.k + "." + minClust
newind = os.path.join(nd, ni)
niList.append(ni)
copyfile(f, newind)
for f in self.minclumppoutpop:
allLevels = self.splitAll(f)
minClust = allLevels[-3]
np = self.oldpop + "." + self.k + "." + minClust
newpop = os.path.join(nd, np)
npList.append(np)
copyfile(f, newpop)
return npList,niList
def getMinorClusterRuns(self):
mcRunsDict = DefaultListOrderedDict() #dict of runs associated with K for json dump
for d in self.mincdir:
bn = os.path.basename(d)
num = bn.replace("MinorCluster", "")
fn = "MinorClusterRuns.K" + str(self.k) + "." + str(num)
with open(fn, 'w') as mcruns:
content = list()
clusDir = os.path.join(d, "clusterFiles")
with open(clusDir) as f:
content = f.readlines()
for line in content:
tlist = line.split(".")
tlist.pop(-1)
tlist.pop(-1)
tlist.append("stdout")
temp = ".".join(tlist)
mcruns.write(temp)
mcruns.write("\n")
newKey = str(self.k) + ".MinClust." + str(num) #make new key for minor cluster
mcRunsDict[newKey].append(temp)
return mcRunsDict
def getMajorClusterRuns(self,mc):
mcRunsDict = DefaultListOrderedDict() #dict of runs associated with K for json dump
with open(mc, 'a') as mcruns:
content = list()
with open(self.clusdir) as f:
content = f.readlines()
for line in content:
tlist = line.split(".")
tlist.pop(-1)
tlist.pop(-1)
tlist.append("stdout")
temp = ".".join(tlist)
mcruns.write(temp)
mcruns.write("\n")
mcRunsDict[self.k].append(temp)
return mcRunsDict
def getMajorClusterLoglikelihood(self, mc):
with open(mc) as mcruns:
mcfiles = mcruns.readlines()
with open("loglikelihood_file.MajClust.txt", 'a') as llf:
for f in mcfiles:
templist = f.split(".")
templist2 = templist[-2].split("_")
k=templist2[0]
filepath = os.path.join(self.ad, f).rstrip()
with open(filepath, 'r') as llin:
for line in llin.readlines():
if line.startswith('Loglikelihood'):
llf.write(str(k))
llf.write("\t")
llf.write(line)
def getMinorClusterLoglikelihood(self):
match = "MinorClusterRuns.K" + str(self.k) + "."
content = os.listdir(os.getcwd())
for f in content:
if f.startswith(match):
with open(f) as mcruns:
mcfiles = mcruns.readlines()
temp = f.split(".")
newlist = list()
newlist.append("loglikelihood_file")
newlist.append("MinClust")
for item in temp[-2:]:
newlist.append(item)
newlist.append("txt")
outfile = ".".join(newlist)
with open(outfile, 'w') as llf:
for f in mcfiles:
filepath = os.path.join(self.ad, f).rstrip()
with open(filepath, 'r') as llin:
for line in llin.readlines():
if line.startswith('Loglikelihood'):
llf.write(str(self.k))
llf.write("\t")
llf.write(line)
def getMajorClusterCVvalues(self, mc):
with open(mc) as mcruns:
mcfiles = mcruns.readlines()
with open("cv_file.MajClust.txt", 'a') as cvf:
for f in mcfiles:
filepath = os.path.join(self.ad, f).rstrip()
#print(filepath)
with open(filepath, 'r') as cvin:
for line in cvin.readlines():
if 'CV' in line:
cvf.write(line)
def getMinorClusterCVvalues(self):
match = "MinorClusterRuns.K" + str(self.k) + "."
content = os.listdir(os.getcwd())
for f in content:
if f.startswith(match):
with open(f) as mcruns:
mcfiles = mcruns.readlines()
temp = f.split(".")
newlist = list()
newlist.append("cv_file")
newlist.append("MinClust")
for item in temp[-2:]:
newlist.append(item)
newlist.append("txt")
outfile = ".".join(newlist)
with open(outfile, 'w') as cvf:
for f in mcfiles:
filepath = os.path.join(self.ad, f).rstrip()
with open(filepath, 'r') as cvin:
for line in cvin.readlines():
if 'CV' in line:
cvf.write(line)
def makeDir(self):
nd = os.path.join(self.wd, "best_results")
if not os.path.exists(nd):
os.makedirs(nd)
return nd
def linecount(self,fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i+1
def fileExists(self, filename):
if( os.path.isfile(filename) != True ):
print( filename, "does not exist" )
print( "Exiting program..." )
print( "" )
raise SystemExit
else:
print(filename, "Exists")
def dirExists(self,directory):
if(os.path.isdir(directory) != True):
print(repr(directory), "does not exist")
print("Exiting program...")
print("")
raise SystemExit
else:
print(directory, "Exists")
def splitAll(self,path):
allparts = list()
while 1:
parts = os.path.split(path)
if parts[0] == path:
allparts.insert(0, parts[0])
break
elif parts[1] == path:
allparts.insert(0, parts[1])
break
else:
path = parts[0]
allparts.insert(0, parts[1])
return allparts