-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmean_of_tables.py
More file actions
executable file
·288 lines (233 loc) · 10.7 KB
/
mean_of_tables.py
File metadata and controls
executable file
·288 lines (233 loc) · 10.7 KB
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
#!/usr/bin/env python3
"""
Purpose: Compute the mean values across all numeric cells for multiple identically formatted tables
Author : Chase W. Nelson <chase.nelson@nih.gov>
Cite : https://github.com/chasewnelson/
Date : 2022-03-10
"""
import argparse
import os
import numpy as np
import pandas as pd
import sys
from typing import NamedTuple, TextIO
usage = """# -----------------------------------------------------------------------------
mean_of_tables.py - Compute the mean values across all numeric cells for multiple identically formatted tables
# -----------------------------------------------------------------------------
For DOCUMENTATION, run:
$ mean_of_tables.py --help
$ pydoc ./mean_of_tables.py
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
EXAMPLE:
$ mean_of_tables.py --help
# -----------------------------------------------------------------------------
"""
class Args(NamedTuple):
""" Command-line arguments """
in_files: TextIO
out_file: str
key: str
exclude: str
# -----------------------------------------------------------------------------
def get_args() -> Args:
""" Get command-line arguments """
parser = argparse.ArgumentParser(
description='Compute the mean values across all numeric cells for multiple identically formatted tables. '
'HELP: mean_of_tables.py --help',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Rename "optional" arguments
parser._optionals.title = 'Named arguments'
# -------------------------------------------------------------------------
# REQUIRED
parser.add_argument('-i',
'--in_files',
metavar='FILE',
help='Two or more identically formatted TSV (TAB-separated values) tables [REQUIRED]',
required=True,
nargs='+',
type=argparse.FileType('rt'))
parser.add_argument('-o',
'--out_file',
metavar='str',
help='Name of output file to contain table of mean values [REQUIRED]',
required=True,
type=str)
parser.add_argument('-k',
'--key',
metavar='str',
help='Name of column to use as the identifying KEY; auto-excluded from calculation [REQUIRED]',
required=True,
type=str)
# -------------------------------------------------------------------------
# OPTIONAL
parser.add_argument('-e',
'--exclude',
metavar='str',
help='Column names to exclude; '
'multiple should be comma-separated (e.g., "name,color"). '
'Failure to exclude non-numeric columns will result in an ERROR [REQUIRED]',
required=False,
nargs=1,
type=str)
args = parser.parse_args()
# -------------------------------------------------------------------------
# VALIDATE arguments
# At least TWO input files
if len(args.in_files) < 2:
parser.error(f'\n### ERROR: must provide at least 2 input files, with names separated by spaces')
# DIE if out_file already exists
if os.path.isfile(args.out_file):
parser.error(f'\n### ERROR: out_file="{args.out_file}" already exists')
# convert exclude to list with key
exclude_list = [args.key]
if args.exclude is not None:
exclude_list.append(args.exclude[0].split(','))
print(f'exclude_list={exclude_list}')
# verify
# 1) files readable as a pandas DataFrame
# 2) files have identical headers
# 3) files have identical shapes
# 4) all non-excluded columns are NUMERIC
header_list = None
file_shape = None
for fh in args.in_files:
try:
file_df = pd.read_table(fh, sep='\t')
# check for identical shape
if file_shape is None:
file_shape = file_df.shape
elif not file_shape == file_df.shape:
parser.error(f'\n### ERROR: files do not have identical numbers of rows and columns: {file_shape} vs. '
f'{file_df.shape}')
# check for identical header names
if header_list is None:
header_list = list(file_df.columns)
elif not header_list == list(file_df.columns):
parser.error(f'\n### ERROR: files do not use identical header names')
# check for non-numeric columns
for colname in header_list:
if colname not in exclude_list: # and colname != args.key:
if not pd.api.types.is_numeric_dtype(file_df[colname].dtypes):
parser.error(f'\n### ERROR: column is not numeric: file="{fh.name}", '
f'colname={colname}, dtype={file_df[colname].dtypes}')
except pd.errors.ParserError: # didn't conform to TAB-delimited format
parser.error(f'\n### ERROR: file="{fh.name}" cannot be read by pandas as a TAB-delimited table')
# # make sure headers are present
# if args.find[0] not in meta_df:
# parser.error(f'\n### ERROR: find="{args.find[0]}" not column in meta_file="{args.meta_file[0]}"')
#
# if bad_replace := [replacer for replacer in args.replace[0].split(',') if replacer not in meta_df]:
# parser.error(f'\n### ERROR: replace="{",".join(bad_replace)}" not column(s) in meta_file="{args.meta_file[0]}"')
#
# # TODO: delimiter only makes sense if --append or at least two values in --replace: WARNING?
#
# if re_NOT_header.search(args.replace[0]):
# parser.error(f'\n### ERROR: replace="{args.replace[0]}" contains invalid characters')
return Args(in_files=args.in_files,
out_file=args.out_file,
key=args.key,
exclude=args.exclude if args.exclude is None else args.exclude[0])
# -----------------------------------------------------------------------------
def main() -> None:
""" Tell them they are walking around shining like the sun """
# -------------------------------------------------------------------------
# GATHER arguments
args = get_args()
in_fhs = args.in_files
out_file = args.out_file
key = args.key
exclude = args.exclude
# -------------------------------------------------------------------------
# INITIALIZE OUTPUT AND LOG
print(usage)
print('# -----------------------------------------------------------------------------')
print(f'LOG:command="{" ".join(sys.argv)}"')
print(f'LOG:cwd="{os.getcwd()}"')
# arguments received
print(f'LOG:in_files="{",".join([fh.name for fh in in_fhs])}"')
print(f'LOG:in_files_count={len([fh.name for fh in in_fhs])}')
print(f'LOG:out_file="{out_file}"')
print(f'LOG:key="{key}"')
print(f'LOG:exclude={exclude}')
# convert exclude to list with key
exclude_list = [args.key]
if args.exclude is not None:
exclude_list.append(args.exclude.split(','))
print(f'exclude_list={exclude_list}')
# -------------------------------------------------------------------------
# LOOP FILES
nfiles = 0
# INITIALIZE dictionary
col_row_list_dict = dict() # colname -> rowname -> [list of values, 1 from each file]
# FILES
for fh in in_fhs:
nfiles += 1
filename = fh.name # because already opened once?
file_df = pd.read_table(filename, sep='\t')
# file_df = pd.read_table(fh, sep='\t')
if nfiles == 1:
col_names = list(file_df.columns)
# initialize keys
if nfiles == 1:
key_list = [str(item) for item in file_df[key]]
for key_name in key_list:
col_row_list_dict[key_name] = dict()
# COLUMNS
# ncols = 0
for colname in file_df.columns:
if colname not in exclude_list:
# column = file_df[colname]
# ncols += 1
# if nfiles == 1:
# col_row_list_dict[colname] = dict()
# ROWS
for i in range(len(file_df[colname])):
key_name = file_df[key][i]
# print(f'nfiles={nfiles} colname={colname} i={i} key={key_name} save: {file_df[colname][i]}') # ncols={ncols}
# print(f'key={key_name}')
if nfiles == 1:
# col_row_list_dict[key_name] = dict()
# print('here1')
# col_row_list_dict[colname] = dict()
col_row_list_dict[key_name][colname] = [file_df[colname][i]]
else:
# print('here2')
col_row_list_dict[key_name][colname].append(file_df[colname][i])
# LOG number of files process
print(f'LOG:files_processed={nfiles}')
# -------------------------------------------------------------------------
# COMPUTE and PRINT MEANS
# STORE column, row (key) names for a consistent order
row_names = []
for row_name in col_row_list_dict.keys():
row_names.append(row_name)
col_names = []
for col_name in col_row_list_dict[row_names[0]].keys(): # just use first row name
col_names.append(col_name)
# open out_file
out_fh = open(out_file, 'wt')
# form and write header
header_list = [key]
header_list.extend(col_names)
out_fh.write('\t'.join(header_list) + '\n')
# write values
for row_name in row_names: # col_row_list_dict.keys():
this_line = [row_name]
for col_name in col_names: # col_row_list_dict[row_name].keys():
this_col_list = col_row_list_dict[row_name][col_name]
this_line.append(np.mean(this_col_list))
# print(f'\nthis_list={this_col_list}\nthis_list_mean={np.mean(this_col_list)}\n')
# print('\t'.join([str(item) for item in this_line]))
out_fh.write('\t'.join([str(item) for item in this_line]) + '\n')
out_fh.close()
# -------------------------------------------------------------------------
# DONE message
print('\n# -----------------------------------------------------------------------------')
print('DONE')
# -----------------------------------------------------------------------------
# CALL MAIN
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
if __name__ == '__main__':
main()