|
| 1 | +import numpy as np |
| 2 | +from sys import stderr |
| 3 | +from scipy.stats import rankdata |
| 4 | +from utils import percentile |
| 5 | + |
| 6 | +#=============================================================================== |
| 7 | + |
| 8 | +def total_count_normalization(matrix): |
| 9 | + """ |
| 10 | + Total count normalization |
| 11 | + |
| 12 | + Parameters |
| 13 | + ---------- |
| 14 | + matrix : array_like |
| 15 | + Matrix to normalize. |
| 16 | + |
| 17 | + Returns |
| 18 | + ------- |
| 19 | + array_like |
| 20 | + Normalized matrix. |
| 21 | + """ |
| 22 | + return matrix / matrix.sum(axis=0) |
| 23 | + |
| 24 | +#=============================================================================== |
| 25 | + |
| 26 | +def percentile_normalization(matrix, p): |
| 27 | + """ |
| 28 | + Percentile normalization |
| 29 | + |
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + matrix : array_like |
| 33 | + Matrix to normalize. |
| 34 | + p : float in range of [0,100] |
| 35 | + Percentile to compute, which must be between 0 and 100 inclusive. |
| 36 | + |
| 37 | + Returns |
| 38 | + ------- |
| 39 | + array_like |
| 40 | + Normalized matrix. |
| 41 | + """ |
| 42 | + return matrix / percentile(matrix, p) |
| 43 | + |
| 44 | +#=============================================================================== |
| 45 | + |
| 46 | +def quartile_normalization(matrix, q): |
| 47 | + """ |
| 48 | + Quartile normalization |
| 49 | + |
| 50 | + Parameters |
| 51 | + ---------- |
| 52 | + matrix : array_like |
| 53 | + Matrix to normalize. |
| 54 | + q : string from {"lower", "median", "upper"} or quartile number (1, 2 or 3) |
| 55 | + The names of quartiles to compute in accordance: |
| 56 | + "lower" = 1, |
| 57 | + "median" = 2, |
| 58 | + "upper" = 3. |
| 59 | + |
| 60 | + Returns |
| 61 | + ------- |
| 62 | + array_like |
| 63 | + Normalized matrix. |
| 64 | + """ |
| 65 | + d = {"upper": 75, "lower": 25, "median": 50, 3: 75, 1: 25, 2: 50} |
| 66 | + assert q in d, 'Unexpected quartile for normalization: "' + str(q) + '"' |
| 67 | + return percentile_normalization(matrix, d[q]) |
| 68 | + |
| 69 | +#=============================================================================== |
| 70 | + |
| 71 | +def tmm_normalization(matrix, index_ref=None, trim_fold_change=0.3, trim_abs_expr=0.05): |
| 72 | + """ |
| 73 | + Trimmed mean of M-values normalization |
| 74 | + |
| 75 | + Parameters |
| 76 | + ---------- |
| 77 | + matrix : array_like |
| 78 | + Matrix to normalize. |
| 79 | + index_ref: |
| 80 | + Index of reference column. |
| 81 | + trim_fold_change: |
| 82 | + Percent of trimmed for folder change. |
| 83 | + trim_abs_expr: |
| 84 | + Percent of trimmed for absolute expression. |
| 85 | + |
| 86 | + Returns |
| 87 | + ------- |
| 88 | + array_like |
| 89 | + Normalized matrix. |
| 90 | + """ |
| 91 | + matrix_np = np.array(matrix) # better speed of calculating |
| 92 | + np.seterr(divide='ignore', invalid='ignore') # for divide on zeros in log2 |
| 93 | + |
| 94 | + # Calculation log2(tmm_factor) |
| 95 | + def log2_tmm(index_vec): |
| 96 | + # select the necessary vectors |
| 97 | + curr_vec = matrix_np[:, index_vec] |
| 98 | + ref_vec = matrix_np[:, index_ref] |
| 99 | + |
| 100 | + # total number molecules in cells |
| 101 | + total_curr_vec = np.sum(curr_vec) |
| 102 | + total_ref_vec = np.sum(ref_vec) |
| 103 | + |
| 104 | + # select significant genes |
| 105 | + check_inf = (~np.isinf(matr_a[:, index_vec])) & (~np.isinf(matr_m[:, index_vec])) |
| 106 | + ranks = rankdata(matr_a[:, index_vec][check_inf], method='ordinal') |
| 107 | + bool_a = (ranks > len(ranks) * trim_abs_expr) & (ranks < len(ranks) * (1 - trim_abs_expr)) |
| 108 | + ranks = rankdata(matr_m[:, index_vec][check_inf], method='ordinal') |
| 109 | + bool_m = (ranks > len(ranks) * trim_fold_change) & (ranks < len(ranks) * (1 - trim_fold_change)) |
| 110 | + curr_vec = curr_vec[check_inf] |
| 111 | + ref_vec = ref_vec[check_inf] |
| 112 | + bool_curr_vec = curr_vec > 0 |
| 113 | + bool_ref = ref_vec > 0 |
| 114 | + bool_result = bool_curr_vec & bool_ref & bool_a & bool_m |
| 115 | + |
| 116 | + # ñalculation of required values |
| 117 | + w_vec = 1 / ((total_curr_vec - curr_vec[bool_result]) / (total_curr_vec * curr_vec[bool_result]) + |
| 118 | + (total_ref_vec - ref_vec[bool_result]) / (total_ref_vec * ref_vec[bool_result])) |
| 119 | + m_vec = np.log2(curr_vec[bool_result] / total_curr_vec) - np.log2(ref_vec[bool_result] / total_ref_vec) |
| 120 | + |
| 121 | + # calculation log2(tmm_factor) |
| 122 | + w_sum = np.sum(w_vec) |
| 123 | + if np.isclose(w_sum, 0) or np.isinf(w_sum): |
| 124 | + print("Unexpected sum of weights for vector {}: '{}'".format(index_vec, w_sum), file=stderr) |
| 125 | + return 0 |
| 126 | + |
| 127 | + return np.sum(w_vec * m_vec) / w_sum |
| 128 | + |
| 129 | + # find index of reference column |
| 130 | + f75 = percentile(matrix_np, 75) |
| 131 | + if index_ref is None: |
| 132 | + index_ref = np.argmin(abs(f75 - np.mean(f75))) |
| 133 | + elif isinstance(matrix, pd.DataFrame) and ~isinstance(index_ref, int): |
| 134 | + index_ref = np.where(matrix.columns.values == (index_ref))[0][0] |
| 135 | + |
| 136 | + # find matrix A and M described expression levels of genes |
| 137 | + matr_norm = matrix_np / np.sum(matrix_np, axis=0) |
| 138 | + matr_a = np.log2(matr_norm * matr_norm[:, index_ref].reshape(matr_norm.shape[0], 1)) / 2 |
| 139 | + matr_m = np.log2(matr_norm / matr_norm[:, index_ref].reshape(matr_norm.shape[0], 1)) |
| 140 | + |
| 141 | + # calculation tmm_factor and normalization of input data |
| 142 | + tmm_factor = 2 ** np.array([log2_tmm(i) for i in range(matrix_np.shape[1])]) |
| 143 | + return matrix / tmm_factor |
| 144 | + |
| 145 | +#=============================================================================== |
0 commit comments