pycompound 0.1.6__py3-none-any.whl → 0.1.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycompound/build_library.py +77 -20
- pycompound/plot_spectra.py +73 -111
- pycompound/processing.py +5 -5
- pycompound/spec_lib_matching.py +262 -491
- pycompound/spec_lib_matching_CLI.py +48 -2
- pycompound/tuning_CLI_DE.py +22 -22
- pycompound/tuning_CLI_grid.py +22 -6
- pycompound-0.1.8.dist-info/METADATA +824 -0
- pycompound-0.1.8.dist-info/RECORD +14 -0
- {pycompound-0.1.6.dist-info → pycompound-0.1.8.dist-info}/top_level.txt +0 -1
- app.py +0 -1519
- pycompound-0.1.6.dist-info/METADATA +0 -27
- pycompound-0.1.6.dist-info/RECORD +0 -15
- {pycompound-0.1.6.dist-info → pycompound-0.1.8.dist-info}/WHEEL +0 -0
- {pycompound-0.1.6.dist-info → pycompound-0.1.8.dist-info}/licenses/LICENSE +0 -0
pycompound/build_library.py
CHANGED
|
@@ -6,18 +6,19 @@ from pathlib import Path
|
|
|
6
6
|
from pyteomics import mgf
|
|
7
7
|
from pyteomics import mzml
|
|
8
8
|
import sys
|
|
9
|
+
import json
|
|
9
10
|
|
|
10
11
|
def build_library_from_raw_data(input_path=None, output_path=None, is_reference=False):
|
|
11
12
|
'''
|
|
12
|
-
Converts mgf, mzML, cdf, or msp file to the necessary format for spectral library matching.
|
|
13
|
+
Converts mgf, mzML, cdf, json, or msp file to the necessary format for spectral library matching.
|
|
13
14
|
|
|
14
|
-
--input_path: Path to input file (must be mgf, mzML, cdf, or msp file). Mandatory argument.
|
|
15
|
+
--input_path: Path to input file (must be mgf, mzML, cdf, json, or msp file). Mandatory argument.
|
|
15
16
|
--output_path: Path to output TXT file. Default: current working directory.
|
|
16
17
|
--is_reference: Boolean flag indicating whether IDs of spectra should be written to output. Only pass true if building a reference library with known compound IDs. Only applicable to mgf and msp files. Options: \'True\', \'False\'. Optional argument. Default: False.
|
|
17
18
|
'''
|
|
18
19
|
|
|
19
20
|
if input_path is None:
|
|
20
|
-
print('Error: please specify input_path (i.e. the path to the input mgf, mzML, cdf, or msp file). Mandatory argument.')
|
|
21
|
+
print('Error: please specify input_path (i.e. the path to the input mgf, mzML, cdf, json, or msp file). Mandatory argument.')
|
|
21
22
|
sys.exit()
|
|
22
23
|
|
|
23
24
|
if output_path is None:
|
|
@@ -37,18 +38,21 @@ def build_library_from_raw_data(input_path=None, output_path=None, is_reference=
|
|
|
37
38
|
input_file_type = 'mgf'
|
|
38
39
|
elif last_four_chars == 'mzML' or last_four_chars == 'mzml' or last_four_chars == 'MZML':
|
|
39
40
|
input_file_type = 'mzML'
|
|
41
|
+
elif last_four_chars == 'json' or last_four_chars == 'JSON':
|
|
42
|
+
input_file_type = 'json'
|
|
40
43
|
elif last_three_chars == 'cdf' or last_three_chars == 'CDF':
|
|
41
44
|
input_file_type = 'cdf'
|
|
42
45
|
elif last_three_chars == 'msp' or last_three_chars == 'MSP':
|
|
43
46
|
input_file_type = 'msp'
|
|
44
47
|
else:
|
|
45
|
-
print('ERROR: either an \'mgf\', \'mzML\', \'cdf\', or \'msp\' file must be passed to --input_path')
|
|
48
|
+
print('ERROR: either an \'mgf\', \'mzML\', \'cdf\', \'json\', or \'msp\' file must be passed to --input_path')
|
|
46
49
|
sys.exit()
|
|
47
50
|
|
|
48
51
|
|
|
49
52
|
spectra = []
|
|
50
53
|
if input_file_type == 'mgf':
|
|
51
|
-
with mgf.read(input_path, index_by_scans = True) as reader:
|
|
54
|
+
#with mgf.read(input_path, index_by_scans = True) as reader:
|
|
55
|
+
with mgf.read(input_path, use_index=False) as reader:
|
|
52
56
|
for spec in reader:
|
|
53
57
|
spectra.append(spec)
|
|
54
58
|
if input_file_type == 'mzML':
|
|
@@ -61,18 +65,24 @@ def build_library_from_raw_data(input_path=None, output_path=None, is_reference=
|
|
|
61
65
|
ids = []
|
|
62
66
|
mzs = []
|
|
63
67
|
ints = []
|
|
68
|
+
precursor_ion_mzs = []
|
|
64
69
|
for i in range(0,len(spectra)):
|
|
65
70
|
for j in range(0,len(spectra[i]['m/z array'])):
|
|
66
71
|
if input_file_type == 'mzML':
|
|
67
|
-
ids.append(f'ID_{i+1}')
|
|
68
|
-
else:
|
|
69
72
|
if is_reference == False:
|
|
70
73
|
ids.append(f'ID_{i+1}')
|
|
71
|
-
|
|
74
|
+
else:
|
|
75
|
+
ids.append(spectra[i]['id'])
|
|
76
|
+
elif input_file_type == 'mgf':
|
|
77
|
+
precursor_ion_mzs.append(spectra[i]['params']['pepmass'][0])
|
|
78
|
+
if is_reference == False:
|
|
79
|
+
ids.append(f'ID_{i+1}')
|
|
80
|
+
else:
|
|
72
81
|
ids.append(spectra[i]['params']['name'])
|
|
73
82
|
mzs.append(spectra[i]['m/z array'][j])
|
|
74
83
|
ints.append(spectra[i]['intensity array'][j])
|
|
75
84
|
|
|
85
|
+
|
|
76
86
|
if input_file_type == 'cdf':
|
|
77
87
|
dataset = nc.Dataset(input_path, 'r')
|
|
78
88
|
all_mzs = dataset.variables['mass_values'][:]
|
|
@@ -98,31 +108,78 @@ def build_library_from_raw_data(input_path=None, output_path=None, is_reference=
|
|
|
98
108
|
ints.append(ints_tmp[j])
|
|
99
109
|
|
|
100
110
|
|
|
101
|
-
|
|
111
|
+
|
|
112
|
+
if input_file_type == "msp":
|
|
102
113
|
ids = []
|
|
103
114
|
mzs = []
|
|
104
115
|
ints = []
|
|
105
|
-
|
|
116
|
+
precursor_ion_mzs = []
|
|
117
|
+
spectrum_id = None
|
|
118
|
+
precursor_ion_mz = None
|
|
119
|
+
with open(input_path, "r", encoding="utf-8", errors="ignore") as f:
|
|
106
120
|
i = 0
|
|
107
121
|
for line in f:
|
|
108
122
|
line = line.strip()
|
|
109
|
-
if line
|
|
123
|
+
if not line:
|
|
124
|
+
continue
|
|
125
|
+
|
|
126
|
+
if line.startswith("Name:"):
|
|
110
127
|
i += 1
|
|
111
|
-
if is_reference
|
|
112
|
-
spectrum_id = f
|
|
113
|
-
|
|
114
|
-
spectrum_id = line.replace(
|
|
115
|
-
|
|
128
|
+
if not is_reference:
|
|
129
|
+
spectrum_id = f"ID_{i}"
|
|
130
|
+
else:
|
|
131
|
+
spectrum_id = line.replace("Name:", "", 1).strip()
|
|
132
|
+
|
|
133
|
+
elif line.startswith("PrecursorMZ:"):
|
|
134
|
+
try:
|
|
135
|
+
precursor_ion_mz = float(line.replace("PrecursorMZ:", "", 1).strip())
|
|
136
|
+
except ValueError:
|
|
137
|
+
precursor_ion_mz = None
|
|
138
|
+
|
|
139
|
+
elif line[0].isdigit():
|
|
116
140
|
try:
|
|
117
141
|
mz, intensity = map(float, line.split()[:2])
|
|
118
|
-
ids.append(spectrum_id)
|
|
119
|
-
mzs.append(mz)
|
|
120
|
-
ints.append(intensity)
|
|
121
142
|
except ValueError:
|
|
122
143
|
continue
|
|
123
144
|
|
|
145
|
+
if spectrum_id is None:
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
ids.append(spectrum_id)
|
|
149
|
+
mzs.append(mz)
|
|
150
|
+
ints.append(intensity)
|
|
151
|
+
precursor_ion_mzs.append(precursor_ion_mz)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if input_file_type == 'json':
|
|
156
|
+
data = json.load(open(input_path))
|
|
157
|
+
ids = []
|
|
158
|
+
mzs = []
|
|
159
|
+
ints = []
|
|
160
|
+
precursor_ion_mzs = []
|
|
161
|
+
for i in range(0,len(data)):
|
|
162
|
+
spec_ID_tmp = data[i]['spectrum_id']
|
|
163
|
+
tmp = data[i]['peaks_json']
|
|
164
|
+
tmp = tmp[1:-1].split(",")
|
|
165
|
+
tmp = [a.replace("[","") for a in tmp]
|
|
166
|
+
tmp = [a.replace("]","") for a in tmp]
|
|
167
|
+
mzs_tmp = tmp[0::2]
|
|
168
|
+
ints_tmp = tmp[1::2]
|
|
169
|
+
if is_reference == False:
|
|
170
|
+
ids.extend([f'ID_{i+1}'] * len(mzs_tmp))
|
|
171
|
+
elif is_reference == True:
|
|
172
|
+
ids.extend([spec_ID_tmp] * len(mzs_tmp))
|
|
173
|
+
mzs.extend(mzs_tmp)
|
|
174
|
+
ints.extend(ints_tmp)
|
|
175
|
+
precursor_ion_mzs.extend([data[i]['Precursor_MZ']] * len(mzs_tmp))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
if len(precursor_ion_mzs) > 0:
|
|
179
|
+
df = pd.DataFrame({'id':ids, 'mz_ratio':mzs, 'intensity':ints, 'precursor_ion_mz':precursor_ion_mzs})
|
|
180
|
+
else:
|
|
181
|
+
df = pd.DataFrame({'id':ids, 'mz_ratio':mzs, 'intensity':ints})
|
|
124
182
|
|
|
125
|
-
df = pd.DataFrame({'id':ids, 'mz_ratio':mzs, 'intensity':ints})
|
|
126
183
|
df.to_csv(output_path, index=False, sep='\t')
|
|
127
184
|
|
|
128
185
|
|
pycompound/plot_spectra.py
CHANGED
|
@@ -8,32 +8,6 @@ import matplotlib.pyplot as plt
|
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_ID1=None, spectrum_ID2=None, similarity_measure='cosine', weights={'Cosine':0.25,'Shannon':0.25,'Renyi':0.25,'Tsallis':0.25}, spectrum_preprocessing_order='FCNMWL', high_quality_reference_library=False, mz_min=0, mz_max=9999999, int_min=0, int_max=9999999, window_size_centroiding=0.5, window_size_matching=0.5, noise_threshold=0.0, wf_mz=0.0, wf_intensity=1.0, LET_threshold=0.0, entropy_dimension=1.1, y_axis_transformation='normalized', output_path=None, return_plot=False):
|
|
11
|
-
'''
|
|
12
|
-
plots two spectra against each other before and after preprocessing transformations for high-resolution mass spectrometry data
|
|
13
|
-
|
|
14
|
-
--query_data: mgf, mzML, or csv file of query mass spectrum/spectra to be identified. If csv file, each row should correspond to a mass spectrum, the left-most column should contain an identifier, and each of the other columns should correspond to a single mass/charge ratio. Mandatory argument.
|
|
15
|
-
--reference_data: mgf, mzML, or csv file of the reference mass spectra. If csv file, each row should correspond to a mass spectrum, the left-most column should contain in identifier (i.e. the CAS registry number or the compound name), and the remaining column should correspond to a single mass/charge ratio. Mandatory argument.
|
|
16
|
-
--spectrum_ID1: ID of one spectrum to be plotted. Default is first spectrum in the query library. Optional argument.
|
|
17
|
-
--spectrum_ID2: ID of another spectrum to be plotted. Default is first spectrum in the reference library. Optional argument.
|
|
18
|
-
--similarity_measure: cosine, shannon, renyi, tsallis, mixture, jaccard, dice, 3w_jaccard, sokal_sneath, binary_cosine, mountford, mcconnaughey, driver_kroeber, simpson, braun_banquet, fager_mcgowan, kulczynski, intersection, hamming, hellinger. Default: cosine.
|
|
19
|
-
--weights: dict of weights to give to each non-binary similarity measure (i.e. cosine, shannon, renyi, and tsallis) when the mixture similarity measure is specified. Default: 0.25 for each of the four non-binary similarity measures.
|
|
20
|
-
--spectrum_preprocessing_order: The spectrum preprocessing transformations and the order in which they are to be applied. Note that these transformations are applied prior to computing similarity scores. Format must be a string with 2-6 characters chosen from C, F, M, N, L, W representing centroiding, filtering based on mass/charge and intensity values, matching, noise removal, low-entropy trannsformation, and weight-factor-transformation, respectively. For example, if \'WCM\' is passed, then each spectrum will undergo a weight factor transformation, then centroiding, and then matching. Note that if an argument is passed, then \'M\' must be contained in the argument, since matching is a required preprocessing step in spectral library matching of HRMS data. Furthermore, \'C\' must be performed before matching since centroiding can change the number of ion fragments in a given spectrum. Default: FCNMWL')
|
|
21
|
-
--high_quality_reference_library: True/False flag indicating whether the reference library is considered to be of high quality. If True, then the spectrum preprocessing transformations of filtering and noise removal are performed only on the query spectrum/spectra. If False, all spectrum preprocessing transformations specified will be applied to both the query and reference spectra. Default: False')
|
|
22
|
-
--mz_min: Remove all peaks with mass/charge value less than mz_min in each spectrum. Default: 0
|
|
23
|
-
--mz_max: Remove all peaks with mass/charge value greater than mz_max in each spectrum. Default: 9999999
|
|
24
|
-
--int_min: Remove all peaks with intensity value less than int_min in each spectrum. Default: 0
|
|
25
|
-
--int_max: Remove all peaks with intensity value greater than int_max in each spectrum. Default: 9999999
|
|
26
|
-
--window_size_centroiding: Window size parameter used in centroiding a given spectrum. Default: 0.5
|
|
27
|
-
--window_size_matching: Window size parameter used in matching a query spectrum and a reference library spectrum. Default: 0.5
|
|
28
|
-
--noise_threshold: Ion fragments (i.e. points in a given mass spectrum) with intensity less than max(intensities)*noise_threshold are removed. Default: 0.0
|
|
29
|
-
--wf_mz: Mass/charge weight factor parameter. Default: 0.0
|
|
30
|
-
--wf_intensity: Intensity weight factor parameter. Default: 0.0
|
|
31
|
-
--LET_threshold: Low-entropy transformation threshold parameter. Spectra with Shannon entropy less than LET_threshold are transformed according to intensitiesNew=intensitiesOriginal^{(1+S)/(1+LET_threshold)}. Default: 0.0
|
|
32
|
-
--entropy_dimension: Entropy dimension parameter. Must have positive value other than 1. When the entropy dimension is 1, then Renyi and Tsallis entropy are equivalent to Shannon entropy. Therefore, this parameter only applies to the renyi and tsallis similarity measures. This parameter will be ignored if similarity measure cosine or shannon is chosen. Default: 1.1
|
|
33
|
-
--y_axis_transformation: transformation to apply to y-axis (i.e. intensity axis) of plots. Options: \'normalized\', \'none\', \'log10\', and \'sqrt\'. Default: normalized.')
|
|
34
|
-
--output_path: path to output PDF file containing the plots of the spectra before and after preprocessing transformations. If no argument is passed, then the plots will be saved to the PDF ./spectrum1_{spectrum_ID1}_spectrum2_{spectrum_ID2}_plot.pdf in the current working directory.
|
|
35
|
-
'''
|
|
36
|
-
|
|
37
11
|
if query_data is None:
|
|
38
12
|
print('\nError: No argument passed to the mandatory query_data. Please pass the path to the CSV file of the query data.')
|
|
39
13
|
sys.exit()
|
|
@@ -41,12 +15,12 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
41
15
|
extension = query_data.rsplit('.',1)
|
|
42
16
|
extension = extension[(len(extension)-1)]
|
|
43
17
|
if extension == 'mgf' or extension == 'MGF' or extension == 'mzML' or extension == 'mzml' or extension == 'MZML' or extension == 'cdf' or extension == 'CDF':
|
|
44
|
-
output_path_tmp = query_data[:-3] + '
|
|
18
|
+
output_path_tmp = query_data[:-3] + 'txt'
|
|
45
19
|
build_library_from_raw_data(input_path=query_data, output_path=output_path_tmp, is_reference=True)
|
|
46
|
-
df_query = pd.read_csv(output_path_tmp)
|
|
47
|
-
if extension == '
|
|
48
|
-
df_query = pd.read_csv(query_data)
|
|
49
|
-
unique_query_ids = df_query
|
|
20
|
+
df_query = pd.read_csv(output_path_tmp, sep='\t')
|
|
21
|
+
if extension == 'txt' or extension == 'TXT':
|
|
22
|
+
df_query = pd.read_csv(query_data, sep='\t')
|
|
23
|
+
unique_query_ids = df_query['id'].unique().tolist()
|
|
50
24
|
unique_query_ids = [str(tmp) for tmp in unique_query_ids]
|
|
51
25
|
|
|
52
26
|
if reference_data is None:
|
|
@@ -56,25 +30,25 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
56
30
|
extension = reference_data.rsplit('.',1)
|
|
57
31
|
extension = extension[(len(extension)-1)]
|
|
58
32
|
if extension == 'mgf' or extension == 'MGF' or extension == 'mzML' or extension == 'mzml' or extension == 'MZML' or extension == 'cdf' or extension == 'CDF':
|
|
59
|
-
output_path_tmp = reference_data[:-3] + '
|
|
33
|
+
output_path_tmp = reference_data[:-3] + 'txt'
|
|
60
34
|
build_library_from_raw_data(input_path=reference_data, output_path=output_path_tmp, is_reference=True)
|
|
61
|
-
df_reference = pd.read_csv(output_path_tmp)
|
|
62
|
-
if extension == '
|
|
63
|
-
df_reference = pd.read_csv(reference_data)
|
|
64
|
-
unique_reference_ids = df_reference
|
|
35
|
+
df_reference = pd.read_csv(output_path_tmp, sep='\t')
|
|
36
|
+
if extension == 'txt' or extension == 'TXT':
|
|
37
|
+
df_reference = pd.read_csv(reference_data, sep='\t')
|
|
38
|
+
unique_reference_ids = df_reference['id'].unique().tolist()
|
|
65
39
|
unique_reference_ids = [str(tmp) for tmp in unique_reference_ids]
|
|
66
40
|
|
|
67
41
|
|
|
68
42
|
if spectrum_ID1 is not None:
|
|
69
43
|
spectrum_ID1 = str(spectrum_ID1)
|
|
70
44
|
else:
|
|
71
|
-
spectrum_ID1 = str(df_query.iloc[0
|
|
45
|
+
spectrum_ID1 = str(df_query['id'].iloc[0])
|
|
72
46
|
print('No argument passed to spectrum_ID1; using the first spectrum in query_data.')
|
|
73
47
|
|
|
74
48
|
if spectrum_ID2 is not None:
|
|
75
49
|
spectrum_ID2 = str(spectrum_ID2)
|
|
76
50
|
else:
|
|
77
|
-
spectrum_ID2 = str(df_reference.iloc[0
|
|
51
|
+
spectrum_ID2 = str(df_reference['id'].iloc[0])
|
|
78
52
|
print('No argument passed to spectrum_ID2; using the first spectrum in reference_data.')
|
|
79
53
|
|
|
80
54
|
if spectrum_preprocessing_order is not None:
|
|
@@ -157,17 +131,17 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
157
131
|
if spectrum_ID1 in unique_query_ids and spectrum_ID2 in unique_query_ids:
|
|
158
132
|
query_idx = unique_query_ids.index(spectrum_ID1)
|
|
159
133
|
reference_idx = unique_query_ids.index(spectrum_ID2)
|
|
160
|
-
q_idxs_tmp = np.where(df_query
|
|
161
|
-
r_idxs_tmp = np.where(df_query
|
|
162
|
-
q_spec = np.asarray(pd.concat([df_query.iloc[q_idxs_tmp
|
|
163
|
-
r_spec = np.asarray(pd.concat([df_query.iloc[r_idxs_tmp
|
|
134
|
+
q_idxs_tmp = np.where(df_query['id'].astype(str) == unique_query_ids[query_idx])[0]
|
|
135
|
+
r_idxs_tmp = np.where(df_query['id'].astype(str) == unique_query_ids[reference_idx])[0]
|
|
136
|
+
q_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[q_idxs_tmp], df_query['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
137
|
+
r_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[r_idxs_tmp], df_query['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
164
138
|
elif spectrum_ID1 in unique_reference_ids and spectrum_ID2 in unique_reference_ids:
|
|
165
139
|
query_idx = unique_reference_ids.index(spectrum_ID1)
|
|
166
140
|
reference_idx = unique_reference_ids.index(spectrum_ID2)
|
|
167
|
-
q_idxs_tmp = np.where(df_reference
|
|
168
|
-
r_idxs_tmp = np.where(df_reference
|
|
169
|
-
q_spec = np.asarray(pd.concat([df_reference.iloc[q_idxs_tmp
|
|
170
|
-
r_spec = np.asarray(pd.concat([df_reference.iloc[r_idxs_tmp
|
|
141
|
+
q_idxs_tmp = np.where(df_reference['id'].astype(str) == unique_reference_ids[query_idx])[0]
|
|
142
|
+
r_idxs_tmp = np.where(df_reference['id'].astype(str) == unique_reference_ids[reference_idx])[0]
|
|
143
|
+
q_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[q_idxs_tmp], df_reference['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
144
|
+
r_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[r_idxs_tmp], df_reference['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
171
145
|
else:
|
|
172
146
|
if spectrum_ID1 in unique_reference_ids and spectrum_ID2 in unique_query_ids:
|
|
173
147
|
spec_tmp = spectrum_ID1
|
|
@@ -175,10 +149,10 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
175
149
|
spectrum_ID2 = spec_tmp
|
|
176
150
|
query_idx = unique_query_ids.index(spectrum_ID1)
|
|
177
151
|
reference_idx = unique_reference_ids.index(spectrum_ID2)
|
|
178
|
-
q_idxs_tmp = np.where(df_query
|
|
179
|
-
r_idxs_tmp = np.where(df_reference
|
|
180
|
-
q_spec = np.asarray(pd.concat([df_query.iloc[q_idxs_tmp
|
|
181
|
-
r_spec = np.asarray(pd.concat([df_reference.iloc[r_idxs_tmp
|
|
152
|
+
q_idxs_tmp = np.where(df_query['id'].astype(str) == unique_query_ids[query_idx])[0]
|
|
153
|
+
r_idxs_tmp = np.where(df_reference['id'].astype(str) == unique_reference_ids[reference_idx])[0]
|
|
154
|
+
q_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[q_idxs_tmp], df_query['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
155
|
+
r_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[r_idxs_tmp], df_reference['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
182
156
|
|
|
183
157
|
|
|
184
158
|
q_spec_pre_trans = q_spec.copy()
|
|
@@ -293,9 +267,6 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
293
267
|
plt.yticks([])
|
|
294
268
|
|
|
295
269
|
|
|
296
|
-
print('\n\n\n')
|
|
297
|
-
print(high_quality_reference_library)
|
|
298
|
-
print('\n\n\n')
|
|
299
270
|
plt.subplots_adjust(top=0.8, hspace=0.92, bottom=0.3)
|
|
300
271
|
plt.figlegend(loc = 'upper center')
|
|
301
272
|
fig.text(0.05, 0.18, f'Similarity Measure: {similarity_measure.capitalize()}', fontsize=7)
|
|
@@ -315,34 +286,12 @@ def generate_plots_on_HRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
315
286
|
plt.savefig(output_path, format='pdf')
|
|
316
287
|
|
|
317
288
|
if return_plot == True:
|
|
318
|
-
return
|
|
289
|
+
return fig
|
|
319
290
|
|
|
320
291
|
|
|
321
292
|
|
|
322
293
|
|
|
323
294
|
def generate_plots_on_NRMS_data(query_data=None, reference_data=None, spectrum_ID1=None, spectrum_ID2=None, similarity_measure='cosine', weights={'Cosine':0.25,'Shannon':0.25,'Renyi':0.25,'Tsallis':0.25}, spectrum_preprocessing_order='FNLW', high_quality_reference_library=False, mz_min=0, mz_max=9999999, int_min=0, int_max=9999999, noise_threshold=0.0, wf_mz=0.0, wf_intensity=1.0, LET_threshold=0.0, entropy_dimension=1.1, y_axis_transformation='normalized', output_path=None, return_plot=False):
|
|
324
|
-
'''
|
|
325
|
-
plots two spectra against each other before and after preprocessing transformations for high-resolution mass spectrometry data
|
|
326
|
-
|
|
327
|
-
--query_data: cdf or csv file of query mass spectrum/spectra to be identified. If csv file, each row should correspond to a mass spectrum, the left-most column should contain an identifier, and each of the other columns should correspond to a single mass/charge ratio. Mandatory argument.
|
|
328
|
-
--reference_data: cdf of csv file of the reference mass spectra. If csv file, each row should correspond to a mass spectrum, the left-most column should contain in identifier (i.e. the CAS registry number or the compound name), and the remaining column should correspond to a single mass/charge ratio. Mandatory argument.
|
|
329
|
-
--similarity_measure: cosine, shannon, renyi, tsallis, mixture, jaccard, dice, 3w_jaccard, sokal_sneath, binary_cosine, mountford, mcconnaughey, driver_kroeber, simpson, braun_banquet, fager_mcgowan, kulczynski, intersection, hamming, hellinger. Default: cosine.
|
|
330
|
-
--weights: dict of weights to give to each non-binary similarity measure (i.e. cosine, shannon, renyi, and tsallis) when the mixture similarity measure is specified. Default: 0.25 for each of the four non-binary similarity measures.
|
|
331
|
-
--spectrum_preprocessing_order: The spectrum preprocessing transformations and the order in which they are to be applied. Note that these transformations are applied prior to computing similarity scores. Format must be a string with 2-4 characters chosen from F, N, L, W representing filtering based on mass/charge and intensity values, noise removal, low-entropy trannsformation, and weight-factor-transformation, respectively. For example, if \'WN\' is passed, then each spectrum will undergo a weight factor transformation and then noise removal. Default: FNLW')
|
|
332
|
-
--high_quality_reference_library: True/False flag indicating whether the reference library is considered to be of high quality. If True, then the spectrum preprocessing transformations of filtering and noise removal are performed only on the query spectrum/spectra. If False, all spectrum preprocessing transformations specified will be applied to both the query and reference spectra. Default: False')
|
|
333
|
-
--mz_min: Remove all peaks with mass/charge value less than mz_min in each spectrum. Default: 0
|
|
334
|
-
--mz_max: Remove all peaks with mass/charge value greater than mz_max in each spectrum. Default: 9999999
|
|
335
|
-
--int_min: Remove all peaks with intensity value less than int_min in each spectrum. Default: 0
|
|
336
|
-
--int_max: Remove all peaks with intensity value greater than int_max in each spectrum. Default: 9999999
|
|
337
|
-
--noise_threshold: Ion fragments (i.e. points in a given mass spectrum) with intensity less than max(intensities)*noise_threshold are removed. Default: 0.0
|
|
338
|
-
--wf_mz: Mass/charge weight factor parameter. Default: 0.0
|
|
339
|
-
--wf_intensity: Intensity weight factor parameter. Default: 0.0
|
|
340
|
-
--LET_threshold: Low-entropy transformation threshold parameter. Spectra with Shannon entropy less than LET_threshold are transformed according to intensitiesNew=intensitiesOriginal^{(1+S)/(1+LET_threshold)}. Default: 0.0
|
|
341
|
-
--entropy_dimension: Entropy dimension parameter. Must have positive value other than 1. When the entropy dimension is 1, then Renyi and Tsallis entropy are equivalent to Shannon entropy. Therefore, this parameter only applies to the renyi and tsallis similarity measures. This parameter will be ignored if similarity measure cosine or shannon is chosen. Default: 1.1
|
|
342
|
-
--y_axis_transformation: transformation to apply to y-axis (i.e. intensity axis) of plots. Options: \'normalized\', \'none\', \'log10\', and \'sqrt\'. Default: normalized.')
|
|
343
|
-
--output_path: path to output PDF file containing the plots of the spectra before and after preprocessing transformations. If no argument is passed, then the plots will be saved to the PDF ./spectrum1_{spectrum_ID1}_spectrum2_{spectrum_ID2}_plot.pdf in the current working directory.
|
|
344
|
-
'''
|
|
345
|
-
|
|
346
295
|
if query_data is None:
|
|
347
296
|
print('\nError: No argument passed to the mandatory query_data. Please pass the path to the CSV file of the query data.')
|
|
348
297
|
sys.exit()
|
|
@@ -350,12 +299,12 @@ def generate_plots_on_NRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
350
299
|
extension = query_data.rsplit('.',1)
|
|
351
300
|
extension = extension[(len(extension)-1)]
|
|
352
301
|
if extension == 'mgf' or extension == 'MGF' or extension == 'mzML' or extension == 'mzml' or extension == 'MZML' or extension == 'cdf' or extension == 'CDF':
|
|
353
|
-
output_path_tmp = query_data[:-3] + '
|
|
302
|
+
output_path_tmp = query_data[:-3] + 'txt'
|
|
354
303
|
build_library_from_raw_data(input_path=query_data, output_path=output_path_tmp, is_reference=False)
|
|
355
|
-
df_query = pd.read_csv(output_path_tmp)
|
|
356
|
-
if extension == '
|
|
357
|
-
df_query = pd.read_csv(query_data)
|
|
358
|
-
unique_query_ids = df_query
|
|
304
|
+
df_query = pd.read_csv(output_path_tmp, sep='\t')
|
|
305
|
+
if extension == 'txt' or extension == 'TXT':
|
|
306
|
+
df_query = pd.read_csv(query_data, sep='\t')
|
|
307
|
+
unique_query_ids = df_query['id'].unique()
|
|
359
308
|
|
|
360
309
|
if reference_data is None:
|
|
361
310
|
print('\nError: No argument passed to the mandatory reference_data. Please pass the path to the CSV file of the reference data.')
|
|
@@ -364,24 +313,24 @@ def generate_plots_on_NRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
364
313
|
extension = reference_data.rsplit('.',1)
|
|
365
314
|
extension = extension[(len(extension)-1)]
|
|
366
315
|
if extension == 'mgf' or extension == 'MGF' or extension == 'mzML' or extension == 'mzml' or extension == 'MZML' or extension == 'cdf' or extension == 'CDF':
|
|
367
|
-
output_path_tmp = reference_data[:-3] + '
|
|
316
|
+
output_path_tmp = reference_data[:-3] + 'txt'
|
|
368
317
|
build_library_from_raw_data(input_path=reference_data, output_path=output_path_tmp, is_reference=True)
|
|
369
|
-
df_reference = pd.read_csv(output_path_tmp)
|
|
370
|
-
if extension == '
|
|
371
|
-
df_reference = pd.read_csv(reference_data)
|
|
372
|
-
unique_reference_ids = df_reference
|
|
318
|
+
df_reference = pd.read_csv(output_path_tmp, sep='\t')
|
|
319
|
+
if extension == 'txt' or extension == 'TXT':
|
|
320
|
+
df_reference = pd.read_csv(reference_data, sep='\t')
|
|
321
|
+
unique_reference_ids = df_reference['id'].unique()
|
|
373
322
|
|
|
374
323
|
|
|
375
324
|
if spectrum_ID1 is not None:
|
|
376
325
|
spectrum_ID1 = str(spectrum_ID1)
|
|
377
326
|
else:
|
|
378
|
-
spectrum_ID1 = str(df_query.iloc[0
|
|
327
|
+
spectrum_ID1 = str(df_query['id'].iloc[0])
|
|
379
328
|
print('No argument passed to spectrum_ID1; using the first spectrum in query_data.')
|
|
380
329
|
|
|
381
330
|
if spectrum_ID2 is not None:
|
|
382
331
|
spectrum_ID2 = str(spectrum_ID2)
|
|
383
332
|
else:
|
|
384
|
-
spectrum_ID2 = str(df_reference.iloc[0
|
|
333
|
+
spectrum_ID2 = str(df_reference['id'].iloc[0])
|
|
385
334
|
print('No argument passed to spectrum_ID2; using the first spectrum in reference_data.')
|
|
386
335
|
|
|
387
336
|
if spectrum_preprocessing_order is not None:
|
|
@@ -446,12 +395,12 @@ def generate_plots_on_NRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
446
395
|
print(f'Warning: plots will be saved to the PDF ./spectrum1_{spectrum_ID1}_spectrum2_{spectrum_ID2}_plot.pdf in the current working directory.')
|
|
447
396
|
output_path = f'{Path.cwd()}/spectrum1_{spectrum_ID1}_spectrum2_{spectrum_ID2}.pdf'
|
|
448
397
|
|
|
449
|
-
min_mz = np.min([np.min(df_query
|
|
450
|
-
max_mz = np.max([np.max(df_query
|
|
398
|
+
min_mz = np.min([np.min(df_query['mz_ratio'].tolist()), np.min(df_reference['mz_ratio'].tolist())])
|
|
399
|
+
max_mz = np.max([np.max(df_query['mz_ratio'].tolist()), np.max(df_reference['mz_ratio'].tolist())])
|
|
451
400
|
mzs = np.linspace(min_mz,max_mz,(max_mz-min_mz+1))
|
|
452
401
|
|
|
453
|
-
unique_query_ids = df_query
|
|
454
|
-
unique_reference_ids = df_reference
|
|
402
|
+
unique_query_ids = df_query['id'].unique().tolist()
|
|
403
|
+
unique_reference_ids = df_reference['id'].unique().tolist()
|
|
455
404
|
unique_query_ids = [str(ID) for ID in unique_query_ids]
|
|
456
405
|
unique_reference_ids = [str(ID) for ID in unique_reference_ids]
|
|
457
406
|
common_IDs = np.intersect1d([str(ID) for ID in unique_query_ids], [str(ID) for ID in unique_reference_ids])
|
|
@@ -459,35 +408,48 @@ def generate_plots_on_NRMS_data(query_data=None, reference_data=None, spectrum_I
|
|
|
459
408
|
print(f'Warning: the query and reference library have overlapping IDs: {common_IDs}')
|
|
460
409
|
|
|
461
410
|
if spectrum_ID1 in unique_query_ids and spectrum_ID2 in unique_query_ids:
|
|
462
|
-
q_idxs_tmp = np.where(df_query
|
|
463
|
-
r_idxs_tmp = np.where(df_query
|
|
464
|
-
q_spec = np.asarray(pd.concat([df_query.iloc[q_idxs_tmp
|
|
465
|
-
r_spec = np.asarray(pd.concat([df_query.iloc[r_idxs_tmp
|
|
411
|
+
q_idxs_tmp = np.where(df_query['id'].astype(str) == spectrum_ID1)[0]
|
|
412
|
+
r_idxs_tmp = np.where(df_query['id'].astype(str) == spectrum_ID2)[0]
|
|
413
|
+
q_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[q_idxs_tmp], df_query['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
414
|
+
r_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[r_idxs_tmp], df_query['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
466
415
|
elif spectrum_ID1 in unique_reference_ids and spectrum_ID2 in unique_reference_ids:
|
|
467
|
-
q_idxs_tmp = np.where(df_reference
|
|
468
|
-
r_idxs_tmp = np.where(df_reference
|
|
469
|
-
q_spec = np.asarray(pd.concat([df_reference.iloc[q_idxs_tmp
|
|
470
|
-
r_spec = np.asarray(pd.concat([df_reference.iloc[r_idxs_tmp
|
|
416
|
+
q_idxs_tmp = np.where(df_reference['id'].astype(str) == spectrum_ID1)[0]
|
|
417
|
+
r_idxs_tmp = np.where(df_reference['id'].astype(str) == spectrum_ID2)[0]
|
|
418
|
+
q_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[q_idxs_tmp], df_reference['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
419
|
+
r_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[r_idxs_tmp], df_reference['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
471
420
|
else:
|
|
472
421
|
if spectrum_ID1 in unique_reference_ids and spectrum_ID2 in unique_query_ids:
|
|
473
422
|
spec_tmp = spectrum_ID1
|
|
474
423
|
spectrum_ID1 = spectrum_ID2
|
|
475
424
|
spectrum_ID2 = spec_tmp
|
|
476
|
-
q_idxs_tmp = np.where(df_query
|
|
477
|
-
r_idxs_tmp = np.where(df_reference
|
|
478
|
-
q_spec = np.asarray(pd.concat([df_query.iloc[q_idxs_tmp
|
|
479
|
-
r_spec = np.asarray(pd.concat([df_reference.iloc[r_idxs_tmp
|
|
425
|
+
q_idxs_tmp = np.where(df_query['id'].astype(str) == spectrum_ID1)[0]
|
|
426
|
+
r_idxs_tmp = np.where(df_reference['id'].astype(str) == spectrum_ID2)[0]
|
|
427
|
+
q_spec = np.asarray(pd.concat([df_query['mz_ratio'].iloc[q_idxs_tmp], df_query['intensity'].iloc[q_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
428
|
+
r_spec = np.asarray(pd.concat([df_reference['mz_ratio'].iloc[r_idxs_tmp], df_reference['intensity'].iloc[r_idxs_tmp]], axis=1).reset_index(drop=True))
|
|
480
429
|
|
|
481
430
|
q_spec = convert_spec(q_spec,mzs)
|
|
482
431
|
r_spec = convert_spec(r_spec,mzs)
|
|
483
432
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
433
|
+
nz_q = q_spec[:, 1] != 0
|
|
434
|
+
nz_r = r_spec[:, 1] != 0
|
|
435
|
+
|
|
436
|
+
if np.any(nz_q):
|
|
437
|
+
int_min_tmp_q = q_spec[nz_q, 1].min()
|
|
438
|
+
int_max_tmp_q = q_spec[nz_q, 1].max()
|
|
439
|
+
else:
|
|
440
|
+
int_min_tmp_q = 0.0
|
|
441
|
+
int_max_tmp_q = 0.0
|
|
442
|
+
|
|
443
|
+
if np.any(nz_r):
|
|
444
|
+
int_min_tmp_r = r_spec[nz_r, 1].min()
|
|
445
|
+
int_max_tmp_r = r_spec[nz_r, 1].max()
|
|
446
|
+
else:
|
|
447
|
+
int_min_tmp_r = 0.0
|
|
448
|
+
int_max_tmp_r = 0.0
|
|
449
|
+
|
|
450
|
+
int_min_tmp = int(min(int_min_tmp_q, int_min_tmp_r))
|
|
451
|
+
int_max_tmp = int(max(int_max_tmp_q, int_max_tmp_r))
|
|
452
|
+
|
|
491
453
|
fig, axes = plt.subplots(nrows=2, ncols=1)
|
|
492
454
|
|
|
493
455
|
plt.subplot(2,1,1)
|
pycompound/processing.py
CHANGED
|
@@ -295,13 +295,13 @@ def get_reference_df(reference_data, likely_reference_IDs=None):
|
|
|
295
295
|
extension = reference_data.rsplit('.',1)
|
|
296
296
|
extension = extension[(len(extension)-1)]
|
|
297
297
|
if extension == 'mgf' or extension == 'MGF' or extension == 'mzML' or extension == 'mzml' or extension == 'MZML' or extension == 'cdf' or extension == 'CDF':
|
|
298
|
-
output_path_tmp = reference_data[:-3] + '
|
|
298
|
+
output_path_tmp = reference_data[:-3] + 'txt'
|
|
299
299
|
build_library_from_raw_data(input_path=reference_data, output_path=output_path_tmp, is_reference=True)
|
|
300
|
-
df_reference = pd.read_csv(output_path_tmp)
|
|
301
|
-
if extension == '
|
|
302
|
-
df_reference = pd.read_csv(reference_data)
|
|
300
|
+
df_reference = pd.read_csv(output_path_tmp, sep='\t')
|
|
301
|
+
if extension == 'txt' or extension == 'TXT':
|
|
302
|
+
df_reference = pd.read_csv(reference_data, sep='\t')
|
|
303
303
|
if likely_reference_IDs is not None:
|
|
304
|
-
likely_reference_IDs = pd.read_csv(likely_reference_IDs, header=None)
|
|
304
|
+
likely_reference_IDs = pd.read_csv(likely_reference_IDs, header=None, sep='\t')
|
|
305
305
|
df_reference = df_reference.loc[df_reference.iloc[:,0].isin(likely_reference_IDs.iloc[:,0].tolist())]
|
|
306
306
|
return df_reference
|
|
307
307
|
|