]> git.donarmstrong.com Git - samtools.git/blob - sam_header.c
* BUGGY VERSION. Please NOT use it.
[samtools.git] / sam_header.c
1 #include "sam_header.h"
2 #include <stdio.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include <stdlib.h>
6 #include <stdarg.h>
7
8 #include "khash.h"
9 KHASH_MAP_INIT_STR(str, const char *)
10
11 struct _HeaderList
12 {
13     struct _HeaderList *next;
14     void *data;
15 };
16 typedef struct _HeaderList list_t;
17 typedef list_t HeaderDict;
18
19 typedef struct
20 {
21     char key[2];
22     char *value;
23 }
24 HeaderTag;
25
26 typedef struct
27 {
28     char type[2];
29     list_t *tags;
30 }
31 HeaderLine;
32
33 const char *o_hd_tags[] = {"SO","GO",NULL};
34 const char *r_hd_tags[] = {"VN",NULL};
35
36 const char *o_sq_tags[] = {"AS","M5","UR","SP",NULL};
37 const char *r_sq_tags[] = {"SN","LN",NULL};
38 const char *u_sq_tags[] = {"SN",NULL};
39
40 const char *o_rg_tags[] = {"LB","DS","PU","PI","CN","DT","PL",NULL};
41 const char *r_rg_tags[] = {"ID",NULL};
42 const char *u_rg_tags[] = {"ID",NULL};
43
44 const char *o_pg_tags[] = {"VN","CL",NULL};
45 const char *r_pg_tags[] = {"ID",NULL};
46
47 const char *types[]          = {"HD","SQ","RG","PG","CO",NULL};
48 const char **optional_tags[] = {o_hd_tags,o_sq_tags,o_rg_tags,o_pg_tags,NULL,NULL};
49 const char **required_tags[] = {r_hd_tags,r_sq_tags,r_rg_tags,r_pg_tags,NULL,NULL};
50 const char **unique_tags[]   = {NULL,     u_sq_tags,u_rg_tags,NULL,NULL,NULL};
51
52
53 void debug(const char *format, ...)
54 {
55     va_list ap;
56     va_start(ap, format);
57     vfprintf(stderr, format, ap);
58     va_end(ap);
59 }
60
61 void error(const char *format, ...)
62 {
63     va_list ap;
64     va_start(ap, format);
65     vfprintf(stderr, format, ap);
66     va_end(ap);
67     exit(-1);
68 }
69
70 list_t *list_append(list_t *root, void *data)
71 {
72     list_t *l = root;
73     while (l && l->next)
74         l = l->next;
75     if ( l ) 
76     {
77         l->next = malloc(sizeof(list_t));
78         l = l->next;
79     }
80     else
81     {
82         l = malloc(sizeof(list_t));
83         root = l;
84     }
85     l->data = data;
86     l->next = NULL;
87     return root;
88 }
89
90 void list_free(list_t *root)
91 {
92     list_t *l = root;
93     while (root)
94     {
95         l = root;
96         root = root->next;
97         free(l);
98     }
99 }
100
101
102
103 // Look for a tag "XY" in a predefined const char *[] array.
104 int tag_exists(const char *tag, const char **tags)
105 {
106     int itag=0;
107     if ( !tags ) return -1;
108     while ( tags[itag] )
109     {
110         if ( tags[itag][0]==tag[0] && tags[itag][1]==tag[1] ) return itag; 
111         itag++;
112     }
113     return -1;
114 }
115
116
117
118 // Mimics the behaviour of getline, except it returns pointer to the next chunk of the text
119 //  or NULL if everything has been read. The lineptr should be freed by the caller. The
120 //  newline character is stripped.
121 const char *nextline(char **lineptr, size_t *n, const char *text)
122 {
123     int len;
124     const char *to = text;
125
126     if ( !*to ) return NULL;
127
128     while ( *to && *to!='\n' && *to!='\r' ) to++;
129     len = to - text + 1;
130
131     if ( *to )
132     {
133         // Advance the pointer for the next call
134         if ( *to=='\n' ) to++;
135         else if ( *to=='\r' && *(to+1)=='\n' ) to+=2;
136     }
137     if ( !len )
138         return to;
139
140     if ( !*lineptr ) 
141     {
142         *lineptr = malloc(len);
143         *n = len;
144     }
145     else if ( *n<len ) 
146     {
147         *lineptr = realloc(*lineptr, len);
148         *n = len;
149     }
150     if ( !*lineptr )
151             error("FIXME\n");
152
153     memcpy(*lineptr,text,len);
154     (*lineptr)[len-1] = 0;
155
156     return to;
157 }
158
159 // name points to "XY", value_from points to the first character of the value string and
160 //  value_to points to the last character of the value string.
161 HeaderTag *new_tag(const char *name, const char *value_from, const char *value_to)
162 {
163     HeaderTag *tag = malloc(sizeof(HeaderTag));
164     int len = value_to-value_from+1;
165
166     tag->key[0] = name[0];
167     tag->key[1] = name[1];
168     tag->value = malloc(len+1);
169     memcpy(tag->value,value_from,len+1);
170     tag->value[len] = 0;
171     return tag;
172 }
173
174 HeaderTag *header_line_has_tag(HeaderLine *hline, const char *key)
175 {
176     list_t *tags = hline->tags;
177     while (tags)
178     {
179         HeaderTag *tag = tags->data;
180         if ( tag->key[0]==key[0] && tag->key[1]==key[1] ) return tag;
181         tags = tags->next;
182     }
183     return NULL;
184 }
185
186
187 // Return codes:
188 //   0 .. different types or unique tags differ or conflicting tags, cannot be merged
189 //   1 .. all tags identical -> no need to merge, drop one
190 //   2 .. the unique tags match and there are some conflicting tags (same tag, different value) -> error, cannot be merged nor duplicated
191 //   3 .. there are some missing complementary tags and no unique conflict -> can be merged into a single line
192 int sam_header_compare_lines(HeaderLine *hline1, HeaderLine *hline2)
193 {
194     HeaderTag *t1, *t2;
195
196     if ( hline1->type[0]!=hline2->type[0] || hline1->type[1]!=hline2->type[1] )
197         return 0;
198
199     int itype = tag_exists(hline1->type,types);
200     if ( itype==-1 ) error("[sam_header_compare_lines] Unknown type [%c%c]\n", hline1->type[0],hline1->type[1]);
201
202     if ( unique_tags[itype] )
203     {
204         t1 = header_line_has_tag(hline1,unique_tags[itype][0]);
205         t2 = header_line_has_tag(hline2,unique_tags[itype][0]);
206         if ( !t1 || !t2 ) // this should never happen, the unique tags are required
207             return 2;
208
209         if ( strcmp(t1->value,t2->value) )
210             return 0;   // the unique tags differ, cannot be merged
211     }
212     if ( !required_tags[itype] && !optional_tags[itype] )
213     {
214         t1 = hline1->tags->data;
215         t2 = hline2->tags->data;
216         if ( !strcmp(t1->value,t2->value) ) return 1; // identical comments
217         return 0;
218     }
219
220     int missing=0, itag=0;
221     while ( required_tags[itype] && required_tags[itype][itag] )
222     {
223         t1 = header_line_has_tag(hline1,required_tags[itype][itag]);
224         t2 = header_line_has_tag(hline2,required_tags[itype][itag]);
225         if ( !t1 && !t2 )
226             return 2;       // this should never happen
227         else if ( !t1 || !t2 )
228             missing = 1;    // there is some tag missing in one of the hlines
229         else if ( strcmp(t1->value,t2->value) )
230         {
231             if ( unique_tags[itype] )
232                 return 2;   // the lines have a matching unique tag but have a conflicting tag
233                     
234             return 0;    // the lines contain conflicting tags, cannot be merged
235         }
236         itag++;
237     }
238     itag = 0;
239     while ( optional_tags[itype] && optional_tags[itype][itag] )
240     {
241         t1 = header_line_has_tag(hline1,optional_tags[itype][itag]);
242         t2 = header_line_has_tag(hline2,optional_tags[itype][itag]);
243         if ( !t1 && !t2 )
244         {
245             itag++;
246             continue;
247         }
248         if ( !t1 || !t2 )
249             missing = 1;    // there is some tag missing in one of the hlines
250         else if ( strcmp(t1->value,t2->value) )
251         {
252             if ( unique_tags[itype] )
253                 return 2;   // the lines have a matching unique tag but have a conflicting tag
254
255             return 0;   // the lines contain conflicting tags, cannot be merged
256         }
257         itag++;
258     }
259     if ( missing ) return 3;    // there are some missing complementary tags with no conflicts, can be merged
260     return 1;
261 }
262
263
264 HeaderLine *sam_header_line_clone(const HeaderLine *hline)
265 {
266     list_t *tags;
267     HeaderLine *out = malloc(sizeof(HeaderLine));
268     out->type[0] = hline->type[0];
269     out->type[1] = hline->type[1];
270     out->tags = NULL;
271
272     tags = hline->tags;
273     while (tags)
274     {
275         HeaderTag *old = tags->data;
276
277         HeaderTag *new = malloc(sizeof(HeaderTag));
278         new->key[0] = old->key[0];
279         new->key[1] = old->key[1];
280         new->value  = strdup(old->value);
281         out->tags = list_append(out->tags, new);
282
283         tags = tags->next;
284     }
285     return out;
286 }
287
288 int sam_header_line_merge_with(HeaderLine *out_hline, const HeaderLine *tmpl_hline)
289 {
290     list_t *tmpl_tags;
291
292     if ( out_hline->type[0]!=tmpl_hline->type[0] || out_hline->type[1]!=tmpl_hline->type[1] )
293         return 0;
294     
295     tmpl_tags = tmpl_hline->tags;
296     while (tmpl_tags)
297     {
298         HeaderTag *tmpl_tag = tmpl_tags->data;
299         HeaderTag *out_tag  = header_line_has_tag(out_hline, tmpl_tag->key);
300         if ( !out_tag )
301         {
302             HeaderTag *tag = malloc(sizeof(HeaderTag));
303             tag->key[0] = tmpl_tag->key[0];
304             tag->key[1] = tmpl_tag->key[1];
305             tag->value  = strdup(tmpl_tag->value);
306             out_hline->tags = list_append(out_hline->tags,tag);
307         }
308         tmpl_tags = tmpl_tags->next;
309     }
310     return 1;
311 }
312
313
314 HeaderLine *sam_header_line_parse(const char *headerLine)
315 {
316     HeaderLine *hline;
317     HeaderTag *tag;
318     const char *from, *to;
319     from = headerLine;
320
321     if ( *from != '@' ) error("[sam_header_line_parse] expected '@', got [%s]\n", headerLine);
322     to = ++from;
323
324     while (*to && *to!='\t') to++;
325     if ( to-from != 2 ) error("[sam_header_line_parse] expected '@XY', got [%s]\n", headerLine);
326     
327     hline = malloc(sizeof(HeaderLine));
328     hline->type[0] = from[0];
329     hline->type[1] = from[1];
330     hline->tags = NULL;
331
332     int itype = tag_exists(hline->type, types);
333     
334     from = to;
335     while (*to && *to=='\t') to++;
336     if ( to-from != 1 ) 
337         error("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
338     from = to;
339     while (*from)
340     {
341         while (*to && *to!='\t') to++;
342
343         if ( !required_tags[itype] && !optional_tags[itype] )
344             tag = new_tag("  ",from,to-1);
345         else
346             tag = new_tag(from,from+3,to-1);
347
348         if ( header_line_has_tag(hline,tag->key) ) 
349                 debug("The tag '%c%c' present (at least) twice on line [%s]\n", tag->key[0],tag->key[1], headerLine);
350         hline->tags = list_append(hline->tags, tag);
351
352         from = to;
353         while (*to && *to=='\t') to++;
354         if ( *to && to-from != 1 ) 
355                 error("[sam_header_line_parse] multiple tabs on line [%s] (%d)\n", headerLine,(int)(to-from));
356
357         from = to;
358     }
359     return hline;
360 }
361
362
363 // Must be of an existing type, all tags must be recognised and all required tags must be present
364 int sam_header_line_validate(HeaderLine *hline)
365 {
366     list_t *tags;
367     HeaderTag *tag;
368     int itype, itag;
369     
370     // Is the type correct?
371     itype = tag_exists(hline->type, types);
372     if ( itype==-1 ) 
373     {
374         debug("The type [%c%c] not recognised.\n", hline->type[0],hline->type[1]);
375         return 0;
376     }
377
378     // Has all required tags?
379     itag = 0;
380     while ( required_tags[itype] && required_tags[itype][itag] )
381     {
382         if ( !header_line_has_tag(hline,required_tags[itype][itag]) )
383         {
384             debug("The tag [%c%c] required for [%c%c] not present.\n", required_tags[itype][itag][0],required_tags[itype][itag][1],
385                 hline->type[0],hline->type[1]);
386             return 0;
387         }
388         itag++;
389     }
390
391     // Are all tags recognised?
392     tags = hline->tags;
393     while ( tags )
394     {
395         tag = tags->data;
396         if ( !tag_exists(tag->key,required_tags[itype]) && !tag_exists(tag->key,optional_tags[itype]) )
397         {
398             debug("Unknown tag [%c%c] for [%c%c].\n", tag->key[0],tag->key[1], hline->type[0],hline->type[1]);
399             return 0;
400         }
401         tags = tags->next;
402     }
403
404     return 1;
405 }
406
407
408 void print_header_line(FILE *fp, HeaderLine *hline)
409 {
410     list_t *tags = hline->tags;
411     HeaderTag *tag;
412
413     fprintf(fp, "@%c%c", hline->type[0],hline->type[1]);
414     while (tags)
415     {
416         tag = tags->data;
417
418         fprintf(fp, "\t");
419         if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
420             fprintf(fp, "%c%c:", tag->key[0],tag->key[1]);
421         fprintf(fp, "%s", tag->value);
422
423         tags = tags->next;
424     }
425     fprintf(fp,"\n");
426 }
427
428
429 void sam_header_free(void *_header)
430 {
431         HeaderDict *header = (HeaderDict*)_header;
432     list_t *hlines = header;
433     while (hlines)
434     {
435         HeaderLine *hline = hlines->data;
436         list_t *tags = hline->tags;
437         while (tags)
438         {
439             HeaderTag *tag = tags->data;
440             free(tag->value);
441             free(tag);
442             tags = tags->next;
443         }
444         list_free(hline->tags);
445         free(hline);
446         hlines = hlines->next;
447     }
448     list_free(header);
449 }
450
451 HeaderDict *sam_header_clone(const HeaderDict *dict)
452 {
453     HeaderDict *out = NULL;
454     while (dict)
455     {
456         HeaderLine *hline = dict->data;
457         out = list_append(out, sam_header_line_clone(hline));
458         dict = dict->next;
459     }
460     return out;
461 }
462
463 // Returns a newly allocated string
464 char *sam_header_write(const void *_header)
465 {
466         const HeaderDict *header = (const HeaderDict*)_header;
467     char *out = NULL;
468     int len=0, nout=0;
469     const list_t *hlines;
470
471     // Calculate the length of the string to allocate
472     hlines = header;
473     while (hlines)
474     {
475         len += 4;   // @XY and \n
476
477         HeaderLine *hline = hlines->data;
478         list_t *tags = hline->tags;
479         while (tags)
480         {
481             HeaderTag *tag = tags->data;
482             len += strlen(tag->value) + 1;                  // \t
483             if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
484                 len += strlen(tag->value) + 3;              // XY:
485             tags = tags->next;
486         }
487         hlines = hlines->next;
488     }
489
490     nout = 0;
491     out  = malloc(len+1);
492     hlines = header;
493     while (hlines)
494     {
495         HeaderLine *hline = hlines->data;
496
497         nout += sprintf(out+nout,"@%c%c",hline->type[0],hline->type[1]);
498
499         list_t *tags = hline->tags;
500         while (tags)
501         {
502             HeaderTag *tag = tags->data;
503             nout += sprintf(out+nout,"\t");
504             if ( tag->key[0]!=' ' || tag->key[1]!=' ' )
505                 nout += sprintf(out+nout,"%c%c:", tag->key[0],tag->key[1]);
506             nout += sprintf(out+nout,"%s", tag->value);
507             tags = tags->next;
508         }
509         hlines = hlines->next;
510         nout += sprintf(out+nout,"\n");
511     }
512     out[len] = 0;
513     return out;
514 }
515
516 void *sam_header_parse2(const char *headerText)
517 {
518     list_t *hlines = NULL;
519     HeaderLine *hline;
520     const char *text;
521     char *buf=NULL;
522     size_t nbuf = 0;
523
524     if ( !headerText )
525         error("FIXME");
526
527     text = headerText;
528     while ( (text=nextline(&buf, &nbuf, text)) )
529     {
530         hline = sam_header_line_parse(buf);
531         if ( sam_header_line_validate(hline) )
532             hlines = list_append(hlines, hline);
533         else
534         {
535             sam_header_free(hlines);
536             return NULL;
537         }
538     }
539     if ( buf ) free(buf);
540
541     return hlines;
542 }
543
544 void *sam_header2tbl(const void *_dict, char type[2], char key_tag[2], char value_tag[2])
545 {
546         const HeaderDict *dict = (const HeaderDict*)_dict;
547     const list_t *l   = dict;
548     khash_t(str) *tbl = kh_init(str);
549     khiter_t k;
550     int ret;
551
552     while (l)
553     {
554         HeaderLine *hline = l->data;
555         if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) 
556         {
557             l = l->next;
558             continue;
559         }
560         
561         HeaderTag *key, *value;
562         key   = header_line_has_tag(hline,key_tag);
563         value = header_line_has_tag(hline,value_tag); 
564         if ( !key || !value )
565         {
566             l = l->next;
567             continue;
568         }
569         
570         k = kh_get(str, tbl, key->value);
571         if ( k != kh_end(tbl) )
572             debug("[sam_header_lookup_table] They key %s not unique.\n", key->value);
573         k = kh_put(str, tbl, key->value, &ret);
574         kh_value(tbl, k) = value->value;
575
576         l = l->next;
577     }
578     return tbl;
579 }
580
581 char **sam_header2list(const void *_dict, char type[2], char key_tag[2], int *_n)
582 {
583         const HeaderDict *dict = (const HeaderDict*)_dict;
584     const list_t *l   = dict;
585     int max, n;
586         char **ret;
587
588         ret = 0; *_n = max = n = 0;
589     while (l)
590     {
591         HeaderLine *hline = l->data;
592         if ( hline->type[0]!=type[0] || hline->type[1]!=type[1] ) 
593         {
594             l = l->next;
595             continue;
596         }
597         
598         HeaderTag *key;
599         key   = header_line_has_tag(hline,key_tag);
600         if ( !key )
601         {
602             l = l->next;
603             continue;
604         }
605
606                 if (n == max) {
607                         max = max? max<<1 : 4;
608                         ret = realloc(ret, max * sizeof(void*));
609                 }
610                 ret[n++] = key->value;
611
612         l = l->next;
613     }
614         *_n = n;
615     return ret;
616 }
617
618 const char *sam_tbl_get(void *h, const char *key)
619 {
620         khash_t(str) *tbl = (khash_t(str)*)h;
621         khint_t k;
622         k = kh_get(str, tbl, key);
623         return k == kh_end(tbl)? 0 : kh_val(tbl, k);
624 }
625
626 int sam_tbl_size(void *h)
627 {
628         khash_t(str) *tbl = (khash_t(str)*)h;
629         return h? kh_size(tbl) : 0;
630 }
631
632 void sam_tbl_destroy(void *h)
633 {
634         khash_t(str) *tbl = (khash_t(str)*)h;
635         kh_destroy(str, tbl);
636 }
637
638 void *sam_header_merge(int n, const void **_dicts)
639 {
640         const HeaderDict **dicts = (const HeaderDict**)_dicts;
641     HeaderDict *out_dict;
642     int idict, status;
643
644     if ( n<2 ) return NULL;
645
646     out_dict = sam_header_clone(dicts[0]);
647
648     for (idict=1; idict<n; idict++)
649     {
650         const list_t *tmpl_hlines = dicts[idict];
651
652         while ( tmpl_hlines )
653         {
654             list_t *out_hlines = out_dict;
655             int inserted = 0;
656             while ( out_hlines )
657             {
658                 status = sam_header_compare_lines(tmpl_hlines->data, out_hlines->data);
659                 if ( status==0 )
660                 {
661                     out_hlines = out_hlines->next;
662                     continue;
663                 }
664                 
665                 if ( status==2 ) 
666                 {
667                     print_header_line(stderr,tmpl_hlines->data);
668                     print_header_line(stderr,out_hlines->data);
669                     error("Conflicting lines, cannot merge the headers.\n");
670                 }
671                 if ( status==3 )
672                     sam_header_line_merge_with(out_hlines->data, tmpl_hlines->data);
673
674                 inserted = 1;
675                 break;
676             }
677             if ( !inserted )
678                 out_dict = list_append(out_dict, sam_header_line_clone(tmpl_hlines->data));
679
680             tmpl_hlines = tmpl_hlines->next;
681         }
682     }
683
684     return out_dict;
685 }
686
687