annotate lifelines_tool/plotlykm.py @ 0:dd49a7040643 draft

Initial commit
author fubar
date Wed, 09 Aug 2023 11:12:16 +0000
parents
children 232b874046a7
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
dd49a7040643 Initial commit
fubar
parents:
diff changeset
1 # script for a lifelines ToolFactory KM/CPH tool for Galaxy
dd49a7040643 Initial commit
fubar
parents:
diff changeset
2 # km models for https://github.com/galaxyproject/tools-iuc/issues/5393
dd49a7040643 Initial commit
fubar
parents:
diff changeset
3 # test as
dd49a7040643 Initial commit
fubar
parents:
diff changeset
4 # python plotlykm.py --input_tab rossi.tab --htmlout "testfoo" --time "week" --status "arrest" --title "test" --image_dir images --cphcol="prio,age,race,paro,mar,fin"
dd49a7040643 Initial commit
fubar
parents:
diff changeset
5
dd49a7040643 Initial commit
fubar
parents:
diff changeset
6 import argparse
dd49a7040643 Initial commit
fubar
parents:
diff changeset
7 import os
dd49a7040643 Initial commit
fubar
parents:
diff changeset
8 import sys
dd49a7040643 Initial commit
fubar
parents:
diff changeset
9
dd49a7040643 Initial commit
fubar
parents:
diff changeset
10 import lifelines
dd49a7040643 Initial commit
fubar
parents:
diff changeset
11
dd49a7040643 Initial commit
fubar
parents:
diff changeset
12 from matplotlib import pyplot as plt
dd49a7040643 Initial commit
fubar
parents:
diff changeset
13
dd49a7040643 Initial commit
fubar
parents:
diff changeset
14 import pandas as pd
dd49a7040643 Initial commit
fubar
parents:
diff changeset
15
dd49a7040643 Initial commit
fubar
parents:
diff changeset
16 # Ross Lazarus July 2023
dd49a7040643 Initial commit
fubar
parents:
diff changeset
17
dd49a7040643 Initial commit
fubar
parents:
diff changeset
18
dd49a7040643 Initial commit
fubar
parents:
diff changeset
19 kmf = lifelines.KaplanMeierFitter()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
20 cph = lifelines.CoxPHFitter()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
21
dd49a7040643 Initial commit
fubar
parents:
diff changeset
22 parser = argparse.ArgumentParser()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
23 a = parser.add_argument
dd49a7040643 Initial commit
fubar
parents:
diff changeset
24 a('--input_tab', default='', required=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
25 a('--header', default='')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
26 a('--htmlout', default="test_run.html")
dd49a7040643 Initial commit
fubar
parents:
diff changeset
27 a('--group', default='')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
28 a('--time', default='', required=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
29 a('--status',default='', required=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
30 a('--cphcols',default='')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
31 a('--title', default='Default plot title')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
32 a('--image_type', default='png')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
33 a('--image_dir', default='images')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
34 a('--readme', default='run_log.txt')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
35 args = parser.parse_args()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
36 sys.stdout = open(args.readme, 'w')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
37 df = pd.read_csv(args.input_tab, sep='\t')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
38 NCOLS = df.columns.size
dd49a7040643 Initial commit
fubar
parents:
diff changeset
39 NROWS = len(df.index)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
40 defaultcols = ['col%d' % (x+1) for x in range(NCOLS)]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
41 testcols = df.columns
dd49a7040643 Initial commit
fubar
parents:
diff changeset
42 if len(args.header.strip()) > 0:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
43 newcols = args.header.split(',')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
44 if len(newcols) == NCOLS:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
45 if (args.time in newcols) and (args.status in newcols):
dd49a7040643 Initial commit
fubar
parents:
diff changeset
46 df.columns = newcols
dd49a7040643 Initial commit
fubar
parents:
diff changeset
47 else:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
48 sys.stderr.write('## CRITICAL USAGE ERROR (not a bug!): time %s and/or status %s not found in supplied header parameter %s' % (args.time, args.status, args.header))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
49 sys.exit(4)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
50 else:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
51 sys.stderr.write('## CRITICAL USAGE ERROR (not a bug!): Supplied header %s has %d comma delimited header names - does not match the input tabular file %d columns' % (args.header, len(newcols), NCOLS))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
52 sys.exit(5)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
53 else: # no header supplied - check for a real one that matches the x and y axis column names
dd49a7040643 Initial commit
fubar
parents:
diff changeset
54 colsok = (args.time in testcols) and (args.status in testcols) # if they match, probably ok...should use more code and logic..
dd49a7040643 Initial commit
fubar
parents:
diff changeset
55 if colsok:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
56 df.columns = testcols # use actual header
dd49a7040643 Initial commit
fubar
parents:
diff changeset
57 else:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
58 colsok = (args.time in defaultcols) and (args.status in defaultcols)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
59 if colsok:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
60 sys.stderr.write('replacing first row of data derived header %s with %s' % (testcols, defaultcols))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
61 df.columns = defaultcols
dd49a7040643 Initial commit
fubar
parents:
diff changeset
62 else:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
63 sys.stderr.write('## CRITICAL USAGE ERROR (not a bug!): time %s and status %s do not match anything in the file header, supplied header or automatic default column names %s' % (args.time, args.status, defaultcols))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
64 print('## Lifelines tool starting.\nUsing data header =', df.columns, 'time column =', args.time, 'status column =', args.status)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
65 os.makedirs(args.image_dir, exist_ok=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
66 fig, ax = plt.subplots()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
67 if args.group > '':
dd49a7040643 Initial commit
fubar
parents:
diff changeset
68 names = []
dd49a7040643 Initial commit
fubar
parents:
diff changeset
69 times = []
dd49a7040643 Initial commit
fubar
parents:
diff changeset
70 events = []
dd49a7040643 Initial commit
fubar
parents:
diff changeset
71 rmst = []
dd49a7040643 Initial commit
fubar
parents:
diff changeset
72 for name, grouped_df in df.groupby(args.group):
dd49a7040643 Initial commit
fubar
parents:
diff changeset
73 T = grouped_df[args.time]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
74 E = grouped_df[args.status]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
75 gfit = kmf.fit(T, E, label=name)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
76 kmf.plot_survival_function(ax=ax)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
77 rst = lifelines.utils.restricted_mean_survival_time(gfit)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
78 rmst.append(rst)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
79 names.append(str(name))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
80 times.append(T)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
81 events.append(E)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
82 ngroup = len(names)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
83 if ngroup == 2: # run logrank test if 2 groups
dd49a7040643 Initial commit
fubar
parents:
diff changeset
84 results = lifelines.statistics.logrank_test(times[0], times[1], events[0], events[1], alpha=.99)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
85 print(' vs '.join(names), results)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
86 results.print_summary()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
87 elif ngroup > 1:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
88 fig, ax = plt.subplots(nrows=ngroup, ncols=1, sharex=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
89 for i, rst in rmst:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
90 lifelines.plotting.rmst_plot(rst, ax=ax)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
91 fig.savefig(os.path.join(args.image_dir,'RMST_%s.png' % args.title))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
92 else:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
93 kmf.fit(df[args.time], df[args.status])
dd49a7040643 Initial commit
fubar
parents:
diff changeset
94 kmf.plot_survival_function(ax=ax)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
95 fig.savefig(os.path.join(args.image_dir,'KM_%s.png' % args.title))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
96 if len(args.cphcols) > 0:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
97 fig, ax = plt.subplots()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
98 cphcols = args.cphcols.strip().split(',')
dd49a7040643 Initial commit
fubar
parents:
diff changeset
99 cphcols = [x.strip() for x in cphcols]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
100 notfound = sum([(x not in df.columns) for x in cphcols])
dd49a7040643 Initial commit
fubar
parents:
diff changeset
101 if notfound > 0:
dd49a7040643 Initial commit
fubar
parents:
diff changeset
102 sys.stderr.write('## CRITICAL USAGE ERROR (not a bug!): One or more requested Cox PH columns %s not found in supplied column header %s' % (args.cphcols, df.columns))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
103 sys.exit(6)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
104 print('### Lifelines test of Proportional Hazards results with %s as covariates on %s' % (', '.join(cphcols), args.title))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
105 cphcols += [args.time, args.status]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
106 cphdf = df[cphcols]
dd49a7040643 Initial commit
fubar
parents:
diff changeset
107 cph.fit(cphdf, duration_col=args.time, event_col=args.status)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
108 cph.print_summary()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
109 cphaxes = cph.check_assumptions(cphdf, p_value_threshold=0.01, show_plots=True)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
110 for i, ax in enumerate(cphaxes):
dd49a7040643 Initial commit
fubar
parents:
diff changeset
111 figr = ax[0].get_figure()
dd49a7040643 Initial commit
fubar
parents:
diff changeset
112 titl = figr._suptitle.get_text().replace(' ','_').replace("'","")
dd49a7040643 Initial commit
fubar
parents:
diff changeset
113 oname = os.path.join(args.image_dir,'CPH%s.%s' % (titl, args.image_type))
dd49a7040643 Initial commit
fubar
parents:
diff changeset
114 figr.savefig(oname)
dd49a7040643 Initial commit
fubar
parents:
diff changeset
115
dd49a7040643 Initial commit
fubar
parents:
diff changeset
116
dd49a7040643 Initial commit
fubar
parents:
diff changeset
117
dd49a7040643 Initial commit
fubar
parents:
diff changeset
118