forked from stevemussmann/admixturePipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaladmix.py
175 lines (147 loc) · 4.66 KB
/
evaladmix.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
from evalAdmixComline import ComLine
from syscall import SysCall
from rpy2.robjects import StrVector
from rpy2.robjects.conversion import localconverter
from rpy2.robjects.packages import STAP
from rpy2.robjects.packages import importr
from rpy2.robjects import r, pandas2ri
import json
import os.path
import pandas
import rpy2.robjects
import sys
class EvalAdmix():
'Class for executing evalAdmix commands'
def __init__(self,prefix,mc,funcs):
self.prefix = prefix
self.mc = mc
self.mcOnly = False
if(self.mc != "none"):
self.mcOnly = True
self.qfiles = dict()
self.runs = dict()
self.qfilePaths = dict()
if(self.mcOnly == True):
self.parseMC()
#import R functions
self.utils = importr('utils')
self.base = importr('base')
self.grdevices = importr('grDevices')
# import R plotting functions from evalAdmix
with open(funcs, 'r') as f:
string = f.read()
self.myfunc = STAP(string, "myfunc")
def parseMC(self):
print("Parsing MC")
with open(self.mc) as fh:
newlist = fh.read().splitlines()
print(newlist)
def loadJson(self):
self.loadQ()
self.loadRuns()
self.loadQfilePaths()
def loadQ(self):
qfn = self.prefix + ".qfiles.json"
if os.path.isfile(qfn):
with open(qfn) as fh:
self.qfiles = json.load(fh)
else:
print("ERROR:", qfn, "does not exist.")
print("Exiting program...")
raise SystemExit
def loadRuns(self):
rfn = "cvRuns.json"
if os.path.isfile(rfn):
with open(rfn) as fh:
self.runs = json.load(fh)
else:
print("ERROR:", rfn, "does not exist.")
print("Exiting program...")
raise SystemExit
def loadQfilePaths(self):
rfn = "qfilePaths.json"
if os.path.isfile(rfn):
with open(rfn) as fh:
self.qfilePaths = json.load(fh)
else:
print("ERROR:", rfn, "does not exist.")
print("Exiting program...")
raise SystemExit
def evalAdmix(self, minK, maxK, np):
ks = range(int(minK), int(maxK)+1)
for k in ks:
for qf in self.qfiles[str(k)]:
print(qf)
temp = qf.split(".")
#make .P file name
temp[-1] = "P"
pf = ".".join(temp)
#make output .corres file name
temp[-1] = "corres"
eAf = ".".join(temp)
#build command for evalAdmix
evalAdmix_str_com = "evalAdmix -plink " + self.prefix + " -fname " + pf + " -qname " + qf + " -o " + eAf + " -P " + str(np)
call = SysCall(evalAdmix_str_com)
call.run_program()
def averageCorres(self, funcs):
for k in self.runs:
matrixList = list()
print(k)
for run in self.runs[k]:
temp = run.split(".")
temp[-1] = "corres"
eAf = ".".join(temp)
if(os.path.isfile(eAf)):
cor = self.base.as_matrix(self.utils.read_table(eAf))
matrixList.append(cor)
else:
print("ERROR:", eAf, "does not exist.")
print("Exiting program...")
raise SystemExit
reducedList = self.base.Reduce('+', matrixList) #sum matrices in list
cor = reducedList.ro/float(len(matrixList)) #div by num elements in list to get mean
q = self.parseClumpp(self.qfilePaths[k])
famf = self.prefix + ".fam"
pop = self.base.as_matrix(self.utils.read_table(famf))
output = k + ".png"
ordr = self.myfunc.orderInds(pop=self.base.as_vector(pop.rx(True,2)), q=q)
title=k
self.grdevices.png(file=output)
try:
self.myfunc.plotCorRes(cor_mat=cor, pop=self.base.as_vector(pop.rx(True,2)), ord=ordr, title=title, max_z=0.1, min_z=-0.1)
except rpy2.rinterface_lib.embedded.RRuntimeError:
print("Error in R code (plotting functions) from evalAdmix.")
self.grdevices.dev_off()
def parseClumpp(self,f):
if(os.path.isfile(f)):
df = pandas.read_csv(f, delimiter="\s+", header=None, index_col=False)
df.drop(df.columns[0:5],axis=1,inplace=True)
#print(df)
with localconverter(rpy2.robjects.default_converter + pandas2ri.converter):
Rdf = rpy2.robjects.conversion.py2rpy(df)
#print(Rdf)
return Rdf
def Rcode(self, funcs, minK, maxK):
#make file names
famf = self.prefix + ".fam"
ks = range(int(minK), int(maxK)+1)
for k in ks:
title="K="+str(k)
for qf in self.qfiles[str(k)]:
temp = qf.split(".")
temp[-1] = "corres"
eAf = ".".join(temp)
output = eAf + ".png"
# read in files
pop = self.base.as_matrix(self.utils.read_table(famf))
print(qf)
q = self.utils.read_table(qf)
cor = self.base.as_matrix(self.utils.read_table(eAf))
# run plotting functions
ordr = self.myfunc.orderInds(pop=self.base.as_vector(pop.rx(True,2)), q=q)
self.grdevices.png(file=output)
try:
self.myfunc.plotCorRes(cor_mat=cor, pop=self.base.as_vector(pop.rx(True,2)), ord=ordr, title=title, max_z=0.1, min_z=-0.1)
except rpy2.rinterface_lib.embedded.RRuntimeError:
print("Something happened.")
self.grdevices.dev_off()