4  Creating an EBVCube with the ebvcube R package

In this unit

By the end you will be able to:

  • create an empty EBVCube netCDF from a metadata JSON with ebv_create();
  • populate its data cubes with raster data using ebv_add_data();
  • verify that data written to an EBVCube match the source values;
  • use ebv_attribute() to correct metadata when necessary; and
  • create a species-level EBVCube with ebv_create_taxonomy() when taxonomic information is required.

This unit covers the core creation workflow: turning prepared data and metadata into an EBVCube. We use published dataset id = 30 as a controlled example. The source netCDF and its matching metadata JSON are downloaded, and part of the dataset is then reconstructed in a new file.

The workflow follows a simple round trip: read a data slice from the published EBVCube, write the same values into a newly created EBVCube, and compare the result with the source. This lets you practise the complete creation workflow without needing your own raster data.

STEP 1
ebv_create() Creates an empty EBVCube whose structure is defined by the metadata JSON.

STEP 2
ebv_add_data() Writes raster values to a selected scenario, metric, entity, and time step.

STEP 3
ebv_analyse() Summarises the source and reconstructed data so their values can be checked.

STEP 4
Optional extensions

Rebuild every cube, correct metadata, or add a species taxonomy.

What we are rebuilding. Dataset id = 30 contains three entities (All birds, Forest birds, and Non-forest birds), three metrics, three SSP-RCP scenarios, and three time steps (1900, 2015, and 2050).

Each scenario–metric combination is stored as a separate data cube, giving nine data cubes in total, from scenario_1/metric_1/ebv_cube to scenario_3/metric_3/ebv_cube. metric_1 represents species richness.

In this unit, you create the full nine-cube structure but populate only one cube with real data. The same procedure can then be repeated for the remaining cubes.

4.1 Prepare the inputs

The creation workflow requires two main inputs. For this example, both are obtained from the published dataset so that the unit remains self-contained:

A metadata JSON Describes the dataset, its attributes, metrics, and scenarios. It can be downloaded from the EBV Data Portal or created in R with ebv_metadata().

Data values The spatial values used to populate the data cubes. Here, they are read directly from the published EBVCube.

The example uses one temporary working folder, so that all files are stored in one place and no step depends on your current working directory. The folder is removed when the R session ends. To keep the files, replace tempdir() with a folder in your project.

# Load ebvcube library
library(ebvcube)

# Keep all files for this example together.
work_dir <- file.path(tempdir(), "ebvcube_id30")
dir.create(work_dir, recursive = TRUE, showWarnings = FALSE)

# Download the published source file and define the file we will create.
source_id <- 30L
orig <- ebv_download(id = source_id, outputdir = work_dir, overwrite = FALSE)
new_nc <- file.path(work_dir, "ebvcube_id30_single_cube.nc")

# ebv_download() saves the matching JSON beside the netCDF file.
json <- sub("\\.nc$", "_metadata.json", orig)
stopifnot(file.exists(orig), file.exists(json))

# Read the real structure from the published file so the rebuild lines up.
source_properties <- ebv_properties(orig, verbose = FALSE)
entities <- source_properties@general$entity_names
entities
#> [1] "All birds"  "Forest birds"  "Non-forest birds"

The metadata JSON corresponds to the file generated through Download metadata in the EBV Data Portal. Deriving its path from orig avoids relying on a specific versioned filename.

For your own dataset, create and download the JSON through the portal or generate it in R with ebv_metadata(), as described in Chapter 3.

4.2 Create the empty netCDF with ebv_create()

ebv_create() reads the metadata JSON and creates the netCDF structure before any data values are added. You provide the entity names, coordinate reference system, spatial extent, resolution, time steps, and fill value.

For dataset id = 30, the entities are taken directly from the published file so that the reconstructed structure matches the source. The example uses a global 1° grid in EPSG:4326.

The timesteps argument requires particular attention. Dataset id = 30 does not contain a regular annual time series, but three specific years. These are therefore supplied explicitly:

# Create EBVCube with full structure 
ebv_create(
  jsonpath   = json,
  outputpath = new_nc,
  entities   = entities,
  epsg       = 4326,
  extent     = c(-180, 180, -90, 90),
  resolution = c(1, 1),
  timesteps  = c("1900", "2015", "2050"),
  fillvalue  = -3.4e+38,
  overwrite  = TRUE,
  verbose    = FALSE
)

