## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  out.width = "100%"
)
library(pizzarr)

sample_dir <- tools::R_user_dir("pizzarr")
clean <- !dir.exists(sample_dir)

has_blosc <- requireNamespace("blosc", quietly = TRUE)

idr_url <- "https://uk1s3.embassy.ebi.ac.uk/idr/zarr/v0.4/idr0062A/6001240.zarr"
online <- tryCatch({
  con <- url(paste0(idr_url, "/.zattrs"))
  on.exit(try(close(con), silent = TRUE))
  length(readLines(con, warn = FALSE)) > 0
}, error = function(e) FALSE, warning = function(w) FALSE)

## ----eval = has_blosc---------------------------------------------------------
root <- pizzarr_sample("dog.ome.zarr")

g <- zarr_open_group(DirectoryStore$new(root))

attrs <- g$get_attrs()$to_list()
names(attrs)

## ----eval = has_blosc---------------------------------------------------------
vapply(attrs$multiscales[[1]]$datasets, function(d) d$path, character(1))

## ----eval = has_blosc---------------------------------------------------------
first_resolution <- attrs$multiscales[[1]]$datasets[[1]]$path

zarr_arr <- g$get_item(first_resolution)
zarr_arr$get_shape()

## ----eval = has_blosc, fig.alt = "Photograph of a dog, decoded from a local OME-NGFF Zarr store."----
arr <- zarr_arr$get_item("...")$data

dm <- dim(arr)
plot.new()
plot.window(c(0, dm[3]), c(0, dm[2]), asp = 1)
rasterImage(aperm(arr, c(2, 3, 1)) / 255, 0, 0, dm[3], dm[2])

## ----eval = has_blosc && online-----------------------------------------------
# g <- zarr_open_group(HttpStore$new(idr_url))
# 
# attrs <- g$get_attrs()$to_list()
# first_resolution <- attrs$multiscales[[1]]$datasets[[1]]$path
# 
# zarr_arr <- g$get_item(first_resolution)
# zarr_arr$get_shape()

## ----eval = has_blosc && online-----------------------------------------------
# z_index <- 118
# 
# nested_arr <- zarr_arr$get_item(list(
#   slice(1, 2), slice(z_index, z_index), slice(NA, NA), slice(NA, NA)
# ))
# 
# nested_arr$shape

## ----eval = has_blosc && online, fig.alt = "Two-channel fluorescence microscopy Z-plane rendered as a red and green composite."----
# arr <- nested_arr$data
# 
# rg_arr <- aperm(arr, c(2, 4, 3, 1))[1, , , ]
# rgb_arr <- array(0, dim = c(271, 275, 3))
# rgb_arr[, , 1] <- rg_arr[, , 1]
# rgb_arr[, , 2] <- rg_arr[, , 2]
# 
# plot.new()
# plot.window(c(0, 271), c(0, 275), asp = 1)
# rasterImage(rgb_arr / max(rgb_arr), 0, 0, 271, 275)

## ----include = FALSE----------------------------------------------------------
if (clean) unlink(sample_dir, recursive = TRUE)

