current state
Browse files- .gitattributes +59 -0
- .gitignore +3 -0
- causal-candidate-extraction/dev.parquet +3 -0
- causal-candidate-extraction/test.parquet +3 -0
- causal-candidate-extraction/train.parquet +3 -0
- causality-detection/dev.parquet +3 -0
- causality-detection/test.parquet +3 -0
- causality-detection/train.parquet +3 -0
- causality-identification/dev.parquet +3 -0
- causality-identification/test.parquet +3 -0
- causality-identification/train.parquet +3 -0
- conversion_script.py +275 -19
.gitattributes
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
# Audio files - uncompressed
|
| 39 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
# Audio files - compressed
|
| 43 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
# Image files - uncompressed
|
| 49 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
# Image files - compressed
|
| 54 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
# Video files - compressed
|
| 58 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.cache/
|
causal-candidate-extraction/dev.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:17b47069d0ea9a6aa3282ee2a5db4ea26c00515ea4eb1c7e8a737cd302ce816b
|
| 3 |
+
size 45224
|
causal-candidate-extraction/test.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:606d2a57366c8deb97472f22b24880d7108f50c976913068f56fede33b91fe4a
|
| 3 |
+
size 48622
|
causal-candidate-extraction/train.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:143a2753aa36493f2dd4fd29dd139160dd9b55c9efeb84f46373dc33d66c47cc
|
| 3 |
+
size 216013
|
causality-detection/dev.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb72c72e80a86c27bffef0674bd0b0606b7c68075c3c9a57b51bf67bbf5b0401
|
| 3 |
+
size 44703
|
causality-detection/test.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f2be511d213e726c45e0c7fdabbf53cf15e951e298c678418145efa2a06c568d
|
| 3 |
+
size 48118
|
causality-detection/train.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6210c0dd6c2aa12678db83720095ccd7bad77fcde872089ecfbc1fbbce352fe
|
| 3 |
+
size 215175
|
causality-identification/dev.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8238c72f58d2cd9f398f0532c25f948c45db79dd617578a24894a0dfb17a7ec4
|
| 3 |
+
size 46824
|
causality-identification/test.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9e205a4fd3b9fd15144747a713d95b1bb5538bc7c3c1392e28509fd98603b5a3
|
| 3 |
+
size 50309
|
causality-identification/train.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e47c60e4b250675607aa8dd6259be0dca465dded8da4fe1934cf5c57ee81c644
|
| 3 |
+
size 221070
|
conversion_script.py
CHANGED
|
@@ -1,28 +1,284 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
|
| 3 |
"""
|
| 4 |
-
Run this script as ./conversion_script.py to convert the BioCause
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
from pathlib import Path
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
converter = CREST2HF(
|
| 19 |
-
"https://raw.githubusercontent.com/phosseini/CREST/master/data/crest_v2.xlsx",
|
| 20 |
-
Path.cwd(),
|
| 21 |
-
prefix="biocause",
|
| 22 |
-
filters={"source": CRESTSource.BioCause},
|
| 23 |
-
)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
|
| 3 |
"""
|
| 4 |
+
Run this script as ./conversion_script.py to convert the BioCause dataset
|
| 5 |
+
DIRECTLY from its original brat-format annotation files, bypassing the
|
| 6 |
+
CREST aggregation (crest_v2.xlsx). CREST's own copy of BioCause has (a)
|
| 7 |
+
train only, 0 dev/test rows (a real CREST-source gap, not fixable by
|
| 8 |
+
adjusting causalatee's split logic), and (b) the same
|
| 9 |
+
idx/context character-offset misalignment already found and fixed for
|
| 10 |
+
CaTeRS, dropping some spans on conversion.
|
| 11 |
+
|
| 12 |
+
Citation / original source
|
| 13 |
+
---------------------------
|
| 14 |
+
Mihaila, C., Ohta, T., Pyysalo, S., & Ananiadou, S. (2013). "BioCause:
|
| 15 |
+
Annotating and analysing causality in the biomedical domain." BMC
|
| 16 |
+
Bioinformatics, 14, 2. https://doi.org/10.1186/1471-2105-14-2
|
| 17 |
+
Corpus home: https://www.nactem.ac.uk/biocause/
|
| 18 |
+
Direct download (verified working, no login): a zip archive at
|
| 19 |
+
https://www.nactem.ac.uk/biocause/download-biocause-corpus.php containing
|
| 20 |
+
one BioCause_corpus/ directory of paired .ann/.txt files (brat standoff),
|
| 21 |
+
one pair per section of a PMC Open-Access article's Discussion (also
|
| 22 |
+
includes TIAB/Introduction/Results sections for some articles) -- 198
|
| 23 |
+
file pairs across 20 unique PMC article ids, verified directly.
|
| 24 |
+
|
| 25 |
+
Format: brat standoff, built on top of a pre-existing BioNLP-ST 2011
|
| 26 |
+
Infectious Diseases event/entity layer in the SAME .ann files (Organism,
|
| 27 |
+
Protein, Positive_regulation, Regulation, Gene_expression, ... -- ignored
|
| 28 |
+
here, we only want the Causality layer). Causal relations are event-style:
|
| 29 |
+
T<n> Causality <start> <end> <connective text, e.g. "resulting in">
|
| 30 |
+
E<n> Causality:T<n> Cause:T<a> Effect:T<b>
|
| 31 |
+
E<n> Causality:T<n> Effect:T<b> Evidence:T<c> (no Cause -- common)
|
| 32 |
+
Cause/Effect/Evidence roles always reference a T-line directly (verified:
|
| 33 |
+
grepped the whole corpus for a role pointing at another E-line -- none
|
| 34 |
+
found), so no recursive event resolution is needed. ~18 T-line spans are
|
| 35 |
+
discontinuous (semicolon-joined offset pairs) -- preserved via
|
| 36 |
+
causalatee's multi-segment entity schema.
|
| 37 |
+
|
| 38 |
+
Only 51 of 851 Causality events have an explicit Cause role; the other
|
| 39 |
+
800 have Effect+Evidence with NO separate cause span at all -- the
|
| 40 |
+
causing participant is not marked as its own argument in those cases.
|
| 41 |
+
Causality-DETECTION uses all 851 (a sentence is causal if it contains ANY
|
| 42 |
+
Causality event, span or no span). Causal-candidate-extraction and
|
| 43 |
+
causality-IDENTIFICATION need an explicit (cause, effect) span pair, so
|
| 44 |
+
they only use the 51 Cause+Effect events -- a real, small, and worth
|
| 45 |
+
documenting limitation of this corpus, not an artefact of this script.
|
| 46 |
+
|
| 47 |
+
No train/dev/test split exists upstream (checked: no filename in the
|
| 48 |
+
archive contains train/dev/test) -- CREST's own split was entirely
|
| 49 |
+
invented. This script creates its own deterministic split BY ARTICLE
|
| 50 |
+
(not by section) so sections of the same PMC article never end up split
|
| 51 |
+
across train/dev/test: 14 articles -> train, 3 -> dev, 3 -> test.
|
| 52 |
|
| 53 |
+
Only 7 of the 20 articles contain any of the 51 Cause+Effect relations at
|
| 54 |
+
all (the other 13 have Effect+Evidence-only Causality events, which count
|
| 55 |
+
for detection but not identification/extraction -- see below). A first
|
| 56 |
+
version of this split just sorted article ids and sliced [:14]/[14:17]/
|
| 57 |
+
[17:20] -- deterministic, but blind to where those 51 relations actually
|
| 58 |
+
live: alphabetically, ALL THREE of the last 3 article ids happen to be
|
| 59 |
+
relation-free, so causality-IDENTIFICATION's test split silently ended up
|
| 60 |
+
with 0 usable pairs (found the hard way: the dependency-baseline runner
|
| 61 |
+
crashed with "BioCause has no usable identification pairs"). Fixed by
|
| 62 |
+
`_assign_documents_to_splits`: a
|
| 63 |
+
deterministic greedy assignment that places the 20 articles (sorted by
|
| 64 |
+
relation count descending, ties by id) one at a time into whichever split
|
| 65 |
+
is currently furthest below its target relation share (train/dev/test's
|
| 66 |
+
14/3/3 document-count ratio), so every split ends up with a reasonable,
|
| 67 |
+
non-zero share of the 51 relations (currently 28/12/11) while whole
|
| 68 |
+
articles still never cross a split boundary.
|
| 69 |
|
| 70 |
+
Granularity: each row is a WHOLE SECTION (not a sentence). An earlier
|
| 71 |
+
version of this script cut each section into per-sentence rows (spaCy
|
| 72 |
+
boundaries, one row per sentence), but ~30 of BioCause's 851 Causality
|
| 73 |
+
events have a cause and/or effect span that references an ADJACENT
|
| 74 |
+
sentence rather than the one their trigger is in (discourse-level
|
| 75 |
+
causality, e.g. "X requires Y... [new sentence] This substitution
|
| 76 |
+
decreases Z") -- verified this really happens by inspecting real output.
|
| 77 |
+
A per-sentence schema can't represent such an event at all: either drop it
|
| 78 |
+
(losing ~30 real relations for no reason other than granularity) or
|
| 79 |
+
re-base it onto the wrong sentence's text (a real bug hit during that
|
| 80 |
+
attempt: a marker landing mid-word, "h<e1>istidine"). Keeping the whole
|
| 81 |
+
section as one unit sidesteps the tradeoff entirely -- every event's spans
|
| 82 |
+
are always within the row's text, nothing is dropped or corrupted. The
|
| 83 |
+
per-sentence view can still be derived on demand from this whole-section
|
| 84 |
+
data via causalatee's reusable
|
| 85 |
+
``causalatee.data.utils.split_identification_to_sentences`` /
|
| 86 |
+
``split_extraction_to_sentences`` utilities -- built specifically to
|
| 87 |
+
generalise the guard this script used to hand-roll.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
import io
|
| 91 |
+
import re
|
| 92 |
+
import urllib.request
|
| 93 |
+
import zipfile
|
| 94 |
from pathlib import Path
|
| 95 |
|
| 96 |
+
import pandas as pd
|
| 97 |
+
|
| 98 |
+
from causalatee.data.constants import ClassLabel, Relation, Task
|
| 99 |
+
from causalatee.data.utils import insert_entity_markers, verify_dataset
|
| 100 |
+
|
| 101 |
+
_ZIP_URL = "https://www.nactem.ac.uk/biocause/download-biocause-corpus.php"
|
| 102 |
+
_CACHE_DIR = Path(__file__).parent / ".cache"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _fetch_corpus_dir() -> Path:
|
| 106 |
+
"""Download + extract the BioCause zip once, cached under .cache/."""
|
| 107 |
+
corpus_dir = _CACHE_DIR / "BioCause_corpus"
|
| 108 |
+
if corpus_dir.is_dir() and any(corpus_dir.iterdir()):
|
| 109 |
+
return corpus_dir
|
| 110 |
+
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
| 111 |
+
with urllib.request.urlopen(_ZIP_URL) as resp:
|
| 112 |
+
data = resp.read()
|
| 113 |
+
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
| 114 |
+
zf.extractall(_CACHE_DIR)
|
| 115 |
+
return corpus_dir
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _parse_ann(ann_text: str) -> tuple[dict[str, list[tuple[int, int]]], dict[str, str], list[dict]]:
|
| 119 |
+
"""Parse one .ann file.
|
| 120 |
+
|
| 121 |
+
Returns (t_spans: T-line id -> segments, t_types: T-line id -> type,
|
| 122 |
+
causality_events: list of {"trigger": tid, "cause": tid|None,
|
| 123 |
+
"effect": tid|None} for every Causality-typed event).
|
| 124 |
+
"""
|
| 125 |
+
t_spans: dict[str, list[tuple[int, int]]] = {}
|
| 126 |
+
t_types: dict[str, str] = {}
|
| 127 |
+
for line in ann_text.splitlines():
|
| 128 |
+
if not line.startswith("T"):
|
| 129 |
+
continue
|
| 130 |
+
tid, mid, _ = (line.split("\t", 2) + [""])[:3]
|
| 131 |
+
etype, offsets_str = mid.split(" ", 1)
|
| 132 |
+
segments = [tuple(int(x) for x in pair.split()) for pair in offsets_str.split(";")]
|
| 133 |
+
t_spans[tid] = sorted(segments)
|
| 134 |
+
t_types[tid] = etype
|
| 135 |
+
|
| 136 |
+
causality_events = []
|
| 137 |
+
for line in ann_text.splitlines():
|
| 138 |
+
if not line.startswith("E"):
|
| 139 |
+
continue
|
| 140 |
+
_, mid = line.split("\t", 1)
|
| 141 |
+
roles = mid.strip().split(" ")
|
| 142 |
+
trigger_role, trigger_tid = roles[0].split(":")
|
| 143 |
+
if trigger_role != "Causality":
|
| 144 |
+
continue
|
| 145 |
+
args = dict(r.split(":") for r in roles[1:] if ":" in r)
|
| 146 |
+
causality_events.append({
|
| 147 |
+
"trigger": trigger_tid,
|
| 148 |
+
"cause": args.get("Cause"),
|
| 149 |
+
"effect": args.get("Effect"),
|
| 150 |
+
})
|
| 151 |
+
return t_spans, t_types, causality_events
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _load_sections() -> list[dict]:
|
| 155 |
+
"""One dict per .ann/.txt pair: {"doc_id", "text", "events": [...]}."""
|
| 156 |
+
corpus_dir = _fetch_corpus_dir()
|
| 157 |
+
sections = []
|
| 158 |
+
for ann_path in sorted(corpus_dir.glob("*.ann")):
|
| 159 |
+
txt_path = ann_path.with_suffix(".txt")
|
| 160 |
+
text = txt_path.read_text(encoding="utf-8")
|
| 161 |
+
t_spans, _, events = _parse_ann(ann_path.read_text(encoding="utf-8"))
|
| 162 |
+
doc_id = re.match(r"(PMC\d+)-", ann_path.stem).group(1)
|
| 163 |
+
resolved = [
|
| 164 |
+
{
|
| 165 |
+
"cause_segments": t_spans[e["cause"]] if e["cause"] else None,
|
| 166 |
+
"effect_segments": t_spans[e["effect"]] if e["effect"] else None,
|
| 167 |
+
}
|
| 168 |
+
for e in events
|
| 169 |
+
if e["effect"] in t_spans and (e["cause"] is None or e["cause"] in t_spans)
|
| 170 |
+
]
|
| 171 |
+
sections.append({"doc_id": doc_id, "text": text, "events": resolved})
|
| 172 |
+
return sections
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _load_rows() -> list[dict]:
|
| 176 |
+
"""One row per whole section, cached across the 3 convert_for_* calls.
|
| 177 |
+
|
| 178 |
+
No sentence segmentation happens here at all -- every event's
|
| 179 |
+
cause/effect segments are already within the section's own text by
|
| 180 |
+
construction, so there is nothing to re-base and nothing to drop.
|
| 181 |
+
"""
|
| 182 |
+
if hasattr(_load_rows, "_cache"):
|
| 183 |
+
return _load_rows._cache
|
| 184 |
+
|
| 185 |
+
rows = []
|
| 186 |
+
for section in _load_sections():
|
| 187 |
+
segments: dict[str, list[tuple[int, int]]] = {}
|
| 188 |
+
relations = []
|
| 189 |
+
for i, ev in enumerate(section["events"]):
|
| 190 |
+
effect_id = f"e{2 * i + 1}"
|
| 191 |
+
segments[effect_id] = ev["effect_segments"]
|
| 192 |
+
if ev["cause_segments"] is not None:
|
| 193 |
+
cause_id = f"e{2 * i + 2}"
|
| 194 |
+
segments[cause_id] = ev["cause_segments"]
|
| 195 |
+
relations.append({"relationship": Relation.Procausal, "first": cause_id, "second": effect_id})
|
| 196 |
+
rows.append({"doc_id": section["doc_id"], "text": section["text"],
|
| 197 |
+
"relations": relations, "segments": segments})
|
| 198 |
+
|
| 199 |
+
_load_rows._cache = rows
|
| 200 |
+
return rows
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
_SPLIT_DOC_CAPACITY = {"train": 14, "dev": 3, "test": 3}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _assign_documents_to_splits(rows: list[dict]) -> dict[str, set[str]]:
|
| 207 |
+
"""Deterministic greedy split assignment, balanced by relation count.
|
| 208 |
+
|
| 209 |
+
Sorts articles by their number of Cause+Effect relations (descending,
|
| 210 |
+
ties broken by doc id), then assigns each one to whichever split still
|
| 211 |
+
has capacity and is currently furthest below its target relation share
|
| 212 |
+
(train/dev/test's document-count ratio) -- see module docstring for why
|
| 213 |
+
a plain sorted-id slice isn't good enough here.
|
| 214 |
+
"""
|
| 215 |
+
doc_relations: dict[str, int] = {}
|
| 216 |
+
for r in rows:
|
| 217 |
+
doc_relations[r["doc_id"]] = doc_relations.get(r["doc_id"], 0) + len(r["relations"])
|
| 218 |
+
|
| 219 |
+
assigned: dict[str, set[str]] = {split: set() for split in _SPLIT_DOC_CAPACITY}
|
| 220 |
+
rel_totals = {split: 0 for split in _SPLIT_DOC_CAPACITY}
|
| 221 |
+
order = sorted(doc_relations, key=lambda d: (-doc_relations[d], d))
|
| 222 |
+
for doc_id in order:
|
| 223 |
+
candidates = [s for s, cap in _SPLIT_DOC_CAPACITY.items() if len(assigned[s]) < cap]
|
| 224 |
+
best = min(candidates, key=lambda s: (rel_totals[s] / _SPLIT_DOC_CAPACITY[s], -_SPLIT_DOC_CAPACITY[s]))
|
| 225 |
+
assigned[best].add(doc_id)
|
| 226 |
+
rel_totals[best] += doc_relations[doc_id]
|
| 227 |
+
return assigned
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _split_by_document(rows: list[dict], split: str) -> list[dict]:
|
| 231 |
+
wanted = _assign_documents_to_splits(rows)[split]
|
| 232 |
+
return [r for r in rows if r["doc_id"] in wanted]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def convert_for_causality_detection(split: str) -> None:
|
| 236 |
+
rows = _split_by_document(_load_rows(), split)
|
| 237 |
+
df = pd.DataFrame([
|
| 238 |
+
{
|
| 239 |
+
"index": f"biocause_{split}_{i}",
|
| 240 |
+
"text": r["text"],
|
| 241 |
+
"label": ClassLabel.Causal if r["relations"] or r["segments"] else ClassLabel.Uncausal,
|
| 242 |
+
}
|
| 243 |
+
for i, r in enumerate(rows)
|
| 244 |
+
]).set_index("index")
|
| 245 |
+
for error in verify_dataset(df, Task.CausalityDetection):
|
| 246 |
+
print(f"WARNING [BioCause {Task.CausalityDetection}/{split}]: {error}")
|
| 247 |
+
df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def convert_for_causal_candidate_extraction(split: str) -> None:
|
| 251 |
+
rows = _split_by_document(_load_rows(), split)
|
| 252 |
+
out = []
|
| 253 |
+
for i, r in enumerate(rows):
|
| 254 |
+
# Only entities that participate in a full Cause+Effect relation have a
|
| 255 |
+
# usable pair; entities from Effect-only (no Cause) events are dropped
|
| 256 |
+
# here (extraction needs no relation to exist, but we still restrict to
|
| 257 |
+
# spans backing an actual relation, matching the other converters'
|
| 258 |
+
# "only causal_eids" convention).
|
| 259 |
+
involved = {eid for rel in r["relations"] for eid in (rel["first"], rel["second"])}
|
| 260 |
+
entity = [[x for seg in r["segments"][eid] for x in seg] for eid in involved]
|
| 261 |
+
out.append({"index": f"biocause_{split}_{i}", "text": r["text"], "entity": entity})
|
| 262 |
+
df = pd.DataFrame(out).set_index("index")
|
| 263 |
+
for error in verify_dataset(df, Task.CausalCandidateExtraction):
|
| 264 |
+
print(f"WARNING [BioCause {Task.CausalCandidateExtraction}/{split}]: {error}")
|
| 265 |
+
df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def convert_for_causality_identification(split: str) -> None:
|
| 269 |
+
rows = _split_by_document(_load_rows(), split)
|
| 270 |
+
out = []
|
| 271 |
+
for i, r in enumerate(rows):
|
| 272 |
+
marked_text = insert_entity_markers(r["text"], r["segments"]) if r["segments"] else r["text"]
|
| 273 |
+
out.append({"index": f"biocause_{split}_{i}", "text": marked_text, "relations": r["relations"]})
|
| 274 |
+
df = pd.DataFrame(out).set_index("index")
|
| 275 |
+
for error in verify_dataset(df, Task.CausalityIdentification):
|
| 276 |
+
print(f"WARNING [BioCause {Task.CausalityIdentification}/{split}]: {error}")
|
| 277 |
+
df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
for split in ["train", "dev", "test"]:
|
| 282 |
+
convert_for_causality_detection(split)
|
| 283 |
+
convert_for_causal_candidate_extraction(split)
|
| 284 |
+
convert_for_causality_identification(split)
|