gabrielaltay commited on
Commit
b88c542
1 Parent(s): 004288c

upload hubscripts/biorelex_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. biorelex.py +416 -0
biorelex.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
17
+ BioRelEx is a biological relation extraction dataset. Version 1.0 contains 2010
18
+ annotated sentences that describe binding interactions between various
19
+ biological entities (proteins, chemicals, etc.). 1405 sentences are for
20
+ training, another 201 sentences are for validation. They are publicly available
21
+ at https://github.com/YerevaNN/BioRelEx/releases. Another 404 sentences are for
22
+ testing which are kept private for at this Codalab competition
23
+ https://competitions.codalab.org/competitions/20468. All sentences contain words
24
+ "bind", "bound" or "binding". For every sentence we provide: 1) Complete
25
+ annotations of all biological entities that appear in the sentence 2) Entity
26
+ types (32 types) and grounding information for most of the proteins and families
27
+ (links to uniprot, interpro and other databases) 3) Coreference between entities
28
+ in the same sentence (e.g. abbreviations and synonyms) 4) Binding interactions
29
+ between the annotated entities 5) Binding interaction types: positive, negative
30
+ (A does not bind B) and neutral (A may bind to B)
31
+ """
32
+
33
+ import itertools as it
34
+ import json
35
+ from collections import defaultdict
36
+ from typing import Dict, List, Tuple
37
+
38
+ import datasets
39
+
40
+ from .bigbiohub import kb_features
41
+ from .bigbiohub import BigBioConfig
42
+ from .bigbiohub import Tasks
43
+
44
+ # TODO: Add BibTeX citation
45
+ _LANGUAGES = ['English']
46
+ _PUBMED = True
47
+ _LOCAL = False
48
+ _CITATION = """\
49
+ @inproceedings{khachatrian2019biorelex,
50
+ title = "{B}io{R}el{E}x 1.0: Biological Relation Extraction Benchmark",
51
+ author = "Khachatrian, Hrant and
52
+ Nersisyan, Lilit and
53
+ Hambardzumyan, Karen and
54
+ Galstyan, Tigran and
55
+ Hakobyan, Anna and
56
+ Arakelyan, Arsen and
57
+ Rzhetsky, Andrey and
58
+ Galstyan, Aram",
59
+ booktitle = "Proceedings of the 18th BioNLP Workshop and Shared Task",
60
+ month = aug,
61
+ year = "2019",
62
+ address = "Florence, Italy",
63
+ publisher = "Association for Computational Linguistics",
64
+ url = "https://aclanthology.org/W19-5019",
65
+ doi = "10.18653/v1/W19-5019",
66
+ pages = "176--190"
67
+ }
68
+ """
69
+
70
+ _DATASETNAME = "biorelex"
71
+ _DISPLAYNAME = "BioRelEx"
72
+
73
+ _DESCRIPTION = """\
74
+ BioRelEx is a biological relation extraction dataset. Version 1.0 contains 2010
75
+ annotated sentences that describe binding interactions between various
76
+ biological entities (proteins, chemicals, etc.). 1405 sentences are for
77
+ training, another 201 sentences are for validation. They are publicly available
78
+ at https://github.com/YerevaNN/BioRelEx/releases. Another 404 sentences are for
79
+ testing which are kept private for at this Codalab competition
80
+ https://competitions.codalab.org/competitions/20468. All sentences contain words
81
+ "bind", "bound" or "binding". For every sentence we provide: 1) Complete
82
+ annotations of all biological entities that appear in the sentence 2) Entity
83
+ types (32 types) and grounding information for most of the proteins and families
84
+ (links to uniprot, interpro and other databases) 3) Coreference between entities
85
+ in the same sentence (e.g. abbreviations and synonyms) 4) Binding interactions
86
+ between the annotated entities 5) Binding interaction types: positive, negative
87
+ (A does not bind B) and neutral (A may bind to B)"""
88
+
89
+ _HOMEPAGE = "https://github.com/YerevaNN/BioRelEx"
90
+
91
+ _LICENSE = 'License information unavailable'
92
+
93
+ _URLS = {
94
+ _DATASETNAME: {
95
+ "train": "https://github.com/YerevaNN/BioRelEx/releases/download/1.0alpha7/1.0alpha7.train.json",
96
+ "dev": "https://github.com/YerevaNN/BioRelEx/releases/download/1.0alpha7/1.0alpha7.dev.json",
97
+ },
98
+ }
99
+
100
+ _SUPPORTED_TASKS = [
101
+ Tasks.NAMED_ENTITY_RECOGNITION,
102
+ Tasks.NAMED_ENTITY_DISAMBIGUATION,
103
+ Tasks.RELATION_EXTRACTION,
104
+ Tasks.COREFERENCE_RESOLUTION,
105
+ ]
106
+
107
+ _SOURCE_VERSION = "1.0.0"
108
+
109
+ _BIGBIO_VERSION = "1.0.0"
110
+
111
+
112
+ class BioRelExDataset(datasets.GeneratorBasedBuilder):
113
+ """BioRelEx is a biological relation extraction dataset."""
114
+
115
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
116
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
117
+
118
+ BUILDER_CONFIGS = [
119
+ BigBioConfig(
120
+ name="biorelex_source",
121
+ version=SOURCE_VERSION,
122
+ description="BioRelEx source schema",
123
+ schema="source",
124
+ subset_id="biorelex",
125
+ ),
126
+ BigBioConfig(
127
+ name="biorelex_bigbio_kb",
128
+ version=BIGBIO_VERSION,
129
+ description="BioRelEx BigBio schema",
130
+ schema="bigbio_kb",
131
+ subset_id="biorelex",
132
+ ),
133
+ ]
134
+
135
+ DEFAULT_CONFIG_NAME = "biorelex_source"
136
+
137
+ def _info(self) -> datasets.DatasetInfo:
138
+
139
+ if self.config.schema == "source":
140
+ features = datasets.Features(
141
+ {
142
+ "paperid": datasets.Value("string"),
143
+ "interactions": [
144
+ {
145
+ "participants": datasets.Sequence(datasets.Value("int32")),
146
+ "type": datasets.Value("string"),
147
+ "implicit": datasets.Value("bool"),
148
+ "label": datasets.Value("int32"),
149
+ }
150
+ ],
151
+ "url": datasets.Value("string"),
152
+ "text": datasets.Value("string"),
153
+ "entities": [
154
+ {
155
+ "is_state": datasets.Value("bool"),
156
+ "label": datasets.Value("string"),
157
+ "names": [
158
+ {
159
+ "text": datasets.Value("string"),
160
+ "is_mentioned": datasets.Value("bool"),
161
+ "mentions": datasets.Sequence(
162
+ [datasets.Value("int32")]
163
+ ),
164
+ }
165
+ ],
166
+ "grounding": [
167
+ {
168
+ "comment": datasets.Value("string"),
169
+ "entrez_gene": datasets.Value("string"),
170
+ "source": datasets.Value("string"),
171
+ "link": datasets.Value("string"),
172
+ "hgnc_symbol": datasets.Value("string"),
173
+ "organism": datasets.Value("string"),
174
+ }
175
+ ],
176
+ "is_mentioned": datasets.Value("bool"),
177
+ "is_mutant": datasets.Value("bool"),
178
+ }
179
+ ],
180
+ "_line_": datasets.Value("int32"),
181
+ "id": datasets.Value("string"),
182
+ }
183
+ )
184
+ elif self.config.schema == "bigbio_kb":
185
+ features = kb_features
186
+
187
+ return datasets.DatasetInfo(
188
+ description=_DESCRIPTION,
189
+ features=features,
190
+ homepage=_HOMEPAGE,
191
+ license=str(_LICENSE),
192
+ citation=_CITATION,
193
+ )
194
+
195
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
196
+ """Returns SplitGenerators."""
197
+
198
+ urls = _URLS[_DATASETNAME]
199
+ data_dir = dl_manager.download_and_extract(urls)
200
+
201
+ return [
202
+ datasets.SplitGenerator(
203
+ name=datasets.Split.TRAIN,
204
+ gen_kwargs={
205
+ "filepath": data_dir["train"],
206
+ },
207
+ ),
208
+ datasets.SplitGenerator(
209
+ name=datasets.Split.VALIDATION,
210
+ gen_kwargs={
211
+ "filepath": data_dir["dev"],
212
+ },
213
+ ),
214
+ ]
215
+
216
+ def _generate_examples(self, filepath) -> Tuple[int, Dict]:
217
+ """Yields examples as (key, example) tuples."""
218
+
219
+ with open(filepath, "r", encoding="utf8") as f:
220
+ data = json.load(f)
221
+ data = self._prep(data)
222
+
223
+ if self.config.schema == "source":
224
+ for key, example in enumerate(data):
225
+ yield key, example
226
+
227
+ elif self.config.schema == "bigbio_kb":
228
+ for key, example in enumerate(data):
229
+ example_ = self._source_to_kb(example)
230
+ yield key, example_
231
+
232
+ def _prep(self, data):
233
+ for example in data:
234
+ for entity in example["entities"]:
235
+ entity["names"] = self._json_dict_to_list(entity["names"], "text")
236
+ if entity["grounding"] is None:
237
+ entity["grounding"] = []
238
+ else:
239
+ entity["grounding"] = [entity["grounding"]]
240
+ return data
241
+
242
+ def _json_dict_to_list(self, json, new_key):
243
+ list_ = []
244
+ for key, values in json.items():
245
+ assert isinstance(values, dict), "Child element is not a dict"
246
+ assert new_key not in values, "New key already in values"
247
+ values[new_key] = key
248
+ list_.append(values)
249
+ return list_
250
+
251
+ def _source_to_kb(self, example):
252
+ example_id = example["id"]
253
+ entities_, corefs_, ref_id_map = self._get_entities(
254
+ example_id, example["entities"]
255
+ )
256
+ relations_ = self._get_relations(
257
+ example_id, ref_id_map, example["interactions"]
258
+ )
259
+
260
+ document_ = {
261
+ "id": example_id,
262
+ "document_id": example["paperid"],
263
+ "passages": [
264
+ {
265
+ "id": example_id + ".sent",
266
+ "type": "sentence",
267
+ "text": [example["text"]],
268
+ "offsets": [[0, len(example["text"])]],
269
+ }
270
+ ],
271
+ "entities": entities_,
272
+ "coreferences": corefs_,
273
+ "relations": relations_,
274
+ "events": [],
275
+ }
276
+ return document_
277
+
278
+ def _get_entities(self, example_id, entities):
279
+ entities_ = []
280
+ corefs_ = []
281
+
282
+ eid = it.count(0)
283
+ cid = it.count(0)
284
+ # dictionary mapping the original ref ids (indexes of entities) for relations
285
+ org_rel_ref_id_2_kb_entity_id = defaultdict(list)
286
+
287
+ for relation_ref_id, entity in enumerate(entities):
288
+
289
+ # get normalization for entities
290
+ normalized_ = self._get_normalizations(entity)
291
+
292
+ # create entity for each synonym
293
+ coref_eids_ = []
294
+ for names in entity["names"]:
295
+ for id, mention in enumerate(names["mentions"]):
296
+ entity_id = example_id + ".ent" + str(next(eid)) + "_" + str(id)
297
+ org_rel_ref_id_2_kb_entity_id[relation_ref_id].append(entity_id)
298
+ coref_eids_.append(entity_id)
299
+ entities_.append(
300
+ {
301
+ "id": entity_id,
302
+ "type": entity["label"],
303
+ "text": [names["text"]],
304
+ "offsets": [mention],
305
+ "normalized": normalized_,
306
+ }
307
+ )
308
+
309
+ # create coreferences
310
+ coref_id = example_id + ".coref" + str(next(cid))
311
+ corefs_.append(
312
+ {
313
+ "id": coref_id,
314
+ "entity_ids": coref_eids_,
315
+ }
316
+ )
317
+ return entities_, corefs_, org_rel_ref_id_2_kb_entity_id
318
+
319
+ def _get_normalizations(self, entity):
320
+ normalized_ = []
321
+ if entity["grounding"]:
322
+ assert len(entity["grounding"]) == 1
323
+ if entity["grounding"][0]["entrez_gene"] != "NA":
324
+ normalized_.append(
325
+ {
326
+ "db_name": "NCBI gene",
327
+ "db_id": entity["grounding"][0]["entrez_gene"],
328
+ }
329
+ )
330
+ if entity["grounding"][0]["hgnc_symbol"] != "NA":
331
+ normalized_.append(
332
+ {"db_name": "hgnc", "db_id": entity["grounding"][0]["hgnc_symbol"]}
333
+ )
334
+
335
+ # maybe parse some other ids?
336
+ source = entity["grounding"][0]["source"]
337
+ if (
338
+ source != "NCBI gene"
339
+ and source != "https://www.genenames.org/data/genegroup/"
340
+ ): # NCBI gene is same as entrez
341
+ normalized_.append(
342
+ self._parse_id_from_link(
343
+ entity["grounding"][0]["link"], entity["grounding"][0]["source"]
344
+ )
345
+ )
346
+ return normalized_
347
+
348
+ def _get_relations(self, example_id, org_rel_ref_id_2_kb_entity_id, interactions):
349
+ rid = it.count(0)
350
+ relations_ = []
351
+ for interaction in interactions:
352
+ rel_id = example_id + ".rel" + str(next(rid))
353
+ assert len(interaction["participants"]) == 2
354
+
355
+ subjects = org_rel_ref_id_2_kb_entity_id[interaction["participants"][0]]
356
+ objects = org_rel_ref_id_2_kb_entity_id[interaction["participants"][1]]
357
+
358
+ for s in subjects:
359
+ for o in objects:
360
+ relations_.append(
361
+ {
362
+ "id": rel_id + "s" + s + ".o" + o,
363
+ "type": interaction["type"],
364
+ "arg1_id": s,
365
+ "arg2_id": o,
366
+ "normalized": [],
367
+ }
368
+ )
369
+ return relations_
370
+
371
+ def _parse_id_from_link(self, link, source):
372
+ source_template_map = {
373
+ "uniprot": ["https://www.uniprot.org/uniprot/"],
374
+ "pubchem:compound": ["https://pubchem.ncbi.nlm.nih.gov/compound/"],
375
+ "pubchem:substance": ["https://pubchem.ncbi.nlm.nih.gov/substance/"],
376
+ "pfam": ["https://pfam.xfam.org/family/", "http://pfam.xfam.org/family/"],
377
+ "interpro": [
378
+ "http://www.ebi.ac.uk/interpro/entry/",
379
+ "https://www.ebi.ac.uk/interpro/entry/",
380
+ ],
381
+ "DrugBank": ["https://www.drugbank.ca/drugs/"],
382
+ }
383
+
384
+ # fix exceptions manually
385
+ if source == "https://enzyme.expasy.org/EC/2.5.1.18" and link == source:
386
+ return {"db_name": "intenz", "db_id": "2.5.1.18"}
387
+ elif (
388
+ source == "https://www.genome.jp/kegg-bin/show_pathway?map=ko04120"
389
+ and link == source
390
+ ):
391
+ return {"db_name": "kegg", "db_id": "ko04120"}
392
+ elif (
393
+ source == "https://www.genome.jp/dbget-bin/www_bget?enzyme+2.7.11.1"
394
+ and link == source
395
+ ):
396
+ return {"db_name": "intenz", "db_id": "2.7.11.1"}
397
+ elif (
398
+ source == "http://www.chemspider.com/Chemical-Structure.7995676.html"
399
+ and link == source
400
+ ):
401
+ return {"db_name": "chemspider", "db_id": "7995676"}
402
+ elif source == "intenz":
403
+ id = link.split("=")[0]
404
+ return {"db_name": source, "db_id": id}
405
+ else:
406
+ link_templates = source_template_map[source]
407
+ for template in link_templates:
408
+ if link.startswith(template):
409
+ id = link.replace(template, "")
410
+ id = id.split("?")[0]
411
+ assert "/" not in id
412
+ return {"db_name": source, "db_id": id}
413
+
414
+ assert (
415
+ False
416
+ ), f"No template found for {link}, choices: {repr(link_templates)}"