-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdata_generation.py
367 lines (325 loc) · 13.9 KB
/
data_generation.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
# data generator code for training CNN
import sys
import numpy as np
import tensorflow as tf
import msprime
import tskit
import multiprocessing
import warnings
from attrs import define,field
from read_input import *
from process_input import *
@define
class DataGenerator(tf.keras.utils.Sequence):
"Generates data for Keras"
list_IDs: list
targets: dict
trees: dict
num_snps: int
min_n: int
max_n: int
batch_size: int
mu: float
threads: int
shuffle: bool
rho: float
baseseed: int
recapitate: bool
mutate: bool
crop: float
sampling_width: float
edge_width: dict
phase: int
polarize: int
sample_widths: dict
genos: dict
preprocessed: bool
num_reps: int
empirical_locs: list
def __attrs_post_init__(self):
"Initialize a few things"
self.on_epoch_end()
np.random.seed(self.baseseed)
warnings.simplefilter("ignore", msprime.TimeUnitsMismatchWarning) # (recapitate step)
def __len__(self):
"Denotes the number of batches per epoch"
return int(np.floor(len(self.list_IDs) / self.batch_size))
def __getitem__(self, index):
"Generate one batch of data"
# Generate indexes of the batch
indexes = self.indexes[index * self.batch_size : (index + 1) * self.batch_size]
# Find list of IDs
list_IDs_temp = [self.list_IDs[k] for k in indexes]
# Generate data
X, y = self.__data_generation(list_IDs_temp)
return X, y
def on_epoch_end(self):
"Updates indexes after each epoch"
self.indexes = np.arange(len(self.list_IDs))
if self.shuffle == True:
np.random.shuffle(self.indexes)
def cropper(self, ts, W, sample_width, edge_width, alive_inds):
"Cropping the map, returning individuals inside sampling window"
cropped = []
left_edge = np.random.uniform(
low=edge_width, high=W - edge_width - sample_width
)
right_edge = left_edge + sample_width
bottom_edge = np.random.uniform(
low=edge_width, high=W - edge_width - sample_width
)
top_edge = bottom_edge + sample_width
for i in alive_inds:
ind = ts.individual(i)
loc = ind.location[0:2]
if (
loc[0] > left_edge
and loc[0] < right_edge
and loc[1] > bottom_edge
and loc[1] < top_edge
):
cropped.append(i)
return cropped
def unpolarize(self, snp, n):
"Change 0,1 encoding to major/minor allele. Also filter no-biallelic"
alleles = {}
for i in range(n * 2):
a = snp[i]
if a not in alleles:
alleles[a] = 0
alleles[a] += 1
if len(alleles) == 2:
new_genotypes = []
major, minor = list(set(alleles)) # set() gives random order
if alleles[major] < alleles[minor]:
major, minor = minor, major
for i in range(n * 2): # go back through and convert genotypes
a = snp[i]
if a == major:
new_genotype = 0
elif a == minor:
new_genotype = 1
new_genotypes.append(new_genotype)
else:
new_genotypes = False
return new_genotypes
def empirical_sample(self, ts, sampled_inds, n, N, W):
locs = np.array(self.empirical_locs)
np.random.shuffle(locs)
indiv_dict = {} # tracking which indivs have been picked up already
for i in sampled_inds:
indiv_dict[i] = 0
keep_indivs = []
for pt in range(n): # for each sampling location
dists = {}
for i in indiv_dict:
ind = ts.individual(i)
loc = ind.location[0:2]
d = ( (loc[0]-locs[pt,0])**2 + (loc[1]-locs[pt,1])**2 )**(0.5)
dists[d] = i # see what I did there?
nearest = dists[min(dists)]
ind = ts.individual(nearest)
loc = ind.location[0:2]
keep_indivs.append(nearest)
del indiv_dict[nearest]
return keep_indivs
def sample_ts(self, filepath, seed):
"The meat: load in and fully process a tree sequence"
# read input
ts = tskit.load(filepath)
np.random.seed(seed)
# grab map width and sigma from provenance
W = parse_provenance(ts, 'W')
if self.edge_width == 'sigma':
edge_width = parse_provenance(ts, 'sigma')
else:
edge_width = float(self.edge_width)
# recapitate
if self.recapitate == "True":
ts = recapitate(ts, self.rho, seed)
# crop map
if self.sampling_width != None:
sample_width = (float(self.sampling_width) * W) - (edge_width * 2)
else:
sample_width = np.random.uniform(
0, W - (edge_width * 2)
)
### for misspecification analysis only
# sample_width = np.random.uniform(0,40)
# sample_width = np.random.uniform(40,W-(edge_width*2))
###
n = np.random.randint(
self.min_n, self.max_n + 1
) # (excludes the max of the range)
alive_inds = []
for i in ts.individuals():
alive_inds.append(i.id)
sampled_inds = self.cropper(ts, W, sample_width, edge_width, alive_inds)
failsafe = 0
while (
len(sampled_inds) < n
): # keep looping until you get a map with enough samples
if self.sampling_width != None:
sample_width = (float(self.sampling_width) * W) - (edge_width * 2)
else:
sample_width = np.random.uniform(0, W - (edge_width * 2))
### for misspecification analysis only
# sample_width = np.random.uniform(0,40)
# sample_width = np.random.uniform(40,W-(edge_width*2))
###
n = np.random.randint(
self.min_n, self.max_n + 1
) # (excludes the max of the range)
failsafe += 1
if failsafe > 100:
print("\tnot enough samples, killed while-loop after 100 loops")
sys.stdout.flush()
exit()
sampled_inds = self.cropper(ts, W, sample_width, edge_width, alive_inds)
# sampling
if self.empirical_locs == []:
keep_indivs = np.random.choice(sampled_inds, n, replace=False)
else:
keep_indivs = self.empirical_sample(ts, sampled_inds, n, len(sampled_inds), W)
keep_nodes = []
for i in keep_indivs:
ind = ts.individual(i)
keep_nodes.extend(ind.nodes)
# simplify
ts = ts.simplify(keep_nodes)
# mutate
if self.num_reps == 1:
total_snps = self.num_snps
else:
total_snps = self.num_snps * 10 # arbitrary size of SNP table for bootstraps
if self.mutate == "True":
mu = float(self.mu)
ts = msprime.sim_mutations(
ts,
rate=mu,
random_seed=seed,
model=msprime.SLiMMutationModel(type=0),
keep=True,
)
counter = 0
while ts.num_sites < (total_snps * 2): # extra SNPs because a few are likely non-biallelic
counter += 1
mu *= 10
ts = msprime.sim_mutations(
ts,
rate=mu,
random_seed=seed,
model=msprime.SLiMMutationModel(type=0),
keep=True,
)
if counter == 10:
print("\n\nsorry, Dude. Didn't generate enough snps. \n\n")
sys.stdout.flush()
exit()
# grab spatial locations
sample_dict = {}
locs = []
for samp in ts.samples():
node = ts.node(samp)
indID = node.individual
if indID not in sample_dict:
sample_dict[indID] = 0
loc = ts.individual(indID).location[0:2]
locs.append(loc)
# find width of sampling area
locs = np.array(locs)
sampling_width = 0
for i in range(0,n-1):
for j in range(i+1,n):
d = ( (locs[i,0]-locs[j,0])**2 + (locs[i,1]-locs[j,1])**2 )**(0.5)
if d > sampling_width:
sampling_width = float(d)
# grab genos
geno_mat0 = ts.genotype_matrix()
# change 0,1 encoding to major/minor allele
if self.polarize == 2:
shuffled_indices = np.arange(ts.num_sites)
np.random.shuffle(shuffled_indices)
geno_mat1 = []
snp_counter = 0
snp_index_map = {}
for s in range(total_snps):
new_genotypes = self.unpolarize(geno_mat0[shuffled_indices[s]], n)
if new_genotypes != False: # if bi-allelic, add in the snp
geno_mat1.append(new_genotypes)
snp_index_map[shuffled_indices[s]] = int(snp_counter)
snp_counter += 1
while snp_counter < total_snps: # likely need to replace a few non-biallelic sites
s += 1
new_genotypes = self.unpolarize(geno_mat0[shuffled_indices[s]], n)
if new_genotypes != False:
geno_mat1.append(new_genotypes)
snp_index_map[shuffled_indices[s]] = int(snp_counter)
snp_counter += 1
geno_mat0 = []
sorted_indices = list(snp_index_map)
sorted_indices.sort()
for snp in range(total_snps):
geno_mat0.append(geno_mat1[snp_index_map[sorted_indices[snp]]])
geno_mat0 = np.array(geno_mat0)
# sample SNPs
else:
mask = [True] * total_snps + [False] * (ts.num_sites - total_snps)
np.random.shuffle(mask)
geno_mat0 = geno_mat0[mask, :]
# collapse genotypes, change to minor allele dosage (e.g. 0,1,2)
if self.phase == 1:
geno_mat1 = np.zeros((total_snps, n))
for ind in range(n):
geno_mat1[:, ind] += geno_mat0[:, ind * 2]
geno_mat1[:, ind] += geno_mat0[:, ind * 2 + 1]
geno_mat0 = np.array(geno_mat1) # (change variable name)
# sample SNPs for 'b' bootstrap replicates:
geno_mat_all = [] # this array will hold lots of pre-processed tensors from bootstrap reps
sample_width_all = []
for b in range(self.num_reps):
mask = [True] * self.num_snps + [False] * (total_snps - self.num_snps)
np.random.shuffle(mask)
geno_mat1 = geno_mat0[mask, :]
geno_mat2 = np.zeros((self.num_snps, self.max_n * self.phase)) # pad
geno_mat2[:, 0 : n * self.phase] = geno_mat1
geno_mat_all.append(geno_mat2)
sample_width_all.append(sampling_width)
return geno_mat_all, sample_width_all
def preprocess_sample_ts(self, geno_path):
"Seperate function for loading in pre-processed data"
# read input
geno_mat = np.load(geno_path)
return geno_mat
def __data_generation(self, list_IDs_temp):
"Generates data containing batch_size samples"
# Initialization
X1 = np.empty(
(self.batch_size*self.num_reps, self.num_snps, self.max_n * self.phase), dtype="int8"
) # genos
X2 = np.empty((self.batch_size*self.num_reps,)) # sample widths
y = np.empty((self.batch_size*self.num_reps), dtype=float) # targets
if self.preprocessed == False:
ts_list = []
for i, ID in enumerate(list_IDs_temp):
ts_list.append(self.trees[ID])
for rep in range(self.num_reps):
y[rep+(i*self.num_reps)] = self.targets[ID]
seeds = np.random.randint(1e9, size=(self.batch_size))
pool = multiprocessing.Pool(self.threads, maxtasksperchild=1)
batch = pool.starmap(
self.sample_ts, zip(ts_list, seeds)
)
# unpack the multiprocess output
for k in range(self.batch_size):
for r in range(self.num_reps):
est_index = r + (k*self.num_reps)
X1[est_index, :] = batch[k][0][r]
X2[est_index] = batch[k][1][r]
else:
for i, ID in enumerate(list_IDs_temp):
y[i] = self.targets[ID]
X2[i] = self.sample_widths[ID]
X1[i,:] = self.preprocess_sample_ts(self.genos[ID])
X = [X1, X2]
return (X, y)