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.
Files changed (77) hide show
  1. msIO/__init__.py +15 -0
  2. msIO/_templates/__init__.py +12 -0
  3. msIO/_templates/_many_to_many.py +39 -0
  4. msIO/_templates/_many_to_many_bidirectional.py +43 -0
  5. msIO/_templates/_many_to_one.py +22 -0
  6. msIO/_templates/_many_to_one_bidirectional.py +23 -0
  7. msIO/_templates/_one_to_many.py +33 -0
  8. msIO/_templates/_one_to_many_bidirectional.py +32 -0
  9. msIO/_templates/_one_to_one.py +26 -0
  10. msIO/_templates/relationship_patterns.py +65 -0
  11. msIO/_version.py +2 -0
  12. msIO/annotations/__init__.py +0 -0
  13. msIO/annotations/main.py +228 -0
  14. msIO/core.py +29 -0
  15. msIO/environmental/__init__.py +0 -0
  16. msIO/environmental/location.py +21 -0
  17. msIO/environmental/sample.py +48 -0
  18. msIO/export_manager/__init__.py +0 -0
  19. msIO/export_manager/main.py +34 -0
  20. msIO/feature_managers/__init__.py +0 -0
  21. msIO/feature_managers/_read_mzio_graphml_as_xml.py +68 -0
  22. msIO/feature_managers/base.py +45 -0
  23. msIO/feature_managers/combined.py +171 -0
  24. msIO/feature_managers/db.py +1305 -0
  25. msIO/feature_managers/gnps.py +75 -0
  26. msIO/feature_managers/metaboscape.py +114 -0
  27. msIO/feature_managers/sirius.py +162 -0
  28. msIO/feature_managers/util_library.py +42 -0
  29. msIO/features/__init__.py +0 -0
  30. msIO/features/base.py +80 -0
  31. msIO/features/combined.py +143 -0
  32. msIO/features/gnps.py +59 -0
  33. msIO/features/metaboscape.py +128 -0
  34. msIO/features/mgf.py +171 -0
  35. msIO/features/sirius.py +228 -0
  36. msIO/features/util.py +13 -0
  37. msIO/general.py +55 -0
  38. msIO/gui/__init__.py +0 -0
  39. msIO/gui/_gui_log.py +32 -0
  40. msIO/gui/about +16 -0
  41. msIO/gui/annotation/__init__.py +3 -0
  42. msIO/gui/annotation/annotations.py +169 -0
  43. msIO/gui/annotation/app.py +916 -0
  44. msIO/gui/annotation/common.py +694 -0
  45. msIO/gui/annotation/database_panel.py +51 -0
  46. msIO/gui/annotation/dialogs.py +688 -0
  47. msIO/gui/annotation/export.py +105 -0
  48. msIO/gui/annotation/filter_panel.py +398 -0
  49. msIO/gui/annotation/matching.py +294 -0
  50. msIO/gui/annotation/matching_panel.py +99 -0
  51. msIO/gui/annotation/overview_panel.py +367 -0
  52. msIO/gui/annotation/results_panel.py +400 -0
  53. msIO/gui/annotation/scatter_panel.py +898 -0
  54. msIO/gui/annotation/series.py +334 -0
  55. msIO/gui/annotation/shortcuts.py +213 -0
  56. msIO/gui/csv_to_sqlite_gui.py +266 -0
  57. msIO/gui/feature_overview.py +467 -0
  58. msIO/gui/find_lib_matches.py +13 -0
  59. msIO/gui/library_search_by_name.py +222 -0
  60. msIO/gui/main.py +85 -0
  61. msIO/gui/msp_to_sqlite_gui.py +142 -0
  62. msIO/list_of_ions/__init__.py +0 -0
  63. msIO/list_of_ions/base.py +299 -0
  64. msIO/list_of_ions/read_library.py +76 -0
  65. msIO/list_of_ions/read_mca.py +237 -0
  66. msIO/list_of_ions/read_mgf.py +161 -0
  67. msIO/list_of_ions/read_msp.py +281 -0
  68. msIO/metrics.py +72 -0
  69. msIO/sql/__init__.py +0 -0
  70. msIO/sql/create_library.py +151 -0
  71. msIO/sql/session.py +32 -0
  72. msIO/sql/visualize.py +61 -0
  73. msio-1.0.3.dist-info/METADATA +151 -0
  74. msio-1.0.3.dist-info/RECORD +77 -0
  75. msio-1.0.3.dist-info/WHEEL +5 -0
  76. msio-1.0.3.dist-info/licenses/LICENSE +21 -0
  77. msio-1.0.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,75 @@
