Bundling Mishra and Gopi 2017 to a DwC Archive

This is an R Markdown Notebook for converting the species checklist found in the following reference to DarwinCore format for upload into OBIS as part of UNESCO’s eDNA Expeditions project:

Mishra, Subhrendu & Kc, Gopi. (2017). Fish diversity of Indian Sundarban and its resource and research prospects.

Setup

Call the necessary libraries and variables. Suppresses loading messages.

library(magrittr)                       # To use %<>% pipes
suppressMessages(library(janitor))      # To clean input data
suppressMessages(library(dplyr))        # To clean input data
library(stringr)                        # To clean input data
suppressMessages(library(rgnparser))    # To clean species names
suppressMessages(library(taxize))       # To get WoRMS IDs
library(worrms)                         # To get WoRMS IDs
library(digest)                         # To generate hashes
suppressMessages(library(obistools))    # To generate centroid lat/long and uncertainty
suppressMessages(library(sf))           # To generate wkt polygon
suppressMessages(library(EML))          # To create eml.xml file
library(xml2)                           # To create the meta.xml file
suppressMessages(library(zip))          # To zip DwC file

Input Parameters and Paths

path_to_project_root <- "../../.."
site_dir_name <- "the_sundarbans"
dataset_dir_name <- "Mishra_2017"
original_pdf <- "09.FISHDIVERSITYOFINDIANSUNDARBAN.pdf"
short_name <- "indian-sundarbans-mishra-2017"

Parsing PDF table to CSV

The data for this reference is formatted as an image-based table inside a PDF across multiple sheets. First, we use pdf_to_table to OCR and parse out the table to a CSV.

#conda environment
condaenv <- "mwhs-data-mobilization"

# Path to the Python script
script <- paste(path_to_project_root, "scripts_data/pdf_to_tables/pdf_to_table.py", sep="/")

# Input PDF file path
input_pdf <- paste(path_to_project_root, "datasets", site_dir_name, dataset_dir_name, "raw", original_pdf, sep="/")

# Output directory for OCR/table files
output_dir <- paste(path_to_project_root, "datasets", site_dir_name, dataset_dir_name, "processed", sep="/")

# Define page numbers and table areas (see documentation)
page_args <- c(
  "-a 74.813,506.813,638.438,741.938 -p 13",
  "-a 48.938,505.688,636.188,731.813 -p 14",
  "-a 50.063,75.938,631.688,304.313 -p 14",
  "-a 54.563,503.438,632.813,730.688 -p 15",
  "-a 48.938,79.313,638.438,304.313 -p 16",
  "-a 52.313,504.563,632.813,732.938 -p 16",
  "-a 45.563,505.688,635.063,731.813 -p 17",
  "-a 46.688,506.813,637.313,732.938 -p 18",
  "-a 54.563,75.938,630.563,302.063 -p 18",
  "-a 55.688,504.563,631.688,732.938 -p 19",
  "-a 48.938,78.188,638.438,303.188 -p 20",
  "-a 51.188,503.438,632.813,731.813 -p 20",
  "-a 47.813,506.813,637.313,731.813 -p 21",
  "-a 47.813,506.813,637.313,731.813 -p 22"
)

# Define run parameters (see documentation)
run_parameters <- "-l -c -ocr -# 8"

