Skip to content

Commit

Permalink
Optimise complementation of nucleotides (#62)
Browse files Browse the repository at this point in the history
While BioSequences complement nucleotides in bulk, making this necessity not
important, the upcoming Kmers.jl relies on efficient complementation of single
nucleotides, so this is important.
  • Loading branch information
jakobnissen authored Dec 29, 2023
1 parent 41070d2 commit 2f4b82c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
12 changes: 6 additions & 6 deletions src/nucleicacid.jl
Original file line number Diff line number Diff line change
Expand Up @@ -427,12 +427,12 @@ RNA_A
```
"""
function complement(nt::NucleicAcid)
bits = compatbits(nt)
return encode(
typeof(nt),
(bits & 0x01) << 3 | (bits & 0x08) >> 3 |
(bits & 0x02) << 1 | (bits & 0x04) >> 1)
function complement(nt::Union{DNA, RNA})
# This is essentially a lookup table of 16 x 4 bits.
# It's the concatenation of the bitpatterns of the nucleotides,
# in order, complemented.
u64 = 0xf7b3d591e6a2c480 >>> ((4 * encoded_data(nt)) & 63)
reinterpret(typeof(nt), (u64 % UInt8) & 0x0f)
end

function Base.isvalid(::Type{T}, x::Integer) where T <: NucleicAcid
Expand Down
24 changes: 11 additions & 13 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -239,19 +239,17 @@ end
end

@testset "complement" begin
@test complement(DNA_A) === DNA_T
@test complement(DNA_C) === DNA_G
@test complement(DNA_G) === DNA_C
@test complement(DNA_T) === DNA_A
@test complement(DNA_Gap) === DNA_Gap
@test complement(DNA_N) === DNA_N

@test complement(RNA_A) === RNA_U
@test complement(RNA_C) === RNA_G
@test complement(RNA_G) === RNA_C
@test complement(RNA_U) === RNA_A
@test complement(RNA_Gap) === RNA_Gap
@test complement(RNA_N) === RNA_N
for (a, b) in zip(
"-ACMGRSVTWYHKDBN",
"-TGKCYSBAWRDMHVN"
)
da, db = DNA(a), DNA(b)
for (i, j) in ((da, db), (RNA(da), RNA(db)))

@test complement(i) === j
@test complement(j) === i
end
end
end

@testset "Logic operations and Order" begin
Expand Down

0 comments on commit 2f4b82c

Please sign in to comment.