|
2 | 2 | from typing import Tuple |
3 | 3 |
|
4 | 4 | import numpy as np |
5 | | -from numba import njit |
6 | | -from scipy import stats |
| 5 | +from numba import njit, prange |
7 | 6 |
|
8 | 7 | from backend.common.constants import DEPLOYMENT_STAGE_TO_API_URL |
9 | | -from backend.common.utils.rollup import are_cell_types_colinear |
10 | 8 | from backend.wmg.data.utils import setup_retry_session |
11 | 9 |
|
12 | 10 |
|
13 | | -@njit |
14 | | -def nanpercentile_2d(arr: np.ndarray, percentile: float, axis: int) -> np.ndarray: |
15 | | - """ |
16 | | - Calculate the specified percentile of a 2D array along an axis, ignoring NaN values. |
17 | | -
|
18 | | - Arguments |
19 | | - --------- |
20 | | - arr - 2D array to calculate percentile of |
21 | | - percentile - percentile to calculate, as a number between 0 and 100 |
22 | | - axis - axis along which to calculate percentile |
23 | | -
|
24 | | - Returns |
25 | | - ------- |
26 | | - The specified percentile of the 2D array along the specified axis. |
27 | | - """ |
28 | | - if axis == 0: |
29 | | - result = np.empty(arr.shape[1]) |
30 | | - for i in range(arr.shape[1]): |
31 | | - arr_column = arr[:, i] |
32 | | - result[i] = nanpercentile(arr_column, percentile) |
33 | | - return result |
34 | | - else: |
35 | | - result = np.empty(arr.shape[0]) |
36 | | - for i in range(arr.shape[0]): |
37 | | - arr_row = arr[i, :] |
38 | | - result[i] = nanpercentile(arr_row, percentile) |
39 | | - return result |
40 | | - |
41 | | - |
42 | | -@njit |
43 | | -def nanpercentile(arr: np.ndarray, percentile: float): |
44 | | - """ |
45 | | - Calculate the specified percentile of an array, ignoring NaN values. |
46 | | -
|
47 | | - Arguments |
48 | | - --------- |
49 | | - arr - array to calculate percentile of |
50 | | - percentile - percentile to calculate, as a number between 0 and 100 |
51 | | -
|
52 | | - Returns |
53 | | - ------- |
54 | | - The specified percentile of the array. |
55 | | - """ |
56 | | - |
57 | | - arr_without_nan = arr[np.logical_not(np.isnan(arr))] |
58 | | - length = len(arr_without_nan) |
| 11 | +@njit(parallel=True) |
| 12 | +def calculate_specificity_excluding_nans(treatment, control): |
| 13 | + treatment = treatment.flatten() |
59 | 14 |
|
60 | | - if length == 0: |
61 | | - return np.nan |
| 15 | + specificities = np.zeros(treatment.size) |
| 16 | + for i in prange(treatment.size): |
| 17 | + if np.isnan(treatment[i]): |
| 18 | + continue |
| 19 | + col = control[:, i] |
| 20 | + col = col[~np.isnan(col)] |
| 21 | + if col.size == 0: |
| 22 | + specificities[i] = 1 |
| 23 | + else: |
| 24 | + specificities[i] = (treatment[i] > col).mean() |
| 25 | + return specificities |
62 | 26 |
|
63 | | - return np.percentile(arr_without_nan, percentile) |
64 | 27 |
|
65 | | - |
66 | | -def run_ttest( |
| 28 | +def calculate_cohens_d( |
67 | 29 | *, sum1: np.ndarray, sumsq1: np.ndarray, n1: np.ndarray, sum2: np.ndarray, sumsq2: np.ndarray, n2: np.ndarray |
68 | 30 | ) -> Tuple[np.ndarray, np.ndarray]: |
69 | 31 | """ |
70 | | - Run a t-test on two sets of data, element-wise. |
| 32 | + Calculates Cohen's d for two sets of data. |
71 | 33 | Arrays "1" and "2" have to be broadcastable into each other. |
72 | 34 |
|
73 | 35 | Arguments |
@@ -96,73 +58,9 @@ def run_ttest( |
96 | 58 | var1[var1 < 0] = 0 |
97 | 59 | var2 = meansq2 - mean2**2 |
98 | 60 | var2[var2 < 0] = 0 |
99 | | - |
100 | | - var1_n = var1 / n1 |
101 | | - var2_n = var2 / n2 |
102 | | - sum_var_n = var1_n + var2_n |
103 | | - dof = sum_var_n**2 / (var1_n**2 / (n1 - 1) + var2_n**2 / (n2 - 1)) |
104 | | - tscores = (mean1 - mean2) / np.sqrt(sum_var_n) |
105 | 61 | effects = (mean1 - mean2) / np.sqrt(((n1 - 1) * var1 + (n2 - 1) * var2) / (n1 + n2 - 1)) |
106 | 62 |
|
107 | | - pvals = stats.t.sf(tscores, dof) |
108 | | - return pvals, effects |
109 | | - |
110 | | - |
111 | | -def post_process_stats( |
112 | | - *, |
113 | | - cell_type_target: str, |
114 | | - cell_types_context: np.ndarray, |
115 | | - genes: np.ndarray, |
116 | | - pvals: np.ndarray, |
117 | | - effects: np.ndarray, |
118 | | - percentile: float = 0.05, |
119 | | -) -> dict[str, dict[str, float]]: |
120 | | - """ |
121 | | - Post-process the statistical results to handle colinearity of cell types in the ontology and calculate percentiles. |
122 | | -
|
123 | | - Arguments |
124 | | - --------- |
125 | | - cell_type_target - The target cell type |
126 | | - cell_types_context - The context cell types |
127 | | - genes - The genes involved in the analysis |
128 | | - pvals - The p-values from the statistical test |
129 | | - effects - The effect sizes from the statistical test |
130 | | - percentile - The percentile to use for thresholding (default is 0.05) |
131 | | -
|
132 | | - Returns |
133 | | - ------- |
134 | | - A dictionary mapping marker genes to their statistics. |
135 | | - """ |
136 | | - |
137 | | - # parent nodes msut not be compared to their children because they share expressions, |
138 | | - # since the expressions are rolled up across descendants |
139 | | - is_colinear = np.array([are_cell_types_colinear(cell_type, cell_type_target) for cell_type in cell_types_context]) |
140 | | - effects[is_colinear] = np.nan |
141 | | - pvals[is_colinear] = np.nan |
142 | | - |
143 | | - pvals[:, np.all(np.isnan(pvals), axis=0)] = 1 |
144 | | - effects[:, np.all(np.isnan(effects), axis=0)] = 0 |
145 | | - |
146 | | - # aggregate |
147 | | - effects = nanpercentile_2d(effects, percentile * 100, 0) |
148 | | - |
149 | | - effects[effects == 0] = np.nan |
150 | | - |
151 | | - pvals = np.sort(pvals, axis=0)[int(np.round(0.05 * pvals.shape[0]))] |
152 | | - |
153 | | - markers = np.array(genes)[np.argsort(-effects)] |
154 | | - p = pvals[np.argsort(-effects)] |
155 | | - effects = effects[np.argsort(-effects)] |
156 | | - |
157 | | - statistics = [] |
158 | | - final_markers = [] |
159 | | - for i in range(len(p)): |
160 | | - pi = p[i] |
161 | | - ei = effects[i] |
162 | | - if ei is not np.nan and pi is not np.nan: |
163 | | - statistics.append({"p_value": pi, "effect_size": ei}) |
164 | | - final_markers.append(markers[i]) |
165 | | - return dict(zip(list(final_markers), statistics)) |
| 63 | + return effects |
166 | 64 |
|
167 | 65 |
|
168 | 66 | def query_gene_info_for_gene_description(gene_id: str) -> str: |
@@ -193,3 +91,67 @@ def query_gene_info_for_gene_description(gene_id: str) -> str: |
193 | 91 | return data["name"] |
194 | 92 | else: |
195 | 93 | return gene_id |
| 94 | + |
| 95 | + |
| 96 | +@njit(parallel=True) |
| 97 | +def bootstrap_rows_percentiles( |
| 98 | + X: np.ndarray, random_indices: np.ndarray, num_replicates: int = 1000, num_samples: int = 100, percentile: float = 5 |
| 99 | +): |
| 100 | + """ |
| 101 | + This function bootstraps rows of a given matrix X. |
| 102 | +
|
| 103 | + Arguments |
| 104 | + --------- |
| 105 | + X : np.ndarray |
| 106 | + The input matrix to bootstrap. |
| 107 | + num_replicates : int, optional |
| 108 | + The number of bootstrap replicates to generate, by default 1000. |
| 109 | + num_samples : int, optional |
| 110 | + The number of samples to draw in each bootstrap replicate, by default 100. |
| 111 | + percentile : float, optional |
| 112 | + The percentile of the bootstrapped samples for each replicate, by default 15. |
| 113 | +
|
| 114 | + Returns |
| 115 | + ------- |
| 116 | + bootstrap_percentile : np.ndarray |
| 117 | + The percentile of the bootstrapped samples for each replicate. |
| 118 | + """ |
| 119 | + |
| 120 | + bootstrap_percentile = np.zeros((num_replicates, X.shape[1]), dtype="float") |
| 121 | + # for each replicate |
| 122 | + for n_i in prange(num_replicates): |
| 123 | + bootstrap_percentile[n_i] = sort_matrix_columns(X[random_indices[n_i]], percentile, num_samples) |
| 124 | + |
| 125 | + return bootstrap_percentile |
| 126 | + |
| 127 | + |
| 128 | +@njit |
| 129 | +def sort_matrix_columns(matrix, percentile, num_samples): |
| 130 | + """ |
| 131 | + This function sorts the columns of a given matrix and returns the index associated with |
| 132 | + the specified percentile of the sorted samples for each column. This approximates |
| 133 | + np.nanpercentile(matrix, percentile, axis=0). |
| 134 | +
|
| 135 | + Arguments |
| 136 | + --------- |
| 137 | + matrix : np.ndarray |
| 138 | + The input matrix to sort. |
| 139 | + percentile : float |
| 140 | + The percentile of the sorted samples for each column. |
| 141 | + num_samples : int |
| 142 | + The number of samples in each column. |
| 143 | +
|
| 144 | + Returns |
| 145 | + ------- |
| 146 | + result : np.ndarray |
| 147 | + The sorted columns of the input matrix. |
| 148 | + """ |
| 149 | + num_cols = matrix.shape[1] |
| 150 | + result = np.empty(num_cols) |
| 151 | + for col in range(num_cols): |
| 152 | + sorted_col = np.sort(matrix[:, col]) |
| 153 | + num_nans = np.isnan(sorted_col).sum() |
| 154 | + num_non_nans = num_samples - num_nans |
| 155 | + sample_index = int(np.round(percentile / 100 * num_non_nans)) |
| 156 | + result[col] = sorted_col[sample_index] |
| 157 | + return result |
0 commit comments