Skip to content
Merged
2 changes: 1 addition & 1 deletion .github/workflows/UnitTests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
fail-fast: false
matrix:
julia-version:
- '1.6' # LTS
- '1.11' # lowest compatible release

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not ideal to lose the current LTS, but I don't think it's a dealbreaker

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.

I think it's MemoryViews that requires 1.11

- '1'
julia-arch: [x64, x86]
os: [ubuntu-latest, windows-latest, macOS-latest]
Expand Down
19 changes: 15 additions & 4 deletions Project.toml
Original file line number Diff line number Diff line change
@@ -1,35 +1,46 @@
name = "XAM"
uuid = "d759349c-bcba-11e9-07c2-5b90f8f05f7c"
authors = ["Kenta Sato <bicycle1885@gmail.com>", "Ben J. Ward <ward9250@gmail.com>", "Ciarán O'Mara <Ciaran.OMara@utas.edu.au>"]
version = "0.4.2"
authors = ["Kenta Sato <bicycle1885@gmail.com>", "Ben J. Ward <ward9250@gmail.com>", "Ciarán O'Mara <Ciaran.OMara@utas.edu.au>"]

[deps]
Automa = "67c07d97-cdcb-5c2c-af73-a7f9c32a568b"
BGZFStreams = "28d598bf-9b8f-59f1-b38c-5a06b4a0f5e6"
BGZFLib = "b86bd9b6-aa64-492d-a0e2-e61a004d8aed"
BioAlignments = "00701ae9-d1dc-5365-b64a-a3a3ebf5695e"
BioGenerics = "47718e42-2ac5-11e9-14af-e5595289c2ea"
BioSequences = "7e6ae17a-c86d-528c-b3b9-7f778a29fe59"
BufferIO = "ff366017-094f-4144-bd70-a828a0d67152"
GenomicFeatures = "899a7d2d-5c61-547b-bef9-6698a8d05446"
Indexes = "4ffb77ac-cb80-11e8-1b35-4b78cc642f6d"
MemoryViews = "a791c907-b98b-4e44-8f4d-e4c2362c6b2f"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
TranscodingStreams = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"

[weakdeps]
BGZFStreams = "28d598bf-9b8f-59f1-b38c-5a06b4a0f5e6"

[compat]
Automa = "1"
BGZFStreams = "0.3.1"
BGZFLib = "0.1"
BioAlignments = "3"
BioGenerics = "0.1"
BioSequences = "3"
BufferIO = "0.2.5"
FormatSpecimens = "1.1"
GenomicFeatures = "2"
Indexes = "0.1"
MemoryViews = "0.4"
TranscodingStreams = "0.6, 0.7, 0.8, 0.9, 0.10, 0.11"
julia = "1.6"
julia = "1.11"

[extensions]
BGZFStreamsExt = "BGZFStreams"

[extras]
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
FormatSpecimens = "3372ea36-2a1a-11e9-3eb7-996970b6ffbd"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[targets]
test = ["Documenter", "FormatSpecimens", "Test"]
test = ["Documenter", "FormatSpecimens", "Test", "BGZFStreams"]
12 changes: 10 additions & 2 deletions docs/src/man/hts-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,22 @@ SAM.Writer(IOStream(<file my-data.sam>))

```

To make a BAM Writer is slightly different, as you need to use a specific stream type from the [https://github.com/BioJulia/BGZFStreams.jl](https://github.com/BioJulia/BGZFStreams.jl) package:
To make a BAM Writer is slightly different, as you need to use a specific stream type from the [https://github.com/BioJulia/BGZFLib.jl](https://github.com/BioJulia/BGZFLib.jl) package:
Comment thread
jakobnissen marked this conversation as resolved.
Resolved

```julia
julia> using BGZFLib

julia> bamw = BAM.Writer(BGZFLib.BGZFWriter(open("my-data.bam", "w")))
Comment thread
jakobnissen marked this conversation as resolved.
Resolved
BAM.Writer(BGZFWriter{BufferIO.BufWriter{IOStream}}())
```

BGZFStream is also supported for backward compatibility:

```
julia> using BGZFStreams

julia> bamw = BAM.Writer(BGZFStream(open("my-data.bam", "w"), "w"))
BAM.Writer(BGZFStreams.BGZFStream{IOStream}(<mode=write>))

