Datasets:

Languages:
English
License:
gabrielaltay commited on
Commit
90131cc
1 Parent(s): e5d0ba0

upload hubscripts/nlm_wsd_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. nlm_wsd.py +362 -0
nlm_wsd.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ In order to support research investigating the automatic resolution of word sense ambiguity using natural language
18
+ processing techniques, we have constructed this test collection of medical text in which the ambiguities were resolved
19
+ by hand. Evaluators were asked to examine instances of an ambiguous word and determine the sense intended by selecting
20
+ the Metathesaurus concept (if any) that best represents the meaning of that sense. The test collection consists of 50
21
+ highly frequent ambiguous UMLS concepts from 1998 MEDLINE. Each of the 50 ambiguous cases has 100 ambiguous instances
22
+ randomly selected from the 1998 MEDLINE citations. For a total of 5,000 instances. We had a total of 11 evaluators of
23
+ which 8 completed 100% of the 5,000 instances, 1 completed 56%, 1 completed 44%, and the final evaluator completed 12%
24
+ of the instances. Evaluations were only used when the evaluators completed all 100 instances for a given ambiguity.
25
+
26
+ Comment from author:
27
+ BigBio schema fixes off by one error of end offset of entities. The source config remains unchanged.
28
+
29
+ Instructions on how to load locally:
30
+ 1) Create directory
31
+ 2) Download one of the following annotation sets from https://lhncbc.nlm.nih.gov/restricted/ii/areas/WSD/index.html
32
+ and put it into the folder:
33
+ - Full Reviewed Set
34
+ https://lhncbc.nlm.nih.gov/restricted/ii/areas/WSD/downloads/full_reviewed_results.tar.gz
35
+ (Link "Full Reviewed Result Set (requires Common Files above)")
36
+ subset_id = nlm_wsd_reviewed
37
+ - Full Non-Reviewed Set
38
+ https://lhncbc.nlm.nih.gov/restricted/ii/areas/WSD/downloads/full_non_reviewed_results.tar.gz
39
+ (Link "Full Non-Reviewed Result Set (requires Common Files above)")
40
+ subset_id = nlm_wsd_non_reviewed
41
+ 3) Download https://lhncbc.nlm.nih.gov/restricted/ii/areas/WSD/downloads/UMLS1999.tar.gz (Link "1999 UMLS Data Files")
42
+ and put it into the folder
43
+ 4) Set kwarg data_dir of load_datasets to the path of the directory
44
+ """
45
+
46
+ import itertools as it
47
+ import re
48
+ from dataclasses import dataclass
49
+ from pathlib import Path
50
+ from typing import Dict, List, Tuple
51
+
52
+ import datasets
53
+
54
+ from .bigbiohub import kb_features
55
+ from .bigbiohub import BigBioConfig
56
+ from .bigbiohub import Tasks
57
+
58
+ _LANGUAGES = ['English']
59
+ _PUBMED = True
60
+ _LOCAL = True
61
+ _CITATION = """\
62
+ @article{weeber2001developing,
63
+ title = "Developing a test collection for biomedical word sense
64
+ disambiguation",
65
+ author = "Weeber, M and Mork, J G and Aronson, A R",
66
+ journal = "Proc AMIA Symp",
67
+ pages = "746--750",
68
+ year = 2001,
69
+ language = "en"
70
+ }
71
+ """
72
+
73
+ _DATASETNAME = "nlm_wsd"
74
+ _DISPLAYNAME = "NLM WSD"
75
+
76
+ _DESCRIPTION = """\
77
+ In order to support research investigating the automatic resolution of word sense ambiguity using natural language
78
+ processing techniques, we have constructed this test collection of medical text in which the ambiguities were resolved
79
+ by hand. Evaluators were asked to examine instances of an ambiguous word and determine the sense intended by selecting
80
+ the Metathesaurus concept (if any) that best represents the meaning of that sense. The test collection consists of 50
81
+ highly frequent ambiguous UMLS concepts from 1998 MEDLINE. Each of the 50 ambiguous cases has 100 ambiguous instances
82
+ randomly selected from the 1998 MEDLINE citations. For a total of 5,000 instances. We had a total of 11 evaluators of
83
+ which 8 completed 100% of the 5,000 instances, 1 completed 56%, 1 completed 44%, and the final evaluator completed 12%
84
+ of the instances. Evaluations were only used when the evaluators completed all 100 instances for a given ambiguity.
85
+ """
86
+
87
+ _HOMEPAGE = "https://lhncbc.nlm.nih.gov/restricted/ii/areas/WSD/index.html"
88
+
89
+ _LICENSE = 'UMLS - Metathesaurus License Agreement'
90
+
91
+ _URLS = {
92
+ "UMLS": "UMLS1999.tar.gz",
93
+ "reviewed": "full_reviewed_results.tar.gz",
94
+ "non_reviewed": "full_non_reviewed_results.tar.gz",
95
+ }
96
+
97
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_DISAMBIGUATION]
98
+
99
+ _SOURCE_VERSION = "1.0.0"
100
+ _BIGBIO_VERSION = "1.0.0"
101
+
102
+
103
+ @dataclass
104
+ class NlmWsdBigBioConfig(BigBioConfig):
105
+ schema: str = "source"
106
+ name: str = "nlm_wsd_reviewed_source"
107
+ version: datasets.Version = datasets.Version(_SOURCE_VERSION)
108
+ description: str = "NLM-WSD basic reviewed source schema"
109
+ subset_id: str = "nlm_wsd_reviewed"
110
+
111
+
112
+ class NlmWsdDataset(datasets.GeneratorBasedBuilder):
113
+ """Biomedical Word Sense Disambiguation (WSD)."""
114
+
115
+ uid = it.count(0)
116
+
117
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
118
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
119
+
120
+ BUILDER_CONFIGS = [
121
+ NlmWsdBigBioConfig(
122
+ name="nlm_wsd_non_reviewed_source",
123
+ version=SOURCE_VERSION,
124
+ description="NLM-WSD basic non reviewed source schema",
125
+ schema="source",
126
+ subset_id="nlm_wsd_non_reviewed",
127
+ ),
128
+ NlmWsdBigBioConfig(
129
+ name="nlm_wsd_non_reviewed_bigbio_kb",
130
+ version=BIGBIO_VERSION,
131
+ description="NLM-WSD basic non reviewed BigBio schema",
132
+ schema="bigbio_kb",
133
+ subset_id="nlm_wsd_non_reviewed",
134
+ ),
135
+ NlmWsdBigBioConfig(
136
+ name="nlm_wsd_reviewed_source",
137
+ version=SOURCE_VERSION,
138
+ description="NLM-WSD basic reviewed source schema",
139
+ schema="source",
140
+ subset_id="nlm_wsd_reviewed",
141
+ ),
142
+ NlmWsdBigBioConfig(
143
+ name="nlm_wsd_reviewed_bigbio_kb",
144
+ version=BIGBIO_VERSION,
145
+ description="NLM-WSD basic reviewed BigBio schema",
146
+ schema="bigbio_kb",
147
+ subset_id="nlm_wsd_reviewed",
148
+ ),
149
+ ]
150
+
151
+ BUILDER_CONFIG_CLASS = NlmWsdBigBioConfig
152
+
153
+ def _info(self) -> datasets.DatasetInfo:
154
+ if self.config.schema == "source":
155
+ features = datasets.Features(
156
+ {
157
+ "id": datasets.Value("string"),
158
+ "sentence_id": datasets.Value("string"),
159
+ "label": datasets.Value("string"),
160
+ "sentence": {
161
+ "text": datasets.Value("string"),
162
+ "ambiguous_word": datasets.Value("string"),
163
+ "ambiguous_word_alias": datasets.Value("string"),
164
+ "offsets_context": datasets.Sequence(datasets.Value("int32")),
165
+ "offsets_ambiguity": datasets.Sequence(datasets.Value("int32")),
166
+ "context": datasets.Value("string"),
167
+ },
168
+ "citation": {
169
+ "text": datasets.Value("string"),
170
+ "ambiguous_word": datasets.Value("string"),
171
+ "ambiguous_word_alias": datasets.Value("string"),
172
+ "offsets_context": datasets.Sequence(datasets.Value("int32")),
173
+ "offsets_ambiguity": datasets.Sequence(datasets.Value("int32")),
174
+ "context": datasets.Value("string"),
175
+ },
176
+ "choices": [
177
+ {
178
+ "label": datasets.Value("string"),
179
+ "concept": datasets.Value("string"),
180
+ "cui": datasets.Value("string"),
181
+ "type": [datasets.Value("string")],
182
+ }
183
+ ],
184
+ }
185
+ )
186
+ elif self.config.schema == "bigbio_kb":
187
+ features = kb_features
188
+
189
+ return datasets.DatasetInfo(
190
+ description=_DESCRIPTION,
191
+ features=features,
192
+ homepage=_HOMEPAGE,
193
+ license=str(_LICENSE),
194
+ citation=_CITATION,
195
+ )
196
+
197
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
198
+ """Returns SplitGenerators."""
199
+
200
+ if self.config.data_dir is None:
201
+ raise ValueError(
202
+ "This is a local dataset. Please pass the data_dir kwarg to load_dataset."
203
+ )
204
+ else:
205
+ data_dir = Path(self.config.data_dir)
206
+ umls_dir = dl_manager.download_and_extract(data_dir / _URLS["UMLS"])
207
+ mrcon_path = Path(umls_dir) / "META" / "MRCON"
208
+ if self.config.subset_id == "nlm_wsd_reviewed":
209
+ ann_dir = dl_manager.download_and_extract(data_dir / _URLS["reviewed"])
210
+ ann_dir = Path(ann_dir) / "Reviewed_Results"
211
+ else:
212
+ ann_dir = dl_manager.download_and_extract(
213
+ data_dir / _URLS["non_reviewed"]
214
+ )
215
+ ann_dir = Path(ann_dir) / "Non-Reviewed_Results"
216
+
217
+ return [
218
+ datasets.SplitGenerator(
219
+ name=datasets.Split.TRAIN,
220
+ gen_kwargs={
221
+ "mrcon_path": mrcon_path,
222
+ "ann_dir": ann_dir,
223
+ },
224
+ )
225
+ ]
226
+
227
+ def _generate_examples(self, mrcon_path: Path, ann_dir: Path) -> Tuple[int, Dict]:
228
+ """Yields examples as (key, example) tuples."""
229
+
230
+ # read label->cui map
231
+ umls_map = {}
232
+ with mrcon_path.open() as f:
233
+ content = f.readlines()
234
+ content = [x.strip() for x in content]
235
+ for line in content:
236
+ fields = line.split("|")
237
+ assert len(fields) == 9, f"{len(fields)}"
238
+ assert fields[0][0] == "C"
239
+ umls_map[fields[6]] = fields[0]
240
+
241
+ for dir in ann_dir.iterdir():
242
+ if self.config.schema == "source" and dir.is_dir():
243
+ for example in self._generate_parsed_documents(dir, umls_map):
244
+ yield next(self.uid), example
245
+
246
+ elif self.config.schema == "bigbio_kb" and dir.is_dir():
247
+ for example in self._generate_parsed_documents(dir, umls_map):
248
+ yield next(self.uid), self._source_to_kb(example)
249
+
250
+ def _generate_parsed_documents(self, dir, umls_map):
251
+
252
+ # read choices
253
+ choices = []
254
+ choices_path = dir / "choices"
255
+ with choices_path.open() as f:
256
+ content = f.readlines()
257
+ content = [x.strip() for x in content]
258
+ for line in content:
259
+ label, concept, *type = line.split("|")
260
+ type = [x.split(", ")[1] for x in type]
261
+ m = re.search(r"(?<=\().+(?=\))", concept)
262
+ if m is None:
263
+ choices.append(
264
+ {"label": label, "concept": concept, "type": type, "cui": ""}
265
+ )
266
+ else:
267
+ concept = m.group()
268
+ choices.append(
269
+ {
270
+ "label": label,
271
+ "concept": concept,
272
+ "type": type,
273
+ "cui": umls_map[concept],
274
+ }
275
+ )
276
+
277
+ file_path = dir / f"{dir.name}_set"
278
+ with file_path.open() as f:
279
+ for raw_document in self._generate_raw_documents(f):
280
+ document = {}
281
+ id, document_id, label = raw_document[0].strip().split("|")
282
+
283
+ info_sentence = self._parse_ambig_pos_info(raw_document[2].strip())
284
+ info_sentence["text"] = raw_document[1]
285
+
286
+ info_citation = self._parse_ambig_pos_info(raw_document[-1].strip())
287
+ n_cit = len(raw_document) - 3
288
+ info_citation["text"] = "".join(raw_document[3 : 3 + n_cit])
289
+
290
+ document = {
291
+ "id": id,
292
+ "sentence_id": document_id,
293
+ "label": label,
294
+ "sentence": info_sentence,
295
+ "citation": info_citation,
296
+ "choices": choices,
297
+ }
298
+ yield document
299
+
300
+ def _generate_raw_documents(self, fstream):
301
+ raw_document = []
302
+ for line in fstream:
303
+ if line.strip():
304
+ raw_document.append(line)
305
+ elif raw_document:
306
+ yield raw_document
307
+ raw_document = []
308
+ # needed for last document
309
+ if raw_document:
310
+ yield raw_document
311
+
312
+ def _parse_ambig_pos_info(self, line):
313
+ infos = line.split("|")
314
+ assert len(infos) == 8, f"{len(infos)}"
315
+ pos_info = {
316
+ "ambiguous_word": infos[0],
317
+ "ambiguous_word_alias": infos[1],
318
+ "offsets_context": [infos[2], infos[3]],
319
+ "offsets_ambiguity": [infos[4], infos[5]],
320
+ "context": infos[6],
321
+ }
322
+ return pos_info
323
+
324
+ def _source_to_kb(self, example):
325
+ document_ = {}
326
+ document_["events"] = []
327
+ document_["relations"] = []
328
+ document_["coreferences"] = []
329
+ document_["id"] = next(self.uid)
330
+ document_["document_id"] = example["sentence_id"].split(".")[0]
331
+
332
+ citation = example["citation"]
333
+ document_["passages"] = [
334
+ {
335
+ "id": next(self.uid),
336
+ "type": "",
337
+ "text": [citation["text"]],
338
+ "offsets": [[0, len(citation["text"])]],
339
+ }
340
+ ]
341
+ choices = {x["label"]: x["cui"] for x in example["choices"]}
342
+ types = {x["label"]: x["type"][0] for x in example["choices"]}
343
+
344
+ db_id = (
345
+ "" if example["label"] in ["None", "UNDEF"] else choices[example["label"]]
346
+ )
347
+ type = "" if example["label"] in ["None", "UNDEF"] else types[example["label"]]
348
+ document_["entities"] = [
349
+ {
350
+ "id": next(self.uid),
351
+ "type": type,
352
+ "text": [citation["ambiguous_word_alias"]],
353
+ "offsets": [
354
+ [
355
+ int(citation["offsets_ambiguity"][0]),
356
+ int(citation["offsets_ambiguity"][1]) + 1,
357
+ ]
358
+ ],
359
+ "normalized": [{"db_name": "UMLS", "db_id": db_id}],
360
+ }
361
+ ]
362
+ return document_