Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rebase dev #96

Merged
merged 58 commits into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
56813a7
Merge pull request #79 from roaldarbol/dev
roaldarbol Dec 7, 2024
57d6b36
Lots of new functions! Still rough
Dec 12, 2024
72cd715
Mostly docstrings and a few modifications.
Dec 12, 2024
db721a8
A few name changes
Dec 12, 2024
33f4790
Log y-axis on check_poses
Dec 12, 2024
b95b92a
Fix. Also silence ggplot
Dec 12, 2024
e39fc92
Add reference_keypoint to check_pose
Dec 12, 2024
622b533
Add doc and export to replace_na
Dec 12, 2024
143d137
Allow na_interpolation to return an unfiltered data frame with a warning
Dec 12, 2024
d817a39
Pathc to last commit
Dec 12, 2024
d692715
Another small patch
Dec 12, 2024
efcbe5b
Allow plotting of all NAs in check_na_timing
Dec 12, 2024
0118c58
Add min_obs parameter to smooth_movement
Dec 12, 2024
4d752ea
Hopefully improve speed of translate_coords_keypoint
Dec 13, 2024
9e47f16
lots of new functions and test data moved
Dec 14, 2024
d40e5e0
Just filename changes
Dec 14, 2024
906c0f1
Just docs and patches to ensure successful building
Dec 14, 2024
530e868
Add better read_trex docstring
Dec 14, 2024
eb9cb2b
Merge pull request #87 from roaldarbol/main
roaldarbol Dec 14, 2024
4b835ab
Expose and add documentation to set_individual and set_framerate
Dec 15, 2024
6a304fd
Add imports
Dec 15, 2024
91afc51
Expport set_ functions and update get_example_data
Dec 15, 2024
0177652
Add to NAMESPACE
Dec 15, 2024
c58f8ca
Fix time series plots when all values are NA
Dec 15, 2024
4904fdd
Tiny patch
Dec 15, 2024
be0c861
Add peak/trough detection
Dec 16, 2024
7111681
Great improvements the extrema detection functions. Also lots of test…
Dec 16, 2024
004aa31
Add movement classification
Dec 16, 2024
5a12cce
Export classification
Dec 16, 2024
2d5e44d
And add it to NAMESPACE
Dec 16, 2024
add149a
Merge branch 'everything_everywhere_all_at_once' of https://github.co…
Dec 16, 2024
6b71fbc
Fix bug in filter_by_speed
Dec 17, 2024
4f1e22e
Add NA tests
Dec 17, 2024
b547bfd
Bug fix for calculate_kinematics - added group_by keypoint and indivi…
Dec 17, 2024
679d30c
Fix set_framerate so it detects whether a frame rate has previously b…
Dec 17, 2024
a497269
Add bandwidth filters
Dec 19, 2024
d5b0ec6
Updates to the classification functions
Dec 19, 2024
414e90b
Changed method names in smooth_movement function
Dec 19, 2024
eb39902
Added NA testing for filter_by_speed
Dec 19, 2024
fe972ff
Add return_type parameter
Dec 19, 2024
1d35cfc
Add return_type parameter
Dec 19, 2024
4685c92
Merge branch 'everything_everywhere_all_at_once' of https://github.co…
Dec 19, 2024
d746502
Clean-up
Dec 19, 2024
ca26260
Patch
Dec 19, 2024
b05dca9
Another patch
Dec 19, 2024
6a1a08c
Patch again
Dec 19, 2024
65c696d
Improved bandwidth filters
Dec 20, 2024
18e7661
Adds Kalman filters
Dec 20, 2024
d9d1ca5
Add rotation of coordinates and egocentric transformation
Dec 21, 2024
ff8ebdc
Alignment of timeseries and classification w peak+trough
Dec 25, 2024
383aa8d
Improve detection of active periods
Dec 25, 2024
e0589f2
Adds replace_na functions and classify_low_periods
Dec 26, 2024
f8e440e
Filtering functions
Jan 3, 2025
d4b790d
Calculations
Jan 3, 2025
0492954
Filter NA functions
Jan 3, 2025
e64e9fa
The rest
Jan 3, 2025
0c2bba8
Update version
Jan 3, 2025
635e699
Merge pull request #94 from roaldarbol/everything_everywhere_all_at_once
roaldarbol Jan 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Improved bandwidth filters
  • Loading branch information