# Combine page arguments and execute
page_args_combined <- paste(page_args, collapse = " ")
command <- paste("conda run -n", condaenv, "python", script, "-i", input_pdf, run_parameters, page_args_combined, "-o", output_dir)
system(command, intern=TRUE)
##  [1] ""                                                                                                                                 
##  [2] "Script Execution Summary"                                                                                                         
##  [3] "Date and Time: 2023-09-12 13:43:38"                                                                                               
##  [4] "------------------------------"                                                                                                   
##  [5] ""                                                                                                                                 
##  [6] "PDF input: ../../../datasets/the_sundarbans/Mishra_2017/raw/09.FISHDIVERSITYOFINDIANSUNDARBAN.pdf"                                
##  [7] "Perform OCR: True"                                                                                                                
##  [8] "Number of Cores: 8"                                                                                                               
##  [9] "Perform Table Parsing: TRUE"                                                                                                      
## [10] "Selected Areas:"                                                                                                                  
## [11] "  Area 1: [74.813, 506.813, 638.438, 741.938]"                                                                                    
## [12] "  Area 2: [48.938, 505.688, 636.188, 731.813]"                                                                                    
## [13] "  Area 3: [50.063, 75.938, 631.688, 304.313]"                                                                                     
## [14] "  Area 4: [54.563, 503.438, 632.813, 730.688]"                                                                                    
## [15] "  Area 5: [48.938, 79.313, 638.438, 304.313]"                                                                                     
## [16] "  Area 6: [52.313, 504.563, 632.813, 732.938]"                                                                                    
## [17] "  Area 7: [45.563, 505.688, 635.063, 731.813]"                                                                                    
## [18] "  Area 8: [46.688, 506.813, 637.313, 732.938]"                                                                                    
## [19] "  Area 9: [54.563, 75.938, 630.563, 302.063]"                                                                                     
## [20] "  Area 10: [55.688, 504.563, 631.688, 732.938]"                                                                                   
## [21] "  Area 11: [48.938, 78.188, 638.438, 303.188]"                                                                                    
## [22] "  Area 12: [51.188, 503.438, 632.813, 731.813]"                                                                                   
## [23] "  Area 13: [47.813, 506.813, 637.313, 731.813]"                                                                                   
## [24] "  Area 14: [47.813, 506.813, 637.313, 731.813]"                                                                                   
## [25] "Pages: 13, 14, 14, 15, 16, 16, 17, 18, 18, 19, 20, 20, 21, 22"                                                                    
## [26] "Concatenate: True"                                                                                                                
## [27] "Concatenate across headers: False"                                                                                                
## [28] "Stream Extraction: False"                                                                                                         
## [29] "Lattice Extraction: True"                                                                                                         
## [30] ""                                                                                                                                 
## [31] "OCRing PDF"                                                                                                                       
## [32] "------------------------------"                                                                                                   
## [33] ""                                                                                                                                 
## [34] ""                                                                                                                                 
## [35] "Parsing Tables"                                                                                                                   
## [36] "------------------------------"                                                                                                   
## [37] ""                                                                                                                                 
## [38] ""                                                                                                                                 
## [39] "Saving to CSV"                                                                                                                    
## [40] "CSV file: ../../../datasets/the_sundarbans/Mishra_2017/processed/09.FISHDIVERSITYOFINDIANSUNDARBAN_tables_parsed_concatenated.csv"
## [41] "------------------------------"                                                                                                   
## [42] ""                                                                                                                                 
## [43] ""                                                                                                                                 
## [44] "Run Details: ../../../datasets/the_sundarbans/Mishra_2017/processed/09.FISHDIVERSITYOFINDIANSUNDARBAN_parameters.txt"             
## [45] "Finished"                                                                                                                         
## [46] ""

Read source data

Now we’ll read in the csv table outputted from the previous step

processed_csv <- "09.FISHDIVERSITYOFINDIANSUNDARBAN_tables_parsed_concatenated.csv"

input_data <- read.csv(paste(path_to_project_root, "datasets", site_dir_name, dataset_dir_name, "processed", processed_csv, sep="/"))

#to preview pretty table
knitr::kable(head(input_data))
Species Unnamed..1
CLASS|: CHONDRICHTHYES NA
Sub-Class: ELASMOBRANCHII NA
Order1: ORECTOLOBIFORMES NA
Family1: Hemiscylidae NA
Chiloscyllium griseum Muller& Henle,1838 NA
Family2: Stegostomatidae NA

Preprocessing

Here we tidy the data up, since OCR and table parsing errors are common and only take the list of species, since this is a checklist.

Tidy Data

input_data %<>%
  remove_empty(c("rows", "cols")) %>%       # Remove empty rows and columns
  clean_names()                         # Have sensible (lowercase) column names

# Remove lines with colons
cleaned_data <- input_data %>%              
     filter(!str_detect(species, ":"))

