-
Notifications
You must be signed in to change notification settings - Fork 0
/
clustervol.R
213 lines (183 loc) · 7.35 KB
/
clustervol.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#' ClusteredNeuroVol
#'
#' Construct a \code{\linkS4class{ClusteredNeuroVol}} instance
#'
#' @param mask an instance of class \code{\linkS4class{LogicalNeuroVol}}
#' @param clusters a vector of clusters ids with length equal to number of nonzero voxels in mask \code{mask}
#' @param label_map an optional \code{list} that maps from cluster id to a cluster label, e.g. (1 -> "FFA", 2 -> "PPA")
#' @param label an optional \code{character} string used to label of the volume
#' @return \code{\linkS4class{ClusteredNeuroVol}} instance
#'
#' @details
#'
#' The use case of \code{ClusteredNeuroVol} is to store volumetric data that has been clustered into discrete sets of voxels,
#' each of which has an associated id. For example, this class can be used to represent parcellated neuroimaging volumes.
#'
#' @export ClusteredNeuroVol
#' @examples
#'
#' bspace <- NeuroSpace(c(16,16,16), spacing=c(1,1,1))
#' grid <- index_to_grid(bspace, 1:(16*16*16))
#' kres <- kmeans(grid, centers=10)
#' mask <- NeuroVol(rep(1, 16^3),bspace)
#' clusvol <- ClusteredNeuroVol(mask, kres$cluster)
#' @rdname ClusteredNeuroVol-class
ClusteredNeuroVol <- function(mask, clusters, label_map=NULL, label="") {
mask <- as(mask, "LogicalNeuroVol")
space <- space(mask)
ids <- sort(unique(clusters))
stopifnot(length(clusters) == sum(mask))
if (length(ids) == 1) {
warning("clustered volume only contains 1 partition")
}
if (is.null(label_map)) {
labs <- paste("Clus_", ids, sep="")
label_map <- as.list(ids)
names(label_map) <- labs
} else {
stopifnot(length(label_map) == length(ids))
stopifnot(all(unlist(label_map) %in% ids))
}
clus_idx <- which(mask == TRUE)
#cds <- index_to_coords(mask, clus_idx)
clus_split <- split(clus_idx, clusters)
clus_names <- names(clus_split)
cluster_map <- new.env()
for (i in 1:length(clus_split)) {
cluster_map[[clus_names[[i]]]] <- clus_split[[clus_names[[i]]]]
}
sv <- Matrix::sparseVector(x=clusters, i=clus_idx, length=prod(dim(space)))
#svol <- SparseNeuroVol(clusters, space(mask), indices=which(mask != 0))
new("ClusteredNeuroVol", data=sv, mask=mask, clusters=as.integer(clusters),
label_map=label_map, cluster_map=cluster_map, space=space)
}
#' Conversion from ClusteredNeuroVol to LogicalNeuroVol
#'
#' @keywords internal
#' @rdname ClusteredNeuroVol-methods
#' @name as,ClusteredNeuroVol,DenseNeuroVol
#' @noRd
setAs(from="ClusteredNeuroVol", to="DenseNeuroVol", def=function(from) {
data = from@clusters
indices <- which(from@mask == TRUE)
DenseNeuroVol(data, space(from), indices=indices)
})
#' show a \code{ClusteredNeuroVol}
#' @param object the object
#' @export
setMethod(f="show", signature=signature("ClusteredNeuroVol"),
def=function(object) {
sp <- space(object)
cat("NeuroVol\n")
cat(" Type :", class(object), "\n")
cat(" Dimension :", dim(object), "\n")
cat(" Spacing :", paste(paste(signif(sp@spacing[1:(length(sp@spacing)-1)],2), " X ", collapse=" "),
sp@spacing[length(sp@spacing)], "\n"))
cat(" Origin :", paste(paste(signif(sp@origin[1:(length(sp@origin)-1)],2), " X ", collapse=" "),
sp@origin[length(sp@origin)], "\n"))
cat(" Axes :", paste(sp@axes@i@axis, sp@axes@j@axis,sp@axes@k@axis), "\n")
cat(" Num Clusters :", num_clusters(object))
}
)
#' @export
#' @param type the type of center of mass: one of "center_of_mass" or "medoid"
#' @rdname centroids-methods
setMethod(f="centroids", signature=signature(x="ClusteredNeuroVol"),
def = function(x, type=c("center_of_mass", "medoid")) {
type <- match.arg(type)
if (type == "center_of_mass") {
do.call(rbind, split_clusters(x@mask, x) %>% map(~ centroid(.)) )
} else {
if (!requireNamespace("Gmedian", quietly = TRUE)) {
stop("Package \"Gmedian\" needed for this function to work. Please install it.",
call. = FALSE)
}
do.call(rbind, split_clusters(x@mask, x) %>% map(~ Gmedian::Gmedian(coords(., real=TRUE)) ))
}
})
## TODO add split_clusters for neurovec
#' split_clusters
#'
#' @export
#' @rdname split_clusters-methods
#' @examples
#'
#' ## split 'NeuroVol' with a 'ClusteredNeuroVol'
#' vol <- NeuroVol(array(runif(10*10*10),c(10,10,10)), NeuroSpace(c(10,10,10)))
#' mask <- as.logical(vol > .5)
#' mask.idx <- which(mask != 0)
#' grid <- index_to_coord(mask, mask.idx)
#' vox <- index_to_grid(mask, mask.idx)
#'
#' library(purrr)
#' ## partition coordinates into 50 clusters using 'kmeans'
#' kres <- kmeans(grid, centers=50, iter.max=500)
#' kvol <- ClusteredNeuroVol(mask, kres$cluster)
#' klis <- split_clusters(mask, kvol)
#' ret1 <- vol %>% split_clusters(kvol) %>% purrr::map_dbl(~ mean(values(.)))
#'
#' ## split NeuroVol with 'integer' vector of clusters.
#' indices <- numeric(prod(dim(mask)[1:3]))
#'
#' ## locations with a cluster value of 0 are ignored
#' indices[mask.idx] <- kres$cluster
#'
#' ret2 <- vol %>% split_clusters(as.integer(indices)) %>% purrr::map_dbl(~ mean(values(.)))
#' all(ret1 == ret1)
#'
setMethod(f="split_clusters", signature=signature(x="NeuroVol", clusters="ClusteredNeuroVol"),
def = function(x,clusters) {
f <- function(i) {
idx <- clusters@cluster_map[[as.character(i)]]
ROIVol(space(x), index_to_grid(x,as.numeric(idx)), x[idx])
}
#dlis <- deferred_list(lapply(1:num_clusters(clusters), function(i) f))
dlis <- deflist::deflist(f, num_clusters(clusters))
})
#' @export
#' @rdname split_clusters-methods
setMethod(f="split_clusters", signature=signature(x="NeuroVol", clusters="integer"),
def = function(x,clusters) {
assert_that(length(clusters) == prod(dim(x)[1:3]))
ind <- which(clusters > 0)
clusters <- clusters[ind]
clist <- split(ind, clusters)
f <- function(i) {
idx <- clist[[i]]
ROIVol(space(x), index_to_grid(x,as.numeric(idx)), x[idx])
}
#dlis <- deferred_list(lapply(1:length(clist), function(i) f))
dlis <- deflist::deflist(f, length(clist))
})
#' @export
#' @rdname split_clusters-methods
setMethod(f="split_clusters", signature=signature(x="NeuroVol", clusters="numeric"),
def = function(x,clusters) {
callGeneric(x,as.integer(clusters))
})
#' @export
#' @rdname split_clusters-methods
setMethod(f="split_clusters", signature=signature(x="ClusteredNeuroVol", clusters="missing"),
def = function(x,clusters) {
callGeneric(x,as.vector(x@data))
})
#' Number of Clusters
#'
#' This function returns the number of clusters in a ClusteredNeuroVol object.
#'
#' @param x A ClusteredNeuroVol object.
#'
#' @return An integer representing the number of clusters in the input object.
#'
#' @export
#' @rdname num_clusters-methods
setMethod(f="num_clusters", signature=signature(x="ClusteredNeuroVol"),
def=function(x) {
length(x@cluster_map)
})
#' @rdname as.dense-methods
#' @export
setMethod("as.dense", signature(x="ClusteredNeuroVol"),
function(x) {
NeuroVol(as.vector(x@data), space(x@mask))
})