-
Notifications
You must be signed in to change notification settings - Fork 27
/
esl_alphabet.c
2578 lines (2261 loc) · 85.6 KB
/
esl_alphabet.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Implements the standard digitized alphabets for biosequences.
*
* 1. ESL_ALPHABET object for digital alphabets.
* 2. Digitized sequences (ESL_DSQ *).
* 3. Other routines in the API.
* 4. Unit tests.
* 5. Test driver.
* 6. Examples.
*/
#include <esl_config.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#ifdef HAVE_STRINGS_H
#include <strings.h> /* POSIX strcasecmp() */
#endif
#include "easel.h"
#include "esl_mem.h"
#include "esl_alphabet.h"
/*****************************************************************
* 1. The ESL_ALPHABET object
*****************************************************************/
static ESL_ALPHABET *create_rna(void);
static ESL_ALPHABET *create_dna(void);
static ESL_ALPHABET *create_amino(void);
static ESL_ALPHABET *create_coins(void);
static ESL_ALPHABET *create_dice(void);
static int set_complementarity(ESL_ALPHABET *a);
/* Function: esl_alphabet_Create()
* Synopsis: Create alphabet of a standard type.
*
* Purpose: Creates one of the three standard bio alphabets:
* <eslDNA>, <eslRNA>, or <eslAMINO>, and returns
* a pointer to it.
*
* Args: type - <eslDNA>, <eslRNA>, or <eslAMINO>.
*
* Returns: pointer to the new alphabet.
*
* Throws: <NULL> if any allocation or initialization fails.
*/
ESL_ALPHABET *
esl_alphabet_Create(int type)
{
ESL_ALPHABET *a = NULL;
switch(type) {
case eslRNA: a = create_rna(); break;
case eslDNA: a = create_dna(); break;
case eslAMINO: a = create_amino(); break;
case eslCOINS: a = create_coins(); break;
case eslDICE: a = create_dice(); break;
default: esl_fatal("bad alphabet type: unrecognized"); // violation: must be a code error, not user.
}
return a;
}
/* Function: esl_alphabet_CreateCustom()
* Synopsis: Create a custom alphabet.
*
* Purpose: Creates a customized biosequence alphabet,
* and returns a ptr to it. The alphabet type is set
* to <eslNONSTANDARD>.
*
* <alphabet> is the internal alphabet string;
* <K> is the size of the base alphabet;
* <Kp> is the total size of the alphabet string.
*
* In the alphabet string, residues <0..K-1> are the base alphabet;
* residue <K> is the canonical gap (indel) symbol;
* residues <K+1..Kp-4> are additional degeneracy symbols (possibly 0 of them);
* residue <Kp-3> is an "any" symbol (such as N or X);
* residue <Kp-2> is a "nonresidue" symbol (such as *);
* and residue <Kp-1> is a "missing data" gap symbol.
*
* The two gap symbols, the nonresidue, and the "any"
* symbol are mandatory even for nonstandard alphabets, so
* <Kp> $\geq$ <K+4>.
*
* Args: alphabet - internal alphabet; example "ACGT-RYMKSWHBVDN*~"
* K - base size; example 4
* Kp - total size, including gap, degeneracies; example 18
*
* Returns: pointer to new <ESL_ALPHABET> structure.
*
* Throws: <NULL> if any allocation or initialization fails.
*/
ESL_ALPHABET *
esl_alphabet_CreateCustom(const char *alphabet, int K, int Kp)
{
ESL_ALPHABET *a = NULL;
int c,x,y;
int status;
/* Argument checks.
*/
if (strlen(alphabet) != Kp) ESL_XEXCEPTION(eslEINVAL, "alphabet length != Kp");
if (Kp < K+4) ESL_XEXCEPTION(eslEINVAL, "Kp too small in alphabet");
/* Allocation/init, level 1.
*/
ESL_ALLOC(a, sizeof(ESL_ALPHABET));
a->sym = NULL;
a->degen = NULL;
a->ndegen = NULL;
a->complement = NULL;
/* Allocation/init, level 2.
*/
ESL_ALLOC(a->sym, sizeof(char) * (Kp+1));
ESL_ALLOC(a->ndegen, sizeof(int) * Kp);
ESL_ALLOC(a->degen, sizeof(char *) * Kp);
a->degen[0] = NULL;
/* Allocation/init, level 3.
*/
ESL_ALLOC(a->degen[0], sizeof(char) * (Kp*K));
for (x = 1; x < Kp; x++)
a->degen[x] = a->degen[0]+(K*x);
/* Initialize the internal alphabet:
*/
a->type = eslNONSTANDARD;
a->K = K;
a->Kp = Kp;
strcpy(a->sym, alphabet);
/* Initialize the input map, mapping ASCII seq chars to digital codes,
* and eslDSQ_ILLEGAL for everything else.
*/
for (c = 0; c < 128; c++) a->inmap[c] = eslDSQ_ILLEGAL;
for (x = 0; x < a->Kp; x++) a->inmap[(int) a->sym[x]] = x;
/* Initialize the degeneracy map:
* Base alphabet (first K syms) are automatically
* mapped uniquely; (Kp-3) is assumed to be
* the "any" character; other degen chars (K+1..Kp-4) are
* unset; gap, nonresidue, missing character are unmapped (ndegen=0)
*/
for (x = 0; x < a->Kp; x++) /* clear everything */
{
a->ndegen[x] = 0;
for (y = 0; y < a->K; y++) a->degen[x][y] = 0;
}
for (x = 0; x < a->K; x++) /* base alphabet */
{
a->ndegen[x] = 1;
a->degen[x][x] = 1;
}
/* "any" character */
a->ndegen[Kp-3] = K;
for (x = 0; x < a->K; x++) a->degen[Kp-3][x] = 1;
return a;
ERROR:
esl_alphabet_Destroy(a);
return NULL;
}
/* create_rna():
* Creates a standard RNA alphabet.
*/
static ESL_ALPHABET *
create_rna(void)
{
ESL_ALPHABET *a = NULL;
int status;
/* Create the fundamental alphabet
*/
if ((a = esl_alphabet_CreateCustom("ACGU-RYMKSWHBVDN*~", 4, 18)) == NULL) return NULL;
a->type = eslRNA;
/* Add desired synonyms in the input map.
*/
esl_alphabet_SetEquiv(a, 'T', 'U'); /* read T as a U */
esl_alphabet_SetEquiv(a, 'X', 'N'); /* read X as an N (many seq maskers use X) */
esl_alphabet_SetEquiv(a, 'I', 'A'); /* Inosine is a deaminated Adenosine, appears in some RNACentral sequences */
esl_alphabet_SetEquiv(a, '_', '-'); /* allow _ as a gap too */
esl_alphabet_SetEquiv(a, '.', '-'); /* allow . as a gap too */
esl_alphabet_SetCaseInsensitive(a); /* allow lower case input */
/* Define degenerate symbols.
*/
esl_alphabet_SetDegeneracy(a, 'R', "AG");
esl_alphabet_SetDegeneracy(a, 'Y', "CU");
esl_alphabet_SetDegeneracy(a, 'M', "AC");
esl_alphabet_SetDegeneracy(a, 'K', "GU");
esl_alphabet_SetDegeneracy(a, 'S', "CG");
esl_alphabet_SetDegeneracy(a, 'W', "AU");
esl_alphabet_SetDegeneracy(a, 'H', "ACU");
esl_alphabet_SetDegeneracy(a, 'B', "CGU");
esl_alphabet_SetDegeneracy(a, 'V', "ACG");
esl_alphabet_SetDegeneracy(a, 'D', "AGU");
if ( (status = set_complementarity(a)) != eslOK) goto ERROR;
return a;
ERROR:
esl_alphabet_Destroy(a);
return NULL;
}
/* create_dna():
* creates and returns a standard DNA alphabet.
*/
static ESL_ALPHABET *
create_dna(void)
{
ESL_ALPHABET *a = NULL;
int status;
/* Create the fundamental alphabet.
*/
if ((a = esl_alphabet_CreateCustom("ACGT-RYMKSWHBVDN*~", 4, 18)) == NULL) return NULL;
a->type = eslDNA;
/* Add desired synonyms in the input map.
*/
esl_alphabet_SetEquiv(a, 'U', 'T'); /* read U as a T */
esl_alphabet_SetEquiv(a, 'X', 'N'); /* read X as an N (many seq maskers use X) */
esl_alphabet_SetEquiv(a, 'I', 'A'); /* Inosine is a deaminated Adenosine, appears in some RNACentral sequences */
esl_alphabet_SetEquiv(a, '_', '-'); /* allow _ as a gap too */
esl_alphabet_SetEquiv(a, '.', '-'); /* allow . as a gap too */
esl_alphabet_SetCaseInsensitive(a); /* allow lower case input */
/* Define IUBMB degenerate symbols other than the N.
*/
esl_alphabet_SetDegeneracy(a, 'R', "AG");
esl_alphabet_SetDegeneracy(a, 'Y', "CT");
esl_alphabet_SetDegeneracy(a, 'M', "AC");
esl_alphabet_SetDegeneracy(a, 'K', "GT");
esl_alphabet_SetDegeneracy(a, 'S', "CG");
esl_alphabet_SetDegeneracy(a, 'W', "AT");
esl_alphabet_SetDegeneracy(a, 'H', "ACT");
esl_alphabet_SetDegeneracy(a, 'B', "CGT");
esl_alphabet_SetDegeneracy(a, 'V', "ACG");
esl_alphabet_SetDegeneracy(a, 'D', "AGT");
if ( (status = set_complementarity(a)) != eslOK) goto ERROR;
return a;
ERROR:
esl_alphabet_Destroy(a);
return NULL;
}
/* create_amino():
* Creates a new standard amino acid alphabet.
*/
static ESL_ALPHABET *
create_amino(void)
{
ESL_ALPHABET *a = NULL;
/* Create the internal alphabet
*/
if ((a = esl_alphabet_CreateCustom("ACDEFGHIKLMNPQRSTVWY-BJZOUX*~", 20, 29)) == NULL) return NULL;
a->type = eslAMINO;
/* Add desired synonyms in the input map.
*/
esl_alphabet_SetEquiv(a, '_', '-'); /* allow _ as a gap too */
esl_alphabet_SetEquiv(a, '.', '-'); /* allow . as a gap too */
esl_alphabet_SetCaseInsensitive(a); /* allow lower case input */
/* Define IUPAC degenerate symbols other than the X.
*/
esl_alphabet_SetDegeneracy(a, 'B', "ND");
esl_alphabet_SetDegeneracy(a, 'J', "IL");
esl_alphabet_SetDegeneracy(a, 'Z', "QE");
/* Define unusual residues as one-to-one degeneracies.
*/
esl_alphabet_SetDegeneracy(a, 'U', "C"); /* selenocysteine is scored as cysteine */
esl_alphabet_SetDegeneracy(a, 'O', "K"); /* pyrrolysine is scored as lysine */
return a;
}
/* create_coins():
* Creates a toy alphabet for coin examples
*/
static ESL_ALPHABET *
create_coins(void)
{
ESL_ALPHABET *a = NULL;
/* Create the internal alphabet
*/
if ((a = esl_alphabet_CreateCustom("HT-X*~", 2, 6)) == NULL) return NULL;
a->type = eslCOINS;
/* Add desired synonyms in the input map.
*/
esl_alphabet_SetEquiv(a, '_', '-'); /* allow _ as a gap too */
esl_alphabet_SetEquiv(a, '.', '-'); /* allow . as a gap too */
esl_alphabet_SetCaseInsensitive(a); /* allow lower case input */
/* There are no degeneracies in the coin alphabet. */
return a;
}
/* create_dice():
* Creates a toy alphabet for dice examples
*/
static ESL_ALPHABET *
create_dice(void)
{
ESL_ALPHABET *a = NULL;
/* Create the internal alphabet
*/
if ((a = esl_alphabet_CreateCustom("123456-X*~", 6, 10)) == NULL) return NULL;
a->type = eslCOINS;
/* Add desired synonyms in the input map.
*/
esl_alphabet_SetEquiv(a, '_', '-'); /* allow _ as a gap too */
esl_alphabet_SetEquiv(a, '.', '-'); /* allow . as a gap too */
esl_alphabet_SetCaseInsensitive(a); /* allow lower case input */
/* There are no degeneracies in the dice alphabet. */
return a;
}
/* set_complementarity()
* Builds the "complement" lookup table for DNA, RNA alphabets.
*
* Throws <eslEINVAL> if the alphabet isn't <eslDNA> or <eslRNA>.
*/
static int
set_complementarity(ESL_ALPHABET *a)
{
int status;
if (a->type != eslRNA && a->type != eslDNA)
ESL_EXCEPTION(eslEINVAL, "alphabet isn't nucleic: no complementarity to set");
/* We will assume that Kp=18 and sym="ACGT-RYMKSWHBVDN*~" (or RNA equiv).
* Bug #h108 happened because routine fell out of sync w/ a change in alphabet.
* Don't let that happen again.
*/
ESL_DASSERT1(( a->Kp == 18 ));
ESL_DASSERT1(( a->sym[17] == '~' ));
ESL_ALLOC(a->complement, sizeof(ESL_DSQ) * a->Kp);
a->complement[0] = 3; /* A->T */
a->complement[1] = 2; /* C->G */
a->complement[2] = 1; /* G->C */
a->complement[3] = 0; /* T->A */
a->complement[4] = 4; /* - - */
a->complement[5] = 6; /* R->Y */
a->complement[6] = 5; /* Y->R */
a->complement[7] = 8; /* M->K */
a->complement[8] = 7; /* K->M */
a->complement[9] = 9; /* S S */
a->complement[10]= 10; /* W W */
a->complement[11]= 14; /* H->D */
a->complement[12]= 13; /* B->V */
a->complement[13]= 12; /* V->B */
a->complement[14]= 11; /* D->H */
a->complement[15]= 15; /* N N */
a->complement[16]= 16; /* * * */
a->complement[17]= 17; /* ~ ~ */
return eslOK;
ERROR:
return status;
}
/* Function: esl_alphabet_SetEquiv()
* Synopsis: Define an equivalent symbol.
*
* Purpose: Maps an additional input alphabetic symbol <sym> to
* an internal alphabet symbol <c>; for example,
* we might map T to U for an RNA alphabet, so that we
* allow for reading input DNA sequences.
*
* Args: sym - symbol to allow in the input alphabet; 'T' for example
* c - symbol to map <sym> to in the internal alphabet; 'U' for example
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <c> is not in the internal alphabet, or if <sym> is.
*/
int
esl_alphabet_SetEquiv(ESL_ALPHABET *a, char sym, char c)
{
char *sp = NULL;
ESL_DSQ x;
/* Contract checks */
if ((sp = strchr(a->sym, sym)) != NULL)
ESL_EXCEPTION(eslEINVAL, "symbol %c is already in internal alphabet, can't equivalence it", sym);
if ((sp = strchr(a->sym, c)) == NULL)
ESL_EXCEPTION(eslEINVAL, "char %c not in the alphabet, can't map to it", c);
x = sp - a->sym;
a->inmap[(int) sym] = x;
return eslOK;
}
/* Function: esl_alphabet_SetCaseInsensitive()
* Synopsis: Make an alphabet's input map case-insensitive.
*
* Purpose: Given a custom alphabet <a>, with all equivalences set,
* make the input map case-insensitive: for every
* letter that is mapped in either lower or upper
* case, map the other case to the same internal
* residue.
*
* For the standard alphabets, this is done automatically.
*
* Args: a - alphabet to make case-insensitive.
*
* Returns: <eslOK> on success.
*
* Throws: <eslECORRUPT> if any lower/uppercase symbol pairs
* are already both mapped to different symbols.
*/
int
esl_alphabet_SetCaseInsensitive(ESL_ALPHABET *a)
{
int lc, uc;
for (lc = 'a'; lc <= 'z'; lc++)
{
uc = toupper(lc);
if (esl_abc_CIsValid(a, lc) && ! esl_abc_CIsValid(a, uc)) a->inmap[uc] = a->inmap[lc];
else if (esl_abc_CIsValid(a, uc) && ! esl_abc_CIsValid(a, lc)) a->inmap[lc] = a->inmap[uc];
else if (esl_abc_CIsValid(a, lc) && esl_abc_CIsValid(a, uc) && a->inmap[uc] != a->inmap[lc])
ESL_EXCEPTION(eslECORRUPT, "symbols %c and %c map differently already (%c vs. %c)",
lc, uc, a->inmap[lc], a->inmap[uc]);
}
return eslOK;
}
/* Function: esl_alphabet_SetDegeneracy()
* Synopsis: Define degenerate symbol in custom alphabet.
*
* Purpose: Given an alphabet under construction,
* define the degenerate character <c> to mean
* any of the characters in the string <ds>.
*
* <c> must exist in the digital alphabet, as
* one of the optional degenerate residues (<K+1>..<Kp-3>).
* All the characters in the <ds> string must exist
* in the canonical alphabet (<0>..<K-1>).
*
* You may not redefine the mandatory all-degenerate character
* (typically <N> or <X>; <Kp-3> in the digital alphabet).
* It is defined automatically in all alphabets.
*
* Args: a - an alphabet under construction.
* c - degenerate character code; example: 'R'
* ds - string of base characters for c; example: "AG"
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <c> or <ds> arguments aren't valid.
*/
int
esl_alphabet_SetDegeneracy(ESL_ALPHABET *a, char c, char *ds)
{
char *sp;
ESL_DSQ x,y;
if ((sp = strchr(a->sym, c)) == NULL)
ESL_EXCEPTION(eslEINVAL, "no such degenerate character");
x = sp - a->sym;
/* A degenerate character must have code K+1..Kp-4.
* Kp-3, the all-degenerate character, is automatically
* created, and can't be remapped.
*/
if (x == a->Kp-3)
ESL_EXCEPTION(eslEINVAL, "can't redefine all-degenerate char %c", c);
if (x < a->K+1 || x >= a->Kp-2)
ESL_EXCEPTION(eslEINVAL, "char %c isn't in expected position in alphabet", c);
while (*ds != '\0') {
if ((sp = strchr(a->sym, *ds)) == NULL) ESL_EXCEPTION(eslEINVAL, "no such base character");
y = sp - a->sym;
if (! esl_abc_XIsCanonical(a, y)) ESL_EXCEPTION(eslEINVAL, "can't map degeneracy to noncanonical character");
a->degen[x][y] = 1;
a->ndegen[x]++;
ds++;
}
return eslOK;
}
/* Function: esl_alphabet_SetIgnored()
* Synopsis: Define a set of characters to be ignored in input.
*
* Purpose: Given an alphabet <a> (either standard or custom), define
* all the characters in string <ignoredchars> to be
* unmapped: valid, but ignored when converting input text.
*
* By default, the standard alphabets do not define any
* ignored characters.
*
* The most common ignored characters would be space, tab,
* and digits, to skip silently over whitespace and
* sequence coordinates when parsing loosely-defined
* sequence file formats.
*
* Args: a - alphabet to modify
* ignoredchars - string listing characters to ignore; i.e. " \t"
*
* Returns: <eslOK> on success.
*/
int
esl_alphabet_SetIgnored(ESL_ALPHABET *a, const char *ignoredchars)
{
int i;
for (i = 0; ignoredchars[i] != '\0'; i++) a->inmap[(int)ignoredchars[i]] = eslDSQ_IGNORED;
return eslOK;
}
/* Function: esl_alphabet_Sizeof()
* Synopsis: Returns size of an alphabet object, in bytes.
*
* Purpose: Returns the size of alphabet <a> object, in bytes.
*/
size_t
esl_alphabet_Sizeof(ESL_ALPHABET *a)
{
size_t n = 0;
n += sizeof(ESL_ALPHABET);
n += sizeof(char) * a->Kp; /* a->sym */
n += sizeof(char *) * a->Kp; /* a->degen */
n += sizeof(char) * (a->Kp * a->K); /* a->degen[][] */
n += sizeof(int) * a->Kp; /* a->ndegen */
if (a->complement) n += sizeof(ESL_DSQ) * a->Kp; /* a->complement */
return n;
}
/* Function: esl_alphabet_Destroy()
* Synopsis: Frees an alphabet object.
*
* Purpose: Free's an <ESL_ALPHABET> structure.
*
* Args: a - the <ESL_ALPHABET> to free.
*
* Returns: (void).
*/
void
esl_alphabet_Destroy(ESL_ALPHABET *a)
{
if (a)
{
if (a->sym) free(a->sym);
if (a->ndegen) free(a->ndegen);
if (a->degen)
{
if (a->degen[0]) free(a->degen[0]);
free(a->degen);
}
if (a->complement) free(a->complement);
free(a);
}
}
/*--------------- end, ESL_ALPHABET object ----------------------*/
/*****************************************************************
* 2. Digitized sequences (ESL_DSQ *)
*****************************************************************/
/* Design note: SRE, Mon Sep 18 09:11:41 2006
*
* An ESL_DSQ is considered to a special string type, equivalent to
* <char *>, and is not considered to be an Easel "object". Thus it
* does not have a standard object API. Rather, the caller deals with
* an ESL_DSQ directly: allocate for <(L+2)*sizeof(ESL_DSQ)> to leave
* room for sentinels at <0> and <L+1>.
*
* Additionally, an ESL_DSQ is considered to be "trusted"
* data: we're 'guaranteed' that anything in an ESL_DSQ is a valid
* symbol, so we don't need to error-check. Anything else is a programming
* error.
*/
/* Function: esl_abc_CreateDsq()
* Synopsis: Digitizes a sequence into new space.
*
* Purpose: Given an alphabet <a> and an ASCII sequence <seq>,
* digitize the sequence into newly allocated space, and
* return a pointer to that space in <ret_dsq>.
*
* Args: a - internal alphabet
* seq - text sequence to be digitized
* ret_dsq - RETURN: the new digital sequence
*
* Returns: <eslOK> on success, and <ret_dsq> contains the digitized
* sequence; caller is responsible for free'ing this
* memory. Returns <eslEINVAL> if <seq> contains
* one or more characters that are not in the input map of
* alphabet <a>. If this happens, <ret_dsq> is still valid upon
* return: invalid characters are replaced by full ambiguities
* (typically X or N).
*
* Throws: <eslEMEM> on allocation failure.
*
* Xref: STL11/63
*/
int
esl_abc_CreateDsq(const ESL_ALPHABET *a, const char *seq, ESL_DSQ **ret_dsq)
{
ESL_DSQ *dsq = NULL;
int status;
int64_t L;
L = strlen(seq);
ESL_ALLOC(dsq, sizeof(ESL_DSQ) * (L+2));
status = esl_abc_Digitize(a, seq, dsq);
if (ret_dsq != NULL) *ret_dsq = dsq; else free(dsq);
return status;
ERROR:
if (dsq != NULL) free(dsq);
if (ret_dsq != NULL) *ret_dsq = NULL;
return status;
}
/* Function: esl_abc_Digitize()
* Synopsis: Digitizes a sequence into existing space.
*
* Purpose: Given an alphabet <a> and a nul-terminated ASCII sequence
* <seq>, digitize the sequence and put it in <dsq>. Caller
* provides space in <dsq> allocated for at least <L+2>
* <ESL_DSQ> residues, where <L> is the length of <seq>.
*
* Args: a - internal alphabet
* seq - text sequence to be digitized (\0-terminated)
* dsq - RETURN: the new digital sequence (caller allocates,
* at least <(L+2) * sizeof(ESL_DSQ)>).
*
* Returns: <eslOK> on success.
* Returns <eslEINVAL> if <seq> contains one or more characters
* that are not recognized in the alphabet <a>. (This is classed
* as a normal error, because the <seq> may be untrusted user input.)
* If this happens, the digital sequence <dsq> is still valid upon
* return; invalid ASCII characters are replaced by ambiguities
* (X or N).
*/
int
esl_abc_Digitize(const ESL_ALPHABET *a, const char *seq, ESL_DSQ *dsq)
{
int status;
int64_t i; /* position in seq */
int64_t j; /* position in dsq */
ESL_DSQ x;
status = eslOK;
dsq[0] = eslDSQ_SENTINEL;
for (i = 0, j = 1; seq[i] != '\0'; i++)
{
x = a->inmap[(int) seq[i]];
if (esl_abc_XIsValid(a, x)) dsq[j] = x;
else if (x == eslDSQ_IGNORED) continue;
else {
status = eslEINVAL;
dsq[j] = esl_abc_XGetUnknown(a);
}
j++;
}
dsq[j] = eslDSQ_SENTINEL;
return status;
}
/* Function: esl_abc_Textize()
* Synopsis: Convert digital sequence to text.
*
* Purpose: Make an ASCII sequence <seq> by converting a digital
* sequence <dsq> of length <L> back to text, according to
* the digital alphabet <a>.
*
* Caller provides space in <seq> allocated for at least
* <L+1> bytes (<(L+1) * sizeof(char)>).
*
* Args: a - internal alphabet
* dsq - digital sequence to be converted (1..L)
* L - length of dsq
* seq - RETURN: the new text sequence (caller allocated
* space, at least <(L+1) * sizeof(char)>).
*
* Returns: <eslOK> on success.
*/
int
esl_abc_Textize(const ESL_ALPHABET *a, const ESL_DSQ *dsq, int64_t L, char *seq)
{
int64_t i;
for (i = 0; i < L; i++)
seq[i] = a->sym[dsq[i+1]];
seq[i] = '\0';
return eslOK;
}
/* Function: esl_abc_TextizeN()
* Synopsis: Convert subsequence from digital to text.
*
* Purpose: Similar in semantics to <strncpy()>, this procedure takes
* a window of <L> residues in a digitized sequence
* starting at the residue pointed to by <dptr>,
* converts them to ASCII text representation, and
* copies them into the buffer <buf>.
*
* <buf> must be at least <L> residues long; <L+1>, if the
* caller needs to NUL-terminate it.
*
* If a sentinel byte is encountered in the digitized
* sequence before <L> residues have been copied, <buf> is
* NUL-terminated there. Otherwise, like <strncpy()>, <buf>
* will not be NUL-terminated.
*
* Note that because digital sequences are indexed <1..N>,
* not <0..N-1>, the caller must be careful about
* off-by-one errors in <dptr>. For example, to copy from
* the first residue of a digital sequence <dsq>, you must
* pass <dptr=dsq+1>, not <dptr=dsq>. The text in <buf>
* on the other hand is a normal C string indexed <0..L-1>.
*
* Args: a - reference to an internal alphabet
* dptr - ptr to starting residue in a digital sequence
* L - number of residues to convert and copy
* buf - text buffer to store the <L> converted residues in
*
* Returns: <eslOK> on success.
*/
int
esl_abc_TextizeN(const ESL_ALPHABET *a, const ESL_DSQ *dptr, int64_t L, char *buf)
{
int64_t i;
for (i = 0; i < L; i++)
{
if (dptr[i] == eslDSQ_SENTINEL)
{
buf[i] = '\0';
return eslOK;
}
buf[i] = a->sym[dptr[i]];
}
return eslOK;
}
/* Function: esl_abc_dsqcpy()
*
* Purpose: Given a digital sequence <dsq> of length <L>,
* make a copy of it in <dcopy>. Caller provides
* storage in <dcopy> for at least <L+2> <ESL_DSQ>
* residues.
*
* Returns: <eslOK> on success.
*/
int
esl_abc_dsqcpy(const ESL_DSQ *dsq, int64_t L, ESL_DSQ *dcopy)
{
memcpy(dcopy, dsq, sizeof(ESL_DSQ) * (L+2));
return eslOK;
}
/* Function: esl_abc_dsqdup()
* Synopsis: Duplicate a digital sequence.
*
* Purpose: Like <esl_strdup()>, but for digitized sequences:
* make a duplicate of <dsq> and leave it in <ret_dup>.
* Caller can pass the string length <L> if it's known, saving
* some overhead; else pass <-1> and the length will be
* determined for you.
*
* Tolerates <dsq> being <NULL>; in which case, returns
* <eslOK> with <*ret_dup> set to <NULL>.
*
* Args: dsq - digital sequence to duplicate (w/ sentinels at 0,L+1)
* L - length of dsq in residues, if known; -1 if unknown
* ret_dup - RETURN: allocated duplicate of <dsq>, which caller will
* free.
*
* Returns: <eslOK> on success, and leaves a pointer in <ret_dup>.
*
* Throws: <eslEMEM> on allocation failure.
*
* Xref: STL11/48
*/
int
esl_abc_dsqdup(const ESL_DSQ *dsq, int64_t L, ESL_DSQ **ret_dup)
{
int status;
ESL_DSQ *new = NULL;
if (ret_dup == NULL) return eslOK; /* no-op. */
*ret_dup = NULL;
if (dsq == NULL) return eslOK;
if (L < 0) L = esl_abc_dsqlen(dsq);
ESL_ALLOC(new, sizeof(ESL_DSQ) * (L+2));
memcpy(new, dsq, sizeof(ESL_DSQ) * (L+2));
*ret_dup = new;
return eslOK;
ERROR:
if (new != NULL) free(new);
if (ret_dup != NULL) *ret_dup = NULL;
return status;
}
/* Function: esl_abc_dsqcat()
* Synopsis: Concatenate and map input chars to a digital sequence.
*
* Purpose: Append the contents of string or memory line <s> of
* length <n> to a digital sequence, after digitizing
* each input character in <s> according to an Easel
* <inmap>. The destination sequence and its length
* are passed by reference, <*dsq> and <*L>, so that
* the sequence may be reallocated and the length updated
* upon return.
*
* The input map <inmap> may map characters to
* <eslDSQ_IGNORED> or <eslDSQ_ILLEGAL>, but not to <eslDSQ_EOL>,
* <eslDSQ_EOD>, or <eslDSQ_SENTINEL> codes. <inmap[0]> is
* special, and must be set to the code for the 'unknown'
* residue (such as 'X' for proteins, 'N' for DNA) that
* will be used to replace any invalid <eslDSQ_ILLEGAL>
* characters.
*
* If <*dsq> is properly terminated digital sequence and
* the caller doesn't know its length, <*L> may be passed
* as -1. Providing the length when it's known saves an
* <esl_abc_dsqlen()> call. If <*dsq> is unterminated, <*L>
* is mandatory. Essentially the same goes for <*s>, which
* may be a NUL-terminated string (pass <n=-1> if length unknown),
* or a memory line (<n> is mandatory).
*
* <*dsq> may also be <NULL>, in which case it is allocated
* and initialized here.
*
* Caller should provide an <s> that is expected to be
* essentially all appendable to <*dsq> except for a small
* number of chars that map to <eslDSQ_IGNORE>, like an
* input sequence data line from a file, for example. We're
* going to reallocate <*dsq> to size <*L+n>; if <n> is an
* entire large buffer or file, this reallocation will be
* inefficient.
*
* Args: inmap - an Easel input map, inmap[0..127];
* inmap[0] is special, set to the 'unknown' character
* to replace invalid input chars.
* dsq - reference to the current digital seq to append to
* (with sentinel bytes at 0,L+1); may be <NULL>.
* Upon return, this will probably have
* been reallocated, and it will contain the original
* <dsq> with <s> digitized and appended.
* L - reference to the current length of <dsq> in residues;
* may be <-1> if unknown and if <*dsq> is a properly
* terminated digital sequence. Upon return, <L> is set to
* the new length of <dsq>, after <s> is appended.
* s - ASCII text sequence to append. May
* contain ignored text characters (flagged with
* <eslDSQ_IGNORED> in the input map of alphabet <abc>).
* n - Length of <s> in characters, if known; or <-1> if
* unknown and if <s> is a NUL-terminated string.
*
* Returns: <eslOK> on success; <*dsq> contains the result of digitizing
* and appending <s> to the original <*dsq>; and <*L> contains
* the new length of the <dsq> result in residues.
*
* If any of the characters in <s> are illegal in the
* alphabet <abc>, these characters are digitized as
* unknown residues (using <inmap[0]>) and
* concatenation/digitization proceeds to completion, but
* the function returns <eslEINVAL>. The caller might then
* want to call <esl_abc_ValidateSeq()> on <s> if it wants
* to figure out where digitization goes awry and get a
* more informative error report. This is a normal error,
* because the string <s> might be user input.
*
* Throws: <eslEMEM> on allocation or reallocation failure;
* <eslEINCONCEIVABLE> on coding error.
*
* Xref: SRE:STL11/48; SRE:J7/145.
*
* Note: This closely parallels a text mode version, <esl_strmapcat()>.
*/
int
esl_abc_dsqcat(const ESL_DSQ *inmap, ESL_DSQ **dsq, int64_t *L, const char *s, esl_pos_t n)
{
int status = eslOK;
if (*L < 0) *L = ((*dsq) ? esl_abc_dsqlen(*dsq) : 0);
if ( n < 0) n = ( (s) ? strlen(s) : 0);
if (n == 0) { goto ERROR; } /* that'll return eslOK, leaving *dest untouched, and *ldest its length */
if (*dsq == NULL) { /* an entirely new dsq is allocated *and* initialized with left sentinel. */
ESL_ALLOC(*dsq, sizeof(ESL_DSQ) * (n+2));
(*dsq)[0] = eslDSQ_SENTINEL;
} else /* else, existing dsq is just reallocated; leftmost sentinel already in place. */
ESL_REALLOC(*dsq, sizeof(ESL_DSQ) * (*L+n+2)); /* most we'll need */
return esl_abc_dsqcat_noalloc(inmap, *dsq, L, s, n);
ERROR:
return status;
}
/* Function: esl_abc_dsqcat_noalloc()
* Synopsis: Version of esl_abc_dsqcat() that does no reallocation.
*
* Purpose: Same as <esl_abc_dsqcat()>, but with no reallocation of
* <dsq>. The pointer to the destination string <dsq> is
* passed by value not by reference, because it will not
* be reallocated or moved. Caller has already allocated
* at least <*L + n + 2> bytes in <dsq>. <*L> and <n> are
* not optional; caller must know (and provide) the lengths
* of both the old string and the new source.
*
* Note: This version was needed in selex format parsing, where
* we need to prepend and append some number of gaps on
* each new line of each block of input; allocating once
* then adding the gaps and the sequence seemed most efficient.
*/
int
esl_abc_dsqcat_noalloc(const ESL_DSQ *inmap, ESL_DSQ *dsq, int64_t *L, const char *s, esl_pos_t n)
{
int64_t xpos;
esl_pos_t cpos;
ESL_DSQ x;
int status = eslOK;
/* Watch these coords. Start in the 0..n-1 text string at 0;
* start in the 1..L dsq at L+1, overwriting its terminal
* sentinel byte.
*/
for (xpos = *L+1, cpos = 0; cpos < n; cpos++)
{
if (! isascii(s[cpos])) { dsq[xpos++] = inmap[0]; status = eslEINVAL; continue; }
x = inmap[(int) s[cpos]];
if (x <= 127) dsq[xpos++] = x;
else switch (x) {
case eslDSQ_SENTINEL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_SENTINEL"); break;
case eslDSQ_ILLEGAL: dsq[xpos++] = inmap[0]; status = eslEINVAL; break;
case eslDSQ_IGNORED: break;
case eslDSQ_EOL: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOL"); break;
case eslDSQ_EOD: ESL_EXCEPTION(eslEINCONCEIVABLE, "input char mapped to eslDSQ_EOD"); break;
default: ESL_EXCEPTION(eslEINCONCEIVABLE, "bad inmap, no such ESL_DSQ code"); break;
}
}
dsq[xpos] = eslDSQ_SENTINEL;
*L = xpos-1;
return status;
}
/* Function: esl_abc_dsqlen()
* Synopsis: Returns the length of a digital sequence.
*
* Purpose: Returns the length of digitized sequence <dsq> in
* positions (including gaps, if any). The <dsq> must be
* properly terminated by a sentinel byte
* (<eslDSQ_SENTINEL>).
*/