#: Evaluating the classification of the paragraphs (`text.type_text`) --------- # Script goals: # * Measure how well `clean_fulltext_paragraphs()` (functions.R) types the # paragraphs of the Elsevier XML (`main_text`, `footnote`, `front_matter`, # `appendix`, `references`, `table_figure`), and how well-formed the text # of the paragraphs is (merged cells, garbled text...). # * Two stages (see the protocol of the `building-document-databases` skill): # - stage 1, diagnostic: a seeded sample, stratified by type and by the # rule that produced it, is labelled blind by Haiku (Claude subagents); # the disagreements with the code show the error patterns to fix. The # sample is disposable: draw a new one (new seed) after each change of # the extraction version; # - stage 2, measurement: one frozen gold sample, labelled independently # by the user and by Haiku with the same rubric; agreement (Cohen's # kappa), adjudication, then accuracy and per-type precision/recall with # Wilson intervals against the reconciled labels. # # Setup: # * Reads `scopus.duckdb` through `connect_read_only()` (works during a run # of a writing script, on the snapshot). # * The judges follow `resources/text_type_rubric.md`; keep it unchanged # during a stage. # # Inputs: `text`, `article`, `journal`, `xml_download`. # Outputs, in `/evaluation/text_type/v/`: # * `stage1_sample_text_type_v.csv`: the sample with the code's label # (`type_text`) and the strata; # * `stage1_judge_text_type_v_chunkNN.csv`: the same items for the # judge, without the code's label (blind labelling); # * the judges write `stage1_verdicts_text_type_v_chunkNN.csv` # (item_id, judge_type, judge_quality, reason); # * `stage1_summary_text_type_v.csv`: accuracy by stratum, once the # verdicts exist. # Stage 2 writes `resources/text_type_gold_v_.csv`, with empty # `user_type`, `user_quality`, `comment` columns for the user; the script # never overwrites it. In `/evaluation/text_type/v/`: # * `stage2_code_labels_v.csv`: the code's label of each item, kept # apart so that both judges label blind; # * `stage2_population_v.csv`: paragraphs in the database per # stratum x period, the weights of the estimates; # * `stage2_judge_text_type_v_chunkNN.csv`: the same items for the # Haiku judges, who write `stage2_verdicts_text_type_v_chunkNN.csv`; # * `stage2_adjudication_v.csv`: the items where the user and Haiku # disagree, with an empty `final_type` to fill (written once both have # labelled, never overwritten); # * `stage2_metrics_v.csv`: accuracy, precision and recall by type, # once the adjudication is complete. # # How it works: # 1. Statistics over the whole table: share of the characters by type, by # Elsevier document kind and by period; documents whose main text is a # minority of the text (a sign of misclassification). # 2. Sample: `n_by_stratum` items per stratum, a stratum being a type # crossed with the rule that produced it (e.g. `main_text` with or # without section title), each spread evenly over three periods (before # 2000, 2000-2014, 2015 and after) because the XML schema changed over # time. The rare and uncertain strata (untitled paragraphs, appendix by # title) are over-represented on purpose: the sample diagnoses, it does # not estimate shares. # 3. Context for the judge: journal, year, document kind, title, section # path, position, previous and next paragraphs. # 4. Aggregation, when verdicts exist: confusion matrix (code vs judge), # agreement by stratum, list of the disagreements to read. # 5. Stage 2 only, step by step as the labels come in: agreement between # the user and Haiku (Cohen's kappa), adjudication of their # disagreements, then the metrics of the code against the reconciled # labels (see the section for the estimators). #: Setup & parameters --------- source("scripts/paths_and_packages.R") source("scripts/functions.R") # connect_read_only(), text_extraction_version eval_stage <- "stage2" # "stage1" (Haiku, diagnostic) or "stage2" (gold sample) # Change the seed to draw a fresh stage-1 sample. Stage 1: round 1 (v2) # 20261023, round 2 (v3) 20261024, round 3 (v4) 20261025. Stage 2 (v4): # 20261101, a seed never used in stage 1. Stage 1 round 4 (v4, a check of # the stability of the score): 20261102. Before a new round on the same # version, move the files of the previous one to `stage1_round/`. seed <- 20261102 n_by_stratum <- 15L # items per stratum (10 strata: ~150 items) n_chunks <- 4L # judge files (one Haiku subagent per file) text_max <- 1200L # characters of the paragraph shown to the judge context_max <- 300L # characters of the previous and next paragraphs version <- text_extraction_version eval_dir <- file.path(data_path, "evaluation", "text_type", paste0("v", version)) dir.create(eval_dir, recursive = TRUE, showWarnings = FALSE) types <- c("main_text", "footnote", "front_matter", "appendix", "references", "table_figure") con <- connect_read_only() #: 1. Statistics over the whole table --------- cli_h1("Share of the characters by type (extraction version {version})") # One row per document: characters by type, with the document kind # (Elsevier `pub_type`) and the period of publication by_doc <- as.data.table(dbGetQuery( con, 'SELECT t.scopus_id, x.pub_type, CASE WHEN year(a.prism_cover_date::DATE) < 2000 THEN \'<2000\' WHEN year(a.prism_cover_date::DATE) < 2015 THEN \'2000-2014\' ELSE \'2015+\' END AS period, t.type_text, sum(length(t.text)) AS chars FROM "text" t JOIN article a USING (scopus_id) JOIN xml_download x USING (scopus_id) GROUP BY ALL' )) by_doc <- dcast(by_doc, scopus_id + pub_type + period ~ type_text, value.var = "chars", fill = 0) for (t in setdiff(types, names(by_doc))) set(by_doc, j = t, value = 0) by_doc[, total := rowSums(.SD), .SDcols = types] # The references are left out of the denominator of `main_minority`: a short # comment with a long reference list is not a misclassification by_doc[, main_minority := main_text < 0.5 * (total - references)] shares <- by_doc[, c( list(documents = .N), lapply(.SD, \(x) round(sum(x) / sum(total), 3)), list(main_minority = round(mean(main_minority), 3)) ), by = .(pub_type, period), .SDcols = types ][documents >= 50][order(pub_type, period)] print(shares, nrows = 100) cli_alert_info( "{sum(by_doc$main_minority)} document{?s} ({round(100 * mean(by_doc$main_minority), 1)}%) have less main text than other text (references aside)." ) #: 2. Sample --------- # Strata: a type crossed with the rule that produced it. The rule is # recovered from the stored columns: an untitled paragraph has a NULL # `section`; `no_section` marks the body of an article without titled # sections; an appendix paragraph whose section title does not say # "appendix" comes from the `ce:appendices` element of the XML. stratum_sql <- " CASE WHEN t.type_text = 'main_text' AND t.section = 'no_section' THEN 'main_text:no_section' WHEN t.type_text = 'main_text' AND t.section IS NULL THEN 'main_text:untitled' WHEN t.type_text = 'main_text' THEN 'main_text:titled' WHEN t.type_text = 'front_matter' AND t.section IS NULL THEN 'front_matter:untitled' WHEN t.type_text = 'front_matter' THEN 'front_matter:titled' WHEN t.type_text = 'appendix' AND regexp_matches(t.section, '(?i)appendi|supplementary') THEN 'appendix:by_title' WHEN t.type_text = 'appendix' THEN 'appendix:in_appendices' ELSE t.type_text END" # Seeded draw inside DuckDB: `hash(seed || scopus_id || paragraph_id)` gives a # reproducible random order (R's set.seed() does not reach DuckDB); the # first `n_by_stratum / 3` rows of each stratum x period are kept. n_by_cell <- ceiling(n_by_stratum / 3) # A few extra rows are drawn per cell, so that the two stages never share a # paragraph: the gold sample leaves out every paragraph judged in a stage-1 # round of the same version (the code was tuned on them), and a stage-1 # round leaves out the gold paragraphs (tuning the code on them would bias # the measure) n_draw <- n_by_cell + 5L sample_rows <- as.data.table(dbGetQuery( con, glue( 'WITH t AS ( SELECT t.*, {stratum_sql} AS stratum, CASE WHEN year(a.prism_cover_date::DATE) < 2000 THEN \'<2000\' WHEN year(a.prism_cover_date::DATE) < 2015 THEN \'2000-2014\' ELSE \'2015+\' END AS period FROM "text" t JOIN article a USING (scopus_id) ), ranked AS ( SELECT *, row_number() OVER ( PARTITION BY stratum, period ORDER BY hash(\'{seed}\' || scopus_id || paragraph_id) ) AS draw FROM t ) SELECT scopus_id, paragraph_id, stratum, period, type_text FROM ranked WHERE draw <= {n_draw}' ) )) # Stage-1 samples of the version, including earlier rounds moved to # `stage1_round/` subfolders stage1_files <- list.files(eval_dir, "^stage1_sample_text_type_.*\\.csv$", recursive = TRUE, full.names = TRUE) gold_files <- list.files("resources", glue("^text_type_gold_v{version}_.*\\.csv$"), full.names = TRUE) excluded <- rbindlist(lapply( if (eval_stage == "stage2") stage1_files else gold_files, \(f) fread(f)[, .(scopus_id, paragraph_id)] )) if (nrow(excluded) > 0L) { sample_rows <- sample_rows[!excluded, on = .(scopus_id, paragraph_id)] } sample_rows <- sample_rows[order(stratum, period)][, head(.SD, n_by_cell), by = .(stratum, period)] cli_alert_info("{nrow(sample_rows)} paragraphs drawn over {uniqueN(sample_rows$stratum)} strata.") print(sample_rows[, .N, by = .(stratum, period)][order(stratum, period)], nrows = 100) # Population of each cell: the sample over-represents the rare strata, so # the stage-2 estimates weight each item by the number of paragraphs its # cell stands for (N_cell / n_cell) population <- as.data.table(dbGetQuery( con, glue( 'SELECT {stratum_sql} AS stratum, CASE WHEN year(a.prism_cover_date::DATE) < 2000 THEN \'<2000\' WHEN year(a.prism_cover_date::DATE) < 2015 THEN \'2000-2014\' ELSE \'2015+\' END AS period, count(*) AS n_population FROM "text" t JOIN article a USING (scopus_id) GROUP BY ALL' ) )) #: 3. Context for the judge --------- # The whole documents of the sample are read once, to get the neighbours and # the position of each drawn paragraph duckdb::duckdb_register(con, "tmp_sample_ids", unique(sample_rows[, .(scopus_id)])) docs <- as.data.table(dbGetQuery( con, 'SELECT t.scopus_id, t.paragraph_id, t.text, t.section_path, t.section, t.section_number FROM "text" t JOIN tmp_sample_ids USING (scopus_id) ORDER BY t.scopus_id, t.paragraph_id' )) meta <- as.data.table(dbGetQuery( con, 'SELECT a.scopus_id, j.dc_title AS journal, year(a.prism_cover_date::DATE) AS year, x.pub_type, a.dc_title AS title FROM article a JOIN journal j USING (source_id) JOIN xml_download x USING (scopus_id) JOIN tmp_sample_ids USING (scopus_id)' )) duckdb::duckdb_unregister(con, "tmp_sample_ids") dbDisconnect(con, shutdown = TRUE) cut_text <- function(x, n) { fifelse(is.na(x), "", fifelse(nchar(x) > n, paste0(substr(x, 1, n), " [...]"), x)) } docs[, `:=`( n_paragraphs = .N, prev_text = cut_text(shift(text, 1L), context_max), next_text = cut_text(shift(text, -1L), context_max) ), by = scopus_id] items <- docs[sample_rows, on = .(scopus_id, paragraph_id)][meta, on = "scopus_id", nomatch = NULL] items[, `:=`( position = paste(paragraph_id, "of", n_paragraphs), # `section_path` is NULL for the blocks that are not sections # (acknowledgments, bibliography): their title is then in `section` section_shown = fcoalesce(section_path, fifelse(section == "no_section", NA_character_, section), ""), # The printed number of the section ("Appendix A", "3.2"): a reader sees # it, and the title alone does not show that a section is an appendix section_label = fcoalesce(section_number, ""), text = cut_text(text, text_max) )] # Items in random order (seeded), so that a judge does not see the strata. # Sorted first: DuckDB returns rows in no fixed order, and the shuffle must # give the same item ids at every run setorder(items, scopus_id, paragraph_id) set.seed(seed) items <- items[sample(.N)] items[, item_id := sprintf("v%d_%s_%03d", version, eval_stage, seq_len(.N))] judge_cols <- c( "item_id", "journal", "year", "pub_type", "title", "section_label", "section_shown", "position", "prev_text", "text", "next_text" ) #: 4. Write the sample and the judge files --------- if (eval_stage == "stage1") { sample_file <- file.path(eval_dir, glue("stage1_sample_text_type_v{version}.csv")) if (file.exists(sample_file)) { cli_alert_info("Stage-1 sample exists, kept: {.file {sample_file}} (delete it, or change `seed`, to draw a new one).") } else { fwrite( items[, c("item_id", "scopus_id", "paragraph_id", "stratum", "period", "type_text", judge_cols[-1]), with = FALSE], sample_file ) # Judge files: the same items without the code's label (blind labelling) items[, chunk := rep_len(seq_len(n_chunks), .N)] for (k in seq_len(n_chunks)) { fwrite( items[chunk == k, judge_cols, with = FALSE], file.path(eval_dir, sprintf("stage1_judge_text_type_v%d_chunk%02d.csv", version, k)) ) } cli_alert_success("Stage-1 sample and {n_chunks} judge files written to {.file {eval_dir}}.") } } gold_existing <- list.files("resources", glue("^text_type_gold_v{version}_.*\\.csv$"), full.names = TRUE) if (eval_stage == "stage2" && length(gold_existing) > 0L) { cli_alert_info("Gold sample exists, kept (it holds verdicts and is never overwritten): {.file {gold_existing}}.") } if (eval_stage == "stage2" && length(gold_existing) == 0L) { gold_file <- file.path("resources", glue("text_type_gold_v{version}_{format(Sys.Date(), '%Y%m%d')}.csv")) # No `stratum` here: it names the code's label, and the user labels blind gold <- items[, c("item_id", "scopus_id", "paragraph_id", "period", judge_cols[-1]), with = FALSE] gold[, `:=`(user_type = NA_character_, user_quality = NA_character_, comment = NA_character_)] fwrite(gold, gold_file) # The code's labels are kept apart, so that the user and Haiku label blind fwrite( items[, .(item_id, scopus_id, paragraph_id, stratum, period, type_text)], file.path(eval_dir, glue("stage2_code_labels_v{version}.csv")) ) fwrite(population, file.path(eval_dir, glue("stage2_population_v{version}.csv"))) # Haiku judges the same items, blind, with the same rubric items[, chunk := rep_len(seq_len(n_chunks), .N)] for (k in seq_len(n_chunks)) { fwrite( items[chunk == k, judge_cols, with = FALSE], file.path(eval_dir, sprintf("stage2_judge_text_type_v%d_chunk%02d.csv", version, k)) ) } cli_alert_success("Gold sample written: {.file {gold_file}} ({nrow(gold)} items), and {n_chunks} Haiku judge files in {.file {eval_dir}}.") } #: 5. Aggregate the stage-1 verdicts (when the judges have written them) --------- verdict_files <- list.files(eval_dir, "^stage1_verdicts_text_type_.*\\.csv$", full.names = TRUE) if (eval_stage == "stage1" && length(verdict_files) > 0L) { cli_h1("Stage-1 verdicts ({length(verdict_files)} file{?s})") sample_file <- file.path(eval_dir, glue("stage1_sample_text_type_v{version}.csv")) judged <- rbindlist(lapply(verdict_files, fread))[fread(sample_file), on = "item_id", nomatch = NULL] judged[, agree := judge_type == type_text] cli_h2("Code label (rows) x judge label (columns)") print(dcast(judged, type_text ~ judge_type, fun.aggregate = length, value.var = "item_id")) cli_h2("Agreement by stratum (judge `unsure` left out)") summary_tbl <- judged[judge_type != "unsure", .( items = .N, agree = sum(agree), share = round(mean(agree), 2), judge_said = paste(names(sort(table(judge_type[!agree]), decreasing = TRUE)), collapse = ", ") ), by = stratum][order(share)] print(summary_tbl) fwrite(summary_tbl, file.path(eval_dir, glue("stage1_summary_text_type_v{version}.csv"))) cli_h2("Text quality according to the judge") print(judged[, .N, by = .(judge_quality)][order(-N)]) print(judged[judge_quality != "ok", .N, by = .(judge_quality, stratum)][order(-N)]) cli_alert_info("{sum(judged$judge_type == 'unsure')} item{?s} judged `unsure`; {sum(!judged$agree & judged$judge_type != 'unsure')} disagreement{?s} to read.") } #: 6. Stage 2: agreement, adjudication, metrics --------- # Runs as far as the labels allow: # a. once the user has filled `user_type` and Haiku has written its # verdicts: agreement between the two judges (Cohen's kappa), and the # adjudication file listing their disagreements; # b. once `final_type` is filled in the adjudication file: the metrics of # the code against the reconciled labels. # # Estimators. The sample is stratified by the code's label and rule # (stratum) and by period (cell h), with n_h items drawn among N_h # paragraphs. Each item stands for w_i = N_h / n_h paragraphs, and # - accuracy = sum_i w_i 1[code_i = true_i] / sum_i w_i; # - precision of type k = the same ratio among the items the code labels k # (their strata only); # - recall of type k = sum_i w_i 1[code_i = k, true_i = k] / sum_i w_i # 1[true_i = k]: the paragraphs of type k the code labelled otherwise sit # in other strata, hence the weights. # 95% intervals: Wilson, computed on the weighted proportion with the # effective sample size n_eff = (sum w)^2 / sum w^2 (Kish), which shrinks # when the weights are unequal. Items labelled `unsure` by the reconciled # label are left out and counted. if (eval_stage == "stage2" && length(gold_existing) > 0L) { cli_h1("Stage 2: gold sample {.file {basename(gold_existing[1])}}") gold <- fread(gold_existing[1], na.strings = c("", "NA")) code <- fread(file.path(eval_dir, glue("stage2_code_labels_v{version}.csv"))) population <- fread(file.path(eval_dir, glue("stage2_population_v{version}.csv"))) verdict2_files <- list.files(eval_dir, "^stage2_verdicts_text_type_.*\\.csv$", full.names = TRUE) n_user <- sum(!is.na(gold$user_type)) cli_alert_info("User labels: {n_user}/{nrow(gold)}; Haiku verdict files: {length(verdict2_files)}/{n_chunks}.") if (n_user == nrow(gold) && length(verdict2_files) == n_chunks) { haiku <- rbindlist(lapply(verdict2_files, fread)) both <- gold[, .(item_id, user_type, user_quality, comment)][ haiku[, .(item_id, haiku_type = judge_type, haiku_quality = judge_quality, haiku_reason = reason)], on = "item_id" ] bad_labels <- both[!user_type %in% c(types, "unsure")] if (nrow(bad_labels) > 0L) { cli_abort("Unknown `user_type` for {nrow(bad_labels)} item{?s}: {head(bad_labels$item_id, 5)}.") } # Cohen's kappa: observed agreement corrected for the agreement two # judges would reach by chance with their own label frequencies, # kappa = (p_o - p_e) / (1 - p_e). Items where one judge is unsure are # left out (they are adjudicated anyway). k_items <- both[user_type != "unsure" & haiku_type != "unsure"] p_o <- mean(k_items$user_type == k_items$haiku_type) lv <- union(k_items$user_type, k_items$haiku_type) p_e <- sum(prop.table(table(factor(k_items$user_type, lv))) * prop.table(table(factor(k_items$haiku_type, lv)))) kappa <- (p_o - p_e) / (1 - p_e) cli_alert_info( "User vs Haiku on type: agreement {round(100 * p_o, 1)}% on {nrow(k_items)} items, Cohen's kappa = {round(kappa, 3)} ({nrow(both) - nrow(k_items)} item{?s} with an `unsure` left out)." ) print(dcast(both, user_type ~ haiku_type, fun.aggregate = length, value.var = "item_id")) # Adjudication: the items where the two judges differ (or one is # unsure), with the code's label hidden, so that the decision is made # on the text. Written once; the user fills `final_type`. adjudication_file <- file.path(eval_dir, glue("stage2_adjudication_v{version}.csv")) if (!file.exists(adjudication_file)) { to_adjudicate <- both[user_type != haiku_type | user_type == "unsure"][ gold[, c("item_id", judge_cols[-1]), with = FALSE], on = "item_id", nomatch = NULL ] to_adjudicate[, final_type := NA_character_] fwrite(to_adjudicate, adjudication_file) cli_alert_success("{nrow(to_adjudicate)} item{?s} to adjudicate: fill `final_type` in {.file {adjudication_file}}.") } adjudicated <- fread(adjudication_file, na.strings = c("", "NA")) if (all(!is.na(adjudicated$final_type))) { # Reconciled label: the common label when the judges agree, else the # adjudicated one both[, true_type := user_type] both[adjudicated, true_type := i.final_type, on = "item_id"] scored <- code[both, on = "item_id"] cli_alert_info("{sum(scored$true_type == 'unsure')} item{?s} left `unsure` after adjudication, left out of the metrics.") scored <- scored[true_type != "unsure"] # Weights: N_h / n_h for the cell (stratum x period) of the item cell_n <- code[, .(n_sample = .N), by = .(stratum, period)] scored <- population[cell_n, on = .(stratum, period)][scored, on = .(stratum, period)] scored[, w := n_population / n_sample] wilson <- function(p, n, z = 1.96) { centre <- (p + z^2 / (2 * n)) / (1 + z^2 / n) half <- z * sqrt(p * (1 - p) / n + z^2 / (4 * n^2)) / (1 + z^2 / n) c(low = max(0, centre - half), high = min(1, centre + half)) } estimate <- function(hit, w) { if (length(hit) == 0L) return(list(n = 0L, estimate = NA_real_, low = NA_real_, high = NA_real_)) p <- sum(w * hit) / sum(w) n_eff <- sum(w)^2 / sum(w^2) ci <- wilson(p, n_eff) list(n = length(hit), estimate = round(p, 4), low = round(ci[["low"]], 4), high = round(ci[["high"]], 4)) } metrics <- rbindlist(c( list(c(list(metric = "accuracy", type = "all"), estimate(scored$type_text == scored$true_type, scored$w))), lapply(types, \(k) c( list(metric = "precision", type = k), scored[type_text == k, estimate(true_type == k, w)] )), lapply(types, \(k) c( list(metric = "recall", type = k), scored[true_type == k, estimate(type_text == k, w)] )) )) cli_h2("Code against the reconciled labels (weighted by the population of each cell, Wilson 95% intervals)") print(metrics) fwrite(metrics, file.path(eval_dir, glue("stage2_metrics_v{version}.csv"))) cli_h2("Confusion matrix, unweighted counts (code in rows, reconciled label in columns)") print(dcast(scored, type_text ~ true_type, fun.aggregate = length, value.var = "item_id")) cli_h2("Text quality according to the user (unweighted)") print(scored[, .N, by = .(type_text, user_quality)][order(type_text, -N)]) } else { cli_alert_info("{sum(is.na(adjudicated$final_type))} item{?s} still to adjudicate in {.file {adjudication_file}}.") } } }