-
Notifications
You must be signed in to change notification settings - Fork 1
/
TreeWAS.snakefile
292 lines (230 loc) · 9.05 KB
/
TreeWAS.snakefile
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
import os
#################################################################################
# FUNCTIONS #
#################################################################################
def OPJ(*args):
path = os.path.join(*args)
return os.path.normpath(path)
#################################################################################
# GLOBALS #
#################################################################################
PROJECT_NAME = 'phenores'
PROJECT_DIR = OPJ(os.path.dirname(__file__), os.pardir)
FOLDS=range(5)
DATASETS='gene genome'.split()
#DATASETS='gene genome kmer dsm'.split()
METADATAFILE="data/interim/streptomycin_population_groups.csv"
#METADATAFILE="data/interim/test_pop.csv"
#################################################################################
# RULES #
#################################################################################
rule all:
input:
expand("data/interim/treewas/{fold}/{ds}/treewas_results.rdata", fold=FOLDS, ds=DATASETS)
rule binary:
# Convert roary/piggy outputs to binary matrix
input:
METADATAFILE,
"data/interim/roary/gene_presence_absence.csv",
"data/interim/roary/IGR_presence_absence.csv",
output:
"data/interim/roary/gene_presence_absence_matrix.tsv",
"data/interim/roary/gene_and_igr_presence_absence_matrix.tsv",
run:
import pandas as pd
# Rtabs in Piggy are missing cluster names, so we will do it the hard way
genedf = pd.read_csv(input[1], sep=',', header=0, index_col=0, na_values="", dtype=str)
igrdf = pd.read_csv(input[2], sep=',', header=0, index_col=0, na_values="", dtype=str)
sampledf = pd.read_csv(input[0], sep=',', header=0, index_col=0)
genemat = genedf[sampledf["sample"]]
genemat = genemat.applymap(lambda x: 0 if pd.isna(x) else 1)
genemat = genemat.T
igrmat = igrdf[sampledf["sample"]]
igrmat = igrmat.applymap(lambda x: 0 if pd.isna(x) else 1)
igrmat = igrmat.T
genomemat = pd.concat([genemat, igrmat], axis=1)
genemat.to_csv(output[0], sep='\t')
genomemat.to_csv(output[1], sep='\t')
rule filter_genes:
# Filter original gene_presence_absence_matrix.csv to include only relevent training genomes
input:
METADATAFILE,
"data/interim/roary/gene_presence_absence_matrix.csv"
output:
expand("data/interim/cv/{fold}/gene/features.tsv", fold=FOLDS)
run:
from Bio import SeqIO
from contextlib import ExitStack
import pandas as pd
import numpy as np
import os
# Load groups
df = pd.read_csv(input[0], sep=',', header=0, index_col=0)
trainingset = {}
for r in df.itertuples():
g = r.sample
ts = r.fold//2
trainingset[g] = ts
# Open files for writing
with ExitStack() as stack:
files = [stack.enter_context(open(fname, 'w')) for fname in output]
with open(input[1], 'r') as infh:
# Add headers
header = infh.readline()
for fh in files:
fh.write(header)
# Add rest to correct file
for line in infh:
sample = line.split('\t', 1)[0]
if sample in trainingset:
ds = trainingset[sample]
for i in FOLDS:
if i != ds:
fh = files[i]
fh.write(line)
rule filter_genomes:
# Filter original gene_presence_absence_matrix.csv to include only relevent training genomes
input:
METADATAFILE,
"data/interim/roary/gene_and_igr_presence_absence_matrix.csv"
output:
expand("data/interim/cv/{fold}/genome/features.tsv", fold=FOLDS)
run:
from Bio import SeqIO
from contextlib import ExitStack
import pandas as pd
import numpy as np
import os
# Load groups
df = pd.read_csv(input[0], sep=',', header=0, index_col=0)
trainingset = {}
for r in df.itertuples():
g = r.sample
ts = r.fold//2
trainingset[g] = ts
# Open files for writing
with ExitStack() as stack:
files = [stack.enter_context(open(fname, 'w')) for fname in output]
with open(input[1], 'r') as infh:
# Add headers
header = infh.readline()
for fh in files:
fh.write(header)
# Add rest to correct file
for line in infh:
sample = line.split('\t', 1)[0]
if sample in trainingset:
ds = trainingset[sample]
for i in FOLDS:
if i != ds:
fh = files[i]
fh.write(line)
rule filter_pheno:
# Filter original resistance phenotype data to include only relevent training genomes
input:
METADATAFILE,
output:
expand("data/interim/cv/{fold}/phenotypes.tsv", fold=FOLDS)
run:
from Bio import SeqIO
from contextlib import ExitStack
import pandas as pd
import numpy as np
import os
# Load groups
df = pd.read_csv(input[0], sep=',', header=0, index_col=0)
trainingset = {}
pheno = {}
for r in df.itertuples():
g = r.sample
ts = r.fold//2
trainingset[g] = ts
pheno[g] = r.resistant
# Open files for writing
with ExitStack() as stack:
files = [stack.enter_context(open(fname, 'w')) for fname in output]
for fh in files:
fh.write("sample\tresistant\n")
for g in trainingset:
ds = int(trainingset[g])
for i in FOLDS:
if i != ds:
fh = files[i]
fh.write("{}\t{}\n".format(g, pheno[g]))
rule filter_aln:
# Filter original core_gene_alignment.aln to include only relevent training genomes
input:
METADATAFILE,
"data/interim/roary/core_gene_alignment.aln"
output:
expand("data/interim/treewas/{fold}/train_core.aln", fold=FOLDS)
run:
from Bio import SeqIO
import pandas as pd
import numpy as np
import os
# Load groups
df = pd.read_csv(input[0], sep=',', header=0, index_col=0)
# Load sequences
sequences = {}
for seq_record in SeqIO.parse(input[1], "fasta"):
sequences[seq_record.id] = seq_record.seq
# Output to relevent folders
for fold in FOLDS:
# Make directory
d = OPJ("data","interim","treewas",str(fold))
if not os.path.exists(d):
os.makedirs(d)
# Output training fasta file
trainfile=OPJ(d, 'train_core.aln')
with open(trainfile, 'w') as trainfh:
for r in df.itertuples():
g = r.sample
if r.fold < fold*2 or r.fold > fold*2+1:
# Training set
seq = sequences[g]
if not seq:
raise Exception("Missing sequence for genome {}".format(g))
trainfh.write(">{}\n{}\n".format(g, seq))
rule tree:
# Build phylogenetic tree
input:
"data/interim/treewas/{fold}/train_core.aln"
output:
"data/interim/treewas/{fold}/tree.nwk"
shell:
"FastTree -gtr -nt -nosupport -fastest -noml {input} > {output}"
# rule tree:
# # Build phylogenetic tree
# input:
# "data/interim/treewas/{fold}/train_core.aln"
# output:
# "data/interim/treewas/{fold}/tree.nwk"
# shell:
# "clearcut -k --DNA --alignment --in={input} --out={output}"
rule treewas_genes:
# Run treewas with gene presence / absence run
input:
"data/interim/cv/{fold}/gene/features.csv",
"data/interim/cv/{fold}/phenotypes.csv",
"data/interim/cv/{fold}/tree.nwk"
params:
mem=48
output:
"data/interim/cv/{fold}/gene/treewas/treewas_results.rdata",
"data/interim/cv/{fold}/gene/treewas/treewas_plots.pdf"
script:
"src/gwas/run_treewas.R"
rule treewas_genomes:
# Run treewas with gene presence / absence run
input:
"data/interim/cv/{fold}/genome/features.csv",
"data/interim/cv/{fold}/phenotypes.csv",
"data/interim/cv/{fold}/tree.nwk",
params:
mem=48
output:
"data/interim/cv/{fold}/genome/treewas/treewas_results.rdata",
"data/interim/cv/{fold}/genome/treewas/treewas_plots.pdf"
script:
"src/gwas/run_treewas.R"