Mikkel Roald-Arbøl committed Dec 20, 2024
commit 65c696d1b819baadd79b784ea65984326d6e8b59
294 changes: 162 additions & 132 deletions R/filter_bandwidth.R
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
#' - order=4: Standard choice, good balance (~24 dB/octave)
#' - order=6: Steeper rolloff, some ringing (~36 dB/octave)
#' - order=8: Very steep, may have significant ringing (~48 dB/octave)
#' Note: For very low cutoff frequencies (<0.001 of Nyquist), order is automatically
#' reduced to 2 to maintain stability.
#'
#' Common values by field:
#' * Biomechanics: order=2 or 4
Expand Down Expand Up @@ -74,51 +76,60 @@
#' @importFrom signal butter filtfilt
#'
#' @export
filter_lowpass <- function(x, cutoff_freq, sampling_rate, order = 4,
na_action = c("interpolate", "remove", "error")) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
stop("Cutoff frequency must be between 0 and sampling_rate/2")
filter_lowpass <- function(x, cutoff_freq, sampling_rate, order = 4) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
stop("Cutoff frequency must be between 0 and sampling_rate/2")
}
if (order < 1 || order > 8) {
stop("Filter order should be between 1 and 8")
}

# Handle NAs with linear interpolation
if (any(is.na(x))) {
t <- seq_along(x)
# Handle edge cases first
if (is.na(x[1])) {
first_valid <- which(!is.na(x))[1]
x[1:first_valid] <- x[first_valid]
}
if (order < 1 || order > 8) {
stop("Filter order should be between 1 and 8")
if (is.na(x[length(x)])) {
last_valid <- max(which(!is.na(x)))
x[last_valid:length(x)] <- x[last_valid]
}
# Now interpolate internal NAs
x <- as.numeric(stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y)
}

na_action <- match.arg(na_action)

# Handle NAs
has_na <- any(is.na(x))
if (has_na) {
switch(na_action,
"error" = {
stop("Input signal contains NA values")
},
"interpolate" = {
# Use linear interpolation
t <- seq_along(x)
x <- stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y
},
"remove" = {
# Remove NAs and adjust signal
x <- x[!is.na(x)]
# Adjust sampling rate if significant data is removed
if (length(x) < 0.9 * length(x)) {
warning("More than 10% of data points were NA. ",
"Effective sampling rate may be affected.")
}
}
)
}
# Verify no NAs remain
if (any(is.na(x))) {
stop("Failed to properly interpolate NAs")
}

nyquist_freq <- sampling_rate/2
normalized_cutoff <- cutoff_freq/nyquist_freq
# For very low cutoff frequencies (<0.001 normalized), reduce order
nyquist_freq <- sampling_rate/2
normalized_cutoff <- cutoff_freq/nyquist_freq

if (normalized_cutoff < 0.001 & order > 2) {
order <- min(order, 2) # Limit order for very low frequencies
warning("Very low cutoff frequency detected. Reducing filter order to 2 for stability.")
}

# Add reflection padding to reduce edge effects
n_pad <- max(round(sampling_rate/cutoff_freq), order * 10)
start_pad <- rev(x[1:min(n_pad, length(x))])
end_pad <- rev(x[(length(x) - min(n_pad, length(x)) + 1):length(x)])
x_padded <- c(start_pad, x, end_pad)

# Create and apply filter
bf <- signal::butter(order, normalized_cutoff, type = "low")
filtered_padded <- signal::filtfilt(bf, x_padded)

# Create and apply Butterworth filter
bf <- signal::butter(order, normalized_cutoff, type = "low")
filtered <- signal::filtfilt(bf, x)
# Remove padding and ensure original length
filtered <- filtered_padded[(n_pad + 1):(n_pad + length(x))]

return(filtered)
return(filtered)
}

