beacon-biosignals / TimeSpans.jl

A Julia package that provides a `TimeSpan` type for representing a continuous span between two points in time.
Other
6 stars 2 forks source link

index_from_time returning different lengths for offseted TimeSpans #20

Open SimonDanisch opened 3 years ago

SimonDanisch commented 3 years ago

After https://github.com/beacon-biosignals/TimeSpans.jl/pull/16, some TimeSpans produce ranges of different lengths, even though they have the same duration:

using TimeSpans, Dates

sample_rate = 250.0
span = TimeSpan(1032552000000, 1062552000000)
offseted = TimeSpans.translate(span, -start(span))
# Current version
i = index_from_time(sample_rate, start(span))
j = index_from_time(sample_rate, stop(span))
length(i:(j-1)) # 7501 !!!!!!!

i = index_from_time(sample_rate, start(offseted))
j = index_from_time(sample_rate, stop(offseted))
length(i:(j-1)) # 7500 

# old version (TimeSpans#0.2.3)
function index_from_time_old(sample_rate, sample_time::Period)
    time_in_nanoseconds = convert(Nanosecond, sample_time).value
    time_in_nanoseconds >= 0 || throw(ArgumentError("`sample_time` must be >= 0 nanoseconds"))
    ns_per_sample = inv(sample_rate) * 1_000_000_000
    return floor(Int, time_in_nanoseconds / ns_per_sample) + 1
end

to_second(x) = x.value / 1e9

i = index_from_time_old(sample_rate, start(span))
j = index_from_time_old(sample_rate, stop(span))
length(i:(j-1)) # 7500

offset = start(span)
i = index_from_time_old(sample_rate, start(offseted))
j = index_from_time_old(sample_rate, stop(offseted))
length(i:(j-1)) # 7500