| Title: | Core File Structures and Workflows for 'RAVE' |
| Version: | 1.0.0 |
| 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>). |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Language: | en-US |
| URL: | https://rave.wiki, https://rave.wiki/ravecore/, https://github.com/rave-ieeg/ravecore |
| BugReports: | https://github.com/rave-ieeg/ravecore/issues |
| Imports: | tools, utils, bidsr, data.table, filearray (≥ 0.2.0), fs, ieegio, jsonlite, methods, R6, ravepipeline (≥ 0.0.2), ravetools, S7, threeBrain |
| Suggests: | rpyANTs, rpymat, htmltools, httpuv, knitr, plotly, rmarkdown, RNifti, RNiftyReg, shiny, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-09 19:18:23 UTC; dipterix |
| Author: | Zhengjia Wang |
| Maintainer: | Zhengjia Wang <dipterix.wang@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-09 20:10:02 UTC |
ravecore: 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).
Author(s)
Maintainer: Zhengjia Wang dipterix.wang@gmail.com (ORCID)
Authors:
Zhengjia Wang dipterix.wang@gmail.com (ORCID)
Xiang Zhang xiang.zhang@pennmedicine.upenn.edu
John Magnotti john.magnotti@pennmedicine.upenn.edu
Michael Beauchamp michael.beauchamp@pennmedicine.upenn.edu
Other contributors:
Trustees of the University of Pennsylvania (All files in this package unless explicitly stated in the file) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/rave-ieeg/ravecore/issues
Class definition for auxiliary channels
Description
Class definition for auxiliary channels
Super classes
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> Auxiliary_electrode
Active bindings
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
Methods
Public methods
Inherited methods
Auxiliary_electrode$@marshal()
Internal method
Usage
Auxiliary_electrode$@marshal(...)
Arguments
...internal arguments
Auxiliary_electrode$@unmarshal()
Internal method
Usage
Auxiliary_electrode$@unmarshal(object)
Arguments
object, ...internal arguments
Auxiliary_electrode$print()
print electrode summary
Usage
Auxiliary_electrode$print()
Auxiliary_electrode$set_reference()
set reference for current electrode
Usage
Auxiliary_electrode$set_reference(reference)
Arguments
referenceeither
NULLorLFP_electrodeinstance
Auxiliary_electrode$new()
constructor
Usage
Auxiliary_electrode$new(subject, number, quiet = FALSE)
Arguments
subject, number, quietsee constructor in
RAVEAbstarctElectrode
Auxiliary_electrode$.load_noref_voltage()
load non-referenced voltage (internally used)
Usage
Auxiliary_electrode$.load_noref_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
sratevoltage signal sample rate
Auxiliary_electrode$.load_raw_voltage()
load raw voltage (no process)
Usage
Auxiliary_electrode$.load_raw_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
Auxiliary_electrode$load_data_with_epochs()
method to load electrode data
Usage
Auxiliary_electrode$load_data_with_epochs(type = c("raw-voltage", "voltage"))
Arguments
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
Usage
Auxiliary_electrode$load_dimnames_with_epochs(
type = c("raw-voltage", "voltage")
)
Arguments
typesee
load_data_with_epochs
Auxiliary_electrode$load_data_with_blocks()
load electrode block-wise data (with no reference), useful when epoch is absent
Usage
Auxiliary_electrode$load_data_with_blocks(
blocks,
type = c("raw-voltage", "voltage"),
simplify = TRUE
)
Arguments
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
Returns
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
Usage
Auxiliary_electrode$load_dim_with_blocks(
blocks,
type = c("raw-voltage", "voltage")
)
Arguments
blocks, typesee
load_data_with_blocks
Auxiliary_electrode$clear_cache()
method to clear cache on hard drive
Usage
Auxiliary_electrode$clear_cache(...)
Arguments
...ignored
Auxiliary_electrode$clear_memory()
method to clear memory
Usage
Auxiliary_electrode$clear_memory(...)
Arguments
...ignored
Auxiliary_electrode$clone()
The objects of this class are cloneable with this method.
Usage
Auxiliary_electrode$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Definitions of electrode with local field potential signal type
Description
Please use a safer new_electrode function to
create instances. This documentation is to describe the member methods
of the electrode class LFP_electrode
Super classes
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> LFP_electrode
Active bindings
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
Methods
Public methods
Inherited methods
LFP_electrode$@marshal()
Internal method
Usage
LFP_electrode$@marshal(...)
Arguments
...internal arguments
LFP_electrode$@unmarshal()
Internal method
Usage
LFP_electrode$@unmarshal(object)
Arguments
object, ...internal arguments
LFP_electrode$print()
print electrode summary
Usage
LFP_electrode$print()
LFP_electrode$set_reference()
set reference for current electrode
Usage
LFP_electrode$set_reference(reference)
Arguments
referenceeither
NULLorLFP_electrodeinstance
LFP_electrode$new()
constructor
Usage
LFP_electrode$new(subject, number, quiet = FALSE)
Arguments
subject, number, quietsee constructor in
RAVEAbstarctElectrode
LFP_electrode$.load_noref_wavelet()
load non-referenced wavelet coefficients (internally used)
Usage
LFP_electrode$.load_noref_wavelet(reload = FALSE)
Arguments
reloadwhether to reload cache
Returns
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)
Usage
LFP_electrode$.load_noref_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
sratevoltage signal sample rate
LFP_electrode$.load_wavelet()
load referenced wavelet coefficients (internally used)
Usage
LFP_electrode$.load_wavelet(
type = c("power", "phase", "wavelet-coefficient"),
reload = FALSE
)
Arguments
typetype of data to load
reloadwhether to reload cache
LFP_electrode$.load_voltage()
load referenced voltage (internally used)
Usage
LFP_electrode$.load_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
LFP_electrode$.load_raw_voltage()
load raw voltage (no process)
Usage
LFP_electrode$.load_raw_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
LFP_electrode$load_data_with_epochs()
method to load electrode data
Usage
LFP_electrode$load_data_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
Arguments
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
Usage
LFP_electrode$load_dimnames_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
Arguments
typesee
load_data_with_epochs
LFP_electrode$load_data_with_blocks()
load electrode block-wise data (with no reference), useful when epoch is absent
Usage
LFP_electrode$load_data_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage"),
simplify = TRUE
)
Arguments
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
Returns
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
Usage
LFP_electrode$load_dim_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
Arguments
blocks, typesee
load_data_with_blocks
LFP_electrode$clear_cache()
method to clear cache on hard drive
Usage
LFP_electrode$clear_cache(...)
Arguments
...ignored
LFP_electrode$clear_memory()
method to clear memory
Usage
LFP_electrode$clear_memory(...)
Arguments
...ignored
LFP_electrode$clone()
The objects of this class are cloneable with this method.
Usage
LFP_electrode$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# 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()
}
Definitions of reference with local field potential signal type
Description
Please use a safer new_reference function to
create instances. This documentation is to describe the member methods
of the electrode class LFP_reference
Super classes
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> LFP_reference
Active bindings
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
Methods
Public methods
Inherited methods
LFP_reference$@marshal()
Internal method
Usage
LFP_reference$@marshal(...)
Arguments
...internal arguments
LFP_reference$@unmarshal()
Internal method
Usage
LFP_reference$@unmarshal(object)
Arguments
object, ...internal arguments
LFP_reference$print()
print reference summary
Usage
LFP_reference$print()
LFP_reference$set_reference()
set reference for current electrode
Usage
LFP_reference$set_reference(reference)
Arguments
referencemust be
NULL
LFP_reference$new()
constructor
Usage
LFP_reference$new(subject, number, quiet = FALSE)
Arguments
subject, number, quietsee constructor in
RAVEAbstarctElectrode
LFP_reference$.load_noref_wavelet()
load non-referenced wavelet coefficients (internally used)
Usage
LFP_reference$.load_noref_wavelet(reload = FALSE)
Arguments
reloadwhether to reload cache
Returns
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)
Usage
LFP_reference$.load_noref_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
sratevoltage signal sample rate
LFP_reference$.load_wavelet()
load referenced wavelet coefficients (internally used)
Usage
LFP_reference$.load_wavelet(
type = c("power", "phase", "wavelet-coefficient"),
reload = FALSE
)
Arguments
typetype of data to load
reloadwhether to reload cache
LFP_reference$.load_voltage()
load referenced voltage (internally used)
Usage
LFP_reference$.load_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
LFP_reference$load_data_with_epochs()
method to load electrode data
Usage
LFP_reference$load_data_with_epochs(
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
Arguments
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
Usage
LFP_reference$load_data_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient"),
simplify = TRUE
)
Arguments
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
Returns
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
Usage
LFP_reference$load_dim_with_blocks(
blocks,
type = c("power", "phase", "voltage", "wavelet-coefficient", "raw-voltage")
)
Arguments
blocks, typesee
load_data_with_blocks
LFP_reference$clear_cache()
method to clear cache on hard drive
Usage
LFP_reference$clear_cache(...)
Arguments
...ignored
LFP_reference$clear_memory()
method to clear memory
Usage
LFP_reference$clear_memory(...)
Arguments
...ignored
LFP_reference$clone()
The objects of this class are cloneable with this method.
Usage
LFP_reference$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# 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()
}
Abstract definition of electrode class in 'RAVE'
Description
This class is not intended for direct use. Please create new child classes and implement some key methods.
Super class
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode
Public fields
subjectsubject instance (
RAVESubject)numberinteger stands for electrode number or reference ID
referencereference electrode, either
NULLfor no reference or an electrode instance inheritsRAVEAbstarctElectrodeepocha
RAVEEpochinstancestitch_eventsevents to stitch, when loading window is not default to trial onset; must be
NULLor a character vector of length 2
Active bindings
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_TYPESfor detailsexistswhether 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;
NAif epoch or trial intervals are missingtrial_intervalstrial intervals relative to epoch onset
Methods
Public methods
Inherited methods
RAVEAbstarctElectrode$new()
constructor
Usage
RAVEAbstarctElectrode$new(subject, number, quiet = FALSE)
Arguments
subjectcharacter or
RAVESubjectinstancenumbercurrent electrode number or reference ID
quietreserved, whether to suppress warning messages
RAVEAbstarctElectrode$set_reference()
set reference for instance
Usage
RAVEAbstarctElectrode$set_reference(reference)
Arguments
referenceNULLorRAVEAbstarctElectrodeinstance
RAVEAbstarctElectrode$set_epoch()
set epoch instance for the electrode
Usage
RAVEAbstarctElectrode$set_epoch(epoch, stitch_events = NULL)
Arguments
epochcharacters or
RAVEEpochinstance. 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
Usage
RAVEAbstarctElectrode$clear_cache(...)
Arguments
...implemented by child instances
RAVEAbstarctElectrode$clear_memory()
method to clear memory
Usage
RAVEAbstarctElectrode$clear_memory(...)
Arguments
...implemented by child instances
RAVEAbstarctElectrode$load_data_with_epochs()
method to load electrode data
Usage
RAVEAbstarctElectrode$load_data_with_epochs(type)
Arguments
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
Usage
RAVEAbstarctElectrode$load_data(type)
Arguments
typesee
load_data_with_epochs
RAVEAbstarctElectrode$load_dimnames_with_epochs()
get expected dimension names
Usage
RAVEAbstarctElectrode$load_dimnames_with_epochs(type)
Arguments
typesee
load_data_with_epochs
RAVEAbstarctElectrode$load_data_with_blocks()
load electrode block-wise data (with reference), useful when epoch is absent
Usage
RAVEAbstarctElectrode$load_data_with_blocks(blocks, type, simplify = TRUE)
Arguments
blockssession blocks
typedata type such as
"power","phase","voltage","wavelet-coefficient".simplifywhether to simplify the result
Returns
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
Usage
RAVEAbstarctElectrode$load_blocks(blocks, type, simplify = TRUE)
Arguments
blocks, type, simplifysee
load_data_with_blocks
RAVEAbstarctElectrode$load_dim_with_blocks()
get expected dimension information for block-based loader
Usage
RAVEAbstarctElectrode$load_dim_with_blocks(blocks, type)
Arguments
blocks, typesee
load_data_with_blocks
RAVEAbstarctElectrode$clone()
The objects of this class are cloneable with this method.
Usage
RAVEAbstarctElectrode$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
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)
}
Definition for epoch class
Description
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.
Super class
ravepipeline::RAVESerializable -> RAVEEpoch
Public fields
nameepoch name, character
subjectRAVESubjectinstancedataa list of trial information, internally used
tabletrial epoch table
.columnsepoch column names, internally used
Active bindings
columnscolumns of trial table
n_trialstotal number of trials
trialstrial numbers
excluded_trialstrial numbers whose
ExcludedHintisTRUEavailable_eventsavailable events other than trial onset
available_condition_typeavailable condition type other than the default
Methods
Public methods
Inherited methods
RAVEEpoch$@marshal()
Internal method
Usage
RAVEEpoch$@marshal(...)
Arguments
...internal arguments
RAVEEpoch$@unmarshal()
Internal method
Usage
RAVEEpoch$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVEEpoch$new()
constructor
Usage
RAVEEpoch$new(subject, name)
Arguments
subjectRAVESubjectinstance or characternamecharacter, make sure
"epoch_<name>.csv"is in meta folder
RAVEEpoch$trial_at()
get ith trial
Usage
RAVEEpoch$trial_at(i, df = TRUE)
Arguments
itrial number
dfwhether to return as data frame or a list
RAVEEpoch$update_table()
manually update table field
Usage
RAVEEpoch$update_table()
Returns
self$table
RAVEEpoch$set_trial()
set one trial
Usage
RAVEEpoch$set_trial(Block, Time, Trial, Condition, ...)
Arguments
Blockblock string
Timetime in second
Trialpositive integer, trial number
Conditioncharacter, trial condition
...other key-value pairs corresponding to other optional columns;
ExcludedHintdefaults toFALSE
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.
Usage
RAVEEpoch$exclude_trials(..., add = TRUE)
Arguments
...trial numbers; flattened with
unlist(list(...))addwhether to add to the trials already marked (default);
FALSEreplaces them, soexclude_trials(add = FALSE)clears every mark
Returns
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.
Usage
RAVEEpoch$save()
Returns
Paths of the written files, invisibly
RAVEEpoch$get_event_colname()
Get epoch column name that represents the desired event
Usage
RAVEEpoch$get_event_colname(
event = "",
missing = c("warning", "error", "none")
)
Arguments
eventa character string of the event, see
$available_eventsfor all available events; set to"trial onset","default", or blank to use the defaultmissingwhat to do if event is missing; default is to warn
Returns
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
Usage
RAVEEpoch$get_condition_colname(
condition_type = "default",
missing = c("error", "warning", "none")
)
Arguments
condition_typea character string of the condition type, see
$available_condition_typefor all available condition types; set to"default"or blank to use the defaultmissingwhat to do if condition type is missing; default is to warn if the condition column is not found.
Returns
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.
Usage
RAVEEpoch$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# 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
}
Defines preprocess configurations
Description
R6 class definition
Super class
ravepipeline::RAVESerializable -> RAVEPreprocessSettings
Public fields
current_versioncurrent configuration setting version
pathsettings file path
backup_pathalternative back up path for redundancy checks
datalist of raw configurations, internally used only
subjectRAVESubjectinstanceread_onlywhether the configuration should be read-only, not yet implemented
Active bindings
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'projectraw_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 useraw_path2combined withraw_path2_typefor supporting 'BIDS' formatraw_path_typelegacy type for
raw_path, always returns'native'
Methods
Public methods
Inherited methods
RAVEPreprocessSettings$@marshal()
Internal method
Usage
RAVEPreprocessSettings$@marshal(...)
Arguments
...internal arguments
RAVEPreprocessSettings$@unmarshal()
Internal method
Usage
RAVEPreprocessSettings$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVEPreprocessSettings$new()
constructor
Usage
RAVEPreprocessSettings$new(subject, read_only = TRUE)
Arguments
subjectcharacter or
RAVESubjectinstanceread_onlywhether subject should be read-only (not yet implemented)
RAVEPreprocessSettings$valid()
whether configuration is valid or not
Usage
RAVEPreprocessSettings$valid()
RAVEPreprocessSettings$has_raw()
whether raw data folder exists
Usage
RAVEPreprocessSettings$has_raw()
RAVEPreprocessSettings$set_blocks()
set blocks
Usage
RAVEPreprocessSettings$set_blocks(blocks, force = FALSE)
Arguments
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
Usage
RAVEPreprocessSettings$get_block_paths( block, force_native = FALSE, check = TRUE )
Arguments
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
Usage
RAVEPreprocessSettings$set_electrodes( electrodes, type = SIGNAL_TYPES, add = FALSE )
Arguments
electrodesinteger vectors
typesignal type of electrodes, see
SIGNAL_TYPESaddwhether to add to current settings
RAVEPreprocessSettings$set_sample_rates()
set sample frequency
Usage
RAVEPreprocessSettings$set_sample_rates(srate, type = SIGNAL_TYPES)
Arguments
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
Usage
RAVEPreprocessSettings$migrate(force = FALSE)
Arguments
forcewhether to force migrate and save settings
RAVEPreprocessSettings$electrode_info()
get electrode information
Usage
RAVEPreprocessSettings$electrode_info(electrode)
Arguments
electrodeinteger
Returns
list of electrode type, number, etc.
RAVEPreprocessSettings$save()
save settings to hard disk
Usage
RAVEPreprocessSettings$save()
RAVEPreprocessSettings$get_compose_weights()
get weights of each composed channels
Usage
RAVEPreprocessSettings$get_compose_weights(flat = TRUE)
Arguments
flatwhether to flatten the data frame; default is true
Returns
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.
Usage
RAVEPreprocessSettings$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
# 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
}
Definition for 'RAVE' project class
Description
See as_rave_project for creating 'RAVE' project
class
Super class
ravepipeline::RAVESerializable -> RAVEProject
Active bindings
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
Methods
Public methods
Inherited methods
RAVEProject$@marshal()
Internal method
Usage
RAVEProject$@marshal(...)
Arguments
...internal arguments
RAVEProject$@unmarshal()
Internal method
Usage
RAVEProject$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVEProject$print()
override print method
Usage
RAVEProject$print(...)
Arguments
...ignored
RAVEProject$format()
override format method
Usage
RAVEProject$format(...)
Arguments
...ignored
RAVEProject$new()
constructor
Usage
RAVEProject$new(project_name, strict = TRUE, parent_path = NULL)
Arguments
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
Usage
RAVEProject$subjects()
Returns
character vector
RAVEProject$has_subject()
whether a specific subject exists in this project
Usage
RAVEProject$has_subject(subject_code)
Arguments
subject_codecharacter, subject name
Returns
true or false whether subject is in the project
RAVEProject$group_path()
get group data path for 'RAVE' module
Usage
RAVEProject$group_path(module_id, must_work = FALSE)
Arguments
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
Usage
RAVEProject$subject_pipelines( pipeline_name, cache = FALSE, check = TRUE, all = FALSE )
Arguments
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
Returns
A data table of pipeline time-stamps and directories
RAVEProject$clone()
The objects of this class are cloneable with this method.
Usage
RAVEProject$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Defines 'RAVE' subject class
Description
R6 class definition
Super class
ravepipeline::RAVESerializable -> RAVESubject
Active bindings
@implthe internal object
projectproject instance of current subject; see
RAVEProjectproject_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
NApreprocess_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
RAVEPreprocessSettingsblockssubject 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
Methods
Public methods
Inherited methods
RAVESubject$@marshal()
Internal method
Usage
RAVESubject$@marshal(...)
Arguments
...internal arguments
RAVESubject$@unmarshal()
Internal method
Usage
RAVESubject$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubject$print()
override print method: prints format()
Usage
RAVESubject$print(...)
Arguments
...passed to
format()
RAVESubject$format()
summary of the subject's data
Usage
RAVESubject$format(...)
Arguments
...ignored
Returns
A character vector, one element per line
RAVESubject$new()
constructor
Usage
RAVESubject$new( project_name, subject_code = NULL, strict = TRUE, parent_path = NULL )
Arguments
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
Usage
RAVESubject$meta_data(
meta_type = c("electrodes", "frequencies", "time_points", "epoch", "references"),
meta_name = "default",
strict = TRUE
)
Arguments
meta_typechoices are 'electrodes', 'frequencies', 'time_points', 'epoch', 'references'
meta_nameif
meta_type='epoch', read in'epoch_<meta_name>.csv'; ifmeta_type='references', read in'reference_<meta_name>.csv'.strictwhether to raise errors if the files are missing; default is true; alternative is to return
NULLon missing
Returns
data frame
RAVESubject$valid_electrodes()
get valid electrode numbers
Usage
RAVESubject$valid_electrodes(reference_name = NULL, refresh = FALSE)
Arguments
reference_namecharacter, reference name, see
meta_nameinself$meta_dataorload_meta2whenmeta_typeis 'reference'refreshwhether to reload reference table before obtaining data, default is false
Returns
integer vector of valid electrodes
RAVESubject$initialize_paths()
create subject's directories on hard disk
Usage
RAVESubject$initialize_paths(include_freesurfer = TRUE)
Arguments
include_freesurferwhether to create 'FreeSurfer' path
RAVESubject$set_default()
set default key-value pair for the subject, used by 'RAVE' modules
Usage
RAVESubject$set_default(key, value, namespace = "default")
Arguments
keycharacter
valuevalue of the key
namespacefile name of the note (without post-fix)
Returns
The same as value
RAVESubject$get_default()
get default key-value pairs for the subject, used by 'RAVE' modules
Usage
RAVESubject$get_default( ..., default_if_missing = NULL, simplify = TRUE, namespace = "default" )
Arguments
...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
TRUEnamespacefile name of the note (without post-fix)
Returns
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
Usage
RAVESubject$get_note_summary(namespaces, include_history = FALSE)
Arguments
namespacesnamespaces for the entries; see method
get_defaultorset_default. Default is all possible namespacesinclude_historywhether to include history entries; default is false
Returns
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
Usage
RAVESubject$get_epoch( epoch_name = "default", as_table = FALSE, trial_starts = 0 )
Arguments
epoch_nameepoch name, depending on the subject's meta files
as_tablewhether to convert to
data.frame; default is falsetrial_startsthe start of the trial relative to epoch time; default is 0
Returns
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
Usage
RAVESubject$get_reference(reference_name, simplify = FALSE)
Arguments
reference_namereference name, depending on the subject's meta file settings
simplifywhether to only return the reference column
Returns
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
Usage
RAVESubject$get_electrode_table( electrodes, reference_name, subset = FALSE, simplify = FALSE, warn = TRUE )
Arguments
electrodescharacters indicating integers such as
"1-14,20-30", or integer vector of electrode numbersreference_namesee method
get_referencesubsetwhether to subset the resulting data table
simplifywhether to only return electrodes
warnwhether to warn about missing electrodes; default is true
Returns
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.
Usage
RAVESubject$get_frequency(simplify = TRUE)
Arguments
simplifywhether to simplify as vector
Returns
If simplify is true, returns a vector of frequencies;
otherwise returns a table.
RAVESubject$list_pipelines()
list saved pipelines
Usage
RAVESubject$list_pipelines( pipeline_name, cache = FALSE, check = TRUE, all = FALSE )
Arguments
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
Returns
A table of pipeline registry
RAVESubject$load_pipeline()
load saved pipeline
Usage
RAVESubject$load_pipeline(directory)
Arguments
directorypipeline directory name
Returns
A PipelineTools instance
RAVESubject$clone()
The objects of this class are cloneable with this method.
Usage
RAVESubject$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
'RAVE' class for base repository
Description
The class is for creating child classes, to instantiate the class,
please use prepare_subject_bare0 to create base repository.
Super class
ravepipeline::RAVESerializable -> RAVESubjectRepository
Public fields
@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
Active bindings
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 <- TRUEprojectproject instance, see
RAVEProjectsubjectsubject instance, see
RAVESubjectelectrode_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 channelelectrode_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_instancesreference_instancesinstances of reference channels, for referencing on the fly, used for
electrode_instancesdigest_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
Methods
Public methods
Inherited methods
RAVESubjectRepository$@get_container()
Internal method, do not use it directly
Usage
RAVESubjectRepository$@get_container()
RAVESubjectRepository$@marshal()
Internal method
Usage
RAVESubjectRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRepository$@unmarshal()
Internal method
Usage
RAVESubjectRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRepository$print()
User-friendly print method
Usage
RAVESubjectRepository$print()
RAVESubjectRepository$new()
constructor
Usage
RAVESubjectRepository$new( subject, electrodes = NULL, reference_name = NULL, ..., auto_exclude = TRUE, quiet = TRUE, repository_id = NULL, strict = TRUE, .class = NULL )
Arguments
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
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectRepository$export_matlab(..., verbose = TRUE)
Arguments
...reserved for child classes
verboseprint progresses
Returns
The root directory where the files are stored.
RAVESubjectRepository$get_electrode_coordinate()
Get loaded electrode coordinates by type
Usage
RAVESubjectRepository$get_electrode_coordinate( type = "LFP", electrodes = KEY_MISSING, strict = TRUE )
Arguments
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
Returns
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.
Usage
RAVESubjectRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
'RAVE' class for epoch repository - time-frequency phase
Description
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.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochPhaseRepository
Active bindings
phasea named map of time-frequency coefficient phase, mounted by
mount_data
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochPhaseRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochPhaseRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochPhaseRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochPhaseRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectEpochTimeFreqBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectEpochPhaseRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for epoch repository - time-frequency power
Description
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.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochPowerRepository
Active bindings
powera named map of time-frequency power spectrogram, mounted by
mount_data
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochPowerRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochPowerRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochPowerRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochPowerRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectEpochTimeFreqBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectEpochPowerRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for epoch repository - raw voltage
Description
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.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochRawVoltageRepository
Active bindings
digest_keya list of repository data used to generate repository signature
raw_voltagea named map of raw voltage data, mounted by
mount_data, alias ofget_containerreference_tablereference table, all channels will be marked as no reference
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochRawVoltageRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochRawVoltageRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochRawVoltageRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochRawVoltageRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectEpochRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether the mode should be strict; default is true and errors out when subject is missing
lazy_loadwhether to delay calling
mount_data; default is falsereference_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
Usage
RAVESubjectEpochRawVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectEpochRawVoltageRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for epoch repository
Description
Compared to RAVESubjectBaseRepository, this repository
requires epoch information. please use
prepare_subject_with_epochs to instantiate this repository.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository
Active bindings
needs_updatewrite-only attribute when subject needs to be reloaded from the disk and reference table needs to be updated, use
repo$needs_update <- TRUEmeta_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 frequenciessample_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, usesample_ratesfor more accurate numberepoch_namename of the epoch table
epochRAVEEpochinstanceepoch_tableepoch table, equivalent to
repository$epoch$tablestitch_eventsevents where
time_windowsare based ontime_windowslist of time ranges to load; the time is relative to
stitch_events; default is trial onsetelectrode_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_instancesdigest_keya list of repository data used to generate repository signature
Methods
Public methods
Inherited methods
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()
RAVESubjectEpochRepository$@marshal()
Internal method
Usage
RAVESubjectEpochRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectEpochRepository$export_matlab(..., verbose = TRUE)
Arguments
...reserved for child classes
verboseprint progresses
Returns
The root directory where the files are stored.
RAVESubjectEpochRepository$set_epoch()
change trial epoch profiles
Usage
RAVESubjectEpochRepository$set_epoch(epoch_name, stitch_events = NULL)
Arguments
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
Usage
RAVESubjectEpochRepository$mount_data(..., force = TRUE, electrodes = NULL)
Arguments
...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
Usage
RAVESubjectEpochRepository$get_container(force = FALSE, ...)
Arguments
force, ...passed to
mount_data
Returns
A named map, typically with data arrays, shape/dimension information
RAVESubjectEpochRepository$clone()
The objects of this class are cloneable with this method.
Usage
RAVESubjectEpochRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
'RAVE' class for epoch repository - time-frequency (internal)
Description
The repository inherits link{RAVESubjectEpochRepository}, with epoch
trials, and is intended for loading processed and referenced time-frequency
coefficients.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository
Active bindings
sample_ratetime-frequency coefficient sample rate
frequencyfrequencies where the time-frequency coefficients are evaluated
timetime in seconds for each trial
time_pointssee
timefield, existed for backward compatibilitysignal_typedo not use
digest_keya list of repository data used to generate repository signature
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochTimeFreqBaseRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochTimeFreqBaseRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochTimeFreqBaseRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochTimeFreqBaseRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)data_typefor child classes to fill; data type (power, phase, or complex time-frequency coefficients)
...passed to
RAVESubjectEpochRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectEpochTimeFreqBaseRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectEpochTimeFreqBaseRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for epoch repository - time-frequency
Description
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.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochTimeFreqBaseRepository -> RAVESubjectEpochTimeFreqCoefRepository
Active bindings
coefficientsa named map of time-frequency coefficient data, mounted by
mount_datawaveletnot used anymore, see
coefficients
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochTimeFreqCoefRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochTimeFreqCoefRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochTimeFreqCoefRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochTimeFreqCoefRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectEpochTimeFreqBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectEpochTimeFreqCoefRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for epoch repository - voltage
Description
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.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectEpochRepository -> RAVESubjectEpochVoltageRepository
Active bindings
digest_keya list of repository data used to generate repository signature
voltagea named map of voltage data, mounted by
mount_data
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectEpochVoltageRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectEpochVoltageRepository$@unmarshal()
Internal method
Usage
RAVESubjectEpochVoltageRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectEpochVoltageRepository$new()
constructor
Usage
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 )
Arguments
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 onsetstitch_eventsevents where the
time_windowsis based; default is trial onset (NULL)...passed to
RAVESubjectEpochRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectEpochVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectEpochVoltageRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
'RAVE' class for loading time-frequency phase components
Description
Loads time-frequency phase
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockPhaseRepository
Active bindings
phasedata container, alias of
get_container
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectRecordingBlockPhaseRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockPhaseRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockPhaseRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockPhaseRepository$new()
constructor
Usage
RAVESubjectRecordingBlockPhaseRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectRecordingBlockPhaseRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
prepare_subject_phase_with_blocks
'RAVE' class for loading time-frequency power components
Description
Loads time-frequency power
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockPowerRepository
Active bindings
powerdata container, alias of
get_container
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectRecordingBlockPowerRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockPowerRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockPowerRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockPowerRepository$new()
constructor
Usage
RAVESubjectRecordingBlockPowerRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectRecordingBlockPowerRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
prepare_subject_power_with_blocks
'RAVE' class for blocks of voltage repository
Description
Compared to RAVESubjectBaseRepository, this repository
loads the entire voltage traces for selected blocks; use
prepare_subject_raw_voltage_with_blocks to instantiate this
repository.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockRawVoltageRepository
Active bindings
reference_namename of reference table; always
'noref'reference_tablereference table; a reference table with
'noref'on all channelsreferences_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 frequenciesraw_voltagedata container, alias of
get_container
Methods
Public methods
Inherited methods
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()
RAVESubjectRecordingBlockRawVoltageRepository$@marshal()
Internal method
Usage
RAVESubjectRecordingBlockRawVoltageRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockRawVoltageRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockRawVoltageRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockRawVoltageRepository$new()
constructor
Usage
RAVESubjectRecordingBlockRawVoltageRepository$new( subject, electrodes = NULL, reference_name = "noref", blocks = NULL, downsample = NA, ..., quiet = TRUE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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 warningblocksname 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
NAand no down-sample is performed....passed to
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectRecordingBlockRawVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectRecordingBlockRawVoltageRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
prepare_subject_raw_voltage_with_blocks
'RAVE' class for loading entire recording block repository
Description
Compared to RAVESubjectBaseRepository, this repository
requires specifying block information. please use
prepare_subject_with_blocks to instantiate this repository.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository
Active bindings
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 <- TRUEblocksnames of recording blocks
electrode_tablethe entire electrode table with reference information
digest_keya list of repository data used to generate repository signature
Methods
Public methods
Inherited methods
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()
RAVESubjectRecordingBlockRepository$@marshal()
Internal method
Usage
RAVESubjectRecordingBlockRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockRepository$new()
constructor
Usage
RAVESubjectRecordingBlockRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectRecordingBlockRepository$export_matlab(..., verbose = TRUE)
Arguments
...reserved for child classes
verboseprint progresses
Returns
The root directory where the files are stored.
RAVESubjectRecordingBlockRepository$get_container()
get container where loaded data are stored
Usage
RAVESubjectRecordingBlockRepository$get_container(force = FALSE, ...)
Arguments
force, ...passed to
mount_data
Returns
A named map, typically with data arrays, shape/dimension information
RAVESubjectRecordingBlockRepository$clone()
The objects of this class are cloneable with this method.
Usage
RAVESubjectRecordingBlockRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
'RAVE' class for loading entire block of time-frequency coefficients
Description
'RAVE' class for loading entire block of time-frequency coefficients
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository
Active bindings
sample_ratesa named list of sampling frequencies; the names are signal types (
'LFP','Auxiliary', or'Spike') and the values are the sampling frequenciessample_ratenumeric sample rate for 'spectrogram'
Methods
Public methods
-
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal() -
RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data()
Inherited methods
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()
RAVESubjectRecordingBlockTimeFreqBaseRepository$@marshal()
Internal method
Usage
RAVESubjectRecordingBlockTimeFreqBaseRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockTimeFreqBaseRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockTimeFreqBaseRepository$new()
constructor
Usage
RAVESubjectRecordingBlockTimeFreqBaseRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectRecordingBlockTimeFreqBaseRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectRecordingBlockTimeFreqBaseRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
'RAVE' class for loading time-frequency coefficients
Description
Loads time-frequency coefficients (complex numbers)
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockTimeFreqBaseRepository -> RAVESubjectRecordingBlockTimeFreqCoefRepository
Active bindings
coefficientsdata container, alias of
get_container
Methods
Public methods
Inherited methods
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
Usage
RAVESubjectRecordingBlockTimeFreqCoefRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockTimeFreqCoefRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockTimeFreqCoefRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockTimeFreqCoefRepository$new()
constructor
Usage
RAVESubjectRecordingBlockTimeFreqCoefRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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.
Usage
RAVESubjectRecordingBlockTimeFreqCoefRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
prepare_subject_time_frequency_coefficients_with_blocks
'RAVE' class for blocks of voltage repository
Description
Compared to RAVESubjectBaseRepository, this repository
loads the entire voltage traces for selected blocks; use
prepare_subject_voltage_with_blocks to instantiate this
repository.
Super classes
ravepipeline::RAVESerializable -> RAVESubjectRepository -> RAVESubjectRecordingBlockRepository -> RAVESubjectRecordingBlockVoltageRepository
Active bindings
sample_ratesa named list of sampling frequencies; the names are signal types (
'LFP','Auxiliary', or'Spike') and the values are the sampling frequenciesvoltagedata container, alias of
get_container
Methods
Public methods
Inherited methods
ravepipeline::RAVESerializable$@compare()RAVESubjectRepository$@get_container()RAVESubjectRepository$get_electrode_coordinate()RAVESubjectRepository$print()RAVESubjectRecordingBlockRepository$export_matlab()RAVESubjectRecordingBlockRepository$get_container()
RAVESubjectRecordingBlockVoltageRepository$@marshal()
Internal method
Usage
RAVESubjectRecordingBlockVoltageRepository$@marshal(...)
Arguments
...internal arguments
RAVESubjectRecordingBlockVoltageRepository$@unmarshal()
Internal method
Usage
RAVESubjectRecordingBlockVoltageRepository$@unmarshal(object, ...)
Arguments
object, ...internal arguments
RAVESubjectRecordingBlockVoltageRepository$new()
constructor
Usage
RAVESubjectRecordingBlockVoltageRepository$new( subject, electrodes = NULL, reference_name = NULL, blocks = NULL, downsample = NA, ..., quiet = FALSE, repository_id = NULL, strict = TRUE, lazy_load = FALSE, .class = NULL )
Arguments
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
NAand no down-sample is performed....passed to
RAVESubjectBaseRepositoryconstructorquietsee field
quietrepository_idsee field
repository_idstrictwhether 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
Usage
RAVESubjectRecordingBlockVoltageRepository$mount_data( ..., force = TRUE, electrodes = NULL )
Arguments
...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.
Usage
RAVESubjectRecordingBlockVoltageRepository$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
prepare_subject_voltage_with_blocks
Class definition for micro-wire spike channels
Description
Class definition for micro-wire spike channels
Super classes
ravepipeline::RAVESerializable -> RAVEAbstarctElectrode -> Spike_electrode
Active bindings
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
Methods
Public methods
Inherited methods
Spike_electrode$@marshal()
Internal method
Usage
Spike_electrode$@marshal(...)
Arguments
...internal arguments
Spike_electrode$@unmarshal()
Internal method
Usage
Spike_electrode$@unmarshal(object)
Arguments
object, ...internal arguments
Spike_electrode$print()
print electrode summary
Usage
Spike_electrode$print()
Spike_electrode$set_reference()
set reference for current electrode
Usage
Spike_electrode$set_reference(reference)
Arguments
referenceeither
NULLorLFP_electrodeinstance
Spike_electrode$new()
constructor
Usage
Spike_electrode$new(subject, number, quiet = FALSE)
Arguments
subject, number, quietsee constructor in
RAVEAbstarctElectrode
Spike_electrode$.load_noref_voltage()
load non-referenced voltage (internally used)
Usage
Spike_electrode$.load_noref_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
sratevoltage signal sample rate
Spike_electrode$.load_raw_voltage()
load raw voltage (no process)
Usage
Spike_electrode$.load_raw_voltage(reload = FALSE)
Arguments
reloadwhether to reload cache
Spike_electrode$load_data_with_epochs()
method to load electrode data
Usage
Spike_electrode$load_data_with_epochs(type = c("raw-voltage", "voltage"))
Arguments
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
Usage
Spike_electrode$load_dimnames_with_epochs(type = c("raw-voltage", "voltage"))
Arguments
typesee
load_data_with_epochs
Spike_electrode$load_data_with_blocks()
load electrode block-wise data (with no reference), useful when epoch is absent
Usage
Spike_electrode$load_data_with_blocks(
blocks,
type = c("raw-voltage", "voltage"),
simplify = TRUE
)
Arguments
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
Returns
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
Usage
Spike_electrode$load_dim_with_blocks(
blocks,
type = c("raw-voltage", "voltage")
)
Arguments
blocks, typesee
load_data_with_blocks
Spike_electrode$clear_cache()
method to clear cache on hard drive
Usage
Spike_electrode$clear_cache(...)
Arguments
...ignored
Spike_electrode$clear_memory()
method to clear memory
Usage
Spike_electrode$clear_memory(...)
Arguments
...ignored
Spike_electrode$clone()
The objects of this class are cloneable with this method.
Usage
Spike_electrode$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Class definition of the native YAEL image pipeline
Description
Rigid 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.
See examples at as_yael_process
(with engine = "native") and yael_preprocess_native.
Details
Differences from YAELProcess and the rpyANTs pipeline
behind it:
There is no
deep_atropos: argumentuse_antspynetofmap_to_templateis ignored, and the tissue segmentation with the template priors (theAtroposbranch) 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
affinetransform is given.Algorithms: ravetools runs a greedy
SyNwith a single field and a fixed-point inverse; its linear stages use an automatic step size, random (Bernoulli) sampling and no histogram matching, and itsaffineregistration starts with a rigid pass. The smoothing of theSyNupdate field takes the rpyANTs values (3 for the initial registration, 3.5 for the final one) as aGaussianstandard deviation in voxels, whereasANTsreads 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 initial registration, which places the template brain mask and the tissue priors, always goes to the 1 mm'mni_icbm152_nlin_asym_09a'(see the brain extraction below), whereas rpyANTs registers to the template of the normalization.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 (
Atroposkeeps 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).Brain extraction (
yael_brain_extract): the brain mask of'mni_icbm152_nlin_asym_09a', mapped to the native image by the initial registration whatever the template of the normalization, is adjusted to the subject, as inantsBrainExtraction.sh, on the image corrected byN4without intensity truncation. A three-class segmentation of the mask grown by 2 mm finds the largest connected white and gray matter; an erosion, the largest component, a dilation, hole filling and a closing cut what hangs on the brain by a thread, and the mapped mask is added back. Then, as in the watershed of 'FreeSurfer', the gray and white matter that dark voxels (CSFor bone) cut off from the brain, such as skull marrow,duraorscalp, leaves the mask, also where the mapped mask held it, whichantsBrainExtraction.shkeeps whole. The thin strands this can leave (such as marrow as dark as gray matter) go too: the part of the mask that survives an erosion by 2 mm, grown back by 3 mm and kept inside the mask, holds the brain but not what is thinner than about 4 mm and reaches more than about 1 mm out. The distances are millimeters along each axis of the image, so they hold on thick slices. The result replaces the mapped mask in the tissue segmentation (whose priors also come from that template), in the final registration and its final brain mask and image (brainmask2.nii.gz,brain2.nii.gz), and inconstruct_ants_folder_from_template; the files of the extraction in the stage folder of the normalization are reused when all of them are there. The rpyANTs engine uses a network mask fromdeep_atroposfor the registration when'antspynet'is available, and always saves the mapped mask. The mapped mask is kept, with a warning, when the segmentation fails or the volume changes by more than 20 percent.White-matter artifacts: the brain mask can still hold skull marrow that touches the brain with no dark voxel between, which the tissue segmentation labels as white matter and the final registration would pull into the brain. Each white-matter voxel casts one ray away from the center of the white matter; when the ray misses the smoothed outer surface of the gray matter and the cerebellum (
ravetools::mris_outer_surface), the voxel is taken to lie outside the brain. These voxels, dilated by two voxels, are left out of the white-matter channel, and those labeled white matter also leave the brain mask and the brain image of the final registration; the cone below the center of the white matter, which holds the brain stem, is kept, and the removed volume is logged. The tissue classes keep the order of their priors; when the median intensities of theCSF, gray-matter and white-matter classes do not increase, a warning is given and nothing is left out.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_templateandtransform_image_to_templatereturnieegio_volumeobjects; only nearest-neighbor and linear (trilinear) interpolation are available, andinterpolator = "auto"follows its documented rule (YAELProcessuses nearest-neighbor); the queries never create folders;set_input_imagereads the new image before it removes the old one; atlases are saved asfloat32as with'ANTs', and the'NIfTI'data types of other images are chosen by ieegio; normalization results are replaced together, after the new ones are complete, and staleants<K>transforms of earlier layouts are removed; nothing is written into the template folders.Streamlines: ieegio reads and writes
VTKfiles through 'Python', sogenerate_streamlines_from_templateskipsVTKinputs (with a warning) and refusesformat = "vtk"; it also refusesformat = "tt"and savesTTinputs asTCKfiles, since ieegio cannot writeTTfiles.
Super class
ravepipeline::RAVESerializable -> YAELNativeProcess
Active bindings
subject_code'RAVE' subject code
image_typesallowed image types
work_pathWorking directory ('RAVE' imaging path)
Methods
Public methods
Inherited methods
YAELNativeProcess$@marshal()
Internal method
Usage
YAELNativeProcess$@marshal(...)
Arguments
...internal arguments
YAELNativeProcess$@unmarshal()
Internal method
Usage
YAELNativeProcess$@unmarshal(object, ...)
Arguments
object, ...internal arguments
YAELNativeProcess$new()
Constructor to instantiate the class
Usage
YAELNativeProcess$new(subject, image_types, imaging_path = NULL, ...)
Arguments
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
Usage
YAELNativeProcess$set_input_image(
path,
type = YAEL_IMAGE_TYPES,
overwrite = FALSE,
on_error = c("warning", "error", "ignore")
)
Arguments
pathpath to the image files in
'NIfTI'or'MGZ'formattypetype 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
overwriteis false, how should this error be reported; choices are'warning'(default),'error'(throw error and abort), or'ignore'.
Returns
whether the image has been set (or replaced)
YAELNativeProcess$get_input_image()
Get image path
Usage
YAELNativeProcess$get_input_image(type = YAEL_IMAGE_TYPES)
Arguments
typetype of the image
Returns
Absolute path if the image, or NULL if missing
YAELNativeProcess$get_subject()
Get 'RAVE' subject instance
Usage
YAELNativeProcess$get_subject(..., strict = FALSE)
Arguments
...ignored
strictpassed to
as_rave_subject
Returns
'RAVE' subject instance
YAELNativeProcess$register_to_T1w()
Register other images to 'T1' weighted 'MRI'
with two rigid passes (mutual information)
Usage
YAELNativeProcess$register_to_T1w( image_type = "CT", reverse = FALSE, verbose = TRUE )
Arguments
image_typetype of the image to register, must be set via
process$set_input_imagefirst.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 imageverbosewhether to print out the process; default is true
Returns
Nothing
YAELNativeProcess$get_native_mapping()
Get the mapping configurations used by register_to_T1w
Usage
YAELNativeProcess$get_native_mapping( image_type = YAEL_IMAGE_TYPES, relative = FALSE )
Arguments
image_typetype of the image registered to 'T1' weighted 'MRI'
relativewhether to use relative path (to the
work_pathfield)
Returns
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
Usage
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,
...
)
Arguments
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 priorsverbosewhether to print out the process; default is true
...additional tuning parameters:
affine_transform(optional initialaffinetransform, an'ANTs'.matfile from the template to the native image as point map; the final registration starts from it, and for theMNI152templates the registration of the brain extraction too, which then only runs its non-linear stage),with_skull(whether to register the images with skull; default is false), andcost_function(only'CC', the local cross-correlation, is available; other values give a warning); other arguments are ignored
Returns
See method get_template_mapping
YAELNativeProcess$get_template_mapping()
Get configurations used for normalization
Usage
YAELNativeProcess$get_template_mapping( template_name = rpyants_builtin_templates(), native_type = "T1w", relative = FALSE )
Arguments
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)
Returns
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
Usage
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
)
Arguments
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) interpolationverbosewhether the print out the progress
Returns
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
Usage
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
)
Arguments
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) interpolationverbosewhether the print out the progress
Returns
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
Usage
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
)
Arguments
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 neighborsurfaceswhether to generate surfaces (triangle mesh); default is
NA(generate if not existed). Other choices areTRUEfor always generating and overwriting surface files, orFALSEto 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_surfsmooth_methodhow to smooth the surfaces:
"implicit"(default,vcg_smooth_implicitwithlambdaanddegree) or"explicit"(mris_smooth); passed tovolume_to_surfmax_verticessurfaces with more vertices are reduced to about this many after smoothing; passed to
volume_to_surf; default is500000
Returns
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
Usage
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"
)
Arguments
template_namewhich template to use; the template must have been used in
map_to_templateprior to calling this methodstreamlines_folderpath to folder containing streamline tract files (
'.tck','.trk','.tt', or'.vtk'); all matching files are processed recursively, exceptVTKfiles ('.vtk','.vtp'), which ieegio can only read through 'Python': they are skipped with a warningverbosewhether to print progress; default is
TRUEformatoutput format for the saved streamlines;
"auto"(default) preserves the original file extension, except thatTTfiles are saved asTCK(ieegio has noTTwriter);"tck"and"trk"convert every file."tt"(no writer) and"vtk"(written through 'Python') are errorsnative_typewhich native image type defines the target space; default is
"T1w"
Returns
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
Usage
YAELNativeProcess$transform_points_to_template( native_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
Arguments
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
Returns
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
Usage
YAELNativeProcess$transform_points_from_template( template_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
Arguments
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
Returns
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.
Usage
YAELNativeProcess$write_talairach_xfm( template_name = rpyants_builtin_templates() )
Arguments
template_nametemplate that has been used in
map_to_template
Returns
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 brain mask of the normalization
(yael_brain_extract, read from its stage folder
'tmp/coregister_T1w_with_<template>' when all of its files are
there, computed again otherwise; '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.
Usage
YAELNativeProcess$construct_ants_folder_from_template( template_name = rpyants_builtin_templates(), add_surfaces = TRUE )
Arguments
template_nametemplate to use for mapping;
NULLonly 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'pialsurfaces. 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
Usage
YAELNativeProcess$get_brain(
electrodes = TRUE,
coord_sys = c("scannerRAS", "tkrRAS", "MNI152", "MNI305"),
...
)
Arguments
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 underproject_namewill be loaded; whenelectrodesis adata.frame, or path to a'csv'file, then please specifycoord_syson what is the coordinate system used for columns"x","y", and"z".coord_syscoordinate system if
electrodesis 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'(templateMNIcoordinate system averaged over 152 subjects; this is the commonMNIcoordinate space we often refer to), and'MNI305'(templateMNIcoordinate 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.
Usage
YAELNativeProcess$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Class definition of 'YAEL' image pipeline
Description
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
Super class
ravepipeline::RAVESerializable -> YAELProcess
Active bindings
subject_code'RAVE' subject code
image_typesallowed image types
work_pathWorking directory ('RAVE' imaging path)
Methods
Public methods
Inherited methods
YAELProcess$@marshal()
Internal method
Usage
YAELProcess$@marshal(...)
Arguments
...internal arguments
YAELProcess$@unmarshal()
Internal method
Usage
YAELProcess$@unmarshal(object, ...)
Arguments
object, ...internal arguments
YAELProcess$new()
Constructor to instantiate the class
Usage
YAELProcess$new(subject, image_types, imaging_path = NULL, ...)
Arguments
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
Usage
YAELProcess$set_input_image(
path,
type = YAEL_IMAGE_TYPES,
overwrite = FALSE,
on_error = c("warning", "error", "ignore")
)
Arguments
pathpath to the image files in
'NIfTI'formattypetype 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
overwriteis false, how should this error be reported; choices are'warning'(default),'error'(throw error and abort), or'ignore'.
Returns
whether the image has been set (or replaced)
YAELProcess$get_input_image()
Get image path
Usage
YAELProcess$get_input_image(type = YAEL_IMAGE_TYPES)
Arguments
typetype of the image
Returns
Absolute path if the image
YAELProcess$get_subject()
Get 'RAVE' subject instance
Usage
YAELProcess$get_subject(..., strict = FALSE)
Arguments
...ignored
strictpassed to
as_rave_subject
Returns
'RAVE' subject instance
YAELProcess$register_to_T1w()
Register other images to 'T1' weighted 'MRI'
Usage
YAELProcess$register_to_T1w(image_type = "CT", reverse = FALSE, verbose = TRUE)
Arguments
image_typetype of the image to register, must be set via
process$set_input_imagefirst.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 imageverbosewhether to print out the process; default is true
Returns
Nothing
YAELProcess$get_native_mapping()
Get the mapping configurations used by register_to_T1w
Usage
YAELProcess$get_native_mapping(image_type = YAEL_IMAGE_TYPES, relative = FALSE)
Arguments
image_typetype of the image registered to 'T1' weighted 'MRI'
relativewhether to use relative path (to the
work_pathfield)
Returns
A list of moving and fixing images, with rigid transformations from different formats.
YAELProcess$map_to_template()
Normalize native brain to 'MNI152' template
Usage
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,
...
)
Arguments
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 usesdeep_atroposinstead of the conventionalatroposto 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.
Returns
See method get_template_mapping
YAELProcess$get_template_mapping()
Get configurations used for normalization
Usage
YAELProcess$get_template_mapping( template_name = rpyants_builtin_templates(), native_type = "T1w", relative = FALSE )
Arguments
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)
Returns
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
Usage
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
)
Arguments
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
Returns
transformed image in 'ANTs' format
YAELProcess$transform_image_to_template()
Apply transform to images (usually an atlas or 'ROI') from native space to template
Usage
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
)
Arguments
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
Returns
transformed image in 'ANTs' format
YAELProcess$generate_atlas_from_template()
Generate atlas maps from template and morph to native brain
Usage
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
)
Arguments
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 areTRUEfor always generating and overwriting surface files, orFALSEto 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_surfsmooth_methodhow to smooth the surfaces:
"implicit"(default,vcg_smooth_implicitwithlambdaanddegree) or"explicit"(mris_smooth); passed tovolume_to_surfmax_verticessurfaces with more vertices are reduced to about this many after smoothing; passed to
volume_to_surf; default is500000
Returns
Paths to the atlas (volume) files
YAELProcess$generate_streamlines_from_template()
Transform streamline tract files from template space to native brain space
Usage
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"
)
Arguments
template_namewhich template to use; the template must have been used in
map_to_templateprior to calling this methodstreamlines_folderpath to folder containing streamline tract files (
'.tck','.trk','.tt', or'.vtk'); all matching files are processed recursivelyverbosewhether to print progress; default is
TRUEformatoutput 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"
Returns
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
Usage
YAELProcess$transform_points_to_template( native_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
Arguments
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
Returns
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
Usage
YAELProcess$transform_points_from_template( template_ras, template_name = rpyants_builtin_templates(), native_type = "T1w", verbose = TRUE )
Arguments
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
Returns
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.
Usage
YAELProcess$write_talairach_xfm(template_name = rpyants_builtin_templates())
Arguments
template_nametemplate that has been used in
map_to_template
Returns
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.
Usage
YAELProcess$construct_ants_folder_from_template( template_name = rpyants_builtin_templates(), add_surfaces = TRUE )
Arguments
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
Usage
YAELProcess$get_brain(
electrodes = TRUE,
coord_sys = c("scannerRAS", "tkrRAS", "MNI152", "MNI305"),
...
)
Arguments
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 underproject_namewill be loaded; whenelectrodesis adata.frame, or path to a'csv'file, then please specifycoord_syson what is the coordinate system used for columns"x","y", and"z".coord_syscoordinate system if
electrodesis 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.
Usage
YAELProcess$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Archive and share a subject
Description
Archive and share a subject
Usage
archive_subject(
subject,
path,
includes = c("orignal_signals", "processed_data", "rave_imaging", "pipelines", "notes",
"user_generated"),
config = list(),
work_path = NULL,
zip_flags = NULL
)
Arguments
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 |
|
Examples
## 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)
Convert character to RAVEProject instance
Description
Convert character to RAVEProject instance
Usage
as_rave_project(x, ...)
## S3 method for class 'character'
as_rave_project(x, strict = TRUE, parent_path = NULL, ...)
Arguments
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
|
Details
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'.
Value
A RAVEProject instance
See Also
Examples
# ---- 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)
}
Create a 'YAEL' imaging processing instance
Description
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
Usage
as_yael_process(subject, ..., engine = c("rpyANTs", "native"))
Arguments
subject |
character (subject code, or project name with subject code),
or |
... |
internally used |
engine |
which implementation to use: |
Value
A processing instance, see YAELProcess and
YAELNativeProcess
Examples
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)
Back up and rename the file or directory
Description
Back up and rename the file or directory
Usage
backup_file(path, remove = FALSE, quiet = FALSE)
Arguments
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 |
Value
FALSE if nothing to back up, or the back-up path
if path exists
Examples
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
Description
Manipulate cached data on the file systems
Usage
cache_root(check = FALSE)
clear_cached_files(subject_code, quiet = FALSE)
Arguments
check |
whether to ensure the cache root path |
subject_code |
subject code to remove; default is missing. If
|
quiet |
whether to suppress the message |
Details
'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.
Value
cache_root returns the root path that stores the 'RAVE'
cache data; clear_cached_files returns nothing
Examples
cache_root()
External shell commands for 'RAVE'
Description
These shell commands are only tested on 'MacOS' and 'Linux'. On 'Windows' machines, please use the 'WSL2' system.
Usage
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(),
...
)
Arguments
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 |
Value
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
Align images using 'AFNI'
Description
This is a legacy script and possibly contain errors. Please use
cmd_run_ants_coreg for faster and stable implementation
instead.
Usage
cmd_run_3dAllineate(
subject,
mri_path,
ct_path,
overwrite = FALSE,
command_path = NULL,
dry_run = FALSE,
verbose = dry_run
)
Arguments
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 |
Register a computerized tomography (CT) image to MRI via 'ANTs'
Description
Please avoid calling ants_coreg directly; use
cmd_run_ants_coreg for more robust behaviors
Usage
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
)
Arguments
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 |
Value
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
Convert DICOM to NIfTI via 'dcm2niix'
Description
Check https://rave.wiki on how to set up 'conda' environment
for 'RAVE' using 'ravemanager'.
Usage
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
)
Arguments
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 |
Value
A command set running the terminal command; a folder named with
type will be created under the subject image input folder
Examples
## Not run:
cmd_run_dcm2niix(
"YAEL/pt02",
"/path/to/DICOMDIR",
"MRI"
)
## End(Not run)
Workflow: 'FreeSurfer' surface reconstruction
Description
Runs 'FreeSurfer' recon-all command underneath; must have 'FreeSurfer'
installed.
Usage
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,
...
)
Arguments
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 |
Value
A list of shell command set.
Examples
# 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
Description
Run 'FSL' linear registration
Usage
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
)
Arguments
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 |
Value
A command set running the terminal command; a 'coregistration'
folder will be created under the subject imaging directory
Run a built-in 'YAEL' imaging processing workflow
Description
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.
Usage
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,
overwrite = FALSE,
...
)
Arguments
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 |
overwrite |
whether the command should start over: when true, it
removes the temporary folder |
Value
Nothing, a subject imaging folder will be created under 'RAVE' raw folder. It will take a while to run the workflow.
Examples
## 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)
Run the native YAEL imaging processing workflow (without 'Python')
Description
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 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.
Usage
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,
overwrite = FALSE,
...
)
Arguments
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 for the |
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 |
overwrite |
whether the command should start over: when true, it
removes the temporary folder |
Details
Templates are located (and downloaded when missing) by rpyANTs, whose
template functions are pure 'R'; 'Python' is never started. The final
registration uses the full template resolution, which takes a lot of memory;
the first one, which only places the template brain mask and tissue priors,
runs at 1 mm. 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 4
minutes, less than one of them for the brain mask, 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.
Value
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.
See Also
YAELNativeProcess, as_yael_process,
cmd_run_yael_preprocess
Examples
## 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)
Collapse high-dimensional tensor array
Description
Collapse high-dimensional tensor array
Usage
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"), ...)
Arguments
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 |
Value
A collapsed array (or a vector or matrix), depending on keep
See Also
Examples
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)
Collapse power array with given analysis cubes
Description
Collapse power array with given analysis cubes
Usage
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)
Arguments
x |
a |
analysis_index_cubes |
a list of analysis indices for each mode |
Value
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
Examples
# 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)
Compose a phantom channel from existing electrodes
Description
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'.
Usage
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")
)
Arguments
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
|
Value
Nothing
Examples
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
Description
Convert electrode table
Usage
convert_electrode_table_to_bids(
subject,
space = c("ScanRAS", "MNI305", "fsnative")
)
Arguments
subject |
'RAVE' subject |
space |
suggested coordinate space, notice this argument might not be
supported when |
Value
A list of table in data frame and a list of meta information
Examples
# Run `install_subject("DemoSubject")` first!
if( has_rave_subject("demo/DemoSubject") ) {
convert_electrode_table_to_bids(
"demo/DemoSubject",
space = "ScanRAS"
)
}
Export data frame to different common formats
Description
Stores and load data in various of data format. See 'Details' for limitations.
Usage
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"),
...
)
Arguments
x |
data table to be saved to |
file |
file to store the data |
format |
data storage format, default is |
... |
parameters passed to other functions |
Details
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.
Value
The normalized path for export_table, and a
data.table for import_table
Examples
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)
Generate YBA atlas for a 'RAVE' subject
Description
Morphs 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_native.
Usage
generate_atlas_YBA(
subject,
name = c("YBA690", "YBA696"),
template_names = NULL,
radius = 2,
verbose = TRUE,
create_report = TRUE,
disable_viewer = TRUE
)
Arguments
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 |
Details
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_native 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.
Value
An invisible named list of
atlas_pathpath to the atlas volume created under the subject
FreeSurfer'mri'folderlabel_pathpath to the electrode label table, or
NAif no electrode contact has been localizedcolormap_pathpath to the color lookup table saved along with the atlas volume
report_pathpath to the report folder, or
NAifcreate_reportis falsereport_filepath to the report file, or
NAifcreate_reportis false
See Also
generate_atlases_from_template,
cmd_run_yael_preprocess_native
Examples
## 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_native(
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)
Create brain atlases from template
Description
Reverse-transform from template atlases via volume mapping
Usage
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")
)
Arguments
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 |
Details
The workflow generates atlases from a template. To run this function, a
separate normalization is required (see
cmd_run_yael_preprocess_native or
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.
Value
The function returns nothing, but will create a folder named
'atlases' under raw subject 'rave-imaging' folder.
Examples
## 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)
Generate common average reference signal for 'RAVE' subjects
Description
To properly run this function, please install ravetools
package.
Usage
generate_reference(subject, electrodes)
Arguments
subject |
subject ID or |
electrodes |
electrodes to calculate the common average; these electrodes must run through 'Wavelet' first |
Details
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.
Value
A reference instance returned by new_reference with
signal type determined automatically.
Get names of available non-linear transforms to the templates
Description
This function obtains existing transforms rather than creating new
transforms. Please check function
cmd_run_yael_preprocess_native about mapping native images to
the templates.
Usage
get_available_morph_to_template(subject)
Arguments
subject |
'RAVE' subject instance or character; see
|
Value
Template names with valid non-linear transforms.
Examples
## Not run:
get_available_morph_to_template("project_name/subject_code")
## End(Not run)
Get all possible projects in 'RAVE' default directory
Description
Get all possible projects in 'RAVE' default directory
Usage
get_projects(refresh = TRUE)
Arguments
refresh |
whether to refresh the cache; default is true |
Value
characters of project names
Examples
get_projects()
Visualizes repositories with interactive plots
Description
Requires optional package 'plotly'; please install the package prior
to launching the viewer.
Usage
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
)
Arguments
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 |
Value
An R-shiny application container environment; use
print method to launch the application.
Examples
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 into 'RAVE'
Description
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.
Usage
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,
...
)
Arguments
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) |
Recording Blocks
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.
Channel Numbers
(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.
Install data-sets from OpenNeuro
Description
Enjoy hundreds of open-access data sets from https://openneuro.org with a simple accession number.
Usage
install_openneuro(
accession_number,
subject_codes = NULL,
tag = NULL,
parent_folder = NULL
)
Arguments
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 |
Value
The data folder name on the local disk.
Examples
## 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
Description
Install a subject from the internet, a zip file or a directory
Usage
install_subject(
path = ".",
ask = interactive(),
overwrite = FALSE,
backup = TRUE,
use_cache = TRUE,
dry_run = FALSE,
force_project = NA,
force_subject = NA,
...
)
Arguments
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 |
Examples
## Not run:
install_subject("DemoSubject")
## End(Not run)
Load or save meta data to 'RAVE' subject
Description
Load or save meta data to 'RAVE' subject
Usage
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
)
Arguments
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 |
Value
The corresponding metadata
Examples
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
Description
Create new electrode channel instance or a reference signal instance
Create new electrode channel instance or a reference signal instance
Usage
new_electrode(subject, number, signal_type, ...)
new_reference(subject, number, signal_type, ...)
new_electrode(subject, number, signal_type, ...)
new_reference(subject, number, signal_type, ...)
Arguments
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 |
Details
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', orNULLno 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', orNULLno 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 byparse_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.
Value
Electrode or reference instances that inherit
RAVEAbstarctElectrode class
Electrode or reference instances that inherit
RAVEAbstarctElectrode class
Examples
# 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()
}
Get RAVESubject instance from character
Description
Get RAVESubject instance from character
Usage
new_rave_subject(project_name, subject_code, strict = TRUE)
as_rave_subject(subject_id, strict = TRUE, reload = TRUE)
has_rave_subject(subject_id)
Arguments
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 |
Value
RAVESubject instance
See Also
Examples
subject <- new_rave_subject(project_name = "demo@bids:ds04001",
subject_code = "DemoSubject",
strict = FALSE)
subject
subject$project$path
subject$imaging_path
Register a computerized tomography (CT) image to MRI via 'NiftyReg'
Description
Supports rigid, affine, or non-linear transformation
Usage
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,
...
)
Arguments
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 |
Value
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
Plot volume slices into scalable vector graphics SVG images
Description
Display slices, or interleave with image overlays. Require installing
package htmltools.
Usage
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,
...
)
Arguments
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 |
Value
A 'SVG' tag object that can be embedded in shiny applications
or plotted directly.
Examples
# 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
Description
Calculate power baseline
Usage
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"),
...
)
Arguments
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 |
Details
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.
Value
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'.
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
}
'RAVE' repository: basic
Description
'RAVE' repository: basic
Usage
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
)
Arguments
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 |
Value
A RAVESubjectBaseRepository instance
Examples
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)
}
'RAVE' repository: with entire recording blocks
Description
Loads recording blocks - continuous recording chunks, typically a run of minutes.
Usage
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
)
Arguments
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 |
Details
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
Value
A RAVESubjectRecordingBlockRepository instance
Examples
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
Description
'RAVE' repository: with epochs
Usage
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
)
Arguments
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 |
Value
A RAVESubjectEpochRepository instance
Examples
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")
}
Register a computerized tomography (CT) image to MRI via 'nipy'
Description
Align 'CT' using
nipy.algorithms.registration.histogram_registration.
Usage
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
)
Arguments
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 |
Value
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
Load 'FreeSurfer' brain from 'RAVE'
Description
Create 3D visualization of the brain and visualize with modern web browsers
Usage
rave_brain(
subject,
surfaces = "pial",
overlays = "aparc.a2009s+aseg",
annotations = "label/aparc.a2009s",
streamlines = "default/*",
...,
usetemplateifmissing = FALSE,
include_electrodes = TRUE
)
Arguments
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 |
Value
A 'threeBrain' instance if brain is found or
usetemplateifmissing is set to true; otherwise returns NULL
Examples
if(has_rave_subject("demo/DemoSubject")) {
brain <- rave_brain("demo/DemoSubject")
if (interactive()) {
brain$plot()
}
}
Find external command-line tools
Description
Find external command-line tools
Usage
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(...)
Arguments
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 |
Value
Normalized path to the command, or unset if command is
missing.
Legacy support for 'RAVE' 1.0 format
Description
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.
Usage
rave_legacy_subject_format_conversion(subject, verbose = TRUE, ...)
Arguments
subject |
'RAVE' subject characters, such as |
verbose |
whether to verbose the messages |
... |
ignored, reserved for future use |
Value
Nothing
Find file paths based on storage
Description
A generic function that will be dispatched to using different method based
on input x
Usage
rave_path(x, storage = NULL, ...)
Arguments
x |
R object |
storage |
storage type, different options based on different R objects |
... |
additional arguments passed to dispatched method |
'RAVE' constants
Description
Constant variables
Usage
LOCATION_TYPES
SIGNAL_TYPES
IMPORT_FORMATS
YAEL_IMAGE_TYPES
MNI305_to_MNI152
Re-align trials to a given event
Description
'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.
Usage
realign_trials(
x,
event,
epoch,
sample_rate,
time_margin = NA,
trial_margin = NA,
strict = TRUE,
.filebase = tempfile()
)
Arguments
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 |
Value
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 averagingsample_ratethe
sample_rateusedsignature_shift_amount,signaturedigests identifying the applied shifts and the result
See Also
Examples
# 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)
}
Rigidly register a computerized tomography (CT) image to MRI with
the built-in YAEL-reg3d engine
Description
Aligns 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.
Usage
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
)
Arguments
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 |
Value
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.
Apply Morlet-Wavelet to subject
Description
Calculates time-frequency decomposition; not intended for direct use. Please use 'RAVE' pipelines (see 'Examples').
Usage
run_wavelet(
subject,
electrodes,
freqs,
cycles,
target_sample_rate = 100,
kernels_precision = "float",
pre_downsample = 1,
verbose = TRUE
)
Arguments
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 |
Details
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).
Value
The decomposition results are stored in 'RAVE' subject data path; the function only returns the wavelet parameters.
Examples
# 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
Description
Create overview report for given project or subject
Usage
snapshot_subject(x, target_path = NULL, quick = FALSE)
snapshot_project(
x,
target_path = NULL,
template_subjects = NULL,
quick = FALSE
)
Arguments
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
|
Value
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'.
Examples
## Not run:
# Run in parallel
ravepipeline::with_rave_parallel({
snapshot_project("demo")
})
## End(Not run)
Calculate template 'MNI' coordinates for points on native brain
Description
Calculate template 'MNI' coordinates for points on native brain
Usage
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")
)
Arguments
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
|
Value
A table of electrode 'MNI' coordinates.
Examples
if (has_rave_subject("demo/DemoSubject")) {
transform_point_to_template(
subject = 'demo/DemoSubject',
mapping_method = "volumetric"
)
}
Validate and normalize a list of user-supplied condition groupings.
Description
Groups with empty or no conditions (after filtering against epoch, when
provided) are removed from the result.
Usage
validate_condition_groupings(condition_groupings, epoch = NULL)
Arguments
condition_groupings |
A list of condition group items. Each item is
typically a list with elements |
epoch |
Optional. A |
Value
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,TRUEwhenepochwas supplied; -
n_trials- (only whenepochis 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
epochis supplied)-
trials_by_condition- named list of integer trial numbers from the epochTrialcolumn, 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 ofconditions); -
n_trials- total number of trials in the group.
-
Examples
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)
Validate subject data integrity
Description
Check against existence, validity, and consistency
Usage
validate_subject(
subject,
method = c("normal", "basic", "all"),
verbose = TRUE,
version = 2
)
Arguments
subject |
subject ID (character), or |
method |
validation method, choices are |
verbose |
whether to print out the validation messages |
version |
data version, choices are |
Value
A list of nested validation results. The validation process consists of the following parts in order:
- Data paths (
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
- Preprocessing information (
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.csvfile- Meta information (
meta) meta_data_validthis item only exists when the previous preprocess validation is failed or incomplete
meta_electrode_tablethe
electrodes.csvfile in the meta folder has correct format and consistent electrodes numbers to the preprocess informationmeta_reference_xxx(
xxxwill be replaced with actual reference names) checks whether the reference table contains all electrodes and whether each reference data existsmeta_epoch_xxx(
xxxwill 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_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
- Spectral power and phase (
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_databut for the phase data- Epoch table (
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 table (
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
Examples
## Not run:
validate_subject("demo/DemoSubject")
## End(Not run)
Validate time windows to be used
Description
Make sure the time windows are valid intervals and returns a reshaped window list
Usage
validate_time_window(time_windows)
Arguments
time_windows |
vectors or a list of time intervals |
Value
A list of time intervals (ordered, length of 2)
Examples
# 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)
Extract the brain from a 'T1'-weighted image (without 'Python')
Description
The brain mask of a 'T1'-weighted 'MRI', computed in 'R' by the native
YAEL engine on top of ravetools: the brain mask of the template
'mni_icbm152_nlin_asym_09a', brought to the image by a registration
(or a given initial mask), is adjusted to the subject.
Usage
yael_brain_extract(
image,
mask = NULL,
work_path = NULL,
affine_transform = NULL,
verbose = TRUE
)
Arguments
image |
the 'T1'-weighted image: a file path, an |
mask |
optional initial brain mask in the same scanner space (the
voxels above zero), in the same forms as |
work_path |
folder for the working files, which are kept; default
|
affine_transform |
optional initial |
verbose |
whether to log the steps and print the registration progress |
Details
The steps, with the files they write into work_path (named after the
stages of the native normalization):
bias-field correction with the settings of
abp_n4in ANTsPy (nu.nii.gz), for the registration;unless
maskis given, the registration of the whole head to the template image without masks, affine and then deform, as the initial registration ('SyNabp') of the native normalization; it is saved byravetools::save_registrationasSyNabp.dcfwith its'ANTs'transform files, and the registered image asSyNabp_warped_mov.nii.gz;the initial mask: the template brain mask through that registration, or
mask(initial_mask.nii.gz);the brain extraction of the native engine (see the item "Brain extraction" of
YAELNativeProcess) on the image corrected byN4again without the intensity truncation ofabp_n4(which makes bright marrow look like the white matter), which keeps the largest connected gray and white matter, leaves out what dark voxels cut off from it (skull marrow or scalp) and thin strands, and keeps the initial mask, with a warning, when the result differs from it by more than 20 percent in volume (brainmask.nii.gz).
Every call computes all the steps again; existing files in
work_path are replaced.
Value
A binary ieegio_volume (1 inside the brain) on the grid of
image.
Examples
## Not run:
# downloads the template on first use, and takes a few minutes
mask <- yael_brain_extract("sub-01_T1w.nii.gz", work_path = "brain_extraction")
ieegio::write_volume(mask, "sub-01_desc-brain_mask.nii.gz")
# adjust a mask of the same image instead
mask2 <- yael_brain_extract("sub-01_T1w.nii.gz", mask = "fs/mri/brainmask.mgz")
## End(Not run)
Run YAEL-based FreeSurfer reconstruction for macaque brains
Description
A two-stage pipeline that adapts human cortical reconstruction
workflow for ACPC-aligned macaque T1w MRI.
Usage
yael_macaque(
subject,
t1w_path,
folder_name = "fs",
steps = c("normalization", "reconstruction")
)
Arguments
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
|
Details
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.
Value
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.
Examples
## 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)