-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsurvival analysis.py
304 lines (278 loc) · 16.6 KB
/
survival analysis.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import pandas as pd
import scipy.stats
from statistics import mean
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
from lifelines import CoxPHFitter
from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test, multivariate_logrank_test
from statsmodels.stats.multitest import multipletests
from lifelines.plotting import add_at_risk_counts
from sklearn.decomposition import PCA
from umap import UMAP
import statsmodels.api as sm
import forestplot as fp
if __name__ == '__main__':
# Load clinical data of IMmotion151 and Braunetal
signature = ['StromalScore', 'ImmuneScore', 'ESTIMATEScore', 'AdenoSig',
'JAVELIN_26', 'Angio_Score', 'Teff_Score', 'Myeloid_Score']
results_dir = 'revision/results_lennert_project'
# IMmotion151
len_samples = 823
data = pd.read_csv(f'{results_dir}/IMmotion151.ClinicalAndDeconvolution.csv', header=0, index_col='RNASEQ_SAMPLE_ID')
data = data.rename({'PFS_MONTHS': 'PFS_MO'}, axis=1)
data.loc[data['PFS_CENSOR'] == 0, 'PFS_EVENT'] = 1
data.loc[data['PFS_CENSOR'] == 1, 'PFS_EVENT'] = 0
cols = []
cols.extend(signature)
cols.extend(['AGE', 'SEX', 'PFS_MO', 'PFS_EVENT', 'ARM', 'PRIMARY_VS_METASTATIC', 'NMF_GROUP', 'MSKCC_RISK_SCORE', 'PDL1_IHC', 'OBJECTIVE_RESPONSE'])
survival_df = data[cols]
survival_df['Dataset'] = 'IMmotion151'
survival_df = survival_df[survival_df['Myeloid_Score'].notna()]
survival_df['NMF_GROUP'] = survival_df['NMF_GROUP'].astype(int)
survival_df_T_P = survival_df.loc[(survival_df['ARM']=='atezo_bev') & (survival_df['PRIMARY_VS_METASTATIC']=='PRIMARY')]
survival_df_T_M = survival_df.loc[(survival_df['ARM']=='atezo_bev') & (survival_df['PRIMARY_VS_METASTATIC']=='METASTATIC')]
survival_df_C_P = survival_df.loc[(survival_df['ARM']=='sunitinib') & (survival_df['PRIMARY_VS_METASTATIC']=='PRIMARY')]
survival_df_C_M = survival_df.loc[(survival_df['ARM']=='sunitinib') & (survival_df['PRIMARY_VS_METASTATIC']=='METASTATIC')]
survival_df_T = survival_df.loc[survival_df['ARM']=='atezo_bev']
survival_df_C = survival_df.loc[survival_df['ARM']=='sunitinib']
survival_df_P = survival_df.loc[survival_df['PRIMARY_VS_METASTATIC']=='PRIMARY']
survival_df_M = survival_df.loc[survival_df['PRIMARY_VS_METASTATIC']=='METASTATIC']
# BraunEtAl
len_samples = 311
data = pd.read_csv(f'{results_dir}/Braun_et_al.ClinicalAndDeconvolution.csv', header=0, index_col='RNA_ID')
# Unify datasets
cols = []
cols.extend(signature)
cols.extend(['Age', 'Sex', 'OS', 'OS_CNSR', 'PFS', 'PFS_CNSR','Arm', 'Tumor_Sample_Primary_or_Metastas', 'ORR'])
survival_df = data[cols]
survival_df = survival_df.rename({'Age': 'AGE'}, axis=1)
survival_df = survival_df.rename({'Sex': 'SEX'}, axis=1)
survival_df.loc[survival_df['SEX'] == 'Female', 'SEX'] = 'F'
survival_df.loc[survival_df['SEX'] == 'FEMALE', 'SEX'] = 'F'
survival_df.loc[survival_df['SEX'] == 'MALE', 'SEX'] = 'M'
survival_df.loc[survival_df['SEX'] == 'Male', 'SEX'] = 'M'
survival_df.loc[survival_df['PFS_CNSR'] == 0, 'PFS_EVENT'] = 1
survival_df.loc[survival_df['PFS_CNSR'] == 1, 'PFS_EVENT'] = 0
survival_df.loc[survival_df['OS_CNSR'] == 0, 'OS_EVENT'] = 1
survival_df.loc[survival_df['OS_CNSR'] == 1, 'OS_EVENT'] = 0
survival_df = survival_df.rename({'OS': 'OS_MO'}, axis=1)
survival_df = survival_df.rename({'PFS': 'PFS_MO'}, axis=1)
# survival_df = survival_df.drop(columns= ['PFS_CNSR','OS_CNSR'])
survival_df['Dataset'] = 'BraunEtAl'
survival_df = survival_df[survival_df['Myeloid_Score'].notna()]
survival_df_T_P = survival_df.loc[(survival_df['Arm']=='NIVOLUMAB') & (survival_df['Tumor_Sample_Primary_or_Metastas']=='PRIMARY')]
survival_df_T_M = survival_df.loc[(survival_df['Arm']=='NIVOLUMAB') & (survival_df['Tumor_Sample_Primary_or_Metastas']=='METASTASIS')]
survival_df_C_P = survival_df.loc[(survival_df['Arm']=='EVEROLIMUS') & (survival_df['Tumor_Sample_Primary_or_Metastas']=='PRIMARY')]
survival_df_C_M = survival_df.loc[(survival_df['Arm']=='EVEROLIMUS') & (survival_df['Tumor_Sample_Primary_or_Metastas']=='METASTASIS')]
survival_df_T = survival_df.loc[survival_df['Arm']=='NIVOLUMAB' ]
survival_df_C = survival_df.loc[survival_df['Arm']=='EVEROLIMUS']
survival_df_P = survival_df.loc[survival_df['Tumor_Sample_Primary_or_Metastas']=='PRIMARY']
survival_df_M = survival_df.loc[survival_df['Tumor_Sample_Primary_or_Metastas']=='METASTASIS']
# (1) ---------------------PCA and clustering analysis of RNA profiles (Jul 28)-------------------------
# IMmotion151
sub_dir = 'immotion151'
plot_dir = f'{results_dir}/{sub_dir}/umap'
metastatic_colname = 'PRIMARY_VS_METASTATIC'
rna = pd.read_csv('/juno/work/reznik/xiea1/MIRTH/RNA_raw_imputation/IMmotion151.csv', header=0, index_col=0)
rna = np.log(rna+1)
# Step 1: Perform PCA on gene expression data
pca = PCA(n_components=4)
pca_components = pca.fit_transform(rna)
# Step 2: Perform UMAP on the PCA components
#umap = UMAP(n_neighbors=15, min_dist=0.1, metric='euclidean')
#umap_components = umap.fit_transform(pca_components)
# Step 3: Create a combined dataframe with UMAP components and metadata
umap_df = pd.DataFrame(pca_components, columns=['UMAP1', 'UMAP2', 'UMAP3', 'UMAP4'])
umap_df.index = rna.index
umap_df = pd.concat([umap_df, survival_df], axis=1)
umap_df['color'] = umap_df[metastatic_colname].map({'PRIMARY': 0, 'METASTATIC': 1})
# Step 4: Plot the UMAP results with color-coded metastatic vs. primary samples
plt.figure(figsize=(8, 8))
plt.scatter(umap_df['UMAP3'], umap_df['UMAP4'], c=umap_df['color'], cmap='coolwarm', edgecolors='k', s=50)
plt.xlabel('PCA Component 3')
plt.ylabel('PCA Component 4')
plt.title(sub_dir)
cbar = plt.colorbar(ticks=[0, 1], label='Sample Origin')
cbar.ax.set_yticklabels(['PRIMARY', 'METASTATIC'])
plt.savefig(f'{plot_dir}/{sub_dir}_log_rna_pca_34.pdf')
plt.close()
# Braunetal
sub_dir = 'braunetal'
plot_dir = f'{results_dir}/{sub_dir}/umap'
metastatic_colname = 'Tumor_Sample_Primary_or_Metastas'
rna = pd.read_csv('/juno/work/reznik/xiea1/MIRTH/RNA_raw_imputation/BraunEtAl.csv', header=0, index_col=0)
rna = np.log(rna+1)
# Step 1: Perform PCA on gene expression data
pca = PCA(n_components=4)
pca_components = pca.fit_transform(rna)
# Step 2: Perform UMAP on the PCA components
#umap = UMAP(n_neighbors=15, min_dist=0.1, metric='euclidean')
#umap_components = umap.fit_transform(pca_components)
# Step 3: Create a combined dataframe with UMAP components and metadata
umap_df = pd.DataFrame(pca_components, columns=['UMAP1', 'UMAP2', 'UMAP3', 'UMAP4'])
umap_df.index = rna.index
umap_df = pd.concat([umap_df, survival_df], axis=1)
umap_df['color'] = umap_df[metastatic_colname].map({'PRIMARY': 0, 'METASTASIS': 1})
# Step 4: Plot the UMAP results with color-coded metastatic vs. primary samples
plt.figure(figsize=(8, 8))
plt.scatter(umap_df['UMAP3'], umap_df['UMAP4'], c=umap_df['color'], cmap='coolwarm', edgecolors='k', s=50)
plt.xlabel('PCA Component 3')
plt.ylabel('PCA Component 4')
plt.title(sub_dir)
cbar = plt.colorbar(ticks=[0, 1], label='Sample Origin')
cbar.ax.set_yticklabels(['PRIMARY', 'METASTATIC'])
plt.savefig(f'{plot_dir}/{sub_dir}_log_rna_pca_34.pdf')
plt.close()
# (2) ---------------------Signature ~ Response Chi Square test (Jul 29)-------------------------
# IMmotion151
# treatment arm
result_df = pd.DataFrame({'Log Odds Ratio': [], 'Lower Bound': [], 'Upper Bound': [], 'Group': []})
for sig in signature:
for group, df in {'all': survival_df_T, 'primary': survival_df_T_P, 'meta': survival_df_T_M}.items():
df = df.loc[df['OBJECTIVE_RESPONSE'] != 'NE']
df['response'] = np.nan
df.loc[(df['OBJECTIVE_RESPONSE'] == 'PR') | (df['OBJECTIVE_RESPONSE'] == 'CR'), 'response'] = 1
df.loc[(df['OBJECTIVE_RESPONSE'] == 'SD') | (df['OBJECTIVE_RESPONSE'] == 'PD'), 'response'] = 0
median_score = df[sig].median()
df['signature'] = df[sig].apply(lambda x: 1 if x > median_score else 0)
df.loc[(df['response']==1) & (df['signature']==1)].shape
contingency_table = pd.crosstab(df['response'], df['signature'])
# rows are response (0, 1), columns are signature (0, 1)
result_df.loc[f'{sig}_{group}', 'Log Odds Ratio'] = sm.stats.Table2x2(contingency_table.values).log_oddsratio
# log(odds ratio) > 0: higher score in responders
lower_bound, upper_bound = sm.stats.Table2x2(contingency_table.values).log_oddsratio_confint()
result_df.loc[f'{sig}_{group}', 'Lower Bound'] = lower_bound
result_df.loc[f'{sig}_{group}', 'Upper Bound'] = upper_bound
result_df.loc[f'{sig}_{group}', 'P value'] = sm.stats.Table2x2(contingency_table.values).oddsratio_pvalue()
result_df.loc[f'{sig}_{group}', 'Group'] = sig
result_df['Signature'] = result_df.index
result_df.to_csv(f'{results_dir}/immotion151/umap/chi_square_test_response_immotion151_T.csv')
fp.forestplot(result_df,
estimate="Log Odds Ratio",
ll="Lower Bound", hl="Upper Bound",
varlabel="Signature",
groupvar="Group",
pval="P value",
ylabel="Confidence interval",
xlabel="Log(Odds Ratio)")
plt.title("IMmotion151: atezo_bev")
plt.savefig(f'{results_dir}/immotion151/umap/forestplot_immotion151_T.pdf', bbox_inches="tight")
# control arm
result_df = pd.DataFrame({'Log Odds Ratio': [], 'Lower Bound': [], 'Upper Bound': [], 'Group': []})
for sig in signature:
for group, df in {'all': survival_df_C, 'primary': survival_df_C_P, 'meta': survival_df_C_M}.items():
df = df.loc[df['OBJECTIVE_RESPONSE'] != 'NE']
df['response'] = np.nan
df.loc[(df['OBJECTIVE_RESPONSE'] == 'PR') | (df['OBJECTIVE_RESPONSE'] == 'CR'), 'response'] = 1
df.loc[(df['OBJECTIVE_RESPONSE'] == 'SD') | (df['OBJECTIVE_RESPONSE'] == 'PD'), 'response'] = 0
median_score = df[sig].median()
df['signature'] = df[sig].apply(lambda x: 1 if x > median_score else 0)
df.loc[(df['response'] == 1) & (df['signature'] == 1)].shape
contingency_table = pd.crosstab(df['response'], df['signature'])
# rows are response (0, 1), columns are signature (0, 1)
result_df.loc[f'{sig}_{group}', 'Log Odds Ratio'] = sm.stats.Table2x2(
contingency_table.values).log_oddsratio
# log(odds ratio) > 0: higher score in responders
lower_bound, upper_bound = sm.stats.Table2x2(contingency_table.values).log_oddsratio_confint()
result_df.loc[f'{sig}_{group}', 'Lower Bound'] = lower_bound
result_df.loc[f'{sig}_{group}', 'Upper Bound'] = upper_bound
result_df.loc[f'{sig}_{group}', 'P value'] = sm.stats.Table2x2(contingency_table.values).oddsratio_pvalue()
result_df.loc[f'{sig}_{group}', 'Group'] = sig
result_df['Signature'] = result_df.index
result_df.to_csv(f'{results_dir}/immotion151/umap/chi_square_test_response_immotion151_C.csv')
fp.forestplot(result_df,
estimate="Log Odds Ratio",
ll="Lower Bound", hl="Upper Bound",
varlabel="Signature",
groupvar="Group",
pval="P value",
ylabel="Confidence interval",
xlabel="Log(Odds Ratio)")
plt.title("IMmotion151: sunitinib")
plt.savefig(f'{results_dir}/immotion151/umap/forestplot_immotion151_C.pdf', bbox_inches="tight")
# Braunetal
# treatment arm
result_df = pd.DataFrame({'Log Odds Ratio': [], 'Lower Bound': [], 'Upper Bound': [], 'Group': []})
for sig in signature:
for group, df in {'all': survival_df_T, 'primary': survival_df_T_P, 'meta': survival_df_T_M}.items():
df = df.loc[df['ORR'] != 'NE']
df['response'] = np.nan
df.loc[(df['ORR'] == 'PR') | (df['ORR'] == 'CR'), 'response'] = 1
df.loc[(df['ORR'] == 'SD') | (df['ORR'] == 'PD'), 'response'] = 0
median_score = df[sig].median()
df['signature'] = df[sig].apply(lambda x: 1 if x > median_score else 0)
df.loc[(df['response'] == 1) & (df['signature'] == 1)].shape
contingency_table = pd.crosstab(df['response'], df['signature'])
# rows are response (0, 1), columns are signature (0, 1)
result_df.loc[f'{sig}_{group}', 'Log Odds Ratio'] = sm.stats.Table2x2(
contingency_table.values).log_oddsratio
# log(odds ratio) > 0: higher score in responders
lower_bound, upper_bound = sm.stats.Table2x2(contingency_table.values).log_oddsratio_confint()
result_df.loc[f'{sig}_{group}', 'Lower Bound'] = lower_bound
result_df.loc[f'{sig}_{group}', 'Upper Bound'] = upper_bound
result_df.loc[f'{sig}_{group}', 'P value'] = sm.stats.Table2x2(contingency_table.values).oddsratio_pvalue()
result_df.loc[f'{sig}_{group}', 'Group'] = sig
result_df['Signature'] = result_df.index
result_df.to_csv(f'{results_dir}/braunetal/umap/chi_square_test_response_braunetal_T.csv')
fp.forestplot(result_df,
estimate="Log Odds Ratio",
ll="Lower Bound", hl="Upper Bound",
varlabel="Signature",
groupvar="Group",
pval="P value",
ylabel="Confidence interval",
xlabel="Log(Odds Ratio)")
plt.title("braunetal: NIVOLUMAB")
plt.savefig(f'{results_dir}/braunetal/umap/forestplot_braunetal_T.pdf', bbox_inches="tight")
# control arm
result_df = pd.DataFrame({'Log Odds Ratio': [], 'Lower Bound': [], 'Upper Bound': [], 'Group': []})
for sig in signature:
for group, df in {'all': survival_df_C, 'primary': survival_df_C_P, 'meta': survival_df_C_M}.items():
df = df.loc[df['ORR'] != 'NE']
df['response'] = np.nan
df.loc[(df['ORR'] == 'PR') | (df['ORR'] == 'CR') | (df['ORR'] == 'CRPR'), 'response'] = 1
df.loc[(df['ORR'] == 'SD') | (df['ORR'] == 'PD'), 'response'] = 0
median_score = df[sig].median()
df['signature'] = df[sig].apply(lambda x: 1 if x > median_score else 0)
df.loc[(df['response'] == 1) & (df['signature'] == 1)].shape
contingency_table = pd.crosstab(df['response'], df['signature'])
# rows are response (0, 1), columns are signature (0, 1)
result_df.loc[f'{sig}_{group}', 'Log Odds Ratio'] = sm.stats.Table2x2(
contingency_table.values).log_oddsratio
# log(odds ratio) > 0: higher score in responders
lower_bound, upper_bound = sm.stats.Table2x2(contingency_table.values).log_oddsratio_confint()
result_df.loc[f'{sig}_{group}', 'Lower Bound'] = lower_bound
result_df.loc[f'{sig}_{group}', 'Upper Bound'] = upper_bound
result_df.loc[f'{sig}_{group}', 'P value'] = sm.stats.Table2x2(contingency_table.values).oddsratio_pvalue()
result_df.loc[f'{sig}_{group}', 'Group'] = sig
result_df['Signature'] = result_df.index
result_df.to_csv(f'{results_dir}/braunetal/umap/chi_square_test_response_braunetal_C.csv')
fp.forestplot(result_df,
estimate="Log Odds Ratio",
ll="Lower Bound", hl="Upper Bound",
varlabel="Signature",
groupvar="Group",
pval="P value",
ylabel="Confidence interval",
xlabel="Log(Odds Ratio)")
plt.title("braunetal: EVEROLIMUS")
plt.savefig(f'{results_dir}/braunetal/umap/forestplot_braunetal_C.pdf', bbox_inches="tight")
# (3) Generate a forest plot for Lennert (Sep. 7, 2023)
df = pd.read_excel('/juno/work/reznik/xiea1/MIRTH/revision/Table 2a.xlsx',
header=0)
df['Log HR'] = np.log(df['HR'])
df['Lower Bound'] = np.log(df['Lower Bound'])
df['Upper Bound'] = np.log(df['Upper Bound'])
fp.forestplot(df,
estimate="Log HR",
ll="Lower Bound", hl="Upper Bound",
varlabel="Characteristic",
groupvar="Group",
pval="p-value",
ylabel="Confidence interval",
xlabel="Log(Hazard Ratio)")
plt.title("IMmotion151: Atezo_Bev v.s. Sunitinib")
plt.savefig('revision/results_lennert_project/immotion151/umap/forestplot_immotion151_HR.pdf', bbox_inches="tight")
plt.close()