segment_volume_tissue_gmm for prior-guided tissue segmentation of a 3D volume with a Gaussian mixture model, optional spatial prior probability maps (for example template tissue priors warped into the subject space) and a mean-field Markov random field; a native re-implementation of the ANTs Atropos algorithm (Avants and colleagues, 2011) with its default Socrates posterior formulation (posterior proportional to s_k^w * (likelihood * MRF)^(1 - w), the priors re-weighted by the mixture proportions), so prior_weight has the meaning of the priorweight of ANTs; the defaults reproduce ANTsPy atropos(i = 'Kmeans[3]', m = '[0.2,1x1x1]', c = '[5,0]', priorweight = 0.25)segment_volume_tissue_gmm restricts all computation to the mask (memory of order K * N_mask), runs the E-step in parallel with results that are identical for any thread count, propagates the vox2ras attribute (which also sets the physical neighbor distances of the MRF), stops with the convergence rule of Atropos (the iterations end as soon as the mean maximum posterior over the mask changes by less than tolerance, so the default tolerance = 0 stops at the first decrease, like c = [n,0] in ANTs) and returns the integer segmentation, the per-class posteriors, the class means, standard deviations and proportions, and the convergence trace; the remaining difference from Atropos is the mean-field MRF (neighbors' posteriors instead of hard labels)bias_correction_n4 to correct the intensity non-uniformity (bias field) of a 3D volume: a native re-implementation of the N4 algorithm (Tustison and colleagues, 2010) wrapped like the abp_n4 function of ANTsPy, with histogram-quantile intensity truncation, multi-resolution B-spline fitting with histogram sharpening, an optional mask or per-voxel weight mask, intensity rescaling and a return_bias_field switch; the defaults reproduce abp_n4 of ANTsPy 0.6.3 (its truncation rule, the whole image as mask and one spline span per axis; log-bias correlation 0.996 and corrected-image correlation 0.9995 against ants.abp_n4 on a toy phantom), while mask = "auto" with spline_distance = 200 gives the older abpN4 recipe of ANTsR and ANTsPy 0.3 (an automatic head mask and a 200-millimeter spline distance); out-of-range spline distances stop with an explanation, results are identical for any thread count, and no external dependency is neededapply_transform3d_volume to resample a 3D volume (or each frame of a 4D stack) through a register_volume3d result or through an ANTs-style list of affine matrices, displacement fields and transform files in antsApplyTransforms order, with trilinear or nearest-neighbor interpolation; every voxel is streamed through the composite transform in C++ without materializing a composite fieldapply_transform3d_points to map RAS coordinates (such as electrode contacts or surface vertices) through the same registration objects and transform lists; with a registration object, direction = "forward" maps from source to target space for volumes and points alike ("inverse" the reverse), while a transform list follows antsApplyTransforms and antsApplyTransformsToPoints, where the same list resamples an image from moving to fixed space but carries a point from fixed to moving spaceapply_transform3d is superseded by apply_transform3d_volume and apply_transform3d_points; it is kept unchanged (no warning), and ravetools no longer calls it internallyregister_volume3d (SyN) returning inverse_field as the negated forward_field, which is only a first-order inverse; the inverse is now computed from the final forward field by damped fixed-point inversion (Chen and colleagues, 2008; at most 20 sweeps, as in ANTs), so forward and inverse compose to the identity within a small fraction of a voxel wherever the forward map is one-to-one inside the target grid (border voxels of an unmasked registration can fold and stay approximate); transform, image, images and forward_field are unchangedregister_volume3d gains syn_grad_step, syn_total_sigma and syn_cc_radius to control the deformable stage (passing the defaults explicitly gives results identical to omitting them); the documentation describes the ANTs-like T1-to-template preset (syn_cc_radius = 4, syn_grad_step = 0.15, syn_sigma = 3.5) and the metric choice for same-contrast versus cross-contrast pairsregister_volume3d results record the source grid dimension (geometry$source_dim), which save_registration writes as SourceDim in the manifest and load_registration reads back; older manifests without it still loadvcg_smooth_implicit crashing R with a segmentation fault on large meshes, such as a whole-brain surface with about 3 million vertices at degree = 2: the bundled VCG smoother factorized one sparse system with three rows per vertex, whose Cholesky factor needed more entries than the 32-bit indices of Eigen can address, so the factor was never allocated and the factorization wrote through a null pointer. The smoother now solves one system per coordinate in double precision, by conjugate gradients for degree 1 and 2 (memory linear in the mesh size) and by a sparse factorization for higher degrees; results differ from earlier versions by the single-precision round-off of the old solver (below 0.01 millimeters on typical atlas surfaces, more at degree = 3)vcg_smooth_implicit estimates the memory the solve needs before allocating it, and stops with an explanation when the estimate exceeds the new argument max_memory (2 GiB by default)vcg_smooth_implicit(fix_border = TRUE) having no effect; border vertices now keep exactly their input positionsvcg_smooth_implicit(use_mass_matrix = FALSE) collapsing every vertex to the origin; without the mass matrix the fixed border vertices alone now determine the surface, and a mesh with a connected part that has nothing fixed raises an errorvcg_decimate to simplify triangular meshes by quadric edge collapse, adapted from Rvcgvcg_fix_defects compacting the mesh containers while face-to-face adjacency still referenced deleted faces; the VCG compactor remaps such links through a table whose deleted-face entries are size_t(-1), so it computed an out-of-range pointer and stored a stray adjacency link, which clang-UBSAN reported as a pointer overflow. Topology is now rebuilt before compactingvcg_mesh_volume leaking three per-process face bit flags on every call inside the bundled VCG library, which clang-UBSAN reported as a left shift of a negative value; after four calls in one session the bit allocator overran the sign bit, and the reported non-manifold edge count was silently inflatedvalgrind reported as a conditional jump depending on uninitialized values while subdividing edges; normals are now zeroed on loadC++11 tool-chains (such as the conda-forge builds) with recent clang, where converting an Rcpp::Nullable argument to Rcpp::NumericVector or Rcpp::NumericMatrix was ambiguous; the SEXP accessor is now called explicitlyvcg_smooth_implicit returning a completely corrupted mesh (all zeros or NaN, varying between runs) whenever the input contained vertices belonging to no face; such vertices make the implicit linear system singular, and are now excluded from the solve and returned at their input positions, consistent with vcg_smooth_explicitvcg_detect_collision to detect exact collisions and proximity within a distance tolerance between two geometries, where each side may be a point cloud, a chain of connected line segments (such as diffusion streamlines, delimited by NA rows), or a triangular mesh; optionally counts geometry enclosed by a closed surfacecolor_ramp_continuous helper to create a vectorized color-mapping function from a palette and a numeric domainmake_error to properly protect the error class string from garbage collection, preventing class names from being silently lost in nested error callsdesign_filter against bandstop configurations where automatically derived transition bandwidths overlap each other, producing unordered frequency breakpointsmris_curvature to estimate per-vertex mean, Gaussian, and principal curvatures by fitting an osculating quadratic surface to each vertex's two-ring neighborhoodmris_smooth to smooth a triangular surface mesh via iterative Laplacian or Taubin smoothingmris_inflate to inflate a cortical surface mesh by iteratively smoothing and expanding toward a sphere while preserving total surface areamris_sphere to project an inflated cortical surface onto a sphere and relax metric distortion via area-preserving gradient descentmris_remesh to re-mesh a triangular surface to uniform edge length using the Botsch and Kobbelt (2004) isotropic re-meshing algorithmmris_make_surfaces to localize white-matter and pial surfaces from an intensity volumevcg_average_edge_length and vcg_max_edge_length to query edge-length statistics of a meshvcg_count_edge_defects to count non-manifold edge defects in a meshvcg_fix_defects to repair mesh topology defects via VCGvcg_subdivide_max_edge_length to subdivide only edges that exceed a specified length, avoiding global super-sampling and improving Dijkstra path qualityvcg_mesh_patch to extract a geodesic patch of a mesh bounded by a closed curve of user-supplied waypoint verticesmesh3d objects returned by ravetools now carry the ravetools_mesh3d class, enabling a plot() generic that dispatches automatically to plot_mesh_polygon or plot_mesh_dotcloudregister_volume3d (SyN mode) re-implemented from the ANTs paper in pure Rcpp/RcppEigen; no longer depends on RNiftyReg or any external registration libraryregister_volume3d gains a points argument to additionally warp a matrix of anatomical coordinates (e.g. cortical surface vertices) through the estimated transform, enabling direct cortical mapping without a separate resampling stepapply_transform3d to apply a previously estimated rigid, affine, or SyN transform to a new 3D volumeregister_volume3d now returns an object of class ravetools_register_volume3d (carrying the grid geometry and a vox2ras attribute on each deformation field) with a print methodwrite_ants_transform/read_ants_transform to read and write the linear transform as an ITK affine .mat file (a MATLAB level-4 binary in LPS convention) compatible with antsApplyTransforms; implemented in base R with no new dependencywrite_ants_warp/read_ants_warp to read and write the deformation field as an ANTs 5-D warp NIfTI (LPS displacement vectors, vector intent code) via the suggested freesurferformats package; the RAS affine can optionally be hidden in the header text fields for single-file recoveryras_lps_conjugate to convert a 4x4 transform between the RAS and LPS conventionssave_registration/load_registration to write a registration result to (or read it from) ANTs-style files plus a dependency-free manifestplot_mesh_dotcloud for rendering one or more mesh3d objects as an orthographic rim-lit dot cloud in base R (no rgl dependency); supports per-vertex colors, depth-gradient palettes, per-mesh alpha, side filtering, and painter's-algorithm depth sorting across multiple meshesplot_mesh_polygon for rendering one or more mesh3d objects as flat-shaded Lambert-lit triangles in base R; point-cloud meshes (no face matrix) are automatically substituted by small sphere instances; supports camera-facing clipping (mesh_clipping), side filtering, per-mesh alpha blending, and configurable shadow_color, light_intensity, and ambient_intensityplot_mesh_dotcloud and plot_mesh_polygon gain a clipping_plane argument (a 4-element numeric normal-and-offset vector, or a list of such vectors) to discard geometry on one side of arbitrary planes before rendering, and a per-mesh clipping_plane_enabled logical toggle to opt individual meshes in or out of clippingensure_mesh3d for coercing various surface formats (mesh3d, ieegio_surface, fs.surface, surf.asc) to a canonical mesh3d object; previously internal-onlyfreqz2 plot legend: the cutoff legend used the raw cutoffs argument (and could index past the color palette, yielding NA colors) when a requested cutoff did not actually intersect the magnitude curve; the legend now only lists cutoffs that are drawn, and labels the unit as dB instead of the filter's frequency unitmorlet_wavelet gains a segment_length argument (default NULL) that processes long signals (e.g. multi-hour recordings) in overlapping segments using batched mvfftw_c2c convolutions, dramatically reducing peak memory and FFT cost while preserving the legacy result on the signal interiorbaseline_array now supports seven baseline methods: "percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore", and "subtract_mean"; newly added methods include decibel z-score normalizationHaar wavelet feature extractionwavelets package dependency with waveslim for discrete wavelet transform used in spike sorting utilitiesproject_plane gains an n_iters argument to control the number of projection iterations (default is 5)carla implementing the Common Average Re-referencing by Least Anti-Correlation (CARLA) algorithm (see CITATION) for selecting an optimal subset of channels as the common average reference in CCEP datacrp implementing the Canonical Response Parameterization (CRP) method for characterizing single-trial evoked responses (e.g. CCEPs): estimates response duration, extracts the canonical response shape, and reports per-trial weights, SNR, and explained variance; additionally reports a canonical shape (C_full) spanning the entire loaded time range (including the baseline period), and gains an optional reverse-scan response-onset estimator (detect_onset, with an onset_search_start floor) that locates the response start time for delayed responses - even before the analysis window - while keeping the per-trial weights unchanged; non-finite time points are dropped automatically and the analysis window is clamped into the available time rangeFFTW3 wrappers (fftw_r2c, fftw_c2r, fftw_c2c, mvfftw_r2c, mvfftw_c2c, mvfftw_c2r, and their 2D/3D variants) with memory bugs fixed; these are thin bindings for advanced users requiring maximum throughputdesign_filter_fir band-pass scaling reference frequency to use the average of the transition-band midpoints (matching MATLAB fir1/scale_filter), and fixed band-stop scaling to always normalize at DC; previously both could produce incorrect gain for asymmetric transition bandsfiltfilt now accepts a Sos (second-order sections) object from gsignal and delegates to gsignal::filtfilt in that casecatmull_rom_3d for smooth Catmull-Rom spline interpolation through 3D point sequences, including closest-point projection from an arbitrary 3D point onto the curveqfac handling in the matrix to quaternion conversion so that right-handed transforms (negative determinant) are correctly representedfir1 filter computation is significantly faster via an optimized internal implementationfind_peaks to provide finding peaks along a trace of signalgammatone_fast filters to obtain the audio envelope at different frequenciesvcg_subset_certex to subset meshvcg_subdivision to up-sample meshclang20 warning and removed problematic vcglib code that use pointers after free.std::nearbyint instead std::round to round numbers to comply to IEC-60559 standard that half numbers round to nearest even integers3D volume sampling in C++: resample_3d_volumegsignal::resample (however, some edits might be needed in the future to produce the same results as Matlab)ieegio surface geometries to mesh3d to be used in VCG related functionsK-D tree search to find closest points among two point cloudsvcg_raycaster to find intersection of rays and given mesh object.vctrs to Suggests to fix the issue that fails the unit test due to an update in testthat package.design_filter ensures frequency window cuts off within 0 to Nyquistfftfilt allows matrix inputfiltfilt with a=1 (FIR filter) calls fftfilt to speed uppwelch incorrect power calculation. The results agrees mostly with Matlab functionhamming window as the default in pwelch; exported additional window options such as blackman families, bohmanwin, flattopwin, and hanningc++ template issue caused by vcglib, which fails to compile under clang19decimate agrees with Matlab now (both fir and iir filters)freqz2 to obtain the frequency response of a digital filter (similar to gsignal::freqz but with more accurate cutoff frequency calculation and more customize plots)diagnose_filtercheck_filter to obtain expected magnitude at given frequency and reciprocal condition numbersignal and use gsignal insteaddesign_filter for both fir and iir filters, allowing both entry and intermediate users to design band-pass/stop, low/high pass filters easily.iir filter order generated from design_filter will be checked against rcond_filter_ar (reciprocal condition number) to make improve the numeric stabilitydijkstra; the package passed asan, valgrind test provided by rhub2dijkstra method occasionally causing memory error. New method is much faster now.plot.pwelch not displaying the signal names correctly.c++17 requirement and supports 11, 14, and 17 standardsFIR1 filterpwelch throwing warnings when signal is zero (or zero power)dijkstra to find shortest paths in meshvcglibC++ template issue via type explicit callsfir1 filter when band-passing signals with incorrect npwelch plot works with zero power now; mv_pwelch plot error fixedband_pass2 to avoid NA generated when upper band frequency is NyquistVector3, Matrix4, Quaternion for in-place calculationWASMCRAN: "format string is not a string literal (potentially insecure)"filearraygrow_volumemesh_from_volume no longer throw errors if the mesh does not form a manifoldfill_surface to fill in volume based on given surface meshmesh_from_volume to generate mesh from volume. This function can be used together with fill_surface to generate surface enveloperegister_volume to align two imaging data using linear or non-linear registrationfftw on 2D image and 3D volume data1D, 2D, 3D data using FFTpwelch frequency not starting from zero issueTinyThread using the latest pull-request to RcppParallelinterpolate_stimulation to detect stimulation signals within the response and interpolate with smooth signalssplinesfast_quantile and fast_mvquantile to improve the quantile/median calculation speedplot_signals plotting range too large when signals have large values (such as stimulation)TinyThreads library memory leak issuesdiagnose_channel, avoid duplicated pwelch calculationfilter, filtfilt that produce the same results as Matlab (with precision error)pwelch as a row-major matrix to speed up calculationwavelet_cycles_suggest to provide default calculation of wavelet cyclessignature to wavelet to resolve potential cache conflicts when running in multiple processes. (This allows RAVE to run wavelet on multiple subjects at the same time)pwelchpwelch sampling frequency to be greater than the signal lengthpwelch plot to properly handle graph text, margin, axisplot_signals to plot multiple functional data within the same canvasC++ code to inst/includes so other users can dynamically link to the functions (https://github.com/dipterix/ravetools/issues/5)fftw related codefftw plans to respect the flagsC++ to convert raw binary bytes to uint, int, float, and stringParallel processes might use different temporary directory paths. To improve the performance, it is recommended to set a shared temporary directory, hence this version
RAVETOOLS_TEMPDIR or option ravetools.tempdir.This version fixes a memory issue reported by CRAN check (gcc-UBSAN).
NA_INTEGER is subtracted by one before being converted to R_xlen_t type. This update fixes this issueRcppParallel and copied part of it into inst/include folder, with TBB removed under the GPL-3 license framework.This is an initial version of ravetools. Although a bare minimal set of signal processing functions are provided, it is sufficient to perform preprocess pipelines on most iEEG signals. Some functions are added from the dipsaus package, with considerable performance improvement. The C++ functions have been tested on all major platforms, with different architectures (ARM, i386, x64).
README file to demonstrate basic usageNEWS.md file to track changes to the package.decimate with FIR filters creating the same results as in Matlabdetrend function todiagnose_channel to visually inspect channel signalsmorlet_wavelet to enable fast and memory efficient wavelet decomposition; the result agrees with existing Matlab code with floating errors (10^-7)multitaperpwelch (Welch periodogram)notch_filter to remove line noiseThe following functions are implemented in C++ parallel. They tend to be faster than normal base-R implementations, depending on the number of CPU cores used.
collapse to collapse arraysshift_array to shift array along certain indicesfast_cov to calculate pearson covariance matrix in parallelbaseline_array to calculate baseline arrays with multiple margins