msIO 1.0.3__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.
- msIO/__init__.py +15 -0
- msIO/_templates/__init__.py +12 -0
- msIO/_templates/_many_to_many.py +39 -0
- msIO/_templates/_many_to_many_bidirectional.py +43 -0
- msIO/_templates/_many_to_one.py +22 -0
- msIO/_templates/_many_to_one_bidirectional.py +23 -0
- msIO/_templates/_one_to_many.py +33 -0
- msIO/_templates/_one_to_many_bidirectional.py +32 -0
- msIO/_templates/_one_to_one.py +26 -0
- msIO/_templates/relationship_patterns.py +65 -0
- msIO/_version.py +2 -0
- msIO/annotations/__init__.py +0 -0
- msIO/annotations/main.py +228 -0
- msIO/core.py +29 -0
- msIO/environmental/__init__.py +0 -0
- msIO/environmental/location.py +21 -0
- msIO/environmental/sample.py +48 -0
- msIO/export_manager/__init__.py +0 -0
- msIO/export_manager/main.py +34 -0
- msIO/feature_managers/__init__.py +0 -0
- msIO/feature_managers/_read_mzio_graphml_as_xml.py +68 -0
- msIO/feature_managers/base.py +45 -0
- msIO/feature_managers/combined.py +171 -0
- msIO/feature_managers/db.py +1305 -0
- msIO/feature_managers/gnps.py +75 -0
- msIO/feature_managers/metaboscape.py +114 -0
- msIO/feature_managers/sirius.py +162 -0
- msIO/feature_managers/util_library.py +42 -0
- msIO/features/__init__.py +0 -0
- msIO/features/base.py +80 -0
- msIO/features/combined.py +143 -0
- msIO/features/gnps.py +59 -0
- msIO/features/metaboscape.py +128 -0
- msIO/features/mgf.py +171 -0
- msIO/features/sirius.py +228 -0
- msIO/features/util.py +13 -0
- msIO/general.py +55 -0
- msIO/gui/__init__.py +0 -0
- msIO/gui/_gui_log.py +32 -0
- msIO/gui/about +16 -0
- msIO/gui/annotation/__init__.py +3 -0
- msIO/gui/annotation/annotations.py +169 -0
- msIO/gui/annotation/app.py +916 -0
- msIO/gui/annotation/common.py +694 -0
- msIO/gui/annotation/database_panel.py +51 -0
- msIO/gui/annotation/dialogs.py +688 -0
- msIO/gui/annotation/export.py +105 -0
- msIO/gui/annotation/filter_panel.py +398 -0
- msIO/gui/annotation/matching.py +294 -0
- msIO/gui/annotation/matching_panel.py +99 -0
- msIO/gui/annotation/overview_panel.py +367 -0
- msIO/gui/annotation/results_panel.py +400 -0
- msIO/gui/annotation/scatter_panel.py +898 -0
- msIO/gui/annotation/series.py +334 -0
- msIO/gui/annotation/shortcuts.py +213 -0
- msIO/gui/csv_to_sqlite_gui.py +266 -0
- msIO/gui/feature_overview.py +467 -0
- msIO/gui/find_lib_matches.py +13 -0
- msIO/gui/library_search_by_name.py +222 -0
- msIO/gui/main.py +85 -0
- msIO/gui/msp_to_sqlite_gui.py +142 -0
- msIO/list_of_ions/__init__.py +0 -0
- msIO/list_of_ions/base.py +299 -0
- msIO/list_of_ions/read_library.py +76 -0
- msIO/list_of_ions/read_mca.py +237 -0
- msIO/list_of_ions/read_mgf.py +161 -0
- msIO/list_of_ions/read_msp.py +281 -0
- msIO/metrics.py +72 -0
- msIO/sql/__init__.py +0 -0
- msIO/sql/create_library.py +151 -0
- msIO/sql/session.py +32 -0
- msIO/sql/visualize.py +61 -0
- msio-1.0.3.dist-info/METADATA +151 -0
- msio-1.0.3.dist-info/RECORD +77 -0
- msio-1.0.3.dist-info/WHEEL +5 -0
- msio-1.0.3.dist-info/licenses/LICENSE +21 -0
- msio-1.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1305 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import os
|
|
3
|
+
import warnings
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from itertools import groupby
|
|
7
|
+
from typing import Any, Iterable, Iterator, Literal, Callable
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
from LipidCalculator import Adduct, CompoundDict
|
|
14
|
+
from LipidCalculator.isotopes.isotope_pattern import IsotopePattern
|
|
15
|
+
from LipidCalculator.rdkit.plotting import mplt_mol
|
|
16
|
+
from matchms.similarity import ModifiedCosineGreedy
|
|
17
|
+
from matplotlib import pyplot as plt
|
|
18
|
+
from matplotlib.gridspec import GridSpec
|
|
19
|
+
from rdkit import Chem
|
|
20
|
+
from tqdm import tqdm
|
|
21
|
+
|
|
22
|
+
from msIO import PeakList
|
|
23
|
+
from msIO.environmental.sample import Sample
|
|
24
|
+
from msIO.feature_managers.util_library import peaklist_to_spectrum
|
|
25
|
+
from msIO.list_of_ions.base import PeakFeature
|
|
26
|
+
from msIO.metrics import cosine_similarity_sym, cosine_similarity_forward, cosine_similarity_backward
|
|
27
|
+
from msIO.sql.session import get_sessionmaker
|
|
28
|
+
from sqlalchemy import select, inspect, text, or_, and_, func
|
|
29
|
+
from sqlalchemy.orm import selectinload, joinedload
|
|
30
|
+
|
|
31
|
+
# need to import so that sqlalchemy knows about relationships
|
|
32
|
+
from msIO.features.metaboscape import FeatureMetaboScape, Intensity
|
|
33
|
+
from msIO.features.mgf import FeatureMgf, MsSpec
|
|
34
|
+
from msIO.features.sirius import CompoundCandidate, FormulaCandidate, FeatureSirius
|
|
35
|
+
from msIO.features.combined import FeatureCombined
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
# manual annotations are compound candidates whose sirius_compound_folder starts with one of these prefixes
|
|
40
|
+
MANUAL_LIBRARY_ANNOTATION: str = 'manual_library_annotation' # match from a library
|
|
41
|
+
MANUAL_ANNOTATION: str = 'manual_annotation' # compound entered by hand
|
|
42
|
+
MANUAL_IN_SOURCE_FRAGMENT: str = 'manual_in_source_fragment' # in-source fragment of another measured feature
|
|
43
|
+
MANUAL_DUPLICATE: str = 'manual_duplicate' # same compound as another measured feature (e.g. split peak)
|
|
44
|
+
MANUAL_ISOTOPE_PEAK: str = 'manual_isotope_peak' # isotope peak of another measured feature (the monoisotopic one)
|
|
45
|
+
MANUAL_ADDUCT: str = 'manual_adduct' # other adduct of the compound of another measured feature
|
|
46
|
+
ManualAnnotationKind = Literal['library', 'manual', 'in_source_fragment', 'duplicate', 'isotope', 'adduct']
|
|
47
|
+
MANUAL_ANNOTATION_PREFIXES: dict[ManualAnnotationKind, str] = {
|
|
48
|
+
'library': MANUAL_LIBRARY_ANNOTATION,
|
|
49
|
+
'manual': MANUAL_ANNOTATION,
|
|
50
|
+
'in_source_fragment': MANUAL_IN_SOURCE_FRAGMENT,
|
|
51
|
+
'duplicate': MANUAL_DUPLICATE,
|
|
52
|
+
'isotope': MANUAL_ISOTOPE_PEAK,
|
|
53
|
+
'adduct': MANUAL_ADDUCT,
|
|
54
|
+
}
|
|
55
|
+
# kinds that relate a measured feature to another one (the reference feature): name of the annotation
|
|
56
|
+
FEATURE_RELATION_NAMES: dict[ManualAnnotationKind, str] = {
|
|
57
|
+
'in_source_fragment': 'in-source fragment of {}',
|
|
58
|
+
'duplicate': 'duplicate of {}',
|
|
59
|
+
'isotope': 'isotope peak of {}',
|
|
60
|
+
'adduct': 'adduct of {}',
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
# indexes used when loading spectra (index=True in the models, names as generated by SQLAlchemy), databases created
|
|
64
|
+
# before can get them with FeatureManagerDB.create_missing_indexes: {index name: (table, column)}
|
|
65
|
+
SPECTRA_INDEXES: dict[str, tuple[str, str]] = {
|
|
66
|
+
'ix_peak_peak_list_id': ('peak', 'peak_list_id'),
|
|
67
|
+
'ix_ms_spec_feature_mgf_id': ('ms_spec', 'feature_mgf_id'),
|
|
68
|
+
'ix_mgf_features_feature_id': ('mgf_features', 'feature_id'),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@contextmanager
|
|
73
|
+
def gc_paused():
|
|
74
|
+
"""
|
|
75
|
+
Pause the cyclic garbage collector while building millions of objects (spectra, dicts of libraries): its full
|
|
76
|
+
collections get longer with every object and hold the GIL, which freezes a GUI running this in a worker thread.
|
|
77
|
+
"""
|
|
78
|
+
was_enabled: bool = gc.isenabled()
|
|
79
|
+
gc.disable()
|
|
80
|
+
try:
|
|
81
|
+
yield
|
|
82
|
+
finally:
|
|
83
|
+
if was_enabled:
|
|
84
|
+
gc.enable()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def eager_options_for(cls, strategy="selectin", maxdepth=10, seen=None):
|
|
88
|
+
""" Build loader options to eagerly load all relationships on cls up to
|
|
89
|
+
maxdepth.
|
|
90
|
+
strategy: "selectin" (good default) or "joined".
|
|
91
|
+
"""
|
|
92
|
+
if seen is None:
|
|
93
|
+
seen = set()
|
|
94
|
+
|
|
95
|
+
opts = []
|
|
96
|
+
mapper = inspect(cls)
|
|
97
|
+
for rel in mapper.relationships:
|
|
98
|
+
# Skip if already visited this path (prevents cycles via backrefs)
|
|
99
|
+
key = (mapper.class_, rel.key)
|
|
100
|
+
if (key in seen) or key[1].startswith('combined'):
|
|
101
|
+
continue
|
|
102
|
+
seen_add = seen | {key}
|
|
103
|
+
# Choose loader
|
|
104
|
+
loader_fn = selectinload if strategy == "selectin" else joinedload
|
|
105
|
+
loader = loader_fn(getattr(mapper.class_, rel.key))
|
|
106
|
+
|
|
107
|
+
# Recurse into target mapper
|
|
108
|
+
if maxdepth > 1:
|
|
109
|
+
subopts = eager_options_for(rel.mapper.class_, strategy=strategy, maxdepth=maxdepth - 1, seen=seen_add)
|
|
110
|
+
if subopts:
|
|
111
|
+
loader = loader.options(*subopts)
|
|
112
|
+
|
|
113
|
+
opts.append(loader)
|
|
114
|
+
return opts
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class FeatureManagerDB:
|
|
118
|
+
"""
|
|
119
|
+
Object for accessing and modifying a DB created with a ProjectImportManager
|
|
120
|
+
instance
|
|
121
|
+
"""
|
|
122
|
+
path_file: str = None
|
|
123
|
+
_mzs_sorted: np.ndarray[float] = None
|
|
124
|
+
_f_ids_sorted: np.ndarray[int] = None
|
|
125
|
+
|
|
126
|
+
def __init__(self, path_file_db: str):
|
|
127
|
+
if not os.path.exists(path_file_db):
|
|
128
|
+
raise FileNotFoundError(f"File {path_file_db} does not exist!")
|
|
129
|
+
self.path_file: str = path_file_db
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def session_maker(self) -> 'session_maker':
|
|
133
|
+
_Session = get_sessionmaker(self.path_file)
|
|
134
|
+
return _Session
|
|
135
|
+
|
|
136
|
+
def get_feature(self, feature_id: int) -> FeatureCombined:
|
|
137
|
+
feature_id = int(feature_id)
|
|
138
|
+
|
|
139
|
+
opts = eager_options_for(FeatureCombined, strategy="selectin")
|
|
140
|
+
|
|
141
|
+
with self.session_maker() as session:
|
|
142
|
+
obj = session.execute(
|
|
143
|
+
select(FeatureCombined)
|
|
144
|
+
.where(FeatureCombined.feature_id == feature_id)
|
|
145
|
+
.options(*opts)
|
|
146
|
+
).unique().scalar_one()
|
|
147
|
+
return obj
|
|
148
|
+
|
|
149
|
+
def get_value_from_table_for_feature_id(
|
|
150
|
+
self,
|
|
151
|
+
feature_id: int,
|
|
152
|
+
column_name: str,
|
|
153
|
+
table_name: str
|
|
154
|
+
):
|
|
155
|
+
with self.session_maker() as session:
|
|
156
|
+
return session.execute(
|
|
157
|
+
text(f"SELECT {column_name} FROM {table_name} WHERE feature_id = :feature_id"),
|
|
158
|
+
{"feature_id": feature_id},
|
|
159
|
+
).scalar_one()
|
|
160
|
+
|
|
161
|
+
def _get_all_attributes_from(self, obj) -> list:
|
|
162
|
+
with self.session_maker() as session:
|
|
163
|
+
attrs = session.execute(select(obj)).scalars().all()
|
|
164
|
+
return attrs
|
|
165
|
+
|
|
166
|
+
@cached_property
|
|
167
|
+
def feature_ids(self) -> list[int]:
|
|
168
|
+
return self._get_all_attributes_from(FeatureCombined.feature_id)
|
|
169
|
+
|
|
170
|
+
@cached_property
|
|
171
|
+
def mzs(self) -> dict[int, float]:
|
|
172
|
+
return self._get_dict_for_attributes(FeatureMetaboScape, 'mz_meas')
|
|
173
|
+
|
|
174
|
+
def get_missing_indexes(self) -> dict[str, tuple[str, str]]:
|
|
175
|
+
"""
|
|
176
|
+
Indexes that speed up loading spectra but don't exist in the database (databases created before they were
|
|
177
|
+
added to the models): {index name: (table, column)}.
|
|
178
|
+
"""
|
|
179
|
+
missing: dict[str, tuple[str, str]] = {}
|
|
180
|
+
with self.session_maker() as session:
|
|
181
|
+
connection = session.connection()
|
|
182
|
+
for name, (table, column) in SPECTRA_INDEXES.items():
|
|
183
|
+
indexed_columns = {
|
|
184
|
+
connection.exec_driver_sql(f'PRAGMA index_info("{index[1]}")').fetchone()[2]
|
|
185
|
+
for index in connection.exec_driver_sql(f'PRAGMA index_list("{table}")').fetchall()
|
|
186
|
+
}
|
|
187
|
+
if column not in indexed_columns:
|
|
188
|
+
missing[name] = (table, column)
|
|
189
|
+
return missing
|
|
190
|
+
|
|
191
|
+
def create_missing_indexes(self):
|
|
192
|
+
"""Create the missing indexes (once per database, takes a while and some space for large libraries)."""
|
|
193
|
+
with self.session_maker() as session:
|
|
194
|
+
connection = session.connection()
|
|
195
|
+
for name, (table, column) in self.get_missing_indexes().items():
|
|
196
|
+
connection.exec_driver_sql(f'CREATE INDEX IF NOT EXISTS {name} ON "{table}" ("{column}")')
|
|
197
|
+
session.commit()
|
|
198
|
+
|
|
199
|
+
def _fetch_row_chunks(self, stmt, chunk_size: int = 50_000) -> Iterator[list[tuple]]:
|
|
200
|
+
"""
|
|
201
|
+
Execute a select statement with the plain database cursor (SQLAlchemy's row processing is about 5 times
|
|
202
|
+
slower, which matters for libraries with millions of rows) and yield the rows in chunks.
|
|
203
|
+
|
|
204
|
+
Processing millions of rows in one C call (fetchall, dict(rows)) holds the GIL for seconds, which freezes
|
|
205
|
+
a GUI running this in a worker thread, chunks give other threads a chance in between.
|
|
206
|
+
"""
|
|
207
|
+
with self.session_maker() as session:
|
|
208
|
+
connection = session.connection()
|
|
209
|
+
sql = str(stmt.compile(dialect=connection.dialect, compile_kwargs={'literal_binds': True}))
|
|
210
|
+
cursor = connection.connection.cursor().execute(sql)
|
|
211
|
+
while chunk := cursor.fetchmany(chunk_size):
|
|
212
|
+
yield chunk
|
|
213
|
+
|
|
214
|
+
def _fetch_rows(self, stmt) -> list[tuple]:
|
|
215
|
+
rows: list[tuple] = []
|
|
216
|
+
for chunk in self._fetch_row_chunks(stmt):
|
|
217
|
+
rows.extend(chunk)
|
|
218
|
+
return rows
|
|
219
|
+
|
|
220
|
+
def _get_dict_for_attributes(self, parent_obj, attr) -> dict:
|
|
221
|
+
# one query for ids and values, so they are guaranteed to belong together
|
|
222
|
+
values: dict = {}
|
|
223
|
+
with gc_paused():
|
|
224
|
+
for chunk in self._fetch_row_chunks(select(getattr(parent_obj, 'feature_id'), getattr(parent_obj, attr))):
|
|
225
|
+
values.update(chunk)
|
|
226
|
+
return values
|
|
227
|
+
|
|
228
|
+
def get_all_attributes_from(
|
|
229
|
+
self,
|
|
230
|
+
parent_obj,
|
|
231
|
+
attr_name: str,
|
|
232
|
+
missing_value=None,
|
|
233
|
+
add_missing_values: bool = False
|
|
234
|
+
) -> dict[int, Any]:
|
|
235
|
+
d = self._get_dict_for_attributes(parent_obj, attr_name)
|
|
236
|
+
if add_missing_values:
|
|
237
|
+
missing_features = set(self.feature_ids) - set(d.keys())
|
|
238
|
+
for f in missing_features:
|
|
239
|
+
d[f] = missing_value
|
|
240
|
+
return d
|
|
241
|
+
|
|
242
|
+
@cached_property
|
|
243
|
+
def molecular_mass(self) -> dict[int, float]:
|
|
244
|
+
return self._get_dict_for_attributes(FeatureMetaboScape, 'M_metaboscape')
|
|
245
|
+
|
|
246
|
+
@cached_property
|
|
247
|
+
def retention_times_in_seconds(self):
|
|
248
|
+
return self._get_dict_for_attributes(FeatureMetaboScape, 'rt_seconds')
|
|
249
|
+
|
|
250
|
+
@cached_property
|
|
251
|
+
def collisional_cross_sections(self):
|
|
252
|
+
return self._get_dict_for_attributes(FeatureMetaboScape, 'CCS')
|
|
253
|
+
|
|
254
|
+
@cached_property
|
|
255
|
+
def summed_intensities(self) -> dict[int, float]:
|
|
256
|
+
"""Sum of the intensities of each feature over all samples (features without intensities are missing)."""
|
|
257
|
+
stmt = select(Intensity.feature_id, func.sum(Intensity.value)).group_by(Intensity.feature_id)
|
|
258
|
+
with self.session_maker() as session:
|
|
259
|
+
return dict(session.execute(stmt).all())
|
|
260
|
+
|
|
261
|
+
@cached_property
|
|
262
|
+
def formula_metaboscape(self):
|
|
263
|
+
return self._get_dict_for_attributes(
|
|
264
|
+
FeatureMetaboScape, 'formula_metaboscape'
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
@cached_property
|
|
268
|
+
def formula_sirius(self):
|
|
269
|
+
stmt = (
|
|
270
|
+
select(FormulaCandidate).filter(FormulaCandidate.formula_rank == 1)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
with self.session_maker() as session:
|
|
274
|
+
objs = session.execute(stmt).scalars().all()
|
|
275
|
+
formulas = {}
|
|
276
|
+
for o in objs:
|
|
277
|
+
formulas[o.feature_id] = o.formula_sirius
|
|
278
|
+
return formulas
|
|
279
|
+
|
|
280
|
+
@cached_property
|
|
281
|
+
def name_sirius(self):
|
|
282
|
+
"""
|
|
283
|
+
Returns dict mapping feature id to a sirius name based on the best formula. If there is no name for the
|
|
284
|
+
highest scoring formula, None will be assigned to that feature."""
|
|
285
|
+
stmt = (
|
|
286
|
+
select(CompoundCandidate).filter(CompoundCandidate.formula_rank == 1)
|
|
287
|
+
)
|
|
288
|
+
names = {}
|
|
289
|
+
with self.session_maker() as session:
|
|
290
|
+
objs = session.execute(stmt).scalars().all()
|
|
291
|
+
for o in objs:
|
|
292
|
+
names[o.feature_id] = o.name_sirius
|
|
293
|
+
return names
|
|
294
|
+
|
|
295
|
+
@cached_property
|
|
296
|
+
def names_metaboscape(self) -> dict[int, str]:
|
|
297
|
+
return self.get_all_attributes_from(FeatureMetaboScape, 'name_metaboscape')
|
|
298
|
+
|
|
299
|
+
def _set_sorted_mzs(self):
|
|
300
|
+
_mzs: np.ndarray[float] = np.asarray(list(self.mzs.values()))
|
|
301
|
+
o = np.argsort(_mzs)
|
|
302
|
+
self._mzs_sorted = _mzs[o]
|
|
303
|
+
self._f_ids_sorted: np.ndarray[int] = np.asarray(list(self.mzs.keys()))[o]
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def f_ids_sorted(self) -> np.ndarray[int]:
|
|
307
|
+
if self._f_ids_sorted is None:
|
|
308
|
+
self._set_sorted_mzs()
|
|
309
|
+
return self._f_ids_sorted
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def mzs_sorted(self) -> np.ndarray[float]:
|
|
313
|
+
if self._mzs_sorted is None:
|
|
314
|
+
self._set_sorted_mzs()
|
|
315
|
+
return self._mzs_sorted
|
|
316
|
+
|
|
317
|
+
def find_matches_precursor(
|
|
318
|
+
self,
|
|
319
|
+
mzs: Iterable[float],
|
|
320
|
+
max_dmz_da: float = None,
|
|
321
|
+
max_dmz_ppm: float | int = None,
|
|
322
|
+
f_ids = None,
|
|
323
|
+
) -> list[list[int]]:
|
|
324
|
+
"""Returns the matched feature ids"""
|
|
325
|
+
assert (max_dmz_da is not None) or (max_dmz_ppm is not None), \
|
|
326
|
+
'provide either max_dmz_mda or max_dmz_ppm'
|
|
327
|
+
|
|
328
|
+
mzs = np.asarray(mzs)
|
|
329
|
+
|
|
330
|
+
# convert tolerances to Da, if both is provided, select the stricter one
|
|
331
|
+
if max_dmz_da is None:
|
|
332
|
+
max_dmz_da = mzs * (max_dmz_ppm * 1e-6)
|
|
333
|
+
elif (max_dmz_da is not None) and (max_dmz_ppm is not None):
|
|
334
|
+
max_dmz_da_from_ppm: np.ndarray = mzs * (max_dmz_ppm * 1e-6)
|
|
335
|
+
max_dmz_da_from_abs = np.full_like(mzs, max_dmz_da)
|
|
336
|
+
max_dmz_da = np.array([rel if rel < ab else ab for rel, ab in zip(max_dmz_da_from_ppm, max_dmz_da_from_abs)])
|
|
337
|
+
|
|
338
|
+
# get all features that match the mz within the tolerance
|
|
339
|
+
idcs_left = np.searchsorted(self.mzs_sorted, mzs - max_dmz_da, side='right')
|
|
340
|
+
idcs_right = np.searchsorted(self.mzs_sorted, mzs + max_dmz_da, side='right')
|
|
341
|
+
|
|
342
|
+
f_ids_match: list[np.ndarray[int]] = [
|
|
343
|
+
self.f_ids_sorted[idx_left:idx_right]
|
|
344
|
+
for idx_left, idx_right in zip(idcs_left, idcs_right)
|
|
345
|
+
]
|
|
346
|
+
|
|
347
|
+
# convert types, restricted to the given feature ids (a set: "in" on an array scans all library features)
|
|
348
|
+
if f_ids is None:
|
|
349
|
+
return [[int(f_id) for f_id in _f_ids] for _f_ids in f_ids_match]
|
|
350
|
+
f_ids = set(f_ids)
|
|
351
|
+
return [[int(f_id) for f_id in _f_ids if f_id in f_ids] for _f_ids in f_ids_match]
|
|
352
|
+
|
|
353
|
+
def add_neutral_losses(
|
|
354
|
+
self,
|
|
355
|
+
max_spectra_per_query: int = 5_000,
|
|
356
|
+
check_neutral_Losses_present = True
|
|
357
|
+
):
|
|
358
|
+
"""Add neutral losses to peak table: mz - mz_pre (results in negative masses which are easy to filter out)"""
|
|
359
|
+
feature_ids = self.feature_ids.copy()
|
|
360
|
+
|
|
361
|
+
feature_id_chunks: list[list[int]] = [
|
|
362
|
+
feature_ids[i:i + max_spectra_per_query]
|
|
363
|
+
for i in range(0, len(feature_ids), max_spectra_per_query)
|
|
364
|
+
]
|
|
365
|
+
|
|
366
|
+
with self.session_maker() as session:
|
|
367
|
+
# spectrum by spectrum
|
|
368
|
+
for chunk_index, feature_id_chunk in enumerate(feature_id_chunks):
|
|
369
|
+
stmt = (
|
|
370
|
+
select(FeatureMgf.feature_id, PeakList)
|
|
371
|
+
.select_from(MsSpec)
|
|
372
|
+
.join(MsSpec.feature_mgf)
|
|
373
|
+
.join(MsSpec.peaks)
|
|
374
|
+
.options(selectinload(PeakList.peaks))
|
|
375
|
+
.where(
|
|
376
|
+
FeatureMgf.feature_id.in_(feature_id_chunk),
|
|
377
|
+
MsSpec.ms_level == 2,
|
|
378
|
+
MsSpec.peaks_id.is_not(None),
|
|
379
|
+
)
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
# each tuple contains the feature id and peak list
|
|
383
|
+
peak_lists: list[tuple[int, PeakList]] = session.execute(stmt).all()
|
|
384
|
+
for f_id, peak_list in tqdm(
|
|
385
|
+
peak_lists,
|
|
386
|
+
desc=f'adding neutral losses (chunk {chunk_index + 1}/{len(feature_id_chunks)})',
|
|
387
|
+
total=len(peak_lists)
|
|
388
|
+
):
|
|
389
|
+
mz_pre = self.mzs[f_id]
|
|
390
|
+
for peak in list(peak_list.peaks): # create a copy
|
|
391
|
+
if (dmz:= (peak.mz - mz_pre)) > 0: # exclude isotope peaks
|
|
392
|
+
continue
|
|
393
|
+
if check_neutral_Losses_present and peak.mz < 0:
|
|
394
|
+
raise ValueError(f'Encountered negative peak m/z. This indicates that neutral losses have already been added.')
|
|
395
|
+
peak_loss = PeakFeature(
|
|
396
|
+
mz=dmz,
|
|
397
|
+
rt=peak.rt,
|
|
398
|
+
ccs=peak.ccs,
|
|
399
|
+
# annotation is different, so dont copy it
|
|
400
|
+
intensity=peak.intensity,
|
|
401
|
+
height=peak.height,
|
|
402
|
+
area=peak.area,
|
|
403
|
+
fwhm=peak.fwhm,
|
|
404
|
+
snr=peak.snr,
|
|
405
|
+
M=peak.M,
|
|
406
|
+
adduct=peak.adduct
|
|
407
|
+
)
|
|
408
|
+
peak_list.peaks.append(peak_loss)
|
|
409
|
+
session.commit()
|
|
410
|
+
|
|
411
|
+
def filter_by_fragment_mz(self, fragment_mz: float, mz_tol_da: float, min_intensity: float = 100.):
|
|
412
|
+
# find feature ids that have an MS2 peak with mz in the tolerance
|
|
413
|
+
stmt = (
|
|
414
|
+
select(FeatureMgf.feature_id)
|
|
415
|
+
.select_from(MsSpec)
|
|
416
|
+
.join(MsSpec.feature_mgf)
|
|
417
|
+
.join(MsSpec.peaks)
|
|
418
|
+
.join(PeakList.peaks)
|
|
419
|
+
.where(
|
|
420
|
+
MsSpec.ms_level == 2,
|
|
421
|
+
PeakFeature.mz.between(fragment_mz - mz_tol_da, fragment_mz + mz_tol_da),
|
|
422
|
+
PeakFeature.intensity.between(min_intensity, float('inf'))
|
|
423
|
+
)
|
|
424
|
+
.distinct() # if multiple fragment peaks are in the tolerance
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
with self.session_maker() as session:
|
|
428
|
+
f_ids = session.execute(stmt).scalars().all()
|
|
429
|
+
return f_ids
|
|
430
|
+
|
|
431
|
+
def filter_by_neutral_loss(self, neutral_loss: float, mz_tol_da: float, min_intensity: float = 100.):
|
|
432
|
+
return self.filter_by_fragment_mz(-neutral_loss, mz_tol_da, min_intensity)
|
|
433
|
+
|
|
434
|
+
def _get_ms_spectra_limited_variable_number(
|
|
435
|
+
self,
|
|
436
|
+
feature_ids: list[int],
|
|
437
|
+
level: int,
|
|
438
|
+
mz_limits: tuple[float | None, float | None] = (None, None),
|
|
439
|
+
intensity_limits: tuple[float | None, float | None] = (None, None)
|
|
440
|
+
) -> dict[int, PeakList]:
|
|
441
|
+
if len(feature_ids) == 0:
|
|
442
|
+
return {}
|
|
443
|
+
|
|
444
|
+
# filter the peaks in the query, so that no objects are built for removed peaks
|
|
445
|
+
peak_conditions = [PeakFeature.peak_list_id == MsSpec.peaks_id]
|
|
446
|
+
for column, (lower, upper) in ((PeakFeature.mz, mz_limits), (PeakFeature.intensity, intensity_limits)):
|
|
447
|
+
if lower is not None and lower != -float('inf'):
|
|
448
|
+
peak_conditions.append(column >= lower)
|
|
449
|
+
if upper is not None and upper != float('inf'):
|
|
450
|
+
peak_conditions.append(column <= upper)
|
|
451
|
+
|
|
452
|
+
# plain rows of peaks instead of ORM objects (loading the objects is much slower)
|
|
453
|
+
stmt = (
|
|
454
|
+
select(FeatureMgf.feature_id, PeakFeature.mz, PeakFeature.intensity, PeakFeature.annotation)
|
|
455
|
+
.select_from(MsSpec)
|
|
456
|
+
.join(FeatureMgf, FeatureMgf.id == MsSpec.feature_mgf_id)
|
|
457
|
+
# outer join: spectra without peaks within the limits are returned empty
|
|
458
|
+
.outerjoin(PeakFeature, and_(*peak_conditions))
|
|
459
|
+
.where(
|
|
460
|
+
FeatureMgf.feature_id.in_(feature_ids),
|
|
461
|
+
MsSpec.ms_level == level,
|
|
462
|
+
MsSpec.peaks_id.is_not(None),
|
|
463
|
+
)
|
|
464
|
+
# keeps the order of the peaks in the spectra
|
|
465
|
+
.order_by(FeatureMgf.feature_id, PeakFeature.id)
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
spectra: dict[int, PeakList] = {}
|
|
469
|
+
with gc_paused():
|
|
470
|
+
rows = self._fetch_rows(stmt)
|
|
471
|
+
for feature_id, peaks in groupby(rows, key=lambda row: row[0]):
|
|
472
|
+
peaks = [peak for peak in peaks if peak[1] is not None] # empty spectrum: one row without peak
|
|
473
|
+
_, mzs, intensities, annotations = zip(*peaks) if peaks else ((), (), (), ())
|
|
474
|
+
spectra[feature_id] = PeakList(mzs=mzs, intensities=intensities, annotations=annotations)
|
|
475
|
+
return spectra
|
|
476
|
+
|
|
477
|
+
def get_ms_spectra(
|
|
478
|
+
self,
|
|
479
|
+
feature_ids: list[int],
|
|
480
|
+
level: int,
|
|
481
|
+
max_spectra_per_query: int = 20_000,
|
|
482
|
+
mz_limits: tuple = None,
|
|
483
|
+
intensity_limits: tuple = None
|
|
484
|
+
) -> dict[int, PeakList]:
|
|
485
|
+
level = int(level)
|
|
486
|
+
|
|
487
|
+
if mz_limits is None:
|
|
488
|
+
mz_limits = (0, float('inf'))
|
|
489
|
+
|
|
490
|
+
if level not in (1, 2):
|
|
491
|
+
raise ValueError("level must be 1 or 2")
|
|
492
|
+
|
|
493
|
+
# split feature_ids into chunks of max_spectra_per_query
|
|
494
|
+
feature_id_chunks: list[list[int]] = [
|
|
495
|
+
feature_ids[i:i + max_spectra_per_query]
|
|
496
|
+
for i in range(0, len(feature_ids), max_spectra_per_query)
|
|
497
|
+
]
|
|
498
|
+
|
|
499
|
+
out: dict[int, PeakList] = {}
|
|
500
|
+
n_chunks = len(feature_id_chunks)
|
|
501
|
+
for feature_id_chunk in tqdm(
|
|
502
|
+
feature_id_chunks,
|
|
503
|
+
desc=f'loading ms spectra for {len(feature_ids):_} features',
|
|
504
|
+
total=n_chunks,
|
|
505
|
+
disable=n_chunks < 2
|
|
506
|
+
):
|
|
507
|
+
# filters are applied in the query
|
|
508
|
+
out |= self._get_ms_spectra_limited_variable_number(
|
|
509
|
+
feature_id_chunk, level, mz_limits=mz_limits, intensity_limits=intensity_limits or (None, None)
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
return out
|
|
513
|
+
|
|
514
|
+
def get_ms_spectra_precursor_filtered(
|
|
515
|
+
self,
|
|
516
|
+
feature_ids: list[int],
|
|
517
|
+
level: int,
|
|
518
|
+
mz_precursor_window_da=4,
|
|
519
|
+
**kwargs
|
|
520
|
+
) -> dict[int, PeakList]:
|
|
521
|
+
assert 'mz_limits' not in kwargs, 'mz_limits should not be provided for precursor filtering, set the mz_precursor_window_da instead'
|
|
522
|
+
# query all and then filter, this is faster than querying for each feature individually
|
|
523
|
+
out = self.get_ms_spectra(feature_ids, level, **kwargs)
|
|
524
|
+
for f_id, peak_list in out.items():
|
|
525
|
+
precursor_mz = self.mzs[f_id]
|
|
526
|
+
if level == 2: # window defines tolerance around precursor mz
|
|
527
|
+
mz_limits = precursor_mz + mz_precursor_window_da, float('inf')
|
|
528
|
+
elif level == 1: # window defines upper window away from precursor mz
|
|
529
|
+
mz_limits = (precursor_mz - .5, precursor_mz + mz_precursor_window_da)
|
|
530
|
+
else:
|
|
531
|
+
raise ValueError(f'level must be 1 or 2, not {level}')
|
|
532
|
+
peak_list.filter(mz_limits=mz_limits, inplace=True)
|
|
533
|
+
return out
|
|
534
|
+
|
|
535
|
+
def get_ms_spectrum(self, feature_id: int, level: int, **kwargs) -> PeakList | None:
|
|
536
|
+
# fetch ms spectrum sql file for specified feature id and level (1 for isotope pattern, 2 for fragment spectrum)
|
|
537
|
+
return self.get_ms_spectra([feature_id], level, **kwargs).get(feature_id)
|
|
538
|
+
|
|
539
|
+
def set_peak_annotation(self, feature_id: int, level: int, mz: float, annotation: str | None) -> int:
|
|
540
|
+
"""
|
|
541
|
+
Set the annotation of the peak at mz (4 decimals) in the spectrum of a feature, None removes it.
|
|
542
|
+
Returns the number of changed peaks.
|
|
543
|
+
"""
|
|
544
|
+
with self.session_maker() as session:
|
|
545
|
+
peaks_ids = (
|
|
546
|
+
select(MsSpec.peaks_id)
|
|
547
|
+
.join(FeatureMgf, FeatureMgf.id == MsSpec.feature_mgf_id)
|
|
548
|
+
.where(FeatureMgf.feature_id == int(feature_id), MsSpec.ms_level == int(level))
|
|
549
|
+
)
|
|
550
|
+
result = session.execute(
|
|
551
|
+
PeakFeature.__table__.update()
|
|
552
|
+
.where(PeakFeature.peak_list_id.in_(peaks_ids), func.round(PeakFeature.mz, 4) == round(float(mz), 4))
|
|
553
|
+
.values(annotation=annotation)
|
|
554
|
+
)
|
|
555
|
+
session.commit()
|
|
556
|
+
return result.rowcount
|
|
557
|
+
|
|
558
|
+
def get_peak_annotations(self, level: int = 2) -> list[tuple[str, float, int]]:
|
|
559
|
+
"""
|
|
560
|
+
Distinct annotations of peaks (positive m/z) in the spectra of the given level:
|
|
561
|
+
(annotation, mean m/z, number of features), most frequent first.
|
|
562
|
+
"""
|
|
563
|
+
stmt = (
|
|
564
|
+
select(PeakFeature.annotation, func.avg(PeakFeature.mz), func.count(func.distinct(MsSpec.feature_mgf_id)))
|
|
565
|
+
.join(MsSpec, MsSpec.peaks_id == PeakFeature.peak_list_id)
|
|
566
|
+
.where(MsSpec.ms_level == int(level), PeakFeature.annotation.is_not(None), PeakFeature.annotation != '',
|
|
567
|
+
PeakFeature.mz > 0)
|
|
568
|
+
.group_by(PeakFeature.annotation)
|
|
569
|
+
.order_by(func.count(func.distinct(MsSpec.feature_mgf_id)).desc(), PeakFeature.annotation)
|
|
570
|
+
)
|
|
571
|
+
return self._fetch_rows(stmt)
|
|
572
|
+
|
|
573
|
+
def get_intensities(self, feature_id) -> dict[str, int]:
|
|
574
|
+
"""
|
|
575
|
+
Returns a dict mapping sample names to intensities for the given
|
|
576
|
+
feature id.
|
|
577
|
+
"""
|
|
578
|
+
stmt = (
|
|
579
|
+
select(Sample.sample_name, Intensity.value)
|
|
580
|
+
.join(Intensity, Intensity.sample_id == Sample.id)
|
|
581
|
+
.where(Intensity.feature_id == feature_id)
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
with self.session_maker() as session:
|
|
585
|
+
ints = session.execute(stmt).all()
|
|
586
|
+
return dict(ints)
|
|
587
|
+
|
|
588
|
+
def compare_features(self, f_id1: int, f_id2: int):
|
|
589
|
+
fig, axs = plt.subplots(nrows=4)
|
|
590
|
+
|
|
591
|
+
f_1 = self.get_feature(f_id1)
|
|
592
|
+
f_2 = self.get_feature(f_id2)
|
|
593
|
+
|
|
594
|
+
if f_1.mgf is None:
|
|
595
|
+
ms1 = {}
|
|
596
|
+
else:
|
|
597
|
+
ms1: dict[int, PeakList] = {ms_spec.ms_level: ms_spec.peaks for ms_spec in f_1.mgf.ms_specs}
|
|
598
|
+
if f_2.mgf is None:
|
|
599
|
+
ms2 = {}
|
|
600
|
+
else:
|
|
601
|
+
ms2: dict[int, PeakList] = {ms_spec.ms_level: ms_spec.peaks for ms_spec in f_2.mgf.ms_specs}
|
|
602
|
+
|
|
603
|
+
# MS/MS mirror plot
|
|
604
|
+
if 2 in ms1:
|
|
605
|
+
axs[0].stem(ms1[2].mzs, ms1[2].intensities, label=f_id1, markerfmt='', linefmt='C0-')
|
|
606
|
+
if 2 in ms2:
|
|
607
|
+
axs[0].stem(ms2[2].mzs, -np.asarray(ms2[2].intensities), label=f_id2, markerfmt='', linefmt='C1-')
|
|
608
|
+
axs[0].set_title('MS/MS spectra')
|
|
609
|
+
axs[0].legend()
|
|
610
|
+
axs[0].set_xlabel('m/z in Da')
|
|
611
|
+
|
|
612
|
+
# MS1 plot
|
|
613
|
+
if 1 in ms1:
|
|
614
|
+
axs[1].stem(np.asarray(ms1[1].mzs) - ms1[1].mzs[0],
|
|
615
|
+
np.asarray(ms1[1].intensities) / max(ms1[1].intensities),
|
|
616
|
+
label=f_id1, markerfmt='', linefmt='C0-')
|
|
617
|
+
if 1 in ms2:
|
|
618
|
+
axs[1].stem(np.asarray(ms2[1].mzs) - ms2[1].mzs[0], np.asarray(ms2[1].intensities) / max(ms2[1].intensities),
|
|
619
|
+
label=f_id2, markerfmt='', linefmt='C1--')
|
|
620
|
+
axs[1].set_title('To M0 shifted and 1-scaled MS1 spectra')
|
|
621
|
+
axs[1].legend()
|
|
622
|
+
axs[1].set_xlabel('m/z in Da')
|
|
623
|
+
|
|
624
|
+
# table with properties
|
|
625
|
+
def round_if_not_none(val, n_decimals=0):
|
|
626
|
+
if val is None:
|
|
627
|
+
return float('nan')
|
|
628
|
+
return round(val, n_decimals)
|
|
629
|
+
|
|
630
|
+
df = pd.DataFrame(dict(
|
|
631
|
+
rt_min=[round_if_not_none(f_1.metaboscape.rt_seconds / 60, 2), round_if_not_none(f_2.metaboscape.rt_seconds / 60, 2)],
|
|
632
|
+
ccs=[round_if_not_none(f_1.metaboscape.CCS, 1), round_if_not_none(f_2.metaboscape.CCS, 1)],
|
|
633
|
+
mz=[round_if_not_none(f_1.metaboscape.mz_meas, 4), round_if_not_none(f_2.metaboscape.mz_meas, 4)],
|
|
634
|
+
main_ion=[f_1.metaboscape.adduct, f_2.metaboscape.adduct],
|
|
635
|
+
M=[round_if_not_none(f_1.metaboscape.M_metaboscape, 4), round_if_not_none(f_2.metaboscape.M_metaboscape, 4)],
|
|
636
|
+
annotation=[f_1.metaboscape.name_metaboscape, f_2.metaboscape.name_metaboscape],
|
|
637
|
+
))
|
|
638
|
+
df.index = [f_id1, f_id2]
|
|
639
|
+
axs[2].axis("off")
|
|
640
|
+
pd.plotting.table(ax=axs[2], data=df.T, loc="center", cellLoc="center", edges='open')
|
|
641
|
+
|
|
642
|
+
# bar plot with intensities
|
|
643
|
+
ints1 = {i.sample.sample_name: i.value for i in f_1.metaboscape.intensities}
|
|
644
|
+
ints2 = {i.sample.sample_name: i.value for i in f_2.metaboscape.intensities}
|
|
645
|
+
if len(ints1) == 0 and len(ints2) == 0:
|
|
646
|
+
return fig, axs
|
|
647
|
+
df = pd.DataFrame(data=[ints1, ints2], index=[f_id1, f_id2]).T
|
|
648
|
+
|
|
649
|
+
df.plot.bar(rot=45, ax=axs[3])
|
|
650
|
+
axs[3].set_title('Intensities')
|
|
651
|
+
axs[3].legend()
|
|
652
|
+
|
|
653
|
+
return fig, axs
|
|
654
|
+
|
|
655
|
+
def find_objects_for_attr(self, attr_name: str) -> list[object]:
|
|
656
|
+
raise NotImplementedError()
|
|
657
|
+
|
|
658
|
+
def _append_compound_candidate(self, f_id_meas: int, compound_candidate: CompoundCandidate):
|
|
659
|
+
"""Add a compound candidate to a measured feature (creates the sirius entry of the feature if missing)."""
|
|
660
|
+
# cannot use get_feature because session needs to remain active
|
|
661
|
+
with self.session_maker() as session:
|
|
662
|
+
f_meas: FeatureCombined = session.execute(
|
|
663
|
+
select(FeatureCombined)
|
|
664
|
+
.where(FeatureCombined.feature_id == f_id_meas)
|
|
665
|
+
).unique().scalar_one()
|
|
666
|
+
# it is possible that this feature does not have a sirius annotation
|
|
667
|
+
if f_meas.sirius is None:
|
|
668
|
+
f_meas.sirius = FeatureSirius(feature_id=f_id_meas)
|
|
669
|
+
f_meas.sirius.compound_candidates.append(compound_candidate)
|
|
670
|
+
session.commit()
|
|
671
|
+
|
|
672
|
+
def add_annotations_from_library(
|
|
673
|
+
self,
|
|
674
|
+
library: "Library",
|
|
675
|
+
f_id_meas: int,
|
|
676
|
+
f_id_lib: int,
|
|
677
|
+
ms2_score: float = None
|
|
678
|
+
):
|
|
679
|
+
folder: str = f'{MANUAL_LIBRARY_ANNOTATION} from "{os.path.basename(library.path_file)}" for feature "{f_id_lib}"'
|
|
680
|
+
# feature ids of different libraries overlap, so the library is part of the check
|
|
681
|
+
if any(candidate.feature_id == f_id_meas and candidate.sirius_compound_folder == folder
|
|
682
|
+
for candidate in self.get_manual_annotations(kinds=['library'])):
|
|
683
|
+
warnings.warn(f'Measured feature with id {f_id_meas} has already been annotated with library feature {f_id_lib}.')
|
|
684
|
+
return
|
|
685
|
+
|
|
686
|
+
# add attributes from library match to measured feature
|
|
687
|
+
f_lib: FeatureCombined = library.get_feature(f_id_lib) # read only
|
|
688
|
+
compound_candidate_lib: CompoundCandidate = f_lib.sirius.compound_candidates[0]
|
|
689
|
+
self._append_compound_candidate(f_id_meas, CompoundCandidate(
|
|
690
|
+
num_adducts=1,
|
|
691
|
+
confidence_score=ms2_score,
|
|
692
|
+
adduct_sirius=f_lib.metaboscape.adduct_metaboscape,
|
|
693
|
+
formula_sirius=f_lib.metaboscape.formula_metaboscape,
|
|
694
|
+
name_sirius=compound_candidate_lib.name_sirius,
|
|
695
|
+
smiles=compound_candidate_lib.smiles,
|
|
696
|
+
inchi=compound_candidate_lib.inchi,
|
|
697
|
+
xlogp=compound_candidate_lib.xlogp,
|
|
698
|
+
sirius_compound_folder=folder
|
|
699
|
+
))
|
|
700
|
+
|
|
701
|
+
def add_manual_annotation(
|
|
702
|
+
self,
|
|
703
|
+
f_id_meas: int,
|
|
704
|
+
name: str,
|
|
705
|
+
formula: str = None,
|
|
706
|
+
adduct: str = None,
|
|
707
|
+
smiles: str = None
|
|
708
|
+
):
|
|
709
|
+
"""Annotate a measured feature with a compound entered by hand (e.g. built with the LipidCalculator GUI)."""
|
|
710
|
+
self._append_compound_candidate(f_id_meas, CompoundCandidate(
|
|
711
|
+
num_adducts=1,
|
|
712
|
+
name_sirius=name,
|
|
713
|
+
formula_sirius=formula,
|
|
714
|
+
adduct_sirius=adduct,
|
|
715
|
+
smiles=smiles,
|
|
716
|
+
sirius_compound_folder=MANUAL_ANNOTATION
|
|
717
|
+
))
|
|
718
|
+
|
|
719
|
+
def add_in_source_fragment_annotation(self, f_id_fragment: int, f_id_parent: int, note: str = None):
|
|
720
|
+
"""Annotate a measured feature as in-source fragment of another measured feature."""
|
|
721
|
+
self.add_feature_relation('in_source_fragment', f_id_fragment, f_id_parent, note=note)
|
|
722
|
+
|
|
723
|
+
def add_feature_relation(
|
|
724
|
+
self,
|
|
725
|
+
kind: ManualAnnotationKind,
|
|
726
|
+
f_id: int,
|
|
727
|
+
f_id_reference: int,
|
|
728
|
+
note: str = None,
|
|
729
|
+
adduct: str = None
|
|
730
|
+
):
|
|
731
|
+
"""
|
|
732
|
+
Annotate a measured feature as in-source fragment ('in_source_fragment'), duplicate ('duplicate'), isotope peak
|
|
733
|
+
('isotope') or other adduct ('adduct', adduct of this feature) of the reference feature (parent, original,
|
|
734
|
+
monoisotopic peak or feature of the main adduct). The relation is stored as compound candidate of the feature.
|
|
735
|
+
"""
|
|
736
|
+
if kind not in FEATURE_RELATION_NAMES:
|
|
737
|
+
raise ValueError(f'{kind} is not a relation between features, use one of {list(FEATURE_RELATION_NAMES)}')
|
|
738
|
+
self._append_compound_candidate(f_id, CompoundCandidate(
|
|
739
|
+
name_sirius=FEATURE_RELATION_NAMES[kind].format(f_id_reference) + (f' ({note})' if note else ''),
|
|
740
|
+
adduct_sirius=adduct,
|
|
741
|
+
sirius_compound_folder=f'{MANUAL_ANNOTATION_PREFIXES[kind]} of feature "{f_id_reference}"'
|
|
742
|
+
))
|
|
743
|
+
|
|
744
|
+
def plot_scatter(
|
|
745
|
+
self,
|
|
746
|
+
add_annotations: bool = False,
|
|
747
|
+
highlight_features: Iterable[int] = None,
|
|
748
|
+
ax: plt.Axes = None
|
|
749
|
+
) -> plt.Axes:
|
|
750
|
+
if ax is None:
|
|
751
|
+
_, ax = plt.subplots()
|
|
752
|
+
|
|
753
|
+
if highlight_features is None:
|
|
754
|
+
highlight_features = []
|
|
755
|
+
else:
|
|
756
|
+
highlight_features = list(highlight_features)
|
|
757
|
+
|
|
758
|
+
mzs_wo_highlight = [
|
|
759
|
+
mz
|
|
760
|
+
for f_id, mz in self.mzs.items()
|
|
761
|
+
if f_id not in highlight_features
|
|
762
|
+
]
|
|
763
|
+
rts_wo_highlight = [
|
|
764
|
+
rt / 60
|
|
765
|
+
for f_id, rt in self.retention_times_in_seconds.items()
|
|
766
|
+
if f_id not in highlight_features
|
|
767
|
+
]
|
|
768
|
+
mzs_w_highlight = [
|
|
769
|
+
mz
|
|
770
|
+
for f_id, mz in self.mzs.items()
|
|
771
|
+
if f_id in highlight_features
|
|
772
|
+
]
|
|
773
|
+
rts_w_highlight = [
|
|
774
|
+
rt / 60
|
|
775
|
+
for f_id, rt in self.retention_times_in_seconds.items()
|
|
776
|
+
if f_id in highlight_features
|
|
777
|
+
]
|
|
778
|
+
|
|
779
|
+
ax.scatter(rts_wo_highlight, mzs_wo_highlight, c='blue', s=10, alpha=.5)
|
|
780
|
+
ax.scatter(rts_w_highlight, mzs_w_highlight, c='red', s=20)
|
|
781
|
+
# add annotations
|
|
782
|
+
if add_annotations:
|
|
783
|
+
# all information is in compound_candidate table
|
|
784
|
+
for cpd_candidate in self.get_manual_annotations():
|
|
785
|
+
f_id: int = cpd_candidate.feature_id
|
|
786
|
+
ax.annotate(
|
|
787
|
+
text=f'{cpd_candidate.name_sirius} {cpd_candidate.adduct_sirius}',
|
|
788
|
+
xy=(self.retention_times_in_seconds[f_id] / 60, self.mzs[f_id])
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
return ax
|
|
792
|
+
|
|
793
|
+
@staticmethod
|
|
794
|
+
def get_manual_annotation_kind(compound_candidate: CompoundCandidate) -> ManualAnnotationKind | None:
|
|
795
|
+
"""Kind of a manual annotation, identified by the prefix of sirius_compound_folder."""
|
|
796
|
+
folder: str = compound_candidate.sirius_compound_folder or ''
|
|
797
|
+
for kind, prefix in MANUAL_ANNOTATION_PREFIXES.items():
|
|
798
|
+
if folder.startswith(prefix):
|
|
799
|
+
return kind
|
|
800
|
+
return None
|
|
801
|
+
|
|
802
|
+
@staticmethod
|
|
803
|
+
def get_referenced_feature_id(compound_candidate: CompoundCandidate) -> int | None:
|
|
804
|
+
"""Library feature of a library annotation or reference feature of a relation (e.g. in-source fragment)."""
|
|
805
|
+
folder: str = compound_candidate.sirius_compound_folder or ''
|
|
806
|
+
if ' feature "' not in folder:
|
|
807
|
+
return None
|
|
808
|
+
return int(folder.split(' feature "')[1].strip('"'))
|
|
809
|
+
|
|
810
|
+
@staticmethod
|
|
811
|
+
def get_referenced_library(compound_candidate: CompoundCandidate) -> str | None:
|
|
812
|
+
"""File name of the library of a library annotation."""
|
|
813
|
+
folder: str = compound_candidate.sirius_compound_folder or ''
|
|
814
|
+
if ' from "' not in folder:
|
|
815
|
+
return None
|
|
816
|
+
return folder.split(' from "')[1].split('"')[0]
|
|
817
|
+
|
|
818
|
+
def get_manual_annotations(self, kinds: Iterable[ManualAnnotationKind] = None) -> list[CompoundCandidate]:
|
|
819
|
+
"""Manual annotations of the given kinds (default: all kinds)."""
|
|
820
|
+
prefixes = [MANUAL_ANNOTATION_PREFIXES[kind] for kind in (kinds or MANUAL_ANNOTATION_PREFIXES)]
|
|
821
|
+
with self.session_maker() as session:
|
|
822
|
+
opts = eager_options_for(CompoundCandidate, strategy="selectin", maxdepth=1)
|
|
823
|
+
cpd_candidates: list[CompoundCandidate] = (
|
|
824
|
+
session.query(CompoundCandidate)
|
|
825
|
+
.filter(or_(*(CompoundCandidate.sirius_compound_folder.startswith(p) for p in prefixes)))
|
|
826
|
+
.options(*opts)
|
|
827
|
+
.all()
|
|
828
|
+
)
|
|
829
|
+
return cpd_candidates
|
|
830
|
+
|
|
831
|
+
def delete_feature(self, feature_id: int) -> bool:
|
|
832
|
+
"""
|
|
833
|
+
Delete a feature with everything that belongs to it (MetaboScape, mgf, SIRIUS and GNPS entries, intensities,
|
|
834
|
+
spectra with their peaks, formula and compound candidates). Annotations of other features that refer to it
|
|
835
|
+
(e.g. in-source fragments) are kept. Returns False if there is no feature with this id.
|
|
836
|
+
"""
|
|
837
|
+
from msIO.features.gnps import FeatureGnpsNode
|
|
838
|
+
from msIO.features.sirius import CompoundGroup
|
|
839
|
+
|
|
840
|
+
feature_id = int(feature_id)
|
|
841
|
+
with self.session_maker() as session:
|
|
842
|
+
combined_ids = session.execute(
|
|
843
|
+
select(FeatureCombined.id).where(FeatureCombined.feature_id == feature_id)).scalars().all()
|
|
844
|
+
if not combined_ids:
|
|
845
|
+
return False
|
|
846
|
+
|
|
847
|
+
def ids_of(column, *where) -> list:
|
|
848
|
+
return [i for i in session.execute(select(column).where(*where)).scalars().all() if i is not None]
|
|
849
|
+
|
|
850
|
+
def delete(model, *where):
|
|
851
|
+
session.execute(model.__table__.delete().where(*where))
|
|
852
|
+
|
|
853
|
+
# sub-features are linked by the id of the combined feature, their children by the feature id
|
|
854
|
+
metaboscape_f_ids = ids_of(FeatureMetaboScape.feature_id,
|
|
855
|
+
FeatureMetaboScape.combined_feature_id.in_(combined_ids))
|
|
856
|
+
sirius_f_ids = ids_of(FeatureSirius.feature_id, FeatureSirius.combined_feature_id.in_(combined_ids))
|
|
857
|
+
mgf_ids = ids_of(FeatureMgf.id, FeatureMgf.combined_feature_id.in_(combined_ids))
|
|
858
|
+
peak_list_ids = set(ids_of(MsSpec.peaks_id, MsSpec.feature_mgf_id.in_(mgf_ids)))
|
|
859
|
+
peak_list_ids |= set(ids_of(FeatureMgf.ms1_id, FeatureMgf.id.in_(mgf_ids)))
|
|
860
|
+
peak_list_ids |= set(ids_of(FeatureMgf.ms2_id, FeatureMgf.id.in_(mgf_ids)))
|
|
861
|
+
|
|
862
|
+
delete(Intensity, Intensity.feature_id.in_(metaboscape_f_ids))
|
|
863
|
+
for model in (FormulaCandidate, CompoundCandidate, CompoundGroup):
|
|
864
|
+
delete(model, model.feature_id.in_(sirius_f_ids))
|
|
865
|
+
delete(MsSpec, MsSpec.feature_mgf_id.in_(mgf_ids))
|
|
866
|
+
delete(PeakFeature, PeakFeature.peak_list_id.in_(peak_list_ids))
|
|
867
|
+
delete(PeakList, PeakList.id.in_(peak_list_ids))
|
|
868
|
+
for model in (FeatureMetaboScape, FeatureSirius, FeatureMgf, FeatureGnpsNode):
|
|
869
|
+
delete(model, model.combined_feature_id.in_(combined_ids))
|
|
870
|
+
delete(FeatureCombined, FeatureCombined.id.in_(combined_ids))
|
|
871
|
+
session.commit()
|
|
872
|
+
|
|
873
|
+
# cached values (feature ids, m/z, ...) are computed again when needed
|
|
874
|
+
for cls in type(self).__mro__:
|
|
875
|
+
for name, attr in vars(cls).items():
|
|
876
|
+
if isinstance(attr, cached_property):
|
|
877
|
+
self.__dict__.pop(name, None)
|
|
878
|
+
self._mzs_sorted = self._f_ids_sorted = None
|
|
879
|
+
return True
|
|
880
|
+
|
|
881
|
+
def remove_annotations_by_id(self, compound_candidate_ids: Iterable[int]):
|
|
882
|
+
"""Delete manual annotations by the ids of their compound candidates."""
|
|
883
|
+
with self.session_maker() as session:
|
|
884
|
+
session.query(CompoundCandidate).filter(
|
|
885
|
+
CompoundCandidate.id.in_(list(compound_candidate_ids))
|
|
886
|
+
).delete(synchronize_session=False)
|
|
887
|
+
session.commit()
|
|
888
|
+
|
|
889
|
+
def remove_annotation(self, f_id_meas, f_id_lib):
|
|
890
|
+
ids_to_remove = [
|
|
891
|
+
cp_id
|
|
892
|
+
for cp_id, (f_id_meas_, f_id_lib_) in self.get_f_ids_manual_annotations().items()
|
|
893
|
+
if (f_id_meas == f_id_meas_) and (f_id_lib == f_id_lib_)
|
|
894
|
+
]
|
|
895
|
+
|
|
896
|
+
with self.session_maker() as session:
|
|
897
|
+
session.query(CompoundCandidate).filter(CompoundCandidate.id.in_(ids_to_remove)).delete(synchronize_session=False)
|
|
898
|
+
session.commit()
|
|
899
|
+
|
|
900
|
+
def get_f_ids_manual_annotations(self):
|
|
901
|
+
# dictionary mapping the compound candidate ids to a tuple of feature_id_meas, feature_id_lib
|
|
902
|
+
f_ids: dict[int, tuple[int, int]] = {}
|
|
903
|
+
for cpd_candidate in self.get_manual_annotations(kinds=['library']):
|
|
904
|
+
f_id_meas = cpd_candidate.feature_id
|
|
905
|
+
f_id_lib = int(cpd_candidate.sirius_compound_folder.split('for feature ')[1].strip('"'))
|
|
906
|
+
f_ids[cpd_candidate.id] = (f_id_meas, f_id_lib)
|
|
907
|
+
return f_ids
|
|
908
|
+
|
|
909
|
+
class Library(FeatureManagerDB):
|
|
910
|
+
"""
|
|
911
|
+
This class is not intended to be structured like this longterm. This is
|
|
912
|
+
merely necessary because the current architecture is used for turning msp
|
|
913
|
+
libraries into sql files.
|
|
914
|
+
"""
|
|
915
|
+
|
|
916
|
+
@cached_property
|
|
917
|
+
def names(self) -> dict[int, str]:
|
|
918
|
+
# several candidates of a feature: the last one wins, as before
|
|
919
|
+
return self._get_dict_for_attributes(CompoundCandidate, 'name_sirius')
|
|
920
|
+
|
|
921
|
+
@cached_property
|
|
922
|
+
def smiles(self) -> dict[int, str]:
|
|
923
|
+
return self.get_all_attributes_from(CompoundCandidate, 'smiles')
|
|
924
|
+
|
|
925
|
+
@cached_property
|
|
926
|
+
def inchis(self) -> dict[int, str]:
|
|
927
|
+
return self.get_all_attributes_from(CompoundCandidate, 'inchi')
|
|
928
|
+
|
|
929
|
+
@cached_property
|
|
930
|
+
def adduct(self) -> dict[int, str]:
|
|
931
|
+
return self.get_all_attributes_from(FeatureMetaboScape, 'adduct_metaboscape')
|
|
932
|
+
|
|
933
|
+
@cached_property
|
|
934
|
+
def xlogp(self) -> dict[int, float]:
|
|
935
|
+
"""logP of the compounds, entries without one are missing."""
|
|
936
|
+
return {f_id: value for f_id, value in self._get_dict_for_attributes(CompoundCandidate, 'xlogp').items()
|
|
937
|
+
if value is not None}
|
|
938
|
+
|
|
939
|
+
def formula_sirius(self):
|
|
940
|
+
raise NotImplementedError()
|
|
941
|
+
|
|
942
|
+
def name_sirius(self):
|
|
943
|
+
raise NotImplementedError()
|
|
944
|
+
|
|
945
|
+
def get_values_for_feature(self, feature_id) -> dict[str, Any]:
|
|
946
|
+
out = {}
|
|
947
|
+
table_to_vals = {
|
|
948
|
+
'metaboscape_features': ['rt_seconds', 'CCS', 'mz_meas', 'adduct_metaboscape', 'formula_metaboscape', 'annotation_source', 'annotation_type'],
|
|
949
|
+
'compound_candidate': ['name_sirius', 'xlogp', 'inchi', 'smiles']
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
with self.session_maker() as session:
|
|
953
|
+
for table_name, col_names in table_to_vals.items():
|
|
954
|
+
out |= dict(zip(col_names, session.execute(
|
|
955
|
+
text(f"SELECT {', '.join(col_names)} FROM {table_name} WHERE feature_id = :feature_id"),
|
|
956
|
+
{"feature_id": feature_id},
|
|
957
|
+
).one()))
|
|
958
|
+
return out
|
|
959
|
+
|
|
960
|
+
def find_by_name(self, name: str, case_sensitive: bool = False, substring: bool = False) -> list[int]:
|
|
961
|
+
"""Return a list of feature ids with names matching the criteria."""
|
|
962
|
+
t_name = lambda n: n if case_sensitive else n.lower()
|
|
963
|
+
cpr_f = lambda a, b: a in b if substring else a == b
|
|
964
|
+
name_l = t_name(name)
|
|
965
|
+
return [f_id for f_id, name in self.names.items() if cpr_f(name_l, t_name(name))]
|
|
966
|
+
|
|
967
|
+
def find_matches(
|
|
968
|
+
self,
|
|
969
|
+
mzs: Iterable[float] | dict[int, float],
|
|
970
|
+
max_dmz_da: float = None,
|
|
971
|
+
max_dmz_ppm: float | int = None,
|
|
972
|
+
ms2_spectra: Iterable[PeakList | None] | dict[int, PeakList | None] = None,
|
|
973
|
+
max_ms2_dmz_da: float = 10e-3,
|
|
974
|
+
min_ms2_score: float | None = 0.7,
|
|
975
|
+
metric: Callable[[PeakList | None, PeakList | None], float] | Literal['cosine_fwd', 'cosine_bwd', 'cosine_sim', 'modified_cosine_greedy'] = 'cosine_sim',
|
|
976
|
+
return_nhits_ms2: bool = False,
|
|
977
|
+
require_ms2: bool = False,
|
|
978
|
+
progress_callback: Callable[[int, int], None] = None,
|
|
979
|
+
):
|
|
980
|
+
"""
|
|
981
|
+
Find matches in the library for a list of provided m/z values. Optionally, also require MS2 matches.
|
|
982
|
+
|
|
983
|
+
progress_callback(n_done, n_total) is called after scoring the matches of each m/z value (e.g. for a
|
|
984
|
+
progress bar in a GUI).
|
|
985
|
+
"""
|
|
986
|
+
assert (max_dmz_da is not None) or (max_dmz_ppm is not None), \
|
|
987
|
+
'provide either max_dmz_mda or max_dmz_ppm (but not both)'
|
|
988
|
+
if (as_dicts := isinstance(mzs, dict)) and (ms2_spectra is not None) and (not isinstance(ms2_spectra, dict)):
|
|
989
|
+
raise ValueError('If mzs are provided as dict, ms2 must also be a dict')
|
|
990
|
+
|
|
991
|
+
if as_dicts:
|
|
992
|
+
mz_ids: list[int] = list(mzs.keys())
|
|
993
|
+
mzs: list[float] = list(mzs.values())
|
|
994
|
+
if ms2_spectra is not None:
|
|
995
|
+
ms2_spectra: list[PeakList | None] = [ms2_spectra.get(f_id) for f_id in mz_ids]
|
|
996
|
+
else:
|
|
997
|
+
assert len(ms2_spectra) == len(mzs), \
|
|
998
|
+
'ms2 and mzs must have the same length (can set ms2 to None for some mzs, if not available)'
|
|
999
|
+
mz_ids = None
|
|
1000
|
+
|
|
1001
|
+
logger.info(f'finding precursor matches')
|
|
1002
|
+
matched_f_ids: list[list[int]] = self.find_matches_precursor(
|
|
1003
|
+
mzs=mzs, max_dmz_da=max_dmz_da, max_dmz_ppm=max_dmz_ppm
|
|
1004
|
+
)
|
|
1005
|
+
logger.info(f'found matches for {sum(1 for mchs in matched_f_ids if len(mchs) > 0):_} features')
|
|
1006
|
+
|
|
1007
|
+
# no ms2 spectra provided, so we can not score them
|
|
1008
|
+
if ms2_spectra is None:
|
|
1009
|
+
if as_dicts:
|
|
1010
|
+
out = {mz_id: matches_per_meas for mz_id, matches_per_meas in zip(mz_ids, matched_f_ids) if
|
|
1011
|
+
len(matches_per_meas) > 0}
|
|
1012
|
+
return out
|
|
1013
|
+
else:
|
|
1014
|
+
return matched_f_ids
|
|
1015
|
+
|
|
1016
|
+
if isinstance(metric, str):
|
|
1017
|
+
if metric == 'cosine_sim':
|
|
1018
|
+
metric = cosine_similarity_sym
|
|
1019
|
+
elif metric == 'cosine_fwd':
|
|
1020
|
+
metric = cosine_similarity_forward
|
|
1021
|
+
elif metric == 'cosine_backward':
|
|
1022
|
+
metric = cosine_similarity_backward
|
|
1023
|
+
elif metric == 'modified_cosine_greedy':
|
|
1024
|
+
# need to convert to matchms SpectrumType, each spectrum only once (a measured spectrum is
|
|
1025
|
+
# compared to all its library matches, a library spectrum to all measured features it matches)
|
|
1026
|
+
matchms_spectra: dict[int, Any] = {}
|
|
1027
|
+
|
|
1028
|
+
def to_matchms(spectrum: PeakList, precursor_mz: float):
|
|
1029
|
+
if (key := id(spectrum)) not in matchms_spectra: # spectra stay alive during the search
|
|
1030
|
+
matchms_spectra[key] = peaklist_to_spectrum(spectrum, precursor_mz=precursor_mz)
|
|
1031
|
+
return matchms_spectra[key]
|
|
1032
|
+
|
|
1033
|
+
def metric(a, b, max_dmz_da, return_nhits):
|
|
1034
|
+
# a: library spectrum, b: measured spectrum (see call below)
|
|
1035
|
+
if (a is None) or (b is None):
|
|
1036
|
+
return float('nan'), 0 if return_nhits else float('nan'),
|
|
1037
|
+
sim = ModifiedCosineGreedy(tolerance=max_dmz_da, intensity_power=.5)
|
|
1038
|
+
sa = to_matchms(a, precursor_mz=mz_lib)
|
|
1039
|
+
sb = to_matchms(b, precursor_mz=mz_meas)
|
|
1040
|
+
res = sim.pair(sa, sb)
|
|
1041
|
+
if return_nhits:
|
|
1042
|
+
return res['score'], res['matches']
|
|
1043
|
+
return res['score'],
|
|
1044
|
+
else:
|
|
1045
|
+
raise ValueError(f'Unknown metric {metric}')
|
|
1046
|
+
|
|
1047
|
+
# fetch ms2 spectra of library matches
|
|
1048
|
+
matched_f_ids_raveled: set[int] = set()
|
|
1049
|
+
for _f_ids_matched_precursor in matched_f_ids:
|
|
1050
|
+
matched_f_ids_raveled.update(_f_ids_matched_precursor)
|
|
1051
|
+
|
|
1052
|
+
logger.info(f'loading lib ms2 spectra for {len(matched_f_ids_raveled):_} features')
|
|
1053
|
+
matched_ms2_spectra_lib: dict[int, PeakList] = self.get_ms_spectra(list(matched_f_ids_raveled), level=2)
|
|
1054
|
+
|
|
1055
|
+
ann_libs: dict[int, str] = self._get_dict_for_attributes(FeatureMetaboScape, 'annotation_type')
|
|
1056
|
+
|
|
1057
|
+
# assign scores
|
|
1058
|
+
# ms2_scores: list[list[float]] = []
|
|
1059
|
+
# matched_f_ids_filtered: list[list[int]] = []
|
|
1060
|
+
matches: list[list[dict]] = []
|
|
1061
|
+
for idx, (mz_meas, ms2_measured, f_id_libs) in enumerate(tqdm(
|
|
1062
|
+
zip(mzs, ms2_spectra, matched_f_ids),
|
|
1063
|
+
desc='assigning ms2 scores',
|
|
1064
|
+
total=len(mzs)
|
|
1065
|
+
)):
|
|
1066
|
+
if progress_callback is not None:
|
|
1067
|
+
progress_callback(idx, len(mzs))
|
|
1068
|
+
matches_per_meas: list[dict] = []
|
|
1069
|
+
for f_id_lib in f_id_libs:
|
|
1070
|
+
mz_lib = self.mzs[f_id_lib]
|
|
1071
|
+
ms2_score, *n_hits_ms2 = metric(
|
|
1072
|
+
matched_ms2_spectra_lib.get(f_id_lib), ms2_measured, max_ms2_dmz_da, return_nhits=return_nhits_ms2
|
|
1073
|
+
)
|
|
1074
|
+
# only add the entry if ms2 is not required or score is above the threshold
|
|
1075
|
+
if (require_ms2 and np.isnan(ms2_score)) or (ms2_score < min_ms2_score):
|
|
1076
|
+
continue
|
|
1077
|
+
|
|
1078
|
+
match: dict = dict(
|
|
1079
|
+
feature_id=f_id_lib,
|
|
1080
|
+
name=self.names.get(f_id_lib),
|
|
1081
|
+
formula=self.formula_metaboscape.get(f_id_lib),
|
|
1082
|
+
adduct=self.adduct.get(f_id_lib),
|
|
1083
|
+
ms2_score=ms2_score,
|
|
1084
|
+
dmz_mda= (dmz := (mz_meas - mz_lib)) * 1e3,
|
|
1085
|
+
dmz_ppm= dmz / mz_lib * 1e6,
|
|
1086
|
+
source_library=ann_libs.get(f_id_lib, 'unknown'),
|
|
1087
|
+
)
|
|
1088
|
+
if return_nhits_ms2:
|
|
1089
|
+
match['n_hits_ms2'] = n_hits_ms2[0]
|
|
1090
|
+
matches_per_meas.append(match)
|
|
1091
|
+
|
|
1092
|
+
matches.append(matches_per_meas)
|
|
1093
|
+
|
|
1094
|
+
if progress_callback is not None:
|
|
1095
|
+
progress_callback(len(mzs), len(mzs))
|
|
1096
|
+
if as_dicts:
|
|
1097
|
+
out = {mz_id: matches_per_meas for mz_id, matches_per_meas in zip(mz_ids, matches) if len(matches_per_meas) > 0}
|
|
1098
|
+
return out
|
|
1099
|
+
return matches
|
|
1100
|
+
|
|
1101
|
+
def plot_compound_overview(self, f_id, axs: tuple[plt.Axes, plt.Axes] = None, kwargs_mplot=None, **kwargs):
|
|
1102
|
+
if axs is None:
|
|
1103
|
+
_, axs = plt.subplots(nrows=2)
|
|
1104
|
+
|
|
1105
|
+
props = self.get_values_for_feature(f_id)
|
|
1106
|
+
|
|
1107
|
+
if (s:= props['smiles']) is not None:
|
|
1108
|
+
mol = Chem.MolFromSmiles(s)
|
|
1109
|
+
elif (i := props['inchi']) is not None:
|
|
1110
|
+
mol = Chem.MolFromInchi(i)
|
|
1111
|
+
else:
|
|
1112
|
+
mol = Chem.Mol()
|
|
1113
|
+
if kwargs_mplot is None:
|
|
1114
|
+
kwargs_mplot = {}
|
|
1115
|
+
mplt_mol(mol=mol, ax=axs[0], **kwargs_mplot)
|
|
1116
|
+
axs[0].set_title(f'feature id: {f_id}, name: {props['name_sirius']}, adduct: {props['adduct_metaboscape']}\nmz: {props['mz_meas']:.4f} Da, formula: {props['formula_metaboscape']}')
|
|
1117
|
+
ms2: PeakList = self.get_ms_spectrum(f_id, level=2)
|
|
1118
|
+
ms2.plot(ax=axs[1], normalize_intensities=True, **kwargs)
|
|
1119
|
+
return axs
|
|
1120
|
+
|
|
1121
|
+
def plot_match(
|
|
1122
|
+
self,
|
|
1123
|
+
f_id_lib: int,
|
|
1124
|
+
meas: FeatureManagerDB,
|
|
1125
|
+
f_id_meas: int,
|
|
1126
|
+
mz_tol_da: float = None,
|
|
1127
|
+
match_result: dict = None,
|
|
1128
|
+
annotation_relative_cutoff: float = .3,
|
|
1129
|
+
fig=None,
|
|
1130
|
+
**kwargs
|
|
1131
|
+
):
|
|
1132
|
+
if match_result is None:
|
|
1133
|
+
match_result = {}
|
|
1134
|
+
|
|
1135
|
+
if fig is None:
|
|
1136
|
+
fig = plt.figure(figsize=(15, 15))
|
|
1137
|
+
|
|
1138
|
+
gs = GridSpec(
|
|
1139
|
+
3, 2,
|
|
1140
|
+
figure=fig,
|
|
1141
|
+
width_ratios=[1, 2 / 3], # right column is 2/3 as wide
|
|
1142
|
+
height_ratios=[1, 1, 1],
|
|
1143
|
+
hspace=0.3,
|
|
1144
|
+
wspace=0.25
|
|
1145
|
+
)
|
|
1146
|
+
|
|
1147
|
+
# Top row
|
|
1148
|
+
ax1 = fig.add_subplot(gs[0, 0])
|
|
1149
|
+
ax2 = fig.add_subplot(gs[0, 1])
|
|
1150
|
+
|
|
1151
|
+
# Middle row spans both columns
|
|
1152
|
+
ax3 = fig.add_subplot(gs[1, :])
|
|
1153
|
+
|
|
1154
|
+
# Bottom row
|
|
1155
|
+
ax4 = fig.add_subplot(gs[2, 0])
|
|
1156
|
+
ax5 = fig.add_subplot(gs[2, 1])
|
|
1157
|
+
axs = (ax1, ax2, ax3, ax4, ax5)
|
|
1158
|
+
|
|
1159
|
+
# first plot: compound structure
|
|
1160
|
+
# and second plot: ms2 spectrum
|
|
1161
|
+
self.plot_compound_overview(f_id_lib, axs=(ax1, ax3), annotation_relative_cutoff=annotation_relative_cutoff)
|
|
1162
|
+
ax1.set_title('')
|
|
1163
|
+
# add measured as mirror
|
|
1164
|
+
|
|
1165
|
+
# color according to match type
|
|
1166
|
+
ax3.set_title(f'MS2 score: {round(float(match_result.get('ms2_score', -1)), 3)} ({match_result.get('n_hits_ms2')} peaks matched)')
|
|
1167
|
+
ms2_measured: PeakList = meas.get_ms_spectrum(f_id_meas, level=2)
|
|
1168
|
+
if ms2_measured is not None:
|
|
1169
|
+
# scale to library
|
|
1170
|
+
ms2_measured.plot(
|
|
1171
|
+
ax=ax3,
|
|
1172
|
+
as_mirror=True,
|
|
1173
|
+
normalize_intensities=True,
|
|
1174
|
+
annotation_relative_cutoff=annotation_relative_cutoff, linefmt='C1'
|
|
1175
|
+
)
|
|
1176
|
+
|
|
1177
|
+
props: dict[str, Any] = self.get_values_for_feature(f_id_lib)
|
|
1178
|
+
formula = props['formula_metaboscape']
|
|
1179
|
+
adduct = props['adduct_metaboscape']
|
|
1180
|
+
M = CompoundDict(formula).mass
|
|
1181
|
+
mz_theo = Adduct(adduct).mass_to_mz(M)
|
|
1182
|
+
|
|
1183
|
+
prop_cols = ['Name', 'Formula', 'Adduct', 'M / Da', 'RT / min', 'CCS / A2', 'logP', 'Database']
|
|
1184
|
+
ann_props = pd.DataFrame(
|
|
1185
|
+
columns=[''],
|
|
1186
|
+
index=prop_cols,
|
|
1187
|
+
data=[''] * len(prop_cols)
|
|
1188
|
+
)
|
|
1189
|
+
# compound information
|
|
1190
|
+
ann_props.at['Name', ''] = props['name_sirius']
|
|
1191
|
+
ann_props.at['Formula', ''] = formula
|
|
1192
|
+
ann_props.at['Adduct', ''] = adduct
|
|
1193
|
+
ann_props.at['M / Da', ''] = str(round(M, 4))
|
|
1194
|
+
CCS = props['CCS']
|
|
1195
|
+
ann_props.at['CCS / A2', ''] = str(round(CCS, 2)) if CCS is not None else ''
|
|
1196
|
+
ann_props.at['logP', ''] = str(round(props['xlogp'], 3)) if props['xlogp'] is not None else ''
|
|
1197
|
+
ann_props.at['Database', ''] = props['annotation_type']
|
|
1198
|
+
|
|
1199
|
+
import textwrap
|
|
1200
|
+
|
|
1201
|
+
for col in ann_props.columns:
|
|
1202
|
+
ann_props[col] = ann_props[col].astype(str).map(
|
|
1203
|
+
lambda x: "\n".join(textwrap.wrap(x, width=25))
|
|
1204
|
+
)
|
|
1205
|
+
|
|
1206
|
+
ax2.axis("off")
|
|
1207
|
+
pd.plotting.table(ax=ax2, data=ann_props, loc="center", cellLoc="left", edges='open')
|
|
1208
|
+
|
|
1209
|
+
# third plot: theoretical and measured MS1:
|
|
1210
|
+
ax4.set_title('MS1 mirror plot')
|
|
1211
|
+
ms1_measured: PeakList = meas.get_ms_spectrum(f_id_meas, level=1)
|
|
1212
|
+
|
|
1213
|
+
if ms1_measured is not None:
|
|
1214
|
+
mzs = np.array(ms1_measured.mzs)
|
|
1215
|
+
ints = np.array(ms1_measured.intensities)
|
|
1216
|
+
mask = (mzs > mz_theo - .1) & (mzs < mz_theo + (CompoundDict('C[13]') - CompoundDict('C')).mass * 4 + .1)
|
|
1217
|
+
ms1_measured = PeakList(mzs=mzs[mask], intensities=ints[mask])
|
|
1218
|
+
|
|
1219
|
+
ms1_measured.plot(
|
|
1220
|
+
ax=ax4,
|
|
1221
|
+
as_mirror=True,
|
|
1222
|
+
normalize_intensities=True,
|
|
1223
|
+
annotation_relative_cutoff=annotation_relative_cutoff,
|
|
1224
|
+
linefmt='C1'
|
|
1225
|
+
)
|
|
1226
|
+
|
|
1227
|
+
ms1_theo: IsotopePattern = IsotopePattern.from_formula(
|
|
1228
|
+
formula=formula,
|
|
1229
|
+
adduct=adduct,
|
|
1230
|
+
mass_accuracy=kwargs.pop('mass_accuracy', mz_tol_da),
|
|
1231
|
+
mass_resolution=kwargs.pop('mass_resolution', None),
|
|
1232
|
+
merge_method=kwargs.pop('merge_method', 'weighted_average')
|
|
1233
|
+
)
|
|
1234
|
+
ms1_theo: PeakList = PeakList(mzs=ms1_theo.masses, intensities=ms1_theo.intensities)
|
|
1235
|
+
ms1_theo.plot(ax=ax4, normalize_intensities=True, annotation_relative_cutoff=annotation_relative_cutoff, **kwargs)
|
|
1236
|
+
|
|
1237
|
+
ax4.legend(['measured', 'library'], loc='lower right')
|
|
1238
|
+
|
|
1239
|
+
# fourth plot: table with properties
|
|
1240
|
+
cpr = pd.DataFrame(columns=['library', 'measured', 'difference'], index=['feature id', 'm/z', 'RT / min', 'CCS / A2'])
|
|
1241
|
+
cpr.loc[:, :] = ''
|
|
1242
|
+
mz_meas = meas.mzs[f_id_meas]
|
|
1243
|
+
|
|
1244
|
+
cpr.at['feature id', 'library'] = f_id_lib
|
|
1245
|
+
cpr.at['feature id', 'measured'] = f_id_meas
|
|
1246
|
+
cpr.at['m/z', 'library'] = str(round(mz_theo, 4))
|
|
1247
|
+
cpr.at['m/z', 'measured'] = str(round(mz_meas, 4))
|
|
1248
|
+
dmz = mz_theo - meas.mzs[f_id_meas]
|
|
1249
|
+
cpr.at['m/z', 'difference'] = f'{round(dmz * 1e3, 1)} / mDa\n{round(dmz / mz_theo * 1e6, 1)} / ppm'
|
|
1250
|
+
if props['rt_seconds'] is not None:
|
|
1251
|
+
RT_min = round(props['rt_seconds'] / 60, 2)
|
|
1252
|
+
else:
|
|
1253
|
+
RT_min = ''
|
|
1254
|
+
cpr.at['RT / min', 'library'] = RT_min
|
|
1255
|
+
RT_meas_sec = meas.get_value_from_table_for_feature_id(f_id_meas, 'rt_seconds', 'metaboscape_features')
|
|
1256
|
+
cpr.at['RT / min', 'measured'] = round(RT_meas_sec / 60, 2)
|
|
1257
|
+
cpr.at['CCS / A2', 'library'] = CCS if CCS is not None else ''
|
|
1258
|
+
CCS_meas = meas.get_value_from_table_for_feature_id(f_id_meas, 'CCS', 'metaboscape_features')
|
|
1259
|
+
cpr.at['CCS / A2', 'measured'] = round(CCS_meas, 2)
|
|
1260
|
+
if CCS is not None:
|
|
1261
|
+
dCCS = (CCS - CCS_meas) / CCS
|
|
1262
|
+
cpr.at['CCS / A2', 'difference'] = f'{dCCS:.1%}'
|
|
1263
|
+
ax5.axis("off")
|
|
1264
|
+
pl_table2 = pd.plotting.table(ax=ax5, data=cpr, loc="center", cellLoc="left", edges='open')
|
|
1265
|
+
pl_table2.auto_set_font_size(False)
|
|
1266
|
+
pl_table2.set_fontsize(10)
|
|
1267
|
+
|
|
1268
|
+
fig.suptitle('')
|
|
1269
|
+
return axs
|
|
1270
|
+
|
|
1271
|
+
def compare_compounds(self, f_ids):
|
|
1272
|
+
fig, axs = plt.subplots(nrows=2, ncols=len(f_ids))
|
|
1273
|
+
|
|
1274
|
+
for i, f_id in enumerate(f_ids):
|
|
1275
|
+
self.plot_compound_overview(f_id, axs=axs[:, i])
|
|
1276
|
+
return fig, axs
|
|
1277
|
+
|
|
1278
|
+
def lib_match_result_to_table(results: dict) -> pd.DataFrame:
|
|
1279
|
+
series = []
|
|
1280
|
+
for f_id_meas, matches in results.items():
|
|
1281
|
+
for match in matches:
|
|
1282
|
+
series.append(pd.Series(name=f_id_meas, data=match))
|
|
1283
|
+
|
|
1284
|
+
match_table: pd.DataFrame = (
|
|
1285
|
+
pd.concat(series, axis=1).T
|
|
1286
|
+
.reset_index(drop=False, names='feature_id_meas')
|
|
1287
|
+
.rename(columns={'feature_id': 'feature_id_lib'})
|
|
1288
|
+
.astype({
|
|
1289
|
+
'feature_id_meas': int,
|
|
1290
|
+
'feature_id_lib': int,
|
|
1291
|
+
'ms2_score': float,
|
|
1292
|
+
'name': str,
|
|
1293
|
+
'formula': str,
|
|
1294
|
+
'dmz_mda': float,
|
|
1295
|
+
'dmz_ppm': float,
|
|
1296
|
+
'source_library': str,
|
|
1297
|
+
'n_hits_ms2': int}
|
|
1298
|
+
)
|
|
1299
|
+
.sort_values(by=['feature_id_meas', 'ms2_score'])
|
|
1300
|
+
)
|
|
1301
|
+
return match_table
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
if __name__ == '__main__':
|
|
1305
|
+
pass
|