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,128 @@
|
|
|
1
|
+
from functools import cached_property
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from sqlalchemy import Integer, Float, String, ForeignKey, Boolean
|
|
6
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
7
|
+
|
|
8
|
+
from msIO.environmental.sample import Sample
|
|
9
|
+
from msIO.features.base import FeatureBaseClass, SqlBaseClass
|
|
10
|
+
|
|
11
|
+
METABOSCAPE_CSV_RENAME_COLUMNS: dict[str, str] = {
|
|
12
|
+
'FEATURE_ID': 'feature_id',
|
|
13
|
+
'RT': 'rt_seconds',
|
|
14
|
+
'PEPMASS': 'M_metaboscape',
|
|
15
|
+
'CCS': 'CCS',
|
|
16
|
+
'SIGMA_SCORE': 'sigma_score',
|
|
17
|
+
'NAME_METABOSCAPE': 'name_metaboscape',
|
|
18
|
+
'MOLECULAR_FORMULA': 'formula_metaboscape',
|
|
19
|
+
'ADDUCT': 'adduct_metaboscape',
|
|
20
|
+
'KEGG': 'KEGG',
|
|
21
|
+
'CAS': 'CAS',
|
|
22
|
+
'm/z meas.': 'mz_meas',
|
|
23
|
+
'Ions': 'ion_types',
|
|
24
|
+
'Flags': 'flags',
|
|
25
|
+
'AQ': 'annotation_type',
|
|
26
|
+
'Annotation Source': 'annotation_source',
|
|
27
|
+
'Include': 'include_flag'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Intensity(SqlBaseClass, FeatureBaseClass):
|
|
32
|
+
__tablename__ = "intensities"
|
|
33
|
+
|
|
34
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
35
|
+
|
|
36
|
+
value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
37
|
+
|
|
38
|
+
feature_id: Mapped[int] = mapped_column(ForeignKey("metaboscape_features.feature_id"), nullable=False)
|
|
39
|
+
feature: Mapped["FeatureMetaboScape"] = relationship(back_populates="intensities")
|
|
40
|
+
|
|
41
|
+
sample_id: Mapped[int] = mapped_column(ForeignKey("samples.id", ondelete="CASCADE"), nullable=False)
|
|
42
|
+
sample: Mapped["Sample"] = relationship("Sample", back_populates="intensities")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class FeatureMetaboScape(SqlBaseClass, FeatureBaseClass):
|
|
46
|
+
"""Container for features living in the exported feature table from MetaboScape"""
|
|
47
|
+
__tablename__ = "metaboscape_features"
|
|
48
|
+
# __allow_unmapped__ = True
|
|
49
|
+
|
|
50
|
+
# TODO: define Annotation objects
|
|
51
|
+
|
|
52
|
+
id: Mapped[int] = mapped_column(primary_key=True) # include only if not inherited
|
|
53
|
+
feature_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
54
|
+
rt_seconds: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
55
|
+
M_metaboscape: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
56
|
+
CCS: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
57
|
+
sigma_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
58
|
+
# msms_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
59
|
+
name_metaboscape: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
60
|
+
formula_metaboscape: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
61
|
+
adduct_metaboscape: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
62
|
+
KEGG: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
63
|
+
CAS: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
64
|
+
mz_meas: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
65
|
+
flags: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
66
|
+
annotation_type: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
67
|
+
annotation_source: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
68
|
+
include_flag: Mapped[bool] = mapped_column(Boolean, nullable=True)
|
|
69
|
+
|
|
70
|
+
intensities: Mapped[list[Intensity]] = relationship(
|
|
71
|
+
back_populates="feature",
|
|
72
|
+
cascade="all, delete-orphan"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
combined_feature_id: Mapped[Optional[int]] = mapped_column(ForeignKey('features.id'))
|
|
76
|
+
combined_feature: Mapped[Optional["FeatureCombined"]] = relationship(back_populates='metaboscape')
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def from_dataframe_row(cls, ser: pd.Series, sample_name_to_sample: dict[str, Sample]):
|
|
80
|
+
processed = {'intensities': []}
|
|
81
|
+
|
|
82
|
+
for k, v in ser.items():
|
|
83
|
+
if k.endswith('MaxIntensity') or k.endswith('MeanIntensity'):
|
|
84
|
+
continue
|
|
85
|
+
if ((k not in METABOSCAPE_CSV_RENAME_COLUMNS.keys())
|
|
86
|
+
and (k not in METABOSCAPE_CSV_RENAME_COLUMNS.values())):
|
|
87
|
+
# print(f'column "{k}" could not be converted, assuming it contains intensities')
|
|
88
|
+
# set nan values to 0
|
|
89
|
+
if isinstance(v, str):
|
|
90
|
+
v = float(v)
|
|
91
|
+
v = 0. if not (v > 0) else float(v)
|
|
92
|
+
if k not in sample_name_to_sample:
|
|
93
|
+
sample_name_to_sample[k] = Sample(sample_name=k)
|
|
94
|
+
processed['intensities'].append(Intensity(sample=sample_name_to_sample[k], value=v))
|
|
95
|
+
else:
|
|
96
|
+
if k in METABOSCAPE_CSV_RENAME_COLUMNS.values():
|
|
97
|
+
k_new = k
|
|
98
|
+
else:
|
|
99
|
+
k_new = METABOSCAPE_CSV_RENAME_COLUMNS[k]
|
|
100
|
+
processed[k_new] = cls._convert_type(k_new, v)
|
|
101
|
+
return cls(**processed)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def from_metaboscape_api(cls, feature_table_api):
|
|
105
|
+
# TODO
|
|
106
|
+
...
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def M(self):
|
|
110
|
+
return self.M_metaboscape
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def formula(self):
|
|
114
|
+
return self.formula_metaboscape
|
|
115
|
+
|
|
116
|
+
@cached_property
|
|
117
|
+
def mz(self):
|
|
118
|
+
"""MetaboScape does not export mz values, so need to calculate mz from M and adduct (:"""
|
|
119
|
+
from LipidCalculator import Adduct
|
|
120
|
+
return Adduct(self.adduct).mass_to_mz(self.M)
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def adduct(self):
|
|
124
|
+
return self.adduct_metaboscape
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == '__main__':
|
|
128
|
+
pass
|
msIO/features/mgf.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from typing import Self, Optional
|
|
2
|
+
|
|
3
|
+
from enum import Enum as PyEnum
|
|
4
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
5
|
+
from sqlalchemy import ForeignKey, Boolean, String, Integer, Float
|
|
6
|
+
from sqlalchemy import Enum
|
|
7
|
+
|
|
8
|
+
from msIO.features.base import FeatureBaseClass, SqlBaseClass
|
|
9
|
+
from msIO.list_of_ions.base import PeakList
|
|
10
|
+
|
|
11
|
+
# select which ion is most likely (first in list)
|
|
12
|
+
ION_PREFERENCES = ['[M+H]+', '[M+Na]+', '[M+K]+', '[M+NH4]+', '[M]+', '[M+H+H]2+', '[M+H+H2]3+']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_ion_props(inpt: list[str]) -> dict:
|
|
16
|
+
"""Parse mgf entry"""
|
|
17
|
+
do_nothing = lambda x: x
|
|
18
|
+
keyword_to_label_and_conversion = {
|
|
19
|
+
'feature_id': ('feature_id', int),
|
|
20
|
+
'pepmass': ('mz', float),
|
|
21
|
+
'mslevel': ('ms_level', int),
|
|
22
|
+
'charge': ('charge', lambda c: int(c[-1] + c[:-1])), # e.g. 2- --> -2
|
|
23
|
+
'rtinminutes': ('rt_minutes', float),
|
|
24
|
+
'rtinseconds': ('rt_seconds', float),
|
|
25
|
+
'polarity': ('polarity', lambda p: p.lower()[:3]),
|
|
26
|
+
'ionmode': ('polarity', lambda p: p.lower()[:3]),
|
|
27
|
+
'ion': ('ion', do_nothing),
|
|
28
|
+
'adduct': ('ion', do_nothing),
|
|
29
|
+
'title': ('title', do_nothing),
|
|
30
|
+
'ccs': ('ccs', float),
|
|
31
|
+
'spectype': ('spectrum_type', do_nothing),
|
|
32
|
+
'collisionenergy': ('collision_energy', do_nothing),
|
|
33
|
+
'scans': ('num_scans', int),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
kwargs: dict[str, int | float | str] = {}
|
|
37
|
+
|
|
38
|
+
for line in inpt:
|
|
39
|
+
# e.g. CCS=350.07224 or PEPMASS=1821.95234
|
|
40
|
+
if '=' not in line: # peak list
|
|
41
|
+
continue
|
|
42
|
+
key, val = line.split('=', 1)
|
|
43
|
+
# strip whitespaces
|
|
44
|
+
key = key.strip().lower()
|
|
45
|
+
val = val.strip().strip('\n')
|
|
46
|
+
label, func = keyword_to_label_and_conversion.get(key, (key, do_nothing))
|
|
47
|
+
kwargs[label] = func(val)
|
|
48
|
+
return kwargs
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MsSpec(SqlBaseClass, FeatureBaseClass):
|
|
52
|
+
__tablename__ = "ms_spec"
|
|
53
|
+
|
|
54
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
55
|
+
|
|
56
|
+
mz: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
57
|
+
ms_level: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
58
|
+
charge: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
59
|
+
rt_seconds: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
60
|
+
ion: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
61
|
+
rt_minutes: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
62
|
+
|
|
63
|
+
peaks_id: Mapped[Optional[int]] = mapped_column(ForeignKey("peak_list.id"))
|
|
64
|
+
peaks: Mapped[Optional["PeakList"]] = relationship()
|
|
65
|
+
|
|
66
|
+
feature_mgf_id: Mapped[int] = mapped_column(ForeignKey("mgf_features.id"), nullable=False, index=True)
|
|
67
|
+
feature_mgf: Mapped["FeatureMgf"] = relationship(back_populates="ms_specs")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PolarityEnum(PyEnum):
|
|
71
|
+
POS = "pos"
|
|
72
|
+
NEG = "neg"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class FeatureMgf(SqlBaseClass, FeatureBaseClass):
|
|
76
|
+
"""Multiple entries can belong to a single feature id
|
|
77
|
+
(when deconvolution fails or when multiple adducts are found).
|
|
78
|
+
This object sets ambiguous parameters by choosing from the preferred ion
|
|
79
|
+
order"""
|
|
80
|
+
__tablename__ = "mgf_features"
|
|
81
|
+
|
|
82
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
83
|
+
feature_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
|
84
|
+
polarity: Mapped[Optional[str]] = mapped_column(
|
|
85
|
+
Enum("pos", "neg", name="polarity_enum"),
|
|
86
|
+
nullable=True
|
|
87
|
+
)
|
|
88
|
+
has_multiple_adducts: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
|
89
|
+
|
|
90
|
+
mz: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
91
|
+
charge: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
92
|
+
rt_seconds: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
93
|
+
ion: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
94
|
+
rt_minutes: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
95
|
+
|
|
96
|
+
ms1_id: Mapped[Optional[int]] = mapped_column(ForeignKey("peak_list.id"))
|
|
97
|
+
ms1: Mapped[Optional["PeakList"]] = relationship(foreign_keys=[ms1_id])
|
|
98
|
+
|
|
99
|
+
ms2_id: Mapped[Optional[int]] = mapped_column(ForeignKey("peak_list.id"))
|
|
100
|
+
ms2: Mapped[Optional["PeakList"]] = relationship(foreign_keys=[ms2_id])
|
|
101
|
+
|
|
102
|
+
ms_specs: Mapped[list["MsSpec"]] = relationship(
|
|
103
|
+
back_populates="feature_mgf", cascade="all, delete-orphan"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
combined_feature_id: Mapped[Optional[int]] = mapped_column(ForeignKey('features.id'))
|
|
107
|
+
combined_feature: Mapped[Optional["FeatureCombined"]] = relationship(back_populates='mgf')
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def from_lines(cls, inpt: list[str]) -> Self:
|
|
111
|
+
# filter out properties that are accepted by object
|
|
112
|
+
entries = {k: v for k, v in parse_ion_props(inpt) if k in cls.__annotations__}
|
|
113
|
+
return cls(**entries)
|
|
114
|
+
|
|
115
|
+
def __post_init__(self) -> None:
|
|
116
|
+
"""Set properties from preferred ion"""
|
|
117
|
+
if (self.ms_specs is None) or len(self.ms_specs) == 0:
|
|
118
|
+
self.has_multiple_adducts = False
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
adducts: dict[tuple[str, int], "MsSpec"] = {(msspec.ion, msspec.ms_level): msspec for msspec in self.ms_specs}
|
|
122
|
+
self.has_multiple_adducts = len(set([k[0] for k in adducts.keys()])) > 1
|
|
123
|
+
# on first pass, try to find adduct for which both levels exist
|
|
124
|
+
for add_pref in ION_PREFERENCES:
|
|
125
|
+
if ((add_pref, 2) in adducts) and ((add_pref, 1) in adducts):
|
|
126
|
+
key = (add_pref, 2) # prefer MS2
|
|
127
|
+
ms_pref = adducts[key]
|
|
128
|
+
break
|
|
129
|
+
else: # try to find just 1 level
|
|
130
|
+
for add_pref in ION_PREFERENCES:
|
|
131
|
+
# prefer MS2
|
|
132
|
+
if (key := (add_pref, 2)) in adducts:
|
|
133
|
+
ms_pref = adducts[key]
|
|
134
|
+
break
|
|
135
|
+
elif (key := (add_pref, 1)) in adducts:
|
|
136
|
+
ms_pref = adducts[key]
|
|
137
|
+
break
|
|
138
|
+
else:
|
|
139
|
+
# pick any of those that are there
|
|
140
|
+
key = list(adducts.keys())[0]
|
|
141
|
+
add_pref = key[0]
|
|
142
|
+
ms_pref = adducts[key]
|
|
143
|
+
|
|
144
|
+
update_props = ['ion', 'rt_seconds', 'rt_minutes', 'charge', 'mz']
|
|
145
|
+
self.__dict__ |= {k: v
|
|
146
|
+
for k, v in ms_pref.__dict__.items()
|
|
147
|
+
if k in update_props}
|
|
148
|
+
|
|
149
|
+
for level in [1, 2]:
|
|
150
|
+
if (k := (add_pref, level)) in adducts:
|
|
151
|
+
self.__setattr__(f'ms{level}', adducts[k].peaks)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test(path_mgf_sirius):
|
|
155
|
+
lines_ion = []
|
|
156
|
+
is_ion = False
|
|
157
|
+
with open(path_mgf_sirius, 'r') as f:
|
|
158
|
+
for line in f:
|
|
159
|
+
if line.startswith('BEGIN IONS'):
|
|
160
|
+
is_ion = True
|
|
161
|
+
elif line.startswith('END IONS'):
|
|
162
|
+
break
|
|
163
|
+
elif is_ion:
|
|
164
|
+
lines_ion.append(line)
|
|
165
|
+
|
|
166
|
+
f = FeatureMgf.from_lines(lines_ion)
|
|
167
|
+
return f
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
if __name__ == '__main__':
|
|
171
|
+
pass
|
msIO/features/sirius.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
from typing import Optional, Self
|
|
2
|
+
from sqlalchemy import ForeignKey, String, Float, Integer, Boolean
|
|
3
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from msIO.features.base import FeatureBaseClass, SqlBaseClass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class FormulaCandidate(SqlBaseClass, FeatureBaseClass):
|
|
12
|
+
__tablename__ = "formula_candidate"
|
|
13
|
+
|
|
14
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
15
|
+
formula_sirius: Mapped[str] = mapped_column(String, nullable=True)
|
|
16
|
+
formula_rank: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
17
|
+
adduct_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
18
|
+
zodiac_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
19
|
+
sirius_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
20
|
+
tree_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
21
|
+
isotope_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
22
|
+
num_explained_peaks: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
23
|
+
explained_intensity: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
24
|
+
median_mass_error_fragments_ppm: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
25
|
+
mass_error_precursor_ppm: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
26
|
+
lipid_class: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
27
|
+
rt_seconds: Mapped[Optional[float]] = mapped_column(Integer, nullable=True)
|
|
28
|
+
sirius_compound_folder: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
29
|
+
|
|
30
|
+
feature_id: Mapped[int] = mapped_column(ForeignKey("feature_sirius.feature_id"))
|
|
31
|
+
feature: Mapped["FeatureSirius"] = relationship(back_populates="formula_candidates")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CompoundCandidate(SqlBaseClass, FeatureBaseClass):
|
|
35
|
+
__tablename__ = "compound_candidate"
|
|
36
|
+
|
|
37
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
38
|
+
confidence_rank: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
39
|
+
structure_per_id_rank: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
40
|
+
formula_rank: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
41
|
+
num_adducts: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
42
|
+
num_predicted_fingerprints: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
43
|
+
confidence_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
44
|
+
finger_id_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
45
|
+
zodiac_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
46
|
+
sirius_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
47
|
+
formula_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
48
|
+
adduct_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
49
|
+
inchi: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
50
|
+
name_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
51
|
+
smiles: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
52
|
+
xlogp: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
53
|
+
rt_seconds: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
54
|
+
sirius_compound_folder: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
55
|
+
|
|
56
|
+
feature_id: Mapped[int] = mapped_column(ForeignKey("feature_sirius.feature_id"))
|
|
57
|
+
feature: Mapped["FeatureSirius"] = relationship(back_populates="compound_candidates")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CompoundGroup(SqlBaseClass, FeatureBaseClass):
|
|
61
|
+
__tablename__ = "compound_group"
|
|
62
|
+
|
|
63
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
64
|
+
sirius_compound_folder: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
65
|
+
formula_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
66
|
+
adduct_sirius: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
67
|
+
npc_pathway_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
68
|
+
npc_pathway_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
69
|
+
npc_superclass_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
70
|
+
npc_superclass_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
71
|
+
npc_class_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
72
|
+
npc_class_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
73
|
+
cf_most_specific_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
74
|
+
cf_most_specific_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
75
|
+
cf_level5_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
76
|
+
cf_level5_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
77
|
+
cf_subclass_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
78
|
+
cf_subclass_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
79
|
+
cf_class_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
80
|
+
cf_class_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
81
|
+
cf_superclass_name: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
82
|
+
cf_superclass_probability: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
|
83
|
+
cf_path: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
84
|
+
|
|
85
|
+
feature_id: Mapped[int] = mapped_column(ForeignKey("feature_sirius.feature_id"))
|
|
86
|
+
feature: Mapped["FeatureSirius"] = relationship(back_populates="compound_groups")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class FeatureSirius(SqlBaseClass, FeatureBaseClass):
|
|
90
|
+
__tablename__ = "feature_sirius"
|
|
91
|
+
|
|
92
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
93
|
+
feature_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
|
94
|
+
|
|
95
|
+
formula_candidates: Mapped[list[FormulaCandidate]] = relationship(
|
|
96
|
+
back_populates="feature",
|
|
97
|
+
cascade="all, delete-orphan"
|
|
98
|
+
)
|
|
99
|
+
compound_candidates: Mapped[list[CompoundCandidate]] = relationship(
|
|
100
|
+
back_populates="feature",
|
|
101
|
+
cascade="all, delete-orphan"
|
|
102
|
+
)
|
|
103
|
+
compound_groups: Mapped[list[CompoundGroup]] = relationship(
|
|
104
|
+
back_populates="feature",
|
|
105
|
+
cascade="all, delete-orphan"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
use_zodiac_scoring_for_best: Mapped[bool] = mapped_column(Boolean, default=True)
|
|
109
|
+
highest_scoring_formula: Mapped[Optional[String]] = mapped_column(String, nullable=True)
|
|
110
|
+
|
|
111
|
+
combined_feature_id: Mapped[Optional[int]] = mapped_column(ForeignKey('features.id'))
|
|
112
|
+
combined_feature: Mapped[Optional["FeatureCombined"]] = relationship(back_populates='sirius')
|
|
113
|
+
|
|
114
|
+
def __init__(self, use_zodiac_scoring_for_best: bool = True, **kwargs):
|
|
115
|
+
super().__init__(**kwargs)
|
|
116
|
+
# TODO: find better method to set default value
|
|
117
|
+
self.use_zodiac_scoring_for_best = use_zodiac_scoring_for_best
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def best_formula(self) -> str:
|
|
121
|
+
return self.formula_candidates_by_rank[min(self.formula_candidates_by_rank)].formula_sirius
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def formula_candidates_by_rank(self) -> dict[int, FormulaCandidate]:
|
|
125
|
+
return {fc.formula_rank: fc for fc in self.formula_candidates if fc.formula_rank is not None}
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def compound_candidates_by_formula(self) -> dict[str, CompoundCandidate]:
|
|
129
|
+
return {cc.formula_sirius: cc for cc in self.compound_candidates if cc.formula_sirius}
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def compound_groups_by_formula(self) -> dict[str, CompoundGroup]:
|
|
133
|
+
return {cg.formula_sirius: cg for cg in self.compound_groups if cg.formula_sirius}
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
def from_tables(cls, feature_id: int, tables: dict[str, pd.DataFrame]) -> Self:
|
|
137
|
+
def select_rows_by_feature(df: pd.DataFrame) -> pd.DataFrame:
|
|
138
|
+
mask = df.feature_id == feature_id
|
|
139
|
+
return df.loc[mask, :]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
formula_candidates = []
|
|
143
|
+
if 'formula_identifications' in tables:
|
|
144
|
+
sub_df = select_rows_by_feature(tables['formula_identifications'])
|
|
145
|
+
for _, row in sub_df.iterrows():
|
|
146
|
+
f = FormulaCandidate(**row.to_dict())
|
|
147
|
+
formula_candidates.append(f)
|
|
148
|
+
|
|
149
|
+
compound_candidates = []
|
|
150
|
+
if 'compound_identifications' in tables:
|
|
151
|
+
sub_df = select_rows_by_feature(tables['compound_identifications'])
|
|
152
|
+
for _, row in sub_df.iterrows():
|
|
153
|
+
f = CompoundCandidate(**row.to_dict())
|
|
154
|
+
compound_candidates.append(f)
|
|
155
|
+
# TODO: fill nan values, where possible
|
|
156
|
+
|
|
157
|
+
compound_groups = []
|
|
158
|
+
if 'canopus_formula_summary' in tables:
|
|
159
|
+
sub_df = select_rows_by_feature(tables['canopus_formula_summary'])
|
|
160
|
+
for _, row in sub_df.iterrows():
|
|
161
|
+
f = CompoundGroup(**row.to_dict())
|
|
162
|
+
compound_groups.append(f)
|
|
163
|
+
|
|
164
|
+
return cls(feature_id=feature_id,
|
|
165
|
+
formula_candidates=formula_candidates,
|
|
166
|
+
compound_candidates=compound_candidates,
|
|
167
|
+
compound_groups=compound_groups)
|
|
168
|
+
|
|
169
|
+
def _set_highest_scoring_formula(self):
|
|
170
|
+
scores: list[float] = [c.zodiac_score if self.use_zodiac_scoring_for_best else c.sirius_score
|
|
171
|
+
for c in self.formula_candidates]
|
|
172
|
+
idx = int(np.nanargmax(scores))
|
|
173
|
+
best_candidate = self.formula_candidates[idx]
|
|
174
|
+
self.highest_scoring_formula = best_candidate.formula_sirius
|
|
175
|
+
|
|
176
|
+
def get_highest_scoring(self, prefer_npc: bool = True) -> Self:
|
|
177
|
+
"""flatten attributes by taking properties from highest ranked formula,
|
|
178
|
+
returns new instance (shallow copy with added attributes)"""
|
|
179
|
+
def add_from_highest_scoring(obj) -> None:
|
|
180
|
+
new.__dict__ |= obj.__dict__
|
|
181
|
+
|
|
182
|
+
if self.highest_scoring_formula is None:
|
|
183
|
+
self._set_highest_scoring_formula()
|
|
184
|
+
|
|
185
|
+
new = self.__class__()
|
|
186
|
+
new.__dict__ |= self.__dict__
|
|
187
|
+
|
|
188
|
+
# add attributes of objects in reverse order of chain in inference as later attributes override previous ones
|
|
189
|
+
# find best for compound groups based on probability
|
|
190
|
+
candidates_compound_groups = [c for c in self.compound_groups
|
|
191
|
+
if c.formula_sirius == self.highest_scoring_formula]
|
|
192
|
+
if len(candidates_compound_groups) > 0:
|
|
193
|
+
# if there are multiple candidates, use the one with the highest probability
|
|
194
|
+
prob_attrs = [a for a in CompoundGroup.__annotations__.keys()
|
|
195
|
+
if a.endswith('probability') and not (a.startswith('npc') ^ prefer_npc)]
|
|
196
|
+
candidates_probabilities = [max([c.__getattribute__(a) for a in prob_attrs])
|
|
197
|
+
for c in candidates_compound_groups]
|
|
198
|
+
obj_idx = candidates_probabilities.index(max(candidates_probabilities))
|
|
199
|
+
add_from_highest_scoring(candidates_compound_groups[obj_idx])
|
|
200
|
+
|
|
201
|
+
candidates_compounds = [c for c in self.compound_candidates
|
|
202
|
+
if c.formula_sirius == self.highest_scoring_formula]
|
|
203
|
+
# find best candidate based on confidence score or sirius/zodiac score if all confidence scores are nan
|
|
204
|
+
if len(candidates_compounds) > 0:
|
|
205
|
+
if any([c.confidence_score > 0 for c in candidates_compounds]):
|
|
206
|
+
scores = [c.confidence_score for c in candidates_compounds]
|
|
207
|
+
elif self.use_zodiac_scoring_for_best:
|
|
208
|
+
scores = [c.zodiac_score for c in candidates_compounds]
|
|
209
|
+
else:
|
|
210
|
+
scores = [c.sirius_score for c in candidates_compounds]
|
|
211
|
+
idx = np.nanargmax(scores)
|
|
212
|
+
add_from_highest_scoring(candidates_compounds[idx])
|
|
213
|
+
|
|
214
|
+
candidates_formula = [c for c in self.formula_candidates
|
|
215
|
+
if c.formula_sirius == self.highest_scoring_formula]
|
|
216
|
+
# there should always be at least 1
|
|
217
|
+
scores = [c.zodiac_score
|
|
218
|
+
if self.use_zodiac_scoring_for_best
|
|
219
|
+
else c.sirius_score
|
|
220
|
+
for c in candidates_formula]
|
|
221
|
+
add_from_highest_scoring(candidates_formula[np.nanargmax(scores)])
|
|
222
|
+
|
|
223
|
+
return new
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
if __name__ == '__main__':
|
|
227
|
+
pass
|
|
228
|
+
|
msIO/features/util.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from typing import Callable
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def read_csv(file_csv: str, column_renamer: dict[str, str], hook: Callable = None, **kwargs):
|
|
7
|
+
"""Wrapper for pandas read_csv"""
|
|
8
|
+
if hook is None:
|
|
9
|
+
hook = lambda x: x
|
|
10
|
+
|
|
11
|
+
df = pd.read_csv(file_csv, **kwargs)
|
|
12
|
+
df.rename(columns=column_renamer, inplace=True)
|
|
13
|
+
return hook(df)
|
msIO/general.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import Integer, CheckConstraint, String
|
|
4
|
+
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
5
|
+
|
|
6
|
+
from msIO.features.base import SqlBaseClass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TimeStamp(SqlBaseClass):
|
|
10
|
+
__tablename__ = "times"
|
|
11
|
+
|
|
12
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
13
|
+
|
|
14
|
+
second: Mapped[Optional[int]] = mapped_column(
|
|
15
|
+
Integer,
|
|
16
|
+
CheckConstraint("second BETWEEN 0 AND 59"),
|
|
17
|
+
nullable=True)
|
|
18
|
+
minute: Mapped[Optional[int]] = mapped_column(
|
|
19
|
+
Integer,
|
|
20
|
+
CheckConstraint("minute BETWEEN 0 AND 59"),
|
|
21
|
+
nullable=True)
|
|
22
|
+
hour: Mapped[Optional[int]] = mapped_column(
|
|
23
|
+
Integer,
|
|
24
|
+
CheckConstraint("hour BETWEEN 0 AND 23"),
|
|
25
|
+
nullable=True)
|
|
26
|
+
|
|
27
|
+
time_zone: Mapped[Optional[str]] = mapped_column(
|
|
28
|
+
String, nullable=True)
|
|
29
|
+
|
|
30
|
+
day: Mapped[Optional[int]] = mapped_column(
|
|
31
|
+
Integer,
|
|
32
|
+
CheckConstraint("day BETWEEN 1 AND 31"),
|
|
33
|
+
nullable=True)
|
|
34
|
+
|
|
35
|
+
month: Mapped[Optional[int]] = mapped_column(
|
|
36
|
+
Integer,
|
|
37
|
+
CheckConstraint("month BETWEEN 1 AND 12"),
|
|
38
|
+
nullable=True)
|
|
39
|
+
|
|
40
|
+
year: Mapped[Optional[int]] = mapped_column(
|
|
41
|
+
Integer,
|
|
42
|
+
nullable=True
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
sample: Mapped[Optional["Sample"]] = relationship("Sample", back_populates='time')
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Author:
|
|
49
|
+
# TODO: author
|
|
50
|
+
...
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Literature:
|
|
54
|
+
# TODO: literature
|
|
55
|
+
...
|
msIO/gui/__init__.py
ADDED
|
File without changes
|
msIO/gui/_gui_log.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Give windowed executables a stdout / stderr.
|
|
3
|
+
|
|
4
|
+
Windowed PyInstaller builds (--windowed) and pythonw have no console: sys.stdout / sys.stderr are None, so print(),
|
|
5
|
+
tqdm, logging and tracebacks of exceptions in tk callbacks would fail ("'NoneType' object has no attribute 'write'")
|
|
6
|
+
or vanish. Both streams are redirected to a log file in the user's home directory (devnull if that is not writable).
|
|
7
|
+
|
|
8
|
+
Used in two ways:
|
|
9
|
+
- as PyInstaller runtime hook (--runtime-hook msIO/gui/_gui_log.py), runs before any other import in the exe
|
|
10
|
+
- imported first by every GUI entry module, covers pythonw and running the modules without PyInstaller
|
|
11
|
+
|
|
12
|
+
Only uses the standard library and is idempotent, so running it twice does no harm.
|
|
13
|
+
"""
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
LOG_FILE = os.path.join(os.path.expanduser("~"), "msIO_gui.log")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _open_log():
|
|
21
|
+
try:
|
|
22
|
+
return open(LOG_FILE, "a", buffering=1, encoding="utf-8", errors="replace")
|
|
23
|
+
except OSError:
|
|
24
|
+
return open(os.devnull, "w")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
if sys.stdout is None or sys.stderr is None:
|
|
28
|
+
_log = _open_log()
|
|
29
|
+
if sys.stdout is None:
|
|
30
|
+
sys.stdout = _log
|
|
31
|
+
if sys.stderr is None:
|
|
32
|
+
sys.stderr = _log
|
msIO/gui/about
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
This tool allows you to make library and algorithm supported annotations.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
Suggested strategy for making annotations:
|
|
5
|
+
1. A grain of truth: Start with high-certainty annotations:
|
|
6
|
+
I. only consider compounds that have been reported before
|
|
7
|
+
II. only consider annotations that have a high MS2 similarity score (around 0.7)
|
|
8
|
+
III. only consider annotations that have a decent number of matched MS2 peaks (this depends on the compound and the library, but generally more than 3)
|
|
9
|
+
IV. You can be more confident about your annotations if they form a series
|
|
10
|
+
2. Adducts: Using the mass difference tool, look for features with other adducts
|
|
11
|
+
3. Connect the dots: Look for features for systematic modifications (e.g., additional isoprenoid units, variations in double bonds, rings), in the m/z vs. RT plot these should roughly form a line.
|
|
12
|
+
4. Expand the search by allowing lower scores: more information is needed to be certain about annotations, try to always relate annotations to already existing ones about which you are sure.
|
|
13
|
+
5. Red herrings: Be aware of potential in-source-fragments. head-less compounds eluting earlier, are potential candidates. They likely have
|
|
14
|
+
6. Don't lose your head: focus on head group modifications (compounds with head should elute earlier on reverse phase columns). Marking certain neutral losses, can help
|
|
15
|
+
7. Sudoku: Head group changes and chain modifications should roughly form lines, in combination they define a grid. Try to fill in the grid.
|
|
16
|
+
8. Fragment hunting: From the features annotated so far, mark down characteristic fragments. Mark them and investigate whether they could stem from similar compounds.
|