-
Notifications
You must be signed in to change notification settings - Fork 8
/
TreeTest.drw
238 lines (211 loc) · 9 KB
/
TreeTest.drw
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
##
# Script to run the species tree discordance test
#
# input arguments:
# refset_path path to reference dataset
# project_db path to predictions in darwin db format
# title name of the method which is evaluated
# problem problem instance of tree benchmark, i.e. clade name
# treebuilder LSTree (or BIONJ)
# out_dir directory where output is written to. must exist
# assessment_fname directory where the assessment file should be written. must exist
# community_id community id
#
# Initially written: Adrian Altenhoff, Dec 2009
# rewritten for QfO: Adrian Altenhoff, Jun 2011
# rewritten for OpenEBench: Adrian Altenhoff, Jun 2019
Set(printgc=false): printlevel := 2;
SetRandSeed();
CreateDayMatrices();
if not assigned(refset_path) then
error('refset_path not assigned');
fi:
if not assigned(community_id) or not assigned(assessment_fname) or not assigned(out_dir) then
error('community_id, assessment_fname and out_dir all must be defined');
fi:
if not member(treebuilder, {'LSTree','BIONJ'}) then
error('unexpected treebuilder method: '.treebuilder);
fi;
prob_short := lowercase(problem[1..3]);
prob_short[1] := uppercase(prob_short[1]);
prob_path := refset_path.'/TreeCat_'.prob_short.'.drw';
if not FileExists(prob_path) then
error(sprintf('problem file "%s" does not exist. Wrong problem parameter?', prob_path));
fi:
ReadProgram(prob_path); # this loads the 'speciestree', 'catBins', 'MAX_NR_TREES' and 'missThreshold'
nrBins := length(catBins);
catBinsNr := [seq({seq(GenomeNrFromCode(g), g=catBins[i])}, i=1..nrBins)];
# lookup table for a genome to which bin it belongs (if any)
orgNr2Bin := table(0);
for i to nrBins do for z in catBinsNr[i] do orgNr2Bin[z] := i; od od:
SeqDB := ReadDb( refset_path.'/ServerIndexed.db');
FindCases := proc()
global DB:
cases := [];
nr_orthologs := nr_samplings := 0;
for rootGenome in catBins[1] do
ran := GenomeRange(rootGenome):
for eNr from ran[1] to ran[2] do
assert( orgNr2Bin[GenomeNrFromENr(eNr)]=1 );
miss := 0;
nr_samplings := nr_samplings + 1;
vps := ParseLongList(SearchTag('VP', Entry(eNr)));
vpCat := CreateArray(1..nrBins,[]):
vpCat[1] := eNr;
for vp in vps do
bin := orgNr2Bin[ GenomeNrFromENr(vp,dataset) ]:
if bin>1 then
vpCat[bin] := append(vpCat[bin], vp);
nr_orthologs := nr_orthologs + 1;
fi:
od:
for i from 2 to nrBins do
if length(vpCat[i])>0 then
vpCat[i] := vpCat[i, Rand(1..length(vpCat[i]))];
else
miss := miss + 1;
vpCat[i] := 0;
fi:
od:
# check if we're still below the missing lineage limit,
# otherwise break the loop and go on with the next candidate
# protein.
if miss <= missThreshold then
cases := append(cases, vpCat):
fi:
od:
od:
Logger( sprintf('nr of cases: %d, nr of samplings: %d', length(cases), nr_samplings), 'INFO');
return(cases, nr_orthologs, nr_samplings):
end:
InferDistTree := proc(D, V, labs)
if treebuilder='LSTree' then
tree := LeastSquaresTree(D, V, labs);
elif treebuilder='BIONJ' then
treeRes := BioNJ(D, labs);
tree := treeRes['Tree'];
fi:
return(tree);
end:
ComputeCongruenceStat := proc(cases:list, title)
global DB, Ndone:
RFstat := Stat('RobinsonFoulds - '.title);
IdentStat := Stat('Fraction Incorrect Trees - '.title);
rawDat := []:
DB := SeqDB:
cErr := Counter('# errors in PhylogeneticTree');
tot_nr_trees := length(cases);
if not type(Ndone, integer) then Ndone := 0 fi:
tLast := 0; t0 := time();
for cas in cases do
seqs := labs := [];
for i to nrBins do if cas[i]>0 then
seqs := append(seqs, Sequence(Entry(cas[i])));
labs := append(labs, i);
fi od:
nseq := length(seqs):
msa := traperror(MafftMSA(seqs)):
if msa=lasterror then cErr+1; next fi:
D := CreateArray(1..nseq,1..nseq):
V := CreateArray(1..nseq,1..nseq):
for i to nseq do for j from i+1 to nseq do
dps := EstimatePam(msa[AlignedSeqs,i],msa[AlignedSeqs,j],DMS):
D[i,j] := D[j,i] := dps[2];
V[i,j] := V[j,i] := dps[3];
od od:
genetree := traperror( InferDistTree(D,V,labs) ):
if genetree=lasterror then cErr+1; next fi;
pruned_st := PruneTree(copy(speciestree), labs);
rfdist := RobinsonFoulds([genetree, pruned_st])[1,2];
RFstat + rfdist;
IdentStat + If(rfdist>0,1,0);
for tree in [genetree, pruned_st] do for l in Leaves(tree) do
l['Label'] := cas[l['Label']]:
od od:
rawDat := append(rawDat, [genetree, pruned_st, rfdist]);
Ndone := Ndone + 1;
if time()-tLast > 30 then
t := Ndone/tot_nr_trees;
msg := sprintf( 'Finished %d / %d (%.1f%%) trees in %.1f min. '.
'Estimated remaining time: %.1fmin\n',
Ndone, tot_nr_trees, 100*t, (time()-t0)/60, (1-t)/t*(time()-t0)/60 );
fi;
od:
Logger( sprintf('TreeTest result for %s:\n %A\n %A',
title, RFstat, cErr), 'INFO');
return( [RFstat, rawDat, IdentStat] );
end:
StoreRawData := proc(raw_data, name, fname_)
fname := fname_;
if length(fname) > 4 and fname[-3..-1] = '.gz' then
fname := fname[1..-4];
do_gzip := true;
else do_gzip := false fi:
OpenWriting(fname);
printf('# Species Tree Discordance benchmark results\n');
printf('# Reported are inferred gene tree and expected species tree (both in\n');
printf('# newick format) and the normalised Robinson-Foulds distance between them\n');
printf('# Computing timestamp: %s\n', date());
printf('# Project <TAB> gene tree <TAB> species tree <TAB> RF distance\n');
for z in raw_data do
for k to 2 do for l in Leaves(z[k]) do
oE := l['Label'];
if not type(oE, integer) then next fi:
l['Label'] := ENr2XRef(oE);
od od:
printf('%s\t%s\t%s\t%f\n', name, Tree_Newick(z[1]),
Tree_Newick(z[2]), z[3]);
od:
OpenWriting(previous);
if do_gzip then CallSystem('gzip -9f '.fname); fi:
end:
StoreResult := proc(fn:string, data)
OpenWriting(fn): prints(json(data)): OpenWriting(previous);
end:
projDB := ReadDb(project_db);
title_id := ReplaceString(' ','-', ReplaceString('_', '-', title));
challenge := 'STD_'.problem:
hash_of_cur_proj := hash_sha2([problem, project_db, treebuilder]);
raw_out_fn := sprintf('%s_%s_%a_raw.txt.gz', challenge, title_id, hash_of_cur_proj);
casesAndCnts := FindCases();
cases := casesAndCnts[1];
nr_orthologs := casesAndCnts[2];
nr_samplings := casesAndCnts[3];
nr_trees := length(cases);
# limit nr of gene tree cases to compute to max,
# but keeping info on how many we found in total
cases := If(nr_trees > MAX_NR_TREES, Shuffle(cases)[1..MAX_NR_TREES], cases):
# compute gene trees and their congruence to the species tree
compRes := ComputeCongruenceStat(cases, title):
RFstat := compRes[1]; raw_data := compRes[2]; IdentStat := compRes[3];
stderr_nr_trees := 1.96 * sqrt(nr_trees/nr_samplings * (1 - nr_trees/nr_samplings) * nr_samplings);
assessments := [AssessmentDataset(community_id, challenge, title, 'NR_ORTHOLOGS', nr_orthologs, 0),
AssessmentDataset(community_id, challenge, title, 'NR_COMPLETED_TREE_SAMPLINGS', nr_trees, stderr_nr_trees),
AssessmentDataset(community_id, challenge, title, 'RF_DISTANCE', RFstat['Mean'], RFstat['StdErr']),
AssessmentDataset(community_id, challenge, title, 'FRAC_INCORRECT_TREES', IdentStat['Mean'], IdentStat['StdErr'])];
result := table():
result['problem'] := problem;
result['treebuilder'] := treebuilder;
recall_nr_orth := table(): recall_sampled := table():
recall_nr_orth['name'] := 'Number of predicted ortholog pairs';
recall_nr_orth['value'] := nr_orthologs;
recall_nr_orth['stderr'] := 0;
recall_sampled['name'] := 'Number of completed tree samplings';
recall_sampled['value'] := nr_trees;
recall_sampled['stderr'] := stderr_nr_trees;
result['recall_measures'] := [recall_sampled, recall_nr_orth];
prec_rf := table(): prec_id := table():
prec_rf['name'] := 'Avg RobinsonFoulds distance';
prec_rf['value'] := RFstat['Mean'];
prec_rf['stderr'] := RFstat['StdErr'];
prec_id['name'] := 'Avg fraction of incorrect trees';
prec_id['value'] := IdentStat['Mean'];
prec_id['stderr'] := IdentStat['StdErr'];
result['precision_measures'] := [prec_rf, prec_id]:
result['raw_data_fn'] := raw_out_fn:
result['nr_samplings'] := nr_samplings;
result['participant'] := title;
StoreRawData(raw_data, title, out_dir.'/'.result['raw_data_fn']):
#StoreResult(sprintf('%s/%s_%s.json', out_dir, challenge, title_id), result);
StoreResult(assessment_fname, assessments);
done;