Debian Codegraph @

airr/tools.py

raw
1 """
2 AIRR tools and utilities
3 """
4 # Copyright (c) 2018 AIRR Community
5 #
6 # This file is part of the AIRR Community Standards.
7 #
8 # Author: Scott Christley <[email protected]>
9 # Author: Jason Anthony Vander Heiden
10 # Date: March 29, 2018
11 #
12 # This library is free software; you can redistribute it and/or modify
13 # it under the terms of the Creative Commons Attribution 4.0 License.
14 #
15 # This library is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # Creative Commons Attribution 4.0 License for more details.
19
20 # System imports
21 import argparse
22 import sys
23 from warnings import warn
24
25 # Local imports
26 from airr import __version__
27 import airr.interface
28
29 # internal wrapper function before calling merge interface method
30 def merge_cmd(out_file, airr_files, drop=False, debug=False):
31 """
32 Merge one or more AIRR rearrangements files
33
34 Arguments:
35 out_file (str): output file name.
36 airr_files (list): list of input files to merge.
37 drop (bool): drop flag. If True then drop fields that do not exist in all input
38 files, otherwise combine fields from all input files.
39 debug (bool): debug flag. If True print debugging information to standard error.
40
41 Returns:
42 bool: True if files were successfully merged, otherwise False.
43 """
44 return airr.interface.merge_rearrangement(out_file, airr_files, drop=drop, debug=debug)
45
46 # internal wrapper function before calling validate interface method
47 def validate_rearrangement_cmd(airr_files, debug=True):
48 """
49 Validates one or more AIRR rearrangements files
50
51 Arguments:
52 airr_files (list): list of input files to validate.
53 debug (bool): debug flag. If True print debugging information to standard error.
54
55 Returns:
56 boolean: True if all files passed validation, otherwise False
57 """
58 valid = []
59 for f in airr_files:
60 try:
61 v = airr.interface.validate_rearrangement(f, debug=debug)
62 valid.append(v)
63 except Exception as e:
64 sys.stderr.write('%s\n' % e)
65 sys.stderr.write('Validation failed for file: %s\n\n' % f)
66 valid.append(False)
67 else:
68 if not v: sys.stderr.write('Validation failed for file: %s\n\n' % f)
69
70 return all(valid)
71
72 def validate_airr_cmd(airr_files, debug=True):
73 """
74 Validates one or more AIRR Data Model files
75
76 Arguments:
77 airr_files (list): list of input files to validate.
78 debug (bool): debug flag. If True print debugging information to standard error.
79
80 Returns:
81 boolean: True if all files passed validation, otherwise False
82 """
83 valid = []
84 for f in airr_files:
85 if debug: sys.stderr.write('Validating: %s\n' % f)
86 try:
87 data = airr.interface.read_airr(f, validate=False, debug=debug)
88 v = airr.interface.validate_airr(data, debug=debug)
89 valid.append(v)
90 except Exception as e:
91 sys.stderr.write('%s\n' % e)
92 sys.stderr.write('Validation failed for file: %s\n\n' % f)
93 valid.append(False)
94
95 return all(valid)
96
97 #### Deprecated ####
98
99 # internal wrapper function before calling validate interface method
100 def validate_repertoire_cmd(airr_files, debug=True):
101 """
102 Validates one or more AIRR repertoire metadata files
103
104 Arguments:
105 airr_files (list): list of input files to validate.
106 debug (bool): debug flag. If True print debugging information to standard error.
107
108 Returns:
109 boolean: True if all files passed validation, otherwise False
110 """
111 # Deprecation
112 warn('validate_repertoire_cmd is deprecated and will be removed in a future release.\nUse =validate_airr_cmd instead.\n',
113 DeprecationWarning, stacklevel=2)
114
115 valid = []
116 for f in airr_files:
117 try:
118 v = airr.interface.validate_repertoire(f, debug=debug)
119 valid.append(v)
120 except Exception as e:
121 sys.stderr.write('%s\n' % e)
122 sys.stderr.write('Validation failed for file: %s\n\n' % f)
123 valid.append(False)
124
125 return all(valid)
126
127 def define_args():
128 """
129 Define commandline arguments
130
131 Returns:
132 argparse.ArgumentParser: argument parser.
133 """
134 parser = argparse.ArgumentParser(add_help=False,
135 description='AIRR Community Standards utility commands.')
136 group_help = parser.add_argument_group('help')
137 group_help.add_argument('-h', '--help', action='help', help='show this help message and exit')
138 group_help.add_argument('--version', action='version',
139 version='%(prog)s:' + ' %s' % __version__)
140
141 # Setup subparsers
142 subparsers = parser.add_subparsers(title='subcommands', dest='command', metavar='',
143 help='Database operation')
144 # TODO: This is a temporary fix for Python issue 9253
145 subparsers.required = True
146
147 # Define arguments common to all subcommands
148 common_parser = argparse.ArgumentParser(add_help=False)
149 common_help = common_parser.add_argument_group('help')
150 common_help.add_argument('--version', action='version',
151 version='%(prog)s:' + ' %s' % __version__)
152 common_help.add_argument('-h', '--help', action='help', help='show this help message and exit')
153
154 # TODO: workflow provenance
155 # group_prov = common_parser.add_argument_group('provenance')
156 # group_prov.add_argument('-p', '--provenance', action='store', dest='prov_file', default=None,
157 # help='''File name for storing workflow provenance. If specified, airr-tools
158 # will record provenance for all activities performed.''')
159
160 # TODO: study metadata
161 # group_meta = common_parser.add_argument_group('study metadata')
162 # group_meta.add_argument('-m', '--metadata', action='store', dest='metadata_file', default=None,
163 # help='''File name containing study metadata.''')
164
165 # Subparser to merge files
166 parser_merge = subparsers.add_parser('merge', parents=[common_parser],
167 add_help=False,
168 help='Merge AIRR rearrangement files.',
169 description='Merge AIRR rearrangement files.')
170 group_merge = parser_merge.add_argument_group('merge arguments')
171 group_merge.add_argument('-o', action='store', dest='out_file', required=True,
172 help='''Output file name.''')
173 group_merge.add_argument('--drop', action='store_true', dest='drop',
174 help='''If specified, drop fields that do not exist in all input files.
175 Otherwise, include all columns in all files and fill missing data
176 with empty strings.''')
177 group_merge.add_argument('-a', nargs='+', action='store', dest='airr_files', required=True,
178 help='A list of AIRR rearrangement files.')
179 parser_merge.set_defaults(func=merge_cmd)
180
181 # Subparser to validate files
182 parser_validate = subparsers.add_parser('validate', parents=[common_parser],
183 add_help=False,
184 help='Validate files for AIRR Standards compliance.',
185 description='Validate files for AIRR Standards compliance.')
186 validate_subparser = parser_validate.add_subparsers(title='subcommands', metavar='',
187 help='Database operation')
188
189 # Subparser to validate rearrangement files
190 parser_validate = validate_subparser.add_parser('rearrangement', parents=[common_parser],
191 add_help=False,
192 help='Validate AIRR rearrangement files.',
193 description='Validate AIRR rearrangement files.')
194 group_validate = parser_validate.add_argument_group('validate arguments')
195 group_validate.add_argument('-a', nargs='+', action='store', dest='airr_files', required=True,
196 help='A list of AIRR rearrangement files.')
197 parser_validate.set_defaults(func=validate_rearrangement_cmd)
198
199 # Subparser to validate AIRR Data Model files
200 parser_validate = validate_subparser.add_parser('airr', parents=[common_parser],
201 add_help=False,
202 help='Validate AIRR Data Model files.',
203 description='Validate AIRR Data Model files.')
204 group_validate = parser_validate.add_argument_group('validate arguments')
205 group_validate.add_argument('-a', nargs='+', action='store', dest='airr_files', required=True,
206 help='A list of AIRR Data Model files.')
207 parser_validate.set_defaults(func=validate_airr_cmd)
208
209 # Subparser to validate repertoire files
210 parser_validate = validate_subparser.add_parser('repertoire', parents=[common_parser],
211 add_help=False,
212 help='Validate AIRR repertoire metadata files.',
213 description='Validate AIRR repertoire metadata files.')
214 group_validate = parser_validate.add_argument_group('validate arguments')
215 group_validate.add_argument('-a', nargs='+', action='store', dest='airr_files', required=True,
216 help='A list of AIRR repertoire metadata files.')
217 parser_validate.set_defaults(func=validate_repertoire_cmd)
218
219 return parser
220
221
222 def main():
223 """
224 Utility commands for AIRR Community Standards files
225 """
226 # Define argument parsers and print help if subcommand not specified
227 parser = define_args()
228 if len(sys.argv) == 1:
229 parser.print_help()
230 sys.exit(1)
231
232 # Parse arguments
233 args = parser.parse_args()
234 args_dict = args.__dict__.copy()
235 del args_dict['command']
236 del args_dict['func']
237
238 # Deprecation warnings
239 if args.func is validate_repertoire_cmd:
240 print('The "validate repertoire" subcommand is deprecated and will be removed in a future release.',
241 '\nUse the "validate airr" subcommand instead.\n')
242
243 # Call tool function
244 result = args.func(**args_dict)
245
246 # set return code to non-zero if error occurred
247 if args.__dict__['command'] == 'validate' or args.__dict__['command'] == 'merge':
248 if not result:
249 sys.exit(1)