Skip to content

Header API for SAM/BAM/CRAM - #812

Merged
daviesrob merged 54 commits into
samtools:developfrom
valeriuo:merge_headers
Jun 20, 2019
Merged

daviesrob merged 54 commits into
samtools:developfrom
valeriuo:merge_headers

Conversation

@valeriuo

@valeriuo valeriuo commented Jan 3, 2019 •

Copy link
Copy Markdown
Contributor

Management methods:

  • sam_hdr_init - create a new header
  • sam_hdr_destroy - free the resources used by the header
  • sam_hdr_read - read the header from a BGZF file
  • sam_hdr_write - write the header to a BGZF file
  • sam_hdr_dup - duplicate the header structure
  • sam_hdr_length - return the length of the header text
  • sam_hdr_str - return the header text as a string
  • sam_hdr_nref - return the number of references (@SQ lines)
  • sam_hdr_rebuild - rebuild the header text representation
  • sam_hdr_incr_ref - increment the reference counter on the header structure
  • sam_hdr_name2tid - convert reference name to reference index
  • sam_hdr_tid2name - retrieve reference name using the index (tid)
  • sam_hdr_tid2len - retrieve reference length using the index (tid)

Line level methods:

  • sam_hdr_add_lines - add a group of lines from a char buffer
  • sam_hdr_add_line - add a single line with individual key:value pairs
  • sam_hdr_find_line_id - find a line specified by a key:value identifier
  • sam_hdr_find_line_pos - find a line specified by position
  • sam_hdr_remove_line_id - remove a line specified by a key:value identifier
  • sam_hdr_remove_line_pos - remove a line specified by position
  • sam_hdr_update_line - update a line (works for tags)
  • sam_hdr_keep_line - remove all lines of the same type except the current one
  • sam_hdr_remove_lines - remove all lines, except the one specified by the hash set arg
  • sam_hdr_count_lines - count the header lines
  • sam_hdr_add_pg - add a new @PG line
  • sam_hdr_find_hd - return the @HD line
  • sam_hdr_update_hd - @HD line update specific macro

Tag level methods:

  • sam_hdr_find_tag_id - find a tag in a line specified by a key:value identifier
  • sam_hdr_find_tag_pos - find a tag in a line specified by position
  • sam_hdr_remove_tag_id - remove a tag from a line specified by a key:value identifier

Comment thread header.c
}

// @HD goes at the top (unless there's one already)
if (h_type->type == hd_type && hrecs->first_line->type != hd_type) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably prevent the addition of a second @HD line.

