forked from bigbio/proteomics-sample-metadata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.py
executable file
·196 lines (168 loc) · 6.39 KB
/
validate.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
#!/usr/bin/env python
import os
import glob
import sys
import argparse
import logging
import itertools
import re
from pandas_schema import ValidationWarning
from sdrf_pipelines.zooma import ols
from sdrf_pipelines.sdrf import sdrf, sdrf_schema
DIR = 'annotated-projects'
PROJECTS = os.listdir(DIR)
client = ols.OlsClient()
def retry(func):
def wrapper(*args, **kwargs):
for i in range(5):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper
@retry
def get_ancestors(iri):
return client.get_ancestors('ncbitaxon', iri)
def organism_name(s):
m = re.search(r'nt=([^;]*)', s)
if m:
name = m.group(1)
else:
name = s
return name
def get_template(df):
"""Extract organism information and pick a template for validation"""
templates = []
cell = 'characteristics[cell line]'
if cell in df:
is_cell_line = ~df[cell].isin({'not applicable', 'not available'})
if is_cell_line.any():
templates.append(sdrf_schema.CELL_LINES_TEMPLATE)
df = df.loc[~is_cell_line]
organisms = df['characteristics[organism]'].unique()
for org in organisms:
org = organism_name(org)
if org == 'homo sapiens':
templates.append(sdrf_schema.HUMAN_TEMPLATE)
else:
hit = client.besthit(org, ontology='ncbitaxon')
if hit is not None:
iri = hit['iri']
ancestors = get_ancestors(iri)
if ancestors is None:
print('Could not get ancestors for {}!'.format(org))
ancestors = []
labels = {a['label'] for a in ancestors}
if 'Gnathostomata <vertebrates>' in labels:
templates.append(sdrf_schema.VERTEBRATES_TEMPLATE)
elif 'Metazoa' in labels:
templates.append(sdrf_schema.NON_VERTEBRATES_TEMPLATE)
elif 'Viridiplantae' in labels:
templates.append(sdrf_schema.PLANTS_TEMPLATE)
return templates
def is_error(err):
if hasattr(err, '_error_type'):
return err._error_type == logging.ERROR
if not isinstance(err, ValidationWarning):
raise TypeError('Validation errors should be of type ValidationWarning, not {}'.format(type(err)))
return True
def is_warning(err):
if hasattr(err, '_error_type'):
return err._error_type == logging.WARN
if not isinstance(err, ValidationWarning):
raise TypeError('Validation errors should be of type ValidationWarning, not {}'.format(type(err)))
return False
def has_errors(errors):
return any(is_error(err) for err in errors)
def has_warnings(errors):
return any(is_warning(err) for err in errors)
def collapse_warnings(errors):
warnings = [err for err in errors if is_warning(err)]
messages = []
if warnings:
key = lambda w: (w.column, w.message)
for keyv, group in itertools.groupby(sorted(warnings, key=key), key=key):
col, message = keyv
gr = list(group)
w = min(gr, key=lambda w: w.row)
messages.append('{} validation warnings collapsed on column {} (first row {}, value {}): {}'.format(
len(gr), col, w.row, w.value, message))
return messages
def main(args):
statuses = []
messages = []
if args.project:
projects = args.project
else:
projects = PROJECTS
i = 0
try:
for project in projects:
sdrf_files = glob.glob(os.path.join(DIR, project, '*.sdrf.tsv'))
error_types = set()
error_files = set()
status = 0
errors = []
templates = []
if sdrf_files:
result = 'OK'
for sdrf_file in sdrf_files:
errors = []
df = sdrf.SdrfDataFrame.parse(sdrf_file)
err = df.validate(sdrf_schema.DEFAULT_TEMPLATE)
errors.extend(err)
if has_errors(err):
error_types.add('basic')
else:
templates = get_template(df)
if templates:
for t in templates:
err = df.validate(t)
errors.extend(err)
if has_errors(err):
error_types.add('{} template'.format(t))
err = df.validate(sdrf_schema.MASS_SPECTROMETRY)
errors.extend(err)
if has_errors(err):
error_types.add('mass spectrometry')
if has_errors(errors):
error_files.add(os.path.basename(sdrf_file))
if error_types:
result = 'Failed ' + ', '.join(error_types) + ' validation ({})'.format(', '.join(error_files))
status = 2
elif has_warnings(errors):
result = 'OK (with warnings)'
status = 1
if status < 2:
result = '[{} template]\t'.format(', '.join(templates) if templates else 'default') + result
else:
result = 'SDRF file not found'
statuses.append(status)
messages.append(result)
if args.verbose == 2:
for err in errors:
print(err)
elif args.verbose:
for w in collapse_warnings(errors):
print(w)
for err in errors:
if is_error(err):
print(err)
print(project, result, sep='\t')
i += 1
except KeyboardInterrupt:
pass
finally:
errors = sum(s == 2 for s in statuses)
warnings = sum(s == 1 for s in statuses)
print('Final results:')
print(f'Total: {i} of {len(projects)} projects checked, '
f'{errors} had validation errors, {warnings} had validation warnings.')
return errors
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='count', help='Print all errors. If specified twice, print all warnings.')
parser.add_argument('project', nargs='*')
args = parser.parse_args()
out = main(args)
sys.exit(out)