stopifnot(file.exists(new_nc))

At this stage, the EBVCube structure has been created, but no biodiversity data have been added: the data cubes still contain only the fill value. Inspect the file before continuing:

ebv_properties(new_nc, verbose = FALSE)@general$entity_names

ebv_datacubepaths(new_nc, verbose = FALSE)

The entity names should match the values supplied to ebv_create(). Because the metadata JSON defines three scenarios and three metrics, ebv_datacubepaths() should return nine data-cube paths.

If only three paths are returned and they contain no scenario level, check that the scenario information is present in the metadata JSON before continuing. The expected structure was introduced in Chapter 3.

4.3 Populate a data cube with ebv_add_data()

Now populate one of the nine data cubes. When scenarios are present, ebv_add_data() uses the scenario, metric, entity, and timestep arguments to determine where the supplied values are written.

For this example, the values come from the published EBVCube itself. We read species richness for Forest birds (entity = 2) under scenario 1 for all three time steps, then write those values to the corresponding cube in the newly created file. type = "a" returns the values as an array suitable for this workflow.

# Define the source slice once and reuse the identifiers in later checks.
source_cube <- "scenario_1/metric_1/ebv_cube"
source_entity <- 2L
source_timesteps <- 1:3  # Positions of 1900, 2015, and 2050 in this file.

# Read one cube from the published dataset.
slice <- ebv_read(orig, source_cube, entity = source_entity,
                  timestep = source_timesteps, type = "a", verbose = FALSE)

# Write it into the matching cube of the reconstructed file.
ebv_add_data(
  filepath_nc = new_nc,
  scenario    = 1,
  metric      = 1,
  entity      = source_entity,
  timestep    = source_timesteps,
  data        = slice,
  verbose     = FALSE
)

For your own dataset, data would contain the values produced by your analysis or model. Depending on your workflow, these can be supplied as an array or from a GeoTIFF. When using a multi-band GeoTIFF, use band to specify which raster bands correspond to the selected time steps.

4.4 Verify the reconstructed EBVCube

Before extending the workflow, verify that the values were written correctly. First, use ebv_analyse() to compare simple summaries of the source and reconstructed data:

orig_stats <- ebv_analyse(orig, source_cube, entity = source_entity,
                          verbose = FALSE)
new_stats <- ebv_analyse(new_nc, source_cube, entity = source_entity,
                         verbose = FALSE)

orig_stats[c("mean", "n")]
new_stats[c("mean", "n")]

The mean and number of valid pixels should agree between the two files. This provides a useful summary check, but we can also compare the values directly.

reconstructed_slice <- ebv_read(
  new_nc, source_cube, entity = source_entity,
  timestep = source_timesteps, type = "a", verbose = FALSE
)

isTRUE(all.equal(slice, reconstructed_slice, check.attributes = FALSE))
#> [1] TRUE

A result of TRUE confirms that the values read from the reconstructed cube match the source layers.

The entity identifier must remain consistent throughout the check. We populated Forest birds (entity = 2); the other entities in this cube still contain only fill values.

You can also map one time step as a visual check:

ebv_map(new_nc, source_cube, entity = source_entity, timestep = 3, classes = 5)

To reconstruct the entire published dataset, start from a new empty EBVCube and repeat the same operation for every scenario, metric, and entity.

With three scenarios, three metrics, and three entities, the loop performs 27 writes. Each write supplies all three time steps at once.

# Start from a fresh empty EBVCube for the complete reconstruction.
full_nc <- file.path(work_dir, "ebvcube_id30_full_cubes.nc")
ebv_create(
  jsonpath   = json,
  outputpath = full_nc,
  entities   = entities,
  epsg       = 4326,
  extent     = c(-180, 180, -90, 90),
  resolution = c(1, 1),
  timesteps  = c("1900", "2015", "2050"),
  fillvalue  = -3.4e+38,
  overwrite  = TRUE,
  verbose    = FALSE
)

stopifnot(file.exists(full_nc))