#split elements by ), *, | and years
split_string <- function(input_string) {
  items <- strsplit(input_string, "\\) |\\* |\\|")[[1]]
  items <- unlist(strsplit(items, "\\d{4}", perl = TRUE))
  items <- paste0(items, ")")
  return(items)
}
cleaned_data <- unlist(lapply(cleaned_data[,], split_string))
cleaned_data <- cleaned_data[sapply(cleaned_data, function(x) grepl("[A-Za-z]", x))]

#to preview pretty table
knitr::kable(head(cleaned_data))
x
Chiloscyllium griseum Muller& Henle,)
Stegostoma fasciatum (Herman,)
Carcharhinus hemiodon (Muller & Henle,)
Carcharhinus leucas (Muller & Henle,)
Carcharhinus limbatus (Muller & Henle,)
Carcharhinus melanopterus (Quoy& Gaimard,)

Get WoRMS IDs

Auto matching

First we will try to do this automatically by first cleaning the species names using gnparser and then using the taxise library to call the WoRMS database.

#Parse author names out
parsed_names <- rgnparser::gn_parse(cleaned_data)

#Function to get WoRMS IDs. Search for accepted names first and if not found, search for unaccepted. If still not found, use the worrms package to search.
get_worms_id_from_element <- function(element) {
  worms_id <- get_wormsid(element$canonical$full, searchtype="scientific", fuzzy=TRUE, messages = FALSE, accepted = TRUE)
  if (attr(worms_id, "match") == "not found") {
    worms_id <- get_wormsid(element$canonical$full, searchtype="scientific", messages = FALSE, fuzzy=TRUE)
    if (attr(worms_id, "match") == "not found") {
      worms_id <- NA
    }
  }
  return(worms_id)
}

#Call the function
worms_ids <- lapply(parsed_names, function(element) {
  if (element$parsed) {
    return(get_worms_id_from_element(element))
  } else {
    return(NA)
  }
})

#combine original names, parsed data and WoRMS ID into one data frame
combined_dataframe <- data.frame()

for (i in 1:length(cleaned_data)) {
  cleaned_value <- cleaned_data[i]
  canonical_value <- parsed_names[[i]]$canonical$full
  worms_id_value <- worms_ids[[i]][1]
  if (is.null(canonical_value)){
    canonical_value <- NA
  }
  temp_row <- data.frame(CleanedData = cleaned_value, CanonicalFull = canonical_value, WormsIDs = worms_id_value)
  combined_dataframe <- rbind(combined_dataframe, temp_row)
}

knitr::kable(head(combined_dataframe))
CleanedData CanonicalFull WormsIDs
Chiloscyllium griseum Muller& Henle,) Chiloscyllium griseum 277829
Stegostoma fasciatum (Herman,) Stegostoma fasciatum 220032
Carcharhinus hemiodon (Muller & Henle,) Carcharhinus hemiodon 271322
Carcharhinus leucas (Muller & Henle,) Carcharhinus leucas 105792
Carcharhinus limbatus (Muller & Henle,) Carcharhinus limbatus 105793
Carcharhinus melanopterus (Quoy& Gaimard,) Carcharhinus melanopterus 105795

Human Verification

Sometimes there are misspellings in the original text or incorrect OCR that can be searched for and fixed by hand. To do this, view the combined dataframe, search for unmatched species in WoRMS and add the ID, and remove rows that were not autoremoved in the earlier cleaning steps

