Type: Package
Title: Hemodynamic Response Functions for fMRI Data Analysis
Version: 0.1.0
Description: Creates, manipulates, and evaluates hemodynamic response functions and event-related regressors for functional magnetic resonance imaging data analysis. Supports multiple basis sets including Canonical, Gamma, Gaussian, B-spline, and Fourier bases. Features decorators for time-shifting and blocking, and efficient convolution algorithms for regressor construction. Methods are based on standard fMRI analysis techniques as described in Jezzard et al. (2001, ISBN:9780192630711).
License: MIT + file LICENSE
Encoding: UTF-8
RoxygenNote: 7.3.2.9000
Imports: Rcpp, assertthat, purrr, stats, Matrix, cli, memoise, numDeriv, splines, pracma
LinkingTo: Rcpp, RcppArmadillo
SystemRequirements: C++17
Depends: R (≥ 3.5.0)
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown, ggplot2, dplyr, tidyr, viridis, scales, microbenchmark
VignetteBuilder: knitr
URL: https://bbuchsbaum.github.io/fmrihrf/
BugReports: https://github.com/bbuchsbaum/fmrihrf/issues
NeedsCompilation: yes
Packaged: 2025-09-11 12:12:18 UTC; bbuchsbaum
Author: Bradley Buchsbaum [aut, cre]
Maintainer: Bradley Buchsbaum <brad.buchsbaum@gmail.com>
Repository: CRAN
Date/Publication: 2025-09-16 06:50:02 UTC

fmrihrf: Hemodynamic Response Functions for fMRI Data Analysis

Description

Creates, manipulates, and evaluates hemodynamic response functions and event-related regressors for functional magnetic resonance imaging data analysis. Supports multiple basis sets including Canonical, Gamma, Gaussian, B-spline, and Fourier bases. Features decorators for time-shifting and blocking, and efficient convolution algorithms for regressor construction. Methods are based on standard fMRI analysis techniques as described in Jezzard et al. (2001, ISBN:9780192630711).

Details

The fmrihrf package provides tools for creating, manipulating, and evaluating Hemodynamic Response Functions (HRFs) and event-related regressors for fMRI data analysis.

Author(s)

Maintainer: Bradley Buchsbaum brad.buchsbaum@gmail.com

See Also

Useful links:


HRF Constructor Function

Description

The 'HRF' function creates an object representing a hemodynamic response function (HRF). It is a class constructor for HRFs.

Usage

HRF(fun, name, nbasis = 1, span = 24, param_names = NULL)

Arguments

fun

A function representing the hemodynamic response, mapping from time to BOLD response.

name

A string specifying the name of the function.

nbasis

An integer representing the number of basis functions, e.g., the columnar dimension of the HRF. Default is 1.

span

A numeric value representing the span in seconds of the HRF. Default is 24.

param_names

A character vector containing the names of the parameters for the HRF function.

Details

The package provides several pre-defined HRF types that can be used in modeling fMRI responses:

**Canonical HRFs:** * ‘"spmg1"' or 'HRF_SPMG1': SPM’s canonical HRF (single basis function) * '"spmg2"' or 'HRF_SPMG2': SPM canonical + temporal derivative (2 basis functions) * '"spmg3"' or 'HRF_SPMG3': SPM canonical + temporal and dispersion derivatives (3 basis functions) * '"gaussian"' or 'HRF_GAUSSIAN': Gaussian-shaped HRF with peak around 5-6s * '"gamma"' or 'HRF_GAMMA': Gamma function-based HRF with longer tail

**Flexible basis sets:** * '"bspline"' or '"bs"' or 'HRF_BSPLINE': B-spline basis for flexible HRF modeling * '"tent"': Tent (triangular) basis functions for flexible HRF modeling * '"daguerre"' or 'HRF_DAGUERRE': Daguerre basis functions

To see a complete list of available HRF types with details, use the 'list_available_hrfs()' function.

Value

An HRF object with the specified properties.

Examples

hrf <- HRF(hrf_gamma, "gamma", nbasis=1, param_names=c("shape", "rate"))
resp <- evaluate(hrf, seq(0, 24, by=1))

# List all available HRF types
list_available_hrfs(details = TRUE)


Pre-defined Hemodynamic Response Function Objects

Description

A collection of pre-defined HRF objects for common fMRI analysis scenarios. These objects can be used directly in model specifications or as templates for creating custom HRFs.

Usage

HRF_GAMMA(t, shape = 6, rate = 1)

HRF_GAUSSIAN(t, mean = 6, sd = 2)

HRF_SPMG1(t, P1 = 5, P2 = 15, A1 = 0.0833)

HRF_SPMG2(t)

HRF_SPMG3(t)

HRF_BSPLINE(t)

HRF_FIR(t)

Arguments

t

Numeric vector of time points (in seconds) at which to evaluate the HRF

shape, rate

Parameters for gamma distribution HRF (default: shape=6, rate=1)

mean, sd

Parameters for Gaussian HRF (default: mean=6, sd=2)

P1, P2

Shape parameters for SPM canonical HRF (default: P1=5, P2=15)

A1

Amplitude parameter for SPM canonical HRF (default: 0.0833)

Value

When called as functions, return numeric vectors or matrices of HRF values. When used as objects, they are HRF objects with class c("HRF", "function").

Canonical HRFs

HRF_SPMG1

SPM canonical HRF (single basis function)

HRF_SPMG2

SPM canonical HRF with temporal derivative (2 basis functions)

HRF_SPMG3

SPM canonical HRF with temporal and dispersion derivatives (3 basis functions)

HRF_GAMMA

Gamma function-based HRF

HRF_GAUSSIAN

Gaussian function-based HRF

Flexible Basis Sets

HRF_BSPLINE

B-spline basis HRF (5 basis functions)

HRF_FIR

Finite Impulse Response (FIR) basis HRF (12 basis functions)

Creating Custom Basis Sets

The pre-defined objects above have fixed numbers of basis functions. To create basis sets with custom parameters (e.g., different numbers of basis functions), use one of these approaches:

Using getHRF():

Using generator functions directly:

Usage

All HRF objects can be:

See Also

evaluate.HRF for evaluating HRF objects, gen_hrf for creating HRFs with decorators, list_available_hrfs for listing all HRF types, getHRF for creating HRFs by name with custom parameters, hrf_fir_generator, hrf_bspline_generator, hrf_fourier_generator, hrf_daguerre_generator for creating custom basis sets directly

Other hrf: deriv(), penalty_matrix()

Examples

# Evaluate HRFs at specific time points
times <- seq(0, 20, by = 0.5)

# Single basis canonical HRF
canonical_response <- HRF_SPMG1(times)
plot(times, canonical_response, type = "l", main = "SPM Canonical HRF")

# Multi-basis HRF with derivatives
multi_response <- HRF_SPMG3(times)  # Returns 3-column matrix
matplot(times, multi_response, type = "l", main = "SPM HRF with Derivatives")

# Gamma and Gaussian HRFs
gamma_response <- HRF_GAMMA(times)
gaussian_response <- HRF_GAUSSIAN(times)

# Compare different HRF shapes
plot(times, canonical_response, type = "l", col = "blue", 
     main = "HRF Comparison", ylab = "Response")
lines(times, gamma_response, col = "red")
lines(times, gaussian_response, col = "green")
legend("topright", c("SPM Canonical", "Gamma", "Gaussian"), 
       col = c("blue", "red", "green"), lty = 1)

# Create custom FIR basis with 20 bins
custom_fir <- getHRF("fir", nbasis = 20, span = 30)
fir_response <- evaluate(custom_fir, times)
matplot(times, fir_response, type = "l", main = "Custom FIR with 20 bins")

# Create custom B-spline basis  
custom_bspline <- hrf_bspline_generator(nbasis = 8, span = 25)
bspline_response <- evaluate(custom_bspline, times)
matplot(times, bspline_response, type = "l", main = "Custom B-spline with 8 basis functions")


Internal Constructor for Regressor Objects

Description

Internal Constructor for Regressor Objects

Usage

Reg(
  onsets,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1,
  span = 40,
  summate = TRUE
)

Value

An S3 object of class 'Reg' (and 'list') with components: * 'onsets': Numeric vector of event onset times (seconds). * 'hrf': An object of class 'HRF' used for convolution. * 'duration': Numeric vector of event durations (seconds). * 'amplitude': Numeric vector of event amplitudes/scaling factors. * 'span': Numeric scalar indicating the HRF span (seconds). * 'summate': Logical indicating if overlapping HRF responses should summate. * 'filtered_all': Logical attribute set to 'TRUE' when all events were removed due to zero or 'NA' amplitudes.


Get fMRI Acquisition Onset Times

Description

Calculate the onset time in seconds for each fMRI volume acquisition from the start of the experiment.

Usage

acquisition_onsets(x, ...)

## S3 method for class 'sampling_frame'
acquisition_onsets(x, ...)

Arguments

x

A sampling_frame object

...

Additional arguments (for extensibility)

Details

