Title: | File IO for Intracranial Electroencephalography |
---|---|
Description: | Integrated toolbox supporting common file formats used for intracranial Electroencephalography (iEEG) and deep-brain stimulation (DBS) study. |
Authors: | Zhengjia Wang [aut, cre] |
Maintainer: | Zhengjia Wang <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.0.2 |
Built: | 2024-11-19 05:27:12 UTC |
Source: | https://github.com/dipterix/ieegio |
Download sample files
ieegio_sample_data(file, test = FALSE, cache_ok = TRUE)
ieegio_sample_data(file, test = FALSE, cache_ok = TRUE)
file |
file to download; set to |
test |
test whether the sample file exists instead of downloading them;
default is |
cache_ok |
whether to use cache |
When test
is false, returns downloaded file path
(character); when test
is true, returns whether the expected
sample exists (logical).
# list available files ieegio_sample_data() # check if file edfPlusD.edf exists ieegio_sample_data("edfPlusD.edf", test = TRUE) ## Not run: ieegio_sample_data("edfPlusD.edf") ## End(Not run)
# list available files ieegio_sample_data() # check if file edfPlusD.edf exists ieegio_sample_data("edfPlusD.edf", test = TRUE) ## Not run: ieegio_sample_data("edfPlusD.edf") ## End(Not run)
Supports surface geometry, annotation, measurement, and
time-series data.
Please use the high-level function read_surface
, which calls
other low-level functions internally.
read_surface(file, format = "auto", type = NULL, ...) write_surface( x, con, format = c("gifti", "freesurfer"), type = c("geometry", "annotations", "measurements", "color", "time_series"), ... ) io_read_fs( file, type = c("geometry", "annotations", "measurements"), format = "auto", name = basename(file), ... ) io_read_gii(file) io_write_gii(x, con, ...)
read_surface(file, format = "auto", type = NULL, ...) write_surface( x, con, format = c("gifti", "freesurfer"), type = c("geometry", "annotations", "measurements", "color", "time_series"), ... ) io_read_fs( file, type = c("geometry", "annotations", "measurements"), format = "auto", name = basename(file), ... ) io_read_gii(file) io_write_gii(x, con, ...)
file , con
|
path the file |
format |
format of the file, see 'Arguments' section in
|
type |
type of the data; ignored if the file format is 'GIfTI'. For 'FreeSurfer' files, supported types are
|
... |
for |
x |
surface (geometry, annotation, measurement) data |
name |
name of the data; default is the file name |
A surface object container
library(ieegio) # geometry geom_file <- "gifti/GzipBase64/sujet01_Lwhite.surf.gii" # measurements shape_file <- "gifti/GzipBase64/sujet01_Lwhite.shape.gii" # time series ts_file <- "gifti/GzipBase64/fmri_sujet01_Lwhite_projection.time.gii" if(ieegio_sample_data(geom_file, test = TRUE)) { geometry <- read_surface(ieegio_sample_data(geom_file)) print(geometry) measurement <- read_surface(ieegio_sample_data(shape_file)) print(measurement) time_series <- read_surface(ieegio_sample_data(ts_file)) print(time_series) # merge measurement & time_series into geometry merged <- merge(geometry, measurement, time_series) print(merged) # make sure you install `rgl` package plot(merged, name = c("measurements", "Shape001")) plot(merged, name = "time_series", slice_index = c(1, 11, 21, 31)) }
library(ieegio) # geometry geom_file <- "gifti/GzipBase64/sujet01_Lwhite.surf.gii" # measurements shape_file <- "gifti/GzipBase64/sujet01_Lwhite.shape.gii" # time series ts_file <- "gifti/GzipBase64/fmri_sujet01_Lwhite_projection.time.gii" if(ieegio_sample_data(geom_file, test = TRUE)) { geometry <- read_surface(ieegio_sample_data(geom_file)) print(geometry) measurement <- read_surface(ieegio_sample_data(shape_file)) print(measurement) time_series <- read_surface(ieegio_sample_data(ts_file)) print(time_series) # merge measurement & time_series into geometry merged <- merge(geometry, measurement, time_series) print(merged) # make sure you install `rgl` package plot(merged, name = c("measurements", "Shape001")) plot(merged, name = "time_series", slice_index = c(1, 11, 21, 31)) }
Read and write volume data ('MRI', 'CT', etc.) in 'NIfTI' or 'MGH' formats.
Please use read_volume
and write_volume
for high-level
function. These functions
will call other low-level functions internally.
read_volume(file, header_only = FALSE, format = c("auto", "nifti", "mgh"), ...) write_volume(x, con, format = c("auto", "nifti", "mgh"), ...) io_read_mgz(file, header_only = FALSE) io_write_mgz(x, con, ...) ## S3 method for class 'ieegio_volume' io_write_mgz(x, con, ...) ## S3 method for class 'ieegio_mgh' io_write_mgz(x, con, ...) ## S3 method for class 'nifti' io_write_mgz(x, con, ...) ## S3 method for class 'niftiImage' io_write_mgz(x, con, ...) ## S3 method for class 'ants.core.ants_image.ANTsImage' io_write_mgz(x, con, ...) ## S3 method for class 'array' io_write_mgz(x, con, vox2ras = NULL, ...) io_read_nii( file, method = c("oro", "rnifti", "ants"), header_only = FALSE, ... ) io_write_nii(x, con, ...) ## S3 method for class 'ieegio_nifti' io_write_nii(x, con, ...) ## S3 method for class 'ants.core.ants_image.ANTsImage' io_write_nii(x, con, ...) ## S3 method for class 'niftiImage' io_write_nii(x, con, ...) ## S3 method for class 'nifti' io_write_nii(x, con, gzipped = NA, ...) ## S3 method for class 'ieegio_mgh' io_write_nii(x, con, ...) ## S3 method for class 'array' io_write_nii(x, con, vox2ras = NULL, ...)
read_volume(file, header_only = FALSE, format = c("auto", "nifti", "mgh"), ...) write_volume(x, con, format = c("auto", "nifti", "mgh"), ...) io_read_mgz(file, header_only = FALSE) io_write_mgz(x, con, ...) ## S3 method for class 'ieegio_volume' io_write_mgz(x, con, ...) ## S3 method for class 'ieegio_mgh' io_write_mgz(x, con, ...) ## S3 method for class 'nifti' io_write_mgz(x, con, ...) ## S3 method for class 'niftiImage' io_write_mgz(x, con, ...) ## S3 method for class 'ants.core.ants_image.ANTsImage' io_write_mgz(x, con, ...) ## S3 method for class 'array' io_write_mgz(x, con, vox2ras = NULL, ...) io_read_nii( file, method = c("oro", "rnifti", "ants"), header_only = FALSE, ... ) io_write_nii(x, con, ...) ## S3 method for class 'ieegio_nifti' io_write_nii(x, con, ...) ## S3 method for class 'ants.core.ants_image.ANTsImage' io_write_nii(x, con, ...) ## S3 method for class 'niftiImage' io_write_nii(x, con, ...) ## S3 method for class 'nifti' io_write_nii(x, con, gzipped = NA, ...) ## S3 method for class 'ieegio_mgh' io_write_nii(x, con, ...) ## S3 method for class 'array' io_write_nii(x, con, vox2ras = NULL, ...)
file |
file path to read volume data |
header_only |
whether to read header data only;
default is |
format |
format of the file to be written; choices are |
... |
passed to other methods |
x |
volume data (such as 'NIfTI' image, array, or 'MGH') to be saved |
con |
file path to store image |
vox2ras |
a |
method |
method to read the file; choices are |
gzipped |
for writing |
format of the file; default is auto-detection, other choices are
'nifti'
and 'mgh'
;
imaging readers return ieegio_volume
objects.
library(ieegio) nifti_file <- "brain.demosubject.nii.gz" # Use `ieegio_sample_data(nifti_file)` # to download sample data if( ieegio_sample_data(nifti_file, test = TRUE) ) { # ---- NIfTI examples --------------------------------------------- file <- ieegio_sample_data(nifti_file) # basic read vol <- read_volume(file) # voxel to scanner RAS vol$transforms$vox2ras # to freesurfer surface vol$transforms$vox2ras_tkr # to FSL vol$transforms$vox2fsl image(vol$data[,,128], asp = 1, axes = FALSE) # ---- using other methods -------------------------------------- # default vol <- read_volume(file, method = "oro", format = "nifti") vol$header # lazy-load nifti vol2 <- read_volume(file, method = "rnifti", format = "nifti") vol2$header # Using ANTsPyx vol3 <- read_volume(file, method = "ants", format = "nifti") vol3$header # ---- write -------------------------------------------------------- # write as NIfTI f <- tempfile(fileext = ".nii.gz") write_volume(vol, f, format = "nifti") # alternative method write_volume(vol$header, f, format = "nifti") # write to mgz/mgh f2 <- tempfile(fileext = ".mgz") write_volume(vol, f, format = "mgh") # clean up unlink(f) unlink(f2) }
library(ieegio) nifti_file <- "brain.demosubject.nii.gz" # Use `ieegio_sample_data(nifti_file)` # to download sample data if( ieegio_sample_data(nifti_file, test = TRUE) ) { # ---- NIfTI examples --------------------------------------------- file <- ieegio_sample_data(nifti_file) # basic read vol <- read_volume(file) # voxel to scanner RAS vol$transforms$vox2ras # to freesurfer surface vol$transforms$vox2ras_tkr # to FSL vol$transforms$vox2fsl image(vol$data[,,128], asp = 1, axes = FALSE) # ---- using other methods -------------------------------------- # default vol <- read_volume(file, method = "oro", format = "nifti") vol$header # lazy-load nifti vol2 <- read_volume(file, method = "rnifti", format = "nifti") vol2$header # Using ANTsPyx vol3 <- read_volume(file, method = "ants", format = "nifti") vol3$header # ---- write -------------------------------------------------------- # write as NIfTI f <- tempfile(fileext = ".nii.gz") write_volume(vol, f, format = "nifti") # alternative method write_volume(vol$header, f, format = "nifti") # write to mgz/mgh f2 <- tempfile(fileext = ".mgz") write_volume(vol, f, format = "mgh") # clean up unlink(f) unlink(f2) }
Check whether a 'HDF5' file can be opened for read/write
io_h5_valid(file, mode = c("r", "w"), close_all = FALSE) io_h5_names(file)
io_h5_valid(file, mode = c("r", "w"), close_all = FALSE) io_h5_names(file)
file |
path to file |
mode |
|
close_all |
whether to close all connections or just close current
connection; default is false. Set this to |
io_h5_valid
returns a logical value indicating whether the
file can be opened. io_h5_names
returns a character vector of
dataset names.
x <- array(1:27, c(3,3,3)) f <- tempfile() # No data written to the file, hence invalid io_h5_valid(f, 'r') io_write_h5(x, f, 'dset') io_h5_valid(f, 'w') # Open the file and hold a connection ptr <- hdf5r::H5File$new(filename = f, mode = 'w') # Can read, but cannot write io_h5_valid(f, 'r') # TRUE io_h5_valid(f, 'w') # FALSE # However, this can be reset via `close_all=TRUE` io_h5_valid(f, 'r', close_all = TRUE) io_h5_valid(f, 'w') # TRUE # Now the connection is no longer valid ptr # clean up unlink(f)
x <- array(1:27, c(3,3,3)) f <- tempfile() # No data written to the file, hence invalid io_h5_valid(f, 'r') io_write_h5(x, f, 'dset') io_h5_valid(f, 'w') # Open the file and hold a connection ptr <- hdf5r::H5File$new(filename = f, mode = 'w') # Can read, but cannot write io_h5_valid(f, 'r') # TRUE io_h5_valid(f, 'w') # FALSE # However, this can be reset via `close_all=TRUE` io_h5_valid(f, 'r', close_all = TRUE) io_h5_valid(f, 'w') # TRUE # Now the connection is no longer valid ptr # clean up unlink(f)
hdf5r-package
Wrapper for class LazyH5
, which load data with
"lazy" mode - only read part of dataset when needed.
io_read_h5(file, name, read_only = TRUE, ram = FALSE, quiet = FALSE)
io_read_h5(file, name, read_only = TRUE, ram = FALSE, quiet = FALSE)
file |
'HDF5' file |
name |
|
read_only |
only used if |
ram |
load data to memory immediately, default is false |
quiet |
whether to suppress messages |
If ram
is true, then return data as arrays, otherwise return
a LazyH5
instance.
file <- tempfile() x <- array(1:120, dim = c(4,5,6)) # save x to file with name /group/dataset/1 io_write_h5(x, file, '/group/dataset/1', quiet = TRUE) # read data y <- io_read_h5(file, '/group/dataset/1', ram = TRUE) class(y) # array z <- io_read_h5(file, '/group/dataset/1', ram = FALSE) class(z) # LazyH5 dim(z) # clean up unlink(file)
file <- tempfile() x <- array(1:120, dim = c(4,5,6)) # save x to file with name /group/dataset/1 io_write_h5(x, file, '/group/dataset/1', quiet = TRUE) # read data y <- io_read_h5(file, '/group/dataset/1', ram = TRUE) class(y) # array z <- io_read_h5(file, '/group/dataset/1', ram = FALSE) class(z) # LazyH5 dim(z) # clean up unlink(file)
Save objects to 'HDF5' file without trivial checks
io_write_h5( x, file, name, chunk = "auto", level = 4, replace = TRUE, new_file = FALSE, ctype = NULL, quiet = FALSE, ... )
io_write_h5( x, file, name, chunk = "auto", level = 4, replace = TRUE, new_file = FALSE, ctype = NULL, quiet = FALSE, ... )
x |
an array, a matrix, or a vector |
file |
path to 'HDF5' file |
name |
path/name of the data; for example, |
chunk |
chunk size |
level |
compress level from 0 - no compression to 10 - max compression |
replace |
should data be replaced if exists |
new_file |
should removing the file if old one exists |
ctype |
data type such as "character", "integer", or "numeric". If
set to |
quiet |
whether to suppress messages, default is false |
... |
passed to other |
Absolute path of the file saved
file <- tempfile() x <- array(1:120, dim = 2:5) # save x to file with name /group/dataset/1 io_write_h5(x, file, '/group/dataset/1', chunk = dim(x)) # load data y <- io_read_h5(file, '/group/dataset/1') # read data to memory y[] # clean up unlink(file)
file <- tempfile() x <- array(1:120, dim = 2:5) # save x to file with name /group/dataset/1 io_write_h5(x, file, '/group/dataset/1', chunk = dim(x)) # load data y <- io_read_h5(file, '/group/dataset/1') # read data to memory y[] # clean up unlink(file)
provides hybrid data structure for 'HDF5' file
quiet
whether to suppress messages
finalize()
garbage collection method
LazyH5$finalize()
none
print()
overrides print method
LazyH5$print()
self instance
new()
constructor
LazyH5$new(file_path, data_name, read_only = FALSE, quiet = FALSE)
file_path
where data is stored in 'HDF5' format
data_name
the data stored in the file
read_only
whether to open the file in read-only mode. It's highly recommended to set this to be true, otherwise the file connection is exclusive.
quiet
whether to suppress messages, default is false
self instance
save()
save data to a 'HDF5' file
LazyH5$save( x, chunk = "auto", level = 7, replace = TRUE, new_file = FALSE, force = TRUE, ctype = NULL, size = NULL, ... )
x
vector, matrix, or array
chunk
chunk size, length should matches with data dimension
level
compress level, from 1 to 9
replace
if the data exists in the file, replace the file or not
new_file
remove the whole file if exists before writing?
force
if you open the file in read-only mode, then saving
objects to the file will raise error. Use force=TRUE
to force
write data
ctype
data type, see mode
, usually the data type
of x
. Try mode(x)
or storage.mode(x)
as hints.
size
deprecated, for compatibility issues
...
passed to self open()
method
open()
open connection
LazyH5$open(new_dataset = FALSE, robj, ...)
new_dataset
only used when the internal pointer is closed, or to write the data
robj
data array to save
...
passed to createDataSet
in hdf5r
package
close()
close connection
LazyH5$close(all = TRUE)
all
whether to close all connections associated to the data file. If true, then all connections, including access from other programs, will be closed
subset()
subset data
LazyH5$subset(..., drop = FALSE, stream = FALSE, envir = parent.frame())
drop
whether to apply drop
the subset
stream
whether to read partial data at a time
envir
if i,j,...
are expressions, where should the
expression be evaluated
i, j, ...
index along each dimension
subset of data
get_dims()
get data dimension
LazyH5$get_dims(stay_open = TRUE)
stay_open
whether to leave the connection opened
dimension of the array
get_type()
get data type
LazyH5$get_type(stay_open = TRUE)
stay_open
whether to leave the connection opened
data type, currently only character, integer, raw, double, and complex are available, all other types will yield "unknown"
Interfaces to read from or write to files with common formats.
io_read_fst( con, method = c("proxy", "data_table", "data_frame", "header_only"), ..., old_format = FALSE ) io_write_fst(x, con, compress = 50, ...) io_read_ini(con, ...) io_read_json(con, ...) io_write_json( x, con = stdout(), ..., digits = ceiling(-log10(.Machine$double.eps)), pretty = TRUE, serialize = TRUE ) io_read_mat( con, method = c("auto", "R.matlab", "pymatreader", "mat73"), verbose = TRUE, on_convert_error = c("warning", "error", "ignore"), ... ) io_write_mat(x, con, method = c("R.matlab", "scipy"), ...) io_read_yaml(con, ...) io_write_yaml(x, con, ..., sorted = FALSE)
io_read_fst( con, method = c("proxy", "data_table", "data_frame", "header_only"), ..., old_format = FALSE ) io_write_fst(x, con, compress = 50, ...) io_read_ini(con, ...) io_read_json(con, ...) io_write_json( x, con = stdout(), ..., digits = ceiling(-log10(.Machine$double.eps)), pretty = TRUE, serialize = TRUE ) io_read_mat( con, method = c("auto", "R.matlab", "pymatreader", "mat73"), verbose = TRUE, on_convert_error = c("warning", "error", "ignore"), ... ) io_write_mat(x, con, method = c("R.matlab", "scipy"), ...) io_read_yaml(con, ...) io_write_yaml(x, con, ..., sorted = FALSE)
con |
connection or file |
method |
method to read table. For
For
|
... |
passed to internal function calls |
old_format |
see |
x |
data to write to disk |
compress |
compress level from 0 to 100; default is 50 |
digits , pretty
|
for writing numeric values to 'json' format |
serialize |
set to |
verbose |
whether to print out the process |
on_convert_error |
for reading |
sorted |
whether to sort the list; default is |
The reader functions returns the data extracted from files, mostly
as R objects, with few exceptions on some 'Matlab' files. When reading a
'Matlab' file requires using 'Python' modules, io_read_mat
will
try its best effort to convert 'Python' objects to R. However, such
conversion might fail. In this case, the result might partially contain
'Python' objects with warnings.
# ---- fst ---------------------------------------------------------------- f <- tempfile(fileext = ".fst") x <- data.frame( a = 1:10, b = rnorm(10), c = letters[1:10] ) io_write_fst(x, con = f) # default reads in proxy io_read_fst(f) # load as data.table io_read_fst(f, "data_table") # load as data.frame io_read_fst(f, "data_frame") # get header io_read_fst(f, "header_only") # clean up unlink(f) # ---- json --------------------------------------------------------------- f <- tempfile(fileext = ".json") x <- list(a = 1L, b = 2.3, c = "a", d = 1+1i) # default is serialize io_write_json(x, f) io_read_json(f) cat(readLines(f), sep = "\n") # just values io_write_json(x, f, serialize = FALSE, pretty = FALSE) io_read_json(f) cat(readLines(f), sep = "\n") # clean up unlink(f) # ---- Matlab .mat -------------------------------------------------------- ## Not run: f <- tempfile(fileext = ".mat") x <- list(a = 1L, b = 2.3, c = "a", d = 1+1i) # save as MAT 5.0 io_write_mat(x, f) io_read_mat(f) # require setting up Python environment io_read_mat(f, method = "pymatreader") # MAT 7.3 example sample_data <- ieegio_sample_data("mat_v73.mat") io_read_mat(sample_data) # clean up unlink(f) ## End(Not run) # ---- yaml --------------------------------------------------------------- f <- tempfile(fileext = ".yaml") x <- list(a = 1L, b = 2.3, c = "a") io_write_yaml(x, f) io_read_yaml(f) # clean up unlink(f)
# ---- fst ---------------------------------------------------------------- f <- tempfile(fileext = ".fst") x <- data.frame( a = 1:10, b = rnorm(10), c = letters[1:10] ) io_write_fst(x, con = f) # default reads in proxy io_read_fst(f) # load as data.table io_read_fst(f, "data_table") # load as data.frame io_read_fst(f, "data_frame") # get header io_read_fst(f, "header_only") # clean up unlink(f) # ---- json --------------------------------------------------------------- f <- tempfile(fileext = ".json") x <- list(a = 1L, b = 2.3, c = "a", d = 1+1i) # default is serialize io_write_json(x, f) io_read_json(f) cat(readLines(f), sep = "\n") # just values io_write_json(x, f, serialize = FALSE, pretty = FALSE) io_read_json(f) cat(readLines(f), sep = "\n") # clean up unlink(f) # ---- Matlab .mat -------------------------------------------------------- ## Not run: f <- tempfile(fileext = ".mat") x <- list(a = 1L, b = 2.3, c = "a", d = 1+1i) # save as MAT 5.0 io_write_mat(x, f) io_read_mat(f) # require setting up Python environment io_read_mat(f, method = "pymatreader") # MAT 7.3 example sample_data <- ieegio_sample_data("mat_v73.mat") io_read_mat(sample_data) # clean up unlink(f) ## End(Not run) # ---- yaml --------------------------------------------------------------- f <- tempfile(fileext = ".yaml") x <- list(a = 1L, b = 2.3, c = "a") io_write_yaml(x, f) io_read_yaml(f) # clean up unlink(f)
NWBHDF5IO
file containerClass definition for 'PyNWB' container; use read_nwb
for construction function.
opened
Whether the container is opened.
new()
Initialize the class
NWBHDF5IO$new(path = NULL, mode = c("r", "w", "r+", "a", "w-", "x"), ...)
path
Path to a '.nwb'
file
mode
Mode for opening the file
...
Other parameters passed to nwb$NWBHDF5IO
get_handler()
Get internal file handler. Please make sure you close the handler correctly.
NWBHDF5IO$get_handler()
File handler, i.e. 'PyNWB' NWBHDF5IO
instance.
open()
Open the connections, must be used together with $close
method.
For high-level method, see $with
NWBHDF5IO$open()
container itself
\dontrun{ # low-level method to open NWB file, for safer methods, see # `container$with()` below container$open() data <- container$read() # process data... # Make sure the container is closed! container$close() }
close()
Close the connections (low-level method, see 'with' method below)
NWBHDF5IO$close(close_links = TRUE)
close_links
Whether to close all files linked to from this file; default is true
Nothing
close_linked_files()
Close all opened, linked-to files. 'MacOS'
and 'Linux'
automatically release the linked-to file after the linking file is
closed, but 'Windows'
does not, which prevents the linked-to
file from being deleted or truncated. Use this method to close all
opened, linked-to files.
NWBHDF5IO$close_linked_files()
Nothing
read()
Read the 'NWB'
file from the 'IO' source. Please use along with
'$with'
method
NWBHDF5IO$read()
'NWBFile'
container
with()
Safe wrapper for reading and handling 'NWB'
file. See class examples.
NWBHDF5IO$with(expr, quoted = FALSE, envir = parent.frame())
expr
R expression to evaluate
quoted
Whether expr
is quoted; default is false
envir
environment for expr
to evaluate; default is the
parent frame (see parent.frame
)
Whatever results generated by expr
\dontrun{ container$with({ data <- container$read() # process data }) }
clone()
The objects of this class are cloneable with this method.
NWBHDF5IO$clone(deep = FALSE)
deep
Whether to make a deep clone.
## Not run: # Running this example requires a .nwb file library(rnwb) container <- NWBHDF5IO$new(path = file) container$with({ data <- container$read() electrode_table <- data$electrodes[convert = TRUE] }) print(electrode_table) ## End(Not run) ## ------------------------------------------------ ## Method `NWBHDF5IO$open` ## ------------------------------------------------ ## Not run: # low-level method to open NWB file, for safer methods, see # `container$with()` below container$open() data <- container$read() # process data... # Make sure the container is closed! container$close() ## End(Not run) ## ------------------------------------------------ ## Method `NWBHDF5IO$with` ## ------------------------------------------------ ## Not run: container$with({ data <- container$read() # process data }) ## End(Not run)
## Not run: # Running this example requires a .nwb file library(rnwb) container <- NWBHDF5IO$new(path = file) container$with({ data <- container$read() electrode_table <- data$electrodes[convert = TRUE] }) print(electrode_table) ## End(Not run) ## ------------------------------------------------ ## Method `NWBHDF5IO$open` ## ------------------------------------------------ ## Not run: # low-level method to open NWB file, for safer methods, see # `container$with()` below container$open() data <- container$read() # process data... # Make sure the container is closed! container$close() ## End(Not run) ## ------------------------------------------------ ## Method `NWBHDF5IO$with` ## ------------------------------------------------ ## Not run: container$with({ data <- container$read() # process data }) ## End(Not run)
Plot '3D' surface objects
## S3 method for class 'ieegio_surface' plot( x, method = c("basic", "full"), transform = 1L, name = "auto", vlim = NULL, col = c("black", "white"), slice_index = NULL, ... )
## S3 method for class 'ieegio_surface' plot( x, method = c("basic", "full"), transform = 1L, name = "auto", vlim = NULL, col = c("black", "white"), slice_index = NULL, ... )
x |
|
method |
plot method; |
transform |
which transform to use, can be a 4-by-4 matrix; if
the surface contains transform matrix, then this argument can be
an integer index of the transform embedded, or the target
(transformed) space name; print |
name |
attribute and name used for colors, options can be |
vlim |
when plotting with continuous data ( |
col |
color or colors to form the color palette when value data is
continuous; when |
slice_index |
when plotting the |
... |
ignored |
library(ieegio) # geometry geom_file <- "gifti/GzipBase64/sujet01_Lwhite.surf.gii" # measurements shape_file <- "gifti/GzipBase64/sujet01_Lwhite.shape.gii" # time series ts_file <- "gifti/GzipBase64/fmri_sujet01_Lwhite_projection.time.gii" if(ieegio_sample_data(geom_file, test = TRUE)) { geometry <- read_surface(ieegio_sample_data(geom_file)) measurement <- read_surface(ieegio_sample_data(shape_file)) time_series <- read_surface(ieegio_sample_data(ts_file)) ts_demean <- apply( time_series$time_series$value, MARGIN = 1L, FUN = function(x) { x - mean(x) } ) time_series$time_series$value <- t(ts_demean) # merge measurement & time_series into geometry (optional) merged <- merge(geometry, measurement, time_series) print(merged) # ---- plot method/style ------------------------------------ plot(merged, "basic") plot(merged, "full") # ---- plot data -------------------------------------------- ## Measurements or annotations # the first column of `measurements` plot(merged, name = "measurements") # equivalent to plot(merged, name = list("measurements", 1L)) # equivalent to measurement_names <- names(merged$measurements$data_table) plot(merged, name = list("measurements", measurement_names[[1]])) ## Time-series # automatically select 4 slices, trim the color palette # from -25 to 25 plot(merged, name = "time_series", vlim = c(-25, 25)) plot( merged, name = "time_series", vlim = c(-25, 25), slice_index = c(1, 17, 33, 49, 64, 80, 96, 112, 128), col = c("#053061", "#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#ffffff", "#fddbc7", "#f4a582", "#d6604d", "#b2182b", "#67001f") ) }
library(ieegio) # geometry geom_file <- "gifti/GzipBase64/sujet01_Lwhite.surf.gii" # measurements shape_file <- "gifti/GzipBase64/sujet01_Lwhite.shape.gii" # time series ts_file <- "gifti/GzipBase64/fmri_sujet01_Lwhite_projection.time.gii" if(ieegio_sample_data(geom_file, test = TRUE)) { geometry <- read_surface(ieegio_sample_data(geom_file)) measurement <- read_surface(ieegio_sample_data(shape_file)) time_series <- read_surface(ieegio_sample_data(ts_file)) ts_demean <- apply( time_series$time_series$value, MARGIN = 1L, FUN = function(x) { x - mean(x) } ) time_series$time_series$value <- t(ts_demean) # merge measurement & time_series into geometry (optional) merged <- merge(geometry, measurement, time_series) print(merged) # ---- plot method/style ------------------------------------ plot(merged, "basic") plot(merged, "full") # ---- plot data -------------------------------------------- ## Measurements or annotations # the first column of `measurements` plot(merged, name = "measurements") # equivalent to plot(merged, name = list("measurements", 1L)) # equivalent to measurement_names <- names(merged$measurements$data_table) plot(merged, name = list("measurements", measurement_names[[1]])) ## Time-series # automatically select 4 slices, trim the color palette # from -25 to 25 plot(merged, name = "time_series", vlim = c(-25, 25)) plot( merged, name = "time_series", vlim = c(-25, 25), slice_index = c(1, 17, 33, 49, 64, 80, 96, 112, 128), col = c("#053061", "#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#ffffff", "#fddbc7", "#f4a582", "#d6604d", "#b2182b", "#67001f") ) }
Plot '3D' volume in anatomical slices
## S3 method for class 'ieegio_volume' plot( x, position = c(0, 0, 0), center_position = FALSE, which = c("coronal", "axial", "sagittal"), slice_index = 1L, transform = "vox2ras", zoom = 1, pixel_width = max(zoom/2, 1), crosshair_gap = 4, crosshair_lty = 2, col = c("black", "white"), crosshair_col = "#00FF00A0", continuous = TRUE, vlim = NULL, add = FALSE, main = "", axes = FALSE, background = col[[1]], foreground = col[[length(col)]], ..., .xdata = x$data )
## S3 method for class 'ieegio_volume' plot( x, position = c(0, 0, 0), center_position = FALSE, which = c("coronal", "axial", "sagittal"), slice_index = 1L, transform = "vox2ras", zoom = 1, pixel_width = max(zoom/2, 1), crosshair_gap = 4, crosshair_lty = 2, col = c("black", "white"), crosshair_col = "#00FF00A0", continuous = TRUE, vlim = NULL, add = FALSE, main = "", axes = FALSE, background = col[[1]], foreground = col[[length(col)]], ..., .xdata = x$data )
x |
|
position |
cross-hair focused position |
center_position |
whether to center canvas at |
which |
which slice to plot; choices are |
slice_index |
length of 1: if |
transform |
which transform to apply, can be a 4-by-4 matrix,
an integer or name indicating the matrix in |
zoom |
zoom-in level |
pixel_width |
pixel size, ranging from |
crosshair_gap |
the cross-hair gap in milliliter |
crosshair_lty |
the cross-hair line type |
col |
color palette for continuous |
crosshair_col |
the cross-hair color; set to |
continuous |
reserved |
vlim |
the range limit of the data; default is computed from range of
|
add |
whether to add the plot to existing underlay;
default is |
main , ...
|
passed to |
axes |
whether to draw axes; default is |
background , foreground
|
background and foreground colors; default is
the first and last elements of |
.xdata |
default is |
library(ieegio) nifti_file <- "brain.demosubject.nii.gz" # Use `ieegio_sample_data(nifti_file)` # to download sample data if( ieegio_sample_data(nifti_file, test = TRUE) ) { # ---- NIfTI examples --------------------------------------------- file <- ieegio_sample_data(nifti_file) # basic read vol <- read_volume(file) par(mfrow = c(1, 3), mar = c(0, 0, 3.1, 0)) ras_position <- c(-50, -10, 15) ras_str <- paste(sprintf("%.0f", ras_position), collapse = ",") for(which in c("coronal", "axial", "sagittal")) { plot(x = vol, position = ras_position, crosshair_gap = 10, crosshair_lty = 2, zoom = 3, which = which, main = sprintf("%s T1RAS=[%s]", which, ras_str)) } }
library(ieegio) nifti_file <- "brain.demosubject.nii.gz" # Use `ieegio_sample_data(nifti_file)` # to download sample data if( ieegio_sample_data(nifti_file, test = TRUE) ) { # ---- NIfTI examples --------------------------------------------- file <- ieegio_sample_data(nifti_file) # basic read vol <- read_volume(file) par(mfrow = c(1, 3), mar = c(0, 0, 3.1, 0)) ras_position <- c(-50, -10, 15) ras_str <- paste(sprintf("%.0f", ras_position), collapse = ",") for(which in c("coronal", "axial", "sagittal")) { plot(x = vol, position = ras_position, crosshair_gap = 10, crosshair_lty = 2, zoom = 3, which = which, main = sprintf("%s T1RAS=[%s]", which, ras_str)) } }
'NWB'
via 'pynwb'
Install 'NWB'
via 'pynwb'
install_pynwb(python_ver = "auto", verbose = TRUE) pynwb_module(force = FALSE, error_if_missing = TRUE)
install_pynwb(python_ver = "auto", verbose = TRUE) pynwb_module(force = FALSE, error_if_missing = TRUE)
python_ver |
'Python' version, see |
verbose |
whether to print the installation messages |
force |
whether to force-reload the module |
error_if_missing |
whether to raise errors when the module fails to load; default is true |
A 'Python' module pynwb
.
Read 'BCI2000' data file
read_bci2000( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, verbose = TRUE )
read_bci2000( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, verbose = TRUE )
file |
file path to the data file |
extract_path |
location to where the extracted information is to be stored |
header_only |
whether to only load header data |
cache_ok |
whether existing cache should be reused; default is
|
verbose |
whether to print processing messages; default is |
A cached object that is readily to be loaded to memory; see
SignalDataCache
for class definition.
if( ieegio_sample_data("bci2k.dat", test = TRUE) ) { file <- ieegio_sample_data("bci2k.dat") x <- read_bci2000(file) print(x) channel <- x$get_channel(1) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
if( ieegio_sample_data("bci2k.dat", test = TRUE) ) { file <- ieegio_sample_data("bci2k.dat") x <- read_bci2000(file) print(x) channel <- x$get_channel(1) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
Read 'BrainVision' data
read_brainvis( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, verbose = TRUE )
read_brainvis( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, verbose = TRUE )
file |
file path to the data file |
extract_path |
location to where the extracted information is to be stored |
header_only |
whether to only load header data |
cache_ok |
whether existing cache should be reused; default is
|
verbose |
whether to print processing messages; default is |
A cached object that is readily to be loaded to memory; see
SignalDataCache
for class definition.
if( ieegio_sample_data("brainvis.dat", test = TRUE) ) { # ensure the header and marker files are downloaded as well ieegio_sample_data("brainvis.vhdr") ieegio_sample_data("brainvis.dat") file <- ieegio_sample_data("brainvis.vmrk") x <- read_brainvis(file) print(x) x$get_header() x$get_channel_table() x$get_annotations() channel <- x$get_channel(10) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
if( ieegio_sample_data("brainvis.dat", test = TRUE) ) { # ensure the header and marker files are downloaded as well ieegio_sample_data("brainvis.vhdr") ieegio_sample_data("brainvis.dat") file <- ieegio_sample_data("brainvis.vmrk") x <- read_brainvis(file) print(x) x$get_header() x$get_channel_table() x$get_annotations() channel <- x$get_channel(10) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
Read 'EDF' or 'BDF' data file
read_edf( con, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, begin = 0, end = Inf, convert = TRUE, verbose = TRUE )
read_edf( con, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, begin = 0, end = Inf, convert = TRUE, verbose = TRUE )
con |
file or connection to the data file |
extract_path |
location to where the extracted information is to be stored |
header_only |
whether to only load header data |
cache_ok |
whether existing cache should be reused; default is
|
begin , end
|
begin and end of the data to read |
convert |
whether to convert digital numbers to analog signals; default
is |
verbose |
whether to print processing messages; default is |
A cached object that is readily to be loaded to memory; see
SignalDataCache
for class definition.
# ---- EDF/BDF(+) --------------------------------------------------------- # Run `ieegio_sample_data("edfPlusD.edf")` to download sample data # Tun example if the sample data exists if(ieegio_sample_data("edfPlusD.edf", test = TRUE)) { edf_path <- ieegio_sample_data("edfPlusD.edf") data <- read_edf(edf_path) data$get_header() data$get_annotations() data$get_channel_table() channel <- data$get_channel(1) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
# ---- EDF/BDF(+) --------------------------------------------------------- # Run `ieegio_sample_data("edfPlusD.edf")` to download sample data # Tun example if the sample data exists if(ieegio_sample_data("edfPlusD.edf", test = TRUE)) { edf_path <- ieegio_sample_data("edfPlusD.edf") data <- read_edf(edf_path) data$get_header() data$get_annotations() data$get_channel_table() channel <- data$get_channel(1) plot( channel$time, channel$value, type = "l", main = channel$info$Label, xlab = "Time", ylab = channel$info$Unit ) }
Read ('BlackRock') 'NEV' 'NSx' data
read_nsx( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, include_waveform = FALSE, verbose = TRUE )
read_nsx( file, extract_path = getOption("ieegio.extract_path", NULL), header_only = FALSE, cache_ok = TRUE, include_waveform = FALSE, verbose = TRUE )
file |
file path to the data file |
extract_path |
location to where the extracted information is to be stored |
header_only |
whether to only load header data |
cache_ok |
whether existing cache should be reused; default is
|
include_waveform |
whether to include 'waveform' data (usually for
online spike sorting); default is |
verbose |
whether to print processing messages; default is |
A cached object that is readily to be loaded to memory; see
SignalDataCache
for class definition.
Life cycle: experimental.
Read "Neurodata Without Borders" ('NWB' format) file. Unlike other readers
read_nwb
returns low-level 'Python' class handler via pynwb
module.
read_nwb(file, mode = c("r", "w", "r+", "a", "w-", "x"), ...)
read_nwb(file, mode = c("r", "w", "r+", "a", "w-", "x"), ...)
file |
path to 'NWB' file |
mode |
file open mode; default is |
... |
passed to |
A NWBHDF5IO
instance
if(ieegio_sample_data("nwb_sample.nwb", test = TRUE)) { file <- ieegio_sample_data("nwb_sample.nwb") # Create NWBIO container container <- read_nwb(file) # Open connection container$open() # read meta data data <- container$read() data # get `test_timeseries` data ts_data <- data$get_acquisition("test_timeseries") ts_data # read timeseries data into memory ts_arr <- ts_data$data[] ts_arr # Convert Python array to R # using `rpymat::py_to_r(ts_arr)` or as.numeric(ts_arr) # Make sure you close the connection container$close() } # Requires setting up Python environment # run `ieegio::install_pynwb()` to set up environment first ## Not run: # Replicating tutorial # https://pynwb.readthedocs.io/en/stable/tutorials/general/plot_file.html library(rpymat) # Load Python module pynwb <- import("pynwb") uuid <- import("uuid") datetime <- import("datetime") np <- import("numpy") tz <- import("dateutil.tz") # 2018L is 2018 as integer session_start_time <- datetime$datetime( 2018L, 4L, 25L, 2L, 30L, 3L, tzinfo=tz$gettz("US/Pacific")) # ---- Create NWB file object ------------------------ nwbfile <- pynwb$NWBFile( session_description="Mouse exploring a closed field", identifier=py_str(uuid$uuid4()), session_start_time=session_start_time, session_id="session_4321", experimenter=py_list(c("Baggins, Frodo")), lab="Bag End Laboratory", institution="University of Middle Earth at the Shire", experiment_description="Thank you Bilbo Baggins.", keywords=py_list(c("behavior", "exploration")) ) # ---- Add subject ------------------------------------ subject <- pynwb$file$Subject( subject_id="001", age="P90D", description="mouse 5", species="Mus musculus", sex="M" ) nwbfile$subject <- subject nwbfile # ---- Add TimeSeries ------------------------------------ data <- seq(100, 190, by = 10) time_series_with_rate <- pynwb$TimeSeries( name="test_timeseries", description="an example time series", data=data, unit="m", starting_time=0.0, rate=1.0 ) time_series_with_rate nwbfile$add_acquisition(time_series_with_rate) # ---- New Spatial positions ------------------------------------ position_data <- cbind( seq(0, 10, length.out = 50), seq(0, 9, length.out = 50) ) position_timestamps = seq(0, 49) / 200 spatial_series_obj = pynwb$behavior$SpatialSeries( name="SpatialSeries", description="(x,y) position in open field", data=position_data, timestamps=position_timestamps, reference_frame="(0,0) is bottom left corner", ) spatial_series_obj position_obj = pynwb$behavior$Position( spatial_series=spatial_series_obj) position_obj # ---- Behavior Processing Module ------------------------------ behavior_module <- nwbfile$create_processing_module( name="behavior", description="processed behavioral data" ) behavior_module$add(position_obj) nwbfile$processing$behavior # omit some process # ---- Write --------------------------------------------------- f <- normalizePath(tempfile(fileext = ".nwb"), winslash = "/", mustWork = FALSE) io <- pynwb$NWBHDF5IO(f, mode = "w") io$write(nwbfile) io$close() ## End(Not run)
if(ieegio_sample_data("nwb_sample.nwb", test = TRUE)) { file <- ieegio_sample_data("nwb_sample.nwb") # Create NWBIO container container <- read_nwb(file) # Open connection container$open() # read meta data data <- container$read() data # get `test_timeseries` data ts_data <- data$get_acquisition("test_timeseries") ts_data # read timeseries data into memory ts_arr <- ts_data$data[] ts_arr # Convert Python array to R # using `rpymat::py_to_r(ts_arr)` or as.numeric(ts_arr) # Make sure you close the connection container$close() } # Requires setting up Python environment # run `ieegio::install_pynwb()` to set up environment first ## Not run: # Replicating tutorial # https://pynwb.readthedocs.io/en/stable/tutorials/general/plot_file.html library(rpymat) # Load Python module pynwb <- import("pynwb") uuid <- import("uuid") datetime <- import("datetime") np <- import("numpy") tz <- import("dateutil.tz") # 2018L is 2018 as integer session_start_time <- datetime$datetime( 2018L, 4L, 25L, 2L, 30L, 3L, tzinfo=tz$gettz("US/Pacific")) # ---- Create NWB file object ------------------------ nwbfile <- pynwb$NWBFile( session_description="Mouse exploring a closed field", identifier=py_str(uuid$uuid4()), session_start_time=session_start_time, session_id="session_4321", experimenter=py_list(c("Baggins, Frodo")), lab="Bag End Laboratory", institution="University of Middle Earth at the Shire", experiment_description="Thank you Bilbo Baggins.", keywords=py_list(c("behavior", "exploration")) ) # ---- Add subject ------------------------------------ subject <- pynwb$file$Subject( subject_id="001", age="P90D", description="mouse 5", species="Mus musculus", sex="M" ) nwbfile$subject <- subject nwbfile # ---- Add TimeSeries ------------------------------------ data <- seq(100, 190, by = 10) time_series_with_rate <- pynwb$TimeSeries( name="test_timeseries", description="an example time series", data=data, unit="m", starting_time=0.0, rate=1.0 ) time_series_with_rate nwbfile$add_acquisition(time_series_with_rate) # ---- New Spatial positions ------------------------------------ position_data <- cbind( seq(0, 10, length.out = 50), seq(0, 9, length.out = 50) ) position_timestamps = seq(0, 49) / 200 spatial_series_obj = pynwb$behavior$SpatialSeries( name="SpatialSeries", description="(x,y) position in open field", data=position_data, timestamps=position_timestamps, reference_frame="(0,0) is bottom left corner", ) spatial_series_obj position_obj = pynwb$behavior$Position( spatial_series=spatial_series_obj) position_obj # ---- Behavior Processing Module ------------------------------ behavior_module <- nwbfile$create_processing_module( name="behavior", description="processed behavioral data" ) behavior_module$add(position_obj) nwbfile$processing$behavior # omit some process # ---- Write --------------------------------------------------- f <- normalizePath(tempfile(fileext = ".nwb"), winslash = "/", mustWork = FALSE) io <- pynwb$NWBHDF5IO(f, mode = "w") io$write(nwbfile) io$close() ## End(Not run)
This class is an internal abstract class
get_header()
Get header information, often small list object
SignalDataCache$get_header(...)
...
passed to child methods
get_annotations()
Get annotation information, often a large table
SignalDataCache$get_annotations(...)
...
passed to child methods
get_channel_table()
Get channel table
SignalDataCache$get_channel_table(...)
...
passed to child methods
get_channel()
Get channel data
SignalDataCache$get_channel(x, ...)
x
channel order or label
...
passed to child methods
Channel signal with time-stamps inheriting class
'ieegio_get_channel'
delete()
Delete file cache
SignalDataCache$delete(...)
...
passed to child methods