combined_dataframe[22,2:3] = c("Gymnothorax tile", 271890)
combined_dataframe[43,2:3] = c("Tenualosa toli", 217454)
combined_dataframe[44,2:3] = c("Ilisha elongata", 281160)
combined_dataframe[45,2:3] = c("Ilisha kampeni", 281163)
combined_dataframe[67,2:3] = c("Anguilla bicolor", 217455)
combined_dataframe[69,2:3] = c("Ilisha megaloptera", 281166)
combined_dataframe[70,2:3] = c("Ilisha melastoma", 281167)
combined_dataframe[71,2:3] = c("Ilisha sirishae", 281170)
combined_dataframe[79,2:3] = c("Setipinna brevifilis", 1021924)
combined_dataframe[81,2:3] = c("Setipinna taty", 282768)
combined_dataframe[82,2:3] = c("Setipinna tenuifilis", 282769)
combined_dataframe[94,2:3] = c("Amblypharyngodon mola", 1012854)
combined_dataframe[95,2:3] = c("Danio rerio", 1026595)
combined_dataframe[98,2:3] = c("Pethia conchonius", 991302)
combined_dataframe[99,2:3] = c("Pethia gelius", 1022796)
combined_dataframe[100,2:3] = c("Pethia phutunio", 1026592)
combined_dataframe[101,2:3] = c("Pethia ticto", 1021907)
combined_dataframe[102,2:3] = c("Puntius chola", 1026489)
combined_dataframe[104,2:3] = c("Puntius terio", 1026600)
combined_dataframe[113,2:3] = c("Mystus tengara", 1022781)
combined_dataframe[115,2:3] = c("Sperata aor", 1022803)
combined_dataframe[117,2:3] = c("Ompok pabda", 1026982)
combined_dataframe[120,2:3] = c('Ailia coila', 279526)
combined_dataframe[124,2:3] = c('Clarias magur', 314146)
combined_dataframe[132,2:3] = c('Hexanematichthys sagor', 281076)
combined_dataframe[177,2:3] = c('Scomberoides tala', 277037)
combined_dataframe[187,2:3] = c('Secutor insidiator', 218464)
combined_dataframe[188,2:3] = c('Secutor ruconius', 218463)
combined_dataframe[210,2:3] = c('Parambassis baculis', 1022774)
combined_dataframe[243,2:3] = c('Macrospinosa cuja', 281484)
combined_dataframe[244,2:3] = c('Nibea coibor', 281749)
combined_dataframe[246,2:3] = c('Otolithoides biauritus', 281949)
combined_dataframe[247,2:3] = c('Otolithoides pama', 281950)
combined_dataframe[255,2:3] = c('Badis badis', 1026697)

#This is Eleotris ophicephalus / Ophiocara porocephala
combined_dataframe[270,2:3] = c('Ophiocara ophicephalus', NA)

combined_dataframe[304,2:3] = c('Scartelaos histophorus', 282671)
combined_dataframe[311,2:3] = c('Kurtus indicus', 281237)
combined_dataframe[324,2:3] = c('Anabas cobojius', 1026433)
combined_dataframe[326,2:3] = c('Trichogaster fasciata', 315877)
combined_dataframe[327,2:3] = c('Trichogaster lalius', 1027008)
combined_dataframe[328,2:3] = c('Trichogaster chuna', 1022769)
combined_dataframe[329,2:3] = c('Channa gachua', 743378)
combined_dataframe[330,2:3] = c('Channa marulius', 1026844)
combined_dataframe[348,2:3] = c('Dichotomyctere fluviatilis', 1013871)
combined_dataframe[128,2:3] = c('Arius jella', 275575)
combined_dataframe[262,2:3] = c('Callionymus sagitta', 219775)
combined_dataframe[196,2:3] = c('Gerres phaiya', 276965)

combined_dataframe <- combined_dataframe[-c(110),]

Darwin Core mapping

Required Terms

OBIS currently has eight required DwC terms: scientificName, scientificNameID, occurrenceID, eventDate, decimalLongitude, decimalLatitude, occurrenceStatus, basisOfRecord.

scientificName/scientificNameID

Create a dataframe with unique taxa only (though this should already be unique). This will be our primary DarwinCore data frame.

#rename and restructure WoRMSIDs to OBIS requirements
occurrence <- combined_dataframe %>%
  distinct(CanonicalFull, WormsIDs) %>%
  rename(scientificName = CanonicalFull) %>%
  rename(scientificNameID = WormsIDs) %>%
  mutate(scientificNameID = ifelse(!is.na(scientificNameID), paste("urn:lsid:marinespecies.org:taxname:", scientificNameID, sep = ""), NA))

occurrenceID

OccurrenceID is an identifier for the occurrence record and should be persistent and globally unique. It is a combination of dataset-shortname:occurrence: and a hash based on the scientific name.

# Vectorize the digest function (The digest() function isn't vectorized. So if you pass in a vector, you get one value for the whole vector rather than a digest for each element of the vector):
vdigest <- Vectorize(digest)

# Generate taxonID:
occurrence %<>% mutate(occurrenceID = paste(short_name, "occurrence", vdigest (scientificName, algo="md5"), sep=":"))

