File size: 17,570 Bytes
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbdcde3
 
 
 
 
 
16fe403
fbdcde3
 
16fe403
fbdcde3
 
 
 
 
 
16fe403
fbdcde3
16fe403
 
 
fbdcde3
 
 
 
 
 
 
 
16fe403
 
fbdcde3
 
 
 
 
 
 
 
16fe403
fbdcde3
 
 
16fe403
 
 
 
 
 
 
 
 
9d8704e
 
 
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8704e
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8704e
16fe403
 
 
 
 
 
9d8704e
 
16fe403
 
 
 
 
 
 
 
9d8704e
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8704e
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f552d
16fe403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and Gully Burns.
#
# 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.

"""
Research Article document classification dataset based on aspects of disease research. Currently, the dataset consists of three subsets: 

(A) classifies title/abstracts of papers into most popular subtypes of clinical, basic, and translational papers (~20k papers); 

    - Clinical Characteristics, Disease Pathology, and Diagnosis:
        Text that describes (i) symptoms, signs, or ‘phenotype’ of a disease; 
        (ii) the effects of the disease on patient organs, tissues, or cells; 
        (iii)) the results of clinical tests that reveal pathology (including
        biomarkers); (iv) research that use this information to figure out
        a diagnosis.

    - Therapeutics in the clinic: 
        Text describing how treatments work in the clinic (but not in a clinical trial).

    - Disease mechanism: 

    - Patient-Based Therapeutics: 
        Text describing (i) Clinical trials (studies of therapeutic measures being 
        used on patients in a clinical trial); (ii) Post Marketing Drug Surveillance 
        (effects of a drug after approval in the general population or as part of 
        ‘standard healthcare’); (iii) Drug repurposing (how a drug that has been 
        approved for one use is being applied to a new disease).

(B) identifies whether a title/abstract of a paper describes substantive research into Quality of Life (~10k papers); 

    - [-1] - the paper is not a primary experimental study in rare disease

    - [0] - the study does not directly investigate quality of life

    - [1] - the study investigates qol but not as its primary contribution

    - [2] - the study's primary contribution centers on quality of life measures

(C) identifies if a paper is a natural history study (~10k papers). 

   - [-1] - the paper is not a primary experimental study in rare disease

    - [0] - the study is not directly investigating the natural history of a disease

    - [1] - the study includes some elements a natural history but not as its primary contribution

    - [2] - the study's primary contribution centers on observing the time course of a rare disease
    
These classifications are particularly relevant in rare disease research, a field that is generally understudied. 

This data was compiled through the use of a gamified curation approach based on CentaurLabs' 'diagnos.us' platform.
"""

import os
from typing import List, Tuple, Dict

import datasets
import pandas as pd
from pathlib import Path

from .bigbiohub import text_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks

_LOCAL = False

_CITATION = """\
@article{,
  author    = {},
  title     = {},
  journal   = {},
  volume    = {},
  year      = {},
  url       = {},
  doi       = {},
  biburl    = {},
  bibsource = {}
}
"""

_DATASETNAME = "czi_drsm"

_DESCRIPTION = """\
Research Article document classification dataset based on aspects of disease research. Currently, the dataset consists of three subsets: 

(A) classifies title/abstracts of papers into most popular subtypes of clinical, basic, and translational papers (~20k papers); 

    - Clinical Characteristics, Disease Pathology, and Diagnosis - 
        Text that describes (A) symptoms, signs, or ‘phenotype’ of a disease; 
        (B) the effects of the disease on patient organs, tissues, or cells; 
        (C) the results of clinical tests that reveal pathology (including
        biomarkers); (D) research that use this information to figure out
        a diagnosis.
    - Therapeutics in the clinic - 
        Text describing how treatments work in the clinic (but not in a clinical trial).
    - Disease mechanism - 
        Text that describes either (A) mechanistic involvement of specific genes in disease 
        (deletions, gain of function, etc); (B) how molecular signalling or metabolism 
        binding, activating, phosphorylation, concentration increase, etc.) 
        are involved in the mechanism of a disease; or (C) the physiological 
        mechanism of disease at the level of tissues, organs, and body systems.
    - Patient-Based Therapeutics - 
        Text describing (A) Clinical trials (studies of therapeutic measures being 
        used on patients in a clinical trial); (B) Post Marketing Drug Surveillance 
        (effects of a drug after approval in the general population or as part of 
        ‘standard healthcare’); (C) Drug repurposing (how a drug that has been 
        approved for one use is being applied to a new disease).

(B) identifies whether a title/abstract of a paper describes substantive research into Quality of Life (~10k papers); 
    
    - -1 - the paper is not a primary experimental study in rare disease
    - 0 - the study does not directly investigate quality of life
    - 1 - the study investigates qol but not as its primary contribution
    - 2 - the study's primary contribution centers on quality of life measures

(C) identifies if a paper is a natural history study (~10k papers). 
`   
    - -1 - the paper is not a primary experimental study in rare disease
    - 0 - the study is not directly investigating the natural history of a disease
    - 1 - the study includes some elements a natural history but not as its primary contribution
    - 2 - the study's primary contribution centers on observing the time course of a rare disease
    
These classifications are particularly relevant in rare disease research, a field that is generally understudied.
"""

