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
Calculations
  • Loading branch information
Mikkel Roald-Arbøl committed Jan 3, 2025
commit d4b790d9b3ac4ddeb38c50d324fe0eee2096329f
10 changes: 10 additions & 0 deletions R/calculate_derivative.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#' Calculate the derivative (dx/dt)
#' Calculate the derivative (dx/dt) with four arguments
#' @param from_x Current x value
#' @param to_x Lagging x value
#' @param from_t Current timestamp
#' @param to_t Lagging timestamp
#' @keywords internal
calculate_derivative <- function(from_x, to_x, from_t, to_t) {
(from_x - to_x) / (from_t - to_t)
}
8 changes: 8 additions & 0 deletions R/calculate_direction.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#' Calculate direction
#' Calculate direction (angle) from x and y distance using the (two-argument) arc-tangent. Converts to `circular`.
#' @inheritParams calculate_distance
#' @importFrom circular circular
#' @keywords internal
calculate_direction <- function(dx, dy) {
if_else(dx == 0 & dy == 0, NA, circular::circular(atan2(dy, dx), modulo = "asis"))
}
8 changes: 8 additions & 0 deletions R/calculate_distance.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#' Calculate distance (Pythagoras)
#' Calculate distance from an x and y distance, using Pythagoras theorem.
#' @param dx dx
#' @param dy dy
#' @keywords internal
calculate_distance <- function(dx, dy) {
sqrt(dx^2 + dy^2)
}
255 changes: 79 additions & 176 deletions R/calculate_kinematics.R
Original file line number Diff line number Diff line change
@@ -1,198 +1,101 @@
#' Calculate kinematics
#' Calculate kinematics from position data
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' Calculate kinematics.
#' Calculates kinematic measurements including translational and rotational motion from
#' position data. The function computes velocities, accelerations, and angular measurements
#' from x-y coordinate time series data.
#'
#' @param data Data frame
#' @param data A data frame containing at minimum:
#' * time (numeric): Time points of measurements
#' * x (numeric): X-coordinates
#' * y (numeric): Y-coordinates
#' @param by Character vector specifying additional grouping variables (optional).
#' If the input data frame is already grouped, those groups will be preserved
#' and any additional groups specified in `by` will be added.
#'
#' @returns A data frame containing the original data plus calculated kinematics:
#' * distance: Distance traveled between consecutive points
#' * v_translation: Translational velocity
#' * a_translation: Translational acceleration
#' * direction: Movement direction in radians
#' * rotation: Angular change between consecutive points
#' * v_rotation: Angular velocity
#' * a_rotation: Angular acceleration
#'
#' @section Warning:
#' Time points should be regularly sampled for accurate derivatives.
#'
#' @examples
#' # Basic usage with just x-y coordinates
#' df <- data.frame(
#' time = 1:10,
#' x = runif(10),
#' y = runif(10)
#' )
#' calculate_kinematics(df)
#'
#' # Using with grouping variables
#' df_grouped <- data.frame(
#' time = rep(1:5, 2),
#' x = runif(10),
#' y = runif(10),
#' individual = rep(c("A", "B"), each = 5)
#' )
#' calculate_kinematics(df_grouped, by = "individual")
#'
#' @return A data frame with kinematics calculated
#' @export
#' @import dplyr
#' @importFrom rlang :=
#' @importFrom rlang .data
#' @importFrom rlang := .data
#'
calculate_kinematics <- function(
data) {
# We first temporarily back-calculate from our xy coordinates to the distances (dx, dy) covered between each observation (which is what we got from the sensors initially)
calculate_kinematics <- function(data, by = NULL) {
# Validate input
required_cols <- c("time", "x", "y")
missing_cols <- setdiff(required_cols, names(data))
if (length(missing_cols) > 0) {
cli::cli_abort(
c("Missing required columns in input data:",
"x" = "{.val {missing_cols}}")
)
}

# Preserve existing groups and add new ones if specified
if (!is.null(by)) {
missing_by_cols <- setdiff(by, names(data))
if (length(missing_by_cols) > 0) {
cli::cli_abort(
c("Grouping columns specified in 'by' not found in data:",
"x" = "{.val {missing_by_cols}}")
)
}
data <- data |>
group_by(across(all_of(by)), .add = TRUE)
}

# Calculate intermediate values
data <- data |>
dplyr::group_by(.data$individual, .data$keypoint) |>
dplyr::mutate(
dx = .data$x - lag(.data$x),
dy = .data$y - lag(.data$y),
# dt = .data$time - lag(.data$time)
dy = .data$y - lag(.data$y)
)

# Find the sampling rate
# sampling_rate <- round(1 / stats::median(data$dt, na.rm = TRUE))

# Calculate kinematics
data <- data |>
dplyr::group_by(.data$individual, .data$keypoint) |>
dplyr::mutate(
distance = calculate_distance(.data$dx, .data$dy),
v_translation = calculate_derivative(.data$distance, 0, .data$time, lag(.data$time)),
a_translation = calculate_derivative(.data$v_translation, lag(.data$v_translation), .data$time, lag(.data$time)),
d_translation = calculate_distance(.data$dx, .data$dy),
v_translation = calculate_derivative(.data$d_translation, 0, .data$time, lag(.data$time)),
a_translation = calculate_derivative(.data$v_translation, lag(.data$v_translation),
.data$time, lag(.data$time)),
direction = calculate_direction(.data$dx, .data$dy),
rotation = calculate_angular_difference(.data$direction, lag(.data$direction)),
v_rotation = calculate_derivative(0, .data$rotation, .data$time, lag(.data$time)),
a_rotation = calculate_derivative(.data$v_rotation, lag(.data$v_rotation), .data$time, lag(.data$time)),
# We change the directions to stay within 2pi only here, otherwise rotation becomes harder to alculate
direction = adjust_direction(.data$direction) # Keep direction between 0 and 2*pi
d_rotation = calculate_angular_difference(.data$direction, lag(.data$direction)),
v_rotation = calculate_derivative(0, .data$d_rotation, .data$time, lag(.data$time)),
a_rotation = calculate_derivative(.data$v_rotation, lag(.data$v_rotation),
.data$time, lag(.data$time)),
direction = constrain_angles_radians(.data$direction)
)

# Remove leftover columns
data <- data |>
# Remove intermediate columns
data |>
select(-c("dx", "dy"))
# select(-c("dx", "dy", "dt"))

return(data)
}

#' Calculate distance (Pythagoras)
#' Calculate distance from an x and y distance, using Pythagoras theorem.
#' @param dx dx
#' @param dy dy
#' @keywords internal
calculate_distance <- function(dx, dy) {
sqrt(dx^2 + dy^2)
}

#' Calculate direction
#' Calculate direction (angle) from x and y distance using the (two-argument) arc-tangent. Converts to `circular`.
#' @inheritParams calculate_distance
#' @importFrom circular circular
#' @keywords internal
calculate_direction <- function(dx, dy) {
if_else(dx == 0 & dy == 0, NA, circular::circular(atan2(dy, dx), modulo = "asis"))
}

#' Calculate angular difference
#' @param from_angle From angle
#' @param to_angle To angle
#' @keywords internal
calculate_angular_difference <- function(from_angle, to_angle) {
ensure_circular(from_angle)
ensure_circular(to_angle)
diff_angle <- from_angle - to_angle
case_when(diff_angle > pi ~ diff_angle - 2 * pi,
diff_angle < -pi ~ diff_angle + 2 * pi,
.default = diff_angle
)
}

#' Calculate the derivative (dx/dt)
#' Calculate the derivative (dx/dt) with four arguments
#' @param from_x Current x value
#' @param to_x Lagging x value
#' @param from_t Current timestamp
#' @param to_t Lagging timestamp
#' @keywords internal
calculate_derivative <- function(from_x, to_x, from_t, to_t) {
(from_x - to_x) / (from_t - to_t)
}

#' Adjust direction
#' Constrains the direction to be between 0 and 2pi
#' @param direction Direction
#' @importFrom circular circular
#' @keywords internal
adjust_direction <- function(direction) {
circular::circular(direction, modulo = "2pi")
}

#' Add Centroid to Movement Data
#'
#' @description
#' Calculates and adds a centroid point to movement tracking data. The centroid
#' represents the mean position of selected keypoints at each time point.
#'
#' @param data A data frame containing movement tracking data with the following
#' required columns:
#' - `individual`: Identifier for each tracked subject
#' - `keypoint`: Factor specifying tracked points
#' - `time`: Time values
#' - `x`: x-coordinates
#' - `y`: y-coordinates
#' - `confidence`: Confidence values for tracked points
#' @param include_keypoints Optional character vector specifying which keypoints
#' to use for centroid calculation. If NULL (default), all keypoints are used
#' unless `exclude_keypoints` is specified.
#' @param exclude_keypoints Optional character vector specifying which keypoints
#' to exclude from centroid calculation. If NULL (default), no keypoints are
#' excluded unless `include_keypoints` is specified.
#' @param centroid_name Character string specifying the name for the centroid
#' keypoint (default: "centroid")
#'
#' @return A data frame with the same structure as the input, but with an
#' additional keypoint representing the centroid. The centroid's confidence
#' values are set to NA.
#'
#' @details
#' The function calculates the centroid as the mean x and y position of the
#' selected keypoints at each time point for each individual. Keypoints can be
#' selected either by specifying which ones to include (`include_keypoints`) or
#' which ones to exclude (`exclude_keypoints`). The resulting centroid is added
#' as a new keypoint to the data frame.
#'
#' @examples
#' \dontrun{
#' # Add centroid using all keypoints
#' add_centroid(movement_data)
#'
#' # Calculate centroid using only specific keypoints
#' add_centroid(movement_data,
#' include_keypoints = c("head", "thorax", "abdomen"))
#'
#' # Calculate centroid excluding certain keypoints
#' add_centroid(movement_data,
#' exclude_keypoints = c("antenna_left", "antenna_right"),
#' centroid_name = "body_centroid")
#' }
#'
#' @seealso
#' `convert_nan_to_na()` for NaN handling in the centroid calculation
#'
#' @importFrom dplyr filter group_by summarise mutate arrange bind_rows
#'
#' @export
add_centroid <- function(data,
include_keypoints=NULL,
exclude_keypoints=NULL,
centroid_name="centroid"){
# Check that centroid isn't there
# Check that it's a movement data frame
# To be optimised with collapse later on
if (!is.null(include_keypoints)){
df_centroid <- data |>
dplyr::filter(.data$keypoint %in% include_keypoints)
} else if (!is.null(exclude_keypoints)){
df_centroid <- data |>
dplyr::filter(!.data$keypoint %in% exclude_keypoints)
} else {
df_centroid <- data
}

df_centroid <- df_centroid |>
dplyr::group_by(.data$individual, .data$time) |>
dplyr::summarise(x = mean(.data$x, na.rm=TRUE),
y = mean(.data$y, na.rm=TRUE),
confidence = NA,
.groups = "keep") |>
dplyr::mutate(keypoint = factor(as.character(centroid_name))) |>
convert_nan_to_na()

data <- bind_rows(data, df_centroid) |>
dplyr::arrange(.data$time, .data$individual, .data$keypoint)

return(data)
}

calculate_centroid_x <- function(x){
mean(x, na.rm=TRUE)
}

calculate_centroid_y <- function(y){
mean(y, na.rm=TRUE)
}
2 changes: 1 addition & 1 deletion R/calculate_statistics.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ calculate_statistics <- function(

# Calculate translational and rotational separately (maybe?) and gather at the end
totals <- data |>
dplyr::summarise(across(c("distance", "rotation"), ~ collapse::fsum(abs(.x)), .names = "total_{.col}"),
dplyr::summarise(across(c("d_translation", "d_rotation"), ~ collapse::fsum(abs(.x)), .names = "total_{.col}"),
across(c("x", "y"), ~ dplyr::last(.x, na_rm = TRUE), .names = "last_{.col}"),
.by = c("individual", "keypoint")
)
Expand Down
12 changes: 6 additions & 6 deletions R/calculate_straightness.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@ calculate_straightness <- function(data, straightness = c("A", "B", "C", "D")) {
straightness_A = calculate_straightness_A(
.data$last_x,
.data$last_y,
.data$total_distance
.data$total_d_translation
),
straightness_B = calculate_straightness_B(
.data$last_x,
.data$last_y,
.data$total_distance
.data$total_d_translation
),
straightness_C = calculate_straightness_C(
.data$total_distance,
.data$total_rotation
.data$total_d_translation,
.data$total_d_rotation
),
straightness_D = calculate_straightness_D(
.data$total_distance,
.data$total_rotation
.data$total_d_translation,
.data$total_d_rotation
)
)

Expand Down
2 changes: 1 addition & 1 deletion man/calculate_angular_difference.Rd

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

2 changes: 1 addition & 1 deletion man/calculate_derivative.Rd

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

2 changes: 1 addition & 1 deletion man/calculate_direction.Rd

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

2 changes: 1 addition & 1 deletion man/calculate_distance.Rd

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

Loading