Returns the temporal onset of each brain volume acquisition, accounting for TR, start_time, and run structure. This is essentially a convenience wrapper around samples(x, global = TRUE) that provides clearer semantic meaning for the common use case of getting acquisition times.

Note: The onset times include the start_time offset (default TR/2), so the first acquisition typically doesn't start at 0.

Value

Numeric vector of acquisition onset times in seconds

See Also

samples for more flexible timing queries

Examples

# Single block with default start_time (TR/2 = 1)
sf <- sampling_frame(blocklens = 100, TR = 2)
onsets <- acquisition_onsets(sf)
head(onsets)  # Returns: 1, 3, 5, 7, 9, 11, ...

# Multiple blocks with same TR
sf2 <- sampling_frame(blocklens = c(100, 120), TR = 2)
onsets2 <- acquisition_onsets(sf2)
# First block: 1, 3, 5, ..., 199
# Second block: 201, 203, 205, ..., 439

# Variable TR per block
sf3 <- sampling_frame(blocklens = c(100, 100), TR = c(2, 1.5))
onsets3 <- acquisition_onsets(sf3)
# First block: 1, 3, 5, ..., 199 (TR=2)
# Second block: 200.75, 202.25, 203.75, ... (TR=1.5, start_time=0.75)

# Custom start times
sf4 <- sampling_frame(blocklens = c(50, 50), TR = 2, start_time = 0)
onsets4 <- acquisition_onsets(sf4)
head(onsets4)  # Returns: 0, 2, 4, 6, 8, 10, ...

Get amplitudes from an object

Description

Generic accessor returning event amplitudes or scaling factors.

Usage

amplitudes(x, ...)

## S3 method for class 'Reg'
amplitudes(x, ...)

Arguments

x

Object containing amplitude information

...

Additional arguments passed to methods

Value

Numeric vector of amplitudes

Examples

# Create a regressor with varying amplitudes
reg <- regressor(onsets = c(1, 5, 10), hrf = HRF_SPMG1,
                 amplitude = c(1, 0.5, 2), 
                 span = 20)
amplitudes(reg)

Turn any function into an HRF object

Description

This is the core constructor for creating HRF objects in the refactored system. It takes a function 'f(t)' and attaches standard HRF attributes.

Usage

as_hrf(
  f,
  name = deparse(substitute(f)),
  nbasis = 1L,
  span = 24,
  params = list()
)

Arguments

f

The function to be turned into an HRF object. It must accept a single argument 't' (time).

name

The name for the HRF object. Defaults to the deparsed name of 'f'.

nbasis

The number of basis functions represented by 'f'. Must be >= 1. Defaults to 1L.

span

The nominal time span (duration in seconds) of the HRF. Must be positive. Defaults to 24.

params

A named list of parameters associated with the HRF function 'f'. Defaults to an empty list.

Value

A new HRF object.

Examples

# Create a custom HRF from a function
custom_hrf <- as_hrf(function(t) exp(-t/5), 
                     name = "exponential", 
                     span = 20)
evaluate(custom_hrf, seq(0, 10, by = 1))

Bind HRFs into a Basis Set

Description

Combines multiple HRF objects into a single multi-basis HRF object. The resulting function evaluates each input HRF at time 't' and returns the results column-bound together.

Usage

bind_basis(...)

Arguments

...

One or more HRF objects created by 'as_hrf' or other HRF constructors/decorators.

Value

A new HRF object representing the combined basis set.

Examples

# Combine multiple HRF basis functions
hrf1 <- as_hrf(hrf_gaussian, params = list(mean = 5))
hrf2 <- as_hrf(hrf_gaussian, params = list(mean = 10))
basis <- bind_basis(hrf1, hrf2)
nbasis(basis)  # Returns 2


Create a Blocked HRF Object

Description

Creates a new HRF object representing a response to a sustained (blocked) stimulus by convolving the input HRF with a boxcar function of a given width.

Usage

block_hrf(
  hrf,
  width,
  precision = 0.1,
  half_life = Inf,
  summate = TRUE,
  normalize = FALSE
)

Arguments

hrf

The HRF object (of class 'HRF') to block.

width

The width of the block in seconds.

precision

The sampling precision in seconds used for the internal convolution (default: 0.1).

half_life

The half-life of an optional exponential decay applied during the block (default: Inf, meaning no decay).

summate

Logical; if TRUE (default), the responses from each time point within the block are summed. If FALSE, the maximum response at each time point is taken.

normalize

Logical; if TRUE, the resulting blocked HRF is scaled so that its peak value is 1 (default: FALSE).

Value

A new HRF object representing the blocked function.

See Also

Other HRF_decorator_functions: lag_hrf(), normalise_hrf()

Examples

blocked_spmg1 <- block_hrf(HRF_SPMG1, width = 5)
t_vals <- seq(0, 30, by = 0.5)
plot(t_vals, HRF_SPMG1(t_vals), type = 'l', col = "blue", ylab = "Response", xlab = "Time")
lines(t_vals, blocked_spmg1(t_vals), col = "red")
legend("topright", legend = c("Original", "Blocked (width=5)"), col = c("blue", "red"), lty = 1)

Get block identifiers

Description

Generic accessor returning block indices for each sample or onset.

Usage

blockids(x, ...)

## S3 method for class 'sampling_frame'
blockids(x, ...)

Arguments

x

Object containing block structure

...

Additional arguments passed to methods

Value

Integer vector of block ids

Examples

# Get block identifiers from a sampling frame
sframe <- sampling_frame(blocklens = c(100, 120, 80), TR = 2)
blockids(sframe)

Get block lengths

Description

Generic accessor returning the number of scans in each block of a sampling frame or similar object.

Usage

blocklens(x, ...)

## S3 method for class 'sampling_frame'
blocklens(x, ...)

Arguments

x

Object containing block length information

...

Additional arguments passed to methods

Value

Numeric vector of block lengths

Examples

# Get block lengths from a sampling frame
sframe <- sampling_frame(blocklens = c(100, 120, 80), TR = 2)
blocklens(sframe)

Compute derivatives of HRF functions

Description

Calculates the derivative of a Hemodynamic Response Function (HRF) at specified time points. This is useful for:

Usage

deriv(x, t, ...)

Arguments

x

An HRF object

t

Numeric vector of time points at which to evaluate the derivative

...

Additional arguments passed to specific methods

Details

The derivative computation method depends on the HRF type:

The default implementation uses numDeriv::grad for numerical differentiation when analytic derivatives are not available.

Value

Numeric vector or matrix of derivative values at the specified time points. For multi-basis HRFs, returns a matrix with one column per basis function.

See Also

[evaluate()], [HRF_objects], [numDeriv::grad()]

Other hrf: HRF_objects, penalty_matrix()

Examples

# Compute derivative of SPM canonical HRF
t <- seq(0, 20, by = 0.1)
hrf_deriv <- deriv(HRF_SPMG1, t)

# Plot HRF and its derivative
hrf_vals <- evaluate(HRF_SPMG1, t)
plot(t, hrf_vals, type = "l", col = "black",
     ylab = "Response", xlab = "Time (s)")
lines(t, hrf_deriv, col = "red", lty = 2)
legend("topright", c("HRF", "Derivative"),
       col = c("black", "red"), lty = c(1, 2))

# For multi-basis HRFs, returns matrix
deriv_matrix <- deriv(HRF_SPMG3, t)
# Returns derivatives for all 3 basis functions


Default derivative method for HRF objects

Description

Uses numerical differentiation via numDeriv::grad when analytic derivatives are not available for a specific HRF type.

Usage

## S3 method for class 'HRF'
deriv(x, t, ...)

Arguments

x

An HRF object

t

Numeric vector of time points at which to evaluate the derivative

...

Additional arguments (currently unused)

Value

Numeric vector or matrix of derivative values


Derivative method for SPMG1 HRF

Description

Uses the analytic derivative formula for the SPM canonical HRF.

Usage

## S3 method for class 'SPMG1_HRF'
deriv(x, t, ...)

Arguments

x

An SPMG1_HRF object

t

Numeric vector of time points at which to evaluate the derivative

...

Additional arguments (currently unused)

Value

Numeric vector of derivative values


Derivative method for SPMG2 HRF

Description

Returns derivatives for both the canonical HRF and its temporal derivative. The first column contains the derivative of the canonical HRF, and the second column contains the second derivative (derivative of the temporal derivative).

Usage

## S3 method for class 'SPMG2_HRF'
deriv(x, t, ...)

Arguments

x

An SPMG2_HRF object

t

Numeric vector of time points at which to evaluate the derivative

...

Additional arguments (currently unused)

Value

Matrix with 2 columns of derivative values


Derivative method for SPMG3 HRF

Description

Returns derivatives for the canonical HRF and its two derivatives. Since SPMG3 already includes first and second derivatives as basis functions, this method returns their derivatives (1st, 2nd, and 3rd derivatives of the original HRF).

Usage

## S3 method for class 'SPMG3_HRF'
deriv(x, t, ...)

Arguments

x

An SPMG3_HRF object

t

Numeric vector of time points at which to evaluate the derivative

...

Additional arguments (currently unused)

Value

Matrix with 3 columns of derivative values


