Bundling Fourriere et al. 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:
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
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 316.305,68.805,543.015,345.015 -p 1",
"-a 106.425,61.875,542.025,296.505 -p 2",
"-a 108.405,67.815,540.045,309.375 -p 3",
"-a 108.405,61.875,547.965,323.235 -p 4",
"-a 116.325,65.835,541.035,312.345 -p 5",
"-a 111.375,69.795,545.985,307.395 -p 6",
"-a 120.285,64.845,539.055,332.145 -p 7",
"-a 110.385,69.795,542.025,341.055 -p 8",
"-a 110.385,68.805,541.035,298.485 -p 9",
"-a 110.385,69.795,544.005,274.725 -p 10",
"-a 111.375,65.835,537.075,296.505 -p 11",
"-a 110.385,65.835,532.125,274.725 -p 12",
"-a 115.335,63.855,549.945,301.455 -p 13",
"-a 109.395,68.805,536.085,316.305 -p 14",
"-a 114.345,64.845,544.005,283.635 -p 15",
"-a 114.345,69.795,545.985,290.565 -p 16",
"-a 109.395,68.805,541.035,340.065 -p 17",
"-a 112.365,69.795,267.795,258.885 -p 18",
"-a 151.965,75.735,538.065,292.545 -p 19",
"-a 109.395,73.755,533.115,298.485 -p 20",
"-a 111.375,72.765,530.145,292.545 -p 21",
"-a 110.385,70.785,533.115,300.465 -p 22",
"-a 110.385,73.755,532.125,321.255 -p 23",
"-a 109.395,71.775,540.045,318.285 -p 24",
"-a 110.385,71.775,544.005,299.475 -p 25",
"-a 107.415,68.805,543.015,306.405 -p 26",
"-a 110.385,70.785,543.015,293.535 -p 27",
"-a 107.415,72.765,535.095,302.445 -p 28",
"-a 110.385,73.755,544.995,273.735 -p 29",
"-a 110.385,71.775,471.735,290.565 -p 30"
)
# Define run parameters (see documentation)
run_parameters <- "-s -c -nh"
# 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-14 19:36:08"
## [4] "------------------------------"
## [5] ""
## [6] "PDF input: ../../../datasets/cocos_island_national_park/Fourriere_et_al_2017/raw/12526_2016_501_MOESM1_ESM.pdf"
## [7] "Perform Table Parsing: TRUE"
## [8] "Selected Areas:"
## [9] " Area 1: [316.305, 68.805, 543.015, 345.015]"
## [10] " Area 2: [106.425, 61.875, 542.025, 296.505]"
## [11] " Area 3: [108.405, 67.815, 540.045, 309.375]"
## [12] " Area 4: [108.405, 61.875, 547.965, 323.235]"
## [13] " Area 5: [116.325, 65.835, 541.035, 312.345]"
## [14] " Area 6: [111.375, 69.795, 545.985, 307.395]"
## [15] " Area 7: [120.285, 64.845, 539.055, 332.145]"
## [16] " Area 8: [110.385, 69.795, 542.025, 341.055]"
## [17] " Area 9: [110.385, 68.805, 541.035, 298.485]"
## [18] " Area 10: [110.385, 69.795, 544.005, 274.725]"
## [19] " Area 11: [111.375, 65.835, 537.075, 296.505]"
## [20] " Area 12: [110.385, 65.835, 532.125, 274.725]"
## [21] " Area 13: [115.335, 63.855, 549.945, 301.455]"
## [22] " Area 14: [109.395, 68.805, 536.085, 316.305]"
## [23] " Area 15: [114.345, 64.845, 544.005, 283.635]"
## [24] " Area 16: [114.345, 69.795, 545.985, 290.565]"
## [25] " Area 17: [109.395, 68.805, 541.035, 340.065]"
## [26] " Area 18: [112.365, 69.795, 267.795, 258.885]"
## [27] " Area 19: [151.965, 75.735, 538.065, 292.545]"
## [28] " Area 20: [109.395, 73.755, 533.115, 298.485]"
## [29] " Area 21: [111.375, 72.765, 530.145, 292.545]"
## [30] " Area 22: [110.385, 70.785, 533.115, 300.465]"
## [31] " Area 23: [110.385, 73.755, 532.125, 321.255]"
## [32] " Area 24: [109.395, 71.775, 540.045, 318.285]"
## [33] " Area 25: [110.385, 71.775, 544.005, 299.475]"
## [34] " Area 26: [107.415, 68.805, 543.015, 306.405]"
## [35] " Area 27: [110.385, 70.785, 543.015, 293.535]"
## [36] " Area 28: [107.415, 72.765, 535.095, 302.445]"
## [37] " Area 29: [110.385, 73.755, 544.995, 273.735]"
## [38] " Area 30: [110.385, 71.775, 471.735, 290.565]"
## [39] "Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30"
## [40] "Concatenate: True"
## [41] "Concatenate across headers: True"
## [42] "Stream Extraction: True"
## [43] "Lattice Extraction: False"
## [44] ""
## [45] "Parsing Tables"
## [46] "------------------------------"
## [47] ""
## [48] ""
## [49] "Saving to CSV"
## [50] "CSV file: ../../../datasets/cocos_island_national_park/Fourriere_et_al_2017/processed/12526_2016_501_MOESM1_ESM_tables_parsed_concatenated.csv"
## [51] "------------------------------"
## [52] ""
## [53] ""
## [54] "Run Details: ../../../datasets/cocos_island_national_park/Fourriere_et_al_2017/processed/12526_2016_501_MOESM1_ESM_parameters.txt"
## [55] "Finished"
## [56] ""
Read source data
Now we’ll read in the csv table outputted from the previous step
processed_csv <- "12526_2016_501_MOESM1_ESM_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))
X0 |
---|
Phylum CHORDATA |
Class CHONDRICHTHYES |
Order ORECTOLOBIFORMES |
Family Ginglymostomatidae |
Ginglymostoma unami Moral-Flores, Ramírez-Antonio, Angulo & |
Pérez-Ponce de León 2015 |
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()
# Remove Classes, Families and Orders and take first column only
cleaned_data <- input_data %>%
mutate(across(everything(), ~ if_else(str_detect(.x, "Phylum|Family|Order|Class"), "", .x))) %>%
filter(x0 != "")
#to preview pretty table
knitr::kable(head(cleaned_data))
x0 |
---|
Ginglymostoma unami Moral-Flores, Ramírez-Antonio, Angulo & |
Pérez-Ponce de León 2015 |
Rhincodon typus (Smith, 1828) |
Carcharhinus albimarginatus (Rüppell, 1837) |
Carcharhinus galapagensis (Snodgrass & Heller, 1905) |
Carcharhius limbatus (Müller & Henle, 1839) |
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:nrow(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 |
---|---|---|
Ginglymostoma unami Moral-Flores, Ramírez-Antonio, Angulo & | Ginglymostoma unami | 1006832 |
Pérez-Ponce de León 2015 | Pérez-ponce | NA |
Rhincodon typus (Smith, 1828) | Rhincodon typus | 105847 |
Carcharhinus albimarginatus (Rüppell, 1837) | Carcharhinus albimarginatus | 217352 |
Carcharhinus galapagensis (Snodgrass & Heller, 1905) | Carcharhinus galapagensis | 105790 |
Carcharhius limbatus (Müller & Henle, 1839) | Carcharhius limbatus | NA |
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[6,2:3] = c("Carcharhinus limbatus", 105793)
combined_dataframe[56,2:3] = c("Synodus lacertinus", 272130)
combined_dataframe[63, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Ogilbia", "new species", 270080)
combined_dataframe[98,2:3] = c("Baldwinella eos", NA)
combined_dataframe[99,2:3] = c("Cephalopholis colonus", NA)
combined_dataframe[231, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Starksia", "new species", 159668)
combined_dataframe[235, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Chaenopsis", "new species", 268702)
combined_dataframe[246,2:3] = c("Gobiesox fulvus", 1018256)
combined_dataframe[300,2:3] = c("Hydrolagus", 105734)
combined_dataframe[322,2:3] = c("Raja equatorialis", 271576)
combined_dataframe[326,2:3] = c("Gordiichthys combibus", 275477)
combined_dataframe[338, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Saurenchelys", "new species", 125642)
combined_dataframe[380,2:3] = c("Coryphaenoides bulbiceps", 272321)
combined_dataframe[400,2:3] = c("Dibranchus cracens", 272605)
combined_dataframe[434, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Pontinus", "new species", 126170)
combined_dataframe[436, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Scorpaena", "new species", 126171)
combined_dataframe[438, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Bellator", "new species", 159567)
combined_dataframe[441, c("CanonicalFull", "identificationQualifier", "WormsIDs")] <- c("Prionotus", "new species", 159569)
combined_dataframe[472,2:3] = c("Eleotris tubularis", 1018665)
combined_dataframe <- combined_dataframe[-c(2, 323),]
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, identificationQualifier, 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 (paste(scientificName, identificationQualifier), algo="md5"), sep=":"))
eventDate
This is NULL since this is technically a checklist and we do not know the collection date.
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()
#Cocos Island National Park
ind_shape <- shapes_processed$geom[which(shapes_processed$name == "Cocos Island 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)
Extra Terms
coordinateUncertaintyInMeters
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, identificationQualifier,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: 516 × 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
## # ℹ 506 more rows
Create the EML file
This is a file which contains the dataset’s metadata and is required in a DarwinCore-Archive.
## [1] "eml-2.1.1"
#Title
title <- "Updated checklist and analysis of completeness of the marine fish fauna of Isla del Coco, Pacific of Costa Rica: Fishes Checklist"
#AlternateIdentifier
alternateIdentifier <- paste("https://ipt.obis.org/secretariat/resource?r=", short_name, sep="")
#Abstract
abstract <- eml$abstract(
para = "Isla del Coco, Costa Rica, is one of the five groups of oceanic islands of the Eastern Tropical Pacific (ETP), and is considered one of the most diverse. Since the mid-19th century, it has been the target of a number of scientific research expeditions that have produced specimen collections which are housed in natural history museums around the world. The fish assemblage of Isla del Coco is considered one of the most speciose and best documented group of marine organisms of the island. Despite this, recent work has resulted in a need to update the checklist for this important group. We performed a completeness analysis of the ichthyofauna of Isl del Coco based on scientific publications and reports of expeditions, specimens in foreign and national collections, and field surveys. We confirmed the presence of 514 species of marine fishes, representing an increase of approximately 23% compared to what was previously reported. From a habitat perspective, 58 % of this assemblage is typically reef fishes, while the remaining 42% are deep-water, and pelagic species. The average expected reef fish species richness is 318.2 ± 7.3, suggesting that the local inventory represents 93.7 % of the expected total richness. Our updated list and greater number of species has particular relevance to the conservation efforts at Isla del Coco, since current conservation efforts are protecting at least 50 % of ETP fish species and about 40 % of Costa Rica’s Pacific fish species."
)
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 = "Manon",
surName = "Fourriére"),
organizationName = "International Studies in Aquatic Tropical Ecology (ISATEC), Bremen University"
), eml$creator(
individualName = eml$individualName(
givenName = "Juan José",
surName = "Alvarado"),
organizationName = "Centro de Investigación en Ciencias del Mar y Limnología, Universidad de Costa Rica"
), eml$creator(
individualName = eml$individualName(
givenName = "Arturo Ayala",
surName = "Bocos"),
organizationName = "Ecosistemas y Conservación: Proazul Terrestre A. C."
), eml$creator(
individualName = eml$individualName(
givenName = "Jorge",
surName = "Cortés"),
organizationName = "Centro de Investigación en Ciencias del Mar y Limnología, Universidad de Costa Rica"
)
)
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 = "Fourriére, Manon & Alvarado, Juan & Ayala-Bocos, Arturo & Cortés, Jorge. (2016). Updated checklist and analysis of completeness of the marine fish fauna of Isla del Coco, Pacific of Costa Rica. Marine Biodiversity. 47.")
)
)
)
citationdoi <- "http://dx.doi.org/10.1007/s12526-016-0501-6"
Coverage
Here we describe the dataset’s geographic, taxonomic and temporal coverage.
#Coverage
coverage <- eml$coverage(
geographicCoverage = eml$geographicCoverage(
geographicDescription = "Cocos Island National Park",
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="")
)
)
)
#Other Data
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)
}
}
#Add identificationQualifier
new_field <- xml_add_sibling(fields[[3]], "field")
xml_set_attr(new_field, "index", "3")
xml_set_attr(new_field, "term", "http://rs.tdwg.org/dwc/terms/identificationQualifier")
fields <- append(fields, list(new_field))
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 = ""))