-
Notifications
You must be signed in to change notification settings - Fork 3
/
metfrag.py
597 lines (503 loc) · 23.3 KB
/
metfrag.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
from __future__ import absolute_import, print_function
try:
from configparser import ConfigParser
except ImportError as e:
print(e)
from ConfigParser import ConfigParser
import argparse
import csv
import glob
import multiprocessing
import os
import re
import shutil
import sys
import tempfile
from collections import defaultdict
import six
# function to extract the meta data using the regular expressions
def parse_meta(meta_regex, meta_info=None):
if meta_info is None:
meta_info = {}
for k, regexes in six.iteritems(meta_regex):
for reg in regexes:
m = re.search(reg, line, re.IGNORECASE)
if m:
meta_info[k] = '-'.join(m.groups()).strip()
return meta_info
def get_meta_regex(schema):
######################################################################
# Setup regular expressions for MSP parsing dictionary
######################################################################
regex_msp = {}
regex_msp['name'] = [r'^Name(?:=|:)(.*)$']
regex_msp['polarity'] = [r'^ion.*mode(?:=|:)(.*)$',
r'^ionization.*mode(?:=|:)(.*)$',
r'^polarity(?:=|:)(.*)$']
regex_msp['precursor_mz'] = [r'^precursor.*m/z(?:=|:)\s*(\d*[.,]?\d*)$',
r'^precursor.*mz(?:=|:)\s*(\d*[.,]?\d*)$']
regex_msp['precursor_type'] = [r'^precursor.*type(?:=|:)(.*)$',
r'^adduct(?:=|:)(.*)$',
r'^ADDUCTIONNAME(?:=|:)(.*)$']
regex_msp['retention_time'] = [r'^RETENTION.*TIME(?:=|:)\s*(.*)$',
r'^rt(?:=|:)\s*(.*)$',
r'^time(?:=|:)\s*(.*)$']
# From example winter_pos.mspy from kristian
regex_msp['AlignmentID'] = [r'^AlignmentID(?:=|:)\s*(.*)$']
regex_msp['num_peaks'] = [r'^Num.*Peaks(?:=|:)\s*(\d*)$']
regex_msp['msp'] = [r'^Name(?:=|:)(.*)$'] # Flag for standard MSP format
regex_massbank = {}
regex_massbank['name'] = [r'^RECORD_TITLE:(.*)$']
regex_massbank['polarity'] = [
r'^AC\$MASS_SPECTROMETRY:\s+ION_MODE\s+(.*)$']
regex_massbank['precursor_mz'] = [
r'^MS\$FOCUSED_ION:\s+PRECURSOR_M/Z\s+(\d*[.,]?\d*)$']
regex_massbank['precursor_type'] = [
r'^MS\$FOCUSED_ION:\s+PRECURSOR_TYPE\s+(.*)$']
regex_massbank['retention_time'] = [
r'^AC\$CHROMATOGRAPHY:\s+RETENTION_TIME\s*(\d*\.?\d+).*']
regex_massbank['num_peaks'] = [r'^PK\$NUM_PEAK:\s+(\d*)']
regex_massbank['cols'] = [r'^PK\$PEAK:\s+(.*)']
regex_massbank['massbank'] = [
r'^RECORD_TITLE:(.*)$'] # Flag for massbank format
if schema == 'msp':
meta_regex = regex_msp
elif schema == 'massbank':
meta_regex = regex_massbank
elif schema == 'auto':
# If auto we just check for all the available paramter names and then
# determine if Massbank or MSP based on the name parameter
meta_regex = {}
meta_regex.update(regex_massbank)
meta_regex['name'].extend(regex_msp['name'])
meta_regex['polarity'].extend(regex_msp['polarity'])
meta_regex['precursor_mz'].extend(regex_msp['precursor_mz'])
meta_regex['precursor_type'].extend(regex_msp['precursor_type'])
meta_regex['num_peaks'].extend(regex_msp['num_peaks'])
meta_regex['retention_time'].extend(regex_msp['retention_time'])
meta_regex['AlignmentID'] = regex_msp['AlignmentID']
meta_regex['msp'] = regex_msp['msp']
else:
sys.exit("No schema selected")
return meta_regex
######################################################################
# Setup parameter dictionary
######################################################################
def init_paramd(args):
paramd = defaultdict()
paramd["MetFragDatabaseType"] = args.MetFragDatabaseType
if args.MetFragDatabaseType == "LocalCSV":
paramd["LocalDatabasePath"] = args.LocalDatabasePath
elif args.MetFragDatabaseType == "MetChem":
paramd["LocalMetChemDatabase"] = \
config.get('MetChem', 'LocalMetChemDatabase')
paramd["LocalMetChemDatabasePortNumber"] = \
config.get('MetChem', 'LocalMetChemDatabasePortNumber')
paramd["LocalMetChemDatabaseServerIp"] = \
args.LocalMetChemDatabaseServerIp
paramd["LocalMetChemDatabaseUser"] = \
config.get('MetChem', 'LocalMetChemDatabaseUser')
paramd["LocalMetChemDatabasePassword"] = \
config.get('MetChem', 'LocalMetChemDatabasePassword')
paramd["FragmentPeakMatchAbsoluteMassDeviation"] = \
args.FragmentPeakMatchAbsoluteMassDeviation
paramd["FragmentPeakMatchRelativeMassDeviation"] = \
args.FragmentPeakMatchRelativeMassDeviation
paramd["DatabaseSearchRelativeMassDeviation"] = \
args.DatabaseSearchRelativeMassDeviation
paramd["SampleName"] = ''
paramd["ResultsPath"] = os.path.join(wd)
if args.polarity == "pos":
paramd["IsPositiveIonMode"] = True
paramd["PrecursorIonModeDefault"] = "1"
paramd["PrecursorIonMode"] = "1"
paramd["nm_mass_diff_default"] = 1.007276
else:
paramd["IsPositiveIonMode"] = False
paramd["PrecursorIonModeDefault"] = "-1"
paramd["PrecursorIonMode"] = "-1"
paramd["nm_mass_diff_default"] = -1.007276
paramd["MetFragCandidateWriter"] = "CSV"
paramd["NumberThreads"] = args.NumberThreads
if args.ScoreSuspectLists:
paramd["ScoreSuspectLists"] = args.ScoreSuspectLists
paramd["MetFragScoreTypes"] = args.MetFragScoreTypes
paramd["MetFragScoreWeights"] = args.MetFragScoreWeights
dct_filter = defaultdict()
filterh = []
if args.UnconnectedCompoundFilter:
filterh.append('UnconnectedCompoundFilter')
if args.IsotopeFilter:
filterh.append('IsotopeFilter')
if args.FilterMinimumElements:
filterh.append('MinimumElementsFilter')
dct_filter['FilterMinimumElements'] = args.FilterMinimumElements
if args.FilterMaximumElements:
filterh.append('MaximumElementsFilter')
dct_filter['FilterMaximumElements'] = args.FilterMaximumElements
if args.FilterSmartsInclusionList:
filterh.append('SmartsSubstructureInclusionFilter')
dct_filter[
'FilterSmartsInclusionList'] = args.FilterSmartsInclusionList
if args.FilterSmartsExclusionList:
filterh.append('SmartsSubstructureExclusionFilter')
dct_filter[
'FilterSmartsExclusionList'] = args.FilterSmartsExclusionList
# My understanding is that both 'ElementInclusionExclusiveFilter'
# and 'ElementExclusionFilter' use 'FilterIncludedElements'
if args.FilterIncludedExclusiveElements:
filterh.append('ElementInclusionExclusiveFilter')
dct_filter[
'FilterIncludedElements'] = args.FilterIncludedExclusiveElements
if args.FilterIncludedElements:
filterh.append('ElementInclusionFilter')
dct_filter['FilterIncludedElements'] = args.FilterIncludedElements
if args.FilterExcludedElements:
filterh.append('ElementExclusionFilter')
dct_filter['FilterExcludedElements'] = args.FilterExcludedElements
if filterh:
fcmds = ','.join(filterh) + ' '
for k, v in six.iteritems(dct_filter):
fcmds += "{0}={1} ".format(str(k), str(v))
paramd["MetFragPreProcessingCandidateFilter"] = fcmds
return paramd
######################################################################
# Function to run metfrag when all metainfo and peaks have been parsed
######################################################################
def run_metfrag(meta_info, peaklist, args, wd, spectrac, adduct_types):
# Get sample details (if possible to extract) e.g. if created as part of
# the msPurity pipeline) choose between getting additional details to add
# as columns as either all meta data from msp, just details from the
# record name (i.e. when using msPurity and we have the columns coded into
# the name) or just the spectra index (spectrac)].
# Returns the parameters used and the command line call
meta_info = {k: v for k, v in meta_info.items() if k
not in ['msp', 'massbank', 'cols']}
paramd = init_paramd(args)
if args.meta_select_col == 'name':
# have additional column of just the name
paramd['additional_details'] = {'name': meta_info['name']}
elif args.meta_select_col == 'name_split':
# have additional columns split by "|" and
# then on ":" e.g. MZ:100.2 | RT:20 | xcms_grp_id:1
paramd['additional_details'] = {
sm.split(":")[0].strip(): sm.split(":")[1].strip() for sm in
meta_info['name'].split("|")}
elif args.meta_select_col == 'all':
# have additional columns based on all the meta information
# extracted from the MSP
paramd['additional_details'] = meta_info
else:
# Just have an index of the spectra in the MSP file
paramd['additional_details'] = {'spectra_idx': spectrac}
paramd["SampleName"] = "{}_metfrag_result".format(spectrac)
# =============== Output peaks to txt file ==============================
paramd["PeakListPath"] = os.path.join(wd,
"{}_tmpspec.txt".format(spectrac))
# write spec file
with open(paramd["PeakListPath"], 'w') as outfile:
pls = ''
for p in peaklist:
outfile.write(p[0] + "\t" + p[1] + "\n")
pls = pls + '{}_{};'.format(p[0], p[1])
if args.output_cl:
peaklist_str = pls[:-1]
# =============== Update param based on MSP metadata ======================
# Replace param details with details from MSP if required
if 'precursor_type' in meta_info and \
meta_info['precursor_type'] in adduct_types:
adduct = meta_info['precursor_type']
nm = float(meta_info['precursor_mz']) - adduct_types[
meta_info['precursor_type']]
paramd["PrecursorIonMode"] = \
int(round(adduct_types[meta_info['precursor_type']], 0))
elif not args.skip_invalid_adducts:
inv_adduct_types = {int(round(v, 0)): k for k, v in
six.iteritems(adduct_types)}
adduct = inv_adduct_types[int(paramd['PrecursorIonModeDefault'])]
paramd["PrecursorIonMode"] = paramd['PrecursorIonModeDefault']
nm = float(meta_info['precursor_mz']) - paramd['nm_mass_diff_default']
else:
print('Skipping {}'.format(paramd["SampleName"]))
return '', ''
if not ('precursor_type' in paramd['additional_details'] or 'adduct'
in paramd['additional_details']):
paramd['additional_details']['adduct'] = adduct
paramd["NeutralPrecursorMass"] = nm
# ============== Create CLI cmd for metfrag ===============================
cmd = "metfrag"
for k, v in six.iteritems(paramd):
if k not in ['PrecursorIonModeDefault', 'nm_mass_diff_default',
'additional_details']:
cmd += " {}={}".format(str(k), str(v))
if args.output_cl:
cli_str = '{} PeakListString={}'.format(cmd, peaklist_str)
paramd['additional_details']['MetFragCLIString'] = cli_str
# ============== Run metfrag ==============================================
# print(cmd)
# Filter before process with a minimum number of MS/MS peaks
if plinesread >= float(args.minMSMSpeaks):
if int(args.cores_top_level) == 1:
os.system(cmd)
return paramd, cmd
def work(cmds):
return [os.system(cmd) for cmd in cmds]
if __name__ == "__main__":
print(sys.version)
parser = argparse.ArgumentParser()
parser.add_argument('--input_pth')
parser.add_argument('--result_pth', default='metfrag_result.csv')
parser.add_argument('--temp_dir')
parser.add_argument('--polarity', default='pos')
parser.add_argument('--minMSMSpeaks', default=1)
parser.add_argument('--MetFragDatabaseType', default='PubChem')
parser.add_argument('--LocalDatabasePath', default='')
parser.add_argument('--LocalMetChemDatabaseServerIp', default='')
parser.add_argument('--DatabaseSearchRelativeMassDeviation', default=5)
parser.add_argument('--FragmentPeakMatchRelativeMassDeviation', default=10)
parser.add_argument('--FragmentPeakMatchAbsoluteMassDeviation',
default=0.001)
parser.add_argument('--NumberThreads', default=1)
parser.add_argument('--UnconnectedCompoundFilter', action='store_true')
parser.add_argument('--IsotopeFilter', action='store_true')
parser.add_argument('--FilterMinimumElements', default='')
parser.add_argument('--FilterMaximumElements', default='')
parser.add_argument('--FilterSmartsInclusionList', default='')
parser.add_argument('--FilterSmartsExclusionList', default='')
parser.add_argument('--FilterIncludedElements', default='')
parser.add_argument('--FilterExcludedElements', default='')
parser.add_argument('--FilterIncludedExclusiveElements', default='')
parser.add_argument('--score_thrshld', default=0)
parser.add_argument('--pctexplpeak_thrshld', default=0)
parser.add_argument('--schema')
parser.add_argument('--cores_top_level', default=1)
parser.add_argument('--chunks', default=1)
parser.add_argument('--meta_select_col', default='name')
parser.add_argument('--skip_invalid_adducts', action='store_true')
parser.add_argument('--output_cl', action='store_true')
parser.add_argument('--ScoreSuspectLists', default='')
parser.add_argument('--MetFragScoreTypes',
default="FragmenterScore,OfflineMetFusionScore")
parser.add_argument('--MetFragScoreWeights', default="1.0,1.0")
parser.add_argument('-a', '--adducts', action='append', nargs=1,
required=False, default=[], help='Adducts used')
args = parser.parse_args()
print(args)
config = ConfigParser()
config.read(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini'))
if os.stat(args.input_pth).st_size == 0:
print('Input file empty')
exit()
# Create temporary working directory
if args.temp_dir:
wd = args.temp_dir
else:
wd = tempfile.mkdtemp()
if os.path.exists(wd):
shutil.rmtree(wd)
os.makedirs(wd)
else:
os.makedirs(wd)
meta_regex = get_meta_regex(args.schema)
adduct_types = {
'[M+H]+': 1.007276,
'[M+NH4]+': 18.034374,
'[M+Na]+': 22.989218,
'[M+K]+': 38.963158,
'[M+CH3OH+H]+': 33.033489,
'[M+ACN+H]+': 42.033823,
'[M+ACN+Na]+': 64.015765,
'[M+2ACN+H]+': 83.06037,
'[M-H]-': -1.007276,
'[M+Cl]-': 34.969402,
'[M+HCOO]-': 44.99819,
'[M-H+HCOOH]-': 44.99819,
# same as above but different style of writing adduct
'[M+CH3COO]-': 59.01385,
'[M-H+CH3COOH]-': 59.01385
# same as above but different style of writing adduct
}
######################################################################
# Parse MSP file and run metfrag CLI
######################################################################
# keep list of commands if performing in CLI in parallel
cmds = []
# keep a dictionary of all params
paramds = {}
# keep count of spectra (for uid)
spectrac = 0
# this dictionary will store the meta data results form the MSp file
meta_info = {}
if args.adducts:
adducts_from_cli = [
a[0].replace('__ob__', '[').replace('__cb__', ']') for a in
args.adducts
]
else:
adducts_from_cli = []
with open(args.input_pth, "r") as infile:
# number of lines for the peaks
pnumlines = 0
# number of lines read for the peaks
plinesread = 0
for line in infile:
line = line.strip()
if pnumlines == 0:
# ============== Extract metadata from MSP ====================
meta_info = parse_meta(meta_regex, meta_info)
if ('massbank' in meta_info and 'cols' in meta_info) or (
'msp' in meta_info and 'num_peaks' in meta_info):
pnumlines = int(meta_info['num_peaks'])
plinesread = 0
peaklist = []
elif plinesread < pnumlines:
# ============== Extract peaks from MSP =======================
# .split() will split on any empty space (i.e. tab and space)
line = tuple(line.split())
# Keep only m/z and intensity, not relative intensity
save_line = tuple(line[0].split() + line[1].split())
plinesread += 1
peaklist.append(save_line)
elif plinesread and plinesread == pnumlines:
# =Get sample name and additional details for output and RUN ==
if adducts_from_cli:
for adduct in adducts_from_cli:
spectrac += 1
meta_info['precursor_type'] = adduct
paramd, cmd = run_metfrag(meta_info, peaklist, args,
wd, spectrac, adduct_types)
if paramd:
paramds[paramd["SampleName"]] = paramd
cmds.append(cmd)
else:
spectrac += 1
paramd, cmd = run_metfrag(meta_info, peaklist, args,
wd, spectrac, adduct_types)
if paramd:
paramds[paramd["SampleName"]] = paramd
cmds.append(cmd)
meta_info = {}
pnumlines = 0
plinesread = 0
# end of file. Check if there is a MSP spectra to run metfrag on
if plinesread and plinesread == pnumlines:
if adducts_from_cli:
for adduct in adducts_from_cli:
spectrac += 1
meta_info['precursor_type'] = adduct
paramd, cmd = run_metfrag(meta_info, peaklist, args,
wd, spectrac, adduct_types)
if paramd:
paramds[paramd["SampleName"]] = paramd
cmds.append(cmd)
else:
spectrac += 1
paramd, cmd = run_metfrag(meta_info, peaklist, args,
wd, spectrac, adduct_types)
if paramd:
paramds[paramd["SampleName"]] = paramd
cmds.append(cmd)
# Perform multiprocessing on command line call level
if int(args.cores_top_level) > 1:
cmds_chunks = [cmds[x:x + int(args.chunks)] for x in
list(range(0, len(cmds), int(args.chunks)))]
pool = multiprocessing.Pool(processes=int(args.cores_top_level))
pool.map(work, cmds_chunks)
pool.close()
pool.join()
######################################################################
# Concatenate and filter the output
######################################################################
# outputs might have different headers. Need to get a list of all the
# headers before we start merging the files
# outfiles = [os.path.join(wd, f) for f in glob.glob(os.path.join(wd,
# "*_metfrag_result.csv"))]
outfiles = glob.glob(os.path.join(wd, "*_metfrag_result.csv"))
if len(outfiles) == 0:
print('No results')
sys.exit()
headers = []
c = 0
for fn in outfiles:
with open(fn, 'r') as infile:
reader = csv.reader(infile)
if sys.version_info >= (3, 0):
headers.extend(next(reader))
else:
headers.extend(reader.next())
# check if file has any data rows
for i, row in enumerate(reader):
c += 1
if i == 1:
break
# if no data rows (e.g. matches) then do not save an
# output and leave the program
if c == 0:
print('No results')
sys.exit()
additional_detail_headers = ['sample_name']
for k, paramd in six.iteritems(paramds):
additional_detail_headers = list(set(
additional_detail_headers + list(
paramd['additional_details'].keys())))
# add inchikey if not already present (missing in metchem output)
if 'InChIKey' not in headers:
headers.append('InChIKey')
additional_detail_headers = sorted(additional_detail_headers)
headers = additional_detail_headers + sorted(list(set(headers)))
# Sort files nicely
outfiles.sort(
key=lambda s: int(
re.match(r'^.*/(\d+)_metfrag_result.csv', s).group(1)))
print(outfiles)
# merge outputs
with open(args.result_pth, 'a') as merged_outfile:
dwriter = csv.DictWriter(merged_outfile, fieldnames=headers,
delimiter='\t', quotechar='"')
dwriter.writeheader()
for fn in outfiles:
with open(fn) as infile:
reader = csv.DictReader(infile, delimiter=',', quotechar='"')
for line in reader:
bewrite = True
for key, value in line.items():
# Filter when no MS/MS peak matched
if key == "ExplPeaks":
if float(args.pctexplpeak_thrshld) > 0 \
and value and "NA" in value:
bewrite = False
# Filter with a score threshold
elif key == "Score":
if value and float(value) <= float(
args.score_thrshld):
bewrite = False
elif key == "NoExplPeaks":
nbfindpeak = float(value)
elif key == "NumberPeaksUsed":
totpeaks = float(value)
# Filter with a relative number of peak matched
try:
pctexplpeak = nbfindpeak / totpeaks * 100
except ZeroDivisionError:
bewrite = False
else:
if pctexplpeak < float(args.pctexplpeak_thrshld):
bewrite = False
# Write the line if it pass all filters
if bewrite:
bfn = os.path.basename(fn)
bfn = bfn.replace(".csv", "")
line['sample_name'] = paramds[bfn]['SampleName']
ad = paramds[bfn]['additional_details']
if args.MetFragDatabaseType == "MetChem":
# for some reason the metchem database option does
# not report the full inchikey (at least in the
# Bham setup. This ensures we always get
# the fully inchikey
line['InChIKey'] = '{}-{}-{}'.format(
line['InChIKey1'],
line['InChIKey2'],
line['InChIKey3'])
line.update(ad)
dwriter.writerow(line)