Skip to content

Commit

Permalink
Issue #11
Browse files Browse the repository at this point in the history
Create compute_fft(), its documentation, and its tests.
  • Loading branch information
akey7 committed Dec 28, 2022
1 parent a85cdbd commit 4bc33ec
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Generated by roxygen2: do not edit by hand

export("%>%")
export(compute_fft)
export(cos_sum)
export(exp_decay)
export(length_norm)
Expand All @@ -12,4 +13,5 @@ importFrom(ggplot2,geom_line)
importFrom(ggplot2,ggplot)
importFrom(ggplot2,labs)
importFrom(magrittr,"%>%")
importFrom(stats,fft)
importFrom(utils,tail)
25 changes: 25 additions & 0 deletions R/compute_fft.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#' compute_fft()
#'
#' Computes the FFT of the given waveform.
#'
#' @param incoming data.frame containing the incoming waveform for the FFT.
#'
#' @return A data.frame with the following columns: .values with the values from the FFT, and .idx with the indexes for these values (this makes it easier to plot with ggplot later).
#' @export
#' @importFrom stats fft
#'
#' @examples
#' waveform(duration_s = 1.0, sr = 10) %>%
#' cos_sum(freqs = c(2.0, 3.0), amplitudes = c(0.5, 1.0)) %>%
#' length_norm() %>%
#' compute_fft()
compute_fft <- function(incoming) {
stopifnot("incoming must be a data.frame with a waveform." = is.data.frame(incoming))

.value <- stats::fft(incoming$.value)

data.frame(
.idx = seq_along(.value),
.value = .value
)
}
23 changes: 23 additions & 0 deletions man/compute_fft.Rd

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

21 changes: 21 additions & 0 deletions tests/testthat/test-compute_fft.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
test_that("compute_fft() expects a data.frame", {
expect_error(compute_fft(1.0))
})

test_that("compute_fft() computes an FFT of the sum of two cosines", {
wv <- waveform(duration_s = 1.0, sr = 10) %>%
cos_sum(freqs = c(2.0, 3.0), amplitudes = c(0.5, 1.0)) %>%
length_norm()

actual <- compute_fft(wv)$.value

expected <- c(
-4.857226e-17+0.000000e+00i, 0.000000e+00-8.326673e-17i,
7.725425e-02+2.377641e-01i, -1.545085e-01+4.755283e-01i,
-5.551115e-17+5.551115e-17i, -8.326673e-17+2.775558e-17i,
-5.551115e-17-5.551115e-17i, -1.545085e-01-4.755283e-01i,
7.725425e-02-2.377641e-01i, 0.000000e+00+5.551115e-17i
)

expect_equal(expected, actual, tolerance = 1e-3)
})

0 comments on commit 4bc33ec

Please sign in to comment.