From b93854383ab5b3e715db7de957f369bb38989461 Mon Sep 17 00:00:00 2001 From: Eric Hanson <5846501+ericphanson@users.noreply.github.com> Date: Fri, 28 Jan 2022 14:40:41 -0500 Subject: [PATCH] Fix #28 (#29) * fix #28 * rm extra space * bump batch --- Project.toml | 2 +- src/TimeSpans.jl | 16 ++++++++++++---- test/runtests.jl | 6 ++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Project.toml b/Project.toml index e8c06c2..97cc6f0 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "TimeSpans" uuid = "bb34ddd2-327f-4c4a-bfb0-c98fc494ece1" authors = ["Beacon Biosignals, Inc."] -version = "0.2.6" +version = "0.2.7" [deps] Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" diff --git a/src/TimeSpans.jl b/src/TimeSpans.jl index ea25082..9001e3f 100644 --- a/src/TimeSpans.jl +++ b/src/TimeSpans.jl @@ -208,11 +208,15 @@ julia> index_from_time(100, Millisecond(1000)) 101 ``` """ -function index_from_time(sample_rate, sample_time::Period) +index_from_time(sample_rate, sample_time::Period) = first(index_and_is_rounded_from_time(sample_rate, sample_time)) + +# Helper to get the index and whether or not it has been rounded +function index_and_is_rounded_from_time(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")) time_in_seconds = time_in_nanoseconds / NS_IN_SEC - return floor(Int, time_in_seconds * sample_rate) + 1 + index = time_in_seconds * sample_rate + 1 + return floor(Int, index), !isinteger(index) end """ @@ -233,8 +237,12 @@ julia> index_from_time(100, TimeSpan(Second(3), Second(6))) """ function index_from_time(sample_rate, span) i = index_from_time(sample_rate, start(span)) - j = index_from_time(sample_rate, stop(span)) - j = i == j ? j : (j - 1) + j, is_rounded = index_and_is_rounded_from_time(sample_rate, stop(span)) + # if `j` has been rounded down, then we are already excluding the right endpoint + # by means of that rounding. Hence, we don't need to decrement here. + if i != j && !is_rounded + j -= 1 + end return i:j end diff --git a/test/runtests.jl b/test/runtests.jl index b3edb4e..77afb8f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -81,6 +81,12 @@ end @test index_from_time(100, Nanosecond(0)) == 1 @test index_from_time(100, TimeSpan(Second(3), Second(6))) == 301:600 @test index_from_time(100, TimeSpan(Second(1))) == 101:101 + + # https://github.com/beacon-biosignals/TimeSpans.jl/issues/28 + @test index_from_time(1, Millisecond(1500)) == 2 + @test index_from_time(1, Millisecond(2500)) == 3 + @test index_from_time(1, TimeSpan(Millisecond(1500), Millisecond(2500))) == 2:3 + # test non-integer sample rates rate = 100.66 ns_per_sample = nanoseconds_per_sample(rate)