DOTools-py 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dotools_py/__init__.py +33 -0
- dotools_py/_experimental/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/__init__.py +0 -0
- dotools_py/_experimental/_deprecated/_expression.py +761 -0
- dotools_py/_experimental/_deprecated/_language.py +398 -0
- dotools_py/_experimental/_deprecated/_statistics.py +403 -0
- dotools_py/_experimental/gr/__init__.py +0 -0
- dotools_py/_experimental/gr/_generic.py +382 -0
- dotools_py/dt/__init__.py +2 -0
- dotools_py/dt/_datasets.py +112 -0
- dotools_py/dt/_markers.py +150 -0
- dotools_py/dt/example_reduced.h5ad +0 -0
- dotools_py/get/__init__.py +7 -0
- dotools_py/get/_generic.py +626 -0
- dotools_py/logger.py +87 -0
- dotools_py/pl/_Classes.py +358 -0
- dotools_py/pl/_Plotter.py +567 -0
- dotools_py/pl/_StatsPlotter.py +716 -0
- dotools_py/pl/__init__.py +8 -0
- dotools_py/pl/_dotplot.py +2062 -0
- dotools_py/pl/_downstream.py +868 -0
- dotools_py/pl/_embeddings.py +481 -0
- dotools_py/pl/_experimental.py +205 -0
- dotools_py/pl/_expression.py +581 -0
- dotools_py/pl/_heatmap.py +475 -0
- dotools_py/pl/_plot_utils.py +103 -0
- dotools_py/pl/_visium.py +194 -0
- dotools_py/pp/__init__.py +2 -0
- dotools_py/pp/_cellbender.py +179 -0
- dotools_py/pp/_importer.py +583 -0
- dotools_py/settings/__init__.py +1 -0
- dotools_py/settings/_configure.py +185 -0
- dotools_py/settings/_global_parameters.py +16 -0
- dotools_py/tl/_Statistical.py +812 -0
- dotools_py/tl/__init__.py +10 -0
- dotools_py/tl/_analysis.py +772 -0
- dotools_py/tl/_get_stats.py +776 -0
- dotools_py/tl/_rankGenes.py +1112 -0
- dotools_py/util_scripts/_ReadWrite_RDS.R +285 -0
- dotools_py/util_scripts/_run_CCA.R +91 -0
- dotools_py/util_scripts/_run_CellBender.sh +186 -0
- dotools_py/util_scripts/_run_MAST.R +118 -0
- dotools_py/util_scripts/_run_SCTransform.R +60 -0
- dotools_py/util_scripts/_run_edgeR.R +104 -0
- dotools_py/util_scripts/_run_scDblFinder.R +63 -0
- dotools_py/utility/HomoSapiens_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/MusMusculus_GeneMetadata.pickle.gz +0 -0
- dotools_py/utility/__init__.py +4 -0
- dotools_py/utility/_convertion.py +262 -0
- dotools_py/utility/_general.py +136 -0
- dotools_py/utility/_plotting.py +101 -0
- dotools_py/utility/_spatial.py +64 -0
- dotools_py/utils.py +404 -0
- dotools_py-0.0.2.dist-info/METADATA +225 -0
- dotools_py-0.0.2.dist-info/RECORD +57 -0
- dotools_py-0.0.2.dist-info/WHEEL +4 -0
- dotools_py-0.0.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
# from tqdm import tqdm
|
|
2
|
+
# from typing import Literal
|
|
3
|
+
#
|
|
4
|
+
# import anndata as ad
|
|
5
|
+
# import pandas as pd
|
|
6
|
+
# import numpy as np
|
|
7
|
+
# from scipy.stats import false_discovery_control
|
|
8
|
+
#
|
|
9
|
+
# from dotools_py.utility import free_memory
|
|
10
|
+
# from dotools_py import logger
|
|
11
|
+
# from joblib import Parallel, delayed
|
|
12
|
+
#
|
|
13
|
+
# def neigh_perm(adata: ad.AnnData,
|
|
14
|
+
# ref: str,
|
|
15
|
+
# connectivity_key: str = "spatial_connectivities",
|
|
16
|
+
# annotation_key: str = "annotation",
|
|
17
|
+
# condition_key: str = "condition",
|
|
18
|
+
# statistic: Literal["mean", "median", "sum"] = "sum",
|
|
19
|
+
# n_perms: int = 100,
|
|
20
|
+
# alternative: Literal["two-sided", "greater", "less"] = "two-sided"):
|
|
21
|
+
# """Test for differential number of neighbors between cell-types in spatial transcriptomics.
|
|
22
|
+
#
|
|
23
|
+
# Calculate differential number of connections between cell-types comparing across
|
|
24
|
+
# two conditions in spatial transcriptomics. The significance is tested using permutation test.
|
|
25
|
+
# When using connectivities calculated using delaunay triangularity is recommended to use
|
|
26
|
+
# "sum" as statistic.
|
|
27
|
+
# .. note::
|
|
28
|
+
# Connectivities should be calculated per section. Use `squidpy.gr.spatial_neighbors` setting
|
|
29
|
+
# library_key to the batch_key.
|
|
30
|
+
#
|
|
31
|
+
# :param adata: Annotated data matrix.
|
|
32
|
+
# :param ref: Reference condition.
|
|
33
|
+
# :param connectivity_key: Key in `obsp` with the connectivities.
|
|
34
|
+
# :param annotation_key: Column in `obs` with cell annotation.
|
|
35
|
+
# :param condition_key: Column in `obs` with conditions.
|
|
36
|
+
# :param statistic: statistic to use for summarise the connectivities.
|
|
37
|
+
# :param n_perms: Number of permutations to do.
|
|
38
|
+
# :param alternative: Method to use for permutation test.
|
|
39
|
+
# :return: Returns a pandas dataframe with the results from the permutation test.
|
|
40
|
+
# """
|
|
41
|
+
#
|
|
42
|
+
# group_by = [condition_key, annotation_key]
|
|
43
|
+
#
|
|
44
|
+
# labels = []
|
|
45
|
+
# for idx, row in adata.obs[group_by].iterrows():
|
|
46
|
+
# current_row = "-".join(row.values)
|
|
47
|
+
# labels.append(current_row)
|
|
48
|
+
#
|
|
49
|
+
# # Define the groups
|
|
50
|
+
# connections = adata.obsp[connectivity_key]
|
|
51
|
+
# connections_coo = connections.tocoo()
|
|
52
|
+
# row_indices = connections_coo.row.tolist()
|
|
53
|
+
# col_indices = connections_coo.col.tolist()
|
|
54
|
+
# values = connections_coo.data.tolist()
|
|
55
|
+
#
|
|
56
|
+
# row_labels = [labels[idx] for idx in row_indices]
|
|
57
|
+
# col_labels = [labels[idx] for idx in col_indices]
|
|
58
|
+
#
|
|
59
|
+
# connections = pd.DataFrame([row_labels, col_labels, values]).T
|
|
60
|
+
# connections.columns = ["rows", "columns", "connections"]
|
|
61
|
+
#
|
|
62
|
+
# # Extract conditions and clusters from labels like "condition-cluster"
|
|
63
|
+
# connections["row_condition"] = connections["rows"].str.split("-").str[0]
|
|
64
|
+
# connections["row_cluster"] = connections["rows"].str.split("-").str[1]
|
|
65
|
+
# connections["col_condition"] = connections["columns"].str.split("-").str[0]
|
|
66
|
+
# connections["col_cluster"] = connections["columns"].str.split("-").str[1]
|
|
67
|
+
#
|
|
68
|
+
# del connections_coo, row_indices, row_labels, col_indices, col_labels, values
|
|
69
|
+
# free_memory()
|
|
70
|
+
#
|
|
71
|
+
# condition_groups = list(adata.obs[condition_key].unique())
|
|
72
|
+
# condition_groups.remove(ref)
|
|
73
|
+
# annotation_groups = list(adata.obs[annotation_key].unique())
|
|
74
|
+
#
|
|
75
|
+
# def calculate_stat(g1, g2, statistic):
|
|
76
|
+
# if statistic == 'mean':
|
|
77
|
+
# observed_stat = np.mean(g1) - np.mean(g2)
|
|
78
|
+
# elif statistic == 'median':
|
|
79
|
+
# observed_stat = np.median(g1) - np.median(g2)
|
|
80
|
+
# elif statistic == "sum":
|
|
81
|
+
# observed_stat = np.sum(g1) - np.sum(g2)
|
|
82
|
+
# else:
|
|
83
|
+
# raise ValueError("Not a valid statistic method use 'mean' or 'median'")
|
|
84
|
+
# return observed_stat
|
|
85
|
+
#
|
|
86
|
+
# def single_permutation_stat(connections, ref, group, ct1, ct2, statistic):
|
|
87
|
+
# shuffled_conditions = np.random.permutation(connections["row_condition"].values)
|
|
88
|
+
#
|
|
89
|
+
# # Rebuild shuffled labels using NumPy string ops
|
|
90
|
+
# shuffled_rows = shuffled_conditions + "-" + connections["row_cluster"].values
|
|
91
|
+
# shuffled_cols = shuffled_conditions + "-" + connections["col_cluster"].values
|
|
92
|
+
#
|
|
93
|
+
# # Apply shuffled labels to the DataFrame
|
|
94
|
+
# perm_group1 = connections[
|
|
95
|
+
# (shuffled_rows == f"{ref}-{ct1}") &
|
|
96
|
+
# (shuffled_cols == f"{ref}-{ct2}")
|
|
97
|
+
# ]["connections"].values
|
|
98
|
+
#
|
|
99
|
+
# perm_group2 = connections[
|
|
100
|
+
# (shuffled_rows == f"{group}-{ct1}") &
|
|
101
|
+
# (shuffled_cols == f"{group}-{ct2}")
|
|
102
|
+
# ]["connections"].values
|
|
103
|
+
#
|
|
104
|
+
# if len(perm_group1) == 0 or len(perm_group2) == 0:
|
|
105
|
+
# return None
|
|
106
|
+
#
|
|
107
|
+
# return calculate_stat(perm_group1, perm_group2, statistic)
|
|
108
|
+
#
|
|
109
|
+
# pvalues = []
|
|
110
|
+
# for group in condition_groups:
|
|
111
|
+
# logger.info(f"Performing permutation test for {ref} vs {group}")
|
|
112
|
+
# for ct1 in tqdm(annotation_groups):
|
|
113
|
+
# for ct2 in annotation_groups:
|
|
114
|
+
#
|
|
115
|
+
# group1 = np.array(connections[(connections["rows"] == ref + "-" + ct1) &
|
|
116
|
+
# (connections["columns"] == ref + "-" + ct2)
|
|
117
|
+
# ]["connections"])
|
|
118
|
+
# group2 = np.array(connections[(connections["rows"] == group + "-" + ct1) &
|
|
119
|
+
# (connections["columns"] == group + "-" + ct2)
|
|
120
|
+
# ]["connections"])
|
|
121
|
+
#
|
|
122
|
+
# if statistic == "sum":
|
|
123
|
+
# log2fc = np.log2((group1.sum()) / (group2.sum()))
|
|
124
|
+
# else:
|
|
125
|
+
# log2fc = np.log2((group1.mean() + 1e-9) / (group2.mean() + 1e-9))
|
|
126
|
+
#
|
|
127
|
+
# observed_stat = calculate_stat(group1, group2, statistic)
|
|
128
|
+
#
|
|
129
|
+
# permuted_stats = Parallel(n_jobs=-1, backend="loky")(
|
|
130
|
+
# delayed(single_permutation_stat)(
|
|
131
|
+
# connections, ref, group, ct1, ct2, statistic
|
|
132
|
+
# )
|
|
133
|
+
# for _ in tqdm(range(n_perms))
|
|
134
|
+
# )
|
|
135
|
+
# permuted_stats = np.array(permuted_stats)
|
|
136
|
+
#
|
|
137
|
+
# # Compute p-value based on alternative hypothesis
|
|
138
|
+
# if alternative == 'two-sided':
|
|
139
|
+
# p_value = np.mean(np.abs(permuted_stats) >= np.abs(observed_stat))
|
|
140
|
+
# elif alternative == 'greater':
|
|
141
|
+
# p_value = np.mean(permuted_stats >= observed_stat)
|
|
142
|
+
# elif alternative == 'less':
|
|
143
|
+
# p_value = np.mean(permuted_stats <= observed_stat)
|
|
144
|
+
# else:
|
|
145
|
+
# raise ValueError("alternative must be 'two-sided', 'greater', or 'less'")
|
|
146
|
+
#
|
|
147
|
+
# pvalues.append((group, ct1, ct2, log2fc, group1.mean(), group2.mean(), p_value))
|
|
148
|
+
#
|
|
149
|
+
# df_pvals = pd.DataFrame(pvalues, columns=["group", "ref_ct", "alt_ct", "log2fc", "mean_ref", "mean_group", "pval"])
|
|
150
|
+
# df_pvals["padj"] = false_discovery_control(df_pvals["pval"])
|
|
151
|
+
# return df_pvals
|
|
152
|
+
#
|
|
153
|
+
#
|
|
154
|
+
# import squidpy as sq
|
|
155
|
+
# import scanpy as sc
|
|
156
|
+
# adata = sc.read_h5ad("/Users/david/Desktop/AMId3_slide3.h5ad")
|
|
157
|
+
# sq.gr.spatial_neighbors(adata, library_key="batch", delaunay=True, coord_type="generic")
|
|
158
|
+
#
|
|
159
|
+
# df = neigh_perm(adata, "3m", statistic="sum")
|
|
160
|
+
#
|
|
161
|
+
#
|
|
162
|
+
#
|
|
163
|
+
#
|
|
164
|
+
# import numpy as np
|
|
165
|
+
# import pandas as pd
|
|
166
|
+
# from sklearn.preprocessing import LabelEncoder
|
|
167
|
+
# from joblib import Parallel, delayed
|
|
168
|
+
# from tqdm import tqdm
|
|
169
|
+
#
|
|
170
|
+
# def neigh_perm_fast(adata: ad.AnnData,
|
|
171
|
+
# ref: str,
|
|
172
|
+
# connectivity_key: str = "spatial_connectivities",
|
|
173
|
+
# annotation_key: str = "annotation",
|
|
174
|
+
# condition_key: str = "condition",
|
|
175
|
+
# statistic: str = "sum",
|
|
176
|
+
# n_perms: int = 1000,
|
|
177
|
+
# alternative: str = "two-sided"):
|
|
178
|
+
#
|
|
179
|
+
# # Prepare labels for each cell (row in adata.obs)
|
|
180
|
+
# conditions = adata.obs[condition_key].values
|
|
181
|
+
# annotations = adata.obs[annotation_key].values
|
|
182
|
+
#
|
|
183
|
+
# # Encode condition and annotation as integers for speed
|
|
184
|
+
# le_condition = LabelEncoder()
|
|
185
|
+
# cond_codes = le_condition.fit_transform(conditions)
|
|
186
|
+
# le_annotation = LabelEncoder()
|
|
187
|
+
# ann_codes = le_annotation.fit_transform(annotations)
|
|
188
|
+
#
|
|
189
|
+
# ref_code = le_condition.transform([ref])[0]
|
|
190
|
+
# condition_groups = [c for c in le_condition.classes_ if c != ref]
|
|
191
|
+
# condition_group_codes = [le_condition.transform([c])[0] for c in condition_groups]
|
|
192
|
+
#
|
|
193
|
+
# # Get connectivity matrix as COO
|
|
194
|
+
# conn = adata.obsp[connectivity_key].tocoo()
|
|
195
|
+
# row_idx = conn.row
|
|
196
|
+
# col_idx = conn.col
|
|
197
|
+
# values = conn.data
|
|
198
|
+
#
|
|
199
|
+
# # Construct arrays of edge attributes: condition and annotation for rows and cols
|
|
200
|
+
# row_cond = cond_codes[row_idx]
|
|
201
|
+
# col_cond = cond_codes[col_idx]
|
|
202
|
+
# row_ann = ann_codes[row_idx]
|
|
203
|
+
# col_ann = ann_codes[col_idx]
|
|
204
|
+
#
|
|
205
|
+
# # All unique annotation groups
|
|
206
|
+
# ann_groups = np.arange(len(le_annotation.classes_))
|
|
207
|
+
#
|
|
208
|
+
# # Precompute index masks for each (condition, annotation) pair on rows and columns
|
|
209
|
+
# # We'll need these for fast filtering later on
|
|
210
|
+
# # But better yet: create masks for edges connecting pairs of (cond, ann) to (cond, ann)
|
|
211
|
+
#
|
|
212
|
+
# # Create a helper function for masks of edges connecting (cond1, ann1) to (cond2, ann2)
|
|
213
|
+
# def edge_mask(cond1, ann1, cond2, ann2):
|
|
214
|
+
# return (row_cond == cond1) & (row_ann == ann1) & (col_cond == cond2) & (col_ann == ann2)
|
|
215
|
+
#
|
|
216
|
+
# # Precompute the baseline statistics for all pairs (ref vs group) and (ann1, ann2)
|
|
217
|
+
# results = []
|
|
218
|
+
#
|
|
219
|
+
# # Calculate observed stats first
|
|
220
|
+
# def calc_stat(g1, g2):
|
|
221
|
+
# if statistic == "mean":
|
|
222
|
+
# return np.mean(g1) - np.mean(g2)
|
|
223
|
+
# elif statistic == "median":
|
|
224
|
+
# return np.median(g1) - np.median(g2)
|
|
225
|
+
# elif statistic == "sum":
|
|
226
|
+
# return np.sum(g1) - np.sum(g2)
|
|
227
|
+
# else:
|
|
228
|
+
# raise ValueError(f"Statistic {statistic} not supported")
|
|
229
|
+
#
|
|
230
|
+
# # Encode all condition labels as array so we can shuffle permutations on condition only
|
|
231
|
+
# original_conditions = cond_codes.copy()
|
|
232
|
+
#
|
|
233
|
+
# # We will do all permutations in one batch later
|
|
234
|
+
# # But first, for each group, each pair (ct1, ct2), compute observed stat and store masks
|
|
235
|
+
#
|
|
236
|
+
# for group_code in condition_group_codes:
|
|
237
|
+
# print(f"Processing {le_condition.inverse_transform([group_code])[0]} vs {ref}")
|
|
238
|
+
# for ct1 in ann_groups:
|
|
239
|
+
# for ct2 in ann_groups:
|
|
240
|
+
# mask_ref = edge_mask(ref_code, ct1, ref_code, ct2)
|
|
241
|
+
# mask_group = edge_mask(group_code, ct1, group_code, ct2)
|
|
242
|
+
#
|
|
243
|
+
# vals_ref = values[mask_ref]
|
|
244
|
+
# vals_group = values[mask_group]
|
|
245
|
+
#
|
|
246
|
+
# if len(vals_ref) == 0 or len(vals_group) == 0:
|
|
247
|
+
# # No edges for this pair - skip or set nan
|
|
248
|
+
# continue
|
|
249
|
+
#
|
|
250
|
+
# observed_stat = calc_stat(vals_ref, vals_group)
|
|
251
|
+
#
|
|
252
|
+
# # Calculate log2fc with pseudocount to avoid zero division
|
|
253
|
+
# sum_ref = vals_ref.sum()
|
|
254
|
+
# sum_group = vals_group.sum()
|
|
255
|
+
# if statistic == "sum":
|
|
256
|
+
# log2fc = np.log2((sum_group + 1e-9) / (sum_ref + 1e-9))
|
|
257
|
+
# else:
|
|
258
|
+
# mean_ref = vals_ref.mean()
|
|
259
|
+
# mean_group = vals_group.mean()
|
|
260
|
+
# log2fc = np.log2((mean_group + 1e-9) / (mean_ref + 1e-9))
|
|
261
|
+
#
|
|
262
|
+
# # Store info for permutation test
|
|
263
|
+
# results.append({
|
|
264
|
+
# "group_code": group_code,
|
|
265
|
+
# "ct1": ct1,
|
|
266
|
+
# "ct2": ct2,
|
|
267
|
+
# "observed_stat": observed_stat,
|
|
268
|
+
# "vals_ref": vals_ref,
|
|
269
|
+
# "vals_group": vals_group,
|
|
270
|
+
# "log2fc": log2fc,
|
|
271
|
+
# "sum_ref": sum_ref,
|
|
272
|
+
# "sum_group": sum_group,
|
|
273
|
+
# })
|
|
274
|
+
#
|
|
275
|
+
# # Now, perform permutations
|
|
276
|
+
# # We'll generate a matrix of shape (n_perms, n_cells) with permuted condition codes
|
|
277
|
+
# n_cells = adata.n_obs
|
|
278
|
+
# rng = np.random.default_rng()
|
|
279
|
+
#
|
|
280
|
+
# # Generate all permutations at once
|
|
281
|
+
# permutations = np.array([rng.permutation(original_conditions) for _ in range(n_perms)])
|
|
282
|
+
#
|
|
283
|
+
# # For each permutation, we assign permuted cond codes to each edge's row and col
|
|
284
|
+
#
|
|
285
|
+
# # Since edges connect cells, get the indices of the cells connected for rows and cols
|
|
286
|
+
# # We'll do a quick lookup of permuted condition for each edge's row and col cell:
|
|
287
|
+
# # permuted_row_cond = permutations[:, row_idx]
|
|
288
|
+
# # permuted_col_cond = permutations[:, col_idx]
|
|
289
|
+
# # Shapes: (n_perms, n_edges)
|
|
290
|
+
#
|
|
291
|
+
# permuted_row_cond = permutations[:, row_idx] # shape: (n_perms, n_edges)
|
|
292
|
+
# permuted_col_cond = permutations[:, col_idx]
|
|
293
|
+
#
|
|
294
|
+
# # The annotation does not change during permutation, so reuse row_ann and col_ann
|
|
295
|
+
#
|
|
296
|
+
# # For each stored result, compute permutation stats vectorized
|
|
297
|
+
#
|
|
298
|
+
# pvals = []
|
|
299
|
+
#
|
|
300
|
+
# for res in tqdm(results, desc="Permutation testing"):
|
|
301
|
+
# group_code = res["group_code"]
|
|
302
|
+
# ct1 = res["ct1"]
|
|
303
|
+
# ct2 = res["ct2"]
|
|
304
|
+
# observed_stat = res["observed_stat"]
|
|
305
|
+
#
|
|
306
|
+
# # Create mask arrays for permuted edges matching the pairs for ref and group
|
|
307
|
+
#
|
|
308
|
+
# # Condition masks for permuted row and col for ref and group
|
|
309
|
+
# # (n_perms, n_edges) boolean arrays:
|
|
310
|
+
#
|
|
311
|
+
# # For ref condition edges:
|
|
312
|
+
# mask_perm_ref = (permuted_row_cond == ref_code) & (row_ann == ct1) & \
|
|
313
|
+
# (permuted_col_cond == ref_code) & (col_ann == ct2)
|
|
314
|
+
#
|
|
315
|
+
# # For group condition edges:
|
|
316
|
+
# mask_perm_group = (permuted_row_cond == group_code) & (row_ann == ct1) & \
|
|
317
|
+
# (permuted_col_cond == group_code) & (col_ann == ct2)
|
|
318
|
+
#
|
|
319
|
+
# # Sum or mean values for each permutation:
|
|
320
|
+
# if statistic == "sum":
|
|
321
|
+
# vals_perm_ref = (mask_perm_ref * values).sum(axis=1)
|
|
322
|
+
# vals_perm_group = (mask_perm_group * values).sum(axis=1)
|
|
323
|
+
# elif statistic == "mean":
|
|
324
|
+
# # mean = sum / count; need to handle zero counts
|
|
325
|
+
# counts_ref = mask_perm_ref.sum(axis=1)
|
|
326
|
+
# counts_group = mask_perm_group.sum(axis=1)
|
|
327
|
+
#
|
|
328
|
+
# sums_ref = (mask_perm_ref * values).sum(axis=1)
|
|
329
|
+
# sums_group = (mask_perm_group * values).sum(axis=1)
|
|
330
|
+
#
|
|
331
|
+
# vals_perm_ref = np.divide(sums_ref, counts_ref, out=np.zeros_like(sums_ref), where=counts_ref > 0)
|
|
332
|
+
# vals_perm_group = np.divide(sums_group, counts_group, out=np.zeros_like(sums_group), where=counts_group > 0)
|
|
333
|
+
#
|
|
334
|
+
# elif statistic == "median":
|
|
335
|
+
# # median is tricky to vectorize for sparse masks, so skip or approximate with mean
|
|
336
|
+
# # To do exact median, need loop - slows down
|
|
337
|
+
# # For speed, we can skip median or do approximate median
|
|
338
|
+
# # Let's skip median permutation for now
|
|
339
|
+
# raise NotImplementedError("Median statistic is not optimized for permutation")
|
|
340
|
+
#
|
|
341
|
+
# else:
|
|
342
|
+
# raise ValueError(f"Statistic {statistic} not supported")
|
|
343
|
+
#
|
|
344
|
+
# # Calculate permutation stats (difference ref - group)
|
|
345
|
+
# perm_stats = vals_perm_ref - vals_perm_group
|
|
346
|
+
#
|
|
347
|
+
# # Calculate p-values based on alternative hypothesis
|
|
348
|
+
# if alternative == "two-sided":
|
|
349
|
+
# p_value = np.mean(np.abs(perm_stats) >= np.abs(observed_stat))
|
|
350
|
+
# elif alternative == "greater":
|
|
351
|
+
# p_value = np.mean(perm_stats >= observed_stat)
|
|
352
|
+
# elif alternative == "less":
|
|
353
|
+
# p_value = np.mean(perm_stats <= observed_stat)
|
|
354
|
+
# else:
|
|
355
|
+
# raise ValueError(f"Alternative {alternative} not supported")
|
|
356
|
+
#
|
|
357
|
+
# pvals.append({
|
|
358
|
+
# "group": le_condition.inverse_transform([group_code])[0],
|
|
359
|
+
# "ref_ct": le_annotation.inverse_transform([ct1])[0],
|
|
360
|
+
# "alt_ct": le_annotation.inverse_transform([ct2])[0],
|
|
361
|
+
# "log2fc": res["log2fc"],
|
|
362
|
+
# "mean_ref": res["sum_ref"],
|
|
363
|
+
# "mean_group": res["sum_group"],
|
|
364
|
+
# "pval": p_value,
|
|
365
|
+
# })
|
|
366
|
+
#
|
|
367
|
+
# df_pvals = pd.DataFrame(pvals)
|
|
368
|
+
# df_pvals["padj"] = false_discovery_control(df_pvals["pval"])
|
|
369
|
+
# return df_pvals
|
|
370
|
+
#
|
|
371
|
+
# df = neigh_perm_fast(adata, "3m")
|
|
372
|
+
#
|
|
373
|
+
#
|
|
374
|
+
# df_wide = df.pivot(index="ref_ct", columns="alt_ct", values="log2fc")
|
|
375
|
+
# df_annot = df.pivot(index="ref_ct", columns="alt_ct", values="padj")
|
|
376
|
+
# df_annot = df_annot.applymap(lambda x: "*" if x < 0.05 else " ").astype(str)
|
|
377
|
+
#
|
|
378
|
+
#
|
|
379
|
+
#
|
|
380
|
+
# import seaborn as sns
|
|
381
|
+
# sns.clustermap(df_wide, cmap="RdYlBu_r", annot=df_annot, fmt="", square=True, yticklabels=True,
|
|
382
|
+
# xticklabels=True, method="complete", center=0)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import anndata as ad
|
|
4
|
+
|
|
5
|
+
from dotools_py import logger
|
|
6
|
+
from dotools_py.utils import convert_path
|
|
7
|
+
|
|
8
|
+
HERE = Path(__file__).parent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def example_10x(path: str | Path = "/tmp/dotools_datasets/") -> None:
|
|
12
|
+
"""Download 10X datasets.
|
|
13
|
+
|
|
14
|
+
Downloads a dataset of PBMC from healty and malignant B cells. Two H5 files will be downloaded
|
|
15
|
+
(`raw_feature_bc_matrix.h5`) and (`filtered_feature_bc_matrix.h5`) for each condition (healthy and disease). They
|
|
16
|
+
will be saved following the structure output from CellRanger (e.g., `healhty/outs/*.h5` or `disease/outs/*.h5`).
|
|
17
|
+
|
|
18
|
+
:param path: Path where the data is downloaded. Two subfolders will be created.
|
|
19
|
+
:return: Returns `None`. H5 files are saved under the provided path. For each condition a subfolder will be created
|
|
20
|
+
in the provided path.
|
|
21
|
+
|
|
22
|
+
Example
|
|
23
|
+
-------
|
|
24
|
+
>>> import dotools_py as do
|
|
25
|
+
>>> import scanpy as sc
|
|
26
|
+
>>> do.dt.example_10x("/tmp/dotools_datasets/")
|
|
27
|
+
2025-10-22 13:29:52,730 - Downloading data to /tmp/dotools_datasets/
|
|
28
|
+
Downloading healthy filtered: 100%|██████████| 20.8M/20.8M [00:00<00:00, 97.5MiB/s]
|
|
29
|
+
Downloading healthy raw: 100%|██████████| 147M/147M [00:01<00:00, 88.1MiB/s]
|
|
30
|
+
Downloading disease filtered: 100%|██████████| 18.7M/18.7M [00:00<00:00, 104MiB/s]
|
|
31
|
+
Downloading disease raw: 100%|██████████| 144M/144M [00:01<00:00, 85.1MiB/s]
|
|
32
|
+
>>> adata = sc.read_10x_h5("/tmp/dotools_datasets/healthy/outs/filtered_feature_bc_matrix.h5")
|
|
33
|
+
>>> adata
|
|
34
|
+
AnnData object with n_obs × n_vars = 7865 × 33538
|
|
35
|
+
var: 'gene_ids', 'feature_types', 'genome', 'pattern', 'read', 'sequence'
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
from tqdm import tqdm
|
|
39
|
+
import requests
|
|
40
|
+
|
|
41
|
+
logger.info(f"Downloading data to {path}")
|
|
42
|
+
path = convert_path(path)
|
|
43
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
healthy_path = path / "healthy" / "outs"
|
|
45
|
+
healthy_path.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
disease_path = path / "disease" / "outs"
|
|
47
|
+
disease_path.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
|
|
49
|
+
healthy_link1 = ("https://cf.10xgenomics.com/samples/cell-exp/"
|
|
50
|
+
"3.0.0/pbmc_10k_protein_v3/pbmc_10k_protein_v3_filtered_feature_bc_matrix.h5")
|
|
51
|
+
healthy_link2 = ("https://cf.10xgenomics.com/samples/cell-exp/"
|
|
52
|
+
"3.0.0/pbmc_10k_protein_v3/pbmc_10k_protein_v3_raw_feature_bc_matrix.h5")
|
|
53
|
+
disease_link1 = ("https://cf.10xgenomics.com/samples/cell-exp/"
|
|
54
|
+
"3.0.0/malt_10k_protein_v3/malt_10k_protein_v3_filtered_feature_bc_matrix.h5")
|
|
55
|
+
disease_link2 = ("https://cf.10xgenomics.com/samples/cell-exp/"
|
|
56
|
+
"3.0.0/malt_10k_protein_v3/malt_10k_protein_v3_raw_feature_bc_matrix.h5")
|
|
57
|
+
for name, link in [
|
|
58
|
+
("healthy filtered", healthy_link1),
|
|
59
|
+
("healthy raw", healthy_link2),
|
|
60
|
+
("disease filtered", disease_link1),
|
|
61
|
+
("disease raw", disease_link2),
|
|
62
|
+
]:
|
|
63
|
+
filename = link.split("10k_protein_v3_")[-1]
|
|
64
|
+
response = requests.get(link, stream=True) # Download in chunks
|
|
65
|
+
total_size = int(response.headers.get("content-length", 0))
|
|
66
|
+
block_size = 1024 # 1 Kibibyte
|
|
67
|
+
current_path = healthy_path if "healthy" in name else disease_path
|
|
68
|
+
with (
|
|
69
|
+
open(current_path / filename, "wb") as file,
|
|
70
|
+
tqdm(
|
|
71
|
+
desc=f"Downloading {name}",
|
|
72
|
+
total=total_size,
|
|
73
|
+
unit="iB",
|
|
74
|
+
unit_scale=True,
|
|
75
|
+
unit_divisor=1024,
|
|
76
|
+
) as bar,
|
|
77
|
+
):
|
|
78
|
+
for data in response.iter_content(block_size):
|
|
79
|
+
file.write(data)
|
|
80
|
+
bar.update(len(data))
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def example_10x_processed() -> ad.AnnData:
|
|
85
|
+
"""Load example datasets from 10x processed.
|
|
86
|
+
|
|
87
|
+
Loads a reduced version of the example datasets from healthy and malignant B cells from 10x used in the
|
|
88
|
+
tutorial of the package.
|
|
89
|
+
|
|
90
|
+
:return: Returns an AnnData object processed with 700 cells and 1851 genes.
|
|
91
|
+
|
|
92
|
+
Example
|
|
93
|
+
-------
|
|
94
|
+
>>> import dotools_py as do
|
|
95
|
+
>>> adata = do.dt.example_10x_processed()
|
|
96
|
+
>>> adata
|
|
97
|
+
AnnData object with n_obs × n_vars = 700 × 1851
|
|
98
|
+
obs: 'batch', 'condition', 'n_genes_by_counts', 'log1p_n_genes_by_counts', 'total_counts', 'log1p_total_counts',
|
|
99
|
+
'total_counts_mt', 'log1p_total_counts_mt', 'pct_counts_mt', 'total_counts_ribo', 'log1p_total_counts_ribo',
|
|
100
|
+
'pct_counts_ribo', 'n_genes', 'n_counts', 'doublet_class', 'doublet_score', 'leiden', 'cell_type', 'autoAnnot',
|
|
101
|
+
'celltypist_conf_score', 'annotation', 'annotation_recluster'
|
|
102
|
+
var: 'mean', 'std', 'highly_variable', 'means', 'dispersions', 'dispersions_norm', 'highly_variable_nbatches',
|
|
103
|
+
'highly_variable_intersection'
|
|
104
|
+
uns: 'annotation_colors', 'annotation_recluster_colors', 'batch_colors', 'hvg', 'leiden', 'leiden_colors', 'log1p',
|
|
105
|
+
'neighbors', 'pca', 'umap'
|
|
106
|
+
obsm: 'X_CCA', 'X_pca', 'X_umap'
|
|
107
|
+
varm: 'PCs'
|
|
108
|
+
layers: 'counts', 'logcounts'
|
|
109
|
+
obsp: 'connectivities', 'distances'
|
|
110
|
+
|
|
111
|
+
"""
|
|
112
|
+
return ad.read_h5ad(HERE / "example_reduced.h5ad")
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
from dotools_py import logger
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def heart_markers(
|
|
7
|
+
species: Literal["mouse", "human"] = "mouse",
|
|
8
|
+
) -> dict:
|
|
9
|
+
"""Marker genes for cell-types in the heart.
|
|
10
|
+
|
|
11
|
+
:param species: Format for gene names. Set `human` for everything upper case and `mouse` for capitalise.
|
|
12
|
+
:return: Returns a dictionary with a list of marker genes for major cell-types present in the heart.
|
|
13
|
+
|
|
14
|
+
Example
|
|
15
|
+
-------
|
|
16
|
+
>>> import dotools_py as do
|
|
17
|
+
>>> df_mouse = do.dt.heart_markers("mouse")
|
|
18
|
+
2025-07-02 10:55:01,623 - Getting mouse markers
|
|
19
|
+
>>> df_mouse["EndoEC"]
|
|
20
|
+
['Nfatc1', 'Npr3', 'Nrg1', 'Pecam1', 'Cdh5', 'Etv2']
|
|
21
|
+
|
|
22
|
+
**Summary of Markers genes**
|
|
23
|
+
|
|
24
|
+
.. image:: MarkersCellsHeart.png
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
logger.info(f"Getting {species} markers")
|
|
28
|
+
species = species.lower()
|
|
29
|
+
|
|
30
|
+
mouse = {
|
|
31
|
+
"Art_EC": ["Rbp7", "Ly6a", "Id1", "Stmn2", "Fbln5", "Glul", "Cxcl12", "Sox17", "Hey1", "Mgll", "Dusp1",
|
|
32
|
+
"Alpl", "Btg2", "Klf4", "Crip1"], # Refined with Kalucka et al., Cell, 2022
|
|
33
|
+
"CapEC": ["Cd36", "Fabp4", "Aqp1", "Rgcc", "Gpihbp1", "Aplnr", "Lpl", "Sparcl1", "Car4", "Sparc",
|
|
34
|
+
"Tcf15", "Sgk1", "Kdr", "Cav1", "Vwa1"], # Refined with Kalucka et al., Cell, 2022
|
|
35
|
+
"VeinEC": ["Mgp", "Cfh", "Apoe", "Cpe", "Bgn", "Vwf", "Fabp5", "Vcam1", "H19", "Tmem108", "F2r",
|
|
36
|
+
"Ptgs1", "Il6st", "Vim", "Comp"], # Refined with Kalucka et al., Cell, 2022
|
|
37
|
+
"LymphEC": ["Prox1", "Lyve1", "Pdpn", "Ccl21a", "Fgl2", "Mmrn1", "Lcn2", "Nts", "Cp", "Reln",
|
|
38
|
+
"Cd63", "Maf", "Lmo2", "Ntn1", "Anxa1"], # Refined with Kalucka et al., Cell, 2022
|
|
39
|
+
"EndoEC": ["Nfatc1", "Npr3", "Nrg1", "Pecam1", "Cdh5", "Etv2"], # ZMM_shared JW
|
|
40
|
+
"SMC": ["Myh11", "Itga8", "Acta2", "Tagln", "Carmn", "Kcnab1", "Ntrk3", "Rcan2"], # Refined
|
|
41
|
+
"PC": ["Rgs5", "Abcc9", "Gucy1a2", "Egflam", "Dlc1", "Pdgfrb", "Des", "Cd248", "Mcam"], # Refined
|
|
42
|
+
"FB": ["Dcn", "Abca9", "Mgp", "Lama2", "Abca6", "Gsn", "Pdgfra", "Vim", "Fap", "Pdgfrb"], # Refined
|
|
43
|
+
"FBa": ["Postn"], # Refined JW ZMM_shared
|
|
44
|
+
"Neurons": ["Nrxn1", "Cadm2", "Chl1", "Kirrel3", "Sorcs1", "Ncam2", "Pax3"], # Refined
|
|
45
|
+
"CM": ["Ryr2", "Mlip", "Ttn", "Fhl2", "Rbm20", "Ankrd1", "Tecrl", "Mybpc3", "Tnni3", "Myh7", "Mybpc3",
|
|
46
|
+
"Irx4"], # Refined
|
|
47
|
+
"B_cells": ["Igkc", "Ighm", "Aff3", "Cd74", "Bank1", "Ms4a1", "Cd79a", "Cd69"], # Refined
|
|
48
|
+
"T_cells": ["Il7r", "Themis", "Skap1", "Cd247", "Itk", "Ptprc", "Camk4", "Cd3e", "Cd3d",
|
|
49
|
+
"Cd4", "Cd8a"], # Refined
|
|
50
|
+
"Myeloid": ["F13a1", "Rbpj", "Cd163", "Rbm47", "Mrc1", "Fmn1", "Msr1", "Frmd4b", "Mertk", "Lyz2"], # Refined
|
|
51
|
+
"MP_recruit": ["Ccr2"],
|
|
52
|
+
"MP_resident": ["Lyve1", "Timd4"],
|
|
53
|
+
"ImmuneCells": ["Ptprc"],
|
|
54
|
+
"Epicardial": ["Pdzrn4", "Slc39a8", "Gfpt2", "C3", "Wwc1", "Kcnt2", "Wt1", "Dpp4", "Ano1"], # Refined
|
|
55
|
+
"Adip": ["Gpam", "Adipoq", "Acacb", "Ghr", "Pde3b", "Fasn", "Prkar2b", "Plin1", "Pparg"], # Refined
|
|
56
|
+
"Mast": ["Il18r1", "Kit", "Slc24a3", "Ntm", "Cpa3", "Slc8a3", "Cdk15", "Hpgds", "Slc38a11",
|
|
57
|
+
"Rab27b"], # Refined
|
|
58
|
+
} # Cell Type Markers in Mouse Format
|
|
59
|
+
|
|
60
|
+
human = {cell: [gene.upper() for gene in mouse[cell]] for cell in mouse} # Cell Type Markers in Human Format
|
|
61
|
+
|
|
62
|
+
if species == "mouse":
|
|
63
|
+
return mouse
|
|
64
|
+
elif species == "human":
|
|
65
|
+
return human
|
|
66
|
+
else:
|
|
67
|
+
raise Exception("Species not recognise")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def standard_ct_labels_heart() -> dict:
|
|
71
|
+
"""Set common cell-type labels in the Human Heart Model from Celltypist.
|
|
72
|
+
|
|
73
|
+
This set a common an informative label for the cell-types in the heart model. For example, instead of using
|
|
74
|
+
EC1_cap, EC3_cap, the common label CapEC can be used. The nature of the subtypes of cell-types needs to be
|
|
75
|
+
investigated on the dataset. The model might assigned a cell-type based on similarity, however, the assignment
|
|
76
|
+
might be incorrect if the cell-type is not present in the model.
|
|
77
|
+
|
|
78
|
+
:return: Returns a dictionary with the labels from the model as keys and the updated labels as values.
|
|
79
|
+
|
|
80
|
+
Example
|
|
81
|
+
-------
|
|
82
|
+
>>> import dotools_py as do
|
|
83
|
+
>>> labels = do.dt.standard_ct_labels_heart()
|
|
84
|
+
>>> labels
|
|
85
|
+
{'PC1_vent': 'Pericytes',
|
|
86
|
+
'SMC1_basic': 'SMC',
|
|
87
|
+
'SMC2_art': 'SMC',
|
|
88
|
+
'CD16+Mo': 'Ccr2_MP',
|
|
89
|
+
'LYVE1+IGF1+MP': 'MP',
|
|
90
|
+
'B_plasma': 'B_cells',
|
|
91
|
+
'B': 'B_cells',
|
|
92
|
+
'CD4+T_naive':
|
|
93
|
+
'T_cells',
|
|
94
|
+
'EC1_cap': 'CapEC',
|
|
95
|
+
'EC3_cap': 'CapEC',
|
|
96
|
+
'EC5_art': 'ArtEC',
|
|
97
|
+
'EC6_ven': 'VeinEC',
|
|
98
|
+
'EC7_endocardial': 'EndoEC',
|
|
99
|
+
'EC8_ln': 'LymphEC',
|
|
100
|
+
'FB3': 'Fibroblasts',
|
|
101
|
+
'FB4_activated': 'Fibro_activ',
|
|
102
|
+
'FB5': 'Fibroblasts',
|
|
103
|
+
'Meso': 'Epi_cells',
|
|
104
|
+
'vCM1': 'CM',
|
|
105
|
+
'Adip1': 'Adip',
|
|
106
|
+
'NC1_glial': 'Neural',
|
|
107
|
+
'LYVE1+TIMD4+MP': 'MP',
|
|
108
|
+
'MoMP': 'MP',
|
|
109
|
+
'DC': 'Dendritic',
|
|
110
|
+
'Mast': 'Mast',
|
|
111
|
+
'FB1': 'Fibroblasts',
|
|
112
|
+
'CD8+T_trans': 'T_cells',
|
|
113
|
+
'vCM4': 'CM',
|
|
114
|
+
'NC2_glial_NGF+': 'NC_glial_NGF+',
|
|
115
|
+
'NK_CD16hi': 'NK'
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
"""
|
|
119
|
+
return {
|
|
120
|
+
"PC1_vent": "Pericytes",
|
|
121
|
+
"SMC1_basic": "SMC", # SMC1_basic has transcripts that indicate immaturity
|
|
122
|
+
"SMC2_art": "SMC",
|
|
123
|
+
"CD16+Mo": "Ccr2_MP",
|
|
124
|
+
"LYVE1+IGF1+MP": "MP",
|
|
125
|
+
"B_plasma": "B_cells",
|
|
126
|
+
"B": "B_cells",
|
|
127
|
+
"CD4+T_naive": "T_cells",
|
|
128
|
+
"EC1_cap": "CapEC",
|
|
129
|
+
"EC3_cap": "CapEC",
|
|
130
|
+
"EC5_art": "ArtEC",
|
|
131
|
+
"EC6_ven": "VeinEC",
|
|
132
|
+
"EC7_endocardial": "EndoEC",
|
|
133
|
+
"EC8_ln": "LymphEC",
|
|
134
|
+
"FB3": "Fibroblasts", # FB3 is less abundant in the left ventricle, more in the atria
|
|
135
|
+
"FB4_activated": "Fibro_activ", # More abundant in LV
|
|
136
|
+
"FB5": "Fibroblasts", # Less abundant in the right atrium
|
|
137
|
+
"Meso": "Epi_cells",
|
|
138
|
+
"vCM1": "CM", # Mainly in the left ventricle
|
|
139
|
+
"Adip1": "Adip", # Genes for PPAR pathway, metabolism of lipids and lipoproteins and lipolysis
|
|
140
|
+
"NC1_glial": "Neural", # Neural cells with a gene program required for glia development and axon myelination
|
|
141
|
+
"LYVE1+TIMD4+MP": "MP", # Positive for TIMD4 predicted to act on apoptotic cell clearance
|
|
142
|
+
"MoMP": "MP",
|
|
143
|
+
"DC": "Dendritic",
|
|
144
|
+
"Mast": "Mast",
|
|
145
|
+
"FB1": "Fibroblasts",
|
|
146
|
+
"CD8+T_trans": "T_cells",
|
|
147
|
+
"vCM4": "CM",
|
|
148
|
+
"NC2_glial_NGF+": "NC_glial_NGF+",
|
|
149
|
+
"NK_CD16hi": "NK",
|
|
150
|
+
}
|
|
Binary file
|