| Title: | Core File Structures and Workflows for 'RAVE' |
|---|---|
| Description: | Defines storage standard for Read, process, and analyze intracranial electroencephalography and deep-brain stimulation in 'RAVE', a reproducible framework for analysis and visualization of iEEG by Magnotti, Wang, and Beauchamp, (2020, <doi:10.1016/j.neuroimage.2020.117341>). Supports brain imaging data structure (BIDS) <https://bids.neuroimaging.io> and native file structure to ingest signals from 'Matlab' data files, hierarchical data format 5 (HDF5), European data format (EDF), BrainVision core data format (BVCDF), or BlackRock Microsystem (NEV/NSx); process images in Neuroimaging informatics technology initiative (NIfTI) and 'FreeSurfer' formats, providing brain imaging normalization to template brain, facilitating 'threeBrain' package for comprehensive electrode localization via 'YAEL' (your advanced electrode localizer) by Wang, Magnotti, Zhang, and Beauchamp (2023, <doi:10.1523/ENEURO.0328-23.2023>). |
| Authors: | Zhengjia Wang [aut, cre] (ORCID: <https://orcid.org/0000-0001-5629-1116>), Xiang Zhang [aut], John Magnotti [aut], Michael Beauchamp [aut], Trustees of the University of Pennsylvania [cph] (All files in this package unless explicitly stated in the file) |
| Maintainer: | Zhengjia Wang <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1.23 |
| Built: | 2026-10-23 13:59:58 UTC |
| Source: | https://github.com/rave-ieeg/ravecore |
Archive and share a subject
archive_subject( subject, path, includes = c("orignal_signals", "processed_data", "rave_imaging", "pipelines", "notes", "user_generated"), config = list(), work_path = NULL, zip_flags = NULL )archive_subject( subject, path, includes = c("orignal_signals", "processed_data", "rave_imaging", "pipelines", "notes", "user_generated"), config = list(), work_path = NULL, zip_flags = NULL )
subject |
'RAVE' subject to archive |
path |
path to a zip file to store; if missing or empty, then the path will be automatically created |
includes |
data to include in the archive; default includes all ( original raw signals, processed signals, imaging files, stored pipelines, notes, and user-generated exports) |
config |
a list of configurations, including changing subject code, project name, or to exclude cache data; see examples |
work_path |
temporary working path where files are copied; default is temporary path. Set this variable explicitly when temporary path is on external drives (for example, users have limited storage on local drives and cannot hold the entire subject) |
zip_flags |
|
## Not run: # Basic usage path <- archive_subject('demo/DemoSubject') # clean up unlink(path) # Advanced usage: include all the original signals # and processed data, no cache data, re-name to # demo/DemoSubjectLite path <- archive_subject( 'demo/DemoSubject', includes = c("orignal_signals", "processed_data"), config = list( rename = list( project_name = "demo", subject_code = "DemoSubjectLite" ), orignal_signals = list( # include all raw signals include_all = TRUE ), processed_data = list( include_cache = FALSE ) ) ) # Clean up temporary zip file unlink(path) ## End(Not run)## Not run: # Basic usage path <- archive_subject('demo/DemoSubject') # clean up unlink(path) # Advanced usage: include all the original signals # and processed data, no cache data, re-name to # demo/DemoSubjectLite path <- archive_subject( 'demo/DemoSubject', includes = c("orignal_signals", "processed_data"), config = list( rename = list( project_name = "demo", subject_code = "DemoSubjectLite" ), orignal_signals = list( # include all raw signals include_all = TRUE ), processed_data = list( include_cache = FALSE ) ) ) # Clean up temporary zip file unlink(path) ## End(Not run)
RAVEProject instanceConvert character to RAVEProject instance
as_rave_project(x, ...) ## S3 method for class 'character' as_rave_project(x, strict = TRUE, parent_path = NULL, ...)as_rave_project(x, ...) ## S3 method for class 'character' as_rave_project(x, strict = TRUE, parent_path = NULL, ...)
x |
R object that can be converted to 'RAVE' project. When |
... |
passed to other methods, typically includes |
strict |
whether to check project path; if set to true and the project path is missing, the program will raise warnings |
parent_path |
parent path in which the project is non-default, can be
a path to the parent folder of the project, or a
|
A 'RAVE' project is an aggregation of subjects with the similar research
targets. For example, 'RAVE' comes with a demo subject set, and the project
'demo' contains eight subjects undergoing same experiments. Project
'YAEL' contains subject whose electrodes are localized by
'YAEL' modules.
The project can be "arbitrary": this is different to a 'BIDS' "project",
often served as a data-set name or identifier. A 'BIDS' project may have
multiple 'RAVE' projects. For example, an audio-visual 'BIDS' data may have
a 'RAVE' project 'McGurk' to study the 'McGurk' effect and
another 'synchrony' to study the audio-visual synchronization.
A valid 'RAVE' project name must only contain letters and digits;
underscores and dashes may be acceptable but might subject to future change.
For example 'demo' is a valid project name, but 'my demo' is
invalid.
RAVE supports storing the data in 'native' or 'bids'-compliant
formats. The native format is compatible with the 'RAVE' 1.0 and 2.0, and
requires no conversion to 'BIDS' format, while 'bids' requires the
data to be stored and processed in 'BIDS'-complaint format, which is better
for data sharing and migration, but might be over-kill in some cases.
If the project string contains '@', the characters after the 'at'
sign will be interpreted as indication of the storage format. For instance
'demo@native' or 'demo@bids:ds0001' are interpreted
differently. The previous one indicates that the project 'demo' is
stored with native format, usually located at 'rave_data/data_dir'
under the home directory (can be manually set to other locations). The
latter one means the 'RAVE' project 'demo' is stored under 'BIDS'
folder with a 'BIDS' data-set name 'ds0001'.
A RAVEProject instance
# ---- Native format (RAVE legacy) ------------------------ project <- as_rave_project("demo", strict = FALSE) format(project) project$path project$subjects() # Non-standard project locations (native format) as_rave_project("demo", strict = FALSE, parent_path = "~/Downloads") # ---- BIDS format ---------------------------------------- project <- as_rave_project("demo@bids:ds001", strict = FALSE) format(project) project$path # BIDS format, given the parent folder; this example requires # 'bidsr' sample data. Run `bidsr::download_bids_examples()` first. examples <- bidsr::download_bids_examples(test = TRUE) if(!isFALSE(examples)) { project <- as_rave_project( "audiovisual@bids", strict = FALSE, parent_path = file.path(examples, "ieeg_epilepsy_ecog")) # RAVE processed data is under BIDS derivative folder project$path # "audiovisual@bids:ieeg_epilepsy_ecog" format(project) }# ---- Native format (RAVE legacy) ------------------------ project <- as_rave_project("demo", strict = FALSE) format(project) project$path project$subjects() # Non-standard project locations (native format) as_rave_project("demo", strict = FALSE, parent_path = "~/Downloads") # ---- BIDS format ---------------------------------------- project <- as_rave_project("demo@bids:ds001", strict = FALSE) format(project) project$path # BIDS format, given the parent folder; this example requires # 'bidsr' sample data. Run `bidsr::download_bids_examples()` first. examples <- bidsr::download_bids_examples(test = TRUE) if(!isFALSE(examples)) { project <- as_rave_project( "audiovisual@bids", strict = FALSE, parent_path = file.path(examples, "ieeg_epilepsy_ecog")) # RAVE processed data is under BIDS derivative folder project$path # "audiovisual@bids:ieeg_epilepsy_ecog" format(project) }
Image registration across different modals. Normalize brain 'T1'-weighted
'MRI' to template brain and generate subject-level atlas files. See
cmd_run_yael_preprocess to see how to run a built-in workflow
as_yael_process(subject, ..., engine = c("rpyANTs", "native"))as_yael_process(subject, ..., engine = c("rpyANTs", "native"))
subject |
character (subject code, or project name with subject code),
or |
... |
internally used |
engine |
which implementation to use: |
A processing instance, see YAELProcess and
YAELNativeProcess
process <- as_yael_process("YAEL/test_subject") # the same process without 'Python' process_native <- as_yael_process("YAEL/test_subject", engine = "native") ## Not run: # Import and set original T1w MRI and CT process$set_input_image("/path/to/T1w_MRI.nii", type = "T1w") process$set_input_image("/path/to/CT.nii.gz", type = "CT") # Co-register CT to MRI process$register_to_T1w(image_type = "CT") # Morph T1w MRI to 0.5 mm^3 MNI152 template process$map_to_template( template_name = "mni_icbm152_nlin_asym_09b", native_type = "T1w" ) ## End(Not run)process <- as_yael_process("YAEL/test_subject") # the same process without 'Python' process_native <- as_yael_process("YAEL/test_subject", engine = "native") ## Not run: # Import and set original T1w MRI and CT process$set_input_image("/path/to/T1w_MRI.nii", type = "T1w") process$set_input_image("/path/to/CT.nii.gz", type = "CT") # Co-register CT to MRI process$register_to_T1w(image_type = "CT") # Morph T1w MRI to 0.5 mm^3 MNI152 template process$map_to_template( template_name = "mni_icbm152_nlin_asym_09b", native_type = "T1w" ) ## End(Not run)
Class definition for auxiliary channels
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> Auxiliary_electrode
h5_fname'HDF5' file name
validwhether current electrode is valid: subject exists and contains current electrode or reference; subject electrode type matches with current electrode type
raw_sample_ratevoltage sample rate
preprocess_infopreprocess information
voltage_filepath to voltage 'HDF5' file
Auxiliary_electrode$@marshal()Internal method
Auxiliary_electrode$@marshal(...)
...internal arguments
Auxiliary_electrode$@unmarshal()Internal method
Auxiliary_electrode$@unmarshal(object)
object, ...internal arguments
Auxiliary_electrode$print()print electrode summary
Auxiliary_electrode$print()
Auxiliary_electrode$set_reference()set reference for current electrode
Auxiliary_electrode$set_reference(reference)
referenceeither NULL or LFP_electrode instance
Auxiliary_electrode$new()constructor
Auxiliary_electrode$new(subject, number, quiet = FALSE)
subject, number, quietsee constructor in
RAVEAbstarctElectrode
Auxiliary_electrode$.load_noref_voltage()load non-referenced voltage (internally used)
Auxiliary_electrode$.load_noref_voltage(reload = FALSE)
reloadwhether to reload cache
sratevoltage signal sample rate
Auxiliary_electrode$.load_raw_voltage()load raw voltage (no process)
Auxiliary_electrode$.load_raw_voltage(reload = FALSE)
reloadwhether to reload cache
Auxiliary_electrode$load_data_with_epochs()method to load electrode data
Auxiliary_electrode$load_data_with_epochs(type = c("raw-voltage", "voltage"))
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient", and
"raw-voltage". For "power", "phase",
and "wavelet-coefficient", 'Wavelet' transforms are required.
For "voltage", 'Notch' filters must be applied. All these
types except for "raw-voltage" will be referenced.
For "raw-voltage", no reference will be performed since the data
will be the "raw" signal (no processing).
Auxiliary_electrode$load_dimnames_with_epochs()get expected dimension names
Auxiliary_electrode$load_dimnames_with_epochs(
type = c("raw-voltage", "voltage")
)
typesee load_data_with_epochs
Auxiliary_electrode$load_data_with_blocks()load electrode block-wise data (with no reference), useful when epoch is absent
Auxiliary_electrode$load_data_with_blocks(
blocks,
type = c("raw-voltage", "voltage"),
simplify = TRUE
)
blockssession blocks
typedata type such as "power", "phase",
"voltage", "raw-voltage" (with no filters applied, as-is
from imported), "wavelet-coefficient". Note that if type
is "raw-voltage", then the data only needs to be imported;
for "voltage" data, 'Notch' filters must be applied; for
all other types, 'Wavelet' transforms are required.
simplifywhether to simplify the result
If simplify is enabled, and only one block is loaded,
then the result will be a vector (type="voltage") or a matrix
(others), otherwise the result will be a named list where the names
are the blocks.
Auxiliary_electrode$load_dim_with_blocks()get expected dimension information for block-based loader
Auxiliary_electrode$load_dim_with_blocks(
blocks,
type = c("raw-voltage", "voltage")
)
blocks, typesee load_data_with_blocks
Auxiliary_electrode$clear_cache()method to clear cache on hard drive
Auxiliary_electrode$clear_cache(...)
...ignored
Auxiliary_electrode$clear_memory()method to clear memory
Auxiliary_electrode$clear_memory(...)
...ignored
Auxiliary_electrode$clone()The objects of this class are cloneable with this method.
Auxiliary_electrode$clone(deep = FALSE)
deepWhether to make a deep clone.
Back up and rename the file or directory
backup_file(path, remove = FALSE, quiet = FALSE)backup_file(path, remove = FALSE, quiet = FALSE)
path |
path to a file or a directory |
remove |
whether to remove the original path; default is false |
quiet |
whether not to verbose the messages; default is false |
FALSE if nothing to back up, or the back-up path
if path exists
path <- tempfile() file.create(path) path2 <- backup_file(path, remove = TRUE) file.exists(c(path, path2)) unlink(path2)path <- tempfile() file.create(path) path2 <- backup_file(path, remove = TRUE) file.exists(c(path, path2)) unlink(path2)
Manipulate cached data on the file systems
cache_root(check = FALSE) clear_cached_files(subject_code, quiet = FALSE)cache_root(check = FALSE) clear_cached_files(subject_code, quiet = FALSE)
check |
whether to ensure the cache root path |
subject_code |
subject code to remove; default is missing. If
|
quiet |
whether to suppress the message |
'RAVE' intensively uses cache files. If running on personal
computers, the disk space might be filled up very quickly. These cache
files are safe to remove if there is no 'RAVE' instance running.
Function clear_cached_files is designed to remove these cache files.
To run this function, please make sure that all 'RAVE' instances
are shutdown.
cache_root returns the root path that stores the 'RAVE'
cache data; clear_cached_files returns nothing
cache_root()cache_root()
This is a legacy script and possibly contain errors. Please use
cmd_run_ants_coreg for faster and stable implementation
instead.
cmd_run_3dAllineate( subject, mri_path, ct_path, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )cmd_run_3dAllineate( subject, mri_path, ct_path, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )
subject |
subject ID |
ct_path, mri_path
|
absolute paths to 'CT' and 'MR' image files |
overwrite |
whether to overwrite existing files |
command_path |
path to 'AFNI' home |
dry_run |
dry-run flag |
verbose |
whether to print out script |
Please avoid calling ants_coreg directly; use
cmd_run_ants_coreg for more robust behaviors
ants_coreg( ct_path, mri_path, coreg_path = NULL, reg_type = c("DenseRigid", "Rigid", "SyN", "Affine", "TRSAA", "SyNCC", "SyNOnly"), aff_metric = c("mattes", "meansquares", "GC"), syn_metric = c("mattes", "meansquares", "demons", "CC"), verbose = TRUE, ... ) cmd_run_ants_coreg( subject, ct_path, mri_path, reg_type = c("DenseRigid", "Rigid", "SyN", "Affine", "TRSAA", "SyNCC", "SyNOnly"), aff_metric = c("mattes", "meansquares", "GC"), syn_metric = c("mattes", "meansquares", "demons", "CC"), verbose = TRUE, dry_run = FALSE )ants_coreg( ct_path, mri_path, coreg_path = NULL, reg_type = c("DenseRigid", "Rigid", "SyN", "Affine", "TRSAA", "SyNCC", "SyNOnly"), aff_metric = c("mattes", "meansquares", "GC"), syn_metric = c("mattes", "meansquares", "demons", "CC"), verbose = TRUE, ... ) cmd_run_ants_coreg( subject, ct_path, mri_path, reg_type = c("DenseRigid", "Rigid", "SyN", "Affine", "TRSAA", "SyNCC", "SyNOnly"), aff_metric = c("mattes", "meansquares", "GC"), syn_metric = c("mattes", "meansquares", "demons", "CC"), verbose = TRUE, dry_run = FALSE )
ct_path, mri_path
|
absolute paths to 'CT' and 'MR' image files |
coreg_path |
registration path, where to save results; default is
the parent folder of |
reg_type |
registration type, choices are |
aff_metric |
cost function to use for linear or 'affine' transform |
syn_metric |
cost function to use for |
verbose |
whether to verbose command; default is true |
... |
passed to |
subject |
'RAVE' subject |
dry_run |
whether to dry-run the script and to print out the command instead of executing the code; default is false |
Aligned 'CT' will be generated at the coreg_path path:
'ct_in_t1.nii.gz'aligned 'CT' image; the image is also re-sampled into 'MRI' space
'transform.yaml'transform settings and outputs
'CT_IJK_to_MR_RAS.txt'transform matrix from volume 'IJK' space in the original 'CT' to the 'RAS' anatomical coordinate in 'MR' scanner; 'affine' transforms only
'CT_RAS_to_MR_RAS.txt'transform matrix from scanner 'RAS' space in the original 'CT' to 'RAS' in 'MR' scanner space; 'affine' transforms only
'dcm2niix'
Check https://rave.wiki on how to set up 'conda' environment
for 'RAVE' using 'ravemanager'.
cmd_run_dcm2niix( subject, src_path, type = c("MRI", "CT"), merge = c("Auto", "No", "Yes"), float = c("Yes", "No"), crop = c("No", "Yes", "Ignore"), overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )cmd_run_dcm2niix( subject, src_path, type = c("MRI", "CT"), merge = c("Auto", "No", "Yes"), float = c("Yes", "No"), crop = c("No", "Yes", "Ignore"), overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )
subject |
'RAVE' subject or a subject ID |
src_path |
source directory |
type |
image type |
merge, float, crop
|
|
overwrite |
overwrite existing files |
command_path |
path to program |
dry_run |
whether to dry-run |
verbose |
whether to print out command |
A command set running the terminal command; a folder named with
type will be created under the subject image input folder
## Not run: cmd_run_dcm2niix( "YAEL/pt02", "/path/to/DICOMDIR", "MRI" ) ## End(Not run)## Not run: cmd_run_dcm2niix( "YAEL/pt02", "/path/to/DICOMDIR", "MRI" ) ## End(Not run)
Runs 'FreeSurfer' recon-all command underneath; must have 'FreeSurfer'
installed.
cmd_run_freesurfer_recon_all( subject, mri_path, args = c("-all", "-autorecon1", "-autorecon2", "-autorecon3", "-autorecon2-cp", "-autorecon2-wm", "-autorecon2-pial"), work_path = NULL, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run ) cmd_run_freesurfer_recon_all_clinical( subject, mri_path, work_path = NULL, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run, ... )cmd_run_freesurfer_recon_all( subject, mri_path, args = c("-all", "-autorecon1", "-autorecon2", "-autorecon3", "-autorecon2-cp", "-autorecon2-wm", "-autorecon2-pial"), work_path = NULL, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run ) cmd_run_freesurfer_recon_all_clinical( subject, mri_path, work_path = NULL, overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run, ... )
subject |
'RAVE' subject or subject ID |
mri_path |
path to 'T1'-weighted 'MRI', must be a 'NIfTI' file |
args |
type of workflow; see 'FreeSurfer' |
work_path |
working directory; 'FreeSurfer' errors out when working directory contains white spaces. By default, 'RAVE' automatically creates a symbolic link to a path that contains no white space. Do not set this input manually unless you know what you are doing |
overwrite |
whether to overwrite existing work by deleting the folder; default is false. In case of errors, set this to true to restart the workflow; make sure you back up the files first. |
command_path |
'FreeSurfer' home directory. In some cases, 'RAVE' might
not be able to find environment variable |
dry_run |
avoid running the code, but print the process instead |
verbose |
print messages |
... |
ignored |
A list of shell command set.
# Requires `FreeSurfer` and only works on MacOS or Linux # as `FreeSurfer` does not support Windows ## Not run: # Create subject instance; strict=FALSE means it's OK if the subject # is missing subject <- as_rave_subject("YAEL/s01", strict = FALSE) cmd_run_freesurfer_recon_all( subject = subject, mri_path = "/path/to/T1.nii.gz" ) ## End(Not run)# Requires `FreeSurfer` and only works on MacOS or Linux # as `FreeSurfer` does not support Windows ## Not run: # Create subject instance; strict=FALSE means it's OK if the subject # is missing subject <- as_rave_subject("YAEL/s01", strict = FALSE) cmd_run_freesurfer_recon_all( subject = subject, mri_path = "/path/to/T1.nii.gz" ) ## End(Not run)
Run 'FSL' linear registration
cmd_run_fsl_flirt( subject, mri_path, ct_path, dof = 6, cost = c("mutualinfo", "leastsq", "normcorr", "corratio", "normmi", "labeldiff", "bbr"), search = 90, searchcost = c("mutualinfo", "leastsq", "normcorr", "corratio", "normmi", "labeldiff", "bbr"), overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )cmd_run_fsl_flirt( subject, mri_path, ct_path, dof = 6, cost = c("mutualinfo", "leastsq", "normcorr", "corratio", "normmi", "labeldiff", "bbr"), search = 90, searchcost = c("mutualinfo", "leastsq", "normcorr", "corratio", "normmi", "labeldiff", "bbr"), overwrite = FALSE, command_path = NULL, dry_run = FALSE, verbose = dry_run )
subject |
'RAVE' subject or subject ID |
mri_path |
path to 'MRI' (fixed image) |
ct_path |
path to 'CT' (moving image) |
dof |
degrees of freedom; default is 6 (rigid-body); set to 12 ('affine') |
cost, searchcost
|
cost function name |
search |
search degrees; default is 90 to save time, set to 180 for full search |
overwrite |
overwrite existing files |
command_path |
path to |
dry_run |
whether to dry-run |
verbose |
whether to print out command |
A command set running the terminal command; a 'coregistration'
folder will be created under the subject imaging directory
Image processing pipeline doi:10.1523/ENEURO.0328-23.2023, allowing cross-modality image registration, T1-weighted MRI normalization to template brain, creating subject-level brain atlas from inverse normalization.
yael_preprocess( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_policy = c("auto", "all"), register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_policy = c("auto", "all"), normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_back = ifelse(length(normalize_template) >= 1, normalize_template[[1]], NA), normalize_affine = NULL, atlases = list(), add_surfaces = FALSE, use_antspynet = TRUE, verbose = TRUE, additional_images = list(), ... ) cmd_run_yael_preprocess( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_affine = NULL, run_recon_all = TRUE, dry_run = FALSE, use_antspynet = TRUE, verbose = TRUE, ... )yael_preprocess( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_policy = c("auto", "all"), register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_policy = c("auto", "all"), normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_back = ifelse(length(normalize_template) >= 1, normalize_template[[1]], NA), normalize_affine = NULL, atlases = list(), add_surfaces = FALSE, use_antspynet = TRUE, verbose = TRUE, additional_images = list(), ... ) cmd_run_yael_preprocess( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_affine = NULL, run_recon_all = TRUE, dry_run = FALSE, use_antspynet = TRUE, verbose = TRUE, ... )
subject |
subject ID |
t1w_path |
path to 'T1'-weighted preoperative 'MRI', used as underlay and base image. If you want to have 'ACPC' aligned scanner coordinate system. Please align the image before feeding into this function. All images must contain skulls (do not strip skulls) |
ct_path, t2w_path, fgatir_path, preopct_path, flair_path, t1w_contrast_path
|
additional optional images to be aligned to the underlay; the registration
will be symmetric and the rigid-body transforms will be stored. Other
images can be fed with named list |
register_policy |
whether to skip already registered images;
default is true ( |
register_reversed |
whether to swap the moving images and the fixing image; default is false |
normalize_template |
template to normalize to: default is
|
normalize_policy |
whether to skip existing normalization, if
calculated; default is |
normalize_images |
images used for normalization; default is to include common images before the implantation (if available) |
normalize_back |
length of one (select from |
normalize_affine |
optional path for initial affine transform: this allows to manually set the affine transform and perform non-linear normalization only; for advanced users only. |
atlases |
a named list: the names must be template names from
|
add_surfaces |
whether to add surfaces for the subject; default is
|
use_antspynet |
whether to try |
verbose |
whether to print out the information; default is |
additional_images |
named list offering additional image types that are
not built-in. For example |
... |
reserved for legacy code and deprecated arguments |
run_recon_all |
whether to run 'FreeSurfer'; default is true |
dry_run |
whether to dry-run |
Nothing, a subject imaging folder will be created under 'RAVE' raw folder. It will take a while to run the workflow.
## Not run: # For T1 normalization only; add ct_path to include coregistration cmd_run_yael_preprocess( subject = "pt01", t1w_path = "/path/to/T1w.nii.gz", additional_images = list( MEG = "/path/to/meg.nii.gz" ), # normalize T1 to MNI152 normalize_template = 'mni_icbm152_nlin_asym_09b' ) ## End(Not run)## Not run: # For T1 normalization only; add ct_path to include coregistration cmd_run_yael_preprocess( subject = "pt01", t1w_path = "/path/to/T1w.nii.gz", additional_images = list( MEG = "/path/to/meg.nii.gz" ), # normalize T1 to MNI152 normalize_template = 'mni_icbm152_nlin_asym_09b' ) ## End(Not run)
YAEL imaging processing workflow (without 'Python')The image processing pipeline of cmd_run_yael_preprocess
(doi:10.1523/ENEURO.0328-23.2023), with every step computed in 'R' by
YAELNativeProcess on top of ravetools (version 0.3.3 or
later) instead of ANTs through 'Python': cross-modality rigid
registration, normalization of the 'T1'-weighted 'MRI' to template brains,
and subject-level atlases from the inverse normalization. The functions
take the same arguments, run the same steps and write the same files as
yael_preprocess and cmd_run_yael_preprocess, so the results
can be read by either engine.
yael_preprocess_native( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_policy = c("auto", "all"), register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_policy = c("auto", "all"), normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_back = ifelse(length(normalize_template) >= 1, normalize_template[[1]], NA), normalize_affine = NULL, atlases = list(), add_surfaces = FALSE, use_antspynet = TRUE, verbose = TRUE, additional_images = list(), ... ) cmd_run_yael_preprocess_native( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_affine = NULL, run_recon_all = TRUE, dry_run = FALSE, use_antspynet = TRUE, verbose = TRUE, ... )yael_preprocess_native( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_policy = c("auto", "all"), register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_policy = c("auto", "all"), normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_back = ifelse(length(normalize_template) >= 1, normalize_template[[1]], NA), normalize_affine = NULL, atlases = list(), add_surfaces = FALSE, use_antspynet = TRUE, verbose = TRUE, additional_images = list(), ... ) cmd_run_yael_preprocess_native( subject, t1w_path = NULL, ct_path = NULL, t2w_path = NULL, fgatir_path = NULL, preopct_path = NULL, flair_path = NULL, t1w_contrast_path = NULL, register_reversed = FALSE, normalize_template = "mni_icbm152_nlin_asym_09b", normalize_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"), normalize_affine = NULL, run_recon_all = TRUE, dry_run = FALSE, use_antspynet = TRUE, verbose = TRUE, ... )
subject |
subject ID |
t1w_path |
path to the 'T1'-weighted preoperative 'MRI', used as
underlay and base image. To have an |
ct_path, t2w_path, fgatir_path, preopct_path, flair_path, t1w_contrast_path
|
additional optional images to be aligned to the underlay; the registration
will be symmetric and the rigid-body transforms will be stored. Other
images can be fed with named list |
register_policy |
whether to skip already registered images;
default is true ( |
register_reversed |
whether to swap the moving images and the fixing image; default is false |
normalize_template |
template to normalize to: default is
|
normalize_policy |
whether to skip existing normalization, if
calculated; default is |
normalize_images |
images used for normalization; default is to include common images before the implantation (if available) |
normalize_back |
length of one (select from |
normalize_affine |
optional path to an initial linear transform: the normalization then starts from this transform, and its first registration only runs the non-linear stage; for advanced users only |
atlases |
a named list: the names must be template names from
|
add_surfaces |
whether to add surfaces for the subject; default is
|
use_antspynet |
ignored: the native engine has no |
verbose |
whether to print out the information; default is |
additional_images |
named list offering additional image types that are
not built-in. For example |
... |
reserved for legacy code and deprecated arguments |
run_recon_all |
whether to run |
dry_run |
whether to dry-run |
Templates are located (and downloaded when missing) by rpyANTs, whose
template functions are pure 'R'; 'Python' is never started. The full
template resolution is used, which takes a lot of memory. With a 1 mm
'T1' image (256 by 204 by 256 voxels), the normalization to
'mni_icbm152_nlin_asym_09a' (1 mm, with 0.5 mm tissue maps) took
about 2 minutes and peaked at about 8 gigabytes of resident memory; the
normalization to 'mni_icbm152_nlin_asym_09b' (0.5 mm) took about 7
minutes and peaked at 15 gigabytes of resident memory, 22 gigabytes with
the memory that the operating system compressed. Hence the script built by
cmd_run_yael_preprocess_native switches from
'mni_icbm152_nlin_asym_09b' to 'mni_icbm152_nlin_asym_09a'
when the memory recorded in the 'RAVE' settings (max_mem, the
computer memory unless set otherwise) is below 32 gigabytes, where the
script of cmd_run_yael_preprocess switches below 12 gigabytes.
yael_preprocess_native does not switch templates; it warns when
max_mem is below 32 gigabytes and a template has more than 30
million voxels.
The algorithms differ from ANTs in a few ways, described in
YAELNativeProcess: no deep_atropos, local
cross-correlation instead of mutual information in the non-linear stage,
greedy single-field SyN, whose update-field smoothing takes the
rpyANTs values (3 and 3.5) as a Gaussian standard deviation in
voxels where ANTs reads them as a variance, and is increased for
templates with more voxels per brain (doubled for the 0.5 mm templates) so
that the deformation stays one-to-one; additional images resampled onto
the native 'T1' grid (and left out when they cover less than 95 percent of
the brain), and a binary template brain mask. Streamlines in VTK
format are not read or written, since ieegio needs 'Python' for
them.
yael_preprocess_native returns nothing; the subject imaging
folder is created under the 'RAVE' raw folder. It will take a while to run
the workflow. cmd_run_yael_preprocess_native returns, invisibly, a
list with the script, its path, the log file, the image paths, and a
function execute that runs the script; the script is saved as
'scripts/cmd-yael-preprocess-native-full.R' (or '-simple.R'
without FreeSurfer) under the imaging folder when it runs.
YAELNativeProcess, as_yael_process,
cmd_run_yael_preprocess
## Not run: # For T1 normalization only; add ct_path to include coregistration cmd_run_yael_preprocess_native( subject = "pt01", t1w_path = "/path/to/T1w.nii.gz", additional_images = list( MEG = "/path/to/meg.nii.gz" ), # normalize T1 to MNI152 normalize_template = 'mni_icbm152_nlin_asym_09a' ) ## End(Not run)## Not run: # For T1 normalization only; add ct_path to include coregistration cmd_run_yael_preprocess_native( subject = "pt01", t1w_path = "/path/to/T1w.nii.gz", additional_images = list( MEG = "/path/to/meg.nii.gz" ), # normalize T1 to MNI152 normalize_template = 'mni_icbm152_nlin_asym_09a' ) ## End(Not run)
These shell commands are only tested on 'MacOS' and 'Linux'. On 'Windows' machines, please use the 'WSL2' system.
cmd_execute( script, script_path, command = "bash", dry_run = FALSE, backup = TRUE, args = NULL, ... ) cmd_run_r( expr, quoted = FALSE, verbose = TRUE, dry_run = FALSE, log_file = tempfile(), script_path = tempfile(), ... )cmd_execute( script, script_path, command = "bash", dry_run = FALSE, backup = TRUE, args = NULL, ... ) cmd_run_r( expr, quoted = FALSE, verbose = TRUE, dry_run = FALSE, log_file = tempfile(), script_path = tempfile(), ... )
script |
the shell script |
script_path |
path to run the script |
command |
which command to invoke; default is |
dry_run |
whether to run in dry-run mode; under such mode, the shell command will not execute. This is useful for debugging scripts; default is false |
backup |
whether to back up the script file immediately; default is true |
args |
further arguments in the shell command, especially the 'FreeSurfer' reconstruction command |
... |
passed to |
expr |
expression to run as command |
quoted |
whether |
verbose |
whether to print out the command script; default is true under dry-run mode, and false otherwise |
log_file |
where should log file be stored |
A list of data containing the script details:
scriptscript details
script_pathwhere the script should/will be saved
dry_runwhether dry-run mode is turned on
log_filepath to the log file
executea function to execute the script
Collapse power array with given analysis cubes
collapse_power(x, analysis_index_cubes) ## S3 method for class 'array' collapse_power(x, analysis_index_cubes) ## S3 method for class 'FileArray' collapse_power(x, analysis_index_cubes)collapse_power(x, analysis_index_cubes) ## S3 method for class 'array' collapse_power(x, analysis_index_cubes) ## S3 method for class 'FileArray' collapse_power(x, analysis_index_cubes)
x |
a |
analysis_index_cubes |
a list of analysis indices for each mode |
a list of collapsed (mean) results
freq_trial_eleccollapsed over time-points
freq_time_eleccollapsed over trials
time_trial_eleccollapsed over frequencies
freq_timecollapsed over trials and electrodes
freq_eleccollapsed over trials and time-points
freq_trialcollapsed over time-points and electrodes
time_trialcollapsed over frequencies and electrodes
time_eleccollapsed over frequencies and trials
trial_eleccollapsed over frequencies and time-points
freqpower per frequency, averaged over other modes
timepower per time-point, averaged over other modes
trialpower per trial, averaged over other modes
# Generate a 4-mode tensor array x <- filearray::filearray_create( tempfile(), dimension = c(16, 100, 20, 5), partition_size = 1 ) x[] <- rnorm(160000) dnames <- list( Frequency = 1:16, Time = seq(0, 1, length.out = 100), Trial = 1:20, Electrode = 1:5 ) dimnames(x) <- dnames # Collapse array results <- collapse_power(x, list( overall = list(), A = list(Trial = 1:5, Frequency = 1:6), B = list(Trial = 6:10, Time = 1:50) )) # Plot power over frequency and time groupB_result <- results$B image(t(groupB_result$freq_time), x = dnames$Time[groupB_result$cube_index$Time], y = dnames$Frequency[groupB_result$cube_index$Frequency], xlab = "Time (s)", ylab = "Frequency (Hz)", xlim = range(dnames$Time)) x$delete(force = TRUE)# Generate a 4-mode tensor array x <- filearray::filearray_create( tempfile(), dimension = c(16, 100, 20, 5), partition_size = 1 ) x[] <- rnorm(160000) dnames <- list( Frequency = 1:16, Time = seq(0, 1, length.out = 100), Trial = 1:20, Electrode = 1:5 ) dimnames(x) <- dnames # Collapse array results <- collapse_power(x, list( overall = list(), A = list(Trial = 1:5, Frequency = 1:6), B = list(Trial = 6:10, Time = 1:50) )) # Plot power over frequency and time groupB_result <- results$B image(t(groupB_result$freq_time), x = dnames$Time[groupB_result$cube_index$Time], y = dnames$Frequency[groupB_result$cube_index$Frequency], xlab = "Time (s)", ylab = "Frequency (Hz)", xlim = range(dnames$Time)) x$delete(force = TRUE)
Collapse high-dimensional tensor array
collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'FileArray' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'RAVEFileArray' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'Tensor' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'array' collapse2(x, keep, method = c("mean", "sum"), ...)collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'FileArray' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'RAVEFileArray' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'Tensor' collapse2(x, keep, method = c("mean", "sum"), ...) ## S3 method for class 'array' collapse2(x, keep, method = c("mean", "sum"), ...)
x |
R array, |
keep |
integer vector, the margins to keep |
method |
character, calculates mean or sum of the array when collapsing |
... |
passed to other methods |
A collapsed array (or a vector or matrix), depending on keep
x <- array(1:16, rep(2, 4)) collapse2(x, c(3, 2)) # Alternative method, but slower when `x` is a large array apply(x, c(3, 2), mean) # filearray y <- filearray::as_filearray(x) collapse2(y, c(3, 2)) collapse2(y, c(3, 2), "sum") # clean up y$delete(force = TRUE)x <- array(1:16, rep(2, 4)) collapse2(x, c(3, 2)) # Alternative method, but slower when `x` is a large array apply(x, c(3, 2), mean) # filearray y <- filearray::as_filearray(x) collapse2(y, c(3, 2)) collapse2(y, c(3, 2), "sum") # clean up y$delete(force = TRUE)
In some cases, for example, deep-brain stimulation ('DBS'),
it is often needed to analyze averaged electrode channels from segmented
'DBS' leads, or create bipolar contrast between electrode channels, or
to generate non-equally weighted channel averages for 'Laplacian' reference.
compose_channel allows users to generate a phantom channel that does
not physically exist, but is treated as a normal electrode channel in 'RAVE'.
compose_channel( subject, number, from, weights = rep(1/length(from), length(from)), normalize = FALSE, force = FALSE, label = sprintf("Composed-%s", number), signal_type = c("auto", "LFP", "Spike", "EKG", "Auxiliary", "Unknown") )compose_channel( subject, number, from, weights = rep(1/length(from), length(from)), normalize = FALSE, force = FALSE, label = sprintf("Composed-%s", number), signal_type = c("auto", "LFP", "Spike", "EKG", "Auxiliary", "Unknown") )
subject |
'RAVE' subject |
number |
new channel number, must be positive integer, cannot be existing electrode channel numbers |
from |
a vector of electrode channels that is used to compose this
new channel, must be non-empty; see |
weights |
numerical weights used on each |
normalize |
whether to normalize the weights such that the composed
channel has the same variance as |
force |
whether to overwrite existing composed channel if it exists;
default is false. By specifying |
label |
the label for the composed channel; will be stored at
|
signal_type |
signal type of the composed channel; default is
|
Nothing
if(interactive() && has_rave_subject("demo/DemoSubject")) { # the actual example code: # new channel 100 = 2 x channel 14 - (channe 15 + 16) compose_channel( subject = "demo/DemoSubject", number = 100, from = c(14, 15, 16), weights = c(2, -1, -1), normalize = FALSE ) }if(interactive() && has_rave_subject("demo/DemoSubject")) { # the actual example code: # new channel 100 = 2 x channel 14 - (channe 15 + 16) compose_channel( subject = "demo/DemoSubject", number = 100, from = c(14, 15, 16), weights = c(2, -1, -1), normalize = FALSE ) }
Convert electrode table
convert_electrode_table_to_bids( subject, space = c("ScanRAS", "MNI305", "fsnative") )convert_electrode_table_to_bids( subject, space = c("ScanRAS", "MNI305", "fsnative") )
subject |
'RAVE' subject |
space |
suggested coordinate space, notice this argument might not be
supported when |
A list of table in data frame and a list of meta information
# Run `install_subject("DemoSubject")` first! if( has_rave_subject("demo/DemoSubject") ) { convert_electrode_table_to_bids( "demo/DemoSubject", space = "ScanRAS" ) }# Run `install_subject("DemoSubject")` first! if( has_rave_subject("demo/DemoSubject") ) { convert_electrode_table_to_bids( "demo/DemoSubject", space = "ScanRAS" ) }
Stores and load data in various of data format. See 'Details' for limitations.
export_table( x, file, format = c("auto", "csv", "csv.zip", "tsv", "h5", "fst", "json", "rds", "yaml"), ... ) import_table( file, format = c("auto", "csv", "csv.zip", "tsv", "h5", "fst", "json", "rds", "yaml"), ... )export_table( x, file, format = c("auto", "csv", "csv.zip", "tsv", "h5", "fst", "json", "rds", "yaml"), ... ) import_table( file, format = c("auto", "csv", "csv.zip", "tsv", "h5", "fst", "json", "rds", "yaml"), ... )
x |
data table to be saved to |
file |
file to store the data |
format |
data storage format, default is |
... |
parameters passed to other functions |
The format 'rds', 'h5', 'fst', 'json', and
'yaml' try to preserve the first-level column attributes. Factors
will be preserved in these formats. Such property does not exist in
'csv', 'csv.zip' formats.
Open-data formats are 'h5', 'csv', 'csv.zip',
'json', 'yaml'. These formats require the table elements to
be native types (numeric, character, factor, etc.).
'rds', 'h5', and 'fst' can store large data sets.
'fst' is the best choice is performance and file size are the major
concerns. 'rds' preserves all the properties of the table.
The normalized path for export_table, and a
data.table for import_table
x <- data.table::data.table( a = rnorm(10), b = letters[1:10], c = 1:10, d = factor(LETTERS[1:10]) ) f <- tempfile(fileext = ".csv.zip") export_table(x = x, file = f) y <- import_table(file = f) str(x) str(y) # clean up unlink(f)x <- data.table::data.table( a = rnorm(10), b = letters[1:10], c = 1:10, d = factor(LETTERS[1:10]) ) f <- tempfile(fileext = ".csv.zip") export_table(x = x, file = f) y <- import_table(file = f) str(x) str(y) # clean up unlink(f)
YBA atlas for a 'RAVE' subjectMorphs a YBA atlas from the MNI152 symmetric template to the
subject native space, calculates the anatomical labels for the electrode
contacts, and optionally creates a quality-control report. This function
requires the subject to be normalized to a MNI152 symmetric template
first; see cmd_run_yael_preprocess.
generate_atlas_YBA( subject, name = c("YBA690", "YBA696"), template_names = NULL, radius = 2, verbose = TRUE, create_report = TRUE, disable_viewer = TRUE )generate_atlas_YBA( subject, name = c("YBA690", "YBA696"), template_names = NULL, radius = 2, verbose = TRUE, create_report = TRUE, disable_viewer = TRUE )
subject |
'RAVE' subject instance or character; see
|
name |
atlas name; choices are |
template_names |
template names to search for existing non-linear
mappings; default is |
radius |
search radius, in millimeters, when assigning the atlas labels
to the electrode contacts; default is |
verbose |
whether to print out the progress; default is |
create_report |
whether to create a quality-control report; default is
|
disable_viewer |
whether to omit the embedded three-dimensional viewer
in the report; default is |
The workflow requires an existing non-linear normalization from the subject
native T1w image to a MNI152 symmetric template. Please run
cmd_run_yael_preprocess with normalize_template set to
one of "mni_icbm152_nlin_sym_09a", "mni_icbm152_nlin_sym_09b",
or "mni_icbm152_nlin_sym_09c" if such mapping is missing.
Given the mapping, the template atlas is inverse-transformed to the native
space via generate_atlases_from_template. The resulting
NIfTI volume is stored under the subject 'atlases' imaging
folder, with a copy (and its color lookup table) placed under the subject
FreeSurfer 'mri' folder such that the atlas can be displayed
by the threeBrain viewer.
When the subject has electrode contacts localized, the anatomical labels are
calculated within a sphere of radius millimeters around each contact
center, and are stored as 'electrode_atlas_<name>.csv' under the
subject meta folder.
An invisible named list of
atlas_pathpath to the atlas volume created under the subject
FreeSurfer 'mri' folder
label_pathpath to the electrode label table, or NA if
no electrode contact has been localized
colormap_pathpath to the color lookup table saved along with the atlas volume
report_pathpath to the report folder, or NA if
create_report is false
report_filepath to the report file, or NA if
create_report is false
generate_atlases_from_template,
cmd_run_yael_preprocess
# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: subject_id <- "YAEL/subject_code" # ---- Step 1: normalization ------------------------------------------ # Map the native `T1w` image to a `MNI152` symmetric template. This step # is only needed once per subject; skip it when the mapping is available cmd_run_yael_preprocess( subject = subject_id, t1w_path = "/path/to/T1w.nii.gz", # `YBA` atlases are defined in the `MNI152` symmetric space normalize_template = "mni_icbm152_nlin_sym_09b", # set to `TRUE` to also run `FreeSurfer` reconstruction # if you haven't... run_recon_all = FALSE ) # ---- Step 2: atlas, electrode labels, and report --------------------- # Morph the atlas back to the native space, label the electrode contacts, # and create the quality-control report results <- generate_atlas_YBA(subject_id, name = "YBA696") # ---- Step 3: inspect -------------------------------------------------- # Electrode labels: `results$label_path` utils::read.csv(results$label_path) # Quality-control report utils::browseURL(results$report_file) ## End(Not run)# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: subject_id <- "YAEL/subject_code" # ---- Step 1: normalization ------------------------------------------ # Map the native `T1w` image to a `MNI152` symmetric template. This step # is only needed once per subject; skip it when the mapping is available cmd_run_yael_preprocess( subject = subject_id, t1w_path = "/path/to/T1w.nii.gz", # `YBA` atlases are defined in the `MNI152` symmetric space normalize_template = "mni_icbm152_nlin_sym_09b", # set to `TRUE` to also run `FreeSurfer` reconstruction # if you haven't... run_recon_all = FALSE ) # ---- Step 2: atlas, electrode labels, and report --------------------- # Morph the atlas back to the native space, label the electrode contacts, # and create the quality-control report results <- generate_atlas_YBA(subject_id, name = "YBA696") # ---- Step 3: inspect -------------------------------------------------- # Electrode labels: `results$label_path` utils::read.csv(results$label_path) # Quality-control report utils::browseURL(results$report_file) ## End(Not run)
Reverse-transform from template atlases via volume mapping
generate_atlases_from_template( subject, atlas_folders, template_name = "mni_icbm152_nlin_asym_09b", any_mni152 = TRUE, surfaces = TRUE, as_job = FALSE, extra_transform = NULL, extra_transform_type = c("ants", "native") )generate_atlases_from_template( subject, atlas_folders, template_name = "mni_icbm152_nlin_asym_09b", any_mni152 = TRUE, surfaces = TRUE, as_job = FALSE, extra_transform = NULL, extra_transform_type = c("ants", "native") )
subject |
'RAVE' subject instance or character; see
|
atlas_folders |
paths to the atlas folders |
template_name |
template name where the atlases are created;
see |
any_mni152 |
if the template is 'MNI152', then whether to check other template folders; default is true |
surfaces |
whether to generate surfaces; if true, then a 'GIfTI' file and a 'STL' file will be created for each atlas, if applicable. The 'GIfTI' file will be in right-anterior-superior 'RAS' coordinate system to comply with the 'NIfTI' standard, and 'STL' will be in left-posterior-superior 'LPS' system that can be imported to 'ITK'-based software such as 'BrainLab' or 'ANTs'. |
as_job |
whether to run as a background job for cleaner environment; default is false. |
extra_transform |
additional 'affine' transform (a four-by-four matrix)
that maps the subject native image (not points) to the target image. This
argument is for pipelines that take in transformed/processed images as input;
default is |
extra_transform_type |
type of transform if |
The workflow generates atlases from a template. To run this function, a
separate normalization is required (see
cmd_run_yael_preprocess). That function normalizes
native subject's brain ('T1w' image) to
a specified template (typically 'MNI152b' non-linear asymmetric version) via
a deformation field. Once obtaining the normalization transform,
generate_atlases_from_template inverse the process, creating
subject-level atlases based on that template.
When surfaces is TRUE, each atlas or mask file will be binned
with a threshold of 0.5. The resulting binary mask will be used
to generate a mask surface using volume_to_surf
function via implicit Laplacian smoothing.
The resulting surfaces and atlases typically sit at native space aligned
with input 'T1w' image. For each volume, a 'GIfTI' surface will be
created under right-anterior-superior ('RAS') coordinate system for
further inferences. In addition, an 'STL' surface will be created under
left-posterior-superior ('LPS') coordinate system. This file is mainly to
be used as object file for visualizations in software such as 'BrainLab'.
Some users might have extra processing before
'YAEL' pipeline (such as 'ACPC' realignment). This function provides a set of
extra arguments (extra_transform and extra_transform_type)
allowing generating atlases to align with the raw 'DICOM' images.
extra_transform needs to be an 'affine' matrix that maps
the image from the input of the 'YAEL' pipeline to the raw 'DICOM' image.
Be aware that this transform is not the point transformation matrix.
When extra_transform is non-empty, an extra folder
atlases_extra will be created under the subject imaging folder,
with transformed files aligned to 'DICOM' stored.
The function returns nothing, but will create a folder named
'atlases' under raw subject 'rave-imaging' folder.
# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: generate_atlases_from_template( "YAEL/OCD07", "/path/to/OCD_atlases") # If the image was ACPC realigned before being fed into the YAEL # pipeline generate_atlases_from_template( "YAEL/OCD07", "/path/to/OCD_atlases", extra_transform = "/path/to/sub-OCD7_from-T1wACPC_to-T1wNative_mode-image_xfm.mat" ) ## End(Not run)# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: generate_atlases_from_template( "YAEL/OCD07", "/path/to/OCD_atlases") # If the image was ACPC realigned before being fed into the YAEL # pipeline generate_atlases_from_template( "YAEL/OCD07", "/path/to/OCD_atlases", extra_transform = "/path/to/sub-OCD7_from-T1wACPC_to-T1wNative_mode-image_xfm.mat" ) ## End(Not run)
To properly run this function, please install ravetools
package.
generate_reference(subject, electrodes)generate_reference(subject, electrodes)
subject |
subject ID or |
electrodes |
electrodes to calculate the common average; these electrodes must run through 'Wavelet' first |
The goal of generating common average signals is to capture the common movement from all the channels and remove them out from electrode signals.
The common average signals will be stored at subject reference
directories. Two exact same copies will be stored: one in 'HDF5'
format such that the data can be read universally by other programming
languages; one in filearray format that can be
read in R with super fast speed.
A reference instance returned by new_reference with
signal type determined automatically.
This function obtains existing transforms rather than creating new
transforms. Please check function cmd_run_yael_preprocess
about mapping native images to the templates. This function requires
additional 'Python' configuration.
get_available_morph_to_template(subject)get_available_morph_to_template(subject)
subject |
'RAVE' subject instance or character; see
|
Template names with valid non-linear transforms.
# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: get_available_morph_to_template("project_name/subject_code") ## End(Not run)# Please check out https://rave.wiki to configure Python for RAVE # or run ravemanager::configure_python() ## Not run: get_available_morph_to_template("project_name/subject_code") ## End(Not run)
Get all possible projects in 'RAVE' default directory
get_projects(refresh = TRUE)get_projects(refresh = TRUE)
refresh |
whether to refresh the cache; default is true |
characters of project names
get_projects()get_projects()
Requires optional package 'plotly'; please install the package prior
to launching the viewer.
glimpse_voltage_repository_with_blocks( repository, initial_block = NULL, channels = NULL, epoch = NULL, start_time = 0, duration = 5, channel_gap = 1000, highpass_freq = NA, lowpass_freq = NA ) glimpse_voltage_filearray( filearray, sample_rate, channels = NULL, epoch = NULL, start_time = 0, duration = 5, channel_gap = 1000, highpass_freq = NA, lowpass_freq = NA )glimpse_voltage_repository_with_blocks( repository, initial_block = NULL, channels = NULL, epoch = NULL, start_time = 0, duration = 5, channel_gap = 1000, highpass_freq = NA, lowpass_freq = NA ) glimpse_voltage_filearray( filearray, sample_rate, channels = NULL, epoch = NULL, start_time = 0, duration = 5, channel_gap = 1000, highpass_freq = NA, lowpass_freq = NA )
repository |
'RAVE' repository |
initial_block |
initial recording block to select |
channels |
channels to visualize; default is all |
epoch |
additional epoch to annotation |
start_time, duration, channel_gap
|
initial start time, duration, and channel gap (can be changed later) |
highpass_freq, lowpass_freq
|
filter to apply when visualizing the signals, useful when signals have 'DC' shift |
filearray |
a |
sample_rate |
sample rate of the file-array |
An R-shiny application container environment; use
print method to launch the application.
if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) repository <- ravecore::prepare_subject_voltage_with_blocks( subject = subject) if (interactive()) { app <- glimpse_voltage_repository_with_blocks( repository = repository, initial_block = "008", epoch = "auditory_onset", highpass_freq = 0.5 ) print(app) close(app) } } # ---- Example 2 --------------------------------------------------- # Construct a filearray sample_rate <- 100 filearray <- filearray::as_filearray(array(rnorm(50000), dim = c(10000, 5))) dimnames(filearray) <- list( Time = seq_len(10000) / sample_rate, Electrode = 1:5 ) if(interactive()) { app <- glimpse_voltage_filearray(filearray = filearray, sample_rate = sample_rate, channel_gap = 6) print(app) }if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) repository <- ravecore::prepare_subject_voltage_with_blocks( subject = subject) if (interactive()) { app <- glimpse_voltage_repository_with_blocks( repository = repository, initial_block = "008", epoch = "auditory_onset", highpass_freq = 0.5 ) print(app) close(app) } } # ---- Example 2 --------------------------------------------------- # Construct a filearray sample_rate <- 100 filearray <- filearray::as_filearray(array(rnorm(50000), dim = c(10000, 5))) dimnames(filearray) <- list( Time = seq_len(10000) / sample_rate, Electrode = 1:5 ) if(interactive()) { app <- glimpse_voltage_filearray(filearray = filearray, sample_rate = sample_rate, channel_gap = 6) print(app) }
Import signal data from different file formats; supports 'EDF',
'BrainVision', 'BlackRock', 'HDF5', and 'Matlab'
formats under either native or 'BIDS' standard. It is recommended to use
'RAVE' user interfaces to import data.
import_from_brainvis( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", ... ) import_from_edf( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_h5_mat_per_block( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_h5_mat_per_channel( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_nevnsx( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... )import_from_brainvis( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", ... ) import_from_edf( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_h5_mat_per_block( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_h5_mat_per_channel( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... ) import_from_nevnsx( subject, blocks, electrodes, sample_rate, add = FALSE, data_type = "LFP", skip_validation = FALSE, ... )
subject |
a 'RAVE' subject or subject ID, consists of a project name, a
forward slash, followed by a subject code; for example,
|
blocks |
recording block; see Section 'Recording Blocks' for details |
electrodes |
electrode (channels) to import, must be a vector of
integers (channel numbers) or a character that can be interpreted as
integers; for example, integer vector |
sample_rate |
sampling frequency of the channel, must be positive.
'RAVE' only accepts unified consistent sample rate across all channels
with the same type. For example, if one 'LFP' channel is 2000 Hz, then
all 'LFP' channels must be 2000 Hz. Channels with different sample rates
will be either |
add |
whether the operation is to add new channels; default is false to protect data integrity |
data_type |
channel signal data type, can be |
... |
passed to or reserved for other methods |
skip_validation |
whether to skip data validation, default is false (recommended) |
The term "recording block" is defined as a continuous block of signals recorded during the experiment, typically during one run of the experiment, depending on the setups and format standards:
In the context of native standard, the raw 'RAVE' data is typically stored
in the '~/rave_data/raw_dir' directory ('~' stands for your
home directory, or documents directory under Windows). Each subject is
stored under a folder named after the subject code. For example, subject
'DemoSubject' has a raw folder path
'~/rave_data/raw_dir/DemoSubject'. The block folders are stored under
this subject folder (such as '008', '010', ...). Each
block folder contains a 5-min recording from an experiment.
In the context of 'BIDS' standard, there is no official definition of a
'block', instead, 'BIDS' has an explicit definition of sessions, tasks,
and runs. We typically consider that a combination of a session, a task,
and a run consists of a recording block. For example,
'ses-01_task-01_run-01' or 'ses-01_run-01', depending on
the existence of the 'BIDS' entities.
(Electrode) channel numbers refer to vectors of integers, or characters
that can be interpreted as integers. For integers, this is straightforward:
c(1:10, 21:30) refers to channel 1 to 20, then 21 to 30. For
characters, this is converted to integer internally via an unexported
function ravecore:::parse_svec.
The channel numbers must be an integer. In some data formats (such as 'EDF') or some standards ('BIDS'), the channel number is not officially explicitly defined: they use the channel labels as the identifiers. To deal with this situation, 'RAVE' treats the channel order as their numbers. In some cases, this is less ideal because the channel labels might implicitly encode the channel numbers. 'RAVE' will ignore such information for consistent behavior.
Enjoy hundreds of open-access data sets from https://openneuro.org with a simple accession number.
install_openneuro( accession_number, subject_codes = NULL, tag = NULL, parent_folder = NULL )install_openneuro( accession_number, subject_codes = NULL, tag = NULL, parent_folder = NULL )
accession_number |
|
subject_codes |
subject codes, with or without the prefix |
tag |
version number; default is |
parent_folder |
parent directory where the data will be downloaded into the data folder name is always the accession number |
The data folder name on the local disk.
## Not run: # Download Hermes D, Miller KJ, Wandell BA, Winawer J (2015) dataset # from https://openneuro.org/datasets/ds005953 install_openneuro('ds005953') # Download subject sub-HUP070 used by Bernabei & Li et al. # from https://openneuro.org/datasets/ds004100 install_openneuro('ds004100', subject_codes = "HUP070") # access the downloaded data bids_parent_root <- ravepipeline::raveio_getopt("bids_data_dir") # ---- Example of visualizing electrodes on the fsaverage ---- # Load BIDS project proj_ds004100 <- bidsr::bids_project( file.path(bids_parent_root, "ds004100")) # BIDS-R Subject instance sub_HUP070 <- bidsr::bids_subject(proj_ds004100, "HUP070") # Find BIDS entities with electrodes as suffix electrode <- bidsr::query_bids(sub_HUP070, list( data_types = "ieeg", suffixes = "electrodes", sidecars = TRUE )) # resolve electrode table path electrode_path <- bidsr::resolve_bids_path( x = proj_ds004100, format(electrode$parsed[[1]])) # laod electrode coordinate tabular <- bidsr::as_bids_tabular(electrode_path) # Build RAVE electrode table electrode_coordinates <- data.frame( Electrode = 1:nrow(tabular$content), x = tabular$content$x, y = tabular$content$y, z = tabular$content$z, Label = tabular$content$name, Radius = 2, BIDSSubject = "sub-HUP070" ) # Load RAVE brain - fsaverage template <- threeBrain::merge_brain(template_subject = "fsaverage") fsaverage <- template$template_object # This dataset uses surface RAS; see coordsys JSON # tkrRAS: surface RAS # scannerRAS: MRI RAS fsaverage$set_electrodes(electrode_coordinates, coord_sys = "tkrRAS") fsaverage$plot() ## End(Not run)## Not run: # Download Hermes D, Miller KJ, Wandell BA, Winawer J (2015) dataset # from https://openneuro.org/datasets/ds005953 install_openneuro('ds005953') # Download subject sub-HUP070 used by Bernabei & Li et al. # from https://openneuro.org/datasets/ds004100 install_openneuro('ds004100', subject_codes = "HUP070") # access the downloaded data bids_parent_root <- ravepipeline::raveio_getopt("bids_data_dir") # ---- Example of visualizing electrodes on the fsaverage ---- # Load BIDS project proj_ds004100 <- bidsr::bids_project( file.path(bids_parent_root, "ds004100")) # BIDS-R Subject instance sub_HUP070 <- bidsr::bids_subject(proj_ds004100, "HUP070") # Find BIDS entities with electrodes as suffix electrode <- bidsr::query_bids(sub_HUP070, list( data_types = "ieeg", suffixes = "electrodes", sidecars = TRUE )) # resolve electrode table path electrode_path <- bidsr::resolve_bids_path( x = proj_ds004100, format(electrode$parsed[[1]])) # laod electrode coordinate tabular <- bidsr::as_bids_tabular(electrode_path) # Build RAVE electrode table electrode_coordinates <- data.frame( Electrode = 1:nrow(tabular$content), x = tabular$content$x, y = tabular$content$y, z = tabular$content$z, Label = tabular$content$name, Radius = 2, BIDSSubject = "sub-HUP070" ) # Load RAVE brain - fsaverage template <- threeBrain::merge_brain(template_subject = "fsaverage") fsaverage <- template$template_object # This dataset uses surface RAS; see coordsys JSON # tkrRAS: surface RAS # scannerRAS: MRI RAS fsaverage$set_electrodes(electrode_coordinates, coord_sys = "tkrRAS") fsaverage$plot() ## End(Not run)
Install a subject from the internet, a zip file or a directory
install_subject( path = ".", ask = interactive(), overwrite = FALSE, backup = TRUE, use_cache = TRUE, dry_run = FALSE, force_project = NA, force_subject = NA, ... )install_subject( path = ".", ask = interactive(), overwrite = FALSE, backup = TRUE, use_cache = TRUE, dry_run = FALSE, force_project = NA, force_subject = NA, ... )
path |
path to subject archive, can be a path to directory, a zip file,
or an internet address (must starts with |
ask |
when |
overwrite |
whether to overwrite existing subject, see argument
|
backup |
whether to back-up the subject when overwriting the data; default is true, which will rename the old subject folders instead of removing; set to true to remove existing subject. |
use_cache |
whether to use cached extraction directory; default is
true. Set it to |
dry_run |
whether to dry-run the process instead of actually installing; this rehearsal can help you see the progress and prevent you from losing data |
force_project, force_subject
|
force set the project or subject; will raise a warning as this might mess up some pipelines |
... |
passed to |
## Not run: install_subject("DemoSubject") ## End(Not run)## Not run: install_subject("DemoSubject") ## End(Not run)
Please use a safer new_electrode function to
create instances. This documentation is to describe the member methods
of the electrode class LFP_electrode
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> LFP_electrode
h5_fname'HDF5' file name
validwhether current electrode is valid: subject exists and contains current electrode or reference; subject electrode type matches with current electrode type
raw_sample_ratevoltage sample rate
power_sample_ratepower/phase sample rate
preprocess_infopreprocess information
power_filepath to power 'HDF5' file
phase_filepath to phase 'HDF5' file
voltage_filepath to voltage 'HDF5' file
LFP_electrode$@marshal()Internal method
LFP_electrode$@marshal(...)
...internal arguments
LFP_electrode$@unmarshal()Internal method
LFP_electrode$@unmarshal(object)
object, ...internal arguments
LFP_electrode$print()print electrode summary
LFP_electrode$print()
LFP_electrode$set_reference()set reference for current electrode
LFP_electrode$set_reference(reference)
referenceeither NULL or LFP_electrode instance
LFP_electrode$new()constructor
LFP_electrode$new(subject, number, quiet = FALSE)
subject, number, quietsee constructor in
RAVEAbstarctElectrode
LFP_electrode$.load_noref_wavelet()load non-referenced wavelet coefficients (internally used)
LFP_electrode$.load_noref_wavelet(reload = FALSE)
reloadwhether to reload cache
if the reference number if NULL or 'noref', then
returns 0, otherwise returns a FileArray-class
LFP_electrode$.load_noref_voltage()load non-referenced voltage (internally used)
LFP_electrode$.load_noref_voltage(reload = FALSE)
reloadwhether to reload cache
sratevoltage signal sample rate
LFP_electrode$.load_wavelet()load referenced wavelet coefficients (internally used)
LFP_electrode$.load_wavelet(
type = c("power", "phase", "wavelet-coefficient"),
reload = FALSE
)
typetype of data to load
reloadwhether to reload cache
LFP_electrode$.load_voltage()load referenced voltage (internally used)
LFP_electrode$.load_voltage(reload = FALSE)
reloadwhether to reload cache
LFP_electrode$.load_raw_voltage()load raw voltage (no process)
LFP_electrode$.load_raw_voltage(reload = FALSE)
reloadwhether to reload cache
LFP_electrode$load_data_with_epochs()method to load electrode data
LFP_electrode$load_data_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient", and
"raw-voltage". For "power", "phase",
and "wavelet-coefficient", 'Wavelet' transforms are required.
For "voltage", 'Notch' filters must be applied. All these
types except for "raw-voltage" will be referenced.
For "raw-voltage", no reference will be performed since the data
will be the "raw" signal (no processing).
LFP_electrode$load_dimnames_with_epochs()get expected dimension names
LFP_electrode$load_dimnames_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
typesee load_data_with_epochs
LFP_electrode$load_data_with_blocks()load electrode block-wise data (with no reference), useful when epoch is absent
LFP_electrode$load_data_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage"),
simplify = TRUE
)
blockssession blocks
typedata type such as "power", "phase",
"voltage", "raw-voltage" (with no filters applied, as-is
from imported), "wavelet-coefficient". Note that if type
is "raw-voltage", then the data only needs to be imported;
for "voltage" data, 'Notch' filters must be applied; for
all other types, 'Wavelet' transforms are required.
simplifywhether to simplify the result
If simplify is enabled, and only one block is loaded,
then the result will be a vector (type="voltage") or a matrix
(others), otherwise the result will be a named list where the names
are the blocks.
LFP_electrode$load_dim_with_blocks()get expected dimension information for block-based loader
LFP_electrode$load_dim_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
blocks, typesee load_data_with_blocks
LFP_electrode$clear_cache()method to clear cache on hard drive
LFP_electrode$clear_cache(...)
...ignored
LFP_electrode$clear_memory()method to clear memory
LFP_electrode$clear_memory(...)
...ignored
LFP_electrode$clone()The objects of this class are cloneable with this method.
LFP_electrode$clone(deep = FALSE)
deepWhether to make a deep clone.
# Download subject demo/DemoSubject if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) # Electrode 14 in demo/DemoSubject e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() }# Download subject demo/DemoSubject if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) # Electrode 14 in demo/DemoSubject e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() }
Please use a safer new_reference function to
create instances. This documentation is to describe the member methods
of the electrode class LFP_reference
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> LFP_reference
existswhether electrode exists in subject
h5_fname'HDF5' file name
validwhether current electrode is valid: subject exists and contains current electrode or reference; subject electrode type matches with current electrode type
raw_sample_ratevoltage sample rate
power_sample_ratepower/phase sample rate
preprocess_infopreprocess information
power_filepath to power 'HDF5' file
phase_filepath to phase 'HDF5' file
voltage_filepath to voltage 'HDF5' file
LFP_reference$@marshal()Internal method
LFP_reference$@marshal(...)
...internal arguments
LFP_reference$@unmarshal()Internal method
LFP_reference$@unmarshal(object)
object, ...internal arguments
LFP_reference$print()print reference summary
LFP_reference$print()
LFP_reference$set_reference()set reference for current electrode
LFP_reference$set_reference(reference)
referencemust be NULL
LFP_reference$new()constructor
LFP_reference$new(subject, number, quiet = FALSE)
subject, number, quietsee constructor in
RAVEAbstarctElectrode
LFP_reference$.load_noref_wavelet()load non-referenced wavelet coefficients (internally used)
LFP_reference$.load_noref_wavelet(reload = FALSE)
reloadwhether to reload cache
if the reference number if NULL or 'noref', then
returns 0, otherwise returns a FileArray-class
LFP_reference$.load_noref_voltage()load non-referenced voltage (internally used)
LFP_reference$.load_noref_voltage(reload = FALSE)
reloadwhether to reload cache
sratevoltage signal sample rate
LFP_reference$.load_wavelet()load referenced wavelet coefficients (internally used)
LFP_reference$.load_wavelet(
type = c("power", "phase", "wavelet-coefficient"),
reload = FALSE
)
typetype of data to load
reloadwhether to reload cache
LFP_reference$.load_voltage()load referenced voltage (internally used)
LFP_reference$.load_voltage(reload = FALSE)
reloadwhether to reload cache
LFP_reference$load_data_with_epochs()method to load electrode data
LFP_reference$load_data_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient".
LFP_reference$load_data_with_blocks()load electrode block-wise data (with reference), useful when epoch is absent
LFP_reference$load_data_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient"),
simplify = TRUE
)
blockssession blocks
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient". Note that if type
is voltage, then 'Notch' filters must be applied; otherwise 'Wavelet'
transforms are required.
simplifywhether to simplify the result
If simplify is enabled, and only one block is loaded,
then the result will be a vector (type="voltage") or a matrix
(others), otherwise the result will be a named list where the names
are the blocks.
LFP_reference$load_dim_with_blocks()get expected dimension information for block-based loader
LFP_reference$load_dim_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
blocks, typesee load_data_with_blocks
LFP_reference$clear_cache()method to clear cache on hard drive
LFP_reference$clear_cache(...)
...ignored
LFP_reference$clear_memory()method to clear memory
LFP_reference$clear_memory(...)
...ignored
LFP_reference$clone()The objects of this class are cloneable with this method.
LFP_reference$clone(deep = FALSE)
deepWhether to make a deep clone.
# Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { subject <- as_rave_subject("demo/DemoSubject") # Electrode 14 as reference electrode (Bipolar referencing) e <- new_reference(subject = subject, number = "ref_14", signal_type = "LFP") # Reference "ref_13-16,24" (CAR or white-matter reference) ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") ref # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() }# Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { subject <- as_rave_subject("demo/DemoSubject") # Electrode 14 as reference electrode (Bipolar referencing) e <- new_reference(subject = subject, number = "ref_14", signal_type = "LFP") # Reference "ref_13-16,24" (CAR or white-matter reference) ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") ref # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() }
Load or save meta data to 'RAVE' subject
save_meta2(data, meta_type, project_name, subject_code) load_meta2( meta_type = c("electrodes", "frequencies", "time_points", "epoch", "references", "time_excluded", "info"), project_name, subject_code, subject_id, meta_name )save_meta2(data, meta_type, project_name, subject_code) load_meta2( meta_type = c("electrodes", "frequencies", "time_points", "epoch", "references", "time_excluded", "info"), project_name, subject_code, subject_id, meta_name )
data |
data table |
meta_type |
see load meta |
project_name |
project name |
subject_code |
subject code |
subject_id |
subject identified, alternative way to specify the project and subject in one string |
meta_name |
for epoch and reference only, the name the of the table |
The corresponding metadata
if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) electrode_table <- subject$get_electrode_table() save_meta2( data = electrode_table, meta_type = "electrodes", project_name = subject$project_name, subject_code = subject$subject_code ) load_meta2(meta_type = "electrodes", subject_id = subject) }if(has_rave_subject("demo/DemoSubject")) { subject <- as_rave_subject("demo/DemoSubject", strict = FALSE) electrode_table <- subject$get_electrode_table() save_meta2( data = electrode_table, meta_type = "electrodes", project_name = subject$project_name, subject_code = subject$subject_code ) load_meta2(meta_type = "electrodes", subject_id = subject) }
Create new electrode channel instance or a reference signal instance
Create new electrode channel instance or a reference signal instance
new_electrode(subject, number, signal_type, ...) new_reference(subject, number, signal_type, ...) new_electrode(subject, number, signal_type, ...) new_reference(subject, number, signal_type, ...)new_electrode(subject, number, signal_type, ...) new_reference(subject, number, signal_type, ...) new_electrode(subject, number, signal_type, ...) new_reference(subject, number, signal_type, ...)
subject |
characters, or a |
number |
integer in |
signal_type |
signal type of the electrode or reference; can be
automatically inferred, but it is highly recommended to specify a value;
see |
... |
other parameters passed to class constructors, respectively |
In new_electrode, number should be a positive
valid integer indicating the electrode number. In new_reference,
number can be one of the followings:
'noref', or NULL
no reference is needed
'ref_X'where 'X' is a single number, then the
reference is another existing electrode; this could occur in
bipolar-reference cases
'ref_XXX''XXX' is a combination of multiple
electrodes. This
could occur in common average reference, or white matter reference. One
example is 'ref_13-16,24', meaning the reference signal is an
average of electrode 13, 14, 15, 16, and 24.
In new_electrode, number should be a positive
valid integer indicating the electrode number. In new_reference,
number can be one of the followings:
'noref', or NULL
no reference is needed
'ref_X'where 'X' is a single number, then the
reference is another existing electrode; this could occur in
bipolar-reference cases
'ref_XXX''XXX' is a combination of multiple
electrodes that can be parsed by parse_svec. This
could occur in common average reference, or white matter reference. One
example is 'ref_13-16,24', meaning the reference signal is an
average of electrode 13, 14, 15, 16, and 24.
Electrode or reference instances that inherit
RAVEAbstarctElectrode class
Electrode or reference instances that inherit
RAVEAbstarctElectrode class
# Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { # Electrode 14 in demo/DemoSubject subject <- as_rave_subject("demo/DemoSubject") e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power power_array <- subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() } # Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { # Electrode 14 in demo/DemoSubject subject <- as_rave_subject("demo/DemoSubject") e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() }# Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { # Electrode 14 in demo/DemoSubject subject <- as_rave_subject("demo/DemoSubject") e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power power_array <- subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() } # Download subject demo/DemoSubject if( has_rave_subject("demo/DemoSubject") ) { # Electrode 14 in demo/DemoSubject subject <- as_rave_subject("demo/DemoSubject") e <- new_electrode(subject = subject, number = 14, signal_type = "LFP") # Load CAR reference "ref_13-16,24" ref <- new_reference(subject = subject, number = "ref_13-16,24", signal_type = "LFP") e$set_reference(ref) # Set epoch e$set_epoch(epoch = 'auditory_onset') # Set loading window e$trial_intervals <- list(c(-1, 2)) # Preview print(e) # Now epoch power power <- e$load_data_with_epochs("power") names(dimnames(power)) # Subset power subset(power, Time ~ Time < 0, Electrode ~ Electrode == 14) # clear cache on hard disk e$clear_cache() ref$clear_cache() }
RAVESubject instance from characterGet RAVESubject instance from character
new_rave_subject(project_name, subject_code, strict = TRUE) as_rave_subject(subject_id, strict = TRUE, reload = TRUE) has_rave_subject(subject_id)new_rave_subject(project_name, subject_code, strict = TRUE) as_rave_subject(subject_id, strict = TRUE, reload = TRUE) has_rave_subject(subject_id)
project_name |
character of 'RAVE' project name |
subject_code |
character of 'RAVE' subject code |
strict |
whether to check if subject directories exist or not |
subject_id |
character in format |
reload |
whether to reload (update) subject information, default is true |
RAVESubject instance
subject <- new_rave_subject(project_name = "demo@bids:ds04001", subject_code = "DemoSubject", strict = FALSE) subject subject$project$path subject$imaging_pathsubject <- new_rave_subject(project_name = "demo@bids:ds04001", subject_code = "DemoSubject", strict = FALSE) subject subject$project$path subject$imaging_path
'NiftyReg'
Supports rigid, affine, or non-linear transformation
niftyreg_coreg( ct_path, mri_path, coreg_path = NULL, reg_type = c("rigid", "affine", "nonlinear"), interp = c("trilinear", "cubic", "nearest"), verbose = TRUE, ... ) cmd_run_niftyreg_coreg( subject, ct_path, mri_path, reg_type = c("rigid", "affine", "nonlinear"), interp = c("trilinear", "cubic", "nearest"), verbose = TRUE, dry_run = FALSE, ... )niftyreg_coreg( ct_path, mri_path, coreg_path = NULL, reg_type = c("rigid", "affine", "nonlinear"), interp = c("trilinear", "cubic", "nearest"), verbose = TRUE, ... ) cmd_run_niftyreg_coreg( subject, ct_path, mri_path, reg_type = c("rigid", "affine", "nonlinear"), interp = c("trilinear", "cubic", "nearest"), verbose = TRUE, dry_run = FALSE, ... )
ct_path, mri_path
|
absolute paths to 'CT' and 'MR' image files |
coreg_path |
registration path, where to save results; default is
the parent folder of |
reg_type |
registration type, choices are |
interp |
how to interpolate when sampling volumes, choices are
|
verbose |
whether to verbose command; default is true |
... |
other arguments passed to |
subject |
'RAVE' subject |
dry_run |
whether to dry-run the script and to print out the command instead of executing the code; default is false |
Nothing is returned from the function. However, several files will be generated at the 'CT' path:
'ct_in_t1.nii'aligned 'CT' image; the image is also re-sampled into 'MRI' space
'CT_IJK_to_MR_RAS.txt'transform matrix from volume 'IJK' space in the original 'CT' to the 'RAS' anatomical coordinate in 'MR' scanner
'CT_RAS_to_MR_RAS.txt'transform matrix from scanner 'RAS' space in the original 'CT' to 'RAS' in 'MR' scanner space
Display slices, or interleave with image overlays. Require installing
package htmltools.
plot_volume_slices( x, overlay = NULL, depths = seq(-100, 100, by = 18), which = c("coronal", "axial", "sagittal"), nc = NA, col = c("black", "white"), overlay_col = col, overlay_alpha = NA, interleave = is.na(overlay_alpha), interleave_period = 4, interleave_transition = c("ease-in-out", "linear"), pixel_width = 0.5, underlay_range = NULL, overlay_range = NULL, ... )plot_volume_slices( x, overlay = NULL, depths = seq(-100, 100, by = 18), which = c("coronal", "axial", "sagittal"), nc = NA, col = c("black", "white"), overlay_col = col, overlay_alpha = NA, interleave = is.na(overlay_alpha), interleave_period = 4, interleave_transition = c("ease-in-out", "linear"), pixel_width = 0.5, underlay_range = NULL, overlay_range = NULL, ... )
x |
underlay, objects that can be converted to
|
overlay |
same type as |
depths |
depth position in millimeters, along the normal to the
|
which |
which plane to visualize; can be |
nc |
number of columns; default is to be determined by total number of images |
col, overlay_col
|
underlay and overlay color keys, must have at least two colors to construct color palettes |
overlay_alpha |
overlay transparency |
interleave |
whether to interleave overlay; default is true when
|
interleave_period |
interleave animation duration per period, only used when overlay is specified; default is 4 seconds |
interleave_transition |
interleave animation transition, only used
when overlay is specified; choices are |
pixel_width |
pixel width resolution; default is 0.5 millimeters |
underlay_range, overlay_range
|
numeric vectors of two, value ranges of underlay and overlay |
... |
passed to internal method |
A 'SVG' tag object that can be embedded in shiny applications
or plotted directly.
# toy-example: shape <- c(10, 10, 10) vox2ras <- matrix( c(10, 17.32, 0, -136, -17.32, 10, 20, -63, 0, -20, 0, 100, 0, 0, 0, 1), nrow = 4, byrow = TRUE ) # continuous x <- abs(array(sin(seq_len(100) / 10), shape)) underlay <- ieegio::as_ieegio_volume(x, vox2ras = vox2ras) overlay <- ieegio::as_ieegio_volume(x > 0.2, vox2ras = vox2ras) if(interactive()) { plot_volume_slices( underlay, overlay = overlay, depths = seq(0, 150, length.out = 4), pixel_width = 5, overlay_col = c("#00000000", "#FF000044", "#FF0000FF") ) } # Require `install_subject("yael_demo_001")` if(has_rave_subject("YAEL/yael_demo_001")) { subject <- ravecore::as_rave_subject("YAEL/yael_demo_001", strict = FALSE) t1 <- file.path(subject$imaging_path, "coregistration", "MRI_reference.nii.gz") ct <- file.path(subject$imaging_path, "coregistration", "CT_RAW.nii.gz") transform <- read.table( file.path(subject$imaging_path, "coregistration", "CT_IJK_to_MR_RAS.txt") ) ct_image_original <- ieegio::read_volume(ct) ct_image_aligned <- ieegio::as_ieegio_volume( ct_image_original[], vox2ras = as.matrix(transform) ) if(interactive()) { plot_volume_slices( t1, overlay = ct_image_aligned, overlay_col = c("#00000000", "#FF000044", "#FF0000FF"), nc = 6 ) } }# toy-example: shape <- c(10, 10, 10) vox2ras <- matrix( c(10, 17.32, 0, -136, -17.32, 10, 20, -63, 0, -20, 0, 100, 0, 0, 0, 1), nrow = 4, byrow = TRUE ) # continuous x <- abs(array(sin(seq_len(100) / 10), shape)) underlay <- ieegio::as_ieegio_volume(x, vox2ras = vox2ras) overlay <- ieegio::as_ieegio_volume(x > 0.2, vox2ras = vox2ras) if(interactive()) { plot_volume_slices( underlay, overlay = overlay, depths = seq(0, 150, length.out = 4), pixel_width = 5, overlay_col = c("#00000000", "#FF000044", "#FF0000FF") ) } # Require `install_subject("yael_demo_001")` if(has_rave_subject("YAEL/yael_demo_001")) { subject <- ravecore::as_rave_subject("YAEL/yael_demo_001", strict = FALSE) t1 <- file.path(subject$imaging_path, "coregistration", "MRI_reference.nii.gz") ct <- file.path(subject$imaging_path, "coregistration", "CT_RAW.nii.gz") transform <- read.table( file.path(subject$imaging_path, "coregistration", "CT_IJK_to_MR_RAS.txt") ) ct_image_original <- ieegio::read_volume(ct) ct_image_aligned <- ieegio::as_ieegio_volume( ct_image_original[], vox2ras = as.matrix(transform) ) if(interactive()) { plot_volume_slices( t1, overlay = ct_image_aligned, overlay_col = c("#00000000", "#FF000044", "#FF0000FF"), nc = 6 ) } }
Calculate power baseline
power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Trial", "Frequency", "Electrode"), ... ) ## S3 method for class 'rave_prepare_power' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Frequency", "Trial", "Electrode"), electrodes, ... ) ## S3 method for class 'FileArray' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Frequency", "Trial", "Electrode"), filebase = NULL, ... ) ## S3 method for class 'array' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Trial", "Frequency", "Electrode"), ... )power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Trial", "Frequency", "Electrode"), ... ) ## S3 method for class 'rave_prepare_power' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Frequency", "Trial", "Electrode"), electrodes, ... ) ## S3 method for class 'FileArray' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Frequency", "Trial", "Electrode"), filebase = NULL, ... ) ## S3 method for class 'array' power_baseline( x, baseline_windows, method = c("percentage", "sqrt_percentage", "decibel", "zscore", "sqrt_zscore", "db_zscore"), units = c("Trial", "Frequency", "Electrode"), ... )
x |
R array, |
baseline_windows |
list of baseline window (intervals) |
method |
baseline method; choices are |
units |
the unit of the baseline; see 'Details' |
... |
passed to other methods |
electrodes |
the electrodes to be included in baseline calculation;
for power repository object produced by
|
filebase |
where to store the output; default is |
The arrays must be four-mode tensor and must have valid named
dimnames. The dimension names must be 'Trial',
'Frequency', 'Time', 'Electrode', case sensitive.
The baseline_windows determines the baseline windows that are used to
calculate time-points of baseline to be included. This can be one
or more intervals and must pass the validation function
validate_time_window.
The units determines the unit of the baseline. It can be one or
more of 'Trial', 'Frequency', 'Electrode'. The default
value is all of them, i.e., baseline for each combination of trial,
frequency, and electrode. To share the baseline across trials, please
remove 'Trial' from units. To calculate baseline that should
be shared across electrodes (e.g. in some mini-electrodes), remove
'Electrode' from the units.
Usually the same type as the input: for arrays
and filearray, the outputs are
also the same type with the same dimensions; for 'rave_prepare_power'
repositories, the results will be stored in its 'baselined' element;
see 'Examples'.
if( has_rave_subject("demo/DemoSubject") ) { # The following code need to download additional demo data # Please see https://rave.wiki/ for more details repo <- prepare_subject_power_with_epochs( subject = "demo/DemoSubject", time_windows = c(-1, 3), electrodes = c(14, 15)) ##### Direct baseline on the repository power_baseline(x = repo, method = "decibel", baseline_windows = list(c(-1, 0), c(2, 3))) power_mean <- repo$power$baselined$collapse( keep = c(2,1), method = "mean") image(power_mean, x = repo$time_points, y = repo$frequency, xlab = "Time (s)", ylab = "Frequency (Hz)", main = "Mean power over trial (Baseline: -1~0 & 2~3)") abline(v = 0, lty = 2, col = 'blue') text(x = 0, y = 20, "Aud-Onset", col = "blue", cex = 0.6) ##### Alternatively, baseline on electrode instances baselined <- lapply(repo$power$data_list, function(inst) { re <- power_baseline(inst, method = "decibel", baseline_windows = list(c(-1, 0), c(2, 3))) collapse2(re, keep = c(2,1), method = "mean") }) power_mean2 <- (baselined[[1]] + baselined[[2]]) / 2 # Same with precision difference max(abs(power_mean2 - power_mean)) < 1e-6 }if( has_rave_subject("demo/DemoSubject") ) { # The following code need to download additional demo data # Please see https://rave.wiki/ for more details repo <- prepare_subject_power_with_epochs( subject = "demo/DemoSubject", time_windows = c(-1, 3), electrodes = c(14, 15)) ##### Direct baseline on the repository power_baseline(x = repo, method = "decibel", baseline_windows = list(c(-1, 0), c(2, 3))) power_mean <- repo$power$baselined$collapse( keep = c(2,1), method = "mean") image(power_mean, x = repo$time_points, y = repo$frequency, xlab = "Time (s)", ylab = "Frequency (Hz)", main = "Mean power over trial (Baseline: -1~0 & 2~3)") abline(v = 0, lty = 2, col = 'blue') text(x = 0, y = 20, "Aud-Onset", col = "blue", cex = 0.6) ##### Alternatively, baseline on electrode instances baselined <- lapply(repo$power$data_list, function(inst) { re <- power_baseline(inst, method = "decibel", baseline_windows = list(c(-1, 0), c(2, 3))) collapse2(re, keep = c(2,1), method = "mean") }) power_mean2 <- (baselined[[1]] + baselined[[2]]) / 2 # Same with precision difference max(abs(power_mean2 - power_mean)) < 1e-6 }
'RAVE' repository: basic
prepare_subject_bare( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = FALSE, quiet = TRUE, repository_id = NULL ) prepare_subject_bare0( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = FALSE, quiet = TRUE, repository_id = NULL )prepare_subject_bare( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = FALSE, quiet = TRUE, repository_id = NULL ) prepare_subject_bare0( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = FALSE, quiet = TRUE, repository_id = NULL )
subject |
'RAVE' subject |
electrodes |
string or integers indicating electrodes to load |
reference_name |
name of the reference table |
... |
passed to |
auto_exclude |
whether to automatically discard bad channels |
quiet |
see field |
repository_id |
see field |
A RAVESubjectBaseRepository instance
if ( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_bare0("demo/DemoSubject", electrodes = 14:16, reference_name = "default") print(repository) repository$subject repository$subject$raw_sample_rates repository$electrode_table repository$reference_table electrodes <- repository$electrode_instances # Channel 14 e <- electrodes$e_14 # referenced voltage voltage <- e$load_data_with_blocks("008", "voltage") ravetools::diagnose_channel(voltage, srate = 2000) }if ( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_bare0("demo/DemoSubject", electrodes = 14:16, reference_name = "default") print(repository) repository$subject repository$subject$raw_sample_rates repository$electrode_table repository$reference_table electrodes <- repository$electrode_instances # Channel 14 e <- electrodes$e_14 # referenced voltage voltage <- e$load_data_with_blocks("008", "voltage") ravetools::diagnose_channel(voltage, srate = 2000) }
Loads recording blocks - continuous recording chunks, typically a run of minutes.
prepare_subject_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_raw_voltage_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = "noref", downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_voltage_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_time_frequency_coefficients_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_phase_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE )prepare_subject_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_raw_voltage_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = "noref", downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_voltage_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_time_frequency_coefficients_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_phase_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power_with_blocks( subject, electrodes = NULL, blocks = NULL, reference_name = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE )
subject |
'RAVE' subject |
electrodes |
string or integers indicating electrodes to load |
blocks |
names of the recording blocks to load, can be queried via
|
reference_name |
name of the reference table |
... |
passed to |
quiet |
see field |
repository_id |
see field |
strict |
whether to check existence of subject before loading data; default is true |
downsample |
positive integer or |
prepare_subject_with_blocks does not actually load any signal data.
Its existence is simply for backward compatibility. It instantiates a
super-class of the rest of methods. Therefore, please refer to the rest of
the methods for loading specific data types.
If you do not need to analyze super high-frequency signals,
it is recommended to set a proper downsample value to down-sample
the signals while loading voltage traces. This helps optimizing the data
storage and speed up computation (significantly). For example, suppose
you have 200 channels sampled at 30,000 Hz, a 30-minute recording will
cost around 80+ gigabyte memory only to store, let along the storage needed
to compute analyses and time needed to perform those analyses. Down-sampling
the channels helps a lot. If you are mostly interested in signals below
100 Hz, then down-sampling voltage traces to 400 Hz will preserve the
frequency components needed, and it takes 1.2 gigabytes to hold the same
recording in memory.
Due to the large-data nature of blocks of signals, the repository will prepare cache files for all the channels, allowing users to load the cached data later without needing to reload
A RAVESubjectRecordingBlockRepository instance
if( has_rave_subject("demo/DemoSubject") ) { # ---- An use-case example ------------------------------------------------ # Install subject via install_subject("DemoSubject") subject <- as_rave_subject("demo/DemoSubject") # list all blocks subject$blocks repository <- prepare_subject_voltage_with_blocks( subject, electrodes = 13:16, blocks = "008", reference = "default" ) print(repository) repository$blocks # get data container <- repository$get_container() # block data container$`008` lfp_list <- container$`008`$LFP channel_sample_rate <- lfp_list$sample_rate # Even we only load channels 14-16, all the channels are here for # in case we want to use the cache for future purposes lfp_list$dimnames$Electrode # Plot all loaded channels channel_sel <- lfp_list$dimnames$Electrode %in% c(14, 15, 16) channel_signals <- lfp_list$data[, channel_sel, drop = FALSE, dimnames = FALSE] ravetools::plot_signals(t(channel_signals), sample_rate = channel_sample_rate, channel_names = 14:16) # Load channel 14 and plot pwelch channel_sel <- lfp_list$dimnames$Electrode == 14 channel_signals <- lfp_list$data[, channel_sel, drop = TRUE, dimnames = FALSE] ravetools::diagnose_channel(channel_signals, srate = channel_sample_rate, name = "Channel 14", nclass = 30) # ---- Use cache --------------------------------------------------- subject <- as_rave_subject("demo/DemoSubject") # Lazy-load block 008 repository <- prepare_subject_voltage_with_blocks( subject, electrodes = 13:16, blocks = "008", reference = "default", lazy_load = TRUE # <-- trick ) # Immediately load data with force=FALSE to use cache if exists repository$mount_data(force = FALSE) # ---- More examples --------------------------------------------- subject <- as_rave_subject("demo/DemoSubject") repository <- prepare_subject_power_with_blocks( subject, electrodes = 14, blocks = "008", reference_name = "default" ) block_008 <- repository$power$`008`$LFP channel_sel <- block_008$dimnames$Electrode == 14 # Drop electrode margin power <- block_008$data[, , channel_sel, drop = TRUE, dimnames = FALSE] # global baseline power_baselined_t <- 10 * log10(t(power)) power_baselined_t <- power_baselined_t - rowMeans(power_baselined_t) ravetools::plot_signals( power_baselined_t, sample_rate = block_008$sample_rate, channel_names = block_008$dimnames$Frequency, space = 1, start_time = 20, duration = 30, ylab = "Frequency", main = "Channel 14 - Power with Global Baseline (20-50 sec)" ) }if( has_rave_subject("demo/DemoSubject") ) { # ---- An use-case example ------------------------------------------------ # Install subject via install_subject("DemoSubject") subject <- as_rave_subject("demo/DemoSubject") # list all blocks subject$blocks repository <- prepare_subject_voltage_with_blocks( subject, electrodes = 13:16, blocks = "008", reference = "default" ) print(repository) repository$blocks # get data container <- repository$get_container() # block data container$`008` lfp_list <- container$`008`$LFP channel_sample_rate <- lfp_list$sample_rate # Even we only load channels 14-16, all the channels are here for # in case we want to use the cache for future purposes lfp_list$dimnames$Electrode # Plot all loaded channels channel_sel <- lfp_list$dimnames$Electrode %in% c(14, 15, 16) channel_signals <- lfp_list$data[, channel_sel, drop = FALSE, dimnames = FALSE] ravetools::plot_signals(t(channel_signals), sample_rate = channel_sample_rate, channel_names = 14:16) # Load channel 14 and plot pwelch channel_sel <- lfp_list$dimnames$Electrode == 14 channel_signals <- lfp_list$data[, channel_sel, drop = TRUE, dimnames = FALSE] ravetools::diagnose_channel(channel_signals, srate = channel_sample_rate, name = "Channel 14", nclass = 30) # ---- Use cache --------------------------------------------------- subject <- as_rave_subject("demo/DemoSubject") # Lazy-load block 008 repository <- prepare_subject_voltage_with_blocks( subject, electrodes = 13:16, blocks = "008", reference = "default", lazy_load = TRUE # <-- trick ) # Immediately load data with force=FALSE to use cache if exists repository$mount_data(force = FALSE) # ---- More examples --------------------------------------------- subject <- as_rave_subject("demo/DemoSubject") repository <- prepare_subject_power_with_blocks( subject, electrodes = 14, blocks = "008", reference_name = "default" ) block_008 <- repository$power$`008`$LFP channel_sel <- block_008$dimnames$Electrode == 14 # Drop electrode margin power <- block_008$data[, , channel_sel, drop = TRUE, dimnames = FALSE] # global baseline power_baselined_t <- 10 * log10(t(power)) power_baselined_t <- power_baselined_t - rowMeans(power_baselined_t) ravetools::plot_signals( power_baselined_t, sample_rate = block_008$sample_rate, channel_names = block_008$dimnames$Frequency, space = 1, start_time = 20, duration = 30, ylab = "Frequency", main = "Channel 14 - Power with Global Baseline (20-50 sec)" ) }
'RAVE' repository: with epochs
prepare_subject_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_raw_voltage_with_epochs( subject, electrodes = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = TRUE, repository_id = NULL, strict = TRUE ) prepare_subject_voltage_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_time_frequency_coefficients_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_phase_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE )prepare_subject_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_raw_voltage_with_epochs( subject, electrodes = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = TRUE, repository_id = NULL, strict = TRUE ) prepare_subject_voltage_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_time_frequency_coefficients_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_power( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE ) prepare_subject_phase_with_epochs( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE )
subject |
'RAVE' subject |
electrodes |
string or integers indicating electrodes to load |
reference_name |
name of the reference table |
epoch_name |
name of the epoch trial table |
time_windows |
numeric vector with even lengths, the time start
and end of the trials, for example, |
stitch_events |
events where the |
... |
passed to |
quiet |
see field |
repository_id |
see field |
strict |
whether to check existence of subject before loading data; default is true |
A RAVESubjectEpochRepository instance
if ( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_with_epochs( "demo/DemoSubject", electrodes = 14:16, reference_name = "default", epoch_name = "auditory_onset", time_windows = c(-1, 2)) print(repository) head(repository$epoch$table) electrodes <- repository$electrode_instances # Channel 14 e <- electrodes$e_14 # referenced voltage voltage <- e$load_data_with_epochs("voltage") # 6001 time points (2000 sample rate) # 287 trials # 1 channel dim(voltage) ravetools::plot_signals(t(voltage[, 1:10, 1]), sample_rate = 2000, ylab = "Trial", main = "First 10 trials") }if ( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_with_epochs( "demo/DemoSubject", electrodes = 14:16, reference_name = "default", epoch_name = "auditory_onset", time_windows = c(-1, 2)) print(repository) head(repository$epoch$table) electrodes <- repository$electrode_instances # Channel 14 e <- electrodes$e_14 # referenced voltage voltage <- e$load_data_with_epochs("voltage") # 6001 time points (2000 sample rate) # 287 trials # 1 channel dim(voltage) ravetools::plot_signals(t(voltage[, 1:10, 1]), sample_rate = 2000, ylab = "Trial", main = "First 10 trials") }
'nipy'
Align 'CT' using
nipy.algorithms.registration.histogram_registration.
py_nipy_coreg( ct_path, mri_path, clean_source = TRUE, inverse_target = TRUE, precenter_source = TRUE, smooth = 0, reg_type = c("rigid", "affine"), interp = c("pv", "tri"), similarity = c("crl1", "cc", "cr", "mi", "nmi", "slr"), optimizer = c("powell", "steepest", "cg", "bfgs", "simplex"), tol = 1e-04, dry_run = FALSE ) cmd_run_nipy_coreg( subject, ct_path, mri_path, clean_source = TRUE, inverse_target = TRUE, precenter_source = TRUE, reg_type = c("rigid", "affine"), interp = c("pv", "tri"), similarity = c("crl1", "cc", "cr", "mi", "nmi", "slr"), optimizer = c("powell", "steepest", "cg", "bfgs", "simplex"), dry_run = FALSE, verbose = FALSE )py_nipy_coreg( ct_path, mri_path, clean_source = TRUE, inverse_target = TRUE, precenter_source = TRUE, smooth = 0, reg_type = c("rigid", "affine"), interp = c("pv", "tri"), similarity = c("crl1", "cc", "cr", "mi", "nmi", "slr"), optimizer = c("powell", "steepest", "cg", "bfgs", "simplex"), tol = 1e-04, dry_run = FALSE ) cmd_run_nipy_coreg( subject, ct_path, mri_path, clean_source = TRUE, inverse_target = TRUE, precenter_source = TRUE, reg_type = c("rigid", "affine"), interp = c("pv", "tri"), similarity = c("crl1", "cc", "cr", "mi", "nmi", "slr"), optimizer = c("powell", "steepest", "cg", "bfgs", "simplex"), dry_run = FALSE, verbose = FALSE )
ct_path, mri_path
|
absolute paths to 'CT' and 'MR' image files |
clean_source |
whether to replace negative 'CT' values with zeros; default is true |
inverse_target |
whether to inverse 'MRI' color intensity; default is true |
precenter_source |
whether to adjust the 'CT' transform matrix before alignment, such that the origin of 'CT' is at the center of the volume; default is true. This option may avoid the case that 'CT' is too far-away from the 'MR' volume at the beginning of the optimization |
smooth, interp, optimizer, tol
|
optimization parameters, see
|
reg_type |
registration type, choices are |
similarity |
the cost function of the alignment; choices are
|
dry_run |
whether to dry-run the script and to print out the command instead of executing the code; default is false |
subject |
'RAVE' subject |
verbose |
whether to verbose command; default is false |
Nothing is returned from the function. However, several files will be generated at the 'CT' path:
'ct_in_t1.nii'aligned 'CT' image; the image is also re-sampled into 'MRI' space
'CT_IJK_to_MR_RAS.txt'transform matrix from volume 'IJK' space in the original 'CT' to the 'RAS' anatomical coordinate in 'MR' scanner
'CT_RAS_to_MR_RAS.txt'transform matrix from scanner 'RAS' space in the original 'CT' to 'RAS' in 'MR' scanner space
Create 3D visualization of the brain and visualize with modern web browsers
rave_brain( subject, surfaces = "pial", overlays = "aparc.a2009s+aseg", annotations = "label/aparc.a2009s", streamlines = "default/*", ..., usetemplateifmissing = FALSE, include_electrodes = TRUE )rave_brain( subject, surfaces = "pial", overlays = "aparc.a2009s+aseg", annotations = "label/aparc.a2009s", streamlines = "default/*", ..., usetemplateifmissing = FALSE, include_electrodes = TRUE )
subject |
character, list, or |
surfaces |
one or more brain surface types from |
overlays |
volumes to overlay; default is |
annotations |
surface annotation or curvature data to load;
default is |
streamlines |
streamlines (poly-lines) to add to the viewer; stored
under subject FreeSurfer folder (under sub-folder |
... |
ignored, reserved for legacy code |
usetemplateifmissing |
whether to use template brain when the subject
brain files are missing. If set to true, then a template (usually 'N27')
brain will be displayed as an alternative solution, and electrodes will be
rendered according to their |
include_electrodes |
whether to include electrode in the model; default is true |
A 'threeBrain' instance if brain is found or
usetemplateifmissing is set to true; otherwise returns NULL
if(has_rave_subject("demo/DemoSubject")) { brain <- rave_brain("demo/DemoSubject") if (interactive()) { brain$plot() } }if(has_rave_subject("demo/DemoSubject")) { brain <- rave_brain("demo/DemoSubject") if (interactive()) { brain$plot() } }
Find external command-line tools
normalize_commandline_path( path, type = c("dcm2niix", "freesurfer", "fsl", "afni", "others"), unset = NA ) cmd_dcm2niix(error_on_missing = TRUE, unset = NA) cmd_freesurfer_home(error_on_missing = TRUE, unset = NA) cmd_fsl_home(error_on_missing = TRUE, unset = NA) cmd_afni_home(error_on_missing = TRUE, unset = NA) cmd_homebrew(error_on_missing = TRUE, unset = NA) cmd_dry_run() rscript_path(...)normalize_commandline_path( path, type = c("dcm2niix", "freesurfer", "fsl", "afni", "others"), unset = NA ) cmd_dcm2niix(error_on_missing = TRUE, unset = NA) cmd_freesurfer_home(error_on_missing = TRUE, unset = NA) cmd_fsl_home(error_on_missing = TRUE, unset = NA) cmd_afni_home(error_on_missing = TRUE, unset = NA) cmd_homebrew(error_on_missing = TRUE, unset = NA) cmd_dry_run() rscript_path(...)
path |
path to normalize |
type |
type of command |
unset |
default to return if the command is not found |
error_on_missing |
whether to raise errors if command is missing |
... |
ignored |
Normalized path to the command, or unset if command is
missing.
Convert 'RAVE' subject generated by 2.0 pipeline such that 1.0 modules can use the data. The subject must have valid electrodes. The data must be imported, with time-frequency transformed to pass the validation before converting.
rave_legacy_subject_format_conversion(subject, verbose = TRUE, ...)rave_legacy_subject_format_conversion(subject, verbose = TRUE, ...)
subject |
'RAVE' subject characters, such as |
verbose |
whether to verbose the messages |
... |
ignored, reserved for future use |
Nothing
A generic function that will be dispatched to using different method based
on input x
rave_path(x, storage = NULL, ...)rave_path(x, storage = NULL, ...)
x |
R object |
storage |
storage type, different options based on different R objects |
... |
additional arguments passed to dispatched method |
This class is not intended for direct use. Please create new child classes and implement some key methods.
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode
subjectsubject instance (RAVESubject)
numberinteger stands for electrode number or reference ID
referencereference electrode, either NULL for no reference
or an electrode instance inherits RAVEAbstarctElectrode
epocha RAVEEpoch instance
stitch_eventsevents to stitch, when loading window is not default
to trial onset; must be NULL or a character vector of length 2
typesignal type of the electrode, such as 'LFP', 'Spike', and 'EKG'; default is 'Unknown'
power_enabledwhether the electrode can be used in power analyses such as frequency, or frequency-time analyses; this usually requires transforming the electrode raw voltage signals using signal processing methods such as 'Fourier', 'wavelet', 'Hilbert', 'Multitaper', etc.
is_referencewhether this instance is a reference electrode
locationlocation type of the electrode, see
LOCATION_TYPES for details
existswhether electrode exists in subject
preprocess_filepath to preprocess 'HDF5' file
power_filepath to power 'HDF5' file
phase_filepath to phase 'HDF5' file
voltage_filepath to voltage 'HDF5' file
reference_namereference electrode name
epoch_namecurrent epoch name
cache_rootrun-time cache path; NA if epoch or trial
intervals are missing
trial_intervalstrial intervals relative to epoch onset
RAVEAbstarctElectrode$new()constructor
RAVEAbstarctElectrode$new(subject, number, quiet = FALSE)
subjectcharacter or RAVESubject instance
numbercurrent electrode number or reference ID
quietreserved, whether to suppress warning messages
RAVEAbstarctElectrode$set_reference()set reference for instance
RAVEAbstarctElectrode$set_reference(reference)
referenceNULL or RAVEAbstarctElectrode instance
RAVEAbstarctElectrode$set_epoch()set epoch instance for the electrode
RAVEAbstarctElectrode$set_epoch(epoch, stitch_events = NULL)
epochcharacters or RAVEEpoch instance. For
characters, make sure "epoch_<name>.csv" is in meta folder.
stitch_eventsevents to stitch, default is NULL, meaning
when loading data, the time is relative to the trial onset (column
"Time" in the epoch file); set to a character of length 2,
representing the events if time is not relative to trial onset. Please
remove the prefix. For example, for a column named "Event_name",
the event name is "name".
RAVEAbstarctElectrode$clear_cache()method to clear cache on hard drive
RAVEAbstarctElectrode$clear_cache(...)
...implemented by child instances
RAVEAbstarctElectrode$clear_memory()method to clear memory
RAVEAbstarctElectrode$clear_memory(...)
...implemented by child instances
RAVEAbstarctElectrode$load_data_with_epochs()method to load electrode data
RAVEAbstarctElectrode$load_data_with_epochs(type)
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient", or others
depending on child class implementations
RAVEAbstarctElectrode$load_data()alias of load_data_with_epochs for legacy code
RAVEAbstarctElectrode$load_data(type)
typesee load_data_with_epochs
RAVEAbstarctElectrode$load_dimnames_with_epochs()get expected dimension names
RAVEAbstarctElectrode$load_dimnames_with_epochs(type)
typesee load_data_with_epochs
RAVEAbstarctElectrode$load_data_with_blocks()load electrode block-wise data (with reference), useful when epoch is absent
RAVEAbstarctElectrode$load_data_with_blocks(blocks, type, simplify = TRUE)
blockssession blocks
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient".
simplifywhether to simplify the result
If simplify is enabled, and only one block is loaded,
then the result will be a vector (type="voltage") or a matrix
(others), otherwise the result will be a named list where the names
are the blocks.
RAVEAbstarctElectrode$load_blocks()alias of load_data_with_blocks for legacy code
RAVEAbstarctElectrode$load_blocks(blocks, type, simplify = TRUE)
blocks, type, simplifysee load_data_with_blocks
RAVEAbstarctElectrode$load_dim_with_blocks()get expected dimension information for block-based loader
RAVEAbstarctElectrode$load_dim_with_blocks(blocks, type)
blocks, typesee load_data_with_blocks
RAVEAbstarctElectrode$clone()The objects of this class are cloneable with this method.
RAVEAbstarctElectrode$clone(deep = FALSE)
deepWhether to make a deep clone.
if( has_rave_subject("demo/DemoSubject") ) { # To run this example, please download demo subject (~700 MB) from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta generator <- RAVEAbstarctElectrode # load demo subject electrode 14 e <- generator$new("demo/DemoSubject", number = 14) # set epoch e$subject$epoch_names e$set_epoch("auditory_onset") head(e$epoch$table) # set epoch range (-1 to 2 seconds relative to onset) e$trial_intervals <- c(-1,2) # or to set multiple ranges e$trial_intervals <- list(c(-2,-1), c(0, 2)) # set reference e$subject$reference_names reference_table <- e$subject$meta_data( meta_type = "reference", meta_name = "default") ref_name <- subset(reference_table, Electrode == 14)[["Reference"]] # the reference is CAR type, mean of electrode 13-16,24 ref_name # load & set reference ref <- generator$new(e$subject, ref_name) e$set_reference(ref) }if( has_rave_subject("demo/DemoSubject") ) { # To run this example, please download demo subject (~700 MB) from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta generator <- RAVEAbstarctElectrode # load demo subject electrode 14 e <- generator$new("demo/DemoSubject", number = 14) # set epoch e$subject$epoch_names e$set_epoch("auditory_onset") head(e$epoch$table) # set epoch range (-1 to 2 seconds relative to onset) e$trial_intervals <- c(-1,2) # or to set multiple ranges e$trial_intervals <- list(c(-2,-1), c(0, 2)) # set reference e$subject$reference_names reference_table <- e$subject$meta_data( meta_type = "reference", meta_name = "default") ref_name <- subset(reference_table, Electrode == 14)[["Reference"]] # the reference is CAR type, mean of electrode 13-16,24 ref_name # load & set reference ref <- generator$new(e$subject, ref_name) e$set_reference(ref) }
Constant variables
LOCATION_TYPES SIGNAL_TYPES IMPORT_FORMATS YAEL_IMAGE_TYPES MNI305_to_MNI152LOCATION_TYPES SIGNAL_TYPES IMPORT_FORMATS YAEL_IMAGE_TYPES MNI305_to_MNI152
Trial epoch, contains the following information: Block
experiment block/session string; Time trial onset within that block;
Trial trial number; Condition trial condition. Other optional
columns are Event_xxx (starts with "Event"). Column
ExcludedHint (logical, always present; missing or blank values are
FALSE) marks trials that analyses may exclude; see
exclude_trials and save. An epoch whose name ends with
"_OutlierRemoved" is a trimmed copy: marked trials are removed,
trials are renumbered from 1, and OriginalTrial holds the trial
numbers of the epoch it was generated from.
ravepipeline::RAVESerializable -> RAVEEpoch
nameepoch name, character
subjectRAVESubject instance
dataa list of trial information, internally used
tabletrial epoch table
.columnsepoch column names, internally used
columnscolumns of trial table
n_trialstotal number of trials
trialstrial numbers
excluded_trialstrial numbers whose ExcludedHint is
TRUE
available_eventsavailable events other than trial onset
available_condition_typeavailable condition type other than the default
RAVEEpoch$@marshal()Internal method
RAVEEpoch$@marshal(...)
...internal arguments
RAVEEpoch$@unmarshal()Internal method
RAVEEpoch$@unmarshal(object, ...)
object, ...internal arguments
RAVEEpoch$new()constructor
RAVEEpoch$new(subject, name)
subjectRAVESubject instance or character
namecharacter, make sure "epoch_<name>.csv" is in meta
folder
RAVEEpoch$trial_at()get ith trial
RAVEEpoch$trial_at(i, df = TRUE)
itrial number
dfwhether to return as data frame or a list
RAVEEpoch$update_table()manually update table field
RAVEEpoch$update_table()
self$table
RAVEEpoch$set_trial()set one trial
RAVEEpoch$set_trial(Block, Time, Trial, Condition, ...)
Blockblock string
Timetime in second
Trialpositive integer, trial number
Conditioncharacter, trial condition
...other key-value pairs corresponding to other optional columns;
ExcludedHint defaults to FALSE
RAVEEpoch$exclude_trials()Mark trials as excluded through the ExcludedHint
column. Nothing is removed: pipelines decide whether to drop marked
trials. Use save to write the marks to disk.
RAVEEpoch$exclude_trials(..., add = TRUE)
...trial numbers; flattened with unlist(list(...))
addwhether to add to the trials already marked (default);
FALSE replaces them, so exclude_trials(add = FALSE)
clears every mark
The epoch instance, invisibly
RAVEEpoch$save()Save the epoch to the subject's meta folder. A regular
epoch writes epoch_<name>.csv with ExcludedHint (the
existing file is renamed to a time-stamped backup first), then rebuilds
epoch_<name>_OutlierRemoved.csv: the existing copy is always
backed up and removed, and a new one is written when some (not all)
trials are marked, without them, with trials renumbered from 1 and
OriginalTrial holding the trial numbers of
epoch_<name>.csv. An epoch whose name ends with
_OutlierRemoved is saved trimmed the same way: its file is
backed up and removed, then the unmarked trials are written. Its marked
trials, including rows marked by hand in the replaced file, are also
marked in the upstream epoch (the name without the suffix) when that
epoch exists and the trial still matches by Block and
Time; otherwise only the trimmed file is saved.
RAVEEpoch$save()
Paths of the written files, invisibly
RAVEEpoch$get_event_colname()Get epoch column name that represents the desired event
RAVEEpoch$get_event_colname(
event = "",
missing = c("warning", "error", "none")
)
eventa character string of the event, see
$available_events for all available events; set to
"trial onset", "default", or blank to use the default
missingwhat to do if event is missing; default is to warn
If event is one of "trial onset",
"default", "", or NULL, then the result will be
"Time" column; if the event is found, then return will be the
corresponding event column. When the event is not found and
missing is "error", error will be raised; default is
to return "Time" column, as it's trial onset and is mandatory.
RAVEEpoch$get_condition_colname()Get condition column name that represents the desired condition type
RAVEEpoch$get_condition_colname(
condition_type = "default",
missing = c("error", "warning", "none")
)
condition_typea character string of the condition type, see
$available_condition_type for all available condition types;
set to "default" or blank to use the default
missingwhat to do if condition type is missing; default is to warn if the condition column is not found.
If condition_type is one of
"default", "", or NULL, then the result will be
"Condition" column; if the condition type is found, then return
will be the corresponding condition type column. When the condition type
is not found and missing is "error", error will be raised;
default is to return "Condition" column, as it's the default
and is mandatory.
RAVEEpoch$clone()The objects of this class are cloneable with this method.
RAVEEpoch$clone(deep = FALSE)
deepWhether to make a deep clone.
# Please download DemoSubject ~700MB from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if(has_rave_subject("demo/DemoSubject")) { # Load meta/epoch_auditory_onset.csv from subject demo/DemoSubject epoch <-RAVEEpoch$new(subject = 'demo/DemoSubject', name = 'auditory_onset') # first several trials head(epoch$table) # query specific trial old_trial1 <- epoch$trial_at(1) # Create new trial or change existing trial epoch$set_trial(Block = '008', Time = 10, Trial = 1, Condition = 'AknownVmeant') new_trial1 <- epoch$trial_at(1) # Compare new and old trial 1 list(old_trial1, new_trial1) # To get updated trial table, must update first epoch$update_table() head(epoch$table) # Mark trials 1 and 3; pipelines decide whether to drop them epoch$exclude_trials(1, 3) epoch$excluded_trials }# Please download DemoSubject ~700MB from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if(has_rave_subject("demo/DemoSubject")) { # Load meta/epoch_auditory_onset.csv from subject demo/DemoSubject epoch <-RAVEEpoch$new(subject = 'demo/DemoSubject', name = 'auditory_onset') # first several trials head(epoch$table) # query specific trial old_trial1 <- epoch$trial_at(1) # Create new trial or change existing trial epoch$set_trial(Block = '008', Time = 10, Trial = 1, Condition = 'AknownVmeant') new_trial1 <- epoch$trial_at(1) # Compare new and old trial 1 list(old_trial1, new_trial1) # To get updated trial table, must update first epoch$update_table() head(epoch$table) # Mark trials 1 and 3; pipelines decide whether to drop them epoch$exclude_trials(1, 3) epoch$excluded_trials }
R6 class definition
ravepipeline::RAVESerializable -> RAVEPreprocessSettings
current_versioncurrent configuration setting version
pathsettings file path
backup_pathalternative back up path for redundancy checks
datalist of raw configurations, internally used only
subjectRAVESubject instance
read_onlywhether the configuration should be read-only, not yet implemented
versionconfigure version of currently stored files
old_versionwhether settings file is old format
blocksexperiment blocks
electrodeselectrode numbers
sample_ratesvoltage data sample rate
notch_filteredwhether electrodes are notch filtered
has_waveletwhether each electrode has wavelet transforms
data_importedwhether electrodes are imported
data_lockedwhether electrode, blocks and sample rate are locked? usually when an electrode is imported into 'rave', that electrode is locked
electrode_lockedwhether electrode is imported and locked
electrode_composedcomposed electrode channels, not actual physically contacts, but is generated from those physically ones
wavelet_paramswavelet parameters
notch_paramsNotch filter parameters
electrode_typeselectrode signal types
@freeze_blockswhether to free block, internally used
@freeze_lfp_ecogwhether to freeze electrodes that record 'LFP' signals, internally used
@lfp_ecog_sample_rate'LFP' sample rates, internally used
all_blockscharacters, all possible blocks even not included in some projects
raw_path2raw data path, based on the format standard; for native,
this is equivalent to raw_path; for 'BIDS', this is subject raw
directory in 'BIDS' project
raw_path2_typeraw data path type, 'native' or 'bids'
raw_pathlegacy raw data path for 'RAVE', regardless of
raw_path2_type. This field exists for compatibility support
the legacy scripts. Please use raw_path2 combined with
raw_path2_type for supporting 'BIDS' format
raw_path_typelegacy type for raw_path, always returns
'native'
RAVEPreprocessSettings$@marshal()Internal method
RAVEPreprocessSettings$@marshal(...)
...internal arguments
RAVEPreprocessSettings$@unmarshal()Internal method
RAVEPreprocessSettings$@unmarshal(object, ...)
object, ...internal arguments
RAVEPreprocessSettings$new()constructor
RAVEPreprocessSettings$new(subject, read_only = TRUE)
subjectcharacter or RAVESubject instance
read_onlywhether subject should be read-only (not yet implemented)
RAVEPreprocessSettings$valid()whether configuration is valid or not
RAVEPreprocessSettings$valid()
RAVEPreprocessSettings$has_raw()whether raw data folder exists
RAVEPreprocessSettings$has_raw()
RAVEPreprocessSettings$set_blocks()set blocks
RAVEPreprocessSettings$set_blocks(blocks, force = FALSE)
blockscharacter, combination of session task and run
forcewhether to ignore checking. Only used when data structure is not native, for example, 'BIDS' format
RAVEPreprocessSettings$get_block_paths()get block-related files
RAVEPreprocessSettings$get_block_paths( block, force_native = FALSE, check = TRUE )
blockblock names (for all available blocks, see all_blocks)
force_nativewhether to ignore the format standard, such as 'BIDS' and force return the native paths; default is false
checkwhether to check the file paths to make sure the returned paths are valid; default is true
RAVEPreprocessSettings$set_electrodes()set electrodes
RAVEPreprocessSettings$set_electrodes( electrodes, type = SIGNAL_TYPES, add = FALSE )
electrodesinteger vectors
typesignal type of electrodes, see SIGNAL_TYPES
addwhether to add to current settings
RAVEPreprocessSettings$set_sample_rates()set sample frequency
RAVEPreprocessSettings$set_sample_rates(srate, type = SIGNAL_TYPES)
sratesample rate, must be positive number
typeelectrode type to set sample rate. In 'rave', all electrodes with the same signal type must have the same sample rate.
RAVEPreprocessSettings$migrate()convert old format to new formats
RAVEPreprocessSettings$migrate(force = FALSE)
forcewhether to force migrate and save settings
RAVEPreprocessSettings$electrode_info()get electrode information
RAVEPreprocessSettings$electrode_info(electrode)
electrodeinteger
list of electrode type, number, etc.
RAVEPreprocessSettings$save()save settings to hard disk
RAVEPreprocessSettings$save()
RAVEPreprocessSettings$get_compose_weights()get weights of each composed channels
RAVEPreprocessSettings$get_compose_weights(flat = TRUE)
flatwhether to flatten the data frame; default is true
NULL when no channel is composed.
When flat is TRUE, a data frame of weights with
the columns composing electrode channel numbers, composed channel
number, and corresponding weights; if flat is FALSE,
then a weight matrix;
RAVEPreprocessSettings$clone()The objects of this class are cloneable with this method.
RAVEPreprocessSettings$clone(deep = FALSE)
deepWhether to make a deep clone.
# The following example require downloading demo subject (~700 MB) from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if( has_rave_subject("demo/DemoSubject") ) { conf <- RAVEPreprocessSettings$new(subject = 'demo/DemoSubject') conf$blocks # "008" "010" "011" "012" conf$electrodes # 5 electrodes # Electrode 14 information conf$electrode_info(electrode = 14) conf$data_imported # All 5 electrodes are imported conf$data_locked # Whether block, sample rates should be locked }# The following example require downloading demo subject (~700 MB) from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if( has_rave_subject("demo/DemoSubject") ) { conf <- RAVEPreprocessSettings$new(subject = 'demo/DemoSubject') conf$blocks # "008" "010" "011" "012" conf$electrodes # 5 electrodes # Electrode 14 information conf$electrode_info(electrode = 14) conf$data_imported # All 5 electrodes are imported conf$data_locked # Whether block, sample rates should be locked }
See as_rave_project for creating 'RAVE' project
class
ravepipeline::RAVESerializable -> RAVEProject
pathproject folder, absolute path
nameproject name, character
pipeline_pathpath to pipeline scripts under project's folder
format_standardstorage format, can be either 'native' or
'bids'-compliant
@implthe internal object
RAVEProject$@marshal()Internal method
RAVEProject$@marshal(...)
...internal arguments
RAVEProject$@unmarshal()Internal method
RAVEProject$@unmarshal(object, ...)
object, ...internal arguments
RAVEProject$print()override print method
RAVEProject$print(...)
...ignored
RAVEProject$format()override format method
RAVEProject$format(...)
...ignored
RAVEProject$new()constructor
RAVEProject$new(project_name, strict = TRUE, parent_path = NULL)
project_namecharacter
strictwhether to check project path
parent_pathNULL, a path to the project parent folder
for native projects, or the path to 'BIDS' root directory.
RAVEProject$subjects()get all imported subjects within project
RAVEProject$subjects()
character vector
RAVEProject$has_subject()whether a specific subject exists in this project
RAVEProject$has_subject(subject_code)
subject_codecharacter, subject name
true or false whether subject is in the project
RAVEProject$group_path()get group data path for 'RAVE' module
RAVEProject$group_path(module_id, must_work = FALSE)
module_idcharacter, 'RAVE' module ID
must_workwhether the directory must exist; if not exists, should a new one be created?
RAVEProject$subject_pipelines()list saved pipelines
RAVEProject$subject_pipelines( pipeline_name, cache = FALSE, check = TRUE, all = FALSE )
pipeline_namename of the pipeline
cachewhether to use cached registry
checkwhether to check if the pipelines exist as directories
allwhether to list all pipelines; default is false; pipelines with the same label but older time-stamps will be hidden
A data table of pipeline time-stamps and directories
RAVEProject$clone()The objects of this class are cloneable with this method.
RAVEProject$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class definition
ravepipeline::RAVESerializable -> RAVESubject
@implthe internal object
projectproject instance of current subject; see
RAVEProject
project_namecharacter string of project name
subject_codecharacter string of subject code
subject_idsubject ID: "project/subject"
pathsubject root path
rave_path'rave' directory under subject root path
meta_pathmeta data directory for current subject
imaging_pathroot path to imaging processing folder
freesurfer_path'FreeSurfer' directory for current subject. If
no path exists, values will be NA
preprocess_pathpreprocess directory under subject 'rave' path
data_pathdata directory under subject 'rave' path
cache_pathpath to 'FST' copies under subject 'data' path
pipeline_pathpath to pipeline scripts under subject's folder
report_pathpath to pipeline scripts under subject's folder
note_pathpath that stores 'RAVE' related subject notes
epoch_namespossible epoch names
reference_namespossible reference names
reference_pathreference path under 'rave' folder
preprocess_settingspreprocess instance; see
RAVEPreprocessSettings
blockssubject experiment blocks in current project
electrodesall electrodes, no matter excluded or not
raw_sample_ratesvoltage sample rate
power_sample_ratepower spectrum sample rate
has_waveletwhether electrodes have wavelet transforms
notch_filteredwhether electrodes are Notch-filtered
electrode_typeselectrode signal types
electrode_composedcomposed electrode channels, not actual physically contacts, but is generated from those physically ones
RAVESubject$@marshal()Internal method
RAVESubject$@marshal(...)
...internal arguments
RAVESubject$@unmarshal()Internal method
RAVESubject$@unmarshal(object, ...)
object, ...internal arguments
RAVESubject$print()override print method: prints format()
RAVESubject$print(...)
...passed to format()
RAVESubject$format()summary of the subject's data
RAVESubject$format(...)
...ignored
A character vector, one element per line
RAVESubject$new()constructor
RAVESubject$new( project_name, subject_code = NULL, strict = TRUE, parent_path = NULL )
project_namecharacter project name
subject_codecharacter subject code
strictwhether to check if subject folders exist
parent_pathparent path if no default path is used, this is for the root directory if subject is in 'BIDS' format
RAVESubject$meta_data()get subject meta data located in "meta/" folder
RAVESubject$meta_data(
meta_type = c("electrodes", "frequencies", "time_points", "epoch", "references"),
meta_name = "default",
strict = TRUE
)
meta_typechoices are 'electrodes', 'frequencies', 'time_points', 'epoch', 'references'
meta_nameif meta_type='epoch', read in
'epoch_<meta_name>.csv'; if meta_type='references',
read in 'reference_<meta_name>.csv'.
strictwhether to raise errors if the files are missing; default
is true; alternative is to return NULL on missing
data frame
RAVESubject$valid_electrodes()get valid electrode numbers
RAVESubject$valid_electrodes(reference_name = NULL, refresh = FALSE)
reference_namecharacter, reference name, see meta_name
in self$meta_data or load_meta2 when
meta_type is 'reference'
refreshwhether to reload reference table before obtaining data, default is false
integer vector of valid electrodes
RAVESubject$initialize_paths()create subject's directories on hard disk
RAVESubject$initialize_paths(include_freesurfer = TRUE)
include_freesurferwhether to create 'FreeSurfer' path
RAVESubject$set_default()set default key-value pair for the subject, used by 'RAVE' modules
RAVESubject$set_default(key, value, namespace = "default")
keycharacter
valuevalue of the key
namespacefile name of the note (without post-fix)
The same as value
RAVESubject$get_default()get default key-value pairs for the subject, used by 'RAVE' modules
RAVESubject$get_default( ..., default_if_missing = NULL, simplify = TRUE, namespace = "default" )
...single key, or a vector of character keys
default_if_missingdefault value is any key is missing
simplifywhether to simplify the results if there is only one key
to fetch; default is TRUE
namespacefile name of the note (without post-fix)
A named list of key-value pairs, or if one key is specified and
simplify=TRUE, then only the value will be returned.
RAVESubject$get_note_summary()get summary table of all the key-value pairs used by 'RAVE' modules for the subject
RAVESubject$get_note_summary(namespaces, include_history = FALSE)
namespacesnamespaces for the entries; see method
get_default or set_default. Default is all possible
namespaces
include_historywhether to include history entries; default is false
A data frame with four columns: 'namespace' for the group
name of the entry (entries within the same namespace usually share same
module), 'timestamp' for when the entry was registered.
'entry_name' is the name of the entry. If include_history
is true, then multiple entries with the same 'entry_name' might
appear since the obsolete entries are included. 'entry_value'
is the value of the corresponding entry.
RAVESubject$get_epoch()check and get subject's epoch information
RAVESubject$get_epoch( epoch_name = "default", as_table = FALSE, trial_starts = 0 )
epoch_nameepoch name, depending on the subject's meta files
as_tablewhether to convert to data.frame; default
is false
trial_startsthe start of the trial relative to epoch time; default is 0
If as_table is FALSE, then returns as
RAVEEpoch instance; otherwise returns epoch table; will
raise errors when file is missing or the epoch is invalid.
RAVESubject$get_reference()check and get subject's reference information
RAVESubject$get_reference(reference_name, simplify = FALSE)
reference_namereference name, depending on the subject's meta file settings
simplifywhether to only return the reference column
If simplify is true, returns a vector of reference
electrode names, otherwise returns the whole table; will
raise errors when file is missing or the reference is invalid.
RAVESubject$get_electrode_table()check and get subject's electrode table with electrodes that are load-able
RAVESubject$get_electrode_table( electrodes, reference_name, subset = FALSE, simplify = FALSE, warn = TRUE )
electrodescharacters indicating integers such as
"1-14,20-30", or integer vector of electrode numbers
reference_namesee method get_reference
subsetwhether to subset the resulting data table
simplifywhether to only return electrodes
warnwhether to warn about missing electrodes; default is true
If simplify is true, returns a vector of electrodes
that are valid (or won't be excluded) under given reference; otherwise
returns a table. If subset is true, then the table will be
subset and only rows with electrodes to be loaded will be kept.
RAVESubject$get_frequency()check and get subject's frequency table, time-frequency decomposition is needed.
RAVESubject$get_frequency(simplify = TRUE)
simplifywhether to simplify as vector
If simplify is true, returns a vector of frequencies;
otherwise returns a table.
RAVESubject$list_pipelines()list saved pipelines
RAVESubject$list_pipelines( pipeline_name, cache = FALSE, check = TRUE, all = FALSE )
pipeline_namepipeline ID
cachewhether to use cache registry to speed up
checkwhether to check if the pipelines exist
allwhether to list all pipelines; default is false; pipelines with the same label but older time-stamps will be hidden
A table of pipeline registry
RAVESubject$load_pipeline()load saved pipeline
RAVESubject$load_pipeline(directory)
directorypipeline directory name
A PipelineTools instance
RAVESubject$clone()The objects of this class are cloneable with this method.
RAVESubject$clone(deep = FALSE)
deepWhether to make a deep clone.
The class is for creating child classes, to instantiate the class,
please use prepare_subject_bare0 to create base repository.
ravepipeline::RAVESerializable -> RAVESubjectRepository
@restoredinternal flag indicating whether the repository is restored from serialization. Repositories restored from serialization will behave differently (slightly) for performance considerations
repository_idrepository identifier, typically generated with random string
quietwhether to suppress update warning messages, when requested electrodes are not fully processed or excluded
auto_excludewhether to automatically discard channels that are marked as "excluded" (such as bad channels or channels that should not be analyzed); default is often true
meta_infolist of meta information
needs_updatewrite-only attribute when subject needs to be
reloaded from the disk and reference table needs to be updated, use
repo$needs_update <- TRUE
projectproject instance, see RAVEProject
subjectsubject instance, see RAVESubject
electrode_listinteger vector of electrodes included
electrode_tablethe entire electrode table
electrode_signal_typesmore accurate name should be "channel"
signal types: currently returns 'LFP', 'Auxiliary', or
'Spike', for each channel
electrode_instanceselectrode channel instance helpers for loading electrode data
reference_namename of reference table
reference_tablereference table
references_lista vector of reference channel names, used together
with reference_instances
reference_instancesinstances of reference channels, for
referencing on the fly, used for electrode_instances
digest_keya list of repository data used to generate repository signature
signaturesignature of the repository, two repositories might
share the same signature if their contents are the same (even with
different identifiers); generated from digest_key
RAVESubjectRepository$@get_container()Internal method, do not use it directly
RAVESubjectRepository$@get_container()
RAVESubjectRepository$@marshal()Internal method
RAVESubjectRepository$@marshal(...)
...internal arguments
RAVESubjectRepository$@unmarshal()Internal method
RAVESubjectRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRepository$print()User-friendly print method
RAVESubjectRepository$print()
RAVESubjectRepository$new()constructor
RAVESubjectRepository$new( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = TRUE, quiet = TRUE, repository_id = NULL, strict = TRUE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
...reserved, currently ignored
auto_excludewhether to automatically discard bad channels
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
.classinternally used, do not set, even if you know what this is
RAVESubjectRepository$export_matlab()Export the repository to 'Matlab' for future analysis
RAVESubjectRepository$export_matlab(..., verbose = TRUE)
...reserved for child classes
verboseprint progresses
The root directory where the files are stored.
RAVESubjectRepository$get_electrode_coordinate()Get loaded electrode coordinates by type
RAVESubjectRepository$get_electrode_coordinate( type = "LFP", electrodes = KEY_MISSING, strict = TRUE )
typelength of one or more, electrode channel (signal) type;
see constant SIGNAL_TYPES. Default is 'LFP'
electrodeselectrodes to subset, default is a missing key, which uses all the loaded electrodes to subset
strictwhether the returned table must not be empty; default is true, which will raise errors when no electrode matches
Filtered table; see load_meta2 with meta type
'electrodes'. Besides the mandatory columns, the returned table
also contains 'LabelPrefix', used by YAEL to store surgical
labels to group channels by electrode device; 'LeadChannel'
(logical) to indicate whether the channel is a leading channel in this
group, typically the inner-most channel; and 'ShortLabel' for
short electrode label.
RAVESubjectRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochTimeFreqBaseRepository}, with epoch
trials, and is intended for loading processed and referenced time-frequency
coefficients.
Use prepare_subject_phase_with_epochs to create an
instance.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochPhaseRepository
phasea named map of time-frequency coefficient phase,
mounted by mount_data
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochTimeFreqBaseRepository$mount_data()RAVESubjectEpochPhaseRepository$@marshal()Internal method
RAVESubjectEpochPhaseRepository$@marshal(...)
...internal arguments
RAVESubjectEpochPhaseRepository$@unmarshal()Internal method
RAVESubjectEpochPhaseRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochPhaseRepository$new()constructor
RAVESubjectEpochPhaseRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectEpochTimeFreqBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay mount_data;
default is false
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochPhaseRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochPhaseRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochTimeFreqBaseRepository}, with epoch
trials, and is intended for loading processed and referenced time-frequency
coefficients.
Use prepare_subject_power_with_epochs to create an
instance.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochPowerRepository
powera named map of time-frequency power spectrogram,
mounted by mount_data
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochTimeFreqBaseRepository$mount_data()RAVESubjectEpochPowerRepository$@marshal()Internal method
RAVESubjectEpochPowerRepository$@marshal(...)
...internal arguments
RAVESubjectEpochPowerRepository$@unmarshal()Internal method
RAVESubjectEpochPowerRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochPowerRepository$new()constructor
RAVESubjectEpochPowerRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectEpochTimeFreqBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay mount_data;
default is false
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochPowerRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochPowerRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochRepository}, with epoch
trials, and is intended for loading raw (without any processing or reference)
voltage signals.
Use prepare_subject_raw_voltage_with_epochs to create an
instance.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochRawVoltageRepository
digest_keya list of repository data used to generate repository signature
raw_voltagea named map of raw voltage data, mounted by
mount_data, alias of get_container
reference_tablereference table, all channels will be marked as no reference
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochRawVoltageRepository$@marshal()Internal method
RAVESubjectEpochRawVoltageRepository$@marshal(...)
...internal arguments
RAVESubjectEpochRawVoltageRepository$@unmarshal()Internal method
RAVESubjectEpochRawVoltageRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochRawVoltageRepository$new()constructor
RAVESubjectEpochRawVoltageRepository$new( subject, electrodes = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, reference_name = "noref", .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectEpochRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay calling mount_data;
default is false
reference_nameignored, always 'noref' for raw voltage
data
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochRawVoltageRepository$mount_data()function to mount raw voltage signals
RAVESubjectEpochRawVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true
electrodeselectrodes to update for expert-use use; default is
NULL (all electrode channels will be mounted)
RAVESubjectEpochRawVoltageRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochRawVoltageRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
Compared to RAVESubjectBaseRepository, this repository
requires epoch information. please use
prepare_subject_with_epochs to instantiate this repository.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository
needs_updatewrite-only attribute when subject needs to be
reloaded from the disk and reference table needs to be updated, use
repo$needs_update <- TRUE
meta_infolist of meta information
sample_ratesa named list of sampling frequencies; the names
are signal types ('LFP', 'Auxiliary', or 'Spike')
and the values are the sampling frequencies
sample_ratea single number of the sample rate; if the electrode
channels contain local-field potential 'LFP' signal type, then
the sample rate is the 'LFP' sample rate; otherwise the
sample rate is 'Spike' channel sample rate, if exists, or whatever
comes first. This field is for backward compatibility support, use
sample_rates for more accurate number
epoch_namename of the epoch table
epochRAVEEpoch instance
epoch_tableepoch table, equivalent to
repository$epoch$table
stitch_eventsevents where time_windows are based on
time_windowslist of time ranges to load; the time is relative
to stitch_events; default is trial onset
electrode_tablethe entire electrode table with reference information
electrode_instanceselectrode channel instance helpers for loading electrode data
reference_instancesinstances of reference channels, for
referencing on the fly, used for electrode_instances
digest_keya list of repository data used to generate repository signature
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$@marshal()Internal method
RAVESubjectEpochRepository$@marshal(...)
...internal arguments
RAVESubjectEpochRepository$@unmarshal()Internal method
RAVESubjectEpochRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochRepository$new()constructor
RAVESubjectEpochRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochRepository$export_matlab()Export the repository to 'Matlab' for future analysis
RAVESubjectEpochRepository$export_matlab(..., verbose = TRUE)
...reserved for child classes
verboseprint progresses
The root directory where the files are stored.
RAVESubjectEpochRepository$set_epoch()change trial epoch profiles
RAVESubjectEpochRepository$set_epoch(epoch_name, stitch_events = NULL)
epoch_namename of epoch table
stitch_eventsevents to stitch
RAVESubjectEpochRepository$mount_data()function to mount data, not doing anything in this class, but may be used by child classes
RAVESubjectEpochRepository$mount_data(..., force = TRUE, electrodes = NULL)
...reserved
forceforce update data; default is true
electrodeselectrodes to update; default is NULL (all
electrode channels)
RAVESubjectEpochRepository$get_container()get container where loaded data are stored
RAVESubjectEpochRepository$get_container(force = FALSE, ...)
force, ...passed to mount_data
A named map, typically with data arrays, shape/dimension information
RAVESubjectEpochRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochRepository}, with epoch
trials, and is intended for loading processed and referenced time-frequency
coefficients.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository
sample_ratetime-frequency coefficient sample rate
frequencyfrequencies where the time-frequency coefficients are evaluated
timetime in seconds for each trial
time_pointssee time field, existed for backward
compatibility
signal_typedo not use
digest_keya list of repository data used to generate repository signature
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochTimeFreqBaseRepository$@marshal()Internal method
RAVESubjectEpochTimeFreqBaseRepository$@marshal(...)
...internal arguments
RAVESubjectEpochTimeFreqBaseRepository$@unmarshal()Internal method
RAVESubjectEpochTimeFreqBaseRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochTimeFreqBaseRepository$new()constructor
RAVESubjectEpochTimeFreqBaseRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, data_type = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
data_typefor child classes to fill; data type (power, phase, or complex time-frequency coefficients)
...passed to RAVESubjectEpochRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay mount_data;
default is false
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochTimeFreqBaseRepository$mount_data()function to mount processed and referenced spectrogram
RAVESubjectEpochTimeFreqBaseRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true
electrodeselectrodes to update for expert-use use; default is
NULL (all electrode channels will be mounted)
RAVESubjectEpochTimeFreqBaseRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochTimeFreqBaseRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochTimeFreqBaseRepository}, with epoch
trials, and is intended for loading processed and referenced time-frequency
coefficients.
Use prepare_subject_time_frequency_coefficients_with_epochs to create an
instance.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochTimeFreqCoefRepository
coefficientsa named map of time-frequency coefficient data,
mounted by mount_data
waveletnot used anymore, see coefficients
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochTimeFreqBaseRepository$mount_data()RAVESubjectEpochTimeFreqCoefRepository$@marshal()Internal method
RAVESubjectEpochTimeFreqCoefRepository$@marshal(...)
...internal arguments
RAVESubjectEpochTimeFreqCoefRepository$@unmarshal()Internal method
RAVESubjectEpochTimeFreqCoefRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochTimeFreqCoefRepository$new()constructor
RAVESubjectEpochTimeFreqCoefRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectEpochTimeFreqBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay mount_data;
default is false
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochTimeFreqCoefRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochTimeFreqCoefRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
The repository inherits link{RAVESubjectEpochRepository}, with epoch
trials, and is intended for loading processed and referenced voltage
signals.
Use prepare_subject_voltage_with_epochs to create an
instance.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochVoltageRepository
digest_keya list of repository data used to generate repository signature
voltagea named map of voltage data, mounted by
mount_data
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectEpochRepository$export_matlab()RAVESubjectEpochRepository$get_container()RAVESubjectEpochRepository$set_epoch()RAVESubjectEpochVoltageRepository$@marshal()Internal method
RAVESubjectEpochVoltageRepository$@marshal(...)
...internal arguments
RAVESubjectEpochVoltageRepository$@unmarshal()Internal method
RAVESubjectEpochVoltageRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectEpochVoltageRepository$new()constructor
RAVESubjectEpochVoltageRepository$new( subject, electrodes = NULL, reference_name = NULL, epoch_name = NULL, time_windows = NULL, stitch_events = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
epoch_namename of the epoch trial table
time_windowsnumeric vector with even lengths, the time start
and end of the trials, for example, c(-1, 2) means load
1 second before the trial onset and 2 seconds after trial onset
stitch_eventsevents where the time_windows is based;
default is trial onset (NULL)
...passed to RAVESubjectEpochRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay mount_data;
default is false
.classinternally used, do not set, even if you know what this is
RAVESubjectEpochVoltageRepository$mount_data()function to mount referenced voltage signals
RAVESubjectEpochVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true
electrodeselectrodes to update for expert-use use; default is
NULL (all electrode channels will be mounted)
RAVESubjectEpochVoltageRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectEpochVoltageRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
Loads time-frequency phase
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockPhaseRepository
phasedata container, alias of get_container
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()RAVESubjectRecordingBlockPhaseRepository$@marshal()Internal method
RAVESubjectRecordingBlockPhaseRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockPhaseRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockPhaseRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockPhaseRepository$new()constructor
RAVESubjectRecordingBlockPhaseRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockPhaseRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockPhaseRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
prepare_subject_phase_with_blocks
Loads time-frequency power
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockPowerRepository
powerdata container, alias of get_container
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()RAVESubjectRecordingBlockPowerRepository$@marshal()Internal method
RAVESubjectRecordingBlockPowerRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockPowerRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockPowerRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockPowerRepository$new()constructor
RAVESubjectRecordingBlockPowerRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockPowerRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockPowerRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
prepare_subject_power_with_blocks
Compared to RAVESubjectBaseRepository, this repository
loads the entire voltage traces for selected blocks; use
prepare_subject_raw_voltage_with_blocks to instantiate this
repository.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockRawVoltageRepository
reference_namename of reference table; always 'noref'
reference_tablereference table; a reference table with
'noref' on all channels
references_lista vector of reference channel names;
always 'noref'
reference_instancesinstances of reference channels, empty in this type of repositories
sample_ratesa named list of sampling frequencies; the names
are signal types ('LFP', 'Auxiliary', or 'Spike')
and the values are the sampling frequencies
raw_voltagedata container, alias of get_container
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockRawVoltageRepository$@marshal()Internal method
RAVESubjectRecordingBlockRawVoltageRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockRawVoltageRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockRawVoltageRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockRawVoltageRepository$new()constructor
RAVESubjectRecordingBlockRawVoltageRepository$new( subject, electrodes = NULL, reference_name = "noref", blocks = NULL, downsample = NA, ..., quiet = TRUE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namealways 'noref' (no reference); trying to
set to other values will result in a warning
blocksname of the recording blocks to load
downsampledown-sample rate by this integer number to save space
and speed up computation; typically 'ERP' signals do not need super
high sampling frequencies to load; default is NA and no
down-sample is performed.
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockRawVoltageRepository$mount_data()function to mount data
RAVESubjectRecordingBlockRawVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true; set to false to use cache
electrodeselectrodes to update; default is NULL (all
electrode channels)
RAVESubjectRecordingBlockRawVoltageRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockRawVoltageRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
prepare_subject_raw_voltage_with_blocks
Compared to RAVESubjectBaseRepository, this repository
requires specifying block information. please use
prepare_subject_with_blocks to instantiate this repository.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository
meta_infolist of meta information
needs_updatewrite-only attribute when subject needs to be
reloaded from the disk and reference table needs to be updated, use
repo$needs_update <- TRUE
blocksnames of recording blocks
electrode_tablethe entire electrode table with reference information
digest_keya list of repository data used to generate repository signature
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$@marshal()Internal method
RAVESubjectRecordingBlockRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockRepository$new()constructor
RAVESubjectRecordingBlockRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockRepository$export_matlab()Export the repository to 'Matlab' for future analysis
RAVESubjectRecordingBlockRepository$export_matlab(..., verbose = TRUE)
...reserved for child classes
verboseprint progresses
The root directory where the files are stored.
RAVESubjectRecordingBlockRepository$get_container()get container where loaded data are stored
RAVESubjectRecordingBlockRepository$get_container(force = FALSE, ...)
force, ...passed to mount_data
A named map, typically with data arrays, shape/dimension information
RAVESubjectRecordingBlockRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
'RAVE' class for loading entire block of time-frequency coefficients
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository
sample_ratesa named list of sampling frequencies; the names
are signal types ('LFP', 'Auxiliary', or 'Spike')
and the values are the sampling frequencies
sample_ratenumeric sample rate for 'spectrogram'
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal()
RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockTimeFreqBaseRepository$@marshal()Internal method
RAVESubjectRecordingBlockTimeFreqBaseRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockTimeFreqBaseRepository$new()constructor
RAVESubjectRecordingBlockTimeFreqBaseRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()function to mount data
RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true; set to false to use cache
electrodeselectrodes to update; default is NULL (all
electrode channels)
RAVESubjectRecordingBlockTimeFreqBaseRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockTimeFreqBaseRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
Loads time-frequency coefficients (complex numbers)
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockTimeFreqCoefRepository
coefficientsdata container, alias of get_container
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()RAVESubjectRecordingBlockTimeFreqCoefRepository$@marshal()Internal method
RAVESubjectRecordingBlockTimeFreqCoefRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockTimeFreqCoefRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockTimeFreqCoefRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockTimeFreqCoefRepository$new()constructor
RAVESubjectRecordingBlockTimeFreqCoefRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockTimeFreqCoefRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockTimeFreqCoefRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
prepare_subject_time_frequency_coefficients_with_blocks
Compared to RAVESubjectBaseRepository, this repository
loads the entire voltage traces for selected blocks; use
prepare_subject_voltage_with_blocks to instantiate this
repository.
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockVoltageRepository
sample_ratesa named list of sampling frequencies; the names
are signal types ('LFP', 'Auxiliary', or 'Spike')
and the values are the sampling frequencies
voltagedata container, alias of get_container
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()RAVESubjectRecordingBlockVoltageRepository$@marshal()Internal method
RAVESubjectRecordingBlockVoltageRepository$@marshal(...)
...internal arguments
RAVESubjectRecordingBlockVoltageRepository$@unmarshal()Internal method
RAVESubjectRecordingBlockVoltageRepository$@unmarshal(object, ...)
object, ...internal arguments
RAVESubjectRecordingBlockVoltageRepository$new()constructor
RAVESubjectRecordingBlockVoltageRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
subject'RAVE' subject
electrodesstring or integers indicating electrodes to load
reference_namename of the reference table
blocksname of the recording blocks to load
downsampledown-sample rate by this integer number to save space
and speed up computation; typically 'ERP' signals do not need super
high sampling frequencies to load; default is NA and no
down-sample is performed.
...passed to RAVESubjectBaseRepository constructor
quietsee field quiet
repository_idsee field repository_id
strictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay (lazy) the evaluation mount_data
.classinternally used, do not set, even if you know what this is
RAVESubjectRecordingBlockVoltageRepository$mount_data()function to mount data
RAVESubjectRecordingBlockVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
...reserved
forceforce update data; default is true; set to false to use cache
electrodeselectrodes to update; default is NULL (all
electrode channels)
RAVESubjectRecordingBlockVoltageRepository$clone()The objects of this class are cloneable with this method.
RAVESubjectRecordingBlockVoltageRepository$clone(deep = FALSE)
deepWhether to make a deep clone.
prepare_subject_voltage_with_blocks
'RAVE' arrays loaded with a trial epoch are locked to the trial onset.
realign_trials time-locks them to another event instead (for
example a button press),
shifting each trial along the time margin by
event time - trial onset, such that the event occurs at time zero.
Samples exposed at the edges by the shift are filled with NA.
realign_trials( x, event, epoch, sample_rate, time_margin = NA, trial_margin = NA, strict = TRUE, .filebase = tempfile() )realign_trials( x, event, epoch, sample_rate, time_margin = NA, trial_margin = NA, strict = TRUE, .filebase = tempfile() )
x |
an array, a |
event |
character, name of the event to align to; the corresponding
epoch column is resolved by |
epoch |
a |
sample_rate |
sampling frequency, in 'Hz'; used to convert the time differences into integer sample shifts |
time_margin, trial_margin
|
integers, which margins of |
strict |
whether to be strict about the inputs; when |
.filebase |
where to store the resulting file array; the path is
removed first if it already exists. Passing the file base of |
A FileArray-class instance with the same
dimensions and dimnames as x, whose samples are shifted such
that event occurs at time zero; the samples exposed at the trial
edges are NA. The result is read-only, unless it was written in
place, in which case it keeps the mode of x.
The time dimnames are not relabeled: they remain the
original onset-locked time points, now to be read as relative to
event. The following headers are attached, and can be read back with
$get_header:
original_time_rangerange of the time points, in seconds
time_shift_rangerange of the applied shifts, in seconds
valid_time_rangerange of the time points for which no trial
is NA; useful to crop the result before plotting or averaging
sample_ratethe sample_rate used
signature_shift_amount, signature
digests identifying the applied shifts and the result
# Please download DemoSubject ~700MB from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_voltage_with_epochs( "demo/DemoSubject", electrodes = 14, reference_name = "default", epoch_name = "auditory_onset", time_windows = c(-1, 2)) # The demo epoch only contains the trial onset; add a synthetic # response time, 0.1-0.5 seconds after each onset, to align to epoch <- repository$epoch set.seed(1) epoch$table$Event_response <- epoch$table$Time + round(runif(nrow(epoch$table), 0.1, 0.5), 3) epoch$.columns <- unique(c(epoch$.columns, "Event_response")) epoch$available_events # Time x Trial x Electrode voltage <- repository$voltage$data_list$e_14 dim(voltage) aligned <- realign_trials( voltage, event = "response", epoch = epoch, sample_rate = repository$sample_rate) # Trials are now locked to the response instead of the onset aligned$get_header("time_shift_range") # Time points where no trial has been shifted out of range valid_time_range <- aligned$get_header("valid_time_range") valid_time_range # Crop to the valid window before averaging over trials time_points <- as.numeric(dimnames(aligned)$Time) keep <- time_points >= valid_time_range[[1]] & time_points <= valid_time_range[[2]] plot(time_points[keep], rowMeans(aligned[keep, , 1]), type = "l", xlab = "Time to response (s)", ylab = "Voltage", main = "Response-locked average") abline(v = 0, lty = 2) # clean up aligned$.mode <- "readwrite" aligned$delete(force = TRUE) }# Please download DemoSubject ~700MB from # https://github.com/beauchamplab/rave/releases/tag/v0.1.9-beta if( has_rave_subject("demo/DemoSubject") ) { repository <- prepare_subject_voltage_with_epochs( "demo/DemoSubject", electrodes = 14, reference_name = "default", epoch_name = "auditory_onset", time_windows = c(-1, 2)) # The demo epoch only contains the trial onset; add a synthetic # response time, 0.1-0.5 seconds after each onset, to align to epoch <- repository$epoch set.seed(1) epoch$table$Event_response <- epoch$table$Time + round(runif(nrow(epoch$table), 0.1, 0.5), 3) epoch$.columns <- unique(c(epoch$.columns, "Event_response")) epoch$available_events # Time x Trial x Electrode voltage <- repository$voltage$data_list$e_14 dim(voltage) aligned <- realign_trials( voltage, event = "response", epoch = epoch, sample_rate = repository$sample_rate) # Trials are now locked to the response instead of the onset aligned$get_header("time_shift_range") # Time points where no trial has been shifted out of range valid_time_range <- aligned$get_header("valid_time_range") valid_time_range # Crop to the valid window before averaging over trials time_points <- as.numeric(dimnames(aligned)$Time) keep <- time_points >= valid_time_range[[1]] & time_points <= valid_time_range[[2]] plot(time_points[keep], rowMeans(aligned[keep, , 1]), type = "l", xlab = "Time to response (s)", ylab = "Voltage", main = "Response-locked average") abline(v = 0, lty = 2) # clean up aligned$.mode <- "readwrite" aligned$delete(force = TRUE) }
YAEL-reg3d engineAligns the 'CT' to the 'MRI' with
register_volume3d, which is built into 'RAVE' and
needs no external program. The images are registered and saved at their
original resolution. Please use
cmd_run_reg3d_rigid from pipelines: it saves a script that runs
reg3d_rigid and records the results for the electrode localization.
reg3d_rigid( ct_path, mri_path, coreg_path, reg_type = c("Rigid", "DenseRigid", "FastRigid"), cost = c("mattes", "cc"), interp = c("trilinear", "bspline", "nearest"), verbose = TRUE, ... ) cmd_run_reg3d_rigid( subject, ct_path, mri_path, reg_type = c("Rigid", "DenseRigid", "FastRigid"), cost = c("mattes", "cc"), interp = c("trilinear", "bspline", "nearest"), verbose = TRUE, dry_run = FALSE )reg3d_rigid( ct_path, mri_path, coreg_path, reg_type = c("Rigid", "DenseRigid", "FastRigid"), cost = c("mattes", "cc"), interp = c("trilinear", "bspline", "nearest"), verbose = TRUE, ... ) cmd_run_reg3d_rigid( subject, ct_path, mri_path, reg_type = c("Rigid", "DenseRigid", "FastRigid"), cost = c("mattes", "cc"), interp = c("trilinear", "bspline", "nearest"), verbose = TRUE, dry_run = FALSE )
ct_path, mri_path
|
absolute paths to 'CT' and 'MR' image files |
coreg_path |
directory where the results are saved; required. An existing directory is backed up (renamed) once the new results are complete, so a failed registration leaves it untouched |
reg_type |
registration preset; choices are |
cost |
cost function; choices are |
interp |
interpolation used to re-sample the 'CT' onto the 'MRI' grid
( |
verbose |
whether to print the registration progress |
... |
passed to |
subject |
'RAVE' subject |
dry_run |
whether to only build the script without running it; default is false |
reg3d_rigid invisibly returns a list with the result
directory (coreg_path) and the names of the files in it:
'CT_RAW.nii.gz', 'MRI_reference.nii.gz'
the 'CT' and 'MR' images at their original resolution
'ct_in_t1.nii.gz'the 'CT' re-sampled onto the grid of
'MRI_reference.nii.gz'
'CT_RAS_to_MR_RAS.txt'transform from the 'CT' scanner 'RAS' to the 'MR' scanner 'RAS' coordinates
'CT_IJK_to_MR_RAS.txt'transform from the voxel indices of
'CT_RAW.nii.gz' (starting from 0) to the 'MR' scanner 'RAS'
coordinates
'reg3d/reg3d.dcf'registration record written by
save_registration, with the 'ANTs'-style affine
transform 'reg3d/reg3d0GenericAffine.mat'
cmd_run_reg3d_rigid returns a list with the script, its path, the
log file, the image paths, and a function execute that runs the
script.
Calculates time-frequency decomposition; not intended for direct use. Please use 'RAVE' pipelines (see 'Examples').
run_wavelet( subject, electrodes, freqs, cycles, target_sample_rate = 100, kernels_precision = "float", pre_downsample = 1, verbose = TRUE )run_wavelet( subject, electrodes, freqs, cycles, target_sample_rate = 100, kernels_precision = "float", pre_downsample = 1, verbose = TRUE )
subject |
'RAVE' subject or subject ID |
electrodes |
electrode channels to apply, must be imported and
|
freqs |
numeric vector of frequencies to apply |
cycles |
number of wavelet cycles at each |
target_sample_rate |
the resulting 'spectrogram' sampling frequency |
kernels_precision |
double or single (default) floating precision |
pre_downsample |
down-sample (integer) priory to the decomposition; set to 1 (default) to avoid |
verbose |
whether to verbose the progress |
The channel signals are first down-sampled (optional) by a ratio of
pre_downsample via a 'FIR' filter. After the down-sample,
'Morlet' wavelet kernels are applied to the signals to calculate the
wavelet coefficients (complex number) at each frequency in freqs.
The number of cycles at each frequency controls the number of
sine and cosine waves, allowing users to balance the time and power
accuracy. After the decomposition, the 'spectrogram' is further down-sampled
to target_sample_rate, assuming the brain power is a smooth function
over time. This down-sample is done via time-point sampling to preserve the
phase information (so the linear functions such as common-average or
bi-polar reference can be carried over to the complex coefficients).
The decomposition results are stored in 'RAVE' subject data path; the function only returns the wavelet parameters.
# Check https://rave.wiki for additional pipeline installation ## Not run: # ---- Recommended usage -------------------------------------------- pipeline <- ravepipeline::pipeline("wavelet_module") pipeline$set_settings( project_name = "demo", subject_code = "DemoSubject", precision = "float", pre_downsample = 4, kernel_table = ravetools::wavelet_cycles_suggest( freqs = seq(1, 200, by = 1)), target_sample_rate = 100 ) # Internally, the above pipeline includes this function call below # ---- For demonstration use, do not call this function directly ---- # Original sample rate: 2000 Hz # Downsample by 4 to 500 Hz first - 250 Hz Nyquist # Wavelet at each 1, 2, ..., 200 Hz # The number of cycles log-linear from 2 to 20 # The wavelet coefficient sample rate is 500 Hz # Further down-sample to 100 Hz to save storage space run_wavelet( subject = "demo/DemoSubject", electrodes = c(13:16, 2), pre_downsample = 4, freqs = seq(1, 200, by = 1), cycles = c(2, 20), target_sample_rate = 100 ) ## End(Not run)# Check https://rave.wiki for additional pipeline installation ## Not run: # ---- Recommended usage -------------------------------------------- pipeline <- ravepipeline::pipeline("wavelet_module") pipeline$set_settings( project_name = "demo", subject_code = "DemoSubject", precision = "float", pre_downsample = 4, kernel_table = ravetools::wavelet_cycles_suggest( freqs = seq(1, 200, by = 1)), target_sample_rate = 100 ) # Internally, the above pipeline includes this function call below # ---- For demonstration use, do not call this function directly ---- # Original sample rate: 2000 Hz # Downsample by 4 to 500 Hz first - 250 Hz Nyquist # Wavelet at each 1, 2, ..., 200 Hz # The number of cycles log-linear from 2 to 20 # The wavelet coefficient sample rate is 500 Hz # Further down-sample to 100 Hz to save storage space run_wavelet( subject = "demo/DemoSubject", electrodes = c(13:16, 2), pre_downsample = 4, freqs = seq(1, 200, by = 1), cycles = c(2, 20), target_sample_rate = 100 ) ## End(Not run)
Create overview report for given project or subject
snapshot_subject(x, target_path = NULL, quick = FALSE) snapshot_project( x, target_path = NULL, template_subjects = NULL, quick = FALSE )snapshot_subject(x, target_path = NULL, quick = FALSE) snapshot_project( x, target_path = NULL, template_subjects = NULL, quick = FALSE )
x |
characters or a 'RAVE' project or subject instance |
target_path |
directory where the snapshot data will be stored; default
is under |
quick |
whether to skip certain validations and subjects if snapshot reports have already existed |
template_subjects |
a vector of characters of template brain to be
used for generating the group brain; see
|
snapshot_subject returns a list of subject summary and
the calculated target path; snapshot_project returns the path to
the compiled project report in 'HTML'.
## Not run: # Run in parallel ravepipeline::with_rave_parallel({ snapshot_project("demo") }) ## End(Not run)## Not run: # Run in parallel ravepipeline::with_rave_parallel({ snapshot_project("demo") }) ## End(Not run)
Class definition for micro-wire spike channels
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> Spike_electrode
h5_fname'HDF5' file name
validwhether current electrode is valid: subject exists and contains current electrode or reference; subject electrode type matches with current electrode type
raw_sample_ratevoltage sample rate
power_sample_ratepower/phase sample rate
preprocess_infopreprocess information
voltage_filepath to voltage 'HDF5' file
Spike_electrode$@marshal()Internal method
Spike_electrode$@marshal(...)
...internal arguments
Spike_electrode$@unmarshal()Internal method
Spike_electrode$@unmarshal(object)
object, ...internal arguments
Spike_electrode$print()print electrode summary
Spike_electrode$print()
Spike_electrode$set_reference()set reference for current electrode
Spike_electrode$set_reference(reference)
referenceeither NULL or LFP_electrode instance
Spike_electrode$new()constructor
Spike_electrode$new(subject, number, quiet = FALSE)
subject, number, quietsee constructor in
RAVEAbstarctElectrode
Spike_electrode$.load_noref_voltage()load non-referenced voltage (internally used)
Spike_electrode$.load_noref_voltage(reload = FALSE)
reloadwhether to reload cache
sratevoltage signal sample rate
Spike_electrode$.load_raw_voltage()load raw voltage (no process)
Spike_electrode$.load_raw_voltage(reload = FALSE)
reloadwhether to reload cache
Spike_electrode$load_data_with_epochs()method to load electrode data
Spike_electrode$load_data_with_epochs(type = c("raw-voltage", "voltage"))
typedata type such as "power", "phase",
"voltage", "wavelet-coefficient", and
"raw-voltage". For "power", "phase",
and "wavelet-coefficient", 'Wavelet' transforms are required.
For "voltage", 'Notch' filters must be applied. All these
types except for "raw-voltage" will be referenced.
For "raw-voltage", no reference will be performed since the data
will be the "raw" signal (no processing).
Spike_electrode$load_dimnames_with_epochs()get expected dimension names
Spike_electrode$load_dimnames_with_epochs(type = c("raw-voltage", "voltage"))
typesee load_data_with_epochs
Spike_electrode$load_data_with_blocks()load electrode block-wise data (with no reference), useful when epoch is absent
Spike_electrode$load_data_with_blocks(
blocks,
type = c("raw-voltage", "voltage"),
simplify = TRUE
)
blockssession blocks
typedata type such as "power", "phase",
"voltage", "raw-voltage" (with no filters applied, as-is
from imported), "wavelet-coefficient". Note that if type
is "raw-voltage", then the data only needs to be imported;
for "voltage" data, 'Notch' filters must be applied; for
all other types, 'Wavelet' transforms are required.
simplifywhether to simplify the result
If simplify is enabled, and only one block is loaded,
then the result will be a vector (type="voltage") or a matrix
(others), otherwise the result will be a named list where the names
are the blocks.
Spike_electrode$load_dim_with_blocks()get expected dimension information for block-based loader
Spike_electrode$load_dim_with_blocks(
blocks,
type = c("raw-voltage", "voltage")
)
blocks, typesee load_data_with_blocks
Spike_electrode$clear_cache()method to clear cache on hard drive
Spike_electrode$clear_cache(...)
...ignored
Spike_electrode$clear_memory()method to clear memory
Spike_electrode$clear_memory(...)
...ignored
Spike_electrode$clone()The objects of this class are cloneable with this method.
Spike_electrode$clone(deep = FALSE)
deepWhether to make a deep clone.
Calculate template 'MNI' coordinates for points on native brain
transform_point_to_template( subject, positions, space = c("scannerRAS", "tkrRAS"), mapping_method = c("volumetric", "surface"), flip_hemisphere = FALSE, verbose = TRUE, project_surface = "pial", volumetric_transform = c("auto", "affine", "nonlinear"), ... ) transform_thinfilm_to_mni152( subject, flip_hemisphere = FALSE, interpolator = 0.3, n_segments = c(16, 16), group_labels = NULL, project_surface = "pial", volumetric_transform = c("auto", "affine", "nonlinear"), template_subject = c("cvs_avg35_inMNI152", "fsaverage", "bert", "MNI152") )transform_point_to_template( subject, positions, space = c("scannerRAS", "tkrRAS"), mapping_method = c("volumetric", "surface"), flip_hemisphere = FALSE, verbose = TRUE, project_surface = "pial", volumetric_transform = c("auto", "affine", "nonlinear"), ... ) transform_thinfilm_to_mni152( subject, flip_hemisphere = FALSE, interpolator = 0.3, n_segments = c(16, 16), group_labels = NULL, project_surface = "pial", volumetric_transform = c("auto", "affine", "nonlinear"), template_subject = c("cvs_avg35_inMNI152", "fsaverage", "bert", "MNI152") )
subject |
'RAVE' subject |
positions |
optional matrix of 3 columns, either in scanner or surface
space (specified by |
space |
if |
mapping_method |
whether the mapping is |
flip_hemisphere |
whether to flip the hemisphere; default is
|
verbose |
whether to verbose the mapping progress; default is true |
project_surface |
for surface mapping only, which surface to project
electrodes onto; default is |
volumetric_transform |
for volume mapping only, which type of transform
to use; default is |
... |
ignored |
interpolator |
whether the transform lean towards volume mapping
( |
n_segments |
positive integers with length of two: resolution of the mapping; default segments the thin-film array into 16 by 16 segments |
group_labels |
|
template_subject |
template subject to be mapped to; default is
|
A table of electrode 'MNI' coordinates.
if (has_rave_subject("demo/DemoSubject")) { transform_point_to_template( subject = 'demo/DemoSubject', mapping_method = "volumetric" ) }if (has_rave_subject("demo/DemoSubject")) { transform_point_to_template( subject = 'demo/DemoSubject', mapping_method = "volumetric" ) }
Groups with empty or no conditions (after filtering against epoch, when
provided) are removed from the result.
validate_condition_groupings(condition_groupings, epoch = NULL)validate_condition_groupings(condition_groupings, epoch = NULL)
condition_groupings |
A list of condition group items. Each item is
typically a list with elements |
epoch |
Optional. A |
A list with the following elements:
n - the number of valid condition groups remaining after cleaning;
groups - an unnamed list of cleaned group items (see below);
group_indexes - integer vector of the original 1-based positions
of the kept groups (used to derive a stable color);
group_labels - character vector of the cleaned group labels;
unique_conditions - sorted unique condition names across all groups;
use_epoch - logical, TRUE when epoch was supplied;
n_trials - (only when epoch is supplied) integer vector of the
number of trials in each group.
Each cleaned group item contains:
index - original 1-based position of the group in the input;
label - cleaned label (auto-filled if missing/empty);
conditions - unique character vector, in input order (not sorted);
(when epoch is supplied)
trials_by_condition - named list of integer trial numbers from
the epoch Trial column, one element per condition;
trial_count - integer vector of trial counts per condition;
trials_included - integer vector of trial numbers ordered by
condition (concatenated in the condition order of conditions);
n_trials - total number of trials in the group.
condition_groupings <- list( # Normal case list( label = "AOnly", conditions = c("drive_a", "known_a", "last_a", "meant_a") ), # Invalid/empty label list( label = NA, conditions = c("last_av", "drive_av", "known_av", "meant_av") ), # Empty condition list( label = "G3" ), # Missing label list( conditions = c("known_v", NA) ), # Invalid condition if epoch is provided list( conditions = "adafawefwf" ) ) # Without epoch validate_condition_groupings(condition_groupings) ## Not run: # With epoch table: run `ravecore::install_subject("DemoSubject")` # to install the demo-subject subject <- ravecore::new_rave_subject("demo", "DemoSubject") epoch <- subject$get_epoch("auditory_onset") validate_condition_groupings(condition_groupings, epoch) ## End(Not run)condition_groupings <- list( # Normal case list( label = "AOnly", conditions = c("drive_a", "known_a", "last_a", "meant_a") ), # Invalid/empty label list( label = NA, conditions = c("last_av", "drive_av", "known_av", "meant_av") ), # Empty condition list( label = "G3" ), # Missing label list( conditions = c("known_v", NA) ), # Invalid condition if epoch is provided list( conditions = "adafawefwf" ) ) # Without epoch validate_condition_groupings(condition_groupings) ## Not run: # With epoch table: run `ravecore::install_subject("DemoSubject")` # to install the demo-subject subject <- ravecore::new_rave_subject("demo", "DemoSubject") epoch <- subject$get_epoch("auditory_onset") validate_condition_groupings(condition_groupings, epoch) ## End(Not run)
Check against existence, validity, and consistency
subject |
subject ID (character), or |
method |
validation method, choices are |
verbose |
whether to print out the validation messages |
version |
data version, choices are |
A list of nested validation results. The validation process consists of the following parts in order:
paths)paththe subject's root folder
paththe subject's 'RAVE' folder (the 'rave' folder under the root directory)
raw_paththe subject's legacy raw data folder
raw_paththe subject's raw data folder based on format standard
data_patha directory storing all the voltage, power, phase data (before reference)
meta_pathmeta directory containing all the electrode coordinates, reference table, epoch information, etc.
reference_patha directory storing calculated reference signals
preprocess_patha directory storing all the preprocessing information
cache_path (low priority)data caching path
freesurfer_path (low priority)subject's 'FreeSurfer' directory
note_path (low priority)subject's notes
pipeline_path (low priority)a folder containing all saved pipelines for this subject
preprocess)electrodes_setwhether the subject has a non-empty electrode set
blocks_setwhether the session block length is non-zero
sample_rate_setwhether the raw sampling frequency is set to a valid, proper positive number
data_importedwhether all the assigning electrodes have been imported
notch_filteredwhether all the 'LFP' and 'EKG' signals have been 'Notch' filtered
has_waveletwhether all the 'LFP' signals are wavelet-transformed
has_referenceat least one reference has been generated in the meta folder
has_epochat least one epoch file has been generated in the meta folder
has_electrode_filemeta folder has electrodes.csv file
meta)meta_data_validthis item only exists when the previous preprocess validation is failed or incomplete
meta_electrode_tablethe electrodes.csv file in the meta folder has correct format and consistent electrodes numbers to the preprocess information
meta_reference_xxx(xxx will be replaced with actual reference names) checks whether the reference table contains all electrodes and whether each reference data exists
meta_epoch_xxx(xxx will be replaced with actual epoch names) checks whether the epoch table has the correct formats and whether there are missing blocks indicated in the epoch files
voltage_data*)voltage_preprocessingwhether the raw preprocessing voltage data are valid. This includes data lengths are the same within the same blocks for each signal type
voltage_datawhether the voltage data (after 'Notch' filters) exist and readable. Besides, the lengths of the data must be consistent with the raw signals
power_phase_data*)power_datawhether the power data exists for all 'LFP' signals. Besides, to pass the validation process, the frequency and time-point lengths must be consistent with the preprocess record
power_datasame as power_data but for the phase data
epoch_tables*)One or more sub-items depending on the number of epoch tables. To pass the validation, the event time for each session block must not exceed the actual signal duration. For example, if one session lasts for 200 seconds, it will invalidate the result if a trial onset time is later than 200 seconds.
reference_tables*)One or more sub-items depending on the number of reference tables. To pass the validation, the reference data must be valid. The inconsistencies, for example, missing file, wrong frequency size, invalid time-point lengths will result in failure
Make sure the time windows are valid intervals and returns a reshaped window list
validate_time_window(time_windows)validate_time_window(time_windows)
time_windows |
vectors or a list of time intervals |
A list of time intervals (ordered, length of 2)
# Simple time window validate_time_window(c(-1, 2)) # Multiple windows validate_time_window(c(-1, 2, 3, 5)) # alternatively validate_time_window(list(c(-1, 2), c(3, 5))) validate_time_window(list(list(-1, 2), list(3, 5))) ## Not run: # Incorrect usage (will raise errors) # Invalid interval (length must be two for each intervals) validate_time_window(list(c(-1, 2, 3, 5))) # Time intervals must be in ascending order validate_time_window(c(2, 1)) ## End(Not run)# Simple time window validate_time_window(c(-1, 2)) # Multiple windows validate_time_window(c(-1, 2, 3, 5)) # alternatively validate_time_window(list(c(-1, 2), c(3, 5))) validate_time_window(list(list(-1, 2), list(3, 5))) ## Not run: # Incorrect usage (will raise errors) # Invalid interval (length must be two for each intervals) validate_time_window(list(c(-1, 2, 3, 5))) # Time intervals must be in ascending order validate_time_window(c(2, 1)) ## End(Not run)
A two-stage pipeline that adapts human cortical reconstruction
workflow for ACPC-aligned macaque T1w MRI.
yael_macaque( subject, t1w_path, folder_name = "fs", steps = c("normalization", "reconstruction") )yael_macaque( subject, t1w_path, folder_name = "fs", steps = c("normalization", "reconstruction") )
subject |
character or RAVE subject object. The subject identifier in
|
t1w_path |
character. Absolute path to the T1-weighted NIfTI image
( |
folder_name |
character. Name of the FreeSurfer subject folder created
under the subject imaging directory. Defaults to |
steps |
character vector. Which stages to run. One or both of
|
To run this workflow, a dedicated Python library and FreeSurfer
library must be installed. The binaries are not shipped with this package.
Please use ravemanager::configure_python() to configure the
Python environment. For FreeSurfer, version 8.0.0 has
been tested. Other versions should work too.
RAVE looks for FreeSurfer using option 'freesurfer_path'
and please use ravepipeline::raveio_setopt('freesurfer_path', 'path')
to allow RAVE to access the FreeSurfer home.
The workflow consists of two stages.
Stage 1 ("normalization") runs
YAEL normalization against the ACPC aligned NMT v2 template,
crops and rescales the image into a space that satisfies FreeSurfer atlas
assumptions, and writes all intermediate imaging inputs under
'folder_name/mri/raw/'. This stage takes around 10 min to run.
Stage 2 ("reconstruction") drives individual FreeSurfer binaries
(no recon-all) to build white-matter and pial surfaces,
bypassing steps known
to fail on macaque data (human GCA atlas registration,
mri_fill seed placement). This stage takes around one to three
hours to finish, depending on the computing power and normalization
quality.
Called for its side effects. Returns NULL invisibly.
On success the FreeSurfer subject directory at
<imaging_path>/<folder_name>/ is populated with surf/,
mri/, label/ and related child directories, including
lh.white, rh.white, lh.pial, and rh.pial.
## Not run: # Full pipeline yael_macaque( subject = "YAEL/Snorlax", t1w_path = "/data/macaque/native_acpc_aligned.nii.gz" ) # Resume from reconstruction only (normalization already done) yael_macaque( subject = "YAEL/Snorlax", t1w_path = "/data/macaque/native_acpc_aligned.nii.gz", folder_name = "fs", steps = "reconstruction" ) ## End(Not run)## Not run: # Full pipeline yael_macaque( subject = "YAEL/Snorlax", t1w_path = "/data/macaque/native_acpc_aligned.nii.gz" ) # Resume from reconstruction only (normalization already done) yael_macaque( subject = "YAEL/Snorlax", t1w_path = "/data/macaque/native_acpc_aligned.nii.gz", folder_name = "fs", steps = "reconstruction" ) ## End(Not run)
YAEL image pipelineRigid registration across multiple types of images, non-linear
normalization from the native brain to common templates, and mapping of
template atlases or regions of interest back to the native brain, without
'Python'. The class has the same methods, arguments and active fields as
YAELProcess and writes the same files (names, folders,
'ANTs'-compatible .mat and warp files, 'JSON' logs), so
the results of one class can be read by the other. The registrations,
bias-field correction and tissue segmentation come from ravetools
(version 0.3.3 or later). See examples at as_yael_process
(with engine = "native") and yael_preprocess_native.
Differences from YAELProcess and the rpyANTs pipeline
behind it:
There is no deep_atropos: argument use_antspynet of
map_to_template is ignored, and the tissue segmentation with the
template priors (the Atropos branch) always runs.
The non-linear stage uses the local cross-correlation for every image
(ravetools has no non-linear mutual information), also when an
initial affine transform is given.
Algorithms: ravetools runs a greedy SyN with a single
field and a fixed-point inverse; its linear stages use an automatic step
size, random (Bernoulli) sampling and no histogram matching, and its
affine registration starts with a rigid pass. The smoothing of the
SyN update field takes the rpyANTs values (3 for the initial
registration, 3.5 for the final one) as a Gaussian standard
deviation in voxels, whereas ANTs reads them as a variance, so the
native update field is smoothed more. These values hold for 1 mm
templates; for templates with more voxels per brain they are multiplied by
the cube root of the ratio of brain voxels, rounded to a half (2 for the
0.5 mm 'mni_icbm152_nlin_asym_09b' and
'mni_icbm152_nlin_sym_09b', 1.5 for the 0.25 mm macaque template):
with the 1 mm values, the greedy update folded the deformation in about
1.5 percent of the brain on 'mni_icbm152_nlin_asym_09b'. The share
of the template brain mask where the final deformation folds (is not
one-to-one) is logged, with a warning above 1 percent.
The quick three-class segmentation that finds the white matter for
the intensity normalization runs on the raw image, as in rpyANTs;
when a few extreme intensities inside the brain leave one of its classes
empty (Atropos keeps going, ravetools stops), it is run again
with the intensities clipped at their 99.9 percent quantile inside the
brain (then at the 99 percent quantile).
Grids: additional images are resampled onto the grid of the native
'T1w' image, and left out (with a warning) when they cover less than
95 percent of the brain mask; template tissue priors are resampled onto the
grid of the template 'T1' image; the outermost voxel layer of the
stored warp fields has no displacement.
The template brain mask is made binary (this matters for
'fsaverage', whose mask holds intensities); a tissue class whose
prior is empty inside the brain is left out of the segmentation (with a
warning) instead of failing.
Outputs: transform_image_from_template and
transform_image_to_template return ieegio_volume objects;
only nearest-neighbor and linear (trilinear) interpolation are
available, and interpolator = "auto" follows its documented rule
(YAELProcess uses nearest-neighbor); the queries never create
folders; set_input_image reads the new image before it removes the
old one; the 'NIfTI' data types are chosen by ieegio;
normalization results are replaced together, after the new ones are
complete, and stale ants<K> transforms of earlier layouts are
removed; nothing is written into the template folders.
Streamlines: ieegio reads and writes VTK files through
'Python', so generate_streamlines_from_template skips VTK
inputs (with a warning) and refuses format = "vtk"; it also refuses
format = "tt" and saves TT inputs as TCK files, since
ieegio cannot write TT files.
ravepipeline::RAVESerializable -> YAELNativeProcess
subject_code'RAVE' subject code
image_typesallowed image types
work_pathWorking directory ('RAVE' imaging path)
YAELNativeProcess$@marshal()Internal method
YAELNativeProcess$@marshal(...)
...internal arguments
YAELNativeProcess$@unmarshal()Internal method
YAELNativeProcess$@unmarshal(object, ...)
object, ...internal arguments
YAELNativeProcess$new()Constructor to instantiate the class
YAELNativeProcess$new(subject, image_types, imaging_path = NULL, ...)
subject'RAVE' subject or subject ID; for native standard, this can be character code without project names, but for 'BIDS' subjects, this must be a full subject ID with project information
image_typesvector of image types, such as 'T1w',
'CT', 'fGATIR'. All images except 'CT' will be
considered 'preop' (before electrode implantation). Please
use 'postop' to indicate if an image is taken after the
implantation (for example, 'postopT1w')
imaging_pathimaging path (path to 'rave-imaging'
if not default); internally used to set the work path during
serialization. Please do not set it manually unless you know what you
are doing
...reserved for legacy code
YAELNativeProcess$set_input_image()Set the raw input for different image types
YAELNativeProcess$set_input_image(
path,
type = YAEL_IMAGE_TYPES,
overwrite = FALSE,
on_error = c("warning", "error", "ignore")
)
pathpath to the image files in 'NIfTI' or 'MGZ'
format
typetype of the image
overwritewhether to overwrite existing images if the same type has been imported before; default is false
on_errorwhen the file exists and overwrite is false,
how should this error be reported; choices are 'warning' (default),
'error' (throw error and abort), or 'ignore'.
whether the image has been set (or replaced)
YAELNativeProcess$get_input_image()Get image path
YAELNativeProcess$get_input_image(type = YAEL_IMAGE_TYPES)
typetype of the image
Absolute path if the image, or NULL if missing
YAELNativeProcess$get_subject()Get 'RAVE' subject instance
YAELNativeProcess$get_subject(..., strict = FALSE)
...ignored
strictpassed to as_rave_subject
'RAVE' subject instance
YAELNativeProcess$register_to_T1w()Register other images to 'T1' weighted 'MRI'
with two rigid passes (mutual information)
YAELNativeProcess$register_to_T1w( image_type = "CT", reverse = FALSE, verbose = TRUE )
image_typetype of the image to register, must be set via
process$set_input_image first.
reversewhether to reverse the registration; default is false,
meaning the fixed (reference) image is the 'T1'. When setting to
true, then the 'T1' 'MRI' will become the moving image
verbosewhether to print out the process; default is true
Nothing
YAELNativeProcess$get_native_mapping()Get the mapping configurations used by register_to_T1w
YAELNativeProcess$get_native_mapping( image_type = YAEL_IMAGE_TYPES, relative = FALSE )
image_typetype of the image registered to 'T1' weighted 'MRI'
relativewhether to use relative path (to the work_path field)
A list of moving and fixing images, with rigid transformations
from different formats; mappings is empty before the image is
registered. No folder is created.
YAELNativeProcess$map_to_template()Normalize native brain to 'MNI152' template
YAELNativeProcess$map_to_template(
template_name = rpyants_builtin_templates(),
use_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"),
native_type = "T1w",
use_antspynet = TRUE,
verbose = TRUE,
...
)
template_namewhich template to use, choices are
'mni_icbm152_nlin_asym_09a', 'mni_icbm152_nlin_asym_09b',
'mni_icbm152_nlin_asym_09c', and 'fsaverage'.
use_imagesa vector of image types to use for normalization;
default types are 'T1w', 'T2w', 'T1wContrast',
'fGATIR', and 'preopCT'. To use all available images
for normalization, use wildcard "all". Images that are not
registered to 'T1w' yet are registered first (a failure is
reported as a warning and the image is left out)
native_typewhich type of image should be used to map to template;
default is 'T1w'
use_antspynetignored: the native engine has no
deep_atropos, and the tissue segmentation always uses the
template priors
verbosewhether to print out the process; default is true
...additional tuning parameters: affine_transform
(optional initial affine transform, an 'ANTs' .mat file
from the template to the native image as point map; the initial
registration then only runs its non-linear stage), with_skull
(whether to register the images with skull; default is false), and
cost_function (only 'CC', the local cross-correlation, is
available; other values give a warning); other arguments are ignored
See method get_template_mapping
YAELNativeProcess$get_template_mapping()Get configurations used for normalization
YAELNativeProcess$get_template_mapping( template_name = rpyants_builtin_templates(), native_type = "T1w", relative = FALSE )
template_namewhich template is used
native_typewhich native image is mapped to template
relativewhether the paths should be relative or absolute; default is false (absolute paths)
A list of input, output images, with forward and inverse
transform files (usually two 'Affine' with one displacement
field), or NULL if the image is not normalized to the template
yet. The transforms of the subject are used; transforms whose subject
entity is spelled in another letter case are used if there is only one
such spelling, and the transforms of another subject only if they are
the only ones and the native image was imported under that subject
(with a warning)
YAELNativeProcess$transform_image_from_template()Apply transform from images (usually an atlas or a region of interest) on template to native space
YAELNativeProcess$transform_image_from_template(
template_roi_path,
template_name = rpyants_builtin_templates(),
native_type = "T1w",
interpolator = c("auto", "nearestNeighbor", "linear", "gaussian", "bSpline",
"cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc",
"lanczosWindowedSinc", "genericLabel"),
verbose = TRUE
)
template_roi_pathpath to the template image file which will be transformed into individuals' image
template_nametemplates to use
native_typewhich type of native image to use for calculating
the coordinates (default 'T1w')
interpolatorhow to interpolate the 'voxels'; default is
"auto": linear for probability maps (all values between 0 and 1,
some of them fractional) and 'nearestNeighbor' otherwise.
'nearestNeighbor' and 'genericLabel' use the nearest
neighbor, all others the linear (trilinear) interpolation
verbosewhether the print out the progress
transformed image on the grid of the native image, as an
ieegio_volume object
YAELNativeProcess$transform_image_to_template()Apply transform to images (usually an atlas or a region of interest) from native space to template
YAELNativeProcess$transform_image_to_template(
native_roi_path,
template_name = rpyants_builtin_templates(),
native_type = "T1w",
interpolator = c("auto", "nearestNeighbor", "linear", "gaussian", "bSpline",
"cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc",
"lanczosWindowedSinc", "genericLabel"),
verbose = TRUE
)
native_roi_pathpath to the native image file that will be transformed into template
template_nametemplates to use
native_typewhich type of native image to use for calculating
the coordinates (default 'T1w')
interpolatorhow to interpolate the 'voxels'; default is
"auto": linear for probability maps (all values between 0 and 1,
some of them fractional) and 'nearestNeighbor' otherwise.
'nearestNeighbor' and 'genericLabel' use the nearest
neighbor, all others the linear (trilinear) interpolation
verbosewhether the print out the progress
transformed image on the grid of the template 'T1'
image, as an ieegio_volume object
YAELNativeProcess$generate_atlas_from_template()Generate atlas maps from template and morph to native brain
YAELNativeProcess$generate_atlas_from_template(
template_name = rpyants_builtin_templates(),
atlas_folder = NULL,
surfaces = NA,
verbose = TRUE,
lambda = 0.2,
degree = 2,
threshold_lb = 0.5,
threshold_ub = NA,
smooth_method = c("implicit", "explicit"),
max_vertices = 5e+05
)
template_namewhich template to use
atlas_folderpath to the atlas folder (that contains the atlas
files); every 'NIfTI' file in the folder and its sub-folders is
mapped to 'atlases/<sub-folder>/<file name>' under the working
directory (file names starting with a dot are skipped). Probability
maps (values between 0 and 1, some fractional) are interpolated
linearly, other images with the nearest neighbor
surfaceswhether to generate surfaces (triangle mesh); default is
NA (generate if not existed). Other choices are TRUE
for always generating and overwriting surface files, or FALSE
to disable this function. The generated surfaces will stay in native
'T1' space.
verbosewhether the print out the progress
lambda, degree, threshold_lb, threshold_ubpassed to
volume_to_surf
smooth_methodhow to smooth the surfaces: "implicit"
(default, vcg_smooth_implicit with
lambda and degree) or "explicit"
(mris_smooth); passed to
volume_to_surf
max_verticessurfaces with more vertices are reduced to about
this many after smoothing; passed to
volume_to_surf; default is 500000
Paths to the atlas (volume) files under the 'atlases'
folder of the working directory
YAELNativeProcess$generate_streamlines_from_template()Transform streamline tract files from template space to native brain space
YAELNativeProcess$generate_streamlines_from_template(
template_name = rpyants_builtin_templates(),
streamlines_folder = NULL,
verbose = TRUE,
format = c("auto", "tck", "trk", "tt", "vtk"),
native_type = "T1w"
)
template_namewhich template to use; the template must have been
used in map_to_template prior to calling this method
streamlines_folderpath to folder containing streamline tract
files ('.tck', '.trk', '.tt', or '.vtk');
all matching files are processed recursively, except VTK files
('.vtk', '.vtp'), which ieegio can only read
through 'Python': they are skipped with a warning
verbosewhether to print progress; default is TRUE
formatoutput format for the saved streamlines; "auto"
(default) preserves the original file extension, except that TT
files are saved as TCK (ieegio has no TT writer);
"tck" and "trk" convert every file. "tt" (no
writer) and "vtk" (written through 'Python') are errors
native_typewhich native image type defines the target space;
default is "T1w"
Invisibly returns a character vector of the relative paths to
the input streamline files that were processed (VTK files are
left out); transformed files are written under fs/streamline/
from the working directory. The points of all files are transformed
together; points with missing coordinates are dropped. 'Python' is
never started: the files are read and written with the 'Python'
support of ieegio disabled.
YAELNativeProcess$transform_points_to_template()Transform points from native images to template
YAELNativeProcess$transform_points_to_template( native_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
native_rasmatrix or data frame with 3 columns indicating points
sitting on native images in right-anterior-superior ('RAS')
coordinate system.
template_nametemplate to use for mapping
native_typenative image type where the points sit on
verbosewhether the print out the progress
A matrix of 3 columns, each row is a transformed points (
invalid rows will be filled with NA)
YAELNativeProcess$transform_points_from_template()Transform points from template images to native
YAELNativeProcess$transform_points_from_template( template_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
template_rasmatrix or data frame with 3 columns indicating points
sitting on template images in right-anterior-superior ('RAS')
coordinate system.
template_nametemplate to use for mapping
native_typenative image type where the points sit on
verbosewhether the print out the progress
A matrix of 3 columns, each row is a transformed points (
invalid rows will be filled with NA)
YAELNativeProcess$write_talairach_xfm()Write the linear transform 'ants/mri/transforms/talairach.xfm'
from native 'T1w' scanner 'RAS' coordinates to
'MNI305' space, using the affine part of the normalization
created by map_to_template. For templates that are not in
'MNI152' space, the transform maps to the template space
instead ('fsaverage' is already in 'MNI305' space).
This method is called by construct_ants_folder_from_template.
YAELNativeProcess$write_talairach_xfm( template_name = rpyants_builtin_templates() )
template_nametemplate that has been used in
map_to_template
The path to the transform file, invisibly
YAELNativeProcess$construct_ants_folder_from_template()Create a reconstruction folder (as an alternative option) that
is generated from template brain to facilitate the three-dimensional
viewer. Please make sure method map_to_template is called before
using this method (or the program will fail). The folder holds the
conformed 'mri/T1.mgz', the template brain mask mapped to the
native image ('mri/brainmask.nii.gz', binary), the bias-corrected
image ('mri/nu.nii.gz'), its skull-stripped version scaled to
0 to 255 ('mri/brain.finalsurfs.nii.gz'), and the linear
transform 'mri/transforms/talairach.xfm' written by
write_talairach_xfm; if that fails, the file is removed and a
warning is logged.
YAELNativeProcess$construct_ants_folder_from_template( template_name = rpyants_builtin_templates(), add_surfaces = TRUE )
template_nametemplate to use for mapping; NULL only
writes 'mri/T1.mgz'
add_surfaceswhether to create surfaces that is morphed from
template to local; default is TRUE. The surfaces are only
created for templates with 'fs/surf' pial surfaces. Please enable
this option only if the cortical surfaces are not critical (for example,
you are studying the deep brain structures). Always use
'FreeSurfer' if cortical information is used.
YAELNativeProcess$get_brain()Get three-dimensional brain model
YAELNativeProcess$get_brain(
electrodes = TRUE,
coord_sys = c("scannerRAS", "tkrRAS", "MNI152", "MNI305"),
...
)
electrodeswhether to add electrodes to the viewers; can be
logical, data frame, or a character (path to electrode table). When
the value is TRUE, the electrode file under project_name
will be loaded; when electrodes is a data.frame,
or path to a 'csv' file, then please specify coord_sys
on what is the coordinate system used for columns "x", "y",
and "z".
coord_syscoordinate system if electrodes is a data frame
with columns "x", "y", and "z", available choices
are 'scannerRAS' (defined by 'T1' weighted native 'MRI' image),
'tkrRAS' ('FreeSurfer' defined native 'TK-registered'),
'MNI152' (template MNI coordinate system averaged over 152
subjects; this is the common MNI coordinate space we often refer to),
and 'MNI305' (template MNI coordinate system averaged over 305
subjects; this coordinate system used by templates such as
'fsaverage')
...passed to threeBrain
YAELNativeProcess$clone()The objects of this class are cloneable with this method.
YAELNativeProcess$clone(deep = FALSE)
deepWhether to make a deep clone.
Rigid-registration across multiple types of images, non-linear normalization
from native brain to common templates, and map template atlas or
regions of interest back to native brain. See examples at
as_yael_process
ravepipeline::RAVESerializable -> YAELProcess
subject_code'RAVE' subject code
image_typesallowed image types
work_pathWorking directory ('RAVE' imaging path)
YAELProcess$@marshal()Internal method
YAELProcess$@marshal(...)
...internal arguments
YAELProcess$@unmarshal()Internal method
YAELProcess$@unmarshal(object, ...)
object, ...internal arguments
YAELProcess$new()Constructor to instantiate the class
YAELProcess$new(subject, image_types, imaging_path = NULL, ...)
subject'RAVE' subject or subject ID; for native standard, this can be character code without project names, but for 'BIDS' subjects, this must be a full subject ID with project information
image_typesvector of image types, such as 'T1w',
'CT', 'fGATIR'. All images except 'CT' will be
considered 'preop' (before electrode implantation). Please
use 'postop' to indicate if an image is taken after the
implantation (for example, 'postopT1w')
imaging_pathimaging path (path to 'rave-imaging'
if not default); internally used to set the work path during
serialization. Please do not set it manually unless you know what you
are doing
...reserved for legacy code
YAELProcess$set_input_image()Set the raw input for different image types
YAELProcess$set_input_image(
path,
type = YAEL_IMAGE_TYPES,
overwrite = FALSE,
on_error = c("warning", "error", "ignore")
)
pathpath to the image files in 'NIfTI' format
typetype of the image
overwritewhether to overwrite existing images if the same type has been imported before; default is false
on_errorwhen the file exists and overwrite is false,
how should this error be reported; choices are 'warning' (default),
'error' (throw error and abort), or 'ignore'.
whether the image has been set (or replaced)
YAELProcess$get_input_image()Get image path
YAELProcess$get_input_image(type = YAEL_IMAGE_TYPES)
typetype of the image
Absolute path if the image
YAELProcess$get_subject()Get 'RAVE' subject instance
YAELProcess$get_subject(..., strict = FALSE)
...ignored
strictpassed to as_rave_subject
'RAVE' subject instance
YAELProcess$register_to_T1w()Register other images to 'T1' weighted 'MRI'
YAELProcess$register_to_T1w(image_type = "CT", reverse = FALSE, verbose = TRUE)
image_typetype of the image to register, must be set via
process$set_input_image first.
reversewhether to reverse the registration; default is false,
meaning the fixed (reference) image is the 'T1'. When setting to
true, then the 'T1' 'MRI' will become the moving image
verbosewhether to print out the process; default is true
Nothing
YAELProcess$get_native_mapping()Get the mapping configurations used by register_to_T1w
YAELProcess$get_native_mapping(image_type = YAEL_IMAGE_TYPES, relative = FALSE)
image_typetype of the image registered to 'T1' weighted 'MRI'
relativewhether to use relative path (to the work_path field)
A list of moving and fixing images, with rigid transformations from different formats.
YAELProcess$map_to_template()Normalize native brain to 'MNI152' template
YAELProcess$map_to_template(
template_name = rpyants_builtin_templates(),
use_images = c("T1w", "T2w", "T1wContrast", "fGATIR", "preopCT"),
native_type = "T1w",
use_antspynet = TRUE,
verbose = TRUE,
...
)
template_namewhich template to use, choices are
'mni_icbm152_nlin_asym_09a', 'mni_icbm152_nlin_asym_09b',
'mni_icbm152_nlin_asym_09c', and 'fsaverage'.
use_imagesa vector of image types to use for normalization;
default types are 'T1w', 'T2w', 'T1wContrast',
'fGATIR', and 'preopCT'. To use all available images
for normalization, use wildcard "all"
native_typewhich type of image should be used to map to template;
default is 'T1w'
use_antspynetwhether to try 'antspynet' if available;
default is true, which uses deep_atropos instead of the
conventional atropos to speed up and possibly with more accurate
results.
verbosewhether to print out the process; default is true
...additional tuning parameters passed to internal 'Python' code.
See method get_template_mapping
YAELProcess$get_template_mapping()Get configurations used for normalization
YAELProcess$get_template_mapping( template_name = rpyants_builtin_templates(), native_type = "T1w", relative = FALSE )
template_namewhich template is used
native_typewhich native image is mapped to template
relativewhether the paths should be relative or absolute; default is false (absolute paths)
A list of input, output images, with forward and inverse
transform files (usually two 'Affine' with one displacement field)
YAELProcess$transform_image_from_template()Apply transform from images (usually an atlas or 'ROI') on template to native space
YAELProcess$transform_image_from_template(
template_roi_path,
template_name = rpyants_builtin_templates(),
native_type = "T1w",
interpolator = c("auto", "nearestNeighbor", "linear", "gaussian", "bSpline",
"cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc",
"lanczosWindowedSinc", "genericLabel"),
verbose = TRUE
)
template_roi_pathpath to the template image file which will be transformed into individuals' image
template_nametemplates to use
native_typewhich type of native image to use for calculating
the coordinates (default 'T1w')
interpolatorhow to interpolate the 'voxels'; default is
"auto": 'linear' for probabilistic map and 'nearestNeighbor'
otherwise.
verbosewhether the print out the progress
transformed image in 'ANTs' format
YAELProcess$transform_image_to_template()Apply transform to images (usually an atlas or 'ROI') from native space to template
YAELProcess$transform_image_to_template(
native_roi_path,
template_name = rpyants_builtin_templates(),
native_type = "T1w",
interpolator = c("auto", "nearestNeighbor", "linear", "gaussian", "bSpline",
"cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc",
"lanczosWindowedSinc", "genericLabel"),
verbose = TRUE
)
native_roi_pathpath to the native image file that will be transformed into template
template_nametemplates to use
native_typewhich type of native image to use for calculating
the coordinates (default 'T1w')
interpolatorhow to interpolate the 'voxels'; default is
"auto": 'linear' for probabilistic map and 'nearestNeighbor'
otherwise.
verbosewhether the print out the progress
transformed image in 'ANTs' format
YAELProcess$generate_atlas_from_template()Generate atlas maps from template and morph to native brain
YAELProcess$generate_atlas_from_template(
template_name = rpyants_builtin_templates(),
atlas_folder = NULL,
surfaces = NA,
verbose = TRUE,
lambda = 0.2,
degree = 2,
threshold_lb = 0.5,
threshold_ub = NA,
smooth_method = c("implicit", "explicit"),
max_vertices = 5e+05
)
template_namewhich template to use
atlas_folderpath to the atlas folder (that contains the atlas files)
surfaceswhether to generate surfaces (triangle mesh); default is
NA (generate if not existed). Other choices are TRUE
for always generating and overwriting surface files, or FALSE
to disable this function. The generated surfaces will stay in native
'T1' space.
verbosewhether the print out the progress
lambda, degree, threshold_lb, threshold_ubpassed to
volume_to_surf
smooth_methodhow to smooth the surfaces: "implicit"
(default, vcg_smooth_implicit with
lambda and degree) or "explicit"
(mris_smooth); passed to
volume_to_surf
max_verticessurfaces with more vertices are reduced to about
this many after smoothing; passed to
volume_to_surf; default is 500000
Paths to the atlas (volume) files
YAELProcess$generate_streamlines_from_template()Transform streamline tract files from template space to native brain space
YAELProcess$generate_streamlines_from_template(
template_name = rpyants_builtin_templates(),
streamlines_folder = NULL,
verbose = TRUE,
format = c("auto", "tck", "trk", "tt", "vtk"),
native_type = "T1w"
)
template_namewhich template to use; the template must have been
used in map_to_template prior to calling this method
streamlines_folderpath to folder containing streamline tract
files ('.tck', '.trk', '.tt', or '.vtk');
all matching files are processed recursively
verbosewhether to print progress; default is TRUE
formatoutput format for the saved streamlines; "auto"
(default) preserves the original file extension; other choices are
"tck", "trk", "tt", and "vtk"
native_typewhich native image type defines the target space;
default is "T1w"
Invisibly returns a character vector of the relative paths to
the input streamline files that were processed; transformed files are
written under fs/streamline/ from the working directory.
YAELProcess$transform_points_to_template()Transform points from native images to template
YAELProcess$transform_points_to_template( native_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
native_rasmatrix or data frame with 3 columns indicating points
sitting on native images in right-anterior-superior ('RAS')
coordinate system.
template_nametemplate to use for mapping
native_typenative image type where the points sit on
verbosewhether the print out the progress
A matrix of 3 columns, each row is a transformed points (
invalid rows will be filled with NA)
YAELProcess$transform_points_from_template()Transform points from template images to native
YAELProcess$transform_points_from_template( template_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
template_rasmatrix or data frame with 3 columns indicating points
sitting on template images in right-anterior-superior ('RAS')
coordinate system.
template_nametemplate to use for mapping
native_typenative image type where the points sit on
verbosewhether the print out the progress
A matrix of 3 columns, each row is a transformed points (
invalid rows will be filled with NA)
YAELProcess$write_talairach_xfm()Write the linear transform 'ants/mri/transforms/talairach.xfm'
from native 'T1w' scanner 'RAS' coordinates to
'MNI305' space, using the affine part of the normalization
created by map_to_template. For templates that are not in
'MNI152' space, the transform maps to the template space
instead ('fsaverage' is already in 'MNI305' space).
This method is called by construct_ants_folder_from_template,
and can be called alone to repair subjects processed by earlier
versions, where this transform was computed in the wrong direction
and coordinate convention.
YAELProcess$write_talairach_xfm(template_name = rpyants_builtin_templates())
template_nametemplate that has been used in
map_to_template
The path to the transform file, invisibly
YAELProcess$construct_ants_folder_from_template()Create a reconstruction folder (as an alternative option) that
is generated from template brain to facilitate the three-dimensional
viewer. Please make sure method map_to_template is called before
using this method (or the program will fail). The linear transform
'mri/transforms/talairach.xfm' is written by
write_talairach_xfm; if that fails, the file is removed and a
warning is logged.
YAELProcess$construct_ants_folder_from_template( template_name = rpyants_builtin_templates(), add_surfaces = TRUE )
template_nametemplate to use for mapping
add_surfaceswhether to create surfaces that is morphed from
template to local; default is TRUE. Please enable this option
only if the cortical surfaces are not critical (for example,
you are studying the deep brain structures). Always use
'FreeSurfer' if cortical information is used.
YAELProcess$get_brain()Get three-dimensional brain model
YAELProcess$get_brain(
electrodes = TRUE,
coord_sys = c("scannerRAS", "tkrRAS", "MNI152", "MNI305"),
...
)
electrodeswhether to add electrodes to the viewers; can be
logical, data frame, or a character (path to electrode table). When
the value is TRUE, the electrode file under project_name
will be loaded; when electrodes is a data.frame,
or path to a 'csv' file, then please specify coord_sys
on what is the coordinate system used for columns "x", "y",
and "z".
coord_syscoordinate system if electrodes is a data frame
with columns "x", "y", and "z", available choices
are 'scannerRAS' (defined by 'T1' weighted native 'MRI' image),
'tkrRAS' ('FreeSurfer' defined native 'TK-registered'),
'MNI152' (template 'MNI' coordinate system averaged over 152
subjects; this is the common "'MNI' coordinate space" we often refer to),
and 'MNI305' (template 'MNI' coordinate system averaged over 305
subjects; this coordinate system used by templates such as
'fsaverage')
...passed to threeBrain
YAELProcess$clone()The objects of this class are cloneable with this method.
YAELProcess$clone(deep = FALSE)
deepWhether to make a deep clone.