Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
gabrielaltay commited on
Commit
6cc5ae2
1 Parent(s): b0150a2

upload hubscripts/chemprot_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. chemprot.py +446 -0
chemprot.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+ The BioCreative VI Chemical-Protein interaction dataset identifies entities of
17
+ chemicals and proteins and their likely relation to one other. Compounds are
18
+ generally agonists (activators) or antagonists (inhibitors) of proteins. The
19
+ script loads dataset in bigbio schema (using knowledgebase schema: schemas/kb)
20
+ AND/OR source (default) schema
21
+ """
22
+ import os
23
+ from typing import Dict, Tuple
24
+
25
+ import datasets
26
+
27
+ from .bigbiohub import kb_features
28
+ from .bigbiohub import BigBioConfig
29
+ from .bigbiohub import Tasks
30
+
31
+ _LANGUAGES = ['English']
32
+ _PUBMED = True
33
+ _LOCAL = False
34
+ _CITATION = """\
35
+ @article{DBLP:journals/biodb/LiSJSWLDMWL16,
36
+ author = {Krallinger, M., Rabal, O., Lourenço, A.},
37
+ title = {Overview of the BioCreative VI chemical-protein interaction Track},
38
+ journal = {Proceedings of the BioCreative VI Workshop,},
39
+ volume = {141-146},
40
+ year = {2017},
41
+ url = {https://biocreative.bioinformatics.udel.edu/tasks/biocreative-vi/track-5/},
42
+ doi = {},
43
+ biburl = {},
44
+ bibsource = {}
45
+ }
46
+ """
47
+ _DESCRIPTION = """\
48
+ The BioCreative VI Chemical-Protein interaction dataset identifies entities of
49
+ chemicals and proteins and their likely relation to one other. Compounds are
50
+ generally agonists (activators) or antagonists (inhibitors) of proteins.
51
+ """
52
+
53
+ _DATASETNAME = "chemprot"
54
+ _DISPLAYNAME = "ChemProt"
55
+
56
+ _HOMEPAGE = "https://biocreative.bioinformatics.udel.edu/tasks/biocreative-vi/track-5/"
57
+
58
+ _LICENSE = 'Public Domain Mark 1.0'
59
+
60
+ _URLs = {
61
+ "source": "https://biocreative.bioinformatics.udel.edu/media/store/files/2017/ChemProt_Corpus.zip",
62
+ "bigbio_kb": "https://biocreative.bioinformatics.udel.edu/media/store/files/2017/ChemProt_Corpus.zip",
63
+ }
64
+
65
+ _SUPPORTED_TASKS = [Tasks.RELATION_EXTRACTION, Tasks.NAMED_ENTITY_RECOGNITION]
66
+ _SOURCE_VERSION = "1.0.0"
67
+ _BIGBIO_VERSION = "1.0.0"
68
+
69
+
70
+ # Chemprot specific variables
71
+ # NOTE: There are 3 examples (2 in dev, 1 in training) with CPR:0
72
+ _GROUP_LABELS = {
73
+ "CPR:0": "Undefined",
74
+ "CPR:1": "Part_of",
75
+ "CPR:2": "Regulator",
76
+ "CPR:3": "Upregulator",
77
+ "CPR:4": "Downregulator",
78
+ "CPR:5": "Agonist",
79
+ "CPR:6": "Antagonist",
80
+ "CPR:7": "Modulator",
81
+ "CPR:8": "Cofactor",
82
+ "CPR:9": "Substrate",
83
+ "CPR:10": "Not",
84
+ }
85
+
86
+
87
+ class ChemprotDataset(datasets.GeneratorBasedBuilder):
88
+ """BioCreative VI Chemical-Protein Interaction Task."""
89
+
90
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
91
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
92
+
93
+ BUILDER_CONFIGS = [
94
+ BigBioConfig(
95
+ name="chemprot_full_source",
96
+ version=SOURCE_VERSION,
97
+ description="chemprot source schema",
98
+ schema="source",
99
+ subset_id="chemprot_full",
100
+ ),
101
+ BigBioConfig(
102
+ name="chemprot_shared_task_eval_source",
103
+ version=SOURCE_VERSION,
104
+ description="chemprot source schema with only the relation types that were used in the shared task evaluation",
105
+ schema="source",
106
+ subset_id="chemprot_shared_task_eval",
107
+ ),
108
+ BigBioConfig(
109
+ name="chemprot_bigbio_kb",
110
+ version=BIGBIO_VERSION,
111
+ description="chemprot BigBio schema",
112
+ schema="bigbio_kb",
113
+ subset_id="chemprot",
114
+ ),
115
+ ]
116
+
117
+ DEFAULT_CONFIG_NAME = "chemprot_full_source"
118
+
119
+ def _info(self):
120
+
121
+ if self.config.schema == "source":
122
+ features = datasets.Features(
123
+ {
124
+ "pmid": datasets.Value("string"),
125
+ "text": datasets.Value("string"),
126
+ "entities": datasets.Sequence(
127
+ {
128
+ "id": datasets.Value("string"),
129
+ "type": datasets.Value("string"),
130
+ "text": datasets.Value("string"),
131
+ "offsets": datasets.Sequence(datasets.Value("int64")),
132
+ }
133
+ ),
134
+ "relations": datasets.Sequence(
135
+ {
136
+ "type": datasets.Value("string"),
137
+ "arg1": datasets.Value("string"),
138
+ "arg2": datasets.Value("string"),
139
+ }
140
+ ),
141
+ }
142
+ )
143
+
144
+ elif self.config.schema == "bigbio_kb":
145
+ features = kb_features
146
+
147
+ return datasets.DatasetInfo(
148
+ description=_DESCRIPTION,
149
+ features=features,
150
+ homepage=_HOMEPAGE,
151
+ license=str(_LICENSE),
152
+ citation=_CITATION,
153
+ )
154
+
155
+ def _split_generators(self, dl_manager):
156
+ """Returns SplitGenerators."""
157
+ my_urls = _URLs[self.config.schema]
158
+ data_dir = dl_manager.download_and_extract(my_urls)
159
+
160
+ # Extract each of the individual folders
161
+ # NOTE: omitting "extract" call cause it uses a new folder
162
+ train_path = dl_manager.extract(
163
+ os.path.join(data_dir, "ChemProt_Corpus/chemprot_training.zip")
164
+ )
165
+ test_path = dl_manager.extract(
166
+ os.path.join(data_dir, "ChemProt_Corpus/chemprot_test_gs.zip")
167
+ )
168
+ dev_path = dl_manager.extract(
169
+ os.path.join(data_dir, "ChemProt_Corpus/chemprot_development.zip")
170
+ )
171
+ sample_path = dl_manager.extract(
172
+ os.path.join(data_dir, "ChemProt_Corpus/chemprot_sample.zip")
173
+ )
174
+
175
+ return [
176
+ datasets.SplitGenerator(
177
+ name="sample", # should be a named split : /
178
+ gen_kwargs={
179
+ "filepath": os.path.join(sample_path, "chemprot_sample"),
180
+ "abstract_file": "chemprot_sample_abstracts.tsv",
181
+ "entity_file": "chemprot_sample_entities.tsv",
182
+ "relation_file": "chemprot_sample_relations.tsv",
183
+ "gold_standard_file": "chemprot_sample_gold_standard.tsv",
184
+ "split": "sample",
185
+ },
186
+ ),
187
+ datasets.SplitGenerator(
188
+ name=datasets.Split.TRAIN,
189
+ gen_kwargs={
190
+ "filepath": os.path.join(train_path, "chemprot_training"),
191
+ "abstract_file": "chemprot_training_abstracts.tsv",
192
+ "entity_file": "chemprot_training_entities.tsv",
193
+ "relation_file": "chemprot_training_relations.tsv",
194
+ "gold_standard_file": "chemprot_training_gold_standard.tsv",
195
+ "split": "train",
196
+ },
197
+ ),
198
+ datasets.SplitGenerator(
199
+ name=datasets.Split.TEST,
200
+ gen_kwargs={
201
+ "filepath": os.path.join(test_path, "chemprot_test_gs"),
202
+ "abstract_file": "chemprot_test_abstracts_gs.tsv",
203
+ "entity_file": "chemprot_test_entities_gs.tsv",
204
+ "relation_file": "chemprot_test_relations_gs.tsv",
205
+ "gold_standard_file": "chemprot_test_gold_standard.tsv",
206
+ "split": "test",
207
+ },
208
+ ),
209
+ datasets.SplitGenerator(
210
+ name=datasets.Split.VALIDATION,
211
+ gen_kwargs={
212
+ "filepath": os.path.join(dev_path, "chemprot_development"),
213
+ "abstract_file": "chemprot_development_abstracts.tsv",
214
+ "entity_file": "chemprot_development_entities.tsv",
215
+ "relation_file": "chemprot_development_relations.tsv",
216
+ "gold_standard_file": "chemprot_development_gold_standard.tsv",
217
+ "split": "dev",
218
+ },
219
+ ),
220
+ ]
221
+
222
+ def _generate_examples(
223
+ self,
224
+ filepath,
225
+ abstract_file,
226
+ entity_file,
227
+ relation_file,
228
+ gold_standard_file,
229
+ split,
230
+ ):
231
+ """Yields examples as (key, example) tuples."""
232
+ if self.config.schema == "source":
233
+ abstracts = self._get_abstract(os.path.join(filepath, abstract_file))
234
+
235
+ entities, entity_id = self._get_entities(
236
+ os.path.join(filepath, entity_file)
237
+ )
238
+
239
+ if self.config.subset_id == "chemprot_full":
240
+ relations = self._get_relations(os.path.join(filepath, relation_file))
241
+ elif self.config.subset_id == "chemprot_shared_task_eval":
242
+ relations = self._get_relations_gs(
243
+ os.path.join(filepath, gold_standard_file)
244
+ )
245
+ else:
246
+ raise ValueError(self.config)
247
+
248
+ for id_, pmid in enumerate(abstracts.keys()):
249
+ yield id_, {
250
+ "pmid": pmid,
251
+ "text": abstracts[pmid],
252
+ "entities": entities[pmid],
253
+ "relations": relations.get(pmid, []),
254
+ }
255
+
256
+ elif self.config.schema == "bigbio_kb":
257
+
258
+ abstracts = self._get_abstract(os.path.join(filepath, abstract_file))
259
+ entities, entity_id = self._get_entities(
260
+ os.path.join(filepath, entity_file)
261
+ )
262
+ relations = self._get_relations(
263
+ os.path.join(filepath, relation_file), is_mapped=True
264
+ )
265
+
266
+ uid = 0
267
+ for id_, pmid in enumerate(abstracts.keys()):
268
+ data = {
269
+ "id": str(uid),
270
+ "document_id": str(pmid),
271
+ "passages": [],
272
+ "entities": [],
273
+ "relations": [],
274
+ "events": [],
275
+ "coreferences": [],
276
+ }
277
+ uid += 1
278
+
279
+ data["passages"] = [
280
+ {
281
+ "id": str(uid),
282
+ "type": "title and abstract",
283
+ "text": [abstracts[pmid]],
284
+ "offsets": [[0, len(abstracts[pmid])]],
285
+ }
286
+ ]
287
+ uid += 1
288
+
289
+ entity_to_id = {}
290
+ for entity in entities[pmid]:
291
+ _text = entity["text"]
292
+ entity.update({"text": [_text]})
293
+ entity_to_id[entity["id"]] = str(uid)
294
+ entity.update({"id": str(uid)})
295
+ _offsets = entity["offsets"]
296
+ entity.update({"offsets": [_offsets]})
297
+ entity["normalized"] = []
298
+ data["entities"].append(entity)
299
+ uid += 1
300
+
301
+ for relation in relations.get(pmid, []):
302
+ relation["arg1_id"] = entity_to_id[relation.pop("arg1")]
303
+ relation["arg2_id"] = entity_to_id[relation.pop("arg2")]
304
+ relation.update({"id": str(uid)})
305
+ relation["normalized"] = []
306
+ data["relations"].append(relation)
307
+ uid += 1
308
+
309
+ yield id_, data
310
+
311
+ @staticmethod
312
+ def _get_abstract(abs_filename: str) -> Dict[str, str]:
313
+ """
314
+ For each document in PubMed ID (PMID) in the ChemProt abstract data file, return the abstract. Data is tab-separated.
315
+
316
+ :param filename: `*_abstracts.tsv from ChemProt
317
+
318
+ :returns Dictionary with PMID keys and abstract text as values.
319
+ """
320
+ with open(abs_filename, "r") as f:
321
+ contents = [i.strip() for i in f.readlines()]
322
+
323
+ # PMID is the first column, Abstract is last
324
+ return {
325
+ doc.split("\t")[0]: "\n".join(doc.split("\t")[1:]) for doc in contents
326
+ } # Includes title as line 1
327
+
328
+ @staticmethod
329
+ def _get_entities(ents_filename: str) -> Tuple[Dict[str, str]]:
330
+ """
331
+ For each document in the corpus, return entity annotations per PMID.
332
+ Each column in the entity file is as follows:
333
+ (1) PMID
334
+ (2) Entity Number
335
+ (3) Entity Type (Chemical, Gene-Y, Gene-N)
336
+ (4) Start index
337
+ (5) End index
338
+ (6) Actual text of entity
339
+
340
+ :param ents_filename: `_*entities.tsv` file from ChemProt
341
+
342
+ :returns: Dictionary with PMID keys and entity annotations.
343
+ """
344
+ with open(ents_filename, "r") as f:
345
+ contents = [i.strip() for i in f.readlines()]
346
+
347
+ entities = {}
348
+ entity_id = {}
349
+
350
+ for line in contents:
351
+
352
+ pmid, idx, label, start_offset, end_offset, name = line.split("\t")
353
+
354
+ # Populate entity dictionary
355
+ if pmid not in entities:
356
+ entities[pmid] = []
357
+
358
+ ann = {
359
+ "offsets": [int(start_offset), int(end_offset)],
360
+ "text": name,
361
+ "type": label,
362
+ "id": idx,
363
+ }
364
+
365
+ entities[pmid].append(ann)
366
+
367
+ # Populate entity mapping
368
+ entity_id.update({idx: name})
369
+
370
+ return entities, entity_id
371
+
372
+ @staticmethod
373
+ def _get_relations(rel_filename: str, is_mapped: bool = False) -> Dict[str, str]:
374
+ """For each document in the ChemProt corpus, create an annotation for all relationships.
375
+
376
+ :param is_mapped: Whether to convert into NL the relation tags. Default is OFF
377
+ """
378
+ with open(rel_filename, "r") as f:
379
+ contents = [i.strip() for i in f.readlines()]
380
+
381
+ relations = {}
382
+
383
+ for line in contents:
384
+ pmid, label, _, _, arg1, arg2 = line.split("\t")
385
+ arg1 = arg1.split("Arg1:")[-1]
386
+ arg2 = arg2.split("Arg2:")[-1]
387
+
388
+ if pmid not in relations:
389
+ relations[pmid] = []
390
+
391
+ if is_mapped:
392
+ label = _GROUP_LABELS[label]
393
+
394
+ ann = {
395
+ "type": label,
396
+ "arg1": arg1,
397
+ "arg2": arg2,
398
+ }
399
+
400
+ relations[pmid].append(ann)
401
+
402
+ return relations
403
+
404
+ @staticmethod
405
+ def _get_relations_gs(rel_filename: str, is_mapped: bool = False) -> Dict[str, str]:
406
+ """
407
+ For each document in the ChemProt corpus, create an annotation for the gold-standard relationships.
408
+
409
+ The columns include:
410
+ (1) PMID
411
+ (2) Relationship Label (CPR)
412
+ (3) Used in shared task
413
+ (3) Interactor Argument 1 Entity Identifier
414
+ (4) Interactor Argument 2 Entity Identifier
415
+
416
+ Gold standard includes CPRs 3-9. Relationships are always Gene + Protein.
417
+ Unlike entities, there is no counter, hence once must be made
418
+
419
+ :param rel_filename: Gold standard file name
420
+ :param ent_dict: Entity Identifier to text
421
+ """
422
+ with open(rel_filename, "r") as f:
423
+ contents = [i.strip() for i in f.readlines()]
424
+
425
+ relations = {}
426
+
427
+ for line in contents:
428
+ pmid, label, arg1, arg2 = line.split("\t")
429
+ arg1 = arg1.split("Arg1:")[-1]
430
+ arg2 = arg2.split("Arg2:")[-1]
431
+
432
+ if pmid not in relations:
433
+ relations[pmid] = []
434
+
435
+ if is_mapped:
436
+ label = _GROUP_LABELS[label]
437
+
438
+ ann = {
439
+ "type": label,
440
+ "arg1": arg1,
441
+ "arg2": arg2,
442
+ }
443
+
444
+ relations[pmid].append(ann)
445
+
446
+ return relations