Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 10,644 Bytes
6bb60df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import itertools
import os
from pydoc import doc
from typing import Dict, Iterator, List, Tuple

import datasets

from .bigbiohub import kb_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks

_LANGUAGES = ['English']
_PUBMED = True
_LOCAL = False
_CITATION = """\
@article{wei2018tmvar,
title={tmVar 2.0: integrating genomic variant information from literature with dbSNP and ClinVar for precision medicine},
author={Wei, Chih-Hsuan and Phan, Lon and Feltz, Juliana and Maiti, Rama and Hefferon, Tim and Lu, Zhiyong},
journal={Bioinformatics},
volume={34},
number={1},
pages={80--87},
year={2018},
publisher={Oxford University Press}
}
"""

_DATASETNAME = "tmvar_v2"
_DISPLAYNAME = "tmVar v2"

_DESCRIPTION = """This dataset contains 158 PubMed articles manually annotated with mutation mentions of various kinds and dbsnp normalizations for each of them.
It can be used for NER tasks and NED tasks, This dataset has a single split"""

_HOMEPAGE = "https://www.ncbi.nlm.nih.gov/research/bionlp/Tools/tmvar/"

_LICENSE = 'License information unavailable'

_URLS = {
    _DATASETNAME: "https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/tmTools/download/tmVar/tmVar.Normalization.txt",
}

_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.NAMED_ENTITY_DISAMBIGUATION]

_SOURCE_VERSION = "2.0.0"

_BIGBIO_VERSION = "1.0.0"

logger = datasets.utils.logging.get_logger(__name__)