# Fill all nine scenario-metric cubes for all three entities.
for (s in 1:3) {
  for (m in 1:3) {
    for (e in seq_along(entities)) {
      dc <- sprintf("scenario_%d/metric_%d/ebv_cube", s, m)
      ebv_add_data(
        filepath_nc = full_nc,
        scenario    = s, metric = m, entity = e, timestep = 1:3,
        data        = ebv_read(orig, dc, entity = e, timestep = 1:3,
                               type = "a", verbose = FALSE),
        verbose     = FALSE
      )
    }
  }
}

After the loop, use the same verification steps shown above on one or more selected layer, replacing new_nc with full_nc.

Use ebv_attribute() when an existing EBVCube contains a metadata value that needs to be corrected, such as an incorrect unit or description. There is no need to modify dataset id = 30 simply to demonstrate the function, because its published metadata already describe the data.

The following is a reference pattern. Replace each placeholder with the correct file, level, and value for your own dataset:

ebv_attribute(filepath       = "your_file.nc",
              attribute_name = "units",
              value          = "your corrected unit",
              levelpath      = "scenario_1/metric_1",
              verbose        = FALSE)

The levelpath argument specifies where the attribute is stored. For a file with scenarios, for example: - "scenario_1/metric_1" targets the metric level; - "scenario_1/metric_1/ebv_cube" targets the data cube; - "/" targets the global level.

Use ebv_create_taxonomy() when the entities in your dataset are individual species and taxonomic information should be stored with them. This does not apply to dataset id = 30, whose entities represent bird communities.

Unlike ebv_create(), which receives a vector of entity names, ebv_create_taxonomy() uses a CSV table containing the taxonomy of each entity. Each row represents one species, while columns represent taxonomic ranks from higher to lower levels.

order family genus scientificName
Passeriformes Corvidae Corvus Corvus corone
Passeriformes Paridae Parus Parus major

The final column identifies the entities stored in the EBVCube and must correspond to the species represented by the data.

For interoperability, use Darwin Core terms for taxonomic fields, such as order, family, genus, and scientificName. Where available, you can also include an identifier, such as a GBIF usageKey, to link each species to an established taxonomic backbone.

Row order matters

Your taxonomy CSV must contain one row for each entity in the same order that the entities appear in your data. This ensures that each species is linked to the correct layers in the EBVCube.

# Columns run from the highest rank to the lowest. The last column holds the
# entity names. In practice, this table often comes from a GBIF or Catalogue
# of Life export.
taxonomy <- data.frame(
  order          = c("Passeriformes",   "Apodiformes", "Falconiformes"),
  family         = c("Hirundinidae",    "Apodidae",    "Falconidae"),
  genus          = c("Hirundo",         "Apus",        "Falco"),
  scientificName = c("Hirundo rustica", "Apus apus",   "Falco peregrinus")
)
taxonomy_csv <- file.path(work_dir, "taxonomy.csv")
write.csv(taxonomy, taxonomy_csv, row.names = FALSE)

# Use metadata for a species-level dataset, not the JSON from id = 30.
species_json <- "path/to/species_level_metadata.json"
new_nc_tax <- file.path(work_dir, "species_level_ebvcube.nc")

ebv_create_taxonomy(
  jsonpath   = species_json,
  outputpath = new_nc_tax,
  taxonomy   = taxonomy_csv,
  sep        = ",",
  epsg       = 4326,
  extent     = c(-180, 180, -90, 90),
  resolution = c(1, 1),
  timesteps  = c("1900", "2015", "2050"),
  fillvalue  = -3.4e+38,
  overwrite  = TRUE,
  verbose    = FALSE
)

From here, ebv_add_data() works as it did above. The taxonomy is read-only metadata and does not change how you fill the cubes. See ?ebv_create_taxonomy for accepted column names and separator options.

Finally, inspect the reconstructed file once more:

ebv_properties(new_nc, verbose = FALSE)

ebv_datacubepaths(new_nc, verbose = FALSE)

Panoply is a free NASA application for viewing netCDF and HDF5 files. Open the reconstructed .nc file to inspect its group hierarchy, dimensions, and attributes, or to display a selected data cube as a map.

This provides a useful visual inspection of the file before moving on to validation, without requiring additional R code.

Checkpoint. You created an empty EBVCube with ebv_create(), confirmed its nine scenario–metric data cubes, populated one of them with ebv_add_data(), and verified that the written values match the published source.

You now have a populated .nc file ready for the validation and visualisation steps in Chapter 5.