gastrulation_mmusculus / gastrulation_mmusculus.py
luxai's picture
Upload folder using huggingface_hub
b6de393 verified
raw
history blame
4.89 kB
# 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.ArrowBasedBuilder):
"""RNA Expression Baseclass."""
def _info(self):
self.config = RNAExpConfig(
name = "mmusculus",
description = DESCRIPTION,
features = ["raw_counts",'cell_type'],
raw_counts = "X",
data_url = "./data/mmusculus_gastrulation.h5ad",
citation = CITATION,
url = "https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-6967")
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_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