gabrielaltay commited on
Commit
add6d58
1 Parent(s): bb981d1

upload hubscripts/bc5cdr_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. bc5cdr.py +371 -0
bc5cdr.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ To this end, we set up a challenge task through BioCreative V to automatically
17
+ extract CDRs from the literature. More specifically, we designed two challenge
18
+ tasks: disease named entity recognition (DNER) and chemical-induced disease
19
+ (CID) relation extraction. To assist system development and assessment, we
20
+ created a large annotated text corpus that consists of human annotations of
21
+ all chemicals, diseases and their interactions in 1,500 PubMed articles.
22
+
23
+ -- 'Overview of the BioCreative V Chemical Disease Relation (CDR) Task'
24
+ """
25
+ import collections
26
+ import itertools
27
+ import os
28
+
29
+ import datasets
30
+ from bioc import biocxml
31
+
32
+ from .bigbiohub import kb_features
33
+ from .bigbiohub import BigBioConfig
34
+ from .bigbiohub import Tasks
35
+
36
+ _LANGUAGES = ['English']
37
+ _PUBMED = True
38
+ _LOCAL = False
39
+ _CITATION = """\
40
+ @article{DBLP:journals/biodb/LiSJSWLDMWL16,
41
+ author = {Jiao Li and
42
+ Yueping Sun and
43
+ Robin J. Johnson and
44
+ Daniela Sciaky and
45
+ Chih{-}Hsuan Wei and
46
+ Robert Leaman and
47
+ Allan Peter Davis and
48
+ Carolyn J. Mattingly and
49
+ Thomas C. Wiegers and
50
+ Zhiyong Lu},
51
+ title = {BioCreative {V} {CDR} task corpus: a resource for chemical disease
52
+ relation extraction},
53
+ journal = {Database J. Biol. Databases Curation},
54
+ volume = {2016},
55
+ year = {2016},
56
+ url = {https://doi.org/10.1093/database/baw068},
57
+ doi = {10.1093/database/baw068},
58
+ timestamp = {Thu, 13 Aug 2020 12:41:41 +0200},
59
+ biburl = {https://dblp.org/rec/journals/biodb/LiSJSWLDMWL16.bib},
60
+ bibsource = {dblp computer science bibliography, https://dblp.org}
61
+ }
62
+ """
63
+
64
+ _DATASETNAME = "bc5cdr"
65
+ _DISPLAYNAME = "BC5CDR"
66
+
67
+ _DESCRIPTION = """\
68
+ The BioCreative V Chemical Disease Relation (CDR) dataset is a large annotated \
69
+ text corpus of human annotations of all chemicals, diseases and their \
70
+ interactions in 1,500 PubMed articles.
71
+ """
72
+
73
+ _HOMEPAGE = "http://www.biocreative.org/tasks/biocreative-v/track-3-cdr/"
74
+
75
+ _LICENSE = 'Public Domain Mark 1.0'
76
+
77
+ _URLs = {
78
+ "source": "http://www.biocreative.org/media/store/files/2016/CDR_Data.zip",
79
+ "bigbio_kb": "http://www.biocreative.org/media/store/files/2016/CDR_Data.zip",
80
+ }
81
+
82
+ _SUPPORTED_TASKS = [
83
+ Tasks.NAMED_ENTITY_RECOGNITION,
84
+ Tasks.NAMED_ENTITY_DISAMBIGUATION,
85
+ Tasks.RELATION_EXTRACTION,
86
+ ]
87
+ _SOURCE_VERSION = "01.05.16"
88
+ _BIGBIO_VERSION = "1.0.0"
89
+
90
+
91
+ class Bc5cdrDataset(datasets.GeneratorBasedBuilder):
92
+ """
93
+ BioCreative V Chemical Disease Relation (CDR) Task.
94
+ """
95
+
96
+ DEFAULT_CONFIG_NAME = "bc5cdr_source"
97
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
98
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
99
+
100
+ BUILDER_CONFIGS = [
101
+ BigBioConfig(
102
+ name="bc5cdr_source",
103
+ version=SOURCE_VERSION,
104
+ description="BC5CDR source schema",
105
+ schema="source",
106
+ subset_id="bc5cdr",
107
+ ),
108
+ BigBioConfig(
109
+ name="bc5cdr_bigbio_kb",
110
+ version=BIGBIO_VERSION,
111
+ description="BC5CDR simplified BigBio schema",
112
+ schema="bigbio_kb",
113
+ subset_id="bc5cdr",
114
+ ),
115
+ ]
116
+
117
+ def _info(self):
118
+
119
+ if self.config.schema == "source":
120
+ # this is a variation on the BioC format
121
+ features = datasets.Features(
122
+ {
123
+ "passages": [
124
+ {
125
+ "document_id": datasets.Value("string"),
126
+ "type": datasets.Value("string"),
127
+ "text": datasets.Value("string"),
128
+ "entities": [
129
+ {
130
+ "id": datasets.Value("string"),
131
+ "offsets": [[datasets.Value("int32")]],
132
+ "text": [datasets.Value("string")],
133
+ "type": datasets.Value("string"),
134
+ "normalized": [
135
+ {
136
+ "db_name": datasets.Value("string"),
137
+ "db_id": datasets.Value("string"),
138
+ }
139
+ ],
140
+ }
141
+ ],
142
+ "relations": [
143
+ {
144
+ "id": datasets.Value("string"),
145
+ "type": datasets.Value("string"),
146
+ "arg1_id": datasets.Value("string"),
147
+ "arg2_id": datasets.Value("string"),
148
+ }
149
+ ],
150
+ }
151
+ ]
152
+ }
153
+ )
154
+
155
+ elif self.config.schema == "bigbio_kb":
156
+ features = kb_features
157
+
158
+ return datasets.DatasetInfo(
159
+ description=_DESCRIPTION,
160
+ features=features,
161
+ supervised_keys=None,
162
+ homepage=_HOMEPAGE,
163
+ license=str(_LICENSE),
164
+ citation=_CITATION,
165
+ )
166
+
167
+ def _split_generators(self, dl_manager):
168
+ """Returns SplitGenerators."""
169
+ my_urls = _URLs[self.config.schema]
170
+ data_dir = dl_manager.download_and_extract(my_urls)
171
+ return [
172
+ datasets.SplitGenerator(
173
+ name=datasets.Split.TRAIN,
174
+ # These kwargs will be passed to _generate_examples
175
+ gen_kwargs={
176
+ "filepath": os.path.join(
177
+ data_dir, "CDR_Data/CDR.Corpus.v010516/CDR_TrainingSet.BioC.xml"
178
+ ),
179
+ "split": "train",
180
+ },
181
+ ),
182
+ datasets.SplitGenerator(
183
+ name=datasets.Split.TEST,
184
+ # These kwargs will be passed to _generate_examples
185
+ gen_kwargs={
186
+ "filepath": os.path.join(
187
+ data_dir, "CDR_Data/CDR.Corpus.v010516/CDR_TestSet.BioC.xml"
188
+ ),
189
+ "split": "test",
190
+ },
191
+ ),
192
+ datasets.SplitGenerator(
193
+ name=datasets.Split.VALIDATION,
194
+ # These kwargs will be passed to _generate_examples
195
+ gen_kwargs={
196
+ "filepath": os.path.join(
197
+ data_dir,
198
+ "CDR_Data/CDR.Corpus.v010516/CDR_DevelopmentSet.BioC.xml",
199
+ ),
200
+ "split": "dev",
201
+ },
202
+ ),
203
+ ]
204
+
205
+ def _get_bioc_entity(self, span, doc_text, db_id_key="MESH"):
206
+ """Parse BioC entity annotation.
207
+
208
+ Parameters
209
+ ----------
210
+ span : BioCAnnotation
211
+ BioC entity annotation
212
+ doc_text : string
213
+ document text, required to construct text spans
214
+ db_id_key : str, optional
215
+ database name used for normalization, by default "MESH"
216
+
217
+ Returns
218
+ -------
219
+ dict
220
+ entity information
221
+ """
222
+ # offsets = [(loc.offset, loc.offset + loc.length) for loc in span.locations]
223
+ # texts = [doc_text[i:j] for i, j in offsets]
224
+ offsets, texts = get_texts_and_offsets_from_bioc_ann(span)
225
+ db_ids = span.infons[db_id_key] if db_id_key else "-1"
226
+
227
+ # some entities are not linked and
228
+ # some entities are linked to multiple normalized ids
229
+ if db_ids == "-1":
230
+ db_ids_list = []
231
+ else:
232
+ db_ids_list = db_ids.split("|")
233
+
234
+ normalized = [{"db_name": db_id_key, "db_id": db_id} for db_id in db_ids_list]
235
+
236
+ return {
237
+ "id": span.id,
238
+ "offsets": offsets,
239
+ "text": texts,
240
+ "type": span.infons["type"],
241
+ "normalized": normalized,
242
+ }
243
+
244
+ def _get_relations(self, relations, entities):
245
+ """
246
+ BC5CDR provides abstract-level annotations for entity-linked relation
247
+ pairs rather than materializing links between all surface form
248
+ mentions of relations. An example from train id=2670794, the relation
249
+ - (chemical, disease) (D014148, D004211)
250
+ is materialized as 6 mentions of entity pairs
251
+ - 2x ('tranexamic acid', 'intravascular coagulation')
252
+ - 4x ('AMCA', 'intravascular coagulation')
253
+ """
254
+ # index entities by normalized id
255
+ index = collections.defaultdict(list)
256
+ for ent in entities:
257
+ for norm in ent["normalized"]:
258
+ index[norm["db_id"]].append(ent)
259
+ index = dict(index)
260
+
261
+ # transform doc-level relations to mention-level
262
+ rela_mentions = []
263
+ for rela in relations:
264
+ arg1 = rela.infons["Chemical"]
265
+ arg2 = rela.infons["Disease"]
266
+ # all mention pairs
267
+ all_pairs = itertools.product(index[arg1], index[arg2])
268
+ for a, b in all_pairs:
269
+ # create relations linked by entity ids
270
+ rela_mentions.append(
271
+ {
272
+ "id": None,
273
+ "type": rela.infons["relation"],
274
+ "arg1_id": a["id"],
275
+ "arg2_id": b["id"],
276
+ "normalized": [],
277
+ }
278
+ )
279
+ return rela_mentions
280
+
281
+ def _get_document_text(self, xdoc):
282
+ """Build document text for unit testing entity span offsets."""
283
+ text = ""
284
+ for passage in xdoc.passages:
285
+ pad = passage.offset - len(text)
286
+ text += (" " * pad) + passage.text
287
+ return text
288
+
289
+ def _generate_examples(
290
+ self,
291
+ filepath,
292
+ split, # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
293
+ ):
294
+ """Yields examples as (key, example) tuples."""
295
+ if self.config.schema == "source":
296
+ reader = biocxml.BioCXMLDocumentReader(str(filepath))
297
+
298
+ for uid, xdoc in enumerate(reader):
299
+ doc_text = self._get_document_text(xdoc)
300
+ yield uid, {
301
+ "passages": [
302
+ {
303
+ "document_id": xdoc.id,
304
+ "type": passage.infons["type"],
305
+ "text": passage.text,
306
+ "entities": [
307
+ self._get_bioc_entity(span, doc_text)
308
+ for span in passage.annotations
309
+ ],
310
+ "relations": [
311
+ {
312
+ "id": rel.id,
313
+ "type": rel.infons["relation"],
314
+ "arg1_id": rel.infons["Chemical"],
315
+ "arg2_id": rel.infons["Disease"],
316
+ }
317
+ for rel in xdoc.relations
318
+ ],
319
+ }
320
+ for passage in xdoc.passages
321
+ ]
322
+ }
323
+
324
+ elif self.config.schema == "bigbio_kb":
325
+ reader = biocxml.BioCXMLDocumentReader(str(filepath))
326
+ uid = 0 # global unique id
327
+
328
+ for i, xdoc in enumerate(reader):
329
+ data = {
330
+ "id": uid,
331
+ "document_id": xdoc.id,
332
+ "passages": [],
333
+ "entities": [],
334
+ "relations": [],
335
+ "events": [],
336
+ "coreferences": [],
337
+ }
338
+ uid += 1
339
+ doc_text = self._get_document_text(xdoc)
340
+
341
+ char_start = 0
342
+ # passages must not overlap and spans must cover the entire document
343
+ for passage in xdoc.passages:
344
+ offsets = [[char_start, char_start + len(passage.text)]]
345
+ char_start = char_start + len(passage.text) + 1
346
+ data["passages"].append(
347
+ {
348
+ "id": uid,
349
+ "type": passage.infons["type"],
350
+ "text": [passage.text],
351
+ "offsets": offsets,
352
+ }
353
+ )
354
+ uid += 1
355
+
356
+ # entities
357
+ for passage in xdoc.passages:
358
+ for span in passage.annotations:
359
+ ent = self._get_bioc_entity(span, doc_text, db_id_key="MESH")
360
+ ent["id"] = uid # override BioC default id
361
+ data["entities"].append(ent)
362
+ uid += 1
363
+
364
+ # relations
365
+ relations = self._get_relations(xdoc.relations, data["entities"])
366
+ for rela in relations:
367
+ rela["id"] = uid # assign unique id
368
+ data["relations"].append(rela)
369
+ uid += 1
370
+
371
+ yield i, data