```

Once you have a BAM or SAM writer, you can use the `write` method to write `BAM.Record`s or `SAM.Record`s to file:
Expand Down
33 changes: 33 additions & 0 deletions ext/BGZFStreamsExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module BGZFStreamsExt

using XAM
using BGZFStreams

import XAM.BAM: write_header

function write_header(stream::BGZFStreams.BGZFStream, header, refseqnames, refseqlens)
@assert length(refseqnames) == length(refseqlens) "Lengths of refseq names and lengths must match."
n = 0

# magic bytes
n += write(stream, "BAM\1")

# SAM header
buf = IOBuffer()
l = write(SAM.Writer(buf), header)
n += write(stream, Int32(l))
n += write(stream, take!(buf))

# reference sequences
n += write(stream, Int32(length(refseqnames)))
for (seqname, seqlen) in zip(refseqnames, refseqlens)
namelen = length(seqname)
n += write(stream, Int32(namelen + 1))
n += write(stream, seqname, '\0')
n += write(stream, Int32(seqlen))
end

return n
end

end
90 changes: 89 additions & 1 deletion src/bam/bam.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,102 @@ using XAM.SAM
import ..XAM: flags, XAMRecord, XAMReader, XAMWriter,
ismapped, isprimaryalignment, ispositivestrand, isnextmapped #TODO: Deprecate import of flag queries. These were imported to preseve existing API.

import BGZFStreams
import BGZFLib
import MemoryViews
import BioAlignments
import Indexes
import BioSequences
import BioGenerics: isfilled, header
import BufferIO

import GenomicFeatures: eachoverlap

# Indexes.Chunk.start/stop are BGZFStreams.VirtualOffset (a 64-bit primitive type).
# Convert to BGZFLib.VirtualOffset without importing BGZFStreams.
@inline function _to_virtual_offset(vo)
u = reinterpret(UInt64, vo)
BGZFLib.VirtualOffset(u >> 16, u & 0xffff)
end

@inline function load_le(
io::BufferIO.AbstractBufReader,
::Type{T}
) where T <: Union{Int16,UInt16,Int32,UInt32,Int64,UInt64,Float32,Float64}
# Fast path: Buffer has the data immediately available
buffer = BufferIO.get_buffer(io)
return if length(buffer) >= sizeof(T)
value = GC.@preserve buffer htol(unsafe_load(Ptr{T}(pointer(buffer))))
@inbounds BufferIO.consume(io, sizeof(T))
value
else
load_le_slowpath(io, T)
end
end

@noinline function load_le_slowpath(io::BufferIO.AbstractBufReader, T)
# Second fastest path: A single fill_buffer (called via get_nonempty_buffer)
# provides enough data, and then we load it immediately
buffer = BufferIO.get_nonempty_buffer(io)
sz = sizeof(T)
buffer === nothing && throw(EOFError())
if length(buffer) >= sz
value = GC.@preserve buffer htol(unsafe_load(Ptr{T}(pointer(buffer))))
@inbounds BufferIO.consume(io, sizeof(T))
return value
end

# Very unlikely path: The T does not fit in the buffer of the IO, so
# We need to store a temporary buffer.
memory = MemoryViews.MemoryView(Memory{UInt8}(undef, sizeof(T)))
remaining = memory
while true
buffer = @inbounds buffer[1:min(length(buffer), length(remaining))]
@inbounds copyto!(remaining, buffer)
@inbounds BufferIO.consume(io, length(buffer))
remaining = @inbounds remaining[length(buffer) + 1 : end]
if isempty(remaining)
value = GC.@preserve memory htol(unsafe_load(Ptr{T}(pointer(memory))))
return value
end
buffer = let
b = BufferIO.get_nonempty_buffer(io)
b === nothing && throw(EOFError())
b
end
end
end

@inline function store_le(
io::Union{BGZFLib.BGZFWriter, BGZFLib.SyncBGZFWriter},
x::T
) where T <: Union{Int16,UInt16,Int32,UInt32,Int64,UInt64,Float32,Float64}
x = htol(x)
# Fast path: Buffer already has room to store the T
buffer = BufferIO.get_buffer(io)
if length(buffer) >= sizeof(T)
GC.@preserve buffer unsafe_store!(Ptr{T}(pointer(buffer)), x)
@inbounds BufferIO.consume(io, sizeof(T))
return nothing
else
store_le_slowpath(io, x)
end
end

@noinline function store_le_slowpath(io::Union{BGZFLib.BGZFWriter, BGZFLib.SyncBGZFWriter}, x::T) where T
BufferIO.grow_buffer(io)
buffer = BufferIO.get_buffer(io)
# BGZFLib documents that grow_buffer will do a shallow flush,
# and that the buffer size is 2^16 bytes.
# Some bytes are used for overhead, but this means we can guarantee around 2^16
# bytes are available now.
if length(buffer) < sizeof(T)
error("Invalid BGZF implementation, too small buffer size after grow_buffer is called")
end
GC.@preserve buffer unsafe_store!(Ptr{T}(pointer(buffer)), x)
@inbounds BufferIO.consume(io, sizeof(T))
return nothing
end


include("bai.jl")
include("auxdata.jl")
Expand Down
17 changes: 13 additions & 4 deletions src/bam/overlap.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,23 @@ function Base.iterate(iter::OverlapIterator)
return nothing
end
state = OverlapIteratorState(refindex, chunks, 1, Record())
seek(iter.reader, state.chunks[state.chunkid].start)
seek(iter.reader, _to_virtual_offset(state.chunks[state.chunkid].start))
return iterate(iter, state)
end

function Base.iterate(iter::OverlapIterator, state)
while state.chunkid ≤ lastindex(state.chunks)
chunk = state.chunks[state.chunkid]
while BGZFStreams.virtualoffset(iter.reader.stream) < chunk.stop
read!(iter.reader, state.record)
while BGZFLib.virtual_position(iter.reader.stream) < _to_virtual_offset(chunk.stop)
Comment thread
jakobnissen marked this conversation as resolved.
Resolved

# FIXME: This is a bit of a hack, should be fixed in the future, BioGenerics uses this pattern
try
read!(iter.reader, state.record)
catch ex
ex isa EOFError && break
rethrow()
end

c = compare_intervals(state.record, (state.refindex, iter.interval))
if c == 0 # overlapping
return copy(state.record), state
Expand All @@ -75,10 +83,11 @@ function Base.iterate(iter::OverlapIterator, state)
# no more overlapping records in this chunk since records are sorted
break
end

end
state.chunkid += 1
if state.chunkid ≤ lastindex(state.chunks)
seek(iter.reader, state.chunks[state.chunkid].start)
seek(iter.reader, _to_virtual_offset(state.chunks[state.chunkid].start))
end
end
# no more overlapping records
Expand Down
36 changes: 19 additions & 17 deletions src/bam/reader.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ Create a data reader of the BAM file format.
* `index=nothing`: filepath to a random access index (currently *bai* is supported) or BAI object
"""
mutable struct Reader{T} <: XAMReader
stream::BGZFStreams.BGZFStream{T}
stream::BGZFLib.BGZFReader{T}
header::SAM.Header
start_offset::BGZFStreams.VirtualOffset
start_offset::BGZFLib.VirtualOffset
refseqnames::Vector{String}
refseqlens::Vector{Int}
index::Union{Nothing, BAI}
Expand Down Expand Up @@ -59,12 +59,12 @@ function header(reader::Reader; fillSQ::Bool=false)::SAM.Header
return header
end

function Base.seek(reader::Reader, voffset::BGZFStreams.VirtualOffset)
seek(reader.stream, voffset)
function Base.seek(reader::Reader, voffset::BGZFLib.VirtualOffset)
BGZFLib.virtual_seek(reader.stream, voffset)
end

function Base.seekstart(reader::Reader)
seek(reader.stream, reader.start_offset)
BGZFLib.virtual_seek(reader.stream, reader.start_offset)
end

function Base.iterate(reader::Reader, nextone = Record())
Expand All @@ -75,7 +75,7 @@ function Base.iterate(reader::Reader, nextone = Record())
end

# Initialize a BAM reader by reading the header section.
function init_bam_reader(input::BGZFStreams.BGZFStream)
function init_bam_reader(input::BGZFLib.BGZFReader)
Comment thread
jakobnissen marked this conversation as resolved.
Resolved
# magic bytes
B = read(input, UInt8)
A = read(input, UInt8)
Expand All @@ -87,25 +87,23 @@ function init_bam_reader(input::BGZFStreams.BGZFStream)
end

# SAM header
textlen = read(input, Int32)
textlen = load_le(input, Int32)
samreader = SAM.Reader(IOBuffer(read(input, textlen)))

# reference sequences
n_refs = read(input, Int32)
n_refs = load_le(input, Int32)
refseqnames = Vector{String}(undef, n_refs)
refseqlens = Vector{Int}(undef, n_refs)
@inbounds for i in 1:n_refs
namelen = read(input, Int32)
namelen = load_le(input, Int32)
data = read(input, namelen)
seqname = unsafe_string(pointer(data))
seqlen = read(input, Int32)
seqlen = load_le(input, Int32)
refseqnames[i] = seqname
refseqlens[i] = seqlen
end

voffset = isa(input.io, Base.AbstractPipe) ?
BGZFStreams.VirtualOffset(0, 0) :
BGZFStreams.virtualoffset(input)
voffset = BGZFLib.virtual_position(input)

return Reader(
input,
Expand All @@ -117,7 +115,7 @@ function init_bam_reader(input::BGZFStreams.BGZFStream)
end

function init_bam_reader(input::IO)
return init_bam_reader(BGZFStreams.BGZFStream(input))
return init_bam_reader(BGZFLib.BGZFReader(input))
end

init_bam_index(index::AbstractString) = BAI(index)
Expand All @@ -126,15 +124,19 @@ init_bam_index(index::Nothing) = nothing
init_bam_index(index) = error("unrecognizable index argument")

function _read!(reader::Reader, record)
unsafe_read(
# BufferIO.unsafe_read returns a byte count (unlike Base.IO which throws EOFError).
# Check explicitly so the overlap iterator's virtual_position check stays bounded.
n = unsafe_read(
reader.stream,
pointer_from_objref(record),
FIXED_FIELDS_BYTES)
UInt(FIXED_FIELDS_BYTES))
n < FIXED_FIELDS_BYTES && throw(EOFError())
dsize = data_size(record)
if length(record.data) < dsize
resize!(record.data, dsize)
end
unsafe_read(reader.stream, pointer(record.data), dsize)
n = unsafe_read(reader.stream, pointer(record.data), UInt(dsize))
n < dsize && throw(EOFError())
record.reader = reader
return record
end
Loading
Loading