-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpaint.py
187 lines (168 loc) · 5.69 KB
/
paint.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
import msprime, sys, argparse, csv, itertools, random, numpy as np, threading, tskit, math, tqdm
from random import sample
import argparse, tensorflow as tf, keras, pandas as pd, numpy as np, sys
import keras.backend.tensorflow_backend as tfback
from keras import backend
from numpy import loadtxt
from keras.models import load_model
from find_nearest import find_nearest
def _get_available_gpus():
"""Get a list of available gpu devices (formatted as strings).
# Returns
A list of available GPU devices.
"""
#global _LOCAL_DEVICES
if tfback._LOCAL_DEVICES is None:
devices = tf.config.list_logical_devices()
tfback._LOCAL_DEVICES = [x.name for x in devices]
return [x for x in tfback._LOCAL_DEVICES if 'device:gpu' in x.lower()]
tfback._get_available_gpus = _get_available_gpus
tfback._get_available_gpus()
tf.config.list_logical_devices()
backend.set_image_data_format('channels_first')
parser = argparse.ArgumentParser()
parser.add_argument("-out", help="Filename prefix to wite paths to", required=True)
parser.add_argument("-model",help="Name of the NN model",required=True)
parser.add_argument("-ts", help="Tree sequence file to load", required=True)
parser.add_argument("-poplab", help="File of population labels", required=True)
parser.add_argument("-nn", help="Number of nodes to traverse up to", required=False, default=5)
parser.add_argument("-samples", help="File containing sample order", required=True)
parser.add_argument("-map", help="Genetic map file", required=True)
args = parser.parse_args()
#############################3
model=load_model(args.model)
ts=msprime.load(args.ts)
num_trees=ts.get_num_trees()
num_sites=ts.num_sites
num_muts=ts.get_num_mutations()
print("Number of sites=",num_sites)
print("Number of mutations=",num_muts)
print("Number of trees in tree sequence =", ts.get_num_trees())
map = pd.read_csv(args.map, delimiter = "\t")
#############################
def all_nodes(tree, samples, results):
counts=np.zeros((num_samples,(9*int(args.nn))), dtype=np.float32)
counted=set()
for sam in range(num_samples):
if sam in counted:
continue
sib=tree.left_sib(sam)
if sib==-1:
sib=tree.right_sib(sam)
if sib<num_samples:
pop=samples[sam]
pop_sib=samples[sib]
if pop_sib==pop:
sam_rel=np.array([sam, sib])
else:
sam_rel=np.array([sam])
else:
child_pops=[samples[leaf] for leaf in tree.leaves(sib)]
if len(set(child_pops))==1 and child_pops[0]==8 and samples[sam]==8:
sam_rel=np.append(np.array(list(tree.leaves(sib))), sam)
else:
sam_rel=np.array([sam])
u=tree.parent(sam)
nodes=[]
v=0
leaves_previous=set()
while u != -1 and v != int(args.nn):
total={leaves for leaves in tree.leaves(u) if samples[leaves]!=8 and leaves not in leaves_previous}
#### Moving to next node if none of the samples are found without recording age: Different to previous and how classifier is trained
if len(total)==0:
u=tree.parent(u)
continue
##Finding the label from population and age of nodes
age=tree.time(u)
age_norm=float(age)/1500
counts[sam_rel,8+(9*v)]=age_norm
##Finding the GNN distributions and the age of nodes
add=float(1/len(total))
leaves_previous.update(total)
for leaf in total:
counts[sam_rel,(9*v)+samples[leaf]]+=add
v+=1
u=tree.parent(u)
if (v!=int(args.nn)):
while (v!=int(args.nn)):
counts[sam,(9*v):(9+(9*v))]=-15
v+=1
counted.update(sam_rel)
##################################
counts_test=counts.reshape(counts.shape[0],1,int(args.nn),9)
results[t,:, 0]=model.predict_classes(counts_test, batch_size = 128)+1
prediction=model.predict(counts_test, batch_size=128)
results[t,:,1]=np.max(prediction, axis=1)
###################################
sam_order=[]
with open(args.samples, 'r') as sams_ordered:
for line in sams_ordered:
line=line.strip()
sam_order.append(line)
print(sam_order)
samples={}
with open(args.poplab, 'r') as poplab:
i=0
for line in poplab:
if (line.startswith("sample")):
continue
line=line.strip()
field=line.split(' ')
index=sam_order.index(field[0])
ind_1=(index*2)
ind_2=(index*2)+1
if str(field[1])=="Bronze_Age":
samples[int(ind_1)]=0
samples[int(ind_2)]=0
elif str(field[1])=="BAA":
samples[int(ind_1)]=1
samples[int(ind_2)]=1
elif str(field[1])=="Yam":
samples[int(ind_1)]=2
samples[int(ind_2)]=2
elif str(field[1])=="Neo":
samples[int(ind_1)]=3
samples[int(ind_2)]=3
elif str(field[1])=="WHG":
samples[int(ind_1)]=4
samples[int(ind_2)]=4
elif str(field[1])=="EHG":
samples[int(ind_1)]=5
samples[int(ind_2)]=5
elif str(field[1])=="Ana":
samples[int(ind_1)]=6
samples[int(ind_2)]=6
elif str(field[1])=="CHG":
samples[int(ind_1)]=7
samples[int(ind_2)]=7
else:
samples[int(ind_1)]=8
samples[int(ind_2)]=8
i+=1
print(len(samples), file=sys.stderr)
num_samples=len(list(ts.samples()))
print(num_samples)
##############################
results=np.zeros((num_trees,num_samples,3),dtype=float)
length_dist = np.zeros((num_samples, 5, num_trees), dtype=float)
progress_bar = tqdm.tqdm(total=num_trees)
for t, tree in enumerate(ts.trees()):
iv=tree.interval.right
results[t,:,2]=iv
all_nodes(tree, samples, results)
if t==0:
length_dist[:,0,t]=0
else:
length_dist[:, 0, t] = length_dist[:,1,t-1]
if(iv < map["Position(bp)"][0]):
continue
map_row=map.iloc[find_nearest(map['Position(bp)'], iv),:]
x=(((float(iv) - float(map_row["Position(bp)"]))/1000000)*float(map_row["Rate(cM/Mb)"]))+float(map_row["Map(cM)"])
length_dist[:,3,t] = x
for sample in range(num_samples):
path=results[t,sample,0]
softmax=results[t,sample,1]
progress_bar.update()
np.savez_compressed(str(args.out)+"_painted.npz", paths=results)
np.savez_compressed(str(args.out)+"_intervals.npz", length_dist)
progress_bar.close()