eventDate

This is NULL since this is technically a checklist and we do not know the collection date.

eventDate <- ""
occurrence %<>% mutate(eventDate)

decimalLongitude/decimalLatitude

Use obistools::calculate_centroid to calculate a centroid and radius for WKT strings. This is useful for populating decimalLongitude, decimalLatitude and coordinateUncertaintyInMeters. The WKT strings are from https://github.com/iobis/mwhs-shapes.

if (!file.exists(paste(path_to_project_root, "scripts_data/marine_world_heritage.gpkg", sep="/"))) {
  download.file("https://github.com/iobis/mwhs-shapes/blob/master/output/marine_world_heritage.gpkg?raw=true", paste(path_to_project_root, "scripts_data/marine_world_heritage.gpkg", sep="/"))
}

shapes <- st_read(paste(path_to_project_root, "scripts_data/marine_world_heritage.gpkg", sep="/"))
## Reading layer `marine_world_heritage' from data source 
##   `/mnt/c/Users/Chandra Earl/Desktop/Labs/UNESCO/mwhs-data-mobilization/scripts_data/marine_world_heritage.gpkg' 
##   using driver `GPKG'
## Simple feature collection with 60 features and 4 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -180 ymin: -55.32282 xmax: 180 ymax: 71.81381
## Geodetic CRS:  4326
#For some sites, the GeoPackage has core as well as buffer areas. Merge the geometries by site.
shapes_processed <- shapes %>%
  group_by(name) %>%
  summarize()

#Sundarbans National Park
ind_shape <- shapes_processed$geom[which(shapes_processed$name == "Sundarbans National Park")]


#convert shape to WKT
wkt <- st_as_text(ind_shape, digits = 6)

localities <- calculate_centroid(wkt)

occurrence %<>% mutate(decimalLatitude = localities$decimalLatitude)
occurrence %<>% mutate(decimalLongitude = localities$decimalLongitude)

occurrenceStatus

occurrenceStatus <- "present"
occurrence %<>% mutate(occurrenceStatus)

basisOfRecord

basisOfRecord <- "HumanObservation"
occurrence %<>% mutate(basisOfRecord)

Extra Terms

footprintWKT

occurrence %<>% mutate(footprintWKT = wkt)

coordinateUncertaintyInMeters

occurrence %<>% mutate(coordinateUncertaintyInMeters = localities$coordinateUncertaintyInMeters)

geodeticDatum

geodeticDatum <- "WGS84"
occurrence %<>% mutate(geodeticDatum)

country

country <- "India"
occurrence %<>% mutate(country)

locality

locality <- "Indian Sundarbans"
occurrence %<>% mutate(locality)

Post-processing

Check data

Use the check_fields command from obistools to check if all OBIS required fields are present in an occurrence table and if any values are missing.

#Reorganize columns
occurrence = occurrence %>% select(occurrenceID, scientificName, scientificNameID, eventDate, country, locality, decimalLatitude, decimalLongitude, coordinateUncertaintyInMeters, footprintWKT, geodeticDatum, occurrenceStatus, basisOfRecord)

#Check fields
check_fields(occurrence)
## Warning: `data_frame()` was deprecated in tibble 1.1.0.
## ℹ Please use `tibble()` instead.
## ℹ The deprecated feature was likely used in the obistools package.
##   Please report the issue to the authors.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## # A tibble: 351 × 4
##    level field       row message                                 
##    <chr> <chr>     <int> <chr>                                   
##  1 error eventDate     1 Empty value for required field eventDate
##  2 error eventDate     2 Empty value for required field eventDate
##  3 error eventDate     3 Empty value for required field eventDate
##  4 error eventDate     4 Empty value for required field eventDate
##  5 error eventDate     5 Empty value for required field eventDate
##  6 error eventDate     6 Empty value for required field eventDate
##  7 error eventDate     7 Empty value for required field eventDate
##  8 error eventDate     8 Empty value for required field eventDate
##  9 error eventDate     9 Empty value for required field eventDate
## 10 error eventDate    10 Empty value for required field eventDate
## # ℹ 341 more rows

Create the EML file

This is a file which contains the dataset’s metadata and is required in a DarwinCore-Archive.

