Skip to content

Commit 34904b0

Browse files
committed
factor out max-projection
1 parent f37a032 commit 34904b0

3 files changed

Lines changed: 29 additions & 15 deletions

File tree

R/plotImage.R

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,8 @@ NULL
161161
#' @importFrom spatialdataR data_type
162162
.df_i <- \(x, k=NULL, ch=NULL, c=NULL, cl=NULL) {
163163
a <- .get_ms_data(x, k)
164-
# max-projection over z-stacks
165-
d <- length(dim(x))
166-
if (d == 4) a <- apply(a, c(1, 3, 4), max)
164+
# 2D max-projection
165+
a <- .project(x, a)
167166
# subset channels of interest
168167
a <- a[.ch_idx(x, ch),,,drop=FALSE]
169168
a <- .norm_ia(a, data_type(x))

R/plotLabel.R

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ NULL
6060
setMethod("plotLabel", "SpatialData", \(x, i=1, j=1, k=NULL, c=NULL,
6161
a=0.5, pal=NULL, nan=NA, assay=1, z=NULL) {
6262

63+
if (!is.null(z)) {
64+
ok <- length(z) == 1 && is.numeric(z) && z == round(z) && z > 0
65+
if (!ok) stop("invalid 'z'; should be a scalar integer > 0")
66+
}
67+
6368
if (is.numeric(i)) i <- labelNames(x)[i]
6469
i <- match.arg(i, labelNames(x))
6570
y <- label(x, i)
@@ -71,18 +76,8 @@ setMethod("plotLabel", "SpatialData", \(x, i=1, j=1, k=NULL, c=NULL,
7176

7277
# get array data
7378
ym <- .get_ms_data(y, k)
74-
if (length(dim(ym)) > 2) {
75-
if (is.null(z)) {
76-
# max-projection across z-slices
77-
nm <- vapply(axes(y), \(.) .$name, character(1))
78-
yx <- match(c("y", "x"), nm)
79-
ym <- apply(ym, yx, max)
80-
} else {
81-
# subset target z-slice
82-
ym <- ym[z,,]
83-
}
84-
}
85-
79+
ym <- .project(y, ym, z)
80+
8681
# keep only indices != 0 since labels might be sparse
8782
# and thus save memory by not plotting all pixels
8883
idx <- BiocGenerics::which(ym != 0L, arr.ind=TRUE)

R/utils.R

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,26 @@
5959
data(x, .guess_scale(x, w, h))
6060
}
6161

62+
# x = image or label
63+
# y = high-dim. array
64+
# z = (optional) index
65+
.project <- \(x, y, z=NULL) {
66+
ok <- c("x", "y", "c")
67+
as <- axes(x, "name")
68+
ok <- as %in% ok
69+
if (all(ok)) return(y) # 2D
70+
if (is.null(z)) { # project
71+
y <- apply(y, which(ok), max)
72+
return(y)
73+
}
74+
# specific slice
75+
i <- !logical(length(as))
76+
i <- as.list(i)
77+
i[as == "z"] <- z
78+
arg <- c(list(y), i)
79+
do.call(`[`, arg)
80+
}
81+
6282
#' @importFrom utils tail
6383
.raw_wh <- \(x) {
6484
wh <- metadata(x)$wh

0 commit comments

Comments
 (0)