-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevolve_main.c
396 lines (343 loc) · 12.6 KB
/
evolve_main.c
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/************************************************************
* HMMER - Biological sequence analysis with HMMs
* Copyright 1992-1995 Sean R. Eddy
*
* This source code is distributed under the terms of the
* GNU General Public License. See the files COPYING and
* GNULICENSE for details.
*
************************************************************/
/* evolve_main.c
* Build an evolved hmm from a starting alignment.
* Derived from build_main.c
*
* Fri Jun 24 15:57:41 1994
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef NEED_GETOPTH
#include <getopt.h>
#endif
#include "states.h"
#include "externs.h"
#include "squid.h"
#include "version.h"
char Alphabet[MAXABET]; /* ACGT, for instance */
int Alphabet_size; /* 4 or 20 */
int Alphabet_type; /* kDNA, kRNA, or kAmino */
#ifdef MEMDEBUG
#include "dbmalloc.h"
#endif
#define OPTIONS "dfhp:vwA:"
static char usage[] = "\
Usage: hmm-evolve [-options] <hmmfile output> <alignment file>\n\
where options are:\n\
-d : maximum discrimination (shepherd) model\n\
-f : save hmm in flat text format instead of binary\n\
-h : print brief help on usage\n\
-p <scale>: set evolution scale; default 1.0\n\
-v : weighted maximum likelihood (Voronoi rule)\n\
-w : weighted maximum likelihood (Sonnhammer rule)\n\
-A <prior>: set architectural prior to <prior> (0-1.0)\n";
static char banner[] = "\
hmm-evolve: hidden Markov model construction from alignment,\n\
with simulated evolution";
int
main(int argc, char **argv)
{
struct hmm_struc *hmm; /* calculated hidden Markov model */
struct hmm_struc *newhmm; /* tmp or evolved model */
struct shmm_s *shmm; /* HMM in search form */
struct prior_s *prior; /* prior HMM model configuration */
char **aseqs; /* aligned sequences */
AINFO ainfo; /* info for aseqs */
int nseqs; /* number of aseqs */
char *seqfile; /* sequence file */
int format; /* format of sequence file */
char *hmmfile; /* OUTPUT: learned hmm */
FILE *hmmfp; /* OUTPUT: pointer to open hmmfile */
FILE *mxfp; /* ptr to subst matrix file */
int idx; /* counter for sequences */
double bmx[1][20][20]; /* base substitution matrices */
struct trace_s **tr; /* fake tracebacks of model/aseq alignments */
double convergence_thresh; /* convergence threshold for shepherd rules */
double converge_criterion;
double weighted_average;
float score;
float tot_score;
int iteration;
float worstscore; /* worst current score */
float bestscore; /* best current score */
float sqsum; /* for calculating std. dev. of scores */
double pamscale; /* evolution scaling factor */
float *wt; /* array of sequence weights */
float randomseq[MAXABET]; /* random seq model, frequencies */
float mpri;
int save_binary;
double damp_factor; /* damping factor for shepherd rules */
enum strategy_e { NORMAL, MINUSQ, ERIK_WEIGHT, VORONOI } model_style;
int optc;
extern char *optarg; /* for getopt() */
extern int optind; /* for getopt() */
/***********************************************
* Parse command line
***********************************************/
save_binary = TRUE;
model_style = NORMAL;
damp_factor = 0.99;
convergence_thresh = 0.001;
pamscale = 1.0;
mpri = 0.85;
while ((optc = getopt(argc, argv, OPTIONS)) != -1)
switch (optc) {
case 'd': model_style = MINUSQ; break;
case 'f': save_binary = FALSE; break;
case 'p': pamscale = atof(optarg); break;
case 'v': model_style = VORONOI; break;
case 'w': model_style = ERIK_WEIGHT; break;
case 'A': mpri = atof(optarg); break;
case 'h':
printf("%s\n version %s, %s\n\n%s\n",
banner, RELEASE, RELEASEDATE, usage);
exit(0);
default:
Die(usage);
}
if (argc - optind != 2) Die("Incorrect number of arguments.\n%s\n", usage);
hmmfile = argv[argc-2];
seqfile = argv[argc-1];
sre_srandom(time(0));
/***********************************************
* Get sequence data
***********************************************/
if (! SeqfileFormat(seqfile, &format, NULL))
switch (squid_errno) {
case SQERR_NOFILE: Die("Alignment file %s could not be opened for reading", seqfile);
case SQERR_FORMAT:
default: Die("Failed to determine format of sequence file %s", seqfile);
}
/* read the training seqs from file */
if (! ReadAlignment(seqfile, format, &aseqs, &nseqs, &ainfo))
Die("Failed to read aligned sequence file %s", seqfile);
for (idx = 0; idx < nseqs; idx++)
s2upper(aseqs[idx]);
if (! DetermineAlphabet(aseqs, nseqs))
Die("Failed to determine alphabet used in seqs in %s", seqfile);
DefaultRandomModel(randomseq);
DefaultSimplePrior(&prior);
/***********************************************
* Create the model
***********************************************/
printf("%s\n version %s, %s\n", banner, RELEASE, RELEASEDATE);
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf( "Training alignment: %s\n", seqfile);
printf( "Number of sequences: %d\n", nseqs);
printf( "Model output to: %s\n", hmmfile);
printf( "Model construction strategy: ");
switch (model_style) {
case NORMAL: puts("Max likelihood"); break;
case ERIK_WEIGHT: puts("Weighted ML (Sonnhammer rule)"); break;
case VORONOI: puts("Weighted ML (Voronoi rule)"); break;
case MINUSQ: puts("Shepherd (1-q rule)"); break;
default: Die("No such strategy");
}
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
if (model_style == ERIK_WEIGHT)
{
SonnhammerWeights(aseqs, nseqs, ainfo.alen, &wt);
for (idx = 0; idx < nseqs; idx++)
{
ainfo.sqinfo[idx].weight = wt[idx];
ainfo.sqinfo[idx].flags |= SQINFO_WGT;
}
free(wt);
}
else if (model_style == VORONOI)
{
printf("Calculating Voronoi weights. Be patient... this is slow...\n");
VoronoiWeights(aseqs, nseqs, ainfo.alen, &wt);
printf("OK, done.\n");
for (idx = 0; idx < nseqs; idx++)
{
ainfo.sqinfo[idx].weight = wt[idx];
ainfo.sqinfo[idx].flags |= SQINFO_WGT;
}
free(wt);
}
/* Normal or weighted model.
* Built by maximum likelihood model construction.
*/
if (model_style == NORMAL ||
model_style == ERIK_WEIGHT ||
model_style == VORONOI)
{
if (! Maxmodelmaker(aseqs, &ainfo, nseqs, prior, randomseq, mpri, &hmm, &tr))
Die("Maxmodelmaker failed");
PriorifyHMM(hmm, prior);
Renormalize(hmm);
}
/* Shepherd model, original (1-q) training rule
* Iterative re-weighting.
*/
else if (model_style == MINUSQ)
{
double qscore, weightsum;
if (! Maxmodelmaker(aseqs, &ainfo, nseqs, prior, randomseq, mpri, &hmm, &tr))
Die("Maxmodelmaker failed");
PriorifyHMM(hmm, prior);
Renormalize(hmm);
shmm = AllocSearchHMM(hmm->M);
printf("%10s %10s %12s\n", " iteration", " qscore ", "convergence");
printf("---------- ---------- ------------\n");
weighted_average = 0.;
iteration = 0;
while (1) /* iterate until we converge */
{
/* Calculate log-odds probabilities that each sequence matches the
* current model.
*/
qscore = 0.0;
MakeSearchHMM(hmm, randomseq, shmm);
for (idx = 0; idx < nseqs; idx++)
{
TraceScore(shmm, aseqs[idx], tr[idx], &score);
qscore += 1.0 / (1.0 + EXP2(score));
ainfo.sqinfo[idx].weight = 1.0 / (1.0 + EXP2(score));
ainfo.sqinfo[idx].flags |= SQINFO_WGT;
}
/* Normalize the weights so that they add up to the number of
* training sequences again.
*/
weightsum = 0.;
for (idx = 0; idx < nseqs; idx++)
weightsum += ainfo.sqinfo[idx].weight;
for (idx = 0; idx < nseqs; idx++)
ainfo.sqinfo[idx].weight = nseqs * ainfo.sqinfo[idx].weight / weightsum;
/* Recount the sequences into a counts-based model, using
* new weights
*/
newhmm = AllocHMM(hmm->M);
for (idx = 0; idx < nseqs; idx++)
TraceCount(newhmm, aseqs[idx], ainfo.sqinfo[idx].weight, tr[idx]);
PriorifyHMM(newhmm, prior);
Renormalize(newhmm);
/* Damp out instability
*/
HybridizeHMMs(newhmm, hmm, damp_factor);
/* Exchange newhmm for old hmm, free old
*/
FreeHMM(hmm);
hmm = newhmm;
/* Check for convergence.
* This rule checks the current negative log-odds score against
* a rolling average of the previous scores. The rolling average
* damps out slight oscillations which appear as we approach a
* solution.
*/
qscore = -LOG2(qscore);
weighted_average = (9. * weighted_average + qscore) / 10.;
converge_criterion = fabs((weighted_average - qscore) / weighted_average);
iteration++;
printf(" %4d %10.2f %12g\n",
iteration, qscore, converge_criterion);
if (converge_criterion < convergence_thresh) break;
}
FreeSearchHMM(shmm);
puts("\n");
}
/* Evolve the HMM
*/
/* need HMM in counts form */
newhmm = AllocHMM(hmm->M);
for (idx = 0; idx < nseqs; idx++)
TraceCount(newhmm, aseqs[idx], ainfo.sqinfo[idx].weight, tr[idx]);
FreeHMM(hmm);
hmm = newhmm;
PriorifyHMM(hmm, prior);
/* get the substitution matrices */
if ((mxfp = fopen("PAM2.smx", "r")) == NULL)
Die("file open failed for matrix PAM2.smx");
if (! ParseSubstitutionMatrix(mxfp, bmx[0]))
Die("parse failed");
fclose(mxfp);
/* evolve the hmm */
EvolveHMM(hmm, bmx, 1, pamscale, &newhmm);
/* convert to probabilities */
Renormalize(newhmm);
/* Calculate the final average scores.
*/
PriorifyHMM(hmm, prior);
Renormalize(hmm);
MakeSearchHMM(hmm, randomseq, shmm);
TraceScore(shmm, aseqs[0], tr[0], &worstscore);
tot_score = bestscore = worstscore;
sqsum = tot_score * tot_score;
for (idx = 1; idx < nseqs; idx++)
{
TraceScore(shmm, aseqs[idx], tr[idx], &score);
tot_score += score;
sqsum += score * score;
if (score > bestscore) bestscore = score;
if (score < worstscore) worstscore = score;
}
printf("\nUnevolved hidden Markov model (length %d)\n", hmm->M);
printf("Average score: %10.2f bits\n",
tot_score / (double) nseqs);
printf("Minimum score: %10.2f bits\n", worstscore);
printf("Maximum score: %10.2f bits\n", bestscore);
printf("Std. deviation: %10.2f bits\n",
sqrt((sqsum - (tot_score * tot_score / (double) nseqs))
/ ((double) nseqs - 1.0)));
printf("Information content: %10.2f bits\n",
HMMInfoContent(hmm, shmm));
/* And now for the evolved model. We can free
* the traces on this pass
*/
MakeSearchHMM(newhmm, randomseq, shmm);
TraceScore(shmm, aseqs[0], tr[0], &worstscore);
tot_score = bestscore = worstscore;
sqsum = tot_score * tot_score;
for (idx = 1; idx < nseqs; idx++)
{
TraceScore(shmm, aseqs[idx], tr[idx], &score);
tot_score += score;
sqsum += score * score;
if (score > bestscore) bestscore = score;
if (score < worstscore) worstscore = score;
FreeTrace(tr[idx]);
}
printf("\nEvolved hidden Markov model (length %d)\n", hmm->M);
printf("Average score: %10.2f bits\n",
tot_score / (double) nseqs);
printf("Minimum score: %10.2f bits\n", worstscore);
printf("Maximum score: %10.2f bits\n", bestscore);
printf("Std. deviation: %10.2f bits\n",
sqrt((sqsum - (tot_score * tot_score / (double) nseqs))
/ ((double) nseqs - 1.0)));
printf("Information content: %10.2f bits\n",
HMMInfoContent(newhmm, shmm));
/* Save the HMM
*/
if ((hmmfp = fopen(hmmfile, "wb")) == NULL)
Die("Failed to open %s for writing hmm result\n%s\n", hmmfile, usage);
if (save_binary)
{
if (! WriteBinaryHMM(hmmfp, newhmm))
Die("failed to save hmm to %s\n", hmmfile);
}
else
{
if (! WriteHMM(hmmfp, newhmm))
Die("failed to save hmm to %s\n", hmmfile);
}
fclose(hmmfp);
printf("\nEvolved HMM written to file %s\n", hmmfile);
FreeHMM(hmm);
FreeHMM(newhmm);
FreeSearchHMM(shmm);
FreePrior(prior);
FreeAlignment(aseqs, nseqs, &ainfo);
return 0;
}