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

`time_from_index` of a range is inconsistent depending on the length of the range #45

Closed kleinschmidt closed 1 year ago

kleinschmidt commented 2 years ago

This is called out in the docs:

  time_from_index(sample_rate, sample_range::AbstractUnitRange)

  Return the TimeSpan corresponding to sample_range given sample_rate in Hz:

  julia> time_from_index(100, 1:100)
  TimeSpan(0 nanoseconds, 1000000000 nanoseconds)

  julia> time_from_index(100, 101:101)
  TimeSpan(1000000000 nanoseconds, 1000000001 nanoseconds)

  julia> time_from_index(100, 301:600)
  TimeSpan(3000000000 nanoseconds, 6000000000 nanoseconds)

but it is causing problems in a very specific application. if you have one signal that's sampled at a substantially lower rate than another (say, a 1/30 Hz label track and a 128 Hz EEG signal), you might want to do something like "give me the signals data for n labels starting at the ith label". The naive way of doing this is to do something like

label_span = time_from_index(1/30, i:(i + n - 1))
signal_samples[:, label_span]

this works great except when n is 1. in that case, you'll get back a label_span that is "instantaneous" (e.g., translate(TimeSpan(0, 0), time_from_index(1/30, i))), rather than 30s long.

another way of putting this is that the duration of the span generated by time_from_index(sampling_rate, range) is not always sampling_rate * length(range).

ericphanson commented 2 years ago

AlignedSpans could be helpful here. Eg n_samples depends only on the duration and sample rate, not the endpoints and this can be used in some places. What the right approach is depends exactly what you need to do downstream of course.

(there’s also https://beacon-biosignals.github.io/AlignedSpans.jl/dev/API/#AlignedSpans.ConstantSamplesRoundingMode for example)

Fwiw I developed AlignedSpans exactly bc of the difficulties of working with both 1Hz and 128Hz data together. You really can’t miss a sample when it’s at 1Hz so you need a lot of control over the rounding.

ararslan commented 1 year ago

This appears to have been fixed by #51.