Title: | Tidy Manipulation of Fourier Transformed Data |
Version: | 0.1.0 |
Description: | The 'fftab' package stores Fourier coefficients in a tibble and allows their manipulation in various ways. Functions are available for converting between complex, rectangular ('re', 'im'), and polar ('mod', 'arg') representations, as well as for extracting components as vectors or matrices. Inputs can include vectors, time series, and arrays of arbitrary dimensions, which are restored to their original form when inverting the transform. Since 'fftab' stores Fourier frequencies as columns in the tibble, many standard operations on spectral data can be easily performed using tidy packages like 'dplyr'. |
License: | MIT + file LICENSE |
Encoding: | UTF-8 |
RoxygenNote: | 7.3.2 |
Suggests: | ggfortify, patchwork, testthat (≥ 3.0.0), zoo |
Config/testthat/edition: | 3 |
Imports: | dplyr, ggplot2, lifecycle, tibble, tidyr |
URL: | https://github.com/thk686/fftab, https://thk686.github.io/fftab/ |
BugReports: | https://github.com/thk686/fftab/issues |
Config/Needs/website: | rmarkdown |
NeedsCompilation: | no |
Packaged: | 2025-01-13 22:31:34 UTC; keittth |
Author: | Timothy Keitt [aut, cre] |
Maintainer: | Timothy Keitt <tkeitt@gmail.com> |
Repository: | CRAN |
Date/Publication: | 2025-01-15 10:40:08 UTC |
fftab: Tidy Manipulation of Fourier Transformed Data
Description
The 'fftab' package stores Fourier coefficients in a tibble and allows their manipulation in various ways. Functions are available for converting between complex, rectangular ('re', 'im'), and polar ('mod', 'arg') representations, as well as for extracting components as vectors or matrices. Inputs can include vectors, time series, and arrays of arbitrary dimensions, which are restored to their original form when inverting the transform. Since 'fftab' stores Fourier frequencies as columns in the tibble, many standard operations on spectral data can be easily performed using tidy packages like 'dplyr'.
Author(s)
Maintainer: Timothy Keitt tkeitt@gmail.com
See Also
Useful links:
Report bugs at https://github.com/thk686/fftab/issues
Build a FFTAB Object
Description
Converts an object into a fftab
object with additional metadata attributes.
Usage
.as_fftab_obj(x, .is_normalized, .is_complex, ...)
Arguments
x |
The input object to convert, typically a tibble or data frame. |
.is_normalized |
A logical value indicating if the input is normalized. |
.is_complex |
A logical value indicating if the original data was complex. |
... |
Additional attributes to include in the structured object, such as metadata or specific attributes required for Fourier Transform analysis. |
Value
The input object x
, with the fftab
class and any additional
attributes provided in ...
.
Compute Normalized Correlation Between Two Signals
Description
Computes the normalized correlation between two signals based on their Fourier representations.
Usage
.correlation(a, b)
Arguments
a |
A |
b |
A |
Details
This function computes the cross-spectrum of two signals, removes the DC component, and calculates the real part of the cross-spectrum sum. The result is normalized using the variances of both signals.
Normalization ensures that the correlation value lies between -1 and 1.
Value
A numeric value representing the normalized correlation between the two signals.
Retrieve Object Dimensions
Description
Retrieves the .dim
attribute from an object.
Usage
.dim(x)
Arguments
x |
An R object to check for dimensions. |
Value
The .dim
attribute or NULL
if not present.
Compute the Fast Fourier Transform (FFT) of a Vector
Description
Computes the Fast Fourier Transform (FFT) of a numeric vector. Optionally, normalizes the result by dividing it by the length of the input vector.
Usage
.fft(x, norm = FALSE)
Arguments
x |
A numeric vector representing the input signal to transform. |
norm |
A logical value indicating whether to normalize the FFT output
by dividing it by the length of the input vector. Default is |
Details
This function wraps around the base R stats::fft
function and provides an
option for normalization.
Value
A complex vector representing the FFT of the input signal.
See Also
Binary search for the DC row in lexicographically sorted data
Description
Binary search for the DC row in lexicographically sorted data
Usage
.find_dc_row(df)
Arguments
df |
A tibble or data.frame with |
Value
Row index of the DC component (0,0,...,0).
Compute Fourier frequencies for default inputs
Description
Computes normalized Fourier frequencies for scalar or vector inputs, which are evenly spaced between -0.5 and 0.5.
Usage
.fourier_frequencies(x)
Arguments
x |
A scalar or vector representing the length of the sequence. |
Value
A numeric vector containing the normalized Fourier frequencies.
Retrieve Frequency
Description
Retrieves the frequency of a time series object.
Usage
.frequency(x)
Arguments
x |
A |
Value
The frequency value or 1
if not a time series.
Select Columns Starting with .dim_
Description
Selects columns from a data frame whose names start with .dim_
.
Usage
.get_dim_cols(x)
Arguments
x |
A data frame or tibble from which to select columns. |
Value
A data frame containing only the columns that start with .dim_
.
Check if an Object is an Array
Description
Determines if an object has a .dim
attribute, indicating it is an array.
Usage
.is_array(x)
Arguments
x |
An R object. |
Value
TRUE
if the object has a .dim
attribute, FALSE
otherwise.
Check if an Object is Complex
Description
Checks whether an object has the .is_complex
attribute.
Usage
.is_complex(x)
Arguments
x |
An R object to check for complexity. |
Value
A logical value indicating whether the .is_complex
attribute is TRUE
.
Check if an Object is Normalized
Description
Checks whether an object has the .is_normalized
attribute.
Usage
.is_normalized(x)
Arguments
x |
An R object to check for normalization. |
Value
A logical value indicating whether the .is_normalized
attribute is TRUE
.
Returns NULL
if the attribute does not exist.
Check if an Object is a Time Series
Description
Determines if an object has a .tsp
attribute.
Usage
.is_ts(x)
Arguments
x |
An R object. |
Value
TRUE
if the object has a .tsp
attribute, FALSE
otherwise.
Compute the number of samples in an input
Description
This helper function determines the number of samples in the input object. For a vector, it returns its length. For a matrix or data frame, it returns the number of rows.
Usage
.num_samples(x)
Arguments
x |
An input object (scalar, vector, matrix, or data frame). |
Value
An integer representing the number of samples (rows) in the input object.
Compute Nyquist Frequency
Description
Computes the Nyquist frequency for an object.
Usage
.nyquist(x)
Arguments
x |
An R object. |
Value
The Nyquist frequency (.frequency(x) / 2
).
Compute Phase Difference Between Two Signals
Description
Computes the phase difference between two signals based on their cross-spectrum, with symmetric and redundant frequency components removed.
Usage
.phase_diff(a, b)
Arguments
a |
A |
b |
A |
Details
This function computes the cross-spectrum of two signals, removes symmetric and redundant frequency components, converts the result into polar representation, weights the phase angles by their magnitudes, and calculates the weighted average phase difference.
Removing symmetric components ensures accurate phase alignment, avoiding ambiguity caused by redundant negative frequencies.
Value
A numeric value representing the phase difference (in radians) between the two signals.
Set Representation Format
Description
Converts an object into a specific representation format.
Usage
.set_repr(x, repr, .keep = "unused")
Arguments
x |
An R object. |
repr |
The representation type ( |
.keep |
Controls preservation of data. |
Value
The object in the specified representation format.
Shift Phase
Description
Adjusts the phase of Fourier coefficients.
Usage
.shift_phase(x, shift)
Arguments
x |
An R object. |
shift |
A numeric value indicating the phase shift. |
Retrieve Object Size
Description
Retrieves the .size
attribute from an object.
Usage
.size(x)
Arguments
x |
An R object to check for size. |
Value
The .size
attribute or NULL
if not present.
Retrieve Time Series Parameters
Description
Retrieves the .tsp
attribute from an object.
Usage
.tsp(x)
Arguments
x |
An R object. |
Value
The .tsp
attribute or NULL
if not present.
Compute Variance
Description
Computes the variance of Fourier coefficients.
Usage
.variance(x)
Arguments
x |
An R object. |
Value
A numeric variance value.
Add Additional Representations to Fourier Coefficients
Description
These functions add additional representations to a fftab
object without removing or modifying existing representations.
Usage
add_cplx(x)
add_rect(x)
add_polr(x)
Arguments
x |
A |
Details
-
add_cplx()
: Adds a complex ("cplx"
) representation to the Fourier coefficients. -
add_rect()
: Adds a rectangular ("rect"
) representation to the Fourier coefficients. -
add_polr()
: Adds a polar ("polr"
) representation to the Fourier coefficients.
These functions are useful for working with multiple representations simultaneously without overwriting existing data.
Value
A fftab
object with the additional representation included.
See Also
Examples
matrix(1:9, 3) |>
fftab() |>
print(n = 3) |>
add_polr() |>
print(n = 3) |>
add_rect() |>
print(n = 3) |>
add_cplx() |>
print(n = 3)
Add L2 Norm and Squared L2 Norm of Frequency Dimensions
Description
These functions compute and append the L2 norm and squared L2 norm of the frequency dimensions
(.dim_*
columns) as new columns in a fftab
object.
Usage
add_l2nm(x)
add_l2sq(x)
get_l2nm(x)
get_l2sq(x)
Arguments
x |
A |
Details
-
add_l2nm()
: Appends a columnl2nm
containing the L2 norm, calculated as the square root of the sum of squared values across.dim_*
columns. -
add_l2sq()
: Appends a columnl2sq
containing the squared L2 norm, calculated as the sum of squared values across.dim_*
columns. -
get_l2nm()
: Returns a numeric vector representing the L2 norm for each row. -
get_l2sq()
: Returns a numeric vector representing the squared L2 norm for each row.
Value
A vector or fftab
object with additional columns:
-
l2nm
: The L2 norm of the frequency dimensions. -
l2sq
: The squared L2 norm of the frequency dimensions.
See Also
Examples
matrix(1:9, 3) |>
fftab() |>
print(n = 3) |>
add_l2nm() |>
print(n = 3) |>
add_l2sq() |>
print(n = 3)
Manage Representations of a fftab
Object
Description
These functions handle representation management for a fftab
object:
Usage
can_repr(x, repr)
get_repr(x)
set_repr(x, repr)
Arguments
x |
A |
repr |
For |
Details
-
get_repr()
: Retrieve current representations. -
can_repr()
: Check if the object supports specific representations. -
set_repr()
: Convert the object to one or more specified representations.
Value
-
can_repr()
: Logical value (TRUE
orFALSE
) indicating if the object supports the specified representations. -
get_repr()
: A character vector of current representations. -
set_repr()
: A modifiedfftab
object with the specified representation(s).
See Also
Examples
fftab(c(1, 0, -1, 0)) |> can_repr("cplx")
fftab(c(1, 0, -1, 0)) |> get_repr()
fftab(c(1, 0, -1, 0)) |> set_repr(c("polr", "rect"))
Compute the Cross-Spectrum (Cross FFT)
Description
The cross_spec
function computes the cross-spectrum between two inputs
using the Fourier transform. It supports multiple input types including
numeric vectors, time series (ts
), arrays, and fftab
objects.
The function provides options for normalization and controlling whether the
conjugate of the second input is used.
Usage
cross_spec(a, b, norm = FALSE, conj = TRUE)
## Default S3 method:
cross_spec(a, b, norm = FALSE, conj = TRUE)
## S3 method for class 'ts'
cross_spec(a, b, norm = FALSE, conj = TRUE)
## S3 method for class 'array'
cross_spec(a, b, norm = FALSE, conj = TRUE)
## S3 method for class 'fftab'
cross_spec(a, b, norm = FALSE, conj = TRUE)
Arguments
a |
The first input for the cross FFT. Supported types include numeric
vectors, |
b |
The second input for the cross FFT. Must match the dimensions or
structure of |
norm |
Logical; if |
conj |
Logical; if |
Value
An object representing the cross-spectrum:
For
default
andfftab
methods: Afftab
object.For
ts
objects: Afftab
object with.tsp
attributes inherited froma
.For arrays: A
fftab
object with.dim
attributes inherited froma
.
Methods (by class)
-
cross_spec(default)
: Default method for computing cross FFT. Converts inputs tofftab
objects before computation. -
cross_spec(ts)
: Method for time series (ts
) objects. Ensures the time series frequencies are consistent and preserves thetsp
attribute. -
cross_spec(array)
: Method for array inputs. Ensures dimensions are consistent and preserves thedim
attribute. -
cross_spec(fftab)
: Method forfftab
objects. Performs the cross-frequency transform directly using the Fourier transforms ofa
andb
.
See Also
Examples
cross_spec(rnorm(8), rnorm(8), norm = TRUE)
cross_spec(
ts(rnorm(8), frequency = 4),
ts(rnorm(8), frequency = 4)
)
Remove DC Component and Symmetric Frequencies
Description
Internal functions to manipulate and filter Fourier coefficients in fftab
objects.
Usage
.remove_dc(x)
.remove_symmetric(x)
.split_symmetric(x)
Arguments
x |
A |
Details
-
.remove_dc()
: Filters out rows where all.dim_*
columns have a value of0
. -
.remove_symmetric()
:For real-valued signals, it filters out redundant, complex-conjugate frequencies.
For complex-valued signals, no filtering is applied as symmetry isn't relevant.
-
.split_symmetric()
: Splits the coefficients into symmetric and asymmetric parts.
Value
A fftab
object with filtered coefficients.
See Also
Perform FFT and IFFT with Tidy Results
Description
Provides functions to compute the Fast Fourier Transform (FFT) and its inverse (IFFT)
while maintaining results in a tabular format. Supports vectors, time series
(ts
), and arrays as inputs.
Usage
fftab(x, norm = FALSE)
## Default S3 method:
fftab(x, norm = FALSE)
## S3 method for class 'ts'
fftab(x, norm = FALSE)
## S3 method for class 'array'
fftab(x, norm = FALSE)
ifftab(x)
Arguments
x |
Input object for which to compute the FFT or IFFT. This can be:
|
norm |
Logical. If |
Details
-
fftab
organizes FFT results into a tibble for downstream analysis. -
ifftab
ensures that reconstructed signals match the input structure (e.g., arrays,ts
).
Value
-
fftab
: A tibble containing:Fourier frequencies (
.dim_1
,.dim_2
, etc.).FFT values stored in the
fx
column as complex values.
-
ifftab
: A vector, array, or time series object representing the reconstructed signal.
FFT
The fftab
function computes the FFT for different input types:
-
Default Input (
fftab.default
): Computes FFT for numeric vectors. -
Time Series Input (
fftab.ts
): Handles FFT forts
objects, scaling frequencies appropriately. -
Array Input (
fftab.array
): Processes multidimensional arrays.
Results are returned as a tibble containing Fourier frequencies and FFT values.
IFFT
The ifftab
function reconstructs the original signal from a fftab
object.
It supports vectors, arrays, and time series inputs. The inverse transform preserves
the original structure (e.g., array dimensions or time series attributes).
See Also
Examples
fftab(c(1, 0, -1, 0))
fftab(c(1, 0, -1, 0)) |> ifftab()
ts(sin(1:10), frequency = 12) |> fftab()
array(1:8, dim = c(2, 2, 2)) |> fftab()
Compute Fourier Frequencies
Description
Computes Fourier frequencies for various types of inputs, such as scalars, vectors, matrices, time series, or arrays. This generic function dispatches appropriate methods based on the input type.
Usage
fourier_frequencies(x)
## Default S3 method:
fourier_frequencies(x)
## S3 method for class 'ts'
fourier_frequencies(x)
## S3 method for class 'array'
fourier_frequencies(x)
Arguments
x |
The input object. Supported input types:
|
Details
This function has the following methods:
-
Default Input (
fourier_frequencies.default
): Computes normalized Fourier frequencies for scalar or vector inputs. -
Time Series Input (
fourier_frequencies.ts
): Computes frequencies scaled by the frequency attribute of ats
object. -
Multidimensional Arrays (
fourier_frequencies.array
): Computes frequencies for each dimension of a matrix or array.
See the examples for details on each case.
Value
A tibble where:
-
.dim_1
,.dim_2
, ..., represent the Fourier frequencies for each dimension.
See Also
tidyr::expand_grid()
, frequency()
Examples
# Default input (vector)
fourier_frequencies(8)
# Time series input
ts(rnorm(36), frequency = 12) |> fourier_frequencies()
# Multidimensional array input
array(1:27, dim = c(3, 3, 3)) |> fourier_frequencies()
# Matrix input
matrix(1:9, nrow = 3, ncol = 3) |> fourier_frequencies()
Extract Fourier Coefficients and Components
Description
These utility functions extract specific components from a fftab
object.
get_fx
retrieves the raw Fourier coefficients, while get_fx_norm
ensures the
coefficients are either normalized or not normalized based on the norm
parameter.
Usage
get_fx(x)
get_fx_norm(x, norm = FALSE)
get_re(x)
get_im(x)
get_mod(x)
get_arg(x)
Arguments
x |
A |
norm |
Logical. If |
Details
-
get_fx
: Returns coefficients as they are stored in thefftab
object. -
get_fx_norm
: Adjusts coefficients if they are not in the desired normalization state. -
get_re
,get_im
: Extract real and imaginary components. -
get_mod
,get_arg
: Compute magnitude and phase of coefficients.
Value
The requested components:
-
get_fx
: A complex vector of raw Fourier coefficients (fx
) as stored in the object. -
get_fx_norm
: A complex vector of Fourier coefficients, explicitly normalized or non-normalized based on thenorm
parameter. -
get_re
: A numeric vector of real parts (re
). -
get_im
: A numeric vector of imaginary parts (im
). -
get_mod
: A numeric vector of magnitudes (mod
). -
get_arg
: A numeric vector of phase angles (arg
), in radians.
See Also
to_cplx()
, to_rect()
, to_polr()
Examples
fftab(c(1, 0, -1, 0)) |> get_fx()
fftab(c(1, 0, -1, 0)) |> get_fx_norm(norm = TRUE)
fftab(c(1, 0, -1, 0)) |> get_re()
fftab(c(1, 0, -1, 0)) |> get_im()
fftab(c(1, 0, -1, 0)) |> get_mod()
fftab(c(1, 0, -1, 0)) |> get_arg()
Extract Rectangular or Polar Components
Description
The get_rect
and get_polr
functions extract specific components from a
fftab
object, representing the Fourier coefficients in either rectangular
or polar form.
Usage
get_rect(x)
get_polr(x)
Arguments
x |
A matrix object containing FFT results. |
Value
-
get_rect
: A matrix with two columns:-
re
: The real part of the coefficients. -
im
: The imaginary part of the coefficients.
-
-
get_polr
: A matrix with two columns:-
mod
: The magnitude of the coefficients. -
arg
: The phase angle of the coefficients, in radians.
-
See Also
get_fx()
, get_re()
, get_mod()
, to_rect()
, to_polr()
Examples
fftab(c(1, 0, -1, 0)) |> get_rect()
fftab(c(1, 0, -1, 0)) |> get_polr()
Check Representations of a fftab
Object
Description
These functions check if specific representations are present in a fftab
object:
Usage
has_cplx(x)
has_rect(x)
has_polr(x)
Arguments
x |
A |
Details
-
has_cplx()
: Checks if the object has complex representation (fx
column). -
has_rect()
: Checks if the object has rectangular representation (re
,im
columns). -
has_polr()
: Checks if the object has polar representation (mod
,arg
columns).
Value
Logical value (TRUE
or FALSE
) indicating whether the specified representation exists.
See Also
Examples
fftab(c(1, 0, -1, 0)) |> has_cplx()
fftab(c(1, 0, -1, 0)) |> has_rect()
fftab(c(1, 0, -1, 0)) |> has_polr()
Compute Phase Difference and Maximum Correlation Between Two Signals
Description
Computes the phase difference and maximum normalized correlation between two input signals
after phase-aligning the second signal (b
) to the first signal (a
).
Usage
phase_diff(a, b)
Arguments
a |
A numeric vector or time series representing the first signal. |
b |
A numeric vector or time series representing the second signal. |
Details
This function performs the following steps:
Computes the Fourier Transform of both input signals using
fftab
.Calculates the cross-spectrum of the signals.
Converts the cross-spectrum to polar form and computes the weighted average phase difference.
Adjusts the phase of the second signal (
b
) using.shift_phase
to maximize alignment with the first signal (a
).Computes the normalized correlation between the phase-aligned signals.
The correlation is normalized using the variances of both signals and will generally be higher than the correlation between the original signals due to the optimal phase alignment.
Value
A numeric vector of length two:
The first element represents the phase difference (in radians) required to maximize alignment between the two signals.
The second element represents the maximum normalized correlation achieved after phase alignment.
See Also
Examples
phase_diff(
sin(seq(0, 2 * pi, length.out = 128)),
cos(seq(0, 2 * pi, length.out = 128))
)
Plot the modulus of FFT results
Description
Plots the modulus of the FFT results against the frequencies.
Usage
## S3 method for class 'fftab'
plot(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
A ggplot
object representing the modulus of FFT results plotted against the frequencies.
The plot shows the modulus (mod
) on the y-axis and frequency values on the x-axis.
Convert a fftab
Object Between Representations
Description
These functions convert a fftab
object to a specified representation:
-
to_cplx()
: Converts to complex representation (fx
). -
to_rect()
: Converts to rectangular representation (re
,im
). -
to_polr()
: Converts to polar representation (mod
,arg
).
Usage
to_cplx(x, .keep = "unused")
to_rect(x, .keep = "unused")
to_polr(x, .keep = "unused")
Arguments
x |
A |
.keep |
Specifies which columns to retain. See |
Details
-
to_cplx()
: Converts from rectangular (re
,im
) or polar (mod
,arg
) components to complex form. -
to_rect()
: Converts from complex (fx
) or polar components to rectangular form. -
to_polr()
: Converts from complex (fx
) or rectangular components to polar form.
Value
A modified fftab
object containing the specified representation:
-
to_cplx()
: Adds thefx
column for complex values. -
to_rect()
: Adds there
andim
columns for rectangular components. -
to_polr()
: Adds themod
andarg
columns for polar components.
See Also
Examples
fftab(c(1, 0, -1, 0)) |> to_cplx()
fftab(c(1, 0, -1, 0)) |> to_rect()
fftab(c(1, 0, -1, 0)) |> to_polr()