66import warnings
77import pandas as pd
88import gc
9+ import pickle
910
1011from corems .mass_spectra .output .export import LCMSMetabolomicsExport
1112
@@ -109,7 +110,7 @@ def determine_polarity(file_path):
109110 lcms_obj = instantiate_lcms_obj (file_path , spectra = "none" )
110111 return lcms_obj .polarity if lcms_obj .polarity else "unknown"
111112
112- def export_results (myLCMSobj , out_path , molecular_metadata = None , final = False ):
113+ def export_results (myLCMSobj , out_path , molecular_metadata , final = False ):
113114 """Export results to hdf5 and csv
114115
115116 Parameters
@@ -158,6 +159,7 @@ def run_lcmetab_ms1(file_in, params_toml, scan_translator):
158159 Dict with keys "positive" and "negative" and values of lists of precursor mzs
159160 """
160161
162+ click .echo (f"...instantiating LCMS object for { file_in } " )
161163 myLCMSobj = instantiate_lcms_obj (file_in )
162164 set_params_on_lcms_obj (myLCMSobj , params_toml )
163165
@@ -193,15 +195,14 @@ def prepare_metadata(msp_file_path, generate_lr_metadata=True, polarity=None):
193195 ----------
194196 msp_file_path : str
195197 Path to sqlite database
196-
197- Returns
198- -------
199- metadata : dict
200- Dict with keys "mzs", "fe", and "molecular_metadata" with values of dicts of precursor mzs (negative and positive), flash entropy search databases (negative and positive), and molecular metadata, respectively
201198 generate_lr_metadata : bool, optional
202199 Whether to generate low resolution metadata, default is True
203200 polarity : str, optional
204201 Polarity to prepare metadata for, can be "positive", "negative", or None (which will prepare for both polarities)
202+
203+ Returns
204+ -------
205+ None, but saves the metadata to a file named "metadata.pkl" in the current directory
205206
206207 Notes
207208 -------
@@ -301,7 +302,11 @@ def prepare_metadata(msp_file_path, generate_lr_metadata=True, polarity=None):
301302 )
302303 metadata ["fe_lr" ]["negative" ] = msp_negative
303304
304- return metadata
305+ # Save this as a pkl in the output directory
306+ output_path = Path ("metadata.pkl" )
307+ output_path .parent .mkdir (parents = True , exist_ok = True )
308+ with open (output_path , "wb" ) as f :
309+ pickle .dump (metadata , f )
305310
306311def process_ms2 (myLCMSobj , metadata , scan_translator ):
307312 """Process ms2 spectra and perform molecular search
@@ -315,8 +320,19 @@ def process_ms2(myLCMSobj, metadata, scan_translator):
315320
316321 Returns
317322 -------
318- None, processes the LCMS object
323+ molecular_metadata : dict
324+ Dict with keys "positive" and "negative" containing the molecular metadata for each polarity
319325 """
326+ click .echo ("...processing ms2 spectra" )
327+
328+ if metadata is None :
329+ # import pickled version (me)
330+ metadata_path = Path ("metadata.pkl" )
331+ if not metadata_path .exists ():
332+ raise FileNotFoundError ("Metadata file not found, please prepare metadata first" )
333+ with open (metadata_path , "rb" ) as f :
334+ metadata = pickle .load (f )
335+
320336 # Perform molecular search on ms2 spectra
321337 # Grab fe from metatdata associated with polarity (this is inherently high resolution as its from a in-silico high res library)
322338 fe_search = metadata ["fe" ][myLCMSobj .polarity ]
@@ -364,24 +380,12 @@ def process_ms2(myLCMSobj, metadata, scan_translator):
364380 ms2_scans_oi_lr .extend (ms2_scans_oi_lri )
365381 # Perform search on low res scans
366382 if len (ms2_scans_oi_lr ) > 0 :
367- # Recast the flashentropy search database to low resolution
368- # fe_search_lr = _to_flashentropy(
369- # metabref_lib=fe_search,
370- # normalize=True,
371- # fe_kwargs={
372- # "normalize_intensity": True,
373- # "min_ms2_difference_in_da": 0.4,
374- # "max_ms2_tolerance_in_da": 0.2,
375- # "max_indexed_mz": 3000,
376- # "precursor_ions_removal_da": None,
377- # "noise_threshold": 0,
378- # },
379- # )
380-
381383 fe_search_lr = metadata ["fe_lr" ][myLCMSobj .polarity ]
382384 myLCMSobj .fe_search (
383385 scan_list = ms2_scans_oi_lr , fe_lib = fe_search_lr , peak_sep_da = 0.3
384386 )
387+
388+ return metadata ["molecular_metadata" ]
385389
386390def process_complete_workflow (args ):
387391 """Process a single file through the complete workflow"""
@@ -397,9 +401,9 @@ def process_complete_workflow(args):
397401 )
398402
399403 # MS2 processing and export
400- process_ms2 (lcms_obj , metadata , scan_translator )
401- export_results (lcms_obj , str (output_path ), metadata [ "molecular_metadata" ] , final = True )
402-
404+ mol_metadata = process_ms2 (lcms_obj , metadata , scan_translator )
405+ export_results (lcms_obj , str (output_path ), mol_metadata , final = True )
406+
403407 return f"Completed: { output_path } "
404408 except Exception as e :
405409 click .echo (f"Error processing { file_in } : { str (e )} " )
@@ -497,24 +501,23 @@ def run_lcms_metabolomics_workflow(
497501 # Prepare metadata for searching
498502 # Check the scan translator, if there are only high resolution scans, then do not make low resolution metadata
499503 click .echo ("Preparing metadata for ms2 spectral search for positive samples" )
500- metadata = prepare_metadata (lcmetab_workflow_params .msp_file_path , generate_lr_metadata = generate_lr_metadata , polarity = "positive" )
504+ prepare_metadata (lcmetab_workflow_params .msp_file_path , generate_lr_metadata = generate_lr_metadata , polarity = "positive" )
501505 click .echo ("Metadata preparation complete for positive samples" )
502506
503507 # Run signal processing, get associated ms1, add associated ms2, do ms1 molecular search, and export intermediate results
504508 # for positive polarity samples
505509 if cores == 1 or len (files_list_positive ) == 1 :
506510 for file_in , output_path in zip (files_list_positive , out_paths_list_positive ):
507- args = (file_in , output_path , params_toml , scan_translator , metadata )
511+ args = (file_in , output_path , params_toml , scan_translator , None )
508512 process_complete_workflow (args )
509513
510514 elif cores > 1 :
511515 with Pool (cores ) as pool :
512516 args = [
513- (str (file_in ), str (file_out ), params_toml , scan_translator , metadata )
517+ (str (file_in ), str (file_out ), params_toml , scan_translator , None )
514518 for file_in , file_out in zip (files_list_positive , out_paths_list_positive )
515519 ]
516520 pool .map (process_complete_workflow , args )
517- del metadata
518521 gc .collect ()
519522
520523 # RUN THE NEGATIVE SAMPLES ================
0 commit comments