Upload folder using huggingface_hub
Browse files- yolksac_human.py +58 -130
yolksac_human.py
CHANGED
@@ -1,161 +1,89 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
|
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 |
-
# Lint as: python3
|
17 |
-
"""The RNA Expression Baseclass."""
|
18 |
-
|
19 |
-
|
20 |
-
import json
|
21 |
-
import os
|
22 |
import anndata as ad
|
23 |
import pyarrow as pa
|
24 |
import pandas as pd
|
25 |
-
import numpy as np
|
26 |
-
|
27 |
import datasets
|
28 |
-
CITATION = """
|
29 |
-
Test
|
30 |
-
"""
|
31 |
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
34 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
-
class RNAExpConfig(datasets.BuilderConfig):
|
37 |
-
"""BuilderConfig for RNAExpConfig."""
|
38 |
-
|
39 |
-
def __init__(self, features, data_url, citation, url, raw_counts="X", **kwargs):
|
40 |
-
"""BuilderConfig for RNAExpConfig.
|
41 |
-
Args:
|
42 |
-
features: `list[string]`, list of the features that will appear in the
|
43 |
-
feature dict. Should not include "label".
|
44 |
-
data_url: `string`, url to download the zip file from.
|
45 |
-
citation: `string`, citation for the data set.
|
46 |
-
url: `string`, url for information about the data set.
|
47 |
-
|
48 |
-
**kwargs: keyword arguments forwarded to super.
|
49 |
-
"""
|
50 |
-
# Version history:
|
51 |
-
# 0.0.1: Initial version.
|
52 |
-
super(RNAExpConfig, self).__init__(version=datasets.Version("0.0.1"), **kwargs)
|
53 |
-
self.features = features
|
54 |
-
self.data_url = data_url
|
55 |
-
self.citation = citation
|
56 |
-
self.url = url
|
57 |
-
self.raw_counts = raw_counts # Could be raw.X
|
58 |
-
self.batch = 1000
|
59 |
-
self.species = None
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
# class RNAExp(datasets.GeneratorBasedBuilder):
|
65 |
class RNAExp(datasets.ArrowBasedBuilder):
|
66 |
"""RNA Expression Baseclass."""
|
67 |
|
68 |
def _info(self):
|
69 |
-
self.config = RNAExpConfig(
|
70 |
-
name="human_yolk_sac",
|
71 |
-
description = DESCRIPTION,
|
72 |
-
features=["raw_counts",'LVL1', 'LVL2', 'LVL3'],
|
73 |
-
raw_counts = "X",
|
74 |
-
data_url="./data/17_04_24_YolkSacRaw_F158_WE_annots.h5ad",
|
75 |
-
citation=CITATION,
|
76 |
-
url="https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-11673")
|
77 |
|
78 |
-
|
79 |
|
80 |
-
# features
|
81 |
-
|
82 |
-
for feature in
|
83 |
-
if features.get(feature
|
84 |
features[feature] = datasets.Value("string")
|
85 |
|
86 |
-
# features["gene_names"] = datasets.Sequence(datasets.Value("string"))
|
87 |
-
|
88 |
return datasets.DatasetInfo(
|
89 |
-
description=
|
90 |
-
features=
|
91 |
-
homepage=
|
92 |
-
citation=
|
93 |
)
|
94 |
|
95 |
def _split_generators(self, dl_manager):
|
96 |
-
self.anndata_file = dl_manager.download_and_extract(
|
|
|
|
|
97 |
|
98 |
-
|
99 |
return [
|
100 |
datasets.SplitGenerator(
|
101 |
-
name=datasets.Split.TRAIN,
|
102 |
-
gen_kwargs={"split": "train","
|
|
|
|
|
|
|
|
|
103 |
)
|
104 |
]
|
105 |
|
106 |
-
def
|
107 |
-
|
108 |
-
# genes = pd.read_csv(gene_names_file)
|
109 |
-
adata = ad.read_h5ad(expression_file)
|
110 |
-
self.genes_list = adata.var.index.str.lower().tolist()
|
111 |
-
|
112 |
-
|
113 |
-
if self.config.raw_counts =="X":
|
114 |
-
X = adata.X
|
115 |
-
else:
|
116 |
-
X = adata.var[raw_counts]
|
117 |
-
num_cells = X.shape[0]
|
118 |
-
for _id,cell in enumerate(X):
|
119 |
-
example = {"raw_counts": cell.toarray().flatten()}
|
120 |
-
|
121 |
-
for feature in self.config.features:
|
122 |
-
if example.get(feature,None) is None:
|
123 |
-
example[feature] = adata.obs[feature][_id]
|
124 |
-
|
125 |
-
yield _id,example
|
126 |
-
|
127 |
-
def _generate_tables(self, expression_file,batch_size,split):
|
128 |
idx = 0
|
129 |
-
adata = ad.read_h5ad(expression_file,backed='r')
|
130 |
-
genes = adata.var_names.str.lower().to_list()
|
131 |
-
|
132 |
-
features = {"raw_counts": datasets.features.Sequence(datasets.features.Value("int32"),id = ",".join(adata.var.index.str.lower().tolist()))}
|
133 |
-
for feature in self.config.features:
|
134 |
-
if features.get(feature,None) is None:
|
135 |
-
features[feature] = datasets.Value("string")
|
136 |
-
|
137 |
-
self.info.features = datasets.Features(features)
|
138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
|
140 |
-
# self.info.features['gene_names'] = datasets.features.ClassLabel(names = genes)
|
141 |
-
|
142 |
-
# self.info.description = adata.var.index.str.lower().tolist() #"+".join(adata.var.index.str.lower().tolist())
|
143 |
-
for batch in range(0,adata.shape[0],batch_size):
|
144 |
-
chunk = adata.X[batch:batch+batch_size].todense().astype('int32')
|
145 |
-
df = pd.DataFrame(chunk,columns=adata.var.index.str.lower())
|
146 |
-
df["raw_counts"] = [x for x in df.to_numpy()]
|
147 |
-
df = df[["raw_counts"]]
|
148 |
-
## 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
|
149 |
-
## Another option would be to replace the description with the list of genes
|
150 |
-
# df[",".join(adata.var.index.str.lower().tolist())] = True
|
151 |
-
# df['gene_names'] = True
|
152 |
-
|
153 |
-
for feature in self.config.features:
|
154 |
-
if feature != "raw_counts":
|
155 |
-
df[feature] = adata.obs[feature][batch:batch+batch_size].tolist()
|
156 |
-
|
157 |
-
# df['gene_names'] = [adata.var.index.str.lower().tolist()]*batch_size
|
158 |
-
# print(df)
|
159 |
pa_table = pa.Table.from_pandas(df)
|
160 |
yield idx, pa_table
|
161 |
idx += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import anndata as ad
|
2 |
import pyarrow as pa
|
3 |
import pandas as pd
|
|
|
|
|
4 |
import datasets
|
|
|
|
|
|
|
5 |
|
6 |
+
# parameters per dataset
|
7 |
+
CITATION = """
|
8 |
+
Simone Webb, Muzlifah Haniffa & Emily Stephenson (2022).
|
9 |
+
Human fetal yolk sac scRNA-seq data (sample ID: F158 for Haniffa Lab; 16099 for HDBR).
|
10 |
+
BioStudies, E-MTAB-11673. Retrieved from https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-11673
|
11 |
"""
|
12 |
+
URL = "https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-11673"
|
13 |
+
DESCRIPTION = """Investigating the blood, immune and stromal cells present in a human fetal embryo in a
|
14 |
+
world first single cell transcriptomic atlas. The embryo was dissected into 12 coronal sections, yolk
|
15 |
+
sac, and yolk sac stalk. Live single cells sorted, with cell suspension then undergoing 10x chromium
|
16 |
+
5 prime scRNA-seq. This accession contains the yolk sac and yolk sac stalk data from this embryo.
|
17 |
+
A matched accession contains the coronal section data. Lane "WS_wEMB12142156" (from yolk sac) was excluded
|
18 |
+
from downstream analysis due to low fraction reads in cells post-CellRanger QC. Termination procedure for
|
19 |
+
this embryo was medical. The F158_[features...barcodes...matrix].[tsv...mtx].gz files attached to this
|
20 |
+
accession represent raw count data from all the 10x lanes in this accession combined, and as output from
|
21 |
+
CellRanger filtered matrices (CellRanger version 6.0.1 using human reference genome GRCh38-2020-A).
|
22 |
+
One set of count matrices relates to the yolk sac data, and one set of count matrices relates to the yolk sac stalk data."""
|
23 |
+
RAW_COUNTS = "X"
|
24 |
+
DATA_URL = "./data/17_04_24_YolkSacRaw_F158_WE_annots.h5ad"
|
25 |
+
FEATURES_TO_INCLUDE = ['LVL1', 'LVL2', 'LVL3']
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
class RNAExp(datasets.ArrowBasedBuilder):
|
28 |
"""RNA Expression Baseclass."""
|
29 |
|
30 |
def _info(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
self.batch = 1000
|
33 |
|
34 |
+
# create a dictionary of features where raw_counts are ints and the rest are strings
|
35 |
+
features = {"raw_counts": datasets.features.Sequence(datasets.features.Value("int32")),"rows": datasets.features.Sequence(datasets.features.Value("int32")),"size":datasets.Value("int32")}
|
36 |
+
for feature in FEATURES_TO_INCLUDE:
|
37 |
+
if not features.get(feature):
|
38 |
features[feature] = datasets.Value("string")
|
39 |
|
|
|
|
|
40 |
return datasets.DatasetInfo(
|
41 |
+
description = DESCRIPTION,
|
42 |
+
features = datasets.Features(features),
|
43 |
+
homepage = URL,
|
44 |
+
citation = CITATION
|
45 |
)
|
46 |
|
47 |
def _split_generators(self, dl_manager):
|
48 |
+
self.anndata_file = dl_manager.download_and_extract(DATA_URL)
|
49 |
+
adata = ad.read_h5ad(self.anndata_file, backed = "r")
|
50 |
+
demarcation = int(len(adata)*80/100)
|
51 |
|
|
|
52 |
return [
|
53 |
datasets.SplitGenerator(
|
54 |
+
name = datasets.Split.TRAIN,
|
55 |
+
gen_kwargs = {"split": "train", "adata": adata[:demarcation], "batch_size":self.batch},
|
56 |
+
),
|
57 |
+
datasets.SplitGenerator(
|
58 |
+
name = datasets.Split.TEST,
|
59 |
+
gen_kwargs = {"split": "test", "adata": adata[demarcation:], "batch_size":self.batch},
|
60 |
)
|
61 |
]
|
62 |
|
63 |
+
def _generate_tables(self, adata, batch_size, split):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
idx = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
+
# save the gene names as the id for the raw_counts feature
|
67 |
+
self.info.features["raw_counts"].id = f"{','.join(adata.var.index.tolist())}"
|
68 |
+
|
69 |
+
# iterate over the data in batches
|
70 |
+
for batch in range(0, adata.shape[0], batch_size):
|
71 |
+
|
72 |
+
# raw counts
|
73 |
+
if RAW_COUNTS == "X":
|
74 |
+
chunk = adata.X[batch:batch+batch_size].tolil().astype('int32')
|
75 |
+
elif RAW_COUNTS == "raw.X":
|
76 |
+
chunk = adata.raw.X[batch:batch+batch_size].tolil().astype('int32')
|
77 |
+
else:
|
78 |
+
raise("Not valid raw_counts")
|
79 |
+
df = pd.DataFrame([chunk.data,chunk.rows]).T
|
80 |
+
df.columns = ['raw_counts','rows']
|
81 |
+
df['size'] = chunk.shape[1]
|
82 |
+
|
83 |
+
# other features are all mapped to a list of strings
|
84 |
+
for feature in FEATURES_TO_INCLUDE:
|
85 |
+
df[feature] = list(map(str, adata.obs[feature][batch:batch+batch_size].tolist()))
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
pa_table = pa.Table.from_pandas(df)
|
88 |
yield idx, pa_table
|
89 |
idx += 1
|