File size: 6,199 Bytes
25eca30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a16c987
25eca30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3490a0c
25eca30
 
 
 
 
 
 
 
 
 
 
 
8ecab8e
25eca30
 
 
 
 
38cb367
a024f23
 
 
25eca30
 
 
 
a16c987
25eca30
 
 
38cb367
25eca30
 
 
 
 
 
a024f23
25eca30
 
 
 
 
 
 
 
 
 
 
 
a16c987
a024f23
 
25eca30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06ae853
a024f23
 
38cb367
 
 
 
 
 
a024f23
 
 
 
09c71ee
25eca30
 
 
38cb367
 
09c71ee
 
a024f23
 
 
25eca30
 
 
a16c987
 
a024f23
25eca30
 
 
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
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.

# Lint as: python3
"""The RNA Expression Baseclass."""


import json
import os
import anndata as ad
import pyarrow as pa
import pandas as pd
import numpy as np

import datasets
CITATION = """
Test
"""

DESCRIPTION = """
Test
"""

class RNAExpConfig(datasets.BuilderConfig):
    """BuilderConfig for RNAExpConfig."""

    def __init__(self, features, data_url, citation, url, raw_counts="X", **kwargs):
        """BuilderConfig for RNAExpConfig.
        Args:
          features: `list[string]`, list of the features that will appear in the
            feature dict. Should not include "label".
          data_url: `string`, url to download the zip file from.
          citation: `string`, citation for the data set.
          url: `string`, url for information about the data set.

          **kwargs: keyword arguments forwarded to super.
        """
        # Version history:
        # 0.0.1: Initial version.
        super(RNAExpConfig, self).__init__(version=datasets.Version("0.0.1"), **kwargs)
        self.features = features
        self.data_url = data_url
        self.citation = citation
        self.url = url
        self.raw_counts = raw_counts # Could be raw.X
        self.batch = 1000
        self.species = None




# class RNAExp(datasets.GeneratorBasedBuilder):
class RNAExp(datasets.ArrowBasedBuilder):
    """RNA Expression Baseclass."""

    def _info(self):
        self.config = RNAExpConfig(
            name="human_yolk_sac",
            description = DESCRIPTION,
            features=["raw_counts",'LVL1', 'LVL2', 'LVL3'],
            raw_counts = "X",
            data_url="./data/17_04_24_YolkSacRaw_F158_WE_annots.h5ad",
            citation=CITATION,
            url="https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-11673")

        features = {"raw_counts": datasets.features.Sequence(feature=datasets.Value("int32"))}

        # features = {"raw_counts": datasets.features.Sequence(feature={"gene":datasets.Value("string"),"count":datasets.Value("int32")})}
        # features = {"raw_counts": datasets.Value("int32") for gene in adata.var.index.str.lower().tolist()}
        for feature in self.config.features:
            if features.get(feature,None) is None:
                features[feature] = datasets.Value("string")

        # features["gene_names"] = datasets.Sequence(datasets.Value("string"))

        return datasets.DatasetInfo(
            description= self.config.description,
            features=None, #datasets.Features(features),
            homepage=self.config.url,
            citation=self.config.citation,
        )

    def _split_generators(self, dl_manager):
        self.anndata_file = dl_manager.download_and_extract(self.config.data_url)
        

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"split": "train","expression_file": self.anndata_file,"batch_size":self.config.batch},#,"gene_names_file": self.gene_names_file},    
            )
        ]

    def _generate_examples(self, expression_file, split):

        # genes = pd.read_csv(gene_names_file)
        adata = ad.read_h5ad(expression_file)
        self.genes_list = adata.var.index.str.lower().tolist()


        if self.config.raw_counts =="X":
            X = adata.X
        else:
            X = adata.var[raw_counts]
        num_cells = X.shape[0]
        for _id,cell in enumerate(X):
            example = {"raw_counts": cell.toarray().flatten()}

            for feature in self.config.features:
                if example.get(feature,None) is None:
                    example[feature] = adata.obs[feature][_id]

            yield _id,example

    def _generate_tables(self, expression_file,batch_size,split):
        idx = 0
        adata = ad.read_h5ad(expression_file,backed='r')
        genes = adata.var_names.str.lower().to_list()

        features = {"raw_counts": datasets.features.Sequence(datasets.features.Value("int32"),id = ",".join(adata.var.index.str.lower().tolist()))}
        for feature in self.config.features:
            if features.get(feature,None) is None:
                features[feature] = datasets.Value("string")

        self.info.features = datasets.Features(features)
        

        # self.info.features['gene_names'] = datasets.features.ClassLabel(names = genes)
        
        # self.info.description   = adata.var.index.str.lower().tolist() #"+".join(adata.var.index.str.lower().tolist())
        for batch in range(0,adata.shape[0],batch_size):
            chunk = adata.X[batch:batch+batch_size].todense().astype('int32')
            df = pd.DataFrame(chunk,columns=adata.var.index.str.lower())
            df["raw_counts"] = [x for x in df.to_numpy()]
            df = df[["raw_counts"]]
            ## We create a dummy column with all the names of the genes as list. We don't use this as value since this would unnecessarily increase the size of the dataset
            ## Another option would be to replace the description with the list of genes 
            # df[",".join(adata.var.index.str.lower().tolist())] = True
            # df['gene_names'] = True
            
            for feature in self.config.features:
                if feature != "raw_counts":
                    df[feature] = adata.obs[feature][batch:batch+batch_size].tolist()
            
            # df['gene_names'] = [adata.var.index.str.lower().tolist()]*batch_size
            # print(df)
            pa_table = pa.Table.from_pandas(df)
            yield idx, pa_table
            idx += 1