Comment thread header.c
if (-1 == bam_hrecs_vadd(hrecs, "PG", args,
"ID", id,
"PN", name,
"PN", !specified_pn ? name : "",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If specified_pp is not null, should it be used as an argument, i.e. "PP", specified_pp?

Comment thread htslib/sam.h
void bam_hdr_destroy(bam_hdr_t *h);
int bam_name2id(bam_hdr_t *h, const char *ref);
bam_hdr_t* bam_hdr_dup(const bam_hdr_t *h0);
/// Alias of bam_hdr_name2ref(), for backwards compatibility.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably ditch (deprecate) the use of bam_hdr_t.sdict altogether and make bam_name2id an actual alias of bam_hdr_name2ref. Currently, they have different implementations.

Comment thread header.c Outdated
if (hrecs->refs_changed >= 0 && rebuild_target_arrays(bh) != 0)
return -1;

bam_hdr_link_pg(bh);

@valeriuo valeriuo Jun 4, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling bam_hdr_link_pg would result in resetting bh->text, which is not intuitive when calling bam_hdr_parse, or some of its callers that do not modify the header, such as bam_hdr_name2ref.
For example, the following code would result in a null text field, which is probably not the expected behaviour.

        samFile *in = sam_open("test_header.sam", "r");
        bam_hdr_t *h = sam_hdr_read(in);	
        int id = bam_hdr_name2ref(h, "ref2");
        printf("id=%d, header=%p\n", id, h->text);

Perhaps, a better place for the bam_hdr_link_pg call would be inside bam_hdr_rebuild.

@daviesrob

Copy link
Copy Markdown
Member

Added bam_hdr_find_line_pos(), which is useful for samtools merge.

All these _pos() functions take 1-based indexes. What is the reason for that? I'm tempted to change them to zero-based as it's annoying to have to put +1 when they are used in a normal for-loop, or when accessing an @SQline with a known tid.

@valeriuo

Copy link
Copy Markdown
Contributor Author

It is just a matter of convention. I was thinking that people see the lines more as 1st @SQ, 2nd @SQ, ... and not like array indices. But if you think it makes more sense to change to a 0-based numeration, I have nothing against.

Comment thread header.c Outdated
static int build_header_line(const bam_hrec_type_t *ty, kstring_t *ks) {
bam_hrec_tag_t *tag;
int r = 0;
char c[2]= { ty->type >> 8, ty->type & 0xff };;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra semicolon.

Comment thread header.c Outdated

int bam_hdr_find_line_pos(bam_hdr_t *bh, const char *type,
int pos, kstring_t *ks) {
bam_hrecs_t *hrecs;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Different indentation.

Comment thread header.c
int bam_hdr_find_line_pos(bam_hdr_t *bh, const char *type,
int pos, kstring_t *ks) {
bam_hrecs_t *hrecs;
if (!bh || !type)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should check for null type in bam_hdr_find_line_id:1026.

valeriuo and others added 15 commits June 18, 2019 16:34
1. Added support for @hd GO (group order) tag.
2. Preserve order of the types as they appear in the original file.
3. Added the possibility of removing a key from an existing line.
4. Fixed the display of the @co lines in the header dump.
The strings being copied are allocated from the string pool,
which is immutable and has the same life-time as the header.  It
is therefore safe to point at the existing strings in the hash
tables.

Co-Authored-By: Rob Davies <[email protected]>
… when there is a need for reading it.

sam_hdr_error(), string_dup() and string_ndup() now take
const pointers to the data they are printing / copying so
they can be used with const inputs.
Makes the diffs for the copy to header.c in the next commit easier
to read.
Removes bam_hrecs_t text kstring as it duplicates the existing
bam_hdr_t text field.  bam_hdr_t text is freed and set to NULL
when the new API functions are used to make an edit so that
outdated text cannot be used in error.

Remove bam_hrecs_t ref_count as bam_hdr_t now has one.

Still a lot of work to be done, but a solid first step.

Co-Authored-By: Rob Davies <[email protected]>
Co-Authored-By: Rob Davies <[email protected]>
  Added extra comments and details.
  Made cigar_tab statically allocated.
  Made KS_FREE set the string pointer to NULL.
  Add a couple of warnings.
bootstrap_bam_hrecs() becomes bam_hrecs_populate()
sam_hdr_find_update2() becomes sam_hdr_update_line()
sam_hdr_keep_line_key2() becomes sam_hdr_keep_line()
sam_hdr_PG_ID2() becomes sam_hdr_pg_id()
sam_hdr_add_PG2() becomes sam_hdr_add_pg()

sam_hdr_rebuild2() and sam_hdr_update_line() are moved.

Conflicts:

	header.c
daviesrob and others added 13 commits June 18, 2019 16:34
Adds a global line order linked list for all header records.  This
allows the input header to be reconstructed exactly when passed
through the new header API.  (The one exception to this is that an
out-of-order @hd line will be lifted to the top of the header).

Headers added programatically will currently be placed immediately
after the last existing line of the same type, of at the end
of the header if no line of the given type is present.

Removes special handling for comments.

Simplifies bam_hrecs_rebuild_text() as it now just has to walk
through the global linked list.
Add documentation for some functions that were missed before

Add note about legacy bam_hdr_t::text and bam_hdr_t::l_text fields

Add some information on ownership of returned strings

Adjust doxygen formatting to be similar to other functions in
htslib/sam.h.  In particular put a one-line abstract in a '///'
comment before the main documentation block.

Backslash-escape @-signs that are part of header record types.

Remove stray bam_name2id() declaration.
Remove bam_hdr_link_pg() from public API as it should not
be necessary to call it directly.

Make bam_hdr_add_pg() work when ID, PP and PN tags are passed
to it in the varargs list.

Make bam_hrecs_vadd() ignore tags passed in its varargs list
which have an empty string as value.  This allows them to be
ignored when the same tag exists in the args va_list.

Add various bam_hdr_add_pg() tests.
Instead of returning char *, write the output into a kstring.
Allows the caller to easily reuse allocated memory when calling
them repeatedly.

Includes some documentation fixes.
…er line identified by type and position.

Rename methods to highlight if the line identification is done by key:value pair or by position.
Make `bam_name2id` static inline.
Also fix double semicolon in bam_hrecs_remove_line() and incorrect
indentation in bam_hdr_find_line_pos().
@jkbonfield

Copy link
Copy Markdown
Contributor

While we're here, we should make bam_hdr_len and related functions return size_t (or ssize_t if they need negatives for errors). See samtools/samtools#1066 for reasons why.

This also means changing the l_text field, or at least having a separate copy that the new API is using so the bam_hdr_len function can return large headers.

Allows (at least on 64-bit platforms with enough RAM) headers
longer than the usual 2^31 byte limit.  Such headers cannot
be written to BAM or CRAM files due to format limits, but
should be usable with SAM.  Attempting to write them to BAM
or CRAM will print an error message and fail.

Places where the header length gets used are upgraded to
use size_t as well.

Makes sam_hdr_sanitise() only check how long the header is
if it really wants to resize it.

Prevent h->l_text from being set to an incorrect value if
old_sam_hdr_change_HD() fails.

Also fixes possible infinite loop in sam_hdr_write() when
searching for @sq lines.
Comment thread sam.c Resolved
daviesrob added a commit to daviesrob/htslib that referenced this pull request Jun 20, 2019
Add NEWS item.

Bump TWO_TO_THREE_TRANSITION_COUNT due to ABI changes.
@daviesrob
daviesrob merged commit 13c9e5b into samtools:develop Jun 20, 2019
@jmarshall

Copy link
Copy Markdown
Member

It is great that HTSlib will finally have a header API 🎉

It is a little bit of a shame that the new functions are of the form bam_hdr_xyz() when HTSlib's convention for generic SAM/BAM/CRAM functions is a sam_ prefix. (cf e.g. bam_hdr_read() which works for BAM files only vs. sam_hdr_read() which is for any of SAM/BAM/CRAM.)

Adding a new swathe of header API seems like an opportunity to make the canonical header struct be sam_hdr_t (with a compatibility bam_hdr_t typedef) and have all the new functions be called sam_hdr_xyz() and perhaps provide sam_hdr_abc()/bam_hdr_abc() names for existing bam_hdr_ functions.

Was this sam_hdr_ naming approach considered during development of this header API?

If they might not have time/interest/priorities to do it themselves, would the maintainers be amenable to pull requests making the new header API functions be named sam_hdr_ etc?

@daviesrob

Copy link
Copy Markdown
Member

@jmarshall Yes it was, it changed in 7f876cf. I don't particularly want to change it back at this point.

I think the sam_hdr_ prefix has a few clashes with pre-existing bits of API, which made it not work quite so well.

@jmarshall

Copy link
Copy Markdown
Member

I can see why having successfully merged this after so many years of the saga, you would be less than keen to reopen it again. 😄

But if the maintainers can bear to look at it for the sake of HTSlib's sam_ convention, #887 is a proposal for doing this.

There were no troublesome clashes with pre-existing API bits and pieces; I suspect that problem may have been limited to this PR when it was in its intermediate state with various parts still up in the air.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants