gabrielaltay commited on
Commit
d6637c6
1 Parent(s): 4267eb3

upload hubscripts/pubtator_central_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. pubtator_central.py +305 -0
pubtator_central.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ PubTator Central (PTC, https://www.ncbi.nlm.nih.gov/research/pubtator/) [1] is a web service for
18
+ exploring and retrieving bioconcept annotations in full text biomedical articles. PTC provides
19
+ automated annotations from state-of-the-art text mining systems for genes/proteins, genetic
20
+ variants, diseases, chemicals, species and cell lines, all available for immediate download. PTC
21
+ annotates PubMed (30 million abstracts), the PMC Open Access Subset and the Author Manuscript
22
+ Collection (3 million full text articles). Updated entity identification methods and a
23
+ disambiguation module [2] based on cutting-edge deep learning techniques provide increased accuracy.
24
+ This FTP repository aggregated all the bio-entity annotations in PTC in tab-separated text format.
25
+ The files are expected to be updated monthly.
26
+
27
+ REFERENCE:
28
+ ---------------------------------------------------------------------------
29
+ [1] Wei C-H, Allot A, Leaman R and Lu Z (2019) "PubTator Central: Automated Concept Annotation for
30
+ Biomedical Full Text Articles", Nucleic Acids Res.
31
+ [2] wei C-H, et al., (2019) "Biomedical Mention Disambiguation Using a Deep Learning Approach",
32
+ ACM-BCB 2019, September 7-10, 2019, Niagara Falls, NY, USA.
33
+ [3] Wei C-H, Kao H-Y, Lu Z (2015) "GNormPlus: An Integrative Approach for Tagging Gene, Gene Family
34
+ and Protein Domain", 2015, Article ID 918710
35
+ [4] Leaman R and Lu Z (2013) "TaggerOne: joint named entity recognition and normalization with
36
+ semi-Markov Models", Bioinformatics, 32(18): 839-2846
37
+ [5] Wei C-H, Kao H-Y, Lu Z (2012) "SR4GN: a species recognition software tool for gene normalization",
38
+ PLoS ONE,7(6):e38460
39
+ [6] Wei C-H, et al., (2017) "Integrating genomic variant information from literature with dbSNP and
40
+ ClinVar for precision medicine", Bioinformatics,34(1): 80-87
41
+ """
42
+
43
+
44
+ from typing import Dict, Iterator, List, Tuple
45
+
46
+ import datasets
47
+ from bioc import pubtator
48
+
49
+ from .bigbiohub import kb_features
50
+ from .bigbiohub import BigBioConfig
51
+ from .bigbiohub import Tasks
52
+
53
+ _LANGUAGES = ['English']
54
+ _PUBMED = True
55
+ _LOCAL = False
56
+ _CITATION = """\
57
+ @article{10.1093/nar/gkz389,
58
+ title = {{PubTator central: automated concept annotation for biomedical full text articles}},
59
+ author = {Wei, Chih-Hsuan and Allot, Alexis and Leaman, Robert and Lu, Zhiyong},
60
+ year = 2019,
61
+ month = {05},
62
+ journal = {Nucleic Acids Research},
63
+ volume = 47,
64
+ number = {W1},
65
+ pages = {W587-W593},
66
+ doi = {10.1093/nar/gkz389},
67
+ issn = {0305-1048},
68
+ url = {https://doi.org/10.1093/nar/gkz389},
69
+ eprint = {https://academic.oup.com/nar/article-pdf/47/W1/W587/28880193/gkz389.pdf}
70
+ }
71
+ """
72
+
73
+ _DATASETNAME = "pubtator_central"
74
+ _DISPLAYNAME = "PubTator Central"
75
+
76
+ _DESCRIPTION = """\
77
+ PubTator Central (PTC, https://www.ncbi.nlm.nih.gov/research/pubtator/) is a web service for
78
+ exploring and retrieving bioconcept annotations in full text biomedical articles. PTC provides
79
+ automated annotations from state-of-the-art text mining systems for genes/proteins, genetic
80
+ variants, diseases, chemicals, species and cell lines, all available for immediate download. PTC
81
+ annotates PubMed (30 million abstracts), the PMC Open Access Subset and the Author Manuscript
82
+ Collection (3 million full text articles). Updated entity identification methods and a
83
+ disambiguation module based on cutting-edge deep learning techniques provide increased accuracy.
84
+ """
85
+
86
+ _HOMEPAGE = "https://www.ncbi.nlm.nih.gov/research/pubtator/"
87
+
88
+ _LICENSE = 'National Center fr Biotechnology Information PUBLIC DOMAIN NOTICE'
89
+
90
+ _URLS = {
91
+ "sample": "https://ftp.ncbi.nlm.nih.gov/pub/lu/PubTatorCentral/bioconcepts2pubtatorcentral.offset.sample",
92
+ "full": "https://ftp.ncbi.nlm.nih.gov/pub/lu/PubTatorCentral/bioconcepts2pubtatorcentral.offset.gz",
93
+ }
94
+
95
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.NAMED_ENTITY_DISAMBIGUATION]
96
+
97
+ _SOURCE_VERSION = "2022.01.08"
98
+ _BIGBIO_VERSION = "1.0.0"
99
+
100
+ # Maps the entity types in PubTator to the name of the database they are grounded to
101
+ _TYPE_TO_DB_NAME = {
102
+ "Gene": "ncbi_gene",
103
+ "Disease": "mesh",
104
+ "Species": "ncbi_taxon",
105
+ "Chemical": "mesh",
106
+ "CellLine": "cellosaurus",
107
+ }
108
+
109
+ _DB_NAME_TO_URL = {
110
+ "ncbi_gene": "https://www.ncbi.nlm.nih.gov/gene/",
111
+ "mesh": "https://www.nlm.nih.gov/mesh/meshhome.html",
112
+ "ncbi_taxon": "https://www.ncbi.nlm.nih.gov/taxonomy/",
113
+ "cellosaurus": "https://web.expasy.org/cellosaurus/",
114
+ "ncbi_dbsnp": "https://www.ncbi.nlm.nih.gov/snp/",
115
+ "tmvar": "https://www.ncbi.nlm.nih.gov/research/bionlp/Tools/tmvar/",
116
+ }
117
+
118
+
119
+ class PubtatorCentralDataset(datasets.GeneratorBasedBuilder):
120
+ """PubTator Central"""
121
+
122
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
123
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
124
+
125
+ BUILDER_CONFIGS = [
126
+ # sample source
127
+ BigBioConfig(
128
+ name="pubtator_central_sample_source",
129
+ version=SOURCE_VERSION,
130
+ description="PubTator Central sample source schema",
131
+ schema="source",
132
+ subset_id="pubtator_central_sample",
133
+ ),
134
+ # sample big bio
135
+ BigBioConfig(
136
+ name="pubtator_central_sample_bigbio_kb",
137
+ version=BIGBIO_VERSION,
138
+ description="PubTator Central sample BigBio schema",
139
+ schema="bigbio_kb",
140
+ subset_id="pubtator_central_sample",
141
+ ),
142
+ # full dataset source
143
+ BigBioConfig(
144
+ name="pubtator_central_source",
145
+ version=SOURCE_VERSION,
146
+ description="PubTator Central source schema",
147
+ schema="source",
148
+ subset_id="pubtator_central",
149
+ ),
150
+ # full dataset bigbio
151
+ BigBioConfig(
152
+ name="pubtator_central_bigbio_kb",
153
+ version=BIGBIO_VERSION,
154
+ description="PubTator Central BigBio schema",
155
+ schema="bigbio_kb",
156
+ subset_id="pubtator_central",
157
+ ),
158
+ ]
159
+
160
+ DEFAULT_CONFIG_NAME = "pubtator_central_source"
161
+
162
+ def _info(self) -> datasets.DatasetInfo:
163
+
164
+ if self.config.schema == "source":
165
+ features = datasets.Features(
166
+ {
167
+ "pmid": datasets.Value("string"),
168
+ "title": datasets.Value("string"),
169
+ "abstract": datasets.Value("string"),
170
+ "mentions": [
171
+ {
172
+ "concept_id": datasets.Value("string"),
173
+ "type": datasets.Value("string"),
174
+ "text": datasets.Value("string"),
175
+ "offsets": datasets.Sequence(datasets.Value("int32")),
176
+ }
177
+ ],
178
+ }
179
+ )
180
+
181
+ elif self.config.schema == "bigbio_kb":
182
+ features = kb_features
183
+
184
+ return datasets.DatasetInfo(
185
+ description=_DESCRIPTION,
186
+ features=features,
187
+ homepage=_HOMEPAGE,
188
+ license=str(_LICENSE),
189
+ citation=_CITATION,
190
+ )
191
+
192
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
193
+ """Returns SplitGenerators."""
194
+ urls = (
195
+ _URLS["sample"]
196
+ if self.config.subset_id.endswith("sample")
197
+ else _URLS["full"]
198
+ )
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,
206
+ "split": "train",
207
+ },
208
+ ),
209
+ ]
210
+
211
+ def _generate_examples(
212
+ self, filepath: str, split: str
213
+ ) -> Iterator[Tuple[str, Dict]]:
214
+ if self.config.schema == "source":
215
+ for source_example in self._pubtator_to_source(filepath):
216
+ yield source_example["pmid"], source_example
217
+
218
+ elif self.config.schema == "bigbio_kb":
219
+ for kb_example in self._pubtator_to_bigbio_kb(filepath):
220
+ yield kb_example["id"], kb_example
221
+
222
+ @staticmethod
223
+ def _pubtator_to_source(filepath: Dict) -> Iterator[Dict]:
224
+ with open(filepath, "r") as f:
225
+ for doc in pubtator.iterparse(f):
226
+ source_example = {
227
+ "pmid": doc.pmid,
228
+ "title": doc.title,
229
+ "abstract": doc.abstract,
230
+ "mentions": [
231
+ {
232
+ "concept_id": mention.id,
233
+ "type": mention.type,
234
+ "text": mention.text,
235
+ "offsets": [mention.start, mention.end],
236
+ }
237
+ for mention in doc.annotations
238
+ ],
239
+ }
240
+ yield source_example
241
+
242
+ def _pubtator_to_bigbio_kb(self, filepath: Dict) -> Iterator[Dict]:
243
+ with open(filepath, "r") as f:
244
+ unified_example = {}
245
+ for doc in pubtator.iterparse(f):
246
+ unified_example["id"] = doc.pmid
247
+ unified_example["document_id"] = doc.pmid
248
+
249
+ unified_example["passages"] = [
250
+ {
251
+ "id": doc.pmid + "_title",
252
+ "type": "title",
253
+ "text": [doc.title],
254
+ "offsets": [[0, len(doc.title)]],
255
+ },
256
+ {
257
+ "id": doc.pmid + "_abstract",
258
+ "type": "abstract",
259
+ "text": [doc.abstract],
260
+ "offsets": [
261
+ [
262
+ # +1 assumes the title and abstract will be joined by a space.
263
+ len(doc.title) + 1,
264
+ len(doc.title) + 1 + len(doc.abstract),
265
+ ]
266
+ ],
267
+ },
268
+ ]
269
+
270
+ unified_entities = []
271
+ for i, entity in enumerate(doc.annotations):
272
+ # We need a unique identifier for this entity, so build it from the document id and entity id
273
+ unified_entity_id = "_".join([doc.pmid, entity.id, str(i)])
274
+ # Determining db_name is tricky so use a helper to determine this from the entity annotation
275
+ db_name = self._get_db_name(entity)
276
+ unified_entities.append(
277
+ {
278
+ "id": unified_entity_id,
279
+ "type": entity.type,
280
+ "text": [entity.text],
281
+ "offsets": [[entity.start, entity.end]],
282
+ "normalized": [{"db_name": db_name, "db_id": entity.id}],
283
+ }
284
+ )
285
+
286
+ unified_example["entities"] = unified_entities
287
+ unified_example["relations"] = []
288
+ unified_example["events"] = []
289
+ unified_example["coreferences"] = []
290
+
291
+ yield unified_example
292
+
293
+ @staticmethod
294
+ def _get_db_name(entity: pubtator.PubTatorAnn) -> str:
295
+ if entity.type in _TYPE_TO_DB_NAME:
296
+ db_name = _TYPE_TO_DB_NAME[entity.type]
297
+ elif entity.type in ["Mutation", "ProteinMutation", "DNAMutation"]:
298
+ # Mutation anntotations are grounded to either tmVar or dbSNP
299
+ if entity.id.startswith("tmVar"):
300
+ db_name = "tmVar"
301
+ else:
302
+ db_name = "ncbi_dbsnp"
303
+ else:
304
+ db_name = "unknown"
305
+ return db_name