_HOMEPAGE = "https://github.com/chanzuckerberg/DRSM-corpus/"
_LICENSE = 'CC0_1p0'

_LANGUAGES = ['English']
_PUBMED = False
_LOCAL = False
_DISPLAYNAME = "DRSM Corpus"

# For publicly available datasets you will most likely end up passing these URLs to dl_manager in _split_generators.
# In most cases the URLs will be the same for the source and bigbio config.
# However, if you need to access different files for each config you can have multiple entries in this dict.
# This can be an arbitrarily nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
    'base': "https://raw.githubusercontent.com/chanzuckerberg/DRSM-corpus/main/v1/drsm_corpus_v1.tsv",
    'qol': "https://raw.githubusercontent.com/chanzuckerberg/DRSM-corpus/main/v2/qol_all_2022_12_15.tsv",
    'nhs': "https://raw.githubusercontent.com/chanzuckerberg/DRSM-corpus/main/v2/nhs_all_2023_03_31.tsv"
}

_SUPPORTED_TASKS = [Tasks.TEXT_CLASSIFICATION]  

_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"

_CLASS_NAMES_BASE = [
    "clinical characteristics or disease pathology",
    "therapeutics in the clinic",
    "disease mechanism",
    "patient-based therapeutics",
    "other",
    "irrelevant"
    ]

_CLASS_NAMES_QOL = [
    "-1 - the paper is not a primary experimental study in rare disease",
    "0 - the study does not directly investigate quality of life",
    "1 - the study investigates qol but not as its primary contribution",
    "2 - the study's primary contribution centers on quality of life measures"
    ]

_CLASS_NAMES_NHS = [
    "-1 - the paper is not a primary experimental study in rare disease",
    "0 - the study is not directly investigating the natural history of a disease",
    "1 - the study includes some elements a natural history but not as its primary contribution",
    "2 - the study's primary contribution centers on observing the time course of a rare disease"
    ]

