diff --git a/R/CTutils.R b/R/CTutils.R index db9d02e6..505b82ec 100644 --- a/R/CTutils.R +++ b/R/CTutils.R @@ -198,7 +198,7 @@ setMethod("addCT", "SpatialDataElement", is.character(type), length(type) == 1) y <- meta(x) .check_ct(y, type, data) - dim <- length(dim(x)) + dim <- length(axes(x)) axes <- .default_ax( type=. <- tolower(sub("^SpatialData", "", class(x)[1])), dim=if (. == "image") dim-1 else dim) # ignore 'channel' diff --git a/R/crop.R b/R/crop.R index 8b8de3ce..000c49d7 100644 --- a/R/crop.R +++ b/R/crop.R @@ -133,7 +133,13 @@ NULL ct[[type]] <- .adapt(data, type) } # update input axes from 'cyx' to 'xy' - ct$input$axes <- .default_ax(type="shape") + # (for affine, also output axes & matrix) + xy <- .default_ax(type="shape") + if (ct$type == "affine") { + ct$affine <- .ct_affine(ct, .ax_names(xy), axes(x, "name")) + ct$output$axes <- xy + } + ct$input$axes <- xy ct$input$name <- "xy" # create temporary shape & transform back md <- SpatialDataAttrs(type="shape", trans=list(ct)) diff --git a/R/trans.R b/R/trans.R index 77df4710..9e4c9ba9 100644 --- a/R/trans.R +++ b/R/trans.R @@ -57,12 +57,35 @@ setMethod("transform", "SpatialDataElement", \(x, i=1, ...) { if (f == "identity") return(x) t <- CTdata(x, i) t <- switch(f, - affine=do.call(rbind, lapply(t, unlist)), + affine=.ct_affine(CTlist(x)[[i]], axes(x, "name")), sequence=lapply(t, unlist), unlist(t)) do.call(f, list(x, t, ...)) }) +# matrix of affine transformation 'ct' for axes 'ax'; its rows follow +# the output & its columns the input axes of 'ct' (if these aren't +# specified, both are taken to be the element's axes 'el') +.ct_affine <- \(ct, ax, el=ax) { + m <- ct$affine # matrix, or list of rows + if (!is.matrix(m)) m <- do.call(rbind, lapply(m, unlist)) + i <- .ax_names(ct$input$axes %||% el) + o <- .ax_names(ct$output$axes %||% el) + if (!all(ax %in% i, ax %in% o)) stop( + "in/output axes of 'affine' transformation ", + "don't include '", paste(ax, collapse=""), "'") + if (!identical(dim(m), c(length(o), length(i)+1L))) stop( + "'affine' transformation data should be a ", length(o), "x", + length(i)+1, " matrix according to its in/output axes") + i <- match(ax, i) + o <- match(ax, o) + # other (e.g., channel) axes are dropped; these mustn't matter + if (any(m[o, -c(i, ncol(m))] != 0)) stop( + "'affine' transformation of '", paste(ax, collapse=""), + "' depends on other axes; this isn't supported") + m[o, c(i, ncol(m)), drop=FALSE] +} + #' @export #' @rdname trans #' @importFrom BiocGenerics sequence @@ -168,6 +191,15 @@ setMethod("translation", # point/shape ---- +# inverse of an affine transformation given as n x (n+1) matrix +# (linear part & translation); returned in the same layout +.inv_affine <- \(m) { + n <- nrow(m) + a <- tryCatch(solve(m[, -(n+1), drop=FALSE]), error=\(e) + stop("'affine' transformation is not invertible")) + cbind(a, -a %*% m[, n+1]) +} + #' @importFrom dplyr mutate #' @importFrom rlang call2 !! .trans_f <- \(x, t, f=c("scale", "rotate", "translation", "affine"), rev=FALSE) { @@ -178,7 +210,7 @@ setMethod("translation", n <- length(axes(x)) map <- list( len=c(scale=n, rotate=1, translation=n, affine=n), - ids=c(scale=1, rotate=0, translation=0, affine=1), + ids=c(scale=1, rotate=0, translation=0), fns=c(scale="ST_Scale", rotate="ST_Rotate", affine="ST_Affine", @@ -197,18 +229,23 @@ setMethod("translation", # skip identity id <- switch(f, rotate=(t %% 360 == 0), + affine=all(t == cbind(diag(n), 0)), all(t == map$ids[f])) if (id) return(x) # (optional) reverse - if (rev) t <- switch(f, scale=1/t, -t) + if (rev) t <- switch(f, scale=1/t, affine=.inv_affine(t), -t) # edge case: rescale radii if (f == "scale" && "radius" %in% names(x)) data(x) <- mutate(data(x), radius=!!t[1]*radius) - # dynamic injection 'ST_*(geo, v1, v2, ...)' - v <- switch(f, rotate=t*pi/180, t) # radians + # dynamic injection 'ST_*(geo, v1, v2, ...)'; + # 'ST_Affine' expects the linear part by row, then offsets + v <- switch(f, + rotate=t*pi/180, # radians + affine=unname(c(base::t(t[, -ncol(t)]), t[, ncol(t)])), + t) data(x) <- mutate(data(x), geometry=!!call2(map$fns[f], quote(geometry), !!!v)) return(x) } diff --git a/inst/NEWS b/inst/NEWS index 6e2ccb96..1176acd0 100644 --- a/inst/NEWS +++ b/inst/NEWS @@ -3,6 +3,8 @@ changes in devel - added 'version()' to retrieve format versions of SpatialData elements (#288) - Now using `backed=TRUE` argument internally in `anndataR::read_zarr` to read `table` elements as Zarr-backed SingleCellExperiment objects (#290) +- fixed 'affine' transformations of points/shapes ('ST_Affine' argument + order, 'rev=TRUE', in/output axes), incl. cropping of images/labels (#289) changes in version 0.99.47 diff --git a/tests/testthat/test-crop.R b/tests/testthat/test-crop.R index ff168889..d59ac01a 100644 --- a/tests/testthat/test-crop.R +++ b/tests/testthat/test-crop.R @@ -117,6 +117,61 @@ test_that("crop,sdLabel", { expect_equal(dim(m <- crop(l, y)), c(h, w)) }) +test_that("crop,sdArray w/ affine", { + # map corners of box 'y' with affine 'm' & return their range + f <- \(m, y) { + xy <- expand.grid(x=c(y$xmin, y$xmax), y=c(y$ymin, y$ymax)) + xy <- cbind(as.matrix(xy), 1) %*% t(m) + list( + xmin=min(xy[, 1]), xmax=max(xy[, 1]), + ymin=min(xy[, 2]), ymax=max(xy[, 2])) + } + # 'm' is the affine (in xy order) to coordinate space 'j' of array 'a'; + # cropping by a pixel-space box mapped with 'm' should give the same + # as cropping by the box around its preimage in pixel space + g <- \(a, j, m) { + # (half-pixel bounds keep rounding off pixel edges) + y <- f(m, list(xmin=30.5, xmax=32.5, ymin=20.5, ymax=22.5)) + z <- f(solve(rbind(m, c(0, 0, 1)))[1:2, ], y) + expect_equal(.box2rev(a, y, j), z) + b <- crop(a, y, j) + expect_identical(as.array(data(b)), as.array(data(crop(a, z)))) + return(b) + } + # label: stored matrix maps (y, x) to (x, y), i.e., + # x' = 10x + 20y + 30 and y' = 40x + 50y + 60 + l <- label(x) + m <- rbind(c(10, 20, 30), c(40, 50, 60)) + expect_identical(dim(g(l, "affine", m)), c(15L, 23L)) + # w/o in/output axes, these are taken to be the label's + # (y, x), i.e., x' = 40x + 50y + 60 and y' = 10x + 20y + 30 + md <- meta(l) + k <- match("affine", CTname(l)) + md$multiscales[[1]]$coordinateTransformations[[k]]$input$axes <- NULL + md$multiscales[[1]]$coordinateTransformations[[k]]$output$axes <- NULL + meta(l) <- md + m <- rbind(c(40, 50, 60), c(10, 20, 30)) + expect_identical(dim(g(l, "affine", m)), c(15L, 23L)) + # image: matrix includes the channel axis, i.e., it's given + # in (c, y, x) order; here, x' = 2x + y + 7 and y' = 3x + y + 5 + m <- list(c(1, 0, 0, 0), c(0, 1, 3, 5), c(0, 1, 2, 7)) + i <- addCT(image(x), "affine", "affine", m) + m <- rbind(c(2, 1, 7), c(3, 1, 5)) + expect_identical(dim(g(i, "affine", m)), c(3L, 35L, 15L)) + # channels mustn't contribute to x/y + y <- list(xmin=0, xmax=1, ymin=0, ymax=1) + m <- list(c(1, 0, 0, 0), c(0, 1, 3, 5), c(1, 1, 2, 7)) + i <- addCT(image(x), "affine", "affine", m) + expect_error(crop(i, y, "affine"), "other axes") + m <- list(c(1, 0, 0, 0), c(-1, 1, 3, 5), c(0, 1, 2, 7)) + i <- addCT(image(x), "affine", "affine", m) + expect_error(crop(i, y, "affine"), "other axes") + # matrix should fit the image's (c, y, x) axes + m <- list(c(1, 3, 5), c(1, 2, 7)) + i <- addCT(image(x), "affine", "affine", m) + expect_error(crop(i, y, "affine"), "3x4 matrix") +}) + test_that("crop input 'y' .to_sf()", { ok <- \(x) { expect_s3_class(x, "sf") diff --git a/tests/testthat/test-trans.R b/tests/testthat/test-trans.R index 6a6b15d6..08f0ee7f 100644 --- a/tests/testthat/test-trans.R +++ b/tests/testthat/test-trans.R @@ -93,8 +93,9 @@ test_that("translation,labelArray", { # point/shape ---- +.xy <- \(x) unname(as.matrix(centroids(x)[unlist(axes(x))])) + test_that("trans,sdFrame", { - .xy <- \(x) unname(as.matrix(centroids(x)[unlist(axes(x))])) for (x in c(as.list(points(sd)), as.list(shapes(sd)))) { n <- length(unlist(axes(x))) @@ -102,6 +103,7 @@ test_that("trans,sdFrame", { expect_identical(rotate(x, 0), x) expect_identical(scale(x, rep(1, n)), x) expect_identical(translation(x, rep(0, n)), x) + expect_identical(affine(x, cbind(diag(n), 0)), x) # invalid expect_error(translation(x, "a")) # non-numeric @@ -144,5 +146,90 @@ test_that("trans,sdFrame", { expect_equal( lapply(extent(affine(x, mtx)), diff), within(lapply(old, diff), { x <- x*sx; y <- y*sy })) + # rotate by 30/90 degrees; should match 'rotate()' + if (n == 2) for (deg in c(30, 90)) { + rad <- deg * pi / 180 + R <- matrix(c(cos(rad), -sin(rad), sin(rad), cos(rad)), 2, 2) + mtx <- cbind(t(R), 0) + expect_equal(.xy(affine(x, mtx)), .xy(rotate(x, deg))) + } + # dimnames should be ignored + mtx <- cbind(diag(n) + seq_len(n) / 10, seq_len(n)) + nms <- list(letters[seq_len(n)], LETTERS[seq_len(n+1)]) + y <- affine(x, `dimnames<-`(mtx, nms)) + expect_equal(.xy(y), .xy(affine(x, mtx))) + # reverse; should invert (not negate) the matrix + y <- affine(affine(x, mtx), mtx, rev=TRUE) + expect_equal(.xy(y), .xy(x)) + inv <- solve(rbind(mtx, c(rep(0, n), 1)))[seq_len(n), ] + expect_equal(.xy(affine(x, mtx, rev=TRUE)), .xy(affine(x, inv))) + y <- affine(x, `dimnames<-`(mtx, nms), rev=TRUE) + expect_equal(.xy(y), .xy(affine(x, inv))) + # (also far from the origin) + mtx <- cbind(diag(n), 5e7) + y <- affine(affine(x, mtx), mtx, rev=TRUE) + expect_equal(.xy(y), .xy(x)) + # singular matrices can't be reversed + mtx <- cbind(matrix(1, n, n), 0) + expect_error(affine(x, mtx, rev=TRUE), "not invertible") + # matrix of ones isn't the identity (all axes become their sum+1) + y <- affine(x, matrix(1, n, n+1)) + y <- sf::st_coordinates(sf::st_as_sf(data(y)))[, seq_len(n)] + z <- sf::st_coordinates(sf::st_as_sf(data(x)))[, seq_len(n)] + expect_equal(unname(y), matrix(rowSums(z)+1, nrow(z), n)) + } +}) + +test_that("transform,sdFrame w/ affine axes", { + x <- shape(sd) + # x' = x + 2y + 3, y' = 4x + 5y + 6 + A <- rbind(c(1, 2, 3), c(4, 5, 6)) + .rows <- \(m) lapply(seq_len(nrow(m)), \(.) m[., ]) + # add affine 'm', with in/output axes modified by 'f'/'g' + .aff <- \(x, m, f=identity, g=f) { + x <- addCT(x, "aff", "affine", .rows(m)) + md <- meta(x) + i <- match("aff", CTname(x)) + ct <- md[["coordinateTransformations"]][[i]] + ct$input$axes <- f(ct$input$axes) + ct$output$axes <- g(ct$output$axes) + md[["coordinateTransformations"]][[i]] <- ct + meta(x) <- md + return(x) } + .ok <- \(y) expect_equal(.xy(transform(y, "aff")), .xy(affine(x, A))) + # axes as for the element, or missing + .ok(.aff(x, A)) + .ok(.aff(x, A, \(.) NULL)) + # in- and/or output axes in reverse order + .ok(.aff(x, A[2:1, c(2, 1, 3)], rev)) + .ok(.aff(x, A[2:1, ], identity, rev)) + .ok(y <- .aff(x, A[, c(2, 1, 3)], rev, identity)) + expect_equal( + .xy(transform(y, "aff", rev=TRUE)), + .xy(affine(x, A, rev=TRUE))) + # axes other than the element's + z <- \(.) `[[<-`(., 1, list(name="z", type="space")) + expect_error(transform(.aff(x, A, z, identity), "aff"), "don't include") + expect_error(transform(.aff(x, A, identity, z), "aff"), "don't include") + # data that don't fit the axes + y <- .aff(x, rbind(A, c(0, 0, 1))) + expect_error(transform(y, "aff"), "2x3 matrix") + y <- .aff(x, cbind(A, 0)) + expect_error(transform(y, "aff"), "2x3 matrix") + # more output than input axes (rows follow the output axes) + z <- \(.) c(., list(list(name="z", type="space"))) + .ok(.aff(x, rbind(A, c(0, 0, 1)), identity, z)) + # 3D; 'addCT()' should use the element's (xyz) axes + p <- data.frame(x=c(1, 2, 3), y=c(4, 5, 6), z=c(7, 8, 9)) + p <- SpatialDataPoint(p, meta=SpatialDataAttrs(type="point", dim=3)) + m <- rbind(c(1, 2, 0, 3), c(4, 5, 0, 6), c(0, 0, 1, 0)) + q <- .aff(p, m) + ct <- CTlist(q)[[match("aff", CTname(q))]] + expect_identical(.ax_names(ct$input$axes), axes(p, "name")) + expect_identical(.ax_names(ct$output$axes), axes(p, "name")) + expect_equal(extent(transform(q, "aff")), extent(affine(p, m))) + # (x' = x + 2y + 3 and y' = 4x + 5y + 6) + expect_equal(extent(affine(p, m)), list(x=c(12, 18), y=c(30, 48))) + expect_equal(extent(affine(affine(p, m), m, rev=TRUE)), extent(p)) })