class TmvarV2Dataset(datasets.GeneratorBasedBuilder):
    """
    This dataset contains 158 PubMed articles manually annotated with mutation mentions of various kinds and dbsnp normalizations for each of them.
    """

    DEFAULT_CONFIG_NAME = "tmvar_v2_source"
    SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
    BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)

    BUILDER_CONFIGS = []
    BUILDER_CONFIGS.append(
        BigBioConfig(
            name=f"{_DATASETNAME}_source",
            version=SOURCE_VERSION,
            description=f"{_DATASETNAME} source schema",
            schema="source",
            subset_id=f"{_DATASETNAME}",
        )
    )
    BUILDER_CONFIGS.append(
        BigBioConfig(
            name=f"{_DATASETNAME}_bigbio_kb",
            version=BIGBIO_VERSION,
            description=f"{_DATASETNAME} BigBio schema",
            schema="bigbio_kb",
            subset_id=f"{_DATASETNAME}",
        )
    )

    def _info(self) -> datasets.DatasetInfo:

        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "pmid": datasets.Value("string"),
                    "passages": [
                        {
                            "type": datasets.Value("string"),
                            "text": datasets.Value("string"),
                            "offsets": [datasets.Value("int32")],
                        }
                    ],
                    "entities": [
                        {
                            "text": datasets.Value("string"),
                            "offsets": [datasets.Value("int32")],
                            "concept_id": datasets.Value("string"),
                            "semantic_type_id": datasets.Value("string"),
                            "rsid": datasets.Value("string"),
                        }
                    ],
                }
            )
        elif self.config.schema == "bigbio_kb":
            features = kb_features

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=str(_LICENSE),
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
        """Returns SplitGenerators."""

        url = _URLS[_DATASETNAME]
        train_filepath = dl_manager.download(url)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": train_filepath,
                },
            )
        ]

    def _generate_examples(self, filepath) -> Tuple[int, Dict]:
        """Yields examples as (key, example) tuples."""
        if self.config.schema == "source":
            with open(filepath, "r", encoding="utf8") as fstream:
                for raw_document in self.generate_raw_docs(fstream):
                    document = self.parse_raw_doc(raw_document)
                    yield document["pmid"], document

        elif self.config.schema == "bigbio_kb":
            with open(filepath, "r", encoding="utf8") as fstream:
                uid = itertools.count(0)
                for raw_document in self.generate_raw_docs(fstream):
                    document = self.parse_raw_doc(raw_document)
                    document["id"] = next(uid)
                    document["document_id"] = document.pop("pmid")

                    entities_ = []
                    for entity in document["entities"]:
                        if entity.get("rsid", ""):
                            normalized = [
                                {
                                    "db_name": "dbsnp",
                                    "db_id": entity.get("rsid").split(":")[1],
                                }
                            ]
                        else:
                            normalized = []

                        entities_.append(
                            {
                                "id": next(uid),
                                "type": entity["semantic_type_id"],
                                "text": [entity["text"]],
                                "normalized": normalized,
                                "offsets": [entity["offsets"]],
                            }
                        )
                    for passage in document["passages"]:
                        passage["id"] = next(uid)

                    document["entities"] = entities_
                    document["relations"] = []
                    document["events"] = []
                    document["coreferences"] = []

                    yield document["document_id"], document

    def generate_raw_docs(self, fstream):
        """
        Given a filestream, this function yields documents from it
        """
        raw_document = []
        for line in fstream:
            if line.strip():
                raw_document.append(line.strip())
            elif raw_document:
                yield raw_document
                raw_document = []
        if raw_document:
            yield raw_document

    def parse_raw_doc(self, raw_doc):
        pmid, _, title = raw_doc[0].split("|")
        pmid = int(pmid)
        _, _, abstract = raw_doc[1].split("|")

        if self.config.schema == "source":
            passages = [
                {"type": "title", "text": title, "offsets": [0, len(title)]},
                {
                    "type": "abstract",
                    "text": abstract,
                    "offsets": [len(title) + 1, len(title) + len(abstract) + 1],
                },
            ]
        elif self.config.schema == "bigbio_kb":
            passages = [
                {"type": "title", "text": [title], "offsets": [[0, len(title)]]},
                {
                    "type": "abstract",
                    "text": [abstract],
                    "offsets": [[len(title) + 1, len(title) + len(abstract) + 1]],
                },
            ]

        entities = []
        for count, line in enumerate(raw_doc[2:]):
            line_pieces = line.split("\t")
            if len(line_pieces) == 6:
                if pmid == 18166824 and count == 0:
                    # this example has the following text
                    # 18166824    880    948    amino acid (proline) with a polar amino acid (serine) at position 29    p|SUB|P|29|S    RSID:2075789
                    # it is missing the semantic_type_id between `... position 29` and `p|SUB|P|29|S`
                    pmid_ = str(pmid)
                    start_idx = "880"
                    end_idx = "948"
                    mention = "amino acid (proline) with a polar amino acid (serine) at position 29"
                    semantic_type_id = "ProteinMutation"
                    entity_id = "p|SUB|P|29|S"
                    rsid = "RSID:2075789"
                    assert line_pieces[0] == pmid_
                    assert line_pieces[1] == start_idx
                    assert line_pieces[2] == end_idx
                    assert line_pieces[3] == mention
                    assert line_pieces[4] == entity_id
                    assert line_pieces[5] == rsid
                    logger.info(
                        f"Adding ProteinMutation semantic_type_id in Document ID: {pmid} Line: {line}"
                    )
                else:
                    (
                        pmid_,
                        start_idx,
                        end_idx,
                        mention,
                        semantic_type_id,
                        entity_id,
                    ) = line_pieces
                    rsid = None

            elif len(line_pieces) == 7:
                (
                    pmid_,
                    start_idx,
                    end_idx,
                    mention,
                    semantic_type_id,
                    entity_id,
                    rsid,
                ) = line_pieces

            else:
                logger.info(
                    f"Inconsistent entity format found. Skipping Document ID: {pmid} Line: {line}"
                )
                continue

            entity = {
                "offsets": [int(start_idx), int(end_idx)],
                "text": mention,
                "semantic_type_id": semantic_type_id,
                "concept_id": entity_id,
                "rsid": rsid,
            }
            entities.append(entity)

        return {"pmid": pmid, "passages": passages, "entities": entities}