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,34 @@
1
+ import os
2
+
3
+
4
+ class ExportManager:
5
+ metaboscape_file: str = None
6
+ gnps_file: str = None
7
+
8
+ def __init__(
9
+ self,
10
+ path_metaboscape_folder: str,
11
+ path_gnps_folder: str,
12
+ path_sirius_export_folder: str,
13
+ sirius_export_tag: str = None
14
+ ) -> None:
15
+ self.path_metaboscape_folder = path_metaboscape_folder
16
+ self.path_gnps_folder = path_gnps_folder
17
+ self.path_sirius_export_folder = path_sirius_export_folder
18
+ self.sirius_export_tag = sirius_export_tag
19
+
20
+ def _find_metaboscape_files(self):
21
+ for file in os.listdir(self.path_metaboscape_folder):
22
+ if file.split('.', 1)[1] == 'csv':
23
+ self.metaboscape_file = file
24
+ break
25
+
26
+ def _find_gnps_file(self):
27
+ for file in os.path.join(self.path_gnps_folder, 'gnps_molecular_network_graphml'):
28
+ if file.endswith('.graphml'):
29
+ self.gnps_file = file
30
+ break
31
+
32
+
33
+ if __name__ == '__main__':
34
+ pass
File without changes
@@ -0,0 +1,68 @@
1
+ """
2
+ Usage
3
+ =====
4
+ >>> file = ...
5
+ >>> node_data, edge_data = get_node_and_edge_data(file)
6
+ >>> coel = edge_data.loc[edge_data.type_string == 'MS1 shape correlation', :]
7
+ >>> sims_long = get_modified_cosine_similarities(edge_data)
8
+
9
+ """
10
+
11
+ import xml.etree.ElementTree as ET
12
+
13
+ import pandas as pd
14
+
15
+ def get_node_and_edge_data(file):
16
+ tree = ET.parse(file)
17
+ root = tree.getroot()
18
+
19
+ # the first few entries define columns of the dataframe
20
+ columns = [c.attrib for c in root]
21
+ columns.pop() # last element is graph
22
+ column_types = pd.DataFrame.from_records(columns)
23
+
24
+ graph = root[-1]
25
+
26
+ nodes = [n for n in graph if n.tag.endswith('node')]
27
+ edges = [e for e in graph if e.tag.endswith('edge')]
28
+
29
+ print(f'#nodes: {len(nodes)}, #edges: {len(edges)}')
30
+ rename_dict = {row['id']: row['attr.name'] for _, row in column_types.iterrows()}
31
+ node_data = pd.DataFrame([{e.attrib['key']: e.text for e in n} for n in nodes]).rename(columns=rename_dict)
32
+ edge_data = pd.DataFrame([n.attrib | {e.attrib['key']: e.text for e in n} for n in edges]).rename(columns=rename_dict)
33
+ edge_data.index = [e.tag for e in edges]
34
+
35
+ return node_data, edge_data
36
+
37
+
38
+ def get_modified_cosine_similarities(edge_data):
39
+ mask_ms2_edge = edge_data.type == 'MS2 (modified) cosine'
40
+ return (
41
+ edge_data
42
+ .loc[mask_ms2_edge, ['id1', 'id2', 'score']]
43
+ .rename(columns={'id1': 'feature_id1', 'id2': 'feature_id2', 'score': 'cosine_similarity'})
44
+ )
45
+
46
+
47
+ def collapse_ms2_similarities_to_compounds(comp_to_f_ids: dict[int, list[int]], ms2_sims: pd.DataFrame):
48
+ """add compound id to each feature, group by compound id pairs and take maximums"""
49
+ def find_cp_id(f_id):
50
+ for cp_id, f_ids in comp_to_f_ids.items():
51
+ if f_id in f_ids:
52
+ return cp_id
53
+ else:
54
+ raise ValueError(f'feature id {f_id} not in compound ids')
55
+
56
+ ms2_sims_cp = ms2_sims.copy()
57
+ ms2_sims_cp.loc[:, 'compound_id1'] = ms2_sims_cp.feature_id1.apply(find_cp_id)
58
+ ms2_sims_cp.loc[:, 'compound_id2'] = ms2_sims_cp.feature_id2.apply(find_cp_id)
59
+ return (
60
+ ms2_sims_cp
61
+ .loc[:, [['compound_id1', 'compound_id2', 'cosine_similarity']]]
62
+ .groupby(by=['compound_id1', 'compound_id2'])
63
+ .max()
64
+ )
65
+
66
+
67
+ if __name__ == '__main__':
68
+ pass
@@ -0,0 +1,45 @@
1
+ from typing import Iterable
2
+
3
+ from tqdm import tqdm
4
+
5
+ from msIO.features.base import FeatureBaseClass
6
+
7
+
8
+ class FeatureManager:
9
+ _features: dict[int, FeatureBaseClass] = None
10
+
11
+ @property
12
+ def feature_ids(self):
13
+ raise NotImplementedError()
14
+
15
+ def _inner_missing_feature(self, f_id) -> None:
16
+ raise NotImplementedError()
17
+
18
+ def _fetch_missing_features(self, feature_ids: Iterable[int]):
19
+ if self._features is None:
20
+ self._features = {}
21
+
22
+ # exclude non-existent ids and those already processed
23
+ missing_features: set[int] = set(feature_ids).difference(set(self._features.keys())) & set(self.feature_ids)
24
+
25
+ for f_id in tqdm(missing_features,
26
+ desc=f'getting values from {self.__class__.__name__}',
27
+ total=(n_missing := len(missing_features)),
28
+ disable=n_missing <= 10):
29
+ self._inner_missing_feature(f_id)
30
+
31
+ def clear_cache(self):
32
+ self._features = None
33
+
34
+ def get_feature(self, feature_id: int) -> FeatureBaseClass:
35
+ feature_id = int(feature_id) # need to convert e.g. numpy int to native int
36
+ assert feature_id in self.feature_ids, f'found no feature of {self.__class__.__name__} with {feature_id=}'
37
+ self._fetch_missing_features([feature_id])
38
+ return self._features[feature_id]
39
+
40
+ def get_features(self, feature_ids: Iterable[int] = None) -> dict[int, FeatureBaseClass]:
41
+ if feature_ids is None:
42
+ feature_ids = self.feature_ids
43
+
44
+ self._fetch_missing_features(feature_ids)
45
+ return {k: v for k, v in self._features.items() if k in feature_ids}
@@ -0,0 +1,171 @@
1
+ from functools import cached_property
2
+ from typing import Any
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ from tqdm import tqdm
7
+
8
+ from msIO import MgfImportManager
9
+ from msIO.feature_managers.base import FeatureManager
10
+ from msIO.feature_managers.gnps import GnpsImportManager
11
+ from msIO.feature_managers.metaboscape import MetaboscapeImportManager
12
+ from msIO.feature_managers.sirius import SiriusImportManager
13
+ from msIO.features.base import SqlBaseClass
14
+ from msIO.features.combined import FeatureCombined, FeatureCombinedFlat
15
+
16
+
17
+ class ProjectImportManager(FeatureManager):
18
+ """Object for creating a db file from import managers"""
19
+ def __init__(
20
+ self,
21
+ metaboscape_manager: MetaboscapeImportManager = None,
22
+ mgf_manager: MgfImportManager = None,
23
+ gnps_manager: GnpsImportManager = None,
24
+ sirius_manager: SiriusImportManager = None
25
+ ) -> None:
26
+ self._metaboscape_manager = metaboscape_manager
27
+ self._mgf_manager = mgf_manager
28
+ self._gnps_manager = gnps_manager
29
+ self._sirius_manager = sirius_manager
30
+
31
+ self._name_to_manager = {
32
+ 'metaboscape': self._metaboscape_manager,
33
+ 'mgf': self._mgf_manager,
34
+ 'gnps': self._gnps_manager,
35
+ 'sirius': self._sirius_manager
36
+ }
37
+
38
+ @property
39
+ def active_managers(self) -> dict[str, FeatureManager]:
40
+ return {name: manager
41
+ for name, manager in self._name_to_manager.items()
42
+ if manager is not None}
43
+
44
+ @cached_property
45
+ def feature_ids(self) -> np.ndarray[int]:
46
+ f_ids = set()
47
+ for m in self.active_managers.values():
48
+ f_ids |= set(m.feature_ids)
49
+ return np.array(sorted(f_ids))
50
+
51
+ def _inner_missing_feature(self, f_id) -> None:
52
+ features = {name: m.get_feature(f_id) for name, m in self.active_managers.items() if f_id in m.feature_ids}
53
+ f = FeatureCombined(feature_id=f_id, **features)
54
+ self._features[f_id] = f
55
+
56
+ def get_metaboscape_feature(self, f_id: int):
57
+ assert 'metaboscape' in self.active_managers
58
+ return self.active_managers['metaboscape'].get_feature(f_id)
59
+
60
+ def get_mgf_feature(self, f_id: int):
61
+ assert 'mgf' in self.active_managers
62
+ return self.active_managers['mgf'].get_feature(f_id)
63
+
64
+ def get_gnps_feature(self, f_id: int):
65
+ assert 'gnps' in self.active_managers
66
+ return self.active_managers['gnps'].get_feature(f_id)
67
+
68
+ def get_sirius_feature(self, f_id: int):
69
+ assert 'sirius' in self.active_managers
70
+ return self.active_managers['sirius'].get_feature(f_id)
71
+
72
+ def to_sql(self, db_file: str, feature_ids=None) -> None:
73
+ from msIO.sql.session import get_sessionmaker
74
+
75
+ if feature_ids is None:
76
+ feature_ids = self.feature_ids
77
+
78
+ Session = get_sessionmaker(db_file)
79
+
80
+ with Session() as session:
81
+ for f_id in tqdm(feature_ids, desc='adding features to DB', total=len(feature_ids)):
82
+ # features = [m.get_feature(f_id) for m in self.active_managers.values() if f_id in m.feature_ids]
83
+ # for f in features:
84
+ # # print(f'adding {f.__class__.__name__} to session')
85
+ # session.add(f)
86
+ f = self.get_feature(f_id)
87
+ session.add(f)
88
+ session.commit()
89
+
90
+
91
+ def write_table(project_import_manager: ProjectImportManager) -> tuple[pd.DataFrame, pd.DataFrame, dict]:
92
+ """Compile feature attributes in dataframes"""
93
+ columns = []
94
+ excluded_columns = []
95
+
96
+ f_ids = project_import_manager.feature_ids
97
+
98
+ include_dtypes = [int, float, str]
99
+ for col, dtype in FeatureCombinedFlat.__annotations__.items():
100
+ if col in columns:
101
+ continue
102
+ # exclude complex dtypes
103
+ if dtype not in include_dtypes:
104
+ excluded_columns.append(col)
105
+ else:
106
+ columns.append(col)
107
+ proto_intensities: dict[int, dict] = {} # don't know columns for intensities beforehand
108
+ excluded_properties: dict[int, dict[str, Any]] = {}
109
+ df = pd.DataFrame(columns=columns, index=f_ids)
110
+ for f_id in tqdm(f_ids, desc='writing tables', total=f_ids.shape[0]):
111
+ f = project_import_manager.get_feature(f_id)
112
+ for col, val in f.__dict__.items():
113
+ if col == 'intensities':
114
+ proto_intensities[f_id] = val
115
+ elif col in columns:
116
+ df.at[f_id, col] = val
117
+ else:
118
+ if f_id not in excluded_properties:
119
+ excluded_properties[f_id] = {}
120
+ excluded_properties[f_id][col] = val
121
+
122
+ df_intensities = pd.DataFrame(proto_intensities)
123
+
124
+ return df, df_intensities, excluded_properties
125
+
126
+
127
+ if __name__ == '__main__':
128
+ path_metaboscape_csv = r"\\hlabstorage.dmz.marum.de\scratch\Yannick\Guaymas\U1545B_U1549B\MetabSscape\timsTOF_combined_re.csv"
129
+ path_mgf_sirius = r"\\hlabstorage.dmz.marum.de\scratch\Yannick\Guaymas\U1545B_U1549B\MetabSscape\timsTOF_combined_re.sirius.mgf"
130
+ path_gnps_folder = r"\\hlabstorage.dmz.marum.de\scratch\Yannick\Guaymas\U1545B_U1549B\GNPS"
131
+ path_sirius_folder = r'\\hlabstorage.dmz.marum.de\scratch\Yannick\Guaymas\U1545B_U1549B\SIRIUS\5.8.1'
132
+
133
+ metaboscape = MetaboscapeImportManager(path_metaboscape_csv)
134
+ mgf = MgfImportManager(path_mgf_sirius)
135
+ # mgf = None
136
+ gnps = GnpsImportManager(path_gnps_folder=path_gnps_folder)
137
+ sr = SiriusImportManager(path_folder_export=path_sirius_folder, export_tag='all')
138
+
139
+ project_import_manager = ProjectImportManager(mgf_manager=mgf,
140
+ gnps_manager=gnps,
141
+ sirius_manager=sr,
142
+ metaboscape_manager=metaboscape)
143
+
144
+ res = write_table(project_import_manager)
145
+
146
+ # # %%
147
+ # f_id = 6
148
+ #
149
+ # # f = project_import_manager.get_feature(f_id)
150
+ #
151
+ # f_mgf = project_import_manager.get_mgf_feature(f_id)
152
+ # f_gnps = project_import_manager.get_gnps_feature(f_id)
153
+ # f_sirius = project_import_manager.get_sirius_feature(f_id)
154
+ # f_meta = project_import_manager.get_metaboscape_feature(f_id)
155
+ #
156
+ # f = FeatureCombined(feature_id=f_id, gnps=f_gnps)
157
+ #
158
+ # f_comb = project_import_manager.get_feature(f_id)
159
+ # # import matplotlib.pyplot as plt
160
+ # # f_mgf.ms2.plot(); plt.show()
161
+ #
162
+ # # %%
163
+ #
164
+ #
165
+ # from msIO.sql.session import initiate_db
166
+ #
167
+ # db_file = 'database.db'
168
+ #
169
+ # initiate_db(db_file)
170
+ # # project_import_manager.to_sql(db_file, feature_ids=project_import_manager.feature_ids[:10])
171
+ # project_import_manager.to_sql(db_file)