#' Apply Butterworth Highpass Filter to Signal
Expand Down Expand Up @@ -184,8 +195,7 @@ filter_lowpass <- function(x, cutoff_freq, sampling_rate, order = 4,
#' @importFrom signal butter filtfilt
#'
#' @export
filter_highpass <- function(x, cutoff_freq, sampling_rate, order = 4,
na_action = c("interpolate", "remove", "error")) {
filter_highpass <- function(x, cutoff_freq, sampling_rate, order = 4) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
Expand All @@ -195,38 +205,48 @@ filter_highpass <- function(x, cutoff_freq, sampling_rate, order = 4,
stop("Filter order should be between 1 and 8")
}

na_action <- match.arg(na_action)

# Handle NAs
has_na <- any(is.na(x))
if (has_na) {
switch(na_action,
"error" = {
stop("Input signal contains NA values")
},
"interpolate" = {
# Use linear interpolation
t <- seq_along(x)
x <- stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y
},
"remove" = {
# Remove NAs and adjust signal
x <- x[!is.na(x)]
# Adjust sampling rate if significant data is removed
if (length(x) < 0.9 * length(x)) {
warning("More than 10% of data points were NA. ",
"Effective sampling rate may be affected.")
}
}
)
# Handle NAs with linear interpolation
if (any(is.na(x))) {
t <- seq_along(x)
# Handle edge cases first
if (is.na(x[1])) {
first_valid <- which(!is.na(x))[1]
x[1:first_valid] <- x[first_valid]
}
if (is.na(x[length(x)])) {
last_valid <- max(which(!is.na(x)))
x[last_valid:length(x)] <- x[last_valid]
}
# Now interpolate internal NAs
x <- as.numeric(stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y)
}

# Verify no NAs remain
if (any(is.na(x))) {
stop("Failed to properly interpolate NAs")
}

# For very low cutoff frequencies (<0.001 normalized), reduce order
nyquist_freq <- sampling_rate/2
normalized_cutoff <- cutoff_freq/nyquist_freq

# Create and apply Butterworth filter
if (normalized_cutoff < 0.001 & order > 2) {
order <- min(order, 2) # Limit order for very low frequencies
warning("Very low cutoff frequency detected. Reducing filter order to 2 for stability.")
}

# Add reflection padding to reduce edge effects
n_pad <- max(round(sampling_rate/cutoff_freq), order * 10)
start_pad <- rev(x[1:min(n_pad, length(x))])
end_pad <- rev(x[(length(x) - min(n_pad, length(x)) + 1):length(x)])
x_padded <- c(start_pad, x, end_pad)

# Create and apply filter
bf <- signal::butter(order, normalized_cutoff, type = "high")
filtered <- signal::filtfilt(bf, x)
filtered_padded <- signal::filtfilt(bf, x_padded)

# Remove padding and ensure original length
filtered <- filtered_padded[(n_pad + 1):(n_pad + length(x))]

return(filtered)
}
Expand Down Expand Up @@ -274,56 +294,61 @@ filter_highpass <- function(x, cutoff_freq, sampling_rate, order = 4,
#' \code{\link{lowpass_filter}} for Butterworth-based filtering
#'
#' @export
filter_lowpass_fft <- function(x, cutoff_freq, sampling_rate,
na_action = c("interpolate", "remove", "error")) {
filter_lowpass_fft <- function(x, cutoff_freq, sampling_rate) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
stop("Cutoff frequency must be between 0 and sampling_rate/2")
}

na.action <- match.arg(na_action)

# Handle NAs
has_na <- any(is.na(x))
if (has_na) {
switch(na_action,
"error" = {
stop("Input signal contains NA values")
},
"interpolate" = {
# Use linear interpolation
t <- seq_along(x)
x <- stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y
},
"remove" = {
# Remove NAs and adjust signal
x <- x[!is.na(x)]
# Adjust sampling rate if significant data is removed
if (length(x) < 0.9 * length(x)) {
warning("More than 10% of data points were NA. ",
"Effective sampling rate may be affected.")
}
}
)
# Handle NAs with linear interpolation
if (any(is.na(x))) {
t <- seq_along(x)
# Handle edge cases first
if (is.na(x[1])) {
first_valid <- which(!is.na(x))[1]
x[1:first_valid] <- x[first_valid]
}
if (is.na(x[length(x)])) {
last_valid <- max(which(!is.na(x)))
x[last_valid:length(x)] <- x[last_valid]
}
# Now interpolate internal NAs
x <- as.numeric(stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y)
}

# Verify no NAs remain
if (any(is.na(x))) {
stop("Failed to properly interpolate NAs")
}

N <- length(x)

# Add reflection padding to reduce edge effects
n_pad <- ceiling(N/10) # 10% padding
start_pad <- rev(x[1:n_pad])
end_pad <- rev(x[(length(x) - n_pad + 1):length(x)])
x_padded <- c(start_pad, x, end_pad)

# Compute FFT
X <- fft(x)
X <- fft(x_padded)
N_padded <- length(x_padded)

# Create frequency vector
freq <- seq(0, sampling_rate - sampling_rate/N, by = sampling_rate/N)
freq <- seq(0, sampling_rate - sampling_rate/N_padded, by = sampling_rate/N_padded)

# Create filter mask
mask <- freq <= cutoff_freq
mask[N:2] <- rev(mask[2:(N/2 + 1)]) # Mirror for negative frequencies
mask[N_padded:2] <- rev(mask[2:(N_padded/2 + 1)]) # Mirror for negative frequencies

# Apply filter
X_filtered <- X * mask

# Inverse FFT
filtered <- Re(fft(X_filtered, inverse = TRUE)/N)
filtered_padded <- Re(fft(X_filtered, inverse = TRUE)/N_padded)

# Remove padding
filtered <- filtered_padded[(n_pad + 1):(n_pad + N)]

return(filtered)
}
Expand Down Expand Up @@ -360,56 +385,61 @@ filter_lowpass_fft <- function(x, cutoff_freq, sampling_rate,
#' @return Numeric vector containing the filtered signal
#'
#' @export
filter_highpass_fft <- function(x, cutoff_freq, sampling_rate,
na_action = c("interpolate", "remove", "error")) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
stop("Cutoff frequency must be between 0 and sampling_rate/2")
}
filter_highpass_fft <- function(x, cutoff_freq, sampling_rate) {
# Input validation
if (!is.numeric(x)) stop("Input signal must be numeric")
if (cutoff_freq <= 0 || cutoff_freq >= sampling_rate/2) {
stop("Cutoff frequency must be between 0 and sampling_rate/2")
}

na_action <- match.arg(na_action)

# Handle NAs
has_na <- any(is.na(x))
if (has_na) {
switch(na_action,
"error" = {
stop("Input signal contains NA values")
},
"interpolate" = {
# Use linear interpolation
t <- seq_along(x)
x <- stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y
},
"remove" = {
# Remove NAs and adjust signal
x <- x[!is.na(x)]
# Adjust sampling rate if significant data is removed
if (length(x) < 0.9 * length(x)) {
warning("More than 10% of data points were NA. ",
"Effective sampling rate may be affected.")
}
}
)
# Handle NAs with linear interpolation
if (any(is.na(x))) {
t <- seq_along(x)
# Handle edge cases first
if (is.na(x[1])) {
first_valid <- which(!is.na(x))[1]
x[1:first_valid] <- x[first_valid]
}
if (is.na(x[length(x)])) {
last_valid <- max(which(!is.na(x)))
x[last_valid:length(x)] <- x[last_valid]
}
# Now interpolate internal NAs
x <- as.numeric(stats::approx(t[!is.na(x)], x[!is.na(x)], t)$y)
}

# Verify no NAs remain
if (any(is.na(x))) {
stop("Failed to properly interpolate NAs")
}

N <- length(x)

# Add reflection padding to reduce edge effects
n_pad <- ceiling(N/10) # 10% padding
start_pad <- rev(x[1:n_pad])
end_pad <- rev(x[(length(x) - n_pad + 1):length(x)])
x_padded <- c(start_pad, x, end_pad)

# Compute FFT
X <- fft(x)
X <- fft(x_padded)
N_padded <- length(x_padded)

# Create frequency vector
freq <- seq(0, sampling_rate - sampling_rate/N, by = sampling_rate/N)
freq <- seq(0, sampling_rate - sampling_rate/N_padded, by = sampling_rate/N_padded)

# Create filter mask
mask <- freq >= cutoff_freq
mask[N:2] <- rev(mask[2:(N/2 + 1)]) # Mirror for negative frequencies
mask[N_padded:2] <- rev(mask[2:(N_padded/2 + 1)]) # Mirror for negative frequencies

# Apply filter
X_filtered <- X * mask

# Inverse FFT
filtered <- Re(fft(X_filtered, inverse = TRUE)/N)
filtered_padded <- Re(fft(X_filtered, inverse = TRUE)/N_padded)

# Remove padding
filtered <- filtered_padded[(n_pad + 1):(n_pad + N)]

return(filtered)
}
8 changes: 1 addition & 7 deletions man/filter_highpass.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading