| Title: | 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. |
| Authors: | Pablo Almaraz [aut, cre] (ORCID: <https://orcid.org/0000-0003-1416-2695>), Manuel Fernandez-Barba [aut] (ORCID: <https://orcid.org/0000-0001-8953-2481>), DataLab ICMAN [aut] (URL: https://datalab-icman.github.io/) |
| Maintainer: | Pablo Almaraz <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.1.0 |
| Built: | 2026-12-02 21:11:37 UTC |
| Source: | https://github.com/cran/volumr |
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.
med_mhwmed_mhw
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.
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.
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.
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
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.
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"))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"))
Draws the quantisation error against the value it was measured at, and the depth profile of that error.
## S3 method for class 'vol_encoding' plot(x, type = c("value", "depth"), bins = 40L, ...)## S3 method for class 'vol_encoding' plot(x, type = c("value", "depth"), bins = 40L, ...)
x |
A |
type |
One of |
bins |
Number of value bins. |
... |
Ignored. |
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.
A ggplot object, returned invisibly.
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.
data(med_mhw) e <- vol_encode(vol_resample(med_mhw)) plot(e) plot(e, type = "depth")data(med_mhw) e <- vol_encode(vol_resample(med_mhw)) plot(e) plot(e, type = "depth")
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.
## S3 method for class 'vol_field' plot( x, type = c("level", "profile", "coverage"), depth = NULL, cmap = "matter", limits = NULL, ... )## S3 method for class 'vol_field' plot( x, type = c("level", "profile", "coverage"), depth = NULL, cmap = "matter", limits = NULL, ... )
x |
A |
type |
One of |
depth |
Depth in metres for |
cmap |
Name of a colour table, from |
limits |
Numeric pair, the ends of the colour scale. Defaults to the 1st and 99th percentiles of the level. |
... |
Ignored. |
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.
A ggplot object, returned invisibly.
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.
data(med_mhw) plot(med_mhw) plot(med_mhw, depth = 50, cmap = "thermal") plot(med_mhw, type = "profile") plot(med_mhw, type = "coverage")data(med_mhw) plot(med_mhw) plot(med_mhw, depth = 50, cmap = "thermal") plot(med_mhw, type = "profile") plot(med_mhw, type = "coverage")
Draws where the bytes of the payload go, level by level, against how much of each level carries a value.
## S3 method for class 'vol_payload' plot(x, type = c("size", "level"), depth = NULL, ...)## S3 method for class 'vol_payload' plot(x, type = c("size", "level"), depth = NULL, ...)
x |
A |
type |
One of |
depth |
Depth for |
... |
Passed to |
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.
A ggplot object, returned invisibly.
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.
data(med_mhw) p <- vol_payload(med_mhw, tempfile("payload")) plot(p) plot(p, type = "level", depth = 50)data(med_mhw) p <- vol_payload(med_mhw, tempfile("payload")) plot(p) plot(p, type = "level", depth = 50)
Reports the transfer, the range it covers and the error it costs, which is the number that decides whether 8 bits are enough.
## S3 method for class 'vol_encoding' print(x, ...)## S3 method for class 'vol_encoding' print(x, ...)
x |
A |
... |
Ignored. |
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.
x, invisibly.
vol_encode() for the constructor, summary.vol_encoding() for the
error by decile, plot.vol_encoding() for the same as a figure.
data(med_mhw) vol_encode(vol_resample(med_mhw))data(med_mhw) vol_encode(vol_resample(med_mhw))
Reports the grid, the span of each axis, the range of the values and the fraction of cells that carry one, in one screen.
## S3 method for class 'vol_field' print(x, ...)## S3 method for class 'vol_field' print(x, ...)
x |
A |
... |
Ignored. |
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.
x, invisibly.
vol_field() for the constructor, summary.vol_field() for the
numbers level by level, plot.vol_field() for the views.
data(med_mhw) med_mhwdata(med_mhw) med_mhw
Reports where the payload was written, the grid it covers, the transfer it used, its size and the settings the viewer will open with.
## S3 method for class 'vol_payload' print(x, ...)## S3 method for class 'vol_payload' print(x, ...)
x |
A |
... |
Ignored. |
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.
x, invisibly.
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.
data(med_mhw) vol_payload(med_mhw, tempfile("payload"))data(med_mhw) vol_payload(med_mhw, tempfile("payload"))
The server half of the shiny pair.
render_vol_widget(expr, env = parent.frame(), quoted = FALSE)render_vol_widget(expr, env = parent.frame(), quoted = FALSE)
expr |
An expression returning a |
env |
Environment in which to evaluate |
quoted |
Is |
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.
A shiny render function.
vol_widget_output() for the user-interface half, vol_widget(),
vol_snapshot(), shinyVolumr().
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) }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) }
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.
shinyVolumr( field = NULL, payload = NULL, tab = "home", launch.browser = TRUE, ... )shinyVolumr( field = NULL, payload = NULL, tab = "home", launch.browser = TRUE, ... )
field |
A |
payload |
A payload the volume tab opens on, as a |
tab |
Identifier of the tab to open on, one of |
launch.browser |
Passed to |
... |
Further arguments for |
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.
Called for its effect. Returns the value of shiny::runApp().
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.
if (interactive()) { shinyVolumr() shinyVolumr(tab = "volume") }if (interactive()) { shinyVolumr() shinyVolumr(tab = "volume") }
Reports where in the range of the field the quantisation error falls, which a single root mean square figure hides.
## S3 method for class 'vol_encoding' summary(object, bins = 10L, ...)## S3 method for class 'vol_encoding' summary(object, bins = 10L, ...)
object |
A |
bins |
Number of value bins the error is summarised over. |
... |
Ignored. |
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.
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.
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.
data(med_mhw) summary(vol_encode(vol_resample(med_mhw)))data(med_mhw) summary(vol_encode(vol_resample(med_mhw)))
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.
## S3 method for class 'vol_field' summary(object, ...)## S3 method for class 'vol_field' summary(object, ...)
object |
A |
... |
Ignored. |
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.
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.
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.
data(med_mhw) s <- summary(med_mhw) s head(s$levels)data(med_mhw) s <- summary(med_mhw) s head(s$levels)
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.
## S3 method for class 'vol_payload' summary(object, ...)## S3 method for class 'vol_payload' summary(object, ...)
object |
A |
... |
Ignored. |
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.
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.
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.
data(med_mhw) summary(vol_payload(med_mhw, tempfile("payload")))data(med_mhw) summary(vol_payload(med_mhw, tempfile("payload")))
Names the perceptually uniform colour tables that the payload writes into its lookup image and that the viewer offers in its menu.
vol_colormaps()vol_colormaps()
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.
A character vector of table names, in the order the viewer lists them.
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
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.
vol_colormaps()vol_colormaps()
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.
vol_encode(field, transfer = c("auto", "sqrt", "linear"))vol_encode(field, transfer = c("auto", "sqrt", "linear"))
field |
A |
transfer |
Name of the transfer: |
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
the value, and its extremes and the codes available, the square-root transfer writes
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.
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.
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.
data(med_mhw) e <- vol_encode(vol_resample(med_mhw)) e summary(e) plot(e) plot(e, type = "depth")data(med_mhw) e <- vol_encode(vol_resample(med_mhw)) e summary(e) plot(e) plot(e, type = "depth")
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.
vol_example_payload()vol_example_payload()
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.
A path to a payload directory, suitable for vol_standalone() and
vol_widget().
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.
dir <- vol_example_payload() list.files(dir) out <- vol_standalone(dir, path = file.path(tempdir(), "med.html")) if (interactive()) utils::browseURL(out)dir <- vol_example_payload() list.files(dir) out <- vol_standalone(dir, path = file.path(tempdir(), "med.html")) if (interactive()) utils::browseURL(out)
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.
vol_field( values, lon, lat, depth, name = "value", unit = "", mask = NULL, source = NULL, geographic = TRUE )vol_field( values, lon, lat, depth, name = "value", unit = "", mask = NULL, source = NULL, geographic = TRUE )
values |
Numeric array of dimension |
lon |
Numeric vector of |
lat |
Numeric vector of |
depth |
Numeric vector of |
name |
Short name of the quantity, used in labels. |
unit |
Unit of the quantity, used in labels. |
mask |
Optional logical matrix of dimension |
source |
Optional named list of provenance strings, carried into the payload manifest. |
geographic |
Logical. |
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.
An object of class vol_field: a list with the elements values,
lon, lat, depth, name, unit, mask, source and geographic.
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.
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")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")
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.
vol_field_from_df( data, value = NULL, x = NULL, y = NULL, z = NULL, time = NULL, at = NULL, name = NULL, unit = "", flip_z = NA )vol_field_from_df( data, value = NULL, x = NULL, y = NULL, z = NULL, time = NULL, at = NULL, name = NULL, unit = "", flip_z = NA )
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 |
name, unit
|
Passed to |
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 |
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.
A vol_field.
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.
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)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)
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.
vol_mask(lon, lat, polygons, planar = TRUE)vol_mask(lon, lat, polygons, planar = TRUE)
lon |
Numeric vector of longitudes. |
lat |
Numeric vector of latitudes. |
polygons |
An |
planar |
Logical. When |
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.
A logical matrix of length(lat) rows by length(lon) columns,
TRUE where the point falls inside the polygon set.
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
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.
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) }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) }
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.
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 )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 )
field |
A |
dir |
Directory to write into. Created when absent. |
transfer |
Name of the transfer, passed to |
display |
Named list of the defaults the viewer opens with: |
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 |
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 |
geographic |
Logical. When |
depth_unit |
Unit of the vertical axis, used in the readouts. Defaults to metres for a geographic field and to none for any other. |
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.
An object of class vol_payload: a list with dir, manifest,
files, encoding and field.
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.
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"))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"))
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.
vol_read_netcdf( path, varid = NULL, lon = NULL, lat = NULL, depth = NULL, time = 1L )vol_read_netcdf( path, varid = NULL, lon = NULL, lat = NULL, depth = NULL, time = 1L )
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. |
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.
A vol_field.
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
vol_read_npy() for the other format, vol_field() for the object
this returns, vol_resample() and vol_payload() for the steps that
follow.
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) }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) }
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.
vol_read_npy(path)vol_read_npy(path)
path |
Path to a |
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.
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.
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
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.
a <- vol_read_npy(system.file("extdata", "example.npy", package = "volumr")) dim(a) aa <- vol_read_npy(system.file("extdata", "example.npy", package = "volumr")) dim(a) a
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.
vol_resample(field, dz = NULL, zmax = NULL, check = TRUE)vol_resample(field, dz = NULL, zmax = NULL, check = TRUE)
field |
A |
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 |
Resample a field onto a uniform depth grid
The interpolation is
with and the measured depths that bracket
, 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 , 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.
A vol_field on the uniform grid, with the other elements carried
over unchanged.
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.
data(med_mhw) med_mhw$depth u <- vol_resample(med_mhw) u$depth summary(u)$griddata(med_mhw) med_mhw$depth u <- vol_resample(med_mhw) u$depth summary(u)$grid
Sends settings to a widget that is already on screen, without rebuilding it.
vol_set(id, options, session = shiny::getDefaultReactiveDomain())vol_set(id, options, session = shiny::getDefaultReactiveDomain())
id |
Output identifier of the widget. |
options |
Named list of viewer settings; see |
session |
The shiny session. |
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.
NULL, invisibly. Called for its effect.
vol_widget() for the widget and the keys it takes,
render_vol_widget(), vol_snapshot(), shinyVolumr().
# 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))) } }# 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))) } }
Asks the browser for the pixels it already holds and hands them to the reader as a download.
vol_snapshot( id, filename = "volume.png", session = shiny::getDefaultReactiveDomain() )vol_snapshot( id, filename = "volume.png", session = shiny::getDefaultReactiveDomain() )
id |
Output identifier of the widget. |
filename |
Name the file is offered under. |
session |
The shiny session. |
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.
NULL, invisibly. Called for its effect.
vol_widget(), render_vol_widget(), shinyVolumr().
# 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")) } }# 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")) } }
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.
vol_standalone(payload, path = NULL, viewer = NULL, manifest = NULL)vol_standalone(payload, path = NULL, viewer = NULL, manifest = NULL)
payload |
A |
path |
Destination file. Defaults to a file named after the template,
|
viewer |
The page template to inline into. Defaults to the copy the package ships. |
manifest |
The manifest to embed. Taken from |
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.
The path written, invisibly.
vol_payload() for the payload, vol_widget() for the same
renderer inside shiny, shinyVolumr() for the application that
drives the whole workflow.
out <- vol_standalone(vol_example_payload(), path = file.path(tempdir(), "med.html")) file.size(out) if (interactive()) utils::browseURL(out)out <- vol_standalone(vol_example_payload(), path = file.path(tempdir(), "med.html")) file.size(out) if (interactive()) utils::browseURL(out)
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.
vol_viewer_template()vol_viewer_template()
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.
A path.
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.
vol_viewer_template()vol_viewer_template()
Puts the viewer in an R Markdown document, a shiny
application or the RStudio viewer, driving the same page that
vol_standalone() writes.
vol_widget( payload, options = list(), panel = TRUE, width = NULL, height = NULL, elementId = NULL, inputId = NULL )vol_widget( payload, options = list(), panel = TRUE, width = NULL, height = NULL, elementId = NULL, inputId = NULL )
payload |
A |
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 |
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 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.
An object of class htmlwidget.
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.
w <- vol_widget(vol_example_payload(), options = list(slab = TRUE, slabT = 25, slabZ = 50)) class(w) if (interactive()) ww <- vol_widget(vol_example_payload(), options = list(slab = TRUE, slabT = 25, slabZ = 50)) class(w) if (interactive()) w
Places the viewer in a shiny user interface.
vol_widget_output(outputId, width = "100%", height = "600px")vol_widget_output(outputId, width = "100%", height = "600px")
outputId |
Output identifier. |
width, height
|
Size of the element. |
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.
A shiny output element.
render_vol_widget() for the server half, vol_widget() for the
widget itself, vol_snapshot() to save a PNG, shinyVolumr() for a
complete application.
if (requireNamespace("shiny", quietly = TRUE)) vol_widget_output("volume", height = "700px")if (requireNamespace("shiny", quietly = TRUE)) vol_widget_output("volume", height = "700px")