class DRSMBaseDataset(datasets.GeneratorBasedBuilder):
    """DRSM Document Classification Datasets."""

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

    # You will be able to load the "source" or "bigbio" configurations with
    #ds_source = datasets.load_dataset('drsm_source_dataset', name='source')
    #ds_bigbio = datasets.load_dataset('drsm_bigbio_dataset', name='bigbio')

    # For local datasets you can make use of the `data_dir` and `data_files` kwargs
    # https://huggingface.co/docs/datasets/add_dataset.html#downloading-data-files-and-organizing-splits
    # ds_source = datasets.load_dataset('my_dataset', name='source', data_dir="/path/to/data/files")
    # ds_bigbio = datasets.load_dataset('my_dataset', name='bigbio', data_dir="/path/to/data/files")

    # TODO: For each dataset, implement Config for Source and BigBio;
    #  If dataset contains more than one subset (see examples/bioasq.py) implement for EACH of them.
    #  Each of them should contain:
    #   - name: should be unique for each dataset config eg. bioasq10b_(source|bigbio)_[bigbio_schema_name]
    #   - version: option = (SOURCE_VERSION|BIGBIO_VERSION)
    #   - description: one line description for the dataset
    #   - schema: options = (source|bigbio_[bigbio_schema_name])
    #   - subset_id: subset id is the canonical name for the dataset (eg. bioasq10b)
    #  where [bigbio_schema_name] = ()

    BUILDER_CONFIGS = [
        BigBioConfig(
            name="czi_drsm_base_source",
            version=SOURCE_VERSION,
            description="czi_drsm base source schema",
            schema="base_source",
            subset_id="czi_drsm_base",
        ),
        BigBioConfig(
            name="czi_drsm_bigbio_base_text",
            version=BIGBIO_VERSION,
            description="czi_drsm base BigBio schema",
            schema="bigbio_text",
            subset_id="czi_drsm_base",
        ),
        BigBioConfig(
            name="czi_drsm_qol_source",
            version=SOURCE_VERSION,
            description="czi_drsm source schema for Quality of Life studies",
            schema="qol_source",
            subset_id="czi_drsm_qol",
        ),
        BigBioConfig(
            name="czi_drsm_bigbio_qol_text",
            version=BIGBIO_VERSION,
            description="czi_drsm BigBio schema for Quality of Life studies",
            schema="bigbio_text",
            subset_id="czi_drsm_qol",
        ),
        BigBioConfig(
            name="czi_drsm_nhs_source",
            version=SOURCE_VERSION,
            description="czi_drsm source schema for Natural History Studies",
            schema="nhs_source",
            subset_id="czi_drsm_nhs",
        ),
        BigBioConfig(
            name="czi_drsm_bigbio_nhs_text",
            version=BIGBIO_VERSION,
            description="czi_drsm BigBio schema for Natural History Studies",
            schema="bigbio_text",
            subset_id="czi_drsm_nhs",
        ),
    ]

    DEFAULT_CONFIG_NAME = "czi_drsm_bigbio_base_text"

    def _info(self) -> datasets.DatasetInfo:

        # Create the source schema; this schema will keep all keys/information/labels as close to the original dataset as possible.

        # You can arbitrarily nest lists and dictionaries.
        # For iterables, use lists over tuples or `datasets.Sequence`

        if self.config.schema == "base_source":
            features = datasets.Features(
                {
                    "document_id": datasets.Value("string"),
                    "labeling_state": datasets.Value("string"),
                    "explanation": datasets.Value("string"),
                    "correct_label": [datasets.ClassLabel(names=_CLASS_NAMES_BASE)],
                    "agreement": [datasets.Value("string")],
                    "title": [datasets.Value("string")],
                    "abstract": [datasets.Value("string")],
                }
            )

        elif self.config.schema == "qol_source":
            features = datasets.Features(
                {
                    "document_id": datasets.Value("string"),
                    "labeling_state": datasets.Value("string"),
                    "correct_label": [datasets.ClassLabel(names=_CLASS_NAMES_QOL)],
                    "explanation": datasets.Value("string"),
                    "agreement": [datasets.Value("string")],
                    "title": [datasets.Value("string")],
                    "abstract": [datasets.Value("string")]
                }
            )

        elif self.config.schema == "nhs_source":
            features = datasets.Features(
                {
                    "document_id": datasets.Value("string"),
                    "labeling_state": datasets.Value("string"),
                    "correct_label": [datasets.ClassLabel(names=_CLASS_NAMES_NHS)],
                    "explanation": datasets.Value("string"),
                    "agreement": [datasets.Value("string")],
                    "title": [datasets.Value("string")],
                    "abstract": [datasets.Value("string")],
                }
            )

        # For example bigbio_kb, bigbio_t2t
        elif self.config.schema == "bigbio_text":
            features = text_features

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

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

        if 'base' in self.config.name:
            url = _URLS['base']
        elif 'qol' in self.config.name:
            url = _URLS['qol']
        elif 'nhs' in self.config.name:
            url = _URLS['nhs']
        else:
            raise ValueError("Invalid config name: {}".format(self.config.name))        

        data_file = dl_manager.download_and_extract(url)
        df = pd.read_csv(data_file, sep="\t", encoding="utf-8").fillna('')

        # load tsv file into huggingface dataset
        ds = datasets.Dataset.from_pandas(df)
        
        # generate train_test split
        ds_dict = ds.train_test_split(test_size=0.2, seed=42)
        ds_dict2 = ds_dict['test'].train_test_split(test_size=0.5, seed=42)
        
        # dump train, val, test to disk
        data_dir = Path(data_file).parent
        ds_dict['train'].to_csv(data_dir / "train.tsv", sep="\t", index=False)
        ds_dict2['train'].to_csv(data_dir / "validation.tsv", sep="\t", index=False)
        ds_dict2['test'].to_csv(data_dir / "test.tsv", sep="\t", index=False)    

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": data_dir / "train.tsv",
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "filepath": data_dir / "validation.tsv",
                    "split": "validation",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepath": data_dir / "test.tsv",
                    "split": "test",
                },
            )
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, filepath, split) -> Tuple[int, Dict]:
        """Yields examples as (key, example) tuples."""
        df = pd.read_csv(filepath, sep="\t", encoding="utf-8").fillna('')
        print(len(df))
        for id_, l in df.iterrows():
            if self.config.subset_id == "czi_drsm_base":
                doc_id = l[0]
                labeling_state = l[1]
                correct_label = l[2]
                agreement = l[3]
                explanation = l[4]
                title = l[5]
                abstract = l[6]
            elif self.config.subset_id == "czi_drsm_qol":
                doc_id = l[0]
                labeling_state = l[1]
                correct_label = l[2][1:-1]
                explanation = l[3]
                agreement = l[4]
                title = l[5]
                abstract = l[6]                
            elif self.config.subset_id == "czi_drsm_nhs":
                doc_id = l[0]
                labeling_state = l[1]
                correct_label = l[2][1:-1]
                explanation = ''
                agreement = l[3]
                title = l[4]
                abstract = l[5]

            if "_source" in self.config.schema:
                yield id_, {
                    "document_id": doc_id,  
                    "labeling_state": labeling_state,
                    "explanation": explanation,
                    "correct_label": [correct_label],
                    "agreement": str(agreement),
                    "title": title,
                    "abstract": abstract
                }
            elif self.config.schema == "bigbio_text":                    
                yield id_, {
                    "id": id_,
                    "document_id": doc_id,
                    "text": title + " " + abstract,
                    "labels": [correct_label]
                }

# This template is based on the following template from the datasets package:
# https://github.com/huggingface/datasets/blob/master/templates/new_dataset_script.py