The hardware and bandwidth for this mirror is donated by dogado GmbH, the Webhosting and Full Service-Cloud Provider. Check out our Wordpress Tutorial.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]dogado.de.

Package {volumr}


Type: Package
Title: Interactive Volume Rendering of Gridded Three-Dimensional Fields
Version: 0.1.0
Description: Turns a gridded three-dimensional field into a volume that a browser renders on the GPU by ray marching a pair of 8-bit textures, under the emission and absorption model of Max (1995) <doi:10.1109/2945.468400>. The field is resampled onto a uniform vertical grid, carried into 8 bits through a monotone transfer whose error is reported against the source, and written as one image per level with a manifest that records the grid, the transfer and a SHA-256 of every input and every output. The payload is served from a directory or carried inside a single HTML file that opens with no server. An 'htmlwidget' exposes the renderer to 'shiny' and to R Markdown, and shinyVolumr() puts the whole workflow in a 'shinydashboard' application that also accepts a field uploaded by the reader. Marine heatwave cumulative intensity in the Mediterranean over the 0 to 250 m layer ships as the case study.
License: GPL (≥ 3)
URL: https://github.com/datalab-icman/volumr
BugReports: https://github.com/datalab-icman/volumr/issues
Encoding: UTF-8
Language: en-GB
Depends: R (≥ 4.1)
Imports: base64enc, digest, ggplot2, grDevices, htmltools, htmlwidgets, jsonlite, Rcpp, stats, tools, utils
LinkingTo: Rcpp
Suggests: cmocean, knitr, ncdf4, png, rmarkdown, sf, shiny, shinydashboard, testthat (≥ 3.0.0)
SystemRequirements: zlib
VignetteBuilder: knitr
Config/testthat/edition: 3
Config/roxygen2/version: 8.1.1
LazyData: true
LazyDataCompression: xz
NeedsCompilation: yes
Packaged: 2026-11-11 18:59:00 UTC; pablo
Author: Pablo Almaraz ORCID iD [aut, cre], Manuel Fernandez-Barba ORCID iD [aut], DataLab ICMAN [aut] (URL: https://datalab-icman.github.io/)
Maintainer: Pablo Almaraz <pablo.almaraz@csic.es>
Repository: CRAN
Date/Publication: 2026-12-02 13:10:02 UTC

volumr: Interactive Volume Rendering of Gridded Three-Dimensional Fields

Description

Turns a gridded three-dimensional field into a volume that a browser renders on the GPU by ray marching a pair of 8-bit textures, under the emission and absorption model of Max (1995) doi:10.1109/2945.468400. The field is resampled onto a uniform vertical grid, carried into 8 bits through a monotone transfer whose error is reported against the source, and written as one image per level with a manifest that records the grid, the transfer and a SHA-256 of every input and every output. The payload is served from a directory or carried inside a single HTML file that opens with no server. An 'htmlwidget' exposes the renderer to 'shiny' and to R Markdown, and shinyVolumr() puts the whole workflow in a 'shinydashboard' application that also accepts a field uploaded by the reader. Marine heatwave cumulative intensity in the Mediterranean over the 0 to 250 m layer ships as the case study.

Author(s)

Maintainer: Pablo Almaraz pablo.almaraz@csic.es (ORCID)

Authors:

See Also

Useful links:


Marine heatwave cumulative intensity in the Mediterranean Sea

Description

Cumulative intensity of marine heatwaves in the Mediterranean Sea over the 0 to 250 m layer, on fifteen measured depths, as the case study of the package, at an eighth of a degree.

Usage

med_mhw

Format

A vol_field(): a list whose values element is a numeric array of 15 depths by 127 latitudes by 339 longitudes, with NA where the water column ends or the domain does. The other elements are lon and lat, the coordinate vectors at an eighth of a degree; depth, the fifteen measured levels 0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100, 125, 150, 175, 200, 225 and 250 m; name and unit; mask, the land points; and source, the provenance, including a SHA-256 of each of the fifteen arrays the field was built from and step, the decimation of the native grid.

Details

Marine heatwave cumulative intensity in the Mediterranean Sea

Cumulative intensity accumulates the temperature anomaly over the days a marine heatwave lasts, in degree Celsius days, under the definition of Hobday et al. (2016), against a 1993 to 2022 reference period. Coverage falls from 37.4 % of the box at the surface to 29.5 % at 250 m, as the sea floor rises to meet the level.

The study computed the field on a grid of a twenty-fourth of a degree, 1016 by 380 points. This object keeps every third point in longitude and latitude, which brings it to 1.6 MB compressed, so that the package stays within the size of a CRAN package; the values at the points kept are the values of the study, not averages.

vol_example_payload() is the field at the native grid, already written as a payload of 1.5 MB, for the picture at the resolution of the study. The script data-raw/med_mhw.R of the package source repository rebuilds this object from the source arrays, and its ⁠--step 1⁠ option gives the native field.

Source

Copernicus Marine Service, Mediterranean Sea physical reanalysis, product MEDSEA_MULTIYEAR_PHY_006_004, doi:10.25423/CMCC/MEDSEA_MULTIYEAR_PHY_006_004_E3R1. The marine heatwave metric was computed from that reanalysis at the Instituto de Ciencias Marinas de Andalucia, CSIC.

References

Escudier, R., Clementi, E., Cipollone, A., Pistoia, J., Drudi, M., Grandi, A., Lyubartsev, V., Lecci, R., Aydogdu, A., Delrosso, D., Omar, M., Masina, S., Coppini, G., & Pinardi, N. (2021). A high resolution reanalysis for the Mediterranean Sea. Frontiers in Earth Science, 9, 702285. doi:10.3389/feart.2021.702285

Hobday, A. J., Alexander, L. V., Perkins, S. E., Smale, D. A., Straub, S. C., Oliver, E. C. J., Benthuysen, J. A., Burrows, M. T., Donat, M. G., Feng, M., Holbrook, N. J., Moore, P. J., Scannell, H. A., Sen Gupta, A., & Wernberg, T. (2016). A hierarchical approach to defining marine heatwaves. Progress in Oceanography, 141, 227-238. doi:10.1016/j.pocean.2015.12.014

See Also

vol_example_payload() for the same field already written as a payload, vol_field() for the class, vol_payload() and vol_standalone() for the two artefacts built from it, shinyVolumr() for the application that opens on this field, plot.vol_field() for the views of it.

Examples

data(med_mhw)
med_mhw
plot(med_mhw, depth = 50)

p <- vol_payload(med_mhw, tempfile("payload"))
vol_standalone(p, path = file.path(tempdir(), "med.html"))

# The field at the native grid, already built
vol_standalone(vol_example_payload(), path = file.path(tempdir(), "med2.html"))

Plot the cost of the transfer

Description

Draws the quantisation error against the value it was measured at, and the depth profile of that error.

Usage

## S3 method for class 'vol_encoding'
plot(x, type = c("value", "depth"), bins = 40L, ...)

Arguments

x

A vol_encoding.

type

One of "value" or "depth".

bins

Number of value bins.

...

Ignored.

Details

Plot the cost of the transfer

The first view is the diagnostic that decides whether the transfer was the right one. A square-root transfer on a positive skewed field gives an error that grows with the value, slowly, and stays flat across the range where most of the cells are; an error that spikes in the middle of the range says the transfer is wrong for this field.

Value

A ggplot object, returned invisibly.

See Also

vol_encode() for the constructor, print.vol_encoding() and summary.vol_encoding() for the other methods, vol_payload() for the step that writes these codes into images.

Examples

data(med_mhw)
e <- vol_encode(vol_resample(med_mhw))
plot(e)
plot(e, type = "depth")

Plot a gridded field

Description

Three views of the field outside the browser: a map of one depth level, the vertical profile of its horizontal statistics, and the coverage of the grid against depth.

Usage

## S3 method for class 'vol_field'
plot(
  x,
  type = c("level", "profile", "coverage"),
  depth = NULL,
  cmap = "matter",
  limits = NULL,
  ...
)

Arguments

x

A vol_field.

type

One of "level", "profile" or "coverage".

depth

Depth in metres for type = "level"; the nearest level is drawn. Defaults to the shallowest.

cmap

Name of a colour table, from vol_colormaps().

limits

Numeric pair, the ends of the colour scale. Defaults to the 1st and 99th percentiles of the level.

...

Ignored.

Details

Plot a gridded field

The map is drawn as an equirectangular projection at the standard parallel of the domain's own middle, so a degree of longitude is shorter than a degree of latitude by the cosine of that latitude and the shapes are the ones an atlas draws. Plain plate carree, which sets the two degrees equal, stretches the Mediterranean vertically by a factor of 1.27 and a polar domain by far more. The browser view uses the same convention when it looks straight down, so the two are directly comparable. The profile shows the median and the interquartile range of the finite cells at each level, which for a marine field is taken over a shrinking sample as the bathymetry rises; the coverage panel is what says by how much.

Value

A ggplot object, returned invisibly.

See Also

vol_field() for the constructor, print.vol_field() for the one-screen report, summary.vol_field() for the numbers behind the profile panel, vol_colormaps() for the colour tables, vol_widget() for the same field in the browser.

Examples

data(med_mhw)
plot(med_mhw)
plot(med_mhw, depth = 50, cmap = "thermal")
plot(med_mhw, type = "profile")
plot(med_mhw, type = "coverage")

Plot a browser payload

Description

Draws where the bytes of the payload go, level by level, against how much of each level carries a value.

Usage

## S3 method for class 'vol_payload'
plot(x, type = c("size", "level"), depth = NULL, ...)

Arguments

x

A vol_payload.

type

One of "size" or "level".

depth

Depth for type = "level", which draws the level as the browser will read it, decoded from its image.

...

Passed to plot.vol_field() for type = "level".

Details

Plot a browser payload

The size panel is the honest picture of what compression is doing. A level whose cells are mostly absent costs a few kilobytes whatever its nominal dimensions, so the payload of a marine field is dominated by the shallow levels where the basin is widest.

Value

A ggplot object, returned invisibly.

See Also

vol_payload() for the constructor, print.vol_payload() and summary.vol_payload() for the other methods, plot.vol_field() for the level view it delegates to.

Examples

data(med_mhw)
p <- vol_payload(med_mhw, tempfile("payload"))
plot(p)
plot(p, type = "level", depth = 50)

Print the transfer into 8 bits

Description

Reports the transfer, the range it covers and the error it costs, which is the number that decides whether 8 bits are enough.

Usage

## S3 method for class 'vol_encoding'
print(x, ...)

Arguments

x

A vol_encoding.

...

Ignored.

Details

Print the transfer into 8 bits

Read the error against the width of a colour band the reader will see. An error well under one band cannot move a cell into the wrong colour.

Value

x, invisibly.

See Also

vol_encode() for the constructor, summary.vol_encoding() for the error by decile, plot.vol_encoding() for the same as a figure.

Examples

data(med_mhw)
vol_encode(vol_resample(med_mhw))

Print a gridded field

Description

Reports the grid, the span of each axis, the range of the values and the fraction of cells that carry one, in one screen.

Usage

## S3 method for class 'vol_field'
print(x, ...)

Arguments

x

A vol_field.

...

Ignored.

Details

Print a gridded field

The axis names follow the geographic element of the field, so a field on longitude and latitude is reported as such and a field on an arbitrary pair of axes is reported as X and Y.

Value

x, invisibly.

See Also

vol_field() for the constructor, summary.vol_field() for the numbers level by level, plot.vol_field() for the views.

Examples

data(med_mhw)
med_mhw

Print a browser payload

Description

Reports where the payload was written, the grid it covers, the transfer it used, its size and the settings the viewer will open with.

Usage

## S3 method for class 'vol_payload'
print(x, ...)

Arguments

x

A vol_payload.

...

Ignored.

Details

Print a browser payload

The size is the whole directory, images and manifest together, which is what a page fetches over http. The single file that carries the same payload inline is about a third larger, since base64 costs that.

Value

x, invisibly.

See Also

vol_payload() for the constructor, summary.vol_payload() for the size level by level, plot.vol_payload() for the figures, vol_standalone() for the single-file build.

Examples

data(med_mhw)
vol_payload(med_mhw, tempfile("payload"))

Render a widget in shiny

Description

The server half of the shiny pair.

Usage

render_vol_widget(expr, env = parent.frame(), quoted = FALSE)

Arguments

expr

An expression returning a vol_widget.

env

Environment in which to evaluate expr.

quoted

Is expr already quoted?

Details

Render a widget in shiny

The camera belongs to the pointer. A camera sent from the server is applied once and only when it carries a nonce the browser has not seen, so a rotation a reader has made survives every other change the server pushes.

Value

A shiny render function.

See Also

vol_widget_output() for the user-interface half, vol_widget(), vol_snapshot(), shinyVolumr().

Examples

if (interactive() && requireNamespace("shiny", quietly = TRUE)) {
  ui <- shiny::fluidPage(
    shiny::checkboxInput("slab", "Depth slab"),
    shiny::actionButton("save", "Save a PNG"),
    vol_widget_output("volume", height = "600px"))
  server <- function(input, output, session) {
    output$volume <- render_vol_widget(
      vol_widget(vol_example_payload(), inputId = "volume"))
    shiny::observeEvent(input$slab, vol_set("volume", list(slab = input$slab)))
    shiny::observeEvent(input$save, vol_snapshot("volume", "volume.png"))
  }
  shiny::shinyApp(ui, server)
}

Run the workflow as an application

Description

Puts the whole path from a gridded field to a rendered volume in one shinydashboard application: read the field, look at it, resample and quantise it, measure what that costs, write the payload, and render it. A field of the reader's own can be uploaded at the first step.

Usage

shinyVolumr(
  field = NULL,
  payload = NULL,
  tab = "home",
  launch.browser = TRUE,
  ...
)

Arguments

field

A vol_field the application opens with. Defaults to the case study, med_mhw.

payload

A payload the volume tab opens on, as a vol_payload or the path of a payload directory. Defaults to vol_example_payload() when field is left at the case study, so that the view opens at the native grid while the analysis tabs work on the packaged field; ignored once the reader builds a payload of their own.

tab

Identifier of the tab to open on, one of "home", "data", "encoding", "payload", "volume", "theory", "limits" or "about".

launch.browser

Passed to shiny::runApp().

...

Further arguments for shiny::runApp(), such as port and host.

Details

Run the workflow as an application

The application keeps three objects in a shiny::reactiveValues() store, one per stage: the field, the encoding and the payload. Each stage invalidates the ones after it, so a control that changes the transfer cannot leave a payload on screen that was built under the old one.

The volume tab drives the same page the standalone build writes, through the widget, so what a reader sees in the application and what they get in the downloaded file are one renderer and not two. The camera belongs to the pointer: the controls on the left set everything except the camera, which the two viewpoint buttons set once each time they are pressed.

An uploaded field is read from an .rds holding a vol_field or a list with the four elements the constructor needs, from a NetCDF file through vol_read_netcdf(), from a .csv of one row per cell through vol_field_from_df(), or from an .rda. Whatever comes back is put through vol_field(), so a file that does not describe a field is refused with the reason rather than half loaded.

Value

Called for its effect. Returns the value of shiny::runApp().

See Also

vol_field() for the object the application is built around, vol_payload() and vol_standalone() for the two artefacts it writes, vol_widget() for the viewer it embeds, med_mhw for the case study.

Examples

if (interactive()) {
  shinyVolumr()
  shinyVolumr(tab = "volume")
}

Summarise the cost of the transfer

Description

Reports where in the range of the field the quantisation error falls, which a single root mean square figure hides.

Usage

## S3 method for class 'vol_encoding'
summary(object, bins = 10L, ...)

Arguments

object

A vol_encoding.

bins

Number of value bins the error is summarised over.

...

Ignored.

Details

Summarise the cost of the transfer

A monotone transfer costs more where it is flat. The square-root transfer is flat at the top of the range, so the worst errors sit in the tail, and the table below says by how much. Compare the worst error in a bin against the width of the colour bands a reader will see: an error well under one band cannot move a cell into the wrong colour.

Value

An object of class summary.vol_encoding, holding the transfer record and a data frame of one row per bin with the count, the mean error and the worst error in that bin.

See Also

vol_encode() for the constructor, print.vol_encoding() and plot.vol_encoding() for the other methods, vol_payload() for the step that writes these codes into images.

Examples

data(med_mhw)
summary(vol_encode(vol_resample(med_mhw)))

Summarise a gridded field

Description

Reports the grid, the coverage of each depth level and the distribution of the values, which together say whether the field is ready for a browser payload.

Usage

## S3 method for class 'vol_field'
summary(object, ...)

Arguments

object

A vol_field.

...

Ignored.

Details

Summarise a gridded field

Coverage is the fraction of cells that are not NA, level by level. A marine field loses cells with depth as the bathymetry rises to meet it, and the profile of coverage against depth is the quickest check that the depth axis has been read in the right direction: coverage must not increase downward.

Value

An object of class summary.vol_field: a list with grid, a data frame levels of one row per depth with its coverage and quantiles, and quantiles over the whole field.

See Also

vol_field() for the constructor, print.vol_field() and plot.vol_field() for the other methods, vol_encode() for the transfer whose error depends on this distribution.

Examples

data(med_mhw)
s <- summary(med_mhw)
s
head(s$levels)

Summarise a browser payload

Description

Reports the size of the payload level by level, together with the grid and the transfer, which is what decides whether it will travel inside a page.

Usage

## S3 method for class 'vol_payload'
summary(object, ...)

Arguments

object

A vol_payload.

...

Ignored.

Details

Summarise a browser payload

Compression does the work that decimation would otherwise have to. A level that is mostly missing compresses to almost nothing, and a level full of structure does not, so the byte counts in the table below are a direct read of where the information sits in the water column.

Value

An object of class summary.vol_payload with manifest, a data frame levels of one row per image with its depth, byte count and coverage, and the totals.

See Also

vol_payload() for the constructor, print.vol_payload() for the one-screen report, plot.vol_payload() for the same numbers as a figure, vol_standalone() for the single-file build.

Examples

data(med_mhw)
summary(vol_payload(med_mhw, tempfile("payload")))

Colour tables the renderer carries

Description

Names the perceptually uniform colour tables that the payload writes into its lookup image and that the viewer offers in its menu.

Usage

vol_colormaps()

Details

Colour tables the renderer carries

The tables are the oceanographic set of Thyng et al. (2016), stored in the package as 256 sampled colours each so that a payload is written without the cmocean package installed. matter runs from pale cream through orange to dark purple and suits a positive, strongly skewed field; thermal and haline are the temperature and salinity tables; deep and dense reverse the light and dark ends, which matters when the background is white.

Value

A character vector of table names, in the order the viewer lists them.

References

Thyng, K. M., Greene, C. A., Hetland, R. D., Zimmerle, H. M., & DiMarco, S. F. (2016). True colors of oceanography: guidelines for effective and accurate colormap selection. Oceanography, 29(3), 9-13. doi:10.5670/oceanog.2016.66

See Also

vol_payload(), which writes these into the payload, plot.vol_field(), which uses one of them, and vol_widget(), whose cmap option selects one by position.

Examples

vol_colormaps()

Carry a field into 8 bits

Description

Quantises the field to the 254 codes an 8-bit texture channel can carry, through a monotone transfer, and measures the error the quantisation costs against the values it started from.

Usage

vol_encode(field, transfer = c("auto", "sqrt", "linear"))

Arguments

field

A vol_field.

transfer

Name of the transfer: "sqrt", "linear", or "auto", which takes the square root for a non-negative field and the linear ramp for any other.

Details

Carry a field into 8 bits

Eight bits per cell is what makes the payload small enough to travel inside a page, and the transfer decides where those bits are spent. With v the value, v_{lo} and v_{hi} its extremes and N = 254 the codes available, the square-root transfer writes

c = 1 + \mathrm{round}\!\left((N-1)\, \frac{\sqrt{v} - \sqrt{v_{lo}}}{\sqrt{v_{hi}} - \sqrt{v_{lo}}}\right),

and the renderer inverts it by squaring. A strongly skewed positive field is served far better by that than by a linear ramp, because the linear ramp spends most of its codes on a tail that holds few cells.

The error is reported and not assumed. For the case study the root mean square error is 0.27 and the worst single cell 1.66 degrees Celsius days, against a field that reaches 580, and the plotted colour bands are 2.5 wide, so the quantisation is well inside the resolution of the picture.

Code 0 is reserved for a missing cell, so the codes that carry data are 1 to 254. The renderer tests the companion mask before it reads a value, so a missing cell contributes nothing to the ray. A constant field takes code 1 everywhere and decodes to the constant to within rounding.

Value

A list of class vol_encoding with codes, an integer array of the same shape as the field holding 0 for a missing cell and 1 to 254 otherwise; transfer, the record the manifest carries; and error, the absolute error at every cell that carries a value.

See Also

vol_field() for the input, vol_resample() for the step before, vol_payload() for the step after, print.vol_encoding(), summary.vol_encoding() and plot.vol_encoding() for the methods that report the error.

Examples

data(med_mhw)
e <- vol_encode(vol_resample(med_mhw))
e
summary(e)
plot(e)
plot(e, type = "depth")

The case study at its native resolution

Description

Gives the path of the browser payload the package ships for the case study, already written at the native grid of a twenty-fourth of a degree, 1016 by 380 by 21.

Usage

vol_example_payload()

Details

The case study at its native resolution

This is the case study put through vol_payload() at the native grid of the study, three times finer in each horizontal direction than med_mhw, with the display settings of the figures of the study (a colour scale from 15 to 60 degree Celsius days on the matter table). The payload is 1.5 MB, since its values travel in 8 bits and its images compress.

Use it whenever the picture at full resolution is what matters. Build a payload from med_mhw instead when the display settings, the transfer or the depth grid need to be something other than these.

Value

A path to a payload directory, suitable for vol_standalone() and vol_widget().

See Also

med_mhw for the field at an eighth of a degree, vol_standalone() for the single-file build, vol_widget() to render it in shiny or R Markdown, vol_payload() to write a payload of your own.

Examples

dir <- vol_example_payload()
list.files(dir)
out <- vol_standalone(dir, path = file.path(tempdir(), "med.html"))
if (interactive()) utils::browseURL(out)

Wrap a gridded three-dimensional field

Description

Builds the object every other function in the package takes: a scalar field on a regular longitude, latitude and depth grid, with the coordinate vectors, the units and the provenance carried alongside the values.

Usage

vol_field(
  values,
  lon,
  lat,
  depth,
  name = "value",
  unit = "",
  mask = NULL,
  source = NULL,
  geographic = TRUE
)

Arguments

values

Numeric array of dimension c(nz, ny, nx), indexed by depth, then latitude, then longitude. Missing cells are NA.

lon

Numeric vector of nx longitudes, strictly increasing.

lat

Numeric vector of ny latitudes, strictly increasing from south to north.

depth

Numeric vector of nz positions along the third axis, strictly increasing. For a marine field these are depths in metres, positive downward, with the surface at or near zero; an axis measured upward is negated before it gets here, so the values may be negative.

name

Short name of the quantity, used in labels.

unit

Unit of the quantity, used in labels.

mask

Optional logical matrix of dimension c(ny, nx), TRUE where an opaque sheet is drawn at zero depth. Land, for a marine field.

source

Optional named list of provenance strings, carried into the payload manifest.

geographic

Logical. TRUE when the first two axes are longitude and latitude, which decides the axis names and the tick labels the viewer draws. FALSE for any other pair, which are then reported as X and Y.

Details

Wrap a gridded three-dimensional field

The index order is fixed and is not a matter of taste. A browser payload is one image per depth level, and an image is a matrix of rows by columns, so a level of the field has to be contiguous as values[k, , ] with latitude down the rows and longitude across the columns. Row one of a level is the southernmost latitude and column one the westernmost longitude, which is the orientation the renderer assumes and the manifest records.

The constructor checks that the three coordinate vectors match the three dimensions of values, that each is numeric, complete and strictly increasing, and that mask, when given, matches the horizontal grid. It does not require the depth axis to be uniform: vol_resample() does that, and the browser payload needs it because the GPU samples a texture on a regular grid.

The value range may be anything the transfer of vol_encode() can carry. For a strictly positive and strongly skewed field, the square-root transfer spends its 254 codes where the data are.

Value

An object of class vol_field: a list with the elements values, lon, lat, depth, name, unit, mask, source and geographic.

See Also

print.vol_field(), summary.vol_field() and plot.vol_field() for the methods, vol_resample() to put the depth axis on a uniform grid, vol_encode() for the transfer into 8 bits, vol_payload() to write the browser payload, vol_read_npy() and vol_read_netcdf() to read a field from a file.

Examples

v <- array(NA_real_, c(4, 20, 30))
for (k in 1:4) v[k, , ] <- outer(1:20, 1:30, function(i, j) exp(-k / 3) * (i + j))
f <- vol_field(v, lon = seq(10, 12.9, by = 0.1), lat = seq(40, 41.9, by = 0.1),
               depth = c(0, 10, 25, 50), name = "Tracer", unit = "mg/l")
f
summary(f)
plot(f)
plot(f, type = "profile")
plot(f, type = "coverage")

Build a field from a long data frame

Description

Turns a data frame of one row per cell into a vol_field(), taking the grid from the distinct values of the three coordinate columns. Both naming conventions are recognised: longitude, latitude and depth for a geographic field, and x, y and z for anything else.

Usage

vol_field_from_df(
  data,
  value = NULL,
  x = NULL,
  y = NULL,
  z = NULL,
  time = NULL,
  at = NULL,
  name = NULL,
  unit = "",
  flip_z = NA
)

Arguments

data

A data frame with one row per cell.

value

Name of the column holding the quantity. Guessed when absent.

x, y, z

Names of the three coordinate columns. Guessed when absent.

time

Name of a further column, when the frame holds more than one volume. Guessed when absent.

at

Value of time to take. Defaults to the first, and is ignored when there is no such column.

name, unit

Passed to vol_field(). name defaults to the value column.

flip_z

Logical. Negate the third coordinate before building, which turns an axis measured upward into the downward axis the package uses. Guessed from the column name when NA.

Details

Build a field from a long data frame

The three coordinates need not be complete and need not be sorted. The grid is the sorted distinct value of each column, a cell absent from the frame becomes NA, and a coordinate that repeats to more than one value at the same position is an error rather than a silent choice between them.

The guesses are conservative and are stated in the message the function prints when it makes them. A column named lon, long, longitude or x is the first axis; lat, latitude or y the second; depth, dep, lev, level, z, elevation, altitude or height the third; time, t, date or step the fourth. The value is whichever numeric column is left, when exactly one is.

The third axis of this package is positive downward, since it was built for a depth. A column named elevation, altitude or height is therefore negated by default, so that a field measured upward arrives the right way up; pass flip_z to say so explicitly for a column whose name does not announce it.

A frame carrying a time column holds a sequence of volumes and not one, so at picks the one to build. Rendering the sequence is not something this function does.

Value

A vol_field.

See Also

vol_field() for the object and the index order it fixes, vol_read_netcdf() and vol_read_npy() for the two file formats, vol_payload() for the step that follows, shinyVolumr() for the application that accepts such a frame as an upload.

Examples

d <- expand.grid(lon = 1:20, lat = 1:15, depth = seq(0, 100, by = 10))
d$value <- with(d, exp(-depth / 40) * sin(lon / 3) * cos(lat / 3) + 2)
f <- vol_field_from_df(d)
f
plot(f, depth = 30)

Mark grid points that fall inside a polygon

Description

Builds the logical mask the renderer draws as an opaque sheet at zero depth, by testing every grid point against a polygon set. Land, for a marine field.

Usage

vol_mask(lon, lat, polygons, planar = TRUE)

Arguments

lon

Numeric vector of longitudes.

lat

Numeric vector of latitudes.

polygons

An sf or sfc object holding the polygons.

planar

Logical. When TRUE, the containment test draws straight edges between the vertices instead of great circles.

Details

Mark grid points that fall inside a polygon

The test runs in the plane by default, and the default is not cosmetic. sf treats longitude and latitude as coordinates on a sphere unless told otherwise, so an edge between two vertices is a great circle; the convention almost every coastline product and plotting library assumes is a straight edge in the longitude and latitude plane. On a grid of a twenty-fourth of a degree the two conventions disagree on a small but non-empty set of cells near the coast, so the choice has to be made explicitly rather than inherited.

The polygons are unioned by the caller when that is worth doing once for many calls. A point exactly on an edge counts as inside, which sf::st_intersects() gives and a strict containment test does not; on a grid whose points are irrational multiples of the polygon vertices this distinction reaches no cell.

This function needs sf, which is a suggested package and not a dependency, because a field that needs no opaque sheet needs no geometry engine.

Value

A logical matrix of length(lat) rows by length(lon) columns, TRUE where the point falls inside the polygon set.

References

Pebesma, E. (2018). Simple features for R: standardized support for spatial vector data. The R Journal, 10(1), 439-446. doi:10.32614/RJ-2018-009

See Also

vol_field(), which carries the mask, vol_payload(), which writes it into the payload as an image, vol_widget(), whose showLand option draws or hides it.

Examples

if (requireNamespace("sf", quietly = TRUE)) {
  land <- readRDS(system.file("extdata", "med_land.rds", package = "volumr"))
  m <- vol_mask(seq(-6, 36, by = 0.5), seq(30, 46, by = 0.5), land)
  dim(m)
  mean(m)
}

Write the browser payload of a field

Description

Writes the directory the renderer reads: one image per depth level holding the quantised field, the image of the opaque sheet, the colour lookup image, and a manifest recording the grid, the transfer, the display defaults and a SHA-256 of every file written.

Usage

vol_payload(
  field,
  dir,
  transfer = "auto",
  display = NULL,
  step = 1L,
  resample = TRUE,
  dz = NULL,
  created = NULL,
  title = NULL,
  subtitle = NULL,
  axes = NULL,
  geographic = NULL,
  depth_unit = NULL
)

Arguments

field

A vol_field.

dir

Directory to write into. Created when absent.

transfer

Name of the transfer, passed to vol_encode(). The default takes the square root for a non-negative field and the linear ramp for any other.

display

Named list of the defaults the viewer opens with: vmin and vmax, the ends of the colour scale; cmap, a name from vol_colormaps(); gamma; od, the opacity a ray accumulates across the full depth; and ow, how far that opacity follows the intensity. Any element left out takes its default, which is the 1st and 99th percentiles (rounded to integers when they lie ten or more units apart, and to three significant digits otherwise), "matter", a gamma of 1, an opacity of 12, which is the top of the slider, and 0.

step

Horizontal decimation. 1 keeps the native grid.

resample

Logical. Put the depth axis on a uniform grid first, when it is not already uniform.

dz

Spacing of that grid, passed to vol_resample().

created

Timestamp written into the manifest. Defaults to the current time in UTC. Pin it to make two builds of one field give one set of bytes.

title

Heading the viewer shows. Defaults to the name of the field.

subtitle

Line under the heading. Defaults to the name of the field and the depth span.

axes

Named list with x, y and z, the axis titles. Defaults to longitude, latitude and depth.

geographic

Logical. When TRUE, tick labels carry the compass letters; when FALSE, they are plain numbers. Taken from the field when left NULL.

depth_unit

Unit of the vertical axis, used in the readouts. Defaults to metres for a geographic field and to none for any other.

Details

Write the browser payload of a field

Every level is written as an 8-bit greyscale PNG, because a browser decodes PNG natively, the format is lossless, and one image per level lets the loader build a three-dimensional texture without any custom container. The whole cube of the case study at its native grid, 1016 by 380 by 21, travels in about 1.5 MB this way (vol_example_payload()).

The horizontal grid is not reduced by default, and step exists for the cases where it must be. A block mean to half the resolution already costs an error comparable with the width of a plotted colour band, whereas the transfer into 8 bits costs a small fraction of one; spending the bits on the vertical and on the value range rather than on the horizontal grid is what keeps the payload both small and faithful.

The manifest records the SHA-256 of every file it names, and carries through the digests of the arrays the field came from when the field carries them, so a rendering can be traced back to its inputs.

Value

An object of class vol_payload: a list with dir, manifest, files, encoding and field.

See Also

vol_field() for the input, vol_encode() for the transfer, vol_standalone() to carry the payload inside one HTML file, vol_widget() to render it in shiny or R Markdown, print.vol_payload(), summary.vol_payload() and plot.vol_payload() for the methods.

Examples

data(med_mhw)
p <- vol_payload(med_mhw, tempfile("payload"))
p
summary(p)
plot(p)
plot(p, type = "level", depth = 50)
vol_standalone(p, path = tempfile(fileext = ".html"))

Read a field from a NetCDF file

Description

Reads one variable of a NetCDF file into a vol_field(), guessing the longitude, latitude and depth axes from their names when they are not given.

Usage

vol_read_netcdf(
  path,
  varid = NULL,
  lon = NULL,
  lat = NULL,
  depth = NULL,
  time = 1L
)

Arguments

path

Path to a NetCDF file.

varid

Name of the variable to read. Defaults to the first variable that carries three dimensions.

lon, lat, depth

Names of the coordinate variables. Each defaults to the first dimension name that matches the usual spellings.

time

Index along the time axis, when the variable carries one.

Details

Read a field from a NetCDF file

The reader is deliberately narrow. It takes a variable on a regular longitude, latitude and depth grid, with at most one further axis, which it subsets at time; a variable with two or more further axes is refused. The axes may be stored in any order. The reader puts them into the depth, latitude, longitude order that vol_field() fixes, reverses any axis that is stored decreasing, and turns the fill value into NA.

A file whose vertical axis is positive upward, which the positive attribute states, has its depths negated and its levels reversed, so the field that comes back is positive downward as the rest of the package expects.

This function needs ncdf4, which is a suggested package.

Value

A vol_field.

References

Rew, R., & Davis, G. (1990). NetCDF: an interface for scientific data access. IEEE Computer Graphics and Applications, 10(4), 76-82. doi:10.1109/38.56302

See Also

vol_read_npy() for the other format, vol_field() for the object this returns, vol_resample() and vol_payload() for the steps that follow.

Examples

if (requireNamespace("ncdf4", quietly = TRUE)) {
  path <- tempfile(fileext = ".nc")
  dims <- list(ncdf4::ncdim_def("lon", "degrees_east", seq(10, 12, by = 0.5)),
               ncdf4::ncdim_def("lat", "degrees_north", c(40, 40.5, 41)),
               ncdf4::ncdim_def("depth", "m", c(0, 10, 20, 30)),
               ncdf4::ncdim_def("time", "days", 1:2))
  var <- ncdf4::ncvar_def("thetao", "degC", dims, -999)
  nc <- ncdf4::nc_create(path, var)
  ncdf4::ncvar_put(nc, var, array(seq_len(5 * 3 * 4 * 2), c(5, 3, 4, 2)))
  ncdf4::nc_close(nc)
  f <- vol_read_netcdf(path, varid = "thetao", time = 2)
  f
  summary(f)
}

Read a NumPy array file

Description

Reads a .npy file into an R array, without calling Python. The format is a short ASCII header followed by the raw buffer, so no package is needed to parse it.

Usage

vol_read_npy(path)

Arguments

path

Path to a .npy file.

Details

Read a NumPy array file

The reader covers the little-endian and big-endian floating-point types f4 and f8, the signed integer types i1, i2, i4 and i8, the unsigned integer types u1, u2 and u4, and the boolean type b1. An unsigned u4 file returns doubles, since its values may pass the largest R integer; any other type is refused. C order is the default that NumPy writes and is transposed on the way in, so dim() of the result matches the shape field of the header. A Fortran-ordered file is refused rather than read wrongly.

Values are carried across exactly. A f4 file widens to double with no loss, since every single-precision number is a double-precision number.

Value

An array of the shape the header states, of type double for a floating-point file, integer for an integer file and logical for a boolean file. A one-dimensional file returns a bare vector.

References

van der Walt, S., Colbert, S. C., & Varoquaux, G. (2011). The NumPy array: a structure for efficient numerical computation. Computing in Science & Engineering, 13(2), 22-30. doi:10.1109/MCSE.2011.37

See Also

vol_field() to wrap arrays as a field, vol_read_netcdf() for the other format the reader accepts, vol_payload() to build the browser payload from a field.

Examples

a <- vol_read_npy(system.file("extdata", "example.npy", package = "volumr"))
dim(a)
a

Resample a field onto a uniform depth grid

Description

Interpolates the field linearly onto depths spaced evenly from the shallowest measured depth, which is what the browser payload needs, because the GPU samples a three-dimensional texture on a regular grid.

Usage

vol_resample(field, dz = NULL, zmax = NULL, check = TRUE)

Arguments

field

A vol_field.

dz

Spacing of the target grid, in metres. Defaults to the largest spacing that reproduces every measured depth exactly, when one exists, and otherwise to the smallest spacing of the input.

zmax

Deepest level of the target grid, no shallower than the first measured depth. Defaults to the deepest level of the input.

check

Logical. When TRUE, stop if a measured depth is absent from the target grid, so that no measured level is silently smoothed away.

Details

Resample a field onto a uniform depth grid

The interpolation is

v(z) = \frac{v_{hi} - v_{lo}}{z_{hi} - z_{lo}}\,(z - z_{lo}) + v_{lo},

with z_{lo} and z_{hi} the measured depths that bracket z, so an interpolated level holds no value where either of the two measured levels around it holds none. A target depth that coincides with a measured depth, to within 10^{-9}, takes that measured level unchanged, so a cell keeps its value at a measured depth whatever its neighbours hold; at the first level this keeps the cells of a column that ends above the second measured depth.

The default dz is chosen so that measured levels survive. For the case study the fifteen measured depths are 0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100, 125, 150, 175, 200 and 225 and 250 m, every one of them a multiple of 12.5 m, so a grid of 12.5 m reproduces all fifteen exactly and interpolates only the six levels that lie between 100 and 250 m.

The target grid starts at the shallowest measured depth, so the interpolation never reaches outside the measured column. Resampling a field that is already uniform at the requested spacing is a copy, not a smoothing pass, and a field with a single level is returned unchanged.

Value

A vol_field on the uniform grid, with the other elements carried over unchanged.

See Also

vol_field() for the object, vol_encode() for the step that follows, vol_payload(), which calls this when the depth axis is not already uniform, plot.vol_field() to see the profile before and after.

Examples

data(med_mhw)
med_mhw$depth
u <- vol_resample(med_mhw)
u$depth
summary(u)$grid

Change a running widget

Description

Sends settings to a widget that is already on screen, without rebuilding it.

Usage

vol_set(id, options, session = shiny::getDefaultReactiveDomain())

Arguments

id

Output identifier of the widget.

options

Named list of viewer settings; see vol_widget() for the keys.

session

The shiny session.

Details

Change a running widget

Rendering the widget again would rebuild the whole page and reload the payload, which for a slider that a reader is dragging is the wrong trade. This sends the settings alone, so the state of the camera and of the loaded textures survives.

Value

NULL, invisibly. Called for its effect.

See Also

vol_widget() for the widget and the keys it takes, render_vol_widget(), vol_snapshot(), shinyVolumr().

Examples

# Inside the server function of a shiny application; see render_vol_widget()
# for a complete one.
if (interactive() && requireNamespace("shiny", quietly = TRUE)) {
  server <- function(input, output, session) {
    output$volume <- render_vol_widget(vol_widget(vol_example_payload()))
    shiny::observe(vol_set("volume", list(slab = input$slab,
                                          slabZ = input$depth)))
  }
}

Save the current view as a PNG

Description

Asks the browser for the pixels it already holds and hands them to the reader as a download.

Usage

vol_snapshot(
  id,
  filename = "volume.png",
  session = shiny::getDefaultReactiveDomain()
)

Arguments

id

Output identifier of the widget.

filename

Name the file is offered under.

session

The shiny session.

Details

Save the current view as a PNG

The canvas holds the frame, so the image is produced in the browser and never crosses the websocket. What the file carries is the render alone: the axis labels, the tick text and the colour bar are drawn over the canvas as HTML and do not reach it.

Value

NULL, invisibly. Called for its effect.

See Also

vol_widget(), render_vol_widget(), shinyVolumr().

Examples

# Inside the server function of a shiny application; see render_vol_widget()
# for a complete one.
if (interactive() && requireNamespace("shiny", quietly = TRUE)) {
  server <- function(input, output, session) {
    output$volume <- render_vol_widget(vol_widget(vol_example_payload()))
    shiny::observeEvent(input$save, vol_snapshot("volume", "volume.png"))
  }
}

Carry a payload inside one HTML file

Description

Inlines a payload into the viewer page, so that the result opens from a local file with no server and travels as a single attachment.

Usage

vol_standalone(payload, path = NULL, viewer = NULL, manifest = NULL)

Arguments

payload

A vol_payload, or the path of a payload directory.

path

Destination file. Defaults to a file named after the template, volume_viewer_standalone.html, in the session's temporary directory.

viewer

The page template to inline into. Defaults to the copy the package ships.

manifest

The manifest to embed. Taken from payload when it is a vol_payload.

Details

Carry a payload inside one HTML file

A page served over http fetches its images. The same page opened from disk cannot, because a browser refuses a cross-origin read from a local file, so this build carries every image as a data URI instead, at the cost of the third that base64 adds. For the case study at its native grid the directory is 1.5 MB and the single file 2.07 MB.

The splice works on bytes and not on lines, so the accented characters of the page and its line endings pass through untouched, and the block goes in immediately before the script that reads it.

Value

The path written, invisibly.

See Also

vol_payload() for the payload, vol_widget() for the same renderer inside shiny, shinyVolumr() for the application that drives the whole workflow.

Examples

out <- vol_standalone(vol_example_payload(),
                      path = file.path(tempdir(), "med.html"))
file.size(out)
if (interactive()) utils::browseURL(out)

Path of the viewer template the package ships

Description

Gives the path of the HTML page that vol_standalone() inlines a payload into, so that a caller can copy it, edit it and pass the edited copy back.

Usage

vol_viewer_template()

Details

Path of the viewer template the package ships

The template is the viewer with no data in it: the stylesheet, the control panel and the renderer, and nothing else. Served over http it fetches a payload directory beside it; opened from a file it says why it cannot and what to do instead.

Value

A path.

See Also

vol_standalone(), which inlines a payload into this file, vol_payload(), which writes the payload it reads, vol_widget() for the renderer without the page around it.

Examples

vol_viewer_template()

Render a payload as a widget

Description

Puts the viewer in an R Markdown document, a shiny application or the RStudio viewer, driving the same page that vol_standalone() writes.

Usage

vol_widget(
  payload,
  options = list(),
  panel = TRUE,
  width = NULL,
  height = NULL,
  elementId = NULL,
  inputId = NULL
)

Arguments

payload

A vol_payload, or the path of a payload directory.

options

Named list of viewer settings applied once the page has loaded. Any state key the page carries is reachable; see Details.

panel

Logical. Draw the control panel of the page, which is the default and is what shinyVolumr() shows, or hide it and leave the controls to the host, which is what a figure in a document wants.

width, height

Widget size, passed to htmlwidgets.

elementId

Optional element identifier.

inputId

Identifier under which the widget reports back to shiny. Set it to the output identifier when the widget is rendered with render_vol_widget(), so that the events below reach the server.

Details

Render a payload as a widget

The widget hosts the viewer in a frame of its own and talks to it with messages, so there is one renderer behind the file, the widget and the application, and no second copy to keep in step.

The settings options accepts are the ones the panel exposes: the camera as azim, elev, dist, panX and panY; the colour scale as vmin, vmax, gamma and cmapRow; the density as od and ow; the geometry as zex, d0, d1, x0, x1, y0, y1 and ortho; the depth slab as slab, slabT, slabZ and slabNorm; the motions as spin and sweep; the quality as steps and adaptive; and the appearance as light, showLand, showBox and panel.

Inside shiny the widget reports three events through shiny::observeEvent(): ⁠<inputId>_ready⁠ when the payload has loaded, carrying the grid and the depth span; ⁠<inputId>_camera⁠ whenever the camera settles; and ⁠<inputId>_snapshot⁠ when a snapshot has been taken.

Value

An object of class htmlwidget.

See Also

vol_payload() for the payload, vol_widget_output() and render_vol_widget() for the shiny pair, vol_snapshot() to save a PNG from the server, shinyVolumr() for the whole workflow.

Examples

w <- vol_widget(vol_example_payload(),
                options = list(slab = TRUE, slabT = 25, slabZ = 50))
class(w)
if (interactive()) w

Widget output for shiny

Description

Places the viewer in a shiny user interface.

Usage

vol_widget_output(outputId, width = "100%", height = "600px")

Arguments

outputId

Output identifier.

width, height

Size of the element.

Details

Widget output for shiny

The identifier is also the prefix of the inputs the widget writes back, so an application that names its output volume observes input$volume_ready and input$volume_camera.

Value

A shiny output element.

See Also

render_vol_widget() for the server half, vol_widget() for the widget itself, vol_snapshot() to save a PNG, shinyVolumr() for a complete application.

Examples

if (requireNamespace("shiny", quietly = TRUE))
  vol_widget_output("volume", height = "700px")

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.
Health stats visible at Monitor.