-
Notifications
You must be signed in to change notification settings - Fork 3
/
checknii.R
107 lines (96 loc) · 2.64 KB
/
checknii.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#' @name checknii-methods
#' @docType methods
#' @aliases checknii
#' @description Ensures the output to be a character filename (or vector) from an input
#' image or \code{nifti}, but not gzipped and has \code{.nii} extension
#'
#' @title Force object to filename with .nii extension
#' @param file character or \code{nifti} object
#' @param ... options passed to \code{\link{checkimg}}
#' @return character filename of image or temporary nii,
#' with .nii extension
#'
#' @export
#' @author John Muschelli \email{muschellij2@@gmail.com}
#' @examples
#' set.seed(5)
#' dims = rep(10, 3)
#' arr = array(rnorm(prod(dims)), dim = dims)
#' arr[,,10] = 0
#' nim = oro.nifti::nifti(arr)
#' rnifti = RNifti::asNifti(nim)
#' timg = tempimg(nim)
#' limg = list(factor(timg), factor(timg))
#' func = checknii
#' func(nim)
#' func(rnifti)
#' func(timg)
#' func(limg)
setGeneric("checknii", function(file, ...) standardGeneric("checknii"))
#' @rdname checknii-methods
#' @aliases checknii,nifti-method
#' @export
setMethod("checknii", "nifti", function(file, ...) {
file = checkimg(file, gzipped = FALSE, ...)
return(file)
})
#' @rdname checknii-methods
#' @aliases checknii,factor-method
#'
#' @export
setMethod("checknii", "factor", function(file, ...) {
file = as.character(file)
checknii(file = file, ...)
})
#' @rdname checknii-methods
#' @aliases checknii,character-method
#' @importFrom R.utils gunzip
#'
#' @export
setMethod("checknii", "character", function(file, ...) {
### add vector capability
if (length(file) > 1){
file = sapply(file, checknii, ...)
return(file)
} else {
file = checkimg(file, gzipped = FALSE, ...)
if (grepl("[.]gz$", file)){
file = gunzip(filename = file,
temporary = TRUE,
overwrite = TRUE,
remove = FALSE)
}
if (!grepl("[.]nii$", file)) {
stop("Original file was not .nii or .nii.gz")
}
}
return(file)
})
#' @rdname checknii-methods
#' @aliases checknii,list-method
#' @export
setMethod("checknii", "list", function(file, ...) {
### add vector capability
file = sapply(file, checknii, ...)
return(file)
})
#' @rdname checknii-methods
#' @aliases checknii,ANY-method
#' @export
setMethod("checknii", "ANY", function(file, ...) {
# workaround because can't get class
if (inherits(file, "niftiImage")) {
tfile = tempfile(fileext = ".nii")
RNifti::writeNifti(image = file, file = tfile, ...)
return(tfile)
} else {
stop("Not implemented for this type!")
}
return(file)
})
#' @rdname checknii-methods
#' @aliases ensure_nii
#' @export
ensure_nii = function(file, ...) {
checknii(file = file, ...)
}