Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
Libraries:
Datasets
License:
File size: 13,437 Bytes
24c19f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cf34d2
24c19f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and Simon Ott, github: nomisto
#
# 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.

"""
The LLL05 challenge task is to learn rules to extract protein/gene interactions from biology abstracts from the Medline
bibliography database. The goal of the challenge is to test the ability of the participating IE systems to identify the
interactions and the gene/proteins that interact. The participants will test their IE patterns on a test set with the
aim of extracting the correct agent and target.The challenge focuses on information extraction of gene interactions in
Bacillus subtilis. Extracting gene interaction is the most popular event IE task in biology. Bacillus subtilis (Bs) is
a model bacterium and many papers have been published on direct gene interactions involved in sporulation. The gene
interactions are generally mentioned in the abstract and the full text of the paper is not needed. Extracting gene
interaction means, extracting the agent (proteins) and the target (genes) of all couples of genic interactions from
sentences.
"""

# NOTE:
# word stop offsets are increased by one to be consistent with python slicing.
# test set does not include entity relation information

import itertools as it
from typing import List

import datasets

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

_LANGUAGES = ['English']
_PUBMED = True
_LOCAL = False
_CITATION = """\
    @article{article,
    author = {Nédellec, C.},
    year = {2005},
    month = {01},
    pages = {},
    title = {Learning Language in Logic - Genic Interaction Extraction Challenge},
    journal = {Proceedings of the Learning Language in Logic 2005 Workshop at the \
        International Conference on Machine Learning}
}
"""

_DATASETNAME = "lll"
_DISPLAYNAME = "LLL05"

_DESCRIPTION = """\
The LLL05 challenge task is to learn rules to extract protein/gene interactions from biology abstracts from the Medline
bibliography database. The goal of the challenge is to test the ability of the participating IE systems to identify the
interactions and the gene/proteins that interact. The participants will test their IE patterns on a test set with the
aim of extracting the correct agent and target.The challenge focuses on information extraction of gene interactions in
Bacillus subtilis. Extracting gene interaction is the most popular event IE task in biology. Bacillus subtilis (Bs) is
a model bacterium and many papers have been published on direct gene interactions involved in sporulation. The gene
interactions are generally mentioned in the abstract and the full text of the paper is not needed. Extracting gene
interaction means, extracting the agent (proteins) and the target (genes) of all couples of genic interactions from
sentences.
"""

_HOMEPAGE = "http://genome.jouy.inra.fr/texte/LLLchallenge"

_LICENSE = 'License information unavailable'

_URLS = {
    _DATASETNAME: [
        "http://genome.jouy.inra.fr/texte/LLLchallenge/data/LLLChalenge05/data/train/task2/genic_interaction_linguistic_data.txt",  # noqa
        "http://genome.jouy.inra.fr/texte/LLLchallenge/data/LLLChalenge05/data/train/task2/genic_interaction_linguistic_data_coref.txt",  # noqa
        "http://genome.jouy.inra.fr/texte/LLLchallenge/data/LLLChalenge05/data/test/task2/enriched_test_data.txt",  # noqa
    ]
}

_SUPPORTED_TASKS = [Tasks.RELATION_EXTRACTION]

_SOURCE_VERSION = "1.0.0"

_BIGBIO_VERSION = "1.0.0"


