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

logo

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:


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 fftab object or signal representing the first input.

b

A fftab object or signal representing the second input.

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 FALSE.

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

stats::fft()


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 ⁠.dim_*⁠ columns sorted lexicographically.

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 fftab object or time series.

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 fftab object or signal representing the first input.

b

A fftab object or signal representing the second input.

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 ("cplx", "rect", "polr").

.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 fftab object containing Fourier coefficients and associated metadata.

Details

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 fftab object containing frequency dimensions (⁠.dim_*⁠) and associated metadata.

Details

Value

A vector or fftab object with additional columns:

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 fftab object.

repr

For can_repr(), a character vector specifying representations ("polr", "rect", "cplx").

Details

Value

See Also

to_cplx(), has_cplx()

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, ts objects, arrays, and fftab objects.

b

The second input for the cross FFT. Must match the dimensions or structure of a.

norm

Logical; if TRUE, normalizes the Fourier transforms before computation. Default is FALSE.

conj

Logical; if TRUE, uses the complex conjugate of the Fourier transform of b. Default is TRUE.

Value

An object representing the cross-spectrum:

Methods (by class)

See Also

fftab()

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 fftab object containing Fourier coefficients and associated metadata.

Details

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:

  • A numeric vector (default method for fftab).

  • A time series object (ts) for fftab.ts.

  • A multidimensional numeric array for fftab.array.

  • A fftab object for ifftab.

norm

Logical. If TRUE, computes normalized coefficients for FFT.

Details

Value

FFT

The fftab function computes the FFT for different input types:

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

stats::fft()

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:

  • Scalar or vector: The length of the sequence.

  • Time series (ts): Frequencies are scaled based on the sampling rate.

  • Multidimensional array or matrix: Frequencies are computed for each dimension.

Details

This function has the following methods:

See the examples for details on each case.

Value

A tibble where:

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 fftab object containing FFT results.

norm

Logical. If TRUE, forces normalized coefficients. If FALSE, ensures non-normalized coefficients.

Details

Value

The requested components:

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

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 fftab object.

Details

Value

Logical value (TRUE or FALSE) indicating whether the specified representation exists.

See Also

to_cplx(), get_repr()

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

[Experimental]

This function performs the following steps:

  1. Computes the Fourier Transform of both input signals using fftab.

  2. Calculates the cross-spectrum of the signals.

  3. Converts the cross-spectrum to polar form and computes the weighted average phase difference.

  4. Adjusts the phase of the second signal (b) using .shift_phase to maximize alignment with the first signal (a).

  5. 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:

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 fftab object. This should contain Fourier-transformed data.

...

Additional arguments passed to ggplot2::ggplot.

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:

Usage

to_cplx(x, .keep = "unused")

to_rect(x, .keep = "unused")

to_polr(x, .keep = "unused")

Arguments

x

A fftab object.

.keep

Specifies which columns to retain. See dplyr::mutate().

Details

Value

A modified fftab object containing the specified representation:

See Also

has_cplx(), get_repr()

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()