1
+ import os
2
+ from functools import cached_property
3
+
4
+ import networkx as nx
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from msIO.feature_managers._read_mzio_graphml_as_xml import get_node_and_edge_data
9
+ from msIO.feature_managers.base import FeatureManager
10
+ from msIO.features.gnps import FeatureGnpsNode, GNPS_RENAME
11
+
12
+
13
+ class GnpsImportManager(FeatureManager):
14
+ _df_nodes: pd.DataFrame = None
15
+
16
+ def __init__(self, path_gnps_folder=None, path_file_gnps_graphml=None):
17
+ # assert (path_gnps_folder is not None) or (path_file_gnps_graphml is not None)
18
+ if (path_gnps_folder is None) and (path_file_gnps_graphml is None):
19
+ return
20
+
21
+ if path_file_gnps_graphml is None:
22
+ path_file_gnps_graphml = self._find_gnps_file(path_gnps_folder)
23
+ self.path_file_gnps_graphml = path_file_gnps_graphml
24
+
25
+ G: nx.Graph = nx.read_graphml(self.path_file_gnps_graphml)
26
+ keep_columns_to_dtype = {'componentindex': int, 'RTConsensus': float, 'precursor mass': float}
27
+ nodes_data = dict(map(lambda x: (int(x[0]), x[1]), G.nodes.data()))
28
+ self._df_nodes = (
29
+ pd.DataFrame(nodes_data)
30
+ .loc[list(keep_columns_to_dtype), :]
31
+ .T
32
+ .astype(keep_columns_to_dtype)
33
+ .rename(columns=GNPS_RENAME)
34
+ )
35
+ self._df_nodes.index.name = 'feature_id'
36
+
37
+ @classmethod
38
+ def from_mzmine(cls, path_file_graphml: str):
39
+ new = cls()
40
+ new.path_file_gnps_graphml = path_file_graphml
41
+
42
+ node_data, _ = get_node_and_edge_data(path_file_graphml)
43
+ node_data = (
44
+ node_data
45
+ .loc[node_data.type == "Feature", ['id', 'rt', 'cluster_id', 'neutral_mass']]
46
+ .rename(columns={'id': 'feature_id', 'rt': 'rt_seconds', 'cluster_id': 'cluster_label', 'neutral_mass': 'M_gnps'})
47
+ .astype({'feature_id': int, 'cluster_label': int, 'rt_seconds': float, 'M_gnps': float})
48
+ .set_index('feature_id')
49
+ )
50
+ node_data.loc[:, 'rt_seconds'] = node_data.rt_seconds * 60
51
+
52
+ new._df_nodes = node_data
53
+ return new
54
+
55
+ @staticmethod
56
+ def _find_gnps_file(path_gnps_folder):
57
+ for file in os.listdir(folder := os.path.join(path_gnps_folder, 'gnps_molecular_network_graphml')):
58
+ if file.endswith('.graphml'):
59
+ return os.path.join(folder, file)
60
+ raise FileNotFoundError(f'could not find graphml file in {folder}')
61
+
62
+ def _inner_missing_feature(self, f_id) -> None:
63
+ f = FeatureGnpsNode(
64
+ feature_id=f_id,
65
+ **self._df_nodes.loc[f_id, :].to_dict(),
66
+ )
67
+ self._features[f_id] = f
68
+
69
+ @cached_property
70
+ def feature_ids(self) -> np.ndarray[int]:
71
+ return self._df_nodes.index.values
72
+
73
+
74
+ if __name__ == '__main__':
75
+ pass
@@ -0,0 +1,114 @@
1
+ from typing import Literal
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from msIO.feature_managers.base import FeatureManager
7
+ from msIO.features.metaboscape import FeatureMetaboScape, METABOSCAPE_CSV_RENAME_COLUMNS
8
+ from msIO.environmental.sample import Sample
9
+
10
+ # MZmine full feature table column -> attribute of FeatureMetaboScape
11
+ MZMINE_CSV_RENAME_COLUMNS: dict[str, str] = {
12
+ 'id': 'feature_id',
13
+ 'rt': 'rt_seconds', # in minutes, converted after renaming
14
+ 'mz': 'mz_meas',
15
+ 'ccs': 'CCS',
16
+ 'ion_identities:neutral_mass': 'M_metaboscape',
17
+ 'preferred_annotation:compound_name': 'name_metaboscape',
18
+ 'preferred_annotation:mol_formula': 'formula_metaboscape',
19
+ 'preferred_annotation:adduct': 'adduct_metaboscape',
20
+ 'preferred_annotation:annotation_method': 'annotation_source',
21
+ }
22
+
23
+
24
+ class MetaboscapeImportManager(FeatureManager):
25
+ _df: pd.DataFrame = None
26
+ path_metaboscape_export_file: str = None
27
+ _sample_name_to_sample: dict[str, Sample] = None
28
+
29
+ def __init__(self, path_metaboscape_export_file: str = None, path_metaboscape_clipboard_file: str = None):
30
+ if path_metaboscape_export_file is None:
31
+ return
32
+
33
+ self.path_metaboscape_export_file = path_metaboscape_export_file
34
+
35
+ _df = pd.read_csv(path_metaboscape_export_file).rename(columns=METABOSCAPE_CSV_RENAME_COLUMNS)
36
+ # for some reason, the retention time in the csv export is not always in seconds
37
+ if _df.loc[:, 'rt_seconds'].diff().median() < 0.1: # likely minutes
38
+ _df.loc[:, 'rt_seconds'] = _df.loc[:, 'rt_seconds'] * 60
39
+
40
+ # discard mean, max intensity columns
41
+ drop_cols = []
42
+ for col in _df.columns:
43
+ if col.endswith('Intensity'):
44
+ drop_cols.append(col)
45
+ self._df: pd.DataFrame = _df.drop(columns=drop_cols)
46
+
47
+ if path_metaboscape_clipboard_file is not None:
48
+ self._add_from_clipboard(path_metaboscape_clipboard_file)
49
+
50
+ self._sample_name_to_sample: dict[str, Sample] = {}
51
+
52
+ @classmethod
53
+ def from_dataframe(cls, df: pd.DataFrame) -> 'MetaboscapeImportManager':
54
+ new = cls()
55
+ new._df = df
56
+ new._sample_name_to_sample = {}
57
+ return new
58
+
59
+ @classmethod
60
+ def from_mzmine(
61
+ cls, path_mzmine_feature_table: str, intensity: Literal['area', 'height'] = 'area'
62
+ ) -> 'MetaboscapeImportManager':
63
+ """Read a full feature table exported by MZmine (CSV export, all columns).
64
+
65
+ Columns are mapped onto the MetaboScape schema so the resulting features end up
66
+ in the same table of the database.
67
+ """
68
+ header = pd.read_csv(path_mzmine_feature_table, nrows=0).columns
69
+ missing = {'id', 'rt'} - set(header)
70
+ if missing:
71
+ raise ValueError(
72
+ f'{path_mzmine_feature_table} does not look like an MZmine full feature table '
73
+ f'(missing columns: {", ".join(sorted(missing))})'
74
+ )
75
+
76
+ prefix, suffix = 'datafile:', f':{intensity}'
77
+ intensity_columns = [c for c in header if c.startswith(prefix) and c.endswith(suffix)]
78
+ meta_columns = [c for c in MZMINE_CSV_RENAME_COLUMNS if c in header]
79
+
80
+ df = pd.read_csv(path_mzmine_feature_table, usecols=meta_columns + intensity_columns, low_memory=False)
81
+ df = df.rename(columns=MZMINE_CSV_RENAME_COLUMNS | {
82
+ c: c[len(prefix):-len(suffix)] for c in intensity_columns
83
+ })
84
+ df.loc[:, 'rt_seconds'] = df.rt_seconds * 60 # MZmine exports retention times in minutes
85
+ df.loc[:, 'feature_id'] = df.feature_id.astype(int)
86
+ return cls.from_dataframe(df)
87
+
88
+ def _add_from_clipboard(self, path_file: str):
89
+ # rows should match 1 to 1
90
+ df_clip = pd.read_csv(path_file, sep='\t')
91
+
92
+ err_msg = 'data in rows of the export and clipboard files should be in the same order'
93
+ assert df_clip.shape[0] == self._df.shape[0], err_msg
94
+ # check the order
95
+ assert np.all(np.abs(self._df.loc[:, 'rt_seconds'] / 60 - df_clip.loc[:, 'RT [min]']) < .02), err_msg
96
+
97
+ columns_to_transfer = ['m/z meas.', 'Flags', 'AQ', 'Annotation Source', 'Include']
98
+
99
+ for c in columns_to_transfer:
100
+ self._df.loc[:, c] = df_clip.loc[:, c]
101
+ self._df.rename(columns=METABOSCAPE_CSV_RENAME_COLUMNS, inplace=True)
102
+
103
+ @property
104
+ def feature_ids(self):
105
+ return self._df.feature_id.unique()
106
+
107
+ def _inner_missing_feature(self, f_id) -> None:
108
+ idx = np.argwhere(self._df.feature_id == f_id)[0][0]
109
+ f = FeatureMetaboScape.from_dataframe_row(self._df.iloc[idx, :], self._sample_name_to_sample)
110
+ self._features[f_id] = f
111
+
112
+
113
+ if __name__ == '__main__':
114
+ pass
@@ -0,0 +1,162 @@
1
+ import logging
2
+ import os
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ from msIO.feature_managers.base import FeatureManager
8
+ from msIO.features.sirius import FeatureSirius
9
+
10
+ SIRIUS_FILE_NAMES = [
11
+ 'formula_identifications',
12
+ 'compound_identifications',
13
+ 'canopus_formula_summary'
14
+ ]
15
+
16
+ RENAME_FORMULA_IDENTIFICATIONS = {
17
+ 'formulaRank': 'formula_rank',
18
+ 'molecularFormula': 'formula_sirius',
19
+ 'adduct': 'adduct_sirius',
20
+ 'ZodiacScore': 'zodiac_score',
21
+ 'SiriusScore': 'sirius_score',
22
+ 'TreeScore': 'tree_score',
23
+ 'IsotopeScore': 'isotope_score',
24
+ 'numExplainedPeaks': 'num_explained_peaks',
25
+ 'explainedIntensity': 'explained_intensity',
26
+ 'medianMassErrorFragmentPeaks(ppm)': 'median_mass_error_fragments_ppm',
27
+ 'massErrorPrecursor(ppm)': 'mass_error_precursor_ppm',
28
+ 'lipidClass': 'lipid_class',
29
+ 'retentionTimeInSeconds': 'rt_seconds',
30
+ 'featureId': 'feature_id',
31
+ 'mappingFeatureId': 'feature_id',
32
+ 'id': 'sirius_compound_folder'
33
+ }
34
+
35
+ RENAME_COMPOUND_IDENTIFICATIONS = {
36
+ 'confidenceRank': 'confidence_rank',
37
+ 'structurePerIdRank': 'structure_per_id_rank',
38
+ 'formulaRank': 'formula_rank',
39
+ '#adducts': 'num_adducts',
40
+ '#predictedFPs': 'num_predicted_fingerprints',
41
+ 'ConfidenceScore': 'confidence_score',
42
+ 'CSI:FingerIDScore': 'finger_id_score',
43
+ 'ZodiacScore': 'zodiac_score',
44
+ 'SiriusScore': 'sirius_score',
45
+ 'molecularFormula': 'formula_sirius',
46
+ 'adduct': 'adduct_sirius',
47
+ 'InChI': 'inchi',
48
+ 'name': 'name_sirius',
49
+ 'smiles': 'smiles',
50
+ 'xlogp': 'xlogp',
51
+ 'retentionTimeInSeconds': 'rt_seconds',
52
+ 'featureId': 'feature_id',
53
+ 'mappingFeatureId': 'feature_id',
54
+ 'id': 'sirius_compound_folder'
55
+ }
56
+
57
+ RENAME_CANOPUS_FORMULA_SUMMARY = {
58
+ 'id': 'sirius_compound_folder',
59
+ 'molecularFormula': 'formula_sirius',
60
+ 'adduct': 'adduct_sirius',
61
+ 'NPC#pathway': 'npc_pathway_name',
62
+ 'NPC#pathway Probability': 'npc_pathway_probability',
63
+ 'NPC#superclass': 'npc_superclass_name',
64
+ 'NPC#superclass Probability': 'npc_superclass_probability',
65
+ 'NPC#class': 'npc_class_name',
66
+ 'NPC#class Probability': 'npc_class_probability',
67
+ 'ClassyFire#most specific class': 'cf_most_specific_name',
68
+ 'ClassyFire#most specific class Probability': 'cf_most_specific_probability',
69
+ 'ClassyFire#level 5': 'cf_level5_name',
70
+ 'ClassyFire#level 5 Probability': 'cf_level5_probability',
71
+ 'ClassyFire#subclass': 'cf_subclass_name',
72
+ 'ClassyFire#subclass Probability': 'cf_subclass_probability',
73
+ 'ClassyFire#class': 'cf_class_name',
74
+ 'ClassyFire#class Probability': 'cf_class_probability',
75
+ 'ClassyFire#superclass': 'cf_superclass_name',
76
+ 'ClassyFire#superclass probability': 'cf_superclass_probability',
77
+ 'ClassyFire#all classifications': 'cf_path',
78
+ 'featureId': 'feature_id',
79
+ 'mappingFeatureId': 'feature_id',
80
+ }
81
+
82
+ logger = logging.getLogger(__name__)
83
+
84
+
85
+ def read_compound_info(path_compound_folder: str) -> dict[str, str]:
86
+ """Read rows as key, value pairs"""
87
+ out = {}
88
+ path_file = os.path.join(path_compound_folder, 'compound.info')
89
+ with open(path_file, 'r') as f:
90
+ for line in f:
91
+ k, v = line.split('\t')
92
+ out[k] = v.strip('\n')
93
+ return out
94
+
95
+
96
+ def get_sirius_file_for_tag(file: str, tag: str | None) -> str:
97
+ return f'{file}.tsv' if tag is None else f'{file}_{tag}.tsv'
98
+
99
+
100
+ class SiriusImportManager(FeatureManager):
101
+ _tables: dict[str, pd.DataFrame] = None
102
+ _features: dict[int, FeatureSirius] = None
103
+
104
+ def __init__(
105
+ self,
106
+ path_folder_export: str = None,
107
+ export_tag: str = None
108
+ ) -> None:
109
+ self.path_folder_export = path_folder_export
110
+ self.export_tag = export_tag
111
+ self._read_tables()
112
+
113
+ @property
114
+ def feature_ids(self) -> np.ndarray:
115
+ assert self._tables is not None, 'feature_ids not available before setting tables'
116
+ return self._tables['formula_identifications'].feature_id.unique()
117
+
118
+ def _read_tables(self):
119
+ def process_with_rename(table_name: str, renamer: dict[str, str]) -> None:
120
+ table = self._tables[table_name]
121
+ table.rename(columns=renamer, inplace=True)
122
+ expected_columns = set(renamer.values())
123
+ actual_columns = set(table.columns) & expected_columns
124
+ missing_columns = expected_columns - actual_columns
125
+ if len(missing_columns) > 0:
126
+ logger.warning(f'Missing columns: {missing_columns} for {table_name}')
127
+
128
+ table = table.loc[:, list(actual_columns)]
129
+ self._tables[table_name] = table
130
+
131
+ files = [get_sirius_file_for_tag(f, self.export_tag)
132
+ for f in SIRIUS_FILE_NAMES]
133
+ print(files)
134
+
135
+ self._tables: dict[str, pd.DataFrame] = {
136
+ name: pd.read_csv(
137
+ path_file, sep='\t'
138
+ )
139
+ for name, file in zip(SIRIUS_FILE_NAMES, files) if os.path.exists(path_file := os.path.join(self.path_folder_export, file))
140
+ }
141
+
142
+ # strip prefix 'SIRIUS_' that is sometimes added (depending on the version, I think)
143
+ for table_name, table in self._tables.items():
144
+ renamer: dict[str, str] = {c: c.replace('SIRIUS_', '') if c.startswith('SIRIUS_') else c for c in table.columns}
145
+ table.rename(columns=renamer, inplace=True)
146
+
147
+ # only need one, otherwise both will be renamed to feature_id below
148
+ if ('featureId' in table.columns) and ('mappingFeatureId' in table.columns):
149
+ table.drop(columns='mappingFeatureId', inplace=True)
150
+
151
+ renamers = dict(zip(SIRIUS_FILE_NAMES, [RENAME_FORMULA_IDENTIFICATIONS, RENAME_COMPOUND_IDENTIFICATIONS, RENAME_CANOPUS_FORMULA_SUMMARY]))
152
+ for n in self._tables:
153
+ renamer = renamers[n]
154
+ process_with_rename(n, renamer)
155
+
156
+ def _inner_missing_feature(self, f_id) -> None:
157
+ f = FeatureSirius.from_tables(f_id, self._tables)
158
+ self._features[f_id] = f
159
+
160
+
161
+ if __name__ == '__main__':
162
+ pass
@@ -0,0 +1,42 @@
1
+ import numpy as np
2
+ from matchms import Spectrum
3
+ from matchms.similarity import ModifiedCosineGreedy
4
+
5
+ from msIO import PeakList
6
+
7
+
8
+ def peaklist_to_spectrum(
9
+ peaklist: PeakList | None,
10
+ precursor_mz: float = None,
11
+ charge: int = None,
12
+ ) -> Spectrum | None:
13
+ if peaklist is None:
14
+ return None
15
+
16
+ mzs = np.array(peaklist.mzs)
17
+ intensities = np.array(peaklist.intensities)
18
+
19
+ # Filter out zero/negative intensities and m/z <= 0
20
+ valid = (mzs > 0) & (intensities > 0)
21
+ mzs = mzs[valid]
22
+ intensities = intensities[valid]
23
+
24
+ # Sort by m/z (required by matchms)
25
+ idx = np.argsort(mzs)
26
+ mzs = mzs[idx]
27
+ intensities = intensities[idx]
28
+
29
+ # Build metadata
30
+ metadata = {}
31
+ if precursor_mz is not None:
32
+ metadata["precursor_mz"] = float(precursor_mz)
33
+ if charge is not None:
34
+ metadata["charge"] = int(charge)
35
+
36
+ return Spectrum(mz=mzs, intensities=intensities, metadata=metadata)
37
+
38
+
39
+
40
+ if __name__ == '__main__':
41
+ pass
42
+
File without changes
msIO/features/base.py ADDED
@@ -0,0 +1,80 @@
1
+ from sqlalchemy.orm import DeclarativeBase
2
+
3
+
4
+ CONVERTABLE_TYPES = {int, float, bool, str}
5
+
6
+
7
+ def get_py_dtypes_for_obj(obj: object) -> dict[str, type]:
8
+ dtypes: dict[str, type] = {}
9
+ for attr_name, mappable in obj.__annotations__.items():
10
+ # pull out the dtype from Mapped
11
+ t = mappable.__args__[0]
12
+ # pull out arg from optional
13
+ if hasattr(t, '_name') and (t._name == 'Optional'):
14
+ t = t.__args__[0]
15
+
16
+ dtypes[attr_name] = t
17
+ return dtypes
18
+
19
+
20
+ class SqlBaseClass(DeclarativeBase):
21
+ pass
22
+
23
+
24
+ class FeatureBaseClass:
25
+ """Some universal functionality for Feature objects."""
26
+
27
+ @classmethod
28
+ def py_types(cls) -> dict[str, type]:
29
+ return get_py_dtypes_for_obj(cls)
30
+
31
+ @classmethod
32
+ def _convert_type(cls, attr: str, val):
33
+ """Use annotations to get desired type"""
34
+ f = cls.py_types()[attr]
35
+ if f not in CONVERTABLE_TYPES:
36
+ return val
37
+ if f is int:
38
+ try:
39
+ v = f(val)
40
+ except ValueError:
41
+ v = None
42
+ return v
43
+ return f(val)
44
+
45
+ def __init__(self, **kwargs):
46
+ super().__init__()
47
+
48
+ # types_from_annotations: dict[str, type] = self.py_types()
49
+ #
50
+ # def do_nothing_conversion(val):
51
+ # return val
52
+ #
53
+ # def convert_func(attr, val):
54
+ # f = types_from_annotations.get(attr, do_nothing_conversion)
55
+ # print(f'attempting to convert {attr} with {val=} to {f}')
56
+ # return f(val)
57
+
58
+ # use type annotations to convert input kwargs to right types
59
+ kwargs_converted = {k: self._convert_type(k, v) for k, v in kwargs.items()}
60
+
61
+ for k, v in kwargs_converted.items():
62
+ setattr(self, k, v) # ensures ORM descriptors are used
63
+ if getattr(self, 'rt_minutes', None) is not None and getattr(self, 'rt_seconds', None) is None:
64
+ self.rt_seconds = self.rt_minutes * 60
65
+ elif getattr(self, 'rt_seconds', None) is not None and getattr(self, 'rt_minutes', None) is None:
66
+ self.rt_minutes = self.rt_seconds / 60
67
+
68
+ # define hook manually such that we don't need to rely on dataclass
69
+ self.__post_init__()
70
+
71
+ def __post_init__(self):
72
+ pass
73
+
74
+
75
+ if __name__ == '__main__':
76
+ # test type conversion and other population
77
+ fbc1 = FeatureBaseClass(rt_seconds=60)
78
+ fbc2 = FeatureBaseClass(rt_seconds="60")
79
+
80
+ assert fbc1.rt_minutes == fbc2.rt_minutes == 1
@@ -0,0 +1,143 @@
1
+ """
2
+ Module for combining information from MetaboScape, SIRIUS and GNPS exports.
3
+
4
+ Each feature is associated with molecular properties, MS1, MS2, annotations, ...
5
+ """
6
+ from typing import Literal, Iterable, Optional
7
+
8
+ from sqlalchemy import Integer
9
+ from sqlalchemy.orm import Mapped, mapped_column, relationship
10
+
11
+ from msIO.features.base import FeatureBaseClass, SqlBaseClass
12
+ from msIO.features.gnps import FeatureGnpsNode
13
+ from msIO.features.metaboscape import FeatureMetaboScape
14
+ from msIO.features.mgf import FeatureMgf
15
+ from msIO.features.sirius import FeatureSirius
16
+ from msIO.list_of_ions.base import PeakList
17
+
18
+
19
+ class FeatureCombined(SqlBaseClass, FeatureBaseClass):
20
+ __tablename__ = "features"
21
+ id: Mapped[int] = mapped_column(primary_key=True) # include only if not inherited
22
+ feature_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
23
+
24
+ metaboscape: Mapped["FeatureMetaboScape"] = relationship(back_populates='combined_feature')
25
+ gnps: Mapped["FeatureGnpsNode"] = relationship(back_populates='combined_feature')
26
+ mgf: Mapped["FeatureMgf"] = relationship(back_populates='combined_feature')
27
+ sirius: Mapped["FeatureSirius"] = relationship(back_populates='combined_feature')
28
+ # TODO: option to add annotations
29
+ # annotations: Mapped[list["AnnotationMatch"]] = relationship(back_populates="feature")
30
+
31
+
32
+ class FeatureCombinedFlat(FeatureBaseClass):
33
+ """Combine information from features"""
34
+
35
+ # sirius.mgf
36
+ feature_id: int = None
37
+ mz: float = None
38
+ polarity: Literal['pos', 'neg'] = None
39
+
40
+ rt_seconds: float = None
41
+ rt_minutes: float = None
42
+ ms1: PeakList = None
43
+ ms2: PeakList = None
44
+
45
+ # metaboscape .csv
46
+ M_metaboscape: float = None
47
+ name_metaboscape: str = None
48
+ formula_metaboscape: str = None
49
+ adduct_metaboscape: str = None
50
+ intensities: dict[str, int] = None
51
+ CCS: float = None
52
+ sigma_score: float = None
53
+ CAS: float = None
54
+ KEGG: float = None
55
+
56
+ # gnps
57
+ M_gnps: float
58
+ cluster_label: int = None
59
+ other: dict = None
60
+
61
+ # sirius files
62
+ # formula
63
+ formula_sirius: str = None
64
+ formula_rank: int = None
65
+ adduct_sirius: str = None
66
+ zodiac_score: float = None
67
+ sirius_score: float = None
68
+ tree_score: float = None
69
+ isotope_score: float = None
70
+ num_explained_peaks: int = None
71
+ explained_intensity: float = None
72
+ median_mass_error_fragments_ppm: float = None
73
+ mass_error_precursor_ppm: float = None
74
+ lipid_class: str = None
75
+ sirius_compound_folder: str = None
76
+
77
+ # compound candidate
78
+ confidence_rank: int = None
79
+ structure_per_id_rank: int = None
80
+ num_adducts: int = None
81
+ num_predicted_fingerprints: int = None
82
+ confidence_score: float = None
83
+ finger_id_score: float = None
84
+ inchi: str = None
85
+ name_sirius: str = None
86
+ smiles: str = None
87
+ xlogp: float = None
88
+
89
+ # compound group
90
+ npc_pathway_name: str = None
91
+ npc_pathway_probability: float = None
92
+ npc_superclass_name: str = None
93
+ npc_superclass_probability: float = None
94
+ npc_class_name: str = None
95
+ npc_class_probability: float = None
96
+ cf_most_specific_name: str = None
97
+ cf_most_specific_probability: float = None
98
+ cf_level5_name: str = None
99
+ cf_level5_probability: float = None
100
+ cf_subclass_name: str = None
101
+ cf_subclass_probability: float = None
102
+ cf_class_name: str = None
103
+ cf_class_probability: float = None
104
+ cf_superclass_name: str = None
105
+ cf_superclass_probability: float = None
106
+ cf_path: str = None
107
+
108
+ def __init__(self, features: Iterable[FeatureBaseClass]):
109
+ _possible_conflicts = ['adduct', 'formula', 'rt_seconds']
110
+ # TODO: SIRIUS should overwrite adduct and formula, rt_seconds should be from metaboscape
111
+ features_dict = {}
112
+ feature_types = ['metaboscape', 'mgf', 'gnps', 'sirius']
113
+ feature_names = [FeatureMetaboScape.__name__, FeatureMgf.__name__, FeatureGnpsNode.__name__,
114
+ FeatureSirius.__name__]
115
+ feature_name_to_key = dict(zip(feature_names, feature_types))
116
+ for feature in features:
117
+ # find right key
118
+ key = feature_name_to_key[feature.__class__.__name__]
119
+ assert key not in features_dict, 'cannot have same feature type twice'
120
+ features_dict[key] = feature
121
+
122
+ attrs = {}
123
+ # order matters, take less derived properties, if possible
124
+ for f_type in ['sirius', 'gnps', 'mgf', 'metaboscape']:
125
+ if f_type not in features_dict:
126
+ continue
127
+ f = features_dict[f_type]
128
+ attrs |= {k: v for k, v in f.__dict__.items() if v is not None}
129
+
130
+ self.__dict__ |= attrs
131
+
132
+ @classmethod
133
+ def from_nested(cls, nested_feature):
134
+ ...
135
+
136
+
137
+ def load_database(in_file: str) -> dict[int, FeatureCombinedFlat]:
138
+ ...
139
+
140
+
141
+ if __name__ == '__main__':
142
+ pass
143
+
msIO/features/gnps.py ADDED
@@ -0,0 +1,59 @@
1
+ import json
2
+
3
+ from typing import Self, Optional
4
+
5
+ from sqlalchemy import Integer, Float, String, ForeignKey
6
+ from sqlalchemy.orm import mapped_column, Mapped, relationship
7
+
8
+ from msIO.features.base import FeatureBaseClass, SqlBaseClass
9
+
10
+ GNPS_RENAME: dict[str, str] = {
11
+ 'componentindex': 'cluster_label',
12
+ 'precursor mass': 'M_gnps',
13
+ 'RTConsensus': 'rt_seconds'
14
+ }
15
+
16
+
17
+ class FeatureGnpsNode(SqlBaseClass, FeatureBaseClass):
18
+ __tablename__ = "gnps_features"
19
+
20
+ id: Mapped[int] = mapped_column(primary_key=True) # required unless inherited
21
+ feature_id: Mapped[Optional[int]] = mapped_column(Integer)
22
+ cluster_label: Mapped[Optional[int]] = mapped_column(Integer)
23
+ M_gnps: Mapped[Optional[float]] = mapped_column(Float)
24
+ rt_seconds: Mapped[Optional[float]] = mapped_column(Float)
25
+
26
+ # not mapped to a column
27
+ # TODO: convert to sql object as well
28
+ # converting to json for now
29
+ other: Mapped[Optional[str]] = mapped_column(String)
30
+
31
+ combined_feature_id: Mapped[int] = mapped_column(ForeignKey('features.id'))
32
+ combined_feature: Mapped["FeatureCombined"] = relationship(back_populates='gnps')
33
+
34
+ @classmethod
35
+ def from_graphml(cls, inpt: tuple[str | int, dict]) -> Self:
36
+ """Handle input from G.nodes.data()"""
37
+ _id, props = inpt
38
+ processed = {'feature_id': int(_id)}
39
+ _other = {}
40
+ for k, v in props.items():
41
+ if k in GNPS_RENAME:
42
+ k_renamed = GNPS_RENAME[k]
43
+ processed[k_renamed] = cls._convert_type(k_renamed, v)
44
+ else:
45
+ _other[k] = v
46
+ processed['other'] = json.dumps(_other)
47
+ return cls(**processed)
48
+
49
+ @property
50
+ def M(self):
51
+ return self.M_gnps
52
+
53
+ @property
54
+ def other_dict(self):
55
+ return json.loads(self.other)
56
+
57
+
58
+ if __name__ == '__main__':
59
+ pass