class LLLDataset(datasets.GeneratorBasedBuilder):
    """LLL dataset for gene interaction extraction (RE)"""

    SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
    BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)

    BUILDER_CONFIGS = [
        BigBioConfig(
            name="lll_source",
            version=SOURCE_VERSION,
            description="LLL source schema",
            schema="source",
            subset_id="lll",
        ),
        BigBioConfig(
            name="lll_bigbio_kb",
            version=BIGBIO_VERSION,
            description="LLL BigBio schema",
            schema="bigbio_kb",
            subset_id="lll",
        ),
    ]

    DEFAULT_CONFIG_NAME = "lll_source"

    def _info(self) -> datasets.DatasetInfo:

        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "sentence": datasets.Value("string"),
                    "words": [
                        {
                            "id": datasets.Value("string"),
                            "text": datasets.Value("string"),
                            "offsets": datasets.Sequence(datasets.Value("int32")),
                        }
                    ],
                    "genic_interactions": [
                        {
                            "ref_id1": datasets.Value("string"),
                            "ref_id2": datasets.Value("string"),
                        }
                    ],
                    "agents": [
                        {
                            "ref_id": datasets.Value("string"),
                        }
                    ],
                    "targets": [
                        {
                            "ref_id": datasets.Value("string"),
                        }
                    ],
                    "lemmas": [
                        {
                            "ref_id": datasets.Value("string"),
                            "lemma": datasets.Value("string"),
                        }
                    ],
                    "syntactic_relations": [
                        {
                            "type": datasets.Value("string"),
                            "ref_id1": datasets.Value("string"),
                            "ref_id2": 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]:

        urls = _URLS[_DATASETNAME]
        train_path, train_coref_path, test_path = dl_manager.download_and_extract(urls)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "data_paths": [train_path, train_coref_path],
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={"data_paths": [test_path], "split": "test"},
            ),
        ]

    def _generate_examples(self, data_paths, split):

        if self.config.schema == "source":
            for path in data_paths:
                with open(path, encoding="utf8") as documents:
                    for document in self._generate_parsed_documents(documents, split):
                        yield document["id"], document

        elif self.config.schema == "bigbio_kb":
            uid = it.count(0)
            for path in data_paths:
                with open(path, encoding="utf8") as documents:
                    for document in self._generate_parsed_documents(documents, split):
                        document_ = {}
                        document_["id"] = next(uid)
                        document_["document_id"] = document["id"]

                        document_["passages"] = [
                            {
                                "id": next(uid),
                                "type": BigBioValues.NULL,
                                "text": [document["sentence"]],
                                "offsets": [[0, len(document["sentence"])]],
                            }
                        ]

                        id_to_word = {i["id"]: i for i in document["words"]}
                        document_["entities"] = []
                        for agent in document["agents"]:
                            word = id_to_word[agent["ref_id"]]
                            document_["entities"].append(
                                {
                                    "id": f"{document_['id']}-agent-{word['id']}",
                                    "type": "agent",
                                    "text": [word["text"]],
                                    "offsets": [
                                        [word["offsets"][0], word["offsets"][1]]
                                    ],
                                    "normalized": [],
                                }
                            )
                        for agent in document["targets"]:
                            word = id_to_word[agent["ref_id"]]
                            document_["entities"].append(
                                {
                                    "id": f"{document_['id']}-target-{word['id']}",
                                    "type": "target",
                                    "text": [word["text"]],
                                    "offsets": [
                                        [word["offsets"][0], word["offsets"][1]]
                                    ],
                                    "normalized": [],
                                }
                            )

                        document_["relations"] = [
                            {
                                "id": next(uid),
                                "type": "genic_interaction",
                                "arg1_id": f"{document_['id']}-agent-{relation['ref_id1']}",
                                "arg2_id": f"{document_['id']}-target-{relation['ref_id2']}",
                                "normalized": [],
                            }
                            for relation in document["genic_interactions"]
                        ]

                        document_["events"] = []
                        document_["coreferences"] = []
                        yield document_["document_id"], document_

    def _generate_parsed_documents(self, fstream, split):
        for raw_document in self._generate_raw_documents(fstream):
            yield self._parse_document(raw_document, split)

    def _generate_raw_documents(self, fstream):
        raw_document = []
        for line in fstream:
            if "%" in line:
                continue
            elif line.strip():
                raw_document.append(line.strip())
            elif raw_document:
                if raw_document:
                    yield raw_document
                raw_document = []
        # needed for last document
        if raw_document:
            yield raw_document

    def _parse_document(self, raw_document, split):
        document = {}
        for line in raw_document:
            key, value = line.split("\t", 1)
            if key in ["ID", "sentence"]:
                document[key.lower()] = value
            elif key in [
                "words",
                "genic_interactions",
                "agents",
                "targets",
                "lemmas",
                "syntactic_relations",
            ]:
                document[key.lower()] = self._parse_elements(value, key)
            else:
                raise NotImplementedError()

        # Needed as testset does not contain agents, targets and genic_interactions (dataset was part of a challenge)
        if split == "test":
            document.setdefault("genic_interactions", [])
            document.setdefault("agents", [])
            document.setdefault("targets", [])

        return document

    def _parse_elements(self, values, type):
        return [self._parse_element(atom, type) for atom in values.split("\t")]

    def _parse_element(self, atom, type):
        # Sorry for that abomination, parses the arguments from atoms like rel(arg1, ..., argn)
        args = atom.split("(", 1)[1][:-1].split(",")
        if type == "words":
            # fix offsets for python slicing
            return {
                "id": args[0],
                "text": args[1].strip("'"),
                "offsets": [int(args[2]), int(args[3]) + 1],
            }
        elif type == "genic_interactions":
            return {"ref_id1": args[0], "ref_id2": args[1]}
        elif type == "agents":
            return {"ref_id": args[0]}
        elif type == "targets":
            return {"ref_id": args[0]}
        elif type == "lemmas":
            return {"ref_id": args[0], "lemma": args[1].strip("'")}
        elif type == "syntactic_relations":
            return {"type": args[0].strip("'"), "ref_id1": args[1], "ref_id2": args[2]}