Get durations of an object

Description

Get durations of an object

Usage

durations(x, ...)

## S3 method for class 'Reg'
durations(x, ...)

Arguments

x

The object to get durations from

...

Additional arguments passed to methods

Value

A numeric vector of durations

Examples

# Create a regressor with event durations
reg <- regressor(onsets = c(1, 5, 10), hrf = HRF_SPMG1,
                 duration = c(2, 3, 1), span = 20)
durations(reg)

Generate an Empirical Hemodynamic Response Function

Description

'empirical_hrf' generates an empirical HRF using provided time points and values.

Usage

empirical_hrf(t, y, name = "empirical_hrf")

gen_empirical_hrf(...)

Arguments

t

Time points.

y

Values of HRF at time 't[i]'.

name

Name of the generated HRF.

Value

An instance of type 'HRF'.

Examples

# Create empirical HRF from data points
t_points <- seq(0, 20, by = 1)
y_values <- c(0, 0.1, 0.5, 0.9, 1.0, 0.8, 0.5, 0.2, 0, -0.1, -0.1, 
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
emp_hrf <- empirical_hrf(t_points, y_values)

# Evaluate at new time points
new_times <- seq(0, 25, by = 0.1)
response <- evaluate(emp_hrf, new_times)

Evaluate a regressor object over a time grid

Description

Generic function to evaluate a regressor object over a specified time grid. Different types of regressors may have different evaluation methods.

Usage

evaluate(x, grid, ...)

## S3 method for class 'Reg'
evaluate(
  x,
  grid,
  precision = 0.33,
  method = c("conv", "fft", "Rconv", "loop"),
  sparse = FALSE,
  ...
)

Arguments

x

A 'Reg' object (or an object inheriting from it, like 'regressor').

grid

Numeric vector specifying the time points (seconds) for evaluation.

...

Additional arguments passed down (e.g., to 'evaluate.HRF' in the loop method).

precision

Numeric sampling precision for internal HRF evaluation and convolution (seconds).

method

The evaluation method:

conv

(Default) Uses the C++ direct convolution ('evaluate_regressor_convolution'). Generally safer and more predictable.

fft

Uses the fast C++ FFT convolution ('evaluate_regressor_fast'). Can be faster but may fail with very fine precision or wide grids. Extremely fine 'precision' or wide 'grid' ranges may trigger an internal FFT size exceeding ~1e7, which results in an error.

Rconv

Uses an R-based convolution ('stats::convolve'). Requires constant event durations and a regular sampling grid. Can be faster than the R loop for many events meeting these criteria.

loop

Uses a pure R implementation involving looping through onsets. Can be slower, especially for many onsets.

sparse

Logical indicating whether to return a sparse matrix (from the Matrix package). Default is FALSE.

Value

A numeric vector or matrix containing the evaluated regressor values

See Also

[single_trial_regressor()], [regressor()]

Examples

# Create a regressor
reg <- regressor(onsets = c(10, 30, 50), hrf = HRF_SPMG1)

# Evaluate at specific time points
times <- seq(0, 80, by = 0.1)
response <- evaluate(reg, times)

# Plot the response
plot(times, response, type = "l", xlab = "Time (s)", ylab = "Response")
# Create a regressor
reg <- regressor(onsets = c(10, 30, 50), hrf = HRF_SPMG1)

# Evaluate with default method (conv)
times <- seq(0, 80, by = 0.5)
response <- evaluate(reg, times)

# Try different evaluation methods
response_loop <- evaluate(reg, times, method = "loop")

# With higher precision
response_precise <- evaluate(reg, times, precision = 0.1)

Evaluate an HRF Object

Description

This function evaluates a hemodynamic response function (HRF) object for a given set of time points (grid) and other parameters. It handles both point evaluation (duration=0) and block evaluation (duration > 0).

Usage

## S3 method for class 'HRF'
evaluate(
  x,
  grid,
  amplitude = 1,
  duration = 0,
  precision = 0.2,
  summate = TRUE,
  normalize = FALSE,
  ...
)

Arguments

x

The HRF object (inherits from 'HRF' and 'function').

grid

A numeric vector of time points at which to evaluate the HRF.

amplitude

The scaling value for the event (default: 1).

duration

The duration of the event (seconds). If > 0, the HRF is evaluated over this duration (default: 0).

precision

The temporal resolution for evaluating responses when duration > 0 (default: 0.2).

summate

Logical; whether the HRF response should accumulate over the duration (default: TRUE). If FALSE, the maximum response within the duration window is taken (currently only supported for single-basis HRFs).

normalize

Logical; scale output so that the peak absolute value is 1 (default: FALSE). Applied *after* amplitude scaling and duration processing.

...

Additional arguments (unused).

Value

A numeric vector or matrix of HRF values at the specified time points.

Examples

# Evaluate canonical HRF at specific times
times <- seq(0, 20, by = 0.5)
response <- evaluate(HRF_SPMG1, times)

# Evaluate with amplitude scaling
response_scaled <- evaluate(HRF_SPMG1, times, amplitude = 2)

# Evaluate with duration (block design)
response_block <- evaluate(HRF_SPMG1, times, duration = 5, summate = TRUE)

# Multi-basis HRF evaluation
response_multi <- evaluate(HRF_SPMG3, times)  # Returns 3-column matrix

Construct an HRF Instance using Decorators

Description

'gen_hrf' takes a base HRF function or object and applies optional lag, blocking, and normalization decorators based on arguments.

Usage

gen_hrf(
  hrf,
  lag = 0,
  width = 0,
  precision = 0.1,
  half_life = Inf,
  summate = TRUE,
  normalize = FALSE,
  name = NULL,
  span = NULL,
  ...
)

Arguments

hrf

A function 'f(t)' or an existing 'HRF' object.

lag

Optional lag in seconds. If non-zero, applies 'lag_hrf'.

width

Optional block width in seconds. If non-zero, applies 'block_hrf'.

precision

Sampling precision for block convolution (passed to 'block_hrf'). Default is 0.1.

half_life

Half-life decay parameter for exponential decay in seconds (passed to 'block_hrf'). Default is Inf (no decay).

summate

Whether to summate within blocks (passed to 'block_hrf'). Default is TRUE.

normalize

If TRUE, applies 'normalise_hrf' at the end. Default is FALSE.

name

Optional name for the *final* HRF object. If NULL (default), a name is generated based on the base HRF and applied decorators.

span

Optional span for the *final* HRF object. If NULL (default), the span is determined by the base HRF and decorators.

...

Extra arguments passed to the *base* HRF function if 'hrf' is a function.

Value

A final 'HRF' object, potentially modified by decorators.

Examples

# Lagged SPMG1
grf_lag <- gen_hrf(HRF_SPMG1, lag=3)
# Blocked Gaussian
grf_block <- gen_hrf(hrf_gaussian, width=5, precision=0.2)
# Lagged and Blocked, then Normalized
grf_both_norm <- gen_hrf(HRF_SPMG1, lag=2, width=4, normalize=TRUE)


Generate a Blocked HRF Function

Description

The 'gen_hrf_blocked' function creates a blocked HRF by convolving the input HRF with a boxcar function. This can be used to model block designs in fMRI analysis.

Usage

gen_hrf_blocked(
  hrf = hrf_gaussian,
  width = 5,
  precision = 0.1,
  half_life = Inf,
  summate = TRUE,
  normalize = FALSE,
  ...
)

hrf_blocked(
  hrf = hrf_gaussian,
  width = 5,
  precision = 0.1,
  half_life = Inf,
  summate = TRUE,
  normalize = FALSE,
  ...
)

Arguments

hrf

A function representing the hemodynamic response function. Default is 'hrf_gaussian'.

width

A numeric value specifying the width of the block in seconds. Default is 5.

precision

A numeric value specifying the sampling resolution in seconds. Default is 0.1.

half_life

A numeric value specifying the half-life of the exponential decay function, used to model response attenuation. Default is 'Inf', which means no decay.

summate

A logical value indicating whether to allow each impulse response function to "add" up. Default is 'TRUE'.

normalize

A logical value indicating whether to rescale the output so that the peak of the output is 1. Default is 'FALSE'.

...

Extra arguments passed to the HRF function.

Value

A function representing the blocked HRF.

A function representing the blocked HRF.

Functions

See Also

Other gen_hrf: gen_hrf_lagged()

Examples

# Deprecated: use gen_hrf(..., width = 10) or block_hrf(HRF, width = 10)

Generate a Lagged HRF Function

Description

The 'gen_hrf_lagged' function takes an HRF function and applies a specified lag to it. This can be useful for modeling time-delayed hemodynamic responses.

Usage

gen_hrf_lagged(hrf, lag = 2, normalize = FALSE, ...)

hrf_lagged(hrf, lag = 2, normalize = FALSE, ...)

Arguments

hrf

A function representing the underlying HRF to be shifted.

lag

A numeric value specifying the lag or delay in seconds to apply to the HRF. This can also be a vector of lags, in which case the function returns an HRF set.

normalize

A logical value indicating whether to rescale the output so that the maximum absolute value is 1. Defaults to 'FALSE'.

...

Extra arguments supplied to the 'hrf' function.

Value

A function representing the lagged HRF. If 'lag' is a vector of lags, the function returns an HRF set.

an lagged hrf function

Functions

See Also

Other gen_hrf: gen_hrf_blocked()

Other gen_hrf: gen_hrf_blocked()

Examples


hrf_lag5 <- gen_hrf_lagged(HRF_SPMG1, lag=5)
hrf_lag5(0:20)



Get HRF by Name

Description

Retrieves an HRF by name from the registry and optionally applies decorators. This provides a unified interface for creating both pre-defined HRF objects and custom basis sets with specified parameters.

Usage

getHRF(
  name = "spmg1",
  nbasis = 5,
  span = 24,
  lag = 0,
  width = 0,
  summate = TRUE,
  normalize = FALSE,
  ...
)

Arguments

name

Character string specifying the HRF type. Options include:

  • "spmg1", "spmg2", "spmg3" - SPM canonical HRFs

  • "gamma", "gaussian" - Simple parametric HRFs

  • "fir" - Finite Impulse Response basis

  • "bspline" or "bs" - B-spline basis

  • "fourier" - Fourier basis

  • "daguerre" - Daguerre spherical basis

  • "tent" - Tent (linear spline) basis

nbasis

Number of basis functions (for basis set types)

span

Temporal window in seconds (default: 24)

lag

Time lag in seconds to apply (default: 0)

width

Block width for block designs (default: 0)

summate

Whether to sum responses in block designs (default: TRUE)

normalize

Whether to normalize the HRF (default: FALSE)

...

Additional arguments passed to generator functions (e.g., scale for daguerre)

Details

For single HRF types (spmg1, gamma, gaussian), the function returns pre-defined objects. For basis set types (fir, bspline, fourier, daguerre), it calls the appropriate generator function with the specified parameters.

Value

An HRF object

Examples

# Get pre-defined canonical HRF
canonical <- getHRF("spmg1")

# Create custom FIR basis with 20 bins
fir20 <- getHRF("fir", nbasis = 20, span = 30)

# Create B-spline basis with lag
bs_lag <- getHRF("bspline", nbasis = 8, lag = 2)

# Create blocked Gaussian HRF
block_gauss <- getHRF("gaussian", width = 5)

Convert onsets to global timing

Description

Generic accessor for converting block-wise onsets to global onsets.

Usage

global_onsets(x, ...)

## S3 method for class 'sampling_frame'
global_onsets(x, onsets, blockids, ...)

Arguments

x

Object describing the sampling frame

...

Additional arguments passed to methods

onsets

Numeric vector of onset times within blocks

blockids

Integer vector identifying the block for each onset. Values must be whole numbers with no NAs.

Value

Numeric vector of global onset times

Examples

# Convert block-relative onsets to global timing
sframe <- sampling_frame(blocklens = c(100, 120), TR = 2)
global_onsets(sframe, onsets = c(10, 20), blockids = c(1, 2))

LWU HRF Basis for Taylor Expansion

Description

Constructs the basis set for the Lag-Width-Undershoot (LWU) HRF model, intended for Taylor expansion-based fitting. The basis consists of the LWU HRF evaluated at a given expansion point theta0, and its partial derivatives with respect to its parameters (tau, sigma, rho).

Usage

hrf_basis_lwu(theta0, t, normalize_primary = "none")

Arguments

theta0

A numeric vector of length 3 specifying the expansion point c(tau0, sigma0, rho0) for the LWU parameters.

t

A numeric vector of time points (in seconds) at which to evaluate the basis.

normalize_primary

Character string, one of "none" or "height". If "height", the primary HRF column (h0(t)) is normalized to have a peak absolute value of 1. For Taylor expansion fitting as described in Fit_LRU.md, this should typically be "none" as the scaling is absorbed by the beta coefficient. Default is "none".

Value

A numeric matrix of dimension length(t) x 4. The columns represent:

See Also

hrf_lwu, grad

Other hrf_functions: hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

t_points <- seq(0, 30, by = 0.5)
theta0_default <- c(tau = 6, sigma = 1, rho = 0.35)

# Generate the basis set
lwu_basis <- hrf_basis_lwu(theta0_default, t_points)
dim(lwu_basis) # Should be length(t_points) x 4
head(lwu_basis)

# Plot the basis functions
matplot(t_points, lwu_basis, type = "l", lty = 1,
        main = "LWU HRF Basis Functions", ylab = "Value", xlab = "Time (s)")
legend("topright", colnames(lwu_basis), col = 1:4, lty = 1, cex = 0.8)

# Example with primary HRF normalization (not typical for Taylor fitting step)
lwu_basis_norm_h0 <- hrf_basis_lwu(theta0_default, t_points, normalize_primary = "height")
plot(t_points, lwu_basis_norm_h0[,1], type="l", main="Normalized h0 in Basis")
max(abs(lwu_basis_norm_h0[,1])) # Should be 1

B-spline HRF (hemodynamic response function)

Description

The 'hrf_bspline' function computes the B-spline representation of an HRF (hemodynamic response function) at given time points 't'.

Usage

hrf_bspline(t, span = 24, N = 5, degree = 3, ...)

Arguments

t

A vector of time points.

span

A numeric value representing the temporal window over which the basis set spans. Default value is 20.

N

An integer representing the number of basis functions. Default value is 5.

degree

An integer representing the degree of the spline. Default value is 3.

...

Additional arguments passed to 'splines::bs'.

Value

A matrix representing the B-spline basis for the HRF at the given time points 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

# Compute the B-spline HRF representation for time points from 0 to 20 with 0.5 increments
hrfb <- hrf_bspline(seq(0, 20, by = .5), N = 4, degree = 2)

Create B-spline HRF Basis Set

Description

Generates an HRF object using B-spline basis functions with custom parameters. This is the generator function that creates HRF objects with variable numbers of basis functions, unlike the pre-defined HRF_BSPLINE which has 5 functions.

Usage

hrf_bspline_generator(nbasis = 5, span = 24)

Arguments

nbasis

Number of basis functions (default: 5)

span

Temporal window in seconds (default: 24)

Value

An HRF object of class c("BSpline_HRF", "HRF", "function")

See Also

HRF_objects for pre-defined HRF objects, getHRF for a unified interface to create HRFs

Examples

# Create B-spline basis with 10 functions
custom_bs <- hrf_bspline_generator(nbasis = 10)
t <- seq(0, 24, by = 0.1)
response <- evaluate(custom_bs, t)
matplot(t, response, type = "l", main = "B-spline HRF with 10 basis functions")

Create Daguerre HRF Basis Set

Description

Generates an HRF object using Daguerre spherical basis functions with custom parameters. These are orthogonal polynomials that naturally decay to zero.

Usage

hrf_daguerre_generator(nbasis = 3, scale = 4)

Arguments

nbasis

Number of basis functions (default: 3)

scale

Scale parameter for the time axis (default: 4)

Details

Daguerre basis functions are orthogonal polynomials on [0,Inf) with respect to the weight function w(x) = x^2 * exp(-x). They are particularly useful for modeling hemodynamic responses as they naturally decay to zero and can capture various response shapes with few parameters.

Value

An HRF object of class c("Daguerre_HRF", "HRF", "function")

See Also

HRF_objects for pre-defined HRF objects, getHRF for a unified interface to create HRFs

Examples

# Create Daguerre basis with 5 functions
custom_dag <- hrf_daguerre_generator(nbasis = 5, scale = 3)
t <- seq(0, 24, by = 0.1)
response <- evaluate(custom_dag, t)
matplot(t, response, type = "l", main = "Daguerre HRF with 5 basis functions")

Create FIR HRF Basis Set

Description

Generates an HRF object using Finite Impulse Response (FIR) basis functions with custom parameters. Each basis function represents a time bin with a value of 1 in that bin and 0 elsewhere.

Usage

hrf_fir_generator(nbasis = 12, span = 24)

Arguments

nbasis

Number of time bins (default: 12)

span

Temporal window in seconds (default: 24)

Details

The FIR basis divides the time window into nbasis equal bins. Each basis function is an indicator function for its corresponding bin. This provides maximum flexibility but requires more parameters than smoother basis sets like B-splines.

Value

An HRF object of class c("FIR_HRF", "HRF", "function")

See Also

HRF_objects for pre-defined HRF objects, getHRF for a unified interface to create HRFs, hrf_bspline_generator for a smoother alternative

Examples

# Create FIR basis with 20 bins over 30 seconds
custom_fir <- hrf_fir_generator(nbasis = 20, span = 30)
t <- seq(0, 30, by = 0.1)
response <- evaluate(custom_fir, t)
matplot(t, response, type = "l", main = "FIR HRF with 20 time bins")

# Compare to default FIR with 12 bins
default_fir <- HRF_FIR
response_default <- evaluate(default_fir, t[1:241])  # 24 seconds
matplot(t[1:241], response_default, type = "l", 
        main = "Default FIR HRF (12 bins over 24s)")

Fourier basis for HRF modeling

Description

Generates a set of Fourier basis functions (sine and cosine pairs) over a given span.

Usage

hrf_fourier(t, span = 24, nbasis = 5)

Arguments

t

A vector of time points.

span

The temporal window over which the basis functions span (default: 24).

nbasis

The number of basis functions (default: 5). Should be even for full sine-cosine pairs.

Value

A matrix of Fourier basis functions with nbasis columns.

Examples

# Create Fourier basis with 5 functions
t <- seq(0, 24, by = 0.5)
basis <- hrf_fourier(t, span = 24, nbasis = 5)
matplot(t, basis, type = "l", main = "Fourier Basis Functions")

Create Fourier HRF Basis Set

Description

Generates an HRF object using Fourier basis functions (sine and cosine pairs) with custom parameters.

Usage

hrf_fourier_generator(nbasis = 5, span = 24)

Arguments

nbasis

Number of basis functions (default: 5). Should be even for complete sine-cosine pairs.

span

Temporal window in seconds (default: 24)

Details

The Fourier basis uses alternating sine and cosine functions with increasing frequencies. This provides a smooth, periodic basis set that can capture oscillatory components in the HRF.

Value

An HRF object of class c("Fourier_HRF", "HRF", "function")

See Also

HRF_objects for pre-defined HRF objects, getHRF for a unified interface to create HRFs

Examples

# Create Fourier basis with 8 functions
custom_fourier <- hrf_fourier_generator(nbasis = 8)
t <- seq(0, 24, by = 0.1)
response <- evaluate(custom_fourier, t)
matplot(t, response, type = "l", main = "Fourier HRF with 8 basis functions")

Combine HRF Basis with Coefficients

Description

Create a new HRF by linearly weighting the basis functions of an existing HRF. Useful when coefficients have been estimated for an FIR/bspline/SPMG3 basis and one wants a single functional HRF.

Usage

hrf_from_coefficients(hrf, h, ...)

## S3 method for class 'HRF'
hrf_from_coefficients(hrf, h, name = NULL, ...)

Arguments

hrf

An object of class 'HRF'.

h

Numeric vector of length 'nbasis(hrf)' giving the weights.

...

Reserved for future extensions.

name

Optional name for the resulting HRF.

Value

A new 'HRF' object with 'nbasis = 1'.

Examples

# Create a custom HRF from SPMG3 basis coefficients
coeffs <- c(1, 0.2, -0.1)  # Main response + slight temporal shift - dispersion
custom_hrf <- hrf_from_coefficients(HRF_SPMG3, coeffs)

# Evaluate the custom HRF
t <- seq(0, 20, by = 0.1)
response <- evaluate(custom_hrf, t)

# Create from FIR basis
fir_coeffs <- c(0, 0.2, 0.5, 1, 0.8, 0.4, 0.1, 0, 0, 0, 0, 0)
custom_fir <- hrf_from_coefficients(HRF_FIR, fir_coeffs)

Gamma HRF (hemodynamic response function)

Description

The 'hrf_gamma' function computes the gamma density-based HRF (hemodynamic response function) at given time points 't'.

Usage

hrf_gamma(t, shape = 6, rate = 1)

Arguments

t

A vector of time points.

shape

A numeric value representing the shape parameter for the gamma probability density function. Default value is 6.

rate

A numeric value representing the rate parameter for the gamma probability density function. Default value is 1.

Value

A numeric vector representing the gamma HRF at the given time points 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

# Compute the gamma HRF representation for time points from 0 to 20 with 0.5 increments
hrf_gamma_vals <- hrf_gamma(seq(0, 20, by = .5), shape = 6, rate = 1)

Gaussian HRF (hemodynamic response function)

Description

The 'hrf_gaussian' function computes the Gaussian density-based HRF (hemodynamic response function) at given time points 't'.

Usage

hrf_gaussian(t, mean = 6, sd = 2)

Arguments

t

A vector of time points.

mean

A numeric value representing the mean of the Gaussian probability density function. Default value is 6.

sd

A numeric value representing the standard deviation of the Gaussian probability density function. Default value is 2.

Value

A numeric vector representing the Gaussian HRF at the given time points 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

# Compute the Gaussian HRF representation for time points from 0 to 20 with 0.5 increments
hrf_gaussian_vals <- hrf_gaussian(seq(0, 20, by = .5), mean = 6, sd = 2)

Hemodynamic Response Function with Half-Cosine Basis

Description

This function models a hemodynamic response function (HRF) using four half-period cosine basis functions. The HRF consists of an initial dip, a rise to peak, a fall and undershoot, and a recovery to the baseline.

Usage

hrf_half_cosine(t, h1 = 1, h2 = 5, h3 = 7, h4 = 7, f1 = 0, f2 = 0)

Arguments

t

Time points at which to evaluate the HRF

h1

Duration of initial fall from f1 to 0 (default: 1)

h2

Duration of rise from 0 to 1 (default: 5)

h3

Duration of fall from 1 to 0 (default: 7)

h4

Duration of final rise from 0 to f2 (default: 7)

f1

Initial baseline level (default: 0)

f2

Final baseline level (default: 0)

Value

A vector of HRF values corresponding to the input time values.

Numeric vector of HRF values at time points t

References

Woolrich, M. W., Behrens, T. E., & Smith, S. M. (2004). Constrained linear basis sets for HRF modelling using Variational Bayes. NeuroImage, 21(4), 1748-1761.

Half-cosine HRF

Creates a hemodynamic response function using half-cosine segments. The function consists of four phases controlled by h1-h4 parameters, with transitions between baseline (f1) and peak (1) and final (f2) levels.

Examples

# Standard half-cosine HRF
t <- seq(0, 30, by = 0.1)
hrf <- hrf_half_cosine(t)
plot(t, hrf, type = "l", main = "Half-cosine HRF")

# Modified shape with undershoot
hrf_under <- hrf_half_cosine(t, h1 = 1, h2 = 4, h3 = 6, h4 = 8, f2 = -0.2)
lines(t, hrf_under, col = "red")

hrf_inv_logit

Description

A hemodynamic response function using the difference of two Inverse Logit functions.

Usage

hrf_inv_logit(t, mu1 = 6, s1 = 1, mu2 = 16, s2 = 1, lag = 0)

Arguments

t

A vector of times.

mu1

The time-to-peak for the rising phase (mean of the first logistic function).

s1

The width (slope) of the first logistic function.

mu2

The time-to-peak for the falling phase (mean of the second logistic function).

s2

The width (slope) of the second logistic function.

lag

The time delay (default: 0).

Value

A vector of the difference of two Inverse Logit HRF values.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

hrf_inv_logit_basis <- hrf_inv_logit(seq(0, 20, by = 0.5), mu1 = 6, s1 = 1, mu2 = 16, s2 = 1)

Generate an HRF library from a parameter grid

Description

'hrf_library' applies a base HRF generating function to each row of a parameter grid.

Usage

hrf_library(fun, pgrid, ...)

gen_hrf_library(...)

Arguments

fun

A function that generates an HRF, given a set of parameters.

pgrid

A data frame where each row is a set of parameters.

...

Additional arguments passed to 'fun'.

Value

A combined HRF object representing the library.

Examples

# Create library of gamma HRFs with varying parameters
param_grid <- expand.grid(
  shape = c(6, 8, 10),
  rate = c(0.9, 1, 1.1)
)
gamma_library <- hrf_library(
  function(shape, rate) as_hrf(hrf_gamma, params = list(shape = shape, rate = rate)),
  param_grid
)

# Create library with fixed and varying parameters
param_grid2 <- expand.grid(lag = c(0, 2, 4))
lagged_library <- hrf_library(
  function(lag) gen_hrf(HRF_SPMG1, lag = lag),
  param_grid2
)

Lag-Width-Undershoot (LWU) HRF

Description

Computes the Lag-Width-Undershoot (LWU) hemodynamic response function. This model uses two Gaussian components to model the main response and an optional undershoot.

Usage

hrf_lwu(t, tau = 6, sigma = 2.5, rho = 0.35, normalize = "none")

Arguments

t

A numeric vector of time points (in seconds).

tau

Lag of the main Gaussian component (time-to-peak of the positive lobe, in seconds). Default: 6.

sigma

Width (standard deviation) of the main Gaussian component (in seconds). Must be > 0.05. Default: 2.5.

rho

Amplitude of the undershoot Gaussian component, relative to the main component. Must be between 0 and 1.5. Default: 0.35.

normalize

Character string specifying normalization type. Either "none" for no normalization (default) or "height" to scale the HRF so its maximum absolute value is 1.

Details

The LWU model formula combines a positive Gaussian peak and a negative undershoot: h(t; tau, sigma, rho) = exp(-(t-tau)^2/(2*sigma^2)) - rho * exp(-(t-tau-2*sigma)^2/(2*(1.6*sigma)^2))

Value

A numeric vector representing the LWU HRF values at the given time points 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_mexhat(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

t_points <- seq(0, 30, by = 0.1)

# Default LWU HRF
lwu_default <- hrf_lwu(t_points)
plot(t_points, lwu_default, type = "l", main = "LWU HRF (Default Params)", ylab = "Amplitude")

# LWU HRF with no undershoot
lwu_no_undershoot <- hrf_lwu(t_points, rho = 0)
lines(t_points, lwu_no_undershoot, col = "blue")

# LWU HRF with a wider main peak and larger undershoot
lwu_custom <- hrf_lwu(t_points, tau = 7, sigma = 1.5, rho = 0.5)
lines(t_points, lwu_custom, col = "red")
legend("topright", c("Default", "No Undershoot (rho=0)", "Custom (tau=7, sigma=1.5, rho=0.5)"),
       col = c("black", "blue", "red"), lty = 1, cex = 0.8)

# Height-normalized HRF
lwu_normalized <- hrf_lwu(t_points, tau = 6, sigma = 1, rho = 0.35, normalize = "height")
plot(t_points, lwu_normalized, type = "l", main = "Height-Normalized LWU HRF", ylab = "Amplitude")
abline(h = c(-1, 1), lty = 2, col = "grey") # Max absolute value should be 1

Mexican Hat HRF (hemodynamic response function)

Description

The 'hrf_mexhat' function computes the Mexican hat wavelet-based HRF (hemodynamic response function) at given time points 't'.

Usage

hrf_mexhat(t, mean = 6, sd = 2)

Arguments

t

A vector of time points.

mean

A numeric value representing the mean of the Mexican hat wavelet. Default value is 6.

sd

A numeric value representing the standard deviation of the Mexican hat wavelet. Default value is 2.

Value

A numeric vector representing the Mexican hat wavelet-based HRF at the given time points 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_sine(), hrf_spmg1(), hrf_time()

Examples

# Compute the Mexican hat HRF representation for time points from 0 to 20 with 0.5 increments
hrf_mexhat_vals <- hrf_mexhat(seq(0, 20, by = .5), mean = 6, sd = 2)

Generate an HRF Basis Set

Description

'hrf_set' constructs an HRF basis set from one or more component HRF objects.

Usage

hrf_set(..., name = "hrf_set")

gen_hrf_set(...)

Arguments

...

One or more HRF objects.

name

The name for the combined HRF set.

Value

A combined HRF object.

Examples

# Combine multiple HRF types into a basis set
hrf_basis <- hrf_set(HRF_SPMG1, HRF_GAUSSIAN, HRF_GAMMA)

# Create custom basis with different parameters
hrf1 <- gen_hrf(hrf_gamma, alpha = 6, beta = 1)
hrf2 <- gen_hrf(hrf_gamma, alpha = 8, beta = 1)
custom_basis <- hrf_set(hrf1, hrf2, name = "custom_gamma_basis")

# Evaluate the basis set
t <- seq(0, 30, by = 0.1)
basis_response <- evaluate(hrf_basis, t)

hrf_sine

Description

A hemodynamic response function using the Sine Basis Set.

Usage

hrf_sine(t, span = 24, N = 5)

Arguments

t

A vector of times.

span

The temporal window over which the basis sets span (default: 24).

N

The number of basis functions (default: 5).

Value

A matrix of sine basis functions.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_spmg1(), hrf_time()

Examples

hrf_sine_basis <- hrf_sine(seq(0, 20, by = 0.5), N = 4)

hrf_spmg1

Description

A hemodynamic response function based on the SPM canonical double gamma parameterization.

Usage

hrf_spmg1(t, P1 = 5, P2 = 15, A1 = 0.0833)

Arguments

t

A vector of time points.

P1

The first exponent parameter (default: 5).

P2

The second exponent parameter (default: 15).

A1

Amplitude scaling factor for the positive gamma function component; normally fixed at .0833

Details

This function models the hemodynamic response using the canonical double gamma parameterization in the SPM software. The HRF is defined by a linear combination of two gamma functions with different exponents (P1 and P2) and amplitudes (A1 and A2). It is commonly used in fMRI data analysis to estimate the BOLD (blood-oxygen-level-dependent) signal changes associated with neural activity.

Value

A vector of HRF values at the given time points.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_time()

Examples

# Generate a time vector
time_points <- seq(0, 30, by=0.1)
# Compute the HRF values using the SPM canonical double gamma parameterization
hrf_values <- hrf_spmg1(time_points)
# Plot the HRF values
plot(time_points, hrf_values, type='l', main='SPM Canonical Double Gamma HRF')

HRF (hemodynamic response function) as a linear function of time

Description

The 'hrf_time' function computes the value of an HRF, which is a simple linear function of time 't', when 't' is greater than 0 and less than 'maxt'.

Usage

hrf_time(t, maxt = 22)

Arguments

t

A numeric value representing time in seconds.

maxt

A numeric value representing the maximum time point in the domain. Default value is 22.

Value

A numeric value representing the value of the HRF at the given time 't'.

See Also

Other hrf_functions: hrf_basis_lwu(), hrf_bspline(), hrf_gamma(), hrf_gaussian(), hrf_inv_logit(), hrf_lwu(), hrf_mexhat(), hrf_sine(), hrf_spmg1()

Examples

# Compute the HRF value for t = 5 seconds with the default maximum time
hrf_val <- hrf_time(5)

# Compute the HRF value for t = 5 seconds with a custom maximum time of 30 seconds
hrf_val_custom_maxt <- hrf_time(5, maxt = 30)

HRF Toeplitz Matrix

Description

Create a Toeplitz matrix for hemodynamic response function (HRF) convolution.

Usage

hrf_toeplitz(hrf, time, len, sparse = FALSE)

Arguments

hrf

The hemodynamic response function.

time

A numeric vector representing the time points.

len

The length of the output Toeplitz matrix.

sparse

Logical, if TRUE, the output Toeplitz matrix is returned as a sparse matrix (default: FALSE).

Value

A Toeplitz matrix for HRF convolution.

Examples

# Create HRF and time points
hrf_fun <- function(t) hrf_spmg1(t)
times <- seq(0, 30, by = 1)

# Create Toeplitz matrix
H <- hrf_toeplitz(hrf_fun, times, len = 50)

# Create sparse version
H_sparse <- hrf_toeplitz(hrf_fun, times, len = 50, sparse = TRUE)

Lag an HRF Object

Description

Creates a new HRF object by applying a temporal lag to an existing HRF object.

Usage

lag_hrf(hrf, lag)

Arguments

hrf

The HRF object (of class 'HRF') to lag.

lag

The time lag in seconds to apply. Positive values shift the response later in time.

Value

A new HRF object representing the lagged function.

See Also

Other HRF_decorator_functions: block_hrf(), normalise_hrf()

Examples

lagged_spmg1 <- lag_hrf(HRF_SPMG1, 5)
# Evaluate at time 10; equivalent to HRF_SPMG1(10 - 5)
lagged_spmg1(10)
HRF_SPMG1(5)

List all available hemodynamic response functions (HRFs)

Description

Reads the internal HRF registry to list available HRF types.

Usage

list_available_hrfs(details = FALSE)

Arguments

details

Logical; if TRUE, attempt to add descriptions (basic for now).

Value

A data frame with columns: name, type (object/generator), nbasis_default.

Examples

# List all available HRFs
hrfs <- list_available_hrfs()
print(hrfs)

# List with details
hrfs_detailed <- list_available_hrfs(details = TRUE)
print(hrfs_detailed)

Create an HRF from a basis specification

Description

'make_hrf' resolves a basis specification to an 'HRF' object and applies an optional temporal lag. The basis may be given as the name of a built-in HRF, as a generating function, or as an existing 'HRF' object.

Usage

make_hrf(basis, lag, nbasis = 1)

Arguments

basis

Character name of a built-in HRF, a function that generates HRF values, or an object of class 'HRF'.

lag

Numeric scalar giving the shift in seconds applied to the HRF.

nbasis

Integer specifying the number of basis functions when 'basis' is provided as a name.

Value

An object of class 'HRF' representing the lagged basis.

Examples

# Canonical SPM HRF delayed by 2 seconds
h <- make_hrf("spmg1", lag = 2)
h(0:5)


Number of basis functions

Description

Return the number of basis functions represented by an object.

Usage

nbasis(x, ...)

## S3 method for class 'HRF'
nbasis(x, ...)

## S3 method for class 'Reg'
nbasis(x, ...)

Arguments

x

Object containing HRF or regressor information.

...

Additional arguments passed to methods.

Details

This information is typically used when constructing penalty matrices or understanding the complexity of an HRF model or regressor.

Value

Integer scalar giving the number of basis functions.

Examples

# Number of basis functions for different HRF types
nbasis(HRF_SPMG1)   # 1 basis function
nbasis(HRF_SPMG3)   # 3 basis functions (canonical + 2 derivatives)
nbasis(HRF_BSPLINE) # 5 basis functions (default)

# For a regressor
reg <- regressor(onsets = c(10, 30, 50), hrf = HRF_SPMG3)
nbasis(reg)  # 3 (inherits from the HRF)

Generate Neural Input Function from Event Timing

Description

Converts event timing information into a neural input function representing the underlying neural activity before HRF convolution. This function is useful for:

Usage

neural_input(x, ...)

## S3 method for class 'Reg'
neural_input(x, start = 0, end = NULL, resolution = 0.33, ...)

Arguments

x

A regressor object containing event timing information

...

Additional arguments passed to methods

start

Numeric; start time of the input function

end

Numeric; end time of the input function

resolution

Numeric; temporal resolution in seconds (default: 0.33)

Details

stimulus

Creating stimulus functions for fMRI analysis

modeling

Modeling sustained vs. transient neural activity

inputs

Generating inputs for HRF convolution

visualization

Visualizing the temporal structure of experimental designs

Value

A list containing:

time

Numeric vector of time points

neural_input

Numeric vector of input amplitudes at each time point

See Also

regressor, evaluate.Reg, HRF_SPMG1

Examples

# Create a regressor with multiple events
reg <- regressor(
  onsets = c(10, 30, 50),
  duration = c(2, 2, 2),
  amplitude = c(1, 1.5, 0.8),
  hrf = HRF_SPMG1
)

# Generate neural input function
input <- neural_input(reg, start = 0, end = 60, resolution = 0.5)

# Plot the neural input function
plot(input$time, input$neural_input, type = "l",
     xlab = "Time (s)", ylab = "Neural Input",
     main = "Neural Input Function")

# Create regressor with varying durations
reg_sustained <- regressor(
  onsets = c(10, 30),
  duration = c(5, 10),  # sustained activity
  amplitude = c(1, 1),
  hrf = HRF_SPMG1
)

# Generate and compare neural inputs
input_sustained <- neural_input(
  reg_sustained,
  start = 0,
  end = 60,
  resolution = 0.5
)


Normalise an HRF Object

Description

Creates a new HRF object whose output is scaled such that the maximum absolute value of the response is 1.

Usage

normalise_hrf(hrf)

Arguments

hrf

The HRF object (of class 'HRF') to normalise.

Details

For multi-basis HRFs, each basis function (column) is normalised independently.

Value

A new HRF object representing the normalised function.

See Also

Other HRF_decorator_functions: block_hrf(), lag_hrf()

Examples

# Create a gaussian HRF with a peak value != 1
gauss_unnorm <- as_hrf(function(t) 5 * dnorm(t, 6, 2), name="unnorm_gauss")
# Normalise it
gauss_norm <- normalise_hrf(gauss_unnorm)
t_vals <- seq(0, 20, by = 0.1)
max(gauss_unnorm(t_vals)) # Peak is > 1
max(gauss_norm(t_vals))   # Peak is 1

Get event onsets from an object

Description

Generic accessor returning event onset times in seconds.

Usage

onsets(x, ...)

## S3 method for class 'Reg'
onsets(x, ...)

Arguments

x

Object containing onset information

...

Additional arguments passed to methods

Value

Numeric vector of onsets

Examples

# Create a regressor with event onsets
reg <- regressor(onsets = c(1, 5, 10, 15), hrf = HRF_SPMG1, span = 20)
onsets(reg)

Generate penalty matrix for regularization

Description

Generate a penalty matrix for regularizing HRF basis coefficients. The penalty matrix encodes shape priors that discourage implausible or overly wiggly HRF estimates. Different HRF types use different penalty structures:

Usage

penalty_matrix(x, ...)

## S3 method for class 'HRF'
penalty_matrix(x, order = 2, ...)

## S3 method for class 'BSpline_HRF'
penalty_matrix(x, order = 2, ...)

## S3 method for class 'Tent_HRF'
penalty_matrix(x, order = 2, ...)

## S3 method for class 'FIR_HRF'
penalty_matrix(x, order = 2, ...)

## S3 method for class 'SPMG2_HRF'
penalty_matrix(x, order = 2, shrink_deriv = 2, ...)

## S3 method for class 'SPMG3_HRF'
penalty_matrix(x, order = 2, shrink_deriv = 2, ...)

## S3 method for class 'Fourier_HRF'
penalty_matrix(x, order = 2, ...)

## S3 method for class 'Daguerre_HRF'
penalty_matrix(x, order = 2, ...)

Arguments

x

The HRF object or basis specification

...

Additional arguments passed to specific methods

order

Integer specifying the order of the penalty (default: 2)

shrink_deriv

Numeric; penalty weight for derivative terms in SPMG2/SPMG3 bases (default: 2)

Details

The penalty matrix R is used in regularized estimation as lambda * h^T R h, where h are the basis coefficients and lambda is the regularization parameter. Well-designed penalty matrices can significantly improve HRF estimation by encoding smoothness or other shape constraints.

Value

A symmetric positive definite penalty matrix of dimension nbasis(x) × nbasis(x)

See Also

[nbasis()], [HRF_objects]

Other hrf: HRF_objects, deriv()

Examples

# FIR basis with smoothness penalty
fir_hrf <- HRF_FIR
R_fir <- penalty_matrix(fir_hrf)

# B-spline basis with second-order smoothness
bspline_hrf <- HRF_BSPLINE  
R_bspline <- penalty_matrix(bspline_hrf, order = 2)

# SPM canonical with derivative shrinkage
spmg3_hrf <- HRF_SPMG3
R_spmg3 <- penalty_matrix(spmg3_hrf, shrink_deriv = 4)


Plot an HRF Object

Description

Plot an HRF Object

Usage

## S3 method for class 'HRF'
plot(x, ...)

Arguments

x

An HRF object

...

Additional arguments passed to plotting functions

Value

No return value, called for side effects (creates a plot)

Examples

# Plot an HRF
hrf <- HRF_SPMG1
plot(hrf)

Print method for Reg objects

Description

Provides a concise summary of the regressor object using the cli package.

Usage

## S3 method for class 'Reg'
print(x, ...)

## S3 method for class 'sampling_frame'
print(x, ...)

Arguments

x

A 'Reg' object.

...

Not used.

Value

No return value, called for side effects (prints to console)


Combine HRF Basis with Coefficients

Description

Create a new HRF by linearly weighting the basis functions of an existing HRF. This is useful for turning estimated basis coefficients into a single functional HRF.

S3 method for 'HRF' objects that returns a matrix mapping basis coefficients to sampled HRF values at the provided time grid. For single-basis HRFs, this returns a one-column matrix. For multi-basis HRFs (e.g., SPMG2/SPMG3, FIR, B-spline), this returns a matrix with one column per basis function.

Usage

reconstruction_matrix(hrf, sframe, ...)

## S3 method for class 'HRF'
reconstruction_matrix(hrf, sframe, ...)

Arguments

hrf

An object of class 'HRF'.

sframe

A numeric vector of times, or a 'sampling_frame' object from which times are extracted via 'samples()'.

...

Additional arguments passed to 'samples()' when 'sframe' is a 'sampling_frame', and to 'evaluate()' for HRF evaluation.

Details

Reconstruction matrix for an HRF basis

Returns a matrix \Phi that converts basis coefficients into a sampled HRF shape.

Value

A numeric matrix with one column per basis function.

A numeric matrix of dimension 'length(times) x nbasis(hrf)'.

Examples

# Create reconstruction matrix for basis functions
hrf <- HRF_SPMG2  # 2-basis HRF
times <- seq(0, 20, by = 0.5)
rmat <- reconstruction_matrix(hrf, times)
dim(rmat)  # Shows dimensions

Construct a Regressor Object

Description

Creates an object representing event-related regressors for fMRI modeling. This function defines event onsets and associates them with a hemodynamic response function (HRF) to generate predicted time courses.

Usage

regressor(
  onsets,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1,
  span = 40,
  summate = TRUE
)

Arguments

onsets

A numeric vector of event onset times in seconds.

hrf

The hemodynamic response function (HRF) to convolve with the events. This can be a pre-defined 'HRF' object (e.g., 'HRF_SPMG1'), a custom 'HRF' object created with 'as_hrf', a function 'f(t)', or a character string referring to a known HRF type (e.g., "spmg1", "gaussian"). Defaults to 'HRF_SPMG1'.

duration

A numeric scalar or vector specifying the duration of each event in seconds. If scalar, it's applied to all events. Defaults to 0 (impulse events).

amplitude

A numeric scalar or vector specifying the amplitude (scaling factor) for each event. If scalar, it's applied to all events. Defaults to 1.

span

The temporal window (in seconds) over which the HRF is defined or evaluated. This influences the length of the convolution. If not provided, it may be inferred from the 'hrf' object or default to 40s. **Note:** Unlike some previous versions, the 'span' is not automatically adjusted based on 'duration'; ensure the provided or inferred 'span' is sufficient for your longest event duration.

summate

Logical scalar; if 'TRUE' (default), the HRF response amplitude scales with the duration of sustained events (via internal convolution/summation). If 'FALSE', the response reflects the peak HRF reached during the event duration.

Details

This function serves as the main public interface for creating regressor objects. Internally, it utilizes the 'Reg()' constructor which performs validation and efficient storage. The resulting object can be evaluated at specific time points using the 'evaluate()' function.

Events with an amplitude of 0 are automatically filtered out.

Value

An S3 object of class 'Reg' and 'list' containing processed event information and the HRF specification. The object includes a 'filtered_all' attribute indicating whether all events were removed due to zero or 'NA' amplitudes.

Examples

# Create a simple regressor with 3 events
reg <- regressor(onsets = c(10, 30, 50), hrf = HRF_SPMG1)

# Regressor with durations and amplitudes
reg2 <- regressor(
  onsets = c(10, 30, 50),
  duration = c(2, 2, 2),
  amplitude = c(1, 1.5, 0.8),
  hrf = HRF_SPMG1
)

# Using different HRF types
reg_gamma <- regressor(onsets = c(10, 30), hrf = "gamma")

# Evaluate regressor at specific time points
times <- seq(0, 60, by = 0.1)
response <- evaluate(reg, times)

Build a Design Matrix from Block-wise Onsets

Description

'regressor_design' extends [regressor_set()] by allowing onsets to be specified relative to individual blocks and by directly returning the evaluated design matrix.

Usage

regressor_design(
  onsets,
  fac,
  block,
  sframe,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1,
  span = 40,
  precision = 0.33,
  method = c("conv", "fft", "Rconv", "loop"),
  sparse = FALSE,
  summate = TRUE
)

Arguments

onsets

Numeric vector of event onset times, expressed relative to the start of their corresponding block.

fac

A factor (or object coercible to a factor) indicating the condition for each onset.

block

Integer vector identifying the block for each onset. Values must be valid block indices for 'sframe'.

sframe

A [sampling_frame] describing the temporal structure of the experiment.

hrf

Hemodynamic response function shared by all conditions.

duration

Numeric scalar or vector of event durations.

amplitude

Numeric scalar or vector of event amplitudes.

span

Numeric scalar giving the HRF span in seconds.

precision

Numeric precision used during convolution.

method

Evaluation method passed to [evaluate()].

sparse

Logical; if 'TRUE' a sparse design matrix is returned.

summate

Logical; passed to [regressor()].

Value

A numeric matrix (or sparse matrix) with one column per factor level and one row per sample defined by 'sframe'.

Examples

# Create a sampling frame for 2 blocks, 100 scans each, TR=2
sframe <- sampling_frame(blocklens = c(100, 100), TR = 2)

# Events in block-relative time
onsets <- c(10, 30, 50, 20, 40, 60)
conditions <- factor(c("A", "B", "A", "B", "A", "B"))
blocks <- c(1, 1, 1, 2, 2, 2)

# Build design matrix
design <- regressor_design(
  onsets = onsets,
  fac = conditions,
  block = blocks,
  sframe = sframe,
  hrf = HRF_SPMG1
)

# Design matrix has 200 rows (total scans) and 2 columns (conditions)
dim(design)

Construct a Regressor Set

Description

Creates a set of regressors, one for each level of a factor. Each condition shares the same HRF and other parameters but has distinct onsets, durations and amplitudes.

Usage

regressor_set(
  onsets,
  fac,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1,
  span = 40,
  summate = TRUE
)

## S3 method for class 'RegSet'
evaluate(
  x,
  grid,
  precision = 0.33,
  method = c("conv", "fft", "Rconv", "loop"),
  sparse = FALSE,
  ...
)

Arguments

onsets

Numeric vector of event onset times.

fac

A factor (or object coercible to a factor) indicating the condition for each onset.

hrf

Hemodynamic response function used for all conditions.

duration

Numeric scalar or vector of event durations.

amplitude

Numeric scalar or vector of event amplitudes.

span

Numeric scalar giving the HRF span in seconds.

summate

Logical; passed to [regressor()].

x

A RegSet object

grid

Numeric vector of time points at which to evaluate

precision

Numeric precision for evaluation

method

Evaluation method

sparse

Logical whether to return sparse matrix

...

Additional arguments passed to evaluate

Value

An object of class 'RegSet' containing one 'Reg' per factor level.

Examples

# Create events for 3 conditions
onsets <- c(10, 20, 30, 40, 50, 60)
conditions <- factor(c("A", "B", "C", "A", "B", "C"))

# Create regressor set
rset <- regressor_set(onsets, conditions, hrf = HRF_SPMG1)

# With durations and amplitudes
rset2 <- regressor_set(
  onsets = onsets,
  fac = conditions,
  duration = 2,
  amplitude = c(1, 1.5, 0.8, 1, 1.5, 0.8),
  hrf = HRF_SPMG1
)

# Evaluate the regressor set
times <- seq(0, 80, by = 0.1)
design_matrix <- evaluate(rset, times)

Get sample acquisition times

Description

Generic function retrieving sampling times from a sampling frame or related object.

Usage

samples(x, ...)

## S3 method for class 'sampling_frame'
samples(x, blockids = NULL, global = FALSE, ...)

Arguments

x

Object describing the sampling grid

...

Additional arguments passed to methods

blockids

Integer vector of block identifiers to include (default: all blocks)

global

Logical indicating whether to return global times (default: FALSE)

Value

Numeric vector of sample times

Examples

# Get sample times from a sampling frame
sframe <- sampling_frame(blocklens = c(100, 120), TR = 2)
samples(sframe, blockids = 1)  # First block only
samples(sframe, global = TRUE)  # All blocks, global timing

A sampling_frame describes the block structure and temporal sampling of an fMRI paradigm.

Description

A sampling_frame describes the block structure and temporal sampling of an fMRI paradigm.

Usage

sampling_frame(blocklens, TR, start_time = TR/2, precision = 0.1)

Arguments

blocklens

A numeric vector representing the number of scans in each block.

TR

A numeric value or vector representing the repetition time in seconds (i.e., the spacing between consecutive image acquisitions). When a vector is provided, its length must be 1 or equal to the number of blocks.

start_time

A numeric value or vector representing the offset of the first scan of each block (default is TR/2). When a vector is provided, its length must be 1 or equal to the number of blocks.

precision

A numeric value representing the discrete sampling interval used for convolution with the hemodynamic response function (default is 0.1).

Value

A list with class "sampling_frame" describing the block structure and temporal sampling of an fMRI paradigm.

Examples

frame <- sampling_frame(blocklens = c(100, 100, 100), TR = 2, precision = 0.5)

# The relative time (with respect to the last block) in seconds of each sample/acquisition
sam <- samples(frame)
# The global time (with respect to the first block) of each sample/acquisition
gsam <- samples(frame, global = TRUE)

# Block identifiers for each acquisition can be retrieved using
# blockids(frame)


Shift a time series object

Description

Apply a temporal shift to a time series object. This function shifts the values in time while preserving the structure of the object. Common uses include:

alignment

Aligning regressors with different temporal offsets

derivatives

Applying temporal derivatives to time series

correction

Correcting for timing differences between signals

Usage

shift(x, ...)

## S3 method for class 'Reg'
shift(x, shift_amount, ...)

Arguments

x

An object representing a time series or a time-based data structure

...

Additional arguments passed to methods

shift_amount

Numeric; amount to shift by (positive = forward, negative = backward)

Value

An object of the same class as the input, with values shifted in time:

Values

Values are moved by the specified offset

Structure

Object structure and dimensions are preserved

Padding

Empty regions are filled with padding value

See Also

[regressor()], [evaluate()]

Examples

# Create a simple time series with events
event_data <- data.frame(
  onsets = c(1, 10, 20, 30),
  run = c(1, 1, 1, 1)
)

# Create regressor from events
reg <- regressor(
  onsets = event_data$onsets,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1
)

# Shift regressor forward by 2 seconds
reg_forward <- shift(reg, shift_amount = 2)

# Shift regressor backward by 1 second
reg_backward <- shift(reg, shift_amount = -1)

# Evaluate original and shifted regressors
times <- seq(0, 50, by = 2)
orig_values <- evaluate(reg, times)
shifted_values <- evaluate(reg_forward, times)

Create a single trial regressor

Description

Creates a regressor object for modeling a single trial event in an fMRI experiment. This is particularly useful for trial-wise analyses where each trial needs to be modeled separately. The regressor represents the predicted BOLD response for a single event using a specified hemodynamic response function (HRF).

Usage

single_trial_regressor(
  onsets,
  hrf = HRF_SPMG1,
  duration = 0,
  amplitude = 1,
  span = 24
)

Arguments

onsets

the event onset in seconds, must be of length 1.

hrf

a hemodynamic response function, e.g. HRF_SPMG1

duration

duration of the event (default is 0), must be length 1.

amplitude

scaling vector (default is 1), must be length 1.

span

the temporal window of the impulse response function (default is 24).

Details

This is a convenience wrapper around 'regressor' that ensures inputs have length 1.

Value

A 'Reg' object (inheriting from 'regressor' and 'list').

See Also

regressor

Examples

# Create single trial regressor at 10 seconds
str1 <- single_trial_regressor(onsets = 10, hrf = HRF_SPMG1)

# Single trial with duration and custom amplitude
str2 <- single_trial_regressor(
  onsets = 15,
  duration = 3,
  amplitude = 2,
  hrf = HRF_SPMG1
)

# Evaluate the response
times <- seq(0, 40, by = 0.1)
response <- evaluate(str1, times)

mirror server hosted at Truenetwork, Russian Federation.