Debian Codegraph @

hmmer/src/p7_hmm.c

raw symbols SCIP
1 /* The Plan7 core HMM data structure.
2 *
3 * Contents:
4 * 1. The P7_HMM object: allocation, initialization, destruction.
5 * 2. Convenience routines for setting fields in an HMM.
6 * 3. Renormalization and rescaling counts in core HMMs.
7 * 4. Debugging and development code.
8 * 5. Other routines in the API.
9 * 6. Unit tests.
10 * 7. Test driver.
11 */
12 #include <p7_config.h>
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <time.h>
18
19 #include "easel.h"
20 #include "esl_alphabet.h"
21 #include "esl_vectorops.h"
22 #include "esl_random.h"
23 #include "esl_dirichlet.h"
24
25 #include "hmmer.h"
26
27
28
29
30 /*****************************************************************
31 *# 1. The P7_HMM object: allocation, initialization, destruction.
32 *****************************************************************/
33
34 /* Function: p7_hmm_Create()
35 * Synopsis: Allocate a new <P7_HMM>.
36 *
37 * Purpose: Allocate a <P7_HMM> of <M> nodes, for symbol
38 * alphabet <abc>, and return a pointer to it.
39 *
40 * The HMM only keeps a copy of the <abc> alphabet
41 * pointer. The caller is responsible for providing the
42 * alphabet, keeping it around while the HMM is in use,
43 * and (eventually) free'ing the alphabet when it's
44 * not needed any more. (Basically, just a step removed
45 * from keeping the alphabet as a global.)
46 *
47 * Throws: <NULL> on allocation failure.
48 */
49 P7_HMM *
50 p7_hmm_Create(int M, const ESL_ALPHABET *abc)
51 {
52 P7_HMM *hmm = NULL;
53
54 if ((hmm = p7_hmm_CreateShell()) == NULL) return NULL;
55 p7_hmm_CreateBody(hmm, M, abc);
56 return hmm;
57 }
58
59
60 /* Function: p7_hmm_CreateShell()
61 * Synopsis: Allocate the ``shell'' of a <P7_HMM>.
62 *
63 * Purpose: Allocate the shell of a <P7_HMM>: everything that
64 * doesn't depend on knowing the number of nodes M.
65 *
66 * HMM input (<hmmio.c>) uses two-step shell/body
67 * allocation because it has to read for a ways from the
68 * HMM file before it reads the model size M or the
69 * alphabet type.
70 *
71 * Returns: a pointer to the new <P7_HMM> on success.
72 *
73 * Throws: <NULL> on allocation failure.
74 */
75 P7_HMM *
76 p7_hmm_CreateShell(void)
77 {
78 P7_HMM *hmm = NULL;
79 int z;
80 int status;
81
82 ESL_ALLOC(hmm, sizeof(P7_HMM));
83 hmm->M = 0;
84 hmm->t = NULL;
85 hmm->mat = NULL;
86 hmm->ins = NULL;
87
88 hmm->name = NULL;
89 hmm->acc = NULL;
90 hmm->desc = NULL;
91 hmm->rf = NULL;
92 hmm->mm = NULL;
93 hmm->consensus = NULL;
94 hmm->cs = NULL;
95 hmm->ca = NULL;
96 hmm->comlog = NULL;
97 hmm->nseq = -1;
98 hmm->eff_nseq = -1.0;
99 hmm->max_length = -1;
100 hmm->ctime = NULL;
101 hmm->map = NULL;
102 hmm->checksum = 0;
103
104 for (z = 0; z < p7_NCUTOFFS; z++) hmm->cutoff[z] = p7_CUTOFF_UNSET;
105 for (z = 0; z < p7_NEVPARAM; z++) hmm->evparam[z] = p7_EVPARAM_UNSET;
106 for (z = 0; z < p7_MAXABET; z++) hmm->compo[z] = p7_COMPO_UNSET;
107
108 hmm->offset = 0;
109 hmm->flags = 0;
110 hmm->abc = NULL;
111 return hmm;
112
113 ERROR:
114 return NULL;
115 }
116
117 /* Function: p7_hmm_CreateBody()
118 * Synopsis: Allocate the ``body'' of a <P7_HMM>.
119 *
120 * Purpose: Given an allocated shell <hmm>, and a now-known number
121 * of nodes <M> and alphabet <abc>, allocate
122 * the remainder of it for that many nodes.
123 *
124 * Returns: <eslOK> on success.
125 *
126 * Throws: <eslEMEM> on allocation failure; in this case, the HMM
127 * is likely corrupted, and the caller should destroy it.
128 */
129 int
130 p7_hmm_CreateBody(P7_HMM *hmm, int M, const ESL_ALPHABET *abc)
131 {
132 int k;
133 int status;
134
135 hmm->abc = abc;
136 hmm->M = M;
137
138 /* level 1 */
139 ESL_ALLOC(hmm->t, (M+1) * sizeof(float *));
140 ESL_ALLOC(hmm->mat, (M+1) * sizeof(float *));
141 ESL_ALLOC(hmm->ins, (M+1) * sizeof(float *));
142 hmm->t[0] = NULL;
143 hmm->mat[0] = NULL;
144 hmm->ins[0] = NULL;
145
146 /* level 2 */
147 ESL_ALLOC(hmm->t[0], (p7H_NTRANSITIONS*(M+1)) * sizeof(float));
148 ESL_ALLOC(hmm->mat[0], (abc->K*(M+1)) * sizeof(float));
149 ESL_ALLOC(hmm->ins[0], (abc->K*(M+1)) * sizeof(float));
150 for (k = 1; k <= M; k++) {
151 hmm->mat[k] = hmm->mat[0] + k * hmm->abc->K;
152 hmm->ins[k] = hmm->ins[0] + k * hmm->abc->K;
153 hmm->t[k] = hmm->t[0] + k * p7H_NTRANSITIONS;
154 }
155
156 /* Enforce conventions on unused but allocated distributions, so
157 * Compare() tests succeed unless memory was corrupted.
158 */
159 if ((status = p7_hmm_Zero(hmm)) != eslOK) goto ERROR;
160 hmm->mat[0][0] = 1.0;
161 hmm->t[0][p7H_DM] = 1.0;
162
163 /* Optional allocation, status flag dependent */
164 if (hmm->flags & p7H_RF) ESL_ALLOC(hmm->rf, (M+2) * sizeof(char));
165 if (hmm->flags & p7H_MMASK) ESL_ALLOC(hmm->mm, (M+2) * sizeof(char));
166 if (hmm->flags & p7H_CONS) ESL_ALLOC(hmm->consensus, (M+2) * sizeof(char));
167 if (hmm->flags & p7H_CS) ESL_ALLOC(hmm->cs, (M+2) * sizeof(char));
168 if (hmm->flags & p7H_CA) ESL_ALLOC(hmm->ca, (M+2) * sizeof(char));
169 if (hmm->flags & p7H_MAP) ESL_ALLOC(hmm->map, (M+1) * sizeof(int));
170
171 return eslOK;
172
173 ERROR:
174 return status;
175 }
176
177
178 /* Function: p7_hmm_Destroy()
179 * Synopsis: Free a <P7_HMM>.
180 *
181 * Purpose: Frees both the shell and body of an <hmm>.
182 * Works even if the <hmm> is damaged (incompletely allocated)
183 * or even <NULL>.
184 *
185 * Note: Remember, leave reference pointers like abc, gm, and
186 * bg alone. These are under the application's control not ours.
187 *
188 * Returns: (void).
189 */
190 void
191 p7_hmm_Destroy(P7_HMM *hmm)
192 {
193 if (hmm == NULL) return;
194
195 if (hmm->mat) { if (hmm->mat[0]) free(hmm->mat[0]); free(hmm->mat); }
196 if (hmm->ins) { if (hmm->ins[0]) free(hmm->ins[0]); free(hmm->ins); }
197 if (hmm->t) { if (hmm->t[0]) free(hmm->t[0]); free(hmm->t); }
198
199 if (hmm->name) free(hmm->name);
200 if (hmm->acc) free(hmm->acc);
201 if (hmm->desc) free(hmm->desc);
202 if (hmm->rf) free(hmm->rf);
203 if (hmm->mm) free(hmm->mm);
204 if (hmm->consensus) free(hmm->consensus);
205 if (hmm->cs) free(hmm->cs);
206 if (hmm->ca) free(hmm->ca);
207 if (hmm->comlog) free(hmm->comlog);
208 if (hmm->ctime) free(hmm->ctime);
209 if (hmm->map) free(hmm->map);
210
211 free(hmm);
212 return;
213 }
214
215 /* Function: p7_hmm_CopyParameters()
216 * Synopsis: Copy parameters from one HMM to another.
217 *
218 * Purpose: Copy parameters of <src> to <dest>. The HMM <dest> must
219 * be allocated by the caller for the same
220 * alphabet and M as <src>.
221 *
222 * Both core and search model parameters are copied.
223 *
224 * No annotation is copied. This is because several
225 * annotation fields are variable-length strings that
226 * require individual allocations. The
227 * <p7_hmm_CopyParameters()> function is for cases where we
228 * have to repeatedly reset the parameters of a model - for
229 * example, in entropy weighting.
230 *
231 * Returns: <eslOK> on success.
232 */
233 int
234 p7_hmm_CopyParameters(const P7_HMM *src, P7_HMM *dest)
235 {
236 int k;
237 for (k = 0; k <= src->M; k++) {
238 esl_vec_FCopy(src->t[k], p7H_NTRANSITIONS, dest->t[k]);
239 esl_vec_FCopy(src->mat[k], src->abc->K, dest->mat[k]);
240 esl_vec_FCopy(src->ins[k], src->abc->K, dest->ins[k]);
241 }
242 return eslOK;
243 }
244
245 /* Function: p7_hmm_Clone()
246 * Synopsis: Make an exact duplicate of an HMM.
247 *
248 * Purpose: Duplicates an hmm.
249 *
250 * Note: does not duplicate the objects the HMM refers to,
251 * if any (profile, null model, or alphabet); only copies
252 * the reference pointers.
253 *
254 * Returns: a pointer to the duplicate.
255 *
256 * Throws: <NULL> on allocation failure.
257 */
258 P7_HMM *
259 p7_hmm_Clone(const P7_HMM *hmm)
260 {
261 int status;
262 P7_HMM *new = NULL;
263 int z;
264
265 if ((new = p7_hmm_Create(hmm->M, hmm->abc)) == NULL) goto ERROR;
266 p7_hmm_CopyParameters(hmm, new);
267
268 if ((status = esl_strdup(hmm->name, -1, &(new->name))) != eslOK) goto ERROR;
269 if ((status = esl_strdup(hmm->acc, -1, &(new->acc))) != eslOK) goto ERROR;
270 if ((status = esl_strdup(hmm->desc, -1, &(new->desc))) != eslOK) goto ERROR;
271
272 if ((hmm->flags & p7H_RF) && (status = esl_strdup(hmm->rf, -1, &(new->rf))) != eslOK) goto ERROR;
273 if ((hmm->flags & p7H_MMASK) && (status = esl_strdup(hmm->mm, -1, &(new->mm))) != eslOK) goto ERROR;
274 if ((hmm->flags & p7H_CONS) && (status = esl_strdup(hmm->consensus, -1, &(new->consensus))) != eslOK) goto ERROR;
275 if ((hmm->flags & p7H_CS) && (status = esl_strdup(hmm->cs, -1, &(new->cs))) != eslOK) goto ERROR;
276 if ((hmm->flags & p7H_CA) && (status = esl_strdup(hmm->ca, -1, &(new->ca))) != eslOK) goto ERROR;
277 if ((hmm->comlog != NULL) && (status = esl_strdup(hmm->comlog, -1, &(new->comlog))) != eslOK) goto ERROR;
278 if ((hmm->ctime != NULL) && (status = esl_strdup(hmm->ctime, -1, &(new->ctime))) != eslOK) goto ERROR;
279 if (hmm->flags & p7H_MAP) {
280 ESL_ALLOC(new->map, sizeof(int) * (hmm->M+1));
281 esl_vec_ICopy(hmm->map, hmm->M+1, new->map);
282 }
283 new->nseq = hmm->nseq;
284 new->eff_nseq = hmm->eff_nseq;
285 new->max_length = hmm->max_length;
286 new->checksum = hmm->checksum;
287
288 for (z = 0; z < p7_NEVPARAM; z++) new->evparam[z] = hmm->evparam[z];
289 for (z = 0; z < p7_NCUTOFFS; z++) new->cutoff[z] = hmm->cutoff[z];
290 for (z = 0; z < p7_MAXABET; z++) new->compo[z] = hmm->compo[z];
291
292 new->offset = hmm->offset;
293 new->flags = hmm->flags;
294 new->abc = hmm->abc;
295 return new;
296
297 ERROR:
298 if (new != NULL) p7_hmm_Destroy(new);
299 return NULL;
300 }
301
302
303 /* Function: p7_hmm_Zero()
304 * Synopsis: Set all parameters to zero (including model composition).
305 *
306 * Purpose: Zeroes all counts/probabilities fields in core model,
307 * including emissions, transitions, and model
308 * composition.
309 *
310 * Returns: <eslOK> on success.
311 */
312 int
313 p7_hmm_Zero(P7_HMM *hmm)
314 {
315 int k;
316
317 for (k = 0; k <= hmm->M; k++) {
318 esl_vec_FSet(hmm->t[k], p7H_NTRANSITIONS, 0.);
319 esl_vec_FSet(hmm->mat[k], hmm->abc->K, 0.);
320 esl_vec_FSet(hmm->ins[k], hmm->abc->K, 0.);
321 }
322 esl_vec_FSet(hmm->compo, p7_MAXABET, 0.);
323 return eslOK;
324 }
325
326
327
328 /* Function: p7_hmm_EncodeStatetype()
329 * Synopsis: Convert a state type string to internal code.
330 *
331 * Purpose: Converts state type string <typestring> case insensitively to
332 * an internal code, and returns the code. For example,
333 * <p7_hmm_DecodeStatetype("M")> returns <p7T_M>.
334 *
335 * If the string isn't recognized, returns <p7T_BOGUS>.
336 */
337 char
338 p7_hmm_EncodeStatetype(char *typestring)
339 {
340 if (strcasecmp(typestring, "M") == 0) return p7T_M;
341 else if (strcasecmp(typestring, "D") == 0) return p7T_D;
342 else if (strcasecmp(typestring, "I") == 0) return p7T_I;
343 else if (strcasecmp(typestring, "S") == 0) return p7T_S;
344 else if (strcasecmp(typestring, "N") == 0) return p7T_N;
345 else if (strcasecmp(typestring, "B") == 0) return p7T_B;
346 else if (strcasecmp(typestring, "E") == 0) return p7T_E;
347 else if (strcasecmp(typestring, "C") == 0) return p7T_C;
348 else if (strcasecmp(typestring, "T") == 0) return p7T_T;
349 else if (strcasecmp(typestring, "J") == 0) return p7T_J;
350 else if (strcasecmp(typestring, "X") == 0) return p7T_X;
351 else return p7T_BOGUS;
352 }
353
354 /* Function: p7_hmm_DecodeStatetype()
355 * Synopsis: Convert an internal state type code to a string.
356 *
357 * Purpose: Returns the state type in text, as a string of length 1
358 * (2 if you count <NUL>). For example, <p7_DecodeStatetype(p7T_S)>
359 * returns "S".
360 *
361 * Throws: an internal <eslEINVAL> exception if the code doesn't
362 * exist, and returns <NULL>.
363 */
364 char *
365 p7_hmm_DecodeStatetype(char st)
366 {
367 switch (st) {
368 case p7T_M: return "M";
369 case p7T_D: return "D";
370 case p7T_I: return "I";
371 case p7T_S: return "S";
372 case p7T_N: return "N";
373 case p7T_B: return "B";
374 case p7T_E: return "E";
375 case p7T_C: return "C";
376 case p7T_T: return "T";
377 case p7T_J: return "J";
378 case p7T_X: return "X";
379 default: break;
380 }
381 esl_exception(eslEINVAL, FALSE, __FILE__, __LINE__, "no such statetype code %d", st);
382 return NULL;
383 }
384
385
386
387
388 /*****************************************************************
389 * 2. Convenience routines for setting fields in an HMM.
390 *****************************************************************/
391
392 /* Function: p7_hmm_SetName()
393 * Synopsis: Set or change the name of an HMM.
394 *
395 * Purpose: Set or change the name of a Plan7 HMM to <name>.
396 * Any trailing whitespace (including newline) is chopped off.
397 *
398 * Returns: <eslOK> on success.
399 *
400 * Throws: <eslEMEM> on allocation error, and original name (if any)
401 * remains.
402 */
403 int
404 p7_hmm_SetName(P7_HMM *hmm, char *name)
405 {
406 int status;
407 void *tmp;
408 int n;
409
410 if (name == NULL) {
411 if (hmm->name != NULL) free(hmm->name);
412 hmm->name = NULL;
413 } else {
414 n = strlen(name);
415 ESL_RALLOC(hmm->name, tmp, sizeof(char)*(n+1));
416 strcpy(hmm->name, name);
417 if ((status = esl_strchop(hmm->name, n)) != eslOK) goto ERROR;
418 }
419 return eslOK;
420
421 ERROR:
422 return status;
423 }
424
425 /* Function: p7_hmm_SetAccession()
426 * Synopsis: Set or change the accession of an HMM.
427 *
428 * Purpose: Set or change the accession number of a Plan7 HMM to <acc>,
429 * and raise the <P7_ACC> flag. Trailing whitespace (including newline)
430 * is chopped.
431 *
432 * If <acc> is <NULL>, unset the HMM's accession (if any) and drop
433 * the <P7_ACC> flag.
434 *
435 * Returns: <eslOK> on success.
436 *
437 * Throws: <eslEMEM> on allocation error, and original name (if any)
438 * remains.
439 */
440 int
441 p7_hmm_SetAccession(P7_HMM *hmm, char *acc)
442 {
443 int status;
444 void *tmp;
445 int n;
446
447 if (acc == NULL) {
448 if (hmm->acc != NULL) free(hmm->acc);
449 hmm->acc = NULL;
450 hmm->flags &= ~p7H_ACC; /* legacy */
451 } else {
452 n = strlen(acc);
453 ESL_RALLOC(hmm->acc, tmp, sizeof(char)*(n+1));
454 strcpy(hmm->acc, acc);
455 if ((status = esl_strchop(hmm->acc, n)) != eslOK) goto ERROR;
456 hmm->flags |= p7H_ACC; /* legacy */
457 }
458 return eslOK;
459
460 ERROR:
461 return status;
462 }
463
464 /* Function: p7_hmm_SetDescription()
465 * Synopsis: Set or change the description line of an HMM.
466 *
467 * Purpose: Set or change the description line of a Plan7 HMM.
468 * Trailing whitespace (including newline) is chopped.
469 */
470 int
471 p7_hmm_SetDescription(P7_HMM *hmm, char *desc)
472 {
473 int status;
474 void *tmp;
475 int n;
476
477 if (desc == NULL)
478 {
479 if (hmm->desc != NULL) free(hmm->desc);
480 hmm->desc = NULL;
481 hmm->flags &= ~p7H_DESC; /* legacy */
482 }
483 else
484 {
485 n = strlen(desc);
486 ESL_RALLOC(hmm->desc, tmp, sizeof(char)*(n+1));
487 strcpy(hmm->desc, desc);
488 if ((status = esl_strchop(hmm->desc, n)) != eslOK) goto ERROR;
489 hmm->flags |= p7H_DESC; /* legacy */
490 }
491 return eslOK;
492
493 ERROR:
494 return status;
495 }
496
497 /* Function: p7_hmm_AppendComlog()
498 * Synopsis: Concatenate and append command line to the command line log.
499 *
500 * Purpose: Concatenate command line options and append as a new line in the
501 * command line log. Command line log is multiline, with each line
502 * ending in newline char, except for last line.
503 *
504 * Returns: <eslOK> on success.
505 *
506 * Throws: <eslEMEM> on allocation failure.
507 */
508 int
509 p7_hmm_AppendComlog(P7_HMM *hmm, int argc, char **argv)
510 {
511 int status;
512 void *tmp;
513 int n;
514 int i;
515
516 /* figure out length of added command line, and (re)allocate comlog */
517 n = argc-1; /* account for 1 space per arg, except last one */
518 for (i = 0; i < argc; i++)
519 n += strlen(argv[i]);
520
521 if (hmm->comlog != NULL) {
522 n += strlen(hmm->comlog) + 1; /* +1 for the \n we're going to add to the old comlog */
523 ESL_RALLOC(hmm->comlog, tmp, sizeof(char)* (n+1));
524 strcat(hmm->comlog, "\n");
525 } else {
526 ESL_ALLOC(hmm->comlog, sizeof(char)* (n+1));
527 *(hmm->comlog) = '\0'; /* need this to make strcat work */
528 }
529
530 for (i = 0; i < argc-1; i++)
531 {
532 strcat(hmm->comlog, argv[i]);
533 strcat(hmm->comlog, " ");
534 }
535 strcat(hmm->comlog, argv[argc-1]);
536 return eslOK;
537
538 ERROR:
539 return status;
540 }
541
542 /* Function: p7_hmm_SetCtime()
543 * Synopsis: Timestamp an HMM.
544 *
545 * Purpose: Set the <ctime> field in a new HMM to the current time.
546 *
547 * Returns: <eslOK> on success.
548 *
549 * Throws: <eslEMEM> on allocation failure.
550 * <eslESYS> if system calls fail to obtain (or format) the time.
551 *
552 * Notes: This function calls <ctime_r()>, supposedly a part of the
553 * ISO/IEC 9945-1:1996 (POSIX.1) standard, but not ANSI
554 * C99, so we have potential portability problems here.
555 *
556 * A known one: <ctime_r()> is by default a three-argument
557 * call on Solaris 10 systems. Our autoconf script sets
558 * -D_POSIX_PTHREAD_SEMANTICS on Solaris systems to fix this
559 * issue, requesting Solaris to use a compliant version of
560 * ctime_r().
561 *
562 * We might want to use strftime() instead; that's what
563 * POSIX 2008 recommends; but we'd still need localtime_r() or
564 * its equivalent, and that has its own portability issues.
565 *
566 * Note to porters: it really doesn't matter what this
567 * timestamp is. HMMER doesn't look at it, it's for human
568 * notetaking. If you have to, set it to an empty string.
569 *
570 * TODO: Oi. Time is complicated. Easel should give us an
571 * easy and portable call to generate time stamps like this;
572 * an esl_time module, perhaps?
573 */
574 int
575 p7_hmm_SetCtime(P7_HMM *hmm)
576 {
577 char *s = NULL;
578 time_t date;
579 int status;
580
581 ESL_ALLOC(s, 32);
582 if ((date = time(NULL)) == -1) { status = eslESYS; goto ERROR; }
583 if (ctime_r(&date, s) == NULL) { status = eslESYS; goto ERROR; }
584 if ((status = esl_strchop(s, -1)) != eslOK) { goto ERROR; }
585
586 if (hmm->ctime != NULL) free(hmm->ctime);
587 hmm->ctime = s;
588 return eslOK;
589
590 ERROR:
591 if (s) free(s);
592 return status;
593 }
594
595
596
597 /* Function: p7_hmm_SetComposition()
598 * Synopsis: Calculate and set model composition, <hmm->compo[]>
599 *
600 * Purpose: Calculates the mean residue composition emitted by
601 * model <hmm>, and set <hmm->compo[]> to it.
602 *
603 * Returns: <eslOK> on success.
604 *
605 * Throws: <eslEMEM> on allocation failure, in which case
606 * values in <hmm->compo[]> are unchanged.
607 *
608 * Note: In principle, you should be able to normalize
609 * hmm->compo[] by dividing thru by the sum of
610 * mocc[] and iocc[] vectors, and that's what the
611 * 3.0 release version did. This allowed p7_hmm_Validate()
612 * to check compo[] for summation to 1.0, as a smoke
613 * check for bugs here. The problem with that
614 * is numerical roundoff error accumulation, when
615 * hmm->M is large [bug #h84]. To fix #h84, we
616 * simply renormalize compo[], rather than the fancier
617 * previous version. This avoids error accumulation,
618 * but it also guarantees that compo[] will trivially
619 * pass the hmm_Validation() step; it's not really
620 * validating the SetComposition() calculation at all.
621 * (For description of #h84, error analysis, and the fix,
622 * xref J7/7; SRE, Tue Nov 2 14:32:29 2010)
623 */
624 int
625 p7_hmm_SetComposition(P7_HMM *hmm)
626 {
627 float *mocc = NULL;
628 float *iocc = NULL;
629 int k;
630 int status;
631
632 ESL_ALLOC(mocc, sizeof(float) * (hmm->M+1));
633 ESL_ALLOC(iocc, sizeof(float) * (hmm->M+1));
634
635 p7_hmm_CalculateOccupancy(hmm, mocc, iocc);
636 esl_vec_FSet(hmm->compo, hmm->abc->K, 0.0);
637 esl_vec_FAddScaled(hmm->compo, hmm->ins[0], iocc[0], hmm->abc->K);
638 for (k = 1; k <= hmm->M; k++)
639 {
640 esl_vec_FAddScaled(hmm->compo, hmm->mat[k], mocc[k], hmm->abc->K);
641 esl_vec_FAddScaled(hmm->compo, hmm->ins[k], iocc[k], hmm->abc->K);
642 }
643
644 esl_vec_FNorm(hmm->compo, hmm->abc->K);
645 hmm->flags |= p7H_COMPO;
646
647 free(mocc);
648 free(iocc);
649 return eslOK;
650
651 ERROR:
652 if (mocc != NULL) free(mocc);
653 if (iocc != NULL) free(iocc);
654 return status;
655 }
656
657
658 /* Function: p7_hmm_SetConsensus()
659 * Synopsis: Set the consensus residue line of the HMM.
660 *
661 * Purpose: Sets the consensus annotation line of the model <hmm>.
662 *
663 * Behavior differs, depending on whether this is a
664 * single-sequence model (i.e. phmmer) or a standard
665 * model of a multiple sequence alignment. If <sq> is
666 * non-<NULL> this is a single-sequence model and <sq> is
667 * the digital sequence it was built from. If <sq> is <NULL>
668 * this is a standard multiple-sequence model.
669 *
670 * In a standard model, the most likely (highest emission
671 * probability) residue is the consensus at each position.
672 * In a single-sequence model, the consensus is the
673 * sequence itself.
674 *
675 * In both cases, if the emission probability is $\geq$
676 * certain threshold, the residue is upper cased. The
677 * threshold is arbitrarily set to 0.9 for nucleic acid
678 * alphabets (<eslDNA>, <eslRNA>) and 0.5 for amino acid
679 * alphabets (<eslAMINO>) and all other alphabets.
680 *
681 * The special handling of single-sequence models avoids
682 * a counterintuitive case where the most likely residue is
683 * not the original residue. For example, under the
684 * BLOSUM62 matrix, given an observed M, the most likely
685 * aligned residue is an L, not an M. (Because L is so much
686 * more likely a priori than M.)
687 *
688 * Args: hmm - model with valid probability parameters mat[1..M][x]
689 * sq - NULL if a standard model;
690 * or the query sequence for a single-sequence model.
691 *
692 * Returns: <eslOK> on success. The <p7H_CONS> flag on the <hmm> is raised
693 * if it wasn't already. The <hmm->consensus> line is set.
694 *
695 * Throws: <eslEMEM> on allocation error. The <p7H_CONS> is dropped, even
696 * if it was up to begin with, and the <hmm->consensus> is <NULL>,
697 * even if we had one to begin with.
698 *
699 * Xref: SRE:J8/26.
700 */
701 int
702 p7_hmm_SetConsensus(P7_HMM *hmm, ESL_SQ *sq)
703 {
704 int k, x;
705 float mthresh;
706 int status;
707
708 /* allocation, if needed */
709 if (! hmm->consensus) ESL_ALLOC(hmm->consensus, sizeof(char) * (hmm->M+2));
710
711 /* set our arbitrary threshold for upper/lower casing */
712 if (hmm->abc->type == eslAMINO) mthresh = 0.5;
713 else if (hmm->abc->type == eslDNA) mthresh = 0.9;
714 else if (hmm->abc->type == eslRNA) mthresh = 0.9;
715 else mthresh = 0.5;
716
717 hmm->consensus[0] = ' ';
718 for (k = 1; k <= hmm->M; k++)
719 {
720 x = (sq ? sq->dsq[k] : esl_vec_FArgMax(hmm->mat[k], hmm->abc->K));
721 hmm->consensus[k] = ((hmm->mat[k][x] >= mthresh) ? toupper(hmm->abc->sym[x]) : tolower(hmm->abc->sym[x]));
722 }
723 hmm->consensus[hmm->M+1] = '\0';
724 hmm->flags |= p7H_CONS;
725 return eslOK;
726
727 ERROR:
728 if (hmm->consensus) free(hmm->consensus);
729 hmm->consensus = NULL;
730 hmm->flags &= (~p7H_CONS);
731 return status;
732 }
733 /*---------------- end, internal-setting routines ---------------*/
734
735
736
737
738 /*****************************************************************
739 * 3. Renormalization and rescaling counts in core HMMs.
740 *****************************************************************/
741
742 /* Function: p7_hmm_Scale()
743 * Synopsis: In a model containing counts, rescale counts by a factor.
744 *
745 * Purpose: Given a counts-based model <hmm>, scale core
746 * by a multiplicative factor of <scale>, where <scale> is
747 * often <eff_nseq/nseq> for absolute sequence weighting.
748 * Only affects core probability model emissions and
749 * transitions (<t>, <ins>, and <mat>).
750 *
751 * Args: hmm - counts based HMM.
752 * scale - scaling factor (e.g. eff_nseq/nseq); 1.0=no scaling.
753 *
754 * Returns: <eslOK> on success.
755 */
756 int
757 p7_hmm_Scale(P7_HMM *hmm, double scale)
758 {
759 int k;
760
761 for (k = 0; k <= hmm->M; k++) {
762 esl_vec_FScale(hmm->t[k], p7H_NTRANSITIONS, scale);
763 esl_vec_FScale(hmm->mat[k], hmm->abc->K, scale);
764 esl_vec_FScale(hmm->ins[k], hmm->abc->K, scale);
765 }
766 return eslOK;
767 }
768
769
770 /* Function: p7_hmm_ScaleExponential()
771 * Synopsis: In a model containing counts, rescale counts by an exponential factor.
772 *
773 * Purpose: Given a counts-based model <hmm>, scale core by an
774 * exponential factor <exp>. This should be thought of as
775 * an alternative to p7_hmm_Scale(). Let C_i be the total
776 * observed count in column i, and F be the scale. In
777 * p7_hmm_Scale, the updated total observed count would be
778 * C_i = C_i * F (i.e. the scaling factor is uniform across
779 * all columns). In this function, C_i = C_i ^ F. The result
780 * is a non-uniform scaling across columns -- columns with
781 * higher C_i will be reduced to a greater extent than will
782 * columns with low counts.
783 *
784 * Consider the case where one column has 30 observations and a
785 * bunch of others have 300. This can happen when heavily-
786 * fragmented sequences are used to reconstruct a family MSA, as
787 * in Dfam models ... but isn't likely to have been seen in Pfam
788 * alignments. Though the column with 30 observations isn't nearly
789 * as complete as the one with 300, it still has enough that we
790 * shouldn't be willing to discount the observations entirely -
791 * something that might happen if uniform entropy weighting needs
792 * to push the average observations down 10-fold in order to achieve
793 * the desired avg relative entropy.
794 * e.g.
795 *
796 * C_i F -> C_i
797 * 3 .8 2.4
798 * 30 .8 15
799 * 300 .8 96
800 * 3 .7 2.2
801 * 30 .7 11
802 * 300 .7 54
803 * 3 .6 1.9
804 * 30 .6 7.6
805 * 300 .6 30
806 *
807 * Note: the observed counts will never drop below 1 in this case.
808 *
809 * After computing the per-column total scale for column i, that
810 * scale is applied to the core probability model emissions and
811 * transitions (<t>, <ins>, and <mat>) for position i.
812 *
813 * Args: hmm - counts based HMM.
814 * exp - exponential factor; 1.0=no scaling.
815 * ret_scaleavg - returns the mean of the per-column scale factors corresponding
816 * to the factor exp.
817 *
818 * Returns: <eslOK> on success.
819 */
820 int
821 p7_hmm_ScaleExponential(P7_HMM *hmm, double exp)
822 {
823
824 int k;
825 for (k = 1; k <= hmm->M; k++) {
826
827 float count = esl_vec_FSum(hmm->mat[k], hmm->abc->K);
828 float new_count = pow(count, exp);
829 double scale = count>0 ? new_count / count : 1.0; /* if no counts in the column (strange, but possible), just use default freqs*/
830
831 esl_vec_FScale(hmm->t[k], p7H_NTRANSITIONS, scale);
832 esl_vec_FScale(hmm->mat[k], hmm->abc->K, scale);
833 esl_vec_FScale(hmm->ins[k], hmm->abc->K, scale);
834 }
835 return eslOK;
836 }
837
838 /* Function: p7_hmm_Renormalize()
839 * Synopsis: Renormalize all parameter vectors (emissions/transitions).
840 *
841 * Purpose: Take a core HMM in counts form, and renormalize
842 * all probability vectors in the core probability model. Enforces
843 * Plan7 restrictions on nonexistent transitions.
844 *
845 * Leaves other flags (stats and profile) alone, so caller
846 * needs to be wary. Renormalizing a probability model that
847 * has stats and profile scores wouldn't usually invalidate
848 * those data; and if we're renormalizing a counts model, we
849 * shouldn't have stats or profile scores yet anyway.
850 *
851 * Args: hmm - the model to renormalize.
852 *
853 * Return: <eslOK> on success.
854 */
855 int
856 p7_hmm_Renormalize(P7_HMM *hmm)
857 {
858 int k; /* counter for model position */
859
860 for (k = 0; k <= hmm->M; k++) {
861 esl_vec_FNorm(hmm->mat[k], hmm->abc->K);
862 esl_vec_FNorm(hmm->ins[k], hmm->abc->K);
863 esl_vec_FNorm(P7H_TMAT(hmm, k), p7H_NTMAT); /* TMX */
864 esl_vec_FNorm(P7H_TDEL(hmm, k), p7H_NTDEL); /* TIX */
865 esl_vec_FNorm(P7H_TINS(hmm, k), p7H_NTINS); /* TDX */
866 }
867 /* If t[M][TD*] distribution was all zeros, we just made TDD nonzero. Oops.
868 * Re-enforce t's on that final delete state. */
869 hmm->t[hmm->M][p7H_DM] = 1.0;
870 hmm->t[hmm->M][p7H_DD] = 0.0;
871
872 /* Rare: if t[M][TM*] distribution was all zeros (all final transitions
873 * were D_M -> E) then we just made nonexistent M_M->D_M+1 transition nonzero.
874 * Fix that too.
875 */
876 if (hmm->t[hmm->M][p7H_MD] > 0.) {
877 hmm->t[hmm->M][p7H_MD] = 0.;
878 hmm->t[hmm->M][p7H_MM] = 0.5;
879 hmm->t[hmm->M][p7H_MI] = 0.5;
880 }
881
882 return eslOK;
883 }
884
885 /*****************************************************************
886 * 4. Debugging and development code
887 *****************************************************************/
888
889 /* Function: p7_hmm_Dump()
890 * Synopsis: Dump HMM data structure to a stream.
891 *
892 * Purpose: Debugging: dump the probabilities (or counts) from a core HMM.
893 *
894 * Returns: <eslOK> on success.
895 */
896 int
897 p7_hmm_Dump(FILE *fp, P7_HMM *hmm)
898 {
899 int k; /* counter for nodes */
900 int x; /* counter for symbols */
901 int ts; /* counter for state transitions */
902
903 for (k = 0; k <= hmm->M; k++)
904 { /* Line 1: k, match emissions */
905 fprintf(fp, " %5d ", k);
906 for (x = 0; x < hmm->abc->K; x++)
907 fprintf(fp, "%9.4f ", hmm->mat[k][x]);
908 fputs("\n", fp);
909 /* Line 2: insert emissions */
910 fprintf(fp, " ");
911 for (x = 0; x < hmm->abc->K; x++)
912 fprintf(fp, "%9.4f ", hmm->ins[k][x]);
913 fputs("\n", fp);
914 /* Line 3: transition probs */
915 fprintf(fp, " ");
916 for (ts = 0; ts < 7; ts++)
917 fprintf(fp, "%9.4f ", hmm->t[k][ts]);
918 fputs("\n", fp);
919 }
920 fputs("//\n", fp);
921 return eslOK;
922 }
923
924 /* Function: p7_hmm_Sample()
925 * Synopsis: Sample an HMM at random.
926 *
927 * Purpose: Creates a random HMM of length <M> nodes,
928 * for alphabet <abc>, obtaining randomness from
929 * <r>.
930 *
931 * Probably only useful for debugging.
932 *
933 * Note: Compare p7_hmm_Renormalize(), which has a similar
934 * structure, except it normalizes instead of
935 * sampling each probability vector.
936 *
937 * Returns: <eslOK> on success, and the new hmm is returned
938 * through <ret_hmm); caller is responsible for
939 * freeing this object with <p7_hmm_Destroy()>.
940 *
941 * Throws: <eslEMEM> on allocation error.
942 */
943 int
944 p7_hmm_Sample(ESL_RANDOMNESS *r, int M, const ESL_ALPHABET *abc, P7_HMM **ret_hmm)
945 {
946 P7_HMM *hmm = NULL;
947 char *logmsg = "[random HMM created by sampling]";
948 int k;
949 int status;
950
951 hmm = p7_hmm_Create(M, abc);
952 if (hmm == NULL) { status = eslEMEM; goto ERROR; }
953
954 for (k = 0; k <= M; k++)
955 {
956 if (k > 0) esl_dirichlet_FSampleUniform(r, abc->K, hmm->mat[k]);
957 esl_dirichlet_FSampleUniform(r, abc->K, hmm->ins[k]);
958 esl_dirichlet_FSampleUniform(r, 3, hmm->t[k]);
959 esl_dirichlet_FSampleUniform(r, 2, hmm->t[k]+3);
960 if (k > 0) esl_dirichlet_FSampleUniform(r, 2, hmm->t[k]+5);
961 }
962 /* Node M is special: no transitions to D, transitions to M
963 * are interpreted as transitions to E. Overwrite a little of
964 * what we did in node M.
965 */
966 esl_dirichlet_FSampleUniform(r, 2, hmm->t[M]); /* TMM,TMI only */
967 hmm->t[M][p7H_MD] = 0.;
968 hmm->t[M][p7H_DM] = 1.0;
969 hmm->t[M][p7H_DD] = 0.0;
970
971 /* Add mandatory annotation, and some relevant optional annotation */
972 p7_hmm_SetName(hmm, "sampled-hmm");
973 p7_hmm_AppendComlog(hmm, 1, &logmsg);
974 p7_hmm_SetCtime(hmm);
975 p7_hmm_SetConsensus(hmm, NULL);
976
977 *ret_hmm = hmm;
978 return eslOK;
979
980 ERROR:
981 if (hmm != NULL) p7_hmm_Destroy(hmm);
982 *ret_hmm = NULL;
983 return status;
984
985 }
986
987 /* Function: p7_hmm_SampleUngapped()
988 * Synopsis: Sample a random HMM with no nonzero indel transitions.
989 *
990 * Purpose: Same as <p7_hmm_Sample()>, except all
991 * M $\rightarrow$ M transitions are 1.0:
992 * an ungapped model. Useful for testing
993 * as a limit case.
994 *
995 * Returns: <eslOK> on success, and the new hmm is returned
996 * through <ret_hmm); caller is responsible for
997 * freeing this object with <p7_hmm_Destroy()>.
998 *
999 * Throws: <eslEMEM> on allocation error.
1000 *
1001 * Xref: STL11/140
1002 */
1003 int
1004 p7_hmm_SampleUngapped(ESL_RANDOMNESS *r, int M, const ESL_ALPHABET *abc, P7_HMM **ret_hmm)
1005 {
1006 P7_HMM *hmm = NULL;
1007 int k;
1008 int status;
1009
1010 if ((status = p7_hmm_Sample(r, M, abc, &hmm)) != eslOK) goto ERROR;
1011 for (k = 0; k <= M; k++) {
1012 hmm->t[k][p7H_MM] = 1.0;
1013 hmm->t[k][p7H_MD] = 0.0;
1014 hmm->t[k][p7H_MI] = 0.0;
1015 }
1016 *ret_hmm = hmm;
1017 return eslOK;
1018
1019 ERROR:
1020 if (hmm != NULL) p7_hmm_Destroy(hmm);
1021 *ret_hmm = NULL;
1022 return status;
1023 }
1024
1025 /* Function: esl_hmm_SampleEnumerable()
1026 * Synopsis: Sample an random HMM with no nonzero insertion transitions.
1027 *
1028 * Purpose: Sample a random HMM with random emission and
1029 * transition probabilities with the exception that
1030 * all transitions to insert are zero. This makes
1031 * it possible to create a model with a finite,
1032 * easily enumerable sequence space (all seqs of
1033 * length $\leq M).
1034 *
1035 * To achieve this in the profile as well as the core HMM,
1036 * the caller must configure a unihit mode
1037 * (<p7_ProfileConfig(hmm, bg, gm, p7_UNILOCAL)> or
1038 * <p7_UNIGLOCAL>), and a target length of zero
1039 * (<p7_ReconfigLength(gm, 0)>).
1040 *
1041 * Useful for debugging and validating Forward/Viterbi
1042 * algorithms.
1043 *
1044 * Returns: <eslOK> on success. The newly allocated hmm is returned through
1045 * <ret_hmm>. The caller is responsible for freeing this object
1046 * with <p7_hmm_Destroy()>.
1047 *
1048 * Throws: <eslEMEM> on allocation error.
1049 */
1050 int
1051 p7_hmm_SampleEnumerable(ESL_RANDOMNESS *r, int M, const ESL_ALPHABET *abc, P7_HMM **ret_hmm)
1052 {
1053 P7_HMM *hmm = NULL;
1054 char *logmsg = "[random enumerable HMM created by sampling]";
1055 int k;
1056 float tmp[2];
1057 int status;
1058
1059 hmm = p7_hmm_Create(M, abc);
1060 if (hmm == NULL) { status = eslEMEM; goto ERROR; }
1061
1062 for (k = 0; k <= M; k++)
1063 {
1064 if (k > 0) esl_dirichlet_FSampleUniform(r, abc->K, hmm->mat[k]); /* match emission probs */
1065 esl_dirichlet_FSampleUniform(r, abc->K, hmm->ins[k]); /* insert emission probs */
1066 esl_dirichlet_FSampleUniform(r, 2, tmp);
1067 hmm->t[k][p7H_MM] = tmp[0];
1068 hmm->t[k][p7H_MI] = 0.;
1069 hmm->t[k][p7H_MD] = tmp[1];
1070 hmm->t[k][p7H_IM] = 1.; /* I transitions irrelevant since I's are unreached. */
1071 hmm->t[k][p7H_II] = 0.;
1072 if (k > 0) esl_dirichlet_FSampleUniform(r, 2, hmm->t[k]+5); /* delete transitions to M,D */
1073 }
1074
1075 /* Node M is special: no transitions to D, transitions to M
1076 * are interpreted as transitions to E. Overwrite a little of
1077 * what we did in node M.
1078 */
1079 hmm->t[M][p7H_MM] = 1.;
1080 hmm->t[M][p7H_MD] = 0.;
1081 hmm->t[M][p7H_DM] = 1.;
1082 hmm->t[M][p7H_DD] = 0.;
1083
1084 /* Add mandatory annotation
1085 */
1086 p7_hmm_SetName(hmm, "sampled-hmm");
1087 p7_hmm_AppendComlog(hmm, 1, &logmsg);
1088 p7_hmm_SetCtime(hmm);
1089 p7_hmm_SetConsensus(hmm, NULL);
1090
1091 /* SRE DEBUGGING */
1092 p7_hmm_Validate(hmm, NULL, 0.0001);
1093
1094 *ret_hmm = hmm;
1095 return eslOK;
1096
1097 ERROR:
1098 if (hmm != NULL) p7_hmm_Destroy(hmm);
1099 *ret_hmm = NULL;
1100 return status;
1101 }
1102
1103 /* Function: p7_hmm_SampleUniform()
1104 * Synopsis: Sample a model that uses fixed (given) transition probs.
1105 *
1106 * Purpose: Sample a model that uses uniform transition probabilities,
1107 * determined by <tmi>, <tii>, <tmd>, and <tdd>,
1108 * the probabilistic equivalent of gap-open/gap-extend for
1109 * inserts, deletes.
1110 *
1111 * Useful for testing expected behavior on single-sequence
1112 * models, where transitions are position-independent.
1113 *
1114 * Returns: <eslOK> on success, and the new hmm is returned
1115 * through <ret_hmm); caller is responsible for
1116 * freeing this object with <p7_hmm_Destroy()>.
1117 *
1118 * Throws: <eslEMEM> on allocation error.
1119 *
1120 * Xref: J1/5.
1121 */
1122 int
1123 p7_hmm_SampleUniform(ESL_RANDOMNESS *r, int M, const ESL_ALPHABET *abc,
1124 float tmi, float tii, float tmd, float tdd,
1125 P7_HMM **ret_hmm)
1126 {
1127 int status;
1128 P7_HMM *hmm = NULL;
1129 char *logmsg = "[HMM with uniform transitions, random emissions]";
1130 int k;
1131
1132 hmm = p7_hmm_Create(M, abc);
1133 if (hmm == NULL) { status = eslEMEM; goto ERROR; }
1134
1135 for (k = 0; k <= M; k++)
1136 {
1137 if (k > 0) esl_dirichlet_FSampleUniform(r, abc->K, hmm->mat[k]);
1138 esl_dirichlet_FSampleUniform(r, abc->K, hmm->ins[k]);
1139 hmm->t[k][p7H_MM] = 1.0 - tmi - tmd;
1140 hmm->t[k][p7H_MI] = tmi;
1141 hmm->t[k][p7H_MD] = tmd;
1142 hmm->t[k][p7H_IM] = 1.0 - tii;
1143 hmm->t[k][p7H_II] = tii;
1144 hmm->t[k][p7H_DM] = 1.0 - tdd;
1145 hmm->t[k][p7H_DD] = tdd;
1146 }
1147
1148 /* Deal w/ special stuff at node 0, M, overwriting some of what we
1149 * just did.
1150 */
1151 hmm->t[M][p7H_MM] = 1.0 - tmi;
1152 hmm->t[M][p7H_MD] = 0.;
1153 hmm->t[M][p7H_DM] = 1.0;
1154 hmm->t[M][p7H_DD] = 0.;
1155
1156 /* Add mandatory annotation
1157 */
1158 p7_hmm_SetName(hmm, "sampled-hmm");
1159 p7_hmm_AppendComlog(hmm, 1, &logmsg);
1160 p7_hmm_SetCtime(hmm);
1161 p7_hmm_SetConsensus(hmm, NULL);
1162
1163 *ret_hmm = hmm;
1164 return eslOK;
1165
1166 ERROR:
1167 if (hmm != NULL) p7_hmm_Destroy(hmm);
1168 *ret_hmm = NULL;
1169 return status;
1170 }
1171
1172
1173
1174 /* Function: p7_hmm_Compare()
1175 * Synopsis: Compare two HMMs for equality.
1176 *
1177 * Purpose: Compare two HMMs <h1> and <h2> to each other;
1178 * return <eslOK> if they're identical, and <eslFAIL>
1179 * if they differ. Floating-point probabilities are
1180 * compared for equality within a fractional tolerance
1181 * <tol>.
1182 */
1183 int
1184 p7_hmm_Compare(P7_HMM *h1, P7_HMM *h2, float tol)
1185 {
1186 int k, z;
1187
1188 if (h1->abc->type != h2->abc->type) return eslFAIL;
1189 if (h1->M != h2->M) return eslFAIL;
1190 if (h1->flags != h2->flags) return eslFAIL;
1191
1192 for (k = 0; k <= h1->M; k++) /* (it's safe to include 0 here.) */
1193 {
1194 if (esl_vec_FCompare(h1->mat[k], h2->mat[k], h1->abc->K, tol) != eslOK) return eslFAIL;
1195 if (esl_vec_FCompare(h1->ins[k], h2->ins[k], h1->abc->K, tol) != eslOK) return eslFAIL;
1196 if (esl_vec_FCompare(h1->t[k], h2->t[k], 7, tol) != eslOK) return eslFAIL;
1197 }
1198
1199 if (strcmp(h1->name, h2->name) != 0) return eslFAIL;
1200 if (esl_strcmp(h1->comlog, h2->comlog) != 0) return eslFAIL;
1201 if (strcmp(h1->ctime, h2->ctime) != 0) return eslFAIL;
1202
1203 if (h1->nseq != h2->nseq) return eslFAIL;
1204 if (esl_FCompare_old(h1->eff_nseq, h2->eff_nseq, tol) != eslOK) return eslFAIL;
1205 if (h1->checksum != h2->checksum) return eslFAIL;
1206
1207 if (esl_strcmp(h1->acc, h2->acc) != 0) return eslFAIL;
1208 if (esl_strcmp(h1->desc, h2->desc) != 0) return eslFAIL;
1209
1210 if ((h1->flags & p7H_RF) && esl_strcmp(h1->rf, h2->rf) != 0) return eslFAIL;
1211 if ((h1->flags & p7H_MMASK) && esl_strcmp(h1->mm, h2->mm) != 0) return eslFAIL;
1212 if ((h1->flags & p7H_CONS) && esl_strcmp(h1->consensus, h2->consensus) != 0) return eslFAIL;
1213 if ((h1->flags & p7H_CS) && esl_strcmp(h1->cs, h2->cs) != 0) return eslFAIL;
1214 if ((h1->flags & p7H_CA) && esl_strcmp(h1->ca, h2->ca) != 0) return eslFAIL;
1215 if ((h1->flags & p7H_MAP) && esl_vec_ICompare(h1->map, h2->map, h1->M+1) != 0) return eslFAIL;
1216
1217 if (h1->flags & p7H_GA) {
1218 if (esl_FCompare_old(h1->cutoff[p7_GA1], h2->cutoff[p7_GA1], tol) != eslOK) return eslFAIL;
1219 if (esl_FCompare_old(h1->cutoff[p7_GA2], h2->cutoff[p7_GA2], tol) != eslOK) return eslFAIL;
1220 }
1221 if (h1->flags & p7H_TC) {
1222 if (esl_FCompare_old(h1->cutoff[p7_TC1], h2->cutoff[p7_TC1], tol) != eslOK) return eslFAIL;
1223 if (esl_FCompare_old(h1->cutoff[p7_TC2], h2->cutoff[p7_TC2], tol) != eslOK) return eslFAIL;
1224 }
1225 if (h1->flags & p7H_NC) {
1226 if (esl_FCompare_old(h1->cutoff[p7_NC1], h2->cutoff[p7_NC1], tol) != eslOK) return eslFAIL;
1227 if (esl_FCompare_old(h1->cutoff[p7_NC2], h2->cutoff[p7_NC2], tol) != eslOK) return eslFAIL;
1228 }
1229
1230 if (h1->flags & p7H_STATS) {
1231 for (z = 0; z < p7_NEVPARAM; z++)
1232 if (esl_FCompare_old(h1->evparam[z], h2->evparam[z], tol) != eslOK) return eslFAIL;
1233 }
1234
1235 return eslOK;
1236 }
1237
1238 /* Function: p7_hmm_Validate()
1239 * Synopsis: Validate a <P7_HMM> data structuure.
1240 *
1241 * Purpose: Validates the internals of the HMM structure <hmm>.
1242 *
1243 * Probability vectors are validated to sum up to
1244 * within a fractional tolerance <tol> of 1.0.
1245 *
1246 * Probably only useful for debugging and development,
1247 * not production code.
1248 *
1249 * Returns: <eslOK> if <hmm> internals look fine.
1250 * Returns <eslFAIL> if something is wrong.
1251 */
1252 int
1253 p7_hmm_Validate(P7_HMM *hmm, char *errbuf, float tol)
1254 {
1255 int status;
1256 int k;
1257
1258 if (hmm == NULL) ESL_XFAIL(eslFAIL, errbuf, "HMM is a null pointer");
1259 if (hmm->M < 1) ESL_XFAIL(eslFAIL, errbuf, "HMM has M < 1");
1260 if (hmm->abc == NULL) ESL_XFAIL(eslFAIL, errbuf, "HMM has no alphabet reference");
1261 if (hmm->abc->type == eslUNKNOWN) ESL_XFAIL(eslFAIL, errbuf, "HMM's alphabet is set to unknown");
1262
1263 for (k = 0; k <= hmm->M; k++)
1264 {
1265 if (esl_vec_FValidate(hmm->mat[k], hmm->abc->K, tol, NULL) != eslOK) ESL_XFAIL(eslFAIL, errbuf, "mat[%d] fails pvector validation", k);
1266 if (esl_vec_FValidate(hmm->ins[k], hmm->abc->K, tol, NULL) != eslOK) ESL_XFAIL(eslFAIL, errbuf, "ins[%d] fails pvector validation", k);
1267 if (esl_vec_FValidate(hmm->t[k], 3, tol, NULL) != eslOK) ESL_XFAIL(eslFAIL, errbuf, "t_M[%d] fails pvector validation", k);
1268 if (esl_vec_FValidate(hmm->t[k]+3, 2, tol, NULL) != eslOK) ESL_XFAIL(eslFAIL, errbuf, "t_I[%d] fails pvector validation", k);
1269 if (esl_vec_FValidate(hmm->t[k]+5, 2, tol, NULL) != eslOK) ESL_XFAIL(eslFAIL, errbuf, "t_D[%d] fails pvector validation", k);
1270 }
1271 if (hmm->t[hmm->M][p7H_MD] != 0.0) ESL_XFAIL(eslFAIL, errbuf, "TMD should be 0 for last node");
1272 if (hmm->t[hmm->M][p7H_DM] != 1.0) ESL_XFAIL(eslFAIL, errbuf, "TDM should be 1 for last node");
1273 if (hmm->t[hmm->M][p7H_DD] != 0.0) ESL_XFAIL(eslFAIL, errbuf, "TDD should be 0 for last node");
1274
1275 if (hmm->name == NULL) ESL_XFAIL(eslFAIL, errbuf, "name is NULL: this field is mandatory");
1276 /* comlog is either NULL or a free text string: hard to validate */
1277 /* ctime, ditto */
1278 if ( (hmm->nseq != -1) && hmm->nseq <= 0) ESL_XFAIL(eslFAIL, errbuf, "invalid nseq");
1279 if ( (hmm->eff_nseq != -1.0f) && hmm->eff_nseq <= 0.0f) ESL_XFAIL(eslFAIL, errbuf, "invalid eff_nseq");
1280 if (!(hmm->flags & p7H_CHKSUM) && hmm->checksum != 0 ) ESL_XFAIL(eslFAIL, errbuf, "p7H_CHKSUM flag down, but nonzero checksum present");
1281
1282 if (hmm->flags & p7H_RF) { if (hmm->rf == NULL || strlen(hmm->rf) != hmm->M+1) ESL_XFAIL(eslFAIL, errbuf, "p7H_RF flag up, but rf string is invalid"); }
1283 else if (hmm->rf) { ESL_XFAIL(eslFAIL, errbuf, "p7H_RF flag down, but rf string is present"); }
1284
1285 if (hmm->flags & p7H_MMASK) { if (hmm->mm == NULL || strlen(hmm->mm) != hmm->M+1) ESL_XFAIL(eslFAIL, errbuf, "p7H_MMASK flag up, but mm string is invalid"); }
1286 else if (hmm->mm) { ESL_XFAIL(eslFAIL, errbuf, "p7H_MMASK flag down, but mm string is present"); }
1287
1288 if (hmm->flags & p7H_CONS) { if (hmm->consensus == NULL || strlen(hmm->consensus) != hmm->M+1) ESL_XFAIL(eslFAIL, errbuf, "p7H_CONS flag up, but consensus string is invalid"); }
1289 else if (hmm->consensus) { ESL_XFAIL(eslFAIL, errbuf, "p7H_CONS flag down, but consensus string is present"); }
1290
1291 if (hmm->flags & p7H_CS) { if (hmm->cs == NULL || strlen(hmm->cs) != hmm->M+1) ESL_XFAIL(eslFAIL, errbuf, "p7H_CS flag up, but cs string is invalid"); }
1292 else if (hmm->cs) { ESL_XFAIL(eslFAIL, errbuf, "p7H_CS flag down, but cs string is present"); }
1293
1294 if (hmm->flags & p7H_CA) { if (hmm->ca == NULL || strlen(hmm->ca) != hmm->M+1) ESL_XFAIL(eslFAIL, errbuf, "p7H_CA flag up, but ca string is invalid"); }
1295 else if (hmm->ca) { ESL_XFAIL(eslFAIL, errbuf, "p7H_CA flag down, but ca string is present"); }
1296
1297 if ( (hmm->flags & p7H_MAP) && hmm->map == NULL) ESL_XFAIL(eslFAIL, errbuf, "p7H_MAP flag up, but map string is null");
1298 if (! (hmm->flags & p7H_MAP) && hmm->map != NULL) ESL_XFAIL(eslFAIL, errbuf, "p7H_MAP flag down, but map string is present");
1299
1300 if (hmm->flags & p7H_STATS) {
1301 if (hmm->evparam[p7_MLAMBDA] <= 0.) ESL_XFAIL(eslFAIL, errbuf, "lambda parameter can't be negative");
1302 if (hmm->evparam[p7_VLAMBDA] <= 0.) ESL_XFAIL(eslFAIL, errbuf, "lambda parameter can't be negative");
1303 if (hmm->evparam[p7_FLAMBDA] <= 0.) ESL_XFAIL(eslFAIL, errbuf, "lambda parameter can't be negative");
1304 }
1305 if (hmm->flags & p7H_COMPO && esl_vec_FValidate(hmm->compo, hmm->abc->K, tol, NULL) != eslOK)
1306 ESL_XFAIL(eslFAIL, errbuf, "composition fails pvector validation");
1307
1308 return eslOK;
1309
1310 ERROR:
1311 return status;
1312 }
1313 /*------------- end of debugging/development code ----------------*/
1314
1315
1316
1317
1318 /*****************************************************************
1319 * 5. Other routines in the API.
1320 *****************************************************************/
1321
1322 /* Function: p7_hmm_CalculateOccupancy()
1323 * Synopsis: Calculate match occupancy and insert expected use count vectors.
1324 *
1325 * Purpose: Calculate a vector <mocc[1..M]> containing probability
1326 * that each match state is used in a sampled glocal path through
1327 * the model. Caller provides allocated space (<M+1> floats)
1328 * for <mocc>.
1329 *
1330 * Caller may optionally provide an array <iocc[0..M]> as
1331 * well, which (if provided) will be set to contain the
1332 * expected number of times that a sampled path would contain
1333 * each insert state.
1334 *
1335 * Returns: <eslOK> on success.
1336 */
1337 int
1338 p7_hmm_CalculateOccupancy(const P7_HMM *hmm, float *mocc, float *iocc)
1339 {
1340 int k;
1341
1342 mocc[0] = 0.; /* no M_0 state */
1343 mocc[1] = hmm->t[0][p7H_MI] + hmm->t[0][p7H_MM]; /* initialize w/ 1 - B->D_1 */
1344 for (k = 2; k <= hmm->M; k++)
1345 mocc[k] = mocc[k-1] * (hmm->t[k-1][p7H_MM] + hmm->t[k-1][p7H_MI]) +
1346 (1.0-mocc[k-1]) * hmm->t[k-1][p7H_DM];
1347 if (iocc != NULL) {
1348 iocc[0] = hmm->t[0][p7H_MI] / hmm->t[0][p7H_IM];
1349 for (k = 1; k <= hmm->M; k++)
1350 iocc[k] = mocc[k] * hmm->t[k][p7H_MI] / hmm->t[k][p7H_IM];
1351 }
1352
1353 return eslOK;
1354 }
1355
1356
1357
1358 /*---------------- end of the rest of the API -------------------*/
1359
1360
1361
1362
1363 /*****************************************************************
1364 * 6. Unit tests.
1365 *****************************************************************/
1366 #ifdef p7HMM_TESTDRIVE
1367
1368 /* The occupancy unit test is based on the principle that
1369 * the stationary match occupancy probability in a random HMM
1370 * converges to 0.6, for long enough M (STL11/138)
1371 */
1372 static void
1373 utest_occupancy(ESL_GETOPTS *go, ESL_RANDOMNESS *r, ESL_ALPHABET *abc)
1374 {
1375 char *msg = "p7_hmm.c:: occupancy unit test failed";
1376 P7_HMM *hmm = NULL;
1377 int M = 200;
1378 float *occ = malloc(sizeof(float) * (M+1));
1379 float x;
1380
1381 if (p7_hmm_Sample(r, M, abc, &hmm) != eslOK) esl_fatal(msg);
1382 if (p7_hmm_CalculateOccupancy(hmm, occ, NULL) != eslOK) esl_fatal(msg);
1383 x = esl_vec_FSum(occ+1, hmm->M) / (float) hmm->M;
1384
1385 if (esl_opt_GetBoolean(go, "-v") == TRUE)
1386 {
1387 printf("occupancy unit test:\n");
1388 printf("expected 0.6; got %.3f\n\n", x);
1389 }
1390
1391 if (esl_FCompare_old(x, 0.6, 0.1) != eslOK) esl_fatal(msg);
1392
1393 free(occ);
1394 p7_hmm_Destroy(hmm);
1395 return;
1396 }
1397
1398 /* The composition unit test validates the SetComposition()
1399 * calculation against the composition of a large number of sampled
1400 * core HMM traces. This also exercises the correctness of
1401 * p7_hmm_Sample() and p7_hmm_SetOccupancy().
1402 *
1403 * SRE, Fri Dec 4 13:04:52 2009 [#h71; J5/120]
1404 */
1405 static void
1406 utest_composition(ESL_GETOPTS *go, ESL_RANDOMNESS *r, ESL_ALPHABET *abc)
1407 {
1408 char *msg = "p7_hmm.c:: composition unit test failed";
1409 P7_HMM *hmm = NULL;
1410 ESL_SQ *sq = esl_sq_CreateDigital(abc);
1411 int M = 3;
1412 int N = 100000;
1413 float *fq = malloc(sizeof(float) * abc->K);
1414 int i,pos;
1415
1416 if (p7_hmm_Sample(r, M, abc, &hmm) != eslOK) esl_fatal(msg);
1417 if (p7_hmm_SetComposition(hmm) != eslOK) esl_fatal(msg);
1418
1419 esl_vec_FSet(fq, abc->K, 0.0);
1420 for (i = 0; i < N; i++)
1421 {
1422 p7_CoreEmit(r, hmm, sq, NULL);
1423
1424 for (pos = 1; pos <= sq->n; pos++)
1425 fq[sq->dsq[pos]] += 1.0;
1426
1427 esl_sq_Reuse(sq);
1428 }
1429 esl_vec_FNorm(fq, abc->K);
1430
1431 if (esl_opt_GetBoolean(go, "-v") == TRUE)
1432 {
1433 printf("composition unit test:\n");
1434 printf(" %6s %6s\n", "calced", "sample");
1435 printf(" %6s %6s\n", "------", "------");
1436 for (i = 0; i < abc->K; i++)
1437 printf("%c %6.3f %6.3f\n", abc->sym[i], hmm->compo[i], fq[i]);
1438 printf("\n");
1439 }
1440
1441 if (esl_vec_FCompare(fq, hmm->compo, abc->K, 0.03) != eslOK) esl_fatal(msg);
1442
1443 free(fq);
1444 esl_sq_Destroy(sq);
1445 p7_hmm_Destroy(hmm);
1446 return;
1447 }
1448
1449 #endif /*p7HMM_TESTDRIVE*/
1450 /*---------------------- end of unit tests -----------------------*/
1451
1452
1453 /*****************************************************************
1454 * 7. Test driver.
1455 *****************************************************************/
1456
1457 #ifdef p7HMM_TESTDRIVE
1458
1459 #include <p7_config.h>
1460 #include "easel.h"
1461 #include "esl_alphabet.h"
1462 #include "esl_random.h"
1463 #include "hmmer.h"
1464
1465 static ESL_OPTIONS options[] = {
1466 /* name type default env range toggles reqs incomp help docgroup*/
1467 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1468 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1469 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose", 0 },
1470 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1471 };
1472 static char usage[] = "[-options]";
1473 static char banner[] = "unit test driver for p7_hmm.c core model routines";
1474
1475 int
1476 main(int argc, char **argv)
1477 {
1478 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1479 ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1480 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
1481
1482 utest_occupancy (go, r, abc);
1483 utest_composition(go, r, abc);
1484
1485 esl_alphabet_Destroy(abc);
1486 esl_randomness_Destroy(r);
1487 esl_getopts_Destroy(go);
1488 exit(0); /* success */
1489 }
1490
1491 #endif /*p7HMM_TESTDRIVE*/
1492 /*-------------------- end of test driver ---------------------*/
1493
1494