forked from avsastry/modulome-workflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_dimension.py
executable file
·144 lines (112 loc) · 3.62 KB
/
get_dimension.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/bin/python
"""
Searches for the optimal dimensionality of independent components
OUT_DIR: Path to output directory
"""
import argparse
import os
import shutil
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy import stats
from tqdm import tqdm
# ------------------------------------
# Argument parsing
parser = argparse.ArgumentParser(
description="Searches for optimal dimensionality of independent components"
)
parser.add_argument(
"-o",
dest="out_dir",
default="",
help="Path to output file directory (default: current directory)",
)
args = parser.parse_args()
print()
print("Computing optimal set of independent components")
print()
# ------------------------------------
# Load data
def load_mat(dim, mat):
df = pd.read_csv(
os.path.join(args.out_dir, "ica_runs", str(dim), mat + ".csv"), index_col=0
)
df.columns = range(len(df.columns))
return df.astype(float)
dims = sorted([int(x) for x in os.listdir(os.path.join(args.out_dir, "ica_runs"))])
M_data = [load_mat(dim, "M") for dim in dims]
A_data = [load_mat(dim, "A") for dim in dims]
# -----------------------------------
# Check large iModulon dimensions
final_a = A_data[-1]
while np.allclose(final_a, 0, atol=0.01):
A_data = A_data[:-1]
M_data = M_data[:-1]
dims = dims[:-1]
final_a = A_data[-1]
final_m = M_data[-1]
n_components = [m.shape[1] for m in M_data]
# -----------------------------------
# Get iModulon statistics
thresh = 0.7
n_final_mods = []
n_single_genes = []
for m in M_data:
# Find iModulons similar to the highest dimension
l2_final = np.sqrt(np.power(final_m, 2).sum(axis=0))
l2_m = np.sqrt(np.power(m, 2).sum(axis=0))
dist = (
pd.DataFrame(abs(np.dot(final_m.T, m)))
.divide(l2_final, axis=0)
.divide(l2_m, axis=1)
)
n_final_mods.append(len(np.where(dist > thresh)[0]))
# Find iModulons with single gene outliers
counter = 0
for col in m.columns:
sorted_genes = abs(m[col]).sort_values(ascending=False)
if sorted_genes.iloc[0] > 2 * sorted_genes.iloc[1]:
counter += 1
n_single_genes.append(counter)
non_single_components = np.array(n_components) - np.array(n_single_genes)
DF_stats = pd.DataFrame(
[n_components, n_final_mods, non_single_components, n_single_genes],
index=[
"Robust Components",
"Final Components",
"Multi-gene Components",
"Single Gene Components",
],
columns=dims,
).T
DF_stats.sort_index(inplace=True)
dimensionality = (
DF_stats[DF_stats["Final Components"] >= DF_stats["Multi-gene Components"]]
.iloc[0]
.name
)
print("Optimal Dimensionality:", dimensionality)
print()
# Plot dimensions
fig, ax = plt.subplots()
ax.plot(dims, n_components, label="Robust Components")
ax.plot(dims, n_final_mods, label="Final Components")
ax.plot(dims, non_single_components, label="Non-single-gene Components")
ax.plot(dims, n_single_genes, label="Single Gene Components")
ax.vlines(dimensionality, 0, max(n_components), linestyle="dashed")
ax.set_xlabel("Dimensionality")
ax.set_ylabel("# Components")
ax.legend(bbox_to_anchor=(1, 1))
plt.savefig(
os.path.join(args.out_dir, "dimension_analysis.pdf"),
bbox_inches="tight",
transparent=True,
)
# Save final matrices
final_M_file = os.path.join(args.out_dir, "ica_runs", str(dimensionality), "M.csv")
final_A_file = os.path.join(args.out_dir, "ica_runs", str(dimensionality), "A.csv")
final_M_dest = os.path.join(args.out_dir, "M.csv")
final_A_dest = os.path.join(args.out_dir, "A.csv")
shutil.copyfile(final_M_file, final_M_dest)
shutil.copyfile(final_A_file, final_A_dest)