emld::eml_version("eml-2.1.1")
## [1] "eml-2.1.1"
#Title
title <- "Fish diversity of Indian Sundarban and its resource and research prospects: Fishes Checklist"

#AlternateIdentifier
alternateIdentifier <- paste("https://ipt.obis.org/secretariat/resource?r=", short_name, sep="")

#Abstract
abstract <- eml$abstract(
  para = "The updated list of fishes of Sundarban gives information of about 350 species belonging to 225 genera, 86 families distributed in 25 orders occurring in this region. Cartilaginous fishes or Elasmobranchs comprise only 10.3% of fishes known, i.e., 36 species belonging to 21 genera, 10 families and 6 orders.The rest, 314 species (89.7%) in 204 genera, 76 families and 19 orders are bony fishes. Among the fishes occurring in Indian Sundarban,
the family Gobiidae is the most diverse group with 40 species, followed by Sciaenidae (18 spp.) and Engraulidae (17 spp.).The highest representation of elasmobranchs is by the gray sharks (Carcharhinidae, 10 spp.), followed by stingrays (Dasyatidae, 9 spp.).")

People

Here we add the people involved in the project:

The creator is the person or organization responsible for creating the resource itself.

The contact is the person or institution to contact with questions about the use, interpretation of a data set.

The metadataProvider is the person responsible for providing the metadata documentation for the resource.

The associatedParty (in this case the Data Curator) is the person who mobilized the data from the original resource.

creator <- list(eml$creator(
    individualName = eml$individualName(
      givenName = "Subhrendu S", 
      surName = "Mishra"),
    organizationName = "Zoological Survey of India"
  ), eml$creator(
    individualName = eml$individualName(
      givenName = "K C", 
      surName = "Gopi"),
    organizationName = "Zoological Survey of India"
  )
)

contact <- eml$creator(
  individualName = eml$individualName(
    givenName = "OBIS", 
    surName = "Secretariat"),
  electronicMailAddress = "helpdesk@obis.org",
  organizationName = "OBIS",
  positionName = "Secretariat"
)

metadataProvider <- eml$metadataProvider(
  individualName = eml$individualName(
    givenName = "Chandra", 
    surName = "Earl"),
  electronicMailAddress = "c.earl@unesco.org",
  organizationName = "UNESCO",
  positionName = "eDNA Scientific Officer"
)

associatedParty <- eml$associatedParty(
  role = "processor",
  individualName = eml$individualName(
    givenName = "Chandra", 
    surName = "Earl"),
  electronicMailAddress = "c.earl@unesco.org",
  organizationName = "UNESCO",
  positionName = "eDNA Scientific Officer"
)

Additional Metadata

Here we add the additionalMetadata element, which is required for a GBIF-type EML file and contains information such as the citation of the dataset, the citation of the original resource and the creation timestamp of the EML.

#{dataset.authors} ({dataset.pubDate}) {dataset.title}. [Version {dataset.version}]. {organization.title}. {dataset.type} Dataset {dataset.doi}, {dataset.url}

additionalMetadata <- eml$additionalMetadata(
  metadata = list(
    gbif = list(
      dateStamp = paste0(format(Sys.time(), "%Y-%m-%dT%H:%M:%OS3"), paste0(substr(format(Sys.time(), "%z"), 1, 3), ":", paste0(substr(format(Sys.time(), "%z"), 4, 5)))),
      hierarchyLevel = "dataset",
      citation = "IPT will autogenerate this",
      bibliography = list(
        citation = "Mishra S & Gopi, KC. (2017). Fish diversity of Indian Sundarban and its resource and research prospects.")
    )
  )
)

citationdoi <- ""

Coverage

Here we describe the dataset’s geographic, taxonomic and temporal coverage.

#Coverage
coverage <- eml$coverage(
  geographicCoverage = eml$geographicCoverage(
    geographicDescription = "Indian Sundarbans",
    boundingCoordinates = eml$boundingCoordinates(
      westBoundingCoordinate = st_bbox(ind_shape)$xmax,
      eastBoundingCoordinate = st_bbox(ind_shape)$xmin,
      northBoundingCoordinate = st_bbox(ind_shape)$ymax,
      southBoundingCoordinate = st_bbox(ind_shape)$ymin)
    ),
  taxonomicCoverage = eml$taxonomicCoverage(
    generalTaxonomicCoverage = "Fishes",
    taxonomicClassification = list(
      eml$taxonomicClassification(
        taxonRankName = "Superclass",
        taxonRankValue = "Agnatha"),
      eml$taxonomicClassification(
        taxonRankName = "unranked",
        taxonRankValue = "Chondrichthyes"),
      eml$taxonomicClassification(
        taxonRankName = "unranked",
        taxonRankValue = "Osteichthyes")
      )
    
#  ),
#  temporalCoverage = eml$temporalCoverage(
#    rangeOfDates = eml$rangeOfDates(
#      beginDate = eml$beginDate(
#        calendarDate = "2019-05-01"
#      ),
#      endDate = eml$endDate(
#        calendarDate = "2016-05-06"
#      )
#    )
   )
)

Extra MetaData

These fields are not required, though they make the metadata more complete.

methods <- eml$methods(
  methodStep = eml$methodStep(
    description = eml$description(
      para = paste("See Github <a href=\"https://github.com/iobis/mwhs-data-mobilization\">Project</a> and <a href=\"https://iobis.github.io/mwhs-data-mobilization/notebooks/", site_dir_name, "/", dataset_dir_name, "\"> R Notebook</a> for dataset construction methods", sep="")
    )
  )
)

pubDate <- "2023-10-15"

#language of original document
language <- "eng"

keywordSet <- eml$keywordSet(
  keyword = "Occurrence",
  keywordThesaurus = "GBIF Dataset Type Vocabulary: http://rs.gbif.org/vocabulary/gbif/dataset_type_2015-07-10.xml"
)

maintenance <- eml$maintenance(
  description = eml$description(
    para = ""),
  maintenanceUpdateFrequency = "notPlanned"
)

#Universal CC
intellectualRights <- eml$intellectualRights(
  para = "To the extent possible under law, the publisher has waived all rights to these data and has dedicated them to the <ulink url=\"http://creativecommons.org/publicdomain/zero/1.0/legalcode\"><citetitle>Public Domain (CC0 1.0)</citetitle></ulink>. Users may copy, modify, distribute and use the work, including for commercial purposes, without restriction."
)

purpose <- eml$purpose(
  para = "These data were made accessible through UNESCO's eDNA Expeditions project to mobilize available marine species and occurrence datasets from World Heritage Sites."
)

additionalInfo <- eml$additionalInfo(
  para = "marine, harvested by iOBIS"
)

Create and Validate EML

#Put it all together
my_eml <- eml$eml(
           packageId = paste("https://ipt.obis.org/secretariat/resource?id=", short_name, "/v1.0", sep = ""),  
           system = "http://gbif.org",
           scope = "system",
           dataset = eml$dataset(
               alternateIdentifier = alternateIdentifier,
               title = title,
               creator = creator,
               metadataProvider = metadataProvider,
               associatedParty = associatedParty,
               pubDate = pubDate,
               coverage = coverage,
               language = language,
               abstract = abstract,
               keywordSet = keywordSet,
               contact = contact,
               methods = methods,
               intellectualRights = intellectualRights,
               purpose = purpose,
               maintenance = maintenance,
               additionalInfo = additionalInfo),
           additionalMetadata = additionalMetadata
)

eml_validate(my_eml)
## [1] TRUE
## attr(,"errors")
## character(0)

Create meta.xml file

This is a file which describes the archive and data file structure and is required in a DarwinCore-Archive. It is based on the template file “meta_occurrence_checklist_template.xml”

meta_template <- paste(path_to_project_root, "scripts_data/meta_occurrence_checklist_template.xml", sep="/")
meta <- read_xml(meta_template)

fields <- xml_find_all(meta, "//d1:field")

for (field in fields) {
  term <- xml_attr(field, "term")
  if (term == "http://rs.tdwg.org/dwc/terms/eventDate") {
    xml_set_attr(field, "default", eventDate)
  } else if (term == "http://rs.tdwg.org/dwc/terms/country") {
    xml_set_attr(field, "default", country)
  } else if (term == "http://rs.tdwg.org/dwc/terms/locality") {
    xml_set_attr(field, "default", locality)
  } else if (term == "http://rs.tdwg.org/dwc/terms/decimalLatitude") {
    xml_set_attr(field, "default", localities$decimalLatitude)
  } else if (term == "http://rs.tdwg.org/dwc/terms/decimalLongitude") {
    xml_set_attr(field, "default", localities$decimalLongitude)
  } else if (term == "http://rs.tdwg.org/dwc/terms/coordinateUncertaintyInMeters") {
    xml_set_attr(field, "default", localities$coordinateUncertaintyInMeters)
  } else if (term == "http://rs.tdwg.org/dwc/terms/footprintWKT") {
    xml_set_attr(field, "default", wkt)
  } else if (term == "http://rs.tdwg.org/dwc/terms/geodeticDatum") {
    xml_set_attr(field, "default", geodeticDatum)
  } else if (term == "http://rs.tdwg.org/dwc/terms/occurrenceStatus") {
    xml_set_attr(field, "default", occurrenceStatus)
  } else if (term == "http://rs.tdwg.org/dwc/terms/basisOfRecord") {
    xml_set_attr(field, "default", basisOfRecord)
  }
}

Save outputs

dwc_output_dir <- paste(path_to_project_root, "output", site_dir_name, dataset_dir_name, sep="/")

write.csv(occurrence, paste(dwc_output_dir, "/occurrence.csv", sep = ""), na = "", row.names = FALSE)
write_xml(meta, file = paste(dwc_output_dir, "/meta.xml", sep = ""))
write_eml(my_eml, paste(dwc_output_dir, "/eml.xml", sep = ""))

Edit EML

We have to further edit the eml file to conform to GBIF-specific requirements that cannot be included in the original EML construction. This includes changing the schemaLocation and rearranging the GBIF element, since the construction automatically arranges the children nodes to alphabetical order.

#edit the schemaLocation and rearrange gbif node for gbif specific eml file
eml_content <- read_xml(paste(dwc_output_dir, "/eml.xml", sep = ""))

#change schemaLocation attributes for GBIF
root_node <- xml_root(eml_content)
xml_set_attr(root_node, "xsi:schemaLocation", "https://eml.ecoinformatics.org/eml-2.1.1 http://rs.gbif.org/schema/eml-gbif-profile/1.2/eml.xsd")
xml_set_attr(root_node, "xmlns:dc", "http://purl.org/dc/terms/")
xml_set_attr(root_node, "xmlns:stmml", NULL)
xml_set_attr(root_node, "xml:lang", "eng")


#rearrange children nodes under the GBIF element
hierarchyLevel <- eml_content %>% xml_find_all(".//hierarchyLevel")
dateStamp <- eml_content %>% xml_find_all(".//dateStamp")
citation <- eml_content %>% xml_find_all("./additionalMetadata/metadata/gbif/citation")
bibcitation <- eml_content %>% xml_find_all("./additionalMetadata/metadata/gbif/bibliography/citation")
xml_set_attr(bibcitation, "identifier", citationdoi)

eml_content %>% xml_find_all(".//hierarchyLevel") %>% xml_remove()
eml_content %>% xml_find_all(".//dateStamp") %>% xml_remove()
eml_content %>% xml_find_all("./additionalMetadata/metadata/gbif/citation") %>% xml_remove()
eml_content %>% xml_find_all(".//gbif") %>% xml_add_child(citation, .where=0)
eml_content %>% xml_find_all(".//gbif") %>% xml_add_child(hierarchyLevel, .where=0)
eml_content %>% xml_find_all(".//gbif") %>% xml_add_child(dateStamp, .where=0)

write_xml(eml_content, paste(dwc_output_dir, "/eml.xml", sep = ""))

Zip files to DwC-A

output_zip <- paste(dwc_output_dir, "DwC-A.zip", sep="/")

if (file.exists(output_zip)) {
  unlink(output_zip)
}

file_paths <- list.files(dwc_output_dir, full.names = TRUE)
zip(zipfile = output_zip, files = file_paths, mode = "cherry-pick")

if (file.exists(output_zip)) {
  unlink(file_paths)
}