#: Extraction function --------------------------- # XML namespaces of the Elsevier full-text API, used in the XPath expressions elsevier_ns <- c( ce = "http://www.elsevier.com/xml/common/dtd", dc = "http://purl.org/dc/elements/1.1/", xocs = "http://www.elsevier.com/xml/xocs/dtd", prism = "http://prismstandard.org/namespaces/basic/2.0/", mml = "http://www.w3.org/1998/Math/MathML" ) #' Version of the text extraction, stored in `xml_download.extraction_version` #' #' Bump it when `extract_elsevier_fulltext()` or `clean_fulltext_paragraphs()` #' change what they write: `formating_text_from_xml.R` then extracts again the #' files extracted by an earlier version. #' - 1 (until October 2026): paragraphs and footnotes, the last section title #' carried down to the following paragraphs; reference lists dropped. #' - 2: section hierarchy (`section_level`, `section_number`, #' `section_path`), reference lists kept as rows of type "bibliography", #' JEL codes saved in `article_jel`. #' - 2 also renames the column `type` to `type_text`, with the labels of the #' JSTOR and ISTEX databases (`bibliography` -> `references`, #' `references_or_appendices` -> `appendix`, `acknowledgments` -> #' `front_matter`), and types by XML context: table cells and notes become #' `table_figure`, the head of the article `front_matter`, and the untitled #' paragraphs of the body `main_text` (`non-identified_section` is gone). #' - 3 (October 2026, after the stage-1 evaluation of the types): paragraphs #' nested in paragraphs (list items, theorems, boxes) are no longer #' repeated in the text of the paragraph around them; tables and figures #' displayed inside a paragraph are removed from its text; a space is put #' after labels and `ce:hsp`; footnotes and table notes start with their #' printed label; untitled acknowledgments are `front_matter` and "Notes #' for Tables" sections `table_figure`. #' - 4 (October 2026, after round 2 of the stage-1 evaluation): a space #' around formulas and after citations glued to the next word; the terms #' of abbreviation lists start their description instead of being glued #' in the paragraph around the list; alt-texts of supplementary files are #' removed. text_extraction_version <- 4L #' Extract the paragraphs, bibliography and JEL codes of an Elsevier XML file #' #' Read an Elsevier full-text XML file and return, for a FULL-TEXT article, #' one row per paragraph (`ce:para`), footnote paragraph (`ce:note-para`) and #' bibliography entry (`ce:bib-reference`), in document order, with the block #' that contains it, and the JEL codes of the article. #' #' @param xml_file Character scalar. Filename of the XML file to process, #' relative to `xml_dir`. #' @param xml_dir Character scalar. Directory containing the XML files. #' Defaults to `xml_data_path` (set in `paths_and_packages.R`). #' @param ns Named character vector of XML namespaces. Defaults to #' `elsevier_ns`. #' #' @details #' - Only documents whose `xocs:item-weight` is "FULL-TEXT" are read. #' - Each row is placed in its nearest enclosing *block*: a section with a #' title (`ce:section`), the acknowledgments, the bibliography, further #' reading, or the abstract (where the highlights are). For sections, the #' depth (1 = top-level section), the printed number (`ce:label`, e.g. #' "2.1") and the titles from the top-level section down ("Model > Firms") #' are kept. Paragraphs in `ce:appendices` are flagged. #' - Inline footnotes and superscript cross-references are removed from the #' paragraph text; the footnotes are kept as their own rows (`note-para`), #' starting with their printed label. #' - Each paragraph is read without the paragraphs nested in it (list items, #' theorems, boxes), which have their own rows, and without the tables and #' figures displayed inside it. #' - The text of a bibliography entry is the reference as printed #' (`ce:source-text`, recent files) or the unstructured reference #' (`ce:other-ref`); otherwise the parts of the structured reference #' (`sb:reference`: authors, title, journal, volume, year, pages) joined by #' spaces. #' - JEL codes are the keywords of the groups of class "jel" (multilingual #' journals repeat the group in each language). #' #' @return NULL if the file cannot be read or is not FULL-TEXT; otherwise a #' list of two data.tables: #' - `paragraphs`: xml_text, xml_name ("para", "note-para", #' "bib-reference"), xml_node_id, file_name, in_appendix, block (kind of #' block: "section", "acknowledgment", "bibliography"...), section (title #' of the block), section_level, section_number, section_path; #' - `jel`: file_name, raw (one row per JEL keyword, as printed). #' #' @seealso clean_fulltext_paragraphs(), clean_jel_codes() extract_elsevier_fulltext <- function( xml_file, xml_dir = xml_data_path, ns = elsevier_ns ) { file_path <- file.path(xml_dir, xml_file) # Handle file read errors gracefully xml_data <- tryCatch( read_xml(file_path), error = function(e) { cli_alert_danger("Failed to read XML: {xml_file} — {conditionMessage(e)}") return(NULL) } ) if (is.null(xml_data)) { return(NULL) } #* Check document type — we only want FULL-TEXT articles type_xml <- xml_text(xml_find_all(xml_data, ".//xocs:item-weight", ns = ns)) if (!identical(type_xml, "FULL-TEXT")) { return(NULL) } #* JEL codes, as printed jel <- data.table( file_name = xml_file, raw = xml_text( xml_find_all(xml_data, ".//ce:keywords[@class='jel']//ce:keyword", ns = ns), trim = TRUE ) ) #* Blocks: every element with a title (sections, acknowledgments, #* declarations of interest, bibliography, abstract...), and the sections #* that only have a number (often appendices: "Appendix A"). # Each block is identified by its XPath (`xml_path()`), which is also how # the paragraphs are matched to their nearest block below. block_xpath <- "ce:section-title or (self::ce:section and ce:label)" blocks <- xml_find_all(xml_data, glue(".//*[{block_xpath}]"), ns = ns) # Title, or number for the sections without title title_or_label <- function(nodes) { dplyr::coalesce( dplyr::na_if(xml_text(xml_find_first(nodes, "./ce:section-title", ns = ns), trim = TRUE), ""), dplyr::na_if(xml_text(xml_find_first(nodes, "./ce:label", ns = ns), trim = TRUE), "") ) } block_info <- data.table( block_path = xml_path(blocks), block = xml_name(blocks), section = title_or_label(blocks), section_number = xml_text(xml_find_first(blocks, "./ce:label", ns = ns), trim = TRUE), section_level = NA_integer_, section_path = NA_character_ ) # Depth and path of the sections: titles of the section and its ancestors is_section <- block_info$block == "section" if (any(is_section)) { lineage <- lapply( blocks[is_section], \(s) xml_find_all(s, "ancestor-or-self::ce:section", ns = ns) ) block_info[is_section, section_level := vapply(lineage, length, integer(1))] block_info[ is_section, section_path := vapply( lineage, function(l) { titles <- title_or_label(l) titles <- titles[!is.na(titles)] if (length(titles) > 0L) paste(titles, collapse = " > ") else NA_character_ }, character(1) ) ] } #* Paragraphs, footnote paragraphs and bibliography entries, in document order nodes <- xml_find_all( xml_data, "(.//ce:para | .//ce:note-para | .//ce:bib-reference)[not(ancestor::ce:bib-reference)]", ns = ns ) if (length(nodes) == 0L) { cli_alert_warning("No paragraphs or sections found in {xml_file}") return(NULL) } node_name <- xml_name(nodes) is_bib <- node_name == "bib-reference" # Nearest block (subsections without title nor number belong to their # parent). Computed before the footnotes are removed below, since removing # nodes changes the XPaths. nearest_block <- xml_path(xml_find_first( nodes, glue("ancestor::*[{block_xpath}][1]"), ns = ns )) in_appendix <- xml_find_lgl(nodes, "boolean(ancestor::ce:appendices)", ns = ns) # Context in the XML tree, which decides the type more surely than the # section titles: cells and notes of tables, figure captions (Elsevier # stores tables and figures in `ce:floats`, before the body, or inline in # a section); and the head of the article (notes on the title and the # authors, data availability statement, abstract) in_table_figure <- xml_find_lgl( nodes, "boolean(ancestor::*[local-name() = 'table' or local-name() = 'table-footnote' or local-name() = 'caption' or local-name() = 'figure'])", ns = ns ) in_head <- xml_find_lgl(nodes, "boolean(ancestor::*[local-name() = 'head'])", ns = ns) # The acknowledgments element, with or without a title (an untitled one is # not a block, since blocks are found by their title) in_acknowledgment <- xml_find_lgl(nodes, "boolean(ancestor::ce:acknowledgment)", ns = ns) # Bibliography entries: the printed reference, else its parts text <- rep(NA_character_, length(nodes)) if (any(is_bib)) { text[is_bib] <- bibliography_text(nodes[is_bib], ns = ns) } # Printed label of the footnotes ("12") and table notes ("a"), put before # the text of the first paragraph of the note, as printed (and as in the # JSTOR database): without it, a footnote read apart from its call looks # like body text note_label <- xml_text( xml_find_first(nodes, "ancestor::*[self::ce:footnote or self::ce:table-footnote][1]/ce:label", ns = ns), trim = TRUE ) first_of_note <- xml_find_lgl(nodes, "boolean(self::ce:note-para and not(preceding-sibling::ce:note-para))", ns = ns) note_label[!first_of_note | node_name != "note-para"] <- NA_character_ # Same for the items of lists ("(i)", "−") and the theorems ("Lemma 5", # `ce:enunciation`): their label sits beside their first paragraph, and # would otherwise stay in the paragraph around the list item_label <- xml_text( xml_find_first(nodes, "parent::*[self::ce:list-item or self::ce:enunciation]/ce:label", ns = ns), trim = TRUE ) first_of_item <- xml_find_lgl(nodes, "boolean(self::ce:para and not(preceding-sibling::ce:para))", ns = ns) item_label[!first_of_item] <- NA_character_ # And for the lists of abbreviations and nomenclatures (`ce:def-list`): # the term ("LCA") is a sibling of the description ("Life cycle # assessment"), not a label; without this the terms were all glued in the # paragraph around the list ("Abbreviation ListMS4LCALCC...") def_term <- xml_text( xml_find_first(nodes, "parent::ce:def-description/preceding-sibling::ce:def-term[1]", ns = ns), trim = TRUE ) def_term[!first_of_item] <- NA_character_ note_label <- fcoalesce(note_label, item_label, def_term) # Labels (list bullets, numbers of theorems and of table notes) and # horizontal spaces (`ce:hsp`) have no space around them in the XML: # without one, the text reads "jEnergy use..." or "Lemma 5Given A1...". # Only leaf labels are changed (setting the text of an element replaces # its children). labels <- xml_find_all(xml_data, ".//ce:label[not(*)]", ns = ns) xml_text(labels) <- paste0(xml_text(labels), " ") # Formulas (inline `mml:math`, displayed `ce:display`) are glued to the # words around them ("By first order condition:UYG−D'..."): a `ce:hsp` is # put on each side, and becomes a space below. The double spaces this # sometimes creates are squished in `clean_fulltext_paragraphs()`. The # inside of a formula stays read token after token ("UYG−D'−UYB=me"): # MathML has no plain-text rendering that would be worth the cost. formulas <- xml_find_all(xml_data, ".//mml:math | .//ce:display", ns = ns) xml_add_sibling(formulas, "ce:hsp", .where = "before") xml_add_sibling(formulas, "ce:hsp", .where = "after") # Citations directly followed by a word, without the space the printed # page has ("Angelini and Guiso (1994)and", "Eqs. (A.4a)are"), mostly in # articles converted from print before 2000. A space is put only when the # next character is a letter, a digit or "(", so that "(1994)," stays as # it is. Superscript calls of footnotes are left out: they are removed. cites <- xml_find_all(xml_data, ".//*[self::ce:cross-ref or self::ce:cross-refs][not(.//ce:sup)]", ns = ns) after_cite <- xml_text(xml_find_first(cites, "following-sibling::node()[1][self::text()]")) glued <- !is.na(after_cite) & grepl("^[[:alnum:](]", after_cite) if (any(glued)) xml_add_sibling(cites[glued], "ce:hsp", .where = "after") spaces <- xml_find_all(xml_data, ".//ce:hsp", ns = ns) xml_text(spaces) <- " " # Paragraphs nested in other paragraphs (items of lists, theorems in # `ce:enunciation`, boxes, footnotes) have their own rows: each paragraph # is read without the paragraphs it contains, otherwise their text is # stored twice. The deepest paragraphs are read first, then detached from # the tree (`xml_remove()` unlinks them; they stay readable), so that the # paragraph around them no longer contains them. depth <- xml_find_num(nodes, "count(ancestor::ce:para | ancestor::ce:note-para)", ns = ns) for (level in sort(unique(depth[!is_bib]), decreasing = TRUE)) { at_level <- which(!is_bib & depth == level) # Remove what does not belong to the text of the paragraph: footnotes # (their paragraphs, deeper, are already read), superscript reference # numbers, and the tables and figures displayed inside a paragraph of # the body (their cells would be glued to the text: "Index stockMatching # stockStock name...") xml_remove(xml_find_all(nodes[at_level], ".//ce:footnote", ns = ns)) xml_remove(xml_find_all(nodes[at_level], ".//ce:cross-ref[.//ce:sup]", ns = ns)) # Labels of the list items and theorems: they now start the first # paragraph of the item (the DTD always puts paragraphs in them; those # paragraphs, deeper, are already read and detached) xml_remove(xml_find_all( nodes[at_level], ".//*[self::ce:list-item or self::ce:enunciation]/ce:label", ns = ns )) # Terms of the lists of abbreviations, now before their description xml_remove(xml_find_all(nodes[at_level], ".//ce:def-term", ns = ns)) body_level <- at_level[!in_table_figure[at_level]] # Supplementary files (`ce:e-component`): their alt-text ("Image, # application 1") is a placeholder for the file; their caption, which # describes the material in sentences, is kept xml_remove(xml_find_all(nodes[at_level], ".//ce:e-component/ce:alt-text", ns = ns)) xml_remove(xml_find_all( nodes[body_level], ".//*[local-name() = 'table' or self::ce:figure]", ns = ns )) text[at_level] <- xml_text(nodes[at_level], trim = TRUE) if (level > 0) xml_remove(nodes[at_level]) } text <- fifelse(is.na(note_label), text, paste(note_label, text)) paragraphs <- data.table( xml_text = text, xml_name = node_name, xml_node_id = seq_along(nodes), file_name = xml_file, in_appendix = in_appendix, in_table_figure = in_table_figure, in_head = in_head, in_acknowledgment = in_acknowledgment, block_path = nearest_block ) paragraphs <- block_info[paragraphs, on = "block_path"][, block_path := NULL] setorder(paragraphs, xml_node_id) list(paragraphs = paragraphs, jel = jel) } #' Text of bibliography entries (`ce:bib-reference` nodes) #' #' @return A character vector: the reference as printed (`ce:source-text`), #' else the unstructured reference (`ce:other-ref`), else the parts of the #' structured reference joined by spaces; NA if the entry is empty. bibliography_text <- function(bibs, ns = elsevier_ns) { printed <- xml_text(xml_find_first(bibs, "./ce:source-text", ns = ns), trim = TRUE) unstructured <- xml_text(xml_find_first(bibs, ".//ce:other-ref", ns = ns), trim = TRUE) out <- dplyr::coalesce( dplyr::na_if(printed, ""), dplyr::na_if(unstructured, "") ) missing <- which(is.na(out)) # The structured reference has one element per part (surname, title, # volume...): their text nodes are joined with spaces, otherwise xml_text() # glues them together ("T.G.AndersonReturn volatility..."). out[missing] <- vapply( missing, function(i) { parts <- xml_text( xml_find_all(bibs[[i]], ".//*[local-name() = 'reference']//text()"), trim = TRUE ) parts <- parts[parts != ""] if (length(parts) > 0L) paste(parts, collapse = " ") else NA_character_ }, character(1) ) stringr::str_squish(out) } #' Clean and classify the paragraphs extracted from Elsevier XML files #' #' Turn the `paragraphs` returned by `extract_elsevier_fulltext()` (for one #' or several files) into the rows of the `text` table. #' #' @param extracted data.table, rows of `extract_elsevier_fulltext()$paragraphs` #' for one or several files, in document order. Modified by reference. #' #' @details #' `type_text` uses the labels shared with the JSTOR and ISTEX databases #' (`building_jstor_database`, `building_istex_database`). It is decided by #' the place of the paragraph in the XML tree first, then by the section #' titles, in this order of precedence: #' - "references": an entry of the reference list or of further reading; #' - "table_figure": a cell or a note of a table, a figure caption, a #' section of table notes ("Notes for Tables 1-14"); #' - "front_matter": a paragraph of the head of the article (notes on the #' title and the authors, data availability statement, abstract), the #' acknowledgments element (titled or not), or a section about #' acknowledgments, funding, #' declarations of interest (the title stays in `section`); #' - "appendix": a paragraph in the appendices, or in a section about #' appendices or supplementary material; #' - "footnote": a footnote paragraph (`note-para`) of the body; #' - "main_text": everything else, including the paragraphs of the body #' outside any titled section: an introduction without heading, or the #' whole text of a document without headings (editorials, comments, book #' reviews, declarations). #' "header_footer" of the other databases is not needed: the XML holds no #' running heads or page numbers. #' The paragraphs of the body of an article without any titled section get #' the section "no_section"; in the other articles, the untitled paragraphs #' keep a NULL section. #' #' @return A data.table with columns scopus_id, paragraph_id, text, section, #' section_level, section_number, section_path, type_text. clean_fulltext_paragraphs <- function(extracted) { # Squish before dropping the empty rows: a paragraph holding only table # anchors (`ce:float-anchor`) keeps a non-breaking space that trim misses extracted[, xml_text := stringr::str_squish(xml_text)] paragraphs <- extracted[!is.na(xml_text) & xml_text != ""] # empty sections, empty entries #* Classify paragraphs: XML context first, then section titles paragraphs[, type_text := NA_character_] paragraphs[xml_name == "bib-reference", type_text := "references"] paragraphs[is.na(type_text) & in_table_figure, type_text := "table_figure"] # Notes of tables printed as a section of their own (some converted # articles of the 1990s: "Notes for Tables 1-14") paragraphs[ is.na(type_text) & section %like% "^(Notes?|Sources?) (for|to|of) (the )?(Tables?|Figures?)", type_text := "table_figure" ] paragraphs[is.na(type_text) & in_head, type_text := "front_matter"] paragraphs[ is.na(type_text) & (in_appendix | section %like% "(A|a)ppendi|Supplementary"), type_text := "appendix" ] # Acknowledgments override the appendix rule (an acknowledgments section # placed among the appendices is still acknowledgments) paragraphs[ type_text %in% c(NA, "appendix") & (block %in% "acknowledgment" | in_acknowledgment | section %like% "^(Declaration|Disclosure).*interests?$|Statement$|interest statement$|conflict of interest|(A|a)cknowledge?ments?|^Fundings?$"), type_text := "front_matter" ] paragraphs[xml_name == "note-para" & is.na(type_text), type_text := "footnote"] # Everything else is body text, with or without a section title: an # untitled paragraph of the body is an introduction without heading, or # the text of a document without headings, not front matter paragraphs[is.na(type_text), type_text := "main_text"] # Body of the articles without any titled section: "no_section" paragraphs[, no_block := all(is.na(section[type_text %in% c("main_text", "footnote")])), by = "file_name" ] paragraphs[ no_block == TRUE & type_text %in% c("main_text", "footnote"), section := "no_section" ] paragraphs[, text := xml_text] # One id per paragraph within each document paragraphs[, paragraph_id := seq_len(.N), by = "file_name"] # We can recover the scopus id and we don't need the file name anymore paragraphs[, scopus_id := stringr::str_remove(file_name, "\\.xml(\\.gz)?$") |> stringr::str_replace("ID_", "ID:") ] paragraphs[, .( scopus_id, paragraph_id, text, section, section_level, section_number, section_path, type_text )] } #' Normalise the JEL codes extracted from Elsevier XML files #' #' @param jel data.table, rows of `extract_elsevier_fulltext()$jel` (file_name, #' raw) for one or several files. #' #' @details #' A keyword can hold one code ("D82") or several ("E31, E52"), with #' variations ("E 52", "JEL: C23"). Codes are read with the pattern "a letter, #' an optional space, one or two digits", upper-cased and stripped of spaces. #' Keywords without any code keep one row with `jel_code` NA, so that the raw #' text stays available. #' #' @return A data.table: scopus_id, jel_code, raw; unique by (scopus_id, #' jel_code). clean_jel_codes <- function(jel) { if (nrow(jel) == 0L) { return(data.table(scopus_id = character(), jel_code = character(), raw = character())) } jel <- jel[!is.na(raw) & raw != ""] codes <- stringr::str_extract_all(toupper(jel$raw), "\\b[A-Z] ?[0-9]{1,2}\\b") out <- data.table( file_name = rep(jel$file_name, pmax(lengths(codes), 1L)), raw = rep(jel$raw, pmax(lengths(codes), 1L)), jel_code = unlist(lapply(codes, \(x) if (length(x) == 0L) NA_character_ else x)) ) out[, jel_code := stringr::str_remove_all(jel_code, " ")] out[, scopus_id := stringr::str_remove(file_name, "\\.xml(\\.gz)?$") |> stringr::str_replace("ID_", "ID:") ] # Drop the code-less rows of articles that have codes, then duplicates # (the same code printed in several languages) out <- out[!is.na(jel_code) | !scopus_id %in% out[!is.na(jel_code), scopus_id]] unique(out[, .(scopus_id, jel_code, raw)], by = c("scopus_id", "jel_code")) } #' Retrieve the journals from the Elsevier Serial Title API #' #' Fetch a single page of journals (serial) metadata for a given subject area from #' the Elsevier Serial Title API. This function performs a small number of #' retry attempts on transient errors. It expects the variables \code{subject_code} #' and \code{api_key} to be available in the calling environment (or to be set #' in the global environment) and uses \pkg{httr}, \pkg{jsonlite} and \pkg{glue} #' to perform the request and parse the response. #' #' @param start_index integer. Offset for the page to request (0-based). #' @param page_size integer. Number of items to request per page. #' @param max_attempts integer. Maximum number of attempts to try the request #' before giving up. Defaults to \code{3L}. #' #' @details #' The function builds a request URL of the form #' \code{https://api.elsevier.com/content/serial/title?subj={subject_code}&count={page_size}&start={start_index}} #' and sends the request with the header \code{X-ELS-APIKey = api_key}. On HTTP #' 200 responses the JSON body is parsed and the \code{entry} element of the #' \code{serial-metadata-response} is returned. If the API returns no entries #' (NULL or length 0) an empty list is returned to indicate that no more results #' are available. On repeated failures (after \code{max_attempts}) the function #' returns \code{NULL} to indicate an error. #' #' The function prints a short message on each failed attempt and performs a #' short sleep between retries (sleep grows linearly with the attempt count). #' #' @return #' - A list of parsed entry objects on success (as returned by #' \code{jsonlite::fromJSON} for the \code{entry} field). #' - An empty list when the API returns no entries (indicates completion). #' - \code{NULL} when all retry attempts fail (indicates an error). #' #' @examples #' \dontrun{ #' # Ensure api_key and subject_code are set in your environment #' api_key <- Sys.getenv("ELSEVIER_API_KEY") #' subject_code <- "MED" # example subject code #' #' # Fetch first page of journals #' entries <- fetch_serial_page(start_index = 0L, page_size = 25L) #' if (is.null(entries)) { #' stop("Failed to fetch journal data from Elsevier API") #' } else if (length(entries) == 0L) { #' message("No journal entries returned (no more results)") #' } else { #' # process `entries` #' } #' } #' #' @seealso \pkg{httr}, \pkg{jsonlite}, \pkg{glue} #' @keywords api journals elsevier retry #' @export fetch_serial_page <- function(start_index, page_size, max_attempts = 3L) { attempt <- 1L while (attempt <= max_attempts) { url <- glue::glue( "https://api.elsevier.com/content/serial/title?subj={subject_code}&count={page_size}&start={start_index}" ) res <- tryCatch( httr::GET(url, httr::add_headers("X-ELS-APIKey" = api_key)), error = function(e) NULL ) if (!is.null(res) && httr::status_code(res) == 200L) { body <- httr::content(res, as = "text", encoding = "UTF-8") parsed <- jsonlite::fromJSON(body, simplifyVector = TRUE) entries <- parsed$`serial-metadata-response`$entry # entries may be NULL or length 0 when there are no more results if (is.null(entries) || length(entries) == 0L) { return(list()) # return empty list to indicate completion } return(entries) } else { message(glue::glue( "Attempt {attempt} failed for start={start_index}. Retrying..." )) attempt <- attempt + 1L Sys.sleep(1 * attempt) } } # If we reach here all attempts failed -> return NULL to indicate error NULL } #' Classify the content of an Elsevier XML response #' #' Say whether the XML returned by the Elsevier Article Retrieval API holds the #' full text. #' #' @param content raw. The (uncompressed) XML content. #' @param head_bytes integer(1). Number of bytes searched first. #' `xocs:item-weight` and `pubType` sit in the first ~35 KB; the whole #' content is searched when they are not found there. #' #' @return A one-row data.table with `item_weight` (e.g. "FULL-TEXT", #' "HEAD-AND-TAIL", NA when the response has only `coredata`), `pub_type` #' (Elsevier document type: "fla" full-length article, "rev" review, "brv" #' book review...), `file_size` (uncompressed size in bytes) and `outcome`: #' - "full_text": `item-weight` is FULL-TEXT; #' - "no_access": any other response (HEAD-AND-TAIL, HEAD-ONLY, coredata #' only...), i.e. the full text is not available with our entitlements; #' - "corrupt": empty or truncated content (no closing root tag). classify_xml_content <- function(content, head_bytes = 65536L) { size <- length(content) result <- data.table::data.table( item_weight = NA_character_, pub_type = NA_character_, file_size = as.numeric(size), outcome = "corrupt" ) if (size == 0) { return(result) } as_text <- function(bytes) rawToChar(bytes[bytes != as.raw(0)]) # First capture group of a byte-wise regex match, NA if none match_first <- function(text, pattern) { m <- regmatches(text, regexec(pattern, text, useBytes = TRUE))[[1]] if (length(m) > 1L) m[2] else NA_character_ } tail_text <- as_text(content[max(1, size - 199):size]) if (!grepl("\\s*$", tail_text, useBytes = TRUE)) { return(result) } head_text <- as_text(content[seq_len(min(head_bytes, size))]) weight <- match_first(head_text, "([^<]+)<") if (is.na(weight) && size > head_bytes) { weight <- match_first(as_text(content), "([^<]+)<") } weight <- trimws(weight) data.table::data.table( item_weight = weight, pub_type = match_first(head_text, "[[:space:]]*([^<[:space:]]+)"), file_size = as.numeric(size), outcome = if (isTRUE(weight == "FULL-TEXT")) "full_text" else "no_access" ) } #' Read an XML file, compressed (.gz) or not, as raw bytes read_xml_bytes <- function(file_path) { if (grepl("\\.gz$", file_path)) { con <- gzfile(file_path, "rb") on.exit(close(con)) chunks <- list() repeat { chunk <- readBin(con, "raw", 1e7) if (length(chunk) == 0L) break chunks[[length(chunks) + 1L]] <- chunk } unlist(chunks, use.names = FALSE) } else { readBin(file_path, "raw", file.size(file_path)) } } #' Classify a saved Elsevier XML file (.xml or .xml.gz) #' #' @param file_path character(1). Path to the XML file. #' @return See `classify_xml_content()`; "corrupt" also when the file is #' missing or cannot be read (e.g. a damaged .gz). classify_xml_file <- function(file_path) { content <- tryCatch( if (file.exists(file_path)) read_xml_bytes(file_path) else raw(0), error = function(e) raw(0) ) classify_xml_content(content) } #' Download the full-text XML of one article from the Elsevier API #' #' Request the article from the Article Retrieval API (by DOI when available, #' otherwise by Scopus ID), classify the response and save it as #' `file.path(path, file_name)`, gzipped when `file_name` ends with ".gz". #' #' @param scopus_id character(1). Scopus identifier ("SCOPUS_ID:..."). #' @param doi character(1). DOI, or NA. #' @param file_name character(1). Name of the file to write #' (`SCOPUS_ID_.xml.gz`). #' @param path character(1). Directory where the XML is saved. #' #' @details #' The response is checked in memory before being written: a truncated #' response (no closing root tag) is not saved and counts as a transient #' error. The file is first written to a `.tmp` file and renamed once complete, #' so an interrupted run never leaves a partial file behind. #' Outcomes (column `outcome`): #' - "full_text", "no_access": HTTP 200, see `classify_xml_content()`; #' - "not_found": HTTP 404 or another client error (bad DOI...); #' - "transient_error": network error, timeout, HTTP 5xx or truncated #' response; worth retrying. #' HTTP 401/403 (not on the institutional network, or wrong key) and 429 #' (quota reached) stop with an error, since every following request would #' fail the same way. Requires a global `api_key`. #' #' @return A one-row data.table: scopus_id, file_name, http_status, #' item_weight, pub_type, outcome, file_size (uncompressed), n_attempts (1), #' last_attempt. fetch_and_save_fulltext <- function(scopus_id, doi, file_name, path) { result <- data.table::data.table( scopus_id = scopus_id, file_name = file_name, http_status = NA_integer_, item_weight = NA_character_, pub_type = NA_character_, outcome = "transient_error", file_size = NA_real_, n_attempts = 1L, last_attempt = Sys.Date() ) url <- if (is.na(doi) || doi == "") { paste0( "https://api.elsevier.com/content/article/scopus_id/", stringr::str_remove(scopus_id, "^SCOPUS_ID:") ) } else { paste0("https://api.elsevier.com/content/article/doi/", utils::URLencode(doi)) } response <- tryCatch( httr::GET( url, httr::add_headers("X-ELS-APIKey" = api_key, "Accept" = "text/xml"), httr::timeout(30) ), error = function(e) NULL ) if (is.null(response)) { return(result) } status <- httr::status_code(response) result[, http_status := status] if (status %in% c(401L, 403L)) { cli::cli_abort( "HTTP {status} for {scopus_id}: not authorised (are you on the institutional network?)." ) } if (status == 429L) { reset <- httr::headers(response)[["x-ratelimit-reset"]] reset_time <- if (is.null(reset)) { "unknown" } else { format(as.POSIXct(as.numeric(reset), origin = "1970-01-01")) } cli::cli_abort("HTTP 429: API quota reached. It resets on {reset_time}.") } if (status >= 500L) { return(result) } if (status != 200L) { result[, outcome := "not_found"] return(result) } content <- httr::content(response, as = "raw") classification <- classify_xml_content(content) if (classification$outcome == "corrupt") { return(result) # truncated response: transient_error, nothing saved } file_path <- file.path(path, file_name) tmp_path <- paste0(file_path, ".tmp") out <- if (grepl("\\.gz$", file_name)) gzfile(tmp_path, "wb") else file(tmp_path, "wb") writeBin(content, out) close(out) file.rename(tmp_path, file_path) result[, (names(classification)) := classification] result } #' Normalize sentinel values to NA in selected data.table columns #' #' Convert selected columns to character and replace common sentinel values #' (e.g. "[NULL]", "NULL", "", empty string, single space, "0") with #' NA. The function operates by reference on a data.table and returns the #' modified data.table invisibly. #' #' @param dt data.table. A data.table which will be modified in-place. #' @param cols character. A character vector of column names in `dt` to #' normalize. Columns that are not present are silently skipped. #' #' @details #' The function first checks that `dt` is a data.table. For each column named #' in `cols` that exists in `dt` the column is coerced to character and any #' values equal to the sentinel set are replaced with `NA_character_`. #' Common sentinel values handled are: `"[NULL]"`, `"NULL"`, `""`, `""`, #' `" "`, and `"0"`. #' #' This is useful when importing heterogeneous datasets that use sentinel #' strings to indicate missingness. Because conversion is performed by #' reference the original data.table is modified; the function returns the #' same data.table invisibly. #' #' @return The input data.table, invisibly, after modification (columns coerced #' to character and sentinel values replaced with `NA_character_`). #' #' @examples #' library(data.table) #' dt <- data.table(a = c("NULL", "x", "[NULL]"), b = c("", " ", "y")) #' normalize_sentinels_to_na(dt, c("a", "b")) #' dt #' #' @export normalize_sentinels_to_na <- function(dt, cols) { values_to_na <- c("[NULL]", "NULL", "", "", " ", "0") if (!data.table::is.data.table(dt)) { stop("`dt` must be a data.table") } for (col_name in cols) { if (!col_name %in% names(dt)) { next } # ensure column is character, then replace sentinel values with NA dt[, (col_name) := as.character(.SD[[1]]), .SDcols = col_name] dt[get(col_name) %in% values_to_na, (col_name) := NA_character_] } invisible(dt) } #' Perform deterministic record matching between two datasets #' #' @title Deterministic record matching (exact-key) #' @description #' Perform deterministic (exact-key) record matching between two data.tables #' (referred to as "left" and "right") using one or more matching variables. #' The function builds a composite key by pasting the provided matching #' variables (order matters), joins the two datasets on that key to produce #' left <-> right id pairs, and returns a per-left-id table of match results #' and summary statistics for the chosen matching strategy. #' #' @param dt_left data.table #' Left-side dataset to be matched. Expected to contain the identifier column #' specified by `id_left_col` and all variables named in `matching_variable`. #' @param dt_right data.table #' Right-side dataset to be matched. Expected to contain the identifier column #' specified by `id_right_col` and all variables named in `matching_variable`. #' @param matching_variable character vector #' One or more column names used to form the deterministic matching key. The #' values are pasted together (in the provided order) to form the composite key. #' Default: c("title_cleaned", "year"). #' @param match_suffix character #' Suffix used to name strategy-specific output columns (e.g. "match_1"). #' Default: "match_1". #' @param id_left_col character #' Name of the identifier column in `dt_left` (required). #' @param id_right_col character #' Name of the identifier column in `dt_right` (required). #' @param normalize_sentinels logical #' Whether to normalize common sentinel values to NA in the matching, based on #' the `matching_variable` columns, before performing the matching. Use #' `normalize_sentinels_to_na`. Default: FALSE. #' #' @details #' - Rows with NA in any `matching_variable` are omitted before matching. #' - A composite key named "paste_match" is created by pasting the #' `matching_variable` columns together for both datasets; matches are exact #' string matches on that key. #' - The function preserves the original input tables and operates on copies. #' - Output column names are constructed from `match_suffix` and identifier #' names: #' - Strategy-specific right id column: paste0(id_right_col, "_", match_suffix) #' - Per-row indicator that a right match was found: paste0("is_", match_suffix, "_true") #' - Strategy-level matched share: paste0("share_matching_", match_suffix) (percent) #' - Strategy-level duplication rate: paste0("duplication_rate", match_suffix) (percent; #' note: no underscore to preserve original script behavior) #' - Informational messages about percent matched and duplication rate are emitted #' via cli::cli_alert_info(). #' #' @return data.table #' A data.table with one row per left-side id (column name given by #' `id_left_col`) and the following columns (names vary with `match_suffix` #' and id column names): #' - strategy-specific right id column (e.g. "id_wos_match_1") #' - binary indicator for whether this left record had a right match #' (e.g. "is_match_1_true"; 1 = matched, 0 = not matched) #' - strategy-level metrics repeated for every row: #' - share of left records matched by this strategy (percent) #' - duplication rate for this strategy (percent) #' #' @examples #' \dontrun{ #' library(data.table) #' #' # Minimal example data.tables #' left_dt <- data.table(id_jstor = 1:3, #' title_cleaned = c("a", "b", "c"), #' year = c(2000, 2001, 2002)) #' right_dt <- data.table(id_wos = c("A","B"), #' title_cleaned = c("a","b"), #' year = c(2000,2001)) #' #' # Run deterministic matching on title_cleaned and year #' res <- perform_record_matching( #' dt_left = left_dt, #' dt_right = right_dt, #' matching_variable = c("title_cleaned", "year"), #' match_suffix = "match_1", #' id_left_col = "id_jstor", #' id_right_col = "id_wos", #' normalize_sentinels = FALSE #' ) #' print(res) #' } #' @seealso #' For fuzzy/probabilistic matching approaches consider packages such as #' stringdist or RecordLinkage. #' #' @export perform_record_matching <- function( dt_left, dt_right, matching_variable = c("title_cleaned", "year"), match_suffix = "match_1", id_left_col, id_right_col, normalize_sentinels = FALSE ) { # Input checks if (missing(dt_left) || !is.data.table(dt_left)) { stop("dt_left must be provided and be a data.table.") } if (missing(dt_right) || !is.data.table(dt_right)) { stop("dt_right must be provided and be a data.table.") } if (missing(id_left_col) || !(id_left_col %in% names(dt_left))) { stop("Provide a valid id_left_col present in dt_left.") } if (missing(id_right_col) || !(id_right_col %in% names(dt_right))) { stop("Provide a valid id_right_col present in dt_right.") } if (any(!(matching_variable %in% names(dt_left)))) { stop("All matching_variable names must exist in dt_left.") } if (any(!(matching_variable %in% names(dt_right)))) { stop("All matching_variable names must exist in dt_right.") } # Prepare minimal copies and drop rows missing any matching variable left_prep <- copy(dt_left[, .SD, .SDcols = c(id_left_col, matching_variable)]) right_prep <- copy(dt_right[, .SD, .SDcols = c(id_right_col, matching_variable) ]) # Normalize sentinels to NA if requested, to make sure they don't interfere with matching if (normalize_sentinels) { normalize_sentinels_to_na(left_prep, matching_variable) normalize_sentinels_to_na(right_prep, matching_variable) } left_prep <- na.omit(left_prep, cols = matching_variable) right_prep <- na.omit(right_prep, cols = matching_variable) # Build composite key left_prep[, paste_match := do.call(paste, .SD), .SDcols = matching_variable] right_prep[, paste_match := do.call(paste, .SD), .SDcols = matching_variable] # Keep unique id/key pairs left_unique <- unique(left_prep[, .SD, .SDcols = c(id_left_col, "paste_match") ]) right_unique <- unique(right_prep[, .SD, .SDcols = c(id_right_col, "paste_match") ]) # Create matched pairs (allowing a left id to map to multiple right ids) matched_pairs <- merge( left_unique, right_unique, by = "paste_match", all.x = TRUE, allow.cartesian = TRUE ) # Ensure we always have a per-left-id output: merge matched right ids back into original left table left_with_matches <- merge( dt_left, matched_pairs[, .SD, .SDcols = c(id_left_col, id_right_col)], by = id_left_col, all.x = TRUE ) # Build output table with one row per left id (keeps original left rows) output_stat_dt <- left_with_matches[, .SD, .SDcols = c(id_left_col, id_right_col) ] # Names for strategy-specific columns id_match_col_name <- paste0(id_right_col, "_", match_suffix) match_check_col_name <- paste0("is_", match_suffix, "_true") id_stat_col_name <- paste0("share_matching_", match_suffix) duplication_rate_stat_col_name <- paste0("duplication_rate", match_suffix) # preserved no underscore # Indicator: 1 if a right id found, else 0 output_stat_dt[, (match_check_col_name) := as.integer(!is.na(get(id_right_col))) ] # Share matched: percent of left rows with at least one right match output_stat_dt[, (id_stat_col_name) := sum(get(match_check_col_name)) / .N * 100 ] # Duplication rate: percent of left ids that match to more than one distinct right id if (nrow(matched_pairs) == 0L) { dup_rate <- 0 } else { left_match_counts <- matched_pairs[, .N, by = id_left_col] n_left_with_duplicates <- left_match_counts[N > 1, .N] n_left_total <- uniqueN(matched_pairs[[id_left_col]]) # If no left keys were matched at all, define duplication as 0 dup_rate <- if (n_left_total == 0L) { 0 } else { round(n_left_with_duplicates / n_left_total * 100, 2) } } output_stat_dt[, (duplication_rate_stat_col_name) := dup_rate] # Create strategy-specific right-id column and drop the generic right id output_stat_dt[, (id_match_col_name) := get(id_right_col)] output_stat_dt[, (id_right_col) := NULL] # Informational messages cli::cli_alert_info( glue::glue( "{match_suffix}: matched {round(output_stat_dt[[id_stat_col_name]][1], 2)}% of {id_left_col} records" ) ) cli::cli_alert_info( glue::glue( "{match_suffix}: duplication rate {round(output_stat_dt[[duplication_rate_stat_col_name]][1], 2)}%" ) ) # Return per-left-id table with the strategy-specific columns return(output_stat_dt[]) } #' Find near-duplicate text pairs between two data.tables #' #' Compute string distances between text fields from two data.tables after #' restricting comparisons to matching groups (e.g. same journal, year, etc.). #' The function returns pairwise matches (one row per pair) including the raw #' string distance and, optionally, a normalized distance (distance divided by #' the maximum length of the two strings). The inputs are copied and never #' modified in-place. #' #' @param data_dt_1 data.table. First input table containing the text to compare. #' @param data_dt_2 data.table. Second input table containing the text to compare. #' @param text_column character(1). Name of the text column present in both #' tables. Default: "text". #' @param grouping_columns character vector or NULL. Column names used to #' group/match rows between the two tables before computing distances. Only #' columns present in both tables will be used; if no common grouping columns #' remain, the function stops with an error. #' @param id_col_1 character(1). Name of the identifier column in data_dt_1 to #' include in the output. If the named column does not exist, a sequential #' integer id is created for data_dt_1. Default: "id". #' @param id_col_2 character(1). Name of the identifier column in data_dt_2 to #' include in the output. If the named column does not exist, a sequential #' integer id is created for data_dt_2. Default: "id". #' @param distance_method character(1). Distance metric passed to #' stringdist::stringdist (e.g. "osa", "lv", "dl", "hamming", etc.). Default: #' "osa". #' @param normalize logical(1). If TRUE, a \code{normalized_distance} column is #' added equal to \code{distance / max(nchar(text1), nchar(text2))}. If both #' strings are empty the normalized distance will be NA. Default: TRUE. #' @param keep_one_to_one logical(1). If TRUE, any id from either table that #' participates in more than one pair is removed from the result (keeps only #' strict one-to-one matches). Default: TRUE. #' #' @details #' - The function performs an inner merge (cartesian allowed) between #' \code{data_dt_1} and \code{data_dt_2} on the selected \code{grouping_columns}. #' Only rows that share the same values for all grouping columns are compared. #' - Text columns are internally renamed to \code{text1} and \code{text2} for #' computation; returned results include those columns alongside the id and #' grouping columns. #' - If no candidate pairs exist after grouping, the function calls #' \code{cli::cli_alert_info("No titles to compare found.")} and returns #' \code{invisible(NULL)}. #' - Inputs are copied with \code{data.table::copy()} so the originals are not #' modified. #' #' @return A data.table (or NULL if no pairs) with one row per compared pair. #' Typical columns (if present) are: #' - the two id columns (named according to \code{id_col_1} and \code{id_col_2}), #' - the chosen \code{grouping_columns}, #' - \code{text1} and \code{text2} (the text values compared), #' - \code{distance} (numeric; raw string distance from \code{stringdist}), #' - \code{normalized_distance} (numeric; present when \code{normalize = TRUE}). #' The result is ordered ascending by \code{normalized_distance} (if present) #' or by \code{distance} otherwise. #' #' @note #' - The function depends on the data.table and stringdist packages and uses #' cartesian joins to generate all cross-group pairs before distance #' calculation. For very large groups this can produce many pairwise #' comparisons and use substantial memory/time. #' - The \code{distance_method} argument is forwarded directly to #' \code{stringdist::stringdist}; consult that function's documentation for #' available methods and their behaviour. #' #' @examples #' if (requireNamespace("data.table", quietly = TRUE)) { #' library(data.table) #' dt1 <- data.table(id = 1:3, journal = c("A", "A", "B"), #' text = c("hello world", "foo bar", "lorem")) #' dt2 <- data.table(id = 10:12, journal = c("A", "A", "B"), #' text = c("helo world", "foobar", "ipsum")) #' # Compare only within the same journal #' res <- find_duplicates(dt1, dt2, text_column = "text", grouping_columns = "journal") #' print(res) #' } #' #' @export find_duplicated_text <- function( data_dt_1, data_dt_2, text_column = "text", grouping_columns = NULL, id_col_1 = "id", id_col_2 = "id", distance_method = "osa", normalize = TRUE, keep_one_to_one = TRUE ) { # Validate inputs stopifnot(is.data.table(data_dt_1), is.data.table(data_dt_2)) grouping_columns <- intersect( grouping_columns, intersect(names(data_dt_1), names(data_dt_2)) ) if (length(grouping_columns) == 0) { stop("No common grouping columns found between the two tables.") } if ( !text_column %in% names(data_dt_1) || !text_column %in% names(data_dt_2) ) { stop("text_column must exist in both data tables.") } # Prepare temporary copies to avoid modifying originals dt1 <- copy(data_dt_1) dt2 <- copy(data_dt_2) # Ensure id columns exist setnames(dt1, old = id_col_1, new = "id_1", skip_absent = TRUE) if (!"id_1" %in% names(dt1)) { dt1[, id_1 := seq_len(.N)] } setnames(dt2, old = id_col_2, new = "id_2", skip_absent = TRUE) if (!"id_2" %in% names(dt2)) { dt2[, id_2 := seq_len(.N)] } # keep only necessary columns dt1 <- dt1[, .SD, .SDcols = c("id_1", grouping_columns, text_column)] dt2 <- dt2[, .SD, .SDcols = c("id_2", grouping_columns, text_column)] # Merge on grouping columns to restrict comparisons merged <- merge( dt1, dt2, by = grouping_columns, suffixes = c("_1", "_2"), all = FALSE, allow.cartesian = TRUE ) # If no pairs, return empty table with expected cols if (nrow(merged) == 0L) { cli_alert_info("No titles to compare found.") return(invisible(NULL)) } # Extract texts (account for suffixing) txt1_name <- paste0(text_column, "_1") txt2_name <- paste0(text_column, "_2") setnames(merged, c(txt1_name, txt2_name), c("text1", "text2")) # Compute distances merged[, distance := stringdist::stringdist(text1, text2, method = distance_method) ] # Normalized distance (by max length); NA if both empty if (normalize) { merged[, normalized_distance := { l1 <- nchar(text1) l2 <- nchar(text2) denom <- pmax(l1, l2) denom[denom == 0] <- NA_real_ distance / denom } ] } # Remove rows with at least one NA in any grouping column merged <- na.omit(merged, cols = grouping_columns) # Optionally keep only one-to-one matches (remove ids with multiple matches) if (keep_one_to_one) { dup1 <- merged[, .N, by = "id_1"][N > 1, id_1] dup2 <- merged[, .N, by = "id_2"][N > 1, id_2] if (length(dup1) || length(dup2)) { merged <- merged[!id_1 %in% dup1 & !id_2 %in% dup2] } } # Keep and order relevant columns cols_keep <- c( "id_1", "id_2", grouping_columns, "text1", "text2", "distance" ) if (normalize) { cols_keep <- c(cols_keep, "normalized_distance") } cols_keep <- intersect(cols_keep, names(merged)) merged <- merged[, .SD, .SDcols = cols_keep] # Give back original id column names setnames(merged, old = "id_1", new = id_col_1, skip_absent = TRUE) setnames(merged, old = "id_2", new = id_col_2, skip_absent = TRUE) if (normalize) { merged <- merged[order(normalized_distance), ] } else { merged <- merged[order(distance), ] } return(merged) } normalize_title <- function(x) { x |> stringr::str_replace_all("&#x([0-9A-Fa-f]+);", function(m) { intToUtf8(strtoi(stringr::str_extract(m, "[0-9A-Fa-f]+"), base = 16L)) }) |> stringr::str_replace_all("\\s*&\\s*", " and ") |> stringr::str_to_lower() |> stringi::stri_trans_general("Latin-ASCII") |> stringr::str_remove("^the\\s+") |> stringr::str_remove_all("[[:punct:]]") |> stringr::str_squish() } #: Scopus Abstract Retrieval (FULL view) --------------------------- #' Version of the parsing of FULL records, stored in #' `abstract_query.parse_version` #' #' Bump it when `parsing_scopus_full_records.R` parses new fields: the records #' parsed by an earlier version are parsed again (from the JSON on disk, no #' request). #' - 1: authors, affiliations, abstract, author keywords; #' - 2 (October 2026): also language, funding, corresponding authors, #' indexed terms and subject areas (`parse_scopus_extra()`). full_record_parse_version <- 2L #' Path of the saved FULL record of an article #' #' @param scopus_id character. Scopus identifiers ("SCOPUS_ID:..."). #' @param json_dir character(1). Folder of the gzipped JSON records. #' @return The paths `/SCOPUS_ID_.json.gz`. abstract_json_file <- function( scopus_id, json_dir = file.path(data_path, "abstract_full_json") ) { file.path( json_dir, paste0(stringr::str_replace(scopus_id, "^SCOPUS_ID:", "SCOPUS_ID_"), ".json.gz") ) } # `read_gz_text()` and `write_gz_text()` (atomic write through a .tmp file) # come from the coRpusdb package (loaded in paths_and_packages.R). #' Download the FULL record of one article from the Scopus Abstract Retrieval API #' #' @param scopus_id character(1). Scopus identifier ("SCOPUS_ID:..." or digits). #' #' @details #' The FULL view holds the abstract, author keywords, authors with their #' affiliations and the complete reference list, in one request (the REF view #' needs one request per 40 references). Requires a global `api_key`. #' HTTP 401/403 (not on the institutional network) and 429 (weekly quota #' reached) stop with an error. Network errors and HTTP 5xx are retried 3 times. #' #' @return A list with `http_status` (NA on network error), `status` #' ("ok", "not_found" or "transient_error") and `json` (raw response text, #' NULL unless status is "ok"). fetch_abstract_full <- function(scopus_id, attempts = 3L) { url <- paste0( "https://api.elsevier.com/content/abstract/scopus_id/", stringr::str_remove(scopus_id, "^SCOPUS_ID:"), "?view=FULL" ) status <- NA_integer_ for (attempt in seq_len(attempts)) { response <- tryCatch( httr::GET( url, httr::add_headers("X-ELS-APIKey" = api_key, "Accept" = "application/json"), httr::timeout(30) ), error = function(e) NULL ) status <- if (is.null(response)) NA_integer_ else httr::status_code(response) if (isTRUE(status == 200L)) { return(list( http_status = status, status = "ok", json = httr::content(response, as = "text", encoding = "UTF-8") )) } if (isTRUE(status %in% c(401L, 403L))) { cli::cli_abort( "HTTP {status} for {scopus_id}: not authorised (are you on the institutional network?)." ) } if (isTRUE(status == 429L)) { reset <- httr::headers(response)[["x-ratelimit-reset"]] reset_time <- if (is.null(reset)) { "unknown" } else { format(as.POSIXct(as.numeric(reset), origin = "1970-01-01")) } cli::cli_abort("HTTP 429: API quota reached. It resets on {reset_time}.") } if (isTRUE(status >= 400L & status < 500L)) { return(list(http_status = status, status = "not_found", json = NULL)) } Sys.sleep(attempt) } list(http_status = status, status = "transient_error", json = NULL) } #' Parse the reference list of a Scopus FULL record #' #' @param json character(1). Raw JSON returned by `fetch_abstract_full()`. #' @param scopus_id character(1). Scopus identifier of the citing article #' ("SCOPUS_ID:..."), stored in `citing_id`. #' #' @return A data.table with one row per reference: citing_id, position (order #' in the reference list), cited_id (Scopus ID of the cited document, #' "SCOPUS_ID:..."; documents not indexed in Scopus also get one), cited_doi, #' first_author, n_authors, title, source_title, year, volume, issue, #' first_page, last_page, raw_text (the reference as printed). Zero rows when #' the record has no reference list. parse_scopus_references <- function(json, scopus_id) { record <- jsonlite::fromJSON(json, simplifyVector = FALSE)$`abstracts-retrieval-response` references <- record$item$bibrecord$tail$bibliography$reference if (is.null(references)) { return(data.table::data.table()) } # A single reference comes as an object, several as an array if (!is.null(references$`ref-info`)) { references <- list(references) } as_list <- function(x) if (!is.null(names(x))) list(x) else x first_or_na <- function(x) if (is.null(x)) NA_character_ else as.character(x) data.table::rbindlist(lapply(references, function(ref) { info <- ref$`ref-info` ids <- as_list(info$`refd-itemidlist`$itemid) id_of <- function(type) { value <- unlist(lapply(ids, \(i) if (identical(i$`@idtype`, type)) i$`$`)) if (is.null(value)) NA_character_ else value[[1]] } authors <- as_list(info$`ref-authors`$author) voliss <- info$`ref-volisspag`$voliss pages <- info$`ref-volisspag`$pagerange sgr <- id_of("SGR") data.table::data.table( citing_id = scopus_id, position = as.integer(first_or_na(ref$`@id`)), cited_id = if (is.na(sgr)) NA_character_ else paste0("SCOPUS_ID:", sgr), cited_doi = id_of("DOI"), first_author = first_or_na(authors[[1]]$`ce:indexed-name`), n_authors = length(authors), title = first_or_na(info$`ref-title`$`ref-titletext`), source_title = first_or_na(info$`ref-sourcetitle`), year = as.integer(first_or_na(info$`ref-publicationyear`$`@first`)), volume = first_or_na(voliss$`@volume`), issue = first_or_na(voliss$`@issue`), first_page = first_or_na(pages$`@first`), last_page = first_or_na(pages$`@last`), raw_text = first_or_na(ref$`ref-fulltext` %||% ref$`ce:source-text`) ) })) } #' Parse authors and affiliations of a Scopus FULL record #' #' @param json character(1). Raw JSON returned by `fetch_abstract_full()`. #' @param scopus_id character(1). Scopus identifier of the article. #' #' @details #' Two parts of the record are used: #' - `authors`: Scopus author ID (`auid`) and names of each author, and the #' Scopus affiliation IDs (`afid`) of the author; #' - `item$bibrecord$head$author-group`: the affiliations as printed in the #' article (organisation parts such as department and university, city, #' country), each with its `afid` when Scopus matched it, and the authors #' who share it. #' Author-affiliation links come from the author groups; authors absent from #' every group fall back on the `afid`s of the `authors` part. #' #' @return A list of three data.tables: #' - `author`: scopus_id, author_seq, auid, indexed_name, surname, given_name; #' - `author_affiliation`: scopus_id, author_seq, auid, afid, organization #' (printed parts joined by "; "), city, country (as printed); #' - `affiliation`: afid, name, city, country (Scopus affiliation profiles). parse_scopus_authors <- function(json, scopus_id) { record <- jsonlite::fromJSON(json, simplifyVector = FALSE)$`abstracts-retrieval-response` as_list <- function(x) { if (is.null(x)) list() else if (!is.null(names(x))) list(x) else x } chr <- function(x) if (is.null(x)) NA_character_ else as.character(x) # * Authors (top-level list, the reference for names and auid) authors <- as_list(record$authors$author) author <- data.table::rbindlist(lapply(authors, function(a) { data.table::data.table( scopus_id = scopus_id, author_seq = as.integer(chr(a$`@seq`)), auid = chr(a$`@auid`), indexed_name = chr(a$`ce:indexed-name`), surname = chr(a$`ce:surname` %||% a$`preferred-name`$`ce:surname`), given_name = chr(a$`ce:given-name` %||% a$`preferred-name`$`ce:given-name`) ) })) author <- unique(author, by = "author_seq") # * Scopus affiliation profiles profiles <- as_list(record$affiliation) affiliation <- data.table::rbindlist(lapply(profiles, function(p) { data.table::data.table( afid = chr(p$`@id`), name = chr(p$affilname), city = chr(p$`affiliation-city`), country = chr(p$`affiliation-country`) ) })) affiliation <- data.table::rbindlist( list( data.table::data.table( afid = character(), name = character(), city = character(), country = character() ), affiliation ) ) affiliation <- unique(affiliation[!is.na(afid)], by = "afid") # * Printed affiliations of the author groups groups <- as_list(record$item$bibrecord$head$`author-group`) author_affiliation <- data.table::rbindlist(lapply(groups, function(g) { aff <- g$affiliation group_authors <- as_list(g$author) if (length(group_authors) == 0L || is.null(aff)) { return(NULL) } organization <- vapply( as_list(aff$organization), \(o) if (is.list(o)) chr(o$`$`) else chr(o), character(1) ) data.table::data.table( scopus_id = scopus_id, author_seq = vapply(group_authors, \(a) as.integer(chr(a$`@seq`)), integer(1)), afid = chr(aff$`@afid`), organization = if (length(organization) > 0L) { paste(organization, collapse = "; ") } else { chr(aff$`ce:source-text`) }, city = chr(aff$city), country = chr(aff$country) ) })) # * Authors in no group: affiliation IDs of the top-level list in_groups <- if (nrow(author_affiliation) > 0L) author_affiliation$author_seq else integer() fallback <- data.table::rbindlist(lapply(authors, function(a) { seq <- as.integer(chr(a$`@seq`)) afids <- unique(vapply(as_list(a$affiliation), \(x) chr(x$`@id`), character(1))) if (seq %in% in_groups || length(afids) == 0L) { return(NULL) } data.table::data.table( scopus_id = scopus_id, author_seq = seq, afid = afids, organization = NA_character_, city = NA_character_, country = NA_character_ ) })) author_affiliation <- data.table::rbindlist( list( data.table::data.table( scopus_id = character(), author_seq = integer(), afid = character(), organization = character(), city = character(), country = character() ), author_affiliation, fallback ), fill = TRUE ) author_affiliation <- unique(author_affiliation) author_affiliation[, auid := NA_character_] if (nrow(author) > 0L) { author_affiliation[author, auid := i.auid, on = "author_seq"] } data.table::setcolorder( author_affiliation, c("scopus_id", "author_seq", "auid", "afid", "organization", "city", "country") ) # * afids of the author groups without a profile in the top-level list (a # few old records): the printed affiliation stands in for the profile, so # that every `author_affiliation.afid` has a row in `affiliation` missing_profiles <- unique( author_affiliation[!is.na(afid) & !afid %in% affiliation$afid], by = "afid" ) if (nrow(missing_profiles) > 0L) { affiliation <- data.table::rbindlist(list( affiliation, missing_profiles[, .(afid, name = organization, city, country)] )) } list( author = author, author_affiliation = author_affiliation, affiliation = affiliation ) } #' Parse the abstract and author keywords of a Scopus FULL record #' #' @param json character(1). Raw JSON returned by `fetch_abstract_full()`. #' @param scopus_id character(1). Scopus identifier of the article. #' #' @details #' The abstract is `coredata$dc:description`. Older records end it with the #' copyright line ("© 1991.", "© 1997 Elsevier Science S.A.") or "-Author"; #' these endings are removed. #' #' @return A one-row data.table: scopus_id, abstract (NA if none), #' author_keywords (keywords joined by "; ", NA if none). parse_scopus_abstract <- function(json, scopus_id) { record <- jsonlite::fromJSON(json, simplifyVector = FALSE)$`abstracts-retrieval-response` abstract <- record$coredata$`dc:description` abstract <- if (is.null(abstract)) { NA_character_ } else { abstract |> stringr::str_remove("\\s*(©|\\([Cc]\\)|Copyright)[^©]{0,200}$") |> stringr::str_remove("\\s*-\\s*Authors?\\.?$") |> stringr::str_squish() } if (isTRUE(abstract == "")) { abstract <- NA_character_ } keywords <- record$authkeywords$`author-keyword` if (!is.null(names(keywords))) { keywords <- list(keywords) } keywords <- unlist(lapply(keywords, \(k) if (is.list(k)) k$`$` else k)) data.table::data.table( scopus_id = scopus_id, abstract = abstract, author_keywords = if (length(keywords) > 0L) { paste(keywords, collapse = "; ") } else { NA_character_ } ) } #' Parse language, funding, correspondence, indexed terms and subject areas of #' a Scopus FULL record #' #' @param json character(1). Raw JSON returned by `fetch_abstract_full()`. #' @param scopus_id character(1). Scopus identifier of the article. #' #' @details #' Where the fields are in the record (checked on ~1,800 records, October 2026): #' - `language$@xml:lang` (ISO 639-2 code, e.g. "eng"; several languages come #' as an array), with `head$citation-info$citation-language` as fallback; #' - `item$xocs:meta$xocs:funding-list`: one `xocs:funding` per funder, with #' the string found in the article (`matched-string`), and, when Elsevier #' matched it to its funder registry, the funder's name, acronym, registry #' URI and country (GeoNames URI); `xocs:funding-id` holds grant numbers. #' `xocs:funding-text` is the funding statement as printed. Funding data #' were added by Elsevier in 2021 to records of every age, but are rare #' before the 2000s; #' - `head$correspondence` (object, or array when several corresponding #' authors): the person, the printed affiliation and, in recent records, #' an e-mail (`ce:e-address`, `@type` "email"); #' - `idxterms$mainterm`: controlled terms indexed by Scopus (rare in #' economics: mostly for journals also indexed in Compendex or GEOBASE); #' - `subject-areas$subject-area`: ASJC subject areas. In Scopus they are #' assigned to the *source* (journal), so they mostly repeat #' `journal.subject_codes`. #' #' @return A list of data.tables: #' - `info`: one row, scopus_id, language, funding_text; #' - `funding`: scopus_id, funding_seq, matched_string, agency, #' agency_acronym, agency_id, agency_country, grant_id (several grant #' numbers joined by "; "); #' - `correspondence`: scopus_id, corresp_seq, indexed_name, surname, #' given_name, email, organization, city, country; #' - `indexed_term`: scopus_id, term, weight, candidate; #' - `subject_area`: scopus_id, code, abbrev, name. parse_scopus_extra <- function(json, scopus_id) { record <- jsonlite::fromJSON(json, simplifyVector = FALSE)$`abstracts-retrieval-response` as_list <- function(x) { if (is.null(x)) list() else if (!is.null(names(x))) list(x) else x } chr <- function(x) if (is.null(x)) NA_character_ else as.character(x) # Several values (array or `$` objects) joined by "; ", NA if none collapse <- function(x) { values <- unlist(lapply(as_list(x), \(v) if (is.list(v)) v$`$` else v)) if (length(values) == 0L) NA_character_ else paste(unique(values), collapse = "; ") } head <- record$item$bibrecord$head # * Language: record level first, citation-info as fallback language <- collapse(lapply(as_list(record$language), \(l) l$`@xml:lang`)) if (is.na(language)) { language <- collapse(lapply( as_list(head$`citation-info`$`citation-language`), \(l) l$`@xml:lang` )) } # * Funding funding_list <- record$item$`xocs:meta`$`xocs:funding-list` funding <- data.table::rbindlist(lapply( seq_along(as_list(funding_list$`xocs:funding`)), function(i) { f <- as_list(funding_list$`xocs:funding`)[[i]] # A few records give the funder as a bare string instead of an object if (!is.list(f)) f <- list(`xocs:funding-agency-matched-string` = f) data.table::data.table( scopus_id = scopus_id, funding_seq = i, matched_string = chr(f$`xocs:funding-agency-matched-string`), agency = chr(f$`xocs:funding-agency`), agency_acronym = chr(f$`xocs:funding-agency-acronym`), agency_id = chr(f$`xocs:funding-agency-id`), agency_country = chr(f$`xocs:funding-agency-country`), grant_id = collapse(f$`xocs:funding-id`) ) } )) funding_text <- collapse(funding_list$`xocs:funding-text`) # * Corresponding authors. The e-mail may sit in the correspondence block # or in the person: search the whole block for e-addresses of type "email". find_emails <- function(x) { if (!is.list(x)) { return(character()) } here <- if (!is.null(x$`ce:e-address`)) { unlist(lapply(as_list(x$`ce:e-address`), function(e) { if (is.list(e) && !identical(e$`@type`, "url")) e$`$` else if (!is.list(e)) e })) } c(here, unlist(lapply(x[names(x) != "ce:e-address"], find_emails))) } correspondence <- data.table::rbindlist(lapply( seq_along(as_list(head$correspondence)), function(i) { cor <- as_list(head$correspondence)[[i]] person <- cor$person aff <- cor$affiliation organization <- collapse(aff$organization) emails <- unique(find_emails(cor)) data.table::data.table( scopus_id = scopus_id, corresp_seq = i, indexed_name = chr(person$`ce:indexed-name`), surname = chr(person$`ce:surname`), given_name = chr(person$`ce:given-name`), email = if (length(emails) > 0L) paste(emails, collapse = "; ") else NA_character_, organization = if (is.na(organization)) chr(aff$`ce:source-text`) else organization, city = chr(aff$city %||% aff$`city-group`), country = chr(aff$country) ) } )) # * Indexed terms and subject areas indexed_term <- data.table::rbindlist(lapply( as_list(record$idxterms$mainterm), function(t) { data.table::data.table( scopus_id = scopus_id, term = chr(t$`$`), weight = chr(t$`@weight`), candidate = chr(t$`@candidate`) ) } )) subject_area <- data.table::rbindlist(lapply( as_list(record$`subject-areas`$`subject-area`), function(s) { data.table::data.table( scopus_id = scopus_id, code = chr(s$`@code`), abbrev = chr(s$`@abbrev`), name = chr(s$`$`) ) } )) list( info = data.table::data.table( scopus_id = scopus_id, language = language, funding_text = funding_text ), funding = funding, correspondence = correspondence, indexed_term = unique(indexed_term), subject_area = unique(subject_area) ) } #: Read-only snapshot of the database --------------------------- # While a script writes to scopus.duckdb, no other process can open it, even # read-only. Writing scripts therefore keep a copy, `scopus_snapshot.duckdb`, # next to the database: refreshed at their start and every few hours, and # removed at their end, when the database itself is free again. # The copy is a btrfs "reflink" (copy-on-write clone): it shares its disk # blocks with the database and costs no space when it is made. It grows only # as the database is rewritten (at most the size of the database), and each # refresh resets it. On a file system without reflinks the copy would double # the disk space, so it is skipped unless `allow_full_copy = TRUE`. # The snapshot functions are thin wrappers around coRpusdb (`db_snapshot_path()`, # `db_refresh_snapshot()`, `db_remove_snapshot()`, `db_connect_read_only()`), # which implement the same logic; the wrappers keep this project's defaults # (`db_path`), its option `scopus.snapshot` and its environment variable # `SCOPUS_DUCKDB`, so that the scripts need no change. #' Path of the snapshot of a database file snapshot_path <- function(main_path = db_path) { db_snapshot_path(main_path) } #' Refresh the read-only snapshot from a writing connection #' #' @param con DBI connection that writes to `main_path` (no open transaction). #' @param main_path character(1). The database file. #' @param min_interval_hours numeric(1). Do nothing if the snapshot is younger #' than this (0: always refresh). Lets a loop call it after every batch. #' @param allow_full_copy logical(1). Copy the file when reflinks are not #' supported (doubles the disk space). #' @return TRUE (invisibly) if the snapshot was refreshed. refresh_snapshot <- function( con, main_path = db_path, min_interval_hours = 0, allow_full_copy = FALSE ) { if (!isTRUE(getOption("scopus.snapshot", TRUE))) { return(invisible(FALSE)) } db_refresh_snapshot( con, main_path, min_interval_hours = min_interval_hours, allow_full_copy = allow_full_copy ) } #' Remove the snapshot (at the end of a writing script) remove_snapshot <- function(main_path = db_path) { db_remove_snapshot(main_path) } #' Open the database read-only, or its snapshot when a script is writing #' #' @param main_path character(1). The database file. The environment variable #' SCOPUS_DUCKDB, when set, overrides it (and no fallback is attempted). #' @return A DBI connection (read-only). DuckDB's memory is capped by #' coRpusdb (option `coRpusdb.memory_limit`, 6 GB by default). connect_read_only <- function(main_path = db_path) { forced <- Sys.getenv("SCOPUS_DUCKDB", "") db_connect_read_only( resolve_db_path(main_path, env_var = "SCOPUS_DUCKDB"), snapshot = !nzchar(forced) ) }