| |
|
|
| """ |
| Run this script as ./conversion_script.py to convert the BioCause dataset |
| DIRECTLY from its original brat-format annotation files, bypassing the |
| CREST aggregation (crest_v2.xlsx). CREST's own copy of BioCause has (a) |
| train only, 0 dev/test rows (a real CREST-source gap, not fixable by |
| adjusting causalatee's split logic), and (b) the same |
| idx/context character-offset misalignment already found and fixed for |
| CaTeRS, dropping some spans on conversion. |
| |
| Citation / original source |
| --------------------------- |
| Mihaila, C., Ohta, T., Pyysalo, S., & Ananiadou, S. (2013). "BioCause: |
| Annotating and analysing causality in the biomedical domain." BMC |
| Bioinformatics, 14, 2. https://doi.org/10.1186/1471-2105-14-2 |
| Corpus home: https://www.nactem.ac.uk/biocause/ |
| Direct download (verified working, no login): a zip archive at |
| https://www.nactem.ac.uk/biocause/download-biocause-corpus.php containing |
| one BioCause_corpus/ directory of paired .ann/.txt files (brat standoff), |
| one pair per section of a PMC Open-Access article's Discussion (also |
| includes TIAB/Introduction/Results sections for some articles) -- 198 |
| file pairs across 20 unique PMC article ids, verified directly. |
| |
| Format: brat standoff, built on top of a pre-existing BioNLP-ST 2011 |
| Infectious Diseases event/entity layer in the SAME .ann files (Organism, |
| Protein, Positive_regulation, Regulation, Gene_expression, ... -- ignored |
| here, we only want the Causality layer). Causal relations are event-style: |
| T<n> Causality <start> <end> <connective text, e.g. "resulting in"> |
| E<n> Causality:T<n> Cause:T<a> Effect:T<b> |
| E<n> Causality:T<n> Effect:T<b> Evidence:T<c> (no Cause -- common) |
| Cause/Effect/Evidence roles always reference a T-line directly (verified: |
| grepped the whole corpus for a role pointing at another E-line -- none |
| found), so no recursive event resolution is needed. ~18 T-line spans are |
| discontinuous (semicolon-joined offset pairs) -- preserved via |
| causalatee's multi-segment entity schema. |
| |
| Only 51 of 851 Causality events have an explicit Cause role; the other |
| 800 have Effect+Evidence with NO separate cause span at all -- the |
| causing participant is not marked as its own argument in those cases. |
| Causality-DETECTION uses all 851 (a sentence is causal if it contains ANY |
| Causality event, span or no span). Causal-candidate-extraction and |
| causality-IDENTIFICATION need an explicit (cause, effect) span pair, so |
| they only use the 51 Cause+Effect events -- a real, small, and worth |
| documenting limitation of this corpus, not an artefact of this script. |
| |
| No train/dev/test split exists upstream (checked: no filename in the |
| archive contains train/dev/test) -- CREST's own split was entirely |
| invented. This script creates its own deterministic split BY ARTICLE |
| (not by section) so sections of the same PMC article never end up split |
| across train/dev/test: 14 articles -> train, 3 -> dev, 3 -> test. |
| |
| Only 7 of the 20 articles contain any of the 51 Cause+Effect relations at |
| all (the other 13 have Effect+Evidence-only Causality events, which count |
| for detection but not identification/extraction -- see below). A first |
| version of this split just sorted article ids and sliced [:14]/[14:17]/ |
| [17:20] -- deterministic, but blind to where those 51 relations actually |
| live: alphabetically, ALL THREE of the last 3 article ids happen to be |
| relation-free, so causality-IDENTIFICATION's test split silently ended up |
| with 0 usable pairs (found the hard way: the dependency-baseline runner |
| crashed with "BioCause has no usable identification pairs"). Fixed by |
| `_assign_documents_to_splits`: a |
| deterministic greedy assignment that places the 20 articles (sorted by |
| relation count descending, ties by id) one at a time into whichever split |
| is currently furthest below its target relation share (train/dev/test's |
| 14/3/3 document-count ratio), so every split ends up with a reasonable, |
| non-zero share of the 51 relations (currently 28/12/11) while whole |
| articles still never cross a split boundary. |
| |
| Granularity: each row is a WHOLE SECTION (not a sentence). An earlier |
| version of this script cut each section into per-sentence rows (spaCy |
| boundaries, one row per sentence), but ~30 of BioCause's 851 Causality |
| events have a cause and/or effect span that references an ADJACENT |
| sentence rather than the one their trigger is in (discourse-level |
| causality, e.g. "X requires Y... [new sentence] This substitution |
| decreases Z") -- verified this really happens by inspecting real output. |
| A per-sentence schema can't represent such an event at all: either drop it |
| (losing ~30 real relations for no reason other than granularity) or |
| re-base it onto the wrong sentence's text (a real bug hit during that |
| attempt: a marker landing mid-word, "h<e1>istidine"). Keeping the whole |
| section as one unit sidesteps the tradeoff entirely -- every event's spans |
| are always within the row's text, nothing is dropped or corrupted. The |
| per-sentence view can still be derived on demand from this whole-section |
| data via causalatee's reusable |
| ``causalatee.data.utils.split_identification_to_sentences`` / |
| ``split_extraction_to_sentences`` utilities -- built specifically to |
| generalise the guard this script used to hand-roll. |
| """ |
|
|
| import io |
| import re |
| import urllib.request |
| import zipfile |
| from pathlib import Path |
|
|
| import pandas as pd |
|
|
| from causalatee.data.constants import ClassLabel, Relation, Task |
| from causalatee.data.utils import insert_entity_markers, verify_dataset |
|
|
| _ZIP_URL = "https://www.nactem.ac.uk/biocause/download-biocause-corpus.php" |
| _CACHE_DIR = Path(__file__).parent / ".cache" |
|
|
|
|
| def _fetch_corpus_dir() -> Path: |
| """Download + extract the BioCause zip once, cached under .cache/.""" |
| corpus_dir = _CACHE_DIR / "BioCause_corpus" |
| if corpus_dir.is_dir() and any(corpus_dir.iterdir()): |
| return corpus_dir |
| _CACHE_DIR.mkdir(parents=True, exist_ok=True) |
| with urllib.request.urlopen(_ZIP_URL) as resp: |
| data = resp.read() |
| with zipfile.ZipFile(io.BytesIO(data)) as zf: |
| zf.extractall(_CACHE_DIR) |
| return corpus_dir |
|
|
|
|
| def _parse_ann(ann_text: str) -> tuple[dict[str, list[tuple[int, int]]], dict[str, str], list[dict]]: |
| """Parse one .ann file. |
| |
| Returns (t_spans: T-line id -> segments, t_types: T-line id -> type, |
| causality_events: list of {"trigger": tid, "cause": tid|None, |
| "effect": tid|None} for every Causality-typed event). |
| """ |
| t_spans: dict[str, list[tuple[int, int]]] = {} |
| t_types: dict[str, str] = {} |
| for line in ann_text.splitlines(): |
| if not line.startswith("T"): |
| continue |
| tid, mid, _ = (line.split("\t", 2) + [""])[:3] |
| etype, offsets_str = mid.split(" ", 1) |
| segments = [tuple(int(x) for x in pair.split()) for pair in offsets_str.split(";")] |
| t_spans[tid] = sorted(segments) |
| t_types[tid] = etype |
|
|
| causality_events = [] |
| for line in ann_text.splitlines(): |
| if not line.startswith("E"): |
| continue |
| _, mid = line.split("\t", 1) |
| roles = mid.strip().split(" ") |
| trigger_role, trigger_tid = roles[0].split(":") |
| if trigger_role != "Causality": |
| continue |
| args = dict(r.split(":") for r in roles[1:] if ":" in r) |
| causality_events.append({ |
| "trigger": trigger_tid, |
| "cause": args.get("Cause"), |
| "effect": args.get("Effect"), |
| }) |
| return t_spans, t_types, causality_events |
|
|
|
|
| def _load_sections() -> list[dict]: |
| """One dict per .ann/.txt pair: {"doc_id", "text", "events": [...]}.""" |
| corpus_dir = _fetch_corpus_dir() |
| sections = [] |
| for ann_path in sorted(corpus_dir.glob("*.ann")): |
| txt_path = ann_path.with_suffix(".txt") |
| text = txt_path.read_text(encoding="utf-8") |
| t_spans, _, events = _parse_ann(ann_path.read_text(encoding="utf-8")) |
| doc_id = re.match(r"(PMC\d+)-", ann_path.stem).group(1) |
| resolved = [ |
| { |
| "cause_segments": t_spans[e["cause"]] if e["cause"] else None, |
| "effect_segments": t_spans[e["effect"]] if e["effect"] else None, |
| } |
| for e in events |
| if e["effect"] in t_spans and (e["cause"] is None or e["cause"] in t_spans) |
| ] |
| sections.append({"doc_id": doc_id, "text": text, "events": resolved}) |
| return sections |
|
|
|
|
| def _load_rows() -> list[dict]: |
| """One row per whole section, cached across the 3 convert_for_* calls. |
| |
| No sentence segmentation happens here at all -- every event's |
| cause/effect segments are already within the section's own text by |
| construction, so there is nothing to re-base and nothing to drop. |
| """ |
| if hasattr(_load_rows, "_cache"): |
| return _load_rows._cache |
|
|
| rows = [] |
| for section in _load_sections(): |
| segments: dict[str, list[tuple[int, int]]] = {} |
| relations = [] |
| for i, ev in enumerate(section["events"]): |
| effect_id = f"e{2 * i + 1}" |
| segments[effect_id] = ev["effect_segments"] |
| if ev["cause_segments"] is not None: |
| cause_id = f"e{2 * i + 2}" |
| segments[cause_id] = ev["cause_segments"] |
| relations.append({"relationship": Relation.Procausal, "first": cause_id, "second": effect_id}) |
| rows.append({"doc_id": section["doc_id"], "text": section["text"], |
| "relations": relations, "segments": segments}) |
|
|
| _load_rows._cache = rows |
| return rows |
|
|
|
|
| _SPLIT_DOC_CAPACITY = {"train": 14, "dev": 3, "test": 3} |
|
|
|
|
| def _assign_documents_to_splits(rows: list[dict]) -> dict[str, set[str]]: |
| """Deterministic greedy split assignment, balanced by relation count. |
| |
| Sorts articles by their number of Cause+Effect relations (descending, |
| ties broken by doc id), then assigns each one to whichever split still |
| has capacity and is currently furthest below its target relation share |
| (train/dev/test's document-count ratio) -- see module docstring for why |
| a plain sorted-id slice isn't good enough here. |
| """ |
| doc_relations: dict[str, int] = {} |
| for r in rows: |
| doc_relations[r["doc_id"]] = doc_relations.get(r["doc_id"], 0) + len(r["relations"]) |
|
|
| assigned: dict[str, set[str]] = {split: set() for split in _SPLIT_DOC_CAPACITY} |
| rel_totals = {split: 0 for split in _SPLIT_DOC_CAPACITY} |
| order = sorted(doc_relations, key=lambda d: (-doc_relations[d], d)) |
| for doc_id in order: |
| candidates = [s for s, cap in _SPLIT_DOC_CAPACITY.items() if len(assigned[s]) < cap] |
| best = min(candidates, key=lambda s: (rel_totals[s] / _SPLIT_DOC_CAPACITY[s], -_SPLIT_DOC_CAPACITY[s])) |
| assigned[best].add(doc_id) |
| rel_totals[best] += doc_relations[doc_id] |
| return assigned |
|
|
|
|
| def _split_by_document(rows: list[dict], split: str) -> list[dict]: |
| wanted = _assign_documents_to_splits(rows)[split] |
| return [r for r in rows if r["doc_id"] in wanted] |
|
|
|
|
| def convert_for_causality_detection(split: str) -> None: |
| rows = _split_by_document(_load_rows(), split) |
| df = pd.DataFrame([ |
| { |
| "index": f"biocause_{split}_{i}", |
| "text": r["text"], |
| "label": ClassLabel.Causal if r["relations"] or r["segments"] else ClassLabel.Uncausal, |
| } |
| for i, r in enumerate(rows) |
| ]).set_index("index") |
| for error in verify_dataset(df, Task.CausalityDetection): |
| print(f"WARNING [BioCause {Task.CausalityDetection}/{split}]: {error}") |
| df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow") |
|
|
|
|
| def convert_for_causal_candidate_extraction(split: str) -> None: |
| rows = _split_by_document(_load_rows(), split) |
| out = [] |
| for i, r in enumerate(rows): |
| |
| |
| |
| |
| |
| involved = {eid for rel in r["relations"] for eid in (rel["first"], rel["second"])} |
| entity = [[x for seg in r["segments"][eid] for x in seg] for eid in involved] |
| out.append({"index": f"biocause_{split}_{i}", "text": r["text"], "entity": entity}) |
| df = pd.DataFrame(out).set_index("index") |
| for error in verify_dataset(df, Task.CausalCandidateExtraction): |
| print(f"WARNING [BioCause {Task.CausalCandidateExtraction}/{split}]: {error}") |
| df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow") |
|
|
|
|
| def convert_for_causality_identification(split: str) -> None: |
| rows = _split_by_document(_load_rows(), split) |
| out = [] |
| for i, r in enumerate(rows): |
| marked_text = insert_entity_markers(r["text"], r["segments"]) if r["segments"] else r["text"] |
| out.append({"index": f"biocause_{split}_{i}", "text": marked_text, "relations": r["relations"]}) |
| df = pd.DataFrame(out).set_index("index") |
| for error in verify_dataset(df, Task.CausalityIdentification): |
| print(f"WARNING [BioCause {Task.CausalityIdentification}/{split}]: {error}") |
| df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow") |
|
|
|
|
| if __name__ == "__main__": |
| for split in ["train", "dev", "test"]: |
| convert_for_causality_detection(split) |
| convert_for_causal_candidate_extraction(split) |
| convert_